body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The desire for such a function came out of the necessity of generating a &quot;source&quot; of <em>Lorem ipsum</em> by repeating over and over the same 50 or something paragraphs of the text.</p> <p>Actually I am curious to know how to do it in C++ (I guess <code>boost::hana</code> has something to offer in this respect), and <a href="https://stackoverflow.com/questions/62903536/taking-n-lines-from-a-file-which-contains-m-lines-repeating-the-file-lazily-i">I have asked a question on StackOverflow about it aleady</a>.</p> <p>However, to get a better understanding of the functional approach, here's my working solution in Haskell,</p> <pre class="lang-hs prettyprint-override"><code>import System.IO (readFile) main :: IO () main = (\x -&gt; readFile &quot;file&quot; &gt;&gt;= putStrLn . unlines . take x . concat . repeat . lines) =&lt;&lt; return . read =&lt;&lt; getLine </code></pre> <p>where</p> <ul> <li>I'm not sure about the <code>return . read</code> type being the best choice there where it is (one reason being that it doesn't crash gracefully if <code>main</code> is fed with a non-numeric input), and</li> <li>I haven't written the lambda totally in point-free because I think it would be less readable.</li> <li>Most importantly, I'm not sure this works lazily in all its parts, but I'd really like to understand this bit.</li> </ul> <p>The program above assumes the current directory contains a text file named <code>file</code>, which can contain something like this,</p> <pre class="lang-none prettyprint-override"><code>line1 line2 line3 </code></pre> <p>Given this, one can compile and run obtaining this, for instance:</p> <pre class="lang-bsh prettyprint-override"><code>ghc --make -dynamic program.hs &amp;&amp; ./program &lt;&lt;&lt; 7 line1 line2 line3 line1 line2 line3 line1 </code></pre> <p>Any suggestions?</p>
[]
[ { "body": "<ul>\n<li>Even though <code>module Main</code> is implied when no header is given, I'd write it.</li>\n<li><code>return . read =&lt;&lt; getLine = read &lt;$&gt; getLine = fmap read getLine</code> is a worse version of <code>readLn</code>. <code>read &lt;$&gt; getLine</code> is basically <code>return (error msg)</code> when the parse fails. This passes the bottoming value into the &quot;pure&quot; part of your code. <code>readLn badstr</code> crashes at a well defined time—upon its execution—and if you actually wanted to handle the error you'd use <code>Text.Read.readMaybe</code> or <code>readEither</code>.</li>\n<li><code>concat . repeat</code> is <code>cycle</code>. Gets your point across better, doesn't it?</li>\n<li><code>putStrLn . unlines</code> is a bug. It causes an extra newline in the input: <code>unlines</code> creates a trailing newline and <code>putStrLn</code> creates another. Use <code>putStr</code>.</li>\n<li>I don't hate the &quot;expression&quot; style here, but once we replace the <code>=&lt;&lt; return . read =&lt;&lt; getLine</code> with <code>=&lt;&lt; readLine</code> you may as well bring it to the front and use <code>&gt;&gt;=</code>, and at that point let's just use a <code>do</code>.</li>\n<li><code>x</code>? Really?</li>\n</ul>\n<p>So:</p>\n<pre><code>module Main (main) where -- not my style of spacing; but fine\nimport System.IO (readFile)\n\nmain = do\n wanted &lt;- readLn\n contents &lt;- readFile &quot;file&quot;\n putStr $ unlines $ take wanted $ cycle $ lines contents\n</code></pre>\n<p>Though I'd also take</p>\n<pre><code>main = do\n wanted &lt;- readLn\n putStr . unlines . take wanted . cycle . lines =&lt;&lt; readFile &quot;file&quot;\n</code></pre>\n<p>Or, if you're attached</p>\n<pre><code>main = readLn &gt;&gt;= (\\wanted -&gt; putStr . unlines . take wanted . cycle . lines =&lt;&lt; readFile &quot;file&quot;)\n</code></pre>\n<p>As to your concern about laziness; this is perfectly fine. <code>readFile</code> is lazy, and so is <code>lines</code>. <code>cycle</code> is actually better than <code>concat . repeat</code>; the latter keeps allocating <code>(:)</code>-cells as long as <code>take</code> consumes them, while <code>cycle</code> will simply connect a pointer that cycles back to the beginning of the output list, which should make it faster. Also, it errors instead of potentially looping forever on an empty input. <code>take</code> is of course lazy, and we've eliminated the excess laziness that would cause any parse errors to be triggered in it. Passing an infinite input (am on a *nix, so I used <code>yes(1)</code> and <code>mkfifo(1)</code>) into this program doesn't break it, which is a good litmus test for laziness.</p>\n<p>Now, as to the functionality of this program: the <code>wanted</code> number should <em>really</em> be an argument, and so should the file (which should be optional and default to stdin). That's done with <a href=\"https://hackage.haskell.org/package/base-4.14.0.0/docs/System-Environment.html#v:getArgs\" rel=\"nofollow noreferrer\"><code>getArgs</code></a>. This is complicated enough to move into new definitions. Let's get that <code>readMaybe</code> going, too. (Hoogle the new names to find the imports.)</p>\n<pre><code>dieWithUsage :: IO a\ndieWithUsage = do\n name &lt;- getProgName\n die $ &quot;Usage: &quot; ++ name ++ &quot; lines [file]&quot;\n\nparseArgs :: [String] -&gt; IO (Int, Handle)\nparseArgs [] = dieWithUsage\nparseArgs (wanted : rest) = (,) &lt;$&gt; getWanted &lt;*&gt; getHandle\n where getWanted = maybe dieWithUsage return $ readMaybe wanted\n getHandle = case rest of\n [] -&gt; return stdin\n [path] -&gt; openFile path ReadMode\n _ -&gt; dieWithUsage\n</code></pre>\n<p>leaving</p>\n<pre><code>main = do\n (wanted, input) &lt;- parseArgs =&lt;&lt; getArgs\n putStr . unlines . take wanted . cycle . lines =&lt;&lt; hGetContents input\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T07:31:00.453", "Id": "482130", "Score": "2", "body": "Welcome to Code Review. This is a good first review. I would also point out that `\\x -> take x . cycle :: Int -> [a] -> [a]` (or the `unlines . ... . lines` variant) is a good candidate for a function without any `IO`, which makes testing a lot easier later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T21:52:25.850", "Id": "245498", "ParentId": "245495", "Score": "7" } } ]
{ "AcceptedAnswerId": "245498", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T20:19:44.333", "Id": "245495", "Score": "6", "Tags": [ "haskell", "functional-programming", "lazy" ], "Title": "Taking n lines from a file which contains m lines, repeating the file lazily if necessary" }
245495
<h1>Background and objective of the code</h1> <p>Based on <a href="https://dev.to/thepracticaldev/daily-challenge-262-no-one-likes-spare-change-5op" rel="nofollow noreferrer">this</a> Dev.to challenge, I wrote the Python code below (<a href="https://tio.run/##vVhtb9s2EP7uX3FLMVhC1dSyG2wz4ABFmxUFin7Yin0xDIOWaJutRHoUlcRL8tuzO5J6c2Qn@zKjjSmJ98K75547ebc3WyUnj49rrXIw@52QGxD5TmkDX0RhIvgoEjPwd2SZ7/aDwSDlayh2mTBLIZcplyoXkhmhZBGwXJXSTEFIEw3g@KcjNbW25iizCOHNpbsiw3QrIl2LxdRqOzs7g0/imhfAsgxS3CdkYuCG7QswCvjtTvMCH1ovUBCE4XkB9nQdkwOr7tuWo6KN0sJscygLnoKwitZCptZEobLSCsBaaeAs2UKR4wOuKyNMplZX51mGnoFaQ1Bg3Hgado2fw@@k7Jblu4xHVrMhT6xCqwxFJ6S5KwfzOILxIrK71yrL1A3l6yulBZjWbE/uJ5oztDkddOP/3mcG7u3lyP5167i1HrfWE7e2ej52E4af12@az4vWPXiYxwu4n9/F01E0no4eFnYdt9bj1nri14OnWqLxi/RELT3R/RF83h9de/0x6gSvP@7zx33@e3w8JjGHiOIyM01OV6XAS61uYLW3X65eEQZG7SDja0OopeuVMkblVpMWm63xWCNwJjzLIlAy24O5URBg@XwvsXx@CmuYQ8FNAVt2TYphxa2eBDMuUq4RU9aEkhxLT/PEoCa2Urg5kMpg/RAaaUdSas2xNtroDa0uwnSlIyaY00V7G1yzrOTVaehk7gRmywxkzBisLnTSkctelfC9xFKTHEsXZRJbkqSc3xrNyEBb@bkL8Xu9KXP0r5jWqWvxFt@gCe8FGd2ywgWjohdiCXlAJ0d4reIBq86Tzh/clFq2bBPdwQ1SkGWcUoq/SwpwgpmwdzvhQWd@8H0dx6SmDE8b1uVDCWv@3NKd9QgR5YiJ4ERqijJH4VpPrZk0Wqbt0FDgUsMK2xJWGC7clighi9AfkYmCt074F9m/0hrzSPxacx0kTA5NN7ToUQ9TXzmybOm8vLw81oTiSWSp8iKCeISMebEIazEiAMDnF1MY0eMpEKfS1UOEj18h6dmTNEXdCIydwKgrcNEn8KsViHsFfusTiDs@1RILEojbPmELdCF5Bd84xgS5vi7fKeIC8KbZW/w4@LhEjihHlgaeAvcfrpULIczgDqt8ZHvSU5g/VJav0g0ihBV8WmVyNoORfSjW7VtNvrSFPcwbY4tKW4ft6kKgUtQ5T0X7hM5hLzBzE8m5TK1o4KcPeE2Bz7gMOs6HYQQpjjh8RjUQVsa/KGRQ5DDXg31ZPI2RDQjdXYr0NnJLig9HF7hGF32rP7TZBIA0OAdJBclqJje85XRrs/Pts3StXmgqWkN2qKIrVsPRQWCgmi3UGfChC09Hl1g33h8kpjH3p2G6YiKEDQ4VnqDNIdCeCDuT8@Z8EYwWmKA54TBoch4uBj2GP9eYQXpIxbUoxCrjNRVEwNLUMdtRB2rY2RP@7BPUf9KjDs/xn4Mmut5S9/at0zc4yM9XjLdzDTsa/tEHREmNCA9BXwQVqr4M4dbRwjOsop6YfKD4k2LnadG0fGTKa6HKokvzBOqXpKWGAZ2RhIKnm05N7s9@Gpy9gXgR9uX76tZw38B8KVvQuQKsB27t55iubCstePYqCpHTEPu@Xzcvl7bTYLmcuW39QKGyrccjKtrDaOExvQtNaKdHIyj5zbJWN7M0HVTX4YukKoS@nkF8VOBk4s/ZbofxD9paaz78sOXJD4oQ4ZlTQbIqSR4pkCp8AaOJz86SOB4aJmSHKMKqFXT86CNlCxKq03ZjaHUNmiRa80OwPrtzyh76hgd0467bsc78wXz78ST9Mrf66gCHr1nG8lXKAOc7nJuC4txNd0EYhv7l2M5GS@wMR96O15lip9@Pe1@QrZh7RcbmePhG3DeUdenIMigmlKZlNy/T3Idf/s3zueHYtjqR/K/D8bfnTnVeb/WyyMrIt6oFYKlgpwrXU@zISOFTh2pOzJnH8vnOzZk4F04wLVg8AS7HISBlBHh/0hT0uJ7d2mAk9Jz6HSXq@hhif2rA5rGWY@0FfnLophtnuaGdG@Ph9GAePoI9t33st48bCfx/MTotNWmMjE8a8UMkTY/k4zyonERbE5zRaOAd46IrHVS@vWQX6frl4oSKow8n@PDd6PChH1r8DLiULOdR60cme5QGMSnMupmYV0KLes9OIwSD9fCLhbYDJUK25jZLZPiFZTKEw19O1sO70wyDuAkf7GsaFgDD/0d0yGfhF6Ke6tc1uzccEvCQ2Zf2RMslcfdwuSQYLpdDFwWHycHj478" rel="nofollow noreferrer" title="Python 3 – Try It Online">TIO link</a> also available).</p> <p>The task was to return the least number of coins in a given denomination to from a specified amount of money. I generalised this into a function that gives all possible combinations of coins that form a specified amount of money. From that, it was easy to write a oneliner function that does exactly that.</p> <h1>Review questions and review scope</h1> <p>I'm happy with the code that I wrote, and I'd really like some feedback to improve my (amateur) Python coding skills and style.</p> <p>I'm interested in a general review of the code and functions that I've written: style, clarity, documentation, etc. I'm not specifically interested if there is an other/better way to give the answer to the challenge (although of course, also this feedback is welcome!).</p> <p>Specific review questions that I can think of:</p> <ul> <li>is the <code>split_in_denominations()</code> function too long (too many lines)? If so: any suggestions to split it?</li> <li>Am I nesting too deep?</li> <li>Any comments/suggestions on the way I use a Numpy ndarray to store the intermediate results as a list of dicts?</li> <li>Although not the main (pun!) focus of my review question: is there a &quot;better&quot; way to show the test cases in <code>main()</code>? I'm aware of Python's unittest module, but that adds a considerable amount of boilerplate code...</li> </ul> <h1>Here is my code:</h1> <pre class="lang-python prettyprint-override"><code>from typing import List, Dict import numpy def split_in_denominations(amount: int, denominations: List[int]) -&gt; List[Dict[int, int]]: """ Gives all distinct ways to express amount in items from denominations The algorithm used is to find all solutions for each smaller amount and each smaller list of (sorted) denominations. For example, for the amount of 3 and denominations [1, 2], the following Numpy array is created: Amount: | 0 | 1 | 2 | 3 | Denominations: +-----------+-----------+-----------+-----------+ [1] |[{1:0,2:0}]|[{1:1,2:0}]|[{1:2,2:0}]|[{1:3,2:0}]| [1,2] |[{1:0,2:0}]|[{1:1,2:0}]|[{1:2,2:0},|[{1:3,2:0},| | | | {1:0,2:1}]| {1:1,2:1}]| +-----------+-----------+-----------+-----------+ This result array is built row by row from the top left to the bottom right. For each cell, only two (disjunct!) solution sets have to be considered: the one directly above (not using the current denomination) and the one 1 of the denomination value to the left. For that latter set, you just need to count one extra of denomination. Arguments: amount: integer value that has to be expressed in denominations denominations: list of values Returns: List with all unique dicts with denomination as key and the count of that denomination as value. The list is sorted by the sum of the count of all denominations (the least number of coins) Raises: ValueError is the amount can't be expressed by denominations Examples: &gt;&gt;&gt; split_in_denominations(13, [1, 5, 10, 25]) [{1: 3, 5: 0, 10: 1, 25: 0}, # 3 coins {1: 3, 5: 2, 10: 0, 25: 0}, # 5 coins {1: 8, 5: 1, 10: 0, 25: 0}, # 9 coins {1: 13, 5: 0, 10: 0, 25: 0}] # 13 coins """ # Template solution: an empty dict with count 0 of each denominations zero_denom = {d: 0 for d in denominations} # Edge case: amount == 0 if amount == 0: return [zero_denom] # result array with all intermediate solutions result = numpy.ndarray((amount + 1, len(denominations)), dtype=list) # Loop over the sorted denominations for denom_idx, denom in enumerate(sorted(denominations)): for amount_idx in range(amount + 1): # In the first iteration of denom, fill the first row of result if denom_idx == 0: # Start with a copy of the template solution result[amount_idx, 0] = [dict(zero_denom)] # If amount is divisible by denom, add that solution if amount_idx % denom == 0: result[amount_idx, 0][0][denom] = amount_idx // denom # Now add the other denominations one by one in each loop else: # Copy the results from the previous denomination list result[amount_idx, denom_idx] = list(result[amount_idx, denom_idx - 1]) # Extend the result with the solutions from # amount_idx minus denom, with 1 extra count of denom if amount_idx &gt;= denom: for solution in result[amount_idx - denom, denom_idx]: new_solution = dict(solution) new_solution[denom] += 1 result[amount_idx, denom_idx].append(new_solution) # Check if there is a result (result does not only contain the template) if result[amount, len(denominations) - 1] == [zero_denom]: raise ValueError(f"{amount} can't be expressed in {denominations}") return sorted(result[amount, len(denominations) - 1], key=lambda s: sum(s.values())) def least_num_denominations(amount: float, denominations: List[float]) -&gt; int: """ Gives the least number of denominations that is needed to sum to amount Arguments: amount: numeric value that has to be expressed in denominations denominations: list of values Returns: The least number of denominations. Returns None of there is no possible split into denominations. Examples: &gt;&gt;&gt; least_num_denominations(4, [1, 2, 3]) # (2, 2) or (1, 3) 2 """ return sum(split_in_denominations(amount, denominations)[0].values()) def main(): denominations = {'coins1': [1, 5, 10, 25], 'coins2': [1, 2, 5, 10, 20, 50], 'coins3': [1, 5, 20, 25], } cases = [('coins1', 13), # 123), ('coins2', 13), # 123), ('coins1', 75), ('coins2', 75), ('coins3', 40), ] for den_name, amount in cases: d = denominations[den_name] print(f'Least split of {amount} in {d} is: ' + f'{least_num_denominations(amount, d)} (there are ' + f'{len(split_in_denominations(amount, d))} ways to split)') if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T02:28:08.357", "Id": "482125", "Score": "3", "body": "_I'm not interested if there is an other/better way to give the answer to the challenge_ - Fine; but you might get an opinion on this anyway. Any insightful review is on-topic here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:53:42.427", "Id": "482148", "Score": "0", "body": "@Reinderien: thank you for commenting. That sentence indeed reads more harsh than I intended. I rephrased it to a more friendly tone of voice and more welcoming to broader feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:10:14.547", "Id": "482151", "Score": "0", "body": "Is the table in the first comment correct? I wonder why the resulting array would contain a (zero) number of coin 2 (e.g. `[{1:3,2:0}]` for the amount of 3 in the first row) if the input says nothing about a coin 2 (the list of available coins is `[1]`)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:12:36.827", "Id": "482152", "Score": "0", "body": "Something is also wrong in the example result: `{1: 3, 5: 0, 10: 1, 25: 0}` is certainly NOT `# 3 coins`...\\" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:17:45.550", "Id": "482153", "Score": "0", "body": "@CiaPan: Thanks for your comments! The first row only uses one denomination: `[1]`. The second row adds the second denominations. Hence, for the amount of 3, `{1: 3, 2:0}` is a valid (and only) answer, using only denomination `[1]`. Note that this table is used as an intermediate result for implementing the dynamic programming solution. The final result is in the last column of the bottom row. That's what the function is working towards. As for the number of coins in the example: you are completely correct. That comment should be `4 coins` instead of `3 coins`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:25:46.237", "Id": "482155", "Score": "0", "body": "_\"(...) for the amount of 3, `{1: 3, 2:0}` is a valid (and only) answer, using only denomination `[1]`.\"_ I don't get it. Yes, it is valid in that the coin 2 is not used. But why does it appear at all? Coins 5, 17 and 6389 are not used, either, so why isn't the answer `{1:3, 2:0, 5:0, 17;0, 6389:0}`...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:33:08.210", "Id": "482157", "Score": "0", "body": "Typing too fast, I made a typo – it should be `{1:3, 2:0, 5:0, 17:0, 6389:0}` in the last line above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:42:26.023", "Id": "482160", "Score": "0", "body": "The valid (coin) denominations are given as an input argument of the function. In the example case, the amount (value) of `3` must be expressed in coins with value `1` or `2` (`denominations = [1, 2]`). The keys of the solution dict are exactly the values of `denomination`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T10:35:45.137", "Id": "482243", "Score": "0", "body": "_'The keys of the **solution** dict are exactly the values of **denomination**.'_ – that's what I'm talking about: why does **2** appear in your example as a key in a solution dict `[{1:3,2:0}]` for the denomination set `[1]` which does **not** contain **2**?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T23:04:35.170", "Id": "245500", "Score": "3", "Tags": [ "python", "python-3.x", "dynamic-programming" ], "Title": "Split money into every possible combination of coin denominations" }
245500
<p>This project is designed to enable clear-net browsing over the Tor network with the Lynx web-browser. Currently everything <em>seems</em> to be functioning as intended, however, it would be most appreciated if anyone could point out mistakes and/or ways that this project can be improved.</p> <hr /> <h2>Questions</h2> <ul> <li><p>Are there any mistakes in this project that would harm the privacy of those using this project?</p> </li> <li><p>Any additional features needed?</p> </li> <li><p>Is there a way to add <code>.onion</code> Top Level Domain look-up support to Lynx browser?</p> </li> </ul> <blockquote> <p>Note, currently for <code>.onion</code> addresses result in the following error...</p> </blockquote> <pre><code>Looking up 127.0.0.1:9999 Making HTTP connection to 127.0.0.1:9999 Sending HTTP request. HTTP request sent; waiting for response. Alert!: HTTP/1.0 405 Method Not Allowed Data transfer complete lynx: Start file could not be found or is not text/html or text/plain Exiting... </code></pre> <blockquote> <p>... so while clear-net browsing is groovy, for some reason browsing hidden services be going a bit goofy.</p> </blockquote> <hr /> <h2>Requirements</h2> <p>Prior to utilizing this project, the Lynx web browser should be installed, and <code>bash --version</code> should report a version number of <code>4</code> or greater.</p> <p>Optional dependencies include <a href="https://github.com/netblue30/firejail" rel="nofollow noreferrer" title="Source code repository for Firejail"><code>firejail</code></a> and <code>socat</code>, for process sandboxing and DNS over Tor respectively.</p> <hr /> <h2>Setup</h2> <p>The <a href="https://github.com/paranoid-linux/torrific-lynx/tree/main/.github" rel="nofollow noreferrer" title="Documentation for torrific-lynx project"><em><code>ReadMe</code></em></a> file contains more detailed instructions for setup, but the TLDR is...</p> <ul> <li>Clone</li> </ul> <pre><code>mkdir -vp ~/git/hub/paranoid-linux cd ~/git/hub/paranoid-linux git clone --recurse-submodules git@github.com:paranoid-linux/torrific-lynx.git </code></pre> <ul> <li>Link/Install</li> </ul> <pre><code>cd torrific-lynx sudo ./update-configs.sh ln -s &quot;${PWD}/torrific-lynx&quot; &quot;${HOME}/bin/&quot; </code></pre> <ul> <li>Use</li> </ul> <pre><code>torrific-lynx 'https://duckduckgo.com' </code></pre> <ul> <li>Exit when done by pressing the <kbd>q</kbd> key to quit</li> </ul> <hr /> <h2>Source Code</h2> <blockquote> <p>Note, source code for this question is maintained on GitHub at <a href="https://github.com/paranoid-linux/torrific-lynx/blob/main/torrific-lynx" rel="nofollow noreferrer" title="Main source code for torrific-lynx project"><code>paranoid-linux/torrific-lynx</code></a>, what is included here are the scripts, configuration file, and shared functions required to test/review without need of any Git <em>fanciness</em>.</p> </blockquote> <h3><a href="https://github.com/paranoid-linux/torrific-lynx/blob/main/torrific-lynx.cfg" rel="nofollow noreferrer" title="Configuration file for torrific-lynx project"><code>torrific-lynx.cfg</code></a></h3> <pre><code>include:/etc/lynx/lynx.cfg cso_proxy:http://127.0.0.1:9999/ finger_proxy:http://127.0.0.1:9999/ ftp_proxy:http://127.0.0.1:9999/ gopher_proxy:http://127.0.0.1:9999/ https_proxy:http://127.0.0.1:9999/ http_proxy:http://127.0.0.1:9999/ newspost_proxy:http://127.0.0.1:9999/ newsreply_proxy:http://127.0.0.1:9999/ news_proxy:http://127.0.0.1:9999/ nntp_proxy:http://127.0.0.1:9999/ snewspost_proxy:http://127.0.0.1:9999/ snewsreply_proxy:http://127.0.0.1:9999/ snews_proxy:http://127.0.0.1:9999/ wais_proxy:http://127.0.0.1:9999/ no_proxy:http://127.0.0.1:9999/ FORCE_SSL_COOKIES_SECURE:TRUE PERSISTENT_COOKIES:FALSE </code></pre> <h3><a href="https://github.com/paranoid-linux/torrific-lynx/blob/main/torrific-lynx" rel="nofollow noreferrer" title="Main source code for torrific-lynx project"><code>torrific-lynx</code></a></h3> <pre><code>#!/usr/bin/env bash ## Find true directory script resides in, true name, and true path __SOURCE__=&quot;${BASH_SOURCE[0]}&quot; while [[ -h &quot;${__SOURCE__}&quot; ]]; do __SOURCE__=&quot;$(find &quot;${__SOURCE__}&quot; -type l -ls | sed -n 's@^.* -&gt; \(.*\)@\1@p')&quot; done __DIR__=&quot;$(cd -P &quot;$(dirname &quot;${__SOURCE__}&quot;)&quot; &amp;&amp; pwd)&quot; __NAME__=&quot;${__SOURCE__##*/}&quot; __PATH__=&quot;${__DIR__}/${__NAME__}&quot; __AUTHOR__='S0AndS0' __DESCRIPTION__='Enables clear-net browsing over the Tor network via Lynx web browser' _cfg_path=&quot;${__DIR__}/torrific-lynx.cfg&quot; _url='https://check.torproject.org/' _useragent='Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0' # _useragent='L_y_n_x/2.8.9dev.16 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.5.17' _verbose='' _disable_firejail='' _disable_socat='' _firejail_lynx_profile=&quot;/usr/local/etc/firejail/lynx.profile&quot; _firejail_socat_profile=&quot;&quot; _cloud_flare_hidden_service='dns4torpnlfs2ifuz2s2yf3fc7rdmsbhm6rw75euj35pac6ap25zgqad.onion' ## Provides: 'falure' &lt;line-number&gt; &lt;command&gt; exit-code source &quot;${__DIR__}/shared_functions/modules/trap-failure/failure.sh&quot; trap 'failure &quot;LINENO&quot; &quot;BASH_LINENO&quot; &quot;${BASH_COMMAND}&quot; &quot;${?}&quot;' ERR ## Provides: 'argument_parser &lt;ref_to_allowed_args&gt; &lt;ref_to_user_supplied_args&gt;' source &quot;${__DIR__}/shared_functions/modules/argument-parser/argument-parser.sh&quot; __license__(){ _year=&quot;$(date +'%Y')&quot; cat &lt;&lt;EOF ${__DESCRIPTION__} Copyright (C) ${_year:-2020} ${__AUTHOR__:-S0AndS0} This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. EOF } usage() { local _message=&quot;${1}&quot; cat &lt;&lt;EOF ${__DESCRIPTION__} --help -h Prints this message and exists --license -l Prints license and exits --cfg-path --cfg='${_cfg_path}' Lynx configuration file path --useragent='${_useragent}' User agent string to submit to remote servers --verbose -v Prints full Lynx command and options prior to running --disable-firejail Disables Firejail customizations, note system defaults are **not** modified --disable-socat Disables usage of Socat for DNS over Tor --firejail-lynx-profile --lynx-profile=&quot;${_firejail_lynx_profile}&quot; Firejail profile to use for Lynx sandbox ${_url} Web address to load at start-up ## Example usage ${__NAME__} 'https://check.torproject.org/' EOF if ((&quot;${#_message}&quot;)); then printf &gt;&amp;2 '\n## Error: %s\n' &quot;${_message}&quot; fi } # # Read &amp; save recognized arguments to variables # _args=(&quot;${@}&quot;) _valid_args=('--help|-h|help:bool' '--license|-l|license:bool' '--verbose|-v:bool' '--disable-firejail:bool' '--disable-socat:bool' '--useragent:print' '--cfg-path|--cfg:path' '--firejail-lynx-profile|--lynx-profile:path' '--url:print-nil') argument_parser '_args' '_valid_args' _exit_status=&quot;$?&quot; ((_help)) || ((_exit_status)) &amp;&amp; { usage exit ${_exit_status:-0} } ((_license)) &amp;&amp; { __license__ exit ${_exit_status:-0} } [[ -e &quot;$(which lynx)&quot; ]] || { usage 'Cannot find executable path for lynx' exit 1 } [[ -f &quot;${_cfg_path}&quot; ]] || { usage &quot;Cannot find configuration file for path -&gt; ${_cfg_path}&quot; exit 1 } _lynx_opts=( -cfg=&quot;${_cfg_path}&quot; -useragent=&quot;${_useragent}&quot; ) _firejail_opts=( --private ) ! ((_disable_firejail)) &amp;&amp; ! ((_disable_socat)) &amp;&amp; { _firejail_opts+=( --hosts-file=&quot;${__DIR__}/hosts&quot; --dns='127.0.0.1' ) } ! ((_disable_firejail)) &amp;&amp; [[ -f &quot;${_firejail_lynx_profile}&quot; ]] &amp;&amp; { _firejail_opts+=( &quot;--profile=${_firejail_lynx_profile}&quot; ) } || { usage &quot;No firejail profile found at -&gt; ${_firejail_lynx_profile}&quot; exit 1 } _socat_opts=( 'TCP4-LISTEN:443' 'reuseaddr' &quot;fork SOCKS4A:127.0.0.1:${_cloud_flare_hidden_service}:443&quot; 'socksport=9150' ) _socat_opts=(&quot;$(printf '%s\n' &quot;$(IFS=,; printf '%s' &quot;${_socat_opts[*]}&quot;)&quot;)&quot;) kill_socat() { local _socat_pid=&quot;${1:?No PID provided!}&quot; ((_verbose)) &amp;&amp; { printf 'Killing socat PID -&gt; %i\n' &quot;${_socat_pid}&quot; } sudo kill &quot;${_socat_pid}&quot; local _ps_search=&quot;$(ps aux | grep &quot;${_socat_pid}&quot; | grep -v grep)&quot; ((&quot;${#_ps_search}&quot;)) &amp;&amp; { # printf &gt;&amp;2 'Trying to kill socat again PID -&gt; %i\n' &quot;${_socat_pid}&quot; # sudo kill &quot;${_socat_pid}&quot; ## TODO: Find cleaner way of killing socat process printf &gt;&amp;2 'Trying to killall socat\n' sudo killall socat } } [[ -e &quot;$(which firejail)&quot; ]] &amp;&amp; ! ((_disable_firejail)) &amp;&amp; { _lynx_path=&quot;$(which -a lynx | head -2 | tail -1)&quot; [[ -e &quot;$(which socat)&quot; ]] &amp;&amp; ! ((_disable_socat)) &amp;&amp; { ((_verbose)) &amp;&amp; { printf '# DEBUG: sudo %s %s &amp;\n' &quot;$(which socat)&quot; &quot;${_socat_opts[*]}&quot; } ## TODO: Find cleaner way of asking for elevated permissions sudo echo &quot;Starting socat...&quot; sudo &quot;$(which socat)&quot; ${_socat_opts[@]} &amp; _socat_pid=&quot;$!&quot; trap &quot;kill_socat ${_socat_pid}&quot; RETURN SIGINT SIGTERM EXIT } ((_verbose)) &amp;&amp; { printf '# DEBUG: %s %s -- %s %s %s\n' &quot;$(which firejail)&quot; &quot;${_firejail_opts[*]}&quot; &quot;${_lynx_path}&quot; &quot;${_lynx_opts[*]}&quot; &quot;${_url}&quot; } &quot;$(which firejail)&quot; &quot;${_firejail_opts[@]}&quot; -- &quot;${_lynx_path}&quot; &quot;${_lynx_opts[@]}&quot; &quot;${_url}&quot; } || { ((_verbose)) &amp;&amp; { printf '# DEBUG: %s %s %s\n' &quot;$(which lynx)&quot; &quot;${_lynx_opts[@]}&quot; &quot;${_url}&quot; } &quot;$(which lynx)&quot; &quot;${_lynx_opts[@]}&quot; &quot;${_url}&quot; } </code></pre> <hr /> <h3><a href="https://github.com/bash-utilities/argument-parser/blob/master/argument-parser.sh" rel="nofollow noreferrer" title="Main source code for argument-parser project"><code>shared_functions/modules/argument-parser/argument-parser.sh</code></a></h3> <pre><code>#!/usr/bin/env bash # argument-parser.sh, source it in other Bash scripts for argument parsing # Copyright (C) 2019 S0AndS0 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation; version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. shopt -s extglob _TRUE='1' _DEFAULT_ACCEPTABLE_ARG_LIST=('--help|-h:bool' '--foo|-f:print' '--path:path-nil') arg_scrubber_alpha_numeric(){ printf '%s' &quot;${@//[^a-z0-9A-Z]/}&quot;; } arg_scrubber_regex(){ printf '%s' &quot;$(sed 's@.@\\.@g' &lt;&lt;&lt;&quot;${@//[^[:print:]$'\t'$'\n']/}&quot;)&quot;; } arg_scrubber_list(){ printf '%s' &quot;$(sed 's@\.\.*@.@g; s@--*@-@g' &lt;&lt;&lt;&quot;${@//[^a-z0-9A-Z,+_./@:-]/}&quot;)&quot; } arg_scrubber_path(){ printf '%s' &quot;$(sed 's@\.\.*@.@g; s@--*@-@g' &lt;&lt;&lt;&quot;${@//[^a-z0-9A-Z ~+_./@:-]/}&quot;)&quot; } arg_scrubber_posix(){ _value=&quot;${@//[^a-z0-9A-Z_.-]/}&quot; _value=&quot;$(sed 's@^[-_.]@@g; s@[-_.]$@@g; s@\.\.*@.@g; s@--*@-@g' &lt;&lt;&lt;&quot;${_value}&quot;)&quot; printf '%s' &quot;${_value::32}&quot; } return_scrubbed_arg(){ _raw_value=&quot;${1}&quot; _opt_type=&quot;${2:?## Error - no option type provided to return_scrubbed_arg}&quot; case &quot;${_opt_type}&quot; in 'bool'*) _value=&quot;${_TRUE}&quot; ;; 'raw'*) _value=&quot;${_raw_value}&quot; ;; 'path'*) _value=&quot;$(arg_scrubber_path &quot;${_raw_value}&quot;)&quot; ;; 'posix'*) _value=&quot;$(arg_scrubber_posix &quot;${_raw_value}&quot;)&quot; ;; 'print'*) _value=&quot;${_raw_value//[^[:print:]]/}&quot; ;; 'regex'*) _value=&quot;$(arg_scrubber_regex &quot;${_raw_value}&quot;)&quot; ;; 'list'*) _value=&quot;$(arg_scrubber_list &quot;${_raw_value}&quot;)&quot; ;; 'alpha_numeric'*) _value=&quot;$(arg_scrubber_alpha_numeric &quot;${_raw_value}&quot;)&quot; ;; esac if [[ &quot;${_opt_type}&quot; =~ ^'bool'* ]] || [[ &quot;${_raw_value}&quot; == &quot;${_value}&quot; ]]; then printf '%s' &quot;${_value}&quot; else printf '## Error - return_scrubbed_arg detected differences in values\n' &gt;&amp;2 return 1 fi } argument_parser(){ local -n _arg_user_ref=&quot;${1:?# No reference to an argument list/array provided}&quot; local -n _arg_accept_ref=&quot;${2:-_DEFAULT_ACCEPTABLE_ARG_LIST}&quot; _args_user_list=(&quot;${_arg_user_ref[@]}&quot;) unset _assigned_args for _acceptable_args in ${_arg_accept_ref[@]}; do ## Take a break when user supplied argument list becomes empty [[ &quot;${#_args_user_list[@]}&quot; == '0' ]] &amp;&amp; break ## First in listed acceptable arg is used as variable name to save value to ## example, '--foo-bar fizz' would transmute into '_foo_bar=fizz' _opt_name=&quot;${_acceptable_args%%[:|]*}&quot; _var_name=&quot;${_opt_name#*[-]}&quot; _var_name=&quot;${_var_name#*[-]}&quot; _var_name=&quot;_${_var_name//-/_}&quot; ## Divine the type of argument allowed for this iteration of acceptable args case &quot;${_acceptable_args}&quot; in *':'*) _opt_type=&quot;${_acceptable_args##*[:]}&quot; ;; *) _opt_type=&quot;bool&quot; ;; esac ## Set case expressions to match user arguments against and for non-bool type ## what alternative case expression to match on. ## example '--foo|-f' will also check for '--foo=*|-f=*' _arg_opt_list=&quot;${_acceptable_args%%:*}&quot; _valid_opts_pattern=&quot;@(${_arg_opt_list})&quot; case &quot;${_arg_opt_list}&quot; in *'|'*) _valid_opts_pattern_alt=&quot;@(${_arg_opt_list//|/=*|}=*)&quot; ;; *) _valid_opts_pattern_alt=&quot;@(${_arg_opt_list}=*)&quot; ;; esac ## Attempt to match up user supplied arguments with those that are valid for (( i = 0; i &lt; &quot;${#_args_user_list[@]}&quot;; i++ )); do _user_opt=&quot;${_args_user_list[${i}]}&quot; case &quot;${_user_opt}&quot; in ${_valid_opts_pattern}) ## Parse for script-name --foo bar or --true if [[ &quot;${_opt_type}&quot; =~ ^'bool'* ]]; then _var_value=&quot;$(return_scrubbed_arg &quot;${_user_opt}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; else i+=1 _var_value=&quot;$(return_scrubbed_arg &quot;${_args_user_list[${i}]}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; unset _args_user_list[$(( i - 1 ))] fi ;; ${_valid_opts_pattern_alt}) ## Parse for script-name --foo=bar _var_value=&quot;$(return_scrubbed_arg &quot;${_user_opt#*=}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; ;; *) ## Parse for script-name direct_value case &quot;${_opt_type}&quot; in *'nil'|*'none') _var_value=&quot;$(return_scrubbed_arg &quot;${_user_opt}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; ;; esac ;; esac if ((_exit_status)); then return ${_exit_status}; fi ## Break on matched options after clearing temp variables and re-assigning ## list (array) of user supplied arguments. ## Note, re-assigning is to ensure the next looping indexes correctly ## and is designed to require less work on each iteration if [ -n &quot;${_var_value}&quot; ]; then declare -g &quot;${_var_name}=${_var_value}&quot; declare -ag &quot;_assigned_args+=('${_opt_name}=\&quot;${_var_value}\&quot;')&quot; unset _user_opt unset _var_value unset _args_user_list[${i}] unset _exit_status _args_user_list=(&quot;${_args_user_list[@]}&quot;) break fi done unset _opt_type unset _opt_name unset _var_name done } </code></pre> <blockquote> <p>Note, the source code for <a href="https://github.com/bash-utilities/argument-parser/blob/master/argument-parser.sh" rel="nofollow noreferrer" title="Main source code for argument-parser project"><code>argument-parser.sh</code></a> is a Git Submodule maintained on GitHub at <a href="https://github.com/bash-utilities/argument-parser" rel="nofollow noreferrer" title="Repository for argument-parser project"><code>bash-utilities/argument-parser</code></a>, and can be cloned individually via...</p> </blockquote> <pre><code>mkdir -vp ~/git/hub/bash-utilities cd ~/git/hub/bash-utilities git clone git@github.com:bash-utilities/argument-parser.git </code></pre> <hr /> <h3><a href="https://github.com/bash-utilities/trap-failure/blob/master/failure.sh" rel="nofollow noreferrer" title="Main source code for trap-failure project"><code>shared_functions/modules/trap-failure/failure.sh</code></a></h3> <pre><code>#!/usr/bin/env bash # Bash Trap Failure, a submodule for other Bash scripts tracked by Git # Copyright (C) 2019 S0AndS0 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation; version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. ## Outputs Front-Mater formatted failures for functions not returning 0 ## Use the following line after sourcing this file to set failure trap ## trap 'failure &quot;LINENO&quot; &quot;BASH_LINENO&quot; &quot;${BASH_COMMAND}&quot; &quot;${?}&quot;' ERR failure(){ local -n _lineno=&quot;${1:-LINENO}&quot; local -n _bash_lineno=&quot;${2:-BASH_LINENO}&quot; local _last_command=&quot;${3:-${BASH_COMMAND}}&quot; local _code=&quot;${4:-0}&quot; ## Workaround for read EOF combo tripping traps ((_code)) || { return &quot;${_code}&quot; } local _last_command_height=&quot;$(wc -l &lt;&lt;&lt;&quot;${_last_command}&quot;)&quot; local -a _output_array=() _output_array+=( '---' &quot;lines_history: [${_lineno} ${_bash_lineno[*]}]&quot; &quot;function_trace: [${FUNCNAME[*]}]&quot; &quot;exit_code: ${_code}&quot; ) [[ &quot;${#BASH_SOURCE[@]}&quot; -gt '1' ]] &amp;&amp; { _output_array+=('source_trace:') for _item in &quot;${BASH_SOURCE[@]}&quot;; do _output_array+=(&quot; - ${_item}&quot;) done } || { _output_array+=(&quot;source_trace: [${BASH_SOURCE[*]}]&quot;) } [[ &quot;${_last_command_height}&quot; -gt '1' ]] &amp;&amp; { _output_array+=( 'last_command: -&gt;' &quot;${_last_command}&quot; ) } || { _output_array+=(&quot;last_command: ${_last_command}&quot;) } _output_array+=('---') printf '%s\n' &quot;${_output_array[@]}&quot; &gt;&amp;2 exit ${_code} } </code></pre> <blockquote> <p>Note, the source code for <a href="https://github.com/bash-utilities/trap-failure/blob/master/failure.sh" rel="nofollow noreferrer" title="Main source code for trap-failure project"><code>failure.sh</code></a> is a Git Submodule maintained on GitHub at <a href="https://github.com/bash-utilities/trap-failure" rel="nofollow noreferrer" title="Repository for trap-failure project"><code>bash-utilities/trap-failure</code></a>, and can be cloned individually via...</p> </blockquote> <pre><code>mkdir -vp ~/git/hub/bash-utilities cd ~/git/hub/bash-utilities git clone git@github.com:bash-utilities/trap-failure.git </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T23:28:50.867", "Id": "245501", "Score": "4", "Tags": [ "security", "bash", "networking" ], "Title": "Clear-net browsing with Lynx over Tor" }
245501
<p>I'm working on a bot that can use a wordlist to play hangman optimally as fast as possible. With the current implementation, the <code>simulateGame</code> function, which plays a whole game against the bot, takes ~500-700 microseconds to execute for the words I've tested, like &quot;fatherhood&quot;, &quot;esoteric&quot;, &quot;joyousnesses&quot;, etc.</p> <p>Wordlist can be found <a href="https://github.com/Tom25/Hangman/blob/master/wordlist.txt" rel="noreferrer">here</a>, and the <code>SIMDStarterKit.h</code> header can be found <a href="https://gist.github.com/jackmott/b7268510227303bb28756596a09cd1e2" rel="noreferrer">here</a>.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;limits.h&gt; #include &lt;strings.h&gt; #include &lt;sys/time.h&gt; #include &quot;SIMDStarterKit.h&quot; typedef struct { char **buffer; int length; int capacity; } StringArray; StringArray newStringArray() { StringArray array; array.buffer = malloc(sizeof(char **)); array.length = 0; array.capacity = 1; return array; } void appendToStringArray(StringArray *array, char *string) { if (array-&gt;length == array-&gt;capacity) { int newCapacity = array-&gt;capacity * 2; array-&gt;buffer = realloc(array-&gt;buffer, sizeof(char **) * newCapacity); array-&gt;capacity = newCapacity; } array-&gt;buffer[array-&gt;length++] = string; } typedef struct { StringArray *arrays; int *lengths; } IndexedWordlist; IndexedWordlist indexWordlist(StringArray wordlist) { int minLength = INT_MAX; int maxLength = INT_MIN; for (int i = 0; i &lt; wordlist.length; i++) { int len = (int) strlen(wordlist.buffer[i]); if (len &gt; maxLength) maxLength = len; else if (len &lt; minLength) minLength = len; } int lists = (maxLength - minLength) + 1; StringArray *wordlists = malloc(sizeof(StringArray) * lists); for (int i = 0; i &lt; lists; i++) wordlists[i] = newStringArray(); for (int i = 0; i &lt; wordlist.length; i++) { int len = (int) strlen(wordlist.buffer[i]); int lenIdx = len - minLength; appendToStringArray(wordlists + lenIdx, wordlist.buffer[i]); } IndexedWordlist indexedWordlist; indexedWordlist.arrays = wordlists; indexedWordlist.lengths = malloc(sizeof(int) * lists); for (int i = 0; i &lt; lists; i++) { indexedWordlist.lengths[i] = i + minLength; } return indexedWordlist; } char mostLikelyCharacter(char *query, char *noCount, char *forbidden, StringArray wordlist) { int len = (int) strlen(query); int *globalCounts = aligned_alloc(MEMORY_ALIGNMENT, 128 * sizeof(int)); int *localCounts = aligned_alloc(MEMORY_ALIGNMENT, 128 * sizeof(int)); long *largeLocalCounts = (long *) localCounts; for (int i = 0; i &lt; 128; i++) { globalCounts[i] = 0; localCounts[i] = 0; } for (int i = 0; i &lt; wordlist.length; i++) { char *string = wordlist.buffer[i]; for (int j = 0; j &lt; len; j++) { char predCharacter = string[j]; char realCharacter = query[j]; if (realCharacter == '_') { if (forbidden[predCharacter] == 1) goto forbiddenWord; } else { if (predCharacter != realCharacter) goto forbiddenWord; } if (noCount[predCharacter] == 1) goto skipCount; localCounts[predCharacter] += 1; skipCount:; } for (int j = 0; j &lt; 128; j += VECTOR_SIZE) { SIMDi global = Load(&amp;globalCounts[j]); SIMDi local = Load(&amp;localCounts[j]); SIMDi added = Add(global, local); Store(globalCounts + j, added); } forbiddenWord: for (int j = 0; j &lt; 128 / 2; j++) largeLocalCounts[j] = 0; } char bestCharacter = '\0'; int bestCount = 0; for (int i = 0; i &lt; 128; i++) { if (globalCounts[i] &gt; bestCount) { bestCount = globalCounts[i]; bestCharacter = (char) i; } } free(globalCounts); free(localCounts); return bestCharacter; } char *fgetsCopy(char *src) { int len = (int) strlen(src); char *newBuffer = malloc(sizeof(char) * len); memcpy(newBuffer, src, len - 1); newBuffer[len - 1] = '\0'; return newBuffer; } StringArray loadWordlist() { FILE* file = fopen(&quot;/Users/tanmaybakshi/wordlist.txt&quot;, &quot;r&quot;); char line[256]; StringArray words = newStringArray(); while (fgets(line, sizeof(line), file)) { appendToStringArray(&amp;words, fgetsCopy(line)); } return words; } char stringsEqual(char *a, char *b) { for (int i = 0; i &lt; strlen(a); i++) if (a[i] != b[i]) return 0; return 1; } void simulateGame(char *word, IndexedWordlist indexedWordlist) { int i = 0; StringArray wordlist; while (1) { if (indexedWordlist.lengths[i] == strlen(word)) { wordlist = indexedWordlist.arrays[i]; break; } i++; } char *forbidden = calloc(128, sizeof(char)); char *noCount = calloc(128, sizeof(char)); char *query = malloc(sizeof(char) * strlen(word) + 1); for (int i = 0; i &lt; strlen(word); i++) query[i] = '_'; query[strlen(word)] = '\0'; while (stringsEqual(query, word) == 0) { char result = mostLikelyCharacter(query, noCount, forbidden, wordlist); char correct = 0; for (int i = 0; i &lt; strlen(word); i++) { if (word[i] == result) { correct = 1; query[i] = result; } } if (correct == 0) { printf(&quot;Incorrect response! (%.1s)\n&quot;, &amp;result); forbidden[result] = 1; } else { printf(&quot;Correct response! (%.1s)\n&quot;, &amp;result); printf(&quot;%s\n&quot;, query); noCount[result] = 1; } } free(forbidden); free(noCount); free(query); } long long timems() { struct timeval tv; gettimeofday(&amp;tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000; } int main() { StringArray wordlist = loadWordlist(); IndexedWordlist indexedWordlist = indexWordlist(wordlist); long long start = timems(); for (int i = 0; i &lt; 5000; i++) simulateGame(&quot;esoteric&quot;, indexedWordlist); long long end = timems(); printf(&quot;Time: %lld\n&quot;, end - start); for (int i = 0; i &lt; wordlist.length; i++) { free(wordlist.buffer[i]); } free(wordlist.buffer); free(indexedWordlist.lengths); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T00:38:11.187", "Id": "482202", "Score": "0", "body": "have you tried profiling your code? My gut feeling is that manual SIMD is not helping much. C strings are slow when it comes to strlen." } ]
[ { "body": "<p>The only obvious thing I see is that your <code>realloc</code> machinery is too complicated given the task at hand. Your entire word file is only 530 KB. You could easily iterate over the entire file to count newlines and get the exact array length you need, and this would be done quite quickly.</p>\n<p>If alignment of the resulting strings is crucial, you'd want to keep your current method of <code>malloc</code>ing a copy of every single line. If not, there is a much simpler solution: read the entire file into memory in one big blob, null out the newlines, and then form a secondary array of pointers into that blob.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T00:44:14.547", "Id": "482204", "Score": "0", "body": "I agree with the complicated machinery and manually specifying SIMD might not even help if the compiler can handle it automatically. The advice I was given for writing high performance code: always profile first!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T03:43:53.617", "Id": "245509", "ParentId": "245508", "Score": "9" } }, { "body": "<p>There is no need to implement <code>stringEqual</code> yourself. Use <code>strcmp(a, b) == 0</code> instead.</p>\n<p>For all variables that contain memory sizes, you should use <code>size_t</code> instead of <code>int</code>.</p>\n<p>In C, the function <code>strlen</code> is terribly slow since it has to scan the entire string for the terminating <code>'\\0'</code>. Never use <code>strlen</code> in a loop for the same string.</p>\n<p>Bug: as soon as your word list contains non-ASCII words, your code runs into undefined behavior (array index out of bounds). The code should be able to work for Arabic and Cyrillic as well. I don't know how Koreans play Hangman, that might be interesting as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T00:40:40.240", "Id": "482203", "Score": "0", "body": "It's reasonable to leave the spec as english only, as long as its documented somewhere. I wouldn't expect a hangman program to support all languages unless it explicitly is designed to. I don't know Arabic, but the alphabet characters are joining, which may cause a lot of problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T19:29:32.230", "Id": "482441", "Score": "0", "body": "Arabic is pretty simple since the joining is only in the representation, not in the selection of the letters. Korean is more interesting since the Unicode code points are typically in their composed form but keyboard input is via individual letters." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T04:36:38.327", "Id": "245510", "ParentId": "245508", "Score": "8" } }, { "body": "<p>The SIMD code has type errors.</p>\n<p>The problem is currently a bunch of floats are read, assigned to a <code>SIMDi</code> anyway, added as floats (and remember, these were integers, reinterpreted as floats), assigned to a <code>SIMDi</code> again, and then stored as floats (into an array of integers). The type warnings are not just noise, it's also actually wrong: integers are being reinterpreted as floats and have floating point addition applied to them. That sort of works for certain ranges of integers that after reinterpretation correspond to subnormal floats (though on some processors adding subnormals is very slow, for example Intel Atom and AMD Bulldozer), so this can fly under the radar for a while, until it can't .. and anyway, even if the right result comes out, this is still an unnecessary level of disregard for types.</p>\n<p>&quot;SIMDStarterKit.h&quot; apparently does not have integer loads.. that's a bit odd. Actually I would question why this header is used at all. The official intrinsics are admittedly gross-looking (or to be generous, they're an acquired taste), but at least they are standard. <code>Load</code> could do just about anything, who knows? Whereas what <code>_mm256_load_ps</code> (or preferably <code>_mm256_load_si256</code>, there are no floats in this program) does is right on the tin.</p>\n<p>Keeping &quot;SIMDStarterKit.h&quot;, the cast functions can be used to remove a couple of warnings, and some manual pointer casting needs to happen, for example:</p>\n<pre><code> for (int j = 0; j &lt; 128; j += VECTOR_SIZE) {\n SIMDi global = CastToInt(Load((float*)&amp;globalCounts[j]));\n SIMDi local = CastToInt(Load((float*)&amp;localCounts[j]));\n SIMDi added = Addi(global, local);\n Store((float*)&amp;globalCounts[j], CastToFloat(added));\n }\n</code></pre>\n<p>With that, and also <code>#include &lt;string.h&gt;</code> (not the same as <code>strings.h</code>), the code can compile without warnings, and the SIMD addition does the right thing.</p>\n<p>By the way, writing this with loop with explicit SIMD is not really necessary, it <a href=\"https://godbolt.org/z/Yqbhxa\" rel=\"noreferrer\">gets autovectorized anyway</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T06:43:28.960", "Id": "245511", "ParentId": "245508", "Score": "11" } } ]
{ "AcceptedAnswerId": "245511", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T03:21:17.910", "Id": "245508", "Score": "11", "Tags": [ "performance", "c", "hangman", "simd" ], "Title": "Hangman Bot built with performance in mind" }
245508
<p>I wrote this piece of code which works as expected:</p> <pre><code>XElement theContentWhichIncludeBuilds = xDocument.XPathSelectElement($&quot;//Project/Group&quot;).Elements() .FirstOrDefault(e =&gt; e.Name== &quot;Content&quot; &amp;&amp; e.Attribute(&quot;Included&quot;).Value == &quot;buildings&quot;); </code></pre> <p>It targets all the <code>Group</code> elements under the <code>Project</code> nodes,<br /> where its <code>Content</code> has an <code>Include</code> attribute with a value of <code>buildings</code>.</p> <p><strong>The base sample XML:</strong></p> <pre><code>&lt;Project&gt; &lt;Group&gt; &lt;Content Include=&quot;buildings&quot;/&gt; </code></pre> <p>I need to use the provided code on top in 2,3 places in my project, the problem with it is that some XML files that I will process will not have that structure, and I am checking if it has that elements based on the condition or not.</p> <p>Obviously it may cause errors when it doesn't have that element or the needed architecture. So I need to put it in Try/Catch.</p> <p>Isn't it better to check each level one-by one and if that existed then check for the next node? (That way also avoid using try/catch) Does anyone confirm the used method can be good or bad on this case, or can provide any better alternative method for it?</p> <p><strong>Edit:</strong></p> <p>The XML files could be similar to the <code>.CSProj</code> structure which I altered a bit for my need. basically, here we may have:</p> <pre><code>&lt;Project&gt; Basic data under the project node, which might be the same in all documents &lt;/Project&gt; </code></pre> <p>only some may have:</p> <pre><code> &lt;Group&gt; &lt;Content Include=&quot;buildings&quot;/&gt; </code></pre> <p>Now we want to check if it doesn't have the missed part we be able to add it, or if it contained the part we may alter its' values.</p> <p>It is an upgrade process of those documents.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:17:55.570", "Id": "482136", "Score": "0", "body": "Have you considered to `Descendants(\"xyz\").Any()` to check element's existence?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:21:15.103", "Id": "482137", "Score": "0", "body": "No didn't try, what is different, I am kind of new to XML iteration, found that there could be tons of ways for doing anything, at first liked the approach I used, cause it was just a single line, but now I am trying to consider other approaches and ideas, if you think it may has some benefits over my provided code, please provide your suggestion as some piece of code and tell me what differs here. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:23:09.737", "Id": "482138", "Score": "0", "body": "Guess your approach may not cause the NullException if I am right. How can I change this code to your suggested approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:35:01.687", "Id": "482139", "Score": "0", "body": "No it will cause any exception. The `Descendants`, `Elements` and `Attributes` methods return those items where the predicate is met. If there is no match, then it will return an empty collection. The `Any` extension method checks the length of the collection. If it is zero then it returns false otherwise true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:36:50.447", "Id": "482140", "Score": "0", "body": "That's probably a fine way. If possible, could you provide that piece of code as an answer, so I be able to mark it as the answer." } ]
[ { "body": "<p>There are several ways how you can process an XML using Linq2XML.</p>\n<p>As I can understand you want to process only those XML files that are matching a given format. You can check this with XML native tools, like XSD or DTD schema definitions and validation or manually via XLinq.</p>\n<p>If you want to check that with XLinq I would suggest to use the following methods: <code>Descendants</code>, <code>Elements</code> and <code>Attributes</code>. Each returns those items where the predicate is met. If there is no match, then it will return an empty collection.</p>\n<p>If you combine this logic with the <code>Any</code> extension method then you can turn your query operators into existence operators. If the queried collection's length is zero then it returns <code>false</code> otherwise <code>true</code>.</p>\n<hr />\n<p>I would suggest to break your logic into two sub-functions:</p>\n<ul>\n<li>Check whether or not the given xml meets the desired format</li>\n<li>Process only that xml, which satisfies the preconditions</li>\n</ul>\n<hr />\n<p>EDIT: To reflect new requirements</p>\n<p>Check the presence of the Group element and act based on its existence:</p>\n<pre><code>var xml = &quot;&lt;Project&gt;&lt;Group&gt;&lt;Content Include = \\&quot;buildings\\&quot; /&gt;&lt;/Group&gt;&lt;/Project&gt;&quot;;\nvar xDocument = XDocument.Parse(xml);\nvar project = xDocument.Root;\nvar isGroupExist = project.Elements(&quot;Group&quot;).Any();\nif (!isGroupExist)\n{\n var group = new XElement(&quot;Group&quot;) { ... };\n project.AddAfterSelf(group);\n}\n//Process it\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:58:21.207", "Id": "482141", "Score": "0", "body": "The main format of all could be the same, the key is some may have those elements and some may have not, so I want to add those elements into them. I am eager to see 2,3 lines of code based on your approach which I be able to judge and replace mine, can you please provide your approach in a simple 2,3 lines of code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:00:06.350", "Id": "482142", "Score": "0", "body": "+1 , and still have some doubts on how to use that which it cover all those elements and the applied needed condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:06:52.253", "Id": "482143", "Score": "0", "body": "@Kasrak Okey, but I need to know, which element might present or not. Can you please extend the question post with some negative example(s) as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:14:05.673", "Id": "482144", "Score": "1", "body": "The Group element and its children might not be there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:26:02.013", "Id": "482145", "Score": "0", "body": "Added some more info, which may help you understand more of the scenario. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:43:53.220", "Id": "482146", "Score": "0", "body": "Still not sure, maybe as you said earlier XSD validation also could be applied and be a best practice doing that, I don't know cause never used it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:49:00.903", "Id": "482147", "Score": "0", "body": "Also with Descendants(\"xyz\").Any() not sure how I can target //Project/Group/Content elements. Still waiting for you if you be able to finalize this answer. thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:57:39.893", "Id": "482149", "Score": "1", "body": "@Kasrak I've just updated the my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:09:53.473", "Id": "482150", "Score": "0", "body": "For this line: \"var isGroupExist = project.Elements(\"Group\").Any();\" we need to apply to our conditions to check based on their attributes. The condition which I provided in FirstOrDefault part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:47:02.627", "Id": "482161", "Score": "0", "body": "@Kasrak If you need to further scrutinize the child elements then yes you should get the Group element first by calling `project.Element(\"Group\")` and then apply your criteria on it. Please pay attention that there is `Element` and `Elements` methods defined by the `XContainer`class. Former gives the first child with the provided name whereas the latter will return all of the matching elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:55:34.470", "Id": "482163", "Score": "1", "body": "thanks for the participation on this issue and sharing your idea, I still need to play with the idea and some other codes I gathered about it, BTW will mark this as the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:59:44.137", "Id": "482164", "Score": "1", "body": "And yes I am aware of Element and Elements, as you have seen my example was also based on Elements filtering." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:50:47.433", "Id": "245516", "ParentId": "245515", "Score": "2" } } ]
{ "AcceptedAnswerId": "245516", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:11:46.607", "Id": "245515", "Score": "2", "Tags": [ "c#", "linq", "xml" ], "Title": "Iteration over an XDocument based on some existing elements and conditions" }
245515
<p>Yet another implementation of A* pathfinding. It is focused on:</p> <ul> <li>Performance (both speed and memory allocations).</li> <li>Readability and simplicity.</li> <li>Well defined objects and methods.</li> <li>Accordance with general conventions (naming, signatures, class structure, design principles etc).</li> </ul> <p>Path is calculated on 2D grid using integer vectors:</p> <pre><code>public interface IPath { IReadOnlyCollection&lt;Vector2Int&gt; Calculate(Vector2Int start, Vector2Int target, IReadOnlyCollection&lt;Vector2Int&gt; obstacles); } </code></pre> <p>First, I'll define <code>Vector2Int</code>. It's pretty straightforward:</p> <pre><code>namespace AI.A_Star { public readonly struct Vector2Int : IEquatable&lt;Vector2Int&gt; { private static readonly float Sqr = (float) Math.Sqrt(2); public Vector2Int(int x, int y) { X = x; Y = y; } public int X { get; } public int Y { get; } /// &lt;summary&gt; /// Estimated path distance without obstacles. /// &lt;/summary&gt; public float DistanceEstimate() { int linearSteps = Math.Abs(Y - X); int diagonalSteps = Math.Max(Math.Abs(Y), Math.Abs(X)) - linearSteps; return linearSteps + Sqr * diagonalSteps; } public static Vector2Int operator +(Vector2Int a, Vector2Int b) =&gt; new Vector2Int(a.X + b.X, a.Y + b.Y); public static Vector2Int operator -(Vector2Int a, Vector2Int b) =&gt; new Vector2Int(a.X - b.X, a.Y - b.Y); public static bool operator ==(Vector2Int a, Vector2Int b) =&gt; a.X == b.X &amp;&amp; a.Y == b.Y; public static bool operator !=(Vector2Int a, Vector2Int b) =&gt; !(a == b); public bool Equals(Vector2Int other) =&gt; X == other.X &amp;&amp; Y == other.Y; public override bool Equals(object obj) { if (!(obj is Vector2Int)) return false; var other = (Vector2Int) obj; return X == other.X &amp;&amp; Y == other.Y; } public override int GetHashCode() =&gt; HashCode.Combine(X, Y); public override string ToString() =&gt; $&quot;({X}, {Y})&quot;; } } </code></pre> <p><code>IEquatable</code> interface is implemented for future optimizations. <code>Sqr</code> value is cached because there is no need to calculate it more than once.</p> <p><code>DistanceEstimate()</code> used for heuristic cost calculation. It is more accurate than <code>Math.Abs(X) + Math.Abs(Y)</code> version, which overestimates diagonal cost.</p> <hr /> <p>Next: <code>PathNode</code> which represents single location on grid:</p> <pre><code>namespace AI.A_Star { internal interface IPathNode { Vector2Int Position { get; } [CanBeNull] IPathNode Parent { get; } float TraverseDistance { get; } float HeuristicDistance { get; } float EstimatedTotalCost { get; } } internal readonly struct PathNode : IPathNode { public PathNode(Vector2Int position, float traverseDistance, float heuristicDistance, [CanBeNull] IPathNode parent) { Position = position; TraverseDistance = traverseDistance; HeuristicDistance = heuristicDistance; Parent = parent; } public Vector2Int Position { get; } public IPathNode Parent { get; } public float TraverseDistance { get; } public float HeuristicDistance { get; } public float EstimatedTotalCost =&gt; TraverseDistance + HeuristicDistance; } } </code></pre> <p><code>PathNode</code> is defined as struct: there will be a lot of node creation. However, it has to include a reference to it's parent, so I'm using <code>IPathNode</code> interface to avoid cycle inside the struct.</p> <hr /> <p>Next: creator of Node neighbours:</p> <pre><code>namespace AI.A_Star { internal class PathNodeNeighbours { private static readonly (Vector2Int position, float cost)[] NeighboursTemplate = { (new Vector2Int(1, 0), 1), (new Vector2Int(0, 1), 1), (new Vector2Int(-1, 0), 1), (new Vector2Int(0, -1), 1), (new Vector2Int(1, 1), (float) Math.Sqrt(2)), (new Vector2Int(1, -1), (float) Math.Sqrt(2)), (new Vector2Int(-1, 1), (float) Math.Sqrt(2)), (new Vector2Int(-1, -1), (float) Math.Sqrt(2)) }; private readonly PathNode[] buffer = new PathNode[NeighboursTemplate.Length]; public PathNode[] FillAdjacentNodesNonAlloc(IPathNode parent, Vector2Int target) { var i = 0; foreach ((Vector2Int position, float cost) in NeighboursTemplate) { Vector2Int nodePosition = position + parent.Position; float traverseDistance = parent.TraverseDistance + cost; float heuristicDistance = (nodePosition - target).DistanceEstimate(); buffer[i++] = new PathNode(nodePosition, traverseDistance, heuristicDistance, parent); } return buffer; } } } </code></pre> <p>Another straightforward class, which simply creates neighboring Nodes around the parent on the grid (including diagonal ones). It uses array buffer, avoiding creation of unnecessary collections.</p> <p>Code didn't seem quite right inside <code>PathNode</code> struct or inside <code>Path</code> class. It felt like minor SRP violation - so I moved it to separate class.</p> <hr /> <p>Now, the interesting one:</p> <pre><code>namespace AI.A_Star { public class Path : IPath { private readonly PathNodeNeighbours neighbours = new PathNodeNeighbours(); private readonly int maxSteps; private readonly SortedSet&lt;PathNode&gt; frontier = new SortedSet&lt;PathNode&gt;(Comparer&lt;PathNode&gt;.Create((a, b) =&gt; a.EstimatedTotalCost.CompareTo(b.EstimatedTotalCost))); private readonly HashSet&lt;Vector2Int&gt; ignoredPositions = new HashSet&lt;Vector2Int&gt;(); private readonly List&lt;Vector2Int&gt; output = new List&lt;Vector2Int&gt;(); public Path(int maxSteps) { this.maxSteps = maxSteps; } public IReadOnlyCollection&lt;Vector2Int&gt; Calculate(Vector2Int start, Vector2Int target, IReadOnlyCollection&lt;Vector2Int&gt; obstacles) { if (!TryGetPathNodes(start, target, obstacles, out IPathNode node)) return Array.Empty&lt;Vector2Int&gt;(); output.Clear(); while (node != null) { output.Add(node.Position); node = node.Parent; } return output.AsReadOnly(); } private bool TryGetPathNodes(Vector2Int start, Vector2Int target, IReadOnlyCollection&lt;Vector2Int&gt; obstacles, out IPathNode node) { frontier.Clear(); ignoredPositions.Clear(); frontier.Add(new PathNode(start, 0, 0, null)); ignoredPositions.UnionWith(obstacles); var step = 0; while (frontier.Count &gt; 0 &amp;&amp; ++step &lt;= maxSteps) { PathNode current = frontier.Min; if (current.Position.Equals(target)) { node = current; return true; } ignoredPositions.Add(current.Position); frontier.Remove(current); GenerateFrontierNodes(current, target); } // All nodes analyzed - no path detected. node = default; return false; } private void GenerateFrontierNodes(PathNode parent, Vector2Int target) { // Get adjacent positions and remove already checked. var nodes = neighbours.FillAdjacentNodesNonAlloc(parent, target); foreach(PathNode newNode in nodes) { // Position is already checked or occupied by an obstacle. if (ignoredPositions.Contains(newNode.Position)) continue; // Node is not present in queue. if (!frontier.TryGetValue(newNode, out PathNode existingNode)) frontier.Add(newNode); // Node is present in queue and new optimal path is detected. else if (newNode.TraverseDistance &lt; existingNode.TraverseDistance) { frontier.Remove(existingNode); frontier.Add(newNode); } } } } } </code></pre> <p>Collections are defined inside class body, not inside methods: this way in subsequent calculations there will be no need in collection creation and resizing (assuming calculated paths are always have somewhat same length).</p> <p><code>SortedSet</code> and <code>HashSet</code> allows calculation to complete 150-200 times faster; <code>List</code> usage is miserably slow.</p> <p><code>TryGetPathNodes()</code> returns child node as <code>out</code> parameter; <code>Calculate()</code> iterates through all node's parents and returns collection of their positions.</p> <hr /> <p>I'm really uncertain about following things:</p> <ol> <li><p><code>PathNode</code> struct contains <code>IPathNode</code> reference. It doesn't seem normal at all.</p> </li> <li><p>The rule of thumb, <em>never return reference to mutable collection</em>. However, <code>PathNodeNeighbours</code> class returns original array buffer itself instead of it's copy. Is that tolerable behavior for <code>internal</code> classes (which are expected to be used in one single place)? Or it is <strong>always</strong> preferable to provide external buffer and fill it via <code>CopyTo()</code>? I'd prefer to keep classes as clean as possible, without multiple 'temporary' arrays.</p> </li> <li><p>85% of memory allocations are happening inside <code>GenerateFrontierNodes()</code> method. Half of that caused by <code>SortedSet.Add()</code> method. Nothing I can do there?</p> </li> <li><p>Boxing from value <code>PathNode</code> to reference <code>IPathNode</code> causes another half of allocations. But making <code>PathNode</code> a class instead of struct makes things worse! There are thousands of <code>PathNode</code>'s! And I have to provide a reference to a parent to each node: otherwise there will be no way to track final path through nodes.</p> </li> </ol> <hr /> <p>Are there any poor solutions used in my pathfinding algorithm? Are there potential improvements in performance to achieve? How can I further improve readability?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T18:04:13.590", "Id": "484304", "Score": "2", "body": "Please do not update the code in your question after receiving feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<blockquote>\n<p>Boxing from value <code>PathNode</code> to reference <code>IPathNode</code> causes another half of allocations. But making <code>PathNode</code> a class instead of struct makes things worse! There are thousands of <code>PathNode</code>'s! And I have to provide a reference to a parent to each node: otherwise there will be no way to track final path through nodes.</p>\n</blockquote>\n<p>It's normally good software engineering practice to have the interface, probably, but for this situation I recommend removing it. Boxing should be avoided, not by switching to classes, but by removing the boxing. So let's work around needing a reference to a node.</p>\n<p>There are other ways to remember the &quot;parent&quot; information, that do not involve a reference to a node. For example, a <code>Dictionary&lt;Vector2Int, Vector2Int&gt;</code>, or <code>Vector2Int[,]</code>, or <code>Direction[,]</code>, there are many variants. When at the end of A* the path is reconstructed, the nodes are mostly irrelevant: only the positions matter, so only the positions need to be accessible, and they still are with these solutions.</p>\n<blockquote>\n<p>85% of memory allocations are happening inside <code>GenerateFrontierNodes()</code> method. Half of that caused by <code>SortedSet.Add()</code> method. Nothing I can do there?</p>\n</blockquote>\n<p>There is something that can be done: use a binary heap. Actually <code>SortedSet</code> is not that good to begin with, it has decent asymptotic behaviour, but its contant factor is poor. A binary heap is great for this use. It's simple to implement, low-overhead, low-allocation. It doesn't keep the collection completely sorted but A* does not require that.</p>\n<p>Then &quot;the update problem&quot; needs to be solved. Currently, it is solved by <code>frontier.Remove</code> and <code>frontier.Add</code> to re-add the node with the new weight. A binary heap is not searchable (not properly), but a <code>Dictionary&lt;Vector2Int, int&gt;</code> can be maintained on the side to record the index in the heap of a node with a given location. Maintaining that dictionary is not a great burden for the heap, and allows an O(log n) &quot;change weight&quot; operation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T13:06:16.887", "Id": "245522", "ParentId": "245518", "Score": "4" } }, { "body": "<p>(For anyone who stumbles across this question and decides to use the sample code).</p>\n<p>Actually, the following collection does not work as intended:</p>\n<pre><code> private readonly SortedSet&lt;PathNode&gt; frontier = new SortedSet&lt;PathNode&gt;(Comparer&lt;PathNode&gt;.Create((a, b) =&gt; a.EstimatedTotalCost.CompareTo(b.EstimatedTotalCost)));\n</code></pre>\n<p>It disallows duplicate nodes with the same estimated cost although their positions are different. It increases pathfinding speed dramatically (there are <em>a lot</em> of nodes with the same cost), but may lead to inaccurate paths or false-negative results.</p>\n<p>I didn't find any built-in collection with keys sorting <strong>and</strong> duplicate keys <strong>and</strong> fast lookup <strong>and</strong> low allocations overhead. There is non-generic <strong>binary heap</strong> implementation instead of <code>SortedSet</code>, as <a href=\"https://codereview.stackexchange.com/questions/245518/c-a-pathfinding-performance-and-simplicity/245522#245522\">@harold</a> suggested:</p>\n<pre><code>internal interface IBinaryHeap&lt;in TKey, T&gt; where TKey : IEquatable&lt;TKey&gt;\n{\n void Enqueue(T item);\n T Dequeue();\n void Clear();\n bool TryGet(TKey key, out T value);\n void Modify(T value);\n int Count { get; }\n}\n\ninternal class BinaryHeap : IBinaryHeap&lt;Vector2Int, PathNode&gt; \n{\n private readonly IDictionary&lt;Vector2Int, int&gt; map;\n private readonly IList&lt;PathNode&gt; collection;\n private readonly IComparer&lt;PathNode&gt; comparer;\n \n public BinaryHeap(IComparer&lt;PathNode&gt; comparer)\n {\n this.comparer = comparer;\n collection = new List&lt;PathNode&gt;();\n map = new Dictionary&lt;Vector2Int, int&gt;();\n }\n\n public int Count =&gt; collection.Count;\n\n public void Enqueue(PathNode item)\n {\n collection.Add(item);\n int i = collection.Count - 1;\n map[item.Position] = i;\n while(i &gt; 0)\n {\n int j = (i - 1) / 2;\n \n if (comparer.Compare(collection[i], collection[j]) &lt;= 0)\n break;\n\n Swap(i, j);\n i = j;\n }\n }\n\n public PathNode Dequeue()\n {\n if (collection.Count == 0) return default;\n \n var result = collection.First();\n RemoveRoot();\n map.Remove(result.Position);\n return result;\n }\n \n public bool TryGet(Vector2Int key, out PathNode value)\n {\n if (!map.TryGetValue(key, out int index))\n {\n value = default;\n return false;\n }\n \n value = collection[index];\n return true;\n }\n\n public void Modify(PathNode value)\n {\n if (!map.TryGetValue(value.Position, out int index))\n throw new KeyNotFoundException(nameof(value));\n\n collection.RemoveAt(index);\n Enqueue(value);\n }\n\n public void Clear()\n {\n collection.Clear();\n map.Clear();\n }\n\n private void RemoveRoot()\n {\n collection[0] = collection.Last();\n map[collection[0].Position] = 0;\n collection.RemoveAt(collection.Count - 1);\n\n int i = 0;\n while(true)\n {\n int largest = LargestIndex(i);\n if (largest == i)\n return;\n\n Swap(i, largest);\n i = largest;\n }\n }\n\n private void Swap(int i, int j)\n {\n PathNode temp = collection[i];\n collection[i] = collection[j];\n collection[j] = temp;\n map[collection[i].Position] = i;\n map[collection[j].Position] = j;\n }\n\n private int LargestIndex(int i)\n {\n int leftInd = 2 * i + 1;\n int rightInd = 2 * i + 2;\n int largest = i;\n\n if (leftInd &lt; collection.Count &amp;&amp; comparer.Compare(collection[leftInd], collection[largest]) &gt; 0) largest = leftInd;\n\n if (rightInd &lt; collection.Count &amp;&amp; comparer.Compare(collection[rightInd], collection[largest]) &gt; 0) largest = rightInd;\n \n return largest;\n }\n}\n</code></pre>\n<p>Generic version:</p>\n<pre><code>internal class BinaryHeap&lt;TKey, T&gt; : IBinaryHeap&lt;TKey, T&gt; where TKey : IEquatable&lt;TKey&gt;\n{\n private readonly IDictionary&lt;TKey, int&gt; map;\n private readonly IList&lt;T&gt; collection;\n private readonly IComparer&lt;T&gt; comparer;\n private readonly Func&lt;T, TKey&gt; lookupFunc;\n \n public BinaryHeap(IComparer&lt;T&gt; comparer, Func&lt;T, TKey&gt; lookupFunc)\n {\n this.comparer = comparer;\n this.lookupFunc = lookupFunc;\n collection = new List&lt;T&gt;();\n map = new Dictionary&lt;TKey, int&gt;();\n }\n\n public int Count =&gt; collection.Count;\n\n public void Enqueue(T item)\n {\n collection.Add(item);\n int i = collection.Count - 1;\n map[lookupFunc(item)] = i;\n while(i &gt; 0)\n {\n int j = (i - 1) / 2;\n \n if (comparer.Compare(collection[i], collection[j]) &lt;= 0)\n break;\n\n Swap(i, j);\n i = j;\n }\n }\n\n public T Dequeue()\n {\n if (collection.Count == 0) return default;\n \n var result = collection.First();\n RemoveRoot();\n map.Remove(lookupFunc(result));\n return result;\n }\n\n public void Clear()\n {\n collection.Clear();\n map.Clear();\n }\n\n public bool TryGet(TKey key, out T value)\n {\n if (!map.TryGetValue(key, out int index))\n {\n value = default;\n return false;\n }\n \n value = collection[index];\n return true;\n }\n\n public void Modify(T value)\n {\n if (!map.TryGetValue(lookupFunc(value), out int index))\n throw new KeyNotFoundException(nameof(value));\n \n collection[index] = value;\n }\n \n private void RemoveRoot()\n {\n collection[0] = collection.Last();\n map[lookupFunc(collection[0])] = 0;\n collection.RemoveAt(collection.Count - 1);\n\n int i = 0;\n while(true)\n {\n int largest = LargestIndex(i);\n if (largest == i)\n return;\n\n Swap(i, largest);\n i = largest;\n }\n }\n\n private void Swap(int i, int j)\n {\n T temp = collection[i];\n collection[i] = collection[j];\n collection[j] = temp;\n map[lookupFunc(collection[i])] = i;\n map[lookupFunc(collection[j])] = j;\n }\n\n private int LargestIndex(int i)\n {\n int leftInd = 2 * i + 1;\n int rightInd = 2 * i + 2;\n int largest = i;\n\n if (leftInd &lt; collection.Count &amp;&amp; comparer.Compare(collection[leftInd], collection[largest]) &gt; 0) largest = leftInd;\n\n if (rightInd &lt; collection.Count &amp;&amp; comparer.Compare(collection[rightInd], collection[largest]) &gt; 0) largest = rightInd;\n \n return largest;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T13:58:31.633", "Id": "482260", "Score": "2", "body": "Good catch about the SortedSet disallowing duplicate weights, that completely slipped past me" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T13:11:08.137", "Id": "245559", "ParentId": "245518", "Score": "2" } } ]
{ "AcceptedAnswerId": "245522", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:26:44.923", "Id": "245518", "Score": "6", "Tags": [ "c#", "algorithm", "pathfinding" ], "Title": "C#: A* pathfinding - performance and simplicity" }
245518
<p>I'm working with Knockout3 in a Chromium 40 environment (ES5).</p> <p>I have a series of preset difficulty options, and a player has an option to switch to custom difficulty and tweak the options. When they tweak an option the save button lights up and the player cannot proceed to start the game until they save their settings. If they switch away from custom difficulty to a preset all changes are marked as saved so that they can proceed.</p> <p>To track whether there has been a change I am using ko.computed, and it all looks as follows:</p> <pre><code>model.gwaioDifficultySettings = { shuffleSpawns: ko.observable(true), easierStart: ko.observable(false), tougherCommanders: ko.observable(false), factionTech: ko.observable(false), customDifficulty: ko.observable(false), goForKill: ko.observable(false), microType: ko.observableArray([0, 1, 2]), microTypeDescription: ko.observable({ 0: &quot;!LOC:No&quot;, 1: &quot;!LOC:Basic&quot;, 2: &quot;!LOC:Advanced&quot;, }), microTypeChosen: ko.observable(0), getmicroTypeDescription: function (value) { return loc(model.gwaioDifficultySettings.microTypeDescription()[value]); }, mandatoryMinions: ko.observable(0).extend({ precision: 3, }), minionMod: ko.observable(0).extend({ precision: 3, }), priorityScoutMetalSpots: ko.observable(false), useEasierSystemTemplate: ko.observable(false), factoryBuildDelayMin: ko.observable(0).extend({ precision: 0, }), factoryBuildDelayMax: ko.observable(0).extend({ precision: 0, }), unableToExpandDelay: ko.observable(0).extend({ precision: 0, }), enableCommanderDangerResponses: ko.observable(false), perExpansionDelay: ko.observable(0).extend({ precision: 0, }), personalityTags: ko.observableArray([ &quot;Default&quot;, &quot;Tutorial&quot;, &quot;SlowerExpansion&quot;, &quot;PreventsWaste&quot;, ]), personalityTagsDescription: ko.observable({ Default: &quot;!LOC:Default&quot;, Tutorial: &quot;!LOC:Lobotomy&quot;, SlowerExpansion: &quot;!LOC:Slower Expansion&quot;, PreventsWaste: &quot;!LOC:Prevent Waste&quot;, }), personalityTagsChosen: ko.observableArray([]), getpersonalityTagsDescription: function (value) { return loc( model.gwaioDifficultySettings.personalityTagsDescription()[value] ); }, econBase: ko.observable(0).extend({ precision: 3, }), econRatePerDist: ko.observable(0).extend({ precision: 3, }), maxBasicFabbers: ko.observable(0).extend({ precision: 0, }), maxAdvancedFabbers: ko.observable(0).extend({ precision: 0, }), startingLocationEvaluationRadius: ko.observable(0).extend({ precision: 0, }), ffaChance: ko.observable(0).extend({ precision: 0, }), bossCommanders: ko.observable(0).extend({ precision: 0, }), landAnywhereChance: ko.observable(0).extend({ precision: 0, }), suddenDeathChance: ko.observable(0).extend({ precision: 0, }), bountyModeChance: ko.observable(0).extend({ precision: 0, }), bountyModeValue: ko.observable(0).extend({ precision: 3, }), unsavedChanges: ko.observable(false), newGalaxyNeeded: ko.observable(false).extend({ notify: &quot;always&quot; }), }; ko.computed(function () { if (model.gwaioDifficultySettings.customDifficulty()) { model.gwaioDifficultySettings.bossCommanders(); model.gwaioDifficultySettings.bountyModeChance(); model.gwaioDifficultySettings.bountyModeValue(); model.gwaioDifficultySettings.microTypeChosen(); model.gwaioDifficultySettings.personalityTagsChosen(); model.gwaioDifficultySettings.econBase(); model.gwaioDifficultySettings.econRatePerDist(); model.gwaioDifficultySettings.enableCommanderDangerResponses(); model.gwaioDifficultySettings.factoryBuildDelayMax(); model.gwaioDifficultySettings.factoryBuildDelayMin(); model.gwaioDifficultySettings.ffaChance(); model.gwaioDifficultySettings.goForKill(); model.gwaioDifficultySettings.landAnywhereChance(); model.gwaioDifficultySettings.mandatoryMinions(); model.gwaioDifficultySettings.maxAdvancedFabbers(); model.gwaioDifficultySettings.maxBasicFabbers(); model.gwaioDifficultySettings.minionMod(); model.gwaioDifficultySettings.perExpansionDelay(); model.gwaioDifficultySettings.priorityScoutMetalSpots(); model.gwaioDifficultySettings.startingLocationEvaluationRadius(); model.gwaioDifficultySettings.suddenDeathChance(); model.gwaioDifficultySettings.unableToExpandDelay(); model.gwaioDifficultySettings.useEasierSystemTemplate(); model.gwaioDifficultySettings.unsavedChanges(true); } }); // Prevent simply switching to GW-CUSTOM causing unsaved changes to become true model.gwaioDifficultySettings.customDifficulty.subscribe(function () { model.gwaioDifficultySettings.unsavedChanges(false); }); </code></pre> <p>This all seems to work rather well, except that switching to custom difficulty causes <code>unsavedChanges</code> to become true, when in reality the desired behaviour is that changes to fields like <code>shuffleSpawns</code> cause it to become true, but only when <code>customDifficulty</code> is true. I'm using a subscription to <code>customDifficulty</code> to workaround this, but given my inexperience with Knockout I'm wondering if there's a better way to achieve the desired result? I can replace the subscription with:</p> <pre><code>ko.computed(function () { model.gwaioDifficultySettings.customDifficulty(); model.gwaioDifficultySettings.unsavedChanges(false); }); </code></pre> <p>This achieves the same thing, but I've no idea if that's consider better, worse, or irrelevant.</p> <p>I have seen commentary on dirtyFlag extenders, and was wondering if that's the route I should have gone down, or if my current method is acceptable.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T11:39:35.660", "Id": "482158", "Score": "4", "body": "Fair enough. I've expanded the question to include the full view model" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T10:31:28.193", "Id": "245519", "Score": "6", "Tags": [ "javascript", "knockout.js" ], "Title": "Monitoring a view model for changes to display a save button" }
245519
<p>I have recently been working through a number of the <a href="https://cryptopals.com/" rel="nofollow noreferrer">Cryptopals Cryptography Challenges</a> to try and improve my knowledge and understanding of both cryptography and Python. As five of the first six challenges are XOR related problems I thought it would be a good idea to compile my work into a single program capable of encrypting, decrypting, and cracking using the XOR cipher. The program is capable of both single-byte and multi-byte encryption modes and can employ statistical analysis to guess a key when none is given.</p> <p>I have previously asked for reviews on my <a href="https://codereview.stackexchange.com/questions/214945/cracking-vigenere-and-caesar-ciphered-text-in-python">Ceasar and Vigenere implementations/crackers</a> and have included all of them together as a small suite for these fun little ciphers which I have uploaded to <a href="https://github.com/Jess-Turner/ciphertools" rel="nofollow noreferrer">a repository on GitHub</a>. I won't include all the code here but if possible I would like to know what improvements I could make to the overall structure of the project as I am trying to learn about how to organise a project like this with the intention of growing it with more and more encryption tools in the future. Due to folder structure dependencies I would suggest you clone the GitHub repository if you intend to run this code although all the relevant code will be posted below.</p> <p><strong>What I Would Like Feedback On</strong></p> <ul> <li>Correctness of my implementations. Please let me know if there are any errors in my code.</li> <li>Readability, Pythonic-ness, style, and documentation. I am learning Python with the intention of working with large teams on projects in the future and I feel these will be important for collaborative work.</li> <li>There is an issue with the method <code>predictKeySize()</code> in XORAnalysis.py in which it will have a strong bias towards short keys if it is allowed to guess short keys. As such it is currently hard coded to only guess lengths greater than 6 meaning my program is incapable of cracking keys between two and five characters long. Any ideas about how to improve this would be much appreciated</li> <li>Performance improvements and memory usage reductions. Not as important as other areas as the program isn't particularly slow or resource intensive but still nice to know about.</li> </ul> <p><strong>The Code</strong></p> <p><strong>xor.py</strong></p> <pre><code>#!/usr/bin/python3 &quot;&quot;&quot; Filename: xor.py Author: Jess Turner Date: 15/07/20 Licence: GNU GPL V3 Multipurpose XOR Encryption tool, can encrypt and decrypt text using a specified single-byte or multi-byte key or attempt to decrypt an input without a given key by using statistical analysis Options: --encrypt Enable encryption mode (Default) --decrypt Enable decryption mode --key Specify the encryption key --guess Attempt to guess the encryption key by statistical analysis --single-byte Enable single-byte XOR mode (Default) --multi-byte Enable multi-byte XOR mode &quot;&quot;&quot; import argparse import string import codecs import sys from itertools import cycle from internal.XORAnalysis import predictKeySize, multiByteXORCrack, multiByteXOR, repeatingByteXOR, repeatingByteXORCrack def initialiseParser(): parser = argparse.ArgumentParser(description = &quot;Encrypt, decrypt, or crack a message using the XOR Cipher&quot;) parser.add_argument(&quot;--key&quot;, &quot;-k&quot;, help = &quot;The encryption key to be used (if relevant)&quot;, type = str) parser.add_argument(&quot;--guess&quot;, &quot;-g&quot;, help = &quot;Perform statistical analysis to estimate the most likely value of the encryption key&quot;, action = &quot;store_true&quot;) parser.add_argument(&quot;--single-byte&quot;, &quot;--single&quot;, &quot;-s&quot;, help = &quot;Enable single-byte key mode&quot;, action = &quot;store_true&quot;) parser.add_argument(&quot;--multi-byte&quot;, &quot;--multi&quot;, &quot;-m&quot;, help = &quot;Enable multi-byte key mode&quot;, action = &quot;store_true&quot;) parser.add_argument(&quot;--decrypt&quot;, &quot;-d&quot;, help = &quot;Enable decryption mode&quot;, action = &quot;store_true&quot;) return parser def main(): parser = initialiseParser() args = parser.parse_args() inputString = sys.stdin.read().encode() if args.decrypt or args.guess: inputString = codecs.decode(inputString, &quot;base-64&quot;) if args.guess: if args.multi_byte: print(&quot;[+] Selecting multi-byte key mode...&quot;, file = sys.stderr) print(&quot;[+] Predicting key length...&quot;, file = sys.stderr) # At this point we have the entire decoded input in memory, all that is left is to crack it keyLength = predictKeySize(inputString) print(&quot;[-] Got length of {}...\n[+] Attempting to crack key...&quot;.format(keyLength), file = sys.stderr) crack = multiByteXORCrack(inputString, keyLength) key = crack['key'] else: print(&quot;[+] Selecting single-byte key mode...&quot;, file = sys.stderr) print(&quot;[+] Attempting to crack key...&quot;, file = sys.stderr) crack = repeatingByteXORCrack(inputString) key = chr(crack['key']) print(&quot;[-] Got key: \&quot;{}\&quot; !\n[+] Decrypting message...&quot;.format(key), file = sys.stderr) output = crack['message'] elif args.key != None: if len(args.key) &gt; 1 and not args.multi_byte: print(&quot;[+] Single-byte mode selected but multi-byte key was given. Defaulting to multi-byte mode...&quot;, file = sys.stderr) args.multi_byte = True output = multiByteXOR(inputString, [ord(c) for c in args.key]) if args.multi_byte else repeatingByteXOR(inputString, ord(args.key)) else: print(&quot;[-] Error: No key given!&quot;, file = sys.stderr) return if not args.decrypt and not args.guess: output = codecs.encode(output.encode(), &quot;base-64&quot;).decode() print(output, end = &quot;&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p><strong>XORAnalysis.py</strong></p> <pre><code>&quot;&quot;&quot; Filename: XORAnalysis.py Author: Jess Turner Date: 19/06/20 Licence: GNU GPL V3 A collection of analysis functions and pieces of information required byciphertools programs which implement XOR-based algorithms &quot;&quot;&quot; from itertools import cycle import string from .Strings import alphanumeric_characters, buildSubStrings # XOR analysis functions def letterRatio(inputString): return sum([x in alphanumeric_characters for x in inputString]) / len(inputString) def probablyText(inputString): return letterRatio(inputString) &gt; 0.7 # Functions for single-byte key XOR def repeatingByteXOR(inputString, byte): return &quot;&quot;.join(chr(c ^ byte) for c in inputString) def repeatingByteXORCrack(inputString): best = None for byte in range(256): currentString = repeatingByteXOR(inputString.strip(), byte) num_chars = sum([x in alphanumeric_characters for x in currentString]) if best == None or num_chars &gt; best['num_chars']: best = { 'message': currentString, 'num_chars': num_chars, 'key': byte } return best # Functions for multi-byte key XOR def multiByteXORCrack(inputString, keyLength): key = &quot;&quot;.join(chr(repeatingByteXORCrack(string.strip())['key']) for string in buildSubStrings(inputString, keyLength)) message = multiByteXOR(inputString, key.encode()) return { 'message': message, 'key': key } def multiByteXOR(inputString, key): return &quot;&quot;.join(chr(c ^ byte) for c, byte in zip(inputString, cycle(key))) # Functions for multi-byte XOR key length prediction def XORStrings(first, second): return bytes([i ^ j for i, j in zip(first, second)]) # Convert two byte strings to their xor product def hammingDistance(first, second): return bin(int.from_bytes(XORStrings(first, second), &quot;little&quot;)).count(&quot;1&quot;) # Calculate the bit difference between two strings def predictKeySize(inputString): bestKey = 0 bestDistance = 10000 for i in range(6, 40): # Set to a lower bound of 6 because otherwise it always guesses a really short key. Will try and fix in later version. distance = 0 blocks = len(inputString) // i - 1 for x in range(blocks): distance += hammingDistance(inputString[i * x:i * (x + 2) - 1], inputString[i * (x + 2):i * (x + 4) - 1]) distance /= i distance /= blocks if distance &lt; bestDistance: bestDistance = distance bestKey = i return bestKey </code></pre> <p><strong>Strings.py</strong></p> <pre><code>&quot;&quot;&quot; Filename: strings.py Author: Jess Turner Date: 28/09/19 Licence: GNU GPL V3 A collection of functions for the modification of strings required by multiple programs in the ciphertools suite &quot;&quot;&quot; import re alphanumeric_characters = &quot;1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz &quot; english = { 'monogram-frequencies': [8.167, 1.492, 2.782, 4.253, 12.702, 2.228, 2.015, 6.094, 6.966, 0.153, 0.772, 4.025, 2.406, 6.749, 7.507, 1.929, 0.095, 5.987, 6.327, 9.056, 2.758, 0.978, 2.360, 0.150, 1.974, 0.074 ], 'bigram-frequencies': [] } def stringPrepare(string, preserveSpacing): # Strip all non alphabetic characters from a string and convert to upper case return re.compile(&quot;[^A-Z\s]&quot; if preserveSpacing else &quot;[^A-Z]&quot;).sub(&quot;&quot;, string.upper()) def buildSubStrings(string, separation): # Build a list of substrings required to analyse the ciphertext return [string[i::separation] for i in range(separation)] </code></pre>
[]
[ { "body": "<h2>Nomenclature</h2>\n<p>By PEP8, <code>initialiseParser</code> should be <code>initialise_parser</code>, and similarly for <code>inputString</code>, etc.</p>\n<h2>String interpolation</h2>\n<pre><code>print(&quot;[-] Got length of {}...\\n[+] Attempting to crack key...&quot;.format(keyLength), file = sys.stderr)\n</code></pre>\n<p>is simpler as</p>\n<pre><code>print(\n f&quot;[-] Got length of {key_length}...\\n&quot;\n &quot;Attempting to crack key...&quot;,\n file=sys.stderr,\n)\n</code></pre>\n<h2>Type hints</h2>\n<p>For example,</p>\n<pre><code>def probablyText(inputString):\n</code></pre>\n<p>can be</p>\n<pre><code>def probably_text(input_string: str) -&gt; bool:\n</code></pre>\n<h2>Sum without a comprehension</h2>\n<pre><code>sum([x in alphanumeric_characters for x in currentString])\n</code></pre>\n<p>should use the generator directly instead of making a list; i.e.</p>\n<pre><code>sum(x in alphanumeric_characters for x in current_string)\n</code></pre>\n<p>The same goes for</p>\n<pre><code>return bytes([i ^ j for i, j in zip(first, second)]) # Convert two byte strings to their xor product\n</code></pre>\n<h2>Strongly-typed results</h2>\n<pre><code>best = { 'message': currentString, 'num_chars': num_chars, 'key': byte }\n</code></pre>\n<p>If you're only doing this because you need to return multiple things, idiomatic Python is to simply return them as a tuple, i.e.</p>\n<pre><code>best = current_string, num_chars, byte\n# ...\nreturn best\n</code></pre>\n<p>But this would be better-represented by a named tuple, or (better) a <code>@dataclass</code> with type hints. Just not a dictionary.</p>\n<h2>Combined division</h2>\n<pre><code> distance /= i\n distance /= blocks\n</code></pre>\n<p>can be</p>\n<pre><code>distance /= i * blocks\n</code></pre>\n<h2>Sums rather than successive addition</h2>\n<pre><code> for x in range(blocks):\n distance += hammingDistance(inputString[i * x:i * (x + 2) - 1], inputString[i * (x + 2):i * (x + 4) - 1])\n</code></pre>\n<p>can be</p>\n<pre><code>distance = sum(\n hamming_distance(\n input_string[i*x : i*(x+2)-1],\n input_string[i*(x+2) : i*(x+4)-1],\n )\n for x in range(blocks)\n)\n</code></pre>\n<h2>Drop dictionaries to variables</h2>\n<p>Given your current code,</p>\n<pre><code>english = { 'monogram-frequencies': [8.167, 1.492, 2.782, 4.253, 12.702, 2.228, 2.015, 6.094, 6.966, 0.153, 0.772, 4.025, 2.406, 6.749, 7.507, 1.929, 0.095, 5.987, 6.327, 9.056, 2.758, 0.978, 2.360, 0.150, 1.974, 0.074 ],\n 'bigram-frequencies': [] }\n</code></pre>\n<p>should simply be a monogram variable and a bigram variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T15:08:55.973", "Id": "245525", "ParentId": "245523", "Score": "6" } } ]
{ "AcceptedAnswerId": "245525", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T13:07:45.457", "Id": "245523", "Score": "8", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge", "cryptography" ], "Title": "XOR Encryption, Decryption, and Cracking in Python" }
245523
<p>I want to know if it is okay/safe to use a prepared statement and <code>mysqli_num_rows</code> like this:</p> <pre><code>public function getUnreadNumber() { $userLoggedIn = $this-&gt;user_obj-&gt;getUsername(); // get_result for * and bind for select columns // bind_result Doesn't work with SQL query that use * $query = $this-&gt;con-&gt;prepare('SELECT * FROM notifications WHERE viewed=&quot;0&quot; AND user_to = ? '); $query-&gt;bind_param(&quot;s&quot;, $userLoggedIn); $query-&gt;execute(); $query_result = $query-&gt;get_result(); return mysqli_num_rows($query_result); } </code></pre> <p>Or should I do this?</p> <pre><code>$query = $this-&gt;con-&gt;prepare('SELECT * FROM notifications WHERE viewed=&quot;0&quot; AND user_to = ? '); $query-&gt;bind_param(&quot;s&quot;, $userLoggedIn); $query-&gt;execute(); $query_result = $query-&gt;get_result(); $numRows = $query_result-&gt;num_rows; return $numRows; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T19:11:53.993", "Id": "482188", "Score": "0", "body": "So is it ok if I use this with a prepared statement ? `return mysqli_num_rows($query_result)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T19:26:00.430", "Id": "482189", "Score": "0", "body": "http://www.nusphere.com/kb/phpmanual/function.mysqli-num-rows.htm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T19:40:48.423", "Id": "482190", "Score": "1", "body": "That hasn't been updated since 06" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T05:34:01.030", "Id": "482210", "Score": "2", "body": "What are the possible values returned by `this->user_obj->getUsername()`??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T11:11:23.047", "Id": "482250", "Score": "2", "body": "(If you are not ready to value *feedback and criticism* for [any aspect of the code posted](https://codereview.stackexchange.com/help/on-topic), your question is off-topic.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:43:01.287", "Id": "482316", "Score": "0", "body": "@greybeard what are you responding to? Was there a comment that is now deleted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T22:47:52.963", "Id": "482325", "Score": "0", "body": "I didn't delete a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T04:54:41.350", "Id": "482344", "Score": "0", "body": "(@mickmackusa: I was not responding to anything, let alone a comment. My reference to the definition of the topic of the Code Review Stack Exchange has been triggered by the single \"laser-like\" question `[is it] okay/safe to use a prepared statement and mysqli_num_rows [… or] should I [use get_result()->num_rows]?` From [What types of questions should I avoid asking?](https://codereview.stackexchange.com/help/dont-ask): `It's OK to ask \"Does this code follow common best practices?\", but not \"What is the best practice regarding X?\"`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T07:48:30.490", "Id": "482662", "Score": "0", "body": "Have you considered using `SELECT COUNT(*) FROM ...`?" } ]
[ { "body": "<p>You should definitely not be mixing procedural and object-oriented syntax.</p>\n<p>Although it works with un-mixed syntax, the process is working harder than it needs to and delivering more result set data than you intend to use.</p>\n<p>I would add <code>COUNT(1)</code> or <code>COUNT(*)</code> to the sql like this:</p>\n<pre><code>$sql = &quot;SELECT COUNT(1) FROM notifications WHERE viewed='0' AND user_to = ?&quot;;\n$query = $this-&gt;con-&gt;prepare($sql);\n$query-&gt;bind_param(&quot;s&quot;, $userLoggedIn);\n$query-&gt;execute();\n$query-&gt;bind_result($count);\n$query-&gt;fetch();\nreturn $count;\n</code></pre>\n<p>Assuming the sql is not broken due to syntax errors, this will always return a number.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T23:20:51.140", "Id": "245536", "ParentId": "245527", "Score": "6" } }, { "body": "<p>@mickmackusa is correct, you should <strong>never ever use num_rows</strong> to count the rows in the database, it could kill your database server. This function is rather useless for any other use case too.</p>\n<p>Besides, always follow the rule of thumb: make a database to do the job. If you need tell a database to give you the count.</p>\n<p>As a code improvement, let me suggest you a <a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"nofollow noreferrer\">mysqli helper function</a> I wrote to put all the prepare/bind/execute business under the hood</p>\n<pre><code>public function getUnreadNumber()\n{\n $userLoggedIn = $this-&gt;user_obj-&gt;getUsername();\n $sql = &quot;SELECT COUNT(1) FROM notifications WHERE viewed='0' AND user_to = ?&quot;;\n return prepared_query($this-&gt;con, $sql, $userLoggedIn)-&gt;get_result()-&gt;fetch_row()[0];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:41:35.617", "Id": "482433", "Score": "0", "body": "`If you need` *a count* `tell a database to give you the count.`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:15:51.440", "Id": "245547", "ParentId": "245527", "Score": "3" } } ]
{ "AcceptedAnswerId": "245536", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T17:26:51.253", "Id": "245527", "Score": "1", "Tags": [ "php", "comparative-review", "mysqli" ], "Title": "Return row count from mysqli prepared statement" }
245527
<p>I Used <a href="https://developer.android.com/training/data-storage/shared/media" rel="nofollow noreferrer">MediaStore</a> to scan and display media files from my storage using below code</p> <pre><code>private void displayAllVideos() { Uri uri; Cursor cursor; VideoAdapter videoAdapter; int column_index_data,thum; String absolutePathThumb; uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA}; final String orderBy = MediaStore.Video.Media.DATE_ADDED + &quot; DESC&quot;; cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy); column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA); while (cursor.moveToNext()){ Log.d(&quot;VIDEO&quot;, cursor.getString(0)); absolutePathThumb = cursor.getString(column_index_data); Uri thumbUri = Uri.fromFile(new File(absolutePathThumb)); //String cursorThumb = cursor.getString(thum); String fileName = FilenameUtils.getBaseName(absolutePathThumb); String extension = FilenameUtils.getExtension(absolutePathThumb); String duration = getDuration(absolutePathThumb); VideoModel videoModel = new VideoModel(); videoModel.setDuration(duration); videoModel.setVideo_uri(thumbUri.toString()); videoModel.setVideo_path(absolutePathThumb); videoModel.setVideo_name(fileName); videoModel.setVideo_thumb(cursor.getString(thum)); if (extension!=null){ videoModel.setVideo_extension(extension); }else { videoModel.setVideo_extension(&quot;mp4&quot;); } if (duration!=null){ videoModel.setDuration(duration); }else { videoModel.setDuration(&quot;00:00&quot;); } arrayListVideos.add(videoModel); } </code></pre> <p>with above code i can able to get and display video file, Is there anything i need to improve in my code.</p> <p>Your help in need thanks in advance.android</p>
[]
[ { "body": "<p>There are no big issues with your method, but I noticed something that can be improved:</p>\n<p><strong>Variable declaration</strong></p>\n<p>In Java is not common to declare the variables at the beginning of the method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Uri uri;\nCursor cursor;\nVideoAdapter videoAdapter;\nint column_index_data,thum;\n\nString absolutePathThumb;\n</code></pre>\n<p>Declare and initialize variables in the same place, it's easier to read and maintain.</p>\n<p>By the way, <code>videoAdapter</code> is declared but never used, that's another reason why you should avoid doing this.</p>\n<p><strong>Query results not used</strong></p>\n<p>Here you configure the projection:</p>\n<pre class=\"lang-java prettyprint-override\"><code>String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};\n</code></pre>\n<p>But after the query you never use the results for <code>MediaStore.Video.Media.BUCKET_DISPLAY_NAME</code> and <code>MediaStore.Video.Media._ID</code>.</p>\n<p><strong>Close the resources</strong></p>\n<p>The <code>Cursor</code> object which is returned from the query is a resouce that needs to be closed:</p>\n<pre class=\"lang-java prettyprint-override\"><code>cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);\n</code></pre>\n<p>To close it automatically use the <code>try-with-resources</code> statement:</p>\n<pre class=\"lang-java prettyprint-override\"><code>try (Cursor cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy)) { \n// ...\n}\n</code></pre>\n<p><strong>Camelcase instead of underscore</strong></p>\n<p>From the <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html#367\" rel=\"nofollow noreferrer\">Java Naming Convention</a>:</p>\n<blockquote>\n<p>Methods should be verbs, in mixed case with the first letter\nlowercase, with the first letter of each internal word capitalized.</p>\n</blockquote>\n<p>So instead of <code>videoModel.setVideo_uri()</code> use <code>videoModel.setVideoUri()</code> or even better <code>videoModel.setUri()</code>. Similarly for the other methods.</p>\n<p><strong>Duplicated assignment</strong></p>\n<p><code>videoModel.setDuration(duration)</code> is called three times. Compute the value of <code>duration</code> first and add it to <code>videoModel</code> only once.</p>\n<p><strong>Ternary operator instead of if-else</strong></p>\n<p>Sometime using the ternary operator is better for readability. For example instead of:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (extension!=null){\n videoModel.setVideo_extension(extension);\n}else {\n videoModel.setVideo_extension(&quot;mp4&quot;);\n}\n</code></pre>\n<p>You can get the same result with:</p>\n<pre class=\"lang-java prettyprint-override\"><code>String extension = extension != null ? extension : &quot;mp4&quot;;\nvideoModel.setVideo_extension(extension);\n</code></pre>\n<p><strong>Documentation</strong></p>\n<p>In the link you posted there is an <a href=\"https://developer.android.com/training/data-storage/shared/media#query-collection\" rel=\"nofollow noreferrer\">example</a> that is very similar to your use case. Most of my suggestions are already mentioned there, read it carefully.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-22T02:59:05.420", "Id": "489505", "Score": "0", "body": "hi, i was not able to retrieve some video files ?. any help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T08:24:39.743", "Id": "245738", "ParentId": "245528", "Score": "1" } } ]
{ "AcceptedAnswerId": "245738", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T18:36:52.153", "Id": "245528", "Score": "3", "Tags": [ "java", "android" ], "Title": "Displaying Video file from storage with MediaStore in android Java" }
245528
<p>I'm looking to see if there are any better / faster ways of identifying table structures on a page without gridlines.</p> <p>The text is extracted from the file and the coordinates of each block of text are stored in a dataframe. For the sake of this snippet, this has already been generated and has yielded the dataframe below. This is ordered top to bottom, left to right in reading order.</p> <p>The bounding box (x,y,x1,y1) is represented below as (left,top,left1,top1). Middle is the mid-point between left and left1 and left_diff is the gap between current rows starting x position (left) and previous rows finishing x1 position (left1.shift()). Width is the left to left1 size.</p> <pre><code> top top1 left middle left1 left_diff width 0 78.0 126 54 62.0 70.0 NaN 16.0 1 78.0 123 71 94.0 118.0 1.0 47.0 2 78.0 126 125 136.0 147.0 7.0 22.0 3 78.0 123 147 215.0 283.0 0.0 136.0 4 167.0 199 54 130.0 206.0 -229.0 152.0 5 167.0 187 664 701.0 739.0 458.0 75.0 6 186.0 204 664 722.0 780.0 -75.0 116.0 7 202.0 220 664 751.0 838.0 -116.0 174.0 8 212.0 234 54 347.0 641.0 -784.0 587.0 9 212.0 237 664 737.0 811.0 23.0 147.0 10 232.0 254 54 347.0 641.0 -757.0 587.0 11 232.0 253 664 701.0 738.0 23.0 74.0 12 232.0 253 826 839.0 853.0 88.0 27.0 13 253.0 275 54 137.0 220.0 -799.0 166.0 14 268.0 286 664 717.0 770.0 444.0 106.0 15 285.0 310 54 347.0 641.0 -716.0 587.0 16 285.0 303 664 759.0 855.0 23.0 191.0 17 301.0 330 54 347.0 641.0 -801.0 587.0 18 301.0 319 664 684.0 704.0 23.0 40.0 19 301.0 319 826 839.0 853.0 122.0 27.0 20 328.0 350 54 347.0 641.0 -799.0 587.0 ....... etc...... </code></pre> <p>My method here is to group by an x coordinate (taking into account the text could be justified left, centred or to the right), search for ant other points which are close (within a tolerance of 5 pixels in this snippet). This gives me my columns.</p> <p>Then, for each column identified, look to see where the rows are by looking for the points at which the gap between rows is over a certain a threshold. Here, we take the indexes of the points where the text should break and generate index pairs. By taking the max and min points, we can generate a bounding box around this cell.</p> <p>Then, I look to see if there are other boxes located on the same x coordinate and store this in a table list.</p> <p>Finally, form pairs from the tables and look at the index distance between each of the items in the table list. As the indexes should run sequentially, this should equal 1. If it doesn't, this indicates that the table doesn't continue.</p> <pre><code>import itertools def pairwise(splits): &quot;s -&gt; (s0,s1), (s1,s2), (s2, s3), ...&quot; a, b = itertools.tee(splits, 2) next(b, None) return list(zip(a, b)) def space_sort(df): groups = df.groupby('page') pages = {i:j[['top','top1','left','middle','left1']] for i,j in groups} cols = ['left','middle','left1'] boxes = {} for page in pages: rows = {} c_df = pages[page] min_x = min(c_df.left) gaps = c_df.loc[df.left_diff&gt;5] # value count on left, middle and left1 values so we can deal with text justification. counts = {'left':[], 'middle':[], 'left1':[]} [counts[col].append(gaps[col].unique()) for col in cols if (gaps[col].value_counts()&gt;2).any()] if len(counts['left'])&gt;0: counts['left'][0] = np.insert(counts['left'][0], 0, int(min_x)) # search c_df for other points close to these x values. for col in cols: if len(counts[col])&gt;0: for x in counts[col][0]: row_spaces = {} matches = c_df.loc[np.isclose(c_df[col],x, atol=5)] left_groups = df_coord.loc[matches.index.values].reset_index() # find points where line diff &gt; 5 indicating new row. Get indexes. vert_gaps = left_groups.loc[(left_groups.top - left_groups.top1.shift())&gt;5] vert_indexes = vert_gaps.index.values vert_indexes = np.insert(vert_indexes,0,0) vert_indexes = np.append(vert_indexes,len(left_groups)) # form groups between rows. pairs = pairwise(vert_indexes) for start,end in pairs: box = left_groups.loc[start:end-1] coords = (page, min(box.top),min(box.left),max(box.top1),max(box.left1)) boxes[coords]=(list(left_groups.loc[start:end-1,('index')])) # Find close boxes by seeing which align on the same x value (either top, centre or bottom) table = [] for a, b in itertools.combinations(boxes, 2): a_pg, a_top, a_left, a_top1, a_left1 = a b_pg, b_top, b_left, b_top1, b_left1 = b a_centre = (a_top+a_top1)//2 b_centre = (b_top+b_top1)//2 if (np.isclose(a_top, b_top, atol=5)) | (np.isclose(a_centre, b_centre, atol=5)) | (np.isclose(a_top1, b_top1, atol=5)): table.append([boxes[a],boxes[b]]) # Table list contains two lists of indexes of rows which are close together. # As ordered, the indexes should be sequential. # If difference between one pair and next is 1, sequential. If not, reset rows t = (pairwise(table)) row = 0 for i in t: if (i[1][0][-1] - i[0][1][-1]) == 1: for r in i: row+=1 num = 1 for col in r: print('indexes', col, 'row',row, 'col',num) num+=1 else: row = 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T21:44:31.967", "Id": "482194", "Score": "3", "body": "But why? If this is a \"contrived\" problem for you to practice on, then fine. But if you have to do this in real life, something is wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T21:58:05.080", "Id": "482195", "Score": "1", "body": "Its for preserving tables and paragraph formatting from pdfs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T22:11:29.683", "Id": "482196", "Score": "3", "body": "There are better ways to extract tables from a PDF than copying and pasting text out of them if the PDF is well-understood and comes from the same source every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T22:22:58.117", "Id": "482198", "Score": "0", "body": "The documents are highly variable, not well structured and require preprocessing so at no point is any copying and pasting done. This aims to identify tables where no gridlines are present and give some structure to the doc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T22:32:47.763", "Id": "482199", "Score": "0", "body": "If there is no copying and pasting being done, how do you get the text? OCR?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T06:02:35.783", "Id": "482213", "Score": "0", "body": "The PyPDF2 package does a good job of extracting the text and there's poppler-utils which have some good binaries. This question starts from the point at which the text has already been extracted with the dataframe above representing the coordinates of each of the blocks of text on the page. The task then is to try and get some sense of order from the coordinates which indicate a table and this is what I'm getting at with this question. Whilst this works, I'm sure this could be improved which is what I'm looking for some input with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T14:32:02.883", "Id": "482262", "Score": "0", "body": "I'm confused by the dataframe. What does each column of the sample dataframe correspond to? You've mentioned x co-ordinates, but I don't know which is which? What is df.left_diff?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T14:48:31.627", "Id": "482263", "Score": "0", "body": "Hi @spyr03 - sorry, this isn't clear. I'll update the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:31:02.783", "Id": "482289", "Score": "0", "body": "@lawson I've posted a review, but I'm not happy with it, in that I don't directly address the performance aspect of your question. Hopefully someone else can enlighten us with more knowledge in this area." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T20:10:49.623", "Id": "482311", "Score": "0", "body": "Do you already know how many rows and columns there are, or does the code need to figure that out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:06:14.853", "Id": "482315", "Score": "0", "body": "Hi @RootTwo - yes, need the code to figure that out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T23:54:40.567", "Id": "482328", "Score": "0", "body": "The provided code doesn't appear to work with the sample data. 'page' column is missing. Fix that and get \"NameError: name 'df_coord' is not defined\". Also, what is the expected output for the sample data." } ]
[ { "body": "<p>The process I would follow to improve the performance of any code would be to go through it in 3 passes,</p>\n<ol>\n<li>Cleaning - fix those small issues of style, fix bigger issues of semantics, and make the code nice to read.</li>\n<li>Understanding - find out what we actually want to tell the computer to do.</li>\n<li>Improving - choosing more appropriate algorithms or data structures for the task(s).</li>\n</ol>\n<p>Below I'll walk you through the steps I would take for cleaning up the code.</p>\n<hr />\n<p>The code as it stands is decent. There are some formatting issues, but the spacing and comments are pretty nice. Good job.</p>\n<p>The first thing that stands out is the small inconsistencies. I would suggest using an auto-formatting tool (black, yapf, etc) to find and fix those sort of problems, we really don't need to be wasting mental resources on them. As an example, the spacing between arguments in <code>c_df.loc[np.isclose(c_df[col],x, atol=5)]</code> is not consistent.</p>\n<p>While we are discussing tooling, a linter (pep8, pylint, pyflakes, etc) also picks up on some quick things to clean up. I wouldn't worry too much about lint warnings (or scoring), but I would take into account any critical errors it points out. For example, a quick lint highlights unused variables <code>row_spaces = {}</code> and missing imports &quot;undefined name 'np'&quot;.</p>\n<p>One minor issue which these tools don't catch is extra characters. Often I find code to look a lot nicer if there is less of it. Python is quite good about this, as you don't need brackets around conditions in if statements, or necessarily need square brackets when the generator expression will do.</p>\n<p>If you want, here is the code I will base the next clean up on. I've fixed lint errors like unused variables, removed extra parenthesis, and removed comments for brevity. One thing of note is that in <code>left_groups = df_coord.loc[matches.index.values].reset_index()</code> df_coords is undefined, and I don't know what it should actually be.</p>\n<pre><code>def pairwise(splits):\n &quot;s -&gt; (s0,s1), (s1,s2), (s2, s3), ...&quot;\n a, b = itertools.tee(splits, 2)\n next(b, None)\n return list(zip(a, b))\n\n\ndef space_sort(df):\n groups = df.groupby('page')\n pages = {\n i: j[['top', 'top1', 'left', 'middle', 'left1']]\n for i, j in groups\n }\n cols = ['left', 'middle', 'left1']\n boxes = {}\n for page in pages:\n c_df = pages[page]\n min_x = min(c_df.left)\n gaps = c_df.loc[df.left_diff &gt; 5]\n\n #\n counts = {'left': [], 'middle': [], 'left1': []}\n [\n counts[col].append(gaps[col].unique()) for col in cols\n if (gaps[col].value_counts() &gt; 2).any()\n ]\n\n if len(counts['left']) &gt; 0:\n counts['left'][0] = np.insert(counts['left'][0], 0, int(min_x))\n\n #\n for col in cols:\n if len(counts[col]) &gt; 0:\n for x in counts[col][0]:\n matches = c_df.loc[np.isclose(c_df[col], x, atol=5)]\n left_groups = df_coord.loc[\n matches.index.values].reset_index()\n\n #\n vert_gaps = left_groups.loc[(left_groups.top -\n left_groups.top1.shift()) &gt; 5]\n vert_indexes = vert_gaps.index.values\n vert_indexes = np.insert(vert_indexes, 0, 0)\n vert_indexes = np.append(vert_indexes, len(left_groups))\n\n #\n pairs = pairwise(vert_indexes)\n for start, end in pairs:\n box = left_groups.loc[start:end - 1]\n coords = (page, min(box.top), min(box.left),\n max(box.top1), max(box.left1))\n boxes[coords] = list(left_groups.loc[start:end - 1,\n ('index')])\n\n #\n table = []\n for a, b in itertools.combinations(boxes, 2):\n a_pg, a_top, a_left, a_top1, a_left1 = a\n b_pg, b_top, b_left, b_top1, b_left1 = b\n a_centre = (a_top + a_top1) // 2\n b_centre = (b_top + b_top1) // 2\n if np.isclose(a_top, b_top, atol=5) | np.isclose(\n a_centre, b_centre, atol=5) | np.isclose(\n a_top1, b_top1, atol=5):\n table.append([boxes[a], boxes[b]])\n\n #\n t = pairwise(table)\n row = 0\n for i in t:\n if (i[1][0][-1] - i[0][1][-1]) == 1:\n for r in i:\n row += 1\n num = 1\n for col in r:\n print('indexes', col, 'row', row, 'col', num)\n num += 1\n else:\n row = 0\n</code></pre>\n<hr />\n<pre><code>def pairwise(splits):\n &quot;s -&gt; (s0,s1), (s1,s2), (s2, s3), ...&quot;\n</code></pre>\n<p>PEP8 defers to <a href=\"https://www.python.org/dev/peps/pep-0257/#one-line-docstrings\" rel=\"nofollow noreferrer\">PEP257</a> for docstring convention. Convention dictates even single line docstrings should have three double quotes.</p>\n<hr />\n<pre><code>cols = ['left', 'middle', 'left1']\n</code></pre>\n<p>It looks like <code>cols</code> is not modified anywhere else in the code. You can enforce its immutability by changing <code>cols</code> to a tuple. This is useful to prevent accidental edits. The change is rather nice to make, just drop the square brackets.</p>\n<pre><code>cols = 'left', 'middle', 'left1'\n</code></pre>\n<hr />\n<pre><code>counts = {'left': [], 'middle': [], 'left1': []}\n[\n counts[col].append(gaps[col].unique()) for col in cols\n if (gaps[col].value_counts() &gt; 2).any()\n]\n</code></pre>\n<p>Modifying <code>counts</code> inside of a list comprehension is quite unexpected. List comprehensions are usually used to construct new lists. I would suggest turning this into a loop.</p>\n<p>There is a potential bug waiting to happen. If <code>cols</code> is added to, but <code>counts</code> is forgotten about, an exception will occur due to the missing key.</p>\n<pre><code>&gt;&gt;&gt; cols = ['left', 'middle', 'left1', 'middle_y']\n&gt;&gt;&gt; counts = {'left': [], 'middle': [], 'left1': []}\n&gt;&gt;&gt; counts['middle_y'].append(42.0)\n\nKeyError: 'middle_y'\n</code></pre>\n<p>I think you should link <code>counts</code> to <code>cols</code> with something like <code>counts = {col: [] for col in cols}</code> or make a note beside one of them reminding whoever to do the manual update.</p>\n<hr />\n<pre><code>counts['left'][0] = np.insert(counts['left'][0], 0, int(min_x))\n</code></pre>\n<p>The docs for <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.insert.html\" rel=\"nofollow noreferrer\">np.insert</a> have a see also section (which I find incredibly useful for when you just can't remember the name of a function, but you know a similar one). In it is np.concatentation. While searching for the difference between them, I found two results that suggest you may get better performance by changing the insert to a concatentation<sup><a href=\"https://stackoverflow.com/a/43184184/3503611\">1</a>,<a href=\"https://stackoverflow.com/a/54773471/3503611\">2</a></sup>. I don't know how someone would figure this out by themselves, but hey, potentially a free performance win. You just need to measure it now.</p>\n<hr />\n<pre><code>for col in cols:\n if len(counts[col]) &gt; 0:\n ...\n</code></pre>\n<p>I would much prefer a guard clause here, since the if statement has no else, and since the code inside continues to indent. Less indentation is a good goal. It gives you more room on each subsequent line, and a lot of indentation is an indication of (overly) complicated code<sup><a href=\"https://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">3</a></sup>.</p>\n<pre><code>for col in cols:\n if len(counts[col]) == 0:\n continue\n ...\n</code></pre>\n<hr />\n<pre><code>vert_indexes = vert_gaps.index.values\nvert_indexes = np.insert(vert_indexes, 0, 0)\nvert_indexes = np.append(vert_indexes, len(left_groups))\n</code></pre>\n<p>I think np.concatenate would be especially useful here, since it would make it clear you are pre-pending and appending to the indexes. It could also perform the task more efficiently as it only needs to make one copy of <code>vert_indexes</code> instead of the two above.</p>\n<pre><code>vert_indexes = np.concatenate([0], vert_gaps.index.values, [len(left_groups)])\n</code></pre>\n<p>You should double check this. Without trying it out I don't know if it fails to flatten when it should (and therefore needs axis=None or something).</p>\n<hr />\n<pre><code>a_pg, a_top, a_left, a_top1, a_left1 = a\nb_pg, b_top, b_left, b_top1, b_left1 = b\na_centre = (a_top + a_top1) // 2\nb_centre = (b_top + b_top1) // 2\nif np.isclose(a_top, b_top, atol=5) | np.isclose(\n a_centre, b_centre, atol=5) | np.isclose(\n a_top1, b_top1, atol=5):\n</code></pre>\n<p>You probably want the short circuiting behaviour that the keyword <code>or</code> provides. I don't see a reason to use the bitwise or instead.</p>\n<p>I don't like the unpacking that happens here. If you change the order of packing in <code>coords</code>, it will become outdated here (and vice versa). There is no link between them, so it may silently break. Without good tests you may not notice for a long time. I don't have a solution to this problem, so this is just a &quot;be wary&quot;.</p>\n<p>On a related note to the unpacking, there is a nice idiom for unused variables. As only a_top, a_top1, b_top, and b_top1, you can reduce the noise by using an <a href=\"https://stackoverflow.com/a/5893946/3503611\">underscore</a> to indicate you know about this variable, but don't need it.</p>\n<p>The section of code might now look something like this</p>\n<pre><code>_, a_top, _, a_top1, _ = a\n_, b_top, _, b_top1, _ = b\na_centre = (a_top + a_top1) // 2\nb_centre = (b_top + b_top1) // 2\nif np.isclose(a_top, b_top, atol=5) or np.isclose(\n a_centre, b_centre, atol=5) or np.isclose(\n a_top1, b_top1, atol=5):\n table.append([boxes[a], boxes[b]])\n</code></pre>\n<p>There is some incongruence in this code. There is a mismatch between using np.isclose (which I would expect to be used for floating point numbers) and // 2 (which I would expect for integers). So, are the variables expected to be floats or integers? Should the integer division (<code>// 2</code>) be floating point division (<code>/ 2</code>), or is np.isclose overkill when <code>abs(a_top - b_top) &lt;= 5</code> would do?</p>\n<hr />\n<pre><code>for i in t:\n if (i[1][0][-1] - i[0][1][-1]) == 1:\n for r in i:\n</code></pre>\n<p>This code is not easy to understand at a glance, mostly due to the variable names. Do you have more descriptive names you could use? What are <code>i[1][0]</code> and <code>i[0][1]</code>? Is this just debugging code and can be left out?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:46:50.637", "Id": "482297", "Score": "0", "body": "@spr03 - That's a really generous write up so thanks very much indeed for all of this. Given I'm a solo-coder, this sort of peer review is hugely helpful. I'll see what other answers pop up before marking correct as I'm ideally looking for some insight as to whether the general approach is the best one to take here but very much appreciate the detailed review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:26:14.797", "Id": "245572", "ParentId": "245532", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T21:36:53.390", "Id": "245532", "Score": "4", "Tags": [ "python", "performance", "pandas" ], "Title": "Determine table structure in pdf using whitespace between coordinates" }
245532
<p>I'm building a functional React component that allows a list of products to be sorted by various properties. The properties could be top-level or nested properties. And I'd also like a sort order to be defined. As a secondary sort, I'd like a <code>name</code> property to be used.</p> <p>I have left out the React parts to boil it down to the plain JS.</p> <p>Here's my first take on it:</p> <pre><code>sort = [one-of-the-cases] ascending = [true||false] const sortFunc = (a, b) =&gt; { let aParam = null let bParam = null switch (sort) { case 'brand': aParam = a.brand.title bParam = b.brand.title break case 'weight': aParam = a.metadata.weight bParam = b.metadata.weight break case 'price': aParam = a.price.unit_amount bParam = b.price.unit_amount break case 'style': aParam = a.metadata.style bParam = b.metadata.style break case 'arrival': aParam = b.created bParam = a.created break default: aParam = a.brand.title bParam = b.brand.title break } // Sort by property, ascending or descending if (aParam &lt; bParam) { return ascending ? -1 : 1 } if (aParam &gt; bParam) { return ascending ? 1 : -1 } // Sort by name if (a.name &lt; b.name) { return -1 } if (a.name &gt; b.name) { return 1 } return 0 } products.sort(sortFunc) </code></pre> <p>This seems overly complicated. One idea I have is to flatten the object to eliminate the nested properties, which would make it possible to store the sort param as a variable, and use bracket notation to reference the object property. This would eliminate the switch statement.</p> <p>Any other ideas for simplifying this complicated sort?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T22:16:10.237", "Id": "482197", "Score": "0", "body": "Did you omit the `ascending` intentionally from the `name` comparison?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:11:12.050", "Id": "482222", "Score": "0", "body": "For now, yes. The name comparison is to order by name in the case there are matches in the first comparison." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T13:46:13.777", "Id": "482259", "Score": "0", "body": "@BrettDeWoody That right there should be a comment ;)" } ]
[ { "body": "<p>From a short review;</p>\n<ul>\n<li><code>ascending</code> should probably be a parameter in the <code>sortFunc</code></li>\n<li><code>sort</code> (<code>sortKey</code>) should probably be a parameter in the <code>sortFunc</code></li>\n<li>I feel things should be Spartan (1 char) or spelled out\n<ul>\n<li><code>sortFunc</code> -&gt; <code>sortFunction</code> -&gt; <code>sorter</code>?</li>\n</ul>\n</li>\n<li>I would strongly consider the closure concept (example ion proposal)</li>\n<li>I would harmonize the sort values with the object fields,or create a map</li>\n<li>There is no need to initialize <code>aParam</code> and <code>bParam</code> with <code>null</code>, the default <code>undefined</code> should do</li>\n<li>You probably want to add a comment as to why you compare <code>name</code> at the end</li>\n<li>I prefer the <code>if/else if</code> approach even when <code>if</code> performs a <code>return</code>, it's one line less and increases readability</li>\n</ul>\n<p>This is my counter-proposal;</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const sortAscending = true;\nconst sortDescending = false;\n\nfunction createSortFunction(key, ascending){\n\n const keyMap = {\n brand : 'brand.title',\n weight: 'metadata.weight',\n price: 'price.unit_amount',\n style: 'metadata.style',\n arrival: 'created'\n }\n \n key = keyMap[key]? keyMap[key] : 'brand.title';\n \n return (function sortFunction(a, b){\n \n //Minor magic, derive the property from a the dot notation string\n key.split('.').forEach(part=&gt;{a = a[part], b = b[part];}); \n \n // Sort by property, ascending or descending\n if (a &lt; b) {\n return ascending ? -1 : 1\n }else if (b &gt; a) {\n return ascending ? 1 : -1\n }\n \n // Sort by name if the properties are same\n if (a.name &lt; b.name) {\n return -1\n } else if (a.name &gt; b.name) {\n return 1\n }\n //a and b are equal\n return 0;\n });\n}\n\n\nproducts = [\n { name : 'Bob', metadata: { weight: 160, style: 'sage'}, price: { unit_amount: 145}, created : '19750421', brand : { title: 'Sir' } },\n { name : 'Skeet', metadata: { weight: 130, style: 'ninja'}, price: { unit_amount: 160}, created : '20010611', brand : { title: 'Bro' } }\n]\n\nproducts.sort(createSortFunction('weight', sortAscending));\nconsole.log(products);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:13:48.350", "Id": "482284", "Score": "0", "body": "I like the `keyMap`, that is super helpful, and the magic for deriving the property. But that causes the `a.name` reference to break because `a` and `b` have been reassigned to the property value. This can fixed easily though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T14:13:29.087", "Id": "245562", "ParentId": "245533", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T21:53:58.980", "Id": "245533", "Score": "2", "Tags": [ "javascript", "sorting" ], "Title": "Generic sort function" }
245533
<p>I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>Given a non-empty array of unique positive integers A, consider the following graph:</p> <ul> <li><p>There are <code>nums.length</code> nodes, labeled <code>nums[0]</code> to <code>nums[nums.length - 1]</code>;</p> </li> <li><p>There is an edge between <code>nums[i]</code> and <code>nums[j]</code> if and only if <code>nums[i]</code> and <code>nums[j]</code> share a common factor greater than 1.</p> </li> <li><p>Return the size of the largest connected component in the graph.</p> </li> </ul> <h3>Example 1:</h3> <ul> <li>Input: [4,6,15,35]</li> <li>Output: 4</li> </ul> <p><a href="https://i.stack.imgur.com/IEeHd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IEeHd.png" alt="enter image description here" /></a></p> <h3>Example 2:</h3> <ul> <li>Input: [20,50,9,63]</li> <li>Output: 2</li> </ul> <p><a href="https://i.stack.imgur.com/wObUW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wObUW.png" alt="enter image description here" /></a></p> <h3>Example 3:</h3> <ul> <li>Input: [2,3,6,7,4,12,21,39]</li> <li>Output: 8</li> </ul> <p><a href="https://i.stack.imgur.com/lKtOa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lKtOa.png" alt="enter image description here" /></a></p> <h3>Note:</h3> <ul> <li><span class="math-container">\$1 &lt;= nums.length &lt;= 20000\$</span></li> <li><span class="math-container">\$1 &lt;= nums[i] &lt;= 100000\$</span></li> </ul> </blockquote> <h3>Inputs</h3> <pre><code>[4,6,15,35] [20,50,9,63] [2,3,6,7,4,12,21,39] [2,3,6,7,4,12,21,39,100,101,102,103,104,1200,123,123,13424] </code></pre> <h3>Outputs</h3> <pre><code>4 2 8 15 </code></pre> <h3>Code</h3> <pre><code>#include &lt;cstdint&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;unordered_map&gt; #include &lt;cmath&gt; #define max(a, b) (a &gt; b ? a : b) // std::max(a, b) // Union Find struct DisjointSets { DisjointSets(int_fast64_t n) : parent(n) { for (int_fast64_t index = 0; index &lt; n; index++) { parent[index] = index; } } void union_ds(const int_fast64_t x, const int_fast64_t y) { parent[find_ds(x)] = parent[find_ds(y)]; } const int_fast64_t find_ds(const int_fast64_t x) { if (parent[x] != x) { parent[x] = find_ds(parent[x]); } return parent[x]; } private: std::vector&lt;int&gt; parent; }; struct Solution { static const size_t largestComponentSize(const std::vector&lt;int&gt; &amp;nums) { const size_t max_nums = *std::max_element(nums.begin(), nums.end()); DisjointSets union_find(max_nums + 1); for (const auto &amp;num : nums) { for (size_t k = 2; k &lt;= std::sqrt(num); k++) { if (num % k == 0) { union_find.union_ds(num, k); union_find.union_ds(num, num / k); } } } std::unordered_map&lt;int, int&gt; component_map; size_t largest_component = 1; for (const auto &amp;num : nums) { size_t curr_component = ++component_map[union_find.find_ds(num)]; largest_component = max(largest_component, curr_component); } return largest_component; } }; </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/largest-component-size-by-common-factor/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/largest-component-size-by-common-factor/solution/" rel="nofollow noreferrer">Solution</a></p> </li> <li><p><a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow noreferrer">Union Find</a></p> </li> </ul>
[]
[ { "body": "<h2>Observation</h2>\n<p>I don't understand your solution.</p>\n<h2>Code Review</h2>\n<pre><code>#define max(a, b) (a &gt; b ? a : b) // std::max(a, b)\n</code></pre>\n<p>Don't do this. Use <code>std::max()</code> directly.</p>\n<p>Long gone are the days that we used macros to inline code like this. The <code>std::max()</code> will work correctly in all situation this macro has edge cased that will fail (especially if a or b are not just simple numbers).</p>\n<hr />\n<p>The size_t is coming because you included a C header file <code>cstdint</code>. It is not guaranteed to be in the global namespace (it commonly is but its not guaranteed). So prefer to use <code>std::size_t</code>.</p>\n<pre><code> const size_t max_nums = *std::max_element(nums.begin(), nums.end());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:58:34.117", "Id": "245600", "ParentId": "245535", "Score": "1" } } ]
{ "AcceptedAnswerId": "245600", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T23:02:03.690", "Id": "245535", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 952: Largest Component Size by Common Factor" }
245535
<p>I have the following code:</p> <pre><code>void record_preferences(int ranks[]){ // Update preferences given one voter's ranks for(int i = 0; i &lt; candidate_count; i++){ //Cycle through candidates for(int j = 0; j &lt; candidate_count; j++){ //Cycle through rank list if((i == ranks[j]) &amp;&amp; (j != candidate_count - 1)){ //If found and not last candidate for(int k = j + 1; k &lt; candidate_count; k++){ preferences[i][ranks[k]]++; } } } } return; } </code></pre> <p>When I look at this custom function I made, I felt like there are too many <code>for</code> loops.</p> <p><strong>Question:</strong> Is there a way to make this code more efficient or possibly can I use recursion with it?</p> <p>I tried formulating on how to use recursion, but I am getting stuck and can't seem to find a way.</p> <p>Variables that can't be changed (but you can make more variables if you need to):</p> <ul> <li><code>candidate_count</code> is a global variable and equal to 9</li> <li><code>preferences[i][j]</code> is a global variable. # of voters who prefer Candidate i over Candidate j</li> <li><code>ranks[]</code> is a local variable. This var stores user's input of their candidate ranking</li> </ul> <p>Voting method is <a href="https://en.wikipedia.org/wiki/Ranked_pairs" rel="nofollow noreferrer">Tideman Method</a>. I'm specifically interested in the <code>record_preferences</code> function. For context, <a href="https://hastebin.com/raniwivejo.cpp" rel="nofollow noreferrer">the entire file</a>:</p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define MAX 9 // Max number of candidates int preferences[MAX][MAX]; // preferences[i][j] is number of voters who prefer i over j bool locked[MAX][MAX]; // locked[i][j] means i is locked in over j typedef struct{ // Each pair has a winner, loser int winner; int loser; }pair; string candidates[MAX]; // Array of candidates pair pairs[MAX * (MAX - 1) / 2]; int pair_count; int candidate_count; bool vote(int rank, string name, int ranks[]); // Function prototypes void record_preferences(int ranks[]); void add_pairs(void); void sort_pairs(void); void lock_pairs(void); void print_winner(void); int main(int argc, string argv[]){ if (argc &lt;= 2){ // Check for invalid usage printf(&quot;Usage: tideman [candidate ...]\n&quot;); return 1; } candidate_count = argc - 1; // Populate array of candidates if (candidate_count &gt; MAX){ printf(&quot;Maximum number of candidates is %i\n&quot;, MAX); return 2; } for (int i = 0; i &lt; candidate_count; i++) { candidates[i] = argv[i + 1]; } for (int i = 0; i &lt; candidate_count; i++){ // Clear graph of locked in pairs for (int j = 0; j &lt; candidate_count; j++){ locked[i][j] = false; } } pair_count = 0; int voter_count = get_int(&quot;Number of voters: &quot;); for (int i = 0; i &lt; voter_count; i++){ // Query for votes int ranks[candidate_count]; // ranks[i] is voter's ith preference for (int j = 0; j &lt; candidate_count; j++){ // Query for each rank string name = get_string(&quot;Rank %i: &quot;, j + 1); if (!vote(j, name, ranks)){ printf(&quot;Invalid vote.\n&quot;); return 3; } } record_preferences(ranks); printf(&quot;\n&quot;); } add_pairs(); sort_pairs(); lock_pairs(); print_winner(); return 0; } bool vote(int rank, string name, int ranks[]){ // Update ranks given a new vote // TODO for(int i = 0; i &lt; candidate_count; i++){ if(strcmp(candidates[i], name) == 0){ ranks[rank] = i; return true; } } return false; } void record_preferences(int ranks[]){ // Update preferences given one voter's ranks for(int i = 0; i &lt; candidate_count; i++){ //Cycle through candidates for(int j = 0; j &lt; candidate_count; j++){ //Cycle through rank list if((i == ranks[j]) &amp;&amp; (j != candidate_count - 1)){ //If found and not last candidate for(int k = j + 1; k &lt; candidate_count; k++){ preferences[i][ranks[k]]++; } } } } return; } void add_pairs(void){ // Record pairs of candidates where one is preferred over the other // TODO return; } void sort_pairs(void){ // Sort pairs in decreasing order by strength of victory // TODO return; } void lock_pairs(void){ // Lock pairs into the candidate graph in order, without creating cycles // TODO return; } void print_winner(void){ // Print the winner of the election // TODO return; } </code></pre>
[]
[ { "body": "<h1>Pure Functions vs. Global Variables</h1>\n<p>You might want to consider making the function pure. That is to not use global variables. Pass those variables as additional arguments.</p>\n<p>Although global variables an nonpure functions have their place in some use cases and in C in particular, like embeded systems, small self contained programs/modules, etc. But I would say in general it is a best practice to avoid them whenever possible. It's a good habit to not use globals and keep functions pure as the default way to code and only use them when you find yourself in situation where it seems like the only way (simple enough to be worth it) to go.</p>\n<h1>Always False Condition</h1>\n<p>Here:</p>\n<pre><code>for(int j = 0; j &lt; candidate_count; j++){\n if((i == ranks[j]) &amp;&amp; (j != candidate_count - 1)){\n</code></pre>\n<p>you iterate until <code>j &lt; candidate_count</code>, but when <code>j == candidate_count - 1</code> you do nothing.</p>\n<p>You should just iterate until <code>j &lt; candidate_count - 1</code>.</p>\n<p>To make it a little better you may compute the decrement before the loop to avoid decrementing the same value on every iteration. But the compiler may actually do this for you.</p>\n<h1>Comments</h1>\n<p>It is very uncommon and invisible to keep comments aligned to the right.</p>\n<p>They are easy to miss and they make the lines unnecesarily long. Everytime you have to scroll horizontally, it is uncomfortable. Whether it be because of long code or comments...</p>\n<p>Just put them above the relevant line of code</p>\n<pre><code>// comment here\nconst char* code = &quot;here&quot;;\n</code></pre>\n<h1>Efficiency</h1>\n<p>You are approaching the problem from the wrong side.</p>\n<p>You might want to start with the ranks.</p>\n<pre><code>int least_preferred = candidate_count - 1;\nfor (int i = 0; i &lt; least_preferred; ++i) {\n for (int j = i + 1; j &lt; candidate_count; ++j) {\n ++(preferences[ranks[i]][ranks[j]]);\n }\n} -\n</code></pre>\n<p>Maybe there is a faster solution that would require some more complex data structure, like hash tables, heaps, or something like that. I'm not sure if these basic data structures are available in standard C library. The last time I coded in C was at university and I was probably implementing those data structures myself :) But given the maximum number of candidates is 9, I wouldn't bother implementing something like that. As I see it this is more of an improvement of readability. And performance is not so important here because 9 candidates will be computed in less then a milisecond anyway.</p>\n<p>Note that I iterate <code>i</code> only while less then <code>candidate_count - 1</code> because the least preferred canidate is not preferred over anyone and thus the inner loop would execute zero times because it would start at <code>j = i + 1 = candidate_count</code>.</p>\n<p>Also note that I use pre-increment (<code>++i</code>) rather then post-increment (<code>i++</code>), just out of habit. It is no different in this case (when not part of a bigger expression). But in C++ you can overload these operators on objects and for post-increment you have to keep the old and new copy of the object, while pre-increment acts in-place and thus could be more effective. And so I believe it is a good habit to only use post-increment when it's feature is required.</p>\n<h1>Recursion</h1>\n<p>Recursion is usualy easier to understand, but not better in performance (unless using tail recursion optimization).\nI usualy try to avoid recursion. Of course this may require stacks, queues or other data structures.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T06:50:25.880", "Id": "482216", "Score": "0", "body": "I'm curious, is there a reason you decided to answer this question yet didn't consider it worthy of an upvote?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T05:03:33.127", "Id": "245541", "ParentId": "245540", "Score": "3" } } ]
{ "AcceptedAnswerId": "245541", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T02:40:57.223", "Id": "245540", "Score": "3", "Tags": [ "c" ], "Title": "Computing candidate popularity provided a voter's list of all the candidates sorted by preference" }
245540
<p>Here is my simple model.</p> <pre><code>public class Product { public String Name { get; set; } public int Price { get; set; } public String Info { get; set; } } </code></pre> <p>When I use this in viewmodel as following:</p> <pre><code> public MainViewModel() { Item = new Product() { Name = &quot;Coffee&quot;, Price = 4, Info = &quot;Coffe is hot&quot; }; } protected Product _item; public Product Item { get { return _item; } set { _item = value; NotifyPropertyChanged(&quot;Item&quot;); } } </code></pre> <p>In my XAML, I am binding to the nested properties.</p> <pre><code>&lt;StackPanel&gt; &lt;TextBox Text=&quot;{Binding Item.Name}&quot;/&gt; &lt;TextBox Text=&quot;{Binding Item.Price}&quot;/&gt; &lt;TextBox Text=&quot;{Binding Item.Info}&quot;/&gt; &lt;Button Content=&quot;Change Item&quot; Click=&quot;Change_Item_Clicked&quot;/&gt; &lt;/StackPanel&gt; </code></pre> <p>I change only nested property in the click event:</p> <pre><code> private void Change_Item_Clicked(object sender, RoutedEventArgs e) { MainViewModel vm = DataContext as MainViewModel; vm.Item.Name = &quot;Donut&quot;; } </code></pre> <p>This obviously doesn't update the UI since the parent property implements <code>INotifyPropertyChanged</code> but not the nested one.</p> <p>So I came up with the following solution and it does then update the UI fine.</p> <p>I am essentially creating viewmodel version of the <code>Product</code> class as below that implments <code>INotifyPropertyChanged</code>.</p> <pre><code> public class ProductVM : Notifier { protected Product _p; public ProductVM(Product p) { _p = p; } public String Name { get { return _p.Name; } set { _p.Name = value; NotifyPropertyChanged(&quot;Name&quot;); } } public int Price { get { return _p.Price; } set { _p.Price = value; NotifyPropertyChanged(&quot;Price&quot;); } } public String Info { get { return _p.Info; } set { _p.Info = value; NotifyPropertyChanged(&quot;Info&quot;); } } } </code></pre> <p>Now the viewmodel use its version of the Product class as defined above that has ability to notify on changes.</p> <pre><code> class MainViewModel : Notifier { public MainViewModel() { Item = new ProductVM( new Product() { Name = &quot;Coffee&quot;, Price = 4, Info = &quot;Coffe is hot&quot; }); } protected ProductVM _item; public ProductVM Item { get { return _item; } set { _item = value; NotifyPropertyChanged(&quot;Item&quot;); } } } </code></pre> <p>This works great but what do you guys think of this approach? If we are going to bind to a property (nested or top level), wouldn't it be best for all these properties to implment the INotifyPropertyChanged?</p> <p>What naming conversion can I use to name <code>ProductVM</code> better? Is there a less cody way to achieve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:29:24.013", "Id": "482224", "Score": "0", "body": "Avoid working with \"Click\" etc., instead use commands to bind actions: https://www.c-sharpcorner.com/UploadFile/e06010/wpf-icommand-in-mvvm/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:32:53.813", "Id": "482225", "Score": "1", "body": "WRT NotifyPropertyChanged: perhaps consider avoiding magic string: https://stackoverflow.com/questions/7728465/implementing-notifypropertychanged-without-magic-strings" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:52:17.513", "Id": "482298", "Score": "0", "body": "@BCdotWEB The Click event was meant to just demonstrate updating the property quickly. Command would be the right thing. I wanted to present my approach on using model class/struct with nest properties in viewmodel in good and effective way. Also typically we have objects like `List<Product>` but now viewmodel will have 'List<ProductVM>' I wonder if this be frown upon in anyway?" } ]
[ { "body": "<p>To me it looks fine. If you can or will not modify the model objects (<code>Product</code>) by letting them implement <code>INotifyPropertyChanged</code> then this approach is the price to pay for using XAML. In larger projects, it can be a little annoying to seemingly write the same thing twice, but you on the other hand have a true separation of concerns, and your solution is an implementation of the MVVM-pattern.\nTo me <code>ProductVM</code> is an OK name, I always name my view objects that way.</p>\n<hr />\n<p>Instead of using string literals in the call to <code>NotifyPropertyChanged</code> you can use <code>nameof(&lt;property name&gt;)</code>:</p>\n<pre><code> NotifyPropertyChanged(nameof(Name));\n</code></pre>\n<p>this will make it easier to maintain, if the property name changes.</p>\n<hr />\n<pre><code> Another approach is to define `NotifyPropertyChanged` as:\n\n private void NotifyPropertyChanged([CallerMemberName] string name = &quot;&quot;)\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));\n }\n</code></pre>\n<p>then you don't need to provide the property name in the call:</p>\n<pre><code> public String Name \n { \n get { return _p.Name; }\n set\n {\n _p.Name = value;\n NotifyPropertyChanged();\n }\n }\n</code></pre>\n<p><code>CallerMemberName</code> requires a reference to <code>System.Runtime.CompilerServices</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:36:09.543", "Id": "482306", "Score": "0", "body": "That exactly is the main sissue, which way to go! `Product` as in model (or rest of application) doesn't need `INotifyPropertyChanged', it's only required to update UI so only MVVM layer needs it. So why implement `INotifyPropertyChanged` there, seems like it will make code over complicated. But most of the type these nested properties does bind to UI so we need that interface as well. Not sure if one should use other tricks to do without needing this interface?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:46:48.483", "Id": "482308", "Score": "0", "body": "@zadane: I'm not aware of any tricks as workarounds for using `INotifyPropertyChanged`. As an alternative you could use the `DependencyProperty/DependencyObject` scheme, but that doesn't seems to be a \"trick\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:03:52.467", "Id": "482314", "Score": "0", "body": "A trick that works is to new instance of parent property and that forces the bindings of child properties to be executed as well but like you can see its pretty dirty." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:23:14.777", "Id": "245575", "ParentId": "245542", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T05:39:24.913", "Id": "245542", "Score": "3", "Tags": [ "c#", "wpf", "xaml" ], "Title": "My approach on nested properties that bind to XAML" }
245542
<p>Here is my solution to a series of problems in JS fundamentals. I've made it pass but I know this could be more efficient. I'm not looking for anyone to rewrite the code, but just asking what methods should be used when writing similar code in the future.</p> <p>The goal is basically to input two parameters, both have to be positive numbers and typeof numbers otherwise return ERROR. Also form an array that adds said two integers and all numbers between them. For example: if you enter 1,4 the answer would compute 1 + 2 + 3 + 4 = 10, and return 10.</p> <pre class="lang-js prettyprint-override"><code>const sumAll = function(lowEnd, highEnd) { let total = []; let sum = 0; let first = lowEnd; let second = highEnd; if (typeof first === 'number' &amp;&amp; typeof second === 'number') { if (lowEnd &gt;= 0 &amp;&amp; highEnd &gt;= 0) { if (lowEnd &lt;= highEnd){ for (let i = lowEnd; i &lt;= highEnd; i++) { total.push(i); } } else { for (let i = highEnd; i &lt;= lowEnd; i++) { total.push(i); } } for (let i = 0; i &lt; total.length; i++) { sum += total[i]; }; return sum; } else if (lowEnd &lt; 0 || highEnd &lt; 0) return 'ERROR'; } else { return 'ERROR'; } } </code></pre> <p>and here are the tests,</p> <pre class="lang-js prettyprint-override"><code>const sumAll = require('./sumAll') describe('sumAll', function() { it('sums numbers within the range', function() { expect(sumAll(1, 4)).toEqual(10); }); it('works with large numbers', function() { expect(sumAll(1, 4000)).toEqual(8002000); }); it('works with larger number first', function() { expect(sumAll(123, 1)).toEqual(7626); }); it('returns ERROR with negative numbers', function() { expect(sumAll(-10, 4)).toEqual('ERROR'); }); it('returns ERROR with non-number parameters', function() { expect(sumAll(10, &quot;90&quot;)).toEqual('ERROR'); }); it('returns ERROR with non-number parameters', function() { expect(sumAll(10, [90, 1])).toEqual('ERROR'); }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T06:54:22.540", "Id": "482219", "Score": "2", "body": "You can consider using indentation for your if-satements and maybe using conditional operators to reduce the amount of them needed. This task can also be solved using a formula (see [this](https://stackoverflow.com/a/62861378/5648954) answer I recently wrote if you're curious)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T06:54:39.577", "Id": "482220", "Score": "3", "body": "As an overall remark - please add appropriate nesting. It's very hard to see where each `if` statement ends and thus which piece of code belongs in which block. Something that's crucial to understanding how the function works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T06:57:04.580", "Id": "482221", "Score": "2", "body": "@NickParsons just as an addition to that - I also touch upon arithmetic progression [in my post here](https://stackoverflow.com/a/60905085/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:26:06.410", "Id": "482223", "Score": "2", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:11:54.730", "Id": "482273", "Score": "2", "body": "Re efficiency: how about `return (hiEnd - lowEnd + 1) * (hiEnd + lowEnd) / 2`?" } ]
[ { "body": "<p>My revision:</p>\n<pre><code>const sumAll = function(lowEnd, highEnd) {\n let sum = 0;\n if (lowEnd &gt;= 0 &amp;&amp; highEnd &gt;= 0) {\n const start = Math.min(lowEnd, highEnd);\n const end = Math.max(lowEnd, highEnd);\n\n for(let i = start; i &lt;= end; i++) {\n sum += i;\n }\n return sum;\n } \n return 'ERROR';\n}\n</code></pre>\n<p>Some comments:</p>\n<ul>\n<li><p><code>typeof</code> is not necessary if comparing <code>&gt;=</code> or <code>===</code></p>\n</li>\n<li><p>the <code>total</code> array is useless as you can just sum in one <code>for</code> cycle</p>\n</li>\n<li><p><code>Math.min</code> and <code>Math.max</code> can remove the extra logic of chosing the right ending</p>\n</li>\n<li><p>the two <code>return 'Error'</code> can be joined</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T10:14:01.267", "Id": "482240", "Score": "0", "body": "Thanks. Simple and to the point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T10:36:17.550", "Id": "482244", "Score": "0", "body": "Try `sumAll(true,true)`, it returns 1 instead of 'ERROR'. Still like your answer though ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:25:54.207", "Id": "245548", "ParentId": "245546", "Score": "2" } }, { "body": "<p>A good addition is to add a check at the start of your function to check if your parameters are correct. This way you don't need extra if statements which helps for readability.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isValidNum = (n) =&gt; typeof n === \"number\" &amp;&amp; n &gt;= 0;\n\nconst sumAll = function(lowEnd, highEnd) {\n if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return \"ERROR\";\n\n let total = [];\n let sum = 0;\n\n if (lowEnd &lt;= highEnd) {\n for (let i = lowEnd; i &lt;= highEnd; i++) {\n total.push(i);\n }\n } else {\n for (let i = highEnd; i &lt;= lowEnd; i++) {\n total.push(i);\n }\n }\n\n for (let i = 0; i &lt; total.length; i++) {\n sum += total[i];\n };\n\n return sum;\n}\n\nconsole.log(sumAll(1, 4));\nconsole.log(sumAll(4, 1));\nconsole.log(sumAll(\"1\", 4));\nconsole.log(sumAll(1, \"4\"));\nconsole.log(sumAll(1, -4));\nconsole.log(sumAll(-1, -4));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Another option is to check for the highest and lowest number via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min\" rel=\"nofollow noreferrer\"><code>Math.min()</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max\" rel=\"nofollow noreferrer\"><code>Math.max()</code></a>. This way the order of input doesn't matter and you don't have to write the loop twice.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isValidNum = (n) =&gt; typeof n === \"number\" &amp;&amp; n &gt;= 0;\n\nconst sumAll = function(lowEnd, highEnd) {\n if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return \"ERROR\";\n\n let total = [];\n let sum = 0;\n \n const lowest = Math.min(lowEnd, highEnd);\n const highest = Math.max(lowEnd, highEnd);\n\n for (let i = lowest; i &lt;= highest; i++) {\n total.push(i);\n }\n\n for (let i = 0; i &lt; total.length; i++) {\n sum += total[i];\n };\n\n return sum;\n}\n\nconsole.log(sumAll(1, 4));\nconsole.log(sumAll(4, 1));\nconsole.log(sumAll(\"1\", 4));\nconsole.log(sumAll(1, \"4\"));\nconsole.log(sumAll(1, -4));\nconsole.log(sumAll(-1, -4));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>At last you could add a formula to calculate the total sum of a range of numbers. Which removes the need of loops. (<a href=\"https://stackoverflow.com/questions/62861015/how-to-accumulate-over-each-number-javascript/62861378#62861378\">More info about the formula here</a>)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const isValidNum = (n) =&gt; typeof n === \"number\" &amp;&amp; n &gt;= 0;\n\nconst sumRange = (low, high) =&gt; ((high - low + 1) * (low + high)) / 2;\n\nconst sumAll = function(lowEnd, highEnd) {\n if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return \"ERROR\";\n \n const lowest = Math.min(lowEnd, highEnd);\n const highest = Math.max(lowEnd, highEnd);\n\n return sumRange(lowest, highest);\n}\n\nconsole.log(sumAll(1, 4));\nconsole.log(sumAll(4, 1));\nconsole.log(sumAll(\"1\", 4));\nconsole.log(sumAll(1, \"4\"));\nconsole.log(sumAll(1, -4));\nconsole.log(sumAll(-1, -4));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Total revision with comments:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Return true if \"n\" is positive and of type number, else return false\nconst isValidNum = (n) =&gt; typeof n === \"number\" &amp;&amp; n &gt;= 0;\n\n// Formula for adding a range of numbers\nconst sumRange = (low, high) =&gt; ((high - low + 1) * (low + high)) / 2;\n\nfunction sumAll(lowEnd, highEnd) {\n // Return \"ERROR\" if arguments are invalid\n if (!isValidNum(lowEnd) || !isValidNum(highEnd)) return \"ERROR\";\n\n // Find highest and lowest number\n const lowest = Math.min(lowEnd, highEnd);\n const highest = Math.max(lowEnd, highEnd);\n\n // Return added numbers\n return sumRange(lowest, highest);\n}\n\nconsole.log(sumAll(1, 4));\nconsole.log(sumAll(4, 1));\nconsole.log(sumAll(\"1\", 4));\nconsole.log(sumAll(1, \"4\"));\nconsole.log(sumAll(1, -4));\nconsole.log(sumAll(-1, -4));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>PS: I really like the way your tests are written. nicely clean and concise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T09:15:24.617", "Id": "482230", "Score": "0", "body": "As a side-note - in the cases when I need to take two parameters and then get the highest/lowest from those, I tend to do it in one line with destructuring `const [min, max] = [param1, param2].sort((a, b) => a - b)`. Using a sort is slightly over the top but I find a single line to be better than two. It's also mostly my preference not that big of an improvement but I wanted to mention it. It does become more useful if you have three inputs and you want low, high and middle one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T10:16:18.943", "Id": "482241", "Score": "1", "body": "Thanks for the reply! These are not my tests, I got them from a free source webdev project called Odin. ie TheOdinProject. Take a gander if you're bored!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T23:35:44.730", "Id": "482327", "Score": "0", "body": "just a tiny nitpick but the first sentence has \"add\" instead of \"at\" :^)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T12:05:17.697", "Id": "482377", "Score": "0", "body": "@VLAZ A way to avoid the `sort` could be: `const min = Math.min(param1, param2), max = param1 + param2 - min;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:19:43.370", "Id": "482385", "Score": "0", "body": "@RoToRa `param1 = Number.MAX_SAFE_INTEGER` will break that. Or if those are floating point numbers, as well, so it's a lot more error prone. I don't think the sort is that big of an issue over all - it's going to swap two items at most. With three items it might do two swaps but it at least ensures correctness. The performance benefit is negligible." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T07:37:44.433", "Id": "245549", "ParentId": "245546", "Score": "8" } }, { "body": "<p>I will review just one small aspect of the entire question.</p>\n<p>You have <code>return 'ERROR';</code>, which is ... confusing.</p>\n<p>On the languages I'm familiar with, there are 2 ways to handle errors:</p>\n<ol>\n<li>Return <code>null</code></li>\n<li>Throw an exception</li>\n</ol>\n<p>You do option #3: return something unexpected with a different type than what you're expecting.</p>\n<p>Instead, I suggest that you do this:</p>\n<pre><code>throw new TypeError('Both values must be numbers');\n</code></pre>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError\" rel=\"nofollow noreferrer\"><code>TypeError</code> exception</a> is clear on what the problem is: the type of some value is wrong.</p>\n<p>This way, it's easier to handle and can be caught by a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch\" rel=\"nofollow noreferrer\"><code>try...catch</code> block</a>.</p>\n<hr>\n<p>A tiny nitpick: your function is called <code>sumAll</code>. But sum all? What's this &quot;all&quot;?</p>\n<p>I suggest the name <code>sumRange</code> or similar, with the variables <code>start</code> and <code>end</code>.</p>\n<p><code>lowEnd</code> and <code>highEnd</code> sounds like you're talking about the lower or higher bits from a single number that was split to fit into smaller values (like a 16-bit number into 2 8-bit variables).</p>\n<hr>\n<p>Another tiny nitpick, why don't you do <code>function sumAll(...)</code> instead of <code>const sumAll = function(...)</code>?</p>\n<p>This created an unnamed anonymous function, while <code>sumAll</code> creates a named function that belongs in the current scope, and can be called <em>before</em> it is declared, as long as it is available in the same scope (also known as <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Hoisting\" rel=\"nofollow noreferrer\">&quot;hoisting&quot;</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T01:58:13.673", "Id": "482330", "Score": "1", "body": "Hey appreciate the nitpicks! The reason for a couple of these questions can be answered by the fact this is a programming challenge, and there were sets of instructions given that ask for such things as sumAll and ERROR to be used. Noted your point on anything that wasn't part of the instructions!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:20:26.520", "Id": "245571", "ParentId": "245546", "Score": "1" } }, { "body": "<h3>Prefer <code>const</code> over <code>let</code></h3>\n<p>Others have already mentioned great simplifications like returning early, using <code>Math.min()</code> and <code>Math.max()</code>. The code already uses <code>const</code> for the function <code>sumAll</code> and that is great. <code>const</code> can also be used for any variable that should not be re-assigned - e.g. <code>total</code>. While the variable can still be mutated (e.g. with <code>Array.push()</code>) this helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h3>Optimizing loops</h3>\n<p>The last <code>for</code> loop could be optimized by saving <code>total.length</code> in a variable in the initialization step, and has an excess an excess semi-colon after the closing brace:</p>\n<blockquote>\n<pre><code>for (let i = 0; i &lt; total.length; i++) {\n sum += total[i];\n};\n//^ no need for semi-colon here, \n// though it doesn't hurt\n</code></pre>\n</blockquote>\n<p>The <code>length</code> property can be stored in a temporary variable to reduce property lookups on each iteration, making it run faster in some browsers:</p>\n<pre><code>for (let i = 0, limit = total.length; i &lt; limit; i++) {\n</code></pre>\n<p>Better yet, since the order of iteration doesn't matter, start <code>i</code> at <code>total.length</code> and decrease it to 0:</p>\n<pre><code>for (let i = total.length; i--; ) {\n</code></pre>\n<p>notice that the third condition is intentionally blank because the loop condition contains the operation to decrement <code>i</code> and there is no need to have a post-loop condition.</p>\n<h3>functional approach</h3>\n<p>One could also use a functional approach (e.g. with <code>const sum = total.reduce((a, b) =&gt; a + b )</code> but that would likely be slower because of the iterator functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:44:27.500", "Id": "245573", "ParentId": "245546", "Score": "1" } }, { "body": "<blockquote>\n<p>what methods should be used when writing similar code in the future. Thanks.</p>\n</blockquote>\n<p>I recommend taking a more <code>declarative</code> approach. It's more concise, and easier to read. As explained <a href=\"https://dzone.com/articles/imperative-vs-declarative-javascript\" rel=\"nofollow noreferrer\">here</a>:</p>\n<blockquote>\n<p><em>imperative code</em> is where you explicitly spell out each step of how you want something done, whereas with <em>declarative code</em> you merely say what it is that you want done. In modern JavaScript, that most often boils down to preferring some of the late-model methods of Array and Object over loops with bodies that do a lot of comparison and state-keeping.</p>\n</blockquote>\n<p>For example:</p>\n<pre><code>const sumAll = (a, b) =&gt; {\n const [from, to] = [a, b].sort();\n return ([from, to].some(n =&gt; typeof n != 'number' || n &lt; 0))\n ? 'ERROR'\n : new Array(to - from + 1)\n .fill()\n .map((_, i) =&gt; from + i)\n .reduce((sum, n) =&gt; !(sum += n) || sum);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T05:42:18.393", "Id": "245793", "ParentId": "245546", "Score": "0" } }, { "body": "<p>Well, if you just want to get the sum, you can simply do this:</p>\n<pre><code>const sumAll = (lowEnd, highEnd) =&gt;\n (lowEnd + highEnd) * ((Math.abs(highEnd - lowEnd)) + 1) / 2;\n</code></pre>\n<p>However, if you still want to sum them one by one, I prefer to create a function called <code>range</code> first\n.</p>\n<pre><code>function range (start, end) {\n return Array.from({ length: end - start + 1 }, () =&gt; start).map((v, i) =&gt; v + i);\n}\n</code></pre>\n<p>Then create a function to sum the range:</p>\n<pre><code>function sumRange (start, end) {\n return range(start, end).reduce((a, b) =&gt; a + b);\n}\n</code></pre>\n<p>But what if end is smaller than start? Let's fix it:</p>\n<pre><code>function sumRange (start, end) {\n if (end &lt; start) return sumRange(end, start);\n return range(start, end).reduce((a, b) =&gt; a + b);\n}\n</code></pre>\n<p>But what if params are not valid number? Let's create a function to do this:</p>\n<pre><code>function isValidNumber (num) {\n return typeof num === 'number' &amp;&amp; num &gt;= 0;\n}\n</code></pre>\n<p>I don't want to hardcode it into <code>sumRange</code>, so I create a high order function:</p>\n<pre><code>function checkParams (validFn) {\n return fn =&gt; {\n return (...args) =&gt; {\n if (args.some(v =&gt; !validFn(v))) throw new Error('error');\n return fn.apply(null, args);\n } \n }\n}\n</code></pre>\n<p>Finally we can get <code>sumAll</code>:</p>\n<pre><code>const sumAll = checkParams(isValidNumber)(sumRange);\n</code></pre>\n<p>Put them together:</p>\n<pre><code>function checkParams (validFn) {\n return fn =&gt; (...args) =&gt; {\n if (args.some(v =&gt; !validFn(v))) throw new Error('error');\n return fn.apply(null, args);\n }\n}\n\nfunction isValidNumber (num) {\n return typeof num === 'number' &amp;&amp; num &gt;= 0;\n}\n\n// you can simply replace `range` and `sumRange` with \n// const sumRange = (lowEnd, highEnd) =&gt;\n// (lowEnd + highEnd) * ((Math.abs(highEnd - lowEnd)) + 1) / 2;\n\nfunction range (start, end) {\n return Array.from({ length: end - start + 1 }, () =&gt; start).map((v, i) =&gt; v + i);\n}\n\nfunction sumRange (start, end) {\n if (end &lt; start) return sumRange(end, start);\n return range(start, end).reduce((a, b) =&gt; a + b);\n}\n\nconst sumAll = checkParams(isValidNumber)(sumRange);\n\nsumAll(1, 4); // 10\nsumAll(1, 4000); // 8002000\nsumAll(123, 1); // 7626\nsumAll(-10, 4); // Error\nsumAll(10, '90'); // Error\nsumAll(10, [90, 1]); // Error\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T08:59:10.517", "Id": "245858", "ParentId": "245546", "Score": "1" } } ]
{ "AcceptedAnswerId": "245549", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T06:49:03.933", "Id": "245546", "Score": "9", "Tags": [ "javascript", "programming-challenge" ], "Title": "Sum of integers in an interval" }
245546
<p>I have been designing websites with Django for a while and I have also designed various sites. But here is a question that comes to mind at the beginning of any new project:</p> <p>What is the best <em>URLs architectural Design</em> that creates both logical and meaningful URLs path as well as pluggable apps?</p> <p>I will explain my question with a practical example.</p> <p><strong>Practical Example And Problem</strong></p> <p>Suppose that we have project with these features:</p> <ol> <li><p>It has three applications called <code>Shop</code>, <code>Blog</code> and <code>Support</code>.</p> </li> <li><p>It has three URL section:</p> <p>2.1. Public section: that start with <code>/</code>.</p> <p>2.2. Consumer panel: that start with <code>/panel</code>.</p> <p>2.3. Administrator panel: that start with <code>/administrator</code>.</p> </li> </ol> <p>Each application has 3 views. For example Shop has: <code>public_shop_view</code>, <code>panel_shop_view</code> and <code>administrator_shop_view</code>.</p> <p>Now, What is the best URL design for this project? I describe two possible answers here for URLs design.</p> <p><strong>Solution 1:</strong></p> <p>project/urls.py</p> <pre><code>path('', include('Shop.urls', namespce='Shop')), path('', include('Blog.urls', namespce='Blog')), path('', include('Support.urls', namespce='Support')), </code></pre> <p>Shop/urls.py</p> <pre><code>path('shop/', views.public_shop_view, name='public_shop_view'), path('panel/shop/', views.panel_shop_view, name='panel_shop_view'), path('administrator/shop/', views.administrator_shop_view, name='administrator_shop_view'), </code></pre> <p>Blog/urls.py</p> <pre><code>path('blog/', views.public_blog_view, name='public_blog_view'), path('panel/blog/', views.panel_blog_view, name='panel_blog_view'), path('administrator/blog/', views.administrator_blog_view, name='administrator_shop_view'), </code></pre> <p>Support/urls.py</p> <pre><code>path('support/', views.public_support_view, name='public_support_view'), path('panel/support/', views.panel_support_view, name='panel_support_view'), path('administrator/support/', views.administrator_support_view, name='administrator_support_view'), </code></pre> <hr /> <p><strong>Solution 2:</strong><br /> In this solution we create three apps (<code>Public</code>, <code>Panel</code>, <code>Administrator</code>) that just have <code>urls.py</code> file (to follow the interface strategy):</p> <p>project/urls.py</p> <pre><code>path('', include('Public.urls', namespce='Interface')), path('panel/', include('Panel.urls', namespce='Panel')), path('administrator/', include('Administrator.urls', namespce='Administrator')), </code></pre> <p>Public/urls.py</p> <pre><code>from Support import views as support_views from Blog import views as blog_views from Shop import views as shop_views path('support/', support_views.public_support_view, name='public_support_view'), path('blog/', blog_views.public_blog_view, name='public_blog_view'), path('shop/', shop_views.public_shop_view, name='public_shop_view'), </code></pre> <p>Panel/urls.py</p> <pre><code>from Support import views as support_views from Blog import views as blog_views from Shop import views as shop_views path('support/', support_views.panel_support_view, name='panel_support_view'), path('blog/', blog_views.panel_blog_view, name='panel_blog_view'), path('shop/', shop_views.panel_shop_view, name='panel_shop_view'), </code></pre> <p>Administrator/urls.py</p> <pre><code>from Support import views as support_views from Blog import views as blog_views from Shop import views as shop_views path('support/', support_views.administrator_support_view, name='administrator_support_view'), path('blog/', blog_views.administrator_blog_view, name='administrator_blog_view'), path('shop/', shop_views.administrator_shop_view, name='administrator_shop_view'), </code></pre> <p><strong>Now, What is the best practice? Solution 1 or solution 2 or other solution?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T09:23:09.757", "Id": "482231", "Score": "0", "body": "2nd one for sure. Each app's urls should be included in the urls.py in the settings.py folder." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T09:33:07.203", "Id": "482234", "Score": "0", "body": "Please answer to my question with your reasons @VisheshMangla" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T09:59:01.690", "Id": "482239", "Score": "1", "body": "Django apps are reusable components. You can plug an app from one django project to some other django project.That is the idea and you should design an app in such as way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T13:36:46.717", "Id": "482258", "Score": "1", "body": "Unfortunately CodeReview does not deal in hypotheticals. If you reform this into a stand-alone pet project to demonstrate your situation and show the code from beginning to end, it might become on-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T15:45:22.257", "Id": "482267", "Score": "0", "body": "I think I have explained enough and written my codes so that my questions are part of the topic. @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:15:21.737", "Id": "482274", "Score": "1", "body": "_Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site._ Your phrase _What is the best practice_, as well as the fact that none of your examples is complete (where do you import `path`?) bring this off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:21:54.803", "Id": "482275", "Score": "0", "body": "If you was Django developer you could understand that what is `path`! @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:27:06.443", "Id": "482276", "Score": "1", "body": "It doesn't (and should not) matter whether your reviewers are familiar with Django or not. Relying on implicit knowledge and assumptions about your code will not allow for a high-quality review and will narrow the possible responses that you get. Your code needs to be runnable, period; rather than hoping that reviewers are able to fill in the blanks and read your mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:30:26.480", "Id": "482277", "Score": "0", "body": "Ok. I got that. Is it ok if I put all my codes here that can run? @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:30:45.550", "Id": "482278", "Score": "1", "body": "Yes, absolutely :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:32:41.240", "Id": "482279", "Score": "1", "body": "Thanks a lot for your help. @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:40:17.990", "Id": "482353", "Score": "1", "body": "well, code related to frameworks cannot be runnable unless someone gives you the full repository. Even if someone gives you the repo you can't run it because everyone knows learning a framework is not a matter of few minutes.Therefore this question seems to be very much sensible and it is sufficiently clear for anyone who knows django well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:44:47.357", "Id": "482354", "Score": "1", "body": "Code formatting is essential but in the time of formatters like black, and autopep8 do we really need code review to do that stuff? Many answers on code review just correct a few indents and get the score whereas these kind of questions which in real are asking for best practices get shut." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:24:43.497", "Id": "482387", "Score": "0", "body": "Exactly. Thank you Vishesh @VisheshMangla" } ]
[ { "body": "<p>I've read the comments and am a bit torn by the discussion... yes, this code is not runnable; yes, you assume background knowledge; but you do that because 90% of Django starter code is not relevant to this discussion, but is essential to a Django project, so I think this is worth a shot.</p>\n<p>For starters, it's worth pointing out that which of these solutions you choose <em>has no impact on the code you write</em>, since you will always refer to URL's by their name rather than by their path. This is solely a matter of beauty for how your capabilities are exposed to users and external services.</p>\n<p>For this case, I would suggest a refactor that separates the front-end (paths) from the back-end (functionality). Have an app each for <code>support</code>, <code>blog</code>, and <code>store</code>, each of which implement their own models, serializers, utility functions, Celery tasks, etc. Then, have an app each for <code>panel</code> and <code>administration</code> that implements the paths, views, and user-facing logic about how people interact with those underlying concepts. You end up with some internal dependencies, but they're bipartite (only apps in the &quot;frontend&quot; group depend on only apps in the &quot;backend&quot; groups) and acyclic, so that's not a big deal.</p>\n<p>If designed this way, you get the best of both worlds. You can keep the logical separation you show above among isolated logical components, but can use clean path construction and view implementation designed around how the users interact with your system. The downside is a larger number of apps and some internal dependencies, but those dependencies become explicit and you avoid the apps needing to implicitly know about each other and knowing how to avoid path conflicts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:46:08.000", "Id": "245580", "ParentId": "245551", "Score": "3" } } ]
{ "AcceptedAnswerId": "245580", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T09:05:25.827", "Id": "245551", "Score": "1", "Tags": [ "python", "design-patterns", "django" ], "Title": "Best practice for URL's architectural Design in Django" }
245551
<p>I've created a little class which helps me to generalize many query cases. I have a DbService and couple methods in it. Can you please take a look at it and share some criticism? The usage of that tool is really easy to me and I do wanna know how to make it safer and optimized.</p> <pre><code> public class DbServiceImpl implements DbService { private final EntityManager entityManager; @Inject DbServiceImpl(EntityManager entityManager) { this.entityManager = entityManager; } @Override public &lt;T, V&gt; List&lt;V&gt; createQuery(Query&lt;T, V&gt; query) { try { if (query != null &amp;&amp; query.entityType.getAnnotation(Entity.class) != null) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery&lt;V&gt; criteriaQuery = criteriaBuilder.createQuery(query.returnType); query.root = criteriaQuery.from(query.entityType); query.builder = criteriaBuilder; Selection&lt;? extends V&gt; selection = query.select(); //invokes on the call. Predicate predicate = query.where(); if (predicate != null) { criteriaQuery.where(predicate); //null of a simple select without where clause. } criteriaQuery.select(selection); //null is allowed, it will just select * from the entity return entityManager.createQuery(criteriaQuery).getResultList(); } } catch (Exception exception) { exception.printStackTrace(); } return new ArrayList&lt;&gt;(); //a simple check of .isEmpty() covers that case. } @SuppressWarnings(&quot;unchecked&quot;) public abstract static class Query&lt;T, V&gt; { private final Class&lt;T&gt; entityType; private final Class&lt;V&gt; returnType; //accessible only by outer class's methods. private Root&lt;T&gt; root; private CriteriaBuilder builder; public Query() { this.entityType=(Class&lt;T&gt;) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; this.returnType=(Class&lt;V&gt;) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } protected abstract Selection&lt;? extends V&gt; select(); protected abstract Predicate where(); protected Root&lt;T&gt; root() { return root; } protected CriteriaBuilder builder() { return builder; } } } </code></pre> <p>And here are some use cases. Passed types are as follows - entity &amp; return (User,Long)</p> <pre><code> List&lt;Long&gt; data = dbService.createQuery(new DbServiceImpl.Query&lt;User, Long&gt;() { @Override protected Selection&lt;? extends Long&gt; select() { return builder().count(root()); } @Override protected Predicate where() { return root(); } }); </code></pre> <p>This allows me to find the count of a table so understandable, without a line of pure HQL or any SQL code. One more example:</p> <pre><code> List&lt;User&gt; users = dbService.createQuery(new DbServiceImpl.Query&lt;User, User&gt;() { @Override protected Selection&lt;? extends User&gt; select() { return root(); } @Override protected Predicate where() { return builder().equal(root().get(&quot;username&quot;), username); } }); </code></pre> <p>One with a join:</p> <pre><code> List&lt;Recipe&gt; recipeList= dbService.createQuery(new DbServiceImpl.Query&lt;Recipe, Recipe&gt;() { @Override protected Selection&lt;? extends Recipe&gt; select() { return null; } @Override protected Predicate where() { root().fetch(&quot;author&quot;, JoinType.LEFT); return builder().equal(root().get(&quot;author&quot;).get(&quot;id&quot;),user.getId()); } }); </code></pre> <p>The code structure remains the same but the query is different. The access modifiers I used allowed me to encapsulate the behaviour on the use cases. What do you think? How broken or useful is that?</p>
[]
[ { "body": "<p>Welcome to Code Review, I have seen your code and I have seen you encapsulated your <code>createQuery</code> method like below:</p>\n<pre><code>try { body method } catch (Exception exception) { exception.printStackTrace(); }\n</code></pre>\n<p>You are basically catching all <code>NullPointerException</code> cases and other runtime exceptions you can meet within your method with the <code>Exception</code> class, this is a sign something should be redesigned to avoid these situations.</p>\n<p>About the paradigm you are following , you are implementing a personal version of the <em>repository pattern</em>, referring to structures like the jpa repository present for example in the spring framework. You can check while you are creating different queries worrying about the construction of a valid query (and this is the reason why you had to encapsulate your method in the <code>try catch</code> construct), it should be better using an already built class to do the same things with much less effort.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:04:39.057", "Id": "482448", "Score": "0", "body": "Thank you so much for the feedback , I really do appreciate it ! About the built class u mean a custom one built by me or a 3rd party ? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:22:19.217", "Id": "482482", "Score": "1", "body": "You are welcome, I meant before to construct a totally new class (this is always a useful thing ) always check if there is an already built class doing the same things present in a well known library and if you want to know how problems are solved by the built class you can check the src code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T10:13:08.770", "Id": "482491", "Score": "0", "body": "Thank you once again ! I will try it out. I prefet the custom solution. Have a nice day !" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:11:09.450", "Id": "245629", "ParentId": "245557", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T12:34:12.817", "Id": "245557", "Score": "4", "Tags": [ "java", "sql", "generics", "hibernate" ], "Title": "Generic solution to Hibernate's CriteriaQuery" }
245557
<p><a href="http://alloytools.org/" rel="nofollow noreferrer">Alloy</a> is a formal specification language that is very suitable to use as a <em>software design explorer</em>. It is based on a <em>relational model</em> with a syntax that is familiar to object-oriented developers. To traverse the state space of the model, it uses a <em>bound</em> scope and any of a number of <a href="https://en.wikipedia.org/wiki/Boolean_satisfiability_problem" rel="nofollow noreferrer">SAT</a> or <a href="https://en.wikipedia.org/wiki/Satisfiability_modulo_theories" rel="nofollow noreferrer">SMT</a> solvers to find valid instances of the model. Its relational model is so flexible that it can model time without special constructs to verify concurrent algorithms.</p> <p>Alloy, with an Alloy analyzer application, was developed at MIT under the guidance of Daniel Jackson. The Alloy Analyzer is maintained on <a href="https://github.com/AlloyTools/org.alloytools.alloy" rel="nofollow noreferrer">GitHub</a>.</p> <p>The purpose of this tag is to collect Alloy models. Please tag Alloy models with the <code>alloy</code> tag to attract Alloy experts. You can use it to get feedback but you're also welcome to showcase a really cool model.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T13:34:48.963", "Id": "245560", "Score": "0", "Tags": null, "Title": null }
245560
Alloy is a declarative specification language from MIT, developed into a full structural modelling language.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T13:34:48.963", "Id": "245561", "Score": "0", "Tags": null, "Title": null }
245561
<p>Please explain what I can improve, and why. I'm new to Python, Tkinter &amp; Code Review, so I have a lot to learn. :)</p> <p>I created a Tkinter app for user-input, and the same types of widgets are repeated on each row. A single row is similar to a slide in PowerPoint because it has an image, numbers, and input text. I will later add the &quot;export to separate file&quot; functionality, but for now I'm focused on the &quot;skeleton&quot; of the code, which is the creation &amp; display of the widgets.</p> <p>Since each row is a repeat of the one above it, I know I could somehow create a &quot;row-object&quot; using a class, and/or use a for-loop to create each row. Since I'm not sure how to do either, my code is verbose and repetitive. I manually create each widget. I used Excel to spit out this part of the code. This is what my GUI looks like: <em>notice the repetition in each row</em> <a href="https://i.stack.imgur.com/gi64m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gi64m.jpg" alt="Rendered image of the GUI" /></a></p> <p>This is my code:</p> <pre><code>import tkinter as tk from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button from PIL import ImageTk, Image root = tk.Tk() load1 = Image.open(&quot;example.jpg&quot;) root.render1 = ImageTk.PhotoImage(load1) canv_1 = tk.Canvas(root, bg=&quot;gray&quot;) canv_1.grid_rowconfigure(0, weight=1) #canv_1.grid_columnconfigure((0, 1, 2, 3, 4, 5, 7), weight=1) canv_1.grid_columnconfigure(6, weight=2) canv_1.grid(row=0, column=0, sticky=&quot;news&quot;) canv_1.grid(row=1, column=0, sticky=&quot;news&quot;) labels = [&quot;Image&quot;, &quot;Chapter #&quot;, &quot;Chapter Title&quot;, &quot;Step&quot;, &quot;Slide&quot;, &quot;Sequence Step&quot;, &quot;Instructions&quot;] root.label_wid = [] font1 = (&quot;arial&quot;, 15, &quot;bold&quot;) for i in range(len(labels)): root.label_wid.append(tk.Label(canv_1, font=font1, relief=&quot;raised&quot;, text=labels[i]).grid(row=0, column=i, sticky=&quot;we&quot;)) def exportCode(): print(&quot;code exported&quot;) def change_img(row): if row == 1: root.img1 = filedialog.askopenfilename() root.load_img1 = Image.open(root.img1) root.render_img1 = ImageTk.PhotoImage(root.load_img1) R1C0['image']=root.render_img1 if row == 2: root.img2 = filedialog.askopenfilename() root.load_img2 = Image.open(root.img2) root.render_img2 = ImageTk.PhotoImage(root.load_img2) R2C0['image']=root.render_img2 if row == 3: root.img3 = filedialog.askopenfilename() root.load_img3 = Image.open(root.img3) root.render_img3 = ImageTk.PhotoImage(root.load_img3) R3C0['image']=root.render_img3 if row == 4: root.img4 = filedialog.askopenfilename() root.load_img4 = Image.open(root.img4) root.render_img4 = ImageTk.PhotoImage(root.load_img4) R3C0['image']=root.render_img4 if row == 5: root.img5 = filedialog.askopenfilename() root.load_img5 = Image.open(root.img5) root.render_img5 = ImageTk.PhotoImage(root.load_img5) R3C0['image']=root.render_img5 c1 = &quot;#a9d08e&quot; c2 = &quot;#8dd1bf&quot; # Below is the really repetitive part that I would love to simplify: ########################################################################################### # =============================================================================================== R1C0= tk.Button(canv_1, image=root.render1, relief=&quot;raised&quot;, bg=&quot;light gray&quot;, command = lambda: change_img(1)) R1C0.grid(row=1, column= 0, sticky=&quot;news&quot;) R1C1= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 1, column= 1, sticky= &quot;news&quot;) R1C2= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 1, column= 2, sticky= &quot;news&quot;) R1C3= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 1, column= 3, sticky= &quot;news&quot;) R1C4= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 1, column= 4, sticky= &quot;news&quot;) R1C5= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 1, column= 5, sticky= &quot;news&quot;) R1C6= tk.Text(canv_1, bg=&quot;white&quot;, wrap=&quot;word&quot;, font=(&quot;arial&quot;,15), width=20, height=10) R1C6.grid(row=1, column= 6, sticky= &quot;news&quot;) R2C0= tk.Button(canv_1, image=root.render1, relief=&quot;raised&quot;, bg=&quot;light gray&quot;, command = lambda: change_img(2)) R2C0.grid(row=2, column= 0, sticky=&quot;news&quot;) R2C1= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 2, column= 1, sticky= &quot;news&quot;) R2C2= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 2, column= 2, sticky= &quot;news&quot;) R2C3= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 2, column= 3, sticky= &quot;news&quot;) R2C4= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 2, column= 4, sticky= &quot;news&quot;) R2C5= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 2, column= 5, sticky= &quot;news&quot;) R2C6= tk.Text(canv_1, bg=&quot;white&quot;, wrap=&quot;word&quot;, font=(&quot;arial&quot;,15), width=20, height=10) R2C6.grid(row=2, column= 6, sticky= &quot;news&quot;) R3C0= tk.Button(canv_1, image=root.render1, relief=&quot;raised&quot;, bg=&quot;light gray&quot;, command = lambda: change_img(3)) R3C0.grid(row=3, column= 0, sticky=&quot;news&quot;) R3C1= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 3, column= 1, sticky= &quot;news&quot;) R3C2= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 3, column= 2, sticky= &quot;news&quot;) R3C3= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 3, column= 3, sticky= &quot;news&quot;) R3C4= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 3, column= 4, sticky= &quot;news&quot;) R3C5= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 3, column= 5, sticky= &quot;news&quot;) R3C6= tk.Text(canv_1, bg=&quot;white&quot;, wrap=&quot;word&quot;, font=(&quot;arial&quot;,15), width=20, height=10) R3C6.grid(row=3, column= 6, sticky= &quot;news&quot;) R4C0= tk.Button(canv_1, image=root.render1, relief=&quot;raised&quot;, bg=&quot;light gray&quot;, command = lambda: change_img(4)) R4C0.grid(row=4, column= 0, sticky=&quot;news&quot;) R4C1= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 4, column= 1, sticky= &quot;news&quot;) R4C2= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 4, column= 2, sticky= &quot;news&quot;) R4C3= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 4, column= 3, sticky= &quot;news&quot;) R4C4= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 4, column= 4, sticky= &quot;news&quot;) R4C5= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 4, column= 5, sticky= &quot;news&quot;) R4C6= tk.Text(canv_1, bg=&quot;white&quot;, wrap=&quot;word&quot;, font=(&quot;arial&quot;,15), width=20, height=10) R4C6.grid(row=4, column= 6, sticky= &quot;news&quot;) R5C0= tk.Button(canv_1, image=root.render1, relief=&quot;raised&quot;, bg=&quot;light gray&quot;, command = lambda: change_img(5)) R5C0.grid(row=5, column= 0, sticky=&quot;news&quot;) R5C1= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 5, column= 1, sticky= &quot;news&quot;) R5C2= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 5, column= 2, sticky= &quot;news&quot;) R5C3= tk.Entry(canv_1, bg = c1, font=(&quot;arial&quot;,15)).grid(row= 5, column= 3, sticky= &quot;news&quot;) R5C4= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 5, column= 4, sticky= &quot;news&quot;) R5C5= tk.Entry(canv_1, bg = c2, font=(&quot;arial&quot;,15)).grid(row= 5, column= 5, sticky= &quot;news&quot;) R5C6= tk.Text(canv_1, bg=&quot;white&quot;, wrap=&quot;word&quot;, font=(&quot;arial&quot;,15), width=20, height=10) R5C6.grid(row=5, column= 6, sticky= &quot;news&quot;) # ================================================================================================ bt1 = tk.Button(canv_1, text=&quot;Export&quot;, font=font1, command=exportCode).grid(row=0, column=7) load2 = Image.open(&quot;scroll-up.png&quot;) root.render2 = ImageTk.PhotoImage(load2) load3 = Image.open(&quot;scroll-down.png&quot;) root.render3 = ImageTk.PhotoImage(load3) scroll_up = tk.Button(canv_1, image=root.render2).grid(row=1, column=7, rowspan=2) # , sticky=&quot;n&quot;) scroll_up = tk.Button(canv_1, image=root.render3).grid(row=3, column=7, rowspan=2) # , sticky=&quot;s&quot;) root.mainloop() </code></pre> <p>Any tips on simplifying and refactoring this would be awesome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T15:46:09.543", "Id": "482268", "Score": "2", "body": "Welcome to Code Review! I've [edited](https://codereview.stackexchange.com/posts/245565/edit) your question to make it on topic for the site, but it would be nice if you could [edit](https://codereview.stackexchange.com/posts/245565/edit) the title to make it more clear what your application is *for* (user input is very generic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T15:46:29.897", "Id": "482269", "Score": "2", "body": "I also removed the section related to \"what you tried and didn't work\", as well as \"what you want to be able to do eventually\" - here on Code Review, we strictly review complete, working code. If you have questions on **how** to do something, consider posting on Stack Overflow, but please remember to review their rules for posting and make sure you've done your research before asking over there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T15:53:34.393", "Id": "482270", "Score": "1", "body": "Hi @Dannnno thanks for the welcome and edits! I like to make the skeleton before adding the \"guts\" and functionality. Adding all the functionality here would add clutter. So for now my goal is to produce the image shown, without precluding the later option of extracting values from each entry widget. One way to do this is manually (as I did) but I have a feeling that I could have used a class or a for-loop instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:06:40.570", "Id": "482283", "Score": "1", "body": "This question looks familiar. Did you try posting this code earlier? Did you fix the issues it had back then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:34:07.060", "Id": "482290", "Score": "1", "body": "@Reinderien Yes, I abandoned the scroll bars from the previous code. Now I'm just trying to code incrementally -- the first working increment is what I have here. It works, as in it shows the widgets, and you can change the images and text. However I know there must be a less verbose way of showing all the widgets. Please let me know if I should wait to ask this question after I build in all the functionality I intend, rather than this working \"skeleton\" code. I can understand either way." } ]
[ { "body": "<h2>If there's a list, make it a list</h2>\n<p>Do not represent <code>RxCx</code> variables as separate variables. Represent them as nested lists and it will greatly simplify your code. Consider grouping them by what makes them similar - column 0 (<code>image_col</code>), columns 1-5 (<code>info_cols</code>) and column 6 (<code>instruction_col</code>) as in the following example:</p>\n<pre><code>image_col = [\n tk.Button(\n canv_1, \n image=root.render1, \n relief=&quot;raised&quot;, \n bg=&quot;light gray&quot;, \n command = lambda: change_img(y),\n )\n for y in range(1, 6)\n]\n\nfor y, image_cell in enumerate(image_col, 1):\n image_cell.grid(row=y, column=0, sticky='news')\n\ninstruction_col = [\n tk.Text(\n canv_1,\n bg=&quot;white&quot;,\n wrap=&quot;word&quot;,\n font=(&quot;arial&quot;,15), width=20, height=10)\n]\n\nfor y, image_cell in enumerate(instruction_col, 1):\n image_cell.grid(row=y, column=6, sticky='news')\n\n</code></pre>\n<p>Replace your <code>change_img</code> so that there are no <code>if</code>s, and everything is done via list lookup from the <code>row</code> index passed. Replace <code>root.img*</code>, <code>root.load_img*</code> and <code>root.render_img*</code> with lists.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:38:28.070", "Id": "245576", "ParentId": "245565", "Score": "5" } } ]
{ "AcceptedAnswerId": "245576", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T15:20:02.827", "Id": "245565", "Score": "4", "Tags": [ "python", "tkinter", "gui" ], "Title": "GUI to organize images, chapter titles, animation steps, and instructions" }
245565
<p>This is my first F# program. It's a simple Rock-Paper-Scissors implementation.</p> <p>I am looking for feedback of all sorts, e.g. the choice of types (e.g. List vs Array), whether there are parts that could be solved more elegantly / idiomatic, formatting, etc.</p> <pre><code>open System let allowedActions = [ &quot;r&quot;; &quot;p&quot;; &quot;s&quot; ] let randomItem list (rng: Random) = List.item (rng.Next(List.length list)) list let computerAction () = randomItem allowedActions (Random()) let rec playerAction () = printfn &quot;Write 'r' for Rock, 'p' for Paper, 's' for Scissors. Type 'q' to Quit.&quot; let input = Console.ReadLine() let isInputAllowed = List.contains input allowedActions || input = &quot;q&quot; match isInputAllowed with | true -&gt; input | _ -&gt; printfn &quot;invalid input '%s'&quot; input; playerAction() let computerWin playerAction computerAction = printfn &quot;The computer did win. '%s' beats '%s'.&quot; computerAction playerAction let playerWin playerAction computerAction = printfn &quot;The player did win. '%s' beats '%s'.&quot; playerAction computerAction let tie anAction = printfn &quot;It's a tie. '%s'&quot; anAction let ruling playerAction computerAction = match (playerAction, computerAction) with | (&quot;r&quot;, &quot;p&quot;) | (&quot;p&quot;, &quot;s&quot;) | (&quot;s&quot;, &quot;r&quot;) -&gt; computerWin playerAction computerAction | (&quot;r&quot;, &quot;s&quot;) | (&quot;p&quot;, &quot;r&quot;) | (&quot;s&quot;, &quot;p&quot;) -&gt; playerWin playerAction computerAction | (_, _) -&gt; tie playerAction let playGame playerAction computerAction = printfn &quot;You've chosen '%s'.&quot; playerAction printfn &quot;The computer chose '%s'.&quot; computerAction ruling playerAction computerAction () let game () = let playerAction = playerAction () let computerAction = computerAction () match playerAction with | &quot;q&quot; -&gt; false | _ -&gt; playGame playerAction computerAction true [&lt;EntryPoint&gt;] let rec main arg = printfn &quot;Hello World to Rock Paper Scissors&quot; match game () with | true -&gt; main arg | false -&gt; 0 <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>As a first attempt it looks in many ways ok.</p>\n<p>I have three &quot;complaints&quot;:</p>\n<p><strong>a)</strong> You rely too much on string literals as identifiers for input. That is considered bad practice in - I think - every programming language and should be avoided because it's error prone (typos and illegal input etc.) hence not very robust.</p>\n<p>Instead of <code>&quot;r&quot;</code>, <code>&quot;p&quot;</code> and <code>&quot;s&quot;</code> you could use a discriminated union - which is a very important part of the F#-toolbox to be familiar with:</p>\n<pre><code>type Weapon =\n | Rock\n | Paper\n | Scissors\n</code></pre>\n<p>This will for instance make the match-statement in <code>ruling</code> much more readable and type safe:</p>\n<pre><code>let ruling playerWeapon computerWeapon =\n match (playerWeapon, computerWeapon) with\n | (Rock, Paper)\n | (Paper, Scissors)\n | (Scissors, Rock) -&gt; computerWin playerWeapon computerWeapon\n | (Rock, Scissors)\n | (Paper, Rock)\n | (Scissors, Paper) -&gt; playerWin playerWeapon computerWeapon\n | (_, _) -&gt; tie playerWeapon\n</code></pre>\n<hr />\n<p><strong>b)</strong> Don't repeat yourself. In the functions where you print the results, you do the same thing, and therefore you should extract the common parts to a generalized function, so that:</p>\n<pre><code>let computerWin playerAction computerAction =\n printfn &quot;The computer did win. '%s' beats '%s'.&quot; computerAction playerAction\nlet playerWin playerAction computerAction =\n printfn &quot;The player did win. '%s' beats '%s'.&quot; playerAction computerAction\n</code></pre>\n<p>changes to:</p>\n<pre><code>let showWinner name winnerWeapon looserWeapon = \n printfn &quot;The %s did win. '%A' beats '%A'.&quot; name winnerWeapon looserWeapon\nlet computerWin playerWeapon computerWeapon = showWinner &quot;computer&quot; computerWeapon playerWeapon\nlet playerWin playerWeapon computerWeapon = showWinner &quot;player&quot; playerWeapon computerWeapon\n</code></pre>\n<hr />\n<p><strong>c)</strong> You recursively call the <code>main</code> function. I don't know if you actually violate any formal or informal rules but it just looks &quot;ugly&quot; to me. I would make a dedicated function that runs the game recursively.</p>\n<hr />\n<p>FYI - I have below refactored your program while incorporating my suggestions above:</p>\n<pre><code>// HH: Instead of string literals you should use discriminated unions as identifiers for &quot;weapons&quot;\n// This is much more robust in respect to typos etc.\ntype Weapon =\n | Rock\n | Paper\n | Scissors\n static member Abbreviation w = (w.ToString().[0]).ToString().ToLower()\n static member ToWeapon ch =\n match ch with\n | &quot;r&quot; -&gt; Rock\n | &quot;p&quot; -&gt; Paper\n | &quot;s&quot; -&gt; Scissors\n | _ -&gt; failwith &quot;Invalid Weapon char&quot;\n\nlet weapons = [ Rock; Paper; Scissors ]\n\n// HH: You should only instantiate a single random object - used throughout the session.\nlet rand = new Random()\nlet computerAction () = weapons.[rand.Next(weapons.Length)]\n\n\n// HH: This now returns an optional value of None if the user wants to quit\n// or Some (Weapon) if a valid weapon is chosen\nlet rec playerAction () =\n let allowedActions = weapons |&gt; List.map Weapon.Abbreviation\n let choices = weapons |&gt; List.map (fun w -&gt; sprintf &quot;'%s' = %A&quot; (Weapon.Abbreviation w) w)\n printfn &quot;Enter:\\n%s.\\n'q' to Quit.&quot; (String.Join(&quot;\\n&quot;, choices))\n let input = Console.ReadLine()\n\n let validWeapon w = List.contains w allowedActions\n match input with\n | &quot;q&quot; -&gt; None\n | w when validWeapon w -&gt; Some (Weapon.ToWeapon w)\n | _ -&gt; printfn &quot;invalid input '%s'&quot; input; playerAction()\n\n//HH: Never repeat yourself: extract a function to print the winner...\nlet showWinner name winnerWeapon looserWeapon = \n printfn &quot;The %s did win. '%A' beats '%A'.&quot; name winnerWeapon looserWeapon\n// HH: ... and call that from the dedicated winner functions\nlet computerWin playerWeapon computerWeapon = showWinner &quot;computer&quot; computerWeapon playerWeapon\nlet playerWin playerWeapon computerWeapon = showWinner &quot;player&quot; playerWeapon computerWeapon\nlet tie anAction = printfn &quot;It's a tie. '%A'&quot; anAction\n\nlet ruling playerWeapon computerWeapon =\n // HH: By using discriminated unions this match\n // expression is much more readble and robust\n match (playerWeapon, computerWeapon) with\n | (Rock, Paper)\n | (Paper, Scissors)\n | (Scissors, Rock) -&gt; computerWin playerWeapon computerWeapon\n | (Rock, Scissors)\n | (Paper, Rock)\n | (Scissors, Paper) -&gt; playerWin playerWeapon computerWeapon\n | (_, _) -&gt; tie playerWeapon\n\nlet playGame playerWeapon computerWeapon =\n printfn &quot;You've chosen '%A'.&quot; playerWeapon\n printfn &quot;The computer chose '%A'.&quot; computerWeapon\n ruling playerWeapon computerWeapon\n ()\n\nlet runGame () =\n let playerAction = playerAction ()\n match playerAction with\n | Some playerWeapon -&gt;\n let computerWeapon = computerAction ()\n playGame playerWeapon computerWeapon\n true\n | None -&gt; false\n\n// HH: Personally I don't like,that you call main recursively.\n// You probably don't violate any formal or informal rule, but it just look wrong to me\n// So make a dedicated function to start the game by\nlet rec play () =\n match runGame() with\n | true -&gt; play()\n | false -&gt; ()\n</code></pre>\n<p>I have changed some of the names so that they matches my naming. For the example I show that you can extent a discriminated union with members (static and instance). You could chose to have these methods as normal function instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T11:58:48.683", "Id": "482938", "Score": "0", "body": "Thank you very much. I have learned already a lot and I will look up more of the patterns you've displayed and mentioned." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T09:30:54.547", "Id": "245803", "ParentId": "245567", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T15:59:22.227", "Id": "245567", "Score": "6", "Tags": [ "beginner", "f#" ], "Title": "First-time F#: A simple Rock Paper Scissors" }
245567
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.</p> <p>The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.</p> <p>Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.</p> <p>During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].</p> <p>Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)</p> <p>Then, the game can end in 3 ways:</p> <ul> <li>If ever the Cat occupies the same node as the Mouse, the Cat wins.</li> <li>If ever the Mouse reaches the Hole, the Mouse wins.</li> <li>If ever a position is repeated (ie. the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.</li> </ul> <p>Given a graph, and assuming both players play optimally, return 1 if the game is won by Mouse, 2 if the game is won by Cat, and 0 if the game is a draw.</p> </blockquote> <h3>Inputs</h3> <pre><code>[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]] [[1,3],[0],[3],[0,2]] [[2,3],[3,4],[0,4],[0,1],[1,2]] [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3],[2,3],[3,4],[0,4],[0,1],[1,2]] [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3],[2,3],[3,4],[0,4],[0,1],[1,2],[6,4,3],[6,4,2],[1,4,3],[2,4,3]] </code></pre> <h3>Outputs</h3> <pre><code>0 1 1 2 2 </code></pre> <h3>Code</h3> <pre><code>#include &lt;vector&gt; #include &lt;queue&gt; class Solution { static constexpr int mouse_turn = 0; static constexpr int cat_turn = 1; static constexpr int draw = 0; static constexpr int mouse_wins = 1; static constexpr int cat_wins = 2; public: static const int catMouseGame(const std::vector&lt;std::vector&lt;int&gt;&gt; &amp;graph) { const int size = graph.size(); std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; states( size, std::vector&lt;std::vector&lt;int&gt;&gt;(size, std::vector&lt;int&gt;(2, draw)) ); std::vector&lt;std::vector&lt;std::vector&lt;int&gt;&gt;&gt; indegree_paths( size, std::vector&lt;std::vector&lt;int&gt;&gt;(size, std::vector&lt;int&gt;(2)) ); std::queue&lt;std::vector&lt;int&gt;&gt; queue; for (int i_ind = 0; i_ind &lt; size; i_ind++) { if (i_ind) { states[0][i_ind][mouse_turn] = states[0][i_ind][cat_turn] = mouse_wins; queue.push(std::vector&lt;int&gt; {0, i_ind, mouse_turn, mouse_wins}); queue.push(std::vector&lt;int&gt; {0, i_ind, cat_turn, mouse_wins}); states[i_ind][i_ind][mouse_turn] = states[i_ind][i_ind][cat_turn] = cat_wins; queue.push(std::vector&lt;int&gt; {i_ind, i_ind, mouse_turn, cat_wins}); queue.push(std::vector&lt;int&gt; {i_ind, i_ind, cat_turn, cat_wins}); } for (int j_ind = 0; j_ind &lt; size; j_ind++) { indegree_paths[i_ind][j_ind][mouse_turn] = graph[i_ind].size(); indegree_paths[i_ind][j_ind][cat_turn] = graph[j_ind].size(); if (find(graph[j_ind].begin(), graph[j_ind].end(), 0) != graph[j_ind].end()) { indegree_paths[i_ind][j_ind][cat_turn]--; } } } while (!queue.empty()) { const int mouse_state = queue.front()[0]; const int cat_state = queue.front()[1]; const int turn = queue.front()[2]; const int final_state = queue.front()[3]; queue.pop(); const int prev_turn = not turn; if (mouse_turn == prev_turn) { for (const auto &amp;mouse : graph[mouse_state]) { if (states[mouse][cat_state][prev_turn] == draw) { if (mouse_wins == final_state) { states[mouse][cat_state][prev_turn] = mouse_wins; } else { indegree_paths[mouse][cat_state][prev_turn]--; if (not indegree_paths[mouse][cat_state][prev_turn]) { states[mouse][cat_state][prev_turn] = cat_wins; } } if (states[mouse][cat_state][prev_turn] != draw) { queue.push( std::vector&lt;int&gt; {mouse, cat_state, prev_turn, states[mouse][cat_state][prev_turn]} ); } } } } else { for (const auto &amp;cat : graph[cat_state]) { if (not cat) { continue; } if (states[mouse_state][cat][prev_turn] == draw) { if (cat_wins == final_state) { states[mouse_state][cat][prev_turn] = cat_wins; } else { indegree_paths[mouse_state][cat][prev_turn]--; if (not indegree_paths[mouse_state][cat][prev_turn]) { states[mouse_state][cat][prev_turn] = mouse_wins; } } if (states[mouse_state][cat][prev_turn] != draw) { queue.push( std::vector&lt;int&gt; {mouse_state, cat, prev_turn, states[mouse_state][cat][prev_turn]} ); } } } } } return states[1][2][mouse_turn]; } }; </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/cat-and-mouse/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/cat-and-mouse/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/cat-and-mouse/solution/" rel="nofollow noreferrer">Solution</a></p> </li> </ul>
[]
[ { "body": "<pre><code> for (int i_ind = 0; i_ind &lt; size; i_ind++) {\n if (i_ind) {\n</code></pre>\n<p>is a known anti-pattern. <code>if (i_ind)</code> is guarantied to fail at the first iteration, and is guaranteed to succeed at all the rest of them. Move the special case out of the loop, and start the loop with <code>int i_ind = 1;</code>. To keep the code DRY, make the block</p>\n<pre><code> for (int j_ind = 0; j_ind &lt; size; j_ind++) {\n indegree_paths[i_ind][j_ind][mouse_turn] = graph[i_ind].size();\n indegree_paths[i_ind][j_ind][cat_turn] = graph[j_ind].size();\n\n if (find(graph[j_ind].begin(), graph[j_ind].end(), 0) != graph[j_ind].end()) {\n indegree_paths[i_ind][j_ind][cat_turn]--;\n }\n }\n</code></pre>\n<p>into a function. As a side note, it is always a good idea to avoid naked loops.</p>\n<hr />\n<p>Speaking of DRY, the <code>if (mouse_turn == prev_turn)</code> and <code>else</code> clauses are pretty much identical. You should try to factor them into a function as well. Let me repeat the no-naked-loops mantra.</p>\n<p>It is very unclear why he <code>else</code> clause tests for <code>not cat</code>, but the <code>if</code> clause does not have a symmetric <code>not mouse</code> test. That said, I don't see how these tests may ever fail.</p>\n<hr />\n<p>I am not sure that <code>std::vector</code> holding 4 values of a completely unrelated nature is a right approach. Names are better than indices. Consider a</p>\n<pre><code>struct state {\n int mouse_state;\n int cat_state;\n int turn; // Even maybe `bool turn;`\n int final_state;\n};\n</code></pre>\n<hr />\n<p>I do not endorse using <code>not</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T22:53:24.550", "Id": "245583", "ParentId": "245570", "Score": "2" } }, { "body": "<h2>Code Review</h2>\n<pre><code>static constexpr int mouse_turn = 0;\nstatic constexpr int cat_turn = 1;\nstatic constexpr int draw = 0;\nstatic constexpr int mouse_wins = 1;\nstatic constexpr int cat_wins = 2;\n</code></pre>\n<p>Prefer to use enum for this:</p>\n<pre><code>enum Turn {Mouse, Cat};\nenum State {Draw, MouseWins, CatWins};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:00:58.080", "Id": "245601", "ParentId": "245570", "Score": "2" } } ]
{ "AcceptedAnswerId": "245583", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T16:38:13.663", "Id": "245570", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 913: Cat and Mouse" }
245570
<p>I'm relatively new to Scala and made a small TicTacToe in a functional Style. Any improvement options would be highly appreciated.</p> <p>There are some things which I am unsure of if they are made in an optimal way.</p> <ol> <li>Error Handling in the readMove Function</li> <li>If i should incorporate types like (type Player = Char, type Field = Int) and if they would benefit the code</li> <li>The printBoard function looks unclean and I can't yet figure out how to best change it.</li> <li>board(nextMove) = nextPlayer(board) seems to break the style of immutable values.</li> </ol> <p>This is already an improvement from my <a href="https://codereview.stackexchange.com/questions/244868/improvements-tictactoe-in-scala/245189#245189">first version</a></p> <pre class="lang-scala prettyprint-override"><code>import scala.annotation.tailrec import scala.io.StdIn.readLine object TicTacToeOld { val startBoard: Array[Char] = Array('1', '2', '3', '4', '5', '6', '7', '8', '9') val patterns: Set[Set[Int]] = Set( Set(0, 1, 2), Set(3, 4, 5), Set(6, 7, 8), Set(0, 3, 6), Set(1, 4, 7), Set(2, 5, 8), Set(0, 4, 8), Set(2, 4, 6) ) def main(args: Array[String]): Unit = { startGame() } def startGame(): Unit ={ println(&quot;Welcome to TicTacToe!&quot;) println(&quot;To play, enter the number on the board where you want to play&quot;) printBoard(startBoard) nextTurn(startBoard) } @tailrec private def nextTurn(board: Array[Char]): Unit = { val nextMove = readMove(board) board(nextMove) = nextPlayer(board) printBoard(board) if (!isWon(board)) { nextTurn(board) } } @tailrec private def readMove(board: Array[Char]): Int ={ try { val input = readLine(&quot;Input next Turn: &quot;).toInt-1 if(input&lt;0 || input&gt;8 || !board(input).toString.matches(&quot;[1-9]&quot;)) { throw new Exception } input } catch { case _: Exception =&gt; readMove(board) } } private def nextPlayer(board: Array[Char]): Char = { val remainingTurns = board.count(_.toString.matches(&quot;[1-9]&quot;)) if(remainingTurns%2 == 0) 'x' else 'o' } private def printBoard(board: Array[Char]): Unit = { print( 0 to 2 map { r =&gt; 0 to 2 map { c =&gt; board(c + r*3) } mkString &quot;|&quot; } mkString (&quot;__________\n&quot;, &quot;\n------\n&quot;, &quot;\n&quot;) ) println(&quot;Next Player is &quot; + nextPlayer(board)) } private def isWon(board: Array[Char]): Boolean = { patterns.foreach(pattern=&gt;{ if(pattern.forall(board(_) == board(pattern.head))) { print(&quot;Winner is &quot; + board(pattern.head)) return true } }) false } } </code></pre>
[]
[ { "body": "<ol>\n<li>you can remove main method and use <code>extends App</code>. It's safe 3 line of code.</li>\n<li>replace <code>Array('1', '2', '3', '4', '5', '6', '7', '8', '9')</code> on <code>('1' to '9').toArray</code></li>\n<li>I prefer always use type annotation if it is not clear. E.g.: <code>val nextMove: Int = readMove(board)</code></li>\n<li>use Intellij autoformat (ctrl + alt + L)</li>\n<li>it is good idea to say user what is wrong with his input before prompt new one</li>\n<li><code>[Char].toString.matches(&quot;[1-9]&quot;)</code> may be replaced on <code>[Char].isDigit</code> (PS: may be it is not correct, because <code>0</code> is also digit)</li>\n<li><strong>don't use return keyword</strong>, especially in <code>foreach</code>, <code>map</code> and so on. It is not what you want, at least in this cases. <code>foreach</code> + <code>forall</code> + <code>return</code> should be replaced on <code>contains</code> + <code>forall</code> or something.</li>\n<li>usually <code>list map f</code> used only for non-chained calls, but not for <code>list map m filter filter collect g</code>, because it is unclear for reader. UPDATE: also this syntax used for symbol-named functions, like <code>+</code>, <code>::</code>, <code>!</code> (in akka).</li>\n<li>you can use special type for positive digit, for example, <code>case class PosDigit(v: Int) {require(v &gt;= 0 &amp;&amp; v &lt;= 9, s&quot;invalide positive digit: $v&quot;)}</code></li>\n<li>there is no essential reason to pass board as argument. Commonly if argument is passed, it is not changed. In your code it is not.</li>\n</ol>\n<p>UPDATE for 10. In functional programming the clear way is to pass immutable collection to function and return new one if you need. It is programming without side effects. In OOP there is way to use mutable collection of class (or class's object). Scala both OOP and FP language.</p>\n<p>Sorry for my English.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:50:17.623", "Id": "483372", "Score": "0", "body": "Lots of good points. About your last point - I agree the OP is doing it wrong, but ibstead of having a global array, they should pass a List around everywhere, since that’s more idiomatic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T21:05:09.810", "Id": "483413", "Score": "1", "body": "What I definitely agree on is that the Array 1 to 9 can be put out from the global state and pushed into startGame, as it is just used once. Could you elaborate point 10 please, I don't really understand what you mean, or what the alternative would be. Otherwise great points made. I'm definitely gonna introduce them to the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T11:02:36.927", "Id": "246030", "ParentId": "245574", "Score": "5" } }, { "body": "<ol>\n<li><p>You are right that the <code>readMove</code> could be made better. There's no need for throwing an exception, especially since you're catching it immediately. A simple if/else can do the job here:</p>\n<pre><code>@tailrec\nprivate def readMove(board: Array[Char]): Int = {\n val input = readLine(&quot;Input next Turn: &quot;).toInt-1\n if(input&lt;0 || input&gt;8 || !board(input).toString.matches(&quot;[1-9]&quot;)) {\n readMove(board)\n } else {\n input\n }\n</code></pre>\n<p>However, this means that an exception will be thrown if the input is not an integer. To fix that, regex can be used:</p>\n<pre><code>@tailrec\nprivate def readMove(board: Array[Char]): Int = {\n val input = readLine(&quot;Input next Turn: &quot;)\n if (input.matches(&quot;[1-9]&quot;)) {\n val move = input.toInt - 1\n if (board(move).isDigit) {\n move\n } else {\n println(&quot;That location is already taken.&quot;)\n readMove(board)\n }\n } else {\n println(&quot;The input must be an integer between 1 and 9.&quot;)\n readMove(board)\n }\n}\n</code></pre>\n<p>I added a message telling the user what they did wrong, since simply asking for input again may be confusing. I also used <code>isDigit</code> as Mikhail Ionkin's answer suggested because it's cleaner.</p>\n</li>\n<li><p>Since <code>Char</code> is a pretty simple type, I don't think you need a type alias for it. <code>Array[Char]</code> is also rather simple, but it's up to you if you want it. Personally, I wouldn't use a type alias (yes, I know I recommended it in my last answer, but that was nearly a year ago).</p>\n</li>\n<li><p><code>printBoard</code> looks more or less okay to me (though I may be a bit biased :) ), although here's an alternative using <code>grouped</code> to take advantage of the fact that the board is a single 1D array and not a collection of moves.</p>\n<pre><code>private def printBoard(board: Array[Char]): Unit = {\n println(\n board.grouped(3)\n .map(_.mkString(&quot;|&quot;))\n .mkString(&quot;__________\\n&quot;, &quot;\\n------\\n&quot;, &quot;&quot;)\n )\n println(s&quot;Next Player is ${nextPlayer(board)}&quot;)\n}\n</code></pre>\n<p>Like the original, this creates new collections each time, but it shouldn't make a difference with a board of just 9 cells.</p>\n</li>\n<li><p><code>board(nextMove) = nextPlayer(board)</code> is indeed not idiomatic Scala, where one usually avoids mutable collections such as <code>Array</code>. I'd like to suggest, once again, a <code>List</code> of moves that you can easily prepend to each time you add a move instead of modifying it directly.</p>\n</li>\n</ol>\n<hr />\n<p>Some more things I'd like to point out:</p>\n<ul>\n<li><p>The <code>nextPlayer</code> method doesn't feel right. You're traversing the array each time to find the next player. I'd suggest keeping track of the current player (as a local variable that's passed around, not as a global variable).</p>\n</li>\n<li><p><code>isWon</code> is an effectful method. You should either rename it so that it's clear that you're also going to have side effects there, not just return a <code>Boolean</code>, or you should return a value indicating whether there's a winner, there's a tie, or the game can continue. That value should be used by the calling function to print the results.</p>\n</li>\n<li><p>Also, I don't see any way for the game to end should a tie occur. This seems to be a pretty big problem.</p>\n</li>\n<li><p>In the <code>isWon</code> method, you use <code>return true</code>. Using <code>return</code> from a lambda is a <a href=\"https://tpolecat.github.io/2014/05/09/return.html\" rel=\"nofollow noreferrer\">bad idea</a> (in fact, using <code>return</code> <em>at all</em> isn't a good idea). It throws a <code>NonLocalReturnControl</code> exception to pretend to work like a normal <code>return</code>. It can seriously mess things up if you call the lambda somewhere else and there's nothing to catch the exception. Instead, you can use <code>find</code> here to obtain an <code>Option</code> possibly containing a <code>Player</code>, and then act on that.</p>\n</li>\n<li><p>I agree with all of Mikhail Ionkin's points except the last one. Passing the board around is better than keeping it as a global variable. I'd suggest continuing to do that.</p>\n</li>\n<li><p>Your code's formatted pretty well, but some places lack spaces. Make sure you put a space between <code>if</code> and the opening parenthesis, between operators like <code>&lt;</code> and their operands (<code>input &lt; 0</code> instead of <code>input&lt;0</code>), and between a lambda parameter and the arrow (<code>pattern =&gt;</code>). Also, the lambda in <code>isWon</code> can be rewritten like this:</p>\n<pre><code>patterns.foreach { pattern =&gt;\n ...\n}\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-09T19:14:28.690", "Id": "260539", "ParentId": "245574", "Score": "3" } } ]
{ "AcceptedAnswerId": "246030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:18:44.647", "Id": "245574", "Score": "6", "Tags": [ "functional-programming", "scala" ], "Title": "Improving my Tic Tac Toe Solution in Scala" }
245574
<p>This is my first major project in F#, looking for any critique on how I can make it more standard or more concise.</p> <p>Some things I feel like I could have done better are the command flag parsing and the actual crypto random generation itself. I do know that crypto generators are slower than pseudo rng but I figure that a crytpo generator is better for generating something that should be secure.</p> <pre><code> open System.Security.Cryptography open System.Text open System [&lt;EntryPoint&gt;] let main argv = let rec contains item list : bool = match list with | [] -&gt; false | head::tail -&gt; (head = item) || contains item tail let strContainsOnlyNumber (s:string) = System.UInt32.TryParse s |&gt; fst let rec buildChars chars (args: string list) : char list = let numbers = ['0'..'9'] let lower = ['a'..'z'] let upper = ['A'..'Z'] let special = ['!' .. '/'] @ ['@'] match args with | [] -&gt; lower @ upper @ numbers | head::_ when args.Length = 1 &amp;&amp; strContainsOnlyNumber head -&gt; (chars @ lower @ upper @ numbers) | head::tail when head = &quot;-l&quot; || head = &quot;--lower&quot; -&gt;if tail.Length &gt; 0 then buildChars (chars @ lower) tail else chars @ lower | head::tail when head = &quot;-u&quot; || head = &quot;--upper&quot; -&gt; if tail.Length &gt; 0 then buildChars (chars @ upper) tail else chars @ upper | head::tail when head = &quot;-s&quot; || head = &quot;--special&quot; -&gt; if tail.Length &gt; 0 then buildChars (chars @ special) tail else chars @ special | head::tail when head = &quot;-n&quot; || head = &quot;--numeric&quot; -&gt; if tail.Length &gt; 0 then buildChars (chars @ numbers) tail else chars @ numbers | _::tail when chars.Length = 1 &amp;&amp; tail.Length = 0 -&gt; lower @ upper @ numbers | _::tail when chars.Length = 1 -&gt; buildChars chars tail | _ -&gt; chars let rec buildString (bytes: byte list) (chars: char list) (builder: StringBuilder) : string = match bytes with | [] -&gt; builder.ToString() | head::tail -&gt; buildString tail chars &lt;| builder.Append chars.[(int) head % chars.Length] use rng = new RNGCryptoServiceProvider() let bytes : byte array = Array.zeroCreate &lt;| if strContainsOnlyNumber(argv.[0]) then Convert.ToInt32 argv.[0] else 16 rng.GetBytes(bytes) let byteList : byte list = bytes |&gt; Array.toList let characters = (buildChars [' '] (argv |&gt; Array.toList)).Tail let sb = StringBuilder() let pass = buildString byteList characters sb printfn &quot;%s&quot; &lt;| pass 0 </code></pre>
[]
[ { "body": "<p>As a first attempt in F# you have passed the test, but the overall impression is a little messy, while the algorithm seems to (almost) work as expected.</p>\n<hr />\n<p>If calling it with an empty argument list - from this:</p>\n<blockquote>\n<pre><code>match args with\n | [] -&gt; lower @ upper @ numbers\n</code></pre>\n</blockquote>\n<p>in <code>buildChars</code>, I would expect it to produce a 16 chars password from the default settings. But it fails here:</p>\n<blockquote>\n<pre><code>let bytes : byte array = Array.zeroCreate &lt;| if strContainsOnlyNumber(argv.[0]) then Convert.ToInt32 argv.[0] else 16\n</code></pre>\n</blockquote>\n<p>with an <code>IndexOutOfRangeException</code></p>\n<hr />\n<blockquote>\n<pre><code> let rec contains item list : bool =\n match list with\n | [] -&gt; false\n | head::tail -&gt; (head = item) || contains item tail\n</code></pre>\n</blockquote>\n<p>This is not used, so delete it. If you need a <code>contains</code> function, the <code>List</code>-module has a predefined such ready to use.</p>\n<hr />\n<p>Especially <code>buildChars</code> seems overly messy and complicated, and it is not very efficient that the char lists (<code>numbers</code>, <code>lower</code>, etc) are redefined for each recursion. Instead of having <code>buildChars</code> as a <code>rec</code> function you could have an inner recursive function to the matching and then define the char lists out side of that:</p>\n<pre><code>let buildChars chars (args: string list) : char list =\n let numbers = ['0'..'9']\n let lower = ['a'..'z']\n let upper = ['A'..'Z']\n let special = ['!' .. '/'] @ ['@']\n let rec listBuilder chars args = \n match args with\n | [] -&gt; lower @ upper @ numbers\n // ... etc.\n\n listBuilder chars args\n</code></pre>\n<p>Besides that, I think I would think of another design, if I find my self repeating the almost same code like in this function. <code>List.fold</code> may be a solutions in this case.</p>\n<p>Another issue with the function is that if the argument list contains more of the same argument (for instance &quot;-l&quot;, &quot;-l&quot;) it will be included more than once making the result somewhat biased. Maybe consider to reduce the argument list to a distinct set - unless you want the behavior.</p>\n<hr />\n<p>You could consider to print help/information, if the <code>argv</code> has a <code>&quot;-?&quot;</code> entry.</p>\n<hr />\n<p>In F#, lists are very convenient because of its operators that makes the code more readable, but in this particular algorithm, I think I would stick to use arrays for everything, because you address the list entries by index, which is not efficient for lists, because <code>chars.[index]</code> is an O(index) operation where the same operation is O(1) for arrays, further <code>List.length</code> is a O(n) operation - adding more inefficiency to the equation.</p>\n<hr />\n<blockquote>\n<pre><code>let rec buildString (bytes: byte list) (chars: char list) (builder: StringBuilder) : string =\n match bytes with\n | [] -&gt; builder.ToString()\n | head::tail -&gt; buildString tail chars &lt;| builder.Append chars.[(int) head % chars.Length]\n</code></pre>\n</blockquote>\n<p>This function is not tail recursive and therefore builds up the stack. For a password generator it will probably never be an issue, but there is a hypothetical risk for a stack overflow. Fortunately you can easily make it tail recursive and more efficient, because <code>builder.Append</code> returns the builder itself. So changing the last line to</p>\n<pre><code>| head::tail -&gt; buildString tail chars (builder.Append chars.[(int) head % chars.Length])\n</code></pre>\n<p>makes the function tail recursive.</p>\n<hr />\n<p>Below is my version with some inline explanation:</p>\n<pre><code>let passwordGenerator (argv: string []) = \n\n // The @ - operator for lists is temporarily redefined to work with arrays\n // in order to make the code more readable\n let inline (@) left right = Array.append left right\n\n // From the first argument or a possible empty argument list the\n // custom size and if the default settings should be used is determined\n let useDefaults, size = \n match argv.Length with\n | 0 -&gt; true, 16\n | _ -&gt; \n match (Int32.TryParse(argv.[0])) with\n | true, n -&gt; (argv.Length = 1), n\n | false, _ -&gt; false, 16\n\n // The usable characters are determined from the arguments\n let chars = \n let lower = [| 'a'..'z' |]\n let upper = [| 'A'..'Z' |]\n let numbers = [| '0'..'9' |]\n let special = [| '!' .. '/' |] @ [| '@' |]\n\n if useDefaults then\n lower @ upper @ numbers\n else\n // This will avoid duplicate chars\n let predicate arg short long (chs: char[]) all = \n (arg = short || arg = long) &amp;&amp; not (all |&gt; Array.contains (chs.[0]))\n\n let folder all arg =\n match arg with\n | a when predicate a &quot;-l&quot; &quot;--lower&quot; lower all -&gt; all @ lower\n | a when predicate a &quot;-u&quot; &quot;--upper&quot; upper all -&gt; all @ upper\n | a when predicate a &quot;-n&quot; &quot;--numerics&quot; numbers all -&gt; all @ numbers\n | a when predicate a &quot;-s&quot; &quot;--special&quot; special all -&gt; all @ special\n | _ -&gt; all\n\n argv |&gt; Array.fold folder [||]\n\n // Provides the random bytes\n let bytes = \n use rng = new RNGCryptoServiceProvider()\n let bytes = Array.zeroCreate size\n rng.GetBytes(bytes)\n bytes\n\n // Generates the password\n let password = \n bytes \n |&gt; Array.map (fun b -&gt; chars.[int b % chars.Length]) \n |&gt; fun chs -&gt; new String(chs)\n\n printfn &quot;%s&quot; password\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:09:07.467", "Id": "482404", "Score": "1", "body": "I have done some code cleanup since I posted it. The 16 character password by default works and the contains is removed. Is the [| '0'..'9'|] syntax to create an array instead of a list? Also is the Array.distinct into the Array.fold to get rid of duplicate values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:20:38.470", "Id": "482406", "Score": "1", "body": "@DaltonEdmsiten: The syntax for array initialization is as you assume (`[| '0'..'9' |]`) just as for lists but with the extra pipe char. The `|> Array.distinct` part in my code was a leftover from an earlier version - sorry for that, I've removed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:21:32.090", "Id": "482407", "Score": "1", "body": "I'm also getting a ` Expecting a 'string -> int' but given a 'string -> unit'` error for the printfn and I can't seem to figure out why" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:23:04.660", "Id": "482408", "Score": "1", "body": "@DaltonEdmsiten: From my or your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:23:42.960", "Id": "482409", "Score": "1", "body": "Yours it was because there wasn't a return code though I figured it out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:24:44.273", "Id": "482410", "Score": "0", "body": "OK, yes in real world you'd of cause return the password instead of just print it out :-)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T10:41:17.610", "Id": "245611", "ParentId": "245579", "Score": "1" } }, { "body": "<p>The logic here was kind of hard to understand, but I <em>think</em> this is an equivalent refactoring with comments inlined:</p>\n<pre><code>open System\nopen System.Security.Cryptography\n\nmodule Chars =\n let numbers = ['0'..'9']\n let lower = ['a'..'z']\n let upper = ['A'..'Z']\n let special = ['!' .. '/'] @ ['@']\n\n// First parse the arguments separately. Use a DU to let the compiler\n// complain at us if we introduce a new case but forget to deal with it.\ntype Args =\n | Lower\n | Upper\n | Special\n | Numeric\n | Unknown of string\n\nlet parseArgs =\n let parseArg =\n function\n | &quot;-l&quot; | &quot;--lower&quot; -&gt; Lower\n | &quot;-u&quot; | &quot;--upper&quot; -&gt; Upper\n | &quot;-s&quot; | &quot;--special&quot; -&gt; Special\n | &quot;-n&quot; | &quot;--numeric&quot; -&gt; Numeric\n | s -&gt; Unknown s\n \n let rec parseArgs' knownArgs =\n function\n | [] -&gt; knownArgs\n | arg::rest -&gt;\n parseArgs'\n &lt;| parseArg arg :: knownArgs\n // or if keeping the same order matters:\n // knownArgs @ [parseArg arg]\n &lt;| rest\n\n parseArgs' []\n\n// Then build our chars from those argument cases. We could convert to a\n// set then back to list for uniqueness, or leave it as an array so we can\n// control relative frequency of chars.\nlet buildChars =\n let charSetFromArg =\n function\n | Lower -&gt; Chars.lower\n | Upper -&gt; Chars.upper\n | Special -&gt; Chars.special\n | Numeric -&gt; Chars.numbers\n | Unknown _ -&gt; []\n \n let rec buildChars' chars =\n function\n | [] -&gt; chars\n | arg::rest -&gt;\n buildChars'\n &lt;| chars @ charSetFromArg arg\n &lt;| rest\n // In your code we stop building if we encounter an unknown\n // arg after position 1, if that's intentional then stop recursing:\n // | Unknown _::_ -&gt; chars\n \n buildChars' [' '] // Should space be in special instead?\n\n// Build the password string from a char list and bytes\nlet buildPass =\n let rec buildPass' pass (chars: char list) =\n function\n | head::rest when chars.Length &gt; 0 -&gt;\n buildPass'\n &lt;| pass + string chars.[(int) head % chars.Length]\n &lt;| chars\n &lt;| rest\n | _ -&gt; pass\n\n buildPass' &quot;&quot;\n\n// Put everything together\nlet generatePassword argList =\n let defaultArgs = [\n Lower\n Upper\n Numeric\n ]\n\n let chars =\n let args =\n match parseArgs argList with\n | [] | [Unknown _] -&gt; defaultArgs\n | xs -&gt; xs\n\n buildChars args\n\n let bytes =\n let (|UInt|_|) (x: string) =\n match UInt32.TryParse x with\n | true, num -&gt; Some (int num)\n | false, _ -&gt; None\n\n let length =\n match argList with\n | UInt len::_ -&gt; len\n | _ -&gt; 16\n // This lets us handle no arguments at all, whereas your\n // code currently throws\n\n let bytes' = Array.zeroCreate length\n\n use rng = new RNGCryptoServiceProvider()\n rng.GetBytes(bytes')\n\n bytes' |&gt; Array.toList\n\n buildPass chars bytes\n\n[&lt;EntryPoint&gt;]\nlet main argv =\n argv\n |&gt; Seq.toList\n |&gt; generatePassword\n |&gt; printfn &quot;%s&quot;\n\n 0\n</code></pre>\n<p>The gist is to separate out the flag parsing bits, use a DU for each case, and clarify the complex behavior around having an int argument mixed in there.</p>\n<p>If you were to add any more args, I'd go with an arg parser library like <a href=\"https://fsprojects.github.io/Argu/\" rel=\"nofollow noreferrer\">Argu</a> to help with parsing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T06:10:20.597", "Id": "264309", "ParentId": "245579", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T20:09:26.947", "Id": "245579", "Score": "3", "Tags": [ "strings", ".net", "random", "cryptography", "f#" ], "Title": "Simple Password Generator Feedback" }
245579
<p>I'm writing an adjacency matrix, in this moment I'm trying to figure out how to indicate a default numeric value for an unassigned edge. There is the macro <code>_I64_MAX</code> but it is said that it's a bad practice to use macros. I wish to know if there's other way to assign such value (as a keyword as in the case of <code>nullptr</code> instead of <code>NULL</code>) or if what I'm doing is OK.</p> <p>Why don't I use <code>0</code>? Because the distance for an edge which start and end vertex is the same is: <span class="math-container">$$e=(v_i,v_i);~~~||e||=0$$</span></p> <pre class="lang-cpp prettyprint-override"><code>AdjacencyMatrix::AdjacencyMatrix(const SinglyLinkedList &amp;vertices) : vertices_(vertices) { this-&gt;edge_matrix_ = new int64_t *[this-&gt;vertices_.Size()]; for (size_t i = 0; i &lt; this-&gt;vertices_.Size(); i++) { this-&gt;edge_matrix_[i] = new int64_t[this-&gt;vertices_.Size()]; for (size_t j = 0; j &lt; this-&gt;vertices_.Size(); j++) { this-&gt;edge_matrix_[i][j] = _I64_MAX; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:51:29.647", "Id": "482317", "Score": "0", "body": "This is the wrong site for this question. Maybe a mod will move it to stack-overflow or something like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:52:21.020", "Id": "482318", "Score": "1", "body": "You may find this page interesting: https://en.cppreference.com/w/cpp/types/numeric_limits" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:53:35.520", "Id": "482319", "Score": "0", "body": "No because it is related to best practices, at first I doubted but I read the faq" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:57:06.103", "Id": "482320", "Score": "3", "body": "It's OK to ask \"Does this code follow common best practices?\", but not **\"What is the best practice regarding X?\"**" } ]
[ { "body": "<p><strong>Use of macros</strong></p>\n<p>In this case, the macro you using is from a library header that was included with your compiler. This header (ultimately <code>limits.h</code>, although <code>&lt;climits&gt;</code> is usually used with C++ code) is also used by C code, so C++ specific language features cannot be used. These are OK to use.</p>\n<p>The C++ way of referencing a minimum value for a type is to make use of <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits\" rel=\"nofollow noreferrer\"><code>std::numeric_limits</code></a> (in the <code>&lt;limits&gt;</code>) header. In your case, you can replace <code>_I64_MAX</code> with <code>std::numeric_limits&lt;int64_t&gt;::min()</code>.</p>\n<p><strong>Other notes</strong></p>\n<p>All of the references to <code>this-&gt;</code> are unnecessary and can be removed from your code. You rarely need to specify this in C++ code (there a few specific cases where it is needed, like for variable name disambiguation or calling a function thru a member function pointer).</p>\n<p>The <code>for</code> loop might be able to be rewritten using iterators or the <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-for</a> style if this is supported by the <code>SinglyLinkedList</code> type.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T01:02:35.297", "Id": "245587", "ParentId": "245581", "Score": "1" } } ]
{ "AcceptedAnswerId": "245587", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T21:48:43.663", "Id": "245581", "Score": "0", "Tags": [ "c++" ], "Title": "Handling default value for int64_t representing an edge in an adjacency matrix" }
245581
<p>I had an xls file with lots of full names in the following form at work:</p> <pre><code>+----------------------------+--------------+-----+-----+ | [Full name] | [More data] |[...]|[...]| +----------------------------|--------------------------+ | Cristiano RONALDO | ... | ... | ... | +----------------------------+--------------+-----+-----+ | Carol SEVILLA | ... | ... | ... | +----------------------------|--------------+-----+-----+ | Ronald Chris MAC DONALDS | ... | ... | ... | +----------------------------|--------------+-----+-----+ </code></pre> <p>some of the data will still be input this way but I want to add a column for last name and let it clear that I don't need the last name in upper case anymore, so I separated name from last name, and then changed the last name to camel case, notice that last names can have many words like &quot;Mc Donalds Rodriguez&quot; (it happens) so I solved it as follows</p> <pre><code>public static string GetLastNameFromFullName(string fullName) { var lastName = &quot;&quot;; foreach (var ch in fullName) { lastName += ch; if (char.IsLower(ch)) { lastName = &quot;&quot;; } } return lastName.TrimStart(); } public static string GetCameledLastName(string lastNames) { string[] lastNamesArr = lastNames.Split(' '); var lastNamesCameled = &quot;&quot;; foreach (string lastNameUpper in lastNamesArr) { lastNamesCameled += lastNameUpper[0]; for (int i = 1; i &lt; lastNameUpper.Length; i++) { lastNamesCameled += char.ToLower(lastNameUpper[i]); } } return lastNamesCameled; } public static string GetNameWithoutLastName(string fullName) { var possibleLastName = false; char possibleLastNameChar = ' '; //just initialized var name = &quot;&quot;; foreach (var ch in fullName) { if (char.IsUpper(ch)) { possibleLastNameChar = ch; if (possibleLastName) { break; } possibleLastName = true; } else { if (possibleLastName) { name += possibleLastNameChar; } name += ch; possibleLastName = false; } } return name; } private void Form1_Load(object sender, EventArgs e) { var path = @&quot;../../file.txt&quot;; //dumped from xls file string contents = File.ReadAllText(path); using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding(&quot;iso-8859-1&quot;))) //some names had ñ or accented characters { string line; while ((line = reader.ReadLine()) != null) { var fullName = &quot;&quot;; foreach (char ch in line) { if (ch == '\t') { //The columns in the xls file were divided by tab characters } else { fullName += ch; } } var lastName = GetLastNameFromFullName(fullName); Console.WriteLine(&quot;Name: &quot; + GetNameWithoutLastName(fullName)); Console.WriteLine(&quot;Last name: &quot; + GetCameledLastName(lastName)); } } } </code></pre> <p>I think my code could be a lot better.</p> <p><em><strong>UPDATE:</strong></em> please note that while it is true that cases like &quot;Cinthia del Río&quot; is an actual name that is not considered in this way, it will be converted to &quot;Cinthia Del Rio&quot; because in the xls file it would be in a single column as &quot;Cinthia DEL RIO&quot;, and of course it is impossible for the algorithm to know that &quot;DEL&quot; should actually be &quot;del&quot; even though it is perfectly OK for a last name's word to start with a lower case.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:52:44.737", "Id": "482355", "Score": "4", "body": "Have you considered using `CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fullName.ToLower())`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:43:54.170", "Id": "482359", "Score": "4", "body": "FYI: https://github.com/kdeldycke/awesome-falsehood#human-identity" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:45:26.353", "Id": "482360", "Score": "0", "body": "Yes please note that all last names are not correctly written in camel case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T08:33:34.083", "Id": "482371", "Score": "0", "body": "@BCdotWEB I saw the question. Tough \"I have to post that link\", but you already did. Should be mandatory reading for any programmer dealing with names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T11:44:40.993", "Id": "482375", "Score": "3", "body": "Names are tricky and do not fit neatly into a single algorithm. Edge cases taken from IMDB are: \"Sean van der Wilt\" and \"Paz de la Huerta\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:14:20.353", "Id": "482384", "Score": "0", "body": "I know @RickDavin that of course was a concern for me as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:25:38.467", "Id": "482388", "Score": "0", "body": "@HenrikHansen yes, I did see that in asp, as I was working with plain C# I thought I couldn't use that, was I wrong? does that work in c#?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:31:25.737", "Id": "482390", "Score": "2", "body": "@newbie: Yes, you can use it in every .NET environment/language" } ]
[ { "body": "<p>Well, I don't know if your code could be better or faster but the code could be a lot shorter by using some <code>Linq</code>-&quot;magic&quot;.</p>\n<p>Your code could use some level of input-parameter-validation because the methods in question are <code>public</code> which means anybody who uses these methods can pass whatever he/she wants, even <code>null</code> which would blow each method and would expose implementation details.</p>\n<p>I don't know if the requirement is meant to be that passing <code>Ronald Chris MAC DONALDS</code> returns as lastname <code>MacDonalds</code> but for me this doesn't sound correct.</p>\n<p>Instead of splitting the fullname twice and then splitting the lastname again, you should consider to just pass a <code>string[]</code> to the methods.</p>\n<p>You could consider to have one <code>public</code> method where you pass the fullname and get a <code>Tuple&lt;string, string&gt;</code> so you would need only one parameter validation because you can make the other methods <code>private</code>.</p>\n<p>Because a lastname contains only UpperCase letters we can take the passed <code>string[]</code> and take each <code>string</code> in this array which contains only upper-case letters, we will leave the first char because it allready is uppercase and take the remaining chars as lower-case chars. Last we join them using a space char like so</p>\n<pre><code>private static string GetLastName(string[] nameParts)\n{\n return string.Join(&quot; &quot;, nameParts.Where(s =&gt; s.All(c =&gt; char.IsUpper(c)))\n .Select(s =&gt; s[0] + s.Substring(1).ToLowerInvariant()));\n} \n</code></pre>\n<p>For the firstname we know that not all chars are upper-case chars. So we take each <code>string</code> inside the passed array and check if any char is a lower-case char, and then join the found strings by using a space char like so</p>\n<pre><code>private static string GetFirstName(string[] nameParts)\n{\n return string.Join(&quot; &quot;, nameParts.Where(s =&gt; s.Any(c =&gt; char.IsLower(c))));\n} \n</code></pre>\n<p>Last but not least we need to call these 2 methods after some proper validation like so</p>\n<pre><code>public static Tuple&lt;string, string&gt; GetNormalizedNames(string fullName)\n{\n if (fullName == null) { throw new ArgumentNullException(nameof(fullName)); }\n if (string.IsNullOrWhiteSpace(fullName)) { return Tuple.Create(&quot;&quot;, &quot;&quot;); }\n\n var nameParts = fullName.Split(' ');\n\n return Tuple.Create(GetFirstName(nameParts), GetLastName(nameParts));\n} \n</code></pre>\n<p>which we then call like so</p>\n<pre><code>var firstNameLastNameTuple = GetNormalizedNames(fullName);\nConsole.WriteLine(&quot;Name: &quot; + firstNameLastNameTuple.Item1);\nConsole.WriteLine(&quot;Last name: &quot; + firstNameLastNameTuple.Item2); \n</code></pre>\n<p>The whole code is now easier to read and therefor easier to maintain. Sure linq is only syntactic sugar and won't be faster than iterating over the chars by &quot;hand&quot; but the benefit is less and easier to read code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:39:49.487", "Id": "482352", "Score": "0", "body": "Actually these my are only used by me when I say use this file from my computer, so that's security is not really an issue even though that's a really good point, it's more like an app to solve a current problem kind.\nYour answer is just great tbh, so THANKS A LOT." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T05:24:21.230", "Id": "245598", "ParentId": "245584", "Score": "10" } }, { "body": "<p>just need to add another approach. You could use <code>Substring</code> and <code>IndexOf</code> to get the first and the last name without looping. The only loop that you need is on last name to camelCase it. Though, names that needed to be lowered case needs to be defined in an array or a switch statement when looping over the last name, that's if you need to add more precision on your output. Here is an example :</p>\n<pre><code>public static KeyValuePair&lt;string, string&gt; GetFirstAndLastName(string fullName)\n{\n if(fullName?.Length == 0) { return; }\n\n // take the first name, trim any whitespace and camelcase it\n var firstName = ToCamelCase(fullName.Substring(0, fullName.IndexOf(' ') + 1).Trim());\n \n // take the last name, trim any whitespace, and convert it to array\n var lastNameArray = fullName.Substring(firstName.Length).Trim().Split(' '); \n \n var lastName = string.Empty;\n\n foreach(var name in lastNameArray)\n {\n lastName += ToCamelCase(name) + &quot; &quot;;\n }\n\n lastName.TrimEnd();\n\n return new KeyValuePair&lt;string, string&gt;(firstName, lastName);\n}\n\npublic static string ToCamelCase(string name)\n{\n return name.Substring(0, 1).ToUpperInvariant() + name.Substring(1).ToLowerInvariant();\n}\n</code></pre>\n<p>usage :</p>\n<pre><code>var firstLastName = GetFirstAndLastName(fullName);\nConsole.WriteLine($&quot;Name: {firstLastName.Key}&quot;);\nConsole.WriteLine($&quot;Last name: {firstLastName.Value}&quot;);\n</code></pre>\n<p>another note on :</p>\n<pre><code>string contents = File.ReadAllText(path);\n</code></pre>\n<p>it's not used, and even if it's used, it would be useless, since <code>ReadAllText</code> would open a <code>StreamReader</code>, so you either use <code>ReadAllText</code> or <code>StreamReader</code>, using both would be redundant.</p>\n<p>Also, since your columns are separated by a tab, you can do this :</p>\n<pre><code>string line;\n\nwhile ((line = reader.ReadLine()) != null)\n{\n var columns = line.Split('\\t'); \n\n if(columns != null &amp;&amp; columns.Length &gt; 0)\n {\n var fullName = columns[0]; \n \n var firstLastName = GetFirstAndLastName(fullName);\n Console.WriteLine($&quot;Name: {firstLastName.Key}&quot;);\n Console.WriteLine($&quot;Last name: {firstLastName.Value}&quot;); \n }\n}\n</code></pre>\n<p>finally, I would suggest you use any type of converter that would parse your CVS or excel file into <code>DataTable</code> or an object model to make your work much maintainable. So, you can set your validation process once, and focus on processing the data whenever needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T20:23:36.000", "Id": "245637", "ParentId": "245584", "Score": "1" } } ]
{ "AcceptedAnswerId": "245598", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T23:26:15.930", "Id": "245584", "Score": "12", "Tags": [ "c#", "strings", "array", ".net", "file" ], "Title": "C# - name separation & last name in upper to Camel" }
245584
<p>For practice, I wrote some NASM code that prints out the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture" rel="noreferrer">hailstone sequence</a> of a (unfortunately, hardcoded) number.</p> <p>This is by far the most complex code I've ever written in NASM. I'd like advice on anything, but specifically:</p> <ul> <li>I'm trying to abide by CDECL. Am I doing anything off?</li> <li>The multiplication part seems overly complicated. The problem is, <code>mul</code> doesn't take an immediate, and the register that I want to multiply is <code>ebx</code>, not <code>eax</code>, so I need to do a couple <code>mov</code>s before I can multiply.</li> <li>Anything else that's worth mentioning.</li> </ul> <p><strong>hail.asm</strong>:</p> <pre class="lang-none prettyprint-override"><code>global _start section .data newline: db `\n` end_str: db `1\n` section .text print_string: ; (char* string, int length) push ebp mov ebp, esp push ebx mov eax, 4 mov ebx, 1 mov ecx, [ebp + 8] mov edx, [ebp + 12] int 0x80 pop ebx mov esp, ebp pop ebp ret print_int: ; (int n_to_print) push ebp mov ebp, esp push ebx push esi mov esi, esp ; So we can calculate how many were pushed easily mov ecx, [ebp + 8] .loop: mov edx, 0 ; Zeroing out edx for div mov eax, ecx ; Num to be divided mov ebx, 10 ; Divide by 10 div ebx mov ecx, eax ; Quotient add edx, '0' push edx ; Remainder cmp ecx, 0 jne .loop mov eax, 4 ; Write mov ebx, 1 ; STDOUT mov ecx, esp ; The string on the stack mov edx, esi sub edx, esp ; Calculate how many bytes were pushed int 0x80 add esp, edx pop esi pop ebx mov esp, ebp pop ebp ret main_loop: ; (int starting_n) push ebp mov ebp, esp push ebx mov ebx, [ebp + 8] ; ebx is the accumulator .loop: push ebx call print_int add esp, 4 push 1 push newline call print_string add esp, 8 test ebx, 1 jz .even .odd: mov eax, ebx mov ecx, 3 ; Because multiply needs a memory location mul ecx inc eax mov ebx, eax jmp .end .even: shr ebx, 1 .end: cmp ebx, 1 jnz .loop push 2 push end_str call print_string add esp, 8 pop ebx mov esp, ebp pop ebp ret _start: push 1000 ; The starting number call main_loop add esp, 4 mov eax, 1 mov ebx, 0 int 0x80 </code></pre> <p><strong>Makefile</strong>:</p> <pre><code>nasm hail.asm -g -f elf32 -Wall -o hail.o ld hail.o -m elf_i386 -o hail </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:17:15.530", "Id": "482333", "Score": "0", "body": "Have you compiled from C and disassembled for comparison?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T03:36:08.230", "Id": "482341", "Score": "0", "body": "@Reinderien No, but that's a good idea." } ]
[ { "body": "<h1>Multiplying by 3</h1>\n<blockquote>\n<p>The multiplication part seems overly complicated. The problem is, <code>mul</code> doesn't take an immediate, and the register that I want to multiply is <code>ebx</code>, not <code>eax</code>, so I need to do a couple <code>mov</code>s before I can multiply.</p>\n</blockquote>\n<p>This is all true, but based on the premise that the <code>mul</code> instruction must be used. Here are a couple of alternatives:</p>\n<ul>\n<li><code>imul ebx, ebx, 3</code>, listed in the manual as a <em>signed</em> multiplication, but that <a href=\"https://stackoverflow.com/q/45495711/555045\">makes no difference</a>, because only the low half of the product is used.</li>\n<li><code>lea ebx, [ebx + 2*ebx]</code>, even the +1 can be merged into it: <code>lea ebx, [ebx + 2*ebx + 1]</code>. As a reminder, <code>lea</code> evaluates the address on the right and stores it in the destination register, it does not access memory despite the square-brackets syntax. 3-component <code>lea</code> takes 3 cycles on some processors (eg Haswell, Skylake), making it slightly slower than a 2-component <code>lea</code> and a separate <code>inc</code>. 3-component <code>lea</code> is good on Ryzen.</li>\n</ul>\n<h1>Dividing by 10</h1>\n<p>The simplest way is of course to use the <code>div</code> instruction, but that's not the fastest way, and it's not what a compiler would do. Here is a faster way, similar to <a href=\"https://gcc.godbolt.org/z/Yn7vsW\" rel=\"noreferrer\">how compilers do it</a>, based on multiplying by a fixed-point reciprocal of 10 (namely 2<sup>35</sup> / 10, the difference between 2<sup>35</sup> and 2<sup>32</sup> is compensated for by shifting right by 3, the remaining division by 2<sup>32</sup> is implicit by taking the high half of the output of <code>mul</code>).</p>\n<pre><code>; calculate quotient ecx/10\nmov eax, 0xCCCCCCCD\nmul ecx\nshr edx, 3\nmov eax, ecx\nmov ecx, edx\n; calculate remainder as n - 10*(n/10)\nlea edx, [edx + 4*edx]\nadd edx, edx\nsub eax, edx\n</code></pre>\n<h1><code>push edx</code> in print_int</h1>\n<p>This will put 4 bytes on the stack for every character of the decimal representation of the integer, 1 actual char and 3 zeroes as filler. That looks fine when printed because a zero does not look like anything, so I'm not sure if this should be classed as a bug, but it just seems like an odd thing to do. The characters could be written to some buffer byte-by-byte, with a store and decrementing the pointer, then there would not be zeroes mixed in. A similar &quot;subtract pointers to find the length&quot;-trick could be used, that's a good trick.</p>\n<h1>Small tricks</h1>\n<blockquote>\n<pre><code>mov edx, 0 ; Zeroing out edx for div\n</code></pre>\n</blockquote>\n<p>That's fine but <a href=\"https://stackoverflow.com/q/33666617/555045\"><code>xor edx, edx</code> is preferred</a>, unless the flags must be preserved.</p>\n<blockquote>\n<pre><code> jmp .end\n.even\n</code></pre>\n</blockquote>\n<p>Given that <code>n</code> is odd, <code>3n+1</code> is even, so you could omit the jump and have the flow of execution fall straight into the &quot;even&quot; case. Of course that means that not all integers in the sequence are printed, so maybe you can't use this trick, depending on what you want from the program.</p>\n<p>If skipping some numbers to accelerate the sequence is OK, here is an other trick for that: skip a sequence of even numbers all at once by counting the trailing zeroes and shifting them all out.</p>\n<pre><code>tzcnt ecx, ebx\nshr ebx, cl\n</code></pre>\n<blockquote>\n<pre><code> mov esp, ebp\n pop ebp\n</code></pre>\n</blockquote>\n<p>If you want (it doesn't make a significant difference, so it's mostly personal preference), you can use <code>leave</code> instead of this pair of instructions. Pairing the <code>leave</code> with <code>enter</code> is not recommended <a href=\"https://stackoverflow.com/q/29790175/555045\">because <code>enter</code> is slow, but <code>leave</code> itself is OK</a>. GCC likes to use <code>leave</code> when it makes sense, but Clang and MSVC don't.</p>\n<blockquote>\n<pre><code> cmp ecx, 0\n jne .loop\n</code></pre>\n</blockquote>\n<p>That's fine, but there are a couple of alternatives that you may find interesting:</p>\n<ul>\n<li>\n<pre><code>test ecx, ecx\njne .loop\n</code></pre>\nSaves a byte, thanks to not having to encode the zero explicitly.</li>\n<li>\n<pre><code>jecxz .loop\n</code></pre>\nThis special case can be used because <code>ecx</code> is used. Only 2 bytes instead of 5 or 4. However, unlike a fusible arith/branch pair, this costs 2 µops on Intel processors. On Ryzen there is no downside.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T12:44:51.063", "Id": "482379", "Score": "0", "body": "Awesome, thank you. I really appreciate this. And regarding `push edx`, ya, it's bad. At my current level though, I couldn't think of how to else to do it. That'll be something I revisit as I progress." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:16:13.470", "Id": "482411", "Score": "1", "body": "One other thing, is using `lea` to do basic math on values idiomatic? The \"A\" suggests that it's meant for addresses, so I've only been using `lea` for addresses so far. Is it considered an abuse to do simple non-address math, or is that a very typical, standard technique?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:36:01.333", "Id": "482413", "Score": "3", "body": "@Carcigenicate it is normal to use `lea` for integer arithmetic, just as it is normal to use `add/sub/inc/dec` for addresses, whatever suits the calculation best. [Peter wrote some more about it](https://stackoverflow.com/a/46597375/555045)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:43:57.150", "Id": "482414", "Score": "0", "body": "Good to know. That certainly simplifies things. Thank you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T09:22:09.037", "Id": "245608", "ParentId": "245585", "Score": "5" } } ]
{ "AcceptedAnswerId": "245608", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T00:15:35.243", "Id": "245585", "Score": "5", "Tags": [ "beginner", "assembly", "collatz-sequence", "nasm" ], "Title": "Hailstone Sequence in NASM" }
245585
<p>Very simple square root calculator. I am sure it's terrible and can be made much better.</p> <p>I feel it's way too many lines.</p> <pre><code>import random ## ask user for a number to find sq root for num1 = input(&quot;Please enter number for which we'll find sq root:\n&quot;) ## generate a random number and test it randomNum1 = random.randint(1,9) print(&quot;Random number is &quot; + str(randomNum1)) ranMul1 = 0 while True: if float(ranMul1) == float(num1): print(&quot;square root of &quot; + str(num1) + &quot; is &quot; + str(randomNum1)) break else: randomNum1 = round((float(randomNum1) + (float(num1)/float(randomNum1))) / 2, 4) ranMul1 = round(randomNum1 * randomNum1,4) print(&quot;Trying number &quot; + str(randomNum1)) continue </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:54:57.833", "Id": "482488", "Score": "1", "body": "Search for \"Newton's method for square roots\"." } ]
[ { "body": "<p>Welcome to the community :). A few pointers:</p>\n<ol>\n<li>The code does not follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8 style guide</a>. You should follow the <code>snake_case</code> naming convention for variables.</li>\n<li>Split code into separate functions.</li>\n<li>Instead of the code running as is, the execution condition should be placed inside an <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__</code></a> block.</li>\n<li>If you're on python 3.6+, make use of f-strings over concatenating separate variables and casting them to strings over and over.</li>\n<li>Cast the input from user as float as soon as it is read.</li>\n<li>I don't think you need to round the random variable calculated to 4 digits. For print purpose, you can use the precision specifier.</li>\n<li>Again, if using python 3.6+, you can also provide type hinting.</li>\n</ol>\n<hr />\n<p>The above mentioned points, and a few more changes, your code would be:</p>\n<pre><code>from math import isclose\nfrom random import randint\n\n\ndef calculate_sq_root(num: float) -&gt; float:\n &quot;generate a random number and manipulate it until we calculate square root of input number&quot;\n random_num = randint(1, 9)\n print(f&quot;Random number is {random_num}.&quot;)\n while not isclose(num, random_num * random_num):\n random_num = (random_num ** 2 + num) / (random_num * 2)\n print(f&quot;Trying number {random_num:.4f}&quot;)\n return random_num\n\n\ndef get_input() -&gt; float:\n &quot;ask user for a number to find sq root for&quot;\n return float(input(&quot;Please enter number for which we'll find sq root:\\n&quot;))\n\n\ndef main():\n user_num = get_input()\n sq_root = calculate_sq_root(user_num)\n print(f&quot;Square root of {user_num} is {sq_root}.&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:10:22.190", "Id": "482331", "Score": "3", "body": "Your docstring for `calculate_sq_root` should use triple-quotes, not quotes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:10:57.207", "Id": "482332", "Score": "1", "body": "Also, the cast to `float` is redundant here: `float(num / random_num)` - Python will do type promotion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:30:19.193", "Id": "482335", "Score": "0", "body": "@Reinderien yes. those points are mentioned in pep 8. I edited the code in tio.run page itself, so not much formatting could be done." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T01:10:56.170", "Id": "245588", "ParentId": "245586", "Score": "8" } }, { "body": "<p>The great input from @hjpotter92 gets you 99% of the way there. The only additional comment I have is about this:</p>\n<pre><code>while num != random_num * random_num:\n</code></pre>\n<p>Exact comparison of floating-point numbers is problematic. You're going to want to pick some (very small) number, usually called epsilon, below which the error is insignificant and call that &quot;close enough&quot;.</p>\n<p>Read <a href=\"https://docs.python.org/3/library/math.html#math.isclose\" rel=\"noreferrer\">https://docs.python.org/3/library/math.html#math.isclose</a> for more details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:34:02.613", "Id": "482336", "Score": "0", "body": "updated this in my reply too. thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:15:21.660", "Id": "245590", "ParentId": "245586", "Score": "12" } } ]
{ "AcceptedAnswerId": "245588", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T00:36:25.187", "Id": "245586", "Score": "9", "Tags": [ "python", "reinventing-the-wheel" ], "Title": "Simple square root calculator" }
245586
<p>I just finished coding a Tic Tac Toe game for my first Python project. I need some advice on things I can improve; please help. Everything seems to be running correctly. I used many functions. In the comments you can know what functions do; there is board initialization and prints the board out to the console checks the input and updates the board according to the user's decision, function analyzes the board status in order to check the player using 'O's or 'X's has won the game and a function draws the computer's move and updates the board.</p> <pre><code>from random import randrange result = False board=[[1,2,3],[4,'X',6],[7,8,9]] # #board initialization always first move of computer is in the middle def DisplayBoard(board): for j in range(4): for i in range(4): print(&quot;+&quot;,end='') if i==3: break for i in range(7): print(&quot;-&quot;,end='') if j==3: break print() for d in range (3): for r in range(4): print(&quot;|&quot;,end='') if r==3: break for i in range(7): if d==1 and i==3: print(board[j][r],end='') else: print(&quot; &quot;,end='') print() print() # # the function accepts one parameter containing the board's current status # and prints it out to the console # def EnterMove(board): entredMove=int((input(&quot;Enter your move: &quot;))) while not any(entredMove in i for i in board): print (&quot;this value is wrong&quot;) entredMove=int((input(&quot;Enter your move: &quot;))) for i in range(3): for j in range(3): if int(entredMove)==board[i][j]: board[i][j]= 'O' # # the function accepts the board current status, asks the user about their move, # checks the input and updates the board according to the user's decision # def MakeListOfFreeFields(board): freeFields=[] s=0 global result for i in range(3): for j in range(3): if type(board[i][j])== int: freeFields.append((i,j)) s+=1 if s==0 and result==False: result = True print (&quot;it is a DRAW&quot;) # the function browses the board and builds a list of all the free squares; # the list consists of tuples, while each tuple is a pair of row and column numbers # and test if list is empty that means it is a draw def VictoryFor(board, sign): global result xxx=0 xxxx=0 for i in range(3): x=0 for j in range(3): if board[i][j]==sign: x+=1 if x==3: print(sign,' is won the game') result=True if result == True: break xx=0 for j in range(3): if board[j][i]==sign: xx+=1 if xx==3: print(sign,' is won the game') result=True if result == True: break for j in range(3): if i==j and board[i][j]==sign: xxx+=1 if xxx==3: print(sign,' is won the game') result=True if result ==True: break for j in range(3): if i+j==2 and board[i][j]==sign: xxxx+=1 if xxxx==3: print(sign,' is won the game') result=True if result ==True: break # # the function analyzes the board status in order to check if # the player using 'O's or 'X's has won the game # def DrawMove(board): entredMove=randrange(8)+1 while not any(entredMove in i for i in board): entredMove=randrange(9)+1 for i in range(3): for j in range(3): if int(entredMove)==board[i][j]: print('computer move in ',entredMove) board[i][j]= 'X' # # the function draws the computer's move and updates the board # DisplayBoard(board) while result == False: EnterMove(board) DisplayBoard(board) VictoryFor(board, 'O') if result == False: DrawMove(board) VictoryFor(board, 'X') DisplayBoard(board) MakeListOfFreeFields(board) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:41:42.587", "Id": "482337", "Score": "4", "body": "Great first question!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:52:28.363", "Id": "482338", "Score": "1", "body": "i need to know are there any method to make the same result with less instructions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T05:18:58.030", "Id": "482346", "Score": "2", "body": "(There is an abundance of things to go first, including *readability*, *test*, and *maintainability*.) (`less instructions` (code with few tokens) doesn't make *my* list.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T11:42:47.360", "Id": "482374", "Score": "1", "body": "the biggest change to reduce complexity is in the win_conditions to make a List of all possible triple coordinates, and then simply go through that in a for each and check if the values on those coordinates are all the same." } ]
[ { "body": "<p>Welcome to the community. Here are few pointers from first look at the code:</p>\n<ol>\n<li><p>The code does not follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8 style guide</a>. You should follow the <code>snake_case</code> naming convention for variables and functions; classes follow the <code>CamelCase</code> naming.</p>\n</li>\n<li><p>Instead of the code running as is, the execution condition should be placed inside an <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__</code></a> block.</p>\n</li>\n<li><p>For comparing <code>True</code>, <code>False</code>, <code>None</code>; instead of <code>==</code> the <code>is</code> comparison check is preferred. So, instead of <code>result == False</code>, it would be <code>result is False</code> or just <code>not result</code>.</p>\n</li>\n<li><p>If using python 3.6+, you can also provide type hinting.</p>\n</li>\n<li><p>Instead of comments around the function definitions, <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">use docstrings</a>.</p>\n</li>\n<li><p>The following print statement(s) have a redundant loop (unnecessary CPU instructions):</p>\n<pre><code> for i in range(7):\n print(&quot;-&quot;,end='')\n</code></pre>\n<p>and can simply be:</p>\n<pre><code> print(&quot;-&quot; * 7)\n</code></pre>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T05:29:03.557", "Id": "482349", "Score": "1", "body": "You could use `DisplayBoard()` to *show* docstring use and simplified control & printing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:01:42.490", "Id": "482383", "Score": "0", "body": "You'd still need the `end=''` when using `\"-\" * 7` ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:17:31.667", "Id": "482412", "Score": "1", "body": "Note that `not result` returns True iff `result` is [Falsy](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false), so is inequivalent to `result==False` & `result is False`. For example, `print(0 is False, 0 is True, not 0, 3 is False, 3 is True, not 3)` prints `False False True False False False`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T10:56:16.910", "Id": "482588", "Score": "0", "body": "thanks a lot because i think now i know what must do with my code,\nsorry for my level in english is too bad" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T03:14:27.870", "Id": "245592", "ParentId": "245591", "Score": "10" } }, { "body": "<p>Welcome to the community, my first post was also a tictactoe, <a href=\"https://codereview.stackexchange.com/questions/245574/improving-my-tic-tac-toe-solution-in-scala\">allthough in a functional Style in Scala.</a></p>\n<p>So first some general rules / suggestions, then later I will go into the details.\nIf I am wrong on anything then please feel free to correct me.\nI am more experienced in Java and allthough I have done some projects in Python I still might be ignorant about how things are different.</p>\n<ol>\n<li>Code should be readable from top to bottom</li>\n<li>Try to indent as little as possible. (There are often more than 5 indentations)</li>\n<li>Snake Case in Python so MakeListOfFreeFiels = make_list_of_free_fields</li>\n<li>Use meaningful Variable names. (Your loops are hard to read i,j,r,s etc)</li>\n<li>Use comments only when needed. Your names should be expressive enough</li>\n</ol>\n<p>So first I would make play_game() function, so you have a clean interface to start your game. You just put everything you have in the bottom in it, and place it at the top, so it's more readable.</p>\n<p><strong>Ok on the VictoryFor() function:</strong></p>\n<p>The general pattern is pretty interesting.\nI wouldn't have thought about the way you solved it kind of algorhitmically.</p>\n<p>Personally I solved this by defining a set of sets of all win patterns, then check if the values in those indexes are all the same. I used a flat array, you used a map, so if you want to try implementing it you need to change that. (Copied from scala but the idea is the same).</p>\n<pre><code> val patterns: Set[Set[Int]] = Set(\n Set(0, 1, 2),\n Set(3, 4, 5),\n Set(6, 7, 8),\n Set(0, 3, 6),\n Set(1, 4, 7),\n Set(2, 5, 8),\n Set(0, 4, 8),\n Set(2, 4, 6)\n )\n</code></pre>\n<p>Now back to your implementation and some suggestions.\nYou can represent the string in a different format. Just some syntactic sugar.</p>\n<pre><code>print(sign,' is won the game')\n#changed to\nprint(f'{sign} has won the game')\n</code></pre>\n<p>To make your intent more clear you could split the loops up in separate functions.\ndef check_hor_winner, def check_vert_winner, def check_diag_winner</p>\n<p>Also I would rename sign to player.</p>\n<p>If you changed victoryFor, so that it returns true or false, then you can remove those result = True and breaks, and just return True.</p>\n<p>Here is the final changed VictoryFor function in your algorhitmic Style.\nEspecially in the diagonal functions I would have probably just put in the hardcoded patterns but if you would make a 100x100 ticTacToe then it would make sense.</p>\n<pre><code>def has_won(board, player):\n if (\n has_won_vertically(board, player) or \n has_won_horizontally(board, player) or \n has_won_diagonal_1(board, player) or \n has_won_diagonal_2(board, player)):\n return True\n return False\n\n\ndef has_won_vertically(board, player):\n for row in range(3):\n player_count = 0\n for column in range(3):\n if board[row][column] == player:\n player_count += 1\n if player_count == 3:\n return True\n return False\n\ndef has_won_horizontally(board, player):\n for column in range(3):\n player_count = 0\n for row in range(3):\n if board[row][column] == player:\n player_count += 1\n if player_count == 3:\n return True\n return False\n\ndef has_won_diagonal_1(board, player):\n player_count = 0\n for row in range(3):\n for column in range(3):\n if row == column and board[row][column] != player:\n return False\n return True\n\ndef has_won_diagonal_2(board, player):\n player_count = 0\n for row in range(3):\n for column in range(3):\n if row+column == 2 and board[row][column] != player:\n return False\n return True\n</code></pre>\n<p><strong>Next up your MakeListOfFreeFields</strong>\nThe function Name does not represent what it is doing.\nMaking a List of the free fields is just an implementation Detail.\nWhat it actually is doing is checking if it is a draw.\nTo reflect that let's rename it to is_draw, and while we're at it let's also remove the global variable result and make is_draw return True or false.</p>\n<p>DrawMove and EnterMove can also be renamed to enter_move_player() and enter_move_computer. I'm still not satisfied completely with the names but it's more clear.</p>\n<p>Here is the final result I made.\nThere are still a lot of improovements possible but my time is running out.\nI'm open to any criticism</p>\n<pre><code>from random import randrange\nboard=[[1,2,3],[4,'X',6],[7,8,9]]\n#\n#board initialization always first move of computer is in the middle\n\ndef play_game():\n display_board(board)\n won = False\n draw = False\n while won == False and draw == False:\n enter_move_player(board)\n display_board(board)\n won = has_won(board, 'O')\n if won == False:\n enter_move_computer(board)\n won = has_won(board, 'X')\n display_board(board)\n draw = is_draw(board)\n\ndef display_board(board):\n for j in range(4):\n for i in range(4):\n print(&quot;+&quot;,end='')\n if i==3:\n break\n for i in range(7):\n print(&quot;-&quot;,end='')\n if j==3:\n break\n print()\n for d in range (3):\n for r in range(4):\n print(&quot;|&quot;,end='')\n if r==3:\n break\n for i in range(7):\n if d==1 and i==3:\n print(board[j][r],end='')\n else:\n print(&quot; &quot;,end='')\n print()\n print()\n\n\ndef enter_move_player(board):\n enteredMove=int((input(&quot;Enter your move: &quot;)))\n while not any(enteredMove in i for i in board):\n print (&quot;this value is wrong&quot;)\n enteredMove=int((input(&quot;Enter your move: &quot;)))\n for i in range(3):\n for j in range(3):\n if int(enteredMove)==board[i][j]:\n board[i][j]= 'O'\n\n\ndef is_draw(board):\n freeFields=[]\n s=0\n for i in range(3):\n for j in range(3):\n if type(board[i][j])== int:\n freeFields.append((i,j))\n s+=1\n if s==0 and result==False:\n print (&quot;it is a DRAW&quot;) \n return True\n return False\n \n\ndef has_won(board, player):\n if (\n has_won_vertically(board, player) or \n has_won_horizontally(board, player) or \n has_won_diagonal_1(board, player) or \n has_won_diagonal_2(board, player)):\n return True\n return False\n\n\ndef has_won_vertically(board, player):\n for row in range(3):\n player_count = 0\n for column in range(3):\n if board[row][column] == player:\n player_count += 1\n if player_count == 3:\n return True\n return False\n\ndef has_won_horizontally(board, player):\n for column in range(3):\n player_count = 0\n for row in range(3):\n if board[row][column] == player:\n player_count += 1\n if player_count == 3:\n return True\n return False\n\ndef has_won_diagonal_1(board, player):\n player_count = 0\n for row in range(3):\n for column in range(3):\n if row == column and board[row][column] != player:\n return False\n return True\n\ndef has_won_diagonal_2(board, player):\n player_count = 0\n for row in range(3):\n for column in range(3):\n if row+column == 2 and board[row][column] != player:\n return False\n return True\n\ndef enter_move_computer(board):\n enteredMove = randrange(8)+1\n while not any(enteredMove in i for i in board):\n enteredMove=randrange(9)+1\n for i in range(3):\n for j in range(3):\n if int(enteredMove)==board[i][j]:\n print('computer move in ',enteredMove)\n board[i][j]= 'X'\n\n\nplay_game()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T10:43:32.307", "Id": "245612", "ParentId": "245591", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T02:41:14.830", "Id": "245591", "Score": "11", "Tags": [ "python" ], "Title": "My first project in Python: Tic Tac Toe" }
245591
<p>I have a <code>.tgz</code> file that I need to download given a url inside a <code>Testing</code> folder and then decompress it. I am able to download the <code>.tgz</code> file successfully from the url and also able to successfully decompress it without any issues. My <code>.tgz</code> file will be approx <code>100 MB</code> max. I am using <code>SharpZipLib</code> library here to decompress.</p> <p>There are two parts to this:</p> <ul> <li>Download <code>.tgz </code>file from a url in a particular folder.</li> <li>If file is downloaded successfully then only decompress <code>.tgz</code> file in that same folder othewise not.</li> </ul> <p>Below is my code:</p> <pre><code>private void DownloadTGZFile(string url, string fileToDownload) { using (var client = new WebClient()) { client.DownloadFile(url + fileToDownload, &quot;Testing/configs.tgz&quot;); } Stream inStream = File.OpenRead(&quot;Testing/configs.tgz&quot;); Stream gzipStream = new GZipInputStream(inStream); TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream); tarArchive.ExtractContents(&quot;Testing/&quot;); tarArchive.Close(); gzipStream.Close(); inStream.Close(); } </code></pre> <p><strong>Question:</strong></p> <p>I wanted to check on below things:</p> <ul> <li>Is using <code>WebClient</code> efficient here? If not, then what can I use to download the file efficiently for me considering file size is 100 MB max?</li> <li>Also can I add a timeout here so that if I am not able to download the file in that time period, then it just times out. But it should retry for 3 times (or with some retry policy) and skip it if not able to by logging an error for the last try.</li> <li>And if it is able to download the .tgz file successfully then decompress it in the same folder.</li> </ul> <p>I am a newbie who started working with C# so still confuse on usage of <code>WebClient</code> and not sure if it is the right way to do it also. And this will be a production code so wanted to see what's the best way to re-write this whole code if there is any.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:27:11.440", "Id": "482351", "Score": "1", "body": "Have you considered to use `HttpClient` instead of `WebClient`? (Or `RestSharp` or `Flurl`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:37:14.673", "Id": "482392", "Score": "1", "body": "I am ok using `HttpClient` instead of `WebClient`. Can you provide an example on how my code should be with that and also any improvements considering it's a production code? @PeterCsala" } ]
[ { "body": "<p><code>DownloadTGZFile</code> does two things, which is one thing too many.</p>\n<ul>\n<li>It does what it name says it does (download a .TGZ file),</li>\n<li>but it also unpacks the TGZ file, and that is not in the method's name.</li>\n</ul>\n<p>Unpacking the file should be a different method. You should then have a new method that calls both methods.</p>\n<hr />\n<p>Also, please follow <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"nofollow noreferrer\">the Microsoft guidelines</a>:</p>\n<blockquote>\n<p>The PascalCasing convention, used for all identifiers except parameter\nnames, <strong>capitalizes the first character of each word (including\nacronyms over two letters in length)</strong>, as shown in the following\nexamples:</p>\n<p><code>PropertyDescriptor HtmlTag</code></p>\n<p>A special case is made for two-letter acronyms in which both letters\nare capitalized, as shown in the following identifier:</p>\n<p><code>IOStream</code></p>\n</blockquote>\n<p>Thus the method name should be <code>DownloadTgzFile</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:29:22.377", "Id": "482389", "Score": "0", "body": "Thanks for your suggestion. Can you provide an example on how my code should look like considering it is a production code. It will help me understand better also." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:40:44.350", "Id": "245603", "ParentId": "245595", "Score": "2" } }, { "body": "<p>I would personally not write the archive to disk unless it's extremely huge (we're talking gigabytes here, and not &quot;it might be gigabytes&quot;, but <strong>is</strong> gigabytes).</p>\n<p>Open a stream to the download response content and pass it to your gzip/tar decompressor streams, and then extract the files as they come.</p>\n<p>And of course, use better names, that function should be called <code>ExtractTgzFile</code> and take an <code>Uri</code> parameter to download (if you use the modern CodeAnalysis package, you'll get a warning for this specifically).</p>\n<p>And after that's done, you should rewrite it as an <code>async</code> function, because right now you're wasting time on your caller thread waiting for a file to download, which is unacceptable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:21:00.057", "Id": "482422", "Score": "0", "body": "My archive file will be 100 MB max. Do you think you can provide an example on how to do this right way? It will help me understand better as I am pretty new in C#." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:30:26.047", "Id": "482423", "Score": "0", "body": "You just `await` a `HttpClient.GetAsync` call, then call the `Content` property to get the `HttpContent` instance, then `await` `ReadAsStreamAsync` on it to get the stream. Once you have your stream, the rest of the code is the same as what you wrote, pass it to your gzip & tgz stream readers and extract." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:25:14.767", "Id": "482429", "Score": "0", "body": "Do you think you can provide an example on how to do this? I am still confuse on how to use HttpClient here. Any help will be appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:30:21.610", "Id": "482430", "Score": "0", "body": "What's confusing? What did you write and what doesn't work?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:52:02.577", "Id": "245626", "ParentId": "245595", "Score": "1" } } ]
{ "AcceptedAnswerId": "245603", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T04:23:40.230", "Id": "245595", "Score": "2", "Tags": [ "c#" ], "Title": "How to download tgz file from a url and decompress it efficiently?" }
245595
<p>I just finished my first project in Javascript. It takes an array of locations (with coordinates on position 6 and 7) as Input, then the first location is checked against all other locations. After that it takes the closest neighbor and adds it to the route. Then it takes the coordinates of the neighbor which it just found and does same for it (excluding locations that already have a connection). In the end it returns to the starting point. Please give me some hints how i can write better, cleaner and more readable code. Any feedback is appreciated.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var listCoordinates = [ [1, "München", "Robert-Bürkle-Straße", "1", 85737, "Ismaning", 48.229035, 11.686153, 524, 854], [2, "Berlin", "Wittestraße", "30", 13509, "Berlin", 52.580911, 13.293884, 648, 302], [3, "Braunschweig", "Mittelweg", "7", 38106, "Braunschweig", 52.278748, 10.524797, 434, 341], [4, "Bretten", "Edisonstraße", "2", 75015, "Bretten", 49.032767, 8.698372, 276, 747], [5, "Chemnitz", "Zwickauer Straße", "16a", 9122, "Chemnitz", 50.829383, 12.914737, 622, 525], [6, "Düsseldorf", "Gladbecker Straße", "3", 40472, "Düsseldorf", 51.274774, 6.794912, 138, 455] ]; //Haversine formula: calulate distance between two locations const haversineDistance = ([lat1, lon1], [lat2, lon2], isMiles = false) =&gt; { const toRadian = angle =&gt; (Math.PI / 180) * angle; const distance = (a, b) =&gt; (Math.PI / 180) * (a - b); const RADIUS_OF_EARTH_IN_KM = 6371; const dLat = distance(lat2, lat1); const dLon = distance(lon2, lon1); lat1 = toRadian(lat1); lat2 = toRadian(lat2); //Haversine Formula const a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2); const c = 2 * Math.asin(Math.sqrt(a)); let finalDistance = RADIUS_OF_EARTH_IN_KM * c; if (isMiles) { finalDistance /= 1.60934; } return finalDistance; }; //heuristic strict nearest neighbor (points that already have a connection do not get calculated) function nearestNeighbor(coordinates) { var route = { msg: '', distance: 0, route: [0] } var currentPoint = 0; for (var i = 0; i &lt;= coordinates.length - 2; i++) { var nearestNeighbor = { key: 0, distance: 0 } var pointaLat = coordinates[currentPoint][6], pointaLon = coordinates[currentPoint][7]; for (var j = 0; j &lt;= coordinates.length - 1; j++) { if (j != currentPoint) { if (!route.route.includes(j)) { var pointbLat = coordinates[j][6], pointbLon = coordinates[j][7]; var currentDistance = haversineDistance([pointaLat, pointaLon], [pointbLat, pointbLon], 0); if (nearestNeighbor.distance === 0 || nearestNeighbor.distance &gt; currentDistance) { nearestNeighbor.key = j; nearestNeighbor.distance = currentDistance; } } } } route.distance += nearestNeighbor.distance; route.route.push(nearestNeighbor.key) currentPoint = nearestNeighbor.key; } //return to start point var pointaLat = coordinates[0][6], pointaLon = coordinates[0][7], pointbLat = coordinates[route.route[route.route.length - 1]][6], pointbLon = coordinates[route.route[route.route.length - 1]][7]; route.distance += haversineDistance([pointaLat, pointaLon], [pointbLat, pointbLon], 0); route.route.push(0); route.distance = Math.round((route.distance + Number.EPSILON) * 100) / 100; route.msg = "Die kürzeste Strecke beträgt " + route.distance + " km"; return route; } console.log(nearestNeighbor(listCoordinates));</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:57:17.427", "Id": "482362", "Score": "1", "body": "Welcome to code review. Actually really nice to see js that's readable. <3" } ]
[ { "body": "<p>Are you hoping for the arc length around a sphere or the Earth? What about going through the earth in a straight line? Currently your math solves the sphere but not Earth.</p>\n<p>The earth has 2 radi that are used to solve the arc length.</p>\n<pre><code>R = √ [ (r1² * cos(B))² + (r2² * sin(B))² ] / [ (r1 * cos(B))² + (r2 * sin(B))² ]\nB = Latitude\nR = Radius\nr1 = radius at equator\nr2 = radius at the poles\n</code></pre>\n<p>But your Haversine method is otherwise correct =D</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T11:23:56.023", "Id": "482373", "Score": "1", "body": "Isen't the earth a sphere? Thanks for your nice words :) I will try out what you gave me. What do you think of the nearestNeighbor function? It is not to messy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:52:23.597", "Id": "482415", "Score": "0", "body": "@Herbo The earth is a spheroid. Think of a cartoon with a ball spinning really fast, how it becomes fattened -- that's what is happening with the earth because of physics. Nothing about your function is messy. Internal variables that are used for house keeping (especially lengthy math operations) and increase readability don't require descriptive variable names unless it's obvious what it should probably be named (exactly how you did it with dLat and dLon)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:02:52.673", "Id": "482417", "Score": "0", "body": "Worth pointing out that Henrik Hansen has a point about the efficiency your program -- I didn't see it because I didn't put this in an editor. If you've calculated the distance from A to B, you don't have to calculate it again from B to A." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:56:29.727", "Id": "245604", "ParentId": "245599", "Score": "3" } }, { "body": "<p>Below, I have tried to refactor your code with some inline comments about what and why, I have done it. The overall design and workflow is preserved, so it's in the detail, I have tried to improve and optimize:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var locations = [\n {id: 1, region: \"Ismaning/München (Hauptsitz)\", street: \"Robert-Bürkle-Straße\", streetnumber: \"1\", postcode: 85737, city: \"Ismaning\", latitude: 48.229035, longitude: 11.686153, xaxis: 524, yaxis: 854},\n {id: 2, region: \"Berlin\", street: \"Wittestraße\", streetnumber: \"30\", postcode: 13509, city: \"Berlin\", latitude: 52.580911, longitude: 13.293884, xaxis: 648, yaxis: 302},\n {id: 3, region: \"Braunschweig\", street: \"Mittelweg\", streetnumber: \"7\", postcode: 38106, city: \"Braunschweig\", latitude: 52.278748, longitude: 10.524797, xaxis: 434, yaxis: 341},\n {id: 4, region: \"Bretten\", street: \"Edisonstraße\", streetnumber: \"2\", postcode: 75015, city: \"Bretten\", latitude: 49.032767, longitude: 8.698372, xaxis: 276, yaxis: 747},\n {id: 5, region: \"Chemnitz\", street: \"Zwickauer Straße\", streetnumber: \"16a\", postcode: 9122, city: \"Chemnitz\", latitude: 50.829383, longitude: 12.914737, xaxis: 622, yaxis: 525}\n];\n\n// HH: I have moved these functions outside of haversineDistance\n// in order to keep that function more clear\nconst RADIUS_OF_EARTH_IN_KM = 6371;\nfunction toRadian(angle) { return Math.PI / 180.0 * angle; }\nfunction distance(a, b) { return (Math.PI / 180) * (a - b); }\n\n//Haversine formula: calulate distance between two locations\n// HH: This function now takes two point objects as argument\n// instead of two arrays/tuples (see also below)\nfunction haversineDistance(ptA, ptB, isMiles = false) {\n const dLat = distance(ptB.lat, ptA.lat);\n const dLon = distance(ptB.lng, ptA.lng);\n const lat1 = toRadian(ptA.lat);\n const lat2 = toRadian(ptB.lat);\n\n //Haversine Formula\n const a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);\n const c = 2 * Math.asin(Math.sqrt(a));\n\n let finalDistance = RADIUS_OF_EARTH_IN_KM * c;\n if (isMiles) {\n finalDistance /= 1.60934;\n }\n return finalDistance;\n};\n\n// HH: Name the function after what it does - not after how it does it.\nfunction findShortestPath(coordinates) {\n var route = {\n msg: '',\n distance: 0,\n route: [0]\n }\n\n // HH: Instead of having pairs of lat, lon an object representing a location/point/position is more readable\n function getPoint(index) {\n return {\n lat: coordinates[index].latitude,\n lng: coordinates[index].longitude\n };\n }\n\n\n\n var currentPoint = 0;\n // HH: You iterate over and over again a lot of indices that has already been handled.\n // Instead it would be more efficient to maintain a set of remaining indices\n let indices = Array.from({ length: coordinates.length - 1 }, (_, i) =&gt; i + 1); // we don't want 0 included as it is the first currentPoint\n\n while (indices.length &gt; 0) {\n var nearestNeighbor = {\n key: 0,\n distance: 0\n };\n\n let ptA = getPoint(currentPoint);\n for (let j of indices) {\n let ptB = getPoint(j);\n // HH: Because indices only contains not handled indices, you can omit guarding against current point and points in the route\n var currentDistance = haversineDistance(ptA, ptB, 0);\n if (nearestNeighbor.distance === 0 || nearestNeighbor.distance &gt; currentDistance) {\n nearestNeighbor.key = j;\n nearestNeighbor.distance = currentDistance;\n }\n }\n route.distance += nearestNeighbor.distance;\n route.route.push(nearestNeighbor.key);\n // HH: The nearest neighbor is removed from indices\n indices.splice(indices.indexOf(nearestNeighbor.key), 1);\n currentPoint = nearestNeighbor.key;\n }\n\n //return to start point\n ptA = getPoint(0);\n let ptB = getPoint(route.route[route.route.length - 1]);\n route.distance += haversineDistance(ptA, ptB, 0);\n\n route.route.push(0);\n route.distance = Math.round((route.distance + Number.EPSILON) * 100) / 100;\n route.msg = \"Die kürzeste Strecke beträgt \" + route.distance + \" km\";\n return route;\n}\n\nconsole.log(findShortestPath(locations));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:55:18.153", "Id": "482416", "Score": "0", "body": "Personally, I think the distance thing should be kept outside the the namespace because this distance is calculated differently than most other distances." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:03:43.417", "Id": "482418", "Score": "1", "body": "@DavidFisher: You maybe right, - I thought like you about it - maybe \"distance\" isn't just the right name - it's more like a difference in radians per degree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:10:01.867", "Id": "482419", "Score": "1", "body": "arcLength(degreeA, degreeB) but is still missing the radius?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:00:12.727", "Id": "482446", "Score": "0", "body": "the idea of making objects need to follow through and make a \"complete\" object from each entire array. Do this up front the there are no more \"disconnected\" data and obscure references anywhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T04:19:05.507", "Id": "482478", "Score": "0", "body": "@radarbob: Yeah, you're right, I thought of making a proper `class Location { lat, lng }` object, but your `places` does the trick at the same time as holding all the other information - that's even better. I didn't think that far." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:33:17.400", "Id": "482485", "Score": "1", "body": "thanks alot that helped me so much, i knew that it was stupid to check a to b and b to a but i couldnt get my head around it. Now I just need to refactor all my other functions (i also made a heaps permutation algorithm and a mix of nearestNeighbor, clustering, heaps permutation and cartesian product). Once i am done i might show it here again. I also switched to an array of objects so it's more clear what is what." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T10:11:54.490", "Id": "482490", "Score": "0", "body": "i did most of the changes to the other functions but it is so much slower now. around 8 seconds to calculate everything and befor it was 0.6 seconds. should i change my initial post and put there everything before changes and after changes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T11:19:11.340", "Id": "482493", "Score": "0", "body": "i benchmarked it and it turns out that your version of the haversineDistance function is round about 19 times slower than my version. how could that be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T16:29:47.420", "Id": "482518", "Score": "1", "body": "@Herbo: You're right, it's rather slow. I've tested a little, and it seems to be the `getPoint()` function, that is the bottleneck. I've updated my solution with a new version, that's much faster. But with the object approach we can omit the `getPoint()`thing and work directly on the location objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T17:23:43.753", "Id": "482521", "Score": "1", "body": "thanks i will try it out. As i said i have a mix of nearest neighbor, clustering, heaps permutation and cartesian product which gives me 57600 possible routes to check and i had to wait around 11 second instead of 0.6 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T17:36:06.790", "Id": "482522", "Score": "1", "body": "I externalized the getPoint function so i can reuse it in my other functions and i also pass the the locations (or centroids in the case of my clusters)array to it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-06T04:02:33.977", "Id": "487891", "Score": "0", "body": "*should i change my initial post and put there everything before changes and after changes?* Never change the original post code. It can make existing answers and comments useless and confusing." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:23:01.390", "Id": "245624", "ParentId": "245599", "Score": "1" } }, { "body": "<blockquote>\n<p>Please give me some hints how i can write better, cleaner and more readable code</p>\n</blockquote>\n<p>.</p>\n<p><strong>Objects: anything else is merely arranging the deck chairs on the Titanic</strong></p>\n<pre><code>var listCoordinates = [\n [1, &quot;München&quot;, &quot;Robert-Bürkle-Straße&quot;, &quot;1&quot;, 85737, &quot;Ismaning&quot;, 48.229035, 11.686153, 524, 854],\n [2, &quot;Berlin&quot;, &quot;Wittestraße&quot;, &quot;30&quot;, 13509, &quot;Berlin&quot;, 52.580911, 13.293884, 648, 302],\n [3, &quot;Braunschweig&quot;, &quot;Mittelweg&quot;, &quot;7&quot;, 38106, &quot;Braunschweig&quot;, 52.278748, 10.524797, 434, 341],\n [4, &quot;Bretten&quot;, &quot;Edisonstraße&quot;, &quot;2&quot;, 75015, &quot;Bretten&quot;, 49.032767, 8.698372, 276, 747],\n [5, &quot;Chemnitz&quot;, &quot;Zwickauer Straße&quot;, &quot;16a&quot;, 9122, &quot;Chemnitz&quot;, 50.829383, 12.914737, 622, 525],\n [6, &quot;Düsseldorf&quot;, &quot;Gladbecker Straße&quot;, &quot;3&quot;, 40472, &quot;Düsseldorf&quot;, 51.274774, 6.794912, 138, 455]\n];\n\n\n// if I'm making lots of mistakes identifying the array elements, \n// its because the reader starts off not knowing that the heck the\n// this array data is, then it's ripped apart several times, named and\n// then renamed. \n// I cannot tell without very careful study and tracing what the heck\n// is going on.\n\nvar places = []; \nlistCoordinates.forEach(place =&gt; {\n places.push(\n { order : place[0],\n city : place[1],\n street : place[2],\n doNotKnow : place[3],\n whatIsThis : place[4],\n nearestNeighbor : place[5],\n latitude : place[6],\n longatude : place[7],\n something : place[8],\n somethingElse : place[9]\n }\n ) );\n\n\n//heuristic strict nearest neighbor (points that already have a connection do not get calculated)\n\n// pass in a place object and use its properties. \n// I'm not going to rewrite this because I cannot tell how/where all these independent\n// variables match to the place object.\n// The stark contrast after *you* rewrite using coherent, understandable objects will be a huge &quot;a-ha&quot; moment\n// in your understanding of readability, understandability,\n// and the potential of object oriented coding in general.\n</code></pre>\n<p>P.S. write <code>toString</code> methods for objects that output the properties - great for debugging.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:29:59.947", "Id": "482484", "Score": "0", "body": "i changed the array of arrays to an array of objects (your code ha some problems but my data is beeing fetched from a server with an php script i just changed it there) and i combind it with Henrik Hansens version of the code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:49:45.697", "Id": "245645", "ParentId": "245599", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T06:20:57.973", "Id": "245599", "Score": "6", "Tags": [ "javascript", "beginner" ], "Title": "First project in Javascript: NearestNeighbor Calculator" }
245599
<p>I wrote a linked list class and don't know how to optimize it, please suggest some ideas for optimizing and fixing possible memory leaks.</p> <pre><code>#define indexTooLarge -1 template &lt;typename T&gt; class LincedList { public: LincedList(){} template&lt;typename... Types&gt; LincedList(T value,Types... values) : LincedList(values...) { push_front(value); } LincedList(T value) { push_front(value); } ~LincedList() { clear(); } void push_back(T value_a) { if(tail == nullptr) { tail = new Node(nullptr,value_a); head = tail; m_size++; return; } tail-&gt;next = new Node(nullptr,value_a); tail = tail-&gt;next; m_size++; } void push_front(T value_a) { if(head == nullptr) { head = new Node(nullptr,value_a); tail = head; m_size++; return; } head = new Node(head,value_a); m_size++; } void clear() { Node *buffer; for(int i = 0;i&lt;m_size;i++) { buffer = head; head = head-&gt;next; delete buffer; } m_size = 0; } void remove(unsigned int index) { if(index &gt;= m_size) throw indexTooLarge; Node *currectNode = head; for(int i = 0; i &lt; index-1;i++) currectNode = currectNode-&gt;next; Node* buffer = currectNode-&gt;next; currectNode-&gt;next = currectNode-&gt;next-&gt;next; delete buffer; m_size--; } void remove(unsigned int index,unsigned int lenght) { if(index+lenght &gt;= m_size) throw indexTooLarge; Node *currectNode = head; for(int i = 0; i &lt; index-1; i++) currectNode = currectNode-&gt;next; Node* buffer = currectNode; currectNode = currectNode-&gt;next; for(int i = 0; i &lt; lenght; i++ ) { Node* buffer2 = currectNode; currectNode = currectNode-&gt;next; delete buffer2; } buffer-&gt;next = currectNode; m_size -= lenght; } T&amp; operator[](unsigned const int &amp;index) { if(index &gt;= m_size) throw indexTooLarge; if(index == m_size-1) return tail-&gt;value; Node *currectNode = head; for(unsigned int i = 0; i &lt; index;i++) currectNode = currectNode-&gt;next; return currectNode-&gt;value; } void operator=(const LincedList &amp;C1) { head-&gt;value = C1.head-&gt;value; Node *currectNode = new Node(nullptr,C1[1]); Node *C1CurrectNode = C1[1]; head-&gt;next = currectNode; for(int i = 2; i &lt; m_size; i++) { C1CurrectNode = C1CurrectNode-&gt;next; currectNode-&gt;next = new Node(nullptr,C1CurrectNode-&gt;value); currectNode = currectNode-&gt;next; } tail-&gt;value = C1.tail-&gt;value; } unsigned int size() { return m_size; } private: struct Node { Node* next; T value; Node(Node* next_a, T value_a) : next(next_a) , value(value_a) {} }; unsigned int m_size = 0; Node* head = nullptr; Node* tail = nullptr; }; #include &lt;iostream&gt; int main() { LincedList&lt;int&gt; ll(0,1,2,3); std::cout &lt;&lt; ll[1] &lt;&lt; std::endl; //writes to console 1 ll.remove(1); //removes the element at index 1 std::cout &lt;&lt; ll[1] &lt;&lt; std::endl; //writes to console 2 ll.push_back(4);//adds to the end 4 ll.push_front(5);//adds 5 to the beginning std::cout &lt;&lt; ll.size() &lt;&lt; std::endl; //writes to console 5 ll.remove(1,2); //remove all 2 to 3 elements std::cout &lt;&lt; ll[1] &lt;&lt; std::endl ; //writes to console 3 return 0; } </code></pre>
[]
[ { "body": "<h2>Spelling</h2>\n<ul>\n<li><code>LincedList</code> -&gt; <code>LinkedList</code>;</li>\n<li><code>currectNode </code> -&gt; <code>currentNode</code>;</li>\n<li><code>lenght</code> -&gt; <code>length</code>.</li>\n</ul>\n<h2>Factor out iteration</h2>\n<p>Make a private utility method to do this:</p>\n<pre><code> for(unsigned int i = 0; i &lt; index;i++)\n currectNode = currectNode-&gt;next;\n return currectNode;\n</code></pre>\n<p>given the number of times you do it.</p>\n<h2>Const methods</h2>\n<pre><code>unsigned int size()\n</code></pre>\n<p>should be</p>\n<pre><code>unsigned int size() const\n</code></pre>\n<p>and you should offer a similar <code>const</code> wrapper to your <code>operator[]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:54:35.193", "Id": "245621", "ParentId": "245602", "Score": "7" } }, { "body": "<p>In addition to what Reinderien posted:</p>\n<h1>Look at <code>std::forward_list</code></h1>\n<p>Your linked list is a single-linked list, the closes equivalent in the standard library is <a href=\"https://en.cppreference.com/w/cpp/container/forward_list\" rel=\"noreferrer\"><code>std::forward_list</code></a>. You will notice from the documentation of <code>std::forward_list</code> that it doesn't implement a <code>push_back()</code>, and its <code>erase()</code> function only takes iterators, not indices. All this is to keep this data structure light and focused only on the properties that a single-linked list has: inserting and removing at the head is fast, and you can iterate over it in one direction. There is no <code>operator[]</code> overload.</p>\n<p>Slower operations, like finding the node at a given index, are left to other functions such as <a href=\"https://en.cppreference.com/w/cpp/iterator/advance\" rel=\"noreferrer\"><code>std::advance()</code></a>. And this makes it clear that if you want to do something like access random elements, you are better off using a different data structure, such as a <code>std::vector</code>.</p>\n<h1>Spelling</h1>\n<p>There are some spelling errors in your code:</p>\n<ul>\n<li><code>LincedList</code> -&gt; <code>LinkedList</code></li>\n<li><code>currectNode</code> -&gt; <code>currentNode</code> (and some variants)</li>\n</ul>\n<p>Maybe English is not your native language, that's fine. There are some tools that can help you find and fix common spelling errors in source code, like <a href=\"https://github.com/codespell-project/codespell\" rel=\"noreferrer\">codespell</a>. Consider running them on your code from time to time.</p>\n<h1>Don't do bounds checking</h1>\n<p>Well, you asked how to improve performance.\nIn C++ it is normal for standard containers to not do any bounds checking. The burden of bounds checking is placed on the caller. This avoids some overhead every time your functions are called.</p>\n<p>Not throwing exceptions also allows code using your class to be compiled without exceptions enabled, which can have various benefits.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:58:04.683", "Id": "245622", "ParentId": "245602", "Score": "8" } }, { "body": "<p>You should make sure to follow the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">rule of three/five/zero</a>.</p>\n<p>In your case we have a user defined destructor, which clears the list by deleting all nodes. Problems arise now when you make a copy of a list:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>LincedList&lt;int&gt; one(1,2);\nLincedList&lt;int&gt; two(one); // a copy?\n</code></pre>\n<p>When that scope ends, <em>both</em> lists try to delete the same nodes; resulting in &quot;double free&quot; and thus undefined behavior. (<a href=\"https://ideone.com/gH9QMW\" rel=\"nofollow noreferrer\">example on ideone</a>)</p>\n<p>Therefore you should provide a user defined copy constructor and a user defined copy assignment operator with a suitable implementation. A suitable implementation could be to create copies of all nodes. A suitable implementation could also be to disallow copies of lists being made (by <a href=\"https://stackoverflow.com/q/5513881/1116364\">deleting</a> the copy constructor and copy assignment operator). If your lists can be copied, then it makes probably sense to allow list (contents) to be also <em>moved</em> from one list to the other; reducing the needs for copies. Therefore you should then also implement a user defined move constructor and a user defined move assignment operator.</p>\n<p>Or, to follow the rule of zero, you could also use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr&lt;Node&gt;</code> </a>instead of a raw pointer to the head of the node as well as <code>std::unique_ptr&lt;Node&gt;</code> instead of a raw pointers to the next nodes. Then memory would be taken care of itself (no need to write a destructor!) and copies would be disallowed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:48:47.000", "Id": "245657", "ParentId": "245602", "Score": "3" } } ]
{ "AcceptedAnswerId": "245622", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T07:40:12.310", "Id": "245602", "Score": "8", "Tags": [ "c++", "c++11", "reinventing-the-wheel" ], "Title": "Optimizing a linked list" }
245602
<p>I am trying to render in a leaflet map that should render a single marker. I am building the JavaScript as follows.</p> <ol> <li>build the map</li> <li>an even listener for when the user opens the page where the map is rendered.</li> </ol> <p>I query as follows:</p> <pre><code>@company = Company.friendly.find_by( slug: [ params[:id], params[:company_id] ]) respond_to do |format| format.html format.json { render json: { type: &quot;Feature&quot;, &quot;geometry&quot;: { &quot;type&quot;: &quot;Point&quot;, &quot;coordinates&quot;: [@company.longitude, @company.latitude] # this part is tricky }, properties: { &quot;title&quot;: @company.name, &quot;address&quot;: @company.street_address, } } } end </code></pre> <p>I console log the steps and everything seems to &quot;work&quot;. The data is loaded and <code>data.responseJSON</code> renders as follows:</p> <pre><code>geometry: {…} ​​coordinates: Array [ 1.5918642, 43.7189496 ]​​ type: &quot;Point&quot; &lt;prototype&gt;: Object { … } properties: Object { title: &quot;Acme SaS&quot;, address: &quot;xxx&quot;, &quot;marker-color&quot;: &quot;#FFFFFF&quot;, … } type: &quot;Feature&quot; </code></pre> <p>However, the map does not ​render as wanted. Only a grey box shows up. If I provide with a lat, Lon array, the map renders a map.</p> <pre><code>function buildCompanyMap() { document.getElementById('company_map').innerHTML = &quot;&lt;div id='map' style='width: 100%; height: 100%;'&gt;&lt;/div&gt;&quot;; console.log(&quot;script #1: %o&quot;, document.getElementById('company_map')); console.log(&quot;script #2: %o&quot;, document.getElementById('map')); var data = $.ajax({ url: &quot;#companies/company.json&quot;, dataType: &quot;json&quot;, success: console.log(&quot;company data successfully loaded.&quot;), error: function(xhr) { alert(xhr.statusText) } }); console.log(&quot;script #3: %o&quot;, $); console.log(&quot;script #4: %o&quot;, data); $.when(data).done(function() { var map = new L.Map('map', { dragging: false, tap: false, scrollWheelZoom: false }); var osmUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png', osmAttribution = 'Map data © &lt;a href=&quot;http://openstreetmap.org&quot;&gt;OpenStreetMap&lt;/a&gt; contributors,' + ' &lt;a href=&quot;http://creativecommons.org/licenses/by-sa/2.0/&quot;&gt;CC-BY-SA&lt;/a&gt;', osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution}); map.addLayer(osmLayer); console.log(&quot;script #5: %o&quot;, data.responseJSON); var geojsonMarkerOptions = { radius: 8, fillColor: &quot;#ff7800&quot;, color: &quot;#000&quot;, weight: 1, opacity: 1, fillOpacity: 0.8 }; L.geoJSON(data.responseJSON, { pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, geojsonMarkerOptions); } }).addTo(map); }); }; document.addEventListener(&quot;turbolinks:load&quot;, function() { if (document.getElementById('company_map') == null) { //console.log('true') } else { buildCompanyMap(); } }); </code></pre>
[]
[ { "body": "<p>A correction. I have removed the use of jQuery in the correction. The main issue was that you don't set anywhere a map center and a zoom. I've changed the behaviour by zooming the map to GeoJSON extent (e.g <code>map.fitBounds(jsonLayer.getBounds());</code>)</p>\n<p>You could also made the change by setting a map center and a zoom like described in <a href=\"https://leafletjs.com/reference-1.6.0.html#map-example\" rel=\"nofollow noreferrer\">this link to official doc</a>.</p>\n<pre class=\"lang-js prettyprint-override\"><code>function buildCompanyMap() {\n\n document.getElementById('company_map').innerHTML = &quot;&lt;div id='map' style='width: 100%; height: 100%;'&gt;&lt;/div&gt;&quot;;\n\n console.log(&quot;script #1: %o&quot;, document.getElementById('company_map'));\n console.log(&quot;script #2: %o&quot;, document.getElementById('map'));\n\n var map = new L.Map('map', {\n dragging: false,\n tap: false,\n scrollWheelZoom: false\n });\n\n var osmUrl = 'https://{s}.tile.osm.org/{z}/{x}/{y}.png',\n osmAttribution = 'Map data © &lt;a href=&quot;http://openstreetmap.org&quot;&gt;OpenStreetMap&lt;/a&gt; contributors,' +\n ' &lt;a href=&quot;http://creativecommons.org/licenses/by-sa/2.0/&quot;&gt;CC-BY-SA&lt;/a&gt;',\n osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});\n\n map.addLayer(osmLayer);\n\n console.log(&quot;script #5: %o&quot;, data.responseJSON);\n\n var geojsonMarkerOptions = {\n radius: 8,\n fillColor: &quot;#ff7800&quot;,\n color: &quot;#000&quot;,\n weight: 1,\n opacity: 1,\n fillOpacity: 0.8\n };\n\n fetch('#companies/company.json', {\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n })\n .then(response =&gt; response.json())\n .then (json =&gt; {\n var jsonLayer = L.geoJSON(json, {\n pointToLayer: function (feature, latlng) {\n return L.circleMarker(latlng, geojsonMarkerOptions);\n }\n })\n jsonLayer.addTo(map);\n map.fitBounds(jsonLayer.getBounds());\n })\n .catch(function(error) {\n console.log('Error on fetch operation: ' + error.message);\n });\n\n};\n\ndocument.addEventListener(&quot;turbolinks:load&quot;, function() {\n if (document.getElementById('company_map') == null) {\n //console.log('true')\n }\n else {\n buildCompanyMap();\n }\n});\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:46:32.297", "Id": "482366", "Score": "0", "body": "Thanks. I might have an issue with my formatting on the son response as I get: \"Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:55:28.683", "Id": "482367", "Score": "0", "body": "Copy the content of your returned GeoJSON to https://geojsonlint.com. It validates you are using GeoJSON" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T19:02:59.460", "Id": "482368", "Score": "0", "body": "well, it's valid geojson\n\nWhen I modify the map var and add a set view on dummy data, the map will render o the coordinates.\n\n var map = new L.Map('map', {\n dragging: false,\n tap: false,\n scrollWheelZoom: false\n }).setView([39.045753, -76.641273], 9);" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T19:25:21.287", "Id": "482369", "Score": "0", "body": "Yes but without the GeoJSON. It's the issue here. Made some changes in the fetch (adding headers to explicitly ask for JSON output and catch statement to help debug error)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T19:58:30.170", "Id": "482370", "Score": "0", "body": "You got it solved. Thanks a bunch. So the solution was to be be explicit by adding headers." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:00:57.053", "Id": "245606", "ParentId": "245605", "Score": "2" } } ]
{ "AcceptedAnswerId": "245606", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T17:36:55.720", "Id": "245605", "Score": "4", "Tags": [ "javascript", "ajax", "leaflet" ], "Title": "Simple marker rendering" }
245605
<p>Looks next nested if a little structure redundancy? Any better way for next nested if?</p> <pre><code># !/usr/bin/python3 num = int(input(&quot;enter number&quot;)) if num%2 == 0: if num%3 == 0: print (&quot;Divisible by 3 and 2&quot;) else: print (&quot;divisible by 2 not divisible by 3&quot;) else: if num%3 == 0: print (&quot;divisible by 3 not divisible by 2&quot;) else: print (&quot;not Divisible by 2 not divisible by 3&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:16:32.457", "Id": "482451", "Score": "1", "body": "Do you need to check one specific number, or are you checking some consecutive numbers in sequence?" } ]
[ { "body": "<p>Instead of checking for division by 2 and 3 separately twice, you can make use of the fact that:</p>\n<p><span class=\"math-container\">$$ 2 * 3 = 6$$</span></p>\n<pre><code>num = int(input(&quot;enter number&quot;))\nif num % 6 == 0:\n print(&quot;Divisible by 3 and 2&quot;)\nelif num % 3 == 0:\n print(&quot;divisible by 3 not divisible by 2&quot;)\nelif num % 2 == 0:\n print(&quot;divisible by 2 not divisible by 3&quot;)\nelse:\n print(&quot;not Divisible by 2 not divisible by 3&quot;)\n</code></pre>\n<p>python <a href=\"https://www.python.org/dev/peps/pep-0008/#id17\" rel=\"nofollow noreferrer\">pep8 suggests to use 4-whitespace</a> nesting as indentation levels.</p>\n<blockquote>\n<p>Use 4 spaces per indentation level.</p>\n</blockquote>\n<hr />\n<p>If you have more numbers to check divisibility against, keep a set of the numbers for which <code>num % x == 0</code>, and print the factors at the end.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T21:27:25.993", "Id": "482444", "Score": "0", "body": "Is it intentional that some of the print statements are indented 6 spaces in instead of 4 spaces?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T21:52:20.347", "Id": "482445", "Score": "1", "body": "@SimplyBeautifulArt my mistake. fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:00:15.707", "Id": "482447", "Score": "0", "body": "The disadvantage of this approach is its worst-case performance, if we consider modulation to be costly. If there are many \"divisible by neither 2 nor 3\" cases, then there will be many triple-modulations, whereas the approach of putting mod-2 and mod-3 results in boolean variables will only ever have worst-case two modulations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:06:55.017", "Id": "482449", "Score": "0", "body": "@Reinderien I don't think modulo operations are that costly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:08:05.033", "Id": "482450", "Score": "0", "body": "Depends on whether you're running on a microcontroller :) Also, this is a classic interview question. It's entirely possible for the interviewers to add that stipulation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:45:36.223", "Id": "482606", "Score": "0", "body": "I would say modulo operations _are_ (or, rather, can be) pretty darn costly. But one only needs to perform a single modulo operation. The result of `n % 6` will be `0` iff 6 is a factor `n`; `3` iff 3 is a factor; and either `2` or `4` iff `n` is even." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T10:06:40.840", "Id": "245609", "ParentId": "245607", "Score": "2" } } ]
{ "AcceptedAnswerId": "245609", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T09:18:46.590", "Id": "245607", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Check if number is divisible by three and two" }
245607
<p>This is my C++ implementation of a Red-Black Tree, referring the CLRS book. Half for fun, half for studying.</p> <ul> <li><p>As implementing child node, I chose <code>std::unique_ptr</code> over <code>std::shared_ptr</code> because <code>std::unique_ptr</code> is cheaper/faster and the nodes are not shared across multiple threads with indeterminate access order. Of course, this decision made the implementation extremely annoying.</p> </li> <li><p>To test it, I inserted and deleted integers from 1 to 100000 with random order. Comparing with <code>std::set</code> (which uses raw pointers), the benchmark gives:</p> </li> </ul> <pre><code>Inserting 100000 elements: unique ptr red-black tree : 40 ms standard red-black tree : 35 ms Deleting 100000 elements: unique ptr red-black tree : 49 ms standard red-black tree : 45 ms </code></pre> <p>Features could be useful but not been implemented:</p> <ul> <li>Iterators.</li> <li>Join operation.</li> </ul> <p>Any feedback will be welcomed, thanks!</p> <pre><code>#include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;utility&gt; #include &lt;numeric&gt; #include &lt;vector&gt; #include &lt;random&gt; #include &lt;set&gt; #include &lt;chrono&gt; std::mt19937 gen(std::random_device{}()); enum class Color { Red, Black }; template &lt;typename T&gt; struct Node { T key; Color color; std::unique_ptr&lt;Node&lt;T&gt;&gt; left; std::unique_ptr&lt;Node&lt;T&gt;&gt; right; Node&lt;T&gt;* parent; Node(const T&amp; key) : key {key}, color {Color::Red}, parent {nullptr} {} }; template &lt;typename T&gt; struct RBTree { public: std::unique_ptr&lt;Node&lt;T&gt;&gt; root; private: void LeftRotate(std::unique_ptr&lt;Node&lt;T&gt;&gt;&amp;&amp; x) { auto y = std::move(x-&gt;right); x-&gt;right = std::move(y-&gt;left); if (x-&gt;right) { x-&gt;right-&gt;parent = x.get(); } y-&gt;parent = x-&gt;parent; auto xp = x-&gt;parent; if (!xp) { auto px = x.release(); root = std::move(y); root-&gt;left = std::unique_ptr&lt;Node&lt;T&gt;&gt;(px); root-&gt;left-&gt;parent = root.get(); } else if (x == xp-&gt;left) { auto px = x.release(); xp-&gt;left = std::move(y); xp-&gt;left-&gt;left = std::unique_ptr&lt;Node&lt;T&gt;&gt;(px); xp-&gt;left-&gt;left-&gt;parent = xp-&gt;left.get(); } else { auto px = x.release(); xp-&gt;right = std::move(y); xp-&gt;right-&gt;left = std::unique_ptr&lt;Node&lt;T&gt;&gt;(px); xp-&gt;right-&gt;left-&gt;parent = xp-&gt;right.get(); } } void RightRotate(std::unique_ptr&lt;Node&lt;T&gt;&gt;&amp;&amp; x) { auto y = std::move(x-&gt;left); x-&gt;left = std::move(y-&gt;right); if (x-&gt;left) { x-&gt;left-&gt;parent = x.get(); } y-&gt;parent = x-&gt;parent; auto xp = x-&gt;parent; if (!xp) { auto px = x.release(); root = std::move(y); root-&gt;right = std::unique_ptr&lt;Node&lt;T&gt;&gt;(px); root-&gt;right-&gt;parent = root.get(); } else if (x == xp-&gt;left) { auto px = x.release(); xp-&gt;left = std::move(y); xp-&gt;left-&gt;right = std::unique_ptr&lt;Node&lt;T&gt;&gt;(px); xp-&gt;left-&gt;right-&gt;parent = xp-&gt;left.get(); } else { auto px = x.release(); xp-&gt;right = std::move(y); xp-&gt;right-&gt;right = std::unique_ptr&lt;Node&lt;T&gt;&gt;(px); xp-&gt;right-&gt;right-&gt;parent = xp-&gt;right.get(); } } public: Node&lt;T&gt;* Search(const T&amp; key) { return Search(root.get(), key); } void Insert(const T&amp; key) { auto z = std::make_unique&lt;Node&lt;T&gt;&gt;(key); Insert(std::move(z)); } void Delete(const T&amp; key) { auto z = Search(key); Delete(z); } private: Node&lt;T&gt;* Search(Node&lt;T&gt;* x, const T&amp; key) { if (!x || x-&gt;key == key) { return x; } if (key &lt; x-&gt;key) { return Search(x-&gt;left.get(), key); } else { return Search(x-&gt;right.get(), key); } } void Insert(std::unique_ptr&lt;Node&lt;T&gt;&gt; z) { Node&lt;T&gt;* y = nullptr; Node&lt;T&gt;* x = root.get(); while (x) { y = x; if (z-&gt;key &lt; x-&gt;key) { x = x-&gt;left.get(); } else { x = x-&gt;right.get(); } } z-&gt;parent = y; if (!y) { root = std::move(z); InsertFixup(std::move(root)); } else if (z-&gt;key &lt; y-&gt;key) { y-&gt;left = std::move(z); InsertFixup(std::move(y-&gt;left)); } else { y-&gt;right = std::move(z); InsertFixup(std::move(y-&gt;right)); } } void InsertFixup(std::unique_ptr&lt;Node&lt;T&gt;&gt;&amp;&amp; z) { auto zp = z-&gt;parent; while (zp &amp;&amp; zp-&gt;color == Color::Red) { auto zpp = zp-&gt;parent; if (zp == zpp-&gt;left.get()) { auto y = zpp-&gt;right.get(); if (y &amp;&amp; y-&gt;color == Color::Red) { zp-&gt;color = Color::Black; y-&gt;color = Color::Black; zpp-&gt;color = Color::Red; zp = zpp-&gt;parent; } else { if (z == zp-&gt;right) { LeftRotate(std::move(zpp-&gt;left)); zp = zpp-&gt;left.get(); } zp-&gt;color = Color::Black; zpp-&gt;color = Color::Red; auto zppp = zpp-&gt;parent; if (!zppp) { RightRotate(std::move(root)); } else if (zpp == zppp-&gt;left.get()) { RightRotate(std::move(zppp-&gt;left)); } else { RightRotate(std::move(zppp-&gt;right)); } } } else { auto y = zpp-&gt;left.get(); if (y &amp;&amp; y-&gt;color == Color::Red) { zp-&gt;color = Color::Black; y-&gt;color = Color::Black; zpp-&gt;color = Color::Red; zp = zpp-&gt;parent; } else { if (z == zp-&gt;left) { RightRotate(std::move(zpp-&gt;right)); zp = zpp-&gt;right.get(); } zp-&gt;color = Color::Black; zpp-&gt;color = Color::Red; auto zppp = zpp-&gt;parent; if (!zppp) { LeftRotate(std::move(root)); } else if (zpp == zppp-&gt;left.get()) { LeftRotate(std::move(zppp-&gt;left)); } else { LeftRotate(std::move(zppp-&gt;right)); } } } } root-&gt;color = Color::Black; } Node&lt;T&gt;* Transplant(Node&lt;T&gt;* u, std::unique_ptr&lt;Node&lt;T&gt;&gt;&amp;&amp; v) { if (v) { v-&gt;parent = u-&gt;parent; } Node&lt;T&gt;* w = nullptr; if (!u-&gt;parent) { w = root.release(); root = std::move(v); } else if (u == u-&gt;parent-&gt;left.get()) { w = u-&gt;parent-&gt;left.release(); u-&gt;parent-&gt;left = std::move(v); } else { w = u-&gt;parent-&gt;right.release(); u-&gt;parent-&gt;right = std::move(v); } return w; } Node&lt;T&gt;* Minimum(Node&lt;T&gt;* x) { if (!x) { return x; } while (x-&gt;left) { x = x-&gt;left.get(); } return x; } void Delete(Node&lt;T&gt;* z) { if (!z) { return; } Color orig_color = z-&gt;color; Node&lt;T&gt;* x = nullptr; Node&lt;T&gt;* xp = nullptr; if (!z-&gt;left) { x = z-&gt;right.get(); xp = z-&gt;parent; auto pz = Transplant(z, std::move(z-&gt;right)); auto upz = std::unique_ptr&lt;Node&lt;T&gt;&gt;(pz); } else if (!z-&gt;right) { x = z-&gt;left.get(); xp = z-&gt;parent; auto pz = Transplant(z, std::move(z-&gt;left)); auto upz = std::unique_ptr&lt;Node&lt;T&gt;&gt;(pz); } else { auto y = Minimum(z-&gt;right.get()); orig_color = y-&gt;color; x = y-&gt;right.get(); xp = y; if (y-&gt;parent == z) { if (x) { x-&gt;parent = y; } auto pz = Transplant(z, std::move(z-&gt;right)); y-&gt;left = std::move(pz-&gt;left); y-&gt;left-&gt;parent = y; y-&gt;color = pz-&gt;color; auto upz = std::unique_ptr&lt;Node&lt;T&gt;&gt;(pz); } else { xp = y-&gt;parent; auto py = Transplant(y, std::move(y-&gt;right)); py-&gt;right = std::move(z-&gt;right); py-&gt;right-&gt;parent = py; auto upy = std::unique_ptr&lt;Node&lt;T&gt;&gt;(py); auto pz = Transplant(z, std::move(upy)); py-&gt;left = std::move(pz-&gt;left); py-&gt;left-&gt;parent = py; py-&gt;color = pz-&gt;color; auto upz = std::unique_ptr&lt;Node&lt;T&gt;&gt;(pz); } } if (orig_color == Color::Black) { DeleteFixup(x, xp); } } void DeleteFixup(Node&lt;T&gt;* x, Node&lt;T&gt;* xp) { while (x != root.get() &amp;&amp; (!x || x-&gt;color == Color::Black)) { if (x == xp-&gt;left.get()) { Node&lt;T&gt;* w = xp-&gt;right.get(); if (w &amp;&amp; w-&gt;color == Color::Red) { w-&gt;color = Color::Black; xp-&gt;color = Color::Red; auto xpp = xp-&gt;parent; if (!xpp) { LeftRotate(std::move(root)); } else if (xp == xpp-&gt;left.get()) { LeftRotate(std::move(xpp-&gt;left)); } else { LeftRotate(std::move(xpp-&gt;right)); } w = xp-&gt;right.get(); } if (w &amp;&amp; (!w-&gt;left || w-&gt;left-&gt;color == Color::Black) &amp;&amp; (!w-&gt;right || w-&gt;right-&gt;color == Color::Black)) { w-&gt;color = Color::Red; x = xp; xp = xp-&gt;parent; } else if (w) { if (!w-&gt;right || w-&gt;right-&gt;color == Color::Black) { w-&gt;left-&gt;color = Color::Black; w-&gt;color = Color::Red; auto wp = w-&gt;parent; if (!wp) { RightRotate(std::move(root)); } else if (w == wp-&gt;left.get()) { RightRotate(std::move(wp-&gt;left)); } else { RightRotate(std::move(wp-&gt;right)); } w = xp-&gt;right.get(); } w-&gt;color = xp-&gt;color; xp-&gt;color = Color::Black; w-&gt;right-&gt;color = Color::Black; auto xpp = xp-&gt;parent; if (!xpp) { LeftRotate(std::move(root)); } else if (xp == xpp-&gt;left.get()) { LeftRotate(std::move(xpp-&gt;left)); } else { LeftRotate(std::move(xpp-&gt;right)); } x = root.get(); } else { x = root.get(); } } else { Node&lt;T&gt;* w = xp-&gt;left.get(); if (w &amp;&amp; w-&gt;color == Color::Red) { w-&gt;color = Color::Black; xp-&gt;color = Color::Red; auto xpp = xp-&gt;parent; if (!xpp) { RightRotate(std::move(root)); } else if (xp == xpp-&gt;left.get()) { RightRotate(std::move(xpp-&gt;left)); } else { RightRotate(std::move(xpp-&gt;right)); } w = xp-&gt;left.get(); } if (w &amp;&amp; (!w-&gt;left || w-&gt;left-&gt;color == Color::Black) &amp;&amp; (!w-&gt;right || w-&gt;right-&gt;color == Color::Black)) { w-&gt;color = Color::Red; x = xp; xp = xp-&gt;parent; } else if (w) { if (!w-&gt;left || w-&gt;left-&gt;color == Color::Black) { w-&gt;right-&gt;color = Color::Black; w-&gt;color = Color::Red; auto wp = w-&gt;parent; if (!wp) { LeftRotate(std::move(root)); } else if (w == wp-&gt;left.get()) { LeftRotate(std::move(wp-&gt;left)); } else { LeftRotate(std::move(wp-&gt;right)); } w = xp-&gt;left.get(); } w-&gt;color = xp-&gt;color; xp-&gt;color = Color::Black; w-&gt;left-&gt;color = Color::Black; auto xpp = xp-&gt;parent; if (!xpp) { RightRotate(std::move(root)); } else if (xp == xpp-&gt;left.get()) { RightRotate(std::move(xpp-&gt;left)); } else { RightRotate(std::move(xpp-&gt;right)); } x = root.get(); } else { x = root.get(); } } } if (x) { x-&gt;color = Color::Black; } } }; template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Node&lt;T&gt;* node) { if (node) { os &lt;&lt; node-&gt;left.get(); os &lt;&lt; node-&gt;key; if (node-&gt;color == Color::Black) { os &lt;&lt; &quot;● &quot;; } else { os &lt;&lt; &quot;○ &quot;; } os &lt;&lt; node-&gt;right.get(); } return os; } template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const RBTree&lt;T&gt;&amp; tree) { os &lt;&lt; tree.root.get(); return os; } int main() { constexpr size_t SIZE = 100'000; std::vector&lt;int&gt; v (SIZE); std::iota(v.begin(), v.end(), 1); std::shuffle(v.begin(), v.end(), gen); RBTree&lt;int&gt; rbtree; auto t1 = std::chrono::steady_clock::now(); for (auto n : v) { rbtree.Insert(n); } auto t2 = std::chrono::steady_clock::now(); auto dt1 = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t2 - t1); std::set&lt;int&gt; rbset; t1 = std::chrono::steady_clock::now(); for (auto n : v) { rbset.insert(n); } t2 = std::chrono::steady_clock::now(); auto dt2 = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t2 - t1); std::cout &lt;&lt; &quot;Inserting &quot; &lt;&lt; SIZE &lt;&lt; &quot; elements:\n&quot;; std::cout &lt;&lt; &quot;unique ptr red-black tree : &quot; &lt;&lt; dt1.count() &lt;&lt; &quot; ms\n&quot;; std::cout &lt;&lt; &quot;standard red-black tree : &quot; &lt;&lt; dt2.count() &lt;&lt; &quot; ms\n&quot;; std::shuffle(v.begin(), v.end(), gen); t1 = std::chrono::steady_clock::now(); for (auto n : v) { rbtree.Delete(n); } t2 = std::chrono::steady_clock::now(); auto dt3 = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t2 - t1); t1 = std::chrono::steady_clock::now(); for (auto n : v) { rbset.erase(n); } t2 = std::chrono::steady_clock::now(); auto dt4 = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t2 - t1); std::cout &lt;&lt; &quot;Deleting &quot; &lt;&lt; SIZE &lt;&lt; &quot; elements:\n&quot;; std::cout &lt;&lt; &quot;unique ptr red-black tree : &quot; &lt;&lt; dt3.count() &lt;&lt; &quot; ms\n&quot;; std::cout &lt;&lt; &quot;standard red-black tree : &quot; &lt;&lt; dt4.count() &lt;&lt; &quot; ms\n&quot;; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T03:34:21.783", "Id": "483273", "Score": "0", "body": "I am confused about usage of `std::unique_ptr<Node<T>>&& z`. Normally one either passes a raw pointer or unique_ptr depending on whether you pass ownership over the object or not. Passing rvalue-reference of unique_ptr makes little to no sence. I can understand lvalue reference of unique_ptr - for relocating stuff. But rvalue reference? Just why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:12:31.147", "Id": "483279", "Score": "0", "body": "@ALX23z No, lvalue referenced ```std::unique_ptr``` parameter cannot transfer its ownership in the scope." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:52:11.833", "Id": "483291", "Score": "0", "body": "Look for internet guides on these things before giving someone an advice, please. https://stackoverflow.com/a/8114913/7772722" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:56:35.847", "Id": "483292", "Score": "0", "body": "Quote from the reply in the SO link above: ...Although your argument favoring passing by value over passing by rvalue reference makes sense, I think that the standard itself always passes unique_ptr values by rvalue reference (for instance when transforming them into shared_ptr). The rationale for that might be that it is slightly more efficient (no moving to temporary pointers is done) while it gives the exact same rights to the caller (may pass rvalues, or lvalues wrapped in std::move, but not naked lvalues)...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:18:35.577", "Id": "483295", "Score": "0", "body": "In that question was referred an odd case of instantiating base from `unique_ptr` to base. I doubt that standart passes unique_ptr by rvalue reference unless it is done with a generic scope - and they might be doing it due to complexity of possible non-trivial deleter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:22:11.023", "Id": "483296", "Score": "0", "body": "In your case you have a function with quite a lot of code. It won't be inlined. And since you pass unique_ptr by reference it will have to dereference it almost each it is being accessed. This is because it might coincide with other unique_ptr inside the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:25:18.393", "Id": "483297", "Score": "0", "body": "Another problem is that by the end of the function - it might not have moved at all. It is a good way to confuse user that assumes that the object gets moved and he has an empty unique_ptr. As well you should note that in the answer they told him that it is best to accept as an instance and not a reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T09:53:46.747", "Id": "514182", "Score": "2", "body": "Hi @frozenca thank you for taking part in the review queues, but please be careful when using the _No Action Needed_ action in the _First Posts_ queue. For more information please read [First Post Review Queue — what is it? Why is it a bad idea to click “No Action Needed”?](https://codereview.meta.stackexchange.com/q/1946). Thank you." } ]
[ { "body": "<h1>Don't forget to <code>#include &lt;algorithm&gt;</code></h1>\n<p>You have to <code>#include &lt;algorithm&gt;</code> to get <code>std::shuffle</code>.</p>\n<h1>Move <code>struct Node</code> and <code>enum class Color</code> inside <code>struct RBTree</code></h1>\n<p>A <code>Node</code> is just an implementation detail of <code>RBTree</code>. It is better to move it inside <code>struct RBTree</code>. This also ensures you can just write <code>Node</code> instead of <code>Node&lt;T&gt;</code> everywhere. The same goes for <code>Color</code>. In fact, <code>Color</code> is just a property of a <code>Node</code>, so it could be moved into <code>struct Node</code>, but in this case it would just involve unnecessary typing.</p>\n<p>This is how it looks:</p>\n<pre><code>template &lt;typename T&gt;\nstruct RBTree {\n enum class Color {\n Red,\n Black,\n };\n\n struct Node {\n T key;\n Color color;\n std::unqiue_ptr&lt;Node&gt; left;\n ...\n };\n\n std::unique_ptr&lt;Node&gt; root;\n\nprivate:\n ...\n};\n</code></pre>\n<p>There is a slight difficulty changing the <code>operator&lt;&lt;</code> overload for <code>Node</code>, because <code>Node</code> is a <a href=\"https://en.cppreference.com/w/cpp/language/dependent_name\" rel=\"nofollow noreferrer\">dependent name</a> of <code>RBTree&lt;T&gt;</code>. To make it compile, you have to add <code>typename</code> before <code>RBTree&lt;T&gt;::Node</code>:</p>\n<pre><code>template &lt;typename T&gt;\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, typename RBTree&lt;T&gt;::Node *node) {\n ...\n}\n</code></pre>\n<h1>The public <code>Search()</code> function should not return a <code>Node *</code></h1>\n<p><code>Node</code>s are just an implementation detail of your tree. By exposing this, it allows a user of your tree to make modifications to a <code>Node</code> that could cause the tree to become corrupted. I would make it return the key found in the tree as a <code>const T*</code> instead:</p>\n<pre><code>const T* Search(const T&amp; key) {\n auto z = Search(root.get(), key);\n return z ? &amp;z-&gt;key : nullptr;\n}\n</code></pre>\n<p>Another option is to return the key by value, and use <code>std::optional&lt;T&gt;</code> so you can inform the caller that the key was not in the tree:</p>\n<pre><code>std::optional&lt;T&gt; Search(const T&amp; key) {\n auto z = Search(root.get(), key);\n return z ? std::make_optional(z-&gt;key) : nullopt;\n}\n</code></pre>\n<p>You have to modify <code>Delete()</code> slightly to compensate for this.</p>\n<h1>Make functions that do not modify the tree <code>const</code></h1>\n<p>Make functions that do not change the tree <code>const</code>, so the compiler can generate better code, and will also allow you to call those functions on a <code>const RBTree</code>. The functions relating to searches can all be marked <code>const</code>:</p>\n<pre><code>const T* Search(const T&amp; key) const { ... }\nNode* Search(Node* x, const T&amp; key) const { ... }\nNode* Minimum(Node* x) const { ... }\n</code></pre>\n<h1>Some unnecessary code</h1>\n<p>I see some lines of code that basically do nothing and could be simplified. For example, in <code>Delete()</code>:</p>\n<pre><code>auto pz = Transplant(z, std::move(z-&gt;right));\nauto upz = std::unique_ptr&lt;Node&gt;(pz);\n</code></pre>\n<p>And afterwards, <code>upz</code> is no longer used. The above can be simplified to:</p>\n<pre><code>delete Transplant(z, std::move(z-&gt;right));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:36:22.557", "Id": "482391", "Score": "2", "body": "Thanks a lot! The purpose of ```upz``` is to free pointer ```pz```." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:40:25.757", "Id": "482393", "Score": "2", "body": "Oops, I forgot to add the `delete` there. Moving something into a temporary `unique_ptr<>` to free it is a very roundabout way :) If you don't like the raw `delete`, then consider having `Transplant()` return a `std::unique_ptr<Node>` instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:09:56.323", "Id": "245615", "ParentId": "245613", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T10:57:45.357", "Id": "245613", "Score": "5", "Tags": [ "c++", "tree" ], "Title": "C++ : Red-Black Tree with std::unique_ptr" }
245613
<p><strong>Goal:</strong></p> <p>I have thought of a project to create and came up with this goal of: <em><strong>&quot;To record temperatures for different Fridges or Freezers.&quot;</strong></em></p> <p><strong>Current situation</strong></p> <p>I have a working method to get data from html and send it to MySQL. But I feel like it can be simplified, as I have way too much code.</p> <p>I'd like to see if anyone has different methods and help me out if I am going anywhere wrong or using very old methods.</p> <p><strong>Html, Jquery and Javascript</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en" dir="ltr"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" href="/style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container mt-4"&gt; &lt;div id="errors" class="mt-4"&gt; &lt;/div&gt; &lt;h1 class="text-left" style="margin-bottom: 50px"&gt;Daily Fridge &amp; Freezer Monitoring Record&lt;/h1&gt; &lt;form action="/auth/21-TEMP-01b" method="post" id="form"&gt; &lt;div class="form-group"&gt; &lt;label&gt;Select Fridge Or Freezer&lt;/label&gt; &lt;select class="form-control" id="fridgeFreezer" name="fridge"&gt; &lt;option value="fridge1"&gt;Fridge 1&lt;/option&gt; &lt;option value="fridge2"&gt;Fridge 2&lt;/option&gt; &lt;option value="fridge3"&gt;Fridge 3&lt;/option&gt; &lt;option value="fridge4"&gt;Fridge 4&lt;/option&gt; &lt;option value="fridge5"&gt;Fridge 5&lt;/option&gt; &lt;option value="fridge6"&gt;Fridge 6&lt;/option&gt; &lt;option value="fridge7"&gt;Fridge 7&lt;/option&gt; &lt;option value="fridge8"&gt;Fridge 8&lt;/option&gt; &lt;option value="fridge9"&gt;Fridge 9&lt;/option&gt; &lt;option value="fridge10"&gt;Fridge 10&lt;/option&gt; &lt;option value="freezer1"&gt;Freezer 1&lt;/option&gt; &lt;option value="freezer2"&gt;Freezer 2&lt;/option&gt; &lt;option value="freezer3"&gt;Freezer 3&lt;/option&gt; &lt;option value="freezer4"&gt;Freezer 4&lt;/option&gt; &lt;option value="freezer5"&gt;Freezer 5&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;!-- Fridges --&gt; &lt;div class="form-group fridges fridge1"&gt; &lt;h4&gt;Fridge 1&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature1" name="temperature1"&gt; &lt;input type="hidden" name="Fridge1" value="Fridge 1"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments1" name="comments1"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge2"&gt; &lt;h4&gt;Fridge 2&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature2" name="temperature2"&gt; &lt;input type="hidden" name="Fridge2" value="Fridge 2"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments2" name="comments2"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge3"&gt; &lt;h4&gt;Fridge 3&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature3" name="temperature3"&gt; &lt;input type="hidden" name="Fridge3" value="Fridge 3"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments3" name="comments3"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge4"&gt; &lt;h4&gt;Fridge 4&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature4" name="temperature4"&gt; &lt;input type="hidden" name="Fridge4" value="Fridge 4"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments4" name="comments4"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge5"&gt; &lt;h4&gt;Fridge 5&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature5" name="temperature5"&gt; &lt;input type="hidden" name="Fridge5" value="Fridge 5"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments5" name="comments5"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge6"&gt; &lt;h4&gt;Fridge 6&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature6" name="temperature6"&gt; &lt;input type="hidden" name="Fridge6" value="Fridge 6"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments6" name="comments6"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge7"&gt; &lt;h4&gt;Fridge 2&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature7" name="temperature7"&gt; &lt;input type="hidden" name="Fridge7" value="Fridge 7"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments7" name="comments7"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge8"&gt; &lt;h4&gt;Fridge 8&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature8" name="temperature8"&gt; &lt;input type="hidden" name="Fridge8" value="Fridge 8"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments8" name="comments8"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge9"&gt; &lt;h4&gt;Fridge 9&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature9" name="temperature9"&gt; &lt;input type="hidden" name="Fridge9" value="Fridge 9"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments9" name="comments9"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges fridge10"&gt; &lt;h4&gt;Fridge 10&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="temperature10" name="temperature10"&gt; &lt;input type="hidden" name="Fridge10" value="Fridge 10"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="comments10" name="comments10"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;!-- Freezers --&gt; &lt;div class="form-group fridges freezer1"&gt; &lt;h4&gt;Freezer 1&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="freezertemperature1" name="freezertemperature1"&gt; &lt;input type="hidden" name="Freezer1" value="Freezer 1"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="freezercomments1" name="freezercomments1"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges freezer2"&gt; &lt;h4&gt;Freezer 2&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="freezertemperature2" name="freezertemperature2"&gt; &lt;input type="hidden" name="Freezer2" value="Freezer 2"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="freezercomments2" name="freezercomments2"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges freezer3"&gt; &lt;h4&gt;Freezer 3&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="freezertemperature3" name="freezertemperature3"&gt; &lt;input type="hidden" name="Freezer3" value="Freezer 3"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="freezercomments3" name="freezercomments3"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges freezer4"&gt; &lt;h4&gt;Freezer 4&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="freezertemperature4" name="freezertemperature4"&gt; &lt;input type="hidden" name="Freezer4" value="Freezer 4"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="freezercomments4" name="freezercomments4"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group fridges freezer5"&gt; &lt;h4&gt;Freezer 5&lt;/h4&gt; &lt;label&gt;Temperature °C&lt;/label&gt; &lt;input class="form-control" type="number" id="freezertemperature5" name="freezertemperature5"&gt; &lt;input type="hidden" name="Freezer5" value="Freezer 5"&gt; &lt;label&gt;Comments&lt;/label&gt; &lt;textarea class="form-control" rows="3" id="freezercomments5" name="freezercomments5"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ if($(this).attr("value")=="fridge1"){ $(".fridges").not(".fridge1").hide(); $(".fridge1").show(); } else if($(this).attr("value")=="fridge2"){ $(".fridges").not(".fridge2").hide(); $(".fridge2").show(); } else if($(this).attr("value")=="fridge3"){ $(".fridges").not(".fridge3").hide(); $(".fridge3").show(); } else if($(this).attr("value")=="fridge4"){ $(".fridges").not(".fridge4").hide(); $(".fridge4").show(); } else if($(this).attr("value")=="fridge5"){ $(".fridges").not(".fridge5").hide(); $(".fridge5").show(); } else if($(this).attr("value")=="fridge6"){ $(".fridges").not(".fridge6").hide(); $(".fridge6").show(); } else if($(this).attr("value")=="fridge7"){ $(".fridges").not(".fridge7").hide(); $(".fridge7").show(); } else if($(this).attr("value")=="fridge8"){ $(".fridges").not(".fridge8").hide(); $(".fridge8").show(); } else if($(this).attr("value")=="fridge9"){ $(".fridges").not(".fridge9").hide(); $(".fridge9").show(); } else if($(this).attr("value")=="fridge10"){ $(".fridges").not(".fridge10").hide(); $(".fridge10").show(); } else if($(this).attr("value")=="freezer1"){ $(".fridges").not(".freezer1").hide(); $(".freezer1").show(); } else if($(this).attr("value")=="freezer2"){ $(".fridges").not(".freezer2").hide(); $(".freezer2").show(); } else if($(this).attr("value")=="freezer3"){ $(".fridges").not(".freezer3").hide(); $(".freezer3").show(); } else if($(this).attr("value")=="freezer4"){ $(".fridges").not(".freezer4").hide(); $(".freezer4").show(); } else if($(this).attr("value")=="freezer5"){ $(".fridges").not(".freezer5").hide(); $(".freezer5").show(); } else{ $(".fridges").hide(); } }); }) .change(); // Checking if all information has been filled out var form = document.getElementById('form'); // Get each individual temperature var temp1 = document.getElementById('temperature1'); var temp2 = document.getElementById('temperature2'); var temp3 = document.getElementById('temperature3'); var temp4 = document.getElementById('temperature4'); var temp5 = document.getElementById('temperature5'); var temp6 = document.getElementById('temperature6'); var temp7 = document.getElementById('temperature7'); var temp8 = document.getElementById('temperature8'); var temp9 = document.getElementById('temperature9'); var temp10 = document.getElementById('temperature10'); var freezertemp1 = document.getElementById('freezertemperature1'); var freezertemp2 = document.getElementById('freezertemperature2'); var freezertemp3 = document.getElementById('freezertemperature3'); var freezertemp4 = document.getElementById('freezertemperature4'); var freezertemp5 = document.getElementById('freezertemperature5'); // Error element var errorElement = document.getElementById('errors'); // Add event listener to form on submit form.addEventListener('submit', function(e) { // Combine all errors into 1 let messages = []; // Fridge 1 - here we are checking if all fields are not empty if(temp1.value === '' || temp1.value == null) { messages.push('Fridge 1'); $('#fridgeFreezer').val("fridge1"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 2 if(temp2.value === '' || temp2.value == null) { messages.push('Fridge 2'); $('#fridgeFreezer').val("fridge2"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 3 if(temp3.value === '' || temp3.value == null) { messages.push('Fridge 3'); $('#fridgeFreezer').val("fridge3"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 4 if(temp4.value === '' || temp4.value == null) { messages.push('Fridge 4'); $('#fridgeFreezer').val("fridge4"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 5 if(temp5.value === '' || temp5.value == null) { messages.push('Fridge 5'); $('#fridgeFreezer').val("fridge5"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 6 if(temp6.value === '' || temp6.value == null) { messages.push('Fridge 6'); $('#fridgeFreezer').val("fridge6"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 7 if(temp7.value === '' || temp7.value == null) { messages.push('Fridge 7'); $('#fridgeFreezer').val("fridge7"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 8 if(temp8.value === '' || temp8.value == null) { messages.push('Fridge 8'); $('#fridgeFreezer').val("fridge8"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 9 if(temp9.value === '' || temp9.value == null) { messages.push('Fridge 9'); $('#fridgeFreezer').val("fridge9"); $('#fridgeFreezer').trigger("change"); // important line } // Fridge 10 if(temp10.value === '' || temp10.value == null) { messages.push('Fridge 10'); $('#fridgeFreezer').val("fridge10"); $('#fridgeFreezer').trigger("change"); // important line } // Freezer 1 if(freezertemp1.value === '' || freezertemp1.value == null) { messages.push('Freezer 1'); $('#fridgeFreezer').val("freezer1"); $('#fridgeFreezer').trigger("change"); // important line } // Freezer 2 if(freezertemp2.value === '' || freezertemp2.value == null) { messages.push('Freezer 2'); $('#fridgeFreezer').val("freezer2"); $('#fridgeFreezer').trigger("change"); // important line } // Freezer 3 if(freezertemp3.value === '' || freezertemp3.value == null) { messages.push('Freezer 3'); $('#fridgeFreezer').val("freezer3"); $('#fridgeFreezer').trigger("change"); // important line } // Freezer 4 if(freezertemp4.value === '' || freezertemp4.value == null) { messages.push('Freezer 4'); $('#fridgeFreezer').val("freezer4"); $('#fridgeFreezer').trigger("change"); // important line } // Freezer 5 if(freezertemp5.value === '' || freezertemp5.value == null) { messages.push('Freezer 5'); $('#fridgeFreezer').val("freezer5"); $('#fridgeFreezer').trigger("change"); // important line } if(messages.length &gt; 0) { e.preventDefault() errorElement.innerHTML = '&lt;div class="alert alert-danger" role="alert"&gt;' + messages.join(', &lt;br/&gt;') + "&lt;br/&gt;" + ' Not Recorded' + '&lt;/div&gt;'; } }) }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>NODE JS - Not fully done (Need to add more variables for all fridges and freezers)</strong></p> <pre><code>// Send temperature records to MySQL exports.tempSend = async function(req, res) { var { Fridge1,temperature1, comments1, Fridge2, temperature2, comments2 } = req.body; var values = [ [Fridge1, temperature1, comments1], [Fridge2, temperature2, comments2] ] db.query('insert into tempcheck (fridge, temp, comments) values ?', [values], function(error, result) { if(error) { console.log(error); } else{ console.log(result); } }); } </code></pre>
[]
[ { "body": "<p>Your Node side could be simplified by sending over the readings JSON as a singular list of objects.</p>\n<pre><code>// assuming readings looks like this\n\n[\n {\n 'fridge':'old sketchy fridge',\n 'temperature':-3,\n 'comment':'yup, still works'\n },\n {\n 'fridge':'new fancy fridge',\n 'temperature':-4,\n 'comment':'this one better be worth the money'\n }\n]\n\nconst {readings} = req.body;\nconst values = readings.map(\n reading=&gt;[reading.fridge,reading.temperature,reading.comment]\n);\n</code></pre>\n<p>Your use case sounds ideal for React, but vanilla javascript can also help you remove duplicated code. Anytime you find yourself creating a variable with a number tacked on the end of the name, you should be suspicious.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T11:11:37.083", "Id": "245661", "ParentId": "245614", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T11:39:53.660", "Id": "245614", "Score": "3", "Tags": [ "jquery", "html", "node.js" ], "Title": "Node JS Express - Temperature records" }
245614
<h1>Dole Out Cadbury</h1> <h2>Problem Description</h2> <blockquote> <p>You are a teacher in reputed school. During Celebration Day you were assigned a task to distribute Cadbury such that maximum children get the chocolate. You have a box full of Cadbury with different width and height. You can only distribute largest square shape Cadbury. So if you have a Cadbury of length 10 and width 5, then you need to break Cadbury in 5X5 square and distribute to first child and then remaining 5X5 to next in queue</p> <h2>Constraints</h2> <p><span class="math-container">\$0&lt;P&lt;Q&lt;1501\$</span><br /> <span class="math-container">\$0&lt;R&lt;S&lt;1501\$</span></p> <h2>Input Format</h2> <p>First line contains an integer P that denotes minimum length of Cadbury in the box<br /> Second line contains an integer Q that denotes maximum length of Cadbury in the box<br /> Third line contains an integer R that denotes minimum width of Cadbury in the box<br /> Fourth line contains an integer S that denotes maximum width of Cadbury in the box</p> <p>Output<br /> Print total number of children who will get chocolate.</p> <p>Timeout<br /> 1</p> <p>Example</p> <p>Input</p> <pre><code>5 7 3 4 </code></pre> <p>Output</p> <pre><code>24 </code></pre> <p>Explanation</p> <p>Length is in between 5 to 7 and width is in between 3 to 4.<br /> So we have 5X3,5X4,6X3,6X4,7X3,7X4 type of Cadbury in the box. If we take 5X3:</p> <p>First, we can give 3X3 square Cadbury to 1st child .Then we are left with 3X2. Now largest square is 2X2 which will be given to next child. Next, we are left with two 1X1 part of Cadbury which will be given to another two children.<br /> And so on.</p> </blockquote> <p>Here is my code, which works but returns <a href="/questions/tagged/time-limit-exceeded" class="post-tag" title="show questions tagged &#39;time-limit-exceeded&#39;" rel="tag">time-limit-exceeded</a>. I'm looking for optimizations.</p> <pre><code>def cadbury(l,b): count = 0 while True: lon=max(l,b) sh=min(l,b) count+=1 diff=lon-sh if diff==0: return count else : l=min(l,b) b=diff minl=int(input()) maxl=int(input()) minw=int(input()) maxw=int(input()) count=0 for i in range(minl,maxl+1): for j in range(minw,maxw+1): count+=cadbury(i,j) print(count) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:48:14.653", "Id": "482396", "Score": "5", "body": "Did you consider to reuse results computed in the `while` loop of the `cadbury` function instead of computing these again and again with every call?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T14:09:29.900", "Id": "482512", "Score": "0", "body": "I thought of reusing it. so only i asked for help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T14:41:56.993", "Id": "482513", "Score": "1", "body": "Implement such a code that's working, and we willl happily suggest improvements of it for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T05:00:01.003", "Id": "482564", "Score": "1", "body": "There is an abstraction for *repeat subtraction until not enough is left*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:28:32.347", "Id": "482709", "Score": "0", "body": "To close voters, see https://codereview.stackexchange.com/questions/142008/cadbury-problem-solution-in-python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T18:38:23.893", "Id": "483243", "Score": "2", "body": "I agree this is a poorly written question and the initial revision could've used some more effort. However, a quick test indicates it *does* work so the the current 4 close votes it has that claim it doesn't should either be backed up with an example case or be retracted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T21:32:28.287", "Id": "485317", "Score": "0", "body": "Please link to the problem, so we can test potential solutions there. Not interested in starting this when I can't test." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:39:50.910", "Id": "245616", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Better performance in solution for the Dole Out Cadbury challenge" }
245616
<p>As a first step into the world of Alloy, I've done my own version of the Fox/Chicken/Grain problem. I'd be grateful for any comments (also, is there a better place to do this?).</p> <p>I thought it worth separating out the Farmer from the other items so I don't have to keep removing it from the set of items.</p> <pre><code>open util/ordering[Time] sig Time {} enum Place {Near, Far} abstract sig Locatable { location: Place one -&gt; Time } abstract sig Edible extends Locatable {} one sig Fox, Chicken, Grain extends Edible {} one sig Farmer extends Locatable {} pred init(t: Time) { Locatable.location.t = Near } pred done(t: Time) { Locatable.location.t = Far } pred stayPut(t, t': Time, edibles: set Edible) { all e : edibles | e.location.t = e.location.t' } pred carryAcross(t, t' : Time) { one e: Edible { e.location.t = Farmer.location.t e.location.t' = Farmer.location.t' stayPut[t, t', Edible - e] } } pred crossRiver(t, t' : Time) { stayPut[t, t', Edible] } pred nextCrossing(t, t' : Time) { Farmer.location.t' != Farmer.location.t carryAcross[t, t'] or crossRiver[t, t'] } pred eats [a, b: Edible] { a-&gt;b in Fox-&gt;Chicken + Chicken-&gt;Grain } fact ProtectFromEating { all p, q: Edible, t: Time | p.eats[q] and p.location.t = q.location.t =&gt; q.location.t = Farmer.location.t } fact Traces { first.init all t: Time - last | let t' = t.next | done[t] or nextCrossing [t, t'] } fact Done { some t: Time | done[t] } run {} for 8 Time </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:42:50.360", "Id": "482434", "Score": "1", "body": "Welcome to Code Review! Could you please provide more details about the _Fox/Chicken/Grain problem_? if there is a description from a third party source you are using then feel free to paste the text here (provided that is allowed given licensing), as well as any sample inputs and expected outputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T08:03:05.293", "Id": "482665", "Score": "0", "body": "Is this really necessary? This appears to be a standard example for people in the Alloy world. I'm finding the entry costs to posting \"correctly\" to SE beginning to outweigh the benefits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T21:53:18.263", "Id": "482753", "Score": "2", "body": "No it isn't necessary but might help others provide better reviews. After searching the internet I believe I learned about the F/C/G problems when I was younger. Please forgive my naivety." } ]
[ { "body": "<p>I am personally not a fan of the Time pattern, it gets messy quickly. There is an extension in the works, called electrum that allows you to use variables.</p>\n<p>Overall your solution seems too detailed. The magic of alloy is that you only have to say what you want to <em>achieve</em>. I.e. the animals should always be safe and and somehow they need to end up on the other side. I.e. you don't care about the crossing itself that much as long as you ensure there is never a lunch happening.</p>\n<p>My personal favorite solution for this problem is:</p>\n<pre><code>open util/ordering[Crossing]\nenum Object { Farmer, Chicken, Grain, Fox }\n\nlet eats = Chicken-&gt;Grain + Fox-&gt;Chicken\nlet safe[place] = Farmer in place or (no place.eats &amp; place)\n\nsig Crossing {\n near, far : set Object,\n carry : Object\n} {\n near = Object - far\n safe[near] \n safe[far]\n}\n</code></pre>\n<pre><code>run {\n first.near = Object\n no first.far\n all c : Crossing - last, c': c.next {\n Farmer in c.near implies { \n c'.far = c.far + c.carry + Farmer\n } else {\n c'.near = c.near + c.carry + Farmer\n }\n }\n some c : Crossing | c.far = Object\n} for 8\n</code></pre>\n<p>Peter Kriens @pkriens</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:56:43.583", "Id": "482398", "Score": "0", "body": "Thanks for this, very helpful. I particularly like the way that the table view shows the traffic so clearly. That looks like an useful design heuristic.\n \nSo, “Crossing” is actually the result of a Crossing, i.e. a state, rather than a transition, which is different from the events version of the hotel example in the book. Is there any guidance on when to use the singleton approach instead?\n \nI don’t know if it matters, but this solution doesn’t have a “lock” for when the solution is complete, so on a 9th step the farmer takes the grain back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:56:48.833", "Id": "482399", "Score": "0", "body": "Electrum looks cool, but for my purposes I need to stick with “stable” versions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:03:46.683", "Id": "482402", "Score": "2", "body": "_\"From Pieter Kriens\"_ Who is that? Could you cite properly with a link please. Also are you sure that they'll read your _Thank you_ comment here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:08:16.580", "Id": "482403", "Score": "0", "body": "Yes, it is ok to use my comments" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T14:15:05.087", "Id": "482405", "Score": "0", "body": "@PeterKriens Ah, nice you jumped in ;-). I suspected but wasn't sure, you are the guy who asked to add the [tag:alloy] tag at CR. Welcome!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:53:11.443", "Id": "245620", "ParentId": "245618", "Score": "0" } }, { "body": "<p>As said, the <code>Time</code> pattern never made me fall in love with it so I started to experiment. However, I am an outsider in this. My experience is 44 years of software design but I am more or less an autodidact, not been to university. Big chance a lot of people are now cringing behind their email with this solution :-)</p>\n<p>The pattern to put all variable state in a <em>trace</em> sig (Crossing here) seems to work very well though. One of the reasons I love it is that it is easy to add 'debug' variables that trace progress. When things don't work out as you think (which is 98% of the time) it is easy to store some more information.</p>\n<p>I got the idea when I had been writing some models where I desperately tried to control the variables with quantifications, which usually created dead models (no instance). Like:</p>\n<pre><code> all c : Crossing-last, c': c.next {\n some carry : Object {\n ...\n }\n }\n</code></pre>\n<p>I had one model and then Daniel told me to remove the unnecessary quantifications. At first I had no idea what he was talking about and then it hit me that the complete state space is reachable the trace signature. So you do not need quantifications, the state space is out there, you only need to constrain it to only visit the states you want it to visit. That was a HUGE insight for me, things really fell in place then. Now it seems so rather obvious :-(</p>\n<p>With this approach, you design a <code>sig</code> that contains all the state variables and then have predicates that let it transition to the next state properly. (In this case, the single transition predicate is expanded in the trace predicate for conciseness.) This is usually quite straightforward and maps well to an implementation. The transition predicates are then the <em>events</em>, which also maps well to implementations where events are usually methods.</p>\n<p>The disadvantage is that it does not provide very nice graphs, all data is mixed up in one sig. This was one of the reasons I added the table view. And I expect it is the reason a lot of people don't like it, a lot of Alloy users put a lot of weight on good looking visualizations :-) I like it but find that most of the problems I use Alloy with are not that suitable for nice visualizations.</p>\n<blockquote>\n<p>I don’t know if it matters, but this solution doesn’t have a “lock” for when the solution is complete, so on a 9th step the farmer takes the grain back.</p>\n</blockquote>\n<p>I did't care but it should be a nice simple exercise for the reader to lock it on the <code>far</code> side. :-) You could also lock the <em>last</em> Crossing to be the solution. Just replace:</p>\n<pre><code>some c : Crossing | c.far = Object\n</code></pre>\n<p>with:</p>\n<pre><code>last.far = Object\n</code></pre>\n<blockquote>\n<p>Is there any guidance on when to use the singleton approach instead?</p>\n</blockquote>\n<p>Well, I would not call it a singleton approach but further I am also still struggling to find the best patterns. It is a testimony to Alloy that there are so many good ways to do something, it really is an incredible environment that deserves a lot more attention.</p>\n<p>Peter Kriens @pkriens\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T17:07:13.183", "Id": "483469", "Score": "1", "body": "If this review was actually done by @PeterKriens (as well as the other one) then he should be the one to post it - that way it can be properly attributed to him (protip: he can gain more reputation that way)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T17:08:48.643", "Id": "483470", "Score": "2", "body": "@SᴀᴍOnᴇᴌᴀ I agree with this. These are solid answers and I only want to upvote the person who wrote them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:58:20.830", "Id": "245623", "ParentId": "245618", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T13:50:53.880", "Id": "245618", "Score": "3", "Tags": [ "alloy" ], "Title": "Farmer crossing as first exercise" }
245618
<p>We need to create a car with apiCar and log in two places CosmosDB and the logger, whether there is an error or not. Except if the error happens in Cosmos, in that case we only log in the logger. Finally, if there is an exception, any exception, we need rethrow it so the &quot;MyFunction&quot; caller can handle it. This is my best shot that works but I don't like it. Is there any way to improve it?</p> <pre><code>public async Task MyFunction(Car car) { try { var apiCar = await _APIService.CreateAsync(car); car.Status = CarStatus.Created; _logger.LogInformation(&quot;Created apiCar for car: {carId}&quot;, car.Id); } catch (ApiErrorException exception) { _logger.LogError(exception, &quot;API exception for car: {carId}&quot;, car.Id); car.Status = CarStatus.Error; car.ErrorMessage = exception.Body.Error.Message; } catch (Exception exception) { _logger.LogError(exception, &quot;Exception for car: {carId}&quot;, car.Id); car.Status = CarStatus.Error; car.ErrorMessage = exception.Message; } try { await _cosmosService.UpdateItemAsync(car); } catch (CosmosException exception) { _logger.LogError(exception, &quot;Cosmos exception for car: {carId}&quot;, car.Id); throw; } if (car.Status == CarStatus.Error) { throw new Exception(); } } </code></pre>
[]
[ { "body": "<p>First, any <code>async</code> function should end with <code>Async</code>, ie <code>MyFunctionAsync</code>. You can see examples of this in the other <code>async</code> functions you're calling throughout your code.</p>\n<p>As to your requirements, the exception you throw at the end is devoid of any useful information. It has no exception origination information (line number etc) and no correct stack trace. Either save the exception you're handling in the top <code>try</code> when it happens, or even better rethrow it on the spot.</p>\n<p>I very much question your updating the item even though the first part errored out, so rethrowing the first set of exceptions on the spot is what I'd do, but if you want to update it even in an error case, bring the update function with you in the <code>catch</code> and then rethrow.</p>\n<p>The second part is fine, you're rethrowing as you should.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:13:34.923", "Id": "482420", "Score": "0", "body": "MyFunctionAsync indeed. Creating a top reference seems convenient. Regarding the update function, we need to log in two places Cosmos and the logger. If I bring the Cosmos update function to each catch, each catch will need to have an inner try-catch for that Cosmos call, so the logger reports the Cosmos failure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:16:00.337", "Id": "482421", "Score": "0", "body": "That's fine, use a local function that does the equivalent of the 2nd `try`..`catch` and call it in as many places as needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:50:46.313", "Id": "482424", "Score": "0", "body": "If I call the SaveToCosmosWithTryCatch from the first try, the exception it generates will be catched by the general catch, and as a consequence will call SaveToCosmosWithTryCatch twice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:53:29.460", "Id": "482425", "Score": "0", "body": "If you call it from the first try's catch? That's not how try..catch works, only the try part has its exceptions handled. Any exception triggered in a catch is unhandled." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:03:02.020", "Id": "482427", "Score": "0", "body": "We need to save the car to Cosmos if everything goes fine, that is if everything in the first try goes fine. That is why I ended with the code in question that I don't like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:03:54.723", "Id": "482428", "Score": "0", "body": "I understand, and what's the problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T02:28:54.750", "Id": "482473", "Score": "1", "body": "I ended up factoring out the Cosmos error logging to a method that is called from ApiErrorException and Exception, adding a catch for Cosmos exceptions and duplicating the Cosmos call in the first try. Thanks for your feedback!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:58:25.407", "Id": "245627", "ParentId": "245625", "Score": "2" } } ]
{ "AcceptedAnswerId": "245627", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T15:47:44.383", "Id": "245625", "Score": "1", "Tags": [ "c#" ], "Title": "Try-catch flow to handle two failing services" }
245625
<p>I'm quite novice here so apologies for any silly mistake in advance</p> <p>I've been writing a simple tic tac toe game which is a part of my course in udemy</p> <p>Since this is my first project, I want to do my best in order to learn new things besides learning how to code better. Generally, I want to optimize my code as much as possible.</p> <p>Can anyone help me with this?</p> <pre class="lang-py prettyprint-override"><code># Tic Tac Toe # 17 July 2020 import os test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] player_input_num = 0 # numbers of inputs entered by player player_num = 0 won = False marker = 'X' def clear_screen(): os.system(&quot;clear&quot;) def display_board(board_cords): ''' display the board board_cords = list(left to right from top to bottom) ''' line = '-'*40 for counter in range(0, len(board_cords), 3): print(&quot;\t|\t\t|&quot;) print( f&quot;{board_cords[counter]}\t|\t{board_cords[counter+1]}\t|\t{board_cords[counter+2]}&quot;) print(line) counter += 3 # go to next row def check_player_input(number): if number &lt; 10 and number &gt;= 0: # checking the range return True else: print('Sorry the input is not in range [0-9] .') return False def player_input(player_in): ''' Executing codes on the previously checked input ''' global player_input_num # access to player_input_num if player_input_num &gt;= 2: # check if the position is free to use if check_capacity(test_board, player_in): result = place_marker(test_board, 'X', player_in) clear_screen() display_board(result) if check_win(test_board, marker): print(&quot;You Won!&quot;) global won won = True else: print(&quot;The current position is occupied.&quot;) else: if check_capacity(test_board, player_in): result = place_marker(test_board, 'X', player_in) clear_screen() display_board(result) player_input_num += 1 else: print(&quot;The current position is occupied.&quot;) def check_capacity(board, position): ''' Check if the current position is free to use. ''' return board[position] == ' ' def place_marker(board, marker, position): ''' Replace the position with a marker ''' board[position] = marker return board def check_win(board, marker): ''' Check if the current game is finished ''' if board[0] == board[1] == board[2] == marker: return True if board[0] == board[3] == board[6] == marker: return True if board[0] == board[4] == board[8] == marker: return True if board[2] == board[5] == board[8] == marker: return True if board[6] == board[7] == board[8] == marker: return True if board[2] == board[4] == board[6] == marker: return True return False def wanna_play(): ''' Check whether the players wanna play again or not. ''' answer = input(&quot;Wanna play again? (Y or N)&quot;) return answer # Main display_board(test_board) while True: while won == False: try: # checking if input is int player_num = int(input(&quot;Enter a position: &quot;)) # casting into int except: print(&quot;Input is not a number&quot;) continue if check_player_input(player_num): player_input(player_num) if wanna_play() in ['y', 'Y', 'n', 'N']: print(&quot;something&quot;) else: print(&quot;Invalid input.&quot;) # print(&quot;Thanks for playing :)&quot;) </code></pre> <p>Edited.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:40:48.240", "Id": "482432", "Score": "0", "body": "Welcome to Code Review! You you clarify what you mean by \"_The only problem is that it takes some extra steps which is unusual_\"? If the code is not working to the best of your knowledge then it is not [on-topic](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:44:34.353", "Id": "482436", "Score": "0", "body": "`check_player_input()` always calls `player_input()`, and `player_input()` always calls `check_player_input()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:59:10.067", "Id": "482439", "Score": "0", "body": "It's unclear what you're asking for. If the code isn't doing what you want and you want to fix that, put this on Stack Overflow which is a forum for helping with bugs. If the code is doing what you want and you want stylistic or algorithmic suggestions for how to write better code, then this is the right place. Which are you asking for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T20:07:06.987", "Id": "482442", "Score": "0", "body": "Welcome to Code Review! I rolled back your last edits. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T20:30:51.713", "Id": "482443", "Score": "0", "body": "Oh thank you so much I didn't know that" } ]
[ { "body": "<p>First thing, I assume that you don't like to use Object Oriented concepts and we will continue by the function approach.</p>\n<p>One thing that I should say to you about the comments is always to use them but in a meaningful way. Adding <code># Variables</code> comment above of the variables will not add any additional value to your code. It only wastes space.</p>\n<p>The second thing is about naming. You should always follow your chosen naming rules.\nSo it's better to use <code>player_input_num</code> or <code>player_in_num</code> instead of the <code>playerin_num</code>. That's more <strong>snake_case</strong>.</p>\n<p>So the beginning of your program will be like this after doing the above things:</p>\n<pre><code>import os\n\ntest_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\nplayer_input_num = 0\n</code></pre>\n<p>Acording to the comment rule we said above, you can remove the <code>clear_screen</code> docstring:</p>\n<pre><code>def clear_screen():\n os.system(&quot;clear&quot;)\n</code></pre>\n<p>Now we can take a look at the <code>display_board</code> function. You've used the <code>while</code> loop heare. But in the Python and for this case, using the <code>for</code> loop is more convient and readable. First, let's see the code:</p>\n<pre><code>def display_board(board_cords):\n '''\n display the board\n board_cords = list(left to right from top to bottom)\n '''\n line = '-'*40\n for i in range(0, len(board_cords), 3):\n print(&quot;\\t|\\t\\t|&quot;)\n print(f&quot;{board_cords[i]}\\t|\\t{board_cords[i + 1]}\\t|\\t{board_cords[i + 2]}&quot;)\n print(line)\n</code></pre>\n<p>The <code>i</code> is the loop counter variable. We said that the loop should start counting from the zero until reaching the <code>len(board_cords)</code>. And also we told that after each iteration, it should increase the <code>i</code> value by 3.</p>\n<p>The next function is <code>check_player_input</code>. In this function, we can remove the <code>syntax</code> variable. Also, we can use a more pythonic way of checking the user input range.</p>\n<pre><code>def check_player_input():\n &quot;&quot;&quot;\n Gets an integer between 0 and 10 and calls `player_input` by that\n &quot;&quot;&quot;\n while True:\n try:\n temp = int(input(&quot;Enter a position: &quot;))\n if 0 &lt;= temp &lt; 10:\n break\n else:\n print('Sorry the input is not in range [0-9].')\n except:\n print(&quot;Input is not a number&quot;)\n player_input(temp)\n</code></pre>\n<p>Why removing the <code>syntax</code> variable is better? Because it's a variable with no real use. The original code is an infinite loop with a redundant variable.\nNow we can go to the <code>player_input</code> function. The function that has an unnecessary <code>global</code> value.</p>\n<p>One of the most famous **Not To Do` rules of software development is to avoid <em>global</em> values as possible. How we can avoid using that global value? The best way for doing that is to get the global value as an input parameter. But here I don't do that (Stay tuned for knowing why. For now, we just remove it and keeping its place).</p>\n<p>The second problem here is the documentation of this function is not sufficient. I mean, what are the &quot;codes&quot;? You should add an extra description here for helping people understanding what is going on.</p>\n<pre><code>def player_input(player_in):\n if player_input_num &gt;= 2:\n while check_win(test_board) == False:\n result = place_marker(test_board, 'X', player_in)\n clear_screen()\n display_board(result)\n check_player_input()\n\n print(&quot;You Won!&quot;)\n else:\n while player_input_num &lt;= 2:\n result = place_marker(test_board, 'X', player_in)\n clear_screen()\n display_board(result)\n player_input_num += 1\n check_player_input()\n</code></pre>\n<p>In the next function, you did a very good thing. Inputting the board instead of using global values. I don't do it in your code in this post, but I strongly recommend doing that in other places of your code.</p>\n<p>Doing that makes your code cleaner, more readable, more testable, and less buggy.</p>\n<p>In the <code>check_win</code> there is a big problem. The login is too long and unreadable. It's better to break the logic down.</p>\n<pre><code>def check_win(board):\n if board[0] == board[1] == board[2]:\n return True\n if board[0] == board[3] == board[6]:\n return True\n if board[0] == board[4] == board[8]:\n return True\n if board[2] == board[5] == board[8]:\n return True\n if board[6] == board[7] == board[8]:\n return True\n if board[2] == board[4] == board[6]:\n return True\n return False\n</code></pre>\n<p>Why we did that? There are 6 different conditions for winning. So it's better to divide them from each other. So the person who reads your code can understand them more quickly.</p>\n<p>All the things I've said until now are good, but there is a problem here. The code doesn't work.</p>\n<p>The first problem is the <code>player_input_num </code> value. In the original code, we only allow the user for inputting 3 values. So, What if the game will not finish after 3 moves? We should continue getting the inputs from the user until he/she wins the game.</p>\n<p>We can change the <code>player_input</code> function like this:</p>\n<pre><code>def player_input(player_in):\n result = place_marker(test_board, 'X', player_in)\n clear_screen()\n display_board(result)\n if check_win(test_board, 'X'):\n print(&quot;You won&quot;)\n else:\n check_player_input()\n</code></pre>\n<p>We should change the <code>check_win</code> function too. Additional to the previous conditions, we should check that all 3 cell values are equal to the marker.</p>\n<pre><code>def check_win(board, marker):\n if board[0] == board[1] == board[2] == marker:\n return True\n if board[0] == board[3] == board[6] == marker:\n return True\n if board[0] == board[4] == board[8] == marker:\n return True\n if board[2] == board[5] == board[8] == marker:\n return True\n if board[6] == board[7] == board[8] == marker:\n return True\n if board[2] == board[4] == board[6] == marker:\n return True\n return False\n</code></pre>\n<p>Here it is. But still, we had a problem. What if the all cells of the board has been filled? We can add a new function for checking if the game has finished or not. But we can do it now because for doing that, you should have two players with two different markers. And I think you can do that by yourself.</p>\n<p>For avoiding mistakes, I leave all the codes we seen above here. I hope this help you (Don't forget that it's not the best program for doing what you wanted, but I think, for now, it is a acceptable one).</p>\n<pre><code>import os\n\ntest_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n\n\ndef clear_screen():\n '''\n clearing the screen\n '''\n os.system(&quot;clear&quot;)\n\n\ndef display_board(board_cords):\n '''\n display the board\n board_cords = list(left to right from top to bottom)\n '''\n line = '-'*40\n for i in range(0, len(board_cords), 3):\n print(&quot;\\t|\\t\\t|&quot;)\n print(f&quot;{board_cords[i]}\\t|\\t{board_cords[i + 1]}\\t|\\t{board_cords[i + 2]}&quot;)\n print(line)\n\n\ndef check_player_input():\n &quot;&quot;&quot;\n Gets an integer between 0 and 10 and calls `player_input` by that\n &quot;&quot;&quot;\n while True:\n try:\n temp = int(input(&quot;Enter a position: &quot;))\n if 0 &lt;= temp &lt; 10:\n break\n else:\n print('Sorry the input is not in range [0-9].')\n except:\n print(&quot;Input is not a number&quot;)\n player_input(temp)\n\n\ndef player_input(player_in):\n result = place_marker(test_board, 'X', player_in)\n clear_screen()\n display_board(result)\n if check_win(test_board, 'X'):\n print(&quot;You won&quot;)\n else:\n check_player_input()\n\ndef place_marker(board, marker, position):\n board[position] = marker\n return board\n\n\ndef check_win(board, marker):\n if board[0] == board[1] == board[2] == marker:\n return True\n if board[0] == board[3] == board[6] == marker:\n return True\n if board[0] == board[4] == board[8] == marker:\n return True\n if board[2] == board[5] == board[8] == marker:\n return True\n if board[6] == board[7] == board[8] == marker:\n return True\n if board[2] == board[4] == board[6] == marker:\n return True\n return False\n\n\nif __name__ == &quot;__main__&quot;:\n display_board(test_board)\n check_player_input()\n</code></pre>\n<p>Two other things: 1. your logic for winning is not complete. 2. search about the <code>if __name__ == &quot;__main__&quot;:</code>, it's better to use that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T19:03:40.300", "Id": "482440", "Score": "0", "body": "Thank you so much it was so helpful for me to learn\nI edited my code and I'm so craved to see my code is now much better\nIt's still uncompleted but I had good moves\nCan you tell me if my code is better or not?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T18:07:12.847", "Id": "245632", "ParentId": "245628", "Score": "2" } } ]
{ "AcceptedAnswerId": "245632", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T16:02:23.957", "Id": "245628", "Score": "1", "Tags": [ "python", "tic-tac-toe" ], "Title": "Tic Tac Toe in Python practice" }
245628
<p>I am trying to save a radiobutton string if it clicked. I am making a survey where I need to save a &quot;yes&quot; or &quot;no&quot; into a MYSQL table using volley. I am having a little trouble doing this and have tried to use the method below. Does anyone have any insight on how to do this? Right now I am</p> <p>Please find my code below:</p> <pre><code>private void MCIRadioSave() { GoToMain.setVisibility(View.VISIBLE); GoToJournal.setVisibility(View.VISIBLE); GoToMain.setVisibility(View.GONE); GoToJournal.setVisibility(View.GONE); if(yesBTN.isChecked()) { final String yes1 = this.yesBTN.getText().toString().trim(); } else { final String no1 = this.noBTN.getText().toString().trim(); } if(yesBTN2.isChecked()) { final String yes2 = this.yesBTN2.getText().toString().trim(); } else { final String no2 = this.noBTN2.getText().toString().trim(); } if(yesBTN3.isChecked()) { final String yes3 = this.yesBTN3.getText().toString().trim(); } else { final String no3 = this.noBTN3.getText().toString().trim(); } if(yesBTN4.isChecked()) { final String yes4 = this.yesBTN4.getText().toString().trim(); } else { final String no4 = this.noBTN4.getText().toString().trim(); } if(yesBTN5.isChecked()) { final String yes5 = this.yesBTN5.getText().toString().trim(); } else { final String no5 = this.noBTN5.getText().toString().trim(); } if(yesBTN6.isChecked()) { final String yes6 = this.yesBTN6.getText().toString().trim(); } else { final String no6 = this.noBTN6.getText().toString().trim(); } if(yesBTN7.isChecked()) { final String yes7 = this.yesBTN7.getText().toString().trim(); } else { final String no7 = this.noBTN7.getText().toString().trim(); } if(yesBTN8.isChecked()) { final String yes8 = this.yesBTN8.getText().toString().trim(); } else { final String no8 = this.noBTN8.getText().toString().trim(); } StringRequest stringRequest = new StringRequest(Request.Method.POST, MCI_SAVE, new Response.Listener&lt;String&gt;() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String success = jsonObject.getString(&quot;success&quot;); if (success.equals(&quot;1&quot;)) { Toast.makeText(checkin1.this, &quot;Thank you for completing your check in&quot;, Toast.LENGTH_SHORT).show(); GoToMain.setVisibility(View.VISIBLE); GoToJournal.setVisibility(View.VISIBLE); } else { Toast.makeText(checkin1.this, &quot;Register Failed&quot;, Toast.LENGTH_SHORT).show(); startActivity(new Intent(checkin1.this, LoginActivity.class)); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(checkin1.this, &quot;Register Error&quot; + e.toString(), Toast.LENGTH_SHORT).show(); GoToMain.setVisibility(View.VISIBLE); GoToJournal.setVisibility(View.VISIBLE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(checkin1.this, &quot;Register Error &quot; + error.toString(), Toast.LENGTH_SHORT).show(); Log.e(&quot;Gallery error =&gt;&quot;, error.toString()); GoToMain.setVisibility(View.VISIBLE); GoToJournal.setVisibility(View.VISIBLE); } }) { @Override protected Map&lt;String, String&gt; getParams() throws AuthFailureError { Map&lt;String, String&gt; params = new HashMap&lt;&gt;(); params.put(&quot;Q1Medical&quot;, yes1 || no1 ); params.put(&quot;Q2Safety&quot;, no2 || yes2 ); params.put(&quot;Q3Completing&quot;, no3 || yes3 ); params.put(&quot;Q4TP&quot;, no4 || yes4 ); params.put(&quot;Q5Supervisor&quot;, no5 || yes5 ); params.put(&quot;Q6English&quot;, no5 || yes5 ); params.put(&quot;Q7Hours&quot;, no6 || yes6 ); params.put(&quot;Q8Additional&quot;, no7 || yes7 ); params.put(&quot;Q8Additional&quot;, no8 || yes8 ); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } ``` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:43:48.490", "Id": "482435", "Score": "2", "body": "Welcome to Code Review! It sounds like this code isn't working to the best of your knowledge, which would not be in line with what is [on-topic](https://codereview.stackexchange.com/help/on-topic) here. When you have implemented the code feel free to [edit] your post to include it for a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:02:22.290", "Id": "482481", "Score": "0", "body": "(`save a radiobutton string when the button is clicked`?)" } ]
[ { "body": "<p>Your <code>yesX</code> / <code>noX</code> variables are local only to the if else block you declared them in.</p>\n<pre class=\"lang-java prettyprint-override\"><code>final String foo;\nif (yesBTN4.isChecked()) {\n foo = &quot;bar&quot;;\n} else if(noBTN4.isChecked()) {\n foo = &quot;barz&quot;;\n}\n</code></pre>\n<p>Which brings me to another choice you decided to make. How are you going to determine if you're passing <code>yes2</code> or <code>no2</code> into your database. That would require another check. Instead have one variable to store per question response. Noticed how I used one variable for both yes and no and it equals different things based on branch.</p>\n<p>Finally, there is no reason to call <code>trim()</code> on the the radiobutton <code>.getText()</code> because the text is typically what YOU specified it to be. So unless you are doing something crazy like <code>RadioButton rb5 = new RadioButton(&quot; Hello, World! &quot;);</code> there isn't a reason to make that method call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T19:18:13.773", "Id": "245635", "ParentId": "245630", "Score": "-1" } } ]
{ "AcceptedAnswerId": "245635", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T17:19:42.073", "Id": "245630", "Score": "-3", "Tags": [ "java", "strings", "mysql", "android", "hash-map" ], "Title": "I am trying to save a string to a MYSQL table from a radiobutton in java/Android studio" }
245630
<p>I was cleaning up some old code and came across this (it's to read input from a terminal):</p> <pre><code>static public int read_input_key() { /* F1 ESC O P [27 79 80] F2 ESC O Q [27 79 81] F3 ESC O R [27 79 82] F4 ESC O S [27 79 83] Up ESC [ A [27 91 65] Down ESC [ B [27 91 66] Left ESC [ D [27 91 68] Right ESC [ C [27 91 67] Home ESC [ 1 ~ [27 91 49 126] F5 ESC [ 1 5 ~ [27 91 49 53 126] F6 ESC [ 1 7 ~ [27 91 49 55 126] F7 ESC [ 1 8 ~ [27 91 49 56 126] F8 ESC [ 1 9 ~ [27 91 49 57 126] End ESC [ 4 ~ [27 91 52 126] Page-up ESC [ 5 ~ [27 91 53 126] Page-down ESC [6 ~ [27 91 54 126] Insert ESC [ 2 ~ [27 91 50 126] F9 ESC [ 2 0 ~ [27 91 50 48 126] F10 ESC [ 2 1 ~ [27 91 50 49 126] F11 ESC [2 2 ~ [27 91 50 50 126] F12 ESC [ 2 3 ~ [27 91 50 51 126] */ // try { if (System.in.available() != 0) { int c = System.in.read(); if (c == 27) { switch (System.in.read()) { case 79: switch (System.in.read()) { case 80: return VK_F1; case 81: return VK_F2; case 82: return VK_F3; case 83: return VK_F4; } case 91: switch (System.in.read()) { case 65: return VK_UP; case 66: return VK_DOWN; case 68: return VK_LEFT; case 67: return VK_RIGHT; case 49: { switch (System.in.read()) { case 126: return VK_HOME; case 53: return System.in.read() == 126 ? VK_F5 : 0; case 55: return System.in.read() == 126 ? VK_F6 : 0; case 56: return System.in.read() == 126 ? VK_F7 : 0; case 57: return System.in.read() == 126 ? VK_F8 : 0; } } case 52: return System.in.read() == 126 ? VK_END : 0; case 53: return System.in.read() == 126 ? VK_PAGE_UP : 0; case 54: return System.in.read() == 126 ? VK_PAGE_DOWN : 0; case 50: { switch (System.in.read()) { case 126: return VK_INSERT; case 48: return System.in.read() == 126 ? VK_F9 : 0; case 49: return System.in.read() == 126 ? VK_F10 : 0; case 50: return System.in.read() == 126 ? VK_F11 : 0; case 51: return System.in.read() == 126 ? VK_F12 : 0; } } } } } else { return c; } } } catch (IOException e) { // restore terminal? e.printStackTrace(); } return 0; } </code></pre> <p>It work's fine, but I feel like it can be done really different. To explain the long comment (I should atleast refactor that), this for example:</p> <pre><code> F1 ESC O P [27 79 80] </code></pre> <p>Means when you press the F1 key you will get the sequence ESC O P, which is represented by the following ascii keys, 27 79 80.</p>
[]
[ { "body": "<p>I think you will be able to implement this in a cleaner way by representing the key codes as <em>data</em> instead of <em>control flow</em>. Not only will the resulting code be shorter, but it will be more abstract. If you need to add new sequences or support multiple sets of sequences, you will be able to use the same basic logic.</p>\n<p>More specifically, a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">trie</a> data structure is a good match for your problem. The mapping process is simple: start at the root, input a character, and follow the corresponding branch. If there is no branch, fail. This must be modified slightly to output the original character if it is the sequence does not start with 27.</p>\n<p>There is no trie in the Java collections framework, so you will have to build your own. The signature should be something like</p>\n<pre><code>class AsciiTrie {\n AsciiTrie[] children;\n int data;\n}\n</code></pre>\n<p>Given this data structure, your new algorithm is the following</p>\n<pre><code>private static int readInputKey(AsciiTrie t) {\n if (System.in.available() == 0) {\n return 0;\n }\n\n int c;\n int depth = 0;\n while (t != null) {\n try {\n c = System.in.read();\n } catch {\n // handle error properly\n }\n\n t = t.children[c];\n depth += 1;\n\n if (t.data != 0) {\n return t.data;\n }\n }\n\n if (depth == 1) {\n return c;\n } else {\n return 0;\n }\n}\n</code></pre>\n<p>I have not included code to build or populate the trie. But it is quite similar to traversal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:30:22.620", "Id": "245643", "ParentId": "245636", "Score": "3" } }, { "body": "<p>What would already improve this would be to use constants instead of numbers, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code> int c = System.in.read();\n if (c == VK_ESC) {\n\n switch (System.in.read()) {\n case VK_O:\n switch (System.in.read()) {\n case VK_P:\n return VK_F1;\n</code></pre>\n<p>That is, if the <code>VK_*</code> constants contain those, otherwise roll your own.</p>\n<hr />\n<p>Another solution would be to use a class to represent each key sequence and test whether the pressed keys match any of that. Something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class KeySequence {\n protected int key = 0;\n protected int[] sequence = null;\n \n public KeySequence(int key, int... sequence) {\n super();\n \n // TODO: Validate key and sequence\n \n this.key = key;\n this.sequence = sequence;\n }\n \n public int getKey() {\n return key;\n }\n \n public int[] getSequence() {\n return sequence;\n }\n \n public boolean matches(int[] keys, int keyCount) {\n if (keyCount &lt; sequence.length) {\n // Can't match, too few keys.\n return false;\n }\n \n for (int index = 0; index &lt; sequence.length; index++) {\n if (sequence[index] != keys[index]) {\n return false;\n }\n }\n \n // keys started with sequence, so it matches.\n return true;\n }\n}\n</code></pre>\n<p>With this your comment at the start of the function becomes logic:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;KeySequence&gt; keySequences = new ArrayList();\nkeySequences.add(new KeySequence(VK_F1, VK_ESC, VK_O, VK_P));\nkeySequences.add(new KeySequence(VK_F2, VK_ESC, VK_O, VK_Q));\n// ...\n</code></pre>\n<p>And then, you just gather keystrokes from the terminal and test whether or not a <code>KeySequence</code> matches:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int[] keyBuffer = new int[16];\nint keyCount = 0;\n\nwhile ((keyBuffer[keyCount++] = System.in.read()) &gt;= 0) {\n for (KeySequence keySequence : keySequences) {\n if (keySequence.matches(keyBuffer, keyCount)) {\n return keySequence.getKey();\n }\n }\n \n if (keyCount &gt;= keyBuffer.length) {\n // TODO Handle that we've read too many keys.\n }\n \n if (keyCount &gt;= MAX_KEYS_IN_SEQUENCE) {\n // TODO Handle that we can't find anything.\n }\n}\n</code></pre>\n<p>Error handling needs to be extended.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:26:48.130", "Id": "245664", "ParentId": "245636", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T20:10:33.097", "Id": "245636", "Score": "2", "Tags": [ "java", "shell" ], "Title": "Reading input keys from a shell" }
245636
<p>The previous code on <a href="https://codereview.stackexchange.com/questions/245628/tic-tac-toe-in-python-practice/245632#245632">codereview</a></p> <p>I'm quite novice here so apologies for any silly mistake in advance</p> <p>I've been writing a simple tic tac toe game which is a part of my course in udemy</p> <p>Since this is my first project, I want to do my best in order to learn new things besides learning how to code better. Generally, I want to optimize my code as much as possible.</p> <p>Can anyone help me with this?</p> <pre class="lang-py prettyprint-override"><code># Tic Tac Toe # 17 July 2020 import os test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] player_input_num = 0 # numbers of inputs entered by player player_num = 0 won = False marker = 'X' def clear_screen(): os.system(&quot;clear&quot;) def display_board(board_cords): ''' display the board board_cords = list(left to right from top to bottom) ''' line = '-'*40 for counter in range(0, len(board_cords), 3): print(&quot;\t|\t\t|&quot;) print( f&quot;{board_cords[counter]}\t|\t{board_cords[counter+1]}\t|\t{board_cords[counter+2]}&quot;) print(line) counter += 3 # go to next row def check_player_input(number): if number &lt; 10 and number &gt;= 0: # checking the range return True else: print('Sorry the input is not in range [0-9] .') return False def player_input(player_in): global player_input_num # access to player_input_num if player_input_num &gt;= 2: # check if the position is free to use if check_capacity(test_board, player_in): result = place_marker(test_board, 'X', player_in) clear_screen() display_board(result) if check_win(test_board, marker): print(&quot;You Won!&quot;) global won won = True else: print(&quot;The current position is occupied.&quot;) else: if check_capacity(test_board, player_in): result = place_marker(test_board, 'X', player_in) clear_screen() display_board(result) player_input_num += 1 else: print(&quot;The current position is occupied.&quot;) def check_capacity(board, position): ''' Check if the current position is free to use. ''' return board[position] == ' ' def place_marker(board, marker, position): ''' Replace the position with a marker ''' board[position] = marker return board def check_win(board, marker): ''' Check if the current game is finished ''' if board[0] == board[1] == board[2] == marker: return True if board[0] == board[3] == board[6] == marker: return True if board[0] == board[4] == board[8] == marker: return True if board[2] == board[5] == board[8] == marker: return True if board[6] == board[7] == board[8] == marker: return True if board[2] == board[4] == board[6] == marker: return True return False def wanna_play(): answer = input(&quot;Wanna play again? (Y or N)&quot;) return answer # Main display_board(test_board) while True: while won == False: try: # checking if input is int player_num = int(input(&quot;Enter a position: &quot;)) except: print(&quot;Input is not a number&quot;) continue if check_player_input(player_num): player_input(player_num) if wanna_play() in ['y', 'Y', 'n', 'N']: print(&quot;something&quot;) else: print(&quot;Invalid input.&quot;) # print(&quot;Thanks for playing :)&quot;) </code></pre> <p>Note that code is working, I just want to know other ways of doing it and optimize it overalls.</p>
[]
[ { "body": "<p>Instead of using indices from 0 to 9, change the way you store your board to be a 3x3 list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>board = list([[0] * 3] * 3)\n&quot;&quot;&quot;\n1 | 2 | 3\n4 | 5 | 6\n7 | 8 | 9\n&quot;&quot;&quot;\n</code></pre>\n<p>This will allow you to come back to it and add a GUI.\nIt also becomes easier for anyone reading the code to understand what's happening visually.</p>\n<p>Next is your printout of the board. Join will be your friend here.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for row in board:\n printout = &quot;\\t|\\t&quot;.join(str(element) for element in row)\n print(printout) # this can be reduced to a single line if you want.\n</code></pre>\n<h3>ranges</h3>\n<p><code>range()</code> accepts 3 variables. START, STOP and INCREMENT AMOUNT</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(0, 9, 3):\n\n</code></pre>\n<p>You can also reverse with negative values</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(9, 0, -1):\n</code></pre>\n<p>or</p>\n<pre class=\"lang-py prettyprint-override\"><code>for row in board[::-1]:\n</code></pre>\n<h3>if statements</h3>\n<p>In math class you know how you were able to write a &lt; x &gt; b? You can do that in python without requiring <code>and</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if 0 &lt;= number &gt; 10:\n</code></pre>\n<p>Then there is checking the board state if someone has won.\nYour current approach requires a lot of coding and can't be expanded on quickly</p>\n<p>There are a few different approaches you can do with this. All will &quot;work.&quot;</p>\n<p>First the rows</p>\n<pre class=\"lang-py prettyprint-override\"><code>for row in board:\n if len(set(row)) == 1:\n return True\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>for row in board:\n if all(element == row[0] for element in rows):\n return True\n</code></pre>\n<p>Diagonals next (I would use a tempory dummy variable for <code>len(board)</code> to increase readability. -&gt; <code>_ = len(board)</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>if len(set(board[i][i] for i in range(len(board)) == 1:\n return True\nif len(set(board[i][len(board)-i-1] for i in range(len(board)) == 1:\n return True\n</code></pre>\n<p>The columns can be a trickier but transposing would probably be the most pythonic way to approach it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>board_T = [list(column) for column in zip(board)]\n</code></pre>\n<p>This will allow you to call the rows again and check to see if someone won.</p>\n<p>It should be noted that the return values for the winner state could return the <strong>PLAYER</strong> of rather than <code>True</code> or <code>False</code>. Python sees 0, None, Empty iterables, and False as False in an if statement.</p>\n<p>I also noticed you didn't follow a lot of the advice given to you in the original post. You are still lacking an <code>if __name__ == &quot;__main__&quot;:</code> statement</p>\n<pre class=\"lang-py prettyprint-override\"><code>def playTicTacToe():\n display_board(test_board)\n ...\n\n...\nif __name__ == &quot;__main__&quot;:\n playTicTacToe()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:16:59.840", "Id": "482452", "Score": "0", "body": "Thank you so much for your amazing help. But now I faced a problem. \nWhen I changed my code and do everything before **range** in your answer, the output is :\n`[0, 0, 0] | [0, 0, 0] | [0, 0, 0]\nEnter a position: `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:18:03.167", "Id": "482453", "Score": "0", "body": "And Yes. I searched for ___name___ thing but i just couldn't find how to use it in my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T23:08:01.137", "Id": "482456", "Score": "0", "body": "@Darklight I added a bit to the end to help with the name == main bit. Also, I had a typo at `board =` it should be `board = list([[0] * 3] * 3])`, sorry about that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T18:13:20.530", "Id": "482523", "Score": "0", "body": "@david_fisher Thanks for your help. I changed the `test_board` variable to `test_board = list([[' '] * 3] * 3)` but now the function `check_capacity()` always returns false" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T18:50:03.903", "Id": "482525", "Score": "0", "body": "You need to convert your position to `y, x = position // 3, position % 3` and then run the check `return board[y][x] == ' '` Btw, you'll also need to have these values for when you place your 'X' and 'O'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T19:20:24.767", "Id": "482526", "Score": "0", "body": "@david_fisher So i guess it would make the code more unreadable, wouldn't it? I think my code was better for optimization. Please correct me if I'm wrong :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T19:33:35.917", "Id": "482528", "Score": "0", "body": "If you were looking for optimization, you wouldn't be writing it in python. You use python for maintainability, readability, and the ease in writing and deploying. If you wanted to optimize it completely, you'd build it in C and make every board state static. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T19:35:24.540", "Id": "482529", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110768/discussion-between-darklight-and-david-fisher)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T21:56:56.847", "Id": "245641", "ParentId": "245639", "Score": "2" } } ]
{ "AcceptedAnswerId": "245641", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T20:34:45.160", "Id": "245639", "Score": "0", "Tags": [ "python", "tic-tac-toe" ], "Title": "Tic Tac Toe in Python practice 2" }
245639
<p>I have improved my code since <a href="https://codereview.stackexchange.com/q/243524/141885">the last time asking for its review</a>.</p> <p>I'd like to know if it is up to the current standards.</p> <pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); error_reporting(-1); require '../../config/connect.php'; $con = new mysqli(...$dbCredentials); $first_name = htmlspecialchars(trim(strip_tags(filter_var($_POST['first_name'], FILTER_SANITIZE_STRING)))); $last_name = htmlspecialchars(trim(strip_tags(filter_var($_POST['last_name'], FILTER_SANITIZE_STRING)))); $username = htmlspecialchars(trim(strip_tags(filter_var($_POST['username'], FILTER_SANITIZE_STRING)))); $email = htmlspecialchars(trim(strip_tags(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)))); $pw = ''; $pw2 = ''; $friend_array = ','; $errors = []; if (empty($_POST[&quot;first_name&quot;])) { $errors[] = &quot;Fill in first name to sign up&quot;; } if (empty($_POST[&quot;last_name&quot;])) { $errors[] = &quot;Fill in last name to sign up&quot;; } if (empty($_POST[&quot;username&quot;])) { $errors[] = &quot;Fill in username to sign up&quot;; } if (empty($_POST[&quot;email&quot;])) { $errors[] = &quot;Fill in username to sign up&quot;; } if (empty($_POST[&quot;pw&quot;])) { $errors[] = &quot;Fill in password to sign up&quot;; } if (empty($_POST[&quot;pw2&quot;])) { $errors[] = &quot;Confirm password to sign up&quot;; } if (!$errors) { //An SQL statement template is created and sent to the database $check_username = $con-&gt;prepare(&quot;SELECT username FROM users WHERE username=?&quot;); // This function binds the parameters to the SQL query and tells the database what the parameters are. $check_username-&gt;bind_param(&quot;s&quot;, $_POST['username']); // the database executes the statement. $check_username-&gt;execute(); $row = $check_username-&gt;get_result()-&gt;fetch_assoc(); if ($row &amp;&amp; $row['username'] == $_POST['username']) { $_SESSION['error'] = '&lt;b&gt;&lt;p style=&quot;color: #000000; font-size: 25px; top: 34%;right: 30%;position: absolute;&quot;&gt;Username exists&lt;/p&gt;&lt;/b&gt;'; header('Location: ../../register.php'); exit(); } } if (!$errors) { //An SQL statement template is created and sent to the database $check_email = $con-&gt;prepare(&quot;SELECT email FROM users WHERE email=?&quot;); // bind_param binds the parameters to the query and tells the DB what the parameters are. $check_email-&gt;bind_param(&quot;s&quot;, $email); // the database executes the statement. $check_email-&gt;execute(); $row = $check_email-&gt;get_result()-&gt;fetch_assoc(); if ($row &amp;&amp; $row['email'] == $_POST['email']) { $_SESSION['error'] = '&lt;b&gt;&lt;p style=&quot;color: #000000; font-size: 25px; top: 34%;right: 30%;position: absolute;&quot;&gt;E-mail exists&lt;/p&gt;&lt;/b&gt;'; header('Location: ../../register.php'); exit(); } } if ($_POST['pw'] !== $_POST['pw2']) { $_SESSION['error'] = '&lt;b&gt;&lt;p style=&quot;color: #000000; font-size: 25px; top: 34%;right: 30%;position: absolute;&quot;&gt;The passwords do not match.&lt;/p&gt;&lt;/b&gt;'; header('Location: ../../register.php'); exit(); } if (!$errors) { $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, array('cost' =&gt; 14)); $stmt = $con-&gt;prepare(&quot;INSERT INTO users (first_name, last_name, username, email, pw, friend_array) VALUES (?, ?, ?, ?, ?, ?)&quot;); $stmt-&gt;bind_param(&quot;ssssss&quot;, $_POST['first_name'], $_POST['last_name'], $_POST['username'], $_POST['email'], $pw, $friend_array); $stmt-&gt;execute(); $_SESSION['error'] = '&lt;b&gt;&lt;p id=&quot;loginnow&quot;&gt;You can now login.&lt;/p&gt;&lt;/b&gt;'; header('Location: ../../register.php'); exit(); } else { // The foreach construct provides an easy way to iterate over arrays. foreach ($errors as $error) { echo &quot;$error &lt;br /&gt; \n&quot;; } $_SESSION['error'] = '&lt;b&gt;&lt;p style=&quot;color: #fff; font-size: 25px; top: 15%;right: 30%;position: absolute;&quot;&gt;An error occurred.&lt;/p&gt;&lt;/b&gt;'; header('Location: ../../register.php'); exit(); } </code></pre>
[]
[ { "body": "<ol>\n<li>Regarding setting up your database connection and error reporting, please refer to <a href=\"https://codereview.stackexchange.com/a/243749/141885\">this recent post from YCS</a>.</li>\n<li>I'm noticing that you are unconditionally mutating several of the user submitted values. If you have any concerns that someone might legitimately access this page without submitting these variables, then you should have a condition to determine if the script should be used as a signup attempt or merely bounced. Otherwise, if the only reason that a legitimate user will be accessing this page is via a signup attempt, then I would say you should remove the <code>empty()</code> calls and use a function-less falsey check (e.g. <code>if (!$_POST[&quot;first_name&quot;]) {</code>) because if the variables are guaranteed to be set, then <code>empty()</code> is doing unnecessary work.</li>\n<li>Be sure that you are calling the right encoding function for the right reason and at the right time. In short, you should not be htmencoding values before they go into the db, you should only be encoding strings just before printing them to screen. Please read: <a href=\"http://htmlentities()%20vs.%20htmlspecialchars()\" rel=\"nofollow noreferrer\">htmlentities() vs. htmlspecialchars()</a> and <a href=\"https://stackoverflow.com/q/2077576/2943403\">PHP &amp; mySQL: When exactly to use htmlentities?</a></li>\n<li>I don't see any reason to declare these empty strings as variables: <code>$pw = '';</code> and <code>$pw2 = '';</code>. I also think it is poor naming convention to declare string data as a variable including the word <code>array</code> such as <code>$friend_array = ',';</code>.</li>\n<li>I think <code>if ($_POST['pw'] !== $_POST['pw2']) {</code> should be moved up the script with the other validators. You don't want to do any db fetching until the user input has clear all basic hurdles.</li>\n<li>The secondary condition in <code>if ($row &amp;&amp; $row['email'] == $_POST['email']) {</code> is nonsense. You have already required this expression to be <code>true</code> in your sql. There is no benefit in the redundant check in php. In fact, because you only need to check if the username exists in the db, you should probably just write a COUNT() query. See this suggestion: <a href=\"https://codereview.stackexchange.com/a/245536/141885\">Return row count from mysqli prepared statement</a></li>\n<li>I would not be bloating my <code>$_SESSION</code> array with the markup that you are piling into <code>$_SESSION['error']</code>. Trim all the fat and just keep the &quot;white meat&quot;: <code>$_SESSION['error'] = 'E-mail exists'</code>. You should be moving all of your styling to an external stylesheet anyhow. Drop that <code>&lt;b&gt;</code> tag and just use styling. Never use more html markup than you need to.</li>\n<li>I don't like the idea of saving a default value of a comma in the <code>friend_array</code> column. If they have no friends, then the value should be <code>NULL</code> (or an empty string if you must). That said, if you are unconditionally hardcoding a value to be INSERTed into every row, then that argues that you should be modifying the table structure and declaring the default value for <code>friends_array</code> as <code>','</code>. This way you don't even need to declare the <code>$friends_array</code> variable or bloat your prepared statement / binding with the extra syntax.</li>\n<li>&quot;<em>You can now login.</em>&quot; is not an error, so it is inappropriate to write that data into <code>$_SESSION['error']</code>. The next developer is going to be scratching their head at your decision to write conflicting data into certain SESSION elements. Create better naming convention and/or change your SESSION structure.</li>\n<li>I don't like that you are printing the <code>$errors</code> then redirecting the user. Please read this: <a href=\"https://stackoverflow.com/q/7066527/2943403\">Redirect a user after the headers have been sent</a> Not only will <code>header()</code> prompt problems after you have printed to screen, it doesn't make a lot of sense if you aren't going to let them see the errors that are printed. I'd say it makes better sense to push all of the errors into <code>$_SESSION['errors']</code>, then after the redirect you should <code>echo implode(&quot;&lt;br&gt;\\n&quot;, $_SESSION['errors']);</code> in whatever format will be attractive to the user.</li>\n<li>I do like that you are sanitizing the input heavily and that you are using <code>$_POST</code> to transfer the form data to a database writing process.</li>\n</ol>\n<hr />\n<p>A late note... if the <code>friends_array</code> is a collection of user ids/usernames, then a First Normal Form (1NF) rule should be implemented. Ditch the <code>friends_array</code> column. Create a new table called <code>friends</code> with separate rows for each relationship. The functional benefits are many.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T16:21:02.780", "Id": "482517", "Score": "0", "body": "If you don't mind, can you show me some links that made you such an expert ? I'm trying to find some things but whenever I think I learned, someone tells me it's wrong. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T22:18:41.573", "Id": "482541", "Score": "1", "body": "I am a self-taught php developer for over 13 years now. I am not comfortable with the label \"expert\". This is a bit triggering for me. I don't think I'll ever call myself an expert or even a Senior Dev because it seems no matter how much I learn there is always an enormous amount that I haven't learned. I have given my honest review and included some links. With all due respect I don't really \"feel like\" or \"want to get into the habit of\" defending every bullet point with a hyperlink. Expect a career of life-long-learning. Find multiple educational Stack Exchange users and digest their wisdom." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T22:26:48.183", "Id": "482542", "Score": "0", "body": "Thanks a lot. I'll start with you" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T04:01:23.617", "Id": "245651", "ParentId": "245642", "Score": "3" } }, { "body": "<p>First of all you are doing great. This code is already above the average.</p>\n<p>But of course it can be improved. The process is eternal, actually. So don't forget to post the next iteration as well :)</p>\n<p>The first thing that catches my eye is inconsistent user level error reporting. Why some\nerror messages are shown as is and some are lavishly decorated and sent through a session variable? I would stick with the former. There is no point a redirection. Just show all errors in place, then show the form and fill all the entered values in for the better usability.</p>\n<p>Besides, PHP code should never contain any HTML. Imagine a designer would create a nifty icon to be shown next to the error message. Are you going to edit every occurrence of the error message in your code? All the decorations must be added at the output time, not at the definition. Whatever way you choose, remove all HTML from the error message. Add it at output</p>\n<p>Another matter is redundant input treatment. Why both <code>strip_tags()</code> and <code>htmlspecialchars()</code>? Why <code>empty()</code> for a variable which is deliberately set? For the existing variable you can use just <code>if (!$var)</code>. <code>empty()</code> should be used only if you want to know whether a variable is not set or has a falsey value.</p>\n<p>Also, using $_POST when you already assigned the validated values to variables is <strong>flat out inconsistent.</strong></p>\n<p><code>htmlspecialchars()</code> should be used on the output, not input.</p>\n<p>Besides, for such a specific data as user information, you shouldn't sanitize it, but rather <strong>validate</strong> it instead, checking for the improper input and giving a warning. Hence, instead of sanitization, I would just assign input values to variables and then validate them</p>\n<pre><code>$first_name = $_POST['first_name'] ?? '', \n$last_name = $_POST['last_name'] ?? '', \n$email = $_POST['email'] ?? '';\n\nif (!trim($first_name)) {\n $errors[] = &quot;Fill in first name to sign up&quot;;\n}\nif (!ctype_alnum($first_name)) {\n $errors[] = &quot;Invalid first name, it only may contain letters or digits&quot;;\n}\n</code></pre>\n<p>For email and password it is going to be a bit different, as for the password we don't want to verify the contents at all and for the email we have a distinct validation function</p>\n<pre><code>if (!trim($pw)) {\n $errors[] = &quot;Fill in password to sign up&quot;;\n}\nif (!trim($pw2)) {\n $errors[] = &quot;Confirm password to sign up&quot;;\n}\nif (!trim($email)) {\n $errors[] = &quot;Fill in email to sign up&quot;;\n}\nif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {\n $errors[] = &quot;Invalid email&quot;;\n}\n</code></pre>\n<p>On a side note, consider to get rid of the username. If you think of it, email just duplicates its functionality. And having two entities to serve for the same purpose (to identify a user) adds nothing but a confusion. Only if you are going to show usernames somewhere, it makes sense to keep them. But given there is a name, it makes sense to use it as a display name.</p>\n<p>Another point is redundancy again. As you may have noticed, mysqli prepared statements are a little verbose, repeating the same prepare/bind execute over and over again.</p>\n<p>Well, for practice, it's indeed a good thing to write some statements manually, just to get the feel, to see how it works. But for the real life application it looks redundant. Why not to write a simple function to encapsulate all the routine inside?</p>\n<p>I wrote a <a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"nofollow noreferrer\">mysqli helper function</a> exactly for the purpose.</p>\n<p>Now let's see how we can greatly reduce the amount of code.</p>\n<pre><code>if (!$errors) {\n $sql = &quot;SELECT email FROM users WHERE email=?&quot;;\n $row = prepared_query($con, $sql, [$email])-&gt;get_result()-&gt;fetch_row();\n if ($row) {\n $errors[] = 'E-mail exists';\n }\n}\n</code></pre>\n<p>Just like @mick said, the following line is absolutely redundant.</p>\n<pre><code>if ($row &amp;&amp; $row['email'] == $_POST['email']) {\n</code></pre>\n<p>in reality, it could (and should) be shortened to just</p>\n<pre><code> if ($row) {\n</code></pre>\n<p>because <code>$row</code> already serves as a flag. It is empty when no such email is found and not empty otherwise. No need for anything else.</p>\n<p>The same function could be used for the insert too,</p>\n<pre><code>$sql = &quot;INSERT INTO users (first_name, last_name, email, pw, friend_array)\n VALUES (?, ?, ?, ?, ?, ?)&quot;;\nprepared_query($con, $sql, [$first_name, $last_name, $email, $pw, $friend_array]);\n</code></pre>\n<p>Don't you like how meaningful and tidy your code becomes at once?</p>\n<p>For the convenience, you can put this function's definition <a href=\"https://phpdelusions.net/mysqli/mysqli_connect#credentials_file\" rel=\"nofollow noreferrer\">in the same file with mysqli connection code</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:48:51.637", "Id": "482638", "Score": "0", "body": "`prepared_query` Is the same a a normal mysqli prepared statement ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:03:26.517", "Id": "482668", "Score": "0", "body": "Well, the name, the description that says \"the same prepare/bind execute\" and the [code](https://phpdelusions.net/mysqli/simple#code) aren't convincing enough?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T06:09:45.943", "Id": "245686", "ParentId": "245642", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:00:04.663", "Id": "245642", "Score": "1", "Tags": [ "php", "mysql", "mysqli" ], "Title": "Receiving a user's registration submission and inserting row into database" }
245642
<p>Not sure if I am overcomplicating the requirement but this is what I need (for simplicity I will show a the <code>List&lt;Map&lt;String, Object&gt;&gt;</code> as a <code>JSON</code>):</p> <pre><code>[ { &quot;project&quot;: &quot;Project1&quot;, &quot;workType&quot;: &quot;Dev&quot;, &quot;taskTitle&quot;: &quot;Dev Title 1&quot;, &quot;effort&quot;: 150 }, { &quot;project&quot;: &quot;Project1&quot;, &quot;workType&quot;: &quot;Dev&quot;, &quot;taskTitle&quot;: &quot;Dev Title 2&quot;, &quot;effort&quot;: 200 }, { &quot;project&quot;: &quot;Project1&quot;, &quot;workType&quot;: &quot;QA&quot;, &quot;taskTitle&quot;: &quot;QA Title 1&quot;, &quot;effort&quot;: 50 }, { &quot;project&quot;: &quot;Project1&quot;, &quot;workType&quot;: &quot;QA&quot;, &quot;taskTitle&quot;: &quot;QA Title 2&quot;, &quot;effort&quot;: 25 }, { &quot;project&quot;: &quot;Project2&quot;, &quot;workType&quot;: &quot;Dev&quot;, &quot;taskTitle&quot;: &quot;Dev Title 3&quot;, &quot;effort&quot;: 300 }, { &quot;project&quot;: &quot;Project2&quot;, &quot;workType&quot;: &quot;Dev&quot;, &quot;taskTitle&quot;: &quot;Dev Title 4&quot;, &quot;effort&quot;: 300 }, { &quot;project&quot;: &quot;Project2&quot;, &quot;workType&quot;: &quot;QA&quot;, &quot;taskTitle&quot;: &quot;QA Title 3&quot;, &quot;effort&quot;: 125 }, { &quot;project&quot;: &quot;Project2&quot;, &quot;workType&quot;: &quot;QA&quot;, &quot;taskTitle&quot;: &quot;QA Title 4&quot;, &quot;effort&quot;: 125 } ] </code></pre> <p>I want to process a HashMap which is equivalent to the above to produce a HashMap equivalent to below:</p> <pre><code>[ { &quot;project&quot;: &quot;Project1&quot;, &quot;effort&quot;: 425, // sum of all efforts &quot;types&quot;: [ { &quot;workType&quot;: &quot;Dev&quot;, &quot;effort&quot;: 350 // sum of all effort where workType == Dev }, { &quot;workType&quot;: &quot;QA&quot;, &quot;effort&quot;: 75 // sum of all effort where workType == QA } ] }, { &quot;project&quot;: &quot;Project2&quot;, &quot;effort&quot;: 850, // sum of all efforts &quot;types&quot;: [ { &quot;workType&quot;: &quot;Dev&quot;, &quot;effort&quot;: 600 // sum of all effort where workType == Dev }, { &quot;workType&quot;: &quot;QA&quot;, &quot;effort&quot;: 250 // sum of all effort where workType == QA } ] } ] </code></pre> <p>This is the starting point of my attempt:</p> <pre><code>transformedData.stream().collect( Collectors.groupingBy( m -&gt; m.get(&quot;project&quot;), Collectors.mapping( m2 -&gt; m2, Collectors.toList() ) ) ); </code></pre> <p>Unfortunately I am a bit stuck on how to proceed..</p> <p>UPDATE: The below gives me the expected result but it does not look performance friendly at all..</p> <pre><code>Map&lt;Object, List&lt;Map&lt;String, Object&gt;&gt;&gt; appGrouping = transformedData.stream().collect( Collectors.groupingBy( m -&gt; m.get(&quot;project&quot;), Collectors.mapping(m2 -&gt; m2, Collectors.toList()) ) ); List&lt;Map&lt;String, Object&gt;&gt; finalData = new ArrayList&lt;&gt;(); appGrouping.forEach((k,v) -&gt; { Map&lt;String, Object&gt; data = new HashMap&lt;&gt;(); data.put(&quot;project&quot;, k); data.put(&quot;types&quot;, new ArrayList&lt;&gt;()); v.stream().collect( Collectors.groupingBy( m -&gt; m.get(&quot;workType&quot;), Collectors.summingDouble(m -&gt; getDoubleVal(m.get(&quot;effort&quot;))) ) ).forEach((k2,v2) -&gt; { Map&lt;String, Object&gt; data2 = new HashMap&lt;&gt;(); data2.put(&quot;workType&quot;, k2); data2.put(&quot;effort&quot;, v2); getFromMap(data, &quot;types&quot;, List.class).add(data2); // this is a util method I wrote to get a value from a map Double totalEffort = Objects.requireNonNull(getFromMap(data, &quot;effort&quot;, Double.class)) + v2; data.put(&quot;effort&quot;, totalEffort); }); finalData.add(data); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T21:01:02.483", "Id": "482459", "Score": "1", "body": "It can be done. But wouldn't it be better to have a `Project` class and a `WorkType` class with getters for the fields? Then you can have a `List<Project>` which, based on the above, would have two instances." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T21:06:10.513", "Id": "482460", "Score": "0", "body": "Thanks for the reply.. You are correct but the reason I did not map it to a POJO is because the method that does this should be sort of generic as in the group by keys (in this scenario its `project` and `workType` is parameterized) and I don't want to use reflection or anything like that yet.. However, if its simpler, it would be great if you could show me the way you would do it. Even if you use POJO's its fine. I'll do my best to translate it to my usecase" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T21:08:53.500", "Id": "482461", "Score": "0", "body": "I will also post an update to the question soon with the current progress. Thanks for your time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:14:44.103", "Id": "482462", "Score": "0", "body": "You say *The below gives me 75% of the expected result* - What's in the missing 25%? And your question needs more focus; right now its goal is too broad/complex. Please edit your question to isolate the specific problem and the smallest amount of codein which the problem exists. The context (json etc) of your question seems irrelevant to your problem, which cold be described using POJO's, thus simlifying the problem statement and the code. See [MCVE](https://stackoverflow.com/help/minimal-reproducible-example)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:22:23.460", "Id": "482463", "Score": "0", "body": "@Bohemian hi the missing part was I was not getting sum of the grouped effort at the project level but I updated the question. Now the attempt I have shown gives me the expected result.. I dont know how to optimize it :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:26:11.893", "Id": "482464", "Score": "0", "body": "@Bohemian I showed the JSON because it will make it easier to visualize the problem I am having. Which is to group a List of Maps. I dont agree that the problem could be DESCRIBED using POJO since POJO is irrelevant to this question. However an answer could be given using POJO's which is fine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:26:55.123", "Id": "482465", "Score": "0", "body": "What do you mean exactly by \"optimization\"? eg Less code? Easier to read? Faster execution? Easier maintenance? Easier to test? Better style?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:31:10.837", "Id": "482466", "Score": "0", "body": "@Bohemian Faster execution is what I am hoping for. I am not all that knowledgeable on Java Streams and more particularly the `groupingBy` functionality. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:52:34.743", "Id": "482467", "Score": "0", "body": "@WJS Thanks for your effort, however if you read recent comments, OP *already* has it working. Now OP's focus has shifted to \"optimization\" - yet to be defined by OP - so I've asked OP to clarify and edit to bring more focus to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T22:54:40.960", "Id": "482468", "Score": "1", "body": "@Bohemian I found out streams was just to cumbersome (at least for me) But I did it in one pass using various `compute` constructs of map. I'll save my results and follow the question for changes in its status." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T23:05:22.383", "Id": "482469", "Score": "0", "body": "@Bohemian by optimization I hope for faster execution as I have stated in my comment from 30 mins ago at the time of posting this comment. That being said I would like to see the logic implemented by WJS. I have implemented a working model, yes, but I have posted in the hope of someone improving it or posting a better way of doing it. Hope this changes your mind and you reopen the question. Thanks :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T23:05:40.053", "Id": "482470", "Score": "0", "body": "@WJS thanks for your time :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T23:26:45.273", "Id": "482471", "Score": "0", "body": "@Bohemian so when looking at the code I posted do you not feel that it could be improved? Be it performance wise or better coding practices etc.? I know I said I want more performant code but honestly at this point, whatever gets this question reopened :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T13:39:00.137", "Id": "482511", "Score": "0", "body": "Please state what is the current run time complexity. Do you want a better solution in terms of run time complexity or in terms of milliseconds?" } ]
[ { "body": "<p>Here is one way to get it in a single pass.</p>\n<pre><code>Map&lt;String, Map&lt;String, Object&gt;&gt; tempMap = new HashMap&lt;String, Map&lt;String, Object&gt;&gt;();\n\ntransformedData.forEach(i -&gt; {\n Double currentEffort = (Double) i.get(&quot;effort&quot;);\n \n Map&lt;String, Object&gt; subMap = \n tempMap.computeIfAbsent((String)i.get(&quot;project&quot;), \n (k) -&gt; new HashMap&lt;String, Object&gt;(){{\n put(&quot;project&quot;, (String)i.get(&quot;project&quot;));\n put(&quot;effort&quot;, 0.0D);\n put(&quot;types&quot;, new HashMap&lt;String, Double&gt;());}});\n \n subMap.merge(&quot;effort&quot;, currentEffort, (o, n) -&gt; (Double)o + (Double)n);\n \n ((Map&lt;String, Double&gt;)subMap.get(&quot;types&quot;))\n .merge((String) i.get(&quot;workType&quot;), currentEffort, (o, n) -&gt; (Double)o + (Double)n);\n});\nList&lt;Map&lt;String, Object&gt;&gt; finalData = (List&lt;Map&lt;String, Object&gt;&gt;) tempMap.values();\n</code></pre>\n<p>The finalData object converted to JSON (using your data above as input) is the below. I've changed the types object from a list of maps to a map of workType to effort.</p>\n<pre><code>[\n {\n &quot;types&quot;: {\n &quot;QA&quot;: 250.0,\n &quot;Dev&quot;: 600.0\n },\n &quot;project&quot;: &quot;Project2&quot;,\n &quot;effort&quot;: 850.0\n },\n {\n &quot;types&quot;: {\n &quot;QA&quot;: 75.0,\n &quot;Dev&quot;: 350.0\n },\n &quot;project&quot;: &quot;Project1&quot;,\n &quot;effort&quot;: 425.0\n }\n]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T17:08:25.493", "Id": "245668", "ParentId": "245646", "Score": "1" } }, { "body": "<pre><code>Map&lt;Object, List&lt;Project&gt;&gt; result3 = projList.stream()\n .collect(Collectors.groupingBy(Project::getProject))\n .entrySet().stream().collect(\n Collectors.toMap(x -&gt; {\n int sumInt = x.getValue().stream().mapToInt(Project::getEffort).sum();\n return new Project(x.getKey(), sumInt);\n }\n ,\n Map.Entry::getValue));\n \n Map&lt;Object,Object&gt; returnValueMap = new HashMap&lt;&gt;();\n \n for(Map.Entry&lt;Object, List&lt;Project&gt;&gt; entry: result3.entrySet()) {\n returnValueMap.put(entry.getKey(), \n entry.getValue().stream().collect(Collectors.groupingBy(Project::getWorkType))\n .entrySet().stream().collect(\n Collectors.toMap(x -&gt; {\n int sumInt = x.getValue().stream().mapToInt(Project::getEffort).sum();\n \n return new Project(x.getKey(), sumInt);\n }, Map.Entry::getValue)));\n \n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T17:45:58.160", "Id": "483238", "Score": "1", "body": "Welcome to Code Review! 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. Please read [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/a/8404/120114)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T17:09:55.613", "Id": "245968", "ParentId": "245646", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T20:53:53.990", "Id": "245646", "Score": "5", "Tags": [ "java", "collections" ], "Title": "Java group list of maps by value and insert as grouped list" }
245646
<p>I've implemented a simple <code>Maybe</code> type around <code>std::function</code> that implements function composition where any function in the composition can fail (causing the entire composition to fail) - in essence, a Maybe monad where <code>operator&lt;&lt;</code> implements <code>bind</code>.</p> <p>For example,</p> <pre><code> // one binary function that cannot fail. std::function&lt;int(float, float)&gt; h = [](const float a, const float b) -&gt; int { return a * b; }; // a unary function that CAN fail. std::function&lt;std::optional&lt;int&gt;(int)&gt; g = [](const int c) -&gt; std::optional&lt;int&gt; { if (c &lt; 0) return std::nullopt; else return c; }; // another unary function that CAN fail. std::function&lt;std::optional&lt;bool&gt;(int)&gt; f = [](const int d) -&gt; std::optional&lt;bool&gt; { if (d &lt; 10) return true; else return std::nullopt; }; // compose f, g, and h auto G = Maybe(f) &lt;&lt; Maybe(g) &lt;&lt; Maybe(h); // evaluate the composition - this maps (float, float) -&gt; optional&lt;bool&gt; auto result = G(1.0, 7.0); // and check if the computation was successful if (result) std::cout &lt;&lt; &quot;Result: &quot; &lt;&lt; *result &lt;&lt; &quot;\n&quot;; else std::cout &lt;&lt; &quot;Computation failed!\n&quot;; </code></pre> <p>Here is my current implementation:</p> <pre><code>#include &lt;functional&gt; #include &lt;optional&gt; #include &lt;iostream&gt; template &lt;typename TReturn, typename... TArgs&gt; struct Maybe { /** * The (lifted) function that we evaluate. */ std::function&lt;std::optional&lt;TReturn&gt;(const std::optional&lt;TArgs&gt;...)&gt; eval_; /** * Lift a non-failable function into the Maybe monad. */ auto lift(std::function&lt;TReturn(const TArgs...)&gt; const&amp; f) { // construct a lambda that implements the Maybe monad. return [f](const std::optional&lt;TArgs&gt; ... args) -&gt; std::optional&lt;TReturn&gt; { if ((args &amp;&amp; ...)) return f(*(args)...); else return {}; }; } /** * Lift a (failable) function returning an optional into the Maybe monad. */ auto lift(std::function&lt;std::optional&lt;TReturn&gt;(const TArgs...)&gt; const&amp; f) { // this overload is currently necessary so that I can extract the TReturn // value type so that `eval_` doesn't pick up another layer of std::optional // i.e. std::optional&lt;std::optional&lt;int(float, float)&gt;&gt;. // construct a lambda that implements the Maybe monad. return [f](const std::optional&lt;TArgs&gt; ... args) -&gt; std::optional&lt;TReturn&gt; { if ((args &amp;&amp; ...)) return f(*(args)...); else return {}; }; } /** * Construct a Maybe from a std::function returning an optional. */ Maybe(std::function&lt;TReturn(TArgs...)&gt; const f) : eval_(lift(f)) {} /** * Construct a Maybe from a std::function returning an optional. */ Maybe(std::function&lt;std::optional&lt;TReturn&gt;(TArgs...)&gt; const f) : eval_(lift(f)) {} /** * Apply the Maybe to the given arguments. */ auto operator()(std::optional&lt;TArgs&gt; const... args) const { return this-&gt;eval_(args...); } /** * Compose the callable in `this` with the callable in `other`. * * @param other Another monadic filter instance. */ template &lt;typename TOReturn, typename... TOArgs&gt; auto operator&lt;&lt;(Maybe&lt;TOReturn, TOArgs...&gt; const&amp; other) const -&gt; Maybe&lt;TReturn, TOArgs...&gt; { // get references to the underlying lifted functions // capturing the Maybe instances into the lambda results in a seg-fault auto f = this-&gt;eval_; auto g = other.eval_; // construct the coposition lambda std::function&lt;std::optional&lt;TReturn&gt;(TOArgs...)&gt; fg = [=](TOArgs... args) -&gt; std::optional&lt;TReturn&gt; { return f(g(args...)); }; return fg; } }; // END: class Maybe </code></pre> <p>This is targeting C++17 only. Any and all feedback appreciated!</p> <p>There's currently some duplication in the constructors and the <code>lift</code> method so that I wrap functions that already return <code>std::optional</code> without being wrapped in a second layer of optional i.e. <code>std::optional&lt;std::optional&lt;...&gt;&gt;</code> which makes the composition impossible (I'm sure there is some template trickery that could make this work with just a single method and constructor).</p>
[]
[ { "body": "<p>First issue with this design is that it is going to be slow and non-optimizable. <code>std::function</code> has a couple of features that hide type and implementation and neither is easy to optimize nor cheap. If you make complex functions that run in milliseconds than it is of no problem at all but otherwise consider a different more efficient approach.</p>\n<p>Second issue, is that if a function returns <code>std::optional</code> and composed with function that accepts <code>std::optional</code> and does something non-trivial when <code>std::nullopt</code> is supplied then the <code>Maybe</code> composition will change output. I don't think that this is what uses desires.</p>\n<p>Also, the naming isn't good <code>Maybe</code>... come up with something more meaningful and intuitive.</p>\n<hr />\n<p>To deal with the first issue, first look for an inspiration to <code>std::bind</code> as one can see in the <a href=\"https://en.cppreference.com/w/cpp/utility/functional/bind\" rel=\"nofollow noreferrer\">cppreference</a> it doesn't return a <code>std::function</code> but an unspecified type. Why?</p>\n<p>One possible implementation is that it returns a lambda that calls the function with the given arguments. That's it. And in this way it is a see-through method which is easily convertible to <code>std::function</code> and other function/method wrappers. (To implement placeholders feature its complexity raises beyond that of just generating a trivial lambda function that forwards arguments.)</p>\n<p>Imagine what <code>std::bind</code> would generate if supplementing each argument was done via an operator and converting to a <code>std::function</code> each time - instead of the variadic template approach? That would be a disaster I assure you.</p>\n<p>For instance, <code>boost::format</code> uses operators to fill arguments while <code>fmt::format</code> relies on variadic template approach... and as a result <code>fmt::format</code> is considerably faster both in performance and in compilation time. (Can't blame <code>boost::format</code> as it was implemented and designed way before C++11)</p>\n<p>So it would be much better if you wrote a template function that generates a callable from a sequence of callable:</p>\n<pre><code>template&lt;typename... Collables&gt;\nauto compose_callables(Callables...){...}\n</code></pre>\n<p>This will also allow you to address the second issue about how to properly implement the &quot;optional&quot; feature: suppose you compose <code>f</code> with <code>g</code> to make <code>f(g)</code>. And input type of <code>f</code> is <code>Arg</code> and function <code>g</code> returns output <code>std::optional&lt;Arg&gt;</code> then abort the execution whenever the optional has no value. However, forward the argument as is when the function <code>f</code> accepts the same type that <code>g</code> returns even if it is an <code>std::optional</code> of something.</p>\n<p>To implement this properly you'll need to stretch some muscles with template meta programming and SFINEA. This is quite challenging for most C++ programmers. Wish you luck if you attempt to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T07:21:39.927", "Id": "245656", "ParentId": "245647", "Score": "1" } }, { "body": "<p>You have the exact same comment (<code>Construct a Maybe from a std::function returning an optional</code>) on two different constructors. I don't think the comment was necessary anyway. Both constructors should be <code>explicit</code>, to prevent implicit conversions.</p>\n<p>Using <code>return {}</code> instead of <code>return std::nullopt</code> strikes me as needless obfuscation. (In the same way, I wouldn't use <code>return {}</code> when I meant <code>return nullptr</code>.)</p>\n<hr />\n<p>Your use of const-qualified function <em>parameter</em> variables is an antipattern (see my blog post <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">&quot;<code>const</code> is a contract&quot;</a>). In this particular case, it prevents you from moving-out-of the parameters, which is exactly what you should want to do here:</p>\n<pre><code>static auto lift(std::function&lt;TReturn(TArgs...)&gt; f) {\n return [f = std::move(f)](std::optional&lt;TArgs&gt;... args) -&gt; std::optional&lt;TReturn&gt; {\n if ((args.has_value() &amp;&amp; ...)) {\n return f(std::move(*args)...);\n } else {\n return std::nullopt;\n }\n };\n}\n</code></pre>\n<p>You're actually very lucky that <code>std::function&lt;TReturn(const TArgs...)&gt;</code> and <code>std::function&lt;TReturn(TArgs...)&gt;</code> happen to be the same type! You use the two spellings inconsistently throughout this code. Stick to the simpler shorter one.</p>\n<hr />\n<p>It would probably make sense to try to provide an overload of <code>operator&lt;&lt;</code> taking rvalues on left and/or right, to avoid some copying.</p>\n<p>It's surprising that <code>operator&lt;&lt;</code> returns a <code>std::function&lt;...&gt;</code> instead of a <code>Maybe&lt;...&gt;</code>. I don't actually see what that buys you.</p>\n<hr />\n<p>As ALX23z said, it's unfortunate that you build everything around <code>std::function</code> instead of around arbitrary callables. For example, I couldn't write</p>\n<pre><code>auto f = [](int x) -&gt; std::optional&lt;int&gt; { return (x &lt; 10) ? x + 1 : std::nullopt; };\nauto g = [](int y) { return y * 2; };\nauto G = Maybe(f) &lt;&lt; Maybe(g);\nassert(G(5) == 12);\nassert(G(12) == std::nullopt);\n</code></pre>\n<p>As I write that, I realize that it's also pretty confusing to me that you picked <code>&lt;&lt;</code> to mean &quot;compose with.&quot; <a href=\"https://en.wikipedia.org/wiki/Function_composition\" rel=\"nofollow noreferrer\">Wikipedia tells me</a> that the notation I'm familiar with, <code>f ∘ g</code>, is also ambiguous — does it mean &quot;f(g(x))&quot; or &quot;g(f(x))&quot;? Well, I might pick something like</p>\n<pre><code>auto g_of_f_of_x = Maybe(f).then(g);\nauto f_of_g_of_x = Maybe(f).of(g);\n</code></pre>\n<p>so as to be completely unambiguous.</p>\n<hr />\n<p>Using <code>std::function</code> allowed you to cheat around one of the <a href=\"https://quuxplusone.github.io/blog/2018/06/12/perennial-impossibilities/#detect-the-first-argument-type-of-a-function\" rel=\"nofollow noreferrer\">perennial impossibilities of C++</a>: detecting a callable's &quot;argument types.&quot; This means you can't use your <code>Maybe</code> with generic lambdas or templates like <code>std::plus&lt;&gt;</code>. If I were writing it, I'd ditch that cheat and try to make it work for generic lambdas from the very beginning.</p>\n<p>You can see my worked solution <a href=\"https://godbolt.org/z/fnWP4d\" rel=\"nofollow noreferrer\">here on Godbolt</a> — notice the left-hand pane using <code>std::function</code> for your <code>f,g,h</code> variables, and the right-hand pane using <code>auto</code> to make them actually lambda types, thus eliminating all the <code>std::function</code> overhead. The meat of my solution is</p>\n<pre><code>template&lt;class Callable&gt;\nstruct Maybe {\n Callable f_;\n explicit Maybe(Callable f) : f_(std::move(f)) {}\n\n template&lt;class... Args&gt;\n auto operator()(Args&amp;&amp;... args) const\n -&gt; decltype(optional_of(f_(value_of(static_cast&lt;Args&amp;&amp;&gt;(args))...)))\n {\n if ((has_value(args) &amp;&amp; ...)) {\n return f_(value_of(static_cast&lt;Args&amp;&amp;&gt;(args))...);\n } else {\n return std::nullopt;\n }\n }\n};\n\ntemplate&lt;class T, class U&gt;\nauto operator&lt;&lt;(const Maybe&lt;T&gt;&amp; a, const Maybe&lt;U&gt;&amp; b) {\n // &quot;a &lt;&lt; b&quot; means &quot;a(b(x))&quot;\n return Maybe([a, b](auto&amp;&amp;... args) {\n return a(b(static_cast&lt;decltype(args)&gt;(args)...));\n });\n}\n</code></pre>\n<p><code>value_of</code>, <code>optional_of</code>, <code>has_value</code> are just overload sets with special overloads for <code>std::optional</code>.</p>\n<p>Making this code safe against ADL is left as an exercise for the reader — but I think basically you can just slap a <code>namespace detail</code> around the helper bits and you'll be good to go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:44:55.717", "Id": "245722", "ParentId": "245647", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T00:31:43.287", "Id": "245647", "Score": "4", "Tags": [ "c++", "c++17" ], "Title": "Composable monadic std::function using std::optional" }
245647
<p>I will describe two techniques, then the question will be how I can make an algorithm that is more efficient, if possible.</p> <p>I want to find an efficient way to determine the squares where the pieces on a chess board can go. I want to start with a simple case, and just find the square where two rooks could move in an otherwise empty board. The two rooks are assumed to be &quot;transparent&quot; to one another, since the conditions for the interaction with other pieces will be added at a later stage.</p> <p>The boards are represented by a collection of <code>64</code>-components boolean <code>numpy.array</code>.</p> <p>I start by creating the the board with the two rooks, assumed to be in position <code>15</code> and <code>25</code> on the 1-D board:</p> <pre><code>import numpy as np import time r_pos=np.zeros(64, dtype=bool) r_pos[15] = True r_pos[25] = True </code></pre> <p>Now I show the first method, which simply consist in setting to <code>True</code> the squares available making the rows and the columns separately. It can be shown that for this method the simulation time required increases with the number of pieces.</p> <pre><code>t1=time.time() attack_r=np.zeros(64, dtype=bool) for piece in np.where(r_pos)[0]: attack_r[8 * (piece // 8):8 * (piece // 8 + 1)] = True attack_r[piece % 8::8] = True t2=time.time() print t2-t1 print attack_a </code></pre> <p>To better visualize the board we can create a function that converts the 1-D array in the 2-D matrix:</p> <pre><code>def from_array_to_matrix(v): m=np.zeros((8,8)).astype('int') for row in range(8): for column in range(8): m[row,column]=v[row*8+column] return m </code></pre> <p>and thus we can check that we obtained the desired output:</p> <pre><code>print from_array_to_matrix(attack_r) </code></pre> <p>The second method creates a certain number of static boards as a template for the moves, and then uses boolean operators to select the proper template on the basis of the rook positions. It is slower, but it has the nice advantage that the simulation time does not depend on the number of pieces:</p> <pre><code># create the collection of possible rook # moves (just all the columns and all # the rows in separate matrices) m_rook=np.zeros((16,64), dtype=bool) for line in range(8): m_rook[line,line*8:(line+1)*8]=True col=0 for line in range(8,16): m_rook[line, col % 8::8]=True col+=1 % then we use the template to find the available moves t1=time.time() attack_r= np.any(m_rook[np.any(np.logical_and(r_pos, m_rook), axis=1)], axis=0) t2=time.time() print t2-t1 print from_array_to_matrix(attack_r) </code></pre> <p>I feel that it should be possible to use some technique that is even faster. Is it possible that using <code>numpy</code> arrays is actually not the best way to go ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T03:37:17.243", "Id": "482475", "Score": "4", "body": "Python2 has reached its [end of life](https://www.python.org/doc/sunset-python-2/). It's recommended to use Python3." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T03:43:21.493", "Id": "482476", "Score": "0", "body": "Ok, TY. I think that the `print` should be the only thing that changes in the particular case of the codes above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T23:25:45.087", "Id": "482544", "Score": "0", "body": "There are web sites that go into detail about programming chess games. Here is a page on using [bitboards](https://www.chessprogramming.org/Efficient_Generation_of_Sliding_Piece_Attacks), 64-bit values, to represent boards, pieces, moves, etc" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T03:33:18.867", "Id": "245649", "Score": "2", "Tags": [ "python", "python-2.x", "numpy", "chess" ], "Title": "Find the available squares for rooks in empty board using boolean arrays" }
245649
<p>I'm just trying to build a quick and crude error messaging system. It currently looks like this:</p> <pre><code>#include &lt;exception&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;map&gt; enum MsgTy { OK = 0, WARNING, ERROR, CRITICAL, }; class FileWriter { std::string filename_; std::ostringstream msg_; public: FileWriter(const std::string&amp; filename, std::ostringstream&amp; msg) : filename_{ filename } { operator()(msg); } void operator()(std::ostringstream&amp; msg) { std::ofstream out(&quot;log.txt&quot;, std::ios::app); out &lt;&lt; msg.str(); } }; static std::map&lt;MsgTy, std::string&gt; msg_id{ {MsgTy::OK, {&quot;OK: &quot;}}, {MsgTy::WARNING, {&quot;WARNING: &quot;}}, {MsgTy::ERROR, {&quot;ERROR: &quot;}}, {MsgTy::CRITICAL, {&quot;CRITICAL: &quot;}} }; #define messaging(MsgTy, msg, log2file) do { \ std::ostringstream strm; \ if ((MsgTy) == OK) { \ strm &lt;&lt; msg_id[(MsgTy)] &lt;&lt; (msg) &lt;&lt; '\n'; \ std::cout &lt;&lt; strm.str(); \ if((log2file) == true) \ FileWriter fw(&quot;log.txt&quot;, strm); \ } \ if ((MsgTy) == WARNING) { \ strm &lt;&lt; msg_id[(MsgTy)] &lt;&lt; (msg) &lt;&lt; '\n'; \ std::cout &lt;&lt; strm.str(); \ if((log2file) == true) \ FileWriter fw(&quot;log.txt&quot;, strm);\ } \ if ((MsgTy) == ERROR) { \ strm &lt;&lt; msg_id[(MsgTy)] &lt;&lt; (msg) &lt;&lt; '\n'; \ std::cerr &lt;&lt; strm.str(); \ if((log2file) == true) \ FileWriter fw(&quot;log.txt&quot;, strm); \ throw strm.str(); \ } \ if ((MsgTy) == CRITICAL) { \ strm &lt;&lt; msg_id[(MsgTy)] &lt;&lt; (msg) &lt;&lt; '\n'; \ std::cerr &lt;&lt; strm.str(); \ if((log2file) == true) \ FileWriter fw(&quot;log.txt&quot;, strm); \ throw strm.str(); \ } \ } while(0) int main() { try { messaging(MsgTy::OK, &quot;Everything is good!&quot;, true); messaging(MsgTy::WARNING, &quot;Something isn't quite right!&quot;, false); messaging(MsgTy::ERROR, &quot;Something went wrong!&quot;, true); messaging(MsgTy::CRITICAL, &quot;Something horribly went wrong!&quot;, true); } catch (const std::exception&amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre> <p>I'm using a combination of several techniques... I'm using a class as a functor object for writing to basic text files, currently, it will only append to the file if it already exists or tries to create one. The file writer will only be invoked if the condition flag is true within the messaging system.</p> <p>I'm using an enumeration and a static map to hold the basic strings for the different types of errors, warnings, or messages that my application or library might use. Then I'm using macro expansion to act as a function. Specific Error Message Types will also throw an exception and halt the program, while others, will just log to the console and let execution continue.</p> <p>Yes I know I could have just written a function, class, functor, etc. and I know that macros can be tricky to get correct and are harder to debug, but this was also an exercise to refresh my skills at writing good solid macros.</p> <p>What I would like to know:</p> <ul> <li>Are there any apparent issues with how I implemented the macro?</li> <li>Can there be any improvements made to it?</li> <li>Is the intent clear on its usage?</li> <li>I'm also interested in any other feedback.</li> </ul> <hr> <p><strong>Note</strong> <em>-This is not production code: it's for a personal project, however, I would still like it to be critiqued as if it were to be production code!-</em></p>
[]
[ { "body": "<p>You’ve already noted that this could be done better without macros, so I won’t belabour the point. I will note, though, that your goal—“to refresh [your] skills at writing good solid macros”—makes about as much sense as refreshing your skills at writing code on punch cards. You are exercising an archaic practice that is dying out, and is unwelcome in any modern project.</p>\n<pre><code>enum MsgTy {\n OK = 0,\n WARNING,\n ERROR,\n CRITICAL,\n};\n</code></pre>\n<p>In modern C++, you should use a strong <code>enum</code>—an <code>enum class</code>. That way your enumerators won’t pollute the namespace.</p>\n<p>Speaking of polluting the namespace, the almost universal convention in C++ is that all-caps identifiers are used for preprocessor defines. By using them in this case, you run the risk of someone else’s macro definitions fuggering up your <code>enum</code>. And given that having a macro named something like <code>ERROR</code> is <em>highly</em> likely in large enough projects, you’re really cruising for a bruising here. (Actually, POSIX reserves everything starting with <code>E</code> followed by a digit or uppercase letter… so you’re <em>REALLY</em> asking for trouble with that in particular.)</p>\n<p>I’m also not keen on the name <code>MsgTy</code>. Seems a little ugly and obtuse. I get that you want it to be short but… this seems a bit much.</p>\n<pre><code>class FileWriter {\n std::string filename_;\n std::ostringstream msg_;\npublic:\n FileWriter(const std::string&amp; filename, std::ostringstream&amp; msg) \n : filename_{ filename } {\n operator()(msg);\n }\n\n void operator()(std::ostringstream&amp; msg) {\n std::ofstream out(&quot;log.txt&quot;, std::ios::app);\n out &lt;&lt; msg.str(); \n }\n};\n</code></pre>\n<p>Oi, this class is….</p>\n<p>First off… what is the point of the data members? You don’t use either of them.</p>\n<p>Second… what’s the point of the function call operator? You could just as well do all the work in the constructor. You never use the function call operator anywhere else.</p>\n<p>Third… what’s the point of taking the argument as a string stream when you just go ahead and re-format it through a file stream? You’re double-formatting it.</p>\n<p>This entire class could boil down to:</p>\n<pre><code>struct FileWriter\n{\n FileWriter(std::string_view filename, std::string_view msg)\n {\n auto out = std::ofstream{filename, std::ios_base::app};\n out &lt;&lt; msg;\n }\n};\n</code></pre>\n<p>But even then, I’m not sure this is a great idea, because you’re reopening the file every time you’re writing a new log line, then closing it after. That doesn’t seem like a great idea, efficiency-wise.</p>\n<p>A better idea would be to open the file once, and keep it open. Then just syncronize your writes (assuming you care about concurrency, which it sure doesn’t look like it), and flush after every log line. Normally <code>std::endl</code> is a terrible idea… but flushing after every line is <em>exactly</em> the singular use case it’s actually intended for.</p>\n<pre><code>static std::map&lt;MsgTy, std::string&gt; msg_id{\n {MsgTy::OK, {&quot;OK: &quot;}},\n {MsgTy::WARNING, {&quot;WARNING: &quot;}}, \n {MsgTy::ERROR, {&quot;ERROR: &quot;}},\n {MsgTy::CRITICAL, {&quot;CRITICAL: &quot;}}\n};\n</code></pre>\n<p>As far as mapping enumerators to strings, this isn’t really the best way to go about it. It’s astoundingly inefficient and clunky for what should be a trivial task. A <code>std::map</code> is a <em>heavyweight</em> object… using it for literally 4 elements is… not a good usage.</p>\n<p>A better solution is to either implement a <code>to_string()</code> function:</p>\n<pre><code>constexpr auto to_string(MsgTy mt)\n{\n using namespace std::string_view_literals;\n\n switch (mt)\n {\n case MsgTy::OK:\n return &quot;OK&quot;sv;\n case MsgTy::WARNING:\n return &quot;WARNING&quot;sv;\n case MsgTy::ERROR:\n return &quot;ERROR&quot;sv;\n case MsgTy::CRITICAL:\n return &quot;CRITICAL&quot;sv;\n }\n}\n</code></pre>\n<p>or to implement a stream inserter for the type:</p>\n<pre><code>template &lt;typename CharT, typename Traits&gt;\nauto operator&lt;&lt;(std::basic_ostream&lt;CharT, Traits&gt;&amp; o, MsgTy mt)\n -&gt; std::basic_ostream&lt;CharT, Traits&gt;&amp;\n{\n switch (mt)\n {\n case MsgTy::OK:\n o &lt;&lt; &quot;OK&quot;;\n case MsgTy::WARNING:\n o &lt;&lt; &quot;WARNING&quot;;\n case MsgTy::ERROR:\n o &lt;&lt; &quot;ERROR&quot;;\n case MsgTy::CRITICAL:\n o &lt;&lt; &quot;CRITICAL&quot;;\n }\n\n return o;\n}\n</code></pre>\n<p>or both.</p>\n<p>Either option will be hundreds, if not thousands of times faster than using a <code>std::map</code>.</p>\n<pre><code>#define messaging(MsgTy, msg, log2file)\n</code></pre>\n<p>Okay, this is where the meat of the code is, and this is what you really want the focus to be on. Unfortunately, this is all wrong. This is exactly the way you should <em>NEVER</em> write a macro.</p>\n<p>First let’s get the initial stuff out of the way. As I mentioned above, the convention in C++ (and even in C) is that macros should be in all caps. That’s not just for style, it’s because the unconstrained text replacement of the preprocessor is so dangerous. <code>messaging</code> isn’t exactly an uncommon word; it’s quite likely that it could be used for another identifer… with disastrous consequences. Using all caps accomplishes two things:</p>\n<ol>\n<li>it alerts people to what they’re messing with; and</li>\n<li>the only way it could every be used again is via a redefinition… which will trigger at least a warning.</li>\n</ol>\n<p>The other problem with this preamble is that you’re using the message type enumeration’s type name as the parameter name. I can’t imagine why you’d think that’s a good idea. The only reason it works in this case is that you’re using an old-style <code>enum</code>. If you tried using a modern <code>enum class</code>, this whole macro would break.</p>\n<p>There’s another issue buried in there: if the message type is <code>ERROR</code> or <code>CRITICAL</code>, you throw an exception. Okay, but the problem is the exception you throw is a <code>std::string</code>. If you run your program, it’s going to crash, because you catch a <code>std::exception</code>… but a <code>std::string</code> is not a <code>std::exception</code>. You probably want to either throw a <code>std::runtime_error</code> or, better, a custom exception type depending on whether it’s a <code>ERROR</code> or <code>CRITICAL</code> message.</p>\n<p>Finally, you’ve made a critical macro error: you have repeated the argument(s). You have correctly wrapped them in parentheses, which helps prevent unexpected interactions with the surrounding code when expanded… but doesn’t help with the fact they they’re expanded multiple times. If you use an expression that changes the first argument in particular, who knows what could happen.</p>\n<p>Overall, this is a terrible macro, for a number of reasons. First of all, it’s needlessly long. It injects almost <em>30 lines of code</em> every time it’s used! In your <code>main()</code>, that <code>try</code> block that looks like it only has 4 lines in fact expands to <em>well over 100 lines</em>. That’s just ridiculous.</p>\n<p>It’s also absurdly complex. Putting control flow in a macro is not just a “eh, it’s a thing you do”… it’s an absolute last resort. That’s really the golden rule of macros: keep them as simple as possible. That’s because they’re not only so hard to debug, but also because they’re expanded everywhere. They’re also exceptionally dangerous, so they should be written as simple as possible to avoid the need to ever tweak it in the future… as it is now, any time the requirements for how to log change, you have to mess with the macro code… which is playing with fire.</p>\n<p>And a macro this complex just destroys your performance. Firstly, it will just absolutely trash your cache because all that machine code gets dumped everywhere the macro is used. (Although, if you’re lucky, and the macro is <em>always</em> used as you demonstrate, the compiler can probably remove most of those <code>if</code>s.) But also, there are other side effects, too: for example, if <code>messaging()</code> were a function, profile-guided optimization would almost certainly mark the <code>OK</code> path as the hot path, and optimize the code accordingly… but that’s because there’s one <code>if</code> in one place; as a macro, that <code>if</code> gets repeated everywhere the macro is used, and it’s a different <code>if</code> every time, so PGO won’t help you much.</p>\n<p>As it is, the macro’s code is in dire need of a rewrite, because it’s so repetitive, and there’s so much hard-coded in there (specifically the file name, over and over and over). But screwing with a macro is always a dangerous proposition; it’s <em>MUCH</em> riskier than refactoring a function. (It’s also sometimes much more frustrating, because the moment you touch a macro, you have to recompile <em>everything</em>, whereas a function can (sometimes!) be tweaked in isolation.)</p>\n<p>And not only is it dodgy to use, hard to maintain, and inefficient… it’s also a terrible interface! Why is it necessary to specify whether you want the message written to the file or not on <em>EVERY</em> call? Isn’t assuming <code>true</code> a good default? With a function you could use an overload or a defaulted parameter for that, no problem.</p>\n<p>At a bare minimum, to improve this macro, you should refactor as much as possible into functions:</p>\n<pre><code>#define MESSAGING(mt, msg, log_to_file) do { \\\n auto const mt_ = (mt);\n\n if (mt_ == MsgTy::ok) \\\n messaging_ok((msg), (log_to_file)); \\\n else if (mt_ == MsgTy::warning) \\\n messaging_warning((msg), (log_to_file)); \\\n else if (mt_ == MsgTy::error) \\\n messaging_error((msg), (log_to_file)); \\\n else if (mt_ == MsgTy::critical) \\\n messaging_critical((msg), (log_to_file)); \\\n} while (false)\n</code></pre>\n<p>Now you can fuss with the logic of each option safely.</p>\n<p>Even better would be use static dispatch for this kind of thing. You could create a few types (<code>ok_t</code>, <code>warning_t</code>) and instances of those types (<code>ok</code>, <code>warning</code>), and then dispatch based on those:</p>\n<pre><code>struct ok_t {};\ninline constexpr auto ok = ok_t{};\n// etc. for the other message types\n\nauto messaging(ok_t, std::string_view msg, bool log_to_file = true)\n{\n std::cout &lt;&lt; &quot;OK: &quot; &lt;&lt; msg &lt;&lt; std::endl; // endl to flush\n \n if (log_to_file)\n {\n auto out = std::ofstream{&quot;log.txt&quot;, std::ios_base::app};\n out &lt;&lt; &quot;OK: &quot; &lt;&lt; msg;\n \n // or better yet, have a class that keeps the log file open\n // and just appends to it, rather than opening and closing\n // it repeatedly.\n }\n}\n// etc. for the other message types\n\nmessaging(ok, &quot;Everything is good!&quot;);\nmessaging(warning, &quot;Something isn't quite right!&quot;, false);\nmessaging(error, &quot;Something went wrong!&quot;);\nmessaging(critical, &quot;Something horribly went wrong!&quot;);\n</code></pre>\n<p>But that’s just one of dozens of techniques you can use to <em>AVOID</em> the use of macros… which is a much more useful skill to have in 2020.</p>\n<p>In other words, all this has brought us back to the original point I wasn’t going to belabour. The best macro is the one you don’t write.</p>\n<h1>Questions</h1>\n<h2>Are there any apparent issues with how I implemented the macro?</h2>\n<p>Yes, it is needlessly long and complex. Even for a <em>non</em> macro function, this is unnecessarily long and complex. It should be refactored into smaller functions for each of the four different behaviours.</p>\n<h2>Can there be any improvements made to it?</h2>\n<p>The best way to write a macro is: don’t.</p>\n<p>I can’t conceive of why anyone would <em>want</em> to write a macro in 2020. Macros were a dirty hack when they were first created back in the 1970s. There may be a few very rare cases where you still need them, but by and large, if you can possibly solve a problem <em>without</em> macro, then <em>THAT</em> is the skill you should be exercising.</p>\n<h2>Is the intent clear on its usage?</h2>\n<p>Eeeh? Not really.</p>\n<p>Is this the intended usage:</p>\n<pre><code>messaging(MsgTy::OK, 42, true);\n</code></pre>\n<p>Is this:</p>\n<pre><code>// won't work, but is it intended to?\nmessaging(MsgTy::OK, &quot;a&quot; &lt;&lt; &quot;b&quot; &lt;&lt; &quot;c&quot;, true);\n</code></pre>\n<h2>I'm also interested in any other feedback.</h2>\n<p>Don’t waste your time honing skills that nobody wants. Macros are old tech that are only, at best, tolerated, and only when there is absolutely no other option. The best skills you can learn regarding macros are ways to <em>NOT</em> use them. A programmer who is a master at writing macros, but because they don’t know all the ways they can avoid them always falls back to writing them, is less than useless to me on my projects.</p>\n<p>Bottom line: Don’t waste your time. Getting good at writing macros helps no one. Instead, learn the techniques for <em>AVOIDING</em> macros. <em>THOSE</em> are skills that are actually useful in 2020 and beyond.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:43:12.637", "Id": "482502", "Score": "2", "body": "Good review! Just one further note: using `std::endl` reduces but doesn't solve the concurrency issue. Instead, use the C++20 `std::osyncstream` if available or roll your own if not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:43:18.333", "Id": "482503", "Score": "0", "body": "I appreciate your feedback. You pointed out the issues, where, how, and why. As for saying not to write macros in modern c++ I can understand where you are coming from. I have my reasons for doing so. It isn't so much to use them in actual code, it's more about having a better understanding of the pre-processor and how it behaves with code substitution and text expansion. \"Compiler-Design\" is one of my fields of study. Yes, in a real piece of useful software, I wouldn't consider using macros, unless if I was using libraries with legacy C code that required them!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:48:10.210", "Id": "482504", "Score": "2", "body": "The preprocessor is an interesting beast that can be abused in interesting ways: https://codereview.stackexchange.com/questions/93775/compile-time-sieve-of-eratosthenes Usually, though, as you've figured out, there's a better way in modern c++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:49:16.493", "Id": "482505", "Score": "0", "body": "You gave just what I was looking for. This also wasn't just for me... I'm 100% self-taught and have no formal training or credited college courses, yet, I have written small scale fully functional 3D graphics rendering systems, hardware emulators, and such... Recently I got into ISA (CPU-Hardware design) and looking into compiler design... So I just want to be aware of all aspects of the language both good and bad!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:51:23.197", "Id": "482506", "Score": "0", "body": "@Edward I didn't figure it out, I already knew it! I rarely or hardly ever use Macros! I try to use `constexpr` where I can, simplified templates where I can, basic class structures with single purposes, etc... The only thing I can't do yet is to utilize C++20 as I currently only have Visual Studio 2017 and not 19... I'm still running Windows 7! I just wanted a critique as I have read, to point out all of the pitfalls, corner cases, etc... It's just for a better understanding and for clarity reasons! It also makes for a great future reference!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:54:41.657", "Id": "482507", "Score": "0", "body": "It is also for others who are new to the field that would come across it! Especially for those who may be self-taught as well! Very nice write-up! You gave great detail and explained it very well!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:54:56.297", "Id": "482508", "Score": "2", "body": "If it helps, [this question](https://codereview.stackexchange.com/questions/243640/multithreaded-console-based-monster-battle-with-earliest-deadline-first-schedule) contains a limited C++11 version roughly equivalent to the C++20 `std::osyncstream`. Feel free to use and adapt!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:57:59.153", "Id": "482509", "Score": "0", "body": "@Edward, yeah I can't wait to be able to use it! I had written a small program to demonstrate why a simple piece of code would compile in Release mode but not Debug mode in Visual Studio using the `__LINE__` macro! With C++20 that my become obsolete except for use with legacy code! The C++20 feature will be able to give you the line number information at the call site of the object that was invoked, unlike `__LINE__`! Here is the link to that Q/A! https://stackoverflow.com/q/62870536/1757805 and the new feature is `std::source_location`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T18:36:59.290", "Id": "482524", "Score": "0", "body": "@Edward Yeah, my wording was bad there. `endl` does *NOTHING* for concurrency. When I said this was the use case for `endl`, I was referring to flushing after every line… not fixing concurrency issues. If you care about concurrency issues, `osyncstream` won’t help here either. That only syncs to a single buffer… won’t help if you keep reopening the file with *different* buffers. You’re relying on the OS in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T08:43:01.693", "Id": "482574", "Score": "0", "body": "Is it really true that uppercase identifiers are used _only_ for preprocessor macros? My understanding was that it's quite common to name global constants using uppercase as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:47:58.583", "Id": "482637", "Score": "0", "body": "@David Z Yes, [it is an almost universal convention](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rl-all-caps). There may be some confusion because, in the past, all global constants *were* macros. But now with `const` and `constexpr` (and `constinit`), that’s no longer true. If macros have their own unique format, you can easily detect shenanigans—the preprocessor can flag macro redefinitions, and all non-uppercase identifiers are (mostly) safe to use anywhere. But if you mix macros and non-macros… anything goes." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:09:58.580", "Id": "245663", "ParentId": "245653", "Score": "14" } }, { "body": "<h2>Observation</h2>\n<p>This is a common one beginners do. And to be blunt I wish they would not do this. It would be much better to learn how to sue the system logging tools.</p>\n<h2>Questions</h2>\n<ul>\n<li>Are there any apparent issues with how I implemented the macro?</li>\n</ul>\n<p>I don't see any. But the way you have done it there are no advantages of using the macro over a normal inline function. Also the normal inline function is probably safer and better because of the extra type checking.</p>\n<ul>\n<li>Can there be any improvements made to it?</li>\n</ul>\n<p>Macros if used differently could be good. You can turn them off at compile time and save the cost of evaluating any parameters. Though with modern C++ lambda's you can potentially have the same affect.</p>\n<p>If you want to do this you should log to the syslog rather than your own personal logging system. Now saying that there is nothing wrong with wrapping syslog with your own code is not a bad idea.</p>\n<ul>\n<li>Is the intent clear on its usage?</li>\n</ul>\n<p>Sure. I don't see anything particularly wrong. But it does require that you build the message before hand (there is no way to build the message as part of the message statement (OK you can do some simple stuff, but anything complex would break the macro (i.e. anything with a comma)).</p>\n<ul>\n<li>I'm also interested in any other feedback.</li>\n</ul>\n<p>Sure one second</p>\n<h2>Code Review</h2>\n<p>What are you using <code>msg_</code> for?</p>\n<pre><code>class FileWriter {\n std::string filename_;\n std::ostringstream msg_;\npublic:\n</code></pre>\n<p>You don't use it in any methods.</p>\n<p>You are forcing people to build a string stream them logging the string you can extract from the stream.</p>\n<pre><code> void operator()(std::ostringstream&amp; msg) {\n std::ofstream out(&quot;log.txt&quot;, std::ios::app);\n out &lt;&lt; msg.str(); \n }\n</code></pre>\n<p>Why not just allow people to pass a <code>std::string</code>. They you can pass a simple string without having to build a string stream first. Even better would be allow you to chain a series of objects with the <code>operator&lt;&lt;</code>.</p>\n<p>How about this:</p>\n<pre><code>class LokiFileWriter;\nclass LokiFileWriterStream\n{\n std::ofstream file;\n friend class LokiFileWriter;\n\n // Private so only LokiFileWriter can create one.\n LokiFileWriterStream(std::ofstream&amp;&amp; output)\n : file(std::move(output))\n {}\n public:\n LokiFileWriterStream(LokiFileWriterStream&amp;&amp; move) = default;\n template&lt;typename T&gt;\n LokiFileWriterStream&amp; operator&lt;&lt;(T const&amp; item)\n {\n // Send the T to the file stream.\n // Then return a reference to allow chaining\n file &lt;&lt; item;\n return *this;\n }\n ~LokiFileWriterStream()\n {\n // When the expression is closed\n // We will close the file stream.\n //\n // But remember that the move constructor is available\n // So objects that have been moved move the stream object\n // an object that has been moved from has a file object that\n // is no longer valid (calling close() will fail in some way)\n // but it is a valid object that we are allowed to call close on\n file.close();\n }\n};\nclass LokiFileWriter\n{\n std::string filename;\n public:\n LokiFileWriter(std::string const&amp; filename)\n : filename(filename)\n {}\n template&lt;typename T&gt;\n LokiFileWriterStream operator&lt;&lt;(T const&amp; item)\n {\n // We create a stream object.\n LokiFileWriterStream stream(std::ofstream(filename, std::ios::app));\n stream &lt;&lt; item;\n\n // The stream object is returned forcing a move\n // of the object to external calling frame.\n // This means the object inside this function may be\n // destroyed but the file object it contains has already been\n // moved and thus not destroyed.\n return stream;\n }\n};\n\nint main()\n{\n LokiFileWriter out(&quot;MyLogFile&quot;);\n // The first &lt;&lt; creates the `LokiFileWriterStream`\n // Each subsequent &lt;&lt; returns a reference to the same object.\n out &lt;&lt; &quot;Test&quot; &lt;&lt; 123 &lt;&lt; &quot; Plop&quot;;\n // At the end of the expression `LokiFileWriterStream` goes\n // out of scope and we destroy the object which calls the\n // destructor which then calls the close method.\n}\n</code></pre>\n<hr />\n<p>Sure. This is useful.</p>\n<pre><code>static std::map&lt;MsgTy, std::string&gt; msg_id{\n {MsgTy::OK, {&quot;OK: &quot;}},\n {MsgTy::WARNING, {&quot;WARNING: &quot;}}, \n {MsgTy::ERROR, {&quot;ERROR: &quot;}},\n {MsgTy::CRITICAL, {&quot;CRITICAL: &quot;}}\n};\n</code></pre>\n<p>But I would put it inside a method to make using it simple:</p>\n<pre><code>std::string const&amp; to_string(MsgTy const&amp; msg)\n{\n static std::map&lt;MsgTy, std::string&gt; msg_id{\n {MsgTy::OK, {&quot;OK: &quot;}},\n {MsgTy::WARNING, {&quot;WARNING: &quot;}}, \n {MsgTy::ERROR, {&quot;ERROR: &quot;}},\n {MsgTy::CRITICAL, {&quot;CRITICAL: &quot;}}\n };\n return msg_id[msg];\n }\n</code></pre>\n<p>You may think this is a bit trivial. But think of the situation where your enum is passed to a function that is has a template parameter and it would normally use <code>to_string()</code> to convert to a string.</p>\n<pre><code> template&lt;typename t&gt;\n void print(T const&amp; object)\n {\n using std::to_string;\n std::cout &lt;&lt; to_string(object); // This would work for\n // your enum just like all\n // other types that support\n // to_string in the standard.\n }\n</code></pre>\n<hr />\n<p>I think you have over complicated this:</p>\n<pre><code>#define messaging(MsgTy, msg, log2file) do { \\\n std::ostringstream strm; \\\n ... OK\n ... WARNING\n ... ERROR\n ... CRITICAL\n }\n</code></pre>\n<p>I would create a separate macro for each type of message:</p>\n<pre><code> #define messagingOK(msg, log2file) \\\n do { \\\n std::ostringstream strm; \\\n strm &lt;&lt; to_string(MsgTy::OK) &lt;&lt; (msg) &lt;&lt; &quot;\\n&quot;; \\\n std::cout &lt;&lt; strm.str(); \\\n if((log2file) == true) { \\\n FileWriter fw(&quot;log.txt&quot;, strm); \\\n } \\\n } while(0)\n</code></pre>\n<p>That way I can turn on/off each macro at compile time. I probably don't want to log <code>OK</code> items in the production version so I would want to turn that off.</p>\n<p>It is no moral difficult to use this than your version.</p>\n<pre><code> messagingOK(&quot;Hi&quot;, true);\n messaging(OK, &quot;Hi&quot;, true);\n</code></pre>\n<hr />\n<p>Now the reason to use macros is that you can turn them off and the cost of using the macros is reduced to zero!</p>\n<p>If you had written this as an inline function it would look like this:</p>\n<pre><code>template&lt;typename... Args&gt;\ninline void messagingOK(bool log2File, Args... const&amp; args)\n{\n#if TURNON_OK\n/* STUFF HERE */\n#endif\n}\n</code></pre>\n<p>The trouble here is that all the <code>args</code> are required to be evaluated (even if the function is inlined and the parameters are not used. The language guarantees that all the parameters are fully evaluated.</p>\n<p>This is why we use macros like this:</p>\n<pre><code>#if TURNON_OK\n#define messagingOK(msg, log2file) /* STUFF HERE */\n#else\n#define messagingOK(msg, log2file)\n#endif\n</code></pre>\n<p>So when you turn the macro off the cost of building the parameters is reduced to zero in this situation as they don't exist.</p>\n<hr />\n<p>OK. So you got the correct reason for using the macro but your function does not allow you to use the macro in a way that makes this possible.</p>\n<pre><code> // notice the brackets around the msg.\n // This means the expression inside the macros must be expanded first\n // unfortunately that does not work for the above\n strm &lt;&lt; msg_id[(MsgTy)] &lt;&lt; (msg) &lt;&lt; '\\n';\n\n // This will fail as the message part\n // will be included inside the brackets and thus must\n // be evaluated first with the stream object so you get\n // a compiler failure.\n messaging(OK, &quot;OK: &quot; &lt;&lt; 15 &lt;&lt; &quot; Testing&quot;, true);\n</code></pre>\n<p>So you could move this into a function and pass the parameters to that and convert to a string.</p>\n<pre><code> // Unfortunatel this also fails.\n // This time because of the way the macros interacts with commas.\n messaging(OK, buildString(&quot;OK: &quot;, 15, &quot; Testing&quot;), true);\n</code></pre>\n<p>So now you have to build the string external to the macro:</p>\n<pre><code> std::string message = std::string(&quot;OK: &quot;) + 15 + &quot; Testing&quot;;\n messaging(OK, message, true);\n</code></pre>\n<p>Now if I turn off the macro <code>messaging</code> we are still evaluating the string <code>message</code> so there is no advantage to using the macro.</p>\n<hr />\n<p>If we go back to functions we can put off evaluation of parameters by using lambdas.</p>\n<pre><code> inline void message(std::function&lt;void(std::ostream)&gt;&amp;&amp; messagePrinter)\n {\n #if TURNON_OK\n messagePrinter(std::cerr);\n #endif\n }\n</code></pre>\n<p>Here we are passing a function object. Creating a function object is usually very cheap so creating this object should be cheap and the cost is only invoked when the function is invoked.</p>\n<pre><code> // The cost of the function `add()` is only payed\n // if we actually want generate the error message.\n message([](std::ostream&amp; out){\n out &lt;&lt; &quot;This &quot; &lt;&lt; add(12, 3) &lt;&lt; &quot; a &quot; &lt;&lt; test &lt;&lt; &quot;\\n&quot;;\n });\n</code></pre>\n<hr />\n<p>Sure you want to throw a string?</p>\n<pre><code>throw strm.str();\n</code></pre>\n<p>This throws a <code>std::string</code>. This is not derived from <code>std::exception</code>. So youe code does not get caught in this catch...</p>\n<pre><code> catch (const std::exception&amp; e) {\n std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;\n return EXIT_FAILURE;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T21:41:08.180", "Id": "245675", "ParentId": "245653", "Score": "3" } } ]
{ "AcceptedAnswerId": "245663", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T06:37:13.470", "Id": "245653", "Score": "5", "Tags": [ "c++", "file", "error-handling", "logging", "macros" ], "Title": "A simple error messaging and logging system via macro(s) in C++" }
245653
<p>I'm working on a multivariate cross-entropy minimization model (for more details about it, see <a href="http://www.systemicrisk.ac.uk/sites/default/files/downloads/publications/dp-74-web.pdf" rel="nofollow noreferrer">this paper</a>, pp. 32-33). It's purpose is to adjust a prior multivariate distribution (in this case, a gaussian normal) with information on marginals coming from real observations.</p> <p>The code at the end of the post represents my current implementation. The maths should have been correctly reproduced, unless I missed something critical during the review. The real problem I'm struggling to deal with is the performance of the code.</p> <p>In the first part of the model, cumulative probabilities have to be computed over all the orthants of the distribution density. This process has a time complexity of <code>2^N</code>, where <code>N</code> is the number of entities included into the dataset. As long as the number of entities is less than <code>12</code>, everything is fast enough on my PC. With <code>20</code> entities, which is my current target, the model needs to run <code>mvncdf</code> over <code>1048576</code> combinations of orthants and this takes forever to finish.</p> <p>I already improved the code a little bit by replacing the main <code>for</code> loop with a <code>parfor</code> loop. I acquired a huge performance gain by replacing the built-in <code>mvncdf</code> function with a user-made one.</p> <p>I'm not very familiar with cross-entropy minimization models, so maybe there are math tricks I can use to simplify this calculation. Maybe the code can be vectorized even more. Well... any help or suggestion to improve the calculations speed is more than welcome!</p> <pre><code>clc(); clear(); % DATA pods = [0.015; 0.02; 0.013; 0.007; 0.054; 0.034; 0.009; 0.065; 0.029; 0.205]; dts = [2.1; 2; 2.2; 2.4; 1.5; 1.8; 2.3; 1.5; 1.8; 0.8]; % Test of time complexity: % pods = [pods; pods]; % dts = [dts; dts]; n = numel(pods); c = eye(n); k = 2^n; kh = k / 2; offsets = ones(n,1); % G / BOUNDS FOR 1 g1 = combn([0 1],n); bounds_1 = zeros(k,1); parfor i = 1:k g1_c = g1(i,:).'; lb = min([(-Inf * ~g1_c) dts],[],2); ub = max([(Inf * g1_c) dts],[],2); bounds_1(i) = mvncdf2(c,lb,ub); end % G / BOUNDS FOR 2:N g2 = repmat({zeros(kh,n)},n,1); bounds_2 = zeros(n,kh); for i = 2:k g1_c = g1(i,:); b = bounds_1(i); for j = 1:n if (g1_c(j) == 0) continue; end offset_j = offsets(j); g2t_j = g2{j}; g2t_j(offset_j,:) = g1_c; g2{j} = g2t_j; bounds_2(j,offset_j) = b; offsets(j) = offset_j + 1; end end % SOLUTION options = optimset(optimset(@fsolve),'Display','iter','TolFun',1e-08,'TolX',1e-08); cns = [1; pods]; x0 = zeros(size(pods,1)+1,1); lm = fsolve(@(x)objective(x,n,g1,bounds_1,g2,bounds_2,cns),x0,options); stop = 1; % Objective function of the model. function p = objective(x,n,g1,bounds_1,g2,bounds_2,cns) mu = x(1); lambda = x(2:end); p = zeros(n + 1,1); for i = 1:numel(bounds_1) p(1) = p(1) + exp(-g1(i,:) * lambda) * bounds_1(i); end for i = 1:n g2_k = g2{i,1}; for j = 1:size(bounds_2,2) p(i+1) = p(i+1) + exp(-g2_k(j,:) * lambda) * bounds_2(i,j); end end p = (exp(-1-mu) * p) - cns; end % All combinations of elements. function [m,i] = combn(v,n) if ((fix(n) ~= n) || (n &lt; 1) || (numel(n) ~= 1)) error('Parameter N must be a scalar positive integer.'); end if (isempty(v)) m = []; i = []; elseif (n == 1) m = v(:); i = (1:numel(v)).'; else i = combn_local(1:numel(v),n); m = v(i); end function y = combn_local(v,n) if (n &gt; 1) [y{n:-1:1}] = ndgrid(v); y = reshape(cat(n+1,y{:}),[],n); else y = v(:); end end end % Multivariate normal cumulative distribution function. function y = mvncdf2(c,lb,ub) persistent options; if (isempty(options)) options = optimset(optimset(@fsolve),'Algorithm','trust-region-dogleg','Diagnostics','off','Display','off','Jacobian','on'); end n = size(c,1); [cp,lb,ub] = cholperm(n,c,lb,ub); d = diag(cp); if any(d &lt; eps()) y = NaN; return; end lb = lb ./ d; ub = ub ./ d; cp = (cp ./ repmat(d,1,n)) - eye(n); [sol,~,exitflag] = fsolve(@(x)gradpsi(x,cp,lb,ub),zeros(2 * (n - 1),1),options); if (exitflag ~= 1) y = NaN; return; end x = sol(1:(n - 1)); x(n) = 0; x = x(:); mu = sol(n:((2 * n) - 2)); mu(n) = 0; mu = mu(:); c = cp * x; lb = lb - mu - c; ub = ub - mu - c; y = exp(sum(lnpr(lb,ub) + (0.5 * mu.^2) - (x .* mu))); end function [cp,l,u] = cholperm(n,c,l,u) s2p = sqrt(2 * pi()); cp = zeros(n,n); z = zeros(n,1); for j = 1:n j_seq = 1:(j - 1); jn_seq = j:n; j1n_seq = (j + 1):n; cp_off = cp(jn_seq,j_seq); z_off = z(j_seq); cpz = cp_off * z_off; d = diag(c); s = d(jn_seq) - sum(cp_off.^2,2); s(s &lt; 0) = eps(); s = sqrt(s); lt = (l(jn_seq) - cpz) ./ s; ut = (u(jn_seq) - cpz) ./ s; p = Inf(n,1); p(jn_seq) = lnpr(lt,ut); [~,k] = min(p); jk = [j k]; kj = [k j]; c(jk,:) = c(kj,:); c(:,jk) = c(:,kj); cp(jk,:) = cp(kj,:); l(jk) = l(kj); u(jk) = u(kj); s = c(j,j) - sum(cp(j,j_seq).^2); s(s &lt; 0) = eps(); cp(j,j) = sqrt(s); cp(j1n_seq,j) = (c(j1n_seq,j) - (cp(j1n_seq,j_seq) * (cp(j,j_seq)).')) / cp(j,j); cp_jj = cp(j,j); cpz = cp(j,j_seq) * z(j_seq); lt = (l(j) - cpz) / cp_jj; ut = (u(j) - cpz) / cp_jj; w = lnpr(lt,ut); z(j) = (exp((-0.5 * lt.^2) - w) - exp((-0.5 * ut.^2) - w)) / s2p; end end function [g,j] = gradpsi(y,L,l,u) d = length(u); d_seq = 1:(d - 1); x = zeros(d,1); x(d_seq) = y(d_seq); mu = zeros(d,1); mu(d_seq) = y(d:end); c = zeros(d,1); c(2:d) = L(2:d,:) * x; lt = l - mu - c; ut = u - mu - c; w = lnpr(lt,ut); pd = sqrt(2 * pi()); pl = exp((-0.5 * lt.^2) - w) / pd; pu = exp((-0.5 * ut.^2) - w) / pd; p = pl - pu; dfdx = -mu(d_seq) + (p.' * L(:,d_seq)).'; dfdm = mu - x + p; g = [dfdx; dfdm(d_seq)]; lt(isinf(lt)) = 0; ut(isinf(ut)) = 0; dp = -p.^2 + (lt .* pl) - (ut .* pu); dl = repmat(dp,1,d) .* L; mx = -eye(d) + dl; mx = mx(d_seq,d_seq); xx = L.' * dl; xx = xx(d_seq,d_seq); j = [xx mx.'; mx diag(1 + dp(d_seq))]; end function p = lnpr(a,b) p = zeros(size(a)); a_indices = a &gt; 0; if (any(a_indices)) x = a(a_indices); pa = (-0.5 * x.^2) - log(2) + reallog(erfcx(x / sqrt(2))); x = b(a_indices); pb = (-0.5 * x.^2) - log(2) + reallog(erfcx(x / sqrt(2))); p(a_indices) = pa + log1p(-exp(pb - pa)); end b_indices = b &lt; 0; if (any(b_indices)) x = -a(b_indices); pa = (-0.5 * x.^2) - log(2) + reallog(erfcx(x / sqrt(2))); x = -b(b_indices); pb = (-0.5 * x.^2) - log(2) + reallog(erfcx(x / sqrt(2))); p(b_indices) = pb + log1p(-exp(pa - pb)); end indices = ~a_indices &amp; ~b_indices; if (any(indices)) pa = erfc(-a(indices) / sqrt(2)) / 2; pb = erfc(b(indices) / sqrt(2)) / 2; p(indices) = log1p(-pa - pb); end end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T00:53:20.183", "Id": "482548", "Score": "0", "body": "Have you ran the profiler? That should be your first step. Guessing as to what parts are slow is hard, we often guess wrong. Regarding your “micro-cache”, this is called memoization, and is trivial to add in MATLAB: https://blogs.mathworks.com/loren/2018/07/05/memoize-functions-in-matlab/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:00:43.200", "Id": "482549", "Score": "2", "body": "Though the `parfor` will likely prevent the use of `memoize`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T13:47:05.193", "Id": "482602", "Score": "0", "body": "Hi Cris, it's a pleasure to see you're still in here. I updated my answer with the last improvements I planned to include: memoization is no more required with the new way I use to perform computations. The new mvncdf function is blazing fast compared to the built-in one. Overall, the script performance now is much much better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T13:49:14.743", "Id": "482603", "Score": "0", "body": "I optimized every single piece of code I could. And I run many profiling sessions. Yet, mvncdf takes about 80% / 90% of execution time. For 10 historical time series, it's just a matter of seconds and it's fine... the script starts taking a little bit too long at 13... with 20 it's still unfeasible, every rolling window (I have about 4500) takes like 30 minutes to finish. I'm really clueless about how to improve it further. Maybe big problems require big time and I reached a dead end?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T23:15:20.830", "Id": "483147", "Score": "0", "body": "It's hard to work out how to improve `mvncdf` without knowing what sort of inputs you're using (it could be fast and just being called a lot). I don't think you're going to get big improvements in speed, and the O(2^n) run time is unavoidable with this method. That being said, pre-allocating `x` and `mu` as `zeros(n,1)` would probably help a little. You are asking for a lot with so much uncommented code with mysterious variable names, I couldn't go through the rest of the code in much detail, or run it for larger `n` because I didn't know what inputs would be realistic to use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T23:15:54.453", "Id": "483148", "Score": "1", "body": "And have you considered other optimisation methods for `fsolve` or picked the one you're using for a reason?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-15T09:04:26.073", "Id": "245659", "Score": "4", "Tags": [ "performance", "time-limit-exceeded", "matlab" ], "Title": "Cross-Entropy Minimization - Extreme Code Performance" }
245659
<p>I've created a fake WeakReference class for VBA by chance. A Weak Reference is not counted (i.e. IUnknown::AddRef method is not called). I knew about the Weak Reference concept from Swift and I accidentaly read about a COM <a href="https://docs.microsoft.com/en-us/windows/win32/api/oaidl/ns-oaidl-variant" rel="nofollow noreferrer">Variant</a>.</p> <p>In short, I am using a Variant (ByRef) to manipulate the first 2 bytes (var type) in a second Variant in order to flip between an Object and a Long/LongLong Variant.</p> <p>The advantage of this approach is that only some inital API calls are needed to set things up. When the referenced object is needed only plain VBA calls are done thus making code fast even if called millions of times. Also, the 'Object' property safely returns Nothing if the referenced object has been destroyed already. Finally, because the Variants used are ByRef, the Application can safely clean up memory even if state is lost.</p> <p>The full code with explanation is under MIT license on GitHub at <a href="https://github.com/cristianbuse/VBA-WeakReference" rel="nofollow noreferrer">VBA-WeakReference</a>. I've been asked by <a href="https://github.com/Greedquest" rel="nofollow noreferrer">Greedquest</a> to post the code here on Code Review. So, here it is:</p> <p><code>WeakReference</code> class:</p> <pre><code>Option Explicit #If Mac Then #If VBA7 Then Private Declare PtrSafe Function CopyMemory Lib &quot;/usr/lib/libc.dylib&quot; Alias &quot;memmove&quot; (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr #Else Private Declare Function CopyMemory Lib &quot;/usr/lib/libc.dylib&quot; Alias &quot;memmove&quot; (Destination As Any, Source As Any, ByVal Length As Long) As Long #End If #Else 'Windows 'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx #If VBA7 Then Private Declare PtrSafe Sub CopyMemory Lib &quot;kernel32&quot; Alias &quot;RtlMoveMemory&quot; (Destination As Any, Source As Any, ByVal Length As LongPtr) #Else Private Declare Sub CopyMemory Lib &quot;kernel32&quot; Alias &quot;RtlMoveMemory&quot; (Destination As Any, Source As Any, ByVal Length As Long) #End If #End If 'https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oaut/3fe7db9f-5803-4dc4-9d14-5425d3f5461f 'https://docs.microsoft.com/en-us/windows/win32/api/oaidl/ns-oaidl-variant?redirectedfrom=MSDN 'Flag used to simulate ByRef Variants in order to avoid memory reclaim Private Const VT_BYREF As Long = &amp;H4000 'Makes it all possible 'A memory address Long Integer Private Type MEM_ADDRESS #If VBA7 Then ptr As LongPtr 'Defaults to LongLong on x64 or Long on x32 #Else ptr As Long 'For VB6 #End If End Type Private Type FAKE_REFERENCE remoteVarType As Variant 'Manipulates the variant type for 'reference' reference As Variant 'Will be holding the object reference/address vTable As MEM_ADDRESS 'Initial address of virtual table vTableByRef As Variant 'Address used to check if reference is still valid vbLongPtr As Long 'Data type enum (vbLong = 3 or vbLongLong = 20) isValid As Boolean 'Indicates if the memory reference is valid End Type Private m_fake As FAKE_REFERENCE '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'Class Constructor '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Private Sub Class_Initialize() 'Save address of the Variant that will hold the target reference/address m_fake.remoteVarType = VarPtr(m_fake.reference) ' 'Change remoteVT variant type to Integer ByRef. This will now be linked ' to the first 2 bytes of the Variant holding the target reference 'Setting the VT_BYREF flag makes sure that the 2 bytes are not reclaimed ' twice when both 'remoteVarType' and 'reference' go out of scope 'And most importantly this gives the ability to switch the variant type of ' the reference at will, just by changing the Integer value of remoteVT CopyMemory ByVal VarPtr(m_fake.remoteVarType), vbInteger + VT_BYREF, 2 ' 'Store the data type enum for mem addresses (vbLong = 3 or vbLongLong = 20) m_fake.vbLongPtr = VBA.VarType(ObjPtr(Nothing)) End Sub '******************************************************************************* 'Sets the weak/fake reference to an object '******************************************************************************* Public Property Let Object(obj As Object) 'Save memory address of the object m_fake.reference = ObjPtr(obj) ' m_fake.isValid = (m_fake.reference &lt;&gt; 0) If Not m_fake.isValid Then Exit Property ' 'Save the default interface's virtual table address by reference. The vTable ' address is found at the first 4 (x32) or 8 (x64) bytes at the referenced ' interface address m_fake.vTableByRef = m_fake.reference CopyMemory ByVal VarPtr(m_fake.vTableByRef), m_fake.vbLongPtr + VT_BYREF, 2 ' 'Save the current vTable address. This is needed later to compare with the ' vTableByRef address in order to establish if the Object has been ' destroyed and it's memory reclaimed. 'vTableByRef can still be read within the scope of this method m_fake.vTable.ptr = m_fake.vTableByRef End Property '******************************************************************************* 'Safely retrieves the object that the saved reference is pointing to 'No external API calls are needed! '******************************************************************************* Public Property Get Object() As Object If Not m_fake.isValid Then Exit Property ' 'Compare the current vTable address value with the initial address 'The current redirected value vTableByRef can NOT be read directly anymore ' so it must be passed ByRef to an utility function m_fake.isValid = (GetRemoteAddress(m_fake.vTableByRef).ptr = m_fake.vTable.ptr) ' If m_fake.isValid Then 'Address is still valid. Retrive the object 'Turn the reference into an object (needs to be done ByRef) VarType(m_fake.remoteVarType) = vbObject Set Object = m_fake.reference End If ' 'The fake object is not counted (reference count was never incremented by ' calling the IUnknown::AddRef method) so a crash will occur if the ' Variant type remains as vbObject, because when the Variant goes out ' of scope the object count is decremented one more time than it should 'Meanwhile, as Integer, the Variant can safely go out of scope anytime VarType(m_fake.remoteVarType) = m_fake.vbLongPtr 'vbLong or vbLongLong End Property '******************************************************************************* 'Utility. Changes the data type for the reference Variant while preserving the ' level of redirection of remoteVarType '******************************************************************************* Private Property Let VarType(ByRef v As Variant, newType As Integer) v = newType End Property '******************************************************************************* 'Returns the value of a Variant that has the VT_BYREF flag set '******************************************************************************* Private Function GetRemoteAddress(ByRef memAddress As Variant) As MEM_ADDRESS GetRemoteAddress.ptr = memAddress End Function </code></pre> <p>Can this code be better?</p> <hr /> <p>A quick demo showing how a reference cycle can be avoided:</p> <p><code>DemoParent</code> class:</p> <pre><code>Option Explicit Private m_child As DemoChild Public Property Let Child(ch As DemoChild) Set m_child = ch End Property Public Property Get Child() As DemoChild Set Child = m_child End Property Private Sub Class_Terminate() Set m_child = Nothing Debug.Print &quot;Parent terminated &quot; &amp; Now End Sub </code></pre> <p>And a <code>DemoChild</code> class:</p> <pre><code>Option Explicit Private m_parent As WeakReference Public Property Let Parent(newParent As DemoParent) Set m_parent = New WeakReference m_parent.Object = newParent End Property Public Property Get Parent() As DemoParent Set Parent = m_parent.Object End Property Private Sub Class_Terminate() Debug.Print &quot;Child terminated &quot; &amp; Now End Sub </code></pre> <p>Here's a demo:</p> <pre><code>Sub DemoTerminateParentFirst() Dim c As New DemoChild Dim p As New DemoParent ' p.Child = c c.Parent = p ' Debug.Print TypeName(p.Child.Parent) End Sub </code></pre> <p>And another demo:</p> <pre><code>Sub DemoTerminateChildFirst() Dim c As New DemoChild Dim p As New DemoParent ' p.Child = c c.Parent = p Set c = Nothing ' Debug.Print TypeName(p.Child.Parent) End Sub </code></pre> <p>Both Parent and Child Class_Terminate events are firing properly.</p> <p>Updated version and more demos are available at the GitHub repository <a href="https://github.com/cristianbuse/VBA-WeakReference" rel="nofollow noreferrer">VBA-WeakReference</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T12:32:04.400", "Id": "482501", "Score": "2", "body": "Related: [Solution for Parent/Child circular references: WeakReference class](https://codereview.stackexchange.com/q/202414/146810)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T13:11:22.740", "Id": "482510", "Score": "2", "body": "Yes. But completely different and unsafe if the object has been already destroyed (i.e. crashes Application)" } ]
[ { "body": "<p>Looks great overall, although I'm really not a fan of <em>banner comments</em> (some of them would do well as <a href=\"https://rubberduckvba.com/Annotations/Details/Description\" rel=\"noreferrer\">@Description annotations</a>), but I like that the commenting is very extensive. Good job!</p>\n<p>This is dangerous though:</p>\n<blockquote>\n<pre><code>'*******************************************************************************\n'Sets the weak/fake reference to an object\n'*******************************************************************************\nPublic Property Let Object(obj As Object)\n</code></pre>\n</blockquote>\n<p>It breaks a very well-established convention where object references are assigned using the <code>Set</code> keyword. By defining the property as a <code>Property Let</code> member, the consuming code has all rights to consider this legal:</p>\n<pre><code>Set weakRef.Object = someObject\n</code></pre>\n<p>But they'll be met with a confusing &quot;invalid use of property&quot; compile-time error.</p>\n<blockquote>\n<pre><code>Public Property Let Parent(newParent As DemoParent)\n Set m_parent = New WeakReference\n m_parent.Object = newParent\nEnd Property\n</code></pre>\n</blockquote>\n<p>That <em>should</em> read:</p>\n<pre><code>Public Property Set Parent(ByVal newParent As DemoParent)\n Set m_parent = New WeakReference\n Set m_parent.Object = newParent\nEnd Property\n</code></pre>\n<p><sub>(note: Property Let/Set RHS argument is always passed ByVal; the implicit default being ByRef everywhere else, it's a good idea to make it explicit here)</sub></p>\n<p>Why? Because depending on how the <code>newParent</code> object is defined, this code might not do what you think it does:</p>\n<pre><code> m_parent.Object = newParent\n</code></pre>\n<p>Indeed, classes in VBA can have hidden <em>member attributes</em>. If you have <a href=\"https://rubberduckvba.com\" rel=\"noreferrer\">Rubberduck</a>, you can do this:</p>\n<pre><code>'@DefaultMember\nPublic Property Get Something() As Long\n Something = 42\nEnd Property\n</code></pre>\n<p>And when you synchronize the Rubberduck <a href=\"https://rubberduckvba.com/Annotations/Details/DefaultMember\" rel=\"noreferrer\">annotations</a> (via inspection results), the member would look like this if you exported the module:</p>\n<pre><code>'@DefaultMember\nPublic Property Get Something() As Long\nAttribute Something.VB_UserMemId = 0\n Something = 42\nEnd Property\n</code></pre>\n<p>If that's what the <code>DemoParent</code> class does, then this:</p>\n<pre><code> m_parent.Object = newParent\n</code></pre>\n<p>Is <em>implicitly</em> doing this, through a mechanism known as <em>let coercion</em>, where an object can be coerced into a value:</p>\n<pre><code> Let m_parent.Object = newParent.Something\n</code></pre>\n<p>That makes <code>WeakReference</code> not work with most classes that define a <em>default member/property</em>. Granted, most classes <em>should not</em> define such a member (implicit code is code that says one thing and does another: avoid it!), but it wouldn't be uncommon to see it adorn a custom collection class' <code>Item</code> property - if each item in that custom data structure has a reference to its containing collection, then the error would be complaining about an argument (to a method we don't intend to invoke, and whose name won't appear in the error message) not being optional...</p>\n<p>VBA uses the <code>Set</code> keyword specifically to disambiguate this assignment scenario:</p>\n<pre><code> [Let] m_parent.Object = newParent 'ambiguous, RHS could be let-coerced\n Set m_parent.Object = newParent 'unambiguous\n</code></pre>\n<p>The <code>Let</code> keyword is redundant and can safely be omitted, but not the <code>Set</code> keyword.</p>\n<p>The keyword is not needed in <em>later</em> versions of Visual Basic, because in these versions, the compiler will refuse to allow the definition of a <em>parameterless</em> default member: the possible presence of a parameterless default member on a VBA class is why the <code>Set</code> keyword is required: skirting around it introduces unexpected implicit behavior that can be very hard to diagnose and/or debug.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T07:13:24.630", "Id": "482571", "Score": "0", "body": "Nice explanation. You had me convinced at \"It breaks a very well-established convention where object references are assigned using the Set keyword\". One bad practice that I need to change.\n\nHowever, I am using the reserved DISPIDs myself so I am aware of default members and the Let coercion mechanism.\n\nThe example you've presented does not work because in the Let Procedure the expected parameter is defined as Object. It doesn't matter if the Object is passed ByVal/ByRef and it also doesn't matter if the Object has a default member or not. The Object will still be passed correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T13:27:31.207", "Id": "482601", "Score": "0", "body": "@CristianBuse admittedly I hadn't tested any of it... you are correct of course, the `Property Let` member receives the correct and expected object pointer every time - my answer would have been slightly different had I tested that, but let-coercion absolutely has *everything* to do with the presence of a default member though (which could *also* be an `Object` with a default member!), and `Property Let`/`Set` always receives its parameters `ByVal` regardless of whether you specify `ByRef` or not. Dang now I need to come up with an example of unintended recursive default member resolution..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T15:01:55.770", "Id": "482608", "Score": "1", "body": "Gave this a little more thought (haven't tested though); I think let-coercion would have necessitated parentheses around the `(newParent)` argument, and that would have made the operation as explicit as it gets: `foo.Bar = (thing)` looks reasonably suspicious, and there doesn't appear to be a way for the coercion to happen implicitly in that case. Still a good idea to define it as `Property Set`; the rules around let coercion and implicit conversions in VBA aren't exactly simple, so making the API stick with established convention removes any *apparent* ambiguity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T15:19:01.840", "Id": "482609", "Score": "0", "body": "I absolutely agree I should use Set. As mentioned before I also believe it's bad practice (using Let property instead of Set). I am always in favour of unambiguous code. I just needed somebody to notice my blind spot. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T15:26:19.453", "Id": "482610", "Score": "0", "body": "@CristianBuse I can't wait to read Greedo's feedback! Mine was just going to be a comment about the \"example usage\" code, but made it an answer when I realized where the weirdness came from. It's still a single-point review - I'm hoping Greedo/Greedquest (or another reviewer) puts up an answer that actually dives into the meat of it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T16:37:32.127", "Id": "245666", "ParentId": "245660", "Score": "9" } }, { "body": "<p>Sorry for taking so long with this review despite being the one to prompt you to post your code here, but I hope you (and others) may still find it useful.</p>\n<p>Now, although I do have a number of more general points to talk about, as Matt says I think it'd be nice to dive into the &quot;meat&quot; of your code and dissect the approach you've taken, then hopefully include some of the general points along the way.</p>\n<hr />\n<p>Let's remind ourselves first of the &quot;standard approach&quot;, as you referred to it in the GitHub repository, which is more or less the approach Matt uses in the question I linked (minus a nice constructor and some other OOP stuff), and looks something like this:</p>\n<pre><code>Property Get ObjectFromPtr() As Object\n Dim result As Object\n CopyMemory result, ByVal this.ptr, LenB(ptr) 'De-reference cached ptr into temp object\n Set ObjectFromPtr = result 'IUnknown::AddRef once for the return value\n ZeroMemory result, LenB(ptr) 'Manually clear the temp reference so IUnknown::Release isn't called when it goes out of scope\nEnd Property\n</code></pre>\n<p>For the sake of having something to compare to, what's good and bad about this code?</p>\n<p>Pros:</p>\n<ul>\n<li>Quite simple technique; only requires basic knowledge of pointers and reference types</li>\n<li>Short clear code</li>\n<li>Minimal number of API calls</li>\n<li>Small instance memory footprint (only 1 cached LongPtr)</li>\n</ul>\n<p>Cons:</p>\n<ul>\n<li>Fairly slow API used for most performance critical part</li>\n<li>If parent has been nulled and cached pointer references a bit of memory that no longer represents a real object instance, Excel will likely crash when the returned Object is inspected</li>\n<li>If parent has been nulled, but the memory has been overwritten with a <em>valid</em> but different object instance, then this approach will appear to succeed, yet return an incorrect/unintended object, since <code>Object</code> is effectively weakly typed in VBA</li>\n</ul>\n<hr />\n<p>So how does your approach differ (ideally maintaining or adding to the pros while reducing the cons)? I see 3 key areas where your underlying approach is different:</p>\n<ol>\n<li>You use modified ByRef variants to do the memory manipulation in the performance critical area*</li>\n<li>Rather than creating a temporary Object instance and filling it with the Object pointer, you toggle the VarType flag of a Variant to create the temporary Object</li>\n<li>You partially circumvent the weak typing of the Object return type by caching the parent's VTable pointer in the <code>Let</code> method and then manually checking it still matches the referenced object instance every time <code>Get</code> is called</li>\n</ol>\n<p>Let's take a look at these 3 differences in turn to see what they bring to the implementation as a whole</p>\n<p>*<sub>well, if you don't count the <code>Let</code> procedure as performance critical, which it probably isn't in the typical use case. It's called once at the Child's birth, while the <code>Get</code> is potentially called many times in the Child's lifetime. However best not to make assumptions on how users will interact with your code, especially something as fundamental as this</sub></p>\n<h3>1) ByRef Variants for moving memory</h3>\n<p>You set up these <em>&quot;remote variables&quot;</em> by manually modifying the VarType of a Variant:</p>\n<pre><code>CopyMemory ByVal VarPtr(m_fake.vTableByRef), m_fake.vbLongPtr + VT_BYREF, 2\n</code></pre>\n<p>I haven't seen this before, impressive to come up with a totally new approach, well done! At a glance it seems to offer a number of benefits:</p>\n<ul>\n<li>Make use of super-fast native VBA code to do the pointer dereference + memory overwrite for you instead of an API call</li>\n<li>Simplify call sites by interacting with native VBA variants</li>\n<li>Avoid the VBA interpreter trying to reclaim the same bit of memory twice by using ByRef</li>\n</ul>\n<p>However there are some issues with all of these arguments...</p>\n<hr />\n<p>To begin with, I'm not sure reclaiming memory was ever really a concern; value types aren't reference counted so there was never any risk of double reclaiming. The real risk to watch out for is where the variable that owns the memory goes out of scope before the remote variable does. This leaves the remote variable pointing to a section of memory that has been reclaimed.</p>\n<p>In the case of reading memory like with your <code>vTableByRef</code>, it's sufficient to know that the value it reads could be anything. However when you set up a variable to <em>write</em> memory, then you have to be very careful you don't end up corrupting memory you don't own. This isn't too much of a risk for your code, since <code>reference</code> and <code>remoteVarType</code> are in the same scope, however if the Child_Terminate code runs after the parent's, and the child attempts to access its parent's reference at this point, then in some circumstances I'll discuss later the <code>remoteVarType</code> will allow writing to an un-owned bit of memory, which is, needless to say, a bad thing!</p>\n<p>So accessing memory with remote variables doesn't do much to protect you compared to an API call.</p>\n<hr />\n<p>Secondly, does using ByRef variants really help to simplify call sites compared to an API?</p>\n<blockquote>\n<pre><code>'*******************************************************************************\n'Utility. Changes the data type for the reference Variant while preserving the\n' level of redirection of remoteVarType\n'*******************************************************************************\nPrivate Property Let VarType(ByRef v As Variant, newType As Integer)\n v = newType\nEnd Property\n\n'*******************************************************************************\n'Returns the value of a Variant that has the VT_BYREF flag set\n'*******************************************************************************\nPrivate Function GetRemoteAddress(ByRef memAddress As Variant) As MEM_ADDRESS\n GetRemoteAddress.ptr = memAddress\nEnd Function\n</code></pre>\n</blockquote>\n<p>The fact that you need these 2 methods to interact with the remote variables is itself a warning sign. It would be great if you could simplify your calling sites to this:</p>\n<pre><code>m_fake.isValid = (m_fake.vTableByRef = m_fake.vTable) 'check live value against the cache\n</code></pre>\n<p>Or</p>\n<pre><code>m_fake.remoteVarType = vbObject 'toggle the VarType flag\n</code></pre>\n<p>... which would be a big improvement over accessing the memory the old way:</p>\n<pre><code>CopyMemory m_fake.remoteVarType, vbObject, 2 'much less clear\n</code></pre>\n<p>But in fact the call sites are not nearly that clear:</p>\n<blockquote>\n<pre><code>VarType(m_fake.remoteVarType) = vbObject\nm_fake.isValid = (GetRemoteAddress(m_fake.vTableByRef).ptr = m_fake.vTable.ptr)\n</code></pre>\n</blockquote>\n<p><code>VarType</code> and <code>GetRemoteAddress</code> indicate that storing Variants ByRef beyond their typical function argument scope is not something VBA is happy about, hence the additional redirection required to get around VBA's complaints.</p>\n<hr />\n<p>Final point regarding these remote variables is performance. Low level APIs are always risky and VBA's complaints haven't stopped me in the past, so maybe this technique's speed will make it worthwhile? While it's true that native is native, Variant is not Integer, and using variants for dereferencing brings overhead as they are essentially dynamically sized variables. Since we know dynamic sizing isn't something to worry about (the memory these remote variables work with is fixed in size), it is more efficient to move memory around in pre-defined chunks. Fortunately the VB6 (msvbvm60.dll) runtime exposes a <a href=\"http://www.xbeat.net/vbspeed/i_VBVM6Lib.html#Runtime\" rel=\"nofollow noreferrer\">family of undocumented methods</a> to do just that, let's compare everything for speed:</p>\n<p><a href=\"https://i.stack.imgur.com/rge9N.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rge9N.png\" alt=\"Comparison of integer dereferencing techniques\" /></a></p>\n<p>Here I've run an integer dereference (read 2 bytes from one variable and write to another) many times (x axis) and calculated the average time per call (y axis) for the standard, ByRef and GetMem2 techniques, and the latter comes out on top.</p>\n<p>All things considered, the remote variable technique you use doesn't in fact improve readability, safety or performance, and requires additional knowledge of COM Variants that means people looking at your code for the first time (myself included) may need a couple of takes to understand what's going on - ultimately hindering maintainability and accessibility of the approach. So should you scrap the remote variables? Well there is still one important advantage over the faster Get/PutMem functions which is that I can't seem to find any examples of using them on Mac! I'm fairly certain it has to be possible since they should ship with VBA, but I haven't found them in Office's <code>VBE7.dll</code>, only Windows' <code>msvbvm60.dll</code> so I'm not so sure. So maybe on Mac you could fall-back to ByRef Variants as they still outperform MoveMem, but if anyone has better suggestions do drop them in the comments.</p>\n<h3>2) Object References</h3>\n<p>So while the standard code has this for creating an object from a pointer</p>\n<pre><code>CopyMemory result, ByVal ptr, LenB(ptr)\nSet ObjectFromPtr = result\nZeroMemory result, LenB(ptr)\n</code></pre>\n<p>Yours has</p>\n<blockquote>\n<pre><code>VarType(m_fake.remoteVarType) = vbObject\nSet Object = m_fake.reference\nVarType(m_fake.remoteVarType) = m_fake.vbLongPtr\n</code></pre>\n</blockquote>\n<p>I think the only drawback of your approach over the standard (ignoring the dereferencing technique discussed above) is the conceptual one; the standard method requires understanding of Object pointers, the method you've used also requires additional knowledge of COM Variants, so is just a slightly steeper learning curve. In terms of performance, both have 2 dereferencing steps and one native <code>Set</code> call, so probably nothing in it (although you could time it to see if copying 2 bytes is faster than 4). Some better naming might help with the conceptual difficulties:</p>\n<pre><code>Private Declare PtrSafe Sub SetVariantType Lib &quot;msvbvm60&quot; Alias &quot;PutMem2&quot; (ByRef target As Variant, ByVal varTypeFlag As Integer)\n\n'Toggle the varType flag on the variant to create a temporary, non reference-counted Object\nSetVariantType m_fake.reference, vbObject\nSet Object = m_fake.reference\nSetVariantType m_fake.reference, vbLongPtr\n</code></pre>\n<p>Renaming imports introduces a simple layer of abstraction that clarifies the intent of the code, reducing the need for comments (in fact, you could even declare <code>varTypeFlag As VbVarType</code> - a Long with intellisense, since Longs are stored little-endian in VBA so the first 2 bytes at the pointer to a Long are the same as an Integer with the same decimal value). It also allows for type checking of parameters which is nice.</p>\n<h3>3) VTable check</h3>\n<p>Finally we come to it, what I think is the most innovative part of your code. As I mentioned at the start of this post, one of the downsides of the standard approach is that if the parent instance goes out of scope, and its memory is overwritten, then 2 things can happen:</p>\n<ul>\n<li>It can be overwritten with a valid object instance, perhaps even a separate instance of the same Class as the parent! That's really bad and will lead to a successful dereference but undefined behaviour and nasty hard to diagnose bugs.</li>\n<li>More likely (purely by probability) the memory will be re-allocated to an invalid object instance (i.e. something that's not an object, or maybe a load of zeros). This will likely lead to a crash - which seems nasty for the developer but is actually the best course of action when dealing with a bad pointer - at least you know something's definitely wrong.</li>\n</ul>\n<p>Your approach vastly reduces the number of headaches for developers by eliminating most of the false positives, so really well done for that. There are still a few exceptions I can see:</p>\n<ul>\n<li>If the parent instance is overwritten with another, different instance of the same class, it will have the same VTable so your check will not catch this. I don't know how likely this is to happen, but it may be worth investing in an additional interface for parent classes that exposes something like a GUID, so that once you successfully dereference the Object, you cast it to an <code>IGUID</code> interface and check it has a GUID that matches what you expect, if so then return the parent Object. This will bring false positives from this mode of failure down to zero (or as good as)</li>\n<li>If the parent instance has been overwritten with an invalid object, but it so happens that the first 4/8 bytes of the memory have been reused to store a string of binary that coincidentally matches the VTable pointer exactly, then once again your class will not catch this. What's worse is that rather than crashing, everything will plow on but with random data you don't own populating an imaginary instance of the parent class! Who knows what will happen... *</li>\n</ul>\n<p>What I'm trying to say is that the behavior of pointer dereferencing once the thing they point to has gone out of scope is undefined, so while returning <code>Nothing</code> is very nice for a developer and cuts down many of the false positives, it doesn't mean that the <code>Something</code> can be trusted any more than before, they will still need to perform other checks or employ other measures like carefully handling scope to ensure bugs don't creep in.</p>\n<p>*<sub>Well... IUnknown::AddRef will attempt to increase the class' reference count, incrementing the random chunk of memory at <code>ObjPtr + 4</code>. You may then cast to the <code>IGUID</code> interface, incrementing some other memory - which might actually succeed because the IUnknown methods are the real ones from a valid VTable and don't know the instance data isn't from a real object. If you get this far then it should be obvious the GUIDs don't match, but then what? It's possible you'll be able to undo all of the effects if you do work out that the instance you started with doesn't match the one you currently have, but it most likely assumes a lot about the layout of classes in memory which may be true generally, but what if the parent class isn't user defined, but a COM object from another library?\n</sub></p>\n<h3>D) Misc</h3>\n<blockquote>\n<pre><code>m_fake.vbLongPtr\n</code></pre>\n</blockquote>\n<p>This should not be linked to the class instance, it should be defined with conditional compilation</p>\n<pre><code>#If Win64 Then\n Const vbLongPtr As Long = vbLongLong\n#Else\n Const vbLongLong As Long = 20\n Const vbLongPtr As Long = vbLong\n#End If\n</code></pre>\n<p>Or if you don't trust <code>#Win64</code> and prefer to keep <code>VBA.VarType(ObjPtr(Nothing))</code> then put it in a standard module or a static class instance perhaps</p>\n<hr />\n<blockquote>\n<pre><code>CopyMemory ByVal VarPtr(m_fake.remoteVarType), vbInteger + VT_BYREF, 2\n</code></pre>\n</blockquote>\n<p>should be</p>\n<pre><code>CopyMemory m_fake.remoteVarType, vbInteger + VT_BYREF, 2\n</code></pre>\n<p><code>ByVal VarPtr(blah)</code> is like telling the function that the argument it is receiving &quot;has a value equal to the pointer to blah&quot; rather than &quot;is the pointer to blah&quot;. No difference</p>\n<hr />\n<blockquote>\n<pre><code>vTable As MEM_ADDRESS\n</code></pre>\n</blockquote>\n<p>I'd probably rename to <code>cachedVTablePointer</code> and get rid of <code>MEM_ADDRESS</code> altogether, just put the conditional compilation inside the <code>FAKE_REFERENCE</code> type</p>\n<p>Also you could simplify the vtable check potentially. Right now you dereference the original objptr and cache it. You then have the remote variable which essentially dereferences the objptr again, live, to see if the vtable pointer is still there. Finally you compare these two dereferenced variables for equality. You could instead check for equality in place without any explicit dereferencing using <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlcomparememory\" rel=\"nofollow noreferrer\">RtlCompareMemory</a> which can be imported from <code>kernel32</code> or <code>ntdll</code>\ne.g.</p>\n<pre><code>Private Declare Function EqualMemory Lib &quot;ntdll&quot; Alias &quot;RtlCompareMemory&quot; (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr\n</code></pre>\n<p>might be faster, maybe a bit clearer</p>\n<hr />\n<p><em>Overall, nice job, I've enjoyed reading through it and thinking about it</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-09T17:59:17.417", "Id": "488258", "Score": "0", "body": "For those intrested in the solution that solves the issues raised here go to this [answer](https://codereview.stackexchange.com/a/249125/227582)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T13:27:53.700", "Id": "502741", "Score": "0", "body": "I sincerely hope you don't mind me accepting my own answer as the 'accepted answer' thus making you lose score points. Without any doubt your answer was extremely useful and it is linked in the first row of my answer. I just want to make sure people see the actual solution at the top." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T19:52:47.210", "Id": "502813", "Score": "0", "body": "@CristianBuse Don't worry, the accumulated internet points don't really mean much to me, other than as a signal to know I've helped someone. Accepting an answer is kind of tricky on CR, unlike SO there isn't really a best answer here. So go ahead and set it whichever way you see fit!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T20:29:01.523", "Id": "502816", "Score": "1", "body": "Thanks! Same with me. Don't care about the points. The only reason I proceeded this way is because I know some readers simply skip to the accepted answer and don't bother reading the rest of them. I kind of covered both (I hope) by linking back to your great answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T13:56:04.413", "Id": "246125", "ParentId": "245660", "Score": "5" } }, { "body": "<p>The improvements found in this answer were triggered by the great <a href=\"https://codereview.stackexchange.com/a/246125/227582\">answer</a> that @Greedo provided on this question. Many thanks for his effort and apologies I took so long to act on his suggestions.</p>\n<hr />\n<p><strong>VTable check</strong><br />\nBy far, the most important aspect touched in the above-mentioned answer is that the VTable check is not sufficient to cover all cases (refer to point 3) and could lead to crashes or worse - pointing to a wrong object. The most likely case is when an instance of an object targeted by a WeakReference is terminated and the same memory address is overwritten with another different instance of the same class. It is very easy to produce:</p>\n<pre><code>Sub VTableCheckProblem()\n Dim c As Class1\n Dim w As New WeakReference\n \n Set c = New Class1\n c.x = 1\n Set w.Object = c\n \n Debug.Print w.Object.x 'Prints 1 (correct)\n Set c = Nothing\n Set c = New Class1\n Debug.Print w.Object.x 'Prints 0 (wrong - w.Object should return Nothing)\nEnd Sub\n</code></pre>\n<p>The suggested improvement:</p>\n<blockquote>\n<p>... it may be worth investing in an additional interface for parent classes that exposes something like a GUID, so that once you successfully dereference the Object, you cast it to an IGUID interface and check it has a GUID that matches what you expect, if so then return the parent Object ...</p>\n</blockquote>\n<p>works very nicely (tested) but only if an actual object resides at the referenced address.\nHowever, if this happens:</p>\n<blockquote>\n<p>If there parent instance has been overwritten with an invalid object, but it so happens that the first 4/8 bytes of the memory have been reused to store a string of binary that coincidentally matches the VTable pointer exactly, then once again your class will not catch this</p>\n</blockquote>\n<p>Indeed, this would crash the whole Application (tested).</p>\n<p>If not using an interface, then the issue stated <a href=\"https://stackoverflow.com/questions/63301510/can-i-safely-check-when-a-com-object-has-been-released-in-vba\">here</a> (same author) also crashes the Application.</p>\n<p><strong>Solution</strong><br />\nForce the implementation of an interface <em>IWeakable</em> by changing code (inside <code>WeakReference</code> class) from:</p>\n<pre><code>Public Property Let Object(obj As Object)\n</code></pre>\n<p>to:</p>\n<pre><code>Public Property Set Object(obj As IWeakable) \n</code></pre>\n<p>and then to somehow inform all the weak references pointing to the IWeakable object that the object has terminated (from that object's Class_Terminate or in another way).<br />\n<sup>Note that <em>Let</em> has changed to <em>Set</em> thanks to the <a href=\"https://codereview.stackexchange.com/a/245666/227582\">answer</a> provided by @MathieuGuindon</sup></p>\n<p>In order for the referenced object to inform the weak references about termination, it needs to be aware of all weak references pointing to it.</p>\n<p>Here is the <code>IWeakable</code> interface:</p>\n<pre><code>Option Explicit\n\nPublic Sub AddWeakRef(wRef As WeakReference)\nEnd Sub\n</code></pre>\n<p>and the modified property:</p>\n<pre><code>Public Property Set Object(obj As IWeakable)\n m_fake.reference = ObjPtr(GetDefaultInterface(obj))\n If m_fake.reference = 0 Then Exit Property\n '\n obj.AddWeakRef Me\nEnd Property\n</code></pre>\n<p>inside the improved <code>WeakReference</code> class:</p>\n<pre><code>Option Explicit\n\n#If Mac Then\n #If VBA7 Then\n Private Declare PtrSafe Function CopyMemory Lib &quot;/usr/lib/libc.dylib&quot; Alias &quot;memmove&quot; (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr\n #Else\n Private Declare Function CopyMemory Lib &quot;/usr/lib/libc.dylib&quot; Alias &quot;memmove&quot; (Destination As Any, Source As Any, ByVal Length As Long) As Long\n #End If\n#Else 'Windows\n 'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx\n #If VBA7 Then\n Private Declare PtrSafe Sub CopyMemory Lib &quot;kernel32&quot; Alias &quot;RtlMoveMemory&quot; (Destination As Any, Source As Any, ByVal Length As LongPtr)\n #Else\n Private Declare Sub CopyMemory Lib &quot;kernel32&quot; Alias &quot;RtlMoveMemory&quot; (Destination As Any, Source As Any, ByVal Length As Long)\n #End If\n#End If\n\n'https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oaut/3fe7db9f-5803-4dc4-9d14-5425d3f5461f\n'https://docs.microsoft.com/en-us/windows/win32/api/oaidl/ns-oaidl-variant?redirectedfrom=MSDN\n'Flag used to simulate ByRef Variants\nPrivate Const VT_BYREF As Long = &amp;H4000\n\nPrivate Type FAKE_REFERENCE\n remoteVarType As Variant 'Manipulates the variant type for 'reference'\n reference As Variant 'Will be holding the object reference/address\nEnd Type\n\n#If Win64 Then\n #If Mac Then\n Const vbLongLong As Long = 20 'Apparently missing for x64 on Mac\n #End If\n Const vbLongPtr As Long = vbLongLong\n#Else\n Const vbLongPtr As Long = vbLong\n#End If\n\nPrivate m_fake As FAKE_REFERENCE\n\n'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'Class Constructor\n'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nPrivate Sub Class_Initialize()\n 'Save address of the Variant that will hold the target reference/address\n m_fake.remoteVarType = VarPtr(m_fake.reference)\n '\n 'Change remoteVT variant type to Integer ByRef. This will now be linked\n ' to the first 2 bytes of the Variant holding the target reference\n 'Setting the VT_BYREF flag makes sure that the 2 bytes are not reclaimed\n ' twice when both 'remoteVarType' and 'reference' go out of scope\n 'And most importantly this gives the ability to switch the variant type of\n ' the reference at will, just by changing the Integer value of remoteVT\n CopyMemory m_fake.remoteVarType, vbInteger + VT_BYREF, 2\nEnd Sub\n\n'*******************************************************************************\n'Saves the memory address to an object's default interface (not to IWeakable)\n'*******************************************************************************\nPublic Property Set Object(obj As IWeakable)\n m_fake.reference = ObjPtr(GetDefaultInterface(obj))\n If m_fake.reference = 0 Then Exit Property\n '\n obj.AddWeakRef Me\nEnd Property\n\n'*******************************************************************************\n'Returns the default interface for an object\n'Casting from IUnknown to IDispatch (Object) forces a call to QueryInterface for\n' the IDispatch interface (which knows about the default interface)\n'*******************************************************************************\nPrivate Function GetDefaultInterface(obj As IUnknown) As Object\n Set GetDefaultInterface = obj\nEnd Function\n\n'*******************************************************************************\n'Retrieves the object pointed by the saved reference\n'No external API calls are needed!\n'*******************************************************************************\nPublic Property Get Object() As Object\n If m_fake.reference = 0 Then Exit Property\n '\n Set Object = DeReferenceByVarType(m_fake.remoteVarType)\nEnd Property\n\n'*******************************************************************************\n'Utility function needed to redirect remoteVT - See Class_Initialize comments\n'*******************************************************************************\nPrivate Function DeReferenceByVarType(ByRef remoteVT As Variant) As Object\n remoteVT = vbObject\n Set DeReferenceByVarType = m_fake.reference\n remoteVT = vbLongPtr\nEnd Function\n\n'*******************************************************************************\n'Needs to be called when the referenced object is terminated\n'*******************************************************************************\n#If VBA7 Then\nPublic Sub ObjectTerminated(refAddress As LongPtr)\n#Else\nPublic Sub ObjectTerminated(refAddress As Long)\n#End If\n If m_fake.reference = refAddress Then m_fake.reference = 0\nEnd Sub\n\n'*******************************************************************************\n'Returns the referenced memory address\n'*******************************************************************************\n#If VBA7 Then\nPublic Function ReferencedAddress() As LongPtr\n#Else\nPublic Function ReferencedAddress() As Long\n#End If\n ReferencedAddress = m_fake.reference\nEnd Function\n</code></pre>\n<p>All there is left to do is to inform the weak reference objects about the termination of the object they are targeting.<br />\nUnfortunately, the <em>Class_Terminate</em> event is not part of the interface so it cannot be forced to do anything.</p>\n<p>Because too much boilerplate code would need to be added to all classes implementing <em>IWeakable</em> it is probably best to encapsulate all the logic inside a separate class called <code>WeakRefInformer</code>:</p>\n<pre><code>'*******************************************************************************\n'' When terminated, informs all stored WeakReference objects about termination\n'*******************************************************************************\n\nOption Explicit\n\nPrivate m_refs As Collection\n#If VBA7 Then\n Private m_reference As LongPtr\n#Else\n Private m_reference As Long\n#End If\n\nPublic Sub AddWeakRef(wRef As WeakReference, obj As IWeakable)\n 'Store the address for the object implementing IWeakable\n 'When Class_Terminate is triggered, this will be passed to each\n ' WeakReference object in case the WeakReference will be set to point\n ' to a different target (in-between this call and the termination call)\n If m_reference = 0 Then m_reference = ObjPtr(GetDefaultInterface(obj))\n '\n If wRef.ReferencedAddress = m_reference Then m_refs.Add wRef\nEnd Sub\n\nPrivate Function GetDefaultInterface(obj As IUnknown) As Object\n Set GetDefaultInterface = obj\nEnd Function\n\nPrivate Sub Class_Initialize()\n Set m_refs = New Collection\nEnd Sub\n\nPrivate Sub Class_Terminate()\n Dim wRef As WeakReference\n '\n For Each wRef In m_refs\n wRef.ObjectTerminated m_reference\n Next wRef\n Set m_refs = Nothing\nEnd Sub\n</code></pre>\n<p>and the only code needed in any class implementing <em>IWeakable</em> would be:</p>\n<pre><code>Implements IWeakable\n\nPrivate Sub IWeakable_AddWeakRef(wRef As WeakReference)\n Static informer As New WeakRefInformer\n informer.AddWeakRef wRef, Me\nEnd Sub\n</code></pre>\n<p>The main idea is that by not exposing the contained <em>WeakRefInformer</em> object, it will surely go out of scope when the object implementing IWeakable is terminated.</p>\n<p>A quick visual example. Consider a &quot;parent&quot; object containing 2 &quot;child&quot; objects pointing back through weak references and a 3rd &quot;loose&quot; weak reference. This would look like:<br />\n<a href=\"https://i.stack.imgur.com/7VhWj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7VhWj.png\" alt=\"Reference diagram\" /></a></p>\n<p>Finally, a check is made inside the <em>ObjectTerminated</em> method of the <em>WeakReference</em> class to be sure the current referenced object has terminated (and not a previously referenced object).</p>\n<p><strong>Demo</strong></p>\n<p><code>Class1</code> class:</p>\n<pre><code>Option Explicit\n\nImplements IWeakable\n\nPublic x As Long\n\nPrivate Sub IWeakable_AddWeakRef(wRef As WeakReference)\n Static informer As New WeakRefInformer\n informer.AddWeakRef wRef, Me\nEnd Sub\n</code></pre>\n<p>And the test:</p>\n<pre><code>Sub TestWeakReference()\n Dim c As Class1\n Dim w1 As New WeakReference\n Dim w2 As New WeakReference\n Dim w3 As New WeakReference\n '\n Set c = New Class1\n c.x = 1\n '\n Set w1.Object = c\n Set w2.Object = c\n Set w3.Object = c\n \n Debug.Print w1.Object.x 'Prints 1 (correct)\n Debug.Print w2.Object.x 'Prints 1 (correct)\n Debug.Print w3.Object.x 'Prints 1 (correct)\n Debug.Print TypeName(w1.Object) 'Prints Class1 (correct)\n Debug.Print TypeName(w2.Object) 'Prints Class1 (correct)\n Debug.Print TypeName(w3.Object) 'Prints Class1 (correct)\n '\n Dim temp As Class1\n Set temp = New Class1\n Set w3.Object = temp\n temp.x = 2\n '\n Set c = Nothing 'Note this only resets w1 and w2 (not w3)\n Set c = New Class1\n c.x = 3\n '\n Debug.Print TypeName(w1.Object) 'Prints Nothing (correct)\n Debug.Print TypeName(w2.Object) 'Prints Nothing (correct)\n Debug.Print TypeName(w3.Object) 'Prints Class1 (correct)\n Debug.Print w3.Object.x 'Prints 2 (correct)\nEnd Sub\n</code></pre>\n<hr />\n<p>The rest of this answer is focused on all the other improvements suggested in the same mentioned <a href=\"https://codereview.stackexchange.com/a/246125/227582\">answer</a>.</p>\n<hr />\n<p><strong>Let/Set Performance</strong></p>\n<blockquote>\n<p>You use modified ByRef variants to do the memory manipulation in the performance critical area*<br />\n...<br />\n*well, if you don't count the Let procedure as performance critical, which it probably isn't in the typical use case. It's called once at the Child's birth, while the Get is potentially called many times in the Child's lifetime. However best not to make assumptions on how users will interact with your code, especially something as fundamental as this</p>\n</blockquote>\n<p>There is no need to do the vTable check since the weak reference is informed about the termination so <em>Let</em> (now <em>Set</em>) does not have any API calls anymore (so it is fast).\nThere is no need for the <em>GetRemoteAddress</em> method as well.</p>\n<p><strong>Speed comparison</strong></p>\n<blockquote>\n<p>Here I've run an integer dereference (read 2 bytes from one variable and write to another) many times (x axis) and calculated the average time per call (y axis) for the standard, ByRef and GetMem2 techniques, and the latter comes out on top.</p>\n</blockquote>\n<p>I've decided to test this on the 2 Windows computers I have. On my third machine, a Mac, the <em>msvbvm60</em> library is missing.</p>\n<p>Machine 1 (M1) configuration:<br />\nIntel Xeon CPU E5-2699A v4 @ 2.40GHz, 6.00GB RAM, 64-bit Operating System<br />\nExcel version 1902 (Build 11328.20420 Click-to-run)<br />\nVBA x32</p>\n<p>Machine 2 (M2) configuration:<br />\nIntel Core i7-9750H CPU @ 2.60GHz, 16.00GB RAM, 64-bit Operating System<br />\nExcel version 2007 (Build 13029.20344 Click-to-run)<br />\nVBA x64</p>\n<p>I've tested method:</p>\n<pre><code>Set Object = DeReferenceByVarType(m_fake.remoteVarType)\n</code></pre>\n<p>for <em>ByRef</em> and:</p>\n<blockquote>\n<pre><code>SetVariantType m_fake.reference, vbObject\nSet Object = m_fake.reference\nSetVariantType m_fake.reference, vbLongPtr\n</code></pre>\n</blockquote>\n<p>for <em>PutMem2</em></p>\n<p>inside a loop directly in the <code>Public Property Get Object() As Object</code> property using <a href=\"https://stackoverflow.com/a/198702/8488913\">CTimer</a>. <em>CTimer</em> seems to be consistent with the VBA Timer function for the longer runs (where the latter has enough resolution).</p>\n<p>On Machine 1 I got:<br />\n<a href=\"https://i.stack.imgur.com/uMX1X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uMX1X.png\" alt=\"M1 chart\" /></a><br />\nwhich seems to be off by a factor of 10 from what the other answer showed for the <em>ByRef</em> approach and way off (much slower) for the <em>PutMem2</em> approach.</p>\n<p>On machine 2 I got:<br />\n<a href=\"https://i.stack.imgur.com/N8JZ4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/N8JZ4.png\" alt=\"M2 prompt\" /></a></p>\n<p>Since that is not really helpful, I compared the <em>ByRef</em> approach between M1 and M2:<br />\n<a href=\"https://i.stack.imgur.com/y19wD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y19wD.png\" alt=\"enter image description here\" /></a><br />\nwhich seems to be consistent.</p>\n<p>Considering that the <em>msvbvm60.dll</em> library is only present on some Windows machines and that the speed is quite different from machine to machine (looking at this answer and the mentioned answer), the ByRef approach seems to be the correct choice. Readability has been improved slightly by wrapping the calls into the <em>DeReferenceByVarType</em> function.</p>\n<p><strong>Misc 1</strong></p>\n<blockquote>\n<p>This should not be linked to the class instance, it should be defined with conditional compilation</p>\n<pre><code>#If Win64 Then\n Const vbLongPtr As Long = vbLongLong\n#Else\n Const vbLongLong As Long = 20\n Const vbLongPtr As Long = vbLong\n#End If \n</code></pre>\n</blockquote>\n<p>True, with the added note that on Mac the vbLongLong is missing for x64:</p>\n<pre><code>#If Win64 Then\n #If Mac Then\n Const vbLongLong As Long = 20 'Apparently missing for x64 on Mac\n #End If\n Const vbLongPtr As Long = vbLongLong\n#Else\n Const vbLongPtr As Long = vbLong\n#End If\n</code></pre>\n<p><strong>Misc 2</strong></p>\n<blockquote>\n<p><code>ByVal VarPtr(blah)</code> is like telling the function that the argument it is receiving &quot;has a value equal to the pointer to blah&quot; rather than &quot;is the pointer to blah&quot;. No difference</p>\n</blockquote>\n<p>Absolutely. I've only noticed this when reading the answer. It was a leftover from previous testing code where the assignment happened in the 9th byte of the code with:</p>\n<pre><code>CopyMemory ByVal VarPtr(m_fake.vTableByRef) + 8, m_fake.reference, 8 'Or 4 on x32\n</code></pre>\n<p>which obviously is just a mere:</p>\n<pre><code>m_fake.vTableByRef = m_fake.reference\n</code></pre>\n<p>It got propagated through copy-paste. Nice attention to detail by @Greedo</p>\n<hr />\n<p>As stated in the question, the full code with explanation is under MIT license on GitHub at <a href=\"https://github.com/cristianbuse/VBA-WeakReference\" rel=\"nofollow noreferrer\">VBA-WeakReference</a>.</p>\n<p>Many thanks to @Greedo and @MathieuGuindon for their contribution!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-09T15:04:56.243", "Id": "249125", "ParentId": "245660", "Score": "5" } } ]
{ "AcceptedAnswerId": "249125", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T09:48:26.273", "Id": "245660", "Score": "11", "Tags": [ "vba", "weak-references" ], "Title": "Simulated WeakReference class" }
245660
<p>I made program for parsing CSV and XLS files, I just want to know if there is some space to improvement and is it all written good?</p> <p>My goal is when I got CSV or XLS file to parse that file and got list of objects for specific class, besides of getting list I made metod to populate datatable and show data in DataGridView.</p> <p>I made two custom attribute classes for specifying column position, column name, column caption, data format (e.g. Date - &quot;dd.MM.yyyy&quot; and similar...) and skip from parsing.</p> <pre><code>public class FileHelperAttribute : Attribute { public int DataPosition { get; set; } public string Format { get; set; } public bool Skip { get; set; } public FileHelperAttribute(int position, string format = &quot;&quot;, bool skip = false) { this.DataPosition = position; this.Format = format; this.Skip = skip; } } public class DataColumnHelperAttribute : Attribute { public string ColumnName { get; set; } public string Caption { get; set; } public DataColumnHelperAttribute(string columnName, string caption) { this.ColumnName = columnName; this.Caption = caption; } } </code></pre> <p>I defined generic interface IFileParser:</p> <pre><code>public interface IFileParser&lt;out T&gt; { bool HasHeader { get; set; } IEnumerable&lt;T&gt; ReadFile(string path); DataTable GetDataTable(string path); } </code></pre> <p>And generic class CsvParser which implements interface IFileParser:</p> <pre><code>public class CsvParser&lt;T&gt; : IFileParser&lt;T&gt; { public bool HasHeader { get; set; } public IEnumerable&lt;T&gt; ReadFile(string path) { using (TextFieldParser csvParser = new TextFieldParser(path)) { List&lt;T&gt; lstObj = new List&lt;T&gt;(); csvParser.SetDelimiters(&quot;;&quot;); if (this.HasHeader) csvParser.ReadLine(); while (!csvParser.EndOfData) { string[] fields = csvParser.ReadFields(); T obj = Activator.CreateInstance&lt;T&gt;(); foreach (var prop in obj.GetType().GetProperties().Where(p =&gt; p.IsDefined(typeof(FileHelperAttribute), true) &amp;&amp; p.GetCustomAttributes(typeof(FileHelperAttribute), true) .Where(a =&gt; (a as FileHelperAttribute).Skip) .Any()).ToList()) { var attribute = (FileHelperAttribute)prop.GetCustomAttributes(typeof(FileHelperAttribute), true)[0]; int dataPosition = attribute.DataPosition; string format = attribute.Format; string value = fields[dataPosition]; if (string.IsNullOrEmpty(format)) { if (prop.PropertyType == typeof(DateTime)) { var ci = new CultureInfo(CultureInfo.InvariantCulture.LCID); ci.Calendar.TwoDigitYearMax = 2099; //default 2029 prop.SetValue(obj, Convert.ChangeType(DateTime.ParseExact(value, format, ci), prop.PropertyType), null); } else prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType), null); } else { if (prop.PropertyType == typeof(decimal)) prop.SetValue(obj, Convert.ChangeType(value.Replace(&quot;.&quot;, &quot;,&quot;), prop.PropertyType), null); else if (prop.PropertyType == typeof(bool)) prop.SetValue(obj, Convert.ChangeType(int.Parse(value), prop.PropertyType), null); else prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType), null); } } lstObj.Add(obj); } return lstObj; } } public DataTable GetDataTable(string path) { List&lt;T&gt; lstObj = ReadFile(path) as List&lt;T&gt;; var dataTable = new DataTable(typeof(T).Name); foreach (var prop in typeof(T).GetProperties().Where(p =&gt; p.IsDefined(typeof(DataColumnHelperAttribute), true)).ToList()) { var attribute = (DataColumnHelperAttribute)prop.GetCustomAttributes(typeof(DataColumnHelperAttribute), true)[0]; string columnName = attribute.ColumnName; string caption = attribute.Caption; dataTable.Columns.Add(columnName, prop.PropertyType).Caption = caption; } foreach (var obj in lstObj) { DataRow dataRow = dataTable.NewRow(); foreach (var prop in typeof(T).GetProperties().Where(p =&gt; p.IsDefined(typeof(DataColumnHelperAttribute), true)).ToList()) { var attribute = (DataColumnHelperAttribute)prop.GetCustomAttributes(typeof(DataColumnHelperAttribute), true)[0]; string columnName = attribute.ColumnName; dataRow[columnName] = Convert.ChangeType(prop.GetValue(obj, null), prop.PropertyType) != null ? Convert.ChangeType(prop.GetValue(obj, null), prop.PropertyType) : DBNull.Value; } dataTable.Rows.Add(dataRow); } dataTable.AcceptChanges(); return dataTable; } } </code></pre> <p>I didn't write XlsParser yet but I'm planning to write using spreadsheet gear library, but it will work similar as csv parser class.</p> <p>I made two classes Category and User which represents data from file.</p> <pre><code>public class Data { } public class Category : Data { [FileHelper(0)] [DataColumnHelper(&quot;CODE&quot;, &quot;Code&quot;)] public string Code { get; set; } [FileHelper(1)] [DataColumnHelper(&quot;NAME&quot;, &quot;Name&quot;)] public string Name { get; set; } [FileHelper(2)] [DataColumnHelper(&quot;ACTIVE&quot;, &quot;Active&quot;)] public bool Active { get; set; } [FileHelper(3)] [DataColumnHelper(&quot;START_DATE&quot;, &quot;Start date&quot;)] public DateTime StartDate { get; set; } } public class User : Data { [FileHelper(0)] [DataColumnHelper(&quot;FIRST_NAME&quot;, &quot;First name&quot;)] public string FirstName { get; set; } [FileHelper(1)] [DataColumnHelper(&quot;LAST_NAME&quot;, &quot;Last name&quot;)] public string LastName { get; set; } [FileHelper(2)] [DataColumnHelper(&quot;ADDRESS&quot;, &quot;Address&quot;)] public string Address { get; set; } [FileHelper(3)] [DataColumnHelper(&quot;PHONE&quot;, &quot;Phone&quot;)] public string Phone { get; set; } } public enum DataType { Category, User } public class DataFactory { public static IFileParser&lt;Data&gt; Create(DataType type) { switch (type) { case DataType.Category: return new CsvParser&lt;Category&gt;(); case DataType.User: return new CsvParser&lt;User&gt;(); default: throw new NotImplementedException(&quot;&quot;); } } } static void PopulateDataGridView(string path) { IFileParser&lt;Data&gt; fileParser = FileParser.Factory(DataType.User); DataTable dataTable = fileParser.GetDataTable(path); ... // pass datatable to DataGridView control... } </code></pre> <p>My question now is it better to keep separately attribute classes or make one attribute class with all neded information (properties)? If I keep them separately is it better to make another class that would had method which returns DataTable?</p> <p>Edit: Changed factory class.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T16:21:19.943", "Id": "245665", "Score": "3", "Tags": [ "c#", "object-oriented", "design-patterns" ], "Title": "File parser for csv and xls files" }
245665
<p>I am creating an <span class="math-container">\$O(n)\$</span> solver for an <span class="math-container">\$Ax = b\$</span> system where <span class="math-container">\$A\$</span> has the form <span class="math-container">\$ A = \begin{pmatrix} a_1 &amp; b_1 &amp;&amp;&amp;d_{u}\\ c_1 &amp; a_2 &amp; b_2\\&amp; \ddots &amp; \ddots &amp; \ddots\\&amp; &amp; c_{n-2}&amp;a_{n-1}&amp; b_{n-1}\\ d_{l} &amp;&amp;&amp;c_{n-1}&amp; a_{n} \end{pmatrix} \$</span></p> <p>To do this, I wrote a basic function that just performs Gaussian elimination. I was wondering if there are any immediate ways to improve the code below. My main goal is obviously speed, so I would like to know of any tricks that would minimize memory usage (while preserving <span class="math-container">\$A\$</span>) and the number of computations being performed. I have already made <span class="math-container">\$A\$</span> into a sparse matrix which helped a fair bit already. Also to note, that even though the code is in python, it's not written in a pythonic way because I typically develop initial code (for easier debugging) in python before writing the final version in C.</p> <pre><code>def solve_periodic_sparseA_vectB(A, b, results, corner_upper, corner_lower): n = b.shape[0] results[0] = b[0] results[n - 1] = b[n - 1] supra_diag = A[2].copy() last_col = np.zeros(n - 1) # excludes final val main last_col[0] = corner_upper last_col[n - 2] = supra_diag[n - 2] last_row_val = corner_lower current_main = A[1][0] next_main = A[1][1] last_main = A[1][n - 1] for i in range(n - 2): # divide by pivot ci = current_main results[i] = results[i] / ci supra_diag[i] = A[2][i + 1] / ci last_col[i] /= ci # -aRi + Ri+1 --&gt; Ri+1 a = A[0][i] results[i + 1] = b[i + 1] - a * results[i] next_main -= a * supra_diag[i] last_col[i + 1] -= a * last_col[i] # -aRi + Rn --&gt; Rn a = last_row_val results[n - 1] = results[n - 1] - a * results[i] last_main -= a * last_col[i] last_row_val = (A[0][i + 1] if i == n - 3 else 0.0) - a * supra_diag[i] current_main = next_main next_main = A[1][i + 2] i = n - 2 # divide by pivot ci = current_main last_col[i] /= ci results[i] /= ci a = last_row_val results[n - 1] -= a * results[i] last_main -= a * last_col[i] # solve last results[n - 1] /= last_main # last column for i in range(n - 1): results[i] -= last_col[i] * results[n - 1] # supra-diagonal (final pass) for i in range(n - 2, 0, -1): results[i - 1] -= supra_diag[i - 1] * results[i] </code></pre> <p>EDIT: Example usage would be something like</p> <pre><code>import numpy as np if __name__ == '__main__': sig = 1.0 n = 5 # sparse matrix where rows 0 1 2 are the sub main and supra diagonals respectively A = np.r_['0,2', np.full(n, -sig), np.full(n, 1 + 2 * sig), np.full(n, -sig)] b = np.arange(n, dtype=np.float64) x = np.empty_like(b) solve_periodic_sparseA_vectB(A, b, x, -sig, -sig) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:34:37.783", "Id": "482655", "Score": "0", "body": "Can you include your imports, as well as a small example matrix to run equivalence tests?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T16:41:10.960", "Id": "245667", "Score": "4", "Tags": [ "python", "performance", "algorithm", "matrix" ], "Title": "Naive Solver of Matrix with Periodic Boundary Conditions Feedback" }
245667
<p>My first attempt at a sudoku solver using the backtrack algorithm.</p> <pre><code># Functions for solving Sudoku puzzles of any size # NumPy makes it easier to work with 2D arrays import numpy as np def find_empty_cells(board): &quot;&quot;&quot;Traverse the board and return a tuple of positions of empty cells&quot;&quot;&quot; return [(i, j) for i in range(len(board)) for j in range(len(board[i])) if board[i][j] == 0] def check_rows_cols(board, cell, test_value): &quot;&quot;&quot;Return True if the given number is legal i.e. does not appear in the current row or column Return False if the given number is illegal &quot;&quot;&quot; if test_value not in board[cell[0], :] and test_value not in board[:, cell[1]]: return True return False def check_subgrid(board, cell, test_value, subgrid_height, subgrid_width): &quot;&quot;&quot;Return True if the given number is legal i.e. does not appear in the current subgrid Return False if the given number is illegal &quot;&quot;&quot; # Find subgrid coordinates # Map cell coordinates to top-left corner of subgrid subgrid_coords = ((cell[0] // subgrid_height) * subgrid_height, (cell[1] // subgrid_width) * subgrid_width) # Use that top-left corner to define subgrid subgrid = board[subgrid_coords[0]:subgrid_coords[0]+subgrid_height, subgrid_coords[1]:subgrid_coords[1]+subgrid_width] if test_value not in subgrid: return True return False def update_cell(board, cell, available_nums, subgrid_height, subgrid_width): &quot;&quot;&quot;Try to update the current cell Return a two-tuple, with second element as the board First element is True if the cell was successfully updated First element is False otherwise &quot;&quot;&quot; # Get current cell value and index cell_value = board[cell[0], cell[1]] cell_value_index = available_nums.index(cell_value) # available_nums is a list of numbers that could populate a cell # If we backtracked and the current cell has no more options, reset it and go to the previous cell if cell_value_index == len(available_nums) - 1: board[cell[0], cell[1]] = 0 return (False, board) if subgrid_height == 0: # Don't call check_subgrid if there aren't subgrids (e.g. on a 3x3 board) # Check all numbers from the value of the current cell (the earlier numbers have already been checked) for num in available_nums[cell_value_index + 1:]: # If the number is legal, update the cell and move on if check_rows_cols(board, cell, num): board[cell[0], cell[1]] = num return (True, board) # Otherwise, none of the numbers worked and we need to backtrack elif available_nums.index(num) == len(available_nums) - 1: board[cell[0], cell[1]] = 0 return (False, board) else: # Call check_subgrid otherwise for num in available_nums[cell_value_index + 1:]: if check_rows_cols(board, cell, num) and check_subgrid(board, cell, num, subgrid_height, subgrid_width): board[cell[0], cell[1]] = num return (True, board) elif available_nums.index(num) == len(available_nums) - 1: board[cell[0], cell[1]] = 0 return (False, board) def solve(board, empty_cells, available_nums, subgrid_height, subgrid_width): &quot;&quot;&quot;Perform the backtrack algorithm&quot;&quot;&quot; count = 0 while count != len(empty_cells): try: result = update_cell(board, empty_cells[count], available_nums, subgrid_height, subgrid_width) except IndexError: # Subgrid dimensions might be wrong return [0, 0] # Could return None, but that gives a ValueError in main() # The reason is that if solve() produces an array, then main() will need to compare None with an array # This produces a ValueError # So we just never return None, instead we return a definitely incorrect array if result[0] is False: # Cell was not updated, so backtrack count -= 1 else: # Cell was updated, so carry on to the next cell count += 1 return result[1] def main(BOARD, available_nums, subgrid_height=0, subgrid_width=0): board = np.array(BOARD) # Make a copy of the original board empty_cells = find_empty_cells(board) board = solve(board, empty_cells, available_nums, subgrid_height, subgrid_width) if board == [0, 0]: return &quot;Sudoku not solvable, check subgrid dimensions or numbers input onto board&quot; else: board = [list(row) for row in board] # Convert from NumPy array back to 2D Python list return board # Solved puzzle </code></pre> <p>An example call to this solver might be:</p> <pre><code>board = [ [0, 0, 9, 0, 6, 0, 4, 0, 1] .... .... 8 rows later .... [1, 0, 0, 2, 0, 5, 8, 0, 3] ] solution = main(board, list(range(10)), 3, 3) </code></pre> <p>I'm mainly interested in improving the code quality and efficiency of this implementation. I've designed it to generalise to any size board, which may add some overhead, such as checking whether or not there are sub grids. I'm also aware that there are better methods, such as recursion. In fact, I have also written a recursive version, which is much faster than this, but I would still like to improve this version, as it is quite slow on some of the <a href="https://www.sudokuoftheday.com/about/difficulty/" rel="nofollow noreferrer">diabolical</a> rated puzzles.</p>
[]
[ { "body": "<p>Just a couple notes.</p>\n<h1><code>check_row_cols</code></h1>\n<p>This function can just be:</p>\n<pre><code>def check_row_cols(board, cell, test_value):\n return test_value not in board[cell[0], :] and test_value not in board[:, cell[1]]\n</code></pre>\n<p>Since the expression results in a boolean value, you can return the expression itself.</p>\n<h1><code>check_subgrid</code></h1>\n<p>Same concept as above:</p>\n<pre><code>def check_subgrid(...):\n ...\n\n return test_value not in subgrid\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T20:27:55.643", "Id": "245674", "ParentId": "245669", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T17:30:22.350", "Id": "245669", "Score": "2", "Tags": [ "python", "python-3.x", "sudoku", "backtracking" ], "Title": "Python sudoku solver using backtrack algorithm" }
245669
<p>I am working on a little project where I need to scan all the files present in a folder on the disk and load it in memory. Below is my code which does that exactly and works fine.</p> <p>Here are the steps:</p> <ul> <li>On the disk there is already a default <code>Records</code> folder which has all the default config files present. This is to fallback if in case something gets wrong or the <code>loadDefaultFlag</code> is enabled.</li> <li>There are also new config files present as a <code>tar.gz</code> file (max 100 MB size) in a remote url location which I need to download and store it on disk in <code>_secondaryLocation</code> if <code>loadDefaultFlag</code> is disabled.</li> <li>Depending on whether <code>loadDefaultFlag</code> is present or not - we will either load default local files already present on the disk or load it from <code>_secondaryLocation</code> (after downloading it from the remote url location).</li> <li>During server startup call goes to my <code>RecordManager</code> constructor where it checks whether <code>loadDefaultFlag</code> is enabled or not and basis on that it loads the file either from <code>Records</code> folder as mentioned in point 1 or download new configs from url as mentioned in point 2 and then load it in memory.</li> </ul> <p>I get the json value of <code>configKey</code> from <code>IConfiguration</code> object in my constructor which has all the details whether to use default configs or download files from a remote url and store it on disk. Sample content of <code>configKey</code> object is -</p> <pre><code>{&quot;loadDefaultFlag&quot;: &quot;false&quot;, &quot;remoteFileName&quot;:&quot;data-1234.tgz&quot;, ...} </code></pre> <p>Basis on the above json value I figure out what to do as outlined in above series of points.</p> <p>Below is my code:</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Net.Http; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using Polly; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; public class RecordManager { private readonly string _remoteUrl = &quot;remote-url-from-where-to-download-new-configs&quot;; private readonly string _secondaryLocation = &quot;SecondaryConfigs&quot;; private readonly string _localPath = null; private readonly IConfiguration _configuration; private static HttpClient _httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(3) }; public RecordManager(IConfiguration configuration, string localPath = &quot;Records&quot;) { _localPath = localPath ?? throw new ArgumentNullException(nameof(localPath)); _configuration = configuration; ChangeToken.OnChange(configuration.GetReloadToken, _ =&gt; ConfigChanged(), new object()); string jsonValue = configuration[&quot;configKey&quot;]; if (!string.IsNullOrWhiteSpace(jsonValue)) { RecordPojo dcc = JsonConvert.DeserializeObject&lt;RecordPojo&gt;(jsonValue); Boolean.TryParse((string)dcc.loadDefaultFlag, out bool loadDefaultFlag); string remoteFileName = dcc.remoteFileName; if (!loadDefaultFlag &amp;&amp; !string.IsNullOrWhiteSpace(remoteFileName)) { // get all the configs from the url and load it in memory if (!LoadAllConfigsInMemory(_url, remoteFileName, _secondaryLocation).Result) throw new ArgumentNullException(nameof(_records)); } else { var recordsList = LoadDefaultConfigsInMemory() ?? throw new ArgumentNullException(&quot;recordsList&quot;); if (recordsList.Count == 0) throw new ArgumentNullException(&quot;recordsList&quot;); if (!UpdateRecords(recordsList)) throw new ArgumentNullException(nameof(_records)); } } else { var recordsList = LoadDefaultConfigsInMemory() ?? throw new ArgumentNullException(&quot;recordsList&quot;); if (recordsList.Count == 0) throw new ArgumentNullException(&quot;recordsList&quot;); if (!UpdateRecords(recordsList)) throw new ArgumentNullException(nameof(_records)); } } // This method will load all the configs downloaded from the url in memory private async Task&lt;bool&gt; LoadAllConfigsInMemory(string url, string fileName, string directory) { IList&lt;RecordHolder&gt; recordsList = new List&lt;RecordHolder&gt;(); try { recordsList = GetRecords(url, fileName, directory); if (recordsList == null || recordsList.Count == 0) { throw new ArgumentException(&quot;No config records loaded from remote service.&quot;); } return UpdateRecords(recordsList); } catch (Exception ex) { // log error } // falling back to load default configs recordsList = LoadDefaultConfigsInMemory(); return UpdateRecords(recordsList); } // This will return list of all the RecordHolder by iterating on all the files. private IList&lt;RecordHolder&gt; GetRecords(string url, string fileName, string directory) { var recordsList = new List&lt;RecordHolder&gt;(); var recordPaths = GetAllTheFiles(url, fileName, directory); for (int i = 0; i &lt; recordPaths.Count; i++) { var configPath = recordPaths[i]; if (File.Exists(configPath)) { var fileDate = File.GetLastWriteTimeUtc(configPath); string fileContent = File.ReadAllText(configPath); var pathPieces = configPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); var fileName = pathPieces[pathPieces.Length - 1]; recordsList.Add(new RecordHolder() { Name = fileName, Date = fileDate, JDoc = fileContent }); } } return recordsList; } // This method will return list of all the files by downloading a tar.gz file // from a url and then extracting contents of tar.gz into a folder. // Maybe this code can be simplified better - I am doing lot of boolean checks here // not sure if that's good. private IList&lt;string&gt; GetAllTheFiles(string url, string fileName, string directory) { IList&lt;string&gt; allFiles = new List&lt;string&gt;(); bool isDownloadSuccessful = DownloadConfigs(url, fileName).Result; if (!isDownloadSuccessful) { return allFiles; } bool isExtracted = ExtractTarGz(fileName, directory); if (!isExtracted) { return allFiles; } return GetFiles(directory); } // This method will download a tar.gz file from a remote url and save it onto the disk // in a particular folder private async Task&lt;bool&gt; DownloadConfigs(string remoteUrl, string fileName) { var policyResult = await Policy .Handle&lt;TaskCanceledException&gt;() .WaitAndRetryAsync(retryCount: 5, sleepDurationProvider: i =&gt; TimeSpan.FromMilliseconds(500)) .ExecuteAndCaptureAsync(async () =&gt; { using (var httpResponse = await _httpClient.GetAsync(remoteUrl + fileName).ConfigureAwait(false)) { httpResponse.EnsureSuccessStatusCode(); return await httpResponse.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } }).ConfigureAwait(false); if (policyResult.Outcome == OutcomeType.Failure || policyResult.Result == null) return false; try { // write all the content of tar.gz file onto the disk File.WriteAllBytes(fileName, policyResult.Result); return true; } catch (Exception ex) { // log error return false; } } // This method extracts contents of tar.gz file in a directory private bool ExtractTarGz(string fileName, string directory) { try { Stream inStream = File.OpenRead(fileName); Stream gzipStream = new GZipInputStream(inStream); TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream); tarArchive.ExtractContents(directory); tarArchive.Close(); gzipStream.Close(); inStream.Close(); } catch (Exception ex) { // log error return false; } return true; } // This method gets list of all files in a folder matching particular suffix private IList&lt;string&gt; GetFiles(string path) { var allFiles = new List&lt;string&gt;(); try { var jsonFiles = Directory.GetFiles(path, &quot;*.json&quot;, SearchOption.AllDirectories); var testFiles = Directory.GetFiles(path, &quot;*.txt&quot;, SearchOption.AllDirectories); allFiles.AddRange(jsonFiles); allFiles.AddRange(testFiles); } catch (UnauthorizedAccessException ex) { // log error } return allFiles; } // This method will load all the default local configs in memory // if `loadDefaultFlag` is enabled or cannot talk to remote url location private IList&lt;RecordHolder&gt; LoadDefaultConfigsInMemory() { var configs = new List&lt;RecordHolder&gt;(); var recordPaths = GetFiles(_localPath); for (int i = 0; i &lt; recordPaths.Count; i++) { var configPath = recordPaths[i]; if (File.Exists(configPath)) { var fileDate = File.GetLastWriteTimeUtc(configPath); string fileContent = File.ReadAllText(configPath); var pathPieces = configPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); var fileName = pathPieces[pathPieces.Length - 1]; configs.Add(new RecordHolder() { Name = fileName, Date = fileDate, JDoc = fileContent }); } } return configs; } private bool UpdateRecords(IList&lt;RecordHolder&gt; recordsHolder) { // leaving out this code as it just updates the config in memory } } </code></pre> <p>Opting for a code review here. I am specifically interested in the way I have designed and implemented my code. I am sure there must be a better way to rewrite this whole class efficiently with clear design and implementation. Also there are few methods above which could be written in a better and efficient way as well.</p> <p>The idea is very simple - During server startup, either load default local configs already present on the disk or load it from a secondary folder on the disk after downloading it from remote url location.</p>
[]
[ { "body": "<h2>Coalesce abuse</h2>\n<p>There's no reason for this to use <code>??</code>, since the value of the second half of the expression isn't actually used:</p>\n<pre><code>_localPath = localPath ?? throw new ArgumentNullException(nameof(localPath));\n \n</code></pre>\n<p>Just use <code>if (localPath == null)</code>.</p>\n<h2>Anonymous lambda</h2>\n<p>Try replacing this:</p>\n<pre><code>_ =&gt; ConfigChanged()\n</code></pre>\n<p>with <code>ConfigChanged</code> (no parens). This should bind to the function itself rather than wrapping it in a lambda. Under certain circumstances I seem to remember this needing a cast and I'm not sure whether that's needed here.</p>\n<h2>Log the error</h2>\n<pre><code> catch (Exception ex)\n {\n // log error\n }\n</code></pre>\n<p>Okay? But you didn't log it. That needs to happen.</p>\n<h2>For-each</h2>\n<pre><code> for (int i = 0; i &lt; recordPaths.Count; i++)\n {\n var configPath = recordPaths[i];\n</code></pre>\n<p>should use a simple <code>foreach</code>.</p>\n<h2>IDisposable</h2>\n<p>This:</p>\n<pre><code> TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);\n tarArchive.ExtractContents(directory);\n tarArchive.Close();\n</code></pre>\n<p>should be checked for inheritance from <code>IDisposable</code>. If that is the case, remove your explicit <code>Close</code> and use a <code>using</code> statement. <code>using</code> should also be used for the two <code>Stream</code>s in that method.</p>\n<p>See <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement</a> for more details.</p>\n<p>Read <a href=\"https://icsharpcode.github.io/SharpZipLib/help/api/ICSharpCode.SharpZipLib.Tar.TarArchive.html\" rel=\"nofollow noreferrer\">your library's documentation</a>:</p>\n<blockquote>\n<p>Implements</p>\n<p>System.IDisposable</p>\n</blockquote>\n<p>So it can be used as <code>using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream)) { ... }</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:11:34.493", "Id": "482550", "Score": "0", "body": "Thanks for your suggestion. Can you provide an example for the last `IDisposable` case basis on my example? I am not sure I understand that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:14:09.303", "Id": "482551", "Score": "0", "body": "You need to show your `using`s for me to be able to comment further." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:15:16.973", "Id": "482552", "Score": "0", "body": "I don't have any `using` code in my class and I am not using it also. That method just extracts the contents of `tar.gz` file in a directory. Whatever code I have provided is the exact same code I use also." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:17:54.463", "Id": "482553", "Score": "1", "body": "Your code will not compile without `using` directives at the top to import the symbols you need." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:19:02.187", "Id": "482554", "Score": "0", "body": "ohh you mean that `using` sorry. I just updated my question with that details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T02:17:32.213", "Id": "482559", "Score": "0", "body": "thanks for the update. got it now. do you see any other design or implementation changes I can do in my above code? There are lot of methods that can be rewritten in a better way I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T05:56:46.217", "Id": "482567", "Score": "1", "body": "Is your first point true?: If you explicitly provide a `null` for `localPath` then the exception is thrown." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:10:19.960", "Id": "482604", "Score": "0", "body": "@HenrikHansen Yes, my first point is true. I know that this works now, but it's awkward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:26:03.077", "Id": "482605", "Score": "0", "body": "@HenrikHansen What I mean by \"used\" in this case is that, where the second half is _evaluated_, its value is discarded." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:07:43.630", "Id": "245680", "ParentId": "245670", "Score": "3" } }, { "body": "<p>In additional to @Reinderien answer:</p>\n<p><strong>Constructor</strong></p>\n<p>You're doing much work in your constructor, consider moving most of the configuration part into a separate method, and just keep the constructors to work on validating its parameters only, if you want any other code to be executed with the constructor, just put it inside a private method, then recall it from the constructor to initialize your configuration or required logic. Also, don't use optional parameters on the constructor arguments. Use overloads instead, as it would be safer for future changes, and also, to avoid any confusion.</p>\n<p><strong>Naming Convention</strong></p>\n<p>while your naming methodology is partially clear to me, but it took me sometime to follow up your code because of the naming confusion. For instance, <code>GetAllTheFiles</code> and <code>GetFiles</code> this confused me at first, but when I dig into the code, it came clear that <code>GetFiles</code> is for getting the files from the local disk, and <code>GetAllTheFiles</code> would download the remotely file. So, you need to consider naming your objects based on their logic and result. for instance, <code>GetAllTheFiles</code> can be renamed to something like `GetConfigurationFileFromServer' (just an example).</p>\n<p><strong>Methods</strong></p>\n<p>It's partially unclear, and could be misled others. As your requirements is clear (switch between local and remote configuration). you'll need to minimize them to have a better code clarity. Some methods can be used as helper methods like <code>GetFiles</code> so it would be useful to create a separate helper class for managing files, and then use this class. This way, you'll have a chance of reusing these methods in any part of the project.</p>\n<p><strong>Design Pattern</strong></p>\n<p>I suggest to try to find a design pattern that fits your current project, as designing your objects in a clear design would give you many advantages in which would make it easier to bind for future changes.</p>\n<p>For instance, you could use Fluent API design pattern, here is an example of your code (including some changes based on the notes above).</p>\n<pre><code>public class RecordManager\n{\n private const string _remoteUrl = &quot;remote-url-from-where-to-download-new-configs&quot;;\n private string _remoteFileName; \n \n private const string SecondaryLocation = &quot;SecondaryConfigs&quot;;\n private readonly IConfiguration _configuration;\n private readonly string _localPath; \n private IEnumerable&lt;RecordHolder&gt; _records; \n private readonly FileHelper _fileHelper = new FileHelper();\n \n public enum ConfigLocation { System, Local, Remote }\n \n public RecordManager(IConfiguration configuration, string localPath)\n {\n if(configuration == null) { throw new ArgumentNullException(nameof(configuration)); }\n \n if(localPath?.Length == 0) { throw new ArgumentNullException(nameof(localPath)); }\n \n _localPath = localPath;\n _configuration = configuration;\n ChangeToken.OnChange(configuration.GetReloadToken, _ =&gt; ConfigChanged(), new object());\n }\n \n public RecordManager(IConfiguration configuration) : this(configuration, &quot;Records&quot;) { } \n \n public RecordManager LoadConfigurationsFrom(ConfigLocation location)\n {\n switch(location)\n {\n case ConfigLocation.Remote:\n _records = GetConfigurationsFromServer();\n break; \n case ConfigLocation.Local:\n _records = GetConfigurationsFromLocalFiles();\n break; \n case ConfigLocation.System:\n _records = IsConfigruationFromServer() ? GetConfigurationsFromServer() : GetConfigurationsFromLocalFiles();\n break; \n }\n \n return this; \n }\n \n public void Save()\n {\n // finalize your work.\n }\n\n private bool IsConfigruationFromServer()\n {\n string configValue = configuration[&quot;configKey&quot;];\n\n if (string.IsNullOrWhiteSpace(configValue)){ return false; }\n \n var dcc = JsonConvert.DeserializeObject&lt;RecordPojo&gt;(configValue);\n \n // use conditional access instead of casting to avoid casting exceptions \n // also you only need a valid boolean value, any other value should be ignored.\n if(!bool.TryParse(dcc.loadDefaultFlag?.ToString(), out bool loadDefaultFlag)) { return false; }\n \n _remoteFileName = dcc.remoteFileName;\n \n return !loadDefaultFlag &amp;&amp; !string.IsNullOrWhiteSpace(dcc.remoteFileName);\n }\n \n // adjust this to be parameterless\n // use the global variables _remoteUrl, _remoteFileName instead\n private IEnumerable&lt;RecordHolder&gt; GetConfigurationsFromServer()\n { \n var isDownloaded = _fileHelper.Download($&quot;{_remoteUrl}{_remoteFileName}&quot;, _secondaryLocation);\n \n if(!isDownloaded) { yield return default; }\n \n var isExtracted = _fileHelper.ExtractTarGz(_remoteFileName, _directory);\n \n if(!isExtracted) { yield return default; }\n \n foreach(var configPath in _fileHelper.GetFiles(directory))\n {\n if(!File.Exists(configPath)) { continue; }\n \n var fileDate = File.GetLastWriteTimeUtc(configPath);\n \n var fileContent = File.ReadAllText(configPath);\n \n var pathPieces = configPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);\n \n var fileName = pathPieces[pathPieces.Length - 1];\n \n yield return new RecordHolder\n {\n Name = fileName,\n Date = fileDate,\n JDoc = fileContent\n };\n }\n }\n\n\n private IEnumerable&lt;RecordHolder&gt; GetConfigurationsFromLocalFiles()\n {\n // Same concept as GetConfigurationsFromServer \n }\n\n}\n</code></pre>\n<p>usage would be like :</p>\n<pre><code>new RecordManager(configuration)\n .LoadConfigurationsFrom(RecordManager.ConfigLocation.Remote)\n .Save();\n</code></pre>\n<p>I hope this would give you the boost you're seeking.</p>\n<p>From Comments :</p>\n<blockquote>\n<p>Btw can you also explain what is the use of <code>yield</code> here and what\nadvantage does it have compared to what I had earlier.</p>\n</blockquote>\n<p><code>yield</code> keyword basically a shortcut of what you've already done in the same method, but with an effective and more efficient enumeration.</p>\n<p>It would create a lazy enumeration over a managed collection elements that would only create what you asked for nothing more nothing less. (say you're iterating over 100 elements, and you just need the first element, it'll only build a collection for one element and it would ignore the rest). and it works with <code>IEnumerable</code> only. I encourage you to read more about it and try to use it when possible.</p>\n<blockquote>\n<p>Also what does yield return default means here?</p>\n</blockquote>\n<p>it would return the default value of the current element type. Say you're enumerating over <code>int</code> collection. the default value of <code>int</code> is <code>0</code> since it's <code>non-nullable</code> type. same thing for other types (each type has its own default value).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T17:20:17.680", "Id": "482615", "Score": "0", "body": "Thanks for your great suggestion. Really appreciate it. When I try to use your suggestion, I am seeing error on this line `if(!isDownloaded) { return default; }` and same with `isExtracted` as well in the same method. Error is `Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration. `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T17:42:59.643", "Id": "482617", "Score": "0", "body": "@dragons my bad, I've missed `yield` statement. Note I have not tested the code, I just wrote it to give you a visual of the main idea. So, I apology if you find any error in the code, and I would be happy to update them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T17:44:43.873", "Id": "482618", "Score": "0", "body": "yeah I do understand that. No worries at all. I will try it out on my own and if I see any issues or question - I will touch base with you. Learning a lot from you. Thanks a lot from the help! Btw can you also explain what is the use of `yield` here and what advantage does it have compared to what I had earlier. Also what does `yield return default` means here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:11:48.000", "Id": "482619", "Score": "0", "body": "@dragons check the update" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:18:25.840", "Id": "482621", "Score": "0", "body": "@dragons no problem, glad to help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T13:55:54.600", "Id": "482815", "Score": "0", "body": "I created a new [question](https://codereview.stackexchange.com/questions/245784/reload-configs-in-memory-basis-on-a-trigger-efficiently) for review regarding `ConfigChanged` as we discussed in chat last time if you remember. Wanted to see if you can take a look and provide suggestions and improvements. I am in the same [chat room](https://chat.stackexchange.com/rooms/110787/room-for-dragons-and-isr5) if you want to discuss more." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T12:51:12.270", "Id": "245698", "ParentId": "245670", "Score": "5" } } ]
{ "AcceptedAnswerId": "245698", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T18:34:53.920", "Id": "245670", "Score": "6", "Tags": [ "c#", "performance", "json.net" ], "Title": "Scan a directory for files and load it in memory efficiently" }
245670
<p>Here is a programming task:</p> <blockquote> <p>Write a program with a function that converts a string of digits into an integer value. Do not use the <code>strtol()</code> function or any other standard C library function. Write your own!</p> </blockquote> <p>I wanted this program to work perfectly with no errors. First I did the power function (power) and then next is function that return the length of a string (lent) and lastly is function that gives the value of asciicode (ascton).</p> <p>In the main function there is a loop for the string where it multiple the value of how much zeros in has after it. For example, the string is &quot;1100&quot; so the first 1 is 1000 then this value is stored in variable z, and then this works for the other character and add it to variable z. At the end it return z as an integer of the string.</p> <p>Is this code efficient, or did I use the &quot;long way&quot;? Please give me some hints how I can write better, cleaner and more readable code. Any feedback is appreciated.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; int powe(int ex , int po) { int z = 1; for (int i = 0; i &lt; po; i++) { z = z * (10 * 1); } return z; } int lent (char a [20]) { int i=0; int l = 0; for(i=0 ; a[i] != '\0';i++) { l++; } return l; } int ascton (int a) { int asciicode[10] = {48,49,50,51,52,53,54,55,56,57}; for(int i = 0; i &lt; 10; i++) { if (a == asciicode[i]) {a = i; break;} else continue; } return a; } int main(void) { int z = 0; char sn[20]; printf(&quot;enter your string number!:&quot;); scanf(&quot;%s&quot;,sn); int s = lent(sn); for(int i = 0; sn[i] != '\0';i++) { int k = 0; k = ascton(sn[i]); z = z + (k * powe(10, s-1)); s = s-1; } printf(&quot;%d&quot;,z); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T20:28:26.880", "Id": "482534", "Score": "0", "body": "\"is this code efficient ?\" I suggest using a profiler like Instruments (mac), WPA (win) or Hotspot (linux) and check the bottlenecks once you feel that algorithm is fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T23:26:40.180", "Id": "482545", "Score": "0", "body": "\"Do not use the strtol() function or any other standard C library function.\" --> Can code use standard functions `printf()` and `scanf()`? If so, what is the _true_ limitation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:28:09.113", "Id": "482582", "Score": "1", "body": "HINT: You don't need a power function at all" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T12:12:29.143", "Id": "482599", "Score": "0", "body": "Related: [NASM Assembly convert input to integer?](https://stackoverflow.com/a/49548057) describes the efficient algorithm with C syntax, and uses C syntax for asm comments on an efficient implementation that stops at the first non-digit. (It only handles unsigned, not negative inputs, like strtoul which you're implementing, so you should be returning `unsigned` not signed `int`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:49:06.513", "Id": "482607", "Score": "1", "body": "Your use of fixed-width arrays instead of pointers is very problematic. You don't want your function prototype to look like `int f(char x[20]);` because that function can't accept an arbitrary c-str; it will only accept a fixed-width array. You could prototype a variable-width array, `int f(char x[]);`, or simply use `int f(char *x);`, which I feel is preferable because it's standard.\n\nThere's another way to define your `asciicode[]` array too: `const char *asciicode = \"0123456789\";`. However, my favorite way to go from a single ascii digit to an integer 0-9 is simply `int i = a - '0';`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T16:45:08.147", "Id": "482612", "Score": "1", "body": "You might also explain why you're doing \"z = z * (10 * 1);\" Of course any level of code optimization should remove the \"10 * 1\", but still... Also the \"else continue\" in your ascton is unnecessary, though as others have pointed out, there are better ways to do the conversion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:10:26.273", "Id": "482634", "Score": "1", "body": "@sig_seg_v: it would only be a real correctness problem if the prototype was `int f(char x[static 20])` (which would promise that all 20 array elements were definitely readable, even if the C string actually ended after 2 bytes, right before an unmapped page). ([reference](https://stackoverflow.com/questions/3430315/what-is-the-purpose-of-static-keyword-in-array-parameter-of-function-like-char)) As written, the `20` is ignored by C, and is confusing / misleading only for humans. But yes, a sane prototype would be `unsigned f(const char *s)`." } ]
[ { "body": "<p>Welcome to code review.</p>\n<blockquote>\n<p>Now my question is, is this code efficient ? or did I use the &quot;long way&quot;.</p>\n</blockquote>\n<p>You used the long way.</p>\n<p>The solution you provide is not portable to systems that don't use ASCII. Use '0' to '9' instead.</p>\n<p>Rather than iterating through each of the ASCII characters do a range check:</p>\n<pre><code> if (a &gt;= '0' &amp;&amp; a &lt;= '9')\n {\n return a - '0';\n }\n</code></pre>\n<p>Prefer variable and function names that are longer and more meaningful.</p>\n<p>The function <code>scanf()</code> returns a value that is the number of items read, you can use this for error checking input.</p>\n<p>A little less vertical spacing would be good. Formatters can also help with keeping consistent code style unlike:</p>\n<pre><code>int i=0;\nint l = 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T16:46:52.697", "Id": "482613", "Score": "0", "body": "\"Longer\" is not a synonym for \"more meaningful\"." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T20:17:18.063", "Id": "245673", "ParentId": "245672", "Score": "6" } }, { "body": "<p>regarding:</p>\n<pre><code>scanf(&quot;%s&quot;,sn);\n</code></pre>\n<p>To avoid any possible buffer overflow, should include a MAX characters modifier that is 1 less than the length of the input buffer ( 1 less because the <code>%s</code> input format conversion specifier always appends a NUL byte to the input.</p>\n<p>Should check the returned value to assure the operation was successful. Note: the <code>scanf()</code> family of functions returns the number of successful 'input format conversions'</p>\n<p>Suggest:</p>\n<pre><code>if ( scanf(&quot;%19s&quot;,sn) != 1 )\n{\n fprintf( stderr, &quot;scanf for the input string failed\\n&quot; );\n exit( EXIT_FAILURE );\n}\n</code></pre>\n<p>For ease of readability and understanding:</p>\n<p>Please consistently indent the code. Indent after each opening brace '{'. Unindent before each closing brace ']'. Suggest each indent level be 4 spaces. 1 or 2 space indents will 'disappear' when using variable width fonts.</p>\n<p>Please follow the axiom:</p>\n<pre><code>*only one statement per line and (at most) one variable declaration per statement.*\n</code></pre>\n<p>Therefore,</p>\n<pre><code> {a = i; \n break;}\n</code></pre>\n<p>would be much better written as:</p>\n<pre><code> {\n a = i; \n break;\n }\n</code></pre>\n<p>regarding:</p>\n<pre><code>#include &lt;math.h&gt;\n</code></pre>\n<p>Nothing in that header file is being used by the OPs program. Therefore, that statement should be removed.</p>\n<p>if the user enters a value larger than 2147483647 (aka: 2^31 -1) then the <code>int</code> result overflows, resulting in a negative value being printed I.E. results in undefined behavior Suggest 1) limit the user input to 10 characters + the NUL terminator, 2) check for the result becoming negative</p>\n<p>regarding the function:</p>\n<pre><code>int ascton (int a)\n</code></pre>\n<p>This whole function can be reduced to:</p>\n<pre><code>a -= '0';\n</code></pre>\n<p>suggest, before operating on each character the user input, to first check that char is a digit. Suggest:</p>\n<pre><code>#include &lt;ctype.h&gt;\n....\nint main( void )\n{\n ...\n if( ! isdigit( sn[i] )\n {\n fprintf( stderr, &quot;input contains characters other than digits\\n&quot; );\n return -1;\n }\n ....\n</code></pre>\n<p>the function: <code>lent()</code> can be reduced to:</p>\n<pre><code>int lent (char a [20] )\n{\n return (int)strlen( a );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T22:11:29.213", "Id": "482538", "Score": "1", "body": "The spec says that can't use C library functions which leaves `isdigit()` out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T22:14:54.173", "Id": "482540", "Score": "0", "body": "I must have misunderstood. I thought the question stated that could not use any of the string to integer functions like: `strtol()` `strtoll()` `atoi()`, etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T10:25:20.627", "Id": "482586", "Score": "1", "body": "Regarding: `#include <math.h>`., there is an advantage to using it given \"Do not use the strtol() function or any other standard C library function.\". It helps detect if this code collides with the standard C library. Consider if code here was `int pow(int ex , int po)`. By having `#include <math.h>`, a quick compile time error would generate. Of course it has the disadvantage too of allowing code to use a banned function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T12:07:57.560", "Id": "482598", "Score": "1", "body": "*check for the result becoming negative* - signed integer overflow is undefined behaviour in ISO C; you can't safely check for overflow this way unless you compile with `gcc -fwrapv` or something to define the behaviour as 2's complement wraparound. A common result of the UB is wrapping, but a compiler could optimize away a check if it could prove that both inputs to a multiply were non-negative. Causing UB means nothing at all is guaranteed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T21:44:15.473", "Id": "245676", "ParentId": "245672", "Score": "4" } }, { "body": "<blockquote>\n<p>is this code efficient ?</p>\n</blockquote>\n<p>No. Rather than using the unnecessary <code>powe()</code>, <code>lent()</code>,</p>\n<ol>\n<li>simply scale by 10 each operation; and</li>\n<li>use <code>- '0'</code>.</li>\n</ol>\n<p>.</p>\n<pre><code>char sn[20];\n//scanf(&quot;%s&quot;,sn);\nif (scanf(&quot;%19s&quot;, sn) == 1) {\n int z = 0;\n for (int i = 0; sn[i] &gt;= '0' &amp;&amp; sn[i] &lt;= '9'; i++) {\n z = z*10 + (sn[i] - '0');\n }\n printf(&quot;%d&quot;,z);\n}\n</code></pre>\n<p>Even better code would detect overflow and maybe use <code>unsigned</code> and/or wider types.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T23:25:04.937", "Id": "245678", "ParentId": "245672", "Score": "7" } } ]
{ "AcceptedAnswerId": "245676", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-18T19:51:13.150", "Id": "245672", "Score": "6", "Tags": [ "c" ], "Title": "A program with a function that converts a string of digits into an integer value" }
245672
<p>I am Relatively new to C, and did a calculator for my first year project. Could you guys, rate the calculator's efficiency and suggest some improvements?</p> <p>Link to the previous version of this calculator: <a href="https://codereview.stackexchange.com/questions/243131/math-calculator-in-c">Math Calculator in C</a></p> <p>Improvements added to this: I did formatting from this website: <a href="https://codebeautify.org/c-formatter-beautifier" rel="nofollow noreferrer">https://codebeautify.org/c-formatter-beautifier</a> , as the clang formatter was not downloaded in windows.</p> <p>Removed the nonsense loading screen, pretty useless.</p> <p>Did not change the body of the main as, for the Fibonacci Series Mode, i used <code>goto Start</code> which cannot be called from outside of the main function, got error, so i just leave all of the modes within the main function, cause it looks ugly, to have the Fibonacci Series Mode only to be full inside the main, not the others.</p> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;windows.h&gt; //For function Sleep() #include &lt;math.h&gt; //For functions like pow(), sin(), cos(), tan() #include &lt;time.h&gt; //For time based modules and functions #include &lt;conio.h&gt; //For kbhit, input detector #define PI 3.14159265358979323846 Exit_0(); //Function Prototype main() { system(&quot;COLOR F1&quot;); char Opt, oper, H; int i = 1, Oof, Check, N, K, Numbering, F, Choice, a, b, c, d; float Num1, Num2, ans, CheckF, A, B, C, A1, A2, Z; double x, xy, y; system(&quot;cls&quot;); //Clears terminal screen printf(&quot;Welcome to calculator HeX.\n&quot;); while (1) { //While loop that never ends, unless exit(0) is used Start: printf(&quot;\n\nWhich mode do you want to use?\n[1] Normal maths operations\n[2] Special Functions\n[3] Fibonacci Series\n[4] Random Mathematical Question\n[5] Exit\n\nYour input: &quot;); scanf(&quot; %c&quot;, &amp; Opt); if (Opt == '1') { printf(&quot;Welcome to Normal maths operation Mode.\n\nYour two numbers: &quot;); scanf(&quot;%f%f&quot;, &amp; Num1, &amp; Num2); printf(&quot;\nAVAILABLE SYMBOLS:\n\n+ for Addition\n- for Subtraction\n/ for Division\n* for Multiplication\n^ for Power function\n\\ for Rooting\nYour input: &quot;); scanf(&quot; %c&quot;, &amp; oper); if (oper == '+') { ans = (Num1 + Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (To 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); } else if (oper == '-') { ans = (Num1 - Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); } else if (oper == '/') { ans = (Num1 / Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); } else if (oper == '*') { ans = (Num1 * Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5g (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); } else if (oper == '^') { ans = (pow(Num1, Num2)); printf(&quot;Here is your answer:\n%f %c %f = %.5g (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); } else if (oper == '\\') { ans = pow(Num2, 1 / Num1); Check = Num1; Oof = Check % 2; if (Num2 &lt; 0) { system(&quot;COLOR B4&quot;); printf(&quot;Cannot root a negative number; ERROR 1 Sintek\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else if (Oof == 0) { printf(&quot;Here is your answer:\n%f root(%f) = - %.5f or + %.5f (to 5 decimal places)\n\n&quot;, Num1, Num2, ans, ans); } else if (!Oof == 0) { printf(&quot;Here is your answer:\n%f root(%f) = + %.5f (to 5 decimal places)\n\n&quot;, Num1, Num2, ans); } } else { system(&quot;COLOR B4&quot;); printf(&quot;\n\nYour input operator is incorrect; ERROR 1 Sintek\n&quot;); printf(&quot;\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } else if (Opt == '2') { printf(&quot;Welcome to Special Functions Mode.\n\n[1] Sine Function\n[2] Cosine Function\n[3] Tangent Function\n[4] Log (With base 10)\n[5] Log (With base e)\n[6] Log (With user defined base)\n[7] Sine Inverse Function\n[8] Cosine Inverse Function\n[9] Tangent Inverse Function\n[10] Quadratic Equation Solver\n\nWhich mode do you want: &quot;); scanf(&quot;%d&quot;, &amp; N); if (N == 1) { printf(&quot;Your angle: &quot;); scanf(&quot;%f&quot;, &amp; Num1); ans = (sin(Num1 * PI / 180)); printf(&quot;\nHere is your answer:\nSine(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); } else if (N == 2) { printf(&quot;Your angle: &quot;); scanf(&quot;%f&quot;, &amp; Num1); ans = (cos(Num1 * PI / 180)); printf(&quot;Here is your answer:\nCosine(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); } else if (N == 3) { printf(&quot;Your angle: &quot;); scanf(&quot;%f&quot;, &amp; Num1); ans = (tan(Num1 * PI / 180)); printf(&quot;Here is your answer:\nTangent(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); } else if (N == 4) { printf(&quot;Your number: &quot;); scanf(&quot;%f&quot;, &amp; Num1); ans = log10(Num1); if (Num1 &lt; 0) { system(&quot;COLOR B4&quot;); printf(&quot;Cannot log a negative number; ERROR 1 Sintek\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else if (Num1 == 0) { system(&quot;COLOR B4&quot;); printf(&quot;Cannot log(0); ERROR 1 Sintek\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else if (Num1 &gt; 0) { printf(&quot;Here is your answer:\nLg(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); } } else if (N == 5) { printf(&quot;Your number: &quot;); scanf(&quot;%f&quot;, &amp; Num1); ans = log(Num1); if (Num1 &lt; 0) { system(&quot;COLOR B4&quot;); printf(&quot;Cannot ln a negative number; ERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else if (Num1 == 0) { system(&quot;COLOR B4&quot;); printf(&quot;Cannot ln(0); Error 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else if (Num1 &gt; 0) { printf(&quot;Here is your answer:\nLn(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); } } else if (N == 6) { printf(&quot;Enter the base number, followed by the number: &quot;); scanf(&quot;%f%f&quot;, &amp; Num1, &amp; Num2); ans = (log(Num2) / log(Num1)); if (Num1 &lt;= 0 || Num2 &lt;= 0) { system(&quot;COLOR B4&quot;); printf(&quot;Cannot log a negative/zero base/number; ERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else if (Num1 &gt; 0 &amp;&amp; Num2 &gt; 0) { printf(&quot;Here is your answer:\nLog[base %f]%f = %.5f (to 5 decimal places)\n\n&quot;, Num1, Num2, ans); } } else if (N == 7) { printf(&quot;[1] Entering hypotenuse and opposite of triangle\n[2] Entering the value directly\n\nYour option: &quot;); scanf(&quot;%d&quot;, &amp; K); if (K == 1) { printf(&quot;Enter hypotenuse and opposite sides of the triangle: &quot;); scanf(&quot;%f%f&quot;, &amp; Num1, &amp; Num2); CheckF = Num2 / Num1; if (CheckF &lt; -1 || CheckF &gt; 1) { system(&quot;COLOR B4&quot;); printf(&quot;The opposite side should not be larger than the hypotenuse side. Please recheck your values!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else { ans = (asin(CheckF)); printf(&quot;Sine inverse %f/%f =\n%f (In radians)&quot;, Num2, Num1, ans); ans = ans * 180 / PI; printf(&quot;\n%f (In degrees)&quot;, ans); } } else if (K == 2) { printf(&quot;Enter your value: &quot;); scanf(&quot;%f&quot;, &amp; CheckF); if (CheckF &lt; -1 || CheckF &gt; 1) { system(&quot;COLOR B4&quot;); printf(&quot;Value cannot be higher than 1/lower than -1. Please recheck your input!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else { ans = (asin(CheckF)); printf(&quot;Sine inverse %f =\n%f (In radians)&quot;, CheckF, ans); ans = ans * 180 / PI; printf(&quot;\n%f (In degrees)&quot;, ans); } } else if (K != 1 || K != 2) { system(&quot;COLOR B4&quot;); printf(&quot;Your input option is not found! ERROR 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } else if (N == 8) { printf(&quot;[1] Entering adjacent and hypotenuse of triangle\n[2] Entering the value directly\n\nYour option: &quot;); scanf(&quot;%d&quot;, &amp; K); if (K == 1) { printf(&quot;Enter adjacent and hypotenuse sides of the triangle: &quot;); scanf(&quot;%f%f&quot;, &amp; Num1, &amp; Num2); CheckF = Num1 / Num2; if (CheckF &lt; -1 || CheckF &gt; 1) { system(&quot;COLOR B4&quot;); printf(&quot;The adjacent side should not be larger than the hypotenuse side. Please reckeck your values!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else { ans = (acos(CheckF)); printf(&quot;Cosine inverse %f/%f =\n%f (In radians)&quot;, Num1, Num2, ans); ans = ans * 180 / PI; printf(&quot;\n%f (In degrees)&quot;, ans); } } else if (K == 2) { printf(&quot;Enter your value: &quot;); scanf(&quot;%f&quot;, &amp; CheckF); if (CheckF &lt; -1 || CheckF &gt; 1) { system(&quot;COLOR B4&quot;); printf(&quot;Value cannot be higher than 1/lower than -1. Please recheck your input!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else { ans = (acos(CheckF)); printf(&quot;Cosine inverse %f = \n%f (In radians)&quot;, CheckF, ans); ans = ans * 180 / PI; printf(&quot;\n%f (In degrees)&quot;, ans); } } else if (K != 1 || K != 2) { system(&quot;COLOR B4&quot;); printf(&quot;Your input option is not found! Error 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } else if (N == 9) { printf(&quot;[1] Entering opposite and adjacent of triangle\n[2] Entering the value directly\n\nYour option: &quot;); scanf(&quot;%d&quot;, &amp; K); if (K == 1) { printf(&quot;Enter opposite and adjacent sides of the triangle: &quot;); scanf(&quot;%f%f&quot;, &amp; Num1, &amp; Num2); CheckF = Num1 / Num2; ans = (atan(CheckF)); printf(&quot;Tangent inverse %f/%f =\n%f (In radians)&quot;, Num1, Num2, ans); ans = ans * 180 / PI; printf(&quot;\n%f (In degrees)&quot;, ans); } else if (K == 2) { printf(&quot;Enter your value: &quot;); scanf(&quot;%f&quot;, &amp; CheckF); if (CheckF &lt; -1 || CheckF &gt; 1) { system(&quot;COLOR B4&quot;); printf(&quot;Value cannot be higher than 1/lower than -1. Please recheck your input!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } else { ans = (atan(CheckF)); printf(&quot;Tangent inverse %f =\n%f (In radians)&quot;, CheckF, ans); ans *= 180 / PI; printf(&quot;\n%f (In degrees)&quot;, ans); } } else if (K != 1 || K != 2) { system(&quot;COLOR B4&quot;); printf(&quot;Your input option is not found! ERROR 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } else if (N == 10) { printf(&quot;Welcome to Quadratic Equation solver. Enter the coefficient of X^2, followed by\nthe coefficient of X, followed by the integer value.\n\nEnter values: &quot;); scanf(&quot;%f%f%f&quot;, &amp;A, &amp;B, &amp;C); CheckF = (B * B - 4 * A * C); if (A == 0) { ans = -C/B; printf(&quot;Root of equation is %f \n&quot;, ans); } else if (CheckF &lt; 0) { system(&quot;COLOR B4&quot;); printf(&quot;This calculator HeX, currently cannot handle complex numbers.\nPlease pardon my developer. I will now redirect you to the main menu.\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); goto Start; } else if (CheckF &gt;= 0) { Z = pow(CheckF, 0.5); A1 = (-B + Z)/(A+A); A2 = (-B - Z)/(A+A); if (A1 == A2) { ans = A1; printf(&quot;\nRoot of equation is %f (Repeated root)\n&quot;, ans); } else if (A1 != A2) { printf(&quot;Roots of equation are %f and %f \n&quot;, A1, A2); } } } else { system(&quot;COLOR B4&quot;); printf(&quot;Your input option is not found! ERROR 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } else if (Opt == '3') { printf(&quot;Welcome to Fibonacci Series Mode.\n\nPress any key to stop while printing the numbers, to pause.\nEnter how many numbers do you want from the series, from the start: &quot;); scanf(&quot;%d&quot;, &amp; N); x = 0; y = 1; F = 3; Numbering = 3; printf(&quot;Here is Your Series:\n\n&quot;); if (N == 1) { printf(&quot;[1] 0\n&quot;); Sleep(1000); } if (N == 2) { printf(&quot;[1] 0\n&quot;); Sleep(75); printf(&quot;[2] 1\n&quot;); Sleep(1075); } if (N == 3) { printf(&quot;[1] 0\n&quot;); Sleep(75); printf(&quot;[2] 1\n&quot;); Sleep(75); printf(&quot;[3] 1\n&quot;); Sleep(1075); } if (N &gt; 3) { printf(&quot;[1] 0\n&quot;); Sleep(75); printf(&quot;[2] 1\n&quot;); Sleep(75); } while (N &gt; 3 &amp;&amp; F &lt;= N) { xy = x + y; printf(&quot;[%.0d] %.5g\n&quot;, Numbering, xy); Sleep(75); x = y; y = xy; F++; Numbering++; while (kbhit()) { system(&quot;COLOR B4&quot;); printf(&quot;\n\n[+] Interrupted\n\nE to exit\nC to continue printing\n\nOption: &quot;); scanf(&quot; %c&quot;, &amp; H); if (H == 'E') { printf(&quot;Exiting to main menu, in 2 seconds.&quot;); Sleep(2000); system(&quot;COLOR F1&quot;); goto Start; } else if (H == 'C') { system(&quot;COLOR F1&quot;); continue; } } } Sleep(1000); } else if (Opt == '4') { srand(time(NULL)); Choice = rand() % 3; if (Choice == 0) { a = rand() % 5001; b = rand() % 5001; c = a + b; printf(&quot;What is %d + %d?\nYour answer: &quot;, a, b); scanf(&quot;%d&quot;, &amp; d); if (d == c) { system(&quot;COLOR 2F&quot;); printf(&quot;Yes. You are right; Congratulations\n\n&quot;); system(&quot;pause&quot;); system(&quot;COLOR F1&quot;); } else { system(&quot;COLOR B4&quot;); printf(&quot;No. The correct answer is %.0d. Need to practice more!\n\n&quot;, c); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } if (Choice == 1) { a = rand() % 5001; b = rand() % 5001; c = a - b; printf(&quot;What is %d - %d?\nYour answer: &quot;, a, b); scanf(&quot;%d&quot;, &amp; d); if (d == c) { system(&quot;COLOR 2F&quot;); printf(&quot;Yes. You are right; Congratulations\n\n&quot;); system(&quot;pause&quot;); system(&quot;COLOR F1&quot;); } else { system(&quot;COLOR B4&quot;); printf(&quot;No. The correct answer is %.0d. Need to practice more!\n\n&quot;, c); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } if (Choice == 2) { a = rand() % 20; b = rand() % 20; c = a * b; printf(&quot;What is %d times %d?\nYour answer: &quot;, a, b); scanf(&quot;%d&quot;, &amp; d); if (d == c) { system(&quot;COLOR 2F&quot;); printf(&quot;Yes. You are right; Congratulations\n\n&quot;); system(&quot;pause&quot;); system(&quot;COLOR F1&quot;); } else { system(&quot;COLOR B4&quot;); printf(&quot;No. The correct answer is %.0d. Need to practice more!\n\n&quot;, c); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } } else if (Opt == '5') { Exit_0(); } else if (Opt &lt; '1' || Opt &gt; '5') { system(&quot;COLOR B4&quot;); printf(&quot;Your option is not found! ERROR 404&quot;); printf(&quot;\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); system(&quot;COLOR F1&quot;); } } } Exit_0() { printf(&quot;Thank you for using my calculator. Hope to see you again!!&quot;); Sleep(1250); system(&quot;cls&quot;); system(&quot;COLOR 0F&quot;); exit(0); } </code></pre> <p>Any help will be nice.</p>
[]
[ { "body": "<h2>Pi</h2>\n<p>There are some dissenting opinions on this, but: most compilers offer an <code>M_PI</code> if they are configured to do so. I prefer to do that rather than defining my own.</p>\n<h2>Implicit return types</h2>\n<p>Leaving these return types implicit:</p>\n<pre><code>load(); //Function Prototype\nExit_0(); //Function Prototype\nmain() {\n</code></pre>\n<p>is not great. <code>main</code> should be <code>int main</code>. <code>Exit_0</code> should be <code>void</code>. <code>load</code> seems to be missing and should be deleted.</p>\n<h2>Monster functions</h2>\n<p>You need to expend a significant amount of effort into dividing the bulk of your code up into subroutines. As it stands, it's difficult to read and maintain.</p>\n<p>While doing this refactoring, keep in mind that your <code>goto</code> will likely be able to be replaced with a <code>return</code> once this is done. <code>goto</code> should be avoided.</p>\n<h2>Predeclaration of variables</h2>\n<p>You should use (at least) C99, which obviates the need for these:</p>\n<pre><code>char Opt, oper, H;\nint i = 1, Oof, Check, N, K, Numbering, F, Choice, a, b, c, d;\nfloat Num1, Num2, ans, CheckF, A, B, C, A1, A2, Z;\ndouble x, xy, y;\n</code></pre>\n<p>to be declared at the beginning of the function. Declare them where they're used. Also, make an attempt to avoid single-letter variable names unless it's crystal clear what they do (it isn't here).</p>\n<h2>Why sleep?</h2>\n<pre><code> Sleep(75);\n</code></pre>\n<p>There is no advantage to doing this; it just slows down the program and may frustrate the user.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:45:48.503", "Id": "482555", "Score": "0", "body": "The `Sleep(75);`, is required because it is in the series mode. if the user input some 100 numbers of the series, for example 400, that function prints the numbers from the start, so by using sleep for that mode, it it more nice to see the whole series rather than the series being printed out instantly. Moreover, if it is printed instantly, the user will need to scroll up a lot to see smaller numbers of the series. Then the use of `kbhit()`, `goto` will have no use also" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:48:35.130", "Id": "482556", "Score": "0", "body": "If you're concerned about a screen buffer being scrolled out of view, sleeping is the wrong solution; you should pause to continue instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:53:16.497", "Id": "482557", "Score": "0", "body": "but `system(\"pause\");` is bit more time consuming right? like for every number there is a `system(\"pause\");` will take more time then just printing the list, then letting the user decide when he wants to pause the list and continue by the `kbhit()` right? Correct me if i am wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T02:21:55.743", "Id": "482560", "Score": "3", "body": "The idea is that you would not pause after every number; you would pause after \"a screenful of numbers\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T02:28:53.833", "Id": "482561", "Score": "0", "body": "Oh, now i get it. Thank you. I will add that change in to my code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:40:10.807", "Id": "245681", "ParentId": "245679", "Score": "3" } }, { "body": "<p><strong><code>float</code> vs. <code>double</code></strong></p>\n<p>Little reason to use <code>float</code> here, suggest <code>double</code> instead. Save <code>float</code> for selective space/speed issues - which are not present here.</p>\n<p>If code uses <code>float</code> variables, use <code>float</code> functions like <code>sinf(), log10f(), powf(), ...</code> than <code>sin(), log10(), pow()</code>.</p>\n<p><strong>Printing floating point</strong></p>\n<p>Rather than <code>printf(&quot;%f&quot;, ans)</code>, print using <code>&quot;%g&quot;</code> or <code>&quot;%e&quot;</code>. When values are much smaller than 1.0, <code>&quot;%f&quot;</code> prints as <code>0.000000</code> and large values with many uninformative digits.</p>\n<pre><code>// printf(&quot;%f&quot;, ans);\nprintf(&quot;%g&quot;, ans);\n</code></pre>\n<p><strong>Form 1 scale factor</strong></p>\n<p><code>ans * 180 / PI</code> can differ from <code>ans * (180 / PI)</code>. First performs a multiplication and division at run time. 2nd multiplies once at run-time and 1 division <em>at compile time</em>.\nWhich one do you want?</p>\n<p>I recommend <code>ans * (180 / PI)</code> here.</p>\n<p>Advanced: With <code>sin(Num1 * PI / 180)</code> though, consider the advantages of <a href=\"https://stackoverflow.com/q/31502120/2410359\">range reduction in degrees</a> first.</p>\n<p><strong>Call <code>srand(time(NULL));</code> once</strong></p>\n<p>Seeding is only needed once per program run.</p>\n<p><strong>Use protection</strong></p>\n<p>User input is evil. Watch out for bad input.</p>\n<pre><code>//scanf(&quot;%f&quot;, &amp; Num1);\nif (scanf(&quot;%f&quot;, &amp; Num1) != 1) { Handle_Nonnumeric_Input(); ... }\nif (Num1 &lt;= 0.0) { Handle_Bad_Domain_Input(); ... }\n\n// Now OK to call log()\nans = log(Num1);\n\n...\n\nif (Num1 != 0) { Handle_Bad_Domain_Input(); ... }\nans = pow(Num2, 1 / Num1);\n</code></pre>\n<hr />\n<p><strong>Advanced: FP constant precision</strong></p>\n<p>Below is not much concern here, given the lower precision of printing, but is for a more advanced uses of FP code.</p>\n<p>Depending on <code>FLT_EVAL_METHOD</code>, code can evaluate expressions at higher than the usual precision, perhaps even as <code>long double</code>.</p>\n<p>Consider the effects of using the various <code>PI</code> definitions.</p>\n<pre><code>#define PI_a 3.14159265358979323846 /* OP's */\n#define PI_b 3.14159265358979323846264338327950288420 /* 3 more than LDBL_DECIMAL_DIG */\n// 1 23456789012345678901234567890123456789\n#define PI_c (22.0/7) // not a serious choice, but illustrative of a coarse approximation\n#define PI_d acos(-1) // Let the implementation provide the best pi\n</code></pre>\n<p>Avoid using insufficient precision. So what is a reasonable upper bound?</p>\n<p>I recommend to use 3 digits more than <code>LDBL_DECIMAL_DIG</code>. For <code>long double</code>, encoded as a very precise <a href=\"https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format#IEEE_754_quadruple-precision_binary_floating-point_format:_binary128\" rel=\"nofollow noreferrer\">binary128</a>, this is 36 + 3.</p>\n<p>Notes: <code>LDBL_DECIMAL_DIG</code> is the round trip <code>long double</code> to text to <code>long double</code> needed precision. IEEE math allows implementations to only use the first <code>LDBL_DECIMAL_DIG + 3</code> significant digits on evaluating decimal floating point text.</p>\n<p>For me I would use <code>M_PI</code> (many systems provide this pi) if available or a high precision one and let the compiler approximate as needed.</p>\n<pre><code>#ifdef M_PI\n#define PI M_PI\n#else\n#define PI 3.14159265358979323846264338327950288420 \n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:30:19.483", "Id": "482653", "Score": "0", "body": "Re. `Form 1 scale factor` - When you say _can differ from_, I think that \"can\" is limited to some rather old or obscure compilers. Modern optimizing compilers will be able to squash that expression into a constant regardless of where the programmer adds parens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:41:49.887", "Id": "482656", "Score": "0", "body": "@Reinderien Consider FP multiplications are not [associative](https://stackoverflow.com/a/10371890/2410359) - it is not an obscure issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T13:46:26.657", "Id": "482696", "Score": "0", "body": "This is surprising. Thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:41:00.210", "Id": "245696", "ParentId": "245679", "Score": "2" } } ]
{ "AcceptedAnswerId": "245696", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T01:02:44.957", "Id": "245679", "Score": "4", "Tags": [ "beginner", "c", "calculator" ], "Title": "Complex Calculator in C" }
245679
<p>This is a personal project of mine. I made a simple seven day agenda program in Python that stores tasks as a string, saves it into a .dat file, and returns that task when you input a day of the week. This works on a terminal. I'm new to programming in general.</p> <p>This is Python 3.8.2, 32 bit, and in a virtual environment.</p> <pre><code># Pickle module allows you to save data after program closes import pickle week = {&quot;Sunday&quot;: [], &quot;Monday&quot;: [], &quot;Tuesday&quot;: [], &quot;Wednesday&quot;: [], &quot;Thursday&quot;: [], &quot;Friday&quot;: [], &quot;Saturday&quot;: []} def agenda(): option = input( &quot;What would you like to do? (A - look at agenda, B - create task, C - clear list, or D - quit) &quot;).upper() if option == &quot;A&quot;: look_at_agenda() elif option == &quot;B&quot;: create_task() elif option == &quot;C&quot;: clear_list() elif option == &quot;D&quot;: print(&quot;Have a nice day!&quot;) else: print(&quot;Invalid option.&quot;) agenda() # global allows day variable in other functions to work even without declaring it def valid_days(): global day day = input(&quot;Which day? &quot;).capitalize() week_list = [day_list for day_list in week.keys()] if day not in week_list: print(&quot;Invalid day.&quot;) valid_days() # Loads whatever string from week.dat file def look_at_agenda(): see_all = input(&quot;See entire week? Y - yes, N - no. &quot;).upper() if see_all == &quot;Y&quot;: week = pickle.load(open(&quot;week.dat&quot;, &quot;rb&quot;)) print(week) elif see_all == &quot;N&quot;: valid_days() week = pickle.load(open(&quot;week.dat&quot;, &quot;rb&quot;)) print(week[day]) else: print(&quot;Invalid option.&quot;) look_at_agenda() agenda() def create_task(): valid_days() task = input(&quot;Describe your task. &quot;) # Loads string from week.dat file; when program restarts, it allows you to create a task without deleting the saved ones week = pickle.load(open(&quot;week.dat&quot;, &quot;rb&quot;)) week[day].append(task) # Saves string into week.dat file so it remembers when you open the program again pickle.dump(week, open(&quot;week.dat&quot;, &quot;wb&quot;)) agenda() def clear_list(): clear_all = input(&quot;Clear all lists? Y - yes, N - no &quot;).upper() if clear_all == &quot;N&quot;: valid_days() week[day].clear() print(f&quot;List cleared for {day}!&quot;) # saves the new list into a week.dat file pickle.dump(week, open(&quot;week.dat&quot;, &quot;wb&quot;)) elif clear_all == &quot;Y&quot;: [week[day].clear() for day in week] # saves the now empty list into a week.dat file pickle.dump(week, open(&quot;week.dat&quot;, &quot;wb&quot;)) else: print(&quot;Invalid option.&quot;) clear_list() agenda() agenda() </code></pre>
[]
[ { "body": "<p>Welcome to the code review community. The code looks clean, and follows the PEP8 style guide. Here are a few suggestions/modifications you can make though:</p>\n<ol>\n<li><p><a href=\"https://stackoverflow.com/a/19158418/1190388\">Do not use global variables</a>.</p>\n</li>\n<li><p>Instead of calling <code>agenda()</code> at the end, put it inside <a href=\"https://stackoverflow.com/q/419163/1190388\">the <code>if __name__</code></a> block.</p>\n</li>\n<li><p>Since you're working with python 3.8+, you may also add type hinting for function arguments.</p>\n</li>\n<li><p>For user input/validation, you can make use of a while loop:</p>\n<pre><code> from typing import List\n\n def read_user_input_from_options(message: str, valid_inputs: List = None):\n &quot;&quot;&quot;\n Show `message` in the console while asking for user input.\n\n If `valid_inputs` is not provided, returns the value from user as is.\n &quot;&quot;&quot;\n if valid_inputs:\n valid_inputs = map(lambda x: x.upper(), valid_inputs)\n while True:\n user_input = input(message)\n if not valid_inputs:\n return user_input\n user_input = user_input.upper()\n if user_input in valid_inputs:\n return user_input\n print(&quot;Invalid option chosen. Try again.&quot;)\n</code></pre>\n<p>The above is an example suited for your case, where all the input option you need are capitalised alphabets. It can be extended to support other validators as per requirements.</p>\n</li>\n<li><p>Use multiline strings. Makes it more readable. It is more a personal preference than rules to live by.</p>\n</li>\n<li><p>You can map the option to a function call (see below):</p>\n<pre><code> def quit_program():\n print(&quot;Have a nice day!&quot;)\n return\n\n\n def main():\n OPTION_TO_FUNCTION = {\n &quot;A&quot;: look_at_agenda,\n &quot;B&quot;: create_task,\n &quot;C&quot;: clear_list,\n &quot;D&quot;: quit_program,\n }\n option = read_user_input_from_options(\n &quot;&quot;&quot;\n What would you like to do?\n A - look at agenda\n B - create task\n C - clear list\n D - quit\n &quot;&quot;&quot;,\n valid_inputs=[&quot;a&quot;, &quot;b&quot;, &quot;C&quot;, &quot;d&quot;],\n )\n return OPTION_TO_FUNCTION[option]()\n</code></pre>\n<p>where <code>main</code> is the function called from inside your <code>if __name__ == &quot;__main__&quot;</code> block.</p>\n</li>\n<li><p>Make use of a class to keep the state of current execution. This would accompany my point about avoiding globals as well.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T05:03:19.820", "Id": "245684", "ParentId": "245683", "Score": "2" } } ]
{ "AcceptedAnswerId": "245684", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T03:43:24.000", "Id": "245683", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "console" ], "Title": "7-Day Agenda in Python" }
245683
<p>I'm working through Chapter 6 in &quot;Automate the Boring Stuff, 2nd Edition.&quot; Here is the chapter project at the end.</p> <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']] Your printTable() function would print the following: apples Alice dogs oranges Bob cats cherries Carol moose banana David goose </code></pre> <p>The first time I tackled this project, here was what I came up with:</p> <pre><code>#! python3 # Displays a table with each column right-justified. table_data = [[&quot;apples&quot;, &quot;oranges&quot;, &quot;cherries&quot;, &quot;bananas&quot;], [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Carol&quot;, &quot;David&quot;], [&quot;dogs&quot;, &quot;cats&quot;, &quot;moose&quot;, &quot;goose&quot;]] def print_table(table_data): # Create a new list of 3 &quot;0&quot; values: one for each list in table_data col_widths = [0] * len(table_data) # Search for the longest string in each list of table_data # and put the numbers of characters in the new list for y in range(len(table_data)): for x in table_data[y]: if col_widths[y] &lt; len(x): col_widths[y] = len(x) # Rotate and print the list of lists for x in range(len(table_data[0])): for y in range(len(table_data)): print(table_data[y][x].rjust(col_widths[y]), end=&quot; &quot;) print() print_table(table_data) </code></pre> <p>The second time, I found out about the MAX method after several searches on Google. Here is what I came up with using the MAX method.</p> <pre><code>#! python3 # Displays a table with each column right-justified table_data = [[&quot;apples&quot;, &quot;oranges&quot;, &quot;cherries&quot;, &quot;bananas&quot;], [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Carol&quot;, &quot;David&quot;], [&quot;dogs&quot;, &quot;cats&quot;, &quot;moose&quot;, &quot;goose&quot;]] def print_table(table_data): # Create a new list of 3 &quot;0&quot; values: one for each list in table_data col_widths = [0] * len(table_data) # Search for longest string in each list of table_data # and put the numbers of characters in new list for y in range(len(table_data)): x = max(table_data[y], key=len) if col_widths[y] &lt; len(x): col_widths[y] = len(x) # Rotate and print the lists of lists for x in range(len(table_data[0])): for y in range(len(table_data)): print(table_data[y][x].rjust(col_widths[y]), end=&quot; &quot;) print() print_table(table_data) </code></pre> <p>Any feedback would be greatly appreciated. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T05:41:40.670", "Id": "482565", "Score": "3", "body": "Welcome to Code Review, I added `python` and `comparative-review` tags to your post. To increase odds of receiving detailed answers I suggest you to change the title to one including the description of the task because the current title is too general and can be applied to a lot of questions present on the site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T06:45:51.743", "Id": "482570", "Score": "1", "body": "Thanks @dariosicily. I edited the title. I appreciate the feedback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T10:13:49.687", "Id": "482585", "Score": "0", "body": "Not really a code review, so suggesting by comment: you could use a library for this. [Suggestions here](https://stackoverflow.com/a/26937531) and [an example with your data using PrettyTable](https://tio.run/#%23bZDBSsQwEIbveYq5pYVSFG@Ch3X3srCuC@qplDJt0zSQJiEdlT59TdMqK5oc5s/8k28mcRP11tzNc@ftAM4Loomw1gLU4KwnuMTU65LKAC6n3fFc7Z9Pb0/nF2CMxdoDEsIDFAVH57QYeQbcejRylU0vvFerrtGEzcuMwfUq@E6rRiwVj7Zewh691Ys44Idq/7nQWrnSkWIcrB0jQEZRlt/ThcmuHpGkjHXWQ2M1KAM/899Hfjzm2LZV8N8Hk/BADDJdUfkoqBppCphfP5FurXLUSprQkHu@ZbToqHKBqIysPlVLfbBvNtMr2f91bxlzXhlKYlFgwzx/AQ)" } ]
[ { "body": "<p>You can transpose the given list of lists using a single line:</p>\n<pre><code>zip(*table_data)\n</code></pre>\n<p>That's it. Now, to find the longest word in each column, it would be another 1-liner:</p>\n<pre><code>map(len, [max(_, key=len) for _ in table_data])\n</code></pre>\n<hr />\n<p>You are calculating <code>len(table_data)</code> a lot of times. Better to store it as a variable? Although, another comprehension could be:</p>\n<pre><code>for row in zip(*table_data):\n for index, cell in enumerate(row):\n print(cell.rjust(col_width[index]), end=&quot; &quot;)\n</code></pre>\n<hr />\n<p>You whole function now becomes:</p>\n<pre><code>from typing import List\ndef print_table(table_data: List):\n col_width = list(map(len, [max(_, key=len) for _ in table_data]))\n for row in zip(*table_data):\n for index, cell in enumerate(row):\n print(cell.rjust(col_width[index]), end=&quot; &quot;)\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T23:02:25.737", "Id": "482640", "Score": "0", "body": "Thank you! I'm just using the methods I've read up until chapter 6. I appreciate it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T08:52:06.107", "Id": "245693", "ParentId": "245685", "Score": "3" } }, { "body": "<p>First, get the width of each column. This can be easily done with a list comprehension:</p>\n<pre><code> width = [max(len(item) for item in column) for column in tableData]\n</code></pre>\n<p>Where <code>max(len(item) for item in column)</code> gets the maximum length of an item in the column. And the <code>[ ... for column in tableData]</code> repeats it for each column.</p>\n<p>Then build a format string to format each row in the desired format.</p>\n<pre><code> fmt = ' '.join(f&quot;{{:&gt;{w}}}&quot; for w in width)\n</code></pre>\n<p>Where <code>f&quot;{{:&gt;{w}}}&quot;</code> is a f-string expression. Double braces get replaced by single braces and <code>{w}</code> gets replace by the value of w. For example, with <code>w = 8</code> the f-string evaluates to <code>&quot;{:&gt;8}&quot;</code>. This corresponds to a format to right justify (the <code>&gt;</code>) in a field of width 8. A separate string is created for each column, which are joined by a space (' '). In the example table, width = [8, 5, 5], so fmt is <code>&quot;{:&gt;8} {:&gt;5} {:&gt;5}&quot;</code>.</p>\n<p>Lastly, print each row of the table using the format.</p>\n<pre><code> for row in zip(*tableData):\n print(fmt.format(*row))\n</code></pre>\n<p>Where <code>for row in zip(*tableData)</code> is a Python idiom for iterating over the rows when you have a list of columns.</p>\n<p>Putting it together:</p>\n<pre><code>def print_table(table_data):\n width = [max(len(item) for item in col) for col in tableData]\n\n fmt = ' '.join(f&quot;{{:&gt;{w}}}&quot; for w in width)\n\n for row in zip(*tableData):\n print(fmt.format(*row))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T23:05:18.907", "Id": "482641", "Score": "0", "body": "Thank you! I appreciate the feedback. I'm going to look more into this. I haven't learned list comprehensions yet." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:51:24.767", "Id": "245723", "ParentId": "245685", "Score": "1" } } ]
{ "AcceptedAnswerId": "245723", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T05:24:38.677", "Id": "245685", "Score": "5", "Tags": [ "python", "python-3.x", "comparative-review" ], "Title": "Print a right-justified list of a list" }
245685
<p>I wanted to make an <em>extremely</em> light-weight logging system. What are your thoughts on this and what can be done to improve it?</p> <p>First, the usage:</p> <pre class="lang-cpp prettyprint-override"><code>int main( ) { logging::level = logging::fatal | logging::warning; mini_log( logging::fatal, &quot;entry point&quot;, &quot;nothing&quot;, &quot; is &quot;, &quot;happening!&quot; ); } </code></pre> <p>Now, the code:</p> <pre class="lang-cpp prettyprint-override"><code>#if defined( NDEBUG ) #define mini_log( ... ) static_cast&lt; void &gt;( 0 ) #else namespace logging { enum level_t { none = 0b00000, information = 0b00001, debug = 0b00010, warning = 0b00100, error = 0b01000, fatal = 0b10000, all = 0b11111 } inline level = all; // level should only be used in the entry point inline std::mutex stream; } #define mini_log \ [ ]( logging::level_t const level_message, \ std::string_view const location, \ auto &amp;&amp;... message ) -&gt; void \ { \ std::lock_guard&lt; std::mutex &gt; lock_stream( logging::stream ); \ struct tm buf; \ auto time = [ &amp; ]( ) \ { \ auto t = std::time( nullptr ); \ localtime_s( &amp;buf, \ &amp;t ); \ return std::put_time( &amp;buf, \ &quot;[%H:%M:%S]&quot; ); \ }; \ auto level = [ = ]( ) -&gt; std::string \ { \ switch( level_message ) \ { \ case logging::information: \ return &quot; [&quot; __FILE__ &quot;@&quot; stringize_val( __LINE__ ) &quot;] [Info] [&quot;; \ case logging::debug: \ return &quot; [&quot; __FILE__ &quot;@&quot; stringize_val( __LINE__ ) &quot;] [Dbug] [&quot;; \ case logging::warning: \ return &quot; [&quot; __FILE__ &quot;@&quot; stringize_val( __LINE__ ) &quot;] [Warn] [&quot;; \ case logging::error: \ return &quot; [&quot; __FILE__ &quot;@&quot; stringize_val( __LINE__ ) &quot;] [Erro] [&quot;; \ case logging::fatal: \ return &quot; [&quot; __FILE__ &quot;@&quot; stringize_val( __LINE__ ) &quot;] [Fatl] [&quot;; \ } \ }; \ if( level_message &amp; logging::level ) \ ( ( std::cout &lt;&lt; time( ) &lt;&lt; level( ) &lt;&lt; location &lt;&lt; &quot;]: &quot; &lt;&lt; message ) &lt;&lt; ... ) &lt;&lt; '\n'; \ } #endif </code></pre>
[]
[ { "body": "<h2>Macros</h2>\n<p>Most of your code is in a macro. This makes it harder to write, read and debug.</p>\n<p>Why not place the logic in normal functions and only use macros to pass <code>__FILE__</code> and <code>__LINE__</code>?</p>\n<p>That is until you can switch to C++20 which provides <a href=\"https://en.cppreference.com/w/cpp/utility/source_location\" rel=\"nofollow noreferrer\">std::source_location</a></p>\n<h2>Naming</h2>\n<p>Why is the mutex called <code>stream</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T08:20:18.473", "Id": "482573", "Score": "0", "body": "These feels like it should be a comment asking for clarity instead of an answer. Regardless, I made it a macro because it works. I will never need to debug or touch this again. As for naming, I name the mutex `stream` because it is the mutex for the console-out stream." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:31:58.680", "Id": "482584", "Score": "0", "body": "You can actually avoid the `std::mutex` entirely if you first build the log message in a string, and then pass this string to `std::cout` in one go. Individual calls to `operator<<`, `put()`, `write()` and so on are thread-safe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T10:59:29.463", "Id": "482590", "Score": "0", "body": "I guess I could make a string stream and push it to cout" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T08:15:45.433", "Id": "245690", "ParentId": "245687", "Score": "3" } }, { "body": "<p>If you want the logger to log the details in case the program crashes, you should flush the buffer before the crash happens.</p>\n<pre><code>( std::cout &lt;&lt; time( ) &lt;&lt; level( ) &lt;&lt; location &lt;&lt; &quot;]: &quot; &lt;&lt; message ) &lt;&lt; ... ) &lt;&lt; '\\n'\n</code></pre>\n<p>This does not flush the buffer to the console so you might lose info that is <em>in the buffer</em> when the abort happens. So use the following:</p>\n<pre><code>( std::cout &lt;&lt; time( ) &lt;&lt; level( ) &lt;&lt; location &lt;&lt; &quot;]: &quot; &lt;&lt; message ) &lt;&lt; ... ) &lt;&lt; std::endl;\n</code></pre>\n<p>Also, remove the macro and directly execute the lambda. If that is not suitable, make it a normal static function and make it inline.</p>\n<blockquote>\n<p>Unfortunately, it must remain a lambda because of <code>__FILE__</code> and <code>__LINE__</code>.</p>\n</blockquote>\n<p>Pass <code>__FILE__</code> and <code>__LINE__</code> directly to the function (if you make one) and the function signature will be like:</p>\n<pre><code>void log_to_file(std::string _file_, std::string _line_);\n// usage:\nlog_to_file(__FILE__, __LINE__);\n</code></pre>\n<p>I personally like <code>__func__</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:29:08.973", "Id": "482583", "Score": "1", "body": "Yes, this is one of those rare cases where `std::endl` is the right thing to use." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:13:36.820", "Id": "245694", "ParentId": "245687", "Score": "1" } } ]
{ "AcceptedAnswerId": "245690", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T07:04:30.837", "Id": "245687", "Score": "3", "Tags": [ "c++", "c++17" ], "Title": "52-Line Logging System" }
245687
<p>I have implemented a bitarr class that does bit manipulations. I would love to know if there is any way to make the code more optimized. Any input would be much appreciated. Thank you! <strong>Note</strong>: int main() should not be modified.</p> <pre><code> #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;climits&gt; #include &lt;cstring&gt; template&lt;size_t NumBits&gt; class bitarr { private: static const unsigned NumBytes = (NumBits + CHAR_BIT - 1) / CHAR_BIT;//find number of bytes to track least memory footprint unsigned char arr[NumBytes]; public: bitarr() { std::memset(arr, 0, sizeof(arr)); } //initialize array to 0 void set(size_t bit, bool val = true) { if (val == true) { arr[bit / CHAR_BIT] |= (val &lt;&lt; bit % CHAR_BIT);//left shift and OR with masked-bit } } bool test(size_t bit) const { return arr[bit / CHAR_BIT] &amp; (1U &lt;&lt; bit % CHAR_BIT); //left shift and AND with masked-bit } const std::string to_string(char c1, char c2) { std::string str; for (unsigned int i = NumBits; i-- &gt; 0;) str.push_back(static_cast&lt;char&gt; ('0' + test(i))); while (str.find(&quot;0&quot;) != std::string::npos) { str.replace(str.find(&quot;0&quot;), 1, std::string{ c1 }); } while (str.find(&quot;1&quot;) != std::string::npos) { str.replace(str.find(&quot;1&quot;), 1, std::string{ c2 }); } return str; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const bitarr&amp; b) { for (unsigned i = NumBits; i-- &gt; 0; ) os &lt;&lt; b.test(i); return os &lt;&lt; '\n'; } }; int main() { try { bitarr&lt;5&gt; bitarr; bitarr.set(1); bitarr.set(2); const std::string strr = bitarr.to_string('F', 'T'); std::cout &lt;&lt; strr &lt;&lt; std::endl; if (strr != &quot;FFTTF&quot;) { throw std::runtime_error{ &quot;Conversion failed&quot; }; } } catch (const std::exception&amp; exception) { std::cout &lt;&lt; &quot;Conversion failed\n&quot;; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:20:10.167", "Id": "482581", "Score": "2", "body": "By the way, are you aware of [`std::bitset`](https://en.cppreference.com/w/cpp/utility/bitset)?" } ]
[ { "body": "<h1>Use <code>size_t</code> consistently</h1>\n<p>You use both <code>size_t</code> and <code>unsigned</code> for counting. Stick with <code>size_t</code>.</p>\n<h1>Use default member initialization</h1>\n<p>You can use <a href=\"https://en.cppreference.com/w/cpp/language/data_members\" rel=\"nofollow noreferrer\">default member initialization</a> to ensure <code>arr[]</code> is initialized, without having to call <code>memset()</code>:</p>\n<pre><code>class bitarr\n{\n static const unsigned NumBytes = (NumBits + CHAR_BIT - 1) / CHAR_BIT;\n unsigned char arr[NumBytes] = {};\n ...\n};\n</code></pre>\n<p>You can then also remove the constructor completely.</p>\n<h1>Unnecessary <code>if</code>-statement in <code>set()</code></h1>\n<p>You don't need to check whether <code>val</code> is <code>true</code> in <code>set()</code>. If it is false, the body of the <code>if</code>-statement will still do the right thing. While it might look like that would do a lot of work for nothing, the processor might easily mispredict this condition, making it less efficient than not having the <code>if</code> at all.</p>\n<h1>Make all functions that do not modify <code>arr[]</code> <code>const</code></h1>\n<p>You made the function <code>test()</code> <code>const</code>, but <code>to_string()</code> also does not modify the bit array, so you can make that function <code>const</code> as well.</p>\n<h1>Optimize <code>to_string()</code></h1>\n<p>Your function <code>to_string()</code> is very inefficient. The caller provides you with the characters to use for the representation of one and zero bits, but you first ignore that and build a string of <code>'0'</code> and <code>'1'</code>, and then replace those characters one by one. Why not build the string directly using <code>c1</code> and <code>c2</code>? Also, since you know how long the string will be, you should reserve space for all the characters up front.</p>\n<pre><code>std::string to_string(char c1, char c2) const\n{\n std::string str;\n str.reserve(NumBits);\n\n for (size_t i = NumBits; i-- &gt; 0;)\n str.push_back(test(i) ? c2 : c1);\n\n return str;\n}\n</code></pre>\n<p>You implementation also has bugs: <code>to_string('0', '1')</code> results in an infinite loop, and <code>to_string('1', '0')</code> always results in a string with all zeroes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T10:30:16.050", "Id": "482587", "Score": "0", "body": "Oh, may I know why it results in an infinite loop? Thanks a lot by the way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T11:45:50.593", "Id": "482597", "Score": "2", "body": "If you are trying to replace `'0'` with `'0'` while there are still `'0'`s in the string, then you will have an infinite loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:19:12.263", "Id": "245695", "ParentId": "245688", "Score": "2" } } ]
{ "AcceptedAnswerId": "245695", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T07:04:37.637", "Id": "245688", "Score": "5", "Tags": [ "c++", "bitwise" ], "Title": "Bitarr class optimization C++" }
245688
<p>I have come up with the following solution to find the maximum product for a contiguous sub-array:</p> <pre class="lang-py prettyprint-override"><code>def maxProduct(nums): max_prod = [0]*len(nums) min_prod = [0]*len(nums) for i in range(0, len(nums)): min_prod[i] = min(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i]) max_prod[i] = max(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i]) return max(max_prod) </code></pre> <p>Current solution is <code>O(n)</code> in space, trying to find <code>O(1)</code> solution for space, but I keep seem to missing it. Ideas?</p>
[]
[ { "body": "<ol>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 style guide</a> for variable and function naming convention. Both the variables and function names should have <code>snake_case</code> names.</li>\n<li>You can <a href=\"https://devdocs.io/python%7E3.8/library/functions#enumerate\" rel=\"nofollow noreferrer\">use <code>enumerate</code></a> to get index and value while iterating a list.</li>\n</ol>\n<hr />\n<p>For constant space solution, instead of using a list to keep track of current max and min products, use a variable for both positive product and negative product. If the current number is <span class=\"math-container\">\\$ 0 \\$</span>, reset them both to <span class=\"math-container\">\\$ 1 \\$</span> (They should be initialised as <span class=\"math-container\">\\$ 1 \\$</span> as well). At the end of for-loop (inside the loop), keep updating your <code>current_max</code> value to keep track of max product encountered so far.</p>\n<hr />\n<p>As edge cases, you may also consider returning (or raising errors) when input was empty etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T08:22:54.180", "Id": "245691", "ParentId": "245689", "Score": "2" } } ]
{ "AcceptedAnswerId": "245691", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T07:19:19.697", "Id": "245689", "Score": "1", "Tags": [ "python", "array" ], "Title": "Maximum product contiguous subarray" }
245689
<p>I have solved the palindrome question on LeetCode today, but I wasn't happy with the original solution - I used strings, it worked slowly and used a lot of memory.</p> <p>So I rewrote the answer using a dictionary approach instead knowing that looking up a value in a dictionary has lower time complexity than searching through a list, but the results were strange - my latest answer is much better in terms of memory use (better than 94.65% of other submissions), but it became significantly slower. As you can see in the image below, my last submission is much slower than the first, but memory use has improved a lot:</p> <p><a href="https://i.stack.imgur.com/00WvB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/00WvB.jpg" alt="enter image description here" /></a></p> <p>My original solution was this:</p> <pre class="lang-py prettyprint-override"><code>class Solution: def isPalindrome(self, x: int) -&gt; bool: s = str(x) if len(s) == 1: palindrome = True i = int(len(s)/2) for p in range(i): if s[p] != s[-(p+1)]: return False else: palindrome = True return palindrome </code></pre> <p>And the updated version is:</p> <pre class="lang-py prettyprint-override"><code>class Solution: def isPalindrome(self, x: int) -&gt; bool: s = {i:j for i,j in enumerate(str(x))} i = (max(s)+1)//2 if max(s)+1 == 1: return True for p in range(i): if s[p] != s[max(s)-p]: return False else: palindrome = True return palindrome </code></pre> <p>Can anyone explain why the latest version is so much slower? I thought it should be faster...</p> <p>What should I change to improve the speed?</p> <p><strong>EDIT:</strong> New version based on <em>@hjpotter</em> comment. Now I only have 1 call to <code>max()</code> in the entire script and yet it's even worse - <strong>168ms and 13.9 Mb</strong>. I don't understand what's happening here:</p> <pre><code>class Solution: def isPalindrome(self, x: int) -&gt; bool: s = {i:j for i,j in enumerate(str(x))} m = max(s) i = (m+1)//2 if m+1 == 1: return True for p in range(i): if s[p] != s[m-p]: return False else: palindrome = True return palindrome </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:03:09.697", "Id": "482576", "Score": "1", "body": "You have 2 calls to `max`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:04:28.660", "Id": "482577", "Score": "0", "body": "Is `max()` that expensive to use? What could I replace it with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:10:20.210", "Id": "482578", "Score": "0", "body": "@hjpotter92, I just added a variable `m = max(s)` so that I call `max()` only once in the entire script, but for some reason results are even worse - now it's **168ms** and **13.9Mb** memory use. My worst solution by far. Makes no sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:13:11.300", "Id": "482579", "Score": "2", "body": "might just be an issue with executor environment then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T09:13:37.360", "Id": "482580", "Score": "0", "body": "Try with storing `len(s)` from first solution and check results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T11:08:02.993", "Id": "482591", "Score": "10", "body": "Timings on LeetCode are absolute garbage. I've had one solution be top 10% and bottom 10% just by running it multiple times. Have you timed this multiple times yourself on a computer with minimal usage? (unlike LeetCode's servers) Are you certain that the timings are accurate and uneffected by external load?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:52:42.140", "Id": "482721", "Score": "0", "body": "You aren't searching through a list, you're directly finding the thing you want. Your list code is not slow because of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T17:34:07.843", "Id": "482742", "Score": "2", "body": "I don't understand why you need your \"else\"? You just loop through your number, and if something doesn't match (not a palindrome), you return False. If everything matches, why not just return True at the end? Setting palindrome to True every time might not mean a lot, but why bother?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T02:58:18.863", "Id": "482761", "Score": "0", "body": "@Nyos, true. Also as per Konrad Rudolph's answer below the variable `palindrome` is not necessary at all. I could just have `return True` at the end of the function and if something is not a palindrome it will exit out with `return False` during the `for` loop. Actually, the reason I had the variable originally is because in the early version I declared `palindrome = False` in the beginning of the function and so `else` was there to set it to `True` when conditions are right. When I changed the code I didn't think about removing `else`." } ]
[ { "body": "<p>Time complexity of Orignal Solution u made : O(i)--only using a for loop.\nTime complexity of your new solution Containing enum: as you are using enum it takes time O(n) and then u are running a for loop O(i),which you can see in your run time.some overhead from enum can be seen.\nNote:there comes time with using function (everything is not ultra fast or optimal).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:47:24.077", "Id": "245705", "ParentId": "245692", "Score": "2" } }, { "body": "<blockquote>\n<p>So I rewrote the answer using a dictionary approach instead knowing that looking up a value in a dictionary has lower time complexity than searching through a list</p>\n</blockquote>\n<p>In this case a dictionary is slower than a list-like indexing. A string / list provides direct access to its elements based on indices, while a dictionary -- which is normally implemented as a hash table -- needs more computation such as computing the hash values of keys.</p>\n<blockquote>\n<pre><code>for p in range(i):\n if s[p] != s[max(s)-p]:\n return False\n else:\n palindrome = True\n</code></pre>\n</blockquote>\n<p>Here, <code>max</code> is called repeatedly -- and unnecessarily -- in the loop. There are two problems:</p>\n<ol>\n<li>The value <code>max(s)</code> is unchanged so it should be computed only once outside the loop and the result can be stored and accessed inside the loop.</li>\n<li><code>max(s)</code> requires comparing all keys of <code>s</code>. In this case, using <code>len(s) - 1</code> yields the same value and it is faster.</li>\n</ol>\n<p>There are some Python-specific improvements that could speed up the program. For example, the following implementations should be faster in most cases because they replace explicit <code>for</code> loops in Python with implicit ones, which are implemented in lower-level, interpreter-dependent languages (such as C) and therefore are much faster:</p>\n<p>Solution 1:</p>\n<pre><code>class Solution:\n def isPalindrome(self, x: int) -&gt; bool:\n s = str(x)\n return s == s[::-1]\n</code></pre>\n<p>Solution 2:</p>\n<pre><code>class Solution:\n def isPalindrome(self, x: int) -&gt; bool:\n s = str(x)\n mid = len(s) // 2\n return s[:mid] == s[:-mid-1:-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T07:45:07.020", "Id": "482772", "Score": "1", "body": "+1 for the `return s == s[::-1]`. Admittedly, you have to know that this is an idiom for reversing a string, but it is very sweet and simple once you understand that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T09:05:02.757", "Id": "483184", "Score": "0", "body": "@MichaelGeary, yeah, I didn't know this idiom. Definitely makes things so much simpler!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T16:20:36.557", "Id": "245713", "ParentId": "245692", "Score": "10" } }, { "body": "<p>Dictionary key access is slower than array index access. Both is in O(1), but the constant time is higher for the dictionary access.</p>\n<h2>Is there actually a difference?</h2>\n<p>I'm not sure how leetcode runs the code, so let's make a proper speed analysis:</p>\n<p><a href=\"https://i.stack.imgur.com/88B5e.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/88B5e.png\" alt=\"enter image description here\" /></a></p>\n<p>generated by</p>\n<pre class=\"lang-py prettyprint-override\"><code># Core Library modules\nimport operator\nimport random\nimport timeit\n\n# Third party modules\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\n\ndef is_palindrome_str(x: int) -&gt; bool:\n s = str(x)\n\n if len(s) == 1:\n palindrome = True\n\n i = int(len(s) / 2)\n\n for p in range(i):\n if s[p] != s[-(p + 1)]:\n return False\n else:\n palindrome = True\n\n return palindrome\n\n\ndef is_palindrome_dict(x: int) -&gt; bool:\n s = {i: j for i, j in enumerate(str(x))}\n i = (max(s) + 1) // 2\n\n if max(s) + 1 == 1:\n return True\n\n for p in range(i):\n if s[p] != s[max(s) - p]:\n return False\n else:\n palindrome = True\n\n return palindrome\n\n\ndef generate_palindrome(nb_chars):\n chars = &quot;abcdefghijklmnopqrstuvwxyz&quot;\n prefix = &quot;&quot;.join([random.choice(chars) for _ in range(nb_chars)])\n return prefix + prefix[::-1]\n\n\ndef main():\n text = generate_palindrome(nb_chars=1000)\n functions = [\n (is_palindrome_str, &quot;is_palindrome_str&quot;),\n (is_palindrome_dict, &quot;is_palindrome_dict&quot;),\n ]\n functions = functions[::-1]\n duration_list = {}\n for func, name in functions:\n durations = timeit.repeat(lambda: func(text), repeat=1000, number=3)\n duration_list[name] = durations\n print(\n &quot;{func:&lt;20}: &quot;\n &quot;min: {min:0.3f}s, mean: {mean:0.3f}s, max: {max:0.3f}s&quot;.format(\n func=name,\n min=min(durations),\n mean=np.mean(durations),\n max=max(durations),\n )\n )\n create_boxplot(duration_list)\n\n\ndef create_boxplot(duration_list):\n plt.figure(num=None, figsize=(8, 4), dpi=300, facecolor=&quot;w&quot;, edgecolor=&quot;k&quot;)\n sns.set(style=&quot;whitegrid&quot;)\n sorted_keys, sorted_vals = zip(\n *sorted(duration_list.items(), key=operator.itemgetter(1))\n )\n flierprops = dict(markerfacecolor=&quot;0.75&quot;, markersize=1, linestyle=&quot;none&quot;)\n ax = sns.boxplot(data=sorted_vals, width=0.3, orient=&quot;h&quot;, flierprops=flierprops,)\n ax.set(xlabel=&quot;Time in s&quot;, ylabel=&quot;&quot;)\n plt.yticks(plt.yticks()[0], sorted_keys)\n plt.tight_layout()\n plt.savefig(&quot;output.png&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>There clearly is a difference. And that is for a palindrome. My initial thought was that the generation of the dict is overhead. If you have a long string which clearly is no palindrome (e.g. already clear from the first / last char), then the first approach is obviously faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:21:41.210", "Id": "482652", "Score": "0", "body": "Nice usage of box plot. Consider a violin plot as an alternative :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T16:52:40.413", "Id": "245715", "ParentId": "245692", "Score": "5" } }, { "body": "<p>Apart from performance, there are several other problems in your implementation which the other answers did not address.</p>\n<ol>\n<li><a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">This should not be a class</a>. It should be a function, because it being a class offers no advantage whatsoever and it makes its usage more complex.</li>\n<li>The variable <code>palindrome</code> is unnecessary and confuses the reader: this variable is <em>always</em> going to be <code>True</code>. So remove it.</li>\n<li>Don’t cast the result of a division to <code>int</code>. Use integer division instead.</li>\n<li>The <code>if len(s) == 1</code> check is redundant: its logic is already subsumed in the subsequent code.</li>\n<li>Use descriptive variable names: <code>s</code> for an arbitrary string is fine but <code>i</code> to denote the middle index of a sequence is cryptic.</li>\n</ol>\n<p>An improved implementation (without changing the algorithm) would look as follows:</p>\n<pre><code>def is_palindrome(n: int) -&gt; bool:\n s = str(n)\n mid = len(s) // 2\n for i in range(mid):\n if s[i] != s[-i - 1]:\n return False\n return True\n</code></pre>\n<p>Or, using a generator expression:</p>\n<pre><code>def is_palindrome(n: int) -&gt; bool:\n s = str(n)\n mid = len(s) // 2\n return all(s[i] == s[-i - 1] for i in range(mid))\n</code></pre>\n<p>… and of course this whole loop could also be replaced with <code>return s[:mid] == s[: -mid - 1 : -1]</code> because Python gives us powerful subsetting.</p>\n<hr />\n<p>I also want to address a misconception in your question:</p>\n<blockquote>\n<p>looking up a value in a dictionary has lower time complexity than searching through a list,</p>\n</blockquote>\n<p>That’s only true if the dictionary has the same size as the sequence (more or less …), and if looking up the key is <em>constant</em>. Neither is true in your case. But what’s more, you still need to <em>construct</em> the list/dictionary, and you completely omit the complexity of these operations.</p>\n<p>In fact, the first thing your dictionary does is <em>also</em> construct the sequence — namely, by invoking <code>str(x)</code>. It then goes on to <em>traverse the whole list!</em> Because that’s what <code>i:j for i,j in enumerate(str(x))</code> does.</p>\n<p>So before even starting your algorithm proper, it has already performed <em>more work</em> than your other implementation which, after all, only needs to traverse <em>half</em> the string. Even if you stopped at this point and returned, the second implementation would already be slower than the first, and you haven’t even finished constructing the dictionary yet (constructing the dictionary from key: value mappings <em>also</em> takes time).</p>\n<p>As for the actual algorithm, you’re <em>still</em> traversing half the string, so once again you are doing the same work as your initial algorithm. This means you have the same asymptotic complexity. But even that part of the second algorithm is slower, because a dictionary is a much more complex data structure than a plain sequence, and each key access of the dictionary (<code>s[p]</code>) is substantially slower than the same access on a string or list would be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:00:45.477", "Id": "482633", "Score": "4", "body": "Thanks Konrad! That was very informative! I'd just like to address the first point - this is simply the default way Leetcode structures the answer. The class and function name are given to you even before you start writing any code. Personally, I would never call a Python function `isPalindrome()` like you see in my examples - I'd name it in the same way you did in your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:56:25.373", "Id": "482723", "Score": "4", "body": "The reason the dictionary is not faster than the list is primarily because the list code wasn't slow to begin with. *It does not search through the list.*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T06:49:59.300", "Id": "483066", "Score": "2", "body": "\"This should not be a class.\": This is due to leetcode. They give you a template to fill and it has to be a class. There is no way around it, although I agree with the statement outside of the platform." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T06:50:37.027", "Id": "483067", "Score": "0", "body": "Very nice review!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T21:42:17.343", "Id": "245731", "ParentId": "245692", "Score": "16" } }, { "body": "<p>You're mixing up <em>searching</em> and <em>accessing</em>. If you're looking for the value for a index/key, that's accessing. If you're looking for a particular value, without knowing its index/key, that's searching. Accessing is O(1) for both lists and dictionaries[1][2]. While they are the same time complexity, using a dictionary can take longer, due to the overhead of hashing, and the fact that a hash table takes up more space than list. Under the hood, a dictionary is an array with the indices being the hash values of the keys, and the entries being the values for the indices that are the hag value of a key, and null for indices that aren't. When you access a value in a dictionary, it takes the key you give it, hashes it, then looks at the list for the entry there.</p>\n<p>[1] Accessing is treated as being constant time, but that is somewhat of a simplification. Larger data sets do have longer access times. For one thing, if the data become large enough, it'll have to be moved out of active memory, so strictly speaking the time complexity is a non-constant function of the size of the list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T05:46:44.460", "Id": "245794", "ParentId": "245692", "Score": "3" } }, { "body": "<p>Lol you believe LeetCode's timing is proper? You're so cute.</p>\n<p>If you actually want to see speed differences between those solutions, with LeetCode's test cases and on LeetCode, I suggest running the solution 100 times on each input:</p>\n<pre><code>class Solution:\n \n def isPalindrome(self, x: int) -&gt; bool: \n for _ in range(100):\n result = self.real_isPalindrome(x)\n return result\n \n def real_isPalindrome(self, x: int) -&gt; bool: \n # Your real solution here\n</code></pre>\n<p>And then you should still submit several times and take the average or so, as times for the exact same code can differ a lot depending on server load.</p>\n<p>I did that with your three solutions and the times were about 1200 ms, 4300 ms, and 2600 ms. Since that did 100 times the normal work, the actual times of the solutions were about 12 ms, 43 ms, and 26 ms. The difference between that and the time shown for a regular submission of a solution is the judge overhead, which LeetCode brilliantly includes in the time.</p>\n<p>I also submitted your first solution normally a few times, got 60 ms to 72 ms. So if 100 runs of your solution take 1200 ms and one run takes 66 ms, then you have:</p>\n<pre><code>JudgeOverhead + 100 * Solution = 1200 ms\nJudgeOverhead + Solution = 66 ms\n\nSubtract the second equation from the first:\n=&gt; 99 * Solution = 1134 ms\n\nDivide by 99:\n=&gt; Solution = 11.45 ms\n\nAnd:\n=&gt; JudgeOverhead = 66 ms - 11.45 ms = 54.55 ms\n</code></pre>\n<p>Oh and the ordinary</p>\n<pre><code> def isPalindrome(self, x: int) -&gt; bool:\n s = str(x)\n return s == s[::-1]\n</code></pre>\n<p>solution got about 420 ms with the 100-times trick. Subtract 55 ms judge overhead and divide by 100 and you're at 3.65 ms for the solution. So in that case, the judge overhead absolutely dwarfs the actual solution time, and together with the time variance, the shown time for a normal single-run submission is absolutely meaningless.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T18:03:11.170", "Id": "246047", "ParentId": "245692", "Score": "1" } } ]
{ "AcceptedAnswerId": "245715", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T08:47:11.773", "Id": "245692", "Score": "7", "Tags": [ "python", "performance", "comparative-review" ], "Title": "Checking if an integer is a palindrome using either a string or a dict" }
245692
<p>How to refactor this go code to make it more easy to understand and to maintain?</p> <p>It is email sender worker-pool skeleton.</p> <p>To understand the working-pool logic I coded it without real email client and database code. To simulate the read from database, I used ints, taking them in random groups (0..6 items each) with random sleep times. Instead of sending real emails, Just printing with random sleeps.</p> <p>If I add real email client code into it, it will become more complex.</p> <p>Especially, how to split the code in the main function into smaller functions?</p> <pre><code>// main.go package main import ( &quot;fmt&quot; &quot;math/rand&quot; &quot;os&quot; &quot;os/signal&quot; &quot;strconv&quot; &quot;sync&quot; &quot;syscall&quot; &quot;time&quot; ) // Msg is an email message type Msg struct { From string To string Subject string Body string } var r = make(chan int, 100) func main() { fmt.Println(&quot;Begin&quot;) q := make(chan Msg) sigs := make(chan os.Signal) stop := make(chan bool) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { sig := &lt;-sigs fmt.Println(sig) stop &lt;- true }() var wg sync.WaitGroup for i := 0; i &lt; 4; i++ { wg.Add(1) go func() { defer wg.Done() for m := range q { send(m) } }() } for i := 0; i &lt; 100; i++ { r &lt;- i } close(r) wg.Add(1) go func() { defer wg.Done() for { a, _ := read() for _, m := range a { q &lt;- m } select { case &lt;-stop: close(q) return case &lt;-time.After(time.Millisecond): } } }() wg.Wait() fmt.Println(&quot;End&quot;) } func read() ([]Msg, error) { d := time.Duration(rand.Intn(400)) * time.Millisecond time.Sleep(d) a := []Msg{} c := rand.Intn(6) for i := 0; i &lt; c; i++ { n := &lt;-r m := Msg{&quot;support@example.com&quot;, &quot;user&quot; + strconv.Itoa(n) + &quot;@example.com&quot;, strconv.Itoa(n), &quot;Test Body&quot;} a = append(a, m) } for _, m := range a { fmt.Print(m.Subject, &quot; &quot;) } fmt.Println(&quot;read in&quot;, d) return a, nil } func send(m Msg) { d := time.Duration(rand.Intn(700)) * time.Millisecond time.Sleep(d) fmt.Println(m.Subject, &quot;sent in&quot;, d) } </code></pre> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T12:14:09.860", "Id": "482600", "Score": "1", "body": "Some suggestions to improve the question: 1) Change the title to something like `Email sender worker pool skeleton in go`. 2) Move all the explanations above the code. The current title can make the question off-topic which means it can be closed by the community. See [how to ask a good question](https://codereview.stackexchange.com/help/how-to-ask) for guidance." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T10:58:25.943", "Id": "245697", "Score": "3", "Tags": [ "go", "asynchronous" ], "Title": "Email sender worker-pool skeleton in go" }
245697
<p>I am new in coding in React and I have just joined a new organization where I need to send my code for review .The functionality is working fine but it seems to me that code in my component has become very lengthy ,also my submithandler method is making me iterate the array a couple of times,I don't know how to do it other way.Is there any way I can shorten my code to make it look better and increase the performance??Currently its taking a long time to show the data after i click submit ,looks like iteration oof array is taking time.</p> <p>Also,If i close the browser after clicking the submit button, the ajax pending request is still in progress.I want to end the request and stop loading once i close the browser or navigate to other page.myRequestor is a third party library of my organization that can be used to send a request.Please help me shorten the code and fix the pending ajax request issue.Below is the code that I have tried to do.</p> <pre><code>const propTypes = { name: PropTypes.string, tenant: PropTypes.arrayOf(PropTypes.any), myRequestor: PropTypes.object, // eslint-disable-line react/forbid-prop-types }; let myRequestor = null; const CallerUtil = () =&gt; { myRequestor = React.useContext(MyRequestorContext); return &lt;ApplicationLoadingOverlay isOpen backgroundStyle=&quot;clear&quot; /&gt;; } class ReadinessComponent extends React.Component { constructor(props) { super(props); this.state = { body: '', tenant: null, error: null, errorMsg: '', isOpen: false, showTable: false, isInvalid: false, isLoading: false, tenantId: '', items: [], tenantItems : null }; this.onChangeTenantDropDown = this.onChangeTenantDropDown.bind(this); this.onSubmitHandler = this.onSubmitHandler.bind(this); this.onChangeHandler = this.onChangeHandler.bind(this); this.tenantIdHandler = this.tenantIdHandler.bind(this); this.onClose = this.onClose.bind(this); this.addNewTenant = this.addNewTenant.bind(this); this.fetchInitial = this.fetchInitial.bind(this); } componentDidMount() { this.mounted = true; this.setState({ isLoading: true }); this.fetchInitial(); } componentWillUnmount(){ this.mounted = false; } onChangeTenantDropDown(value) { this.setState({ tenant: value, }); const info = this.state.tenantItems.find(function (t) { return t.name == value }) this.setState({ tenantId: info.id, }); } onSubmitHandler() { if (this.state.body == '') { this.setState({ isInvalid: true }); return; } this.setState({ isLoading: true }); const params = { &quot;tenantId&quot;: this.state.tenantId, &quot;tenantShortName&quot;: this.state.tenant, &quot;contactName&quot;: this.state.body } const { request } = myRequestor.get({ url: '/getReadinessCheck', params: params, }); // request.then(async ({ data }) =&gt; { request.then(({ data }) =&gt; { console.log(this.mounted); if (!this.mounted) { this.setState({ isLoading: false }); return; } console.log(data); let abc = data.find(vrsn =&gt; vrsn.name === 'TENANT_ERROR'); if (abc === undefined) { this.setState({ error: 'Failure', errorMsg:'Invalid Tenant',isLoading: false, isOpen: true, showTable: false, body: '', tenantId: ''}); return; } let readinessResp = data.map(version =&gt; (version.latest === true ? { ...version, name: version.name.concat('_LATEST') } : version)) readinessResp.sort(function (a, b) { var textA = a.name.toUpperCase(); var textB = b.name.toUpperCase(); return textA.localeCompare(textB); }); this.setState({ items: readinessResp, error: 'Success', showTable: true, isLoading: false }); }).catch(error =&gt; { this.setState({ error: 'Failure', errorMsg:'Failure', isLoading: false, isOpen: true, showTable: false ,body: '', tenantId: '' }); }); } onChangeHandler(event) { this.setState({ body: event.target.value, }); } tenantIdHandler(event) { this.setState({ tenantId: event.target.value, }); } onClose() { this.setState(prevState =&gt; ({ isOpen: !prevState.isOpen, })); } addNewTenant(shortName,tenantId){ const newTenantShortName = shortName; const newTenantId = tenantId; const newTenant = {'name':newTenantShortName, 'id':newTenantId}; this.setState({ tenantItems: [...this.state.tenantItems, newTenant] }); } fetchInitial() { this.setState({ isLoading: true }); const { request } = myRequestor.get({ url: '/tenants' });   request .then(({ data }) =&gt; { if(data[0].hasOwnProperty(&quot;error&quot;)){ this.setState({ error: 'Failure', errorMsg:data[0]['error'], isOpen: true, isLoading: false,tenantItems: [{'name':'Default', 'id':'Default'}]}); return; } let tenantsList = data; let tenants =[]; tenantsList.map(tenant =&gt; ( tenants.push({'name':tenant.shortName, 'id':tenant.key}))) this.setState({ tenantItems: tenants,isLoading: false }); }) .catch((error) =&gt; { this.setState({ error: 'Failure', isOpen: true, isLoading: false}); }); } render() { const { error, isOpen, body,showTable } = this.state; if (this.state.tenantItems === null) { return &lt;CallerUtil /&gt;; } if(this.state.isLoading){ return &lt;ApplicationLoadingOverlay isOpen backgroundStyle=&quot;clear&quot; /&gt;; } if (showTable) { return (&lt;div&gt; &lt;h1&gt;Readiness Status&lt;/h1&gt; &lt;ReadinessComponentView readinessInfo={this.state.items} /&gt;&lt;/div&gt;); } return ( &lt;div className=&quot;ruleSupportEvaluation&quot;&gt; &lt;Grid&gt; &lt;Grid.Row&gt; &lt;Grid.Column&gt; &lt;Heading level={1}&gt;Readiness Check&lt;/Heading&gt; &lt;/Grid.Column&gt; &lt;/Grid.Row&gt; &lt;Grid.Row&gt; &lt;Grid.Column className=&quot;ruleSupportEvaluation&quot; large={3} medium={3}&gt; &lt;div&gt; &lt;Heading className=&quot;info&quot; level={3}&gt;About&lt;/Heading&gt; &lt;Divider /&gt; &lt;Text className=&quot;description&quot; fontSize={18}&gt; Readiness Check &lt;/Text&gt; &lt;/div&gt; &lt;/Grid.Column&gt; &lt;Grid.Column className=&quot;ruleSupportEvaluation&quot; large={8} medium={8}&gt; &lt;div&gt; &lt;div className=&quot;readinessComponent&quot;&gt; &lt;Tenant tenant={this.state.tenantItems} change={this.onChangeTenantDropDown} /&gt; &lt;ModalManagerExample addNewTenant={this.addNewTenant} /&gt; &lt;/div&gt; &lt;InputField type=&quot;text&quot; label=&quot;Tenant-Id&quot; value={this.state.tenantId} placeholder=&quot;Tenant Id&quot; onChange={this.tenantIdHandler}/&gt; &lt;InputElement isInvalid ={this.state.isInvalid} change={this.onChangeHandler} value={body} /&gt; &lt;Submit click={this.onSubmitHandler} /&gt; {error === 'Failure' &amp;&amp; ( &lt;Notification errorMessage={this.state.errorMsg} close={this.onClose} isOpen={isOpen} /&gt; ) } &lt;/div&gt; &lt;/Grid.Column&gt; &lt;/Grid.Row&gt; &lt;/Grid&gt; &lt;/div&gt; ); } } ReadinessComponent.propTypes = propTypes; export default ReadinessComponent; </code></pre>
[]
[ { "body": "<pre><code>const info = this.state.tenantItems.find(function (t) { return t.name == value })\n// could be more concise with lambda\nconst info = this.state.tenantItems.find(t =&gt; t.name == value)\n</code></pre>\n<pre><code>let tenantsList = data;\nlet tenants =[];\ntenantsList.map(tenant =&gt; ( tenants.push({'name':tenant.shortName, 'id':tenant.key})))\n// you're implementing map using map+push here\n// can be simplified\nconst tenants = data.map(tenant=&gt;({\n name:tenant.shortName,\n id:tenant.key\n)})\n</code></pre>\n<p>These could all be const.</p>\n<pre><code>let abc = data.find(vrsn =&gt; vrsn.name === 'TENANT_ERROR'); \nvar textA = a.name.toUpperCase();\nvar textB = b.name.toUpperCase();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T17:37:19.733", "Id": "482616", "Score": "0", "body": "Thank you for the reply.But I see my submitHandler method code is making me iterate the response a couple of times.Could you please help me on how can i shorten the submitHandler method code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:19:56.473", "Id": "482622", "Score": "0", "body": "It doesn't look like there's anything awful going on with the array. Have you ruled out the readiness check or possibly the React items re-render for performance bottlenecks?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T19:01:48.017", "Id": "482629", "Score": "0", "body": "The reason I am asking is because after I click the submit button it sends the Ajax request and if I close the browser or navigate to other page before the request gets completed,the page still keeps sending the request unless it is completed .I tried to stop the pending Ajax request by using componentwillunmount but I get a warning saying Warning: Can't perform a React state update on an unmounted component.\nThis is a no-op, but it indicates a memory leak in your application.\nTo fix, cancel all subscriptions and asynchronous tasks" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T13:31:48.270", "Id": "245703", "ParentId": "245699", "Score": "1" } } ]
{ "AcceptedAnswerId": "245703", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T12:52:35.283", "Id": "245699", "Score": "4", "Tags": [ "javascript", "react.js", "react-native" ], "Title": "Clean up and Refactor react code to increase performance" }
245699
<p>I have implemented a neural network in C++. But I'm not sure whether my implementation is correct or not. My code of the implementation of neural networks given bellow. As an inexperienced programmer, I welcome any and all insights to improve my skill.</p> <pre><code>#include &quot;csv.h&quot; using namespace rapidcsv; using namespace std; class Neuron; struct connection{ connection(int i){ weight=a_weight=0; id=i; } void weight_val(double w){ weight=w; } void weight_acc(double a){ a_weight+=a; } void reset(){ a_weight=0.0; }; void move(double m,double alpha,double lambda){ weight=weight-alpha*a_weight/m-lambda*weight; } double weight,a_weight; int id=0; }; typedef vector &lt;Neuron&gt; layer; class Neuron{ public: Neuron(int idx,int nxt_layer_size){ n_id=idx; for(int i=0;i&lt;nxt_layer_size;i++){ n_con.push_back(connection(i)); n_con[i].weight_val(rand()/double(RAND_MAX)); } set_val(0.0); is_output_neuron=false; } void hypothesis(layer &amp;prev_layer){ double sm=0; for(int i=0;i&lt;prev_layer.size();i++){ sm+=prev_layer[i].get_val()*prev_layer[i].get_con(n_id).weight; } set_val(sigmoid(sm)); if(is_output_neuron){ cost+=target*log(get_val())+(1-target)*log(1-get_val()); } } void calc_delta(layer next_layer={}){ if(is_output_neuron||next_layer.size()==0){ delta=get_val()-target; }else{ double sm=0; delta=delta_dot(next_layer)*sigmoid_prime(get_val()); } } void calc_grad(layer &amp;nxt_layer){ for(int i=0;i&lt;nxt_layer.size()-1;i++){ n_con[i].weight_acc(get_val()*nxt_layer[i].get_delta()); } } double flush_cost(){ double tmp=cost; cost=0; return tmp; } double get_delta(){ return delta; } void set_target(double x){ target=x; is_output_neuron=true; } double get_val(){ return a; } void set_val(double x){ a=x; } void update_weight(double m,double alpha,double lambda){ for(int i=0;i&lt;n_con.size();i++){ n_con[i].move(m,alpha,lambda); n_con[i].reset(); } } connection get_con(int idx){ return n_con[idx]; } private: int n_id;double a; vector &lt;connection&gt; n_con; static double sigmoid(double x){ return 1.0/(1+exp(-x)); } static double sigmoid_prime(double x){ return x*(1-x); } double delta_dot(layer nxt_layer){ assert(nxt_layer.size()-1==n_con.size()); double sm=0; for(int i=0;i&lt;n_con.size();i++){ sm+=n_con[i].weight*nxt_layer[i].get_delta(); } return sm; } double target,delta,cost=0;bool is_output_neuron; }; class Network{ public: Network(vector &lt;int&gt; arch){ srand(time(0)); for(int i=0;i&lt;arch.size();i++){ int nxt_layer_size=i==arch.size()-1?0:arch[i+1]; layer tmp; for(int j=0;j&lt;=arch[i];j++){ tmp.push_back(Neuron(j,nxt_layer_size)); } tmp.back().set_val(1.0); n_layers.push_back(tmp); } } vector &lt;double&gt; feed_forward(vector &lt;double&gt; in,bool output=false){ vector &lt;double&gt; ot; assert(in.size()==n_layers[0].size()-1); for(int i=0;i&lt;in.size();i++){ n_layers[0][i].set_val(in[i]); } for(int i=1;i&lt;n_layers.size();i++){ for(int j=0;j&lt;n_layers[i].size()-1;j++){ n_layers[i][j].hypothesis(n_layers[i-1]); } } if(output) { for(int i=0;i&lt;n_layers.back().size()-1;i++){ ot.push_back(n_layers.back()[i].get_val()); } } return ot; } void feed_backward(vector &lt;double&gt; ot){ assert(ot.size()==n_layers.back().size()-1); for(int i=0;i&lt;ot.size();i++){ n_layers.back()[i].set_target(ot[i]); } for(int i=0;i&lt;n_layers.back().size()-1;i++){ n_layers.back()[i].calc_delta(); } for(int i=n_layers.size()-2;i&gt;=0;i--){ for(auto &amp;a:n_layers[i]){ a.calc_delta(n_layers[i+1]); a.calc_grad(n_layers[i+1]); } } } void done(double m){ for(unsigned i=0;i&lt;n_layers.size();i++){ for(unsigned j=0;j&lt;n_layers[i].size();j++){ n_layers[i][j].update_weight(m,alpha,lambda); } } } double calc_cost(){ for(int i=0;i&lt;n_layers.back().size()-1;i++){ cost_acc+=n_layers.back()[i].flush_cost(); } return cost_acc; } double get_cost(double m){ double tmp=cost_acc; cost_acc=0; return -tmp/m; } void set_hyper_params(double alpha,double lambda){ this-&gt;alpha=alpha; this-&gt;lambda=lambda; } private: vector &lt;layer&gt; n_layers; double cost_acc=0,alpha,lambda; }; int main() { Network net({4,5,3}); net.set_hyper_params(0.1,0.0); Document doc(&quot;../dataset.csv&quot;); vector &lt;double&gt; x1=doc.GetColumn&lt;double&gt;(&quot;x1&quot;); vector &lt;double&gt; x3=doc.GetColumn&lt;double&gt;(&quot;x3&quot;); vector &lt;double&gt; x4=doc.GetColumn&lt;double&gt;(&quot;x4&quot;); vector &lt;double&gt; x2=doc.GetColumn&lt;double&gt;(&quot;x2&quot;); vector &lt;double&gt; y=doc.GetColumn&lt;double&gt;(&quot;y&quot;); vector &lt;double&gt; lrc; for(int i=0;i&lt;10000;i++){ for(int j=0;j&lt;x1.size();j++){ net.feed_forward({x1[j],x2[j],x3[j],x4[j]}); vector &lt;double&gt; ot; ot.push_back(y[j]==0); ot.push_back(y[j]==1); ot.push_back(y[j]==2); net.feed_backward(ot); net.calc_cost(); } double cst=net.get_cost(x1.size()); lrc.push_back(cst); if(i%100==0) cout&lt;&lt;&quot;Cost=&quot;&lt;&lt;cst&lt;&lt;&quot;/i=&quot;&lt;&lt;i&lt;&lt;endl; net.done(x1.size()); } return 0; } </code></pre> <p><a href="https://github.com/d99kris/rapidcsv" rel="noreferrer">Rapid Csv</a> <a href="https://github.com/me-sharif-hasan/Machine-learnign-algo-from-scratch/blob/master/iris/dataset.csv" rel="noreferrer">Iris dataset</a></p>
[]
[ { "body": "<p>Looks plausible. The two biggest pieces of advice I have for you are:</p>\n<ul>\n<li><p>Format your code consistently and idiomatically! One easy way to do this is to use the <code>clang-format</code> tool on it. A more tedious, but rewarding, way is to study other people's code and try to emulate their style. For example, you should instinctively write <code>vector&lt;T&gt;</code>, not <code>vector &lt;T&gt;</code>.</p>\n</li>\n<li><p>It sounds like you're not sure if your code behaves correctly. For that, you should use <strong>unit tests</strong>. Figure out what it would mean — what it would look like — for a small part of your code to &quot;behave correctly,&quot; and then write a small test that verifies that what you expect is actually what happens. Repeat many times.</p>\n</li>\n</ul>\n<hr />\n<p>Stylistically: Don't do <code>using namespace std;</code>. Every C++ programmer will tell you this. (Why not? There are reasons, but honestly the best reason is because everyone agrees that you shouldn't.)</p>\n<p>Forward-declaring <code>class Neuron;</code> above <code>struct connection</code> is strange because <code>connection</code> doesn't actually need to use <code>Neuron</code> for anything.</p>\n<p><code>connection(int i)</code> defines an <em>implicit</em> constructor, such that the following line will compile and do an implicit conversion:</p>\n<pre><code>connection conn = 42;\n</code></pre>\n<p>You don't want that. So mark this constructor <code>explicit</code>. (In fact, mark <em>all</em> constructors <code>explicit</code>, except for the two that you want to happen implicitly — that is, copy and move constructors. <em>Everything</em> else should be explicit.)</p>\n<p><code>weight_val</code> and <code>weight_acc</code> look like they should be called <code>set_weight</code> and <code>add_weight</code>, respectively. Use noun phrases for things that are nouns (variables, types) and verb phrases for things that are verbs (functions). Also, avd unnec. abbr'n.</p>\n<p>...Oooh! <code>weight_val</code> and <code>weight_acc</code> actually modify <em>different data members!</em> That was sneaky. Okay, from the formula in <code>move</code>, it looks like we've got a sort of an &quot;alpha weight&quot; and a &quot;lambda weight&quot;? I bet these have established names in the literature. So instead of <code>weight_val(x)</code> I would call it <code>set_lambda_weight(x)</code> (or whatever the established name is); instead of <code>weight_acc(x)</code> I would call it <code>add_alpha_weight(x)</code>; and instead of <code>reset</code> I would call it <code>set_alpha_weight(0)</code>.</p>\n<p>Further down, you use <code>get_val()</code> and <code>set_val(x)</code> to get and set a member whose actual name is <code>a</code>. Pick one name for one concept! If its proper name is <code>a</code>, call the methods <code>get_a()</code> and <code>set_a(a)</code>. If its proper name is <code>val</code>, then name it <code>val</code>.</p>\n<hr />\n<pre><code>void done(double m){\n for(unsigned i=0;i&lt;n_layers.size();i++){\n for(unsigned j=0;j&lt;n_layers[i].size();j++){\n n_layers[i][j].update_weight(m,alpha,lambda);\n }\n }\n}\n</code></pre>\n<p>Again, the name of this method doesn't seem to indicate anything about its purpose. <code>x.done()</code> sounds like we're asking if <code>x</code> is done — it doesn't sound like a mutator method. Seems to me that the function should be called <code>update_all_weights</code>.</p>\n<p>The body of this function can be written simply as</p>\n<pre><code>void update_all_weights(double m) {\n for (Layer&amp; layer : n_layers) {\n for (Neuron&amp; neuron : layer) {\n neuron.update_weight(m, alpha, lambda);\n }\n }\n}\n</code></pre>\n<p>Notice that to distinguish the name of the <em>type</em> <code>Layer</code> from the name of the <em>variable</em> <code>layer</code>, I had to uppercase the former. You already uppercased <code>Neuron</code>, so uppercasing <code>Layer</code> should be a no-brainer.</p>\n<hr />\n<pre><code>weight=weight-alpha*a_weight/m-lambda*weight;\n</code></pre>\n<p>This formula is impossible to read without some whitespace. Look how much clearer this is:</p>\n<pre><code>weight = weight - alpha*a_weight/m - lambda*weight;\n</code></pre>\n<p>And then we can rewrite it as:</p>\n<pre><code>weight -= ((alpha/m) * a_weight) + (lambda * weight);\n</code></pre>\n<p>I might even split that up into two subtractions, if I knew I wasn't concerned about floating-point precision loss.</p>\n<pre><code>weight -= (alpha/m) * a_weight;\nweight -= lambda * weight;\n</code></pre>\n<hr />\n<pre><code>double weight,a_weight;\n</code></pre>\n<p>clang-format will probably do this for you (I hope!), but please: one declaration per line!</p>\n<pre><code>double weight;\ndouble a_weight;\n</code></pre>\n<hr />\n<p>That should be enough nitpicking to give you something to do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:17:04.957", "Id": "483105", "Score": "1", "body": "\"There are reasons, but honestly the best reason is because everyone agrees that you shouldn't.\" I would at least provide one reason: to prevent namespace/typename collisions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T16:11:34.227", "Id": "245712", "ParentId": "245701", "Score": "8" } } ]
{ "AcceptedAnswerId": "245712", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T13:12:09.517", "Id": "245701", "Score": "6", "Tags": [ "c++", "machine-learning", "neural-network" ], "Title": "Simple neural network in c++" }
245701
<p>Hello dear colleagues.</p> <p>As an exercise for Java streams, I've written simple program, which scrapes links to references from a news portal. Basically, I wanted to find out, which portals are the most referenced.</p> <p>Right now, I ended up with the following piece of code:</p> <pre><code>final Map&lt;String, List&lt;URL&gt;&gt; hostToURLs = Analyzer.mapByHost(ReferencesStore.read()); // E.g. bbc.com -&gt; [ https://www.bbc.com/article1, https://www.bbc.com/article2, etc ] // The following creates LinkedHashMap sorted by the number of URLs final LinkedHashMap&lt;String, List&lt;URL&gt;&gt; sortedHostToURLs = hostToURLs .entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.comparingInt(List::size))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m, n) -&gt; { m.addAll(n); return m; }, LinkedHashMap::new)); </code></pre> <p>I'm interested, if the the ugly merge lambda <code>(m,n)-&gt; {m.addAll(n); return m;}</code> in the collect method can be replaced with some method reference from standard library. I wasn't able to find anything useful in the documentation, nor was I able to ask google the right question to find out if such merge function exists. Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:35:19.170", "Id": "482686", "Score": "0", "body": "Why convert back to a map? Just print each `Map.Entry`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T13:53:31.697", "Id": "482699", "Score": "1", "body": "I'm using the sorted Map in following method calls, where I want the data to be sorted. Thank you for pointing this out. The print statement was there only for initial debugging purposes. I removed it so hopefully my intention with the code is more clear now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:43:50.377", "Id": "482828", "Score": "0", "body": "\"How do I join to lists in Java?\" (https://stackoverflow.com/questions/189559/how-do-i-join-two-lists-in-java) suggests that Java does not provide a List concatenation method; the alternatives all suggest converting the lists to streams, concatenating the streams, and converting the output stream to a list." } ]
[ { "body": "<p>The thing is that the merge function is never called in your case, because all you are doing is reordering an existing map, so IMO you don't really need to worry about it.</p>\n<p>Personally in such cases I just use <code>(m, n) -&gt; m</code>, because it's short and doesn't distract.</p>\n<p>Another variant would be to use a function that throws an exception when called. The JDK <a href=\"http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/stream/Collectors.java#l132\" rel=\"nofollow noreferrer\">does this itself</a> when you use the <code>toMap</code> overload that doesn't take a merge function:</p>\n<pre><code>private static &lt;T&gt; BinaryOperator&lt;T&gt; throwingMerger() {\n return (u,v) -&gt; { throw new IllegalStateException(String.format(&quot;Duplicate key %s&quot;, u)); };\n}\n</code></pre>\n<p>Another thing you may want to consider it not to use a <code>(Linked)HashMap</code> at all here, but simply collect the <code>Entry</code>s into a list. If you need to lookup an entry by key later, then just keep the original map around.</p>\n<hr />\n<p>EDIT: In cases where the merge function is used, your implemention is fine. You may want to just put it in a variable, so that its name can describe its function.</p>\n<p>One thing you could consider is using a function that creates a new list instead of &quot;reusing&quot; one of the existing lists. That would reflect the functional style of the code better, where one normally uses immutable data structures.</p>\n<p>The basic problem is that Java's <code>List</code> interface isn't intended for functional/immutable situations and doesn't have a simple method to concatinate two lists.</p>\n<p>If you are open to additional libraries you'd have more options. For example, Apache's Commons has a <a href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html#union-java.util.List-java.util.List-\" rel=\"nofollow noreferrer\"><code>union</code> method</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:16:18.270", "Id": "482704", "Score": "0", "body": "Thank you for your response. I din't realised the merge function is not called. But still, for the sake of my curiosity, would be there a better solution than the mine if the scenario was a bit different and the merge function was called?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T17:53:27.830", "Id": "482744", "Score": "0", "body": "@AnotherNoob See edit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T15:09:50.603", "Id": "245708", "ParentId": "245702", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T13:28:20.817", "Id": "245702", "Score": "4", "Tags": [ "java", "lambda" ], "Title": "Java - Functional interface for merging two lists" }
245702
<p>I'm trying to create a system to log all bookings for a few airbnb hosts, at first I had two models Home and Guest, where a home can have many guests and a guest could book for many homes,</p> <p>then I thought about creating a guest_home pivot table to link both tables... then things got complicated in my head, what about a Booking model, and (have that booking model act as a pivot table ?) , to me doing new Booking() seemed better than attaching ids to home model?</p> <p>How could you guys go about this, it's making my brain malt right now...</p> <p>I thought of doing something like this in my BookingController:</p> <pre><code>public function createBooking(Request $request) { $guestIds = Guest::latest()-&gt;take(3)-&gt;pluck('id'); $home = Home::findOrFail($request-&gt;input('home_id', 2)); $booking = new Booking(); $booking-&gt;home_id = $home-&gt;id; $booking-&gt;guests()-&gt;attach($guestIds); $booking-&gt;save(); return response()-&gt;json([ 'booking' =&gt; $booking, ]); } </code></pre> <p>Should I create home_guest pivot table, is a pivot table even needed? what models would I link, please bear with me, so far this is what I got:</p> <p>Models</p> <pre><code>class Guest extends Model { public function bookings() { return $this-&gt;belongsToMany('App\Models\Home', 'bookings', 'guest_id', 'home_id'); } } class Home extends Model { public function guests() { return $this-&gt;belongsToMany('App\Models\Guest', 'bookings', 'home_id', 'guest_id'); } public function bookings() { return $this-&gt;hasMany('App\Models\Booking'); } } class Booking extends Model { //Is Booking needed or I could make a pivot table like home_guest called 'bookings' ? public function guests() { return $this-&gt;belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id'); } } </code></pre> <p>Migrations:</p> <pre><code>Schema::create('bookings', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;unsignedInteger('home_id')-&gt;index(); $table-&gt;foreign('home_id')-&gt;references('id')-&gt;on('homes')-&gt;onDelete('cascade')-&gt;onUpdate('cascade'); $table-&gt;unsignedInteger('guest_id')-&gt;nullable()-&gt;index(); $table-&gt;foreign('guest_id')-&gt;references('id')-&gt;on('guests')-&gt;onDelete('cascade')-&gt;onUpdate('cascade'); $table-&gt;timestamps(); }); Schema::create('homes', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;unsignedInteger('host_id')-&gt;index(); $table-&gt;foreign('host_id')-&gt;references('id')-&gt;on('hosts')-&gt;onDelete('cascade')-&gt;onUpdate('cascade'); $table-&gt;string('fullAddress')-&gt;unique(); $table-&gt;integer('rooms')-&gt;unique(); $table-&gt;timestamps(); }); Schema::create('guests', function (Blueprint $table) { $table-&gt;increments('id'); $table-&gt;string('fullName')-&gt;unique(); $table-&gt;string('identificationType')-&gt;unique(); $table-&gt;text('country')-&gt;nullable(); $table-&gt;timestamps(); }); <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T06:18:56.653", "Id": "482659", "Score": "2", "body": "Please clarify whether the current code works the way it should or not. Your question is quite unclear." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:19:23.637", "Id": "245704", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "Booking system ala airbnb many to many laravel relationship?" }
245704
<p>Consider the taxicab ring metric space shown below. This is a discrete metric space in which we have both a grid and concentric diamond rings. This metric space stretches infinitely in all four directions, but I have only drawn four rings.</p> <p>I want to write a function that returns the shortest distance between any two points in this metric space. Obviously, the shortest distance must be lesser than or equal to the <a href="https://en.wikipedia.org/wiki/Taxicab_geometry" rel="nofollow noreferrer">taxicab distance</a> because sometimes we can take the diagonal shortcuts. For example, the taxicab distance between (2,-1) and (3,1) is 3. However, we can reduce this to 2 when we follow the diagonal shortcut from (2,-1) to (3,0). Similarly, the taxicab distance between (2,-1) and (-1,3) is 7. However, we can reduce this to 5 when we follow the diagonal shortcut from (2,0) to (0,2).</p> <p><a href="https://i.stack.imgur.com/DGnAQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DGnAQ.png" alt="Taxicab Ring Metric Space" /></a></p> <p>So, here's the function that I came up with in Haskell. It computes the taxicab distance and then subtracts the diagonal shortcut distance to get the final result. The shortcut distance is calculated in one to three steps. First, we translate and rotate p2 such that p1 is at the origin. This is so that we don't repeat ourselves by duplicating code for each of the four quadrants. If the new p2 is in the upper right quadrant then the shortcut distance is 0 because we're moving in a line perpendicular to the diagonal.</p> <p>If the new p2 is in the upper left or the lower right quadrants then we are moving parallel to the diagonal. Hence, we can compute the shortcut distance accordingly. It's the minimum of the difference in x and y coordinates and the corresponding absolute coordinate of p1, i.e. x1 for upper left quadrant and y1 for the lower right quadrant.</p> <p>Finally, if the new p2 is in the lower left quadrant then we take advantage of <a href="https://en.wikipedia.org/wiki/Symmetric_function" rel="nofollow noreferrer">symmetric property</a> of distance functions to perform the above steps again with p1 and p2 swapped. If both p1 and p2 are in opposite quadrants then we'll eventually call the <code>opposite</code> function. Now, there are two paths to get from p1 to p2. Either we go down first and then left or vice versa. Hence, we compute the shortcut distance for both and then select the one which is greater.</p> <pre class="lang-hs prettyprint-override"><code>type Coord = (Integer, Integer) type Metric = Coord -&gt; Coord -&gt; Integer dist :: Metric dist p1@(x1, y1) p2@(x2, y2) = abs (x2 - x1) + abs (y2 - y1) - diag p1 p2 diag :: Metric diag = adjacent (adjacent opposite) adjacent :: Metric -&gt; Metric adjacent metric p1@(x1, y1) p2@(x2, y2) | x &gt;= 0 &amp;&amp; y &gt;= 0 = 0 | x &lt;= 0 &amp;&amp; y &gt;= 0 = minimum [abs x, abs y, abs x1] | x &gt;= 0 &amp;&amp; y &lt;= 0 = minimum [abs x, abs y, abs y1] | otherwise = metric p2 p1 where x = if x1 &lt; 0 then x1 - x2 else if x1 &gt; 0 then x2 - x1 else abs x2 y = if y1 &lt; 0 then y1 - y2 else if y1 &gt; 0 then y2 - y1 else abs y2 opposite :: Metric opposite (x1, y1) (x2, y2) = max (minimum [abs (x2 - x1), abs x1, abs y2]) (minimum [abs (y2 - y1), abs x2, abs y1]) </code></pre> <p>Anyway, is it possible to simplify the above distance function? For example, <code>diag</code> is currently defined as the application of an <a href="https://en.wikipedia.org/wiki/Iterated_function" rel="nofollow noreferrer">iterated function</a> to another function. Can we get rid of this without duplicating code? Alternatively, is it possible to replace the call to <code>diag</code> with a <a href="https://en.wikipedia.org/wiki/Closed-form_expression" rel="nofollow noreferrer">closed-form expression</a>? The <code>diag</code> function is quite complex. Is it possible to simplify it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T14:53:43.617", "Id": "245706", "Score": "3", "Tags": [ "haskell", "mathematics" ], "Title": "How to simplify the following distance function for the taxicab ring metric space?" }
245706
<p>I am making an OOP to calculate growth of money according to theory of interest. I have made 3 classes: <code>Contribution</code> which contain data of a deposit and its growth, <code>InterestRate</code>, and <code>GrowthTL</code> which means to calculate the accumulated value at the <code>t_end</code> of all contributions with applied, may be varying, interest rates. I would like to know if there is better structure to write the code, for efficiency and to make it more user-friendly. Thanks.</p> <pre><code>import random class Contribution(object): def __init__(self, t, amount): self.t = t self.amount = amount def accumulate(self, t_end, interest_rates, sort = True): interest_rates = [i for i in interest_rates] result = self.amount if sort: interest_rates = sorted(interest_rates, key = lambda x: x.t) while True: if len(interest_rates)&gt;1: if (interest_rates[0].t &lt;= self.t &lt; interest_rates[0+1].t): break else: interest_rates.pop(0) elif len(interest_rates)==1: if self.t &gt;= interest_rates[0].t: break else: interest_rates.pop(0) else: break if len(interest_rates)&gt;0: t_start = self.t for i in range(len(interest_rates)-1): power = (interest_rates[i+1].t - t_start)/interest_rates[i].period_length if interest_rates[i].discount: result = result*((1-interest_rates[i].rate)**(-power)) else: if interest_rates[i].compound: result = result*((1+interest_rates[i].rate)**(power)) else: result = result*(1+ (power*interest_rates[i].rate)) t_start = interest_rates[i+1].t if interest_rates[-1].discount: result = result*((1-interest_rates[-1].rate)**(-(t_end-t_start))) else: if interest_rates[-1].compound: result = result*((1+interest_rates[-1].rate)**(t_end-t_start)) else: result = result*(1+((t_end-t_start)*interest_rates[-1].rate)) return result class InterestRate(object): def __init__(self, t, rate, period_desc, compound = True, discount = False): self.t = t self.rate = rate self.period_desc = period_desc self.compound = compound self.discount = discount if self.period_desc == &quot;annual&quot;: self.period_length = 1 elif self.period_desc == &quot;semi-annual&quot;: self.period_length = 1/2 elif self.period_desc == &quot;quarter&quot;: self.period_length = 1/4 elif self.period_desc == &quot;month&quot;: self.period_length = 1/12 else: self.period_length = self.period_desc class GrowthTL(object): def __init__(self, interval, contributions, interest_rates): self.interval = interval self.t_start = self.interval[0] self.t_end = self.interval[1] self.contributions = sorted(contributions, key = lambda x: x.t) contributions = []; t_taken = [] for i in range(len(self.contributions)): if i not in t_taken: contributions.append( self.contributions[i] ) t_taken.append(i) self.contributions = contributions self.interest_rates = sorted(interest_rates, key = lambda x: x.t) int_rates = []; t_taken = [] for i in range(len(self.interest_rates)): if i not in t_taken: int_rates.append( self.interest_rates[i] ) t_taken.append(i) self.interest_rates = int_rates if self.t_start not in t_taken: self.interest_rates[0].t = self.t_start def value_at_end(self): results = [] for c in contributions: result = c.accumulate(self.t_end, self.interest_rates, sort = False) results.append(result) print(result) return sum(results) amount = [100, 200, 300, 400, 500] t_amount = [1, 2, 3, 14, 15] int_rate = [0.1, 0.05, 0.1, 0.04, 0.05, 0.2] t_int_rate = [0, 2, 3, 4, 4.5, 10] periods = [&quot;annual&quot;, &quot;semi-annual&quot;, &quot;quarter&quot;, &quot;month&quot;] contributions = [Contribution(t_amount[i], amount[i]) for i in range(len(amount))] int_rates = [InterestRate(t_int_rate[i], int_rate[i], random.sample(periods, 1)[0]) for i in range(len(int_rate))] obj = GrowthTL([0, 20], contributions, int_rates) print(obj.value_at_end()) </code></pre>
[]
[ { "body": "<h2>Little things</h2>\n<pre><code>class Contribution(object):\n</code></pre>\n<p>object is the implied parent of all classes. This can be written as <code>class Contribution:</code>.</p>\n<pre><code>amount = [100, 200, 300, 400, 500]\nt_amount = [1, 2, 3, 14, 15]\nint_rate = [0.1, 0.05, 0.1, 0.04, 0.05, 0.2]\nt_int_rate = [0, 2, 3, 4, 4.5, 10]\n</code></pre>\n<p>Having separate variables for time values and monetary / fractional values seems odd. The data would be reflected more accurately in your code if it were phrased together.</p>\n<pre><code>contributions_data = [\n (1,100),\n (2,200),\n (3,300),\n (14,400),\n (15,500)\n]\ncontributions = [\n Contribution(t, amount) \n for t,amount in contributions_data\n]\n</code></pre>\n<p>The constructor is a very important method, so it should be left as simple as possible.</p>\n<pre><code>class InterestRate:\n periods = {\n 'annual':1,\n 'semi-annual':1/2,\n 'quarter':1/4,\n 'month':1/12\n }\n @staticmethod\n def get_period_length(period):\n if period in InterestRate.periods:\n return InterestRate.periods[period]\n return period\n \n def __init__(self, t, rate, period_desc, compound = True, discount = False):\n self.t = t\n self.rate = rate\n self.compound = compound\n self.discount = discount\n \n self.period_length = InterestRate.get_period_length(period_desc)\n</code></pre>\n<h2>Big Things</h2>\n<p><code>accumulate()</code> has an insane amount of responsibility. The specific rules for applying interest rates should be moved elsewhere.</p>\n<pre><code>class InterestRate:\n def apply(self,amount,delta):\n power = delta/self.period_length\n if self.discount:\n return amount*((1-self.rate)**(-power))\n if self.compound:\n return amount*((1+self.rate)**power)\n\n return amount*(1+(power*self.rate))\n\nclass Contribution:\n def rate_applies(self,interest_rate,t_end):\n return t_end &gt;= interest_rate.t &gt;= self.t\n def accumulate(self, t_end, interest_rates, sort = True):\n interest_rates = interest_rates[:]\n if sort:\n interest_rates = sorted(interest_rates, key = lambda x: x.t)\n\n applicable_rates = [\n rate for rate in interest_rates \n if self.rate_applies(rate,t_end)\n ]\n\n with_interest = self.amount\n for i in range(len(applicable_rates)-1):\n delta = applicable_rates[i+1].t - max(self.t,applicable_rates[i].t)\n with_interest = applicable_rates[i].apply(with_interest,delta)\n \n if len(applicable_rates)&gt;0:\n delta = t_end - applicable_rates[-1].t\n with_interest = applicable_rates[-1].apply(with_interest,delta)\n\n return with_interest\n</code></pre>\n<p>Both <code>GrowthTL</code> and <code>Contribution</code> seem to be worried about selecting the valid interest for the timespan. Since <code>Contribution</code> already handles interest rate validation, <code>GrowthTL</code> can be simplified.</p>\n<pre><code>class GrowthTL:\n\n def __init__(self, interval, contributions, interest_rates):\n self.t_start,self.t_end = interval\n\n self.contributions = sorted(contributions, key = lambda x: x.t)\n self.interest_rates = sorted(interest_rates, key = lambda x: x.t)\n \n def value_at_end(self):\n return sum([\n contribution.accumulate(self.t_end, self.interest_rates, sort = False)\n for contribution in self.contributions\n ])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:17:01.703", "Id": "245721", "ParentId": "245710", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T15:53:18.110", "Id": "245710", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "mathematics" ], "Title": "Python's OOP for Calculating Growth of Money" }
245710
<p>I have a simple localStorage cache class written in TypeScript, would love to have some insights on <strong>any</strong> way/aspect you think it can be improved (making it more readable, maintainable, usable, etc.):</p> <pre><code>export interface CacheItem&lt;T&gt; { data: T; expiration: number; } class SimpleLocalStorageCache&lt;T&gt; { constructor(private key: string, private durationInSeconds: number) {} get(): CacheItem&lt;T&gt; | null { const cache = localStorage.getItem(this.key); if (!cache) { return null; } const parsedCache = JSON.parse(cache); if (Date.now() &gt;= parsedCache.expiration) { return null; } return parsedCache; } update(data: T): void { const durationInMilliseconds = this.durationInSeconds * 1000; localStorage.setItem( this.key, JSON.stringify({ data, expiration: Date.now() + durationInMilliseconds, }) ); } } export default CacheSimpleLocalStorageCache; </code></pre> <p>Really appreciate any feedback on how to improve.</p>
[]
[ { "body": "<p>I took a look at it and will elaborate on my few findings below.</p>\n<p>First of all, your default export is wrong, but most likely you knew about it and you have already fixed it in your local version (might be also some pasting issue) - it's a no brainer. <code>SimpleLocalStorageCache</code> vs. <code>CacheSimpleLocalStorageCache</code>. Also I don't think it's necessary to export the interface <code>CacheItem</code> as it's most likely an internal interface to be used. Do not leak it, to prevent misuse :-)</p>\n<p>Next, looking at the constructor <code>constructor(private key: string, private durationInSeconds: number) {}</code> it's quite nice that you've used constructor assignment, thumbs up for that. What I think is a bit weird though, is the fact, that you've decided that the consumer of the API has to pass in seconds. That's a bit odd if we look at for example the parameters of <code>setTimeout</code>.</p>\n<p>Another thing that bugs me with the seconds/calculation is, that I would except it to be converted to milliseconds inside the constructor. That's a one time calculation and isn't required to be done each time a consumer of this API is calling the <code>update</code> function.</p>\n<p>I noticed that I can pass in functions which get's lost:</p>\n<pre><code>import Storage from &quot;yourStorageImplementation&quot;;\n\nconst TWO_SECONDS = 2;\nconst instance = new Storage(&quot;someKey&quot;, TWO_SECONDS);\ninstance.update(() =&gt; console.log(&quot;this will be lost!&quot;));\n</code></pre>\n<p>Fetching the exact same, results in this unexpected behavior:</p>\n<pre class=\"lang-js prettyprint-override\"><code>instance.get() // -&gt; { data: undefined, expiration: /*some value */ }\n</code></pre>\n<p>If you don't support persisting functions, which is fine, prevent the consumer of the API to pass in such data. This could be achieved by e.g. adjusting the generic to only allow <code>strings, booleans, and objects with key, value pairs</code> maybe extend/reduce this to your needs:</p>\n<pre class=\"lang-js prettyprint-override\"><code>class SimpleLocalStorageCache&lt;T extends string | number | boolean | { [key: string]: string | number | boolean }&gt; { ... }\n</code></pre>\n<p>Alternatively you could do filter out just any function like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>type IsNotFuction&lt;X&gt; = X extends (...args: any[]) =&gt; any ? never : X;\n\nclass SimpleLocalStorageCache&lt;T&gt; {\n ...\n update(data: IsNotFuction&lt;T&gt;): void {\n const durationInMilliseconds = this.durationInSeconds * 1000;\n \n localStorage.setItem(\n this.key,\n JSON.stringify({\n data,\n expiration: Date.now() + durationInMilliseconds,\n })\n );\n }\n}\n\n// Usage, isn't quite handy:\nconst storage1 = new SimpleLocalStorageCache&lt;() =&gt; void&gt;(&quot;someKey&quot;, 2); // It's required to provide the generic here, meeeh!\nconsole.log(storage1.update(() =&gt; alert(&quot;bla&quot;))) // Errors here!\nconsole.log(storage1.get());\n</code></pre>\n<p>I do like the solution and most of my write up is opinionated. Below are some suggestions I came up with while fiddling around with your solution:</p>\n<p><strong>Suggestion:</strong> Do you intend to extend it for <code>sessionStorage</code> and let the user decide the caching strategy? Is there a plan to properly support functions?</p>\n<p><strong>Suggestion:</strong> What do you think about a fluent API for this extension. Wouldn't it be nice to support something like: <code>new Storage(&quot;key&quot;, 2).update(/* some data */).get();</code> to immediately fetch the result again?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T01:55:52.463", "Id": "485554", "Score": "0", "body": "This is great! Thank you so much for taking the time to review the code and provide this feedback, it is incredible valuable to me. Your suggestions are also great, never thought about any of those, and will try to implement them. Once more, thanks :D, I really appreciate you took the time to provide such nice insight, will be working on it :)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T12:09:16.007", "Id": "247898", "ParentId": "245714", "Score": "2" } } ]
{ "AcceptedAnswerId": "247898", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T16:37:45.873", "Id": "245714", "Score": "4", "Tags": [ "javascript", "typescript", "cache" ], "Title": "TypeScript simple localStorage cache" }
245714
<p>Solved, <a href="https://codereview.stackexchange.com/questions/245878/improved-get-release-npm-module">question with improved code</a></p> <p>I've created a simple npm module and CLI program to get the latest GitHub and Bitbucket release from their APIs using Node.js. Please tell me if there's anything to improve!</p> <h3>Module code:</h3> <pre class="lang-js prettyprint-override"><code>#!/usr/bin/env node const fetch = require(&quot;node-fetch&quot;); /** * @param {string} string * @return {string} */ const normalize = (string) =&gt; { try { return string.toUpperCase().trim() } catch (e) { return string } } /** * @param {string} provider * @param {string} user * @param {string} repo * @param {string} part */ module.exports.getRelease = async ({provider, user, repo, part = &quot;&quot;}) =&gt; { if (normalize(provider) === normalize(&quot;github&quot;)) { let json = (await (await fetch(`https://api.github.com/repos/${user}/${repo}/releases/latest`)).json()) if (json.message === &quot;Not Found&quot;) throw &quot;Invalid repository&quot; if (!(&quot;assets&quot; in json)) throw &quot;Rate limit exceeded&quot; let browser_download_urls = json.assets.map(asset =&gt; asset.browser_download_url) return browser_download_urls.filter(url =&gt; url.includes(part)) } else if (normalize(provider) === normalize(&quot;bitbucket&quot;)) { let json = (await (await fetch(`https://api.bitbucket.org/2.0/repositories/${user}/${repo}/downloads/`)).json()) if (json.type === &quot;error&quot;) throw &quot;Invalid repository&quot; let links = json.values.map(value =&gt; value.links.self.href) return links.filter(url =&gt; url.includes(part)) } else { throw &quot;Invalid provider&quot; } } const usage = _ =&gt; { console.log( `Usage: get-release (github|bitbucket) user repo [partofreleasefile] Ex: get-release github phhusson treble_experimentations get-release github phhusson treble_experimentations arm64-ab-gapps get-release bitbucket JesusFreke smali get-release bitbucket JesusFreke smali baksmali` ) process.exit(1) } // If via CLI if (require.main === module) { let args = process.argv.slice(2) if (args.length !== 3 &amp;&amp; args.length !== 4) { usage() } module.exports.getRelease({ provider: args[0], user: args[1], repo: args[2], part: args[3] }).then(result =&gt; { if (result.length !== 1) { console.log(result) } else { console.log(result[0]) } }).catch(error =&gt; { console.log(error) usage() process.exit(1) }) } </code></pre> <h3>Called using:</h3> <pre class="lang-js prettyprint-override"><code>const { getRelease } = require(&quot;get-release&quot;) ;(async _ =&gt; { let url = await getRelease( { provider: &quot;github&quot;, user: &quot;phhusson&quot;, repo: &quot;treble_experimentations&quot;, part: &quot;arm64-ab-gapps&quot; } ) console.log(url[0]) })() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T06:49:57.090", "Id": "482914", "Score": "0", "body": "Why the double `await` in `(await (await fetch(`, does it not work with a single `await`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:54:17.597", "Id": "482950", "Score": "0", "body": "@konijn Nope, it doesn't work without the double" } ]
[ { "body": "<p>Consider using a hashmap of provider -&gt; process. This will enable you to register new providers with relative ease.</p>\n<pre><code>async function githubRelease({user, repo, part = &quot;&quot;}) {\n let json = (await (await fetch(`https://api.github.com/repos/${user}/${repo}/releases/latest`)).json())\n if (json.message === &quot;Not Found&quot;) throw &quot;Invalid repository&quot;\n if (!(&quot;assets&quot; in json)) throw &quot;Rate limit exceeded&quot;\n let browser_download_urls = json.assets.map(asset =&gt; asset.browser_download_url)\n return browser_download_urls.filter(url =&gt; url.includes(part))\n}\n</code></pre>\n<p>It will then be mapped inside the <code>getRelease</code> function as follows:</p>\n<pre><code>module.exports.getRelease = async ({provider, user, repo, part = &quot;&quot;}) =&gt; {\n if !(providerMethods[normalise(provider)]) {\n throw &quot;Invalid provider&quot;\n }\n return providerMethods[normalise(provider)](user, repo, part)\n}\n</code></pre>\n<p>where <code>providerMethods</code> would be:</p>\n<pre><code>let providerMethods = {\n normalise(&quot;github&quot;): githubReleases\n}\n</code></pre>\n<p>This will enable users of your module to register new (or private) registry providers. They can add a new provider to the <code>providerMethods</code> object (gitlab etc) and don't have to wait for you to update the library first for supporting any extra providers (you can add providers if popular).</p>\n<p>The <code>await (await fetch()).json()</code> can be extracted to another function. Although, I'd prefer using the <code>promise.then(r =&gt; r.json()).catch()</code> chain over multiple awaits, it is entirely dependent on your comfort with the language.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:25:34.143", "Id": "482986", "Score": "0", "body": "Hi, I've made changes: [Improved code](https://codereview.stackexchange.com/questions/245878/improved-get-release-npm-module). Thanks for answering!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T04:32:31.447", "Id": "245851", "ParentId": "245718", "Score": "2" } } ]
{ "AcceptedAnswerId": "245851", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T17:50:27.393", "Id": "245718", "Score": "8", "Tags": [ "javascript", "node.js", "console", "git", "modules" ], "Title": "get-release npm module" }
245718
<p>So I'm making my own singly linked list class, with methods that you'd expect such as <code>remove()</code> and <code>insert()</code>. I don't use pointers that much (almost never), so I thought by making a SLL class it would be good practice for me. But I'm not sure if I'm deallocating my memory correctly.</p> <p>Here's the structure of my SLL:</p> <pre class="lang-cpp prettyprint-override"><code>class singly_linked_list { private: struct Node { Node* next; int value; }; private: int _length; Node* head; public: ~singly_linked_list(); public: void remove(int index); void remove_front(); void remove_back(); }; </code></pre> <p>I'm most concerned about the destructor, and the three remove methods, and those are the ones deallocating memory, and I'm not sure if I'm doing it correctly.</p> <p>Here's their definitions:</p> <pre class="lang-cpp prettyprint-override"><code>class singly_linked_list { private: struct Node { Node* next; int value; }; private: int _length; Node* head; public: ~singly_linked_list() { Node* node_ptr = head; for (int a = 0; a &lt; _length; ++a) { node_ptr = node_ptr-&gt;next; delete head; head = node_ptr; } } public: void remove(int index) { if (index &lt; 0 || index &gt;= _length) throw &quot;index is out of range&quot;; if (index == 0) { this-&gt;remove_front(); return; } Node* node_ptr = head; for (int a = 0; a &lt; index - 1; ++a) head = head-&gt;next; Node* temp = head-&gt;next; head-&gt;next = temp-&gt;next; delete temp; _length -= 1; } void remove_front() { if (_length == 1) { // should I delete head instead? head = nullptr; // delete head; _length = 0; return; } Node* temp = head; head = head-&gt;next; delete temp; _length -= 1; } void remove_back() { if (_length == 1) { head = nullptr; _length = 0; return; } Node* node_ptr = head; for (int a = 0; a &lt; _length - 2; ++a) node_ptr = node_ptr-&gt;next; Node* temp = node_ptr-&gt;next; node_ptr-&gt;next = nullptr; delete temp; _length -= 1; } }; </code></pre> <p>I checked a few other questions including <a href="https://codereview.stackexchange.com/questions/134874/linked-list-design-and-implementation-c">this one</a>, but it didn't go too much in depth on memory management.</p> <p>So a couple questions:</p> <ol> <li>Am I causing any memory leaks, and is there a better, safer way to do things?</li> <li>In <code>remove_front()</code>, should I set <code>head</code> to <code>nullptr</code>, or should I delete it instead?</li> </ol> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:44:07.097", "Id": "482627", "Score": "1", "body": "Please provide the entire class, without the constructor(s) and the insert functions this code really can' be reviewed. The private variables are meaningless without the constructor and the insert functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:57:30.527", "Id": "482628", "Score": "0", "body": "If you want to learn how to make lists is fine and a good exercise, but if you want to build software that is well written in c++ use the standard library stl and use std::list instead of building your own list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T19:14:40.423", "Id": "482630", "Score": "1", "body": "*\"Am I causing any memory leaks,\"* @DynamicSquid consider using leak sanitizer http://clang.llvm.org/docs/LeakSanitizer.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T21:07:17.253", "Id": "482632", "Score": "0", "body": "@camp0 Like I said in my post, I'm doing this just to practice, but yes, I would use STL in an actual application" } ]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Am I causing any memory leaks, and is there a better, safer way to do things?</p>\n</blockquote>\n<p>Yes, see for example your second question. A safer way is to use something like <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> to manage pointers for you.</p>\n<blockquote>\n<p>In remove_front(), should I set head to nullptr, or should I delete it instead?</p>\n</blockquote>\n<p>You should delete it of course. If you just set <code>head</code> to <code>nullptr</code>, the memory for the head node is still allocated.</p>\n<h1>Avoid using names that start with an underscore</h1>\n<p>Names that start with underscores are reserved for the standard library. There are <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">some more specific rules</a>, but in general it is best to avoid them completely. You can safely append an underscore to the end of a name though.</p>\n<p>On the other hand, while you have <code>_length</code>, <code>head</code> is written without an underscore. If you are not consistent in marking private variables with an underscore, there is not much point to it at all.</p>\n<h1>Flawed logic in <code>remove(int index)</code></h1>\n<p>There is an issue with the <code>for</code>-loop in <code>remove(int index)</code>: you are moving the head pointer instead of <code>node_ptr</code>. In fact you are not using <code>node_ptr</code> at all after initializing it. The compiler should have given you a warning about this (be sure to enable compiler warnings and fix them).</p>\n<p>To make this work correctly, even when removing the head node, you should use an extra layer of redirection: you want a pointer to the pointer you need to update, like so:</p>\n<pre><code>Node **node_ptr = &amp;head; // node_ptr is pointing to the variable `head`\nfor (int a = 0; a &lt; index - 1; ++a)\n node_ptr = &amp;(*node_ptr)-&gt;next; // node_ptr is updated to point to some node's `next` variable\n\nNode* temp = *node_ptr; // get the actual Node pointer to\n*node_ptr = (*node_ptr)-&gt;next; // update `head` or a `next` to skip one Node\ndelete temp; // delete the target Node\n</code></pre>\n<p>Once you grasp this you've become a two-star programmer!</p>\n<h1>Unnecessary code duplication</h1>\n<p>You have three different functions for removing an element, but they all do mostly the same. In fact, the first one, <code>remove(int index)</code>, does everything you need. You don't need to treat <code>index == 0</code> as a special case, the code will work correctly anyway. You can make <code>remove_front()</code> and <code>remove_back()</code> call the generic <code>remove()</code> function:</p>\n<pre><code>void remove(int index)\n{\n if (index &lt; 0 || index &gt;= _length)\n throw &quot;index is out of range&quot;;\n\n Node **node_ptr = &amp;head;\n for (int a = 0; a &lt; index - 1; ++a)\n node_ptr = &amp;(*node_ptr)-&gt;next;\n\n Node* temp = *node_ptr;\n *node_ptr = (*node_ptr)-&gt;next;\n delete temp;\n\n _length -= 1;\n}\n\nvoid remove_front()\n{\n remove(0);\n}\n\nvoid remove_back()\n{\n remove(_length - 1);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T19:30:10.893", "Id": "245726", "ParentId": "245719", "Score": "3" } } ]
{ "AcceptedAnswerId": "245726", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T18:06:44.017", "Id": "245719", "Score": "2", "Tags": [ "c++", "linked-list", "memory-management" ], "Title": "Proper way of deallocating memory in SLL?" }
245719
<p>I am wondering if I can get some feedback for my implementation of &quot;Sieve of Eratosthenes&quot; and twin prime. I followed <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">this pseudocode</a>.</p> <p>Few notes:</p> <ul> <li>I added <code>MAX(primes.size &lt;&lt; 1, (x &lt;&lt; 1) + 1)</code> to make I resize the table large enough to find the next twin prime.</li> <li>Use a struct to keep track of the size of the dynamic array</li> </ul> <p>Things I am concerned about:</p> <ul> <li>Using <code>POW</code></li> <li><code>goto</code> statement</li> </ul> <p>Only playground to test the code: <a href="https://www.onlinegdb.com/HydogHGxw" rel="nofollow noreferrer">https://www.onlinegdb.com/HydogHGxw</a></p> <p>Thank you.</p> <pre><code>#include &quot;prime.h&quot; #include &lt;math.h&gt; #include &lt;stdbool.h&gt; #include &quot;stdlib.h&quot; #include &quot;string.h&quot; #define INITIAL_TABLE_SIZE 9973 #define MAX(x, y) (((x) &gt; (y)) ? (x) : (y)) typedef struct { bool *array; unsigned int size } PRIMES; PRIMES primes = {NULL, 0}; /** * Create a boolean array &quot;prime[0..n]&quot; and initialize * all entries it as true. A value in prime[i] will * finally be false if i is Not a prime, else true. */ void sieve_of_eratosthenes(int n) { if (primes.array != NULL) { free(primes.array); } primes.size = n; primes.array = malloc(n * sizeof(bool)); memset(primes.array, true, n * sizeof(bool)); primes.array[0] = false; primes.array[1] = false; int i, j; for (i = 2; i &lt; (int)sqrt((double)n); i++) { // If primes[p] is not changed, then it is a prime if (primes.array[i] == true) { // Update all multiples of p for (j = (int)pow((int)i, 2); j &lt; n; j += i) { primes.array[j] = false; } } } } /** * Return the next prime greater than parameter such that -2 is also a prime */ int next_twin_prime(int x) { if (primes.array == NULL) { sieve_of_eratosthenes(INITIAL_TABLE_SIZE); } resize: if (x &gt;= primes.size) { int new_size = MAX(primes.size &lt;&lt; 1, (x &lt;&lt; 1) + 1); sieve_of_eratosthenes(new_size); } int i; for (i = x; i &lt; primes.size; i++) { if (primes.array[i] == true &amp;&amp; primes.array[i - 2] == true) { return i; } } goto resize; } </code></pre>
[]
[ { "body": "<h2>Your Concerns</h2>\n<p>The use of <code>pow(i, 2)</code> is unnecessary; you should simply use <code>i*i</code>.</p>\n<p>The <code>goto</code> statement is also unnecessary. You could wrap the code in <code>while(true) { ... }</code>.</p>\n<h2>Other Concerns</h2>\n<p>The cast <code>(int) i</code> is also unnecessary, as <code>i</code> is already an integer. Perhaps you meant to cast to a double?</p>\n<p>Computing <code>sqrt(n)</code> in the <code>for</code> loop termination condition is inefficient; you should compute it once outside the loop.</p>\n<p>The <code>primes</code> global should probably be declared static, so it isn’t visible outside the module. Then the “helper” function <code>sieve_of_eratosthenes</code> should also be static.</p>\n<p>Your overflow and resizing of the sieve does not preserve any previous work; perhaps you could use <code>realloc</code>?</p>\n<p>No twin prime pair would ever be even, so you could optimize the sieve to skip even numbers.</p>\n<p>This statement <code>memset(primes.array, true, n * sizeof(bool));</code> is questionable. If a bool is larger than 1 byte, then what are you storing in the array? For instance, if each <code>sizeof(bool) == 2</code>, then <code>primes.array[0]</code> would be <code>0x0101</code>, which is not the same as <code>true</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T00:08:28.190", "Id": "245734", "ParentId": "245725", "Score": "4" } } ]
{ "AcceptedAnswerId": "245734", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T19:29:18.093", "Id": "245725", "Score": "4", "Tags": [ "c", "primes" ], "Title": "C: Sieve of Eratosthenes and next twin prime" }
245725
<p>This is programmed in Visual Studio 2019 with the C++17 feature set.</p> <p>The intent with this code is to be able to create memory blocks of the specified alignment and size, so as to have contiguous cache-friendly memory and to only do one malloc and free for the whole block. Is there something wrong or missing from this implementation so that it would effectively fulfill its purpose?</p> <h3>MemoryBlock.h</h3> <pre><code>#pragma once class MemoryBlock { private: void* p_rawMem; void* p_currentMemLocation; size_t p_currentMemLocationOffset; size_t p_totalMemSize; size_t p_remainingMemSize; size_t p_alignment; void *p_lastMemByteLocation; void p_addCurrentMemLocation(size_t delta); public: MemoryBlock(size_t size, size_t alignment); void* getMemoryWith(size_t size, size_t alignemnt); ~MemoryBlock(); }; </code></pre> <h3>MemoryBlock.cpp</h3> <pre><code>#include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;cmath&gt; #include &lt;assert.h&gt; #include &quot;MemoryBlock.h&quot; void MemoryBlock::p_addCurrentMemLocation(size_t delta) { if (delta == 0) { return; } p_currentMemLocationOffset += delta; assert((p_currentMemLocationOffset) &lt;= p_totalMemSize); p_remainingMemSize -= delta; if (p_remainingMemSize == 0) { p_currentMemLocation = p_lastMemByteLocation; } else { p_currentMemLocation = static_cast&lt;void*&gt;(static_cast&lt;char*&gt;(p_currentMemLocation) + delta); } } MemoryBlock::MemoryBlock(size_t size, size_t alignment): p_rawMem(_aligned_malloc(size, alignment)), p_currentMemLocation(p_rawMem), p_currentMemLocationOffset(0), p_totalMemSize(size), p_remainingMemSize(size), p_alignment(alignment), p_lastMemByteLocation(static_cast&lt;void*&gt;(static_cast&lt;char*&gt;(p_rawMem) + (size - 1))) { } void* MemoryBlock::getMemoryWith(size_t size, size_t alignment) { if (size &gt; p_totalMemSize) { throw std::bad_alloc(); } if (size == 0) { throw std::invalid_argument(&quot;size must be greater than 0&quot;); } if (alignment == 0 || (alignment &amp;(alignment-1))!= 0) {//checks it alignment is power of 2 throw std::invalid_argument(&quot;alignment should be a power of 2.&quot;); } if (alignment &gt; p_alignment) { throw std::invalid_argument(&quot;alignment requirement is greater than the memory block alignment.&quot;); } if (size &gt; p_remainingMemSize) { return nullptr; } if (p_totalMemSize == p_remainingMemSize) { p_addCurrentMemLocation(size); return p_rawMem; } p_addCurrentMemLocation((std::ceil(p_currentMemLocationOffset/(double)alignment)*alignment)-p_currentMemLocationOffset); void* retVal = p_currentMemLocation; p_addCurrentMemLocation(size); return retVal; } MemoryBlock::~MemoryBlock() { _aligned_free(p_rawMem); } </code></pre> <h3>main.cpp</h3> <pre><code>int main() { MemoryBlock memBlock(1024,1024); int *memBlockIntPtr = new(memBlock.getMemoryWith(sizeof(int),alignof(int))) int(1); std::cout &lt;&lt; *memBlockIntPtr &lt;&lt; std::endl; constexpr size_t intArrSize = 4; int *memBlockIntArrPtr = static_cast&lt;int*&gt;(memBlock.getMemoryWith(sizeof(int)*intArrSize, alignof(int))); for (size_t i = 0; i &lt; intArrSize; i++) { new (&amp;memBlockIntArrPtr[i]) int(i); } for (size_t i = 0; i &lt; intArrSize; i++) { std::cout &lt;&lt; memBlockIntArrPtr[i] &lt;&lt; std::endl; } return 0; } </code></pre> <p>I also ask you if the usage of the code is correct in the main function, and if I'm handling the void pointers adequately in both single-variable and array cases. If not, of course, please correct me with an explanation. Say if I'm doing main, specifically, correctly or the whole thing- and if not, make it clear why. Also suggest if I should be using an underlying memory buffer of char* instead of void* (perhaps combined with static arrays).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T08:01:31.807", "Id": "482664", "Score": "0", "body": "What do you mean by *\"I'm doing main\"*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:37:38.373", "Id": "482715", "Score": "0", "body": "\"error: use of undeclared identifier 'p_lastMemByteLocation'\" I cannot compile your code. I think you forgot to add the member. Can you check that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:40:35.713", "Id": "482717", "Score": "0", "body": "@henje done. Fixed." } ]
[ { "body": "<h1>Use C++17 aligned <code>new</code> or <code>aligned_malloc()</code></h1>\n<p><code>_aligned_malloc()</code> is a Windows-specific, non-portable function. Luckily, C++17 added the portable <code>aligned_malloc()</code> without an underscore. It also introduces a variant of <code>new</code> that allows aligned allocation. The latter would look like so:</p>\n<pre><code>#include &lt;new&gt;\n...\nMemoryBlock::MemoryBlock(size_t size, size_t alignment):\n p_rawMem((void *)new(std::align_val_t(alignemnt)) char[size]),\n ...\n{\n}\n</code></pre>\n<h1>Unnecessary special case for <code>p_remainingMemSize == 0</code></h1>\n<p>Why is this a special case in <code>p_addCurrentMemLocation</code>? Just adding <code>delta</code> to the current pointer is perfectly fine. A pointer that points just beyond the end of an array or an allocated memory region is still a valid pointer.</p>\n<h1>Consider avoiding the check for <code>delta == 0</code></h1>\n<p>An <code>if</code>-statement is not free, especially not if the branch predictor cannot correctly predict the result of the condition. If <code>delta</code> is zero, then the rest of the code still works correctly, and it's just two additions and a subtraction.</p>\n<h1>Don't use floating point math</h1>\n<p>You should not need to use floating point math to calculate how much to advance <code>p_currentMemLocationOffset</code> inside <code>getMemoryWith()</code>. Depending on which processor your code is running on, converting to <code>double</code> and back to <code>size_t</code> can be an expensive operation. Furthermore, <code>double</code> has less precision than <code>size_t</code> on 64-bits machines, so the result might be wrong if very large memory blocks are used.</p>\n<p>Instead of <code>ceil(p_CurrentMemLocationOffset / (double)alignment)</code>, use the fact that integer division rounds down, and compensate for this by adding <code>alignment - 1</code> first:</p>\n<pre><code>p_addCurrentMemLocation((((p_currentMemLocationOffset + alignment - 1) / alignment) * alignment) - p_currentMemLocationOffset);\n</code></pre>\n<p>Alternatively, use the modulo operation to determine how much to add:</p>\n<pre><code>p_addCurrentMemLocation((alignment - p_currentMemLocationOffset % alignment) % alignment);\n</code></pre>\n<p>The latter will be especially fast if the compiler can deduce that <code>alignment</code> is always a power of two.</p>\n<h1><code>char *</code> vs. <code>void *</code></h1>\n<p>It's probably easier to use <code>char *</code> internally for the pointers, since you are doing arithmetic on them. And if you do that, the only time you need to cast is when returning from <code>getMemoryWith()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:31:27.930", "Id": "482635", "Score": "1", "body": "Very useful analysis!!! I must point out however a few things: visual studio does not provide an implementation for c++17`s aligned_alloc(), crazy right? and also, I use assert() because if everything goes right in the public function then that private function should *never* have that assertion fail, if it does it is I who has done a mistake not the public interface caller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:47:26.170", "Id": "482636", "Score": "0", "body": "also, are you sure the syntax you show for the aligned overload of the c++17 new operator is correct? gives me a compile error.(again I dont know if this is just visual studio deviating from the standard again or an error on your part, please confirm.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T07:48:53.067", "Id": "482663", "Score": "2", "body": "Ok, that's a good reason for having both `assert()` and `throw()`. Keep on doing that then :) I did make a mistake in the example of aligned `new`. Also, for the aligned `new` operator, you might have to `#include <new>`. But it might be that MSVC does not support aligned `new` anyway." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:27:38.430", "Id": "245732", "ParentId": "245727", "Score": "9" } } ]
{ "AcceptedAnswerId": "245732", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T20:11:58.993", "Id": "245727", "Score": "6", "Tags": [ "c++", "c++17" ], "Title": "Implementing a very simple memory block for quick allocation and memory alignment. C++" }
245727
<p>I have a jsonArray.js file</p> <pre><code>const jsonArray = [ {&quot;click&quot;: &quot;clearValue&quot;, &quot;alt&quot;: &quot;clearValueIcon&quot;, &quot;src&quot; : &quot;https://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/128/Actions-edit-clear-icon.png&quot;, &quot;style&quot;: &quot;grid-column:1/2;grid-row: 2/3;&quot;}, {&quot;click&quot;: &quot;negativePositive&quot;, &quot;alt&quot;: &quot;negativePositiveIcon&quot;, &quot;src&quot; : &quot;https://image.flaticon.com/icons/svg/1777/1777560.svg&quot;, &quot;style&quot;:&quot;grid-column:2/3;grid-row: 2/3&quot;}, {&quot;click&quot;: &quot;percentage&quot;, &quot;alt&quot;: &quot;percentageIcon&quot;, &quot;src&quot; : &quot;https://image.flaticon.com/icons/svg/69/69839.svg&quot;, &quot;style&quot;:&quot;grid-column:3/4;grid-row: 2/3;&quot;} ] </code></pre> <p>In my App.vue file I import it and give the value to imagesData</p> <pre><code> beforeMount() { this.imagesData = JsonArray; } </code></pre> <p>Then I use a for loop to populate my img tags</p> <pre><code>&lt;img v-for=&quot;img in imagesData&quot; :key=&quot;img.alt&quot; @click=&quot;getFunction(img.click)&quot; :alt=&quot;img.alt&quot; :src=&quot;img.src&quot; :style=&quot;img.style&quot; /&gt; </code></pre> <p>The only way I have been able to get the click to work is with a giant switch statement that evaluates the string and calls the method.</p> <pre><code> getFunction: function(fn) { switch (fn) { case &quot;clearValue&quot;: this.clearValue(); break; case &quot;negativePositive&quot;: this.negativePositive(); break; }} </code></pre> <p>I am thinking there is a better way, but cannot think of one.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T22:59:00.480", "Id": "482639", "Score": "4", "body": "Can you provide some context for what kind of application this is? What does the `clearValue()` and `negativePositive()` functions do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T01:16:09.993", "Id": "482644", "Score": "0", "body": "@SimonForsberg it is a calculator app. clearValue turns the value to 0 and negativePositive turns the value negative or positive" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:09:03.887", "Id": "482646", "Score": "3", "body": "When providing more details, even in response to a comment, please use the [edit] link. I would like to see the complete component/app definition for context. Also note that `JsonArray` != `jsonArray`!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:50:58.140", "Id": "482720", "Score": "0", "body": "There is enough to review here, though I agree I would love to see the rest." } ]
[ { "body": "<p>First off, the file <code>jsonArray.js</code> doesn't contain &quot;JSON&quot;. It's a JavaScript source code file containing an JavaScript array literal which in turn contains JavaScript object literals. And since it's not JSON, you could theoretically put functions into the objects:</p>\n<pre><code>{\n alt: &quot;clearValueIcon&quot;, // Quotes around key are not needed, since it's not JSON\n src : &quot;...&quot;, // shortened\n style: &quot;grid-column:1/2;grid-row: 2/3;&quot;,\n handler() {\n this.value = &quot;&quot;; // For example\n }\n}, \n</code></pre>\n<p>And with a helping method:</p>\n<pre><code>methods: {\n callHandler(handler) {\n handler.call(this);\n }\n}\n</code></pre>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;img\n v-for=&quot;img in imagesData&quot;\n :key=&quot;img.alt&quot;\n @click=&quot;callHandler(img.handler)&quot;\n :alt=&quot;img.alt&quot;\n :src=&quot;img.src&quot;\n :style=&quot;img.style&quot;\n/&gt;\n</code></pre>\n<hr />\n<p>However I don't really see the point of outsourcing the buttons into a data array like this. Unless you are using the array in some other way in the project, you should just straight up have a list of <code>img</code>s (or custom &quot;button&quot; components) in your template.</p>\n<p>Two more things:</p>\n<ul>\n<li>The styles belong in the style sheet.</li>\n<li>The chosen texts for the <code>alt</code> attributes are bad. They are supposed to be fallback texts that displayed to the user in the case the images can't be displayed to (or seen by) the user. For the shown buttons something like <code>&quot;Clear&quot;</code>, <code>&quot;+/-&quot;</code> and <code>&quot;%&quot;</code> would be better choices.</li>\n</ul>\n<p>EDIT: One more thing: You shouldn't be using a plain image with a click handler, but for accessability wrap them in a <code>&lt;button&gt;</code> (or <code>&lt;a&gt;</code>) and put the handler on them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T08:35:46.270", "Id": "245739", "ParentId": "245728", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T20:46:18.967", "Id": "245728", "Score": "2", "Tags": [ "json", "vue.js" ], "Title": "Vue.js dynamically passing in functions" }
245728
<p><strong>Background and Code</strong></p> <p>I am using the following JavaScript code to inject CSS classes into a webpage after the page has loaded. These classes act as selectors that I can use to pinpoint a table cell to perform other actions (the actions that I wish to perform are out of the scope of this question).</p> <p>These selectors are used in automated UI testing on a legacy system where tables are used as layout, some tables are often times nested in other tables as layout elements, and unique IDs/names are not available. By injecting CSS classes with JavaScript in this way, I can accurately perform Selenium actions that are resilient (testing is out of the scope of this question the JavaScript that is here and it's performance are the scope of this question).</p> <pre><code>async function addTableCellClassInjector(row, tableIndex, rowIndex) { for (let columnIndex = 0; column = row.cells[columnIndex]; columnIndex++) { column.classList.add('agtelc-' + tableIndex + '-' + rowIndex + '-' + columnIndex); } } async function addTableRowClassInjector(table, tableIndex) { for (let rowIndex = 0; row = table.rows[rowIndex]; rowIndex++) { row.classList.add('agtelr-' + tableIndex + '-' + rowIndex); addTableCellClassInjector(row, tableIndex, rowIndex); } } async function addTableClassInjector(tables) { for (let tableIndex = 0; tableIndex &lt; tables.length; tableIndex++) { tables[tableIndex].classList.add('agtelt-' + tableIndex); addTableRowClassInjector(tables[tableIndex], tableIndex); } } addTableRowClassInjector(document.querySelectorAll('table')); </code></pre> <p>This code performs just fine when there are a couple of tables with a few rows to iterate over. However, the performance slows greatly when there are multiple tables with hundreds of rows.</p> <p>I believe there might be a better way to handle this whether through reworking the algorithm or using a combination of element selection and the arrays that are return through element selection operations.</p> <p><strong>Example Usage</strong></p> <p>Given the following HTML code (inaccuracies and all)</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Convoluted Layout Example&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;table&gt; &lt;tbody&gt; &lt;div&gt; &lt;tr&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/div&gt; &lt;div&gt; &lt;tr&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/div&gt; &lt;div&gt; &lt;tr&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/div&gt; &lt;div&gt; &lt;tr&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button&gt;Hello&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/div&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I am using Selenium to target a button that is listed on a table. Have made an example with similarities to the actual web page I am testing against. Please note that I cannot change the source of page I am testing against.</p> <p>In order to click on the 5 button in the fourth row in Selenium, I need to use the following selector (please note that an additional div or span may be added to the row, or cell elements during run time depending on the JavaScript that is running in the background thusly breaking this selection method).</p> <pre class="lang-css prettyprint-override"><code>body &gt; div:nth-child(1) &gt; table:nth-child(5) &gt; tbody:nth-child(1) &gt; tr:nth-child(3) &gt; td:nth-child(5) &gt; button:nth-child(1) </code></pre> <p>By injecting these classes I can target that same element using the following query.</p> <pre class="lang-css prettyprint-override"><code>.agtelc-0-3-4 &gt; button </code></pre> <p>This allows me to accurately target the button in a more stable way.</p> <p><strong>Question</strong></p> <p>Are there any code improvements that can be made to this solution that will scale well as tables and rows/columns increase?</p> <p>I have setup a sample page as a test for the purposes of this question <a href="https://dodzidenudzakuma.com/code-golf.html" rel="nofollow noreferrer">Example page with tables for iteration performance improvements</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:32:28.317", "Id": "482654", "Score": "0", "body": "Welcome to code review! could you please [edit] your post to include some samples of the CSS that uses the added classes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T05:42:11.793", "Id": "482657", "Score": "1", "body": "Why are those functions async?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:02:08.363", "Id": "482667", "Score": "0", "body": "Why are you doing this in the first place? What do you need the classes for? If it's about selecting the cells in CSS, then that can be done with `:nth-child` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:12:32.547", "Id": "482673", "Score": "0", "body": "@RoToRa this is being done for automated UI testing against a legacy system. In the system tables are often used as layout and are often nested. There may be an element on the 4th row of the table which is actually a table nested in another table. To avoid having to use XPath (which is fragile) and fighting against the dynamic elements changing CSS paths, I'm injecting these class selectors into each cell to make it easy and predictable to identify elements. Continued in next comment..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:16:28.167", "Id": "482674", "Score": "0", "body": "@RoToRa that makes it so I can identify an element as `agtelc-1-1-3 > .action-button` instead of `.data-holder > div > div > table > tbody > tr:last-child > div > table > ....` it gets pretty crazy. And this is legacy software. Testing was an afterthought. It was also designed before a lot of the web standards we use today were commonplace. I did say that the usage of this is out of the scope of this question. Just that I wanted to review the code in hand and optimize it for speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:21:22.617", "Id": "482675", "Score": "0", "body": "@slepic Just doing whatever I can do to optimize for speed which is the reason I posted it here for review. There are a number of things I may be doing incorrectly that are slowing performance. Please let me know how you think I can make performance improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:02:32.633", "Id": "482680", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I've updated the question with your suggestions. Thanks for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:21:53.360", "Id": "482706", "Score": "1", "body": "Just a thought, what about a happy medium where you only give a class to tables? then your example would be reduced to a pointer to the actual table? And it would be much much faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:25:32.257", "Id": "482708", "Score": "0", "body": "@konijn I might actually be able to work something out that way as a short-term solution. A robust ID by class system as listed would be the ideal, but if I just do it per table and per row that might fix things. Each row per table shouldn't be too bad. I think it's slowing down at a per cell level. If I can get the row I should be able to get each cell using nth child." } ]
[ { "body": "<p>From a short review;</p>\n<ul>\n<li><p>There is no point in creating those functions as <code>async</code>, if anything it gives the reader the mistaken impression that anything async may happen in those functions</p>\n</li>\n<li><p><code>(let columnIndex = 0; column = row.cells[columnIndex]; columnIndex++)</code> creates a global variable <code>column</code> which is bad practice</p>\n</li>\n<li><p><code>addTableCellClassInjector</code> is so specific that it currently does not look re-usable at all. As such, I would fold that loop back in to <code>addTableRowClassInjector</code></p>\n</li>\n<li><p>I dislike the <code>Injector</code> at the end of those function names, <code>addTableCellClass</code> is fine</p>\n</li>\n<li><p>I have the suspicion you do all this to find the column and row when you click a cell, this can all be avoid thusly;</p>\n<pre><code>//With td containing the clicked cell\n//Borrowed from https://stackoverflow.com/questions/16130062/\nconst col = td.cellIndex;\nconst row = td.parentNode.rowIndex;\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:33:08.953", "Id": "482676", "Score": "0", "body": "Seeing how performance is the issue I'm trying to solve, how would I parallelize the execution of steps that are not dependent on previous. Once I have all the tables on the page, one of these functions should be able to work on each of the tables in question independently once it has been assigned a table index. Additionally, each row can index its cells without the previous row needing to have finished its indexing cycle. I may be applying a C# mentality to JavaScript, but I would get a several fold performance boost in C# by doing it this way. Is this achievable in JavaScript?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:40:03.197", "Id": "482677", "Score": "1", "body": "I think we are missing each other’s point, every cell already knows what column it is in and what row, so you don’t have to do this at all. As for the asynchronous approach, you should check out webworkers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:44:53.467", "Id": "482678", "Score": "0", "body": "Its probably a lack of clarity on my part. I'm updating the question now with more relevant details. I believe I understand going at it from the cell first instead of from the table. I can look at reversing this algorithm, but I think because I left out the usage case its a little bit confusing to everyone. I'm using Selenium or another browser automation tool to click a button in a table that embedded in a table, that's embedded in another table for UI automation testing. However, the DOM changes and is unpredictable, so adding these classes ensures that my automation works predictably." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:03:09.410", "Id": "482681", "Score": "1", "body": "Just updated the question with a use case for context." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T08:36:04.383", "Id": "245740", "ParentId": "245729", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-19T20:55:21.827", "Id": "245729", "Score": "4", "Tags": [ "javascript", "html", "css", "iteration", "query-selector" ], "Title": "Improving the speed of the injection of class element selectors to HTML tables (sometimes nested) at scale through loop iteration or other methods" }
245729
<p>As an exercise, I've decided to write a lightweight, dictionary type database. Below are some of the features I've implemented:</p> <ul> <li>Overwrite Inserting: I allow the user to determine if they want to overwrite existing data, should they insert a pair that already has a value associated with the key of that pair.</li> <li>Encryption: The user can pass a 32 character long password that encrypts the database when they're done using it.</li> <li>Query Specification: The user can request a value by passing a key, request all keys associated with a particular value, or pass a pair and get the index of where that pair is in the database.</li> </ul> <p>Questions:</p> <ul> <li>Security: Is how I'm implementing security &quot;good&quot;? I've user <code>Fernet</code> in the past, and the absolute requirement of a 32 character long password ensures it will take a considerable amount of time to break the encryption. I'm also fairly concerned about the time between each encrypt and decrypt. Should I only decrypt when the user wants to insert or query the database?</li> <li>Password Verification: I let <code>Fernet</code> decide if the password is correct, instead of implementing something myself. Is this a good way of going about this?</li> <li>Conventions: The ones I'm particular about are the double underscore ones, such as <code>__encrypt_db</code>. I'm familiar with the purpose of hiding functions that are meant to be internal. Am I using this convention correctly?</li> <li>Any other improvements that you think I can make.</li> </ul> <p><strong><code>lindb.py</code></strong></p> <pre><code>&quot;&quot;&quot; LinDB @author Ben Antonellis. @date 07-17-2020. &quot;&quot;&quot; import os import json import base64 from cryptography.fernet import Fernet from cryptography.fernet import InvalidToken from typing import Any, Union, List, Dict class LinDB(): def __init__(self, name, pw=None): self.name = name self.__pw = pw self.db = {} self.file_name = f&quot;{self.name}.json&quot; self.connected = False self.new_db = False self.encrypt = self.__pw != None if self.encrypt: if len(self.__pw) &gt; 32: raise PasswordLengthError(&quot;Password must be at least 32 characters long!&quot;) self.__pw = base64.urlsafe_b64encode(self.__pw.encode()) self.fernet = Fernet(self.__pw) self.__create_db_file() def insert(self, pair: Dict, overwrite:bool=False) -&gt; None: &quot;&quot;&quot; Allows the user to insert a dictionary into the database. &quot;&quot;&quot; if not self.connected: quit(&quot;Please call .connect() to connect to database!&quot;) for key in pair: value = pair[key] if overwrite: for pair_key, db_key in zip(pair, self.db): if pair_key == db_key: self.db[db_key] = value break self.db.update(pair) def query(self, key:Any=None, value:Any=None) -&gt; Union[None, List[Any], bool]: &quot;&quot;&quot; Querys the database for either the key or value. If both key and value: Return position in database the first pair was found. If just key: Return value associated with key. If just value: Return all keys with associated value. &quot;&quot;&quot; if not self.connected: quit(&quot;Please call .connect() to connect to database!&quot;) try: if key and value: index = 0 for k, v in self.db.items(): if k == key and v == value: return index index += 1 if key and not value: return self.db[key] if value and not key: return [k for k, v in self.db.items() if v == value] except KeyError: return def save(self) -&gt; None: &quot;&quot;&quot; Saves the current database to the file. &quot;&quot;&quot; if not self.connected: quit(&quot;Please call .connect() to connect to database!&quot;) with open(self.file_name, &quot;w&quot;) as db_file: json.dump(self.db, db_file, ensure_ascii=False) def connect(self) -&gt; None: &quot;&quot;&quot; Indicates to the database that it should start decrypting now. &quot;&quot;&quot; if self.__db_empty(): self.connected = True return if self.encrypt: try: if not self.new_db: self.__decrypt_db() self.connected = True self.__load_db_file() except InvalidToken: quit(&quot;Wrong password for database!&quot;) def done(self) -&gt; None: &quot;&quot;&quot; Indicates to the database that it should start encrypting now. &quot;&quot;&quot; if not self.connected: quit(&quot;Please call .connect() to connect to database!&quot;) if self.encrypt: self.__encrypt_db() self.connected = False def __create_db_file(self) -&gt; None: &quot;&quot;&quot; Creates a database file with the name of the database as the filename. &quot;&quot;&quot; if not os.path.exists(self.file_name): _ = open(self.file_name, &quot;w&quot;).close() self.new_db = True def __load_db_file(self) -&gt; None: &quot;&quot;&quot; Load the database into the current database dictionary. &quot;&quot;&quot; with open(self.file_name, &quot;r&quot;) as db_file: try: json.load(db_file) except json.decoder.JSONDecodeError: print(&quot;Previous database not found. Creating new database.&quot;) self.db = {} def __encrypt_db(self) -&gt; None: &quot;&quot;&quot; Encrypts the database with Fernet. &quot;&quot;&quot; with open(self.file_name, 'rb') as db_file: db = db_file.readline() encrypted = self.fernet.encrypt(db) with open(self.file_name, 'wb') as db_file: db_file.write(encrypted) def __decrypt_db(self) -&gt; None: &quot;&quot;&quot; Decrypts the database with Fernet. &quot;&quot;&quot; with open(self.file_name, 'rb') as db_file: db = db_file.readline() decrypted = self.fernet.decrypt(db) with open(self.file_name, 'wb') as db_file: db_file.write(decrypted) def __db_empty(self) -&gt; bool: &quot;&quot;&quot; Determines if the database if empty. &quot;&quot;&quot; with open(self.file_name, &quot;r&quot;) as db_file: return not db_file.readlines() def __repr__(self): return f&quot;DB: {self.name}&quot; class PasswordLengthError(Exception): &quot;&quot;&quot; Raised when the user enters a password less than 32 characters long. &quot;&quot;&quot; def __init__(self, message): super().__init__(message) </code></pre> <p>Below is an example file of how an average user would work with this database:</p> <p><strong><code>test_db.py</code></strong></p> <pre><code>from lindb import LinDB # Example password 32 characters long # pw = &quot;zSLfLhAvjhmX6CrzCbxSE2dzXEZaiOfO&quot; db = LinDB(&quot;DB_TEST&quot;, pw=pw) # Decrypts the file if the password is correct # db.connect() # Start inserting pairs # db.insert({&quot;Ben&quot;: 16}) db.insert({&quot;Hannah&quot;: 17}) db.insert({&quot;Will&quot;: 18}) # Query database and display results # results = [ db.query(value=16), db.query(key=&quot;Hannah&quot;), db.query(key=&quot;Will&quot;, value=18), db.query(key=&quot;Test&quot;) ] for result in results: print(result) # Demonstrating the ability to use assignment expressions # # Should the key and/or value not exist, None is returned # if result := db.query(key=&quot;Be&quot;): print(result) # This writes the current database to the file # db.save() # Encrypts the file # db.done() </code></pre>
[]
[ { "body": "<p>Both impressive and ambitious!</p>\n<h2>Passwords</h2>\n<blockquote>\n<p>the absolute requirement of a 32 character long password ensures it will take a considerable amount of time to break the encryption</p>\n</blockquote>\n<p>It will also ensure that some users will be writing that password down or saving it to a text file, defeating the entire purpose of a password. A softer approach would be, during the password saving procedure, do an entropy check with a library that provides this. Issue a warning if the entropy is below a predetermined value.</p>\n<blockquote>\n<p>I let Fernet decide if the password is correct, instead of implementing something myself. Is this a good way of going about this?</p>\n</blockquote>\n<p>Yes!</p>\n<h2>Performance</h2>\n<blockquote>\n<p>I'm also fairly concerned about the time between each encrypt and decrypt. Should I only decrypt when the user wants to insert or query the database?</p>\n</blockquote>\n<p>That's a loaded question. If you expect your database to be potentially massive (over the size of RAM), then some of it will need to stay on disc, and it might as well stay encrypted there.</p>\n<p>The bigger question is: how do you cache your data? If the cache is aggressively memory-resident, it might be considered a security weakness to hold onto unencrypted contents in RAM for long periods of time. Another factor is the maximum acceptable latency between receiving a query, decrypting the contents on-the-fly if necessary and returning the result. Yet another factor is convenience of use: is authentication per-query, or per-session? I've never seen any databases authenticate per-query, but it's not entirely out of the question.</p>\n<p>I don't have good answers to these, so I suggest that you do some testing at scale.</p>\n<h2>Private methods</h2>\n<blockquote>\n<p>the double underscore ones, such as __encrypt_db. I'm familiar with the purpose of hiding functions that are meant to be internal. Am I using this convention correctly?</p>\n</blockquote>\n<p>Not really. It should just be <code>_encrypt_db</code>. Read more <a href=\"https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name\">here</a>.</p>\n<h2>Top-level classes</h2>\n<p>You're in Python 3, so these parens are not necessary:</p>\n<pre><code>class LinDB():\n</code></pre>\n<h2>Type hints</h2>\n<pre><code>pair: Dict\n</code></pre>\n<p>A dictionary of what? <code>Dict[str, str]</code>? Also,</p>\n<pre><code>name, pw=None\n</code></pre>\n<p>is probably</p>\n<pre><code>name: str, pw: Optional[str] = None\n</code></pre>\n<h2>Overambitious methods</h2>\n<p>This return type:</p>\n<pre><code>Union[None, List[Any], bool]\n</code></pre>\n<p>is a huge red flag that your query method is not specific enough, and trying to do too many things at once. I think your callers will not find the merging of all of these invocations convenient, and would benefit instead from you separating this out into <code>query_for_key</code>, <code>query_for_value</code>, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:11:48.770", "Id": "482702", "Score": "0", "body": "`callers will not find the merging of all of these invocations convenient` Maybe... Commenting as a heavy user key value stores, I **LOVE** when libraries make a single accessible method for query and perform their own control flow based on my input. Query optimization doesn't need to be a sql exclusive subsystem. I can pipeline the creation of a query upstream in my app like `q={'key':<something from user>}` or `q={'value':<something from user>}` far away from the actual database query. My code calls `lib.query(**q)` I'd very much prefer not implementing my own query control flow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:14:21.933", "Id": "482703", "Score": "0", "body": "@bauman.space It's precisely because developers shouldn't implement their own control flow that these methods should be separated. It's conceivable that a caller would need to follow `query()` with a long sequence of `if isinstance` to figure out exactly what happened." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T03:13:13.600", "Id": "245737", "ParentId": "245736", "Score": "9" } } ]
{ "AcceptedAnswerId": "245737", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T01:25:41.563", "Id": "245736", "Score": "7", "Tags": [ "python", "python-3.x", "database" ], "Title": "LinDB: A dictionary type database" }
245736
<p>For several days I have been learning about MVC, and I do some code but I don't know if that is correct. I will be grateful for some tips to get this code better.</p> <p><em>Here is my github respository</em><br /> <a href="https://github.com/DanielPeleton/mvc-php" rel="nofollow noreferrer">https://github.com/DanielPeleton/mvc-php</a></p> <p>class/db.php</p> <pre><code>&lt;?php class db{ public static $host = ''; public static $user = ''; public static $pass = ''; public static $dbName = ''; private function connect(){ $con = mysqli_connect($host, $user, $pass, $dbName); return $con; } public function query($query, $param = array()){ if(explode(' ', $query)[0] == 'SELECT'){ $stmt = self::connect()-&gt;query($query); $result = $stmt-&gt;fetch_all(MYSQLI_ASSOC); return $result; }else{ $stmt = self::connect()-&gt;prepare($query); $stmt-&gt;execute(); } } } </code></pre> <p>class/route.php</p> <pre><code>&lt;?php class route{ public static $routes = array(); public function set($route, $function){ self::$routes[] = $route; if($_GET['page'] == $route){ $function-&gt;__invoke(); }else{ echo 'error'; } } } </code></pre> <p>controllers/indexController.php</p> <pre><code> &lt;?php class indexController extends db{ public function getController($index){ $data = [ 'example' =&gt; 'example', 'example2' =&gt; 'example2' ]; indexModel::getModel($index, $data); } } </code></pre> <p>model/IndexModel.php</p> <pre><code>&lt;?php class indexModel extends db{ public function getModel($index, $data){ /* do something on data and index etc */ indexView::getView($index, $data); } } </code></pre> <p>view/indexView.php</p> <pre><code> &lt;?php class indexView{ public function getView($index, $data){ require_once('./template/' . $index . '.php'); } } </code></pre> <p>route.php</p> <pre><code>&lt;?php route::set('index.php', function(){ indexController::getController('index'); }); </code></pre> <p>index.php</p> <pre><code>&lt;?php require_once('route.php'); function __autoload($name){ $directories = array( './class/', './controllers/', './model/', './view/' ); foreach($directories as $dir){ if(file_exists($dir.$name.'.php')){ require_once($dir.$name.'.php'); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:19:01.780", "Id": "482669", "Score": "1", "body": "What `$param = array() ` in the db::query() for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:28:48.067", "Id": "482670", "Score": "0", "body": "oh i thought that will be received parameters but i think i should edit that to send prepared statements to db, and delete query() function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:35:58.783", "Id": "482687", "Score": "3", "body": "`template MVC`/`do something` sounds [hypothetical code](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:30:28.157", "Id": "482710", "Score": "0", "body": "I mean, it's `db.php` and `route.php`, that's how it actually would look like." } ]
[ { "body": "<p>First off, great that you're learning about the MVC design pattern. It can greatly aid you in improving your code readability and maintainability. That being said, there are ways to further improve this. Such as using a backend framework like <a href=\"https://symfony.com/\" rel=\"nofollow noreferrer\">Symfony</a>. It takes care of a lot of structuring, configuration and security related stuff so the programmer doesn't have to think about it anymore.</p>\n<p>But you're not using Symfony right now so I will make some remarks on what you did here:</p>\n<p>db.php: Don't put db credentials hardcoded in your source files. This makes it harder to change when running the application in production. It's also not the best idea security wise. You don't want to have any credentials in your version control since this gives everyone who has access to the repo full access to the whole production application. Also think about input sanitization: make sure your users can't write malicious queries that are executed on your database. <a href=\"https://stackoverflow.com/questions/129677/how-can-i-sanitize-user-input-with-php\">More about sanitization</a>.</p>\n<p>Your other classes don't have a lot of functionality so there's less to say about that but some other stuff I noticed was:</p>\n<ul>\n<li>Use CamelCase for classnames, this is a convention most people use and therefore helps other programmers understand your code.</li>\n<li>Some foldernames are both plural and singular, make them either all singular or all plural. This gives a bit more structure.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:36:23.570", "Id": "482671", "Score": "0", "body": "hello, what you mean here \"db.php: Don't put db credentials hardcoded in your source files. This makes it harder to change when running the application in production.\"\nyou mean it should get public/private $host? or other way?\n\nthanks for your post and help :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T12:47:57.683", "Id": "482689", "Score": "2", "body": "Interestingly, that in the linked post it says \"Do not try to prevent SQL injection by sanitizing input data\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T05:26:14.777", "Id": "482910", "Score": "0", "body": "https://www.php-fig.org/psr/psr-1/#:~:text=Class%20names%20MUST,%20StudlyCaps." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:11:17.427", "Id": "245742", "ParentId": "245741", "Score": "1" } } ]
{ "AcceptedAnswerId": "245742", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T08:53:32.607", "Id": "245741", "Score": "-1", "Tags": [ "php", "mvc" ], "Title": "PHP template MVC" }
245741
<p>What can I improve about this code in order to be production-ready? I'm not worried about security but about errors that could occur.</p> <p>What exceptions should I catch? I feel overwhelmed about exceptions because I feel that there are a lot of exceptions that one can consider.</p> <p>What else should I do? Should I do unit testing for this?</p> <p>The script first loads the client list from an SQL database, then takes the daily work quantity about pallet movements from a SQL database, after that it writes a .csv file with this data, and finally sends it through email.</p> <pre><code>import pyodbc import csv import smtplib import os.path from datetime import date, timedelta from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication def load_clients(): client_list = {} connection_string = f'*' query = &quot;&quot;&quot; SELECT clifor.a1_codice_clifor, anacf.ragione_soc_fiscale FROM anacf anacf, clifor clifor WHERE (clifor.a1_ditta_codice=5) AND (clifor.a1_tipo_cli1_for2=1) AND (anacf.a1_codice_anagrafica_generale=clifor.a2_anagrafica_codice) &quot;&quot;&quot; cnxn = pyodbc.connect(connection_string, autocommit=True) with cnxn: cursor = cnxn.cursor() cursor.execute(query) while True: row = cursor.fetchone() if not row: break client_list[row[0]] = row[1] return client_list def load_movements(clients): movement_list = [] connection_string = f'*' query = &quot;&quot;&quot; SELECT datadoc, cliente, SUM (@DECODE(tipodoc, 3 ,palletts)) AS inputs, SUM (@DECODE(tipodoc, 5 ,palletts)) AS outputs FROM docmagat WHERE ditta=5 AND anno=2020 AND tipodoc in (3,5) AND datadoc=SYSDATE-1 GROUP BY 1,2 &quot;&quot;&quot; cnxn = pyodbc.connect(connection_string) with cnxn: cursor = cnxn.cursor() cursor.execute(query) while True: row = cursor.fetchone() if not row: break inputs = 0 if row[2] is None else row[2] outputs = 0 if row[3] is None else row[3] movement_list.append(tuple( (clients[row[1]], inputs, outputs, inputs + outputs))) return movement_list def load_file(movements, yesterday, folder): filename = 'pallet_movements ' + yesterday + '.csv' full_path = os.path.join(folder, filename) with open(full_path, mode='w', newline='') as pallet_movements: movements_writer = csv.writer(pallet_movements, delimiter=';') movements_writer.writerow(['Day: ' + yesterday]) movements_writer.writerow(['Company', 'inputs', 'outputs', 'Total']) for movement in movements: movements_writer.writerow(movement) return filename def send_email(filename, yesterday, folder): sender = &quot;*&quot; destination = &quot;*&quot; msg = MIMEMultipart() msg['Subject'] = 'Pallet movements ' + yesterday msg['From'] = sender msg['To'] = destination message_text = 'Good morning,\n\nYou can find Pallet movements from\ day ' + yesterday + ' attached.\n\nGoodbye' msg.attach(MIMEText(message_text)) full_path = os.path.join(folder, filename) attachment = MIMEApplication(open(full_path, 'rb').read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) try: with smtplib.SMTP('*', 587) as smtpObj: smtpObj.ehlo() smtpObj.starttls() smtpObj.login(&quot;*&quot;, &quot;*&quot;) smtpObj.sendmail(sender, destination, msg.as_string()) except Exception as e: print(e) def main(): yesterday = date.today() - timedelta(days=1) yesterday = yesterday.strftime(f'%d-%m-%Y') local_folder = os.path.dirname(os.path.abspath(__file__)) clients = load_clients() movements = load_movements(clients) filename = load_file(movements, yesterday, local_folder) send_email(filename, yesterday, local_folder) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T10:10:50.200", "Id": "482672", "Score": "0", "body": "Are you absolutely sure that code works? Look `with smtplib.SMTP('*, 587) as smtpObj:` looks like it's missing an `'`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:01:10.683", "Id": "482679", "Score": "0", "body": "Yes, it works. I deleted all the private information, that's why there are some * in place. I'll correct that typo. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:09:20.070", "Id": "482682", "Score": "0", "body": "Does your company code everything in, what is it, Italian?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:15:06.720", "Id": "482683", "Score": "0", "body": "We don't code much. The last code written here was from 15 years ago. I came here a few months ago and I wanted to automate all the manual processes that I can." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:25:40.113", "Id": "482684", "Score": "0", "body": "Considering most users here won't be able to read Italian, could you tell us more about how the code works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:32:07.260", "Id": "482685", "Score": "3", "body": "I'm sorry, I'll rewrite it now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:19:53.523", "Id": "482705", "Score": "2", "body": "Welcome to Code Review escarta. Thank you for translating the code. Your question would be easier to understand and review if you gave a short overview of what it does. E.g. \"My code is a shop to buy pallets from. When you sign up in `foo` we will send you an email, through `bar`, that looks like …. Upon sending the email we add the user to the database through `baz` that adds to the table `UserTable` that has the following columns ….\"" } ]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>What can I improve about this code in order to be production-ready? I'm not worried about security but about errors that could occur.</p>\n</blockquote>\n<p>So make a list of errors that you expect could occur, and think about what should happen in each case. For example, just looking at <code>main()</code>, I can think of:</p>\n<ul>\n<li>Loading clients fails</li>\n<li>Loading movements fails</li>\n<li>Creating the movement report file fails</li>\n<li>Sending the email fails</li>\n</ul>\n<p>Is it important to know why something fails exactly? If so make it more specific. For example:</p>\n<ul>\n<li>Loading client fails:\n<ul>\n<li>Could not connect to the database</li>\n<li>Could not run the query</li>\n</ul>\n</li>\n</ul>\n<p>What should happen if any of those errors occur in production? If you know the network is flaky, you could for example retry connecting to the database a few times before giving up. But if the query fails there is most likely not much you can do.</p>\n<blockquote>\n<p>What exceptions should I catch? I feel overwhelmed about exceptions because I feel that there are a lot of exceptions that one can consider.</p>\n</blockquote>\n<p>There are many places where exceptions can be thrown, and besides exceptions there are also function that do not throw an exception but just return a value that indicates that an error occurred. The advantage of exceptions is that if you don't catch them, the program will abort instead of doing something unexpected.</p>\n<p>As the name implies, exceptions are normally used to signal that something unexpected has happened. If the system runs out of memory, or it fails to open a file that you expect to exist, there is most likely not much you can do at that point, and letting the program abort is the right thing to do. However, there are situations where you can do better than that. It is up to you to decide what exceptions would be beneficial to catch.</p>\n<p>Another nice thing about exceptions is that you do not have to catch them in the same function as the exception is generated. So you don't necessarily have to add exception handling all over the place, but you can defer it to a function higher up the call stack.</p>\n<p>The code you showed looks like it does a one-off operation, loading some data, and generating a single email based on the data. You could decide to just not handle exceptions at all, and then if any error occurred, the email would just not be sent. But you could do a bit better than that: handle exceptions from all database access and file loading, and in the exception handler send an email notifying the recipient that an error occurred and that there is no list of pallet movements available today due to an error. Alternatively, you could send a notification to a technician so they can investigate why the code failed. Handling this would look like so:</p>\n<pre><code>def main():\n try:\n yesterday = date.today() - timedelta(days=1)\n yesterday = yesterday.strftime(f'%d-%m-%Y')\n local_folder = os.path.dirname(os.path.abspath(__file__))\n clients = load_clients()\n movements = load_movements(clients)\n filename = load_file(movements, yesterday, local_folder)\n except:\n send_error_email()\n raise # Causes the program to abort anyway\n\n send_email(filename, yesterday, local_folder)\n</code></pre>\n<p>I think that's more useful than just printing the exception and exitting the program normally. For example, if your program is run as a cron job, then handling the exception in <code>send_email()</code> like you did would just hide errors.</p>\n<blockquote>\n<p>What else should I do? Should I do unit testing for this?</p>\n</blockquote>\n<p>Yes, you should test your code, regardless of whether you handle exceptions or not. Your test cases should test whether the code performs as required in all the scenarios you expect can happen. It's perfectly fine to not handle exceptions if the requirement is that your code just aborts in case of any error.</p>\n<h1>Give <code>load_file()</code> a better name</h1>\n<p>The function <code>load_file()</code> does not load a file like its name implies, but rather creates a new file. The name <code>create_file()</code> would already be better. But it is still quite generic. What kind of file does it generate? Maybe <code>create_movement_report()</code> would be even better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T00:58:59.020", "Id": "482901", "Score": "1", "body": "Logging the exception might be good--in case the error email can't be sent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T11:54:07.090", "Id": "245807", "ParentId": "245743", "Score": "2" } } ]
{ "AcceptedAnswerId": "245807", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T09:57:03.163", "Id": "245743", "Score": "3", "Tags": [ "python", "python-3.x", "error-handling", "csv" ], "Title": "Sending a CSV file for a client list from a database" }
245743
<p>Here is my vampire based text adventure game. I recently started learning Python and Googled for some good projects to practice with. I wrote all this code myself after checking out some examples on the internet.</p> <pre class="lang-py prettyprint-override"><code>import time #added to enable pause #A text based dracula survival game #possible answers answer_A = ['A', 'a'] answer_B = ['B', 'b'] answer_C = ['C', 'c'] yes = ['yes', 'Yes', 'y', 'Y'] no = ['no', 'No', 'n', 'N'] #story begins here def intro(): print('You wake up in front of a castle, you have no idea where you are or why you are here.' 'You suddenly see a colony of bats fly away.' 'You turn back and see a vampire figure appear out of nowhere. You will:') time.sleep(1) print(''' A. Ask for direction. B. Run inside the castle. C. Run to the cave.''') choice = input('&gt;&gt;&gt; ') if choice in answer_A: print('\n Well you dont ask vampires for directions. \n\nRip') elif choice in answer_B: option_castle() elif choice in answer_C: option_cave() else: print(&quot;That's not an option idiot&quot;) intro() def option_castle(): print('You ran inside the castle and see a glass front cubboard with garlic inside.You hear the Vampire coming,''You will: ') time.sleep(1) print(''' A. Take the garllic to scare the vampire. B. Hide C. Escape from backdoor.''') choice = input('&gt;&gt;&gt; ') if choice in answer_A: print('This is not a story book, what are you doing? Making salad? \n\n RIP') option_death() elif choice in answer_B: print(&quot;This is not hide n'seek \n\n RIP&quot; ) option_death() elif choice in answer_C: option_abdvilllage() else: print('Not an option idiot') option_castle() def option_cave(): print('You ran inside a dark cave, you were not sure if its a good idea or not but in there you see a shiny silver dagger.' 'Hurry bats are coming: ') time.sleep(1) print(''' A. You pick up the dagger and fight. B. You pick up the dagger and hide. C. You run.''') choice = input('&gt;&gt;&gt; ') if choice in answer_A: print('You picked the silver dagger and stood there like a fearsome warrior. The vampire attacked you but you were cunning and avoiding its attack stabbed the vampire right in its heart. Well done vampire slayer, you may live.') elif choice in answer_B: print(&quot;Cowards don't get to fight and live. \n\n RIP&quot;) option_death() elif choice in answer_C: option_abdvilllage() else: print('not an option idiot') option_cave() def option_abdvilllage(): print('You ran towards an abandoned village in the open. The bats are coming faster than before, you will: ') time.sleep(1) print(''' A. Hide B. Pick a wood to stab the vampire C. Enter the cave''') choice = input('&gt;&gt;&gt; ') if choice in answer_A: print('You hid in a hut and well it worked, you were lucky and the sun rose killing the vampire. You were a coward but a lucky one.') elif choice in answer_B: print(&quot;For real? How can a piece of wood kill an immortal blood sucking human size bat? \n\n RIP&quot;) option_death() elif choice in answer_C: option_cave() else: print('not an option idiot') option_abdvilllage() def option_death(): choice = input('Do you want to play again? Yes or No ') if choice in yes: intro() else: print('very well') play = input('Do you want to play? Y or N ') if play == 'Y'.lower(): intro() else: print('very well') </code></pre>
[]
[ { "body": "<h1>Don't ask if the user wants to play the first time</h1>\n<p>If the user started your game, then of course they want to play it, otherwise they wouldn't have started it to begin with. So don't ask and go to the intro immediately. If they started your game in error, they can always quit it by closing the window, pressing control-C or something like that.</p>\n<h1>You will overflow the stack, eventually</h1>\n<p>For every action that does not end the game, you just call another function, but you don't return from a function. This means your call stack will grow indefinitely. With the gigabytes of RAM we have in our computers nowadays, you might not notice this mistake, but on the eight-bitters of the previous century, your game would run out of memory very quickly because of this.</p>\n<p>Generally, you want to have a main loop that handles the input, and that advances the state based on your input. For example, you could write it like so:</p>\n<pre><code>def intro():\n print('You wake up...')\n ...\n choice = input('&gt;&gt;&gt; ')\n if choice in answer_A:\n print(&quot;...&quot;);\n return &quot;game_over&quot;\n elif choice in answer_B:\n return &quot;castle&quot;\n ...\n\ndef main_loop():\n state = &quot;intro&quot;\n\n while state != &quot;end&quot;:\n if state == &quot;intro&quot;:\n state = intro()\n elif state == &quot;castle&quot;:\n state = option_castle()\n ...\n elif state == &quot;game_over&quot;:\n again = input('Do you want to play again? Y or N ')\n if again in yes:\n state = &quot;intro&quot;\n\nmain_loop()\n</code></pre>\n<p>The above is just an illustration of the idea. To do it properly, you would probably use an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\"><code>enum</code></a> for the state, and possibly have a map of states to functions so you can simplify the whole loop. For example:</p>\n<pre><code>from enum import Enum\n\nclass State(Enum):\n INTRO = 1\n CASTLE = 2\n ...\n GAME_OVER = -1\n END = -2\n\ndef intro():\n ...\n\ndef option_castle():\n ...\n\ndef game_over():\n print('Game over.')\n again = input('Do you want to play again? Y or N ')\n if again in yes:\n return State.INTRO\n else\n return State.QUIT\n\nscenarios = {\n State.INTRO: intro,\n State.CASTLE: option_castle,\n ...\n State.GAME_OVER: game_over,\n}\n\ndef main_loop():\n state = State.INTRO\n\n while state != State.END:\n state = scenarios[state]()\n\nmain_loop();\n</code></pre>\n<h1>Consider not sleeping before showing possible choices</h1>\n<p>The calls to <code>time.sleep(1)</code> are not needed for the game, and just make it so the player has to wait unncessarily before being able to read the choices. I would just avoid this.</p>\n<h1>The game is quite rude</h1>\n<p>It might seem funny to you, but if I was a player, and accidentally typed in the wrong character, and got told that I was an idiot, my appreciation of the game would drop significantly. Also, being told that garlic doesn't work because that's just a story book thing is very annoying, since the whole concept of vampires comes from a story book to begin with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:58:27.347", "Id": "482725", "Score": "0", "body": "Thank you so much for your suggestions and i didn't get the `enum` properly but I'll google it. Also i'll rewrite the lame storyline in a better way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-02T05:11:18.007", "Id": "484118", "Score": "0", "body": "\"With the gigabytes of RAM we have in our computers nowadays, you might not notice this mistake,\" Python has a limit on recursion set to 1000 so this is probably more of a problem then you think." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T13:43:10.363", "Id": "245752", "ParentId": "245745", "Score": "3" } } ]
{ "AcceptedAnswerId": "245752", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:32:02.803", "Id": "245745", "Score": "6", "Tags": [ "python", "beginner", "game" ], "Title": "Vampiric text-based adventure game" }
245745
<p>(There is now a <a href="https://codereview.stackexchange.com/q/269889/64513">2nd version</a> of this code)</p> <p>Have you ever written proxy objects, instead of using a setter and a getter method? In that case, I'm interested in your opinion on the following design for a templated proxy:</p> <pre><code>#include &lt;type_traits&gt; #include &lt;utility&gt; template &lt;typename Handle, typename Getter, typename Setter&gt; class proxy { public: using value_type = decltype(std::declval&lt;Getter&gt;()(std::declval&lt;Handle&gt;()) ); operator value_type() const { return getter_(handle_); } proxy&amp; operator=(const value_type&amp; x) { setter_(handle_, x); return *this; } proxy&amp; operator=(const value_type&amp;&amp; x) { setter_(handle_, x); return *this; } proxy(Handle handle, const Getter&amp; getter, const Setter&amp; setter) : handle_(handle), getter_(getter), setter_(setter) { } protected: const Handle handle_; const Getter&amp; getter_; const Setter&amp; setter_; }; // Allows for template argument deduction during &quot;construction&quot; - before C++17 template &lt;typename Handle, typename Getter, typename Setter&gt; proxy&lt;Handle, Getter, Setter&gt; make_proxy(const Handle&amp; handle, const Getter&amp; getter, const Setter&amp; setter) { return proxy&lt;Handle, Getter, Setter&gt;(handle, getter, setter); } </code></pre> <p>Simple example of use:</p> <pre><code>int my_getter(int *x) { return *x; } void my_setter(int *x, int val ) { *x = val; } class foo { public: auto datum() { return make_proxy(&amp;x, my_getter, my_setter); } protected: int x { 123 }; }; int main() { foo my_foo; my_foo.datum() = 456; return my_foo.datum(); } </code></pre> <p><a href="https://godbolt.org/z/Mn5oYs" rel="nofollow noreferrer"><kbd>GodBolt</kbd></a></p> <p><sub>(in this example, the getter and setter aren't really necessary because the &quot;raw&quot; field exists. But think about opqaue operating-system resources, or individual bits in a bit-container etc.)</sub></p> <br> <p>Other than general comments on the design - I was also thinking about the choice of template parameters. I might be able to drop the Handle type - if I could manager to extract that information from <code>Getter</code>; or alternatively, I could <em>add</em> the value_type as a template parameter - as otherwise it could be confusing to the person seeing an instantiation to understand what type they should actually use with the proxy.</p> <p>Also, I was wondering whether I should provide comparators (seeing how this class is convertible to <code>value_type</code>'s, which we should be able to compare).</p> <p>Finally, I was also thinking of not keeping the <code>getter_</code> and <code>setter_</code> at all, and only instantiating them on use. But I'm worried this will make the class too convoluted to write and/or use.</p> <p>Note: This needs to be C++11-compatible.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:48:52.640", "Id": "482719", "Score": "2", "body": "Note to people in the Close Vote Queue, there is nothing wrong with this code." } ]
[ { "body": "<h1>It's always going to be ugly</h1>\n<p>Getters and setters are never going to be as pretty in C++ as in some other languages that natively support them. Maybe something nice will be possible in a future C++ standard, but certainly not if you are stuck with C++11.</p>\n<p>If you are going to use this to proxy member variables of a class, then the best syntax I can come up with is:</p>\n<pre><code>class foo {\n int x{123};\n static int getter(foo *self) { return self-&gt;x; }\n static void setter(foo *self, int val) { self-&gt;x = val; }\npublic:\n auto datum() { return make_proxy(this, getter, setter); }\n};\n</code></pre>\n<p>The above allows the getter and setter access to the whole class, in case it wants to update multiple variables, or if the getter returns some function of multiple member variables. But unless you can reuse getters and setters, there is really not much point to it in my opinion.</p>\n<p>The main reason is that either you have to write <code>my_foo.datum() = 456</code>, which has the added parentheses that make it not look like you are setting a regular member variable, or you have to declare <code>datum</code> like so:</p>\n<pre><code>class foo {\n ...\npublic:\n proxy&lt;foo *, decltype(getter), decltype(setter)&gt; datum{this, getter, setter};\n};\n</code></pre>\n<p>That will allow you to write <code>my_foo.datum = 456</code>.</p>\n<p>The former doesn't even work with C++11, since auto return type deduction doesn't work in that situation. You could add a trailing return type, but it will be ugly and repetetive. The latter has the overhead of storing three pointers for each proxy variable in your class.</p>\n<h1>It doesn't handle const instances</h1>\n<p>Your proxy class doesn't work if you create a <code>const</code> instance of a class that uses proxy member variables, for example:</p>\n<pre><code>const foo my_foo;\nreturn my_foo.datum();\n</code></pre>\n<p>You could probably create a <code>class const_proxy</code> that only has a getter, and which ensures <code>const</code> is used in the right places, and then overload the proxy member like so:</p>\n<pre><code>class foo {\n ...\npublic:\n auto datum() { return make_proxy(this, getter, setter); }\n auto datum() const { return make_const_proxy(this, getter); }\n};\n</code></pre>\n<p>But that adds even more noise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:24:08.673", "Id": "482727", "Score": "0", "body": "You're reviewing my example of use rather than my general proxy template. The example is just an example... indeed, it doesn't have the const variant of the proxy-returning method - but you'll note I _have_ planned for `const`-correctness in proxy itself. Now, about `make_const_proxy` - that might indeed by necessary, especially since we don't have `std::add_const()` like in C++17; but a separate const_proxy class would not be necessary - `const proxy` should do well enough. Now, as for keeping the proxy as a member variable - that costs a bunch of storage. What if I have a bliion foo's?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:32:14.517", "Id": "482729", "Score": "2", "body": "But how you use it is the most important thing! I can write code which looks and works perfectly, but if it doesn't do anything useful, what is the point? The point of a proxy template is that it makes getters and setters easier, but if you have to add several lines of code for each proxied variable just to make that happen, its usefulness is severely diminished. I tried creating a proxy class myself a while ago, but I failed to make it practical, see: https://stackoverflow.com/questions/57531691/why-is-operator-from-a-base-class-not-a-candidate-when-assigning-to-a-derived-c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:38:07.703", "Id": "482730", "Score": "1", "body": "If you come up with a version of your proxy class that also works when creating const instances of a class that uses proxies, then please create a new review for it. I did mention that keeping the proxy as a member variable costs you three pointers worth of storage, so indeed it is not very practical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:45:08.043", "Id": "482738", "Score": "1", "body": "The \"version\" is the same proxy itself. See [here](https://godbolt.org/z/T7a79z). But it's true that this makes the use a little uglier. I haven't quite managed to write a make_const_proxy() that doesn't drop constness somehow." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:07:19.490", "Id": "245757", "ParentId": "245747", "Score": "4" } }, { "body": "<p>It lacks a very important functionality - the proxy should be initializable via lambdas or closures. With current API it is impossible to do properly.</p>\n<p>For instance, consider following code:</p>\n<pre><code>double x=1;\ndouble coef=2.;\nauto pr = make_proxy(&amp;x,\n [coef](double*x){return *x*coef;}, \n [coef](double*x, double nx){*x = nx/coef;});\npr = 8.;\n</code></pre>\n<p>Now, this a nice and simple piece of code where proxy's setter/getter multiply/divide the value by coef. Only issue is that this code is UB. You see these lambdas instances get destroyed past <code>make_proxy</code> because <code>proxy</code> stores only const references which will become dangling and their use turns into UB.</p>\n<p>Note: the Handle variable only incoveniences writing generation of the proxy. Without it, it would be easier to user to write lambdas. If you worry about functions/method then you can simply use <code>std::bind</code> for wrapping those up.</p>\n<p>Technical issue:</p>\n<pre><code> proxy&amp; operator=(const value_type&amp;&amp; x) { setter_(handle_, x); return *this; }\n</code></pre>\n<p>It is not a proper move-assignment implementation. I just write a proper one:</p>\n<pre><code> proxy&amp; operator=(value_type&amp;&amp; x) { setter_(handle_, std::move(x)); return *this;}\n</code></pre>\n<p>(Also frequently these ought to be <code>noexcept</code> - but uncertain whether it suitable for the current case). Also there is little point in writing move+copy assignment operator unless you define them for the current class. Both of them can be implememted via a single definition as:</p>\n<pre><code> proxy&amp; operator = (value_type x) { setter_(handle_, std::move(x)); return *this;}\n</code></pre>\n<p>Some may argue that this is slower but compiler should be able to optimize out the inefficiencies.</p>\n<p>Also you should consider the case where getter returns a const reference instead of the value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:04:50.490", "Id": "482774", "Score": "0", "body": "Thanks for the suggestions. 1. \"the proxy should be initializable via lambdas / closures.\" <- Can you elaborate on this point? 2. I wasn't thinking about `noexcept` because in my mind this always gets inlined, but I probably should. 3. I'm not sure about your move+copy assignment, since `value_type` will generally not be an rvalue reference. And the compiler probably won't be able to optimize this away if there are side-effects involved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:12:44.313", "Id": "482775", "Score": "0", "body": "@einpoklum 1. instead of `getter/setter` functions it is more reasonable to assume that user will make some simple lambdas. E.g., `int x; auto getter =[&x](){return x;}; auto setter = [&x](int x2){x=x2;};` and no need for handle. Now how to make proxy from these?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:15:36.333", "Id": "482776", "Score": "0", "body": "The `make_proxy()` function should handle that, I think... Also, it's not that likely lambdas will be used this way, since it's mostly class authors who will need this proxy, and they can just use plain vanilla functions/methods within the actual source file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:19:00.670", "Id": "482777", "Score": "0", "body": "@einpoklum 2. Hmm... normally you don't want to have side effects in copy-consructor. If a class has complex construction with side effects then presumably it is some function module and not data storage in which normally one simply stores them in some smart pointer and never moves/copies/assigns it. So I find it strange that somebody would want to have getter/setter proxy for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:21:10.497", "Id": "482778", "Score": "0", "body": "R (2.) : Granted, but this is a generic proxy, so I want to minimize my assumptions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:21:31.500", "Id": "482779", "Score": "0", "body": "@einpoklum that's the point that `make_proxy()` cannot handle it as is. Also if you instantiate the proxy from function/method then they will function pointers which are hard to optimize for compilers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:36:35.493", "Id": "482782", "Score": "0", "body": "@einpoklum (R. 2) indeed it is preferable for the general case to implement both assignments. I simply wanted to provide general advise suitable for most cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:16:48.917", "Id": "482796", "Score": "0", "body": "@einpoklum I wasn't clear enough about issues of using lambdas and the API so I wrote an example and updated the answer." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T07:24:56.137", "Id": "245798", "ParentId": "245747", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T12:20:10.567", "Id": "245747", "Score": "6", "Tags": [ "c++", "c++11", "design-patterns", "template", "proxy" ], "Title": "A proxy class as a generic replacement for getters and setters" }
245747
<p>I need to speed up a circular buffer that has space and time requirements.</p> <p>Each cell in the circular buffer represents a list of N elements to be sent. The shipment takes place if the list reaches N elements, or if the elapsed time exceeds X ms.</p> <p>At the moment I have found this solution, but I am quite sure it is not the best possible to achieve my goal. I would like to understand if there are improvements for architecture.</p> <pre><code>public class RingBuffer&lt;T&gt; : IDisposable { protected class TimerArray { private Timer _timer; private Int32 _index; private RingBuffer&lt;T&gt; _ring; public TimerArray(RingBuffer&lt;T&gt; ring, Int32 index) { _index = index; _ring = ring; _timer = new Timer(t =&gt; { ring.Send(_index); }, null, ring.TimerPeriod, ring.TimerPeriod); } public Boolean TimerReset() { return _timer.Change(_ring.TimerPeriod, _ring.TimerPeriod); } } protected Object _locker = new Object(); protected ConcurrentQueue&lt;T&gt;[] _buffers; protected TimerArray[] _timer; protected Int64 current = 0; public Int32 RingDimension { get; set; } public Int32 SendSize { get; set; } public Int32 TimerPeriod { get; set; } public ISender Sender { get; set; } public Int64 BufferSize { get; set; } public RingBuffer(ISender sender, Int32 size, Int32 msTimer) { RingDimension = 10; Init(sender, size, msTimer); } public RingBuffer(ISender sender, Int32 dimension, Int32 size, Int32 msTimer) { RingDimension = dimension; Init(sender, size, msTimer); } protected void Init(ISender sender, Int32 size, Int32 msTimer) { _buffers = new ConcurrentQueue&lt;T&gt;[RingDimension]; Sender = sender; SendSize = size == 0 ? -1 : size; TimerPeriod = msTimer; for (int i = 0; i &lt; RingDimension; i++) _buffers[i] = new ConcurrentQueue&lt;T&gt;(); if (TimerPeriod &gt; 0) { _timer = new TimerArray[RingDimension]; for (int i = 0; i &lt; RingDimension; i++) _timer[i] = new TimerArray(this, i); } } public void Enqueue(T item) { lock (_locker) { if (!Object.ReferenceEquals(item, null)) _buffers[current].Enqueue(item); } if (_buffers[current].Count &gt;= SendSize) { lock (_locker) { if (_buffers[current].Count &gt;= SendSize) { var previous = Interlocked.Exchange(ref current, (current + 1) % RingDimension); if (TimerPeriod &gt; 0) _timer[previous].TimerReset(); BufferSize += Sender.Enqueue(_buffers[previous].ToList()); _buffers[previous] = new ConcurrentQueue&lt;T&gt;(); } } } } protected void Send(Int64 index) { if (_buffers[index].Count &gt; 0) { lock (_locker) { if (_buffers[index].Count &gt; 0) { BufferSize += Sender.Enqueue(_buffers[index].ToList()); _buffers[index] = new ConcurrentQueue&lt;T&gt;(); } } } } public virtual void Dispose() { } } </code></pre> <p>Enqueue method is called by program anytime that a message is ready, check the list dimension and send it when list is full.</p> <p>Send method is called by a Timer array that set a boundry limit for message latency.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T12:40:42.213", "Id": "245748", "Score": "2", "Tags": [ "performance" ], "Title": "C# Performance in a CircularBuffer architecture in size and time" }
245748
<p>This has been my approach for &quot;simplifying&quot; MongoDB aggregation queries in a pythonic syntax - was my intent, at the very least:</p> <pre><code>from datetime import datetime, timedelta class MatchStage(list): def _get_day_range(self): current_time = datetime.now() return (current_time - timedelta(days=1)), current_time def diferent(self, **kwargs): for field, value in kwargs.items(): self.append({field: {&quot;$ne&quot;: value}}) def equals(self, **kwargs): for field, value in kwargs.items(): self.append({field: {&quot;$eq&quot;: value}}) def set_interval(self, field, data): self.starttime, self.endtime = map(datetime.fromtimestamp, ( int(data[&quot;starttime&quot;]), int(data[&quot;endtime&quot;]) )) \ if {&quot;starttime&quot;, &quot;endtime&quot;} &lt;= data.keys() else self._get_day_range() self.append({ field: { &quot;$gte&quot;: self.starttime, &quot;$lt&quot;: self.endtime } }) def set_devices(self, devices): self.devices = devices self.append({&quot;device&quot;: {&quot;$in&quot;: [device.id for device in devices]}}) class SortStage(dict): @staticmethod def ascending_order(*fields): return {&quot;$sort&quot;: {field: 1 for field in fields} } @staticmethod def descending_order(*fields): return {&quot;$sort&quot;: {field: -1 for field in fields} } class ReRootStage(dict): @staticmethod def reset_root(*args): return {&quot;$replaceRoot&quot;: {&quot;newRoot&quot;: {&quot;$mergeObjects&quot;: [{key: '$' + key for key in args}, &quot;$_id&quot;]}}} class GroupStage(dict): def sum_metrics(self, **kwargs): self.update({k: {&quot;$sum&quot;: v if isinstance(v, int) else {&quot;$toLong&quot;: v if v.startswith('$') else '$' + v}} for k, v in kwargs.items()}) def group_fields(self, *fields): self[&quot;_id&quot;].update({field: '$' + field for field in fields}) def _nest_field(self, key, field): self[key] = {&quot;$push&quot;: field} def nest_field(self, key, field): if not field.startswith('$'): field = '$' + field self._nest_field(key, field) def nest_fields(self, *fields, key, **kfields): if not fields and not kfields: raise Exception(&quot;No field specified&quot;) self._nest_field(key, {field: '$' + field for field in fields} or {field: '$' + value for field, value in kfields.items()}) class BasePipeline(list): _match = MatchStage _group = GroupStage _sort = SortStage _reroot = ReRootStage def __init__(self, data, devices): self._set_match().set_interval(&quot;time&quot;, data) if &quot;devid&quot; in data: devices = devices.filter(id__in=data[&quot;devid&quot;].split(',')) assert devices.exists(), &quot;Device not found&quot; self.match.set_devices(devices) def _set_group(self): self.group = self._group() self.append({&quot;$group&quot;: self.group}) return self.group def _set_match(self): self.match = self._match() self.append({&quot;$match&quot;: {&quot;$and&quot;: self.match}}) return self.match def set_simple_group(self, field): self._set_group().update({&quot;_id&quot;: field if field.startswith('$') else '$' + field}) self.extend([{&quot;$addFields&quot;:{&quot;id&quot;: &quot;$_id&quot;}}, {&quot;$project&quot;: {&quot;_id&quot;: 0}}]) def set_composite_group(self, *fields, **kfields): if not fields and not kfields: raise Exception(&quot;No fields specified&quot;) self._set_group().update({&quot;_id&quot;: {field: '$' + field for field in fields} or {field: (value if not isinstance(value, str) or value.startswith('$') else '$' + value) for field, value in kfields.items()}}) def sort_documents(self, *fields, descending=False): self.append(self._sort.descending_order(*fields) if descending else self._sort.ascending_order(*fields)) class WebFilterBlockedPipeline(BasePipeline): def aggregate_root(self, *args): self.append(self._reroot.reset_root(*args)) def aggregate_data(self, **kfields): self.group.sum_metrics(**kfields) self.aggregate_root(*kfields) @classmethod def create(cls, data, devices): pipeline = cls(data, devices) pipeline.match.equals(action=&quot;blocked&quot;) pipeline.set_composite_group(&quot;url&quot;, &quot;source_ip&quot;, &quot;profile&quot;) pipeline.aggregate_data(count=1) pipeline.sort_documents(&quot;count&quot;, descending=True) pipeline.set_simple_group(field=&quot;url&quot;) pipeline.group.sum_metrics(count=&quot;count&quot;) pipeline.group.nest_field(&quot;source_ip&quot;, &quot;profile&quot;, &quot;count&quot;, key=&quot;users&quot;) pipeline.sort_documents(&quot;count&quot;, descending=True) return pipeline </code></pre> <p>Example output of <code>WebFilterBlockedPipeline.create()</code> in JSON-format:</p> <pre><code>[{ &quot;$match&quot;: { &quot;$and&quot;: [{ &quot;time&quot;: { &quot;$gte&quot;: &quot;2020-07-15T16:04:19&quot;, &quot;$lt&quot;: &quot;2020-07-16T16:04:19&quot; } }, { &quot;device&quot;: { &quot;$in&quot;: [&quot;FG100ETK18035573&quot;] } }, { &quot;action&quot;: { &quot;$eq&quot;: &quot;blocked&quot; } }] } }, { &quot;$group&quot;: { &quot;_id&quot;: { &quot;url&quot;: &quot;$url&quot;, &quot;source_ip&quot;: &quot;$source_ip&quot;, &quot;profile&quot;: &quot;$profile&quot; }, &quot;count&quot;: { &quot;$sum&quot;: 1 } } }, { &quot;$replaceRoot&quot;: { &quot;newRoot&quot;: { &quot;$mergeObjects&quot;: [{ &quot;count&quot;: &quot;$count&quot; }, &quot;$_id&quot;] } } }, { &quot;$sort&quot;: { &quot;count&quot;: -1 } }, { &quot;$group&quot;: { &quot;_id&quot;: &quot;$url&quot;, &quot;count&quot;: { &quot;$sum&quot;: { &quot;$toLong&quot;: &quot;$count&quot; } }, &quot;users&quot;: { &quot;$push&quot;: { &quot;source_ip&quot;: &quot;$source_ip&quot;, &quot;profile&quot;: &quot;$profile&quot;, &quot;count&quot;: &quot;$count&quot; } } } }, { &quot;$addFields&quot;: { &quot;id&quot;: &quot;$_id&quot; } }, { &quot;$project&quot;: { &quot;_id&quot;: 0 } }, { &quot;$sort&quot;: { &quot;count&quot;: -1 } }] </code></pre> <p>I'd like to ask if this is an acceptable implementation and, if not, if I should just scratch it completely, follow another design pattern or any constructive criticism.</p>
[]
[ { "body": "<h2>Breathe!</h2>\n<p>Make use of line spacing to make the code easier for humans to read. Using a formatter on the code expands it from 100 lines to nearly 150. It should be even longer, there are multiple lines which are far too dense to read in one go. Avoid leaving out the new line in code like <code>if not field.startswith('$'): field = '$' + field</code> or <code>if not fields and not kfields: raise Exception(&quot;No field specified&quot;)</code>.</p>\n<hr />\n<pre><code>self.starttime, self.endtime = map(datetime.fromtimestamp, (int(data[&quot;starttime&quot;]), int(data[&quot;endtime&quot;]))) \\\n if {&quot;starttime&quot;, &quot;endtime&quot;} &lt;= data.keys() else self._get_day_range()\n</code></pre>\n<p>This line is way too packed. I can see how you would get to it, but it needs to be split back up.</p>\n<p>Mapping over two values seems a bit overkill. Unless there will be more timestamps I would stick with the simpler code.</p>\n<p>Putting the desired keys into a set and using subset (implicitly converting the dictionary keys to a set) is a nice trick. However, it is not a very common pattern, and a quick benchmark says it has worse performance than the more naive <code>&quot;starttime&quot; in data and &quot;endtime&quot; in data</code>.</p>\n<p>The simple benchmark in Ipython (with small dictionaries)</p>\n<pre><code>def f(data): \n return {&quot;starttime&quot;, &quot;endtime&quot;} &lt;= data.keys()\n\ndef g(data): \n return &quot;starttime&quot; in data and &quot;endtime&quot; in data\n\ndata1 = {&quot;starttime&quot;: 50, &quot;endtime&quot;: 100} \ndata2 = {&quot;starttime&quot;: 50, &quot;end&quot;: 100} \ndata3 = {&quot;endtime&quot;: 100, &quot;sus&quot;: 50} \ndata4 = {&quot;start&quot;: 50, &quot;end&quot;: 50} \ndata5 = {}\n\n%timeit f(data1)\n%timeit g(data1)\n%timeit f(data2)\n%timeit g(data2)\n%timeit f(data3)\n%timeit g(data3)\n%timeit f(data4)\n%timeit g(data4)\n%timeit f(data5)\n%timeit g(data5)\n</code></pre>\n<p>highlights a clear 3 to 4x win for the simple check.</p>\n<p><a href=\"https://i.stack.imgur.com/md6dl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/md6dl.png\" alt=\"table of benchmark results for the two potential implementations of 'check multiple keys are in a dictionary'\" /></a></p>\n<p>I would prefer code more in line with</p>\n<pre><code>def set_interval(self, field, data):\n if &quot;starttime&quot; in data and &quot;endtime&quot; in data:\n self.starttime = datetime.fromtimestamp(int(data[&quot;starttime&quot;]))\n self.endtime = datetime.fromtimestamp(int(data[&quot;endtime&quot;]))\n else:\n self.starttime, self.endtime = self._get_day_range()\n\n self.append({field: {&quot;$gte&quot;: self.starttime, &quot;$lt&quot;: self.endtime}})\n</code></pre>\n<hr />\n<pre><code>def sum_metrics(self, **kwargs):\n self.update({k: {&quot;$sum&quot;: v if isinstance(v, int) else {&quot;$toLong&quot;: v if v.startswith('$') else '$' + v}} for k, v in kwargs.items()})\n</code></pre>\n<p>This is another place with too much on one line.</p>\n<p>You have a repeated pattern of prepending a <code>'$'</code> to a string if it doesn't have one already. I would make a little helper function to capture this logic, and question any code which doesn't use it. The other logic in the dictionary comprehension could also use a helper function.</p>\n<pre><code>def dollar(v):\n &quot;&quot;&quot;Prepend a dollar sign to indicate this is a XXX.&quot;&quot;&quot;\n if v.startswith(&quot;$&quot;):\n return v\n return &quot;$&quot; + v\n\ndef sum_metrics(self, **kwargs):\n def encode_metric(v):\n if isinstance(v, int):\n return v\n\n return {&quot;$toLong&quot;: dollar(v)}\n\n metrics = {k: {&quot;$sum&quot;: encode_metric(v)} for k, v in kwargs.items()}\n self.update(metrics)\n</code></pre>\n<hr />\n<pre><code>def nest_fields(self, *fields, key, **kfields):\n if not fields and not kfields:\n raise Exception(&quot;No field specified&quot;)\n self._nest_field(key, {field: '$' + field for field in fields} or {field: '$' + value for field, value in kfields.items()})\n</code></pre>\n<p>Using a broad/generic Exception is a bad habit, it might only rarely be a problem, but when it is a problem it is painful to debug. Consider a more specific exception like ValueError or a custom exception.</p>\n<pre><code>class EmptyFieldsError(ValueError):\n pass\n</code></pre>\n<p>There are two branches in this code (after the initial check). Is that obvious from the line presented? If you flip the conditions to be positive you can make the logic a lot easier to follow at a glance.</p>\n<p>I would have expected the parameter order to be <code>nest_fields(self, key, *fields, **kfields)</code> since then the key is first, followed by a list of parameters, rather than the key looking like the last parameter in a list of them.</p>\n<pre><code>def nest_fields(self, *fields, key, **kfields):\n nested_fields = None\n if fields:\n nested_fields = {field: dollar(field) for field in fields}\n elif kfields:\n nested_fields = {\n field: dollar(value)\n for field, value in kfields.items()\n }\n\n if nested_fields is None:\n raise EmptyFieldsError(&quot;No field specified&quot;)\n\n self._nest_field(key, nested_fields)\n</code></pre>\n<hr />\n<pre><code>def sort_documents(self, *fields, descending=False):\n self.append(self._sort.descending_order(*fields) if descending else self._sort.ascending_order(*fields))\n</code></pre>\n<p>This is a difficult API to read. Why not copy Python's <code>sorted</code> and give <code>_sort</code> a <code>reverse</code> positional arg?</p>\n<pre><code>class SortStage(dict):\n @staticmethod\n def order(*fields, reverse=False):\n return {&quot;$sort&quot;: {field: -1 if reverse else 1 for field in fields}}\n\ndef sort_documents(self, *fields, descending=False):\n sorted_documents = self._sort.order(*fields, reverse=descending)\n self.append(sorted_documents)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T18:17:18.237", "Id": "482869", "Score": "0", "body": "Thank you sooo much for the in-depth and thoughtful answer! I was expecting a lot of issues would be pointed out - as, admittedly, I am still very much a newbie at object oriented programming -, but this really lifts a huge weight off my chest and helps stir a better direction in my thinking. Will be working on the improvements, agreed 100% with all the points you raised - specially enjoyed the suggestion for the sorting part! :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:56:06.503", "Id": "245825", "ParentId": "245749", "Score": "2" } } ]
{ "AcceptedAnswerId": "245825", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T13:11:42.403", "Id": "245749", "Score": "3", "Tags": [ "python", "object-oriented", "design-patterns", "django", "mongodb" ], "Title": "Python REST API and Mongo - Aggregation Pipeline/Stage classes" }
245749
<p>I have written this Sieve of Eratosthenes. This is a bit of software that will find all of the prime numbers between 2 and n, where n is a user-defined value.</p> <p>The code does seem quite bloated and any help at making it more elegant would be great. I know that I am not very good at list comprehensions and if it is possible to utilise them more in this situation I would love to know how.</p> <pre><code>def sieve_of_eratosthenes(n): &quot;&quot;&quot; Create a Sieve of Eratosthenes to find all of the prime numbers between 2 and n &quot;&quot;&quot; n += 1 num_list = [] [num_list.append(i) for i in range(2, n)] test = 0 while test &lt; len(num_list): for i, x in enumerate(num_list): if num_list[i] % num_list[test] == 0: if num_list[i] != num_list[test]: del num_list[i] test += 1 return num_list </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T13:50:50.750", "Id": "482698", "Score": "5", "body": "That is *not* the Sieve of Eratosthenes, see e.g. my remarks here: https://codereview.stackexchange.com/a/194762. The Sieve of Eratosthenes algorithms computes multiples, not remainders." } ]
[ { "body": "<p>Agreed, this is not the Sieve of Eratosthenes. This is trial division by primes. (As long as you're doing trial division, you can do it slightly better, and only test up to the square root of the number.)</p>\n<p>Replace the while loop, making it clearer and more pythonic: <code>for test in num_list:</code></p>\n<p>It is <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">inefficient to delete</a> from the middle of a list in python, which takes O(n) time.</p>\n<p>It is generally unsafe, and will give wrong results to delete from an collection WHILE iterating through it. In this case it seems to work, but be careful. I would instead keep a binary flag for each number, with whether we've found a factor already or not (array of True/False).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T04:11:52.730", "Id": "251580", "ParentId": "245751", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T13:24:29.990", "Id": "245751", "Score": "2", "Tags": [ "python", "python-3.x", "sieve-of-eratosthenes" ], "Title": "A Sieve of Eratosthenes" }
245751
<p>With a reference implementation for <a href="https://www.python.org/dev/peps/pep-0622" rel="nofollow noreferrer">PEP 622</a> now available in a Jupyter <a href="https://mybinder.org/v2/gh/gvanrossum/patma/master?urlpath=lab/tree/playground-622.ipynb" rel="nofollow noreferrer">playground</a>, I decided to copy over my favourite <a href="https://doc.rust-lang.org/std/option/" rel="nofollow noreferrer">feature of Rust</a> in full to Python.<br /> <strong>Note</strong>: this won't be released until Python 3.10 but there is a <a href="https://www.python.org/dev/peps/pep-0622/#reference-implementation" rel="nofollow noreferrer">reference implementation available</a>.</p> <p>Given that I do a lot of interacting with JSON through the web, having a somewhat safe but hacky solution using <code>Some</code> is helpful. And so I've diverged from Rust's Some in that you can get items from the underlying datatype by indexing or through attribute lookup.</p> <p>This is useful if I just want the first phone number from the user.</p> <pre class="lang-py prettyprint-override"><code>match user.phones[0]: case Some(phone): print(f&quot;No : {phone}&quot;) case _: print(&quot;No phone number provided&quot;) </code></pre> <p>To allow for this interface I've built a <code>Null</code> class that returns <code>Null</code> through indexing or attribute lookup. This is only needed if you're using these additional interfaces, and so <code>None</code> can be used otherwise.</p> <p><code>maybe.py</code></p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from typing import Any, Generic, Type, TypeVar, Union, cast __all__ = [ &quot;NSome&quot;, &quot;Null&quot;, &quot;Some&quot;, ] T = TypeVar(&quot;T&quot;) class _Null(type): def __getattr__(self, key: Any) -&gt; Type[Null]: return Null def __getitem__(self, index: Any) -&gt; Type[Null]: return Null def __repr__(self) -&gt; str: return f&quot;Null&quot; class Null(metaclass=_Null): pass class Some(Generic[T]): __slots__ = __match_args__ = (&quot;_value&quot;,) _value: T def __init__(self, value: T) -&gt; None: self._value = value def __repr__(self) -&gt; str: return f&quot;Some({self._value})&quot; def __getattr__(self, key: Any) -&gt; Union[Type[Null], Some[Any]]: try: return Some(getattr(self._value, key)) except AttributeError: return Null def __getitem__(self, index: Any) -&gt; Union[Type[Null], Some[Any]]: try: return Some(cast(Any, self._value)[index]) except IndexError: return Null NSome = Union[None, Type[Null], Some[T]] </code></pre> <p>Usage takes advantage of <a href="https://www.python.org/dev/peps/pep-0622" rel="nofollow noreferrer">PEP 622</a> allowing for somewhat long but very customizable usage.</p> <pre class="lang-py prettyprint-override"><code>import collections import math from maybe import NSome, Null, Some def divide(numerator: int, denominator: int) -&gt; NSome[float]: if denominator == 0: return None else: return Some(numerator / denominator) def display(value: NSome[float]) -&gt; None: match value: case Some(x): print(f&quot;Result: {x}&quot;) case _: print(&quot;Cannot divide by zero&quot;) User = collections.namedtuple(&quot;User&quot;, &quot;name age phones&quot;) def display_user(user: NSome[User]) -&gt; None: match user.name: case Some(name): print(f&quot;Name: {name}&quot;) case _: print(&quot;No name provided&quot;) match user.age: case Some(age): print(f&quot;Age : {age}&quot;) case _: print(&quot;No age provided&quot;) match user.phones[0]: case Some(phone): print(f&quot;No : {phone}&quot;) case _: print(&quot;No phone number provided&quot;) def main() -&gt; None: display(divide(2, 3)) display(divide(2, 0)) display_user(Some(User(&quot;name&quot;, 123, [&quot;123456789&quot;]))) display_user(Some(User(&quot;name&quot;, 123, []))) display_user(Null) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>This outputs the following in the <a href="https://mybinder.org/v2/gh/gvanrossum/patma/master?urlpath=lab/tree/playground-622.ipynb" rel="nofollow noreferrer">playground</a>.</p> <pre class="lang-none prettyprint-override"><code>Result: 0.6666666666666666 Cannot divide by zero Name: name Age : 123 No : 123456789 Name: name Age : 123 No phone number provided No name provided No age provided No phone number provided </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:08:14.730", "Id": "245753", "Score": "2", "Tags": [ "python", "python-3.x", "object-oriented", "optional" ], "Title": "Maybe with a structural pattern matching interface" }
245753
<p>I am a newbie in stack exchange code review. I just wrote a C function where the function checks if the given string is numeric or not. What do you think about my way of doing this? And could this be done in other ways?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; bool is_numeric(const char* str) { while (isspace(*str)) str++; if (*str == '-' || *str == '+') str++; while (*str) { if (!isdigit(*str) &amp;&amp; !isspace(*str)) return false; str++; } return true; } int main(int argc, char** argv) { printf(&quot;%s\n&quot;, is_numeric(&quot;123436&quot;) ? &quot;true&quot; : &quot;false&quot;); // should be true printf(&quot;%s\n&quot;, is_numeric(&quot;123.436&quot;) ? &quot;true&quot; : &quot;false&quot;); // should be false printf(&quot;%s\n&quot;, is_numeric(&quot; 567&quot;) ? &quot;true&quot; : &quot;false&quot;); // should be true printf(&quot;%s\n&quot;, is_numeric(&quot;235 &quot;) ? &quot;true&quot; : &quot;false&quot;); // should be true printf(&quot;%s\n&quot;, is_numeric(&quot;794,347&quot;) ? &quot;true&quot; : &quot;false&quot;); // should be false printf(&quot;%s\n&quot;, is_numeric(&quot;hello&quot;) ? &quot;true&quot; : &quot;false&quot;); // should be false printf(&quot;%s\n&quot;, is_numeric(&quot;-3423&quot;) ? &quot;true&quot; : &quot;false&quot;); // should be true } </code></pre> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:24:31.933", "Id": "482728", "Score": "1", "body": "Consider changing the return type to `bool` (defined in stdbool as of C99)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:52:34.407", "Id": "482733", "Score": "0", "body": "@elyashiv that's a good idea. thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T19:44:03.883", "Id": "482752", "Score": "1", "body": "If it is performance critical code, calling `isdigit` and `isspace` is not a good idea. \n\nThey can be done without introducing the function overhead in a single line by comparing characters directly.\n\n`if ((*str >= '0' && *str <= '9') || *str == ' ')`" } ]
[ { "body": "<p>regarding:</p>\n<pre><code>if (!isdigit(*str) &amp;&amp; !isspace(*str))\n</code></pre>\n<p>the <code>isdigit()</code> handles 0...9, so catches if any of the passed in char array is not numeric.</p>\n<p>The <code>&amp;&amp; !isspace(*str))</code> has nothing to do with numeric values</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:55:07.387", "Id": "482734", "Score": "0", "body": "I was thinking about the trailing spaces, that is why I did that. But you are right, this is going to give the wrong result if the input is \"4545 5657\" which I think it shouldn't." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:55:16.227", "Id": "245756", "ParentId": "245754", "Score": "3" } }, { "body": "<p><strong>Bug</strong>: <code>is_numeric(&quot;&quot;)</code> returns true.</p>\n<p><strong>Bug</strong>: <code>is...(negative_values)</code> is UB. (Aside from <code>is...(EOF)</code>). Possible when <code>*str &lt; 0</code>.</p>\n<p><strong>Bugs</strong>: as reported by <a href=\"https://codereview.stackexchange.com/a/245756/29485\">user3629249</a></p>\n<hr />\n<ul>\n<li><p>Consider allowing hex such as <code>&quot;0xAbC&quot;</code>.</p>\n</li>\n<li><p>Standard library <em>string</em> functions operate as if <code>char</code> is <em>unsigned</em>, even if <code>char</code> is <em>signed</em>. Recommend to do the same here.</p>\n</li>\n</ul>\n<blockquote>\n<p>What do you think about my way of doing this?</p>\n</blockquote>\n<p>I like the idea of allowing of trailing white-space when leading white-space allowed.</p>\n<hr />\n<pre><code>#include &lt;stdbool.h&gt;\n#include &lt;ctype.h&gt; // missing in OP code.\n\nbool is_numeric_integer(const char *str) {\n const unsigned char *ustr = (const unsigned char *) str;\n while (isspace(*ustr)) {\n ustr++;\n }\n \n if (*ustr == '-' || *ustr == '+') {\n ustr++;\n }\n\n const unsigned char *begin = ustr;\n while (isdigit(*ustr)) {\n ustr++;\n }\n if (begin == ustr) {\n return false; // no digits.\n }\n\n // If you want to allow trailing white-space\n while (isspace(*ustr)) {\n ustr++;\n }\n\n return *ustr == '\\0'; // fail with trailing junk\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T01:32:43.007", "Id": "245781", "ParentId": "245754", "Score": "1" } } ]
{ "AcceptedAnswerId": "245781", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:40:03.840", "Id": "245754", "Score": "4", "Tags": [ "c" ], "Title": "Checking String with is_numeric in C" }
245754
<p>At our office there is this piece of code (the original author isn't employed anymore, so I can't ask him).</p> <p>Does anybody have an idea, what he did there? Is there any advantage of using this struct <code>OrderDirection</code> instead directly the enum <code>Direction</code>?</p> <p>(for me, this is interesting and I just wanted to know why.)</p> <pre><code>public struct OrderDirection { private enum Direction { Ascending = 0, Descending = 1 } private OrderDirection(Direction direction) { _direction = direction; } private readonly Direction _direction; public override string ToString() { switch(_direction) { case Direction.Ascending: return &quot;asc&quot;; case Direction.Descending: return &quot;desc&quot;; default: throw new NotImplementedException(nameof(_direction)); } } public static OrderDirection Ascending = new OrderDirection(Direction.Ascending); public static OrderDirection Descending = new OrderDirection(Direction.Descending); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:57:55.337", "Id": "482724", "Score": "3", "body": "First, it looks like a decently object-oriented (specifically, polymorphism) approach to letting the `ToString()` method do the real work of representing what the value is. You'd certainly need to find out where it's being used to get that answer, but that's my guess looking at it. Second, mark those `public static` values as `readonly` - don't need some random code changing what is assigned to `Ascending` or `Descending`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T15:02:51.137", "Id": "482726", "Score": "0", "body": "@JesseC.Slicer so (besides the missing `readonly`) this actually is good code? haha, sorry never seen someone before doing this. He uses it to build sql-queries with stringbuilder and things.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:15:10.910", "Id": "482736", "Score": "0", "body": "I see no need for the `enum` when a simple `bool` would suffice. The original programmer kept all other details hidden that all you should care about is using the static instances, and both of them can be easily be created without the enum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:38:33.357", "Id": "482737", "Score": "2", "body": "@MatthiasBurger It models the business domain very well, even if it is a little over the top for something this small. I'm not really a fan of the `NotImplementedException`. That shouldn't be necessary (nor the `default` label) because all enum values are covered in the switch labels. If you added a different enum value called \"Unknown\" with the zero value, I could see it. But as-is, no." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:45:23.897", "Id": "482739", "Score": "2", "body": "@MatthiasBurger on the other hand, `ToString()` should never throw exceptions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:40:15.330", "Id": "482863", "Score": "0", "body": "In general I'd put that check in the constructor, not `ToString()` -- though in this case it shouldn't be needed, not because the two cases are covered by the `switch`, but because the constructor is inaccessible to anyone but this struct where we can prove that it'll only ever be called with those two enum values. Otherwise a caller could create a `new OrderDirection((Direction)123)`. In any case, you can change the `default` block to an `Debug.Assert(true)`: it should be _impossible_ for that branch to be reached in the struct as provided." } ]
[ { "body": "<p>In my opinion nothing indicate the use of <code>enum</code>.</p>\n<p>According to my understanding your object provides the following functionalities from consumer perspective:</p>\n<ul>\n<li>Provide two factory methods one for <strong>Ascending</strong> and another for <strong>Descending</strong></li>\n<li>Provide custom string representation (abbreviation) for these</li>\n</ul>\n<p>From the public interface point of view the following implementation is equivalent with yours</p>\n<pre><code>public struct OrderDirection \n{\n private readonly string _direction;\n private OrderDirection(string direction)\n {\n _direction = direction;\n }\n \n public override string ToString() =&gt; _direction;\n \n public static OrderDirection Ascending = new OrderDirection(&quot;asc&quot;);\n public static OrderDirection Descending = new OrderDirection(&quot;desc&quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T08:56:57.583", "Id": "245800", "ParentId": "245755", "Score": "3" } }, { "body": "<p>as OOP as is, I think this would avoid unneeded castings, and it gives you more managed approach to handle <code>enum</code> than using <code>enum</code> directly.</p>\n<p>If <code>enum</code> was used directly, it would be possible to cast it to different type than a string, and it will make your hands tight when it comes to handle exceptions. so using <code>struct</code> with an internal <code>enum</code> would force typing it to only accept and output specified types, which avoid unnecessary exceptions and give you more OOP options to work with.</p>\n<p>This is also a security approach where it adds restrictions on the input-output. In this case, avoiding <code>SQL Injections</code>.</p>\n<p>Obviously it can be done in different approaches, however, this implementation would avoid some of the human-errors (like misspelling), and overriding. It would also add more readability and maintainability to the code and avoiding redundancy with less code possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T10:12:04.690", "Id": "245861", "ParentId": "245755", "Score": "1" } } ]
{ "AcceptedAnswerId": "245800", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T14:49:05.253", "Id": "245755", "Score": "2", "Tags": [ "c#", "enum" ], "Title": "Use case of nesting an enum into a struct" }
245755
<p>I have a function :</p> <pre><code>function __throwError(func) { if (func.length === 1) { function passNumber() { func(0); } function passString() { func(&quot;item&quot;); } function passEmptyArray() { func([]); } function passUndefinedOrNull() { func(undefined || null); } expect(passNumber).toThrowError(&quot;The parameter should be an array&quot;); expect(passString).toThrowError(&quot;The parameter should be an array&quot;); expect(passEmptyArray).toThrowError(&quot;The array is empty&quot;); expect(passUndefinedOrNull).toThrowError(&quot;The parameter is null or undefined&quot;); } if (func.length === 2) { function passNumber() { func(0, 1); } function passString() { func(&quot;item&quot;, 1); } function passEmptyArray() { func([], 1); } function passUndefinedOrNull() { func(undefined || null, 1); } expect(passNumber).toThrowError(&quot;The parameter should be an array&quot;); expect(passString).toThrowError(&quot;The parameter should be an array&quot;); expect(passEmptyArray).toThrowError(&quot;The array is empty&quot;); expect(passUndefinedOrNull).toThrowError(&quot;The parameter is null or undefined&quot;); } } </code></pre> <p>You may notice that there are duplicated <code>passNumber</code>,<code>passString</code>,<code>passEmpty</code> inside different <code>if</code> statements and each function call different <code>callback</code> function <code>func</code>.</p> <p>How do I remove duplicated functions: <code>passNumber</code>,<code>passString</code>,<code>passEmpty</code> and just have once call with different parameters ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T07:01:06.027", "Id": "482770", "Score": "0", "body": "What do you want to accomplish? There seems to be no point to this code? If you have `(func.length === 3) ` can you provide it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T09:15:12.927", "Id": "482787", "Score": "0", "body": "@konijn, I've never passed more then 2 parameters in a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T16:13:02.077", "Id": "482846", "Score": "0", "body": "Shouldn't `expect(passString).toThrowError(\"The parameter should be an array\")` be `expect(passString).toThrowError(\"The parameter should be a sting\")` (\"a string\" instead of \"an array\")?" } ]
[ { "body": "<p>The only difference between the two parts is that the second part has an additional parameter <code>1</code>? You can provide an array with the original param, if function.length is 2, push <code>1</code> into it. the just call <code>func.apply(null, params)</code>.</p>\n<p>Here is a solution base on the idea:</p>\n<pre><code>function __throwError (func) {\n const testcases = [\n new TestCase(func, 0, 'The parameter should be an array'),\n new TestCase(func, 'item', 'The parameter should be an array'),\n new TestCase(func, [], 'The array is empty'),\n new TestCase(func, undefined, 'The parameter is null or undefined'),\n new TestCase(func, null, 'The parameter is null or undefined')\n ];\n if (func.length === 2) {\n testcases.forEach(testcase =&gt; testcase.value.push(1));\n }\n for (const testcase of testcases) {\n expect(testcase.fn).toThrowError(testcase.errMsg);\n }\n}\n\nclass TestCase {\n constructor (testFn, value, errMsg) {\n this.value = [value];\n this.errMsg = errMsg;\n this.testFn = testFn;\n }\n fn () {\n this.testFn.apply(null, this.value);\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T11:10:36.860", "Id": "245864", "ParentId": "245762", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:11:09.960", "Id": "245762", "Score": "3", "Tags": [ "javascript" ], "Title": "Remove duplicated functions inside different if within a function?" }
245762
<p>I am making a game event messenger based on the observer pattern and I'd really appreciate some feedback on this please. The intent behind it is that I am sending in a function pointer so that it can work for the broadcasting. Also using the subscribers memory address as a way of detecting it for unsubscribe.</p> <p>Thank you in advance.</p> <pre><code>enum class eGameEventType { SpawnPickup = 0, Max = SpawnPickup }; namespace GameEvents { template &lt;eGameEventType T&gt; struct BaseEvent { static eGameEventType getType() { return T; }; }; struct SpawnPickUp : public BaseEvent&lt;eGameEventType::SpawnPickup&gt; { SpawnPickUp(int type, const std::string&amp; name) : type(type), name(name) {} int type; std::string name; }; } struct Listener { Listener(const std::function&lt;void(const void*)&gt;&amp; fp, const void* ownerAddress) : m_listener(fp), m_ownerAddress(ownerAddress) {} Listener(Listener&amp;&amp; orig) noexcept : m_listener(orig.m_listener), m_ownerAddress(orig.m_ownerAddress) { orig.m_listener = nullptr; orig.m_ownerAddress = nullptr; } Listener&amp; operator=(Listener&amp;&amp; orig) noexcept { m_listener = orig.m_listener; m_ownerAddress = orig.m_ownerAddress; orig.m_listener = nullptr; orig.m_ownerAddress = nullptr; return *this; } std::function&lt;void(const void*)&gt; m_listener; const void* m_ownerAddress; }; class GameEventMessenger { public: static GameEventMessenger&amp; getInstance() { static GameEventMessenger instance; return instance; } template &lt;typename GameEvent&gt; void subscribe(const std::function&lt;void(const GameEvent&amp;)&gt;&amp; gameEvent, const void* ownerAddress) { auto&amp; listeners = m_listeners[static_cast&lt;int&gt;(GameEvent::getType())]; assert(!isOwnerAlreadyRegistered(listeners, GameEvent::getType(), ownerAddress)); listeners.emplace_back(reinterpret_cast&lt;std::function&lt;void(const void*)&gt; const&amp;&gt;(gameEvent), ownerAddress); } template &lt;typename GameEvent&gt; void unsubscribe(const void* ownerAddress) { auto&amp; listeners = m_listeners[static_cast&lt;int&gt;(GameEvent::getType())]; assert(isOwnerAlreadyRegistered(listeners, GameEvent::getType(), ownerAddress)); auto iter = std::find_if(listeners.begin(), listeners.end(), [ownerAddress](const auto&amp; listener) { return listener.m_ownerAddress == ownerAddress; }); assert(iter != listeners.end()); listeners.erase(iter); } template &lt;typename GameEvent&gt; void broadcast(GameEvent gameEvent) { const auto&amp; listeners = m_listeners[static_cast&lt;int&gt;(GameEvent::getType())]; for (const auto&amp; listener : listeners) { reinterpret_cast&lt;std::function&lt;void(const GameEvent&amp;)&gt; const&amp;&gt;(listener.m_listener)(gameEvent); } } private: GameEventMessenger() {} std::array&lt;std::vector&lt;Listener&gt;, static_cast&lt;size_t&gt;(eGameEventType::Max) + 1&gt; m_listeners; bool isOwnerAlreadyRegistered(const std::vector&lt;Listener&gt;&amp; listeners, eGameEventType gameEventType, const void* ownerAddress) const { assert(ownerAddress != nullptr); if (!listeners.empty()) { auto result = std::find_if(listeners.cbegin(), listeners.cend(), [ownerAddress](const auto&amp; listener) { return listener.m_ownerAddress == ownerAddress; }); return result != listeners.cend(); } else { return false; } } }; </code></pre> <p>Working Example:</p> <pre><code>GameEventMessenger::getInstance().subscribe&lt;GameEvents::AddToInventory&gt;(std::bind(&amp;Player::onAddToInventory, this, std::placeholders::_1), this); void Player::onAddToInventory(const GameEvents::AddToInventory &amp; gameEvent) { m_inventory.add(gameEvent.type); } GameEventMessenger::getInstance().unsubscribe&lt;GameEvents::AddToInventory&gt;(this); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T17:06:27.633", "Id": "482740", "Score": "2", "body": "Please also add a working example of how you are using the above classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T17:29:32.840", "Id": "482741", "Score": "0", "body": "Ah, my bad. Thank you!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:19:27.200", "Id": "245763", "Score": "3", "Tags": [ "c++", "design-patterns" ], "Title": "Game Event Messenger based on the Observer pattern" }
245763
<p>for my dissertation (in psychology) I created an emotion recognition test that displays an image of a face displaying a certain emotion for a set time, then allows participants to press a button indicating which emotion they feel was being displayed. This was my first major Python project - and I'm hoping to upload it to github, but first I wanted to check that my code is okay - because it's likely a project I will talk about a lot during interviews (as its a perfect segue from studying psychology to an interest in programming).</p> <p>Could somebody check and make sure there are no glaring errors/everything makes sense and is understandable? Have I overused comments? (I had some feedback telling me to use more comments to ensure my code is understandable - but not sure if I've overdone it!)</p> <p>Here's my code:</p> <pre><code>import pygame import os import random import time from enum import Enum import csv import sys #get participant ID number participantId = input(&quot;Please enter the participant ID number: \n&quot;) #defining button colours buttonColour1 = (20, 40, 170) #button colour when cursor over button buttonColour2 = (19, 47, 230) #button colour when cursor not over button #ms for displaying images displayTime = 1000 # display time for images in ms #generate empty list to store answers answers = [] #this list stores all answers numberofQuestions = 4 #number of non-practice questions pnumberofQuestions = 4 #number of practice questions emotionTypes = [&quot;Happy&quot;, &quot;Sad&quot;, &quot;Neutral&quot;, &quot;Afraid&quot;, &quot;Angry&quot;] #all possible answers - modify if you have more/less emotions #display screen display_width = 1200 display_height = 800 #dictionary containing rects of button positions rectDict = { &quot;sad&quot;: pygame.Rect(0, 700, 200, 100), &quot;happy&quot;: pygame.Rect(240, 700, 200, 100), &quot;neutral&quot;: pygame.Rect(480, 700, 200, 100), &quot;angry&quot;: pygame.Rect(720, 700, 200, 100), &quot;afraid&quot;: pygame.Rect(960, 700, 200, 100), } rectList = list(rectDict.values()) # Define class to keep track of states class States(Enum): VIEWING = 1 ANSWERING = 2 #this function displays an image to the screen def askQuestion(images, imageNumber): xCoord = (display_width/2) - (images[imageNumber].get_size()[0]/2) #display width minus half the image width yCoord = (display_height/2) - (images[imageNumber].get_size()[1]/2) #display height minus half the image height screen.blit(images[imageNumber], ((xCoord, yCoord))) #blit image to screen #define a function to display answer buttons def displayButtons(buttonText, x, y, width, height): mouse = pygame.mouse.get_pos() buttonText_rect = pygame.Rect(x, y, width, height) if buttonText_rect.collidepoint(mouse): #if mouse is hovering over button pygame.draw.rect(screen, buttonColour1, (buttonText_rect)) #display button colour 1 else: pygame.draw.rect(screen, buttonColour2, (buttonText_rect)) #otherwise, display button colour 2 text = pygame.font.SysFont('Arial', 22) #add text to buttons textSurf, textRect = text_objects(buttonText, text) textRect.center = ((x+(width/2)), (y+(height/2))) #center text within buttons screen.blit(textSurf, textRect) #define functions to display text def text_objects(text, font): textSurface = font.render(text, True, (0, 0, 0)) return textSurface, textSurface.get_rect() def displayText(someText, xpos, ypos): #use this function to display text text = pygame.font.SysFont('Arial', 22) textSurf, textRect = text_objects(someText, text) textRect.center = xpos, ypos screen.blit(textSurf, textRect) #initialising pygame pygame.init() #create the screen screen = pygame.display.set_mode((display_width, display_height)) # Caption pygame.display.set_caption(&quot;Emotion Recognition Test&quot;) # Load images and randomise their order imageList = [] questionOrder = [] practiceImages = [] os.chdir(r&quot;C:\Python 3.8\Projects\Emotion Recognition Test\All images&quot;) #change cwd to folder containing non-practice images for image in os.listdir(&quot;C:\Python 3.8\Projects\Emotion Recognition Test\All images&quot;): imageList.append(pygame.image.load(image).convert_alpha()) #this creates a list of surface values questionOrder.append(image) #this contains the image names in order combined = list(zip(imageList, questionOrder)) #this combines image names and associated surface values random.shuffle(combined) #randomises the combined list imageList[:], questionOrder[:] = zip(*combined) #separates the combined list, image name and surface values are still associated os.chdir(r&quot;C:\Python 3.8\Projects\Emotion Recognition Test\Practice images&quot;) #change cwd to folder containing practice images for image in os.listdir(r&quot;C:\Python 3.8\Projects\Emotion Recognition Test\Practice images&quot;): #for every image in the practice images folder practiceImages.append(pygame.image.load(image).convert_alpha()) #append to practiceImages and load in the game random.shuffle(practiceImages) #randomise the order of practice images def instructions(instructionsText): #define a function to display an instruction screen running = True while running: screen.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: running = False elif event.type == pygame.QUIT: running = False pygame.quit() sys.exit() displayText(instructionsText, (display_width/2), (display_height/2)) #displays text to centre of screen pygame.display.update() def mainDisplay(): #this function displays fixation circle + buttons pygame.draw.circle(screen, (0,0,0), (int(display_width/2), int(display_height/2)), 10, 2) displayButtons(&quot;sad&quot;, 0, 700, 200, 100) displayButtons(&quot;happy&quot;, 240, 700, 200, 100) displayButtons(&quot;neutral&quot;, 480, 700, 200, 100) displayButtons(&quot;angry&quot;, 720, 700, 200, 100) displayButtons(&quot;afraid&quot;, 960, 700, 200, 100) def mainGame(images): dt = 0 #delta time is set to 0 to begin timer = displayTime #how long image is displayed for clock = pygame.time.Clock() imageNumber = 0 gameState = States.VIEWING #this is the game state where a participant views a question running = True while running: mouse = pygame.mouse.get_pos() screen.fill((255, 255, 255)) mainDisplay() #this displays the answer buttons dt = clock.tick_busy_loop(30) #dt = number of milliseconds per frame for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False pygame.quit() sys.exit() if ( gameState == States.VIEWING): timer -= dt #minus dt from the timer, making timer count down if timer &gt;= 0: #if the timer remains above 0, continue displaying image askQuestion(images, imageNumber) else: #when timer reaches 0, stop displaying image and move to answering state gameState = States.ANSWERING elif (gameState == States.ANSWERING): #this is where participants select their answer timer = displayTime #reset the timer screen.fill((255, 255, 255)) mainDisplay() #displays answer buttons for emotion, rects in rectDict.items(): #this detects whether a button has been clicked or not if event.type == pygame.MOUSEBUTTONDOWN: if rects.collidepoint(mouse): #if a button is clicked gameState = States.VIEWING #switch back to viewing state answers.append(emotion) #add answer to answer list imageNumber += 1 #move to the next image break elif not any(rect.collidepoint(mouse) for rect in rectList): #if a button is not clicked displayText(&quot;You did not click a button!&quot;, 600, 600) #inform users they have not clicked a button if practice == True: #if in practice mood, stop when number of practice questions is reached if len(answers) == pnumberofQuestions: break elif practice == False: #if in main game loop, stop when number of non-practice questions is reached if len(answers) == numberofQuestions: break pygame.display.update() instructions(&quot;First instruction screen&quot;) #inform participants about the game #Game Loop practice = True mainGame(practiceImages) #this is the practice loop answers = [] #reset the answer list - since we don't track the practice trials practice = False instructions(&quot;Second instruction screen&quot;) #inform participants that practice trials are now over mainGame(imageList) #non-practice round begins instructions(&quot;Thank you for taking part&quot;) #final screen - thank participants for taking part emotions = [] #empty list to store the emotions in each question for image in questionOrder[0:numberofQuestions + 1]: #for loop to generate a list of the emotions presented in each face for emotion in emotionTypes: if emotion in image: #if emotion type is in the name of the image, append emotion type to emotions list emotions.append(emotion) results = list(zip(questionOrder, emotions, answers)) #combine all three lists into tuples within a single list results.insert(0, (&quot;question&quot;, &quot;emotion&quot;, &quot;answer&quot;)) #top row for the CSV file os.chdir(r&quot;C:\Python 3.8\Projects\Emotion Recognition Test&quot;) #change cwd to folder where results are stored with open(f&quot;{participantId}.csv&quot;, &quot;w&quot;, newline='') as f: #save results into a CSV file titled with participant ID no. writer = csv.writer(f) writer.writerows(results) </code></pre>
[]
[ { "body": "<p>Here's a stream of consciousness review. I basically started at the top an jotted down things as I saw them. Don't be discouraged by the number of remarks. If the code works well enough, then fix up the comments and add some doc strings or other documentation and call it a day. Make sure and have a backup before making any changes. Here we go:</p>\n<p>Add a module level docstring describing what the code does and any\ninformation that is needed to use the code. For example, someone\nwould need to change the base directory, provide practice and\nactual images in the proper subdirectories. The image files need\nto have the emotion encoded in the filename. Etc.</p>\n<pre><code>import pygame\nimport os\nimport random\nimport time\nfrom enum import Enum\nimport csv\nimport sys\n</code></pre>\n<p>Comments that just parrot the code just add noise. Useful comments provide\ninformation that isn't apparent from reading the code. It's rather obvious\nwhat the line <code>participantId == input(...)</code> does; the comment\n<code>#get participant ID number</code> adds nothing and should be removed. Most of\nthe comments in the code are similarly useless.</p>\n<p>This should go with the other top level code below.</p>\n<pre><code>#get participant ID number\nparticipantId = input(&quot;Please enter the participant ID number: \\n&quot;)\n</code></pre>\n<p>Rather than using comments to explain what the colors are, use better\nvariable names, like <code>buttonNormalColor</code> and buttonHoverColor`.</p>\n<p>PEP 8 and suggests using camelcase variable names: <code>button_normal_color</code>.\nThings that are meant to be constants, like button color or a list of all\npossible emotions, are generally written in all caps, like <code>BUTTON_NORMAL_COLOR</code>\nor <code>EMOTION_TYPES</code>. There are other python styles. It's your project; pick a style, but be <strong>consistent</strong>.</p>\n<p>Most Python programmers seem to dislike comments on the same line after the code</p>\n<pre><code>#defining button colours\nbuttonColour1 = (20, 40, 170) #button colour when cursor over button\nbuttonColour2 = (19, 47, 230) #button colour when cursor not over button\n\n#ms for displaying images\ndisplayTime = 1000 # display time for images in ms\n</code></pre>\n<p>Avoid global variables like <code>answer</code>.</p>\n<pre><code>#generate empty list to store answers\nanswers = [] #this list stores all answers\nnumberofQuestions = 4 #number of non-practice questions\npnumberofQuestions = 4 #number of practice questions\n</code></pre>\n<p>This is the first worthwhile comment</p>\n<pre><code>#all possible answers - modify if you have more/less emotions\nemotionTypes = [&quot;Happy&quot;, &quot;Sad&quot;, &quot;Neutral&quot;, &quot;Afraid&quot;, &quot;Angry&quot;] \n\n#display screen\ndisplay_width = 1200\ndisplay_height = 800\n</code></pre>\n<p>We can see that it is a dict of rects. A useful comment would be that there\nshould be a button for each emotion type, that the top of all the rects should\nbe below 700 so they don't interfere with the image display.</p>\n<p>Why are the emotions capitalized in <code>emotionTypes</code>, but lowercase here?</p>\n<pre><code>#dictionary containing rects of button positions\nrectDict = {\n&quot;sad&quot;: pygame.Rect(0, 700, 200, 100),\n&quot;happy&quot;: pygame.Rect(240, 700, 200, 100),\n&quot;neutral&quot;: pygame.Rect(480, 700, 200, 100),\n&quot;angry&quot;: pygame.Rect(720, 700, 200, 100),\n&quot;afraid&quot;: pygame.Rect(960, 700, 200, 100),\n}\n</code></pre>\n<p>Under DRY (Don't Repeat Yourself) principle, it might be better to extract the\nemotion types from this dict like you do for the <code>rectList</code>: <code>(emotionTypes = list(rectDict.keys())</code>. Or just use <code>rectDict.keys()</code> or <code>.values()</code> when needed.</p>\n<p>Could put this information in a sequence of tuples, so you don't have to type in <code>pygame.Rect</code> so many times. Then code could build the dict.</p>\n<p>Given a list of button names the program could calculate where the buttons go. rectDict\ncould be build from just the button names.</p>\n<pre><code>rectList = list(rectDict.values())\n\n# Define class to keep track of states\nclass States(Enum):\n VIEWING = 1\n ANSWERING = 2\n</code></pre>\n<p>The name of the function is misleading. It doesn't ask a question, it displays an image.\nInstead of passing in a list of images and an index, just pass in the image to display,\nit simplifies the function signature.</p>\n<p><code>#display width minus half the image width</code> is a long way to say it is centered in the display.</p>\n<p>Use sequence unpacking to make code clearer. <code>image_width, image_height = image.get_size()' then </code>xCoord = (display_width - image_width) / 2`. (Note inconsistent naming style)</p>\n<p>For a function, a doc string is better than a comment. The audience of a doc string is\na user of the function. In most REPLs or IDEs they can query the doc string to see how\nto use the function. Comments are generally to help someone to understand the code to\nbetter debug/modify/enhance/... it.</p>\n<pre><code>#this function displays an image to the screen\ndef askQuestion(images, imageNumber):\n &quot;&quot;&quot;displays an image centered on the display.&quot;&quot;&quot;\n \n xCoord = (display_width/2) - (images[imageNumber].get_size()[0]/2) #display width minus half the image width\n yCoord = (display_height/2) - (images[imageNumber].get_size()[1]/2) #display height minus half the image height\n screen.blit(images[imageNumber], ((xCoord, yCoord))) #blit image to screen\n</code></pre>\n<p>It only displays one button, so <code>displayButton()</code>.</p>\n<p>The calls to <code>displayButtons()</code> below hard code the button name and coords/width.\nBut that data is already in <code>rectDict</code> above; pass in the name and rect from\nthe dict.</p>\n<p>I suspect it would be possible to premake a surface for each button for each color.\nThen simply blit the correct surface to the screen.</p>\n<pre><code>#define a function to display answer buttons\ndef displayButtons(buttonText, x, y, width, height):\n mouse = pygame.mouse.get_pos()\n buttonText_rect = pygame.Rect(x, y, width, height)\n if buttonText_rect.collidepoint(mouse): #if mouse is hovering over button\n pygame.draw.rect(screen, buttonColour1, (buttonText_rect)) #display button colour 1\n else:\n pygame.draw.rect(screen, buttonColour2, (buttonText_rect)) #otherwise, display button colour 2\n\n text = pygame.font.SysFont('Arial', 22) #add text to buttons\n textSurf, textRect = text_objects(buttonText, text)\n textRect.center = ((x+(width/2)), (y+(height/2))) #center text within buttons\n screen.blit(textSurf, textRect)\n</code></pre>\n<p>I don't see a value in this next function. I find it clearer to call <code>font.render()</code>\nand <code>surface.get_rect()</code>.</p>\n<p>Generally, functions <em>do</em> something, so their names are often a verb: <code>display()</code>,\n<code>sort()</code>, etc. Variables are often things so they tend to have nouns for names:\n<code>screen</code>, <code>button</code>, etc.</p>\n<pre><code>#define functions to display text\ndef text_objects(text, font):\n textSurface = font.render(text, True, (0, 0, 0))\n return textSurface, textSurface.get_rect()\n\ndef displayText(someText, xpos, ypos): #use this function to display text\n text = pygame.font.SysFont('Arial', 22)\n textSurf, textRect = text_objects(someText, text)\n textRect.center = xpos, ypos\n screen.blit(textSurf, textRect)\n</code></pre>\n<p>Kinda odd having this module-level code here. Suggest moving it down with\nthe rest, or putting it into a function.</p>\n<pre><code>#initialising pygame\npygame.init()\n\n#create the screen\nscreen = pygame.display.set_mode((display_width, display_height))\n\n# Caption\npygame.display.set_caption(&quot;Emotion Recognition Test&quot;)\n</code></pre>\n<p>Loading images should be a function. It doesn't hurt anything to\nshuffle the practice images. Pass in the directory as an argument, and\nit returns a list of the (imagename, image) tuples (or use a namedtuple or\ndataclass). If there are many images and memory is an issue, return a list\nof the image paths and load them when needed.</p>\n<p>Recommend using <code>pathlib</code>.</p>\n<p>Rather than hard coding the paths to the image file directory, define a base\n<code>BASE_DIR = pathlib.Path(&quot;C:/Python 3.8/Projects/Emotion Recognition Test)&quot;</code>.\nAnd make other directories relative to it: `image_dir = BASE_DIR / &quot;All images&quot;.\nIf the project is moved around, or someone downloads it from github, it only\nneeds to be changed in one spot.</p>\n<p>Use <code>random.sample(os.listdir(), numberOfQuestions)</code> and only load those image\nfiles. No need to shuffle, because they would already be in random order.</p>\n<p>Should the code make sure there are a minimum number images for each emotion type?</p>\n<p>Consider <code>pathlib.Path().glob()</code> instead of <code>os.listdir()</code></p>\n<pre><code># Load images and randomise their order\nimageList = []\nquestionOrder = []\npracticeImages = []\nos.chdir(r&quot;C:\\Python 3.8\\Projects\\Emotion Recognition Test\\All images&quot;) #change cwd to folder containing non-practice images\nfor image in os.listdir(&quot;C:\\Python 3.8\\Projects\\Emotion Recognition Test\\All images&quot;):\n imageList.append(pygame.image.load(image).convert_alpha()) #this creates a list of surface values\n questionOrder.append(image) #this contains the image names in order\n\ncombined = list(zip(imageList, questionOrder)) #this combines image names and associated surface values\nrandom.shuffle(combined) #randomises the combined list\nimageList[:], questionOrder[:] = zip(*combined) #separates the combined list, image name and surface values are still associated\n\n\nos.chdir(r&quot;C:\\Python 3.8\\Projects\\Emotion Recognition Test\\Practice images&quot;) #change cwd to folder containing practice images\nfor image in os.listdir(r&quot;C:\\Python 3.8\\Projects\\Emotion Recognition Test\\Practice images&quot;): #for every image in the practice images folder\n practiceImages.append(pygame.image.load(image).convert_alpha()) #append to practiceImages and load in the game\nrandom.shuffle(practiceImages) #randomise the order of practice images\n</code></pre>\n<p>Something like <code>show_instructions()</code> might be a better name.</p>\n<p>Processing the event queue in multiple places seems like it is asking for\ntrouble.</p>\n<pre><code>def instructions(instructionsText): #define a function to display an instruction screen\n running = True\n while running:\n screen.fill((255, 255, 255))\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n running = False\n elif event.type == pygame.QUIT:\n running = False\n pygame.quit()\n sys.exit()\n \n displayText(instructionsText, (display_width/2), (display_height/2)) #displays text to centre of screen\n pygame.display.update()\n</code></pre>\n<p>Perhaps <code>init_display()</code>.</p>\n<p>Loop over rectDict.items() and call <code>displayButton()</code> with the button name and\nRect (the key and value in the dict) <code>for name, rect in rectDict.items():\\n displayButton(name, rect)</code></p>\n<pre><code>def mainDisplay(): #this function displays fixation circle + buttons\n pygame.draw.circle(screen, (0,0,0), (int(display_width/2), int(display_height/2)), 10, 2)\n displayButtons(&quot;sad&quot;, 0, 700, 200, 100)\n displayButtons(&quot;happy&quot;, 240, 700, 200, 100)\n displayButtons(&quot;neutral&quot;, 480, 700, 200, 100)\n displayButtons(&quot;angry&quot;, 720, 700, 200, 100)\n displayButtons(&quot;afraid&quot;, 960, 700, 200, 100)\n</code></pre>\n<p>Instead of counting images and comparing it to <code>numberofQuestions</code> or <code>pnumberofQuestions</code>\njust loop over the sequence of images passed in.\nfor image in images:\ngameState = States.VIEWING\nrunning = True\nwhile running:\n...</p>\n<p>Maybe <code>run_experiment()</code> for a name.</p>\n<p>Add an argument for the instructions and state States.INSTRUCTING. Then\nthe event loop can be taken out of <code>instructions()</code></p>\n<p><code>answers</code> is a global variable, but without being declared <code>global</code>.\nIt is better for it to be local to the function and then have the\nfunction return the list of answers.</p>\n<pre><code>def mainGame(images):\n dt = 0 #delta time is set to 0 to begin\n timer = displayTime #how long image is displayed for\n clock = pygame.time.Clock()\n imageNumber = 0\n gameState = States.VIEWING #this is the game state where a participant views a question\n running = True\n while running:\n mouse = pygame.mouse.get_pos()\n screen.fill((255, 255, 255))\n mainDisplay() #this displays the answer buttons\n dt = clock.tick_busy_loop(30) #dt = number of milliseconds per frame\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n pygame.quit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n pygame.quit()\n sys.exit()\n\n\n if ( gameState == States.VIEWING):\n timer -= dt #minus dt from the timer, making timer count down\n if timer &gt;= 0: #if the timer remains above 0, continue displaying image\n askQuestion(images, imageNumber)\n else: #when timer reaches 0, stop displaying image and move to answering state\n gameState = States.ANSWERING\n \n</code></pre>\n<p>I think you could use <code>rect.collidedict()</code>. Create a 1-pixel square rect at the\nmouse position:\nmouse = pygame.Rect(pygame.mouse.get_pos(), (1,1))\nhit = mouse_rect.collidedict(rectDict, use_values=1)\nif hit:\nemotion, _ = hit\nanswers.append(emotion)\nelse:\n... didn't click a button</p>\n<pre><code> elif (gameState == States.ANSWERING): #this is where participants select their answer\n timer = displayTime #reset the timer\n screen.fill((255, 255, 255))\n mainDisplay() #displays answer buttons\n for emotion, rects in rectDict.items(): #this detects whether a button has been clicked or not\n if event.type == pygame.MOUSEBUTTONDOWN:\n if rects.collidepoint(mouse): #if a button is clicked\n gameState = States.VIEWING #switch back to viewing state\n answers.append(emotion) #add answer to answer list\n imageNumber += 1 #move to the next image\n break\n elif not any(rect.collidepoint(mouse) for rect in rectList): #if a button is not clicked\n displayText(&quot;You did not click a button!&quot;, 600, 600) #inform users they have not clicked a button\n \n</code></pre>\n<p>These <code>if</code> statements constitute a &quot;hidden interface&quot; for this function, in\nthat the way the function works depends on variables that aren't in the\nfunction's argument list. It makes it harder to test and debug.</p>\n<pre><code> if practice == True: #if in practice mood, stop when number of practice questions is reached\n if len(answers) == pnumberofQuestions:\n break\n elif practice == False: #if in main game loop, stop when number of non-practice questions is reached\n if len(answers) == numberofQuestions:\n break\n\n pygame.display.update()\n</code></pre>\n<p>The rest of the code drives the experiment and saves the results. It would be\ncleaner to put it in a <code>main()</code> function.</p>\n<pre><code>instructions(&quot;First instruction screen&quot;) #inform participants about the game\n\n#Game Loop\npractice = True\n\nmainGame(practiceImages) #this is the practice loop\nanswers = [] #reset the answer list - since we don't track the practice trials\n\npractice = False\n\ninstructions(&quot;Second instruction screen&quot;) #inform participants that practice trials are now over\n\nmainGame(imageList) #non-practice round begins\n\ninstructions(&quot;Thank you for taking part&quot;) #final screen - thank participants for taking part\n</code></pre>\n<p>Here, <code>image</code> is a poor name. It misleads the reader into thinking it is an\nimage, but it is actually an image name, i.e., a string. Call it <code>imagename</code>.</p>\n<p>This code suggests that the emotion represented by an image is encoded in the\nname of the image file. The file name format should be documented.</p>\n<pre><code>emotions = [] #empty list to store the emotions in each question\nfor image in questionOrder[0:numberofQuestions + 1]: #for loop to generate a list of the emotions presented in each face\n for emotion in emotionTypes:\n if emotion in image: #if emotion type is in the name of the image, append emotion type to emotions list\n emotions.append(emotion)\n</code></pre>\n<p>Try <code>results = [&quot;question&quot;, &quot;emotion&quot;, &quot;answer&quot;]</code>\nand <code>results.extend(zip(questionOrder, emotions, answers))</code></p>\n<pre><code>results = list(zip(questionOrder, emotions, answers)) #combine all three lists into tuples within a single list\n \nresults.insert(0, (&quot;question&quot;, &quot;emotion&quot;, &quot;answer&quot;)) #top row for the CSV file\n\nos.chdir(r&quot;C:\\Python 3.8\\Projects\\Emotion Recognition Test&quot;) #change cwd to folder where results are stored\n\nwith open(f&quot;{participantId}.csv&quot;, &quot;w&quot;, newline='') as f: #save results into a CSV file titled with participant ID no.\n writer = csv.writer(f)\n writer.writerows(results)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T18:10:48.740", "Id": "245970", "ParentId": "245764", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T17:01:54.203", "Id": "245764", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "game", "pygame" ], "Title": "An emotion recognition test I designed using Pygame" }
245764
<p>I'm working with numpy arrays and dictionaries, the keys of the dictionary are coordinates in the numpy array and the values of the dictionary are a list of values I need to add in those coordinates, I also have a 3D list of coordinates that I use for reference, I was able to do it, but I'm creating unnecessary copies of some things to do it. I believe there is an easy way, but I really don't know how to do it, this is my code:</p> <pre><code>import numpy as np arr = np.array([[[ 0., 448., 94., 111., 118.], [ 0., 0., 0., 0., 0.], [ 0., 6., 0., 6., 9.], [ 0., 99., 4., 0., 0.], [ 0., 31., 9., 0., 0.]], [[ 0., 496., 99., 41., 20.], [ 0., 0., 0., 0., 0.], [ 0., 41., 0., 1., 6.], [ 0., 34., 2., 0., 0.], [ 0., 91., 4., 0., 0.]], [[ 0., 411., 53., 75., 32.], [ 0., 0., 0., 0., 0.], [ 0., 45., 0., 3., 0.], [ 0., 10., 3., 0., 7.], [ 0., 38., 0., 9., 0.]], [[ 0., 433., 67., 57., 23.], [ 0., 0., 0., 0., 0.], [ 0., 56., 0., 4., 0.], [ 0., 7., 5., 0., 6.], [ 0., 101., 0., 6., 0.]]]) #The first list in reference are the coordinates for the subarray [:,2:,2:] of the first two arrays in arr #The second list in reference are the coordinates for the subarray [:,2:,2:] of the second two arrays in arr reference = [[[2, 3], [2, 4], [3, 2], [4, 2]], [[2, 3], [3, 2], [3, 4], [4, 3]]] #Dictionary whose keys matches the coordinates in the reference list mydict = {(2, 3): [5, 1], (2, 4): [14, 16], (3, 2): [19, 1], (3, 4): [14, 30], (4, 2): [16, 9], (4, 3): [6, 2]} #I extract the values of the dict if the key matches the reference and created a 3D list with the values listvalues = [[mydict.get(tuple(v), v) for v in row] for row in reference] #Output listvalues = [[[5, 1], [14, 16], [19, 1], [16, 9]], [[5, 1], [19, 1], [14, 30], [6, 2]]] #Then I create a numpy array with my aux list and transpose. newvalues = np.array(listvalues).transpose(0, 2, 1) newvalues = [[[ 5, 14, 19, 16], [ 1, 16, 1, 9]], [[ 5, 19, 14, 6], [ 1, 1, 30, 2]]] </code></pre> <p>What I need is to get a copy of <code>arr</code> (<code>arr</code> shape is <code>(4, 5, 5)</code> and then the copy of arr which I will call <code>newarr</code> will have a shape of <code>(8, 5, 5)</code>) then I need to use the array <code>[5 14 19 16]</code> in <code>newvalues</code> to add the numbers in the corresponding coordinates in the first two arrays of <code>newarr</code> and then the values <code>[5 19 14 6]</code> in the next two arrays in <code>newarr</code>, then (here the copy starts) add the values of <code>[ 1 16 1 9]</code> in the next two arrays of <code>newarr</code> and finally add the values of <code>[ 1 1 30 2]</code> in the final two arrays. Here is the rest of the code.</p> <pre><code>newarr = np.tile(arr, (2, 1, 1)) #Here I repeat my original array price = np.reshape(newvalues, (4, 4), order='F') #Here I reshape my 3D array of values to 2D and the order change final = np.repeat(price, 2, axis =0) #And here I repeat the price so newarr and price have the same dimension in axis = 0 #And finally since they have the dimension in axis = 0 I add the values in the subarray. index = newarr[:, 2:, 2:] #This is the slice of the subarray index[index.astype('bool')] = index[index.astype('bool')] + np.array(final).ravel() #And this add values to the right places. print(newarr) </code></pre> <h2>Output</h2> <pre><code>newarr=[[[ 0., 448., 94., 111., 118.], [ 0., 0., 0., 0., 0.], [ 0., 6., 0., 11., 23.], [ 0., 99., 23., 0., 0.], [ 0., 31., 25., 0., 0.]], #In these two add the values of [5 14 19 16] [[ 0., 496., 99., 41., 20.], [ 0., 0., 0., 0., 0.], [ 0., 41., 0., 6., 20.], [ 0., 34., 21., 0., 0.], [ 0., 91., 20., 0., 0.]], [[ 0., 411., 53., 75., 32.], [ 0., 0., 0., 0., 0.], [ 0., 45., 0., 8., 0.], [ 0., 10., 22., 0., 21.], [ 0., 38., 0., 15., 0.]], #In these two add the values of [5 19 14 6] [[ 0., 433., 67., 57., 23.], [ 0., 0., 0., 0., 0.], [ 0., 56., 0., 9., 0.], [ 0., 7., 24., 0., 20.], [ 0., 101., 0., 12., 0.]], #&lt;-Here starts the copy of my original array [[ 0., 448., 94., 111., 118.], [ 0., 0., 0., 0., 0.], [ 0., 6., 0., 7., 25.], [ 0., 99., 5., 0., 0.], [ 0., 31., 18., 0., 0.]], #In these two add the values of [ 1 16 1 9] [[ 0., 496., 99., 41., 20.], [ 0., 0., 0., 0., 0.], [ 0., 41., 0., 2., 22.], [ 0., 34., 3., 0., 0.], [ 0., 91., 13., 0., 0.]], [[ 0., 411., 53., 75., 32.], [ 0., 0., 0., 0., 0.], [ 0., 45., 0., 4., 0.], [ 0., 10., 4., 0., 37.], [ 0., 38., 0., 11., 0.]], #And finally in these two add the values of [ 1 1 30 2] [[ 0., 433., 67., 57., 23.], [ 0., 0., 0., 0., 0.], [ 0., 56., 0., 5., 0.], [ 0., 7., 6., 0., 36.], [ 0., 101., 0., 8., 0.]], </code></pre> <p>I mean it does what I need, but like I said, I think there are some unnecessary copies that I don't need, and it's ugly code, I believe there should be an easy way, exploiting the possibilities of the dictionary and the numpy array, but I just can't see it. Any help will be appreciated, this is just an example to see what's going on, but the arr can have more arrays and the list values of the the dictionary can be bigger.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T19:46:57.160", "Id": "482875", "Score": "2", "body": "What physical problem are you trying to solve?Please share the goals! Also there seems to be problem that it does not run." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T21:45:20.577", "Id": "482885", "Score": "0", "body": "You are absolutely right, the code was wrong, it should work fine now. Basically what I'm trying to do is use the dictionary called \"mydict\" to add values in the coordinates that the keys of the dictionary represent, the values of the dictionary are a list, so, I want to add only the first element of every list, but since there two elements in each list of the values, I want to copy my original array and then use the second element of every list, but I do a bunch of copies and I was wondering if there is an easy way" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:30:41.027", "Id": "483022", "Score": "0", "body": "A good code has to never rely on code comments. Just a tip. Use of effective names for your variables and functions should be done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T20:09:29.800", "Id": "483026", "Score": "0", "body": "I saw something called price in the comments. Can you explain more on that price thing?" } ]
[ { "body": "<p>This seems to so what you want, but is specific to the example and code you gave.</p>\n<p>There are two pairs of subarrays in <code>arr</code> and two different sets of indices and data to add to the subarrays. So there are four combinations. These get figured out by the values of <code>i</code>, <code>j</code>, and 'k'.</p>\n<p>Because the data to be added is sparse, I'm going to use <code>scipy.sparse.coo_matrix()</code> to build arrays from <code>reference</code> and <code>mydict</code>.</p>\n<p>The line <code>data = ...</code> converts the information in <code>mydict</code> and <code>reference</code> into a list of three tuples. <code>data[0]</code> is the values to be added, <code>data[1]</code> are the row coordinates, and <code>data[2]</code> are the col coordinates.</p>\n<p><code>m = coo_matrix(...)</code> builds the sparse matrix and converts it to an <code>numpy.array</code>.</p>\n<p><code>x = arr[2*j:2*j+2] + m</code> uses the numpy array broadcasting rules to add <code>m</code> to the subarrays of the <code>arr</code> slice. So <code>x</code> is a pair of subarrays with the values added to the selected coordinates.</p>\n<p>All of the <code>x</code> arrays are gathered in a list <code>newarr</code>, and are vertically stacked at the end.</p>\n<pre><code>import numpy as np\nfrom scipy.sparse import coo_matrix\n\nnewarr = []\n\nfor k in range(4):\n i,j = divmod(k,2)\n \n data = [*zip(*((mydict[tuple(coord)][i], *coord) for coord in reference[j]))]\n\n m = coo_matrix((data[0],(data[1], data[2]))).toarray()\n \n x = arr[2*j:2*j+2] + m\n\n newarr.append(x)\n \nnewarr = np.vstack(newarr)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T20:56:24.927", "Id": "483410", "Score": "0", "body": "Thank you for the long answer, I can see a lot of things I been doing wrong" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:27:31.070", "Id": "245891", "ParentId": "245766", "Score": "3" } } ]
{ "AcceptedAnswerId": "245891", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T19:25:53.137", "Id": "245766", "Score": "3", "Tags": [ "python", "numpy", "hash-map" ], "Title": "Add values from a dictionary to subarrays using numpy" }
245766
<p>I am new to flutter and i managed to build a working Grid which does what i want it to do but the code is a duplicated hell and i didn't manage to create it dynamically while still keeping track of the input-fields and its input. I really could use some help!</p> <pre><code>import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../widgets/app_bar_row.dart'; import 'package:image_picker/image_picker.dart'; import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; class StockInputScreen extends StatefulWidget { final String standName; StockInputScreen({@required this.standName}); @override _StockInputScreenState createState() =&gt; _StockInputScreenState(standName: this.standName); } class _StockInputScreenState extends State&lt;StockInputScreen&gt; { List&lt;String&gt; gridItems = []; final String standName; _StockInputScreenState({this.standName}); Map&lt;String, dynamic&gt; gridData = {}; String currentDate = DateFormat('yMEd').format(DateTime.now()); File _pickedImage; Future&lt;void&gt; pickImage() async { final picker = ImagePicker(); final pickedImage = await picker.getImage(source: ImageSource.gallery); final pickedImageFile = File(pickedImage.path); setState(() { _pickedImage = pickedImageFile; }); } void fillGridWithData() { print(standName); currentDate = currentDate.replaceAll('/', '.'); setState(() { gridData = { standName: { 'erdbeeren': { 'erdbeerenAB': erdbeerenABController.text, 'erdbeeren13Uhr': erdbeeren13UhrController.text, 'erdbeeren15Uhr': erdbeeren15UhrController.text, 'erdbeeren17Uhr': erdbeeren17UhrController.text, 'erdbeerenEB': erdbeerenEBController.text, }, 'erdbeerenGestern': { 'erdbeerenGesternAB': erdbeerenGesternABController.text, 'erdbeerenGestern13Uhr': erdbeerenGestern13UhrController.text, 'erdbeerenGestern15Uhr': erdbeerenGestern15UhrController.text, 'erdbeerenGestern17Uhr': erdbeerenGestern17UhrController.text, 'erdbeerenGesternEB': erdbeerenGesternEBController.text, }, 'spargelVio': { 'spargelVioAB': spargelVioABController.text, 'spargelVio13Uhr': spargelVio13UhrController.text, 'spargelVio15Uhr': spargelVio15UhrController.text, 'spargelVio17Uhr': spargelVio17UhrController.text, 'spargelVioEB': spargelVioEBController.text, }, 'spargelVioGestern': { 'spargelVioABGestern': spargelVioGesternABController.text, 'spargelVio13UhrGestern': spargelVioGestern13UhrController.text, 'spargelVio15UhrGestern': spargelVioGestern15UhrController.text, 'spargelVio17UhrGestern': spargelVioGestern17UhrController.text, 'spargelVioEBGestern': spargelVioGesternEBController.text, }, 'spargelWeiss': { 'spargelWeissAB': spargelWeissABController.text, 'spargelWeiss13Uhr': spargelWeiss13UhrController.text, 'spargelWeiss15Uhr': spargelWeiss15UhrController.text, 'spargelWeiss17Uhr': spargelWeiss17UhrController.text, 'spargelWeissEB': spargelWeissEBController.text, }, 'spargelWeissGestern': { 'spargelWeissGesternAB': spargelWeissGesternABController.text, 'spargelWeissGestern13Uhr': spargelWeissGestern13UhrController.text, 'spargelWeissGestern15Uhr': spargelWeissGestern15UhrController.text, 'spargelWeissGestern17Uhr': spargelWeissGestern17UhrController.text, 'spargelWeissGesternEB': spargelWeissGesternEBController.text, }, 'kirsche690': { 'kirsche690AB': kirsche690ABController.text, 'kirsche69013Uhr': kirsche69013UhrController.text, 'kirsche69015Uhr': kirsche69015UhrController.text, 'kirsche69017Uhr': kirsche69017UhrController.text, 'kirsche690EB': kirsche690EBController.text, }, 'kirsche790': { 'kirsche790AB': kirsche790ABController.text, 'kirsche79013Uhr': kirsche79013UhrController.text, 'kirsche79015Uhr': kirsche79015UhrController.text, 'kirsche79017Uhr': kirsche79017UhrController.text, 'kirsche790EB': kirsche790EBController.text, }, 'kirsche890': { 'kirsche890AB': kirsche890ABController.text, 'kirsche89013Uhr': kirsche89013UhrController.text, 'kirsche89015Uhr': kirsche89015UhrController.text, 'kirsche89017Uhr': kirsche89017UhrController.text, 'kirsche890EB': kirsche890EBController.text, }, 'kirsche1090': { 'kirsche1090AB': kirsche1090ABController.text, 'kirsche109013Uhr': kirsche109013UhrController.text, 'kirsche109015Uhr': kirsche109015UhrController.text, 'kirsche109017Uhr': kirsche109017UhrController.text, 'kirsche1090EB': kirsche1090EBController.text, }, } }; }); addDataToFirestore(); } void addDataToFirestore() { Firestore.instance.collection('Stände/Testing/' + currentDate).document(standName).setData(gridData); } var erdbeerenABController = TextEditingController(); var erdbeeren13UhrController = TextEditingController(); var erdbeeren15UhrController = TextEditingController(); var erdbeeren17UhrController = TextEditingController(); var erdbeerenEBController = TextEditingController(); var erdbeerenGesternABController = TextEditingController(); var erdbeerenGestern13UhrController = TextEditingController(); var erdbeerenGestern15UhrController = TextEditingController(); var erdbeerenGestern17UhrController = TextEditingController(); var erdbeerenGesternEBController = TextEditingController(); var spargelVioABController = TextEditingController(); var spargelVio13UhrController = TextEditingController(); var spargelVio15UhrController = TextEditingController(); var spargelVio17UhrController = TextEditingController(); var spargelVioEBController = TextEditingController(); var spargelVioGesternABController = TextEditingController(); var spargelVioGestern13UhrController = TextEditingController(); var spargelVioGestern15UhrController = TextEditingController(); var spargelVioGestern17UhrController = TextEditingController(); var spargelVioGesternEBController = TextEditingController(); var spargelWeissABController = TextEditingController(); var spargelWeiss13UhrController = TextEditingController(); var spargelWeiss15UhrController = TextEditingController(); var spargelWeiss17UhrController = TextEditingController(); var spargelWeissEBController = TextEditingController(); var spargelWeissGesternABController = TextEditingController(); var spargelWeissGestern13UhrController = TextEditingController(); var spargelWeissGestern15UhrController = TextEditingController(); var spargelWeissGestern17UhrController = TextEditingController(); var spargelWeissGesternEBController = TextEditingController(); var kirsche690ABController = TextEditingController(); var kirsche69013UhrController = TextEditingController(); var kirsche69015UhrController = TextEditingController(); var kirsche69017UhrController = TextEditingController(); var kirsche690EBController = TextEditingController(); var kirsche790ABController = TextEditingController(); var kirsche79013UhrController = TextEditingController(); var kirsche79015UhrController = TextEditingController(); var kirsche79017UhrController = TextEditingController(); var kirsche790EBController = TextEditingController(); var kirsche890ABController = TextEditingController(); var kirsche89013UhrController = TextEditingController(); var kirsche89015UhrController = TextEditingController(); var kirsche89017UhrController = TextEditingController(); var kirsche890EBController = TextEditingController(); var kirsche1090ABController = TextEditingController(); var kirsche109013UhrController = TextEditingController(); var kirsche109015UhrController = TextEditingController(); var kirsche109017UhrController = TextEditingController(); var kirsche1090EBController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: AppBarRow(), ), body: Column( children: &lt;Widget&gt;[ Row( children: &lt;Widget&gt;[ Text( widget.standName, style: TextStyle(fontSize: 33, fontWeight: FontWeight.bold), ), ], ), Container( height: 400, padding: EdgeInsets.only(bottom: 30), child: GridView.count( padding: const EdgeInsets.all(10), crossAxisSpacing: 10, mainAxisSpacing: 10, crossAxisCount: 6, children: &lt;Widget&gt;[ Container( padding: const EdgeInsets.all(8), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('AB'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('13 Uhr'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('15 Uhr'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('17 Uhr'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('EB'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('Erd'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeeren13UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeeren15UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeeren17UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenEBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('Erd G'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenGesternABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenGestern13UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenGestern15UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenGestern17UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: erdbeerenGesternEBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('S Vio'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVio13UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVio15UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVio17UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioEBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('S Vio G'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioGesternABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioGestern13UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioGestern15UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioGestern17UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelVioGesternEBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('SW'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeiss13UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeiss15UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeiss17UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissEBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('SW G'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissGesternABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissGestern13UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissGestern15UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissGestern17UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: spargelWeissGesternEBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('K 6,90'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche690ABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche69013UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche69015UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche69017UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche690EBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('K 7,90'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche790ABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche79013UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche79015UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche79017UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche790EBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('K 8,90'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche890ABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche89013UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche89015UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche89017UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche890EBController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: const Text('K 10,90'), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche1090ABController), color: Colors.blue[200], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche109013UhrController), color: Colors.blue[300], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche109015UhrController), color: Colors.blue[400], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche109017UhrController), color: Colors.blue[500], ), Container( padding: const EdgeInsets.all(8), child: TextField(controller: kirsche1090EBController), color: Colors.blue[500], ), ], ), ), Row( children: &lt;Widget&gt;[ Container( padding: EdgeInsets.only(left: 40), child: FlatButton( color: Colors.blue, textColor: Colors.white, padding: EdgeInsets.all(8.0), onPressed: () =&gt; { pickImage(), }, child: Text( 'Foto Upload', style: TextStyle(fontSize: 18), ), ), ), Spacer(), CircleAvatar( radius: 50, backgroundColor: Colors.white, backgroundImage: _pickedImage != null ? FileImage(_pickedImage) : null, ), Container( padding: EdgeInsets.only(right: 40), child: FlatButton( color: Colors.blue, textColor: Colors.white, padding: EdgeInsets.all(8.0), onPressed: () =&gt; { fillGridWithData(), }, child: Text( 'Save Data', style: TextStyle(fontSize: 18), ), ), ), ], ) ], ), ); } } </code></pre> <p>This is the grid maybe its helps to see it.</p> <p><a href="https://i.stack.imgur.com/GPxz7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GPxz7.png" alt="This is the Grid" /></a></p>
[]
[ { "body": "<p>Make a data structure, an object, to hold all the data and meta data. The goal is to replace all that disconnected literal object creation with looping through the data structure.</p>\n<p>My sense is the structure is a composite of &quot;row header&quot;, &quot;column header&quot;, &quot;grid data&quot; objects. Put all of your meta data there, including properties to hold heading text, controller references and <code>Container</code> properties; and maybe a spot to put a reference to the associated UI grid-square if needed. So &quot;Row Header&quot; is an array of &quot;top-row-grid-square&quot; objects, in order left to right.</p>\n<p>Then I see other objects that map the data to the actual UI grid. But it's all general looping through the data structure because the structure is organized to map to the UI.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T09:18:30.537", "Id": "482788", "Score": "0", "body": "First of all thank you for your answer, unfortunately i am still left a bit in the dark could you maybe explain this a bit more?\nI am not sure for example how to loop through the input controller do i still need to create all of them like i did before and then add them to a list to loop through them? \nWould i have to check with if else statements if it is the first item in the grid and then place a column header else a grid item with an TextInput field and a controller? \nOr am i thinking in a wrong way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T20:05:54.440", "Id": "483710", "Score": "0", "body": "@Darjusch Seems like you get a general idea. After creating a data structure that would represent the contents of your screen. You would loop over that structure and use data from your structure instead of literals you currently have in your code. Yes, that involves creating headers, etc.. That doesn't mean you necessarily need to have one loop. Usually dividing code by responsibility makes it easier to understand and maintain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T02:18:00.783", "Id": "483744", "Score": "0", "body": "@CezaryButler, yes exactly. Also the headers, for example, seem to be of a certain kind of grid cell and so making that a separate object, a collection of header cells, will be simple to loop through. And so do the same with the of the kinds of cells in the larger grid. Filling the whole grid becomes a series of simple loops, not one massive complex, all at once data barf." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T01:58:25.547", "Id": "245782", "ParentId": "245770", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T21:41:56.700", "Id": "245770", "Score": "3", "Tags": [ "design-patterns", "dart", "flutter" ], "Title": "I have a input grid with more than 40 input-fields hardcoded" }
245770
<p>My solution to string interpretation is pretty fast. However, I worry about repeated <code>if (Len == 1)</code>. That might make the function bigger in the executable. How can I improve my function, to not be as redundant while checking if <code>Len</code> is equal to 1?</p> <pre><code>#include &lt;ctype.h&gt; signed char BoolFromStr(const char *const StrIn, register const unsigned char Len) { if (!Len || Len &gt; 5 || !StrIn) { return -1; } switch (tolower(*StrIn)) { case '0': if (Len == 1) { return 0; } break; case 'f': if (Len == 1 || (Len == 5 &amp;&amp; !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e'}, 4))) { return 0; } break; case 'n': if (Len == 1 || (Len == 2 &amp;&amp; Str[1] == 'o')) { return 0; } break; case '1': if (Len == 1) { return 1; } case 'y': if (Len == 1 || (Len == 3 &amp;&amp; !memcmp(Str+1, (const char[]){'e', 's'}, 2))) { return 1; } break; case 't': if (Len == 1 || (Len == 4 &amp;&amp; !memcmp(Str+1, (const char[]){'r', 'u', 'e'}, 3))) { return 1; } break; } return -1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T02:00:17.340", "Id": "482760", "Score": "1", "body": "Is this for an embedded solution, or PC?" } ]
[ { "body": "<blockquote>\n<p>How can I improve my function, to not be as redundant while checking if Len is equal to 1?</p>\n</blockquote>\n<p>Make the <em>null character</em> part of the check. <code>Len</code> not needed anywhere.</p>\n<pre><code>// if (Len == 1 || (Len == 5 &amp;&amp; !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e'}, 4))) {\n\nif (StrIn[1]==0 || !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e', 0}, 5))) {\n// or\nif (StrIn[1]==0 || \n (StrIn[1]=='a' &amp;&amp; StrIn[2]=='l' &amp;&amp; StrIn[3]=='s' &amp;&amp; StrIn[4]=='e' &amp;&amp; StrIn[5]==0)) {\n</code></pre>\n<hr />\n<p><strong>Bug</strong></p>\n<p><code>BoolFromStr(const char *const StrIn, register const unsigned char Len)</code> is a wrong when the length of the <em>string</em> is say 257 and called as</p>\n<pre><code>const char *s = &quot;ttt....ttt&quot;; // 257 t's\nBoolFromStr(s, strlen(s)); // reports 1 even though `s` is not `&quot;t&quot;`.\n</code></pre>\n<p>Recommend <code>size_t</code> and drop the <code>register</code>. Do not tie the compilers hands.</p>\n<pre><code>BoolFromStr(const char *StrIn, size_t Len);\n</code></pre>\n<hr />\n<p>To reduce size and improve speed I'd consider a hashing of the first byte of <code>StrIn</code></p>\n<pre><code>// Pseudo code\n\nint BoolFromStr(const char *StrIn) {\n const char *tf[] = {&quot;0&quot;, &quot;1&quot;, &quot;false&quot;, &quot;true&quot;, &quot;no&quot;, &quot;yes&quot;, &quot;&quot;, &quot;&quot; };\n unsigned hash = hashf(StrIn[0])%8;\n const char *cmps = tf[hash];\n if (StrIn[0] == cmps[0] &amp;&amp; (StrIn[1] == 0 || (strcmp(StrIn, cmps) == 0))) {\n return hash &amp; 1;\n }\n}\n</code></pre>\n<p>See similar <a href=\"https://stackoverflow.com/a/63005235/2410359\">What's the fastest way to interpret a bool string into a number in C?</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:08:51.627", "Id": "485190", "Score": "0", "body": "'const char *s = \"ttt....ttt\"; // 257 t's\nBoolFromStr(s, strlen(s)); // reports 1 even though `s` is not `\"t\"`.' The issue with that is because in my program it won't be used on strings longer than like five letters" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:39:49.090", "Id": "485192", "Score": "0", "body": "@user227432 If \"it won't be used on strings longer than like five letters\" is true then `Len > 5` test not needed either for this program. Yet the point of good coding includes re-use and avoiding writing code with too narrow an application. Keep in mind, tests like `Len > 5` are useful to detect the unexpected as does avoiding type narrowing. Your call." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T02:02:21.663", "Id": "245783", "ParentId": "245771", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T21:52:16.007", "Id": "245771", "Score": "1", "Tags": [ "c" ], "Title": "Is there a better way to avoid repeated 'Len == 1' when interpreting booleans from strings?" }
245771
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>Let's say a positive integer is a superpalindrome if it is a palindrome, and it is also the square of a palindrome.</p> <p>Now, given two positive integers L and R (represented as strings), return the number of superpalindromes in the inclusive range [L, R].</p> <h3>Example 1:</h3> <ul> <li>Input: L = &quot;4&quot;, R = &quot;1000&quot;</li> <li>Output: 4</li> <li>Explanation: 4, 9, 121, and 484 are superpalindromes.</li> <li>Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.</li> </ul> <p>Note:</p> <ul> <li><span class="math-container">\$1 &lt;= len(L) &lt;= 18\$</span></li> <li><span class="math-container">\$1 &lt;= len(R) &lt;= 18\$</span></li> <li>L and R are strings representing integers in the range [1, 10^18).</li> <li><code>int(L) &lt;= int(R)</code></li> </ul> </blockquote> <h3>Inputs</h3> <pre><code>&quot;4&quot; &quot;1000&quot; &quot;10&quot; &quot;99999199999&quot; &quot;1&quot; &quot;999999999999999999&quot; </code></pre> <h3>Outputs</h3> <pre><code>4 23 70 </code></pre> <h3>Code</h3> <pre><code>#include &lt;cstdint&gt; #include &lt;cmath&gt; #include &lt;string&gt; #include &lt;math.h&gt; #include &lt;queue&gt; #include &lt;utility&gt; struct Solution { static std::int_fast32_t superpalindromesInRange(const std::string L, const std::string R) { const long double lo_bound = sqrtl(stol(L)); const long double hi_bound = sqrtl(stol(R)); std::int_fast32_t superpalindromes = lo_bound &lt;= 3 &amp;&amp; 3 &lt;= hi_bound; std::queue&lt;std::pair&lt;long, std::int_fast32_t&gt;&gt; queue; queue.push({1, 1}); queue.push({2, 1}); while (true) { const auto curr = queue.front(); const long num = curr.first; const std::int_fast32_t length = curr.second; queue.pop(); if (num &gt; hi_bound) { break; } long W = powl(10, -~length / 2); if (num &gt;= lo_bound) { superpalindromes += is_palindrome(num * num); } const long right = num % W; const long left = num - (length &amp; 1 ? num % (W / 10) : right); if (length &amp; 1) { queue.push({10 * left + right, -~length}); } else { for (std::int_fast8_t d = 0; d &lt; 3; ++d) { queue.push({10 * left + d * W + right, -~length}); } } } return superpalindromes; } private: static bool is_palindrome(const long num) { if (!num) { return true; } if (!num % 10) { return false; } long left = num; long right = 0; while (left &gt;= right) { if (left == right || left / 10 == right) { return true; } right = 10 * right + (left % 10); left /= 10; } return false; } }; </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/super-palindromes/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/super-palindromes/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/super-palindromes/solution/" rel="nofollow noreferrer">Solution</a></p> </li> </ul>
[]
[ { "body": "<ul>\n<li><p>The code wastes quite a few cycles rejecting palindromes less than <code>lo_bound</code>. It is not hard to find the smallest palindrome above <code>lo_bound</code>, and start from there.</p>\n<p>If you are not comfortable constructing such palindrome, consider lifting the lead-in into the separate loop:</p>\n<pre><code> long num = 1;\n while (num &lt; lo_bound) {\n num = make_next_palindrome(queue);\n }\n</code></pre>\n</li>\n<li><p>The entire business around <code>queue</code> is very non-obvious, and it takes a great mental effort to realize that it iterates palindromes. I recommend to factor this logic out into a class of its own, along the lines of</p>\n<pre><code>class palindrome_iterator {\n std::queue&lt;...&gt; queue;\n // length, W, etc as necessary\npublic:\n palindrome_iterator(long start_num);\n long next();\n};\n</code></pre>\n<p>This way the main loop is streamlined into</p>\n<pre><code> palindrome_iterator p_i(lo_bound);\n for (long num = p_i.next(); num &lt; hi_bound; num = p_i.next()) {\n superpalindromes += is_palindrome(num * num);\n }\n</code></pre>\n<p>An additional (and possibly more important) benefit of such refactoring is that it enables unit testing of palindrome generation logic (which really sreams to be unit tested).</p>\n</li>\n<li><p>I strongly advise against <code>-~length</code> trick. <code>length + 1</code> is much more clear, and for sure not slower.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T23:36:30.743", "Id": "245774", "ParentId": "245772", "Score": "1" } } ]
{ "AcceptedAnswerId": "245774", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T22:02:24.233", "Id": "245772", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 906: Super Palindromes" }
245772
<p>I'll be teaching Computer Architecture at the undergraduate level this fall and want to make sure that my example Verilog code follows best practices. I welcome any suggestions, however minor, for improving this code, which <a href="https://www.edaplayground.com/x/3brY" rel="noreferrer">runs at EDA Playground</a>.</p> <p>Our textbook is <em>Computer Organization and Design</em> by Hennessy and Patterson. It doesn't say much about Verilog, and I will only be taking a small piece of code from an appendix, so there is no style to be consistent with.</p> <p><strong>Testbench</strong></p> <pre><code>module test; reg a; reg b; reg c_in; wire sum; wire c_out; ADDER adder(a, b, c_in, sum, c_out); initial begin // Dump waves $dumpfile(&quot;dump.vcd&quot;); $dumpvars(1); for (int i = 0; i &lt; 8; i++) begin {a, b, c_in} = i; display; end end task display; #1; $display(&quot;%b + %b + %b = %b%b&quot;, a, b, c_in, c_out, sum); endtask endmodule </code></pre> <p><strong>Design</strong></p> <pre><code>module ADDER (a, b, c_in, sum, c_out); input a; input b; input c_in; output sum; output c_out; assign c_out = (a &amp; b) | (a &amp; c_in) | (b &amp; c_in); assign sum = a ^ b ^ c_in; endmodule </code></pre>
[]
[ { "body": "<p>In the design module, use ANSI-style port declarations to reduce redundant port lists (refer to IEEE-Std 1800-2017, section 23.2.1 <em>Module header definition</em>):</p>\n<pre><code>module ADDER (\n input a,\n input b,\n input c_in,\n output sum,\n output c_out\n);\n</code></pre>\n<p>In the testbench, use connections-by-name instead of connections-by-order:</p>\n<pre><code>ADDER adder (\n .a (a),\n .b (b),\n .c_in (c_in),\n .sum (sum),\n .c_out (c_out)\n);\n</code></pre>\n<p>This involves more typing, but it avoids common connection errors, and it makes the code easier to understand (more self-documenting). Refer to Std section\n23.3.2.2 <em>Connecting module instance ports by name</em>.</p>\n<p>I usually find it helpful for debugging to also display the time:</p>\n<pre><code>$display($time, &quot; %b + %b + %b = %b%b&quot;, a, b, c_in, c_out, sum);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T14:40:16.910", "Id": "246080", "ParentId": "245773", "Score": "3" } } ]
{ "AcceptedAnswerId": "246080", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T23:35:20.850", "Id": "245773", "Score": "6", "Tags": [ "verilog" ], "Title": "Full Adder in Verilog" }
245773
<p>I asked this question before and <code>mickmackusa</code> and <code>Your Common Sense</code> gave me some good answers. I went over them and made as much changes as I could because some of the code didn't work properly for me. So again i want to know if this is a good way to have my registration code for people to sign up.</p> <pre><code>//check if form is submitted if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) { // looks like a hack, send to index.php header('Location: ../../index.php'); die(); } require '../../config/connect.php'; $con = new mysqli(...$dbCredentials); $first_name = $_POST['first_name'] ?? ''; $last_name = $_POST['last_name'] ?? ''; $username = $_POST['username'] ?? ''; $email = $_POST['email'] ?? ''; $pw = $_POST['pw'] ?? ''; $pw2 = $_POST['pw2'] ?? ''; $errors = []; if (!trim($first_name)) { $errors[] = &quot;Fill in first name to sign up&quot;; } if (!ctype_alnum($first_name)) { $errors[] = &quot;Invalid first name, it only may contain letters or digits&quot;; } if (!trim($last_name)) { $errors[] = &quot;Fill in last name to sign up&quot;; } if (!ctype_alnum($last_name)) { $errors[] = &quot;Invalid last name, only letters and/or digits.&quot;; } if (!trim($username)) { $errors[] = &quot;Fill in last name to sign up&quot;; } if (!ctype_alnum($username)) { $errors[] = &quot;Invalid last name, only letters and/or digits.&quot;; } if (!trim($pw)) { $errors[] = &quot;Fill in password to sign up&quot;; } if (!trim($pw2)) { $errors[] = &quot;Confirm password to sign up&quot;; } if (!trim($email)) { $errors[] = &quot;Fill in email to sign up&quot;; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = &quot;Invalid email&quot;; } if ($pw !== $pw2) { echo &quot;Your passwords do not match&quot;; } if (!$errors) { $check_email = $con-&gt;prepare(&quot;SELECT username FROM users WHERE username=?&quot;); $check_email-&gt;bind_param(&quot;s&quot;, $username); $check_email-&gt;execute(); $row = $check_email-&gt;get_result()-&gt;fetch_assoc(); if ($row) { echo &quot;That username is already in use&quot;; die(); } } if (!$errors) { $check_username = $con-&gt;prepare(&quot;SELECT email FROM users WHERE email=?&quot;); $check_username-&gt;bind_param(&quot;s&quot;, $email); $check_username-&gt;execute(); $row = $check_username-&gt;get_result()-&gt;fetch_assoc(); if ($row) { echo &quot;That email is already in use&quot;; die(); } } if (!$errors) { $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, array('cost' =&gt; 14)); $stmt = $con-&gt;prepare(&quot;INSERT INTO users (first_name, last_name, username, email, pw) VALUES (?, ?, ?, ?, ?)&quot;); $stmt-&gt;bind_param(&quot;sssss&quot;, $first_name, $last_name, $username, $email, $pw); $stmt-&gt;execute(); $_SESSION[&quot;id&quot;] = $_POST['username']; header(&quot;Location: ../../index.php&quot;); exit(); } else { // The foreach construct provides an easy way to iterate over arrays. foreach ($errors as $error) { $errors[] = 'An error occurred.'; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T04:18:21.570", "Id": "482765", "Score": "0", "body": "You should **really** invest some effort in testing your code before posting it. What the last foreach loop is supposed to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:28:24.827", "Id": "482797", "Score": "0", "body": "I think it puts the `$errors` in an array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:29:15.150", "Id": "482798", "Score": "0", "body": "isn't $errors already an array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:30:46.403", "Id": "482799", "Score": "0", "body": "I thought this `$errors = [];` puts it in an array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:31:15.257", "Id": "482800", "Score": "0", "body": "Oh wait sorry. I was paying attention close enough" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:31:37.793", "Id": "482801", "Score": "0", "body": "I thought that went around collecting the errors if there are any ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:32:29.073", "Id": "482803", "Score": "0", "body": "Now, *run your code* and see whether it does *anything* sensible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:36:27.940", "Id": "482804", "Score": "0", "body": "Oh wow it doesn't. So I should remove the whole thing ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:37:03.760", "Id": "482805", "Score": "0", "body": "Wowww. I see what you meant now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:38:18.053", "Id": "482806", "Score": "0", "body": "Should I use echo instead of the errors array ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T13:05:37.503", "Id": "482810", "Score": "0", "body": "Actually, I explained what should be done in my review" } ]
[ { "body": "<ol>\n<li><p>Every other condition (for user input validation) adds to the <code>errors</code> array, whereas password matching simply does an <code>echo</code>?</p>\n<pre><code> if ($pw !== $pw2) {\n echo &quot;Your passwords do not match&quot;;\n }\n</code></pre>\n</li>\n<li><p>When checking for existing username/email, you don't really need to fetch the associated row itself. You can use <a href=\"https://www.php.net/manual/en/mysqli-result.num-rows.php\" rel=\"nofollow noreferrer\">the <code>num_rows</code></a> to check if it is <span class=\"math-container\">\\$ \\ge 1 \\$</span>. These check for existing conditions also have <code>echo</code> statements, instead of appending to the <code>errors</code> array.</p>\n</li>\n<li><p>If you're on php 5.4+, the arrays can be declared using square brackets. No need for the <code>array()</code> method:</p>\n<pre><code> $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, ['cost' =&gt; 14]);\n</code></pre>\n</li>\n</ol>\n<hr />\n<p>You generate the list/array of errors occurred during processing of the user input, but at the end, do nothing useful with it. Ideally, these errors should be returned back to the application and shown to the user so that they may update values as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T00:57:32.907", "Id": "482758", "Score": "0", "body": "If there is an error they will see it on that page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T04:17:28.690", "Id": "482764", "Score": "1", "body": "it's on the contrary. When checking for existing username/email, you don't really need no num rows, fetch is enough. It just makes no sense to select some data but not to fetching it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T00:55:13.603", "Id": "245779", "ParentId": "245775", "Score": "0" } }, { "body": "<p>While it is sensible to some people to precisely specify the cause of the submission failure, I prefer to return compound messages rather than a length error message and a quality error message. I would probably save on screen space (versus piling upto a dozen separate email messages on the user), and merge some responses like:</p>\n<blockquote>\n<p>First name is a required field and may only contain letters and/or digits.</p>\n</blockquote>\n<p>Also, you are repeating yourself a few times with these error messages and you can easily implement a looped battery of checks -- and it is simpler to do that within the <code>$_POST</code> array. Not only does this avoid some code bloat, you are assured to have consistent error message and reduce your chances of copy-pasting typos. (Maybe you didn't realize that you wrote <code>last name</code> in the <code>username</code> errors -- this is the kind of thing that really perplexes users!)</p>\n<p>Note: <code>ctype_alnum()</code> will return <code>false</code> on a zero-length string so the <code>!trim()</code> can be omitted.</p>\n<pre><code>$alnums = ['first_name', 'last_name', 'username']; // whitelist of required alphanumeric fields\nforeach ($alnums as $field) {\n if (!isset($_POST[$field]) || !ctype_alnum($_POST[$field])) { \n $errors[] = &quot;$field is a required field and may only contain letters and/or digits.&quot;;\n }\n}\n\nif (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {\n $errors[] = &quot;Email is a required field and must be valid.&quot;;\n}\n\nif (!isset($_POST['pw'], $_POST['pw2']) || $pw !== $pw2) {\n $errors[] = &quot;Password and Password 2 are required fields and must be identical.&quot;;\n}\n</code></pre>\n<p>Ultimately, all of these server-side checks are to protect you and your database -- NOT to help your users. For the best possible user experience (UX), you need to duplicate all of these validations with javascript onsubmit of the form. This way you inform the user as quickly as possible AND avoid making a fruitless trip to your server.</p>\n<p>You can check for unique usernames and email addresses in a single trip to the database. Because the earlier validation assures no leading or trailing whitespace, the posted data will match the respective result set values (iow, no trimming is needed).</p>\n<pre><code>if (!$errors) {\n $stmt = $con-&gt;prepare(&quot;SELECT username, email FROM users WHERE username=? OR email=?&quot;);\n $stmt-&gt;bind_param(&quot;ss&quot;, $_POST['username'], $_POST['email']);\n $stmt-&gt;execute();\n foreach ($stmt-&gt;get_result() as $row) {\n foreach (['username', 'email'] as $field) {\n if ($row[$field] == $_POST[$field]) {\n $errors[] = &quot;Sorry, the submitted $field is already in use.&quot;;\n }\n }\n }\n}\n</code></pre>\n<p>Once you have fully validated all incoming data as valid, THEN you can happily insert the new user into your database and save the SESSION data. By the way, I don't recommend changing the naming convention from <code>username</code> to <code>id</code>.</p>\n<p>If any of the checkpoints are failed then present your <code>$errors</code>. As already pointed out, you are not actually displaying your error messages. In simplest terms, you <em>could</em> create <code>&lt;div&gt;</code> tags as you loop.</p>\n<pre><code>if (!$errors) {\n $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, ['cost' =&gt; 14]);\n $stmt = $con-&gt;prepare(&quot;INSERT INTO users (first_name, last_name, username, email, pw) VALUES (?, ?, ?, ?, ?)&quot;);\n $stmt-&gt;bind_param(\n &quot;sssss&quot;,\n $_POST['first_name'],\n $_POST['last_name'],\n $_POST['username'],\n $_POST['email'],\n $_POST['pw']\n );\n $stmt-&gt;execute();\n \n $_SESSION[&quot;username&quot;] = $_POST['username']; // I always expect an id to be an integer\n header(&quot;Location: ../../index.php&quot;);\n exit();\n}\n\nforeach ($errors as $error) {\n echo &quot;&lt;div class=\\&quot;error\\&quot;&gt;$error&lt;/div&gt;&quot;;\n}\n</code></pre>\n<p>None of the above snippets have been tested; I make no guarantees that they will work &quot;out of the box&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T09:06:44.027", "Id": "483432", "Score": "0", "body": "Thank you for suggesting the `trim()` in my snippet, @YourCommonSense. I do, however, deliberately use the result set object directly in the loop to avoid calling any fetching functions. I have just tested my technique locally to make sure that it works on result sets with and without rows. I do not like to use `fetchAll()` unless I am performing result set processing in a different \"layer\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T09:07:55.033", "Id": "483433", "Score": "0", "body": "My bad I completely forgot that result is iterable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T12:19:04.090", "Id": "483442", "Score": "0", "body": "I've thought a bit more about it and I've rolled back the looped trims too because the `ctype_alnum()` and email validation will rule out leading and trailing whitespaces as well as empty values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T12:27:25.613", "Id": "483443", "Score": "0", "body": "My bad again I didn't think of it" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T07:45:27.527", "Id": "246065", "ParentId": "245775", "Score": "1" } }, { "body": "<p>Some thoughts:</p>\n<p>One thing I liked is the null coalescing operator (??). If I'm not wrong it's one of those new features in PHP7.</p>\n<h1>Clumsy redirect</h1>\n<pre><code>header('Location: ../../index.php');\n</code></pre>\n<p>Use a full (absolute) URL:</p>\n<pre><code>header('Location: https://www.yoursite.com/index.php');\n</code></pre>\n<p>In fact this is even stipulated in RFCs like 2616, for good reasons.\nOtherwise the browser is left to interpret what you mean. In practice the browser will use the current URL to determine the destination but you are relying on the browser to &quot;guess&quot; what the correct location should be. Avoid ambiguity.</p>\n<p>The root URL for your site should be defined as a constant in your application. Then all you have to do is append the desired page to the root URL to perform the redirect.</p>\n<p>Use absolute URLs for the links on your site too. Speaking of relative links, be aware there is an HTML <a href=\"https://www.w3schools.com/tags/tag_base.asp\" rel=\"nofollow noreferrer\"><code>&lt;base&gt;</code> tag</a>.</p>\n<h1>Internationalization is lacking</h1>\n<p>I have the impression that your code is not character set-aware. Have you ever thought about accents ?</p>\n<p>This is an arbitrary decision:</p>\n<pre><code>if (!ctype_alnum($first_name)) {\n $errors[] = &quot;Invalid first name, it only may contain letters or digits&quot;;\n}\n</code></pre>\n<p>Why not allow more characters like apostrophes ? What if my name is Sarah O'Connor or Jean-Michel Jarre ? I cannot register on your site ?\nThe bigger problem is that you are forcing users to use Latin characters whereas they might want to use Arab script or Chinese characters or whatever. Lots of people are <strong>not</strong> comfortable with ASCII. Likewise, you would struggle on a Chinese keyboard.</p>\n<p>Embrace <strong>Unicode</strong> now. Even if you focus on a narrow audience of native English speakers, people are going to post non-ASCII characters in comments anyway (think about emojis). So your script should handle Unicode, and the database should store the data properly so that it can be rendered as it was typed in. If you garble the comments of users they will be unhappy.</p>\n<p>And in fact, your HTML pages probably have a content-encoding already, if not UTF-8 it might be ISO-8859-1 or something like that - I would check. This is an important detail because it dictates how your server will receive the form data.</p>\n<hr />\n<h1>Breaking it up</h1>\n<p>I would also break up the code in small <strong>functions</strong> (I must have said that lots of times), for example one function that validates the input, another one that registers the user in the DB. Your functions can return a boolean value or an array of errors. Or they can be implemented as classes.</p>\n<p>It makes the code more manageable and you can also move the functions to <strong>include files</strong> to declutter that file. You don't want to scroll a page that is 5000 lines long. The more code you add, the more tedious your job becomes. And the code becomes ugly.</p>\n<p>Believe me, you are going to add a lot more code to have a decently-working application (if you don't lose motivation in the meantime). I do more Python these days, but I usually avoid having more than 400 lines in a single file. Smaller files are more manageable. Right now you have only 110 lines but wait.</p>\n<p>And in fact, after registration it is customary to send an <strong>E-mail</strong> (hint: another template), with a link to be clicked to verify the E-mail. So there will be more logic involved in the registration process.</p>\n<p>So I would probably ditch this:</p>\n<pre><code>$_SESSION[&quot;id&quot;] = $_POST['username'];\n</code></pre>\n<p>because I don't want the user to be logged in (have a valid session) and able to post until they have actually verified their E-mail (but where is <code>session_start</code> ?). I would rename the session variable <code>$_SESSION[&quot;username&quot;]</code> to be consistent, unless you wanted to use the newly-created user ID instead.</p>\n<hr />\n<p>I have said it before, but <strong>frameworks</strong> exist for a reason: to relieve developers of complexity and avoid reinventing the wheel. Although it is good to have &quot;low-level&quot; understanding of how things work under the hood, one has to keep pace with modern development.</p>\n<p>Another benefit would be to use <strong>templates</strong> to better separate presentation from logic. Mixing HTML with PHP (or other code) is ugly. To be honest showing something like this to a user is a bit terse:</p>\n<pre><code>if ($row) {\n echo &quot;That email is already in use&quot;;\n die();\n}\n</code></pre>\n<p>In 2020 people are normally expecting a good-looking HTML page, with alerts, colors, images and all that stuff. Good presentation is important. You already have the page, you just have to show errors when and if they occur.</p>\n<hr />\n<p>One suggestion: look at open-source forum software, analyze the code, and see how it's done. Don't always try to reinvent the wheel. I am not saying that you should blindly copy from other people, no the point is to learn from others and improve where you can. Yes, you will find bad stuff too but hopefully you will recognize it. You learn a lot by looking at other people's code because it makes you think about why they did this or that. I myself am never satisfied with my code, I think code can always be improved.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T09:32:11.590", "Id": "483521", "Score": "0", "body": "I don't know if I would call the null coalescing operator \"new\". It was part of PHP7 https://www.php.net/manual/en/migration70.new-features.php . PHP7 was released on Dec 3, 2015 https://www.php.net/releases/index.php and its end of life was Jan 10, 2019. https://www.php.net/eol.php" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T21:21:47.097", "Id": "246096", "ParentId": "245775", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T23:38:52.090", "Id": "245775", "Score": "2", "Tags": [ "php", "mysql", "mysqli" ], "Title": "Receiving a user's registration submission and inserting row into database #2" }
245775
<p>This week I published a project that aims to enable sharing Jekyll built pages on various social media platforms, without unnecessarily degrading client privacy; ie. it does <strong>not</strong> call-out to those third-party sites unless a client actively clicks a share link.</p> <p>Currently supported sites are:</p> <ul> <li><p>Facebook</p> </li> <li><p>Linked-In</p> </li> <li><p>Reddit</p> </li> <li><p>Twitter</p> </li> </ul> <hr /> <h2>Questions</h2> <ul> <li><p>Are there any features for modification that need to be added?</p> </li> <li><p>Got suggestions for making Liquid code easier to extend?</p> </li> <li><p>Is a <em>must have</em> missing from the current listing of social media sites?</p> </li> </ul> <hr /> <h2>Requirements</h2> <p>The source code and setup instructions are intended for those utilizing <a href="https://jekyllrb.com" rel="nofollow noreferrer" title="Home page for Jekyll">Jekyll</a> built sites on GitHub Pages. The Jekyll site has <a href="https://jekyllrb.com/docs/github-pages/" rel="nofollow noreferrer" title="Jekyll documentation for GitHub Pages">documentation</a> regarding GitHub Pages, and GitHub has further <a href="https://docs.github.com/en/github/working-with-github-pages/creating-a-github-pages-site-with-jekyll" rel="nofollow noreferrer" title="GitHub documentation for Jekyll">documentation</a> regarding Jekyll.</p> <hr /> <h2>Setup</h2> <p>The <a href="https://github.com/liquid-utilities/includes-share-page/blob/main/.github/README.md" rel="nofollow noreferrer" title="Documentation for includes-share-page project"><em><code>ReadMe</code></em></a> file contains more detailed instructions for setup, but the TLDR is as follows.</p> <ul> <li>Change current working directory to a repository utilizing Jekyll to build static web pages...</li> </ul> <pre><code>cd ~/git/hub/&lt;name&gt;/&lt;repo&gt; </code></pre> <ul> <li>Check-out the <code>gh-pages</code> branch and make directory path for including modules...</li> </ul> <pre><code>git checkout gh-pages mkdir -p _includes/modules </code></pre> <ul> <li>Add this project as a Git Submodule</li> </ul> <pre><code>git submodule add -b 'main'\ --branch 'includes-share-page'\ 'https://github.com/liquid-utilities/includes-share-page.git'\ '_includes/modules/includes-share-page' </code></pre> <blockquote> <p><strong>Notice</strong>, for GitHub Pages one must use the <code>https</code> URL for Git Submodules</p> </blockquote> <ul> <li>Add an <code>include</code> statement to your site's layout, eg...</li> </ul> <p><a href="https://github.com/liquid-utilities/includes-share-page/blob/gh-pages/_layouts/post.html" rel="nofollow noreferrer" title="Modified source code for page layout from `jekyll/minima` theme"><strong><code>_layouts/post.html</code></strong></a></p> <pre><code>--- layout: default license: MIT source: https://raw.githubusercontent.com/jekyll/minima/v2.0.0/_layouts/post.html --- &lt;article class=&quot;post&quot; itemscope itemtype=&quot;http://schema.org/BlogPosting&quot;&gt; &lt;header class=&quot;post-header&quot;&gt; &lt;h1 class=&quot;post-title&quot; itemprop=&quot;name headline&quot;&gt;{{ page.title | escape }}&lt;/h1&gt; &lt;p class=&quot;post-meta&quot;&gt;&lt;time datetime=&quot;{{ page.date | date_to_xmlschema }}&quot; itemprop=&quot;datePublished&quot;&gt;{{ page.date | date: &quot;%b %-d, %Y&quot; }}&lt;/time&gt;{% if page.author %} • &lt;span itemprop=&quot;author&quot; itemscope itemtype=&quot;http://schema.org/Person&quot;&gt;&lt;span itemprop=&quot;name&quot;&gt;{{ page.author }}&lt;/span&gt;&lt;/span&gt;{% endif %}&lt;/p&gt; &lt;/header&gt; &lt;div class=&quot;post-content&quot; itemprop=&quot;articleBody&quot;&gt; {{ content }} &lt;/div&gt; {%- unless page.share == false -%} {% include modules/includes-share-page/share-page.html %} {%- endunless -%} {% if site.disqus.shortname %} {% include disqus_comments.html %} {% endif %} &lt;/article&gt; </code></pre> <ul> <li>Commit added Git Submodule and theme modifications...</li> </ul> <pre><code>git add _layouts/post.html git commit -F- &lt;&lt;'EOF' :heavy_plus_sign: Adds `liquid-utilities/includes-share-page#1` submodule **Adds** - `.gitmodules`, tracks submodules AKA Git within Git _fanciness_ - `_modules_/includes-share-page`, Builds list of links for sharing on social media sites - `_layouts/post.html`, modified default layout from `jekyll/minima` theme EOF </code></pre> <hr /> <h2>Usage</h2> <p>Configure site wide defaults...</p> <p><a href="https://github.com/liquid-utilities/includes-share-page/blob/gh-pages/_config.yml" rel="nofollow noreferrer" title="Full example Jekyll build configuration file"><strong><code>_config.yml</code> (snip)</strong></a></p> <pre><code>share: disable_linkedin: true figcaption: Share this elsewhere via... </code></pre> <ul> <li>Use standard FrontMatter configurations for the selected layout, modifying any site level defaults on a per-page basis...</li> </ul> <p><a href="https://github.com/liquid-utilities/includes-share-page/blob/gh-pages/_posts/2020-07-19-frontmatter-share.md" rel="nofollow noreferrer" title="Example MarkDown file that customizes list of links for sharing a page elsewhere"><strong><code>_posts/2020-07-19-frontmatter-share.md</code> (FrontMatter)</strong></a></p> <pre><code>--- layout: post title: Example Post description: 'Tests list generated by `includes-share-page/share-page.html` project' categories: programming webdev date: 2020-07-19 15:23:03 -0700 share: disable_linkedin: true text: Customized text for when someone shares a link to this post --- </code></pre> <p>A <a href="https://liquid-utilities.github.io/includes-share-page/2020/07/19/frontmatter-share.html" rel="nofollow noreferrer" title="Live demo of built page share list of links"><em>live</em> example</a> of output above is hosted thanks to GitHub Pages, the resulting HTML for above configurations is similar to...</p> <p><strong><code>includes-share-page/2020/07/19/frontmatter-share.html</code> (snip)</strong></p> <pre><code>&lt;figure class=&quot;social-share__container&quot;&gt; &lt;figcaption&gt;Share this elsewhere via...&lt;/figcaption&gt; &lt;ul class=&quot;social-share__list&quot;&gt; &lt;li class=&quot;social-share__item&quot;&gt; &lt;a href=&quot;https://www.facebook.com/sharer.php?u=https%3A%2F%2Fauthor.github.io%2Frepo-name%2Fprogramming%2Fwebdev%2F2020%2F07%2F06%2Fexample-post.html&quot; class=&quot;social-share__link facebook-share fa fa-facebook&quot; data-name=&quot;Facebook&quot;&gt; Facebook &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;social-share__item&quot;&gt; &lt;a href=&quot;https://reddit.com/submit?url=https%3A%2F%2Fauthor.github.io%2Frepo-name%2Fprogramming%2Fwebdev%2F2020%2F07%2F06%2Fexample-post.html&amp;title=Example%20Post&quot; class=&quot;social-share__link reddit-share fa fa-reddit&quot; data-name=&quot;Reddit&quot;&gt; Reddit &lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;social-share__item&quot;&gt; &lt;a href=&quot;https://www.twitter.com/intent/tweet?url=https%3A%2F%2Fauthor.github.io%2Frepo-name%2Fprogramming%2Fwebdev%2F2020%2F07%2F06%2Fexample-post.html&amp;hashtags=programming,webdev&amp;text=Customized%20text%20for%20when%20someone%20shares%20a%20link%20to%20this%20post&quot; class=&quot;social-share__link twitter-share fa fa-twitter&quot; data-name=&quot;Twitter&quot;&gt; Twitter &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/figure&gt; </code></pre> <ul> <li>Commit changes and push to GitHub...</li> </ul> <pre><code>git add _posts/2020-07-19-frontmatter-share-page.md git commit -m ':memo: Adds post FrontMatter HCard' git push origin gh-pages </code></pre> <hr /> <h2>Source Code</h2> <p><a href="https://github.com/liquid-utilities/includes-share-page/blob/main/share-page.html" rel="nofollow noreferrer" title="Main source code for includes-share-page project"><strong><code>share-page.html</code></strong></a></p> <pre><code>{% capture workspace__share_page %} {% comment %} --- version: 0.0.1 license: AGPL-3.0 author: S0AndS0 --- {% endcomment %} {% assign share__escaped__page_url = page.url | absolute_url | url_param_escape %} {% assign share__escaped__page_title = page.title | url_param_escape %} {% assign share__element_class_block = page.share.element_class_block | default: 'social-share' %} {% assign share__text = page.share.text | default: page.description | default: page.excerpt | default: nil %} {% assign share__figcaption = page.share.figcaption %} {% unless share__figcaption == false or share__figcaption %} {% assign share__figcaption = site.share.figcaption %} {% endunless %} {% assign share__disable_text = page.share.disable_text | default: site.share.disable_text | default: false %} {% assign share__disable_facebook = page.share.disable_facebook | default: site.share.disable_facebook %} {% assign share__disable_linkedin = page.share.disable_linkedin | default: site.share.disable_linkedin %} {% assign share__disable_reddit = page.share.disable_reddit | default: site.share.disable_reddit %} {% assign share__disable_twitter = page.share.disable_twitter | default: site.share.disable_twitter %} {% assign share__tags = page.tags %} {% unless share__tags == false or share__tags %} {% assign share__tags = page.categories %} {% endunless %} {% unless share__tags == false or share__tags %} {% assign share__tags = page.category | split: ' ' %} {% endunless %} {% if share__tags %} {% assign share__escaped__hash_tags = nil %} {% for tag in share__tags %} {% if share__escaped__hash_tags %} {% capture share__escaped__hash_tags %}{{ share__escaped__hash_tags }},{{ tag | url_param_escape }}{% endcapture %} {% else %} {% capture share__escaped__hash_tags %}{{ tag | url_param_escape }}{% endcapture %} {% endif %} {% endfor %} {% endif %} &lt;figure class=&quot;{{ share__element_class_block }}__container&quot;&gt; {% unless share__figcaption == false %} {% if figcaption %} &lt;figcaption&gt;{{ share__figcaption }}&lt;/figcaption&gt; {% else %} &lt;figcaption&gt;Share via:&lt;/figcaption&gt; {% endif %} {% endunless %} &lt;ul class=&quot;{{ share__element_class_block }}__list&quot;&gt; {% comment %} Parameters `u` {% endcomment %} {% unless share__disable_facebook %} &lt;li class=&quot;{{ share__element_class_block }}__item&quot;&gt; &lt;a href=&quot;https://www.facebook.com/sharer.php?u={{ share__escaped__page_url }}&quot; class=&quot;{{ share__element_class_block }}__link facebook-share fa fa-facebook&quot; data-name=&quot;Facebook&quot;&gt; {% unless share__disable_text %}Facebook{% endunless %} &lt;/a&gt; &lt;/li&gt; {% endunless %} {% comment %} Parameters `url` {% endcomment %} {% unless share__disable_linkedin %} &lt;li class=&quot;{{ share__element_class_block }}__item&quot;&gt; &lt;a href=&quot;https://www.linkedin.com/sharing/share-offsite?url={{ share__escaped__page_url }}&quot; class=&quot;{{ share__element_class_block }}__link linkedin-share fa fa-linkedin&quot; data-name=&quot;LinkedIn&quot;&gt; {% unless share__disable_text %}LinkedIn{% endunless %} &lt;/a&gt; &lt;/li&gt; {% endunless %} {% comment %} Parameters `url` `title` {% endcomment %} {% unless share__disable_reddit %} &lt;li class=&quot;{{ share__element_class_block }}__item&quot;&gt; &lt;a href=&quot;https://reddit.com/submit?url={{ share__escaped__page_url }}&amp;title={{ share__escaped__page_title }}&quot; class=&quot;{{ share__element_class_block }}__link reddit-share fa fa-reddit&quot; data-name=&quot;Reddit&quot;&gt; {% unless share__disable_text %}Reddit{% endunless %} &lt;/a&gt; &lt;/li&gt; {% endunless %} {% comment %} Parameters `url` `text` `via` `hashtags` Note `via` == User ID, which is not applicable here {% endcomment %} {% unless share__disable_twitter %} {% if share__text %} {% assign twitter_text = share__text | truncate: 140 | url_encode %} {% endif %} {% assign twitter_query_string = 'url=' | append: share__escaped__page_url %} {% if share__escaped__hash_tags %} {% assign twitter_query_string = twitter_query_string | append: '&amp;hashtags=' | append: share__escaped__hash_tags %} {% endif %} {% if twitter_text %} {% assign twitter_query_string = twitter_query_string | append: '&amp;text=' | append: twitter_text %} {% endif %} &lt;li class=&quot;{{ share__element_class_block }}__item&quot;&gt; &lt;a href=&quot;https://www.twitter.com/intent/tweet?{{ twitter_query_string }}&quot; class=&quot;{{ share__element_class_block }}__link twitter-share fa fa-twitter&quot; data-name=&quot;Twitter&quot;&gt; {% unless share__disable_text %}Twitter{% endunless %} &lt;/a&gt; &lt;/li&gt; {% endunless %} &lt;/ul&gt; &lt;/figure&gt; {% endcapture %}{%- if workspace__share_page -%}{{ workspace__share_page | strip | strip_newlines }}{%- endif -%}{% assign workspace__share_page = nil %} </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T01:08:12.087", "Id": "245780", "Score": "2", "Tags": [ "html", "template", "jekyll", "liquid" ], "Title": "Liquid includes Share Page" }
245780
<p>(following up from <a href="https://codereview.stackexchange.com/questions/245670/scan-a-directory-for-files-and-load-it-in-memory-efficiently">here</a>)</p> <p>I am working on a little project where I need to scan all the config files present in a folder on the disk and load it in memory. Below are the steps:</p> <ul> <li>On the disk there is already a default <code>Records</code> folder which has all the default config files present. This is to fallback if <code>loadDefaultFlag</code> is enabled. We will never overwrite this config or delete at all.</li> <li>There are also new config files present as a tar.gz file (max 100 MB size) in a remote url location which I need to download and store it on disk in secondary location only if <code>loadDefaultFlag</code> is disabled.</li> </ul> <p><strong>During Server startup</strong></p> <p>During server startup I need to either load local files from default <code>Records</code> folder or remote files by downloading it from remote server (and storing it in new secondary location) and then using it in memory.</p> <pre><code>{&quot;loadDefaultFlag&quot;:&quot;false&quot;, &quot;remoteFileName&quot;:&quot;abc-123.tgz&quot;, &quot;reload&quot;:&quot;false&quot;} </code></pre> <p>For example: server started up and loaded <code>abc-123.tgz</code> config in memory.</p> <p><strong>After server startup</strong></p> <p>Case 1:</p> <p>After server started up with some configs <code>(abc-123.tgz)</code> then someone from outside can tell us to download new configs from remote location again or go back and use default local configs from <code>Records</code> folder.</p> <pre><code>{&quot;loadDefaultFlag&quot;:&quot;true&quot;, &quot;remoteFileName&quot;:&quot;abc-123.tgz&quot;, &quot;reload&quot;:&quot;false&quot;} </code></pre> <p>If <code>loadDefaultFlag</code> is true, then it means someone is telling from outside to load configs from default <code>Records</code> folder in memory so once this is changed, all machines will switch to use local configs in memory.</p> <p>Case 2:</p> <p>Second case can be someone telling to download new remote configs as we have new configs available that we should use now.</p> <pre><code>{&quot;loadDefaultFlag&quot;:&quot;false&quot;, &quot;remoteFileName&quot;:&quot;abc-124.tgz&quot;, &quot;reload&quot;:&quot;false&quot;} </code></pre> <p>so now all machines will download <code>abc-124.tgz</code> onto the disk but they won't switch to these new configs yet in memory unless someone is instructing them from outside to start using new configs in memory. Save method actually switches config in memory from old to new. And that flag to switch to new config is <code>reload</code> - once that is true then all machines will switch to use new <code>abc-124.tgz</code> configs in memory.</p> <p><code>Records</code> folder which has default configs is just a backup and not meant to be used in regular cases.</p> <p>Below is my code:</p> <pre><code>public class RecordManager { private const string _remoteUrl = &quot;remote-url-from-where-to-download-new-configs&quot;; private static string _remoteFileName; private const string SecondaryLocation = &quot;SecondaryConfigs&quot;; private readonly IConfiguration _configuration; private readonly string _localPath; private IEnumerable&lt;RecordHolder&gt; _records; public enum ConfigLocation { System, Local, Remote } public RecordManager(IConfiguration configuration, string localPath) { if(configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if(localPath?.Length == 0) { throw new ArgumentNullException(nameof(localPath)); } _localPath = localPath; _configuration = configuration; ChangeToken.OnChange(configuration.GetReloadToken, _ =&gt; ConfigChanged(), new object()); } public RecordManager(IConfiguration configuration) : this(configuration, &quot;Records&quot;) { } public RecordManager LoadConfigurationsFrom(ConfigLocation location) { switch(location) { case ConfigLocation.Remote: _records = GetConfigFromServer(); break; case ConfigLocation.Local: _records = GetConfigFromLocalFiles(); break; case ConfigLocation.System: _records = IsConfigFromServer() ? GetConfigFromServer() : GetConfigFromLocalFiles(); break; } return this; } public void Save() { // now load `_records` configs in memory here // only called once you are ready to switch } private bool IsConfigFromServer() { string configValue = configuration[&quot;configKey&quot;]; if (string.IsNullOrWhiteSpace(configValue)){ return false; } var dcc = JsonConvert.DeserializeObject&lt;RecordPojo&gt;(configValue); if(!bool.TryParse(dcc.loadDefaultFlag?.ToString(), out bool loadDefaultFlag)) { return false; } _remoteFileName = dcc.remoteFileName; return !loadDefaultFlag &amp;&amp; !string.IsNullOrWhiteSpace(dcc.remoteFileName); } // download tar.gz file from remote server, store it on disk in secondary location // uncompress tar.gz file, read it and return RecordHolder list back. private IEnumerable&lt;RecordHolder&gt; GetConfigFromServer() { var isDownloaded = _fileHelper.Download($&quot;{_remoteUrl}{_remoteFileName}&quot;, _secondaryLocation); if(!isDownloaded) { yield return default; } var isExtracted = _fileHelper.ExtractTarGz(_remoteFileName, _directory); if(!isExtracted) { yield return default; } foreach(var configPath in _fileHelper.GetFiles(directory)) { if(!File.Exists(configPath)) { continue; } var fileDate = File.GetLastWriteTimeUtc(configPath); var fileContent = File.ReadAllText(configPath); var pathPieces = configPath.Split(System.IO.Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); var fileName = pathPieces[pathPieces.Length - 1]; yield return new RecordHolder { Name = fileName, Date = fileDate, JDoc = fileContent }; } } private IEnumerable&lt;RecordHolder&gt; GetConfigFromLocalFiles() { // read config files already present in default &quot;Records&quot; folder // and return RecordHolder list back. } // this can be improved a lot to achieve below cases in proper way private void ConfigChanged() { string configValue = _configuration[&quot;configKey&quot;]; if (string.IsNullOrWhiteSpace(configValue)) { return; } var dcc = JsonConvert.DeserializeObject&lt;ConsulConfig&gt;(configValue); bool.TryParse(dcc.loadDefaultFlag?.ToString(), out bool loadDefaultFlag); bool.TryParse(dcc.reloadConfig?.ToString(), out bool reloadConfig); _remoteFileName = dcc.remoteFileName; if (switchConfig) { Save(); } if (loadDefaultFlag) { _records = GetConfigFromLocalFiles(); } else { _records = GetConfigFromServer(); } } } </code></pre> <p>This is how I use it as a fluent api and during server startup this will be called as it is:</p> <pre><code>new RecordManager(configuration) .LoadConfigurationsFrom(RecordManager.ConfigLocation.Remote) .Save(); </code></pre> <p><strong>Question:</strong></p> <p>Now as you can see I have a <code>ChangeToken.OnChange</code> notification enabled in my constructor where I need to do something whenever my configuration (configKey) is changed and it will invoke my <code>ConfigChanged</code> method. Basically after server startup is done and configs is loaded up in memory with above code then someone can tell us to download new configs again and then load it in memory and thats what I do in <code>ConfigChanged</code> method.</p> <p>Opting for a code review here specifically for the case when I need to reload configs again and load it in memory. I am specifically interested in the way I have designed and implemented my code for <strong><code>ConfigChanged</code></strong> method. I am sure there must be a better way to rewrite the <code>ConfigChanged</code> method code in a better way that can handle all those above cases efficiently.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:14:03.073", "Id": "482849", "Score": "1", "body": "I'm a bit confused here, how come (in case 3) you need to download the files while it should be loaded from local config? if every case will require to download the file, then there is no need to have a special case for loading from local, and you'll always go back and check the server for newer version and downloaded if any, then update current stored config locally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:16:25.860", "Id": "482851", "Score": "0", "body": "yeah I mean for case 3 - sometimes people can say lets load local config (example like when we have issues downloading from remote server or we got wrong config files on remote server) as a fallback so for case 3 it should load from local configs again in memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:19:14.960", "Id": "482853", "Score": "0", "body": "then if `loadDefaultFlag` and `reload` are true, it should go and load local config, if any exceptions occurs, then you'll need to retry loading it again, if there another exception, then you can redownload the latest version and reloaded it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:21:12.370", "Id": "482854", "Score": "0", "body": "However, if `reload` is false (in both cases local and remote), it should flag the system to prepare to update the system with the selected configuration, in which will be loaded at certain pre-configured event (say restarting for instance). (the default event in your system)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:34:37.653", "Id": "482859", "Score": "0", "body": "Idea is - Before server startup there is already a local default `Records` folder which has local configs and during server startup, it will try to load config either from local default folder or from remote server as you already know. We don't delete or override files in local default folder (Records) and once we download new files from remote server, we keep it at secondary folder always. Now server started up and working fine without any issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:34:40.987", "Id": "482860", "Score": "0", "body": "After sometime - we can tell our servers to load new configs again by changing that json config value. `loadDefaultFlag` will always be false mostly and it will only be `remoteFileName` and `reload` field will be changed mostly. People can tell us to download new configs by changing `remoteFileName` and once servers have downloaded new configs successfully in secondary location then from outside we can change `reload` to true and then all servers will switch internally to use that new configs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:40:13.650", "Id": "482862", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110863/discussion-between-dragons-and-isr5)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:16:57.263", "Id": "482876", "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)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:18:52.580", "Id": "482877", "Score": "0", "body": "@Mast I wasn't updating code to add feedback. I realized I added a wrong name of a class in my question and thats what I changed. I didn't change anything to add from the answer. It was just a class name change to real one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:27:38.453", "Id": "482878", "Score": "0", "body": "That's unfortunate, please don't touch it." } ]
[ { "body": "<p>The <code>Records</code> is a backup configuration that would be used if there is any issues on the configuration.</p>\n<p>What I think you need is the following workflow:</p>\n<ol>\n<li>On server startup, read the <code>JSON</code> configuration, download the file, and store <code>JSON</code> values statically.</li>\n<li>After server started up, if the <code>JSON</code> values have been changed, get the new values, compared them with the stored values, and execute the logic based on this comparison.</li>\n</ol>\n<p>So, to prepare that we need to add a child private class which would store the json config values. Next, add static instance of this new private class which would store the current settings and On the ConfigChanged just compare between the new file name and the current one. Then, just load the settings from local or server or return the default values.</p>\n<p>You need a separate method for loading the <code>Default</code> settings (which is the backup). So, at the end you'll have three methods for loading the configurations.</p>\n<p>here is the changes you need (I have optout the rest of the code only included the changes).</p>\n<pre><code>public class RecordManager\n{\n private static JsonConfiguation _jsonConfig; \n\n private class JsonConfiguation\n {\n public string RemoteFileName { get; set; }\n\n public bool LoadDefault { get; set; }\n\n public bool Reload { get; set; }\n\n public bool HasNewerFile(JsonConfiguation jsonConfiguation)\n {\n return !RemoteFileName.Equals(jsonConfiguation.RemoteFileName, StringComparison.InvariantCultureIgnoreCase);\n }\n\n public bool IsConfigFromServer =&gt; !LoadDefault &amp;&amp; !string.IsNullOrWhiteSpace(RemoteFileName);\n }\n\n\n \n public RecordManager(IConfiguration configuration, string localPath)\n {\n if(configuration == null) { throw new ArgumentNullException(nameof(configuration)); }\n \n if(localPath?.Length == 0) { throw new ArgumentNullException(nameof(localPath)); }\n \n _localPath = localPath;\n \n _configuration = configuration;\n \n if(_jsonConfig == null)\n _jsonConfig = GetConfigValuesFromJson();\n\n ChangeToken.OnChange(configuration.GetReloadToken, _ =&gt; ConfigChanged(), new object());\n } \n\n private JsonConfiguation GetConfigValuesFromJson()\n {\n string configValue = _configuration[&quot;configKey&quot;];\n \n if (string.IsNullOrWhiteSpace(configValue)) { throw new ArgumentNullException(nameof(configValue)); }\n\n var dcc = JsonConvert.DeserializeObject&lt;ConsulConfig&gt;(configValue);\n \n return new JsonConfiguation\n {\n RemoteFileName = dcc.remoteFileName, \n LoadDefault = bool.TryParse(dcc.loadDefaultFlag?.ToString(), out bool loadDefaultFlag) ? loadDefaultFlag : false, \n Reload = bool.TryParse(dcc.reloadConfig?.ToString(), out bool reloadConfig) ? reloadConfig : false\n };\n }\n\n \n private void ConfigChanged()\n {\n var configNew = GetConfigValuesFromJson();\n\n // fallback in case if something happened unexpectedly. \n if (_jsonConfig == null)\n {\n _jsonConfig = configNew;\n }\n \n if(configNew.IsConfigFromServer)\n {\n // if both (the current downloaded and on the remote) are different, \n // Redownload the file before going to the next step.\n // else just load the local config \n\n _records = _jsonConfig.HasNewerFile(configNew) ? GetConfigFromServer() : GetConfigFromLocalFiles();\n _jsonConfig = configNew;\n }\n else\n {\n // here it will cover if the loadDefaultFlag is true or any other issue with the configuration (like missing values)\n // it will reload the default configuration (as a reset switch). \n _records = GetDefaultConfiguration();\n _jsonConfig = configNew;\n }\n\n\n // if it requires to reload the configuration immediately\n // if not, it'll now reload the configuration, and it would be stored in this instance.\n if (configNew.Reload)\n {\n Save();\n }\n\n }\n\n private IEnumerable&lt;RecordHolder&gt; GetDefaultConfiguration()\n {\n // get the default config files already present in default &quot;Records&quot; folder\n // and return RecordHolder list back.\n } \n\n private IEnumerable&lt;RecordHolder&gt; GetConfigFromServer()\n {\n // get the config files from the server \n // and return RecordHolder list back. \n }\n \n \n private IEnumerable&lt;RecordHolder&gt; GetConfigFromLocalFiles()\n {\n // get the config files from the secondary location \n // and return RecordHolder list back.\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T02:26:25.003", "Id": "482904", "Score": "0", "body": "I see one minor error on this line - `_jsonConfig.RemoteFileName.Equals` as `cannot be accessed with an instance reference; qualify it with a type name instead`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T02:27:19.807", "Id": "482905", "Score": "0", "body": "Also I see you are using return like this `return new JsonConfiguation` but in the previous question you mentioned to use `yield return new ...`. Just wanted to see why in this case we are using differently than other way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T07:31:39.113", "Id": "482918", "Score": "0", "body": "@dragons code updated. About your `return` question, because it's returning `JsonConfiguation` and not `IEnumerable<JsonConfiguation>`. `yield` works only with `IEnumerable<T>`. I've mentioned that in my previous answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:54:07.927", "Id": "482968", "Score": "0", "body": "yeah I realized it after I commented and went back to your previous answer. It makes sense. Also that instance reference error is still there btw." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:07:28.730", "Id": "482970", "Score": "0", "body": "btw I wanted to get your opinion on my design of this json node for loading configurations in dynamic way. If you have time then we can discuss in the chat room, just to keep the comments tab clean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:24:52.413", "Id": "482973", "Score": "1", "body": "@dragons I've just found out that my code was duplicated, shame on me ;(. I've updated code, and also made a small changes to the json class. and configchanged method (i've also moved IsConfigFromServer method inside the json class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:26:43.800", "Id": "482975", "Score": "0", "body": "@dragons will do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:31:52.550", "Id": "482977", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110900/discussion-between-dragons-and-isr5)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:29:18.803", "Id": "483000", "Score": "0", "body": "Let me know once you are free, wanted to get your opinion on json config file which I am using for configuration management." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T19:46:57.090", "Id": "245834", "ParentId": "245784", "Score": "1" } } ]
{ "AcceptedAnswerId": "245834", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T02:38:59.740", "Id": "245784", "Score": "2", "Tags": [ "c#", "performance", "json.net" ], "Title": "Reload configs in memory basis on a trigger efficiently" }
245784
<p><strong>Edit</strong>: I added another configuration vector to CardView, a <code>size</code> attribute, which may be <code>.small</code> or <code>.medium</code>. As such, I had to refactor the design to create several descendent protocols of <code>CardView</code> for each attribute, and several concrete structs corresponding to each possible combinations of size and style. Here is the updated design:</p> <pre><code>// MARK: Example let example: some View = CardView2Factory.create( colors: (.red, .blue), name: &quot;My Birthday&quot;, range: .init(start: Date(), duration: 0), configuration: (size: .small, style: .inverted) ) // MARK: Factory /// A Factory class used to create a customized `CardView` class CardView2Factory { enum Size { case small, medium } enum Style { case plain, inverted } private init() {} /// Creates a new CardView. /// /// The unique combination of the configuration's `size` and `style` attributes correspond one-to-one with an internal View struct conforming to `CardView` /// /// - Parameters: /// - colors: the tuple of colors of an Event, used to form the stops of the gradient /// - name: the name of an Event /// - range: the range of an Event /// - configuration: a configuration specifying the size and style attributes of the View /// /// - Returns: A configuration-dependent CardView expressed as a View @ViewBuilder static func create(colors: (Color, Color), name: String, range: DateInterval, configuration: (size: Size, style: Style)) -&gt; some View { switch configuration { case (.small, .plain): SmallPlainCardView2(colors: colors, name: name, range: range) case (.small, .inverted): SmallInvertedCardView2(colors: colors, name: name, range: range) case (.medium, .plain): MediumPlainCardView2(colors: colors, name: name, range: range) case (.medium, .inverted): MediumInvertedCardView2(colors: colors, name: name, range: range) } } } // MARK: Main Protocol protocol CardView2: View { associatedtype Accent: ShapeStyle &amp; View associatedtype Background: ShapeStyle var colors: (Color, Color) { get } var name: String { get } var range: DateInterval { get } var headerTextColor: Color { get } var accent: Accent { get } var background: Background { get } } // MARK: Size Protocols extension CardView2 { fileprivate var dateFormatter: DateFormatter { } fileprivate var dateComponentsFormatter: DateComponentsFormatter { } fileprivate var mainText: Text { } fileprivate var shape: some Shape { } fileprivate var text: some View { } } protocol SmallCardView2: CardView2 { } extension SmallCardView2 { var body: some View { ViewA(colors, name, range, accent, etc...) } } protocol MediumCardView2: CardView2 { } extension MediumCardView2 { var body: some View { ViewB(colors, name, range, accent, etc...) } } // MARK: Style Protocols protocol PlainCardView2: CardView2 { } extension PlainCardView2 { var headerTextColor: Color { } var accent: LinearGradient { } var background: Color { } } protocol InvertedCardView2: CardView2 { } extension InvertedCardView2 { var headerTextColor: Color { } var accent: Color { } var background: LinearGradient { } } // MARK: Implementation fileprivate struct SmallPlainCardView2: SmallCardView2, PlainCardView2 { let colors: (Color, Color) let name: String let range: DateInterval } fileprivate struct SmallInvertedCardView2: SmallCardView2, InvertedCardView2 { let colors: (Color, Color) let name: String let range: DateInterval } fileprivate struct MediumPlainCardView2: MediumCardView2, PlainCardView2 { let colors: (Color, Color) let name: String let range: DateInterval } fileprivate struct MediumInvertedCardView2: MediumCardView2, InvertedCardView2 { let colors: (Color, Color) let name: String let range: DateInterval } </code></pre> <p>and here is the corresponding class diagram (albeit in Java):</p> <p><a href="https://i.stack.imgur.com/P3jlz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P3jlz.png" alt="class diagram" /></a></p> <hr /> <p>Using SwiftUI, I have multiple different Views which only differ in some style-based variables. So, I created a Protocol <code>CardView</code> to condense all the similarities in one entity. The Protocol itself inherits from <code>View</code> and implements most of the functionality including <code>var body</code>. It also has several <code>associatedtype</code>s.</p> <p>I want the client to be able to retrieve an instance of a struct that conforms to this Protocol by simply selecting a case from an enum <code>Style</code>. I decided to use the Factory pattern to do so. However, I learned that Protocols can't have static functions themselves so I had to create a new <code>CardViewFactory</code> class that had a static <code>create</code> method with a <code>style: Style</code> parameter. Another concession I had to make was that this factory method returned <code>some View</code> and not a <code>CardView</code> as would have been preferred, due to its <code>associatedtype</code> requirements.</p> <p>I'm looking for any feedback on the design of my hierarchy and implementation of the Factory pattern. Thanks!</p> <p><strong>CardViewFactory</strong></p> <pre><code>class CardViewFactory { enum Style { case plain, inverted } @ViewBuilder static func create(name: String, range: DateInterval, colors: (Color, Color), style: Style) -&gt; some View { switch style { case .plain: CardViewA(colors: colors, name: name, range: range) case .inverted: CardViewB(colors: colors, name: name, range: range) } } } </code></pre> <p><strong>CardView</strong></p> <pre><code>protocol CardView: View { associatedtype Accent: ShapeStyle &amp; View associatedtype Background: ShapeStyle var colors: (Color, Color) { get } var name: String { get } var range: DateInterval { get } var headerTextColor: Color { get } var accent: Accent { get } var background: Background { get } } extension CardView { var body: some View { EmptyView() // for example } } </code></pre> <p><strong>Example Implementation</strong></p> <pre><code>struct CardViewA: CardView { let colors: (Color, Color) let name: String let range: DateInterval let headerTextColor: Color = .black var accent: LinearGradient { LinearGradient( gradient: .init(colors: [colors.0, colors.1]), startPoint: .topTrailing, endPoint: .bottomLeading ) } let background: Color = .white } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T04:34:50.410", "Id": "245787", "Score": "2", "Tags": [ "design-patterns", "swift", "factory-method", "abstract-factory" ], "Title": "Swift Struct-based Factory Pattern" }
245787