body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a page with multiple menus. Once I hit a certain window width, I use CSS and jQuery to turn them into accordions. I also check the screen size when resizing so the accordions don't stay hidden if the user resizes the window. Since I have two window widths I need to adjust for, I am using two click events to open and close the accordions and two to check the window width.</p> <p>I could really use some help to clean up this code and combine if possible.</p> <pre><code>$('footer').find('.col-md-2 .accordion-toggle').click(function () { var width = $(window).width(); if (width &lt;= 991) { $(this).next('div').slideToggle('medium'); } }); $('footer').find('.details-wrapper .accordion-toggle').click(function () { var width = $(window).width(); if (width &lt;= 475) { $(this).next('div').slideToggle('medium'); } }); $(window).resize(function () { checkWidth(); }); function checkWidth(){ $width = $(window).width(); var locationToggle = $(".details-wrapper .accordion-toggle").next('div'); if($width &gt; 475){ $(locationToggle).show(); } else { $(locationToggle).hide(); } var accordionToggle = $(".col-md-2 .accordion-toggle").next('div'); if($width &gt; 991){ $(accordionToggle).show(); } else { $(accordionToggle).hide(); } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-29T23:48:09.270", "Id": "241463", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Combine multiple jQuery click events and functions" }
241463
<p>A stab at Project Euler Problem 11: <a href="https://projecteuler.net/problem=11" rel="nofollow noreferrer">Largest product in a grid</a></p> <pre><code>""" In the 20×20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 The product of these numbers is 26 × 63 × 78 × 14 = 1788696. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? """ import numpy as np grid = np.loadtxt("grid.txt") all_products = [] def get_horizontal(): for i in range(20): start, finish = 0, 4 while finish &lt;= 20: four_elements = grid[i, start:finish] all_products.append(np.prod(four_elements)) start += 1 finish += 1 max_horizontal = max(all_products) return max_horizontal def get_vertical(): for i in range(20): start, finish = 0, 4 while finish &lt;= 20: four_elements = grid[start:finish, i] all_products.append(np.prod(four_elements)) start += 1 finish += 1 max_horizontal = max(all_products) return max_horizontal def get_right(): for i in range(-16, 16): dgnl = np.diagonal(grid, i) start, finish = 0, 4 while finish &lt;= len(dgnl): four_elements = dgnl[start:finish] all_products.append(np.prod(four_elements)) start += 1 finish += 1 max_right = max(all_products) return max_right def get_left(): for i in range(-16, 16): dgnl = np.diagonal(np.flipud(grid), i) start, finish = 0, 4 while finish &lt;= len(dgnl): four_elements = dgnl[start:finish] all_products.append(np.prod(four_elements)) start += 1 finish += 1 max_left = max(all_products) return max_left print(max(get_horizontal(), get_left(), get_right(), get_vertical())) </code></pre> <p>Hey, I'm really not too much of a coder, I just do these challenges for fun and I was hoping that maybe some of you have an idea on how to do this challenge a little more concise? I feel like I did way to much work to solve it.</p>
[]
[ { "body": "<p><em>(Disclaimer -- I too am a beginner here and I am happy to read your comments.)</em></p>\n\n<p>The code gets repeated a lot in methods <code>get_horizontal</code>, <code>get_vertical</code>, ...</p>\n\n<p>One idea to fight this is to write a function that gets the starting position, difference in the x-axis <code>dx</code>, and difference in the y-axis <code>dy</code> (possibly also the number of numbers to multiply -- in this case 4).</p>\n\n<p>This leads to another problem that we do not want to address out of the grid. We can have another method that returns whether or not your indexes always stay inside the grid.</p>\n\n<pre><code>\"\"\" Solve Euler problem 11: https://projecteuler.net/problem=11 \"\"\"\nimport numpy as np\n\ndef all_in_grid(start_x, start_y, dif_x, dif_y, numbers):\n \"\"\"Check if all positions are in the grid.\"\"\"\n for i in range(numbers):\n if not (\n 0 &lt;= start_x + i*dif_x &lt; GRID.shape[0]\n and 0 &lt;= start_y + i*dif_y &lt; GRID.shape[1]\n ):\n return False\n return True\n\n\ndef product(start_x, start_y, dif_x, dif_y, numbers):\n \"\"\"Return multiple of the numbers in the grid.\n\n return GRID[start_x][start_y] * GRID[start_x+dif_x][start_y+dif_y]\n * ... * GRID[start_x + (numbers-1)*dif_x][start_y + (numbers-1)*dif_y]\n \"\"\"\n prod = 1\n for i in range(numbers):\n prod *= GRID[start_x + (i*dif_x)][start_y + (i*dif_y)]\n return prod\n\n\ndef max_in_direction(dif_x, dif_y, numbers=4):\n \"\"\"Return maximum in the given direction.\"\"\"\n return max(\n product(start_x=x, start_y=y, dif_x=dif_x, dif_y=dif_y, numbers=numbers)\n for x in range(GRID.shape[0])\n for y in range(GRID.shape[1])\n if all_in_grid(start_x=x, start_y=y, dif_x=dif_x, dif_y=dif_y, \nnumbers=numbers)\n )\n\n\nGRID = np.loadtxt(\"grid.txt\")\nGRID = GRID.astype(int)\n\nSOLUTION = max(\n max_in_direction(1, 0),\n max_in_direction(0, 1),\n max_in_direction(1, 1),\n max_in_direction(1, -1),\n )\nprint(SOLUTION)\n</code></pre>\n\n<p>It would probably be a good idea to convert this solution to a one which would use numpy product instead of looping in python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:00:57.693", "Id": "474464", "Score": "1", "body": "this looks very nice, thanks for the feedback. I'll revise my code and edit/PS in the revised code when I'm done. Might take a few days, I'm pretty flushed with university work right now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T14:32:15.517", "Id": "241711", "ParentId": "241468", "Score": "3" } }, { "body": "<h1>all_products</h1>\n\n<p>At the top, you initialize <code>all_products = []</code>. Then you call <code>get_horizontal()</code>, which appends products of <code>four_elements</code> to <code>all_products</code>. Then you get and return the maximum. </p>\n\n<p>Then you call <code>get_left()</code> which does the same thing ... but continues appending to the <code>all_products</code> list. When the maximum is computed, it is the maximum of both the horizontal and the left diagonals!</p>\n\n<p>In other words, you don't need to find the maximum of the horizontal, left, right and vertical results. That is already being accidentally done.</p>\n\n<pre><code>get_horizontal()\nget_left()\nget_right()\nprint(get_vertical()) # Still returns the maximum over all 4 directions!\n</code></pre>\n\n<p>You should initialize <code>all_products = []</code> inside the <code>get_left</code>, <code>get_right</code>, <code>get_horizontal</code> and <code>get_vertical</code> functions, and remove it from global scope.</p>\n\n<h1>Float or integer?</h1>\n\n<p>Your results ends in <code>.0</code>. All the numbers are integer numbers. You could load the grid as an integer matrix:</p>\n\n<pre><code>grid = np.loadtxt(\"grid.txt\", dtype='i')\n</code></pre>\n\n<p>And now the answer is generated without a decimal point.</p>\n\n<h1>Looping</h1>\n\n<p>You've written code like this 4 times:</p>\n\n<pre><code> start, finish = 0, 4\n while finish &lt;= 20:\n four_elements = ... start:finish ...\n ...\n start += 1\n finish += 1\n</code></pre>\n\n<p>This is a simple loop from <code>finish=4</code> to <code>finish=20</code> (or <code>finish=len(dgnl)</code>). Start and end always differ by 4, so you could use <code>finish - 4</code> instead of <code>start</code>. Or loop over <code>start</code> and use <code>start + 4</code> for <code>finish</code>.</p>\n\n<p>Eg)</p>\n\n<pre><code> for start in range(16 + 1):\n four_elements = ... start : start+4 ...\n ...\n</code></pre>\n\n<p>With 4 copies of the that code, 3 less lines per copy, you've saved 12 lines.</p>\n\n<h1>Flip, and flip, and flip</h1>\n\n<pre><code>def get_left():\n for i in range(-16, 16):\n dgnl = np.diagonal(np.flipud(grid), i)\n</code></pre>\n\n<p>Each time though this loop, you <code>flipud(grid)</code>. That's 32 identical flips. Maybe you'd want to save this as a temporary result:</p>\n\n<pre><code>def get_left():\n flipped_grid = np.flipud(grid)\n for i in range(-16, 16):\n dgnl = np.diagonal(flipped_grid, i)\n</code></pre>\n\n<p><strong>Question</strong>: Why 32? Perhaps you meant <code>for i in range(-16, 16 + 1):</code>? <em>You were missing a diagonal!!! Twice!!!</em></p>\n\n<h1>Call functions more than once</h1>\n\n<p>Now, <code>get_left()</code> and <code>get_right()</code> are identical, save for that initial flip. You could pass the grid into <code>get_right()</code>, and <code>get_left()</code> could pass a flipped copy to <code>get_right()</code>:</p>\n\n<pre><code>def get_right(grid):\n for i in range(-16, 16):\n dgnl = np.diagonal(grid, i)\n for start in range(len(dgnl) - 3):\n four_elements = dgnl[start:start + 4]\n all_products.append(np.prod(four_elements))\n max_right = max(all_products)\n return max_right\n\ndef get_left(grid):\n return get_right(np.flipud(grid))\n</code></pre>\n\n<h1>Call functions more than once (reprise)</h1>\n\n<p><code>get_horizontal()</code> and <code>get_vertical()</code> are duplicates also ... save for grabbing either the ith row or column. If you transposed the matrix, columns would become rows, and you could again use the same function.</p>\n\n<h1>Flip, Transpose ... Rotate!</h1>\n\n<p>If you flip the matrix, one left-up diagonals become left-down ones, but rows and columns are still rows and columns. If you transpose the matrix, rows become columns, columns become rows, but the left-up diagonals are still left-up diagonals.</p>\n\n<p>If you rotate the matrix 90 degrees, rows become columns and left-up diagonals become left-down diagonals.</p>\n\n<pre><code>rotated = np.rot90(grid)\nprint(max(get_horizontal(grid), get_horizontal(rotated), get_right(grid), get_right(rotated)))\n</code></pre>\n\n<h1>Using NumPy</h1>\n\n<p>All you've really used NumPy for is loading the grid from a file, flipping it, and extracting diagonals. It is much more powerful than that.</p>\n\n<pre><code>import numpy as np\n\ngrid = np.loadtxt(\"grid.txt\", dtype='i')\n\nprint(max(np.max(grid[ : , :-3] * grid[ : , 1:-2] * grid[ : , 2:-1] * grid[ : , 3:]),\n np.max(grid[ :-3, : ] * grid[1:-2, : ] * grid[2:-1, : ] * grid[3: , :]),\n np.max(grid[ :-3, :-3] * grid[1:-2, 1:-2] * grid[2:-1, 2:-1] * grid[3: , 3:]),\n np.max(grid[3: , :-3] * grid[2:-1, 1:-2] * grid[1:-2, 2:-1] * grid[ :-3, 3:])))\n</code></pre>\n\n<p>Note: this works for 20 x 20 matrices, and 200 x 200 matrices equally well.</p>\n\n<p>Okay, perhaps we should explain exactly what is going on there. Let's start with a 7x7 matrix, with random single-digit values:</p>\n\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; grid = np.random.randint(0, 10, (7, 7))\n&gt;&gt;&gt; grid\narray([[8, 2, 3, 9, 9, 9, 3],\n [6, 2, 8, 0, 9, 4, 3],\n [0, 6, 9, 5, 6, 8, 8],\n [8, 5, 2, 6, 3, 0, 8],\n [5, 8, 0, 6, 7, 0, 3],\n [4, 3, 1, 0, 2, 5, 5],\n [4, 9, 5, 7, 2, 6, 0]])\n</code></pre>\n\n<p><code>grid[3:, :-3]</code> will extract all the values starting at the 3rd row, and all the columns except the last 3 columns.</p>\n\n<pre><code>&gt;&gt;&gt; grid[3:, :-3]\narray([[8, 5, 2, 6],\n [5, 8, 0, 6],\n [4, 3, 1, 0],\n [4, 9, 5, 7]])\n</code></pre>\n\n<p>The <code>grid[1:-2, 2:-1]</code> extracts the 4x4 matrix one row up and one column to the right of the first:</p>\n\n<pre><code>&gt;&gt;&gt; grid[2:-1, 1:-2]\narray([[6, 9, 5, 6],\n [5, 2, 6, 3],\n [8, 0, 6, 7],\n [3, 1, 0, 2]])\n</code></pre>\n\n<p>And two rows up, two columns to the right:</p>\n\n<pre><code>&gt;&gt;&gt; grid[1:-2, 2:-1]\narray([[8, 0, 9, 4],\n [9, 5, 6, 8],\n [2, 6, 3, 0],\n [0, 6, 7, 0]])\n</code></pre>\n\n<p>And finally three rows up, three columns to the right ... in other words the top 4 rows, and the rightmost four columns:</p>\n\n<pre><code>&gt;&gt;&gt; grid[:-3, 3:]\narray([[9, 9, 9, 3],\n [0, 9, 4, 3],\n [5, 6, 8, 8],\n [6, 3, 0, 8]])\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/0YGPL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0YGPL.png\" alt=\"4 different 4x4 regions\"></a></p>\n\n<p>We can take these matrices, and multiply respective elements together:</p>\n\n<pre><code>&gt;&gt; grid[3:, :-3] * grid[2:-1, 1:-2] * grid[1:-2, 2:-1] * grid[:-3, 3:]\narray([[3456, 0, 810, 432],\n [ 0, 720, 0, 432],\n [ 320, 0, 144, 0],\n [ 0, 162, 0, 0]])\n</code></pre>\n\n<p>For instance, the top-left corners contain <code>8</code>, <code>6</code>, <code>8</code> and <code>9</code>, and the product of those is <code>8*6*8*9 = 3456</code>. Looking at the original matrix, we can see these values in a diagonal starting at row 3, column 0 and going up to row 0, column 3.</p>\n\n<p>The next diagonal contains <code>5</code>, <code>5</code>, <code>9</code>, <code>0</code>, <code>9</code>. <code>5*5*9*0 = 0</code> and <code>5*9*0*9 = 0</code>, which is the next diagonal of our product matrix.</p>\n\n<p>The largest product in that matrix?</p>\n\n<pre><code>&gt;&gt;&gt; np.max(grid[3:, :-3] * grid[2:-1, 1:-2] * grid[1:-2, 2:-1] * grid[:-3, 3:])\n3456\n</code></pre>\n\n<p>The other 3 expressions take different adjacent rectangular regions, multiply them together, and find the maximums for the other diagonal and the rows and columns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:04:47.950", "Id": "474465", "Score": "0", "body": "wow this is insane! Thank you for taking the time! I read through it and I do have one follow-up: \"Question: Why 32?\" in reference to `for in range(-16, 16)`. Why am I missing diagonals? I was trying around, trying to get familiar with the grid and calls and those where the respective starting/end points if I remember correctly.\nI will definitely revise my code based on your feedback and edit/PS in my revised code. Right now I'm pretty flushed with university work and retake exams, so it might take a few days. :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:11:55.440", "Id": "474466", "Score": "0", "body": "Remember `range(start, end)` is inclusive of the start, but exclusive of the end. So `range(-16, 16)` generates the values `[-16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]` ... the last one being 15. And the 15th diagonal is `len(np.diagonal(grid, 15)) == 5` entries long. You need to get to the 16th diagonal to get the 4 entry long diagonal. Hence, you need `range(-16, 16 + 1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:15:46.533", "Id": "474469", "Score": "0", "body": "exlusive at the end always gets gets me. thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:17:26.737", "Id": "474470", "Score": "0", "body": "But, yes, I agree. You asked for \"_a little more concise_\", and I took you from 83 lines down to 8 lines (2 of which are blank) ... quite insane." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T15:09:08.140", "Id": "241713", "ParentId": "241468", "Score": "6" } } ]
{ "AcceptedAnswerId": "241713", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T01:48:46.593", "Id": "241468", "Score": "8", "Tags": [ "python", "programming-challenge", "numpy" ], "Title": "Largest product in a grid - Project Euler 11" }
241468
<p>I'm very new to programming and I don't feel confident about the readability of this program. </p> <p>This program gets the text you copied then extracts phone numbers and email addresses in the text. Once those are extracted, you can paste them anywhere(Eg: notepad).</p> <p>Are there any ways that I can improve this code? Any suggestions will surely be appreciated. Thanks!</p> <pre><code>import pyperclip, re # Python 3 - 30/04/2020 # emailAndNumberExtractor.py - finds phone and email addresses on the clipboard emailRegex = re.compile(r'''( [a-zA-Z0-9._%+-]+ # username @ # @ symbol [a-zA-Z0-9.-]+ # domain name (\.[a-zA-Z]{2,4}) # dot something )''', re.VERBOSE) phoneRegex = re.compile(r'''( (\d{3}|\(\d{3}\))? # area code (\s|-|\.)? # separator \d{3} # first 3 digits (\s|-|\.) # separator \d{4} # last 4 digits (\s*(ext|x|ext.)\s*\d{2,5})?# extension )''', re.VERBOSE) all_emails = "\nEMAILS FOUND:\n" all_numbers = "\nNUMBERS FOUND:\n" # get copied text and paste it to text var text = str(pyperclip.paste()) # check if there are phone numbers/ emails in the text if len(emailRegex.findall(text)) &gt; 0 : for email in emailRegex.findall(text): all_emails += '\n\t' + email[0] else: all_emails += "\n\tSorry, there are no emails." if len(phoneRegex.findall(text)) &gt; 0: for num in (phoneRegex.findall(text)): all_numbers += '\n\t' + num[0] else: all_numbers += "\n\tSorry, there are no phone numbers." # Collects all numbers and emails found matches = all_numbers + "\n" + all_emails print(text) pyperclip.copy(matches) print("Copied to clipboard:") print(matches) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>There are a couple of pointers. I possibly got too ahead of myself with the solution, but hopefully, a step-by-step walkthrough clarifies everything.\nI am happy to answer any questions you have.</p>\n\n<p>The overall suggestion is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"Email and number extractor - finds phone and email addresses on the clipboard.\nPython 3 - 30/04/2020\n\"\"\"\nimport re\nfrom io import StringIO\n\nimport pyperclip\n\n\nclass PastingIO(StringIO):\n def write_items_to_string(self, items, items_name: str):\n self.write(f\"{items_name} found:\\n\\n\".upper())\n\n if items:\n for item in items:\n self.write(f\"\\t{item}\\n\")\n else:\n self.write(f\"\\n\\tSorry, there are no {items_name}\")\n\n self.write(\"\\n\") # padding newline\n\n\ndef main():\n email_regex = re.compile(\n r\"\"\"(\n [a-zA-Z0-9._%+-]+ # username\n @ # @ symbol\n [a-zA-Z0-9.-]+ # domain name\n (\\.[a-zA-Z]{2,4}) # dot something\n )\"\"\",\n re.VERBOSE,\n )\n\n phone_regex = re.compile(\n r\"\"\"(\n (\\d{3}|\\(\\d{3}\\))? # area code\n (\\s|-|\\.)? # separator\n \\d{3} # first 3 digits\n (\\s|-|\\.) # separator\n \\d{4} # last 4 digits\n (\\s*(ext|x|ext.)\\s*\\d{2,5})?# extension\n )\"\"\",\n re.VERBOSE,\n )\n\n # get copied text and paste it to text var\n # text = str(pyperclip.paste())\n text = \"\"\"\n This is sample text.\n hello@you.com\n There is nothing here.\n rofl@mao.org\n 234-654-1234 is a telephone number.\n So is 123-456-7890!\n However, 1234-32-342 is invalid.\n Hello World!\n invalid@email.world should be invalid all-together.\n Check out this email: a@b.c\n \"\"\"\n\n output = PastingIO()\n\n print(\"Working on:\", text, sep=\"\\n\")\n\n matching_targets = {\n \"numbers\": {\"regex\": phone_regex,},\n \"emails\": {\"regex\": email_regex,},\n }\n\n for target_name, target_dict in matching_targets.items():\n regex = target_dict[\"regex\"]\n target_dict[\"results\"] = [match[0] for match in regex.finditer(text)]\n output.write_items_to_string(target_dict[\"results\"], target_name)\n\n match_summary = output.getvalue()\n\n pyperclip.copy(match_summary)\n print(\"Copied to clipboard:\", match_summary, sep=\"\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<h1>Walkthrough</h1>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"Email and number extractor - finds phone and email addresses on the clipboard.\nPython 3 - 30/04/2020\n\"\"\"\n</code></pre>\n\n<p>is a <em>module docstring</em>.\nIt basically supersedes the comments of the same content that you had in your code.\nThe module docstring is more powerful.\nFor example, other people can invoke it with <code>help()</code>:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>~$ python -c \"import emailAndNumberExtractor; help(emailAndNumberExtractor)\"\nHelp on module emailAndNumberExtractor:\n\nNAME\n emailAndNumberExtractor\n\nDESCRIPTION\n Email and number extractor - finds phone and email addresses on the clipboard.\n Python 3 - 30/04/2020\n\nFUNCTIONS\n main()\n\nFILE\n ~\\emailandnumberextractor.py\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\nfrom io import StringIO\n\nimport pyperclip\n</code></pre>\n\n<p>I did not touch either the <code>re</code> import or your <code>re.compile</code> statements.\nYou will have to decide for yourself if these are correct.\nI did however include a sample <code>text</code> to match against.</p>\n\n<p><code>StringIO</code> is used here as a sort of temporary file.\nWhen you look for and find matches, these matches should be collected, ideally in a mutable sequence like a <code>list</code>.\nThis is your <em>data</em>.\nIn your code, you irretrievably intertwine that data with its display, here the <code>print</code> of a <code>str</code>.\nYou did this through string concatenation.\nBut what if you would like to forward the list of found matches somehow, i.e. use it a second time, in another context?\nYou cannot, because the data is mingled with the string.</p>\n\n<p>As such, <code>StringIO</code> will be a virtual, in-memory file for us to write to.\nIt will hold the <em>formatting</em>, i.e. indentations and newlines.\nThe data will come from somewhere else and be kept separate.\nSince we do not need a real file, this will do.\nI chose this over multi-line string formatting, since that is not straightforward to do and has many caveats.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>class PastingIO(StringIO):\n def write_items_to_string(self, items, items_name: str):\n self.write(f\"{items_name} found:\\n\\n\".upper())\n\n if items:\n for item in items:\n self.write(f\"\\t{item}\\n\")\n else:\n self.write(f\"\\n\\tSorry, there are no {items_name}\")\n\n self.write(\"\\n\") # padding newline\n</code></pre>\n\n<p>This class definition might be the trickiest part.\nDon't worry if you haven't learned about classes yet.\nIt can be understood this way:</p>\n\n<p><code>PastingIO</code>, our new custom class, is <em>inheriting</em> from <code>StringIO</code>.\nThis means that <code>PastingIO</code> will have all the functionalities of its parent, <code>StringIO</code>.\nI explained the latter earlier.\nThe reason I did this was to <em>extend</em> <code>StringIO</code> by a simple functionality.\nThis functionality is the function <code>write_items_to_string</code>.\nIf function definitions occur in classes, they are called <em>methods</em>.</p>\n\n<p>Methods are much like normal functions, but since they are methods <em>of a class</em>, they usually do something with their class.</p>\n\n<p>Now, doing something with the <em>class itself</em>, <code>PastingIO</code>, is not getting us far.\nSee, a class is like a blueprint.\nIt contains all the instructions of how something <em>should</em> look like and behave.\nBut it <em>is not yet</em> something substantial.\nA class is like a construction plan, but we are interested in the house that will be built based on that plan.\nThe plan itself is a (to us, useless) piece of paper.</p>\n\n<p>To build the \"house\", <em>instantiation</em> is needed.\nThis is done in the code when we call <code>PastingIO()</code>.\nThe parantheses are important.\nIt is the instruction to actually build an <em>object</em> from the <em>class definition</em>.\nLastly, we give this thing a name, by just assinging it to a variable (<code>output</code>).\nMore on that later.</p>\n\n<p>The object we get is like <code>StringIO</code>, but with the added functionality.\nYou will note that this functionality is much like the loops you defined to concatenate to the string.\nI created this method since those loops do identical things.\nNow, you won't have to repeat yourself anymore.\nThis is in adherence to the DRY principle: <em>don't repeat yourself</em>.</p>\n\n<p>As such, I hope <code>write_items_to_string</code> is self-explanatory.\nThe <code>self</code> just refers to the object <em>instance</em> we created, <code>output</code>.\nIt means that we act <em>on</em> <code>output</code>.\nIn this case, imagine the <code>write</code> method to just write to a file, like you do with real files using <code>with open(\"file.txt\", \"w\") as f: f.write(\"Hello\")</code>, only virtually.\nIt builds and holds our output string, including all the formatting.</p>\n\n<p>Here, a class is important to <em>hold</em> the string.\nA function alone cannot (rather: should not) <em>hold</em> onto anything (referred to as a state).</p>\n\n<hr>\n\n<p>Skipping the <code>re.compile()</code> statements, they are unchanged.\nThe <code>text</code> statement is just a sample text to work on.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>output = PastingIO()\n</code></pre>\n\n<p>This is the line mentioned above.\n<code>output</code> is now an <em>instance</em> of our custom <code>PastingIO</code> class.\nIt has all the capabilities of a <code>StringIO</code> (much like a virtual text file), with the added <code>write_items_to_string</code> <em>method</em>, capable of modifying the content of <code>output</code>.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code> matching_targets = {\n \"numbers\": {\"regex\": phone_regex,},\n \"emails\": {\"regex\": email_regex,},\n }\n</code></pre>\n\n<p>This is a nested dictionary. <code>matching_targets</code> is a dictionary, but each of its values is also a dictionary.\nThis affords us a neat and organized way to store all related data and functionalities, without repeating ourselves.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code> for target_name, target_dict in matching_targets.items():\n regex = target_dict[\"regex\"]\n target_dict[\"results\"] = [match[0] for match in regex.finditer(text)]\n output.write_items_to_string(target_dict[\"results\"], target_name)\n</code></pre>\n\n<p>This is where, finally, the business happens.\nOne key aspect I found in your code was that <code>findall</code> was called twice.\nYou <code>compile</code>d the regex outside the loops, only once, which is great.\nBut even <code>findall</code> only needs to be called once for each regex.\nNote that I replaced it with <code>finditer</code>, a simple iterator that does the same thing here.\nIt returns matches only if you ask it to (lazy stuff), which we do in a loop.</p>\n\n<p>(List) comprehensions are faster than the \"manual\" equivalent using <code>for</code> or <code>while</code> loops.\nThe list at <code>target_dict[\"results\"]</code> will hold all the found strings (well, only the first found capture group).\nNote that we iterate over <code>matching_targets</code>, and thus do both emails and numbers in one sweep.\nThe results are then found in for example <code>matching_targets[\"emails\"][\"results\"]</code>, so <em>two</em> keys are required.</p>\n\n<p>Note that this data would not strictly have to be stored in the <code>dict</code>, since we do nothing with it later on.</p>\n\n<p>The last line calls the <code>write_items_to_string</code> method of <code>output</code>.\nAt first, <code>output</code> is empty.\nWe write to it, and it retains its contents across those loops, building up a virtual text file.</p>\n\n<p>String concatenation in loops is usually a bad idea.\nStrings are immutable, that means even just appending a single letter will lead to the creation of an entirely <em>new</em> object.\nLists are mutable.\nSo a good alternative approach to what was done here would be to collect string components in a mutable sequence, like a list, and then joining them together <em>once</em> afterwards, using <code>join</code>.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>match_summary = output.getvalue()\n</code></pre>\n\n<p>just gets the text contents of the <code>output</code> object.\n<code>match_summary</code> is now a string, printed to the specifications in <code>write_items_to_string</code>.\nIf you want different newlines, indentations etc., look there.</p>\n\n<p>Note that if you did not want each item on a newline, and would be happy with printing the \"raw\" output, that is suddenly much, much easier:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>emails = [\"hello@world.org\", \"a@b.c\"]\nresult = f\"Emails found: {emails}\"\nprint(result)\n</code></pre>\n\n<p>is all that is needed:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>Emails found: ['hello@world.org', 'a@b.c']\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>pyperclip.copy(match_summary)\nprint(\"Copied to clipboard:\", match_summary, sep=\"\\n\")\n</code></pre>\n\n<p>Note that I saved a <code>print</code> call here by just separating the arguments with a comma.\nThey are separated according to the <code>sep</code> argument.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>This is a common pattern used to prevent the file from running when being imported.\nIf a Python file, i.e. module, is run <em>directly</em> as a script, as is the case here, its <code>__name__</code> attribute will be set to <code>\"__main__\"</code>.\nAs such, the <code>main()</code> function is executed, as desired.</p>\n\n<p>However, notice how in the docstring explanation above, I <code>import</code>ed your module to call <code>help</code> on it.\nIn such a case, without the <code>__name__ == \"__main__\"</code> safeguard, the module would <em>also</em> run, which would then of course be undesired.\nAs such, it is a good idea to keep modules <em>importable</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T09:53:24.083", "Id": "241483", "ParentId": "241472", "Score": "1" } } ]
{ "AcceptedAnswerId": "241483", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T03:47:04.323", "Id": "241472", "Score": "1", "Tags": [ "python", "regex" ], "Title": "Phone Number and Email Address Extractor - Is there any way to simplify this code?" }
241472
<p>I have an Outlook Module that contains the VBA Code below. The VBA code opens an Excel Add-In called TMAPAddIn.xlam, which then displays a User Form. I exported the Module and gave it to other colleagues so that they can import it to their Outlook, this allowed them to make a custom button on their Outlook Quick Access Toolbar. </p> <p>The code works great, takes about 5 seconds for the User Form to display and the code executes without a problem. The file is open as ReadOnly to ensure multiple users can run the add in at the same time, without ever having to worry about them modifying its contents. I would like to know if my code can be written better for speed / efficiency.</p> <p>I've written this code only for purposes of ensuring everyone runs and opens the latest version of TMAPAddIn.xlam, unfortunately I don't have the resources or time to develop a COM Add-In. </p> <p>Code</p> <pre><code>Sub LaunchTMAP() Dim ExApp As Object Set ExApp = CreateObject("Excel.Application") Dim informationalBox As UserForm2 Set informationalBox = New UserForm2 informationalBox.Show 'letting the user know the workbook is downloading so they dont think Outlook froze Dim ExWbk As Workbook Set ExWbk = ExApp.Workbooks.Open("Z/TMAPAddIn.xlam", ReadOnly:=True) 'Z is a network drive informationalBox.Hide ExWbk.Application.Run "Module1.example" ExApp = Nothing ExWbk = Nothing End Sub </code></pre>
[]
[ { "body": " \n\n<p>I would propose rearranging and simplifying the code down to this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub LaunchTMAP()\n '' let user know the workbook is downloading so they dont think Outlook froze\n Dim infoBox As New UserForm2\n Call infoBox.Show\n\n\n '' open excel, open the workbook, run the subroutine, then close excel\n Dim xl As New Excel.Application\n Dim wb As Excel.Workbook\n Set wb = ExApp.Workbooks.Open(\"Z/TMAPAddIn.xlam\", ReadOnly:=True) 'Z is a network drive\n Call xl.Run(\"Module1.example\")\n Call xl.Quit\n\n '' hide the userform\n Call infoBox.Hide\nEnd Sub\n</code></pre>\n\n<p>This should not make your code run any faster, but it should make it feel more responsive. By moving the infoBox dim and show to before the new excel window is openned, you make the infoBox appear earlier. This is because the 5 second delay comes from opening excel. I've added a quit call to make sure that you are closing out the excel window when oyu are done with it. I've also gone switched you away from having the <code>CreateObject</code> call, as you appear to already be using the <em>\"Microsoft Excel XX.0 Object Library\"</em> reference. I also used <code>Dim ... As New ..</code> notation where posible to reduce the number of lines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T18:40:07.727", "Id": "242711", "ParentId": "241473", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T04:50:40.613", "Id": "241473", "Score": "3", "Tags": [ "vba", "excel", "outlook" ], "Title": "Calling an Excel User Form from Outlook" }
241473
<h1>Introduction</h1> <h2>Basic Idea</h2> <p>The Sardinas-Patterson algorithm determines (in polynomial time), whether a code is uniquely decodeable or not.</p> <h2>Example</h2> <p><a href="https://i.stack.imgur.com/bQC7c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bQC7c.png" alt="enter image description here"></a></p> <p>Code 1 is not uniquely decodeable, because "100" could be "baa" or "bc".</p> <p>Now let's apply the algorithm to code 2:</p> <ol> <li>It will be checked, whether a codeword is another codeword's prefix. If so, the suffix is added to S (if the suffix does not yet exist in S). So since ’01’ is a prefix of ’011’, ’1’ is added to S. After this step, the strings ’1’, ’11’ and ’111’ are now in S.</li> <li>In this step it will be checked, whether an element in S is a prefix of a codeword (or vice versa). If this is the case, the suffix is added to S and step 2 starts again (recursive call). It will also be checked, whether a full codeword is in S. If this is the case, the method will return that the code is not uniquely decodeable. In case of Code 2, there will no other suffixes be added to S in this step.</li> <li>If step 2 terminates successfully, the code is uniquely decodeable.</li> </ol> <h2>Termination of the algorithm</h2> <p>The algorithm will always terminate, because C is a finite set of codewords, and therefore there only exits a finite number of suffixes that will be added to S.[1]</p> <p>That's an important point: You have to take care that suffixes will be only added to S, if they aren't in S yet. Otherwise, it would be not guaranteed that the algorithm will terminate.</p> <hr> <h1>My implementation</h1> <pre><code>import java.util.Arrays; public class SardinasPatterson { //C = List of codewords public boolean sardinasPatterson(String[] C) { //Creating empty array S with length 1+2+...+n int sLength = ((C.length)*(C.length + 1)) / 2; String[] S = new String[sLength]; return sardinasPatterson(C, S); } private boolean sardinasPatterson(String[] C, String[] S) { //saves first empty place in S int pivot = 0; int length = C.length; //if codeword ist prefix of another codeword, //the suffix is saved in S for(int i = 0; i &lt; length; i++) { for(int j = 0; j &lt; length; j++) { if(i != j &amp;&amp; C[i].startsWith(C[j])) { String cache = getDanglingSuffix(C[j], C[i]); if(!Arrays.stream(S).anyMatch(cache::equals)) { S[pivot] = getDanglingSuffix(C[j], C[i]); pivot++; } } } } boolean unique = uniquelyDecodeable(C, S, pivot); return unique; } private boolean uniquelyDecodeable(String[] C, String[] S, int pivot) { int cLength = C.length; for(int i = 0; i &lt; pivot; i++) { for(int j = 0; j &lt; cLength; j++) { //If Codeword is in S -&gt; Code not uniquely decodeable if(S[i].equals(C[j])) { return false; } //If an element in S is prefix of a codeword, //the suffix is saved in S else if(C[j].startsWith(S[i])) { String cache = getDanglingSuffix(S[i], C[j]); if(!Arrays.stream(S).anyMatch(cache::equals)) { S[pivot] = cache; pivot++; } } //If codeword is prefix of an element in S, the //suffix is saved in S else if(S[i].startsWith(C[j])) { String cache = getDanglingSuffix(C[j], S[i]); if(!Arrays.stream(S).anyMatch(cache::equals)) { S[pivot] = cache; pivot++; } } } } return true; } //getting suffix private String getDanglingSuffix(String prefix, String str) { String suffix = ""; for(int i = prefix.length(); i &lt; str.length(); i++) { suffix += str.charAt(i); } return suffix; } } </code></pre> <hr> <h1>Tests</h1> <p>After running some unit-tests, I think the algorithm is working completely correctly:</p> <pre><code>import org.junit.Test; import org.junit.Assert; public class Tests { @Test public void firstTest() { String[] C = {"011", "111", "0", "01"}; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, true); } @Test public void secondTest() { String[] C = {"0", "01", "11"}; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, true); } @Test public void thirdTest() { String[] C = {"0", "01", "10"}; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void fourthTest() { String[] C = {"1", "011", "01110", "1110", "10011"}; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void fifthTest() { String[] C = {"0", "1", "000000"}; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void sixthTest() { String[] C = {"00", "11", "0101", "111", "1010", "100100", "0110"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void seventhTest() { String[] C = {"0", "01", "0111", "01111", "11110"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void eigthTest() { String[] C = {"0", "01", "011", "0111"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, true); } @Test public void ninthTest() { String[] C = {"00", "00", "11"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void tenthTest() { String[] C = {"0", "10", "11"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, true); } @Test public void eleventhTest() { String[] C = {"0", "1", "00", "11"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, false); } @Test public void twelfhTest() { String[] C = {"0", "01", "011", "0111"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, true); } @Test public void thirteenthTest() { String[] C = {"00", "11", "010", "0100"} ; SardinasPatterson sp = new SardinasPatterson(); boolean test = sp.sardinasPatterson(C); Assert.assertEquals(test, true); } } </code></pre> <hr> <h1>Question</h1> <p>How can this code be improved? One of the main problems with this implementation is that it has a pretty bad time-complexity. How can this be improved?</p> <p>I would appreciate any suggestions.</p> <hr> <p>[1] Wikipedia contributors. (2018, March 6). Sardinas–Patterson algorithm. In Wikipedia, The Free Encyclopedia. Retrieved April 30, 2020, from <a href="https://en.wikipedia.org/w/index.php?title=Sardinas%E2%80%93Patterson_algorithm&amp;oldid=829124957" rel="nofollow noreferrer">https://en.wikipedia.org/w/index.php?title=Sardinas%E2%80%93Patterson_algorithm&amp;oldid=829124957</a></p>
[]
[ { "body": "<p>The Sardinas-Patterson algorithm described in wikipedia as you already said is based on the use of sets for codewords and there is an explanation for every set operation. Consequently I will use the java <code>Set</code> class for every operation involved. I start from the first defined operator:</p>\n<pre><code>In general, for two sets of strings D and N, the (left) quotient is defined as the residual words obtained from D by removing some prefix in N.\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/s9miU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s9miU.png\" alt=\"inverseNMulD\" /></a></p>\n<p>This can be implemented with a function I called <code>inverseNMulD</code> below described:</p>\n<pre><code>private static Set&lt;String&gt; inverseNMulD(Set&lt;String&gt; n, Set&lt;String&gt; d) {\n Set&lt;String&gt; set = new HashSet&lt;&gt;();\n for (String s1 : d) {\n for (String prefix : n) {\n if (s1.startsWith(prefix)) {\n set.add(s1.substring(prefix.length()));\n }\n }\n }\n return set; \n}\n</code></pre>\n<p>After you will have to define a element S succession where S1 is defined in this way:</p>\n<p><a href=\"https://i.stack.imgur.com/xFjYg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xFjYg.png\" alt=\"Initial set\" /></a></p>\n<p>This can be expressed with a function I called <code>firstSet</code> below described:</p>\n<pre><code>private static Set&lt;String&gt; firstSet(Set&lt;String&gt; c) {\n Set&lt;String&gt; set = inverseNMulD(c, c);\n set.remove(&quot;&quot;); &lt;-- I'm removing the empty string\n return set;\n}\n</code></pre>\n<p>After you have will to define how to calculate the i+1th element of your succession starting from the ith element:</p>\n<p><a href=\"https://i.stack.imgur.com/OSHot.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OSHot.png\" alt=\"Union\" /></a></p>\n<p>This can be expressed with a function I called <code>successiveSet</code> below described:</p>\n<pre><code>private static Set&lt;String&gt; successiveSet(Set&lt;String&gt; c, Set&lt;String&gt; s) {\n Set&lt;String&gt; set = inverseNMulD(c, s);\n set.addAll(inverseNMulD(s, c));\n return set;\n}\n</code></pre>\n<p>After I defined a helper function to check if the intersection of two sets is empty:</p>\n<pre><code>private boolean isEmptyIntersection(Set&lt;String&gt; set, Set&lt;String&gt; codewordsSet) {\n Set&lt;String&gt; intersection = new HashSet&lt;&gt;(set);\n intersection.retainAll(codewordsSet);\n return intersection.isEmpty();\n}\n</code></pre>\n<p>Now the explanation of the boolean method <code>sardinasPatterson</code> to check whether a given variable-length code is uniquely decodable. The algorithm computes the sets Si in increasing order of i. As soon as one of the Si contains a word from C or the empty word, then the algorithm terminates and answers that the given code is not uniquely decodable. Otherwise, once a set Si equals a previously encountered set Sj with j &lt; i, then the algorithm would enter in principle an endless loop. Instead of continuing endlessly, it answers that the given code is uniquely decodable.</p>\n<p>This can be implemented with the <code>sardinasPatterson</code> function below described:</p>\n<pre><code>public boolean sardinasPatterson(String[] codewords) {\n Set&lt;String&gt; codewordsSet = Arrays.stream(codewords).collect(Collectors.toSet());\n if (codewordsSet.size() != codewords.length) { return false; }\n Set&lt;String&gt; currentSet = firstSet(codewordsSet);\n List&lt;Set&lt;String&gt;&gt; list = new ArrayList&lt;Set&lt;String&gt;&gt;();\n list.add(currentSet);\n while (!currentSet.contains(&quot;&quot;) &amp;&amp; isEmptyIntersection(currentSet, codewordsSet)) {\n currentSet = successiveSet(codewordsSet, currentSet);\n //one set previously found is equal to current set : success!\n if (list.contains(currentSet)) { return true; } \n list.add(currentSet);\n }\n return false; //&lt;-- failure: the code is not uniquely decodable. \n}\n</code></pre>\n<p>Below the code of the class:</p>\n<pre><code>public class SardinasPatterson {\n\n private static Set&lt;String&gt; inverseNMulD(Set&lt;String&gt; n, Set&lt;String&gt; d) {\n Set&lt;String&gt; set = new HashSet&lt;&gt;();\n for (String s1 : d) {\n for (String prefix : n) {\n if (s1.startsWith(prefix)) {\n set.add(s1.substring(prefix.length()));\n }\n }\n }\n return set; \n }\n \n private static Set&lt;String&gt; firstSet(Set&lt;String&gt; c) {\n Set&lt;String&gt; set = inverseNMulD(c, c);\n set.remove(&quot;&quot;);\n return set;\n }\n \n private static Set&lt;String&gt; successiveSet(Set&lt;String&gt; c, Set&lt;String&gt; s) {\n Set&lt;String&gt; set = inverseNMulD(c, s);\n set.addAll(inverseNMulD(s, c));\n return set;\n }\n \n private boolean isEmptyIntersection(Set&lt;String&gt; set, Set&lt;String&gt; codewordsSet) {\n Set&lt;String&gt; intersection = new HashSet&lt;&gt;(set);\n intersection.retainAll(codewordsSet);\n return intersection.isEmpty();\n }\n \n public boolean sardinasPatterson(String[] codewords) {\n Set&lt;String&gt; codewordsSet = Arrays.stream(codewords).collect(Collectors.toSet());\n if (codewordsSet.size() != codewords.length) { return false; }\n Set&lt;String&gt; currentSet = firstSet(codewordsSet);\n List&lt;Set&lt;String&gt;&gt; list = new ArrayList&lt;Set&lt;String&gt;&gt;();\n list.add(currentSet);\n while (!currentSet.contains(&quot;&quot;) &amp;&amp; isEmptyIntersection(currentSet, codewordsSet)) {\n currentSet = successiveSet(codewordsSet, currentSet);\n if (list.contains(currentSet)) { return true; }\n list.add(currentSet);\n }\n return false;\n }\n}\n\n</code></pre>\n<p>As you can see at a first view code seems more complicated than your's but with use of <code>Set</code> all the controls about strings and their unicity are automatically solved and it is more strictly tied to the documentation of the algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:17:01.900", "Id": "474057", "Score": "0", "body": "First of all, thank you for your answer! Your implementation is really amazing. Could you tell me, if you found any mistakes in my implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T16:18:14.403", "Id": "474077", "Score": "1", "body": "@chrysaetos99 You are welcome, I haven't found mistakes in your implementation of the algorithm, the only problem is that without use of `Set` class you had been obliged to handle the `Set` work by yourself. Just one thing, your function `getDanglingSuffix` can return `str.substring(prefix.length(), str.length())`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T13:31:48.573", "Id": "241553", "ParentId": "241477", "Score": "2" } } ]
{ "AcceptedAnswerId": "241553", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T07:35:41.497", "Id": "241477", "Score": "5", "Tags": [ "java", "algorithm" ], "Title": "Sardinas-Patterson Algorithm" }
241477
<pre><code>const propsSelector = (props:any) =&gt; { let newProps: object = {} Object.keys(props).forEach((prop) =&gt; { if (typeof props[prop] !== 'undefined') { Object.assign(newProps, { [prop]: props[prop] }) } }) return newProps } const selectedProps:any = propsSelector(props) </code></pre> <p><strong>Is there a more efficient way to filter objects?</strong> I would love a reduce like method for objects.</p> <p><strong>Every idea or observation is welcomed!</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T16:55:19.930", "Id": "473955", "Score": "0", "body": "(I don't believe `props:any`. `propertied`?)" } ]
[ { "body": "<p>You can use <code>Object.entries</code> instead, to get an array of entries (an entry is an array of the key and the value), filter it by whether the value is undefined, then use <code>Object.fromEntries</code> to turn it back into an object:</p>\n\n<pre><code>const propsSelector = (props: object) =&gt; {\n return Object.fromEntries(\n Object.entries(props)\n .filter(([_, val]) =&gt; val !== undefined)\n );\n};\n</code></pre>\n\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 propsSelector = (props) =&gt; {\n return Object.fromEntries(\n Object.entries(props)\n .filter(([_, val]) =&gt; val !== undefined)\n );\n};\n\nconsole.log(propsSelector({\n foo: 'foo',\n bar: undefined\n}));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also:</p>\n\n<ul>\n<li>Best to type functions precisely, and <a href=\"https://itnext.io/avoiding-any-in-typescript-advanced-types-and-their-usage-691b02ac345a\" rel=\"nofollow noreferrer\">avoid using <code>any</code></a>, since that loses type safety - if you use <code>any</code> everywhere, you may as well not be using Typescript at all, to some extent. If you don't know anything about what an argument will be, type it as <code>unknown</code> and use type guards to check it inside the function.</li>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">Don't use <code>let</code></a>, always use <code>const</code> when possible</li>\n<li>When assigning a plain property to an object, no need for <code>Object.assign</code> - simple <code>=</code> assignment works just fine. (<code>newProps[prop] = props[prop];</code>)</li>\n</ul>\n\n<blockquote>\n <p>I would love a reduce like method for objects.</p>\n</blockquote>\n\n<p>You <em>can</em> use <code>reduce</code> here, but it's <a href=\"https://www.youtube.com/watch?v=qaGjS7-qWzg\" rel=\"nofollow noreferrer\">arguably not very appropriate</a> since the accumulator is the same object each time.</p>\n\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 propsSelector = (props) =&gt; {\n return Object.entries(props).reduce((a, [prop, val]) =&gt; {\n if (val !== undefined) {\n a[prop] = val;\n }\n return a;\n }, {});\n};\n\nconsole.log(propsSelector({\n foo: 'foo',\n bar: undefined\n}));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T09:43:28.790", "Id": "473909", "Score": "0", "body": "Wooow! That's a thorough answer! I would upvote you but I don't have the permission yet :)\nThank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T09:23:33.027", "Id": "241480", "ParentId": "241478", "Score": "2" } } ]
{ "AcceptedAnswerId": "241480", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T09:06:07.200", "Id": "241478", "Score": "-2", "Tags": [ "javascript", "typescript" ], "Title": "JS Typescript Object filtering" }
241478
<p>Another code for exercism, It is to convert Vec of u32 from one base to another base. Please help to make it more idiomatic, Also if this type of question is welcomed here or not.</p> <pre><code>#[derive(Debug, PartialEq)] pub enum Error { InvalidInputBase, InvalidOutputBase, InvalidDigit(u32), } pub fn convert(number: &amp;[u32], from_base: u32, to_base: u32) -&gt; Result&lt;Vec&lt;u32&gt;, Error&gt; { if from_base &lt; 2 { return Err(Error::InvalidInputBase); } if to_base &lt;2 { return Err(Error::InvalidOutputBase); } if number.iter().any(|&amp;x| x &gt; 0 &amp;&amp; x &gt;= from_base ){ return Err(Error::InvalidDigit(from_base)); } let res: u32 = number.iter().rev().enumerate().map(|(index, x)| x*from_base.pow(index as u32)).sum(); Ok(convert_back(res, to_base)) } fn convert_back(number: u32, base: u32) -&gt; Vec&lt;u32&gt;{ let mut res: Vec&lt;u32&gt; = Vec::new(); let mut inter = number as f64; loop { inter = inter as f64/base as f64; res.push((inter.fract()*base as f64).round() as u32); if inter as u32 ==0{ break } inter = inter.trunc(); } res.reverse(); res } </code></pre> <p>Some tests </p> <pre><code> fn decimal_to_binary() { let input_base = 10; let input_digits = &amp;[4, 2]; let output_base = 2; let output_digits = vec![1, 0, 1, 0, 1, 0]; assert_eq!( ayb::convert(input_digits, input_base, output_base), Ok(output_digits) ); } fn trinary_to_hexadecimal() { let input_base = 3; let input_digits = &amp;[1, 1, 2, 0]; let output_base = 16; let output_digits = vec![2, 10]; assert_eq!( convert(input_digits, input_base, output_base), Ok(output_digits) ); } fn hexadecimal_to_trinary() { let input_base = 16; let input_digits = &amp;[2, 10]; let output_base = 3; let output_digits = vec![1, 1, 2, 0]; assert_eq!( convert(input_digits, input_base, output_base), Ok(output_digits) ); } fn invalid_positive_digit() { let input_base = 2; let input_digits = &amp;[1, 2, 1, 0, 1, 0]; let output_base = 10; assert_eq!( convert(input_digits, input_base, output_base), Err(Error::InvalidDigit(2)) ); } fn output_base_is_zero() { let input_base = 10; let input_digits = &amp;[7]; let output_base = 0; assert_eq!( convert(input_digits, input_base, output_base), Err(Error::InvalidOutputBase) ); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T14:05:51.613", "Id": "473935", "Score": "0", "body": "It's considered bad form to edit the code in your questions after they're posted. The changes you've made are good, but I'd already started writing an answer!" } ]
[ { "body": "<h2>Style</h2>\n\n<p>These are in order of me thinking of them; not in order of first appearance. Sorry!</p>\n\n<h3><code>#[test]</code></h3>\n\n<p>If you mark your tests with <code>#[test]</code>, then running <code>cargo test</code> will run them. If you also mark them with <code>#[cfg(test)]</code>, then they'll only be compiled in test mode.</p>\n\n<h3>Unneeded <code>collect()</code></h3>\n\n<p><code>cargo clippy</code> is an invaluable tool. Here, it found an optimisation!</p>\n\n<pre><code>if !number.iter().filter(|&amp;x| *x &gt; 0 &amp;&amp; *x &gt;= from_base ).collect::&lt;Vec&lt;_&gt;&gt;().is_empty(){\n return Err(Error::InvalidDigit(from_base));\n}\n</code></pre>\n\n<p>It points out that <code>.collect::&lt;Vec&lt;_&gt;&gt;().is_empty()</code> should be replaced with <code>.next().is_none()</code>:</p>\n\n<pre><code>if !number\n .iter()\n .filter(|&amp;x| *x &gt; 0 &amp;&amp; *x &gt;= from_base)\n .next()\n .is_none()\n{\n return Err(Error::InvalidDigit(from_base));\n}\n</code></pre>\n\n<p>The compiler's <em>probably</em> smart enough to turn this into efficient code,<sup><a href=\"//\" rel=\"nofollow noreferrer\">[citation needed]</a></sup> but this code can be made clearer:</p>\n\n<pre><code>if number.iter().any(|&amp;x| x &gt; 0 &amp;&amp; x &gt;= from_base) {\n return Err(Error::InvalidDigit(from_base));\n}\n</code></pre>\n\n<h3>Unnecessary casting</h3>\n\n<pre><code>inter = inter as f64/base as f64;\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>inter /= base as f64;\n</code></pre>\n\n<p>and you can get rid of all of the <code>base as f64</code> bits by putting</p>\n\n<pre><code>let base = base as f64;\n</code></pre>\n\n<p>at the top of <code>convert_back</code>.</p>\n\n<p>After a quick pass through <code>cargo fmt</code> to clean up the errant spacing and expand the iterator chain to separate lines, this all looks pretty good.</p>\n\n<h2>Algorithm</h2>\n\n<p>Your algorithm is, sadly, more limited than it looks. Your use of <code>as</code> is a little risky, as casting to a smaller integer truncates it. However, that won't get to be a problem, because as soon as the <code>from_base.pow</code> ends up with a number bigger than <code>u32</code> can store, it'll panic.</p>\n\n<p>You need some kind of \"too big\" <code>Error</code> variant if you want to handle this gracefully; you could check whether <code>number.len() &gt; u32::MAX</code> (otherwise <code>as</code>'s truncation could cause issues), and then check whether all the <code>.pow</code> calls are guaranteed to work (perhaps with <code>.checked_pow</code>?), and then whether adding all the digits together will exceed the bounds of <code>u32</code>.</p>\n\n<p>Alternatively, you could make the algorithm convert via base 2³² instead of <code>u32</code>s, which would resolve the issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T14:06:17.503", "Id": "241499", "ParentId": "241486", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T10:16:59.410", "Id": "241486", "Score": "4", "Tags": [ "rust" ], "Title": "Convert to different bases" }
241486
<p>Suppose I have a list with N sorted dates and M non-overlapping sorted periods with start date, end date (inclusive), and a tax rate for example. I have to make an efficient algorithm retrieve all tax rates for all dates. If there is not period including this date it should raise an error.</p> <p>Given the brute-force approach I could have a O(N * M) with two nested loops. It is possible to break the inner loop when one date is found (maintains the code worst-case complexity). Another optimization would be to store the index of last period, since the lists are sorted, then I believe I got O(N + M). Is there a more optimal way of doing that? Maybe using other data structures?</p> <p>Working code in Python:</p> <pre><code>import collections import datetime import sys from typing import List RatePeriod = collections.namedtuple("RatePeriod", ["start_date", "end_date", "rate"]) periods = [ RatePeriod(datetime.datetime(2019, 1, 3), datetime.datetime(2019, 4, 1), 10.7), RatePeriod(datetime.datetime(2019, 4, 2), datetime.datetime(2019, 12, 2), 20.5), RatePeriod(datetime.datetime(2019, 12, 3), datetime.datetime(2020, 1, 2), 37.8), ] def get_rates(dates: List[datetime.datetime]) -&gt; List[float]: rates = [] last_period = 0 for idx, date in enumerate(dates, 1): for idx2 in range(last_period, len(periods)): period = periods[idx2] last_period = idx2 if period.start_date &lt;= date &lt;= period.end_date: rates.append(period.rate) break if len(rates) &lt; idx: sys.exit("No period found for date: {}".format(date)) return rates series = [ datetime.datetime(2019, 2, 20), datetime.datetime(2019, 3, 6), datetime.datetime(2019, 12, 14), ] result = get_rates(series) expected = [10.7, 10.7, 37.8] assert result == expected </code></pre>
[]
[ { "body": "<p>Your algorithm seems fine, it seems you brought it down in complexity enough. I have thought about it and couldn't think of anything better.</p>\n\n<p>Still, the code can be rewritten to be more Pythonic:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\nimport sys\nimport timeit\nfrom datetime import datetime as dt\nfrom typing import List\n\nRatePeriod = collections.namedtuple(\"RatePeriod\", [\"start_date\", \"end_date\", \"rate\"])\n\nperiods = [\n RatePeriod(dt(2019, 1, 3), dt(2019, 4, 1), 10.7),\n RatePeriod(dt(2019, 4, 2), dt(2019, 12, 2), 20.5),\n RatePeriod(dt(2019, 12, 3), dt(2020, 1, 2), 37.8),\n RatePeriod(dt(2020, 1, 3), dt(2020, 12, 2), 41.3),\n RatePeriod(dt(2020, 12, 3), dt(2021, 1, 2), 52.7),\n]\n\n\nseries = [\n dt(2019, 2, 20),\n dt(2019, 3, 6),\n dt(2020, 1, 5),\n dt(2020, 12, 5),\n # dt(2022, 1, 1), # error, no period found\n]\n\n\ndef get_rates(dates: List[dt]) -&gt; List[float]:\n rates = []\n last_period = 0\n for idx, date in enumerate(dates, 1):\n for idx2 in range(last_period, len(periods)):\n period = periods[idx2]\n last_period = idx2\n if period.start_date &lt;= date &lt;= period.end_date:\n rates.append(period.rate)\n break\n if len(rates) &lt; idx:\n sys.exit(\"No period found for date: {}\".format(date))\n return rates\n\n\ndef get_rates_generator(dates: List[dt]) -&gt; List[float]:\n last_period = 0\n for date in dates:\n for idx_period, period in enumerate(periods[last_period:], start=last_period):\n if period.start_date &lt;= date &lt;= period.end_date:\n last_period = idx_period\n break\n else:\n sys.exit(f\"No period found for date: {date}\")\n yield period.rate\n\n\nresult = get_rates(series)\nresult_generator = list(get_rates_generator(series))\n\nsetup = \"from __main__ import get_rates, get_rates_generator, series\"\nprint(\"Old:\", timeit.timeit(\"get_rates(series)\", setup=setup))\nprint(\"New:\", timeit.timeit(\"list(get_rates_generator(series))\", setup=setup))\n\nexpected = [10.7, 10.7, 41.3, 52.7]\n\nassert result == result_generator == expected\n</code></pre>\n\n<p>where the printed output will be somewhere in the ballpark of</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>Old: 2.3620867\nNew: 2.3765742000000003\n</code></pre>\n\n<p>aka, the rewritten function is not actually faster.\nA couple notes on the new, suggested approach:</p>\n\n<ul>\n<li>imported <code>datetime.datetime</code> as <code>dt</code> for readability; <code>from datetime import datetime</code> is likely confusing and should be avoided</li>\n<li>handling the case of not finding an item is nicely handled using <code>for</code>/<code>else</code>. In fact, it is one of the prime uses of <code>for</code>/<code>else</code>. The <code>else</code> block is run if no <code>break</code> was encountered for the entire loop. Since there is already a <code>break</code> in place, it is straightforward to implement the <code>else</code> block. This also gets rid of having to <code>enumerate</code> over <code>dates</code>.</li>\n<li>instead of building and returning a list, a generator only <em>yields</em> on request. Having found a match, the loop is broken out of and <code>yield</code> is hit. The function exits and returns to its saved state on the next iteration. As such, <code>list()</code> can be called on the generator object to exhaust it fully and receive a list, as in your code. If no full list is desired, a generator is lighter than a full list.</li>\n<li>the <code>enumerate</code> function, together with list slicing, can do what your <code>range</code> code did. This way, the new code is a bit dense on that line; since it is also verbose, I think it's manageable. I find it to be more readable.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T13:36:43.243", "Id": "473924", "Score": "1", "body": "I really liked all the comments @alex-povel. Just a thought about the imports, I also find datetime.datetime confusing, but I think it is a built-in python problem. I usually try to respect Google Python Style Guide on that and use `import datetime`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T13:49:26.267", "Id": "473928", "Score": "1", "body": "Well, nono, I mean: `from datetime import datetime` is confusing. `import datetime` and then using `datetime.datetime` is fine, as you said. Following the Google Python style guide is a good idea. My point was just that *if* `datetime.datetime` should be shortened, `from datetime import datetime` is **not** the way to go." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T13:24:35.640", "Id": "241495", "ParentId": "241487", "Score": "1" } } ]
{ "AcceptedAnswerId": "241495", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T11:29:41.037", "Id": "241487", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "complexity" ], "Title": "What is the optimal way to retrieve a list of sorted dates in a list of sorted periods in python?" }
241487
<p>I wasn't able to find a standardized source for a working example of Merge Sort.</p> <p>Each learning site had a slightly different take on the algorithm implementation, disregarding the bottom-top implementation.</p> <p>I wrote my own code for this but unsure if it's the most efficient or if efficiency can be improved?</p> <p>Any other syntax/logic improvements are welcomed to be pointed out.</p> <pre><code>def merge(left, right): i = 0 #left index j = 0 #right index sorted_list = [] while len(left) &gt; i and len(right) &gt; j: if left[i] &gt; right[j]: sorted_list.append(right[j]) j += 1 else: sorted_list.append(left[i]) i += 1 sorted_list += left[i:] + right[j:] return sorted_list def MergeSort(MyList): if len(MyList) &gt; 1: mid = len(MyList) // 2 left = MyList[mid:] right = MyList[:mid] left = MergeSort(left) right = MergeSort(right) sorted_list = merge(left, right) return sorted_list return MyList </code></pre> <p>Also, a source where I can find standardized code for most algorithms in Python would be nice? By standardized; I mean code that is deemed efficient and the most up-to-date by the Python community.</p>
[]
[ { "body": "<h1>PEP-8</h1>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> enumerates a set of rules that all Python programs should follow. Of particular note is the <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">Naming Conventions</a>, which indicates that function names and variable names should all be <code>snake_case</code>, not <code>CapitalizedWords</code>. So <code>MergeSort</code> should be renamed <code>merge_sort</code>, and <code>MyList</code> should be renamed <code>my_list</code>.</p>\n\n<h1>Private functions</h1>\n\n<p><code>merge</code> is an internal helper function for <code>MergeSort</code>. PEP-8 also recommends naming internal helpers with a leading underscore, to indicate it is private, and should not be used externally, so <code>merge</code> should be named <code>_merge</code>.</p>\n\n<h1>Repeated computations and lookups</h1>\n\n<pre><code> while len(left) &gt; i and len(right) &gt; j:\n if left[i] &gt; right[j]:\n sorted_list.append(right[j])\n j += 1\n else:\n sorted_list.append(left[i])\n i += 1\n</code></pre>\n\n<p>This code has some inefficiencies.</p>\n\n<ol>\n<li>Every iteration is recomputing <code>len(left)</code> and <code>len(right)</code>.</li>\n<li>Every iteration is performing 3 indexing operations, first looking up <code>left[i]</code> and <code>right[j]</code>, and then looking up either <code>left[i]</code> or <code>right[j]</code> depending on which branch of the <code>if</code>/<code>else</code> is taken.</li>\n</ol>\n\n<p>You only need to test <code>len(left) &gt; i</code> when <code>i</code> changes, and <code>len(right) &gt; j</code> when <code>j</code> changes:</p>\n\n<pre><code> while True:\n if left[i] &gt; right[j]:\n sorted_list.append(right[j])\n j += 1\n if len(right) &gt; j:\n break\n else:\n sorted_list.append(left[i])\n i += 1:\n if len(left) &gt; i:\n break\n</code></pre>\n\n<p>Now, the <code>len()</code> function should be called half as often, and only the part of the expression that is changing is being evaluated, and so this code, while longer, should actually run faster.</p>\n\n<p>Similarly, we can remove the repeated indexing operations, by only performing the indexing operation when the corresponding index changes:</p>\n\n<pre><code> left_value = left[i]\n right_value = right[j]\n\n while True:\n if left_value &gt; right_value:\n sorted_list.append(right_value)\n j += 1\n if len(right) &gt; j:\n break\n right_value = right[j]\n else:\n sorted_list.append(left_value)\n i += 1:\n if len(left) &gt; i:\n break\n left_value = left[i]\n</code></pre>\n\n<p>Again, more code, but it should run faster.</p>\n\n<h1>Iterators</h1>\n\n<p>The above code is complicate because we are responsible for testing if the indices get to the end of the list, looking up the values at the given indices, and incrementing the indices.</p>\n\n<p>Python has iterators, which do all of these operations for us! So the above code could simply be written as:</p>\n\n<pre><code> left_iter = iter(left)\n right_iter = iter(right)\n\n left_value = next(left_iter)\n right_value = next(right_iter)\n\n while True:\n if left_value &gt; right_value:\n sorted_list.append(right_value)\n right_value = next(right_iter)\n else:\n sorted_list.append(left_value)\n left_value = next(left_iter)\n</code></pre>\n\n<p>This takes the <code>left</code> and <code>right</code> lists, creates iterators for them, extracts the first values of each, and then adds the smaller of the two values to the <code>sorted_list</code>, and then fetches the next value from the corresponding iterator.</p>\n\n<p>The only problem is it will raise a <code>StopIteration</code> exception when one of the two iterators runs out. We just need to catch this, and add the remaining entries from the non-expired iterator. But which one? Actually this is easy, since the values for <code>left_value</code> and <code>right_value</code> haven't changed, <code>left_value &gt; right_value</code> will reveal which branch of the <code>if</code>/<code>else</code> the exception was raised in.</p>\n\n<p>The only \"tricky\" part to remember is that if the <code>next(left_iter)</code> raised an exception, then <code>right_value</code> should be added to the <code>sorted_list</code> before the rest of the values from <code>right_iter</code>, and vis-versa. <code>sorted_list.extend()</code> is an easy way of adding the remaining items from the non-expired iterator. </p>\n\n<pre><code>def _merge(left, right):\n left_iter = iter(left)\n right_iter = iter(right)\n\n sorted_list = []\n\n # These should never fail because both left &amp; right have one or more elements.\n left_value = next(left_iter)\n right_value = next(right_iter)\n\n try:\n while True:\n if left_value &gt; right_value:\n sorted_list.append(right_value)\n right_value = next(right_iter)\n else:\n sorted_list.append(left_value)\n left_value = next(left_iter)\n\n except StopIteration:\n if left_value &gt; right_value:\n sorted_list.append(left_value)\n sorted_list.extend(left_iter)\n else:\n sorted_list.append(right_value)\n sorted_list.extend(right_iter)\n\n return sorted_list\n</code></pre>\n\n<p>We've approximately double the number of lines of code in <code>_merge(left, right)</code>, but the code should be faster, since all of the indexing, is now being handled by Python itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:07:38.383", "Id": "241527", "ParentId": "241488", "Score": "2" } } ]
{ "AcceptedAnswerId": "241527", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T11:41:25.027", "Id": "241488", "Score": "2", "Tags": [ "python", "python-3.x", "sorting", "reinventing-the-wheel" ], "Title": "Merge Sort Implementation Efficiency In Python" }
241488
<p>I am in the process of converting this code <code>predictor.py</code> located <a href="https://github.com/YadiraF/PRNet/blob/master/predictor.py" rel="nofollow noreferrer">here</a> to tensorflow v2 with Python 3.7. I want to do this conversion part by part. So from the refence repo, I've been going through <a href="https://github.com/tensorflow/models/blob/a174bf5b1db0e2c1e04697ff5aae5182bd1c60e7/official/vision/image_classification/resnet/resnet_model.py" rel="nofollow noreferrer">this example</a>.</p> <p>For this block:</p> <pre><code>def resBlock(x, num_outputs, kernel_size = 4, stride=1, activation_fn=tf.nn.relu, normalizer_fn=tcl.batch_norm, scope=None): assert num_outputs%2==0 #num_outputs must be divided by channel_factor(2 here) with tf.variable_scope(scope, 'resBlock'): shortcut = x if stride != 1 or x.get_shape()[3] != num_outputs: shortcut = tcl.conv2d(shortcut, num_outputs, kernel_size=1, stride=stride, activation_fn=None, normalizer_fn=None, scope='shortcut') x = tcl.conv2d(x, num_outputs/2, kernel_size=1, stride=1, padding='SAME') x = tcl.conv2d(x, num_outputs/2, kernel_size=kernel_size, stride=stride, padding='SAME') x = tcl.conv2d(x, num_outputs, kernel_size=1, stride=1, activation_fn=None, padding='SAME', normalizer_fn=None) x += shortcut x = normalizer_fn(x) x = activation_fn(x) return x </code></pre> <p>Here is what I have</p> <pre><code>import numpy as np import tensorflow as tf from tensorflow.keras.layers import Activation, BatchNormalization from tensorflow.keras.layers import Conv2D, Conv2DTranspose from tensorflow.keras.models import Sequential from tensorflow.keras.regularizers import l2 def create_sub_model( filters=16, kernel_size=4, stride=(1,1), stage=0, block='1a', activation='relu', normalizer=BatchNormalization()): assert (filters % 2 == 0), __file__ + ":filters is not an integer" name_base = 'conv' + str(stage) + block + '_branch' model = Sequential() #initial layer model.add(Conv2D(filters / 2, kernel_size=1, stride=(1, 1), padding='same', name=conv_name_base + '2a')) model.add(BatchNormalization(name=bn_name_base + '2a')) model.add(Activation(activation)) #add layer model.add(Conv2D(filters / 2, kernel_size=kernel_size, stride=stride, padding='same', name=conv_name_base + '2b')) model.add(BatchNormalization(name=bn_name_base + '2b')) model.add(Activation(activation)) # add layer model.add(Conv2D(filters, kernel_size=1, stride=(1,1), padding='same', name=conv_name_base + '2c',activation=None, normalizer=None)) model.add(BatchNormalization(name=bn_name_base + '2c')) model.add(Activation(activation)) # add layer model.add(Conv2D(filters, kernel_size=1, stride=stride, padding='same', name=conv_name_base + '2d', activation=None, normalizer=None)) model.add(BatchNormalization(normalizername=bn_name_base + '2d')) model.add(Activation(activation)) return model </code></pre> <p>I want to avoid defining the input tensor until later. Is this going down the right way?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T11:58:10.953", "Id": "241489", "Score": "2", "Tags": [ "python", "tensorflow" ], "Title": "Converting tensorflow v1 to v2 without compatability.v1" }
241489
<p>(See the <a href="https://codereview.stackexchange.com/users/58360/coderodde">previous (initial) iteration</a>.)</p> <p>This time, I have substantially reduced the usage of the <code>final</code> and <code>this</code> keywords. Also, I have dropped <code>java.util.(SortedMap/TreeMap)</code> and substituted it with a simple hash table/array, which dropped the running time of the mining phase by half:</p> <pre><code>Seed = 1588247737638 Data generated in 22773 milliseconds. Duration: 51508 milliseconds. Missing lottery rows: 2182644 </code></pre> <p><strong>Code</strong></p> <p><strong><code>net.coderodde.datamining.lottery.LotteryConfiguration.java:</code></strong></p> <pre><code>package net.coderodde.datamining.lottery; /** * This class specifies the lottery game configuration. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Jan 18, 2020) * @since 1.6 (Jan 18, 2020) */ public class LotteryConfiguration { /** * The maximum ball integer value. */ private final int maximumNumberValue; /** * The length of each lottery row. */ private final int lotteryRowLength; /** * Construct a new lottery configuration. * * @param maximumNumberValue the maximum ball integer value. * @param lotteryRowLength the lottery row length. */ public LotteryConfiguration(final int maximumNumberValue, final int lotteryRowLength) { checkArgs(maximumNumberValue, lotteryRowLength); this.maximumNumberValue = maximumNumberValue; this.lotteryRowLength = lotteryRowLength; } public int getMaximumNumberValue() { return this.maximumNumberValue; } public int getLotteryRowLength() { return this.lotteryRowLength; } private static void checkArgs(int maximumNumber, int numberCount) { if (maximumNumber &lt; 1) { throw new IllegalArgumentException( &quot;maximumNumber(&quot; + maximumNumber + &quot;) &lt; 1&quot;); } if (numberCount &lt; 1) { throw new IllegalArgumentException( &quot;numberCount(&quot; + numberCount + &quot;) &lt; 1&quot;); } if (numberCount &gt; maximumNumber) { throw new IllegalArgumentException( &quot;numberCount(&quot; + numberCount + &quot;) &gt; &quot; + &quot;maximumNumber(&quot; + maximumNumber + &quot;)&quot;); } } } </code></pre> <p><strong><code>net.coderodde.datamining.lottery.LotteryRow.java:</code></strong></p> <pre><code>package net.coderodde.datamining.lottery; import java.util.Arrays; import java.util.Objects; /** * This class implements a single lottery row. * * @author Rodion &quot;rodde&quot; Efremove * @version 1.61 (Apr 27, 2020) ~ removed manual sorting. * @version 1.6 (Apr 18, 2020) ~ initial version. * @since 1.6 (Apr 18, 2020) */ public class LotteryRow { /** * The configuration object. */ private final LotteryConfiguration lotteryConfiguration; /** * The actual lottery numbers. */ private final int[] lotteryNumbers; /** * Stores the index of the internal storage array at which the next lottery * number will be inserted. */ private int size = 0; /** * Constructs an empty lottery row with given configuration. * * @param lotteryConfiguration the lottery row configuration. */ public LotteryRow(LotteryConfiguration lotteryConfiguration) { this.lotteryConfiguration = Objects.requireNonNull(lotteryConfiguration); this.lotteryNumbers = new int[lotteryConfiguration.getLotteryRowLength()]; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); boolean isFirst = true; for (final int number : this.lotteryNumbers) { if (isFirst) { isFirst = false; stringBuilder.append(number); } else { stringBuilder.append(&quot;,&quot;).append(number); } } return stringBuilder.toString(); } /** * Appends a number to the tail of this lottery row. * * @param number the number to append. */ public void appendNumber(int number) { checkNumber(number); checkHasSpaceForNewNumber(); lotteryNumbers[size++] = number; Arrays.sort(lotteryNumbers, 0, size); } /** * Returns the &lt;code&gt;index&lt;/code&gt;th number. * * @param index the index of the desired number. * @return the &lt;code&gt;index&lt;/code&gt;th number. */ public int getNumber(int index) { checkIndex(index); return lotteryNumbers[index]; } /** * Returns the configuration object of this row. * * @return the configuration object. */ public LotteryConfiguration getLotteryConfiguration() { return lotteryConfiguration; } /** * Checks that there is more space for lottery numbers in this row. */ private void checkHasSpaceForNewNumber() { if (size == lotteryNumbers.length) { throw new IllegalStateException( &quot;The lottery row cannot accommodate more numbers.&quot;); } } /** * Checks that the input number is within the lottery number range. * * @param number the number to check. */ private void checkNumber(int number) { if (number &lt; 1) { throw new IllegalArgumentException(&quot;number(&quot; + number + &quot;) &lt; 1&quot;); } if (number &gt; this.lotteryConfiguration.getMaximumNumberValue()) { throw new IllegalArgumentException( &quot;number (&quot; + number + &quot;) &gt; &quot; + &quot;this.lotteryConfiguration.getMaximumNumberValue()[&quot; + this.lotteryConfiguration.getMaximumNumberValue() + &quot;]&quot;); } } /** * Checks that the index is withing the range &lt;code&gt;[0, n)&lt;/code&gt;. * * @param index the index to check. */ private void checkIndex(int index) { if (index &lt; 0) { throw new IllegalArgumentException(&quot;index(&quot; + index + &quot;) &lt; 0&quot;); } if (index &gt;= this.size) { throw new IllegalArgumentException( &quot;index(&quot; + index + &quot;) &gt;= this.index(&quot; + this.size + &quot;)&quot;); } } } </code></pre> <p><strong><code>net.coderodde.datamining.lottery.LotteryRowGenerator.java:</code></strong></p> <pre><code>package net.coderodde.datamining.lottery; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; /** * This class implements a facility for creating random lottery rows. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Apr 18, 2020) * @since 1.6 (Apr 18, 2020) */ public final class LotteryRowGenerator { /** * The lottery configuration object. */ private final LotteryConfiguration lotteryConfiguration; /** * The random number generator. */ private final Random random; /** * The storage array for. */ private final int[] numbers; /** * Constructs a {@code LotteryRowGenerator} with a given configuration. * * @param lotteryConfiguration the lottery configuration object. */ public LotteryRowGenerator(LotteryConfiguration lotteryConfiguration) { this(lotteryConfiguration, new Random()); } /** * Constructs a {@code LotteryRowGenerator} with a given configuration and * a seed value. * * @param lotteryConfiguration the lottery configuration object. * @param seed the seed value. */ public LotteryRowGenerator(LotteryConfiguration lotteryConfiguration, long seed) { this(lotteryConfiguration, new Random(seed)); } /** * Constructs a {@code LotteryRowGenerator} with a given configuration and * a random number generator. * * @param lotteryConfiguration the lottery configuration object. * @param random the random number generator. */ public LotteryRowGenerator(LotteryConfiguration lotteryConfiguration, Random random) { this.random = Objects.requireNonNull(random, &quot;The input Random is null.&quot;); this.lotteryConfiguration = Objects.requireNonNull( lotteryConfiguration, &quot;The input LotteryConfiguration is null.&quot;); numbers = new int[lotteryConfiguration.getMaximumNumberValue()]; for (int i = 0; i &lt; numbers.length; i++) { numbers[i] = i + 1; } } /** * Generates and returns a list of random lottery rows. * * @param numberOfLotteryRows the requested number of lottery rows. * @return a list of random rows. */ public List&lt;LotteryRow&gt; generateLotteryRows(int numberOfLotteryRows) { List&lt;LotteryRow&gt; rows = new ArrayList&lt;&gt;(numberOfLotteryRows); for (int i = 0; i &lt; numberOfLotteryRows; i++) { rows.add(generateRow()); } return rows; } private LotteryRow generateRow() { LotteryRow lotteryRow = new LotteryRow(lotteryConfiguration); shuffleInternalNumbers(); loadLotteryRow(lotteryRow); return lotteryRow; } private void shuffleInternalNumbers() { for (int i = 0, n = lotteryConfiguration.getMaximumNumberValue(); i &lt; n; i++) { swap(i, getRandomIndex()); } } public void loadLotteryRow(LotteryRow lotteryRow) { for (int i = 0, n = lotteryConfiguration.getLotteryRowLength(); i &lt; n; i++) { lotteryRow.appendNumber(numbers[i]); } } private int getRandomIndex() { return random.nextInt(lotteryConfiguration.getMaximumNumberValue()); } private void swap(final int index1, final int index2) { int tmp = numbers[index1]; numbers[index1] = numbers[index2]; numbers[index2] = tmp; } } </code></pre> <p><strong><code>net.coderodde.datamining.lottery.MissingLotteryRowsGenerator.java:</code></strong></p> <pre><code>package net.coderodde.datamining.lottery; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * This class implements a data mining algorithm for selecting all possible * lottery rows that do not appear in the given data set. This version differs * from {@link net.coderodde.datamining.lottery.MissingLotteryRowsGenerator} in * that respect that TreeMaps are changed to lighter unbalanced binary search * trees. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Apr 28, 2020) ~ renamed the class. * @since 1.6 (Apr 20, 2020) */ public final class MissingLotteryRowsGenerator { private static final class RadixTreeNode { RadixTreeNode[] children; } private final RadixTreeNode root; private final LotteryConfiguration lotteryConfiguration; /** * Implements the main constructor. * * @param lotteryConfiguration the lottery configuration object. * @param root the root node of the radix tree. */ private MissingLotteryRowsGenerator( LotteryConfiguration lotteryConfiguration, RadixTreeNode root) { this.lotteryConfiguration = Objects.requireNonNull( lotteryConfiguration, &quot;lotteryConfiguration == null&quot;); this.root = Objects.requireNonNull(root, &quot;The root node is null.&quot;); } /** * Constructs a missing rows generator with given lottery configuration. * * @param lotteryConfiguration the lottery configuration. */ public MissingLotteryRowsGenerator( LotteryConfiguration lotteryConfiguration) { this(lotteryConfiguration, new RadixTreeNode()); } /** * Adds a list of lottery rows to this generator. * * @param lotteryRows the lottery rows to add one by one. * @return this generator for chaining. */ public MissingLotteryRowsGenerator addLotteryRows(List&lt;LotteryRow&gt; lotteryRows) { for (LotteryRow lotteryRow : lotteryRows) { addLotteryRow(lotteryRow); } return this; } /** * Adds a single lottery row to this generator. * * @param lotteryRow the lottery row to add. * @return this generator for chaining. */ public MissingLotteryRowsGenerator addLotteryRow(LotteryRow lotteryRow) { Objects.requireNonNull(lotteryRow, &quot;lotteryRow == null&quot;); checkLotteryRow(lotteryRow); RadixTreeNode node = root; int maximumValue = lotteryConfiguration.getMaximumNumberValue(); for (int i = 0, sz = lotteryConfiguration.getLotteryRowLength(); i &lt; sz; i++) { RadixTreeNode nextNode; int number = lotteryRow.getNumber(i); if (node.children == null) { node.children = new RadixTreeNode[maximumValue]; } if (node.children[number - 1] == null) { RadixTreeNode tmp = new RadixTreeNode(); nextNode = tmp; node.children[number - 1] = tmp; if (i &lt; sz - 1) { nextNode.children = new RadixTreeNode[maximumValue]; } } else { nextNode = node.children[number - 1]; } node = nextNode; } return this; } /** * Computes and returns all the &lt;i&gt;missing&lt;/i&gt; lottery rows. A lottery row * is &lt;i&gt;missing&lt;/i&gt; if and only if it was not drawn in the population of * players. * * @return the list of missing lottery rows. */ public List&lt;LotteryRow&gt; computeMissingLotteryRows() { List&lt;LotteryRow&gt; lotteryRows = new ArrayList&lt;&gt;(); int[] numbers = getInitialNumbers(); do { LotteryRow lotteryRow = convertNumbersToLotteryRow(numbers); if (!treeContains(lotteryRow)) { lotteryRows.add(lotteryRow); } } while (increment(numbers)); return lotteryRows; } private boolean treeContains(LotteryRow lotteryRow) { RadixTreeNode node = root; for (int i = 0, sz = lotteryConfiguration.getLotteryRowLength(); i &lt; sz; i++) { int number = lotteryRow.getNumber(i); RadixTreeNode nextNode = node.children[number - 1]; if (nextNode == null) { return false; } node = nextNode; } return true; } private boolean increment(final int[] numbers) { int maximumNumber = lotteryConfiguration.getMaximumNumberValue(); int lotteryRowLength = lotteryConfiguration.getLotteryRowLength(); for (int i = lotteryRowLength - 1, j = 0; i &gt;= 0; i--, j++) { if (numbers[i] &lt; maximumNumber - j) { numbers[i]++; for (int k = i + 1; k &lt; lotteryRowLength; k++) { numbers[k] = numbers[k - 1] + 1; } return true; } } return false; } /** * Converts a number integer array into a * {@link net.coderodde.datamining.lottery.LotteryRow}. * @param numbers the raw number array in ascending order. * @return the lottery row with exactly the same numbers as in * {@code numbers}. */ private LotteryRow convertNumbersToLotteryRow(int[] numbers) { LotteryRow lotteryRow = new LotteryRow(this.lotteryConfiguration); for (int number : numbers) { lotteryRow.appendNumber(number); } return lotteryRow; } private int[] getInitialNumbers() { int lotteryRowLength = lotteryConfiguration.getLotteryRowLength(); int[] numbers = new int[lotteryRowLength]; for (int i = 0, number = 1; i &lt; lotteryRowLength; i++, number++) { numbers[i] = number; } return numbers; } private void checkLotteryRow(final LotteryRow lotteryRow) { if (lotteryRow.getLotteryConfiguration().getLotteryRowLength() != lotteryConfiguration.getLotteryRowLength()) { throw new IllegalArgumentException( &quot;Wrong length of a row (&quot; + lotteryRow.getLotteryConfiguration() .getLotteryRowLength() + &quot;, must be exactly &quot; + this.lotteryConfiguration.getLotteryRowLength() + &quot;.&quot;); } } } </code></pre> <p><strong><code>net.coderodde.datamining.lottery.Demo.java:</code></strong></p> <pre><code>package net.coderodde.datamining.lottery; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * This class demonstrates the functionality of the missing lottery row data * mining algorithm. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Apr 25, 2020) * @since 1.6 (Apr 25, 2020) */ public final class Demo { // 40 choose 7 = 18_643_560 combinations: private static final int LOTTERY_ROW_LENGTH = 7; private static final int LOTTERY_MAXIMUM_NUMBER = 40; private static final int LOTTERY_ROWS = 40_000_000; public static void main(String[] args) throws IOException { smallDemo(); long seed = System.currentTimeMillis(); LotteryConfiguration lotteryConfiguration = new LotteryConfiguration(LOTTERY_MAXIMUM_NUMBER, LOTTERY_ROW_LENGTH); System.out.println(&quot;Seed = &quot; + seed); List&lt;LotteryRow&gt; data = benchmarkAndObtainData(seed); benchmark(lotteryConfiguration, data); } private static List&lt;LotteryRow&gt; benchmarkAndObtainData(final long seed) { LotteryConfiguration lotteryConfiguration = new LotteryConfiguration(LOTTERY_MAXIMUM_NUMBER, LOTTERY_ROW_LENGTH); // Warmup run: new LotteryRowGenerator(lotteryConfiguration, seed) .generateLotteryRows(LOTTERY_ROWS); long startTime = System.nanoTime(); // Data generation: List&lt;LotteryRow&gt; data = new LotteryRowGenerator(lotteryConfiguration) .generateLotteryRows(LOTTERY_ROWS); long endTime = System.nanoTime(); System.out.println( &quot;Data generated in &quot; + ((endTime - startTime) / 1_000_000L) + &quot; milliseconds.&quot;); return data; } // Warms up and benchmarks the private static void benchmark(LotteryConfiguration lotteryConfiguration, List&lt;LotteryRow&gt; data) throws IOException { long startTime = System.nanoTime(); List&lt;LotteryRow&gt; missingLotteryRows = new MissingLotteryRowsGenerator(lotteryConfiguration) .addLotteryRows(data) .computeMissingLotteryRows(); long endTime = System.nanoTime(); System.out.println( &quot;Duration: &quot; + ((endTime - startTime) / 1_000_000L) + &quot; milliseconds.&quot;); System.out.println( &quot;Missing lottery rows: &quot; + missingLotteryRows.size()); // boolean isFirst = true; // // for (final LotteryRow lotteryRow : missingLotteryRows) { // if (isFirst) { // isFirst = false; // } else { // System.out.println(); // } // // System.out.print(lotteryRow); // } } // Runs a small demo: private static void smallDemo() { LotteryConfiguration lotteryConfiguration = new LotteryConfiguration(5, 3); LotteryRow lotteryRow1 = new LotteryRow(lotteryConfiguration); // 1, 2, 4 LotteryRow lotteryRow2 = new LotteryRow(lotteryConfiguration); // 2, 4, 5 LotteryRow lotteryRow3 = new LotteryRow(lotteryConfiguration); // 1, 3, 5 LotteryRow lotteryRow4 = new LotteryRow(lotteryConfiguration); // 3, 4, 5 lotteryRow1.appendNumber(1); lotteryRow1.appendNumber(4); lotteryRow1.appendNumber(2); lotteryRow2.appendNumber(4); lotteryRow2.appendNumber(5); lotteryRow2.appendNumber(2); lotteryRow3.appendNumber(1); lotteryRow3.appendNumber(3); lotteryRow3.appendNumber(5); lotteryRow4.appendNumber(3); lotteryRow4.appendNumber(4); lotteryRow4.appendNumber(5); List&lt;LotteryRow&gt; drawnLotteryRows = Arrays.asList(lotteryRow1, lotteryRow2, lotteryRow3, lotteryRow4); MissingLotteryRowsGenerator generator = new MissingLotteryRowsGenerator(lotteryConfiguration); List&lt;LotteryRow&gt; missingLotteryRows = generator .addLotteryRows(drawnLotteryRows) .computeMissingLotteryRows(); missingLotteryRows.forEach((row) -&gt; { System.out.println(row);}); } } </code></pre> <p><strong>Critique request</strong></p> <p>As always, I am glad to hear all the comments regarding my Java coding routine. Is there anyting code-/performance wise I could improve?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:46:51.900", "Id": "474065", "Score": "0", "body": "I think the calls to `random.nextInt()` will currently take the most time. Can you verify that?" } ]
[ { "body": "<h2>Performance</h2>\n<p>I tried optimizing it all I could, but it seems calls to <code>random.next()</code> really clog things up :(</p>\n<p>Ideas:</p>\n<ul>\n<li>Because there are only ~18M valid items, and because 18M &lt; Integer.MAX, we can store them in an array, using the index as ordinal</li>\n<li>Because <code>40^7</code> &lt; Long.MAX, we can store a ticket in a <code>long</code></li>\n<li>We can use binary search on the ordered array of primitive <code>long</code>s. Because it is only 18M long, we have a maximum of 25 comparisons to find the index. (or not, if it is not contained). I think a tree might be faster, but if you do not use primitives, you will loose speed in auto-boxing and referencing.</li>\n</ul>\n<h2>Source</h2>\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Random;\nimport java.util.stream.IntStream;\n\npublic class FastLottery {\n\n private static final int LOTTERY_ROW_LENGTH = 7;\n private static final int LOTTERY_MAXIMUM_NUMBER = 40;\n private static final int LOTTERY_ROWS = 40_000_000;\n private static final int OPTIONS = 18643560;\n\n\n /* arr[] ---&gt; Input Array\n data[] ---&gt; Temporary array to store current combination\n start &amp; end ---&gt; Staring and Ending indexes in arr[]\n index ---&gt; Current index in data[]\n r ---&gt; Size of a combination to be printed */\n public static List&lt;int[]&gt; combinationsUtil(int arr[], int data[], int start,\n int end, int index, int r)\n {\n List&lt;int[]&gt; results = new ArrayList&lt;&gt;();\n\n // Current combination is ready to be printed, print it\n if (index == r)\n {\n int[] result = new int[data.length];\n System.arraycopy(data,0, result,0, data.length);\n results.add(result);\n return results;\n }\n\n // replace index with all possible elements. The condition\n // &quot;end-i+1 &gt;= r-index&quot; makes sure that including one element\n // at index will make a combination with remaining elements\n // at remaining positions\n for (int i=start; i&lt;=end &amp;&amp; end-i+1 &gt;= r-index; i++)\n {\n data[index] = arr[i];\n results.addAll(combinationsUtil(arr, data, i+1, end, index+1, r));\n }\n return results;\n }\n\n // The main function that gets all combinations of size r\n // in arr[] of size n. This function mainly uses combinationUtil()\n public static List&lt;int[]&gt; getAllCombinations(int[] arr, int n, int r)\n {\n return combinationsUtil(arr, new int[r], 0, n-1, 0, r);\n }\n\n public static long toLong(int[] ticket)\n {\n long l=0;\n for (int i=0; i&lt;LOTTERY_ROW_LENGTH; i++)\n {\n l*=LOTTERY_MAXIMUM_NUMBER;\n l+=ticket[i];\n }\n return l;\n }\n public static int[] fromLong(long l)\n {\n int[] result = new int[LOTTERY_ROW_LENGTH];\n for (int i=LOTTERY_ROW_LENGTH-1; i&gt;=0; i--)\n {\n result[i] = (int) (((l % LOTTERY_MAXIMUM_NUMBER) + LOTTERY_MAXIMUM_NUMBER) % LOTTERY_MAXIMUM_NUMBER);\n l/=LOTTERY_MAXIMUM_NUMBER;\n }\n return result;\n }\n\n private static long[] generateTicketArray(List&lt;int[]&gt; allTickets) {\n System.out.println(&quot;Initializing arrays&quot;);\n long[] longTickets = new long[OPTIONS];\n for (int i=0; i&lt;OPTIONS; i++) {\n int[] tic = allTickets.get(i);\n //System.out.println(&quot;Generating ticket:&quot; + Arrays.toString(tic));\n\n long ticket = toLong(tic);\n longTickets[i] = ticket;\n //System.out.println(&quot;Generating ticket:&quot; + longTickets[i]);\n }\n //Because the allTickets and toLong keep correct order, we don't need to sort :)\n\n return longTickets;\n }\n\n private static List&lt;int[]&gt; generateAllTickets() {\n System.out.println(&quot;Generating all options&quot;);\n\n int arr[] = IntStream.rangeClosed(1,LOTTERY_MAXIMUM_NUMBER).toArray();\n int r = 7;\n int n = arr.length;\n\n List&lt;int[]&gt; allTickets = new ArrayList&lt;int[]&gt;();\n allTickets = getAllCombinations(arr, n, r);\n return allTickets;\n }\n\n public static void main (String[] args) {\n\n Random random = new Random();\n\n //generate all valid tickets\n List&lt;int[]&gt; allTickets = generateAllTickets();\n\n\n long[] longTickets = generateTicketArray(allTickets);\n boolean[] soldTickets = new boolean[longTickets.length];\n\n System.out.println(&quot;Picking random tickets&quot;);\n\n for (int i=0; i&lt;LOTTERY_ROWS; i++)\n {\n long randomTicket = toLong(allTickets.get(random.nextInt(OPTIONS)));\n// long randomTicket = toLong(allTickets.get(i % OPTIONS));\n\n //Use binary search on the sorted long array\n int index = Arrays.binarySearch(longTickets, randomTicket);\n\n //If we have a valid index; mark the index as SOLD\n if (index&gt;=0)\n {\n soldTickets[index] = true;\n }\n if (i%1_000_000 ==0)\n System.out.println(&quot;Picking random tickets, &quot; + i);\n }\n\n System.out.println(&quot;Printing evil tickets&quot;);\n int evilTickets = 0;\n for (int i=0; i&lt;OPTIONS; i++)\n {\n\n if (soldTickets[i] == false)\n {\n evilTickets++;\n //System.out.println(&quot;Evil ticket:&quot; + Arrays.toString(fromLong(longTickets[i])));\n }\n }\n System.out.println(&quot;We have # Evil tickets:&quot; + evilTickets);\n }\n\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:01:14.087", "Id": "241560", "ParentId": "241490", "Score": "3" } } ]
{ "AcceptedAnswerId": "241560", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T12:21:54.287", "Id": "241490", "Score": "1", "Tags": [ "java", "algorithm", "tree", "data-mining" ], "Title": "Data mining in Java: finding undrawn lottery rows - follow-up" }
241490
<p>I designed the code and it works quite well for images of lower res. However my program takes a lot of time and ram to display higher res images (occupies 2GB RAM for 4k images and takes 20 minutes). This program currently only processes files in .png format.</p> <pre><code>#------------------------------------ import matplotlib.pyplot as plt import skimage from skimage import color import numpy as np #------------------------------------ x=plt.imread("s2.png") #the file name #x=color.rgba2rgb(x) y=x n=int(input()) #"n" is the level of blurring(typical values=5,10,20,50) le=y.shape[0] bd=y.shape[1] #------------------------------------ def frame(y): y2=np.ones(shape=(le+(2*n),bd+(2*n))) for i in range(0,le): for j in range(0,bd): y2[(i+n),(j+n)]=y[i,j] return(y2) #------------------------------------ #print((frame(y[:,:,0])).shape) p=(2*n)+1 def kernel(p): k=np.zeros(shape=(p,p)) for i in range(0,p): for j in range(0,p): k[i,j]=1.00005**(-(n-i)**2-(n-j)**2) k=k/(np.sum(k)) return(k) #print(kernel(p).shape) #------------------------------------ def blur(arr,k,y2): z=np.zeros(shape=(le,bd)) for i in range(0,le): for j in range(0,bd): z[i,j]=np.sum(k*(y2[i:(i+n+2+n-1),j:(j+n+2+n-1)])) return(z) #------------------------------------ r=blur(y[:,:,0],kernel(p),frame(y[:,:,0])) g=blur(y[:,:,1],kernel(p),frame(y[:,:,1])) b=blur(y[:,:,2],kernel(p),frame(y[:,:,2])) x2=(np.array([r.transpose(),g.transpose(),b.transpose()])).transpose() plt.imshow(x2) plt.show() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T16:26:15.337", "Id": "474198", "Score": "0", "body": "Python is slow. If you want to speed this up, try using Numba, or try rewriting in a compiled language. However, the better approach (if you’re not writing code to learn) is to use a pre-existing implementation of the convolution. Scikit has several (in sub-packages ndimage, signal, etc)." } ]
[ { "body": "<p>Before we get into deep performance concerns, let's do a quality pass:</p>\n\n<h2>Global code</h2>\n\n<p>Lines like </p>\n\n<pre><code>x=plt.imread(\"s2.png\") #the file name\n#x=color.rgba2rgb(x)\ny=x\nn=int(input()) #\"n\" is the level of blurring(typical values=5,10,20,50)\nle=y.shape[0]\nbd=y.shape[1]\n</code></pre>\n\n<p>should be in a function and not in global scope.</p>\n\n<h2>Mystery input</h2>\n\n<p>Pass a prompt to <code>input</code>, such as <code>Please enter the level of blurring</code>.</p>\n\n<h2>Extraneous parens</h2>\n\n<p>This:</p>\n\n<pre><code>y2=np.ones(shape=(le+(2*n),bd+(2*n)))\nfor i in range(0,le):\n for j in range(0,bd):\n y2[(i+n),(j+n)]=y[i,j]\nreturn(y2)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>y2 = np.ones(shape=(le + 2*n, bd + 2*n))\nfor i in range(le):\n for j in range(bd):\n y2[i + n, j + n] = y[i, j]\nreturn y2\n</code></pre>\n\n<p>Also note the default value for the start of <code>range</code>.</p>\n\n<h2>In-place division</h2>\n\n<p>This:</p>\n\n<pre><code>k=k/(np.sum(k))\nreturn(k)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>k /= np.sum(k)\nreturn k\n</code></pre>\n\n<h2>Empty, not zero</h2>\n\n<p>Your <code>blur</code> method should definitely be vectorized, which I'll get to later, but for now, since it's clear that you're overwriting every entry: use <code>empty</code> rather than <code>zeros</code>.</p>\n\n<h2>Add another dimension</h2>\n\n<p>This:</p>\n\n<pre><code>r=blur(y[:,:,0],kernel(p),frame(y[:,:,0]))\ng=blur(y[:,:,1],kernel(p),frame(y[:,:,1]))\nb=blur(y[:,:,2],kernel(p),frame(y[:,:,2]))\n</code></pre>\n\n<p>should not be three separate calls. Your data should have a dimension (<code>y</code> already does) of length 3, and <code>y</code> should be passed in its entirety.</p>\n\n<h2>Variable names</h2>\n\n<p><code>le</code>, <code>bd</code> and <code>p</code> mean nothing to me, and in three months they might not mean anything to you, either. Write these out with longer, more meaningful names. I promise that it will not slow the program down.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T04:02:10.993", "Id": "474016", "Score": "0", "body": "Thank you for pointing out the flaws in quality. Would be great if you could give some tips for performance enhancement since the program is really slow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:53:00.643", "Id": "241516", "ParentId": "241491", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T12:23:02.013", "Id": "241491", "Score": "5", "Tags": [ "python", "python-3.x", "array", "image", "numpy" ], "Title": "Applying gaussian blur on RGBA images" }
241491
<p>I'm trying to wrap my head around JavaScript Functional Programming.</p> <p>I have created a very basic script that creates a new elements and appends them to the DOM.</p> <p>If anyone could share any feedback, or great resources on the subject, that would be awesome.</p> <p>Where does this style of programming lend itself best? Web Development, or more Software development? I understand that <code>React</code> uses this coding paradigm. I'm actually very comfortable using <code>React</code> - but, I'm wondering how it might be best utilised with vanilla JavaScript</p> <p>Thanks!</p> <pre><code> // create a button that accepts text and a callback function const createButton = (text, func) =&gt; { const button = document.createElement('button'); const buttonText = document.createTextNode(text); button.appendChild(buttonText); button.addEventListener('click', () =&gt; { return func(); }); return button; }; // create paragraph tag that accepts a text arg const createText = (text) =&gt; { const pTag = document.createElement('p'); const pTagText = document.createTextNode(text); pTag.appendChild(pTagText); return pTag; }; // pure functions const myList = [1, 2, 3]; const sayHello = (name) =&gt; { return `Hello, ${name}!`; }; const addNums = (x, y) =&gt; { return x + y; }; const simpleLog = () =&gt; { return 'This is a simple log'; }; const addToArray = (item) =&gt; { return [...myList, item]; } // view - component that will get rendered to the DOM const view = () =&gt; { const component = document.createElement('div'); // create a button element that has a callback function that will append the returned value to the DOM component.appendChild(createButton('Hello', () =&gt; { return component.appendChild( createText( sayHello('Kristian') ) ); })); component.appendChild(createButton('Add Numbers', () =&gt; { return component.appendChild( createText( addNums(3, 7) ) ); })); component.appendChild( createButton('Log', simpleLog) ); component.appendChild(createButton('Add to array', () =&gt; { console.log( `Original array: [${myList}] - New array: [${addToArray(4)}]`); })); return component; }; // grab the el that you want to append the view to const rootNode = document.getElementById('app'); // append view component to el rootNode.appendChild(view()); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T19:12:06.403", "Id": "473969", "Score": "2", "body": "So in \"functional programming\" you've decided to replace the normal `function name(parameters)` by `const name = (parameters) =>`. What's the point of that? It's the \"new\" thing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T12:10:47.243", "Id": "474047", "Score": "1", "body": "Hi @WoodenChops; welcome to CR SE! I'm not much involved with javascript, so I'll let other folks actually answer your question. (I've found it illuminating to think of JS as \"callback\" rather than \"functional\" programming.)\n\nMost of your post looks fine. Can you update your title? It should focus on what your code does (and how, which is where you can mention \"functional programming\")." } ]
[ { "body": "<h1> Preface</h1>\n<p>&quot;Best Practises&quot; are very subjective, so your question cannot really be answered in that regard, but I will try to give you some tips nonetheless.</p>\n<p>To lead into the rest of my answer I would say <a href=\"https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0\" rel=\"nofollow noreferrer\">one of the most beginner-friendly resources for learning a functional style in javascript is this Medium article</a> (without going into a lot of the nitty-gritty theoretical stuff). By reading this I think you will come to understand a lot of the ideas that come with functional programming.</p>\n<br/>\n<hr />\n<br/>\n<h1>‍♀️ Paradigm vs. Style</h1>\n<p>With that out of the way, let us start with a shocker: Javascript is not really a functional programming language. Yep, I said it. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/About_JavaScript\" rel=\"nofollow noreferrer\">Javascript is more a procedural (or object-oriented) language</a> (some newer features have allowed for more functional-ish style but it remains very procedural). But all that ofcourse does not mean you cannot <em>apply</em> a functional style, which I think is more the core of your question?</p>\n<p>Presuming I did correctly interpret your question, let me paraphrase to you the first two sentences of the Wikipedia page about FP:</p>\n<blockquote>\n<p>[...] functional programming is a programming paradigm where programs are constructed by <strong>applying</strong> and <strong>composing</strong> functions. It is a <strong>declarative</strong> programming paradigm [...], rather than a <em>sequence of imperative statements</em> [...].</p>\n</blockquote>\n<p>This means that, when writing your programs, you do not tell the computer exactly what to do every <em>step</em> of the way (i.e. <code>for (let i = 0; i &lt; n; i++)</code>) but rather you chunk a problem into smaller sub-problems, solve those, and compose a function that calls your smaller functions to solve the bigger problem. This leads me to my first tip. Javascript functions come in two forms: procedures, and lambda's. I am not going into the details that differentiate the two, but rather I would like to tell you about lambda's.</p>\n<br/>\n<hr />\n<br/>\n<h1> Tip 1: Embrace expressions</h1>\n<p>You seem to know javascript's lambda syntax, since you use the arrow notation (<code>x =&gt; y</code>), but you are using it in a procedural way. What I mean by that, is that you append a block to each lambda, as such:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const doSomething = (arg1, arg2) =&gt; { /*steps*/ };\n</code></pre>\n<p>This kind of defeats the purpose of the notation, and is basically another syntax for the procedural functions of JS:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function doSomething (arg1, arg2) { /*steps*/ }\n</code></pre>\n<p>In Javascript, <code>x =&gt; y</code> means <em>a function that takes x and returns y</em>. So a lot of your functions can be simplified. Let's change a couple to make it clear:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const sayHello = (name) =&gt; {\n return `Hello, ${name}!`;\n};\n// can be\nconst sayHello = name =&gt; `Hello ${name}!`;\n</code></pre>\n<p>and</p>\n<pre class=\"lang-js prettyprint-override\"><code>const addNums = (x, y) =&gt; {\n return x + y;\n};\n// can be\nconst add = (x, y) =&gt; x + y;\n</code></pre>\n<br/>\n<hr />\n<br/>\n<h1> Tip 2: Spice up your functions</h1>\n<p>But then what is the purpose of the lambda notation, and why is your code defeating its purpose? To put it simply: a lambda is a function that takes <em>zero or one argument(s)</em>, maybe transforms it, and yields a result. <a href=\"https://en.wikipedia.org/wiki/Lambda_calculus#The_lambda_calculus\" rel=\"nofollow noreferrer\">Wikipedia's article about lambda calculus says the same</a>, but with more jargon:</p>\n<blockquote>\n<p>[...] all functions in the lambda calculus are anonymous functions, having no names. They only accept <strong>one</strong> input variable, with <strong>currying</strong> used to implement functions with several variables.</p>\n</blockquote>\n<p>You use a lot of functions as procedures (sequence of steps) which you cannot have in FP, and you are using multiple parameter functions which are also disallowed (or rather just do not exist in FP). But, you might ask, how are you supposed to do anything with just one parameter and a single expression body? Let us take a snippet of your code and refactor it into a nice functional style:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Original\nconst createButton = (text, func) =&gt; {\n const button = document.createElement('button');\n const buttonText = document.createTextNode(text);\n button.appendChild(buttonText);\n\n button.addEventListener('click', () =&gt; {\n return func();\n });\n\n return button;\n};\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>// Functional alternative\n// Some setup, notice the currying for multiple arguments.\nconst text = text =&gt; document.createTextNode(text);\nconst newButton = () =&gt; document.createElement(&quot;button&quot;);\nconst listen = event =&gt; handler =&gt; target =&gt; {\n // Javascript was not meant to be used purely functionally,\n // so we have to use a block with several statements to\n // mutate the target, and then return it (mutation will never\n // happen in functional programming, as you might know).\n target.addEventListener(event, handler);\n return target;\n};\nconst append = child =&gt; target =&gt; {\n // Same story: we have to return the target after mutating it.\n target.append(child);\n return target;\n};\n\n// Here comes the true power of functional programming: composition\nconst onClick = listen(&quot;click&quot;);\nconst addLabel = label =&gt; append(text(label));\nconst sayHi = () =&gt; console.log(&quot;Hi!&quot;);\nconst sayBye = () =&gt; console.log(&quot;Bye.&quot;);\nconst button = label =&gt; handler =&gt;\n addLabel(label)(\n onClick(handler)(\n newButton()));\n\nconst friendlyButton = button(&quot;:)&quot;)(sayHi);\nconst sadButton = button(&quot;:(&quot;)(sayBye);\n\n// Try it out!\ndocument.body.append(friendlyButton, sadButton);\n</code></pre>\n<p>Ok, giant code sample with weird and maybe hideous things. Let me explain it!</p>\n<p>Firstly I would like to say that Javascript is a great language, but the DOM is not the best part to use FP for, because it's an amalgamation of mutation and imperativeness, which are the arch-enemies of FP. But let us do it anyways because it is fun!</p>\n<p>The first statement of the refactor goes as follows:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const text = text =&gt; document.createTextNode(text);\n</code></pre>\n<p>which is essentially a function that, when called with an argument <code>text</code> will create a textNode with <code>text</code> being its text. Now this is a bit of a weird one, because we made a function that takes an argument, and then calls another function with that very argument, so we basically aliased it. Aliasing is the same as storing it in a variable with another name, so why not write it like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const text = document.createTextNode;\n</code></pre>\n<p><code>text</code> is equal to <code>document.createTextNode</code>, so <code>text(&quot;Hi!&quot;)</code> is equal to <code>document.createTextNode(&quot;Hi!&quot;)</code>.</p>\n<blockquote>\n<p>Now JS is a bit weird (and full of <em>side-effects</em>), so we have to specify that the <code>this</code> of <code>document.createElement</code> is <code>document</code> (<code>document.createElement.bind(document)</code>). The peculiarities of Javascript's <code>this</code> go far beyond the purpose of this post so if you do not understand what that meant, just wrap it in a function like so: <code>x =&gt; y(x)</code>;</p>\n</blockquote>\n<p>The first real weirdness happens in the <code>listen</code> function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const listen = event =&gt; handler =&gt; target =&gt; { /*...*/ };\n</code></pre>\n<p><strong>What?</strong> A function that returns a function that returns a function that returns something else?! Yep, that is functional programming baby! But why would we do this? Because it allows for very easy <em>composition</em>. Notice how later on, we defined the function <code>onClick</code>, which is a composed <code>listen</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const onClick = listen(&quot;click&quot;);\n// This means the following:\nconst onClick = handler =&gt; target =&gt; target.addEventListener(&quot;click&quot;, handler);\n</code></pre>\n<p>So we made a function that always adds a <code>click</code> eventlistener to a target. We can take this a step further:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Let's make a function that makes an element yell &quot;OUCH!&quot; on click!\nconst ouch = onClick(() =&gt; console.log(&quot;OUCH!&quot;));\n// This means the following:\nconst ouch = target =&gt; target.addEventListener(&quot;click&quot;, () =&gt; console.log(&quot;OUCH!&quot;));\n\n// Try it out!\nconst boxingDummy = ouch(addLabel(&quot;Don't hit me!&quot;)(newButton()));\ndocument.body.append(boxingDummy);\n</code></pre>\n<p>I hope that made it clear why you would write programs in such a weird (coming from procedural programming) way. I would link you the wiki article but that is just unintelligble jibberish to me too.</p>\n<br/>\n<hr />\n<br/>\n<h1> Tip 3: <a href=\"https://www.youtube.com/watch?v=b7kxtIGaNpw\" rel=\"nofollow noreferrer\">Lose control</a></h1>\n<p>You seem to really rely on the imperativeness of Javascript to perform tasks in a set order, which does not fit well in a functional style -- most functional languages do not even allow it. The great functional programming evangelists have thought about this long and hard, and showed us how you do not need loops, if's or sequences to create complete and functional (in the literal sense) programs. Taking, for example, another function you wrote:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const view = () =&gt; {\n const component = document.createElement('div');\n\n // create a button element that has a callback function that will append the returned value to the DOM\n\n component.appendChild(createButton('Hello', () =&gt; {\n return component.appendChild( createText( sayHello('Kristian') ) );\n }));\n\n component.appendChild(createButton('Add Numbers', () =&gt; {\n return component.appendChild( createText( addNums(3, 7) ) );\n }));\n\n component.appendChild( createButton('Log', simpleLog) );\n\n component.appendChild(createButton('Add to array', () =&gt; {\n console.log( `Original array: [${myList}] - New array: [${addToArray(4)}]`);\n }));\n\n return component;\n};\n</code></pre>\n<p>Pardon the joke, but this looks really WET... (as in, the opposite of <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>). You call <code>component.appendChild(createButton(/*...*/))</code> a lot of times. Apart from that being a bit of a code smell, it also is a really great place to put in some FP magic. Analysing the abstract meaning of your code, let me write that out in a more functional style:</p>\n<pre><code>// Remember our previous functions?\n// I made them nice and generic so they are\n// reusable here!\nconst appendButton = label =&gt; action =&gt; append(button(label)(action));\nconst add = x =&gt; y =&gt; x + y;\nconst addFive = add(5);\nconst saySix = () =&gt; console.log(addFive(1));\nconst fold = (...functions) =&gt; value =&gt; functions.reduce(\n (result, fun) =&gt; fun(result),\n value);\nconst component = document.createElement(&quot;div&quot;);\nconst view = fold(\n appendButton(&quot;Greet&quot;)(sayHi),\n appendButton(&quot;What's five plus one?&quot;)(saySix)\n /* etc... */);\n\n// Try it out!\ndocument.body.append(view(component));\n</code></pre>\n<p>BAM! No blocks, no loops, no if's! Instead of a sequence of statements, we use a fold to abstract away a lot of the DOM boilerplate. Higher-order functions such as fold(left) are very important functions to keep in your arsenal. <a href=\"https://en.wikipedia.org/wiki/Fold_(higher-order_function)\" rel=\"nofollow noreferrer\">I suggest reading up on it a bit</a>, if the article isn't too crytographic (there's a joke that says functional programmers tend to lose their ability to explain FP as soon as they understand, and I think that applies perfectly on most wiki pages).</p>\n<br/>\n<hr />\n<br/>\nWell that should be about it. To summarise:\n<ul>\n<li>Javascript DOM isn't the best place to apply FP (in my humble opinion), but go ahead and break the rules!</li>\n<li><a href=\"https://www.nhs.uk/conditions/repetitive-strain-injury-rsi/\" rel=\"nofollow noreferrer\">Don't get RSI</a>: <code>(x) =&gt; { return y; }</code> is the same as <code>x =&gt; y</code>.</li>\n<li>Procedures are <em>so 1970</em>; compose a function from functions to solve your problems (and most importantly: be able to reason about your solution).</li>\n<li>Currying and higher-order functions are a functional programmer's best friends, conquer the world with them.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T23:12:45.817", "Id": "474000", "Score": "0", "body": "Sometimes there is a wonderful interplay of the right question at the right time and the perfect balance of motivation and expertise of the respondent. This, what happens here, is a great example of such an interplay. Absolutely blown-away by your answer. Never even heard of Functional Programming and your answer just clicked. In my world there was Object-Oriented Programming and Procedural Programming. With the former being the \"best\" way. Where do you even start to understand programming on that level? With higher-order functions and currying?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T09:46:25.060", "Id": "474037", "Score": "1", "body": "@MelvinIdema Thanks for the kind words. I was displeased by all of my imperative code because it didn't have the expressive power I wanted. I figured I couldn't be alone in thinking so. I quickly fell into a rabbit hole of computer science, and I just happened to come out of it [having seen the light](https://www.haskell.org/). To me, everything is composition. Subatomic particles make atoms, atoms make cells, cells make organs, organs make organisms... As I understand the world, everything is a function of smaller functions. Functional programming to me is the only next step in programming." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T21:05:01.160", "Id": "241523", "ParentId": "241501", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T14:48:55.820", "Id": "241501", "Score": "2", "Tags": [ "javascript", "functional-programming" ], "Title": "Is the JavaScript code I've provided following Functional Programming best-practices?" }
241501
<p>I need to understand if the way I am modelling data in a Django application is correct. The idea is of a news site that has sources, authors and articles.</p> <p>I want:</p> <ol> <li><code>Source</code> to have many <code>Article</code> </li> <li><code>Author</code> to have many <code>Article</code></li> <li><code>Article</code> to have many <code>Author</code> </li> </ol> <p>Does the below model do this correctly? I am worried there is a loop on 2 and 3. DO I only need to define the <code>ManyToManyField</code> in one of these?</p> <pre><code># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Source(models.Model): source_id = models.CharField(max_length=20) name = models.CharField(max_length=50) articles = models.ForeignKey(Article, on_delete=models.CASCADE) class Article(models.Model): authors = models.ManyToManyField(Author) title = models.CharField(max_length=200) description = models.CharField(max_length=200) url = models.CharField(max_length=200) urlToImage = models.CharField(max_length=200) publishedAt = models.DateTimeField(max_length=100) content = models.CharField(max_length=5000) class Author(models.Model): name = models.CharField(max_length=50) articles = models.ManyToManyField(Article) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T04:27:39.640", "Id": "474018", "Score": "0", "body": "Is it also possible for an `Article` to have may `Source` or will every `Article` always have just 1 of those?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T04:28:43.833", "Id": "474019", "Score": "2", "body": "At the moment, you just have a design. The code doesn't do anything yet. Feel free to come back once you've implemented a program actually using the model. There's not much we can say at this point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T08:26:37.400", "Id": "474034", "Score": "0", "body": "@Mast ok I see, I've not used code review before. Do you want to see the associated 'controllers' etc? Also the API I'm using just has one source per article, I did think about multiple sources but thought I'd keep it simple" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T14:57:44.050", "Id": "241502", "Score": "1", "Tags": [ "python", "python-3.x", "django" ], "Title": "Modelling articals and authors in Django" }
241502
<p>I am a beginner in programming. And I am learning python as my first language. I went on to do some challenges on <a href="https://hackerrank.com" rel="nofollow noreferrer">HackerRank</a> and stumbled upon <a href="https://www.hackerrank.com/challenges/no-idea/problem" rel="nofollow noreferrer">this problem</a>. The problem goes like this:</p> <blockquote> <p>There is an array of <span class="math-container">\$\ n \$</span> integers. There are also <span class="math-container">\$\ 2 \$</span> disjoint sets , <span class="math-container">\$\ A \$</span> and <span class="math-container">\$\ B \$</span> each containing <span class="math-container">\$\ m \$</span> integers. You like all the integers in set <span class="math-container">\$\ A \$</span> and dislike all the integers in set <span class="math-container">\$\ B \$</span>. Your initial happiness is <span class="math-container">\$\ 0 \$</span>. For each <span class="math-container">\$\ i \$</span> integer in the array, if <span class="math-container">\$\ i \in A\$</span>, you add <span class="math-container">\$\ 1 \$</span> to your happiness. If <span class="math-container">\$\ i \in B\$</span>, you add <span class="math-container">\$\ -1\$</span> to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.</p> <p><strong>Input Format</strong> <br/> The first line contains integers <span class="math-container">\$\ n \$</span> and <span class="math-container">\$\ m \$</span> separated by a space. <br/> The second line contains <span class="math-container">\$\ n \$</span> integers, the elements of the array. <br/> The third and fourth line contains <span class="math-container">\$\ m \$</span> integers, of <span class="math-container">\$\ A \$</span> and <span class="math-container">\$\ B \$</span> respectively.<br/></p> <p><strong>Output Format</strong> <br/> Output a single integer, your total happiness.</p> <p><strong>Sample input</strong> <br/> <code>3 2 1 5 3 3 1 5 7</code> <strong>Sample output</strong> <code>1</code></p> </blockquote> <p>Here's my attempt at the answer. My code is working fine with small inputs but when the values of <span class="math-container">\$\ n \$</span> and <span class="math-container">\$\ m \$</span> are in millions, it gives a <em>Terminated due to timeout :(</em> error. Please help me out with time-efficient code that will execute within the time limits.</p> <pre><code>elems_count = input().split() my_set = input().split() happy_set = input().split() sad_set = input().split() happy = 0 for i in range(int(elems_count[0])): if my_set[i] in happy_set: happy = happy + 1 else: happy = happy - 1 print(happy) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:27:29.267", "Id": "473960", "Score": "2", "body": "Separate from the performance issue, but you have an error in the loop - it's counting every non-liked number as a disliked number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T05:15:28.447", "Id": "474021", "Score": "0", "body": "@Errorsatz Thanks for pointing out the error. I fixed it and tried submitting it again on hackerrank, now it fails one case less, than before fixing the error. It still fails 4 of 8 cases giving the `Terminated due to time out error :(`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T18:49:28.380", "Id": "474103", "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-05-01T22:13:26.803", "Id": "474131", "Score": "0", "body": "\"_Thanks for pointing out the error. I fixed it and tried submitting it again on hackerrank, now it fails one case less, than before fixing the error._\" Since your code was generating failures unrelated to `[time-limit-exeeded]`, this question is off-topic for Code Review. Code must be working, to the best of the author's knowledge before posting it here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T09:21:26.547", "Id": "474162", "Score": "0", "body": "(In essence: re-think *testing* your code. Once confident your code is functionally correct, you are welcome to post a new question when you still have concerns about it.)" } ]
[ { "body": "<p>As pointed out in the comments by both MrVajid and AJNeufeld, the previous solution (now deleted because it is actually irrelevant now; see post history) actually did not work.\nThis is because in reality, the task requires the input array to <em>not</em> be a set, aka it should be allowed to have duplicate entries.</p>\n\n<p>In fact, I had solved that challenge successfully a while ago, using:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>n, m = [int(x) for x in input().split()]\n\narray = [int(x) for x in input().split()]\nA = {int(x) for x in input().split()}\nB = {int(x) for x in input().split()}\n\nhappiness = 0\n\nfor value in array:\n change = 1 if value in A else -1 if value in B else 0\n happiness += change\n\nprint(happiness)\n</code></pre>\n\n<p>This is using <code>set</code> comprehension (<code>{ }</code>) and passes just fine on HackerRank.</p>\n\n<p>Iteration over the input array as a <code>list</code> is still <span class=\"math-container\">\\$O(n)\\$</span>, see <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">here</a>, but containment checks for sets is constant time, <span class=\"math-container\">\\$O(1)\\$</span>. Previously, with <span class=\"math-container\">\\$A\\$</span> and <span class=\"math-container\">\\$B\\$</span> being lists, this was also linear as <span class=\"math-container\">\\$O(m)\\$</span>, leading to <span class=\"math-container\">\\$O(n*m)\\$</span> aka quadratic time complexity.</p>\n\n<p>Since this task on HackerRank is specifically about <code>set</code> usage, it will judge pedantically about time complexity, with only the approach using sets not running into timeout errors.</p>\n\n<hr>\n\n<p>Notice that your solution also has an error apart from the <code>set</code> one.\nYou check for containment in <code>happy_set</code> and decrement <code>happy</code> for a negative result.\nHowever, you first need to check for containment in <code>sad_set</code> first.\nOtherwise, you are much sadder than required.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T06:15:57.587", "Id": "474029", "Score": "0", "body": "Thanks for introducing me to the time complexity analysis and for pointing out the error that makes me much sadder than required. I fixed it and tried submitting it as it is now in the edited question, that still didn't work anyways. `compute_happiness_old` and `compute_happiness_old` both work. It seems like just covering it into `set` does the work. Thanks for helping out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T22:07:33.087", "Id": "474130", "Score": "0", "body": "You have fixed some problem in the OP's code, but introduced other problems. From the actual problem link: \"_However, the array might contain duplicate elements._\" Turning the input array into a set is going to remove duplicates, so if the array contained duplicate happy/sad numbers, those numbers will only count +/- 1, instead of once per occurrence. Your test case cannot generate any duplicate number in the array due to the `random.sample()`, so hides this issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T07:24:35.417", "Id": "474154", "Score": "1", "body": "That is true, but to what degree should questions on here be self-sufficient? In any case, I now rewrote the answer and confirmed it works on HackerRank." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:27:46.310", "Id": "241514", "ParentId": "241503", "Score": "1" } } ]
{ "AcceptedAnswerId": "241514", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T15:14:37.380", "Id": "241503", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Calculate your total happiness, which depends on the integers in the given sets" }
241503
<p>I am trying to work around the problem <a href="https://stackoverflow.com/questions/59876417/pass-through-for-iasyncenumerable">Pass-through for IAsyncEnumerable</a>. The best I have so far is to return <code>IAsyncEnumerable&lt;IAsyncEnumerable&lt;T&gt;&gt;</code> instead of <code>IAsyncEnumerable&lt;T&gt;</code>, then to flatten it. I'm not thrilled about it, so I'm asking here for suggestions. </p> <p>The underlying goal is to allow one to get portions of one's IAsyncEnumerable from child methods without going insane. The Counting() method below is my attempt.</p> <p>I don't think it would be much trouble to design a recursive object in order to allow deeper nesting. But I still don't think I would like it much.</p> <pre><code>public static class AsyncEnumerables { public static async IAsyncEnumerable&lt;T&gt; Flatten&lt;T&gt;(IAsyncEnumerable&lt;IAsyncEnumerable&lt;T&gt;&gt; enumerables) { await foreach (var e in enumerables) { await foreach (var t in e) { yield return t; } } } public static async IAsyncEnumerable&lt;T&gt; Singleton&lt;T&gt;(T t) { await Task.CompletedTask; yield return t; } } public class AsyncEnumerableTests { public async IAsyncEnumerable&lt;int&gt; Children() { yield return 1; await Task.Delay(1000); yield return 2; } public async IAsyncEnumerable&lt;IAsyncEnumerable&lt;int&gt;&gt; Counting() { yield return AsyncEnumerables.Singleton(0); await Task.Delay(100); yield return Children(); yield return AsyncEnumerables.Singleton(3); } [Fact] public async Task Counting_Counts() { var numbers = new List&lt;int&gt;(); await foreach (var n in AsyncEnumerables.Flatten(Counting())) { numbers.Add(n); } Assert.Equal(4, numbers.Count); for (int i=0; i&lt;4; i++) { Assert.Equal(i, numbers[i]); } } } </code></pre>
[]
[ { "body": "<p>There are several things worth considering when you are about to design an API, which should either return an <code>IAsyncEnumerable&lt;IAsyncEnumerable&lt;T&gt;&gt;</code> or return an <code>IAsyncEnumerable&lt;T&gt;</code></p>\n\n<h2>IAsyncEnumerable &lt; IAsyncEnumerable &lt; T > ></h2>\n\n<h3>Pros</h3>\n\n<ul>\n<li>It is flexible from the consumer point of view. It allows you to use a single or multiple consumer model</li>\n<li>In case of multiple consumers the throughput can be higher, because the parallel processing potential</li>\n<li>It allows to use different <code>Timeout</code>s for different providers</li>\n<li>It allows custom code injection between two <code>yield return</code> statements</li>\n</ul>\n\n<h3>Cons</h3>\n\n<ul>\n<li>In case of single consumer the ingestion logic can be a bit more complicated (compared to the flatten version)</li>\n<li>Nested async loops can complicate the exception handling logic (and also the debugging)</li>\n</ul>\n\n<h2>IAsyncEnumerable &lt; T ></h2>\n\n<h3>Pros</h3>\n\n<ul>\n<li>It is easier to use for a single consumer</li>\n<li>If the multiple provider model is just an implementation detail then it can hide this information behind a good abstraction</li>\n<li>It provides easier error handling capabilities</li>\n</ul>\n\n<h3>Cons</h3>\n\n<ul>\n<li>It is harder to support multiple consumers model</li>\n<li>It is harder to inject custom code between <code>yield return</code>s</li>\n<li>Spanning new processing based on different providers is impossible </li>\n</ul>\n\n<p>If you are considering to provide a flattened API then I would suggest to check that package, which is called <a href=\"https://www.nuget.org/packages/System.Interactive.Async/\" rel=\"nofollow noreferrer\">System.Interactive.Async</a>. Inside this package there is a class called <code>AsyncEnumerableEx</code> which defines a <a href=\"https://github.com/dotnet/reactive/blob/305d381dcc46c5966e7260e0959b3083846bf05f/Ix.NET/Source/System.Interactive.Async/System/Linq/Operators/Merge.cs#L13\" rel=\"nofollow noreferrer\">Merge</a> function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-12T08:44:52.093", "Id": "242124", "ParentId": "241505", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T16:12:04.760", "Id": "241505", "Score": "4", "Tags": [ "c#" ], "Title": "Nesting IAsyncEnumerable" }
241505
<p>I have written a Java program that converts an integer to String digit by digit and concatenate them together using the + operator without touching the Stock Java API library.</p> <p>I like to have feedback on my code. Where do I need to improve. If I need to deduct something. So please criticize me. Thank you.</p> <pre><code>import java.util.Scanner; public class StrFromInteger { /* * a single digit is passed as an argument * And a matching digit of String type * is returned. */ public static String returnDigitString(int digit) { String res = ""; switch(digit) { case 0: res = "0"; break; case 1: res = "1"; break; case 2: res = "2"; break; case 3: res = "3"; break; case 4: res = "4"; break; case 5: res = "5"; break; case 6: res = "6"; break; case 7: res = "7"; break; case 8: res = "8"; break; case 9: res = "9"; break; } return res; } public static void main(String[] args) { // TODO Auto-generated method stub //Scan the integer as int Scanner scn = new Scanner(System.in); int number = scn.nextInt(); //find the number of digits using logarithm //if input number is not equal to zero because //log of zero is undefined otherwise if input // number zero length is equal to 1 int input = number; int length = 0; if(number != 0) { length = ( int ) (Math.log10(number) + 1 );} else if(number ==0) { length = 1; } //Save each digit in String format by passing // the integer digit to the returnDigitString() //method one by one String[] reverseStr = new String[length]; String digits = "0123456789"; int remainder =0; int result = number ; --length; number = length; String strSeq = ""; String valStr = ""; // loop through the whole integer digit by digit //use modulo operator get the remainder //save it in remainder. then concatenate valStr //returned from returnDigitString() //method with previous String of Digits. Divide the result by 10. Again //repeat the same process. this time the modulo and the //number to be divided will be one digit less at each decremental //iteration of the loop. for(int i = number; i &gt;= 0; --i) { remainder = result % 10; valStr = returnDigitString(remainder); strSeq = valStr + strSeq; result = result / 10; } //Print the string version of the integer System.out.println("The String conversion of " + input + " is: " + strSeq); } } </code></pre>
[]
[ { "body": "<h1>Things I like about your code</h1>\n\n<ul>\n<li>The idea to calculate the length of a number with the logarithm is really good!</li>\n<li>In my opinion you are writing good comments.</li>\n<li>Good variable names</li>\n<li>Works as intended, without (to my knowledge) any bugs.</li>\n</ul>\n\n<hr>\n\n<h1>Criticism</h1>\n\n<h2>returnDigitString()</h2>\n\n<ul>\n<li>It is considered bad practice to put more than one command into one line. So please make line breaks after every \";\".</li>\n<li>Your solution is pretty long (over 30 lines) in comparison to the complexity of the problem. You could also have done something like that:</li>\n</ul>\n\n<pre><code> public static String returnDigitString(int digit) {\n String res = \"\";\n String[] digits = {\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"};\n for(int i = 0; i &lt;= 9; i++) {\n if(digit == i) {\n res += digits[i];\n break;\n }\n }\n return res;\n }\n</code></pre>\n\n<h2>main()</h2>\n\n<ul>\n<li>You are not using the array \"reverseStr\". The String \"digits\" is not used either.</li>\n<li>When I started your program the first time, I didn't know what to do, because your program didn't tell me. Before scanning a user input, I would tell the user to input something.</li>\n</ul>\n\n<pre><code>System.out.println(\"Please enter number:\");\nScanner scn = new Scanner(System.in);\nint number = scn.nextInt();\n</code></pre>\n\n<p>If you want to improve this point even further (which is highly recommended!), you can use something like that (you will have to use <code>import java.util.InputMismatchException;</code>):</p>\n\n<pre><code>System.out.println(\"Please enter number:\");\nScanner scn = new Scanner(System.in);\nint number;\nwhile(true) {\n try {\n number = scn.nextInt();\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"That's not a number!\");\n scn.nextLine();\n }\n}\n</code></pre>\n\n<p>This will check, whether the user really enters a number. If the user enters something else, the program will ask him again to enter a number.</p>\n\n<ul>\n<li>Something like that is considered bad practice:</li>\n</ul>\n\n<pre><code>if(number != 0) {\nlength = ( int ) (Math.log10(number) + 1 );}\n</code></pre>\n\n<p>Please write</p>\n\n<pre><code>if(number != 0) {\n length = (int) (Math.log10(number) + 1);\n}\n</code></pre>\n\n<p>instead.</p>\n\n<ul>\n<li>\"valStr\" is not necessary. You can just write:</li>\n</ul>\n\n<pre><code>strSeq = returnDigitString(remainder) + strSeq;\n</code></pre>\n\n<p>But this really is a minor point and just my personal opinion. It's fine to use an extra variable for this.</p>\n\n<h2>Codestructure</h2>\n\n<ul>\n<li>I would use an extra method for the content of the main-method. Just use the main-method to call the new method.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T09:20:50.360", "Id": "474035", "Score": "2", "body": "Couldn't the third line of your `returnDigitString` have been `return digits[digit]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T09:28:57.863", "Id": "474036", "Score": "2", "body": "Yes, that's true, but I also wanted to provide an alternative structure to the switch-case-statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:49:21.003", "Id": "474071", "Score": "1", "body": "I'm not so familiar with Java in particular, but the code `for(int i = 0; i <= 9; i++) { if(digit == i) { ... } }` seems like a bad suggestion - it is equivalent to `if(0 <= digit && digit <= 9){ ... }` replacing each instance of `i` with `digit` in `...` - which is far more clear (and more efficient, if we care). It seems like this suggestion gives the wrong impression - if you need to use `switch`, use it. If your code is just dealing with data, look up the data as `digits[digit]`. I don't see any use case for a `for` loop which turns out to be equivalent to an `if` statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T16:30:10.140", "Id": "474078", "Score": "0", "body": "@Milo Brandt, you are abolutely right, but I wanted to avoid long code for a small problem. Of course the solution suggested by Stobor is the best idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T20:41:52.530", "Id": "474117", "Score": "0", "body": "Calculating a logarithm is still a somewhat heavy-hitting exercise. It will also cause this code to break spectacularly when the input number is negative." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:04:42.940", "Id": "241512", "ParentId": "241508", "Score": "7" } }, { "body": "<p>Personally I think your algorithm has been made a lot more complex than needed. </p>\n\n<p>Is the concatenation a requirement? If not, you can simplify by directly converting each digit into a <code>char</code> and storing it in a <code>char[]</code>. This way instead of inefficiently concatenating each digit onto the string, you can use the string constructor overload that takes a <code>char[]</code>.</p>\n\n<p>With this simplification, the method can be reduced to just a few lines:</p>\n\n<pre><code> public static String intToString(int num) {\n if(num == 0){\n return \"0\";\n }\n int count = 0;\n boolean isNeg = false;\n if (num &lt; 0) {\n num *= -1;\n count = 1;\n isNeg = true;\n }\n count += (int) Math.log10(num) + 1;\n char[] digits = new char[count];\n if (isNeg) {\n digits[0] = '-';\n }\n --count;\n while(num &gt; 0) {\n digits[count--] = (char) ((num % 10) + '0');\n num /= 10;\n }\n return new String(digits);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T16:52:10.060", "Id": "474080", "Score": "1", "body": "Might calling `Math.log10()` have a significant overhead (compared to using a `StringBuilder` instead of the `char` array)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T00:55:30.907", "Id": "474137", "Score": "0", "body": "To use a stringbuilder you would have to insert each character at the start or reverse the string. Either way I don't think log10 would be worse than that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:22:49.497", "Id": "241513", "ParentId": "241508", "Score": "9" } }, { "body": "<pre><code>public class StrFromInteger {\n</code></pre>\n<p>This is a convertor, so I would expect some kind of actor in the name, say <code>DecimalStringCreator</code>. What you've currently got is more like a method name.</p>\n<hr />\n<pre><code>public static String returnDigitString(int digit) {\n</code></pre>\n<p>The comment before this function is <strong>almost</strong> a JavaDoc. Generally public methods should be documented with the JavaDoc within <code>/**</code> and <code>*/</code>.</p>\n<p>That something is returned should be logical, try <code>digitToString</code>. As the string is always one character, a <code>digitToCharacter</code> might be better. Unless you want to make it part of programming interface, this method should probably be <code>private</code>.</p>\n<p>Note that an integer might not just be a digit. I would call it <code>digitValue</code> instead and then add a guard statement, such as:</p>\n<pre><code>if (i &lt; 0 || i &gt; 9) {\n throw new IllegalArgumentException(&quot;Value of digit not in the range [0..9]&quot;);\n}\n</code></pre>\n<p>or something similar.</p>\n<hr />\n<pre><code>String res = &quot;&quot;;\n</code></pre>\n<p>Assigning an immutable empty string is almost never a good idea. Don't assign values unless you really have to.</p>\n<hr />\n<pre><code>switch(digit) { ... }\n</code></pre>\n<p>Whenever possible, try and not start calculating yourself. Let the computer handle it. In this case it is important to know that the numbers are all situated in character range <code>0x0030</code> for the zero and <code>0x0039</code> for the 9 - in order of course. The location is not that important, but the order is, as it allows you do to</p>\n<pre><code>char digit = '0' + i;\n</code></pre>\n<p>instead.</p>\n<p>In Java it is perfectly valid to use <code>return &quot;3&quot;;</code> by the way. That way you would not need the many <code>break;</code> statements. Generally we put <code>break</code> on a separate line by the way.</p>\n<hr />\n<pre><code>// TODO Auto-generated method stub\n</code></pre>\n<p>Always remove those kind of comments before posting or - for that matter - checking into source control (e.g. Git).</p>\n<hr />\n<pre><code>public static void main(String[] args) {\n</code></pre>\n<p>A main method is fine for setting up a <code>Scanner</code>, retrieving user input and producing output. But the actual conversion from <code>int</code> to <code>String</code> should be in a separate method.</p>\n<hr />\n<pre><code>//find the number of digits using logarithm\n</code></pre>\n<p>Whenever you type this kind of comment, you should create a method. In this case <code>calculateNumberOfDigits()</code> would be a good name. Now that's clear, you can actually remove the comment - so you would not have to do all that much.</p>\n<hr />\n<pre><code>int input = number;\n</code></pre>\n<p>First of all, the scanner produces the <code>input</code>. You only need one variable for this because neither <code>number</code> or <code>input</code> is ever changed.</p>\n<hr />\n<pre><code>int length = 0;\n</code></pre>\n<p>Another assignment that isn't needed. Java will complain if variables are not assigned. This is useful to find bugs as well, so if the variable is always assigned then specifying a default value is not needed.</p>\n<pre><code>if(number != 0) {\nlength = ( int ) (Math.log10(number) + 1 );}\nelse if(number ==0) {\n length = 1;\n}\n</code></pre>\n<p>Oy, bad indentation and bad usage of white space. This should be:</p>\n<pre><code>if(number != 0) {\n length = (int) (Math.log10(number) + 1);\n} else if(number == 0) {\n length = 1;\n}\n</code></pre>\n<hr />\n<pre><code>String[] reverseStr = new String[length];\n</code></pre>\n<p>String arrays are generally not a good idea. In this case you can always simply perform String concatenation using <code>+</code>. Note that it is completely possible to add Strings / characters at the start of a string as well.</p>\n<hr />\n<pre><code>--length;\n</code></pre>\n<p>Generally we use <code>length--</code>. Don't use <code>--length</code>, unless you need to use the original <code>length</code> value within a larger expression. If possible simply use <code>length--</code> afterwards: expressions without so called <em>side effects</em> are much easier to understand.</p>\n<hr />\n<pre><code>number = length;\n</code></pre>\n<p>Do not reassign variables to other values than that they originally hold. If the meaning of a variable changes then you can be sure that confusion will arise.</p>\n<hr />\n<p>The main idea of getting a list of digits is OK:</p>\n<pre><code>for(int i = number; i &gt;= 0; --i) {\n\n remainder = result % 10;\n\n valStr = returnDigitString(remainder);\n strSeq = valStr + strSeq;\n\n result = result / 10;\n}\n</code></pre>\n<p>But beware of variable naming. <code>result</code> is not really the result that you are looking for; that's the <em>string</em> after all. So another name should be preferred, e.g. <code>numberValueLeft</code> or just <code>valueLeft</code>.</p>\n<p>Note that if <code>valueLeft</code> is zero then the calculation is finished, so that's another way of determining the end of the calculation.</p>\n<hr />\n<p>Here's my take:</p>\n<pre><code>/**\n * Creates a decimal String for a value that is positive or zero.\n * \n * @param value the value to convert\n * @return the string representing the value\n */\npublic static String toDecimalString(int value) {\n // guard statement\n if (value &lt; 0) {\n throw new IllegalArgumentException(&quot;Negative numbers cannot be converted to string by this function&quot;);\n }\n\n if (value == 0) {\n return &quot;0&quot;;\n }\n\n String decimalString = &quot;&quot;;\n\n int left = value;\n while (left &gt; 0) {\n int digitValue = left % 10;\n char digit = (char) ('0' + digitValue);\n decimalString = digit + decimalString;\n left = left / 10;\n }\n\n return decimalString;\n}\n</code></pre>\n<p>Note that you would normally use <code>StringBuilder</code> for this kind of thing, but I presume that that's not allowed in this case.</p>\n<p>I always indicate what kind of string is being returned with a function. I've seen tons of <code>somethingToString()</code> functions that are absolutely unclear of what is being returned. Now I think that a decimal string is what most people expect, but I've also seen <code>somethingToString()</code> functions that return hexadecimals, base 64 or whatnot, so making it clear helps the reader.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T19:33:06.533", "Id": "241518", "ParentId": "241508", "Score": "7" } }, { "body": "<p>Your algorithm only works for values which are zero or positive. Java's \"int\" type is signed, so you need to consider negative numbers too. Your algorithm will fail hard on this, not least because taking a log of a negative number returns NaN, which results in zero when you cast it to int.</p>\n\n<p>Your first step in the algorithm should be to handle the sign of the number. After that you can sort out how to process an unsigned value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T09:48:39.500", "Id": "241543", "ParentId": "241508", "Score": "6" } }, { "body": "<p>Here is my updated code. After this any comments will be highly appreciated.</p>\n\n<pre><code>package IntegerToString;\nimport java.util.Scanner;\n\n\n/**\n * @author Adrian D'Costa \n * @version 1.1 (current version number of program)\n * @since 1.0 (the version of the package this class was first added to)\n */\n\npublic class StrFromInteger {\n\n /* *\n * a single digit is passed as an argument And a matching digit of String\n * type is returned. \n * \n * @param digit a digit of the whole integer\n * \n * @return return a String representation of the digit\n */\n public static String returnDigitString(int digit) {\n String res = \"\";\n\n String[] digits = { \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\" };\n for (int i = 0; i &lt;= 9; i++) {\n if (digit == i) {\n res += digits[i];\n break;\n }\n }\n return res;\n\n }\n /* *\n * Take the input number, if it is less than zero multipy it by -1.\n * loop through the whole integer digit by digit\n * use modulo operator get the remainder\n * save it in remainder. then concatenate valStr\n * returned from returnDigitString()\n * method with previous String of Digits. Divide the result by 10. Again\n * repeat the same process. this time the modulo and the\n * number to be divided will be one digit less at each decremental\n * iteration of the loop. Then print the String and if it is less than zero\n * concatenate \"-\" at the beginning of total String representation of int\n * otherwise just print the String representation of int.\n * \n * @param length number of digits in the integer\n * @param number the integer number itself\n * @param isPosite is positive or not\n */\n public static void printInt(int length, int number, boolean isPositive ) {\n int input = number;\n\n int remainder = 0;\n int result = (number &lt; 0 ? -1 * number : number);\n --length;\n number = length;\n String strSeq = \"\";\n String valStr = \"\";\n\n // loop through the whole integer digit by digit\n // use modulo operator get the remainder\n // save it in remainder. then concatenate valStr\n // returned from returnDigitString()\n // method with previous String of Digits. Divide the result by 10. Again\n // repeat the same process. this time the modulo and the\n // number to be divided will be one digit less at each decremental\n // iteration of the loop.\n for (int i = number; i &gt;= 0; --i) {\n\n remainder = result % 10;\n\n valStr = returnDigitString(remainder);\n strSeq = valStr + strSeq;\n\n result = result / 10;\n }\n if (!isPositive) {\n strSeq = \"-\" + strSeq;\n }\n // Print the string version of the integer\n System.out.println(\"The String conversion of \" + input + \" is: \" + strSeq);\n }\n\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n // Scan the integer as int\n Scanner scn = new Scanner(System.in);\n int number = scn.nextInt();\n\n // find the number of digits using logarithm\n // if input number is not equal to zero because\n // divide the input by 10 each number it will be\n // reduced by 1 digit and increment the length\n int input = number;\n int length = 0;\n if (number != 0) {\n int num = number;\n\n while (num != 0) {\n // num = num/10\n num /= 10;\n ++length;\n\n }\n } else if (number == 0) {\n length = 1;\n }\n printInt(length, input, (input &lt; 0 ? false : true));\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T21:43:24.637", "Id": "241576", "ParentId": "241508", "Score": "1" } } ]
{ "AcceptedAnswerId": "241512", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T16:49:58.160", "Id": "241508", "Score": "5", "Tags": [ "java", "strings", "reinventing-the-wheel", "integer" ], "Title": "Convert Integer to String without using Java API library" }
241508
<p>The <a href="https://en.wikipedia.org/wiki/Permutation_matrix" rel="nofollow noreferrer">permutation matrix</a> is represented as a list of positive integers, plus zero. The number indicates the position of the 1 in that row, e.g. a number zero would mean that the 1 is in the right-most position². </p> <p>My first attempt is as follows, together with a printing function to help assess the result. It seems too convoluted to me. Please note that a permutation matrix multiplication is simpler than an ordinary matrix multiplication.</p> <pre><code>def transpose(m): """Transpose a permutation matrix. m: list of positive integers and zero.""" c = {} idx = 0 for row in reversed(m): c[-row] = idx idx += 1 return list(map( itemgetter(1), sorted(c.items(), reverse=False, key=itemgetter(0)) )) def print_binmatrix(m): """Print a permutation matrix 7x7. m: list of positive integers and zero.""" for row in m: print(format(2 ** row, '07b'), row) # Usage example with a matrix 35x35. Ideally, it should scale up without sacrificing speed at smaller matrices like this. transpose([8, 4, 21, 17, 30, 28, 1, 27, 5, 3, 16, 12, 11, 14, 20, 6, 33, 19, 22, 25, 31, 15, 13, 18, 10, 0, 7, 2, 9, 23, 24, 26, 29, 32, 34]) # Result [25, 6, 27, 9, 1, 8, 15, 26, 0, 28, 24, 12, 11, 22, 13, 21, 10, 3, 23, 17, 14, 2, 18, 29, 30, 19, 31, 7, 5, 32, 4, 20, 33, 16, 34] </code></pre> <p>[2]: This way, the "zero matrix" is the one with 1's in the secondary diagonal, since only one 1 is allowed per column.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:28:31.857", "Id": "473961", "Score": "0", "body": "What are you trying to optimize, speed or memory usage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:29:28.513", "Id": "473962", "Score": "0", "body": "Can you clarify how you are encoding a \"permutation matrix\" as a list of natural numbers? Do the list values represent the zero-based index of the \"1\" in each row of the permutation matrix?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:42:27.593", "Id": "473964", "Score": "0", "body": "And when you say _efficiently_ - does that include pulling in libraries (numpy) to do this properly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:43:28.337", "Id": "473965", "Score": "0", "body": "Also, can you include code in your question that calls your functions with realistic data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:45:12.187", "Id": "473966", "Score": "0", "body": "@pacmaninbw speed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:45:47.400", "Id": "473967", "Score": "0", "body": "@Nick2253 The number indicates the position of the 1 in that row, e.g. a number zero would mean that the 1 is in the right-most position" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T18:46:43.070", "Id": "473968", "Score": "0", "body": "@Reinderien If there is a library that helps, no problem using it." } ]
[ { "body": "<p>Perhaps only marginally, but the readability of your code can be improved by using <code>enumerate</code> and the <code>reverse=True</code> flag in <code>sorted</code>.</p>\n\n<pre><code>def transpose_r(ls): \n return [len(ls)-1-k\n for k, Pk in sorted(enumerate(ls), \n reverse=True, \n key=itemgetter(1))]\n</code></pre>\n\n<p>If we index starting from the left, then this is further simplified.</p>\n\n<pre><code>def transpose_l(ls): \n return [x for x, Px in sorted(enumerate(ls), key=itemgetter(1))]\n</code></pre>\n\n<hr>\n\n<p>The transpose has the funny property that <code>transpose(ls)[ls[j]] == j</code>. We can use this to build the transpose without sorting.</p>\n\n<pre><code>def transpose_l(ls):\n tr_ls = [0]*len(ls)\n\n for l in ls:\n tr_ls[ls[l]] = l\n\n return tr_ls\n\ndef transpose_r(ls):\n n = len(ls)\n tr_ls = [0]*n\n\n for l in ls:\n tr_ls[n - 1 - ls[l]] = n - 1 - l\n\n return tr_ls\n</code></pre>\n\n<p>Alternatively, we can use <code>enumerate</code> again.</p>\n\n<pre><code>def transpose_l(ls):\n tr_ls = [0]*len(ls)\n\n for ix, l in enumerate(ls):\n tr_ls[l] = ix\n\n return tr_ls\n\ndef transpose_r(ls):\n n = len(ls)\n tr_ls = [0]*n\n\n for ix, l in enumerate(ls):\n tr_ls[n - 1 - l] = n - 1 - ix\n\n return tr_ls\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T21:53:30.730", "Id": "473988", "Score": "0", "body": "Your third option is 3 times faster. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:05:10.087", "Id": "473991", "Score": "0", "body": "However the result doesn't seem to match." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:16:29.563", "Id": "473994", "Score": "0", "body": "@viyps The `transpose_l` functions assume indexing from the left! I've added the `_r` versions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:35:12.260", "Id": "473996", "Score": "1", "body": "Ok! The R version is also faster. I have another problem which is to convert a number to such matrices, it has much more room for optimization, but it is far more involved to explain. If you are interested I can post another question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:37:56.033", "Id": "473997", "Score": "1", "body": "@viyps Sure, go ahead. If not I, someone else will surely give you some tips!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:59:24.157", "Id": "473999", "Score": "0", "body": "[https://codereview.stackexchange.com/questions/241530/converting-a-natural-number-to-a-permutation-matrix-in-python-how-to-speed-it-u]" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T21:11:07.333", "Id": "241524", "ParentId": "241511", "Score": "3" } } ]
{ "AcceptedAnswerId": "241524", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T17:53:57.207", "Id": "241511", "Score": "3", "Tags": [ "python", "python-3.x", "matrix" ], "Title": "How to efficiently (fast) calculate the transpose of a *permutation matrix* in Python3?" }
241511
<p>I have a questions as to the proper way to structure the code below.</p> <p>This snippet of code is used within a socket class which is intended to be a high performance socket. Many data handlers subscribe to this sockets <code>OnData</code> event to handle different types of data. Ideally, I'm trying to kick the data handlers off in a task and in parallel where the <code>HandleData</code> method is invoked once the socket has received data.</p> <p>1) Should I make this method async and await the task?</p> <p>2) Should I capture a copy of the delegates inside the task?</p> <p>3) Is there a better way to accomplish this?</p> <pre><code> private void HandleData(string message) { var data = JObject.Parse(message); var delegates = OnData?.GetInvocationList(); if (delegates != null) { Task.Run(() =&gt; { Parallel.ForEach(delegates, d =&gt; { try { d.DynamicInvoke(data); } catch (Exception) { /* Ignore */ } }); }); } } </code></pre>
[]
[ { "body": "<p>I think that unless benchmarking proves otherwise, you should simply <code>OnData?.BeginInvoke()</code> and just let the thread pool handle it for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T11:53:06.970", "Id": "474327", "Score": "0", "body": "The answer was to benchmark it. I guess laziness came over me after a long day and thought it would be easier to ask the question than benchmark it. The code snippet in question came out quickest. I made a slight adjustment by moving the json parsing logic to inside the task as if there are no subscribers it's wasting computational time. I'll mark this as answer on the basis of the benchmarking comment and a kick up the ass to write some code! Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T13:08:08.050", "Id": "474341", "Score": "0", "body": "Didn't mean to kick no one's ass :) I'm a bit surprised because I expected that BeginInvoke() would perform better. Was the difference significant?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T13:36:37.343", "Id": "241554", "ParentId": "241520", "Score": "0" } } ]
{ "AcceptedAnswerId": "241554", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T20:51:51.913", "Id": "241520", "Score": "1", "Tags": [ "c#", "task-parallel-library" ], "Title": "Invoking subscribers of an action in parallel c#" }
241520
<h3>Description</h3> <p>Simply take a JSON file as input and convert the data in it into a CSV file. I won't describe the functionality in too much detail since I have reasonable docstrings for that. As you can see, my solution is not memory efficient since I'm reading all the file into memory.</p> <p>I'd like to improve the performance of my solution as much as possible. (perhaps not load everything at once into memory -- even if it's gonna be slower).</p> <p>The JSON file that I'm trying to convert is 60 GB and I have 64GB of RAM.</p> <hr /> <h3>Code</h3> <pre><code>import csv import json CSV_PATH = 'file.csv' JSON_PATH = 'file.json' def flattenjson(json_data, delim): &quot;&quot;&quot; Flatten a simple JSON by prepending a delimiter to nested children. Arguments: json_data (dict): JSON object e.g: { &quot;key1&quot;: &quot;n1_value1&quot;, &quot;key2&quot;: &quot;n1_value2&quot;, &quot;parent1&quot;: { &quot;child_key1&quot;: &quot;n1_child_value1&quot;, &quot;child_key2&quot;: &quot;n1_child_value2&quot; } } delim (str): Delimiter for nested children (e.g: '.') Returns: Flattened JSON object. e.g: { 'key1': 'n1_value1', 'key2': 'n1_value2', 'parent1.child_key1': 'n1_child_value1', 'parent1.child_key2': 'n1_child_value2' } &quot;&quot;&quot; flattened_json = {} for i in json_data.keys(): if isinstance(json_data[i], dict): get = flattenjson(json_data[i], delim) for j in get.keys(): flattened_json[i + delim + j] = get[j] else: flattened_json[i] = json_data[i] return flattened_json def write_json_to_csv(flattened_json, csv_path): &quot;&quot;&quot; Write flattened json to a csv file. The keys of the json will be the header of the csv and the values..well, the values ^_^. Arguments: flattened_json (dict): Flattened JSON object. e.g: { 'key1': 'n1_value1', 'key2': 'n1_value2', 'parent1.child_key1': 'n1_child_value1', 'parent1.child_key2': 'n1_child_value2' } csv_path (str): path of the CSV file Returns: None &quot;&quot;&quot; with open(csv_path, 'w') as out_file: w = csv.DictWriter(out_file, flattened_json.keys()) w.writeheader() w.writerow(flattened_json) def main(): &quot;&quot;&quot; Main entry to our program. &quot;&quot;&quot; with open(JSON_PATH) as json_file: json_data = json.load(json_file) flattened_json = flattenjson(json_data, '.') write_json_to_csv(flattened_json, CSV_PATH) if __name__ == '__main__': main() </code></pre> <hr /> <h3>More about input / output</h3> <ul> <li>I don't know where the JSON file comes from so I have to stick with it and process it as is.</li> <li>I can't change the structure of the JSON file</li> <li>As far I saw, the JSON data will be at most 7 level-nested so we could have something like:</li> </ul> <pre><code>{ &quot;a&quot;: &quot;1&quot;, &quot;b&quot;: &quot;2&quot;, &quot;c&quot;: { &quot;c_1&quot;: &quot;3&quot;, &quot;c_2&quot;: &quot;4&quot; }, &quot;d&quot;: { &quot;d_1&quot;: { &quot;d_1_1&quot;: &quot;5&quot;, &quot;d_1_2&quot;: &quot;6&quot; }, &quot;d_2&quot;: { &quot;d_2_1&quot;: &quot;5&quot;, &quot;d_2_2&quot;: &quot;6&quot; } ... and so on } } </code></pre> <ul> <li>I have to write the data to the CSV file as described above.</li> <li>The CSV for the above JSON will look like this:</li> </ul> <p><a href="https://i.stack.imgur.com/QlsVr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QlsVr.png" alt="enter image description here" /></a></p> <p>I'm specifically looking for a review orientated on memory optimizations which probably comes with a cost of a slower running time (that's fine) but any other overall improvements are welcome!</p> <p>PS: I've done the above in Python 3.8.2 so I'd like you to focus on a version of Python &gt;= 3.6</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T21:56:11.393", "Id": "473989", "Score": "1", "body": "In NodeJS we have something called \"streaming\" which is basically the same as what happens when you're watching a movie on Netflix or a video on YouTube. In short you take a source, \"pipe it\" and output it. Just like a water-hose. It loads chunks of the data in memory, processes it, outputs it and when it's ready to take more it'll load a new chunk. Isn't there something similar for Python? I know that NodeJS has it build in by default using the \"readDataStream\" method. Makes more sense than loading the whole 60GB in memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:03:46.503", "Id": "473990", "Score": "0", "body": "Seems like Python core module I/O is what you'll need. https://docs.python.org/3/library/io.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T23:25:53.510", "Id": "474002", "Score": "0", "body": "Not quite. In this case you’d probably need to get all the keys beforehand so you can build the header of the csv and only then you might be able to iterate over chunked data and add it to the csv. But IDK if that’s the way to go hence this question here ^^ Thanks for the feedback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T23:30:22.557", "Id": "474004", "Score": "1", "body": "Just check if there are any keys in the chunk that are not yet in the CSV header and if so add them. Streaming is meant exactly for use-cases like this. But I'm not proficient in Python at all. I'm curious to the solution! Goodluck" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T01:40:03.090", "Id": "474222", "Score": "0", "body": "Why don't aren't there 4 rows in the example? I would think there should be a new row for each top level key. Otherwise, you'll end up with one very long row." } ]
[ { "body": "<p>A classic pattern is to set a ceiling for memory consumption and write a buffer function. Once you hit the buffer limit, dump everything to a partial file (\"file_part1.csv\") and begin writing to the next partial file. Once you're done writing everything, stitch the files together as a single csv.</p>\n\n<p>Chapter 12 of the free Python reference \"<a href=\"https://www.py4e.com/\" rel=\"nofollow noreferrer\">Python for Everybody</a>\" demonstrates the pattern. The chapter is written about networked programs, but the examples still apply.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T12:53:00.163", "Id": "474177", "Score": "0", "body": "The format of the CSV output is not good for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:48:53.980", "Id": "476734", "Score": "0", "body": "The original poster's stated purpose is to create a csv file. When I post here I always try to keep in mind what the OP is asking for!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-25T16:51:00.863", "Id": "476735", "Score": "0", "body": "Yes but the order of the output is important. If the output were being added vertically then your solution would be viable. Since it's not you're still stuck with the same problem with merging multiple data sets horizontally." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T02:55:45.607", "Id": "241535", "ParentId": "241521", "Score": "0" } }, { "body": "<p>It looks like the actual processing is quite simple, so I would recommend using a <em>streaming</em> JSON parser like <a href=\"https://stackoverflow.com/a/31980076/96588\"><code>jq --stream</code></a> or (in Python) <a href=\"https://pypi.org/project/ijson/\" rel=\"nofollow noreferrer\">ijson</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T03:51:09.720", "Id": "241537", "ParentId": "241521", "Score": "2" } }, { "body": "<p>Your script seems to create a one row csv file with each data element having a separate column. That didn't seem to make much sense, so here's a script that creates a new csv row for each top-level object in the json file. I suspect this still isn't what you want, because each unique data element gets its own column in the csv file. The script provides an outline; you can change the two passes to get what you want.</p>\n\n<p>The script that does two passes over the json file. First pass is to get the column names. The second pass creates the csv file. I used StringIO for testing, you'll want to change <code>StringIO</code> to <code>open</code> (e.g., <code>with open(...) as f</code>). It uses the <code>ijson</code> library to incrementally read the json file. Also, the script only handles string data, because that's what is in the example data.</p>\n\n<pre><code>import csv\nimport ijson\nimport io\n\nfrom collections import ChainMap\n\ndefaults = {}\n\n#first pass through json data collect all collumn names\n#they will be used for the field names in the csv file\n# and for default values when writing the csv file\nwith io.StringIO(jsondata) as jsonfile:\n for (prefix, event, value) in ijson.parse(jsonfile):\n if event == \"string\":\n defaults[prefix] = ''\n\n\n# row.maps[0] will be updated as each new top level json objec\n# is read from the json file. row.maps[1] holds the default values\n# for csv.DictWriter\nrow = ChainMap({}, defaults)\n\n# StringIO is used for prototyping, you'll probably want to \n# change them to `open(filename, ...)` or something\nwith io.StringIO(jsondata) as jsonfile, io.StringIO() as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=list(defaults.keys()))\n\n for (prefix, event, value) in ijson.parse(jsonfile):\n if event == \"string\":\n row[prefix] = value\n\n # if we're at the top-level key (prefix=='') and we are starting a new\n # row (event=='map_key') or were all done (event=='end_map') and there is\n # a row to write (row.maps[0] not empty), then write a row to the csvfile\n # and clear the row for the next top level json object\n elif prefix=='' and event in ('map_key', 'end_map') and row.maps[0]:\n print(row)\n writer.writerow(row)\n row.maps[0].clear()\n\n # this is to see what would be in the file. It's here, inside the with\n # because the `csvfile` gets deleted when the `with` statement ends\n print(csvfile.getvalue())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:59:06.883", "Id": "241646", "ParentId": "241521", "Score": "1" } } ]
{ "AcceptedAnswerId": "241537", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T20:56:02.813", "Id": "241521", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "json", "csv" ], "Title": "Efficiently convert 60 GB JSON file to a csv file" }
241521
<p>I am working on a custom bot UI with Microsoft Bot Framework. I found a template to create a floating widget with Materialize, however, it was for the "embed" version of webchat UI. My version uses some Divs to add additional elements (header, transcript button). These elements were in conflict with the Materialize CSS.</p> <p>Through a lot of trial an error, I was able to override the settings that were causing issues. In addition to figuring out the right class and div names, I had to use <code>!important</code> to get my settings to stick. And the problem is actually worse than that. When I imported the Materialize CSS onto the page I ultimately will deploy the chatbot on to, it caused the same kind of formatting issues on that webpage itself.</p> <p>So ultimately, my question is this: <strong>Is there a way to force the Materialize CSS to be subservient to any other CSS? Or is there a way to pull out just the CSS for the elements I need for my chatbot UI</strong>, hopefully eliminating the conflicts? In addition to fixes for my current code, and suggestions for other frameworks to use to accomplish the same sort of thing (floating button that expands into a floating chat window) would be appreciated as well.</p> <p>The key point is that I need to make sure that I have the right CSS for the button/floating chat widget to work without overriding the existing CSS for my chatbot UI or the webpage it's going on.</p> <p>Here is the CSS:</p> <pre class="lang-html prettyprint-override"><code> &lt;!--Import Google Icon Font--&gt; &lt;link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"&gt; &lt;!--There is a conflict with this css specification and my own chat specification--&gt; &lt;!--Import materialize.css--&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"&gt; &lt;style&gt; html, body { height: 100%; } input { margin: 0 !important; border: 0 !important; padding: 0 !important; height: 100% !important; } input:focus { border-bottom: none !important; box-shadow: none !important; } form { margin: 0 !important; border: 0 !important; } html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; } #chatbotTitle { display: flex; align-items: center; height: 40px; width: 100%; background-color: #0067CC; color: #FFFFFF; font-family: Calibri, Helvetica Neue, Arial, sans-serif; justify-content: space-between; padding-left: 10px; } #webchat { height: calc(100% - 40px); width: 100%; } .button { display: flex; background-color: white; border: 1px solid #767676; color: #0067CC; text-align: center; align-items: center; margin: 15px; height: 25px; width: 100px; } .button:hover { border-color: #444444; } .button:active { background-color: #CCCCCC; } b { font-size: 1.25em !important; } @media screen and (max-width: 600px) { b { font-size: 1.2em !important; } .button { font-size: 0.8em; font-weight: bold; } #webchatContainer { width: calc(100vw - 2em) !important; height: calc(85vh - 2em) !important; max-width: calc(100vw - 2em) !important; max-height: calc(85vh - 2em) !important; top: 1em !important; } } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;img src="myEatonStatic.png"&gt;&lt;/img&gt; &lt;a id="chatButton" class="btn-large waves-effect waves-light" style="position: fixed;z-index: 10000;top: 8em;right: 0em;background:#0067cc; padding: 0 1em 0 1em;"&gt; &lt;i class="material-icons"&gt;chat&lt;/i&gt; &lt;/a&gt; &lt;div id="webchatContainer" class="z-depth-1 scale-transition scale-out" style="background:white; border: 1px solid #0078d7;position: fixed;z-index: 5000;bottom: 6em;right: 1em;width: 400px; max-width: calc(100% - 1em);height: 78vh;min-height: 400px;max-height: calc(100% - 6em)"&gt; &lt;div id="chatbotTitle"&gt;&lt;b&gt;OEM CSC Support Bot&lt;/b&gt;&lt;button class="button" id="transcriptButton"&gt;Get Transcript&lt;/button&gt;&lt;/div&gt; &lt;div id="webchat" role="main"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T05:44:39.700", "Id": "474025", "Score": "0", "body": "[\"How-to\"s are off topic](https://codereview.stackexchange.com/help/on-topic) with one possible exception: *This code works as intended. But I harbour misgivings a, b, and possibly c. **How to** cope?*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T12:45:05.480", "Id": "474050", "Score": "1", "body": "Sure, I'll see if I can modify the title. The code DOES work, but I definitely have misgivings about how it affects the parent website!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T20:35:51.213", "Id": "474116", "Score": "0", "body": "Can you tell us more about those conflicts and how your code works despite them?" } ]
[ { "body": "<p>Let us keep this brief:</p>\n\n<blockquote>\n <p>Is there a way to force the Materialize CSS to be subservient to any other CSS?</p>\n</blockquote>\n\n<h1>Nope, sorry.</h1>\n\n<p>CSS does not work that way. With CSS, you style elements with increasingly <em>specific</em> selectors, but the least specific styles will always apply, no matter what. You can only overwrite them.</p>\n\n<p><a href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.css\" rel=\"nofollow noreferrer\">A quick ctrl+f in the Materialzed stylesheet</a> tells me it specifies a style for <code>button</code> very non-specifically, so it will definitely interfere with any button on any page using it.</p>\n\n<p>Your two options now are:</p>\n\n<ul>\n<li>Make your selectors <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity\" rel=\"nofollow noreferrer\">more specific</a>.</li>\n<li>Hack your way through it with <code>!important</code> (assigning the highest styling specificity thus overwriting everything), or through a hacky use of <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/all\" rel=\"nofollow noreferrer\">the <code>all: unset</code> property</a>.</li>\n</ul>\n\n<p>The last option is not really an option, please do not do that ):</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T12:43:24.610", "Id": "474049", "Score": "0", "body": "Thanks. The biggest issue isn't my UI, it's the corporate page we're deploying it to. And we aren't going to be able to restyle the entire corporate page just to support this UI. So it seems perhaps that finding just the elements that I need for my UI styling and pulling them out (i.e. defining them in my own stylesheet) might be the way to go? I can definitely make my styles more specific, but just importing the Materialize CSS without any of my bot UI code messes up the corporate site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T13:17:59.440", "Id": "474053", "Score": "1", "body": "@billoverton You might be able to screw around with [shadow-dom styling](https://css-tricks.com/encapsulating-style-and-structure-with-shadow-dom/) ([similar to `<style scoped>`](https://css-tricks.com/saving-the-day-with-scoped-css/)), which is a bit of a hack if you're not using it for custom elements, or find another way to ensure the CSS doesn't leak without altering your CSS. My experience is that css libraries aren't worth the hassle. Why use google's styleguide for your company's website anyways? ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T13:52:03.733", "Id": "474056", "Score": "0", "body": "I'm not a web developer so I needed a template to implement a floating widget. I'm sure I could find a different way, but the Materialize classes take care of the floating button and the show/hide of the chat window. I haven't found any other good templates to do this. I made the widget work with it before finding out Materialize messed up the corporate site too... May sound strange, but we don't have any corporate resources to do this UI design for us. I'm having one of my peers experiment with Angular but we've had no progress on that so far. Thanks for the additional suggestion!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T20:25:58.907", "Id": "474462", "Score": "0", "body": "Though my question was downvoted and closed, your suggestion and link to using specificity was just what I needed. Still have some changes to make, but I've eliminated a vast majority of the interference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T14:53:51.107", "Id": "474556", "Score": "1", "body": "@billoverton That's great to hear -- glad to have sent you on the right track. Stackoverflow has always been so incredibly unwelcoming to people asking questions so I am happy I could help you before it was closed." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T10:41:11.120", "Id": "241545", "ParentId": "241522", "Score": "1" } } ]
{ "AcceptedAnswerId": "241545", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T21:02:35.923", "Id": "241522", "Score": "-1", "Tags": [ "javascript", "css" ], "Title": "Created Floating Widget with Materialize, but I'm concerned about impact on parent websites I embed it in" }
241522
<p>I wrote 2 different implementations to find gcd of 2 big numbers. The simple one using Euclid's algorithm always beat the Binary algorithm in term of speed. Is my implementation of Binary algorithm bad?</p> <pre><code>a = 5**100 - 1 b = 5**120 - 1 def gcd_euclid_recursive(a, b): if b == 0: return a return gcd_euclid_recursive(b, a % b) def gcd_binary_recursive(a, b): if a == b: return a if a == 0: return b if b == 0: return a if a &amp; 1 == 0: # a is even if b &amp; 1 == 1: # b is odd return gcd_binary_recursive(a &gt;&gt; 1, b) else: # both a and b are even return gcd_binary_recursive(a &gt;&gt; 1, b &gt;&gt; 1) &lt;&lt; 1 if b &amp; 1 == 0: # a is odd and b is even return gcd_binary_recursive(a, b &gt;&gt; 1) if (a &gt; b): return gcd_binary_recursive((a-b) &gt;&gt; 1, b) return gcd_binary_recursive((b-a) &gt;&gt; 1, a) </code></pre>
[]
[ { "body": "<p>Your implementation is as efficient as it can be in python. Because python is an interpreted language, every statement that is executed takes a long time compared to something like c.</p>\n\n<p>At the bottom of this answer is an altered version of your code that times 1000 evaluations of both of the functions. It also records the total amount of time spent evaluating the first three lines of the binary algorithm.</p>\n\n<p>Below is the output of the code:</p>\n\n<pre><code>Euler: 0.0010025501251220703\nBinary1: 0.2012491226196289\nFirst three lines: 0.04787778854370117\n</code></pre>\n\n<p>The amount of time spent checking for a==b, a==0, and b==0 takes longer than the entire Euler algorithm. It should be noted that the binary algorithm is only supposed to be faster when dealing with \"regular\" arithmetic. From the Wikipedia page on the binary gcd algorithm:</p>\n\n<p>\"For arbitrary-precision arithmetic, neither the Euclidean algorithm nor the binary GCD algorithm are fastest, as they both take time that is a quadratic function of the number of input digits.\"</p>\n\n<pre><code>first_three_lines = 0\n\ndef gcd_euclid_recursive(a, b):\n if b == 0: return a\n return gcd_euclid_recursive(b, a % b)\n\ndef gcd_binary_recursive(a, b):\n global first_three_lines\n t = time()\n if a == b: return a\n if a == 0: return b\n if b == 0: return a\n first_three_lines += time() - t\n\n if a &amp; 1 == 0: # a is even\n if b &amp; 1 == 1: # b is odd\n return gcd_binary_recursive(a &gt;&gt; 1, b)\n else: # both a and b are even\n return gcd_binary_recursive(a &gt;&gt; 1, b &gt;&gt; 1) &lt;&lt; 1\n\n if b &amp; 1 == 0: # a is odd and b is even\n return gcd_binary_recursive(a, b &gt;&gt; 1)\n\n if (a &gt; b):\n return gcd_binary_recursive((a-b) &gt;&gt; 1, b)\n return gcd_binary_recursive((b-a) &gt;&gt; 1, a)\n\na = 5**100 - 1\nb = 5**120 - 1\n\n\nfrom time import time\neuler_time = 0\nfor i in range(1000):\n t = time()\n x = gcd_euclid_recursive(a,b)\n euler_time += time() - t\n\nbin_time = 0\nfor i in range(1000):\n t = time()\n x = gcd_binary_recursive(a,b)\n bin_time += time() - t\n\nprint(\"Euler: \",euler_time)\nprint(\"Binary1: \",bin_time)\nprint(\"First three lines:\",first_three_lines)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T03:57:42.363", "Id": "241538", "ParentId": "241525", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T21:43:32.370", "Id": "241525", "Score": "1", "Tags": [ "python" ], "Title": "Python GCD implementations" }
241525
<p>The program asks the user to enter values for items bought, the price of each item, the GST rate, the QST rate. The program calculates the subtotal based on these inputs. For every invalid input entered by the user the program will prompt the user to re-enter that value until it is a valid input. Items bought must be between 1 and 10. The price of each item must be between 1 and 1000. The GST must be between 0 and 14. The QST must be between 0 and 17.</p> <p>Im wondering if there's a way I can make this code more efficient by including more methods or anything else. Thanks! </p> <pre><code>import java.util.Scanner; public class Taxes{ public static void main(String[] args){ double subtotal = 0; int errors = 0; Scanner scan = new Scanner(System.in); System.out.println("Please enter the number of items bought (1-10): "); int num_items = scan.nextInt(); while (num_items &lt; 1 || 10 &lt; num_items){ errors += 1; System.out.println("Please enter the number of items bought (1-10): "); num_items = scan.nextInt(); } for (int i = 1; i &lt;= num_items; i++){ Scanner scn = new Scanner(System.in); System.out.println("Please enter the price of item " + i); Double item_cost = scn.nextDouble(); while (item_cost &lt; 1 || 1000 &lt; item_cost){ errors += 1; System.out.println("Please enter the price of item " + i); item_cost = scn.nextDouble(); } subtotal += item_cost; } System.out.println("Please enter the tax rate of GST in %: "); double gRate = scan.nextDouble(); while (gRate &lt; 0 || 14 &lt; gRate){ errors += 1; System.out.println("Please enter the tax rate of GST in %: "); gRate = scan.nextDouble(); } System.out.println("Please enter the tax rate of QST in %: "); double qRate = scan.nextDouble(); while (qRate &lt; 0 || 17 &lt; qRate){ errors += 1; System.out.println("Please enter the tax rate of QST in %: "); qRate = scan.nextDouble(); } calculate(subtotal, gRate, qRate, errors); } public static void calculate(double subtotal, double gRate, double qRate, int errors) { double gst = subtotal * (gRate/100); double qst = (subtotal + gst) * (qRate/100); double total = subtotal + gst + qst; System.out.println("GST: " + gst); System.out.println("QST: " + qst); System.out.println("Subtotal: " + total); System.out.println("You entered " + errors + " invalid inputs"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T01:32:26.900", "Id": "474007", "Score": "3", "body": "Please change the title to show what you're doing (something like \"Tax calculator with command-line interface\")." } ]
[ { "body": "<h2>Style</h2>\n\n<ul>\n<li>Please use proper indentation. It is generally considered good practice to indent the code inside a method. This will make your code more legible.</li>\n<li>The use of curly brackets is inconsistent (have a look at the <code>calculate</code>-method. In Java, the most common use of curly brackets looks like this:</li>\n</ul>\n\n<pre><code>public static void calculate(...) {\n //Commands here\n}\n</code></pre>\n\n<ul>\n<li>For variable names the lowerCamelCase is used. So <code>num_items</code> becomes <code>numItems</code> and <code>item_cost</code> becomes <code>itemCost</code>.</li>\n</ul>\n\n<hr>\n\n<h2>Input</h2>\n\n<p>You have been thinking about how to stop the user from making invalid inputs. You are using:</p>\n\n<pre><code>while (numItems &lt; 1 || 10 &lt; numItems) {\n errors += 1;\n System.out.println(\"Please enter the number of items bought (1-10): \");\n numItems = scan.nextInt();\n }\n</code></pre>\n\n<p>This will stop the user entering other numbers than intended. The problem is that your program crashes, when the user enters not even a number (for example \"hi\"). This can be solved with the following code (use <code>import java.util.InputMismatchException;</code>):</p>\n\n<pre><code>while(true) {\n try {\n numItems = scn.nextInt();\n if(numItems &lt; 1 || 10 &lt; numItems) {\n throw new InputMismatchException()\n }\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"Invalid Input!\");\n scn.nextLine();\n }\n}\n</code></pre>\n\n<p>Also, you have initialized more than one scanner in your program. That's not necessary. Just initialize one in the beginning and use it for the whole time.</p>\n\n<hr>\n\n<h2>Other</h2>\n\n<ul>\n<li>I removed the variable <code>errors</code>, because it is not useful to tell the user how many errors he/she made. But that's just a personal opinion.</li>\n<li>It's not necessary to restrict the number of items and their prices, but I have left it in the code so you can see how to restrict it.</li>\n</ul>\n\n<p>All in all your code could look like this:</p>\n\n<pre><code>import java.util.Scanner;\nimport java.util.InputMismatchException;\n\npublic class Taxes {\n\n public static void main(String[] args) {\n\n double subtotal = 0;\n Scanner scan = new Scanner(System.in);\n System.out.println(\"Please enter the number of items bought (1-10): \");\n int numItems;\n while(true) {\n try {\n numItems = scan.nextInt();\n if(numItems &lt; 1 || 10 &lt; numItems) {\n throw new InputMismatchException();\n }\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"Invalid Input!\");\n scan.nextLine();\n }\n }\n\n for (int i = 1; i &lt;= numItems; i++) {\n System.out.println(\"Please enter the price of item \" + i);\n Double itemCost;\n while(true) {\n try {\n itemCost = scan.nextDouble();\n if(itemCost &lt; 1 || 1000 &lt; itemCost) {\n throw new InputMismatchException();\n }\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"Invalid Input!\");\n scan.nextLine();\n }\n }\n subtotal += itemCost;\n }\n System.out.println(\"Please enter the tax rate of GST in %: \");\n double gRate;\n while(true) {\n try {\n gRate = scan.nextDouble();\n if(gRate &lt; 0 || 14 &lt; gRate) {\n throw new InputMismatchException();\n }\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"Invalid Input!\");\n scan.nextLine();\n }\n }\n System.out.println(\"Please enter the tax rate of QST in %: \");\n double qRate;\n\n while(true) {\n try {\n qRate = scan.nextDouble();\n if(qRate &lt; 0 || 17 &lt; qRate) {\n throw new InputMismatchException();\n }\n break;\n }\n catch(InputMismatchException e) {\n System.out.println(\"Invalid Input!\");\n scan.nextLine();\n }\n }\n\n calculate(subtotal, gRate, qRate);\n }\n\n\n public static void calculate(double subtotal, double gRate, double qRate) {\n double gst = subtotal * (gRate/100); \n double qst = (subtotal + gst) * (qRate/100);\n double total = subtotal + gst + qst;\n System.out.println(\"GST: \" + gst);\n System.out.println(\"QST: \" + qst);\n System.out.println(\"Subtotal: \" + total);\n }\n}\n</code></pre>\n\n<p>I will leave it to you to comment the code properly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T03:30:14.377", "Id": "241536", "ParentId": "241529", "Score": "1" } } ]
{ "AcceptedAnswerId": "241536", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:36:24.227", "Id": "241529", "Score": "1", "Tags": [ "java", "calculator" ], "Title": "Hi there! I've recently been getting into java and was wondering how I can clean up or condense the code for this problem I've been working on" }
241529
<p>It is something a bit complex to explain here, but the code bellow takes a 128-bit number and converts it into a <a href="https://codereview.stackexchange.com/questions/241511/how-to-efficiently-fast-calculate-the-transpose-of-a-permutation-matrix-in-p">permutation matrix, a beast which I have already faced before</a>. The matrix is represented as a list of numbers. Each number is a row. The way I've found to do the mapping number->matrix was to convert the number through a <a href="https://math.stackexchange.com/questions/3652556/is-there-any-stablished-concept-of-a-numeric-base-that-increases-linearly-the-al">multi-radix (or something that could be considered one) </a> numeric system, so each digit corresponds to a row in the matrix. Since there can't be duplicate rows, some offset magic was needed (that is one of the uses of map <code>taboo</code> used below). How could this code be improved regarding data structures and use of loops? More conceptually, what about my choice of conversion through a multi-radix system? Could it be simpler and still be a perfect mapping from naturals to permutation matrices?</p> <p>ps. There are 2^128 numbers and 35! matrices. <code>2^128 &lt; 35!</code> , So all numbers can have a unique corresponding matrix.</p> <pre><code>from sortedcontainers import SortedSet, SortedDict def permutmatrix2int(m): """Convert permutation matrix 35x35 to number.""" taboo = SortedSet() digits = [] rowid = 34 for bit in m[:-1]: bitold = bit for f in taboo: if bitold &gt;= f: bit -= 1 taboo.add(bitold) digits.append(bit) rowid -= 1 big_number = digits[0] pos = 0 base = b = 35 for digit in digits[1:]: big_number += b * digit pos += 1 base -= 1 b *= base return big_number def int2permutmatrix(big_number): """Convert number to permutation matrix 35x35.""" taboo = SortedDict() res = big_number base = 35 bit = 0 while base &gt; 1: res, bit = divmod(res, base) if res + bit == 0: bit = 0 for ta in taboo: if bit &gt;= ta: bit += 1 base -= 1 taboo[bit] = base for bit in range(35): if bit not in taboo: break taboo[bit] = base - 1 return list(map( itemgetter(0), sorted(taboo.items(), reverse=True, key=itemgetter(1)) )) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T11:49:42.097", "Id": "474043", "Score": "0", "body": "@teauxfu thanks for pointing that out!" } ]
[ { "body": "<p>I haven't really tried to follow your code, but it sounds like you're complicating things unnecessarily by talking about \"permutation matrices\" instead of just \"permutations.\" IIUC, it's trivial to get from a permutation matrix to a permutation or vice versa. The hard part is getting from an integer index (\"give me the 42nd permutation of these elements\") to the actual permutation.</p>\n\n<p>So, the non-trivial functions you're looking for are</p>\n\n<pre><code>def nth_permutation(num_elements, which):\n [...]\n\ndef index_of_permutation(num_elements, which):\n [...]\n</code></pre>\n\n<p>The speedy algorithm for <code>nth_permutation</code> is described <a href=\"https://stackoverflow.com/questions/7918806/finding-n-th-permutation-without-computing-others\">here (with C and PHP code)</a>\nand <a href=\"http://code.activestate.com/recipes/126037-getting-nth-permutation-of-a-sequence/\" rel=\"nofollow noreferrer\">here in Python, although apparently the first version doesn't produce permutations in the traditional order and the second version is quadratic</a>.</p>\n\n<hr>\n\n<p>On your actual code, I'm confused by this passage:</p>\n\n<pre><code> res, bit = divmod(res, base)\n if res + bit == 0:\n bit = 0\n</code></pre>\n\n<p>How can <code>res + bit == 0</code>, unless <code>(res == 0) and (bit == 0)</code>? But if <code>(bit == 0)</code>, then it's redundant to assign <code>bit = 0</code>.</p>\n\n<hr>\n\n<p>I also don't understand the significance of <code>35</code>. Is it significant that there are 10+26-1 non-zero \"digits\" available in base 36? If <code>35</code> was picked completely at random, then you should really make it a <em>parameter</em> to the function. It'd be what I called <code>num_elements</code> in my signatures above.</p>\n\n<hr>\n\n<p>Trivial nit: you forgot</p>\n\n<pre><code>from operator import itemgetter\n</code></pre>\n\n<hr>\n\n<pre><code>big_number = digits[0]\npos = 0\nbase = b = 35\nfor digit in digits[1:]:\n big_number += b * digit\n pos += 1\n base -= 1\n b *= base\n</code></pre>\n\n<p>This looks suspiciously like \"convert string to int.\" Is this essentially equivalent to</p>\n\n<pre><code>alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXY\"\nbig_string = ''.join([alphabet[i] for i in digits])\nbig_number = int(big_string[::-1]], 35)\n</code></pre>\n\n<p>?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T00:54:51.263", "Id": "241587", "ParentId": "241530", "Score": "2" } }, { "body": "<p>With a great help from a <a href=\"https://www.quora.com/profile/Mark-Gritter\" rel=\"nofollow noreferrer\">mathematician (at least in spirit)</a> regarding permutations, factoradic and matrices, I could implement the following, which is 30 times faster. </p>\n\n<p>I provide the opposite function as a bonus.</p>\n\n<pre><code>def pmatrix2int(m):\n \"\"\"Convert permutation matrix to number.\"\"\"\n return fac2int(pmatrix2fac(m))\n\n\ndef int2pmatrix(big_number):\n \"\"\"Convert number to permutation matrix.\"\"\"\n return fac2pmatrix((int2fac(big_number)))\n\n\ndef pmatrix2fac(matrix):\n \"\"\"Convert permutation matrix to factoradic number.\"\"\"\n available = list(range(len(matrix)))\n digits = []\n for row in matrix:\n idx = available.index(row)\n del available[idx]\n digits.append(idx)\n return list(reversed(digits))\n\n\ndef fac2pmatrix(digits):\n \"\"\"Convert factoradic number to permutation matrix.\"\"\"\n available = list(range(len(digits)))\n mat = []\n for digit in reversed(digits):\n # print(digit, available)\n mat.append(available.pop(digit))\n return mat\n\n\ndef int2fac(number):\n \"\"\"Convert decimal into factorial numeric system. Left-most is LSB.\"\"\"\n i = 2\n res = [0]\n while number &gt; 0:\n number, r = divmod(number, i)\n res.append(r)\n i += 1\n return res\n\n\ndef fac2int(digits):\n \"\"\"Convert factorial numeric system into decimal. Left-most is LSB.\"\"\"\n radix = 1\n i = 1\n res = 0\n for digit in digits[1:]:\n res += digit * i\n radix += 1\n i *= radix\n return res\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T02:44:19.763", "Id": "241592", "ParentId": "241530", "Score": "1" } } ]
{ "AcceptedAnswerId": "241592", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T22:58:20.293", "Id": "241530", "Score": "3", "Tags": [ "python", "python-3.x", "matrix", "base64" ], "Title": "Converting a natural number to a permutation matrix in Python. How to speed it up perhaps avoiding messing around with lists, sets and dicts?" }
241530
<p>I'm new to Clojure but I already know about functions and lists, so I decided to implement Prime Factors Kata solution. For any natural number the function should return a list of all its prime factors, e.g. for 15 it should return (3 5).</p> <p>It turned out that to implement a stack safe function I needed to use <code>loop</code> and <code>recur</code>, which I was not familiar with.</p> <p>So, does my solution look like idiomatic Clojure? What could be improved? Thanks!</p> <pre><code>(defn primeFactorsOf "Return all prime factors of a number" [n] (loop [number n candidate 2 factors ()] (if (= number 1) (reverse factors) (if (= (mod number candidate) 0) (recur (/ number candidate) candidate (conj factors candidate)) (recur number (inc candidate) factors))))) </code></pre>
[]
[ { "body": "<p>There's a few notable things here:</p>\n\n<p>You're prepending to a list, then reversing the result at the end. It would be better to just start with a vector (<code>[]</code>). <code>conj</code>oining to a vector appends the element to the end instead, so you don't need to reverse it after.</p>\n\n<p>If you really want a list here because it's checking for type, then either ignore this suggestion, or put this code into a helper and do something like:</p>\n\n<pre><code>(def primeFactorsOf [n]\n (list* (helper n)))\n</code></pre>\n\n<p>I personally think a vector makes more sense here, but it may prove to not be worth it in this case.</p>\n\n<hr>\n\n<pre><code>(= (mod number candidate) 0)\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>(zero? (mod number candidate))\n</code></pre>\n\n<hr>\n\n<p>I wouldn't have all your <code>loop</code> accumulators on the same line like you have. It's much harder to read, since you have to manually group them in two's in your head to make sense of them. I'd split them up:</p>\n\n<pre><code>(loop [number n\n candidate 2\n factors []]\n . . .)\n</code></pre>\n\n<p>If you <em>really</em> want to have them on one line though, add some commas in there. Commas have, as far as I know, no purpose other to allow you to group expressions to help readability. I'd add them in every two here:</p>\n\n<pre><code>(loop [number n, candidate 2, factors []]\n . . .)\n</code></pre>\n\n<hr>\n\n<p>Nested <code>if</code> expressions are usually cleaner using a <code>cond</code>. There are a multitude of ways to format a <code>cond</code> block, but when you have long lines like you have here, I like to format it almost like you would an <code>if</code> statement in a imperative language (below).</p>\n\n<hr>\n\n<p>All together, I end up with:</p>\n\n<pre><code>(defn primeFactorsOf\n \"Return all prime factors of a number\"\n [n]\n (loop [number n\n candidate 2\n factors []]\n (cond\n (= number 1)\n factors\n\n (zero? (mod number candidate))\n (recur (/ number candidate) candidate (conj factors candidate))\n\n :else\n (recur number (inc candidate) factors))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T23:20:54.040", "Id": "241583", "ParentId": "241531", "Score": "2" } } ]
{ "AcceptedAnswerId": "241583", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-30T23:38:49.723", "Id": "241531", "Score": "1", "Tags": [ "clojure" ], "Title": "Prime factors kata solution in Clojure" }
241531
<h2>Introduction</h2> <p>I'm new to Pandas. I'm trying to write a vectorized converter for the situation described in <a href="https://codereview.stackexchange.com/questions/241415">What is an efficient ways to parse a bar separated usr file in Python</a> . All code presented here is my own and the data are synthetic.</p> <p>For these data:</p> <pre class="lang-none prettyprint-override"><code>HeaderG|Header1|Header2|Header3 A|Entry1|Entry2|Entry3 B|Entry1|Entry2|Entry3 A|Eggs|Sausage|Bacon B|Bread|Lettuce|Tomato A|aa|bb|cc B|dd|ee|ff A|4aa|4bb|4cc B|4dd|4ee|4ff FooterG|Footer1|Footer2|Footer3 </code></pre> <p>The converter is responsible for parsing out the header and footer, which have nearly nothing to do with the body of the data; and then parsing out one "payload" per set of groups (above, the groups being <code>A</code> and <code>B</code>). In the above sample there are two groups, three "entry columns", and four payloads.</p> <p>The groups, headers and footers are parametric but well-known. The converter is responsible for producing maps of the header, footer and groups given some additional metadata. The algorithm roughly goes:</p> <ul> <li>Deserialize the pipe-separated file into one big dataframe</li> <li>Trim off the header and footer</li> <li>Validate, then trim off the first group column</li> <li>Make a Cartesian-product multi-index frame</li> <li>Construct and assign the multi-index</li> <li>Iterate over the multi-indexed data body to produce the payloads as plain dictionaries</li> </ul> <p>I am aware of both the <code>to_json</code> and <code>to_dict</code> methods of <code>DataFrame</code> but I was unable to get them working as I wanted to, so I had to roll my own. This code does exactly what it should, but I'm sure there's a better way to use Pandas. I want to optimize for speed first, code simplicity second, and memory basically not at all, given that input files are all less than 10 kB each.</p> <p>My specific concerns:</p> <ul> <li><code>make_multi_index</code> is quite ugly and uses a non-vectorized generator conversion of a dictionary; and also has not made (cannot make?) use of <code>MultiIndex.from_product</code></li> <li>It smells like it could make use of <code>np.meshgrid</code> but there was a catch in the nature of the third axis that prevented me from doing so</li> <li>There must be a simpler way to assign header and footer names and produce dictionaries</li> <li>Heavy <code>groupby</code> abuse and lack of vectorization in <code>payloads</code></li> </ul> <h2>The code</h2> <pre><code>from typing import Iterable from pprint import pprint import pandas as pd import numpy as np group_names = {'A': ('A1ValueKey', 'A2ValueKey', 'A3ValueKey'), 'B': ('B1ValueKey', 'B2ValueKey', 'B3ValueKey')} header_names = ('HeaderKeyG', 'HeaderKey1', 'HeaderKey2', 'HeaderKey3') footer_names = ('FooterKeyG', 'FootKey1', 'FootKey2', 'FootKey3') n_groups = len(group_names) n_entries = len(header_names) - 1 def make_multi_index(n_payloads: int) -&gt; pd.MultiIndex: group_indices = np.tile( np.array( [ (k, e) for k, entries in group_names.items() for e in entries ], dtype=object ), (n_payloads, 1), ) indices = np.empty( (group_indices.shape[0], 3), dtype=object ) indices[:, 0] = np.repeat(np.arange(n_payloads), n_groups * n_entries) indices[:, 1:] = group_indices return pd.MultiIndex.from_frame( pd.DataFrame(indices), names=( 'payload', 'group', 'entry', ), ) def parse(fn: str) -&gt; (pd.Series, pd.Series, pd.DataFrame): df = pd.read_csv(fn, sep='|', header=None) n_payloads, leftover = divmod(df.shape[0] - 2, n_groups) assert leftover == 0 assert n_entries == df.shape[1] - 1 header = df.iloc[0, :] footer = df.iloc[-1, :] body = df.iloc[1:-1, :] assert ( body.iloc[:, 0] == np.tile( np.array(tuple(group_names.keys())), n_payloads ) ).all() body.drop(0, axis=1, inplace=True) entries = pd.DataFrame( body.values.flatten(), index=make_multi_index(n_payloads), ) return header, footer, entries def payloads(header: Iterable[str], footer: Iterable[str], entries: pd.DataFrame) -&gt; Iterable[dict]: base = { 'header': dict(zip(header_names, header)), 'footer': dict(zip(footer_names, footer)), } for i_payload, payload in entries.groupby(level=0): d = dict(base) d['groups'] = { groupname: { g: din.values[0, 0] for g, din in d.groupby(level=2) } for groupname, d in payload.groupby(level=1) } yield d def main(): header, footer, entries = parse('file1.usr') print('Multi-index entry representation:') print(entries) print() print('Payloads:') for pay in payloads(header, footer, entries): pprint(pay) main() </code></pre> <h2>Output</h2> <pre class="lang-none prettyprint-override"><code>Multi-index entry representation: 0 payload group entry 0 A A1ValueKey Entry1 A2ValueKey Entry2 A3ValueKey Entry3 B B1ValueKey Entry1 B2ValueKey Entry2 B3ValueKey Entry3 1 A A1ValueKey Eggs A2ValueKey Sausage A3ValueKey Bacon B B1ValueKey Bread B2ValueKey Lettuce B3ValueKey Tomato 2 A A1ValueKey aa A2ValueKey bb A3ValueKey cc B B1ValueKey dd B2ValueKey ee B3ValueKey ff 3 A A1ValueKey 4aa A2ValueKey 4bb A3ValueKey 4cc B B1ValueKey 4dd B2ValueKey 4ee B3ValueKey 4ff Payloads: {'footer': {'FootKey1': 'Footer1', 'FootKey2': 'Footer2', 'FootKey3': 'Footer3', 'FooterKeyG': 'FooterG'}, 'groups': {'A': {'A1ValueKey': 'Entry1', 'A2ValueKey': 'Entry2', 'A3ValueKey': 'Entry3'}, 'B': {'B1ValueKey': 'Entry1', 'B2ValueKey': 'Entry2', 'B3ValueKey': 'Entry3'}}, 'header': {'HeaderKey1': 'Header1', 'HeaderKey2': 'Header2', 'HeaderKey3': 'Header3', 'HeaderKeyG': 'HeaderG'}} {'footer': {'FootKey1': 'Footer1', 'FootKey2': 'Footer2', 'FootKey3': 'Footer3', 'FooterKeyG': 'FooterG'}, 'groups': {'A': {'A1ValueKey': 'Eggs', 'A2ValueKey': 'Sausage', 'A3ValueKey': 'Bacon'}, 'B': {'B1ValueKey': 'Bread', 'B2ValueKey': 'Lettuce', 'B3ValueKey': 'Tomato'}}, 'header': {'HeaderKey1': 'Header1', 'HeaderKey2': 'Header2', 'HeaderKey3': 'Header3', 'HeaderKeyG': 'HeaderG'}} {'footer': {'FootKey1': 'Footer1', 'FootKey2': 'Footer2', 'FootKey3': 'Footer3', 'FooterKeyG': 'FooterG'}, 'groups': {'A': {'A1ValueKey': 'aa', 'A2ValueKey': 'bb', 'A3ValueKey': 'cc'}, 'B': {'B1ValueKey': 'dd', 'B2ValueKey': 'ee', 'B3ValueKey': 'ff'}}, 'header': {'HeaderKey1': 'Header1', 'HeaderKey2': 'Header2', 'HeaderKey3': 'Header3', 'HeaderKeyG': 'HeaderG'}} {'footer': {'FootKey1': 'Footer1', 'FootKey2': 'Footer2', 'FootKey3': 'Footer3', 'FooterKeyG': 'FooterG'}, 'groups': {'A': {'A1ValueKey': '4aa', 'A2ValueKey': '4bb', 'A3ValueKey': '4cc'}, 'B': {'B1ValueKey': '4dd', 'B2ValueKey': '4ee', 'B3ValueKey': '4ff'}}, 'header': {'HeaderKey1': 'Header1', 'HeaderKey2': 'Header2', 'HeaderKey3': 'Header3', 'HeaderKeyG': 'HeaderG'}} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T02:15:44.970", "Id": "474011", "Score": "0", "body": "I feel like this should be included as an example somewhere in the [Guide to Asking Questions](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions). Never heard of a usr file, but I could easily follow the question due to its structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T02:16:27.427", "Id": "474012", "Score": "0", "body": "@teauxfu Thank you <3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T10:02:37.583", "Id": "474038", "Score": "0", "body": "Are the two classes `A` and `B` always alternating in the file, as in your example data? And are there always exactly two classes? Or in other words, how do you know which row if class `A` to combine with which row of class `B` in the final output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T10:06:58.660", "Id": "474039", "Score": "0", "body": "Also, if the input files are only 10KB, parsing it using vanilla Python might be a lot easier. Just read the file line by line and store (or yield, just need to `seek` to the footer and back first) a payload whenever you see the groups repeat." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T13:29:10.400", "Id": "474054", "Score": "0", "body": "@Graphier yes, they always alternate." } ]
[ { "body": "<p>I don't really see the necessity for <code>pandas</code> here. If your input files are only 10KB large, just parse them using vanilla Python:</p>\n\n<pre><code>from pprint import pprint\n\nSENTINEL = object()\n\ndef read_last_line(f):\n \"\"\"Read the last line of an open file.\n Note: file must be opened in binary mode!\n Leaves the file pointer at the end of the file.\"\"\"\n # https://stackoverflow.com/a/18603065/4042267\n if \"b\" not in f.mode:\n raise IOError(\"File must be opened in binary mode!\")\n f.seek(-2, 2) # Jump to the second last byte.\n while f.read(1) != b\"\\n\": # Until EOL is found...\n f.seek(-2, 1) # ...jump back, over the read byte plus one more.\n return f.readline()\n\ndef parse_row(row, sep):\n \"\"\"Decode, strip and split a binary data row using sep.\"\"\"\n return row.decode(\"utf-8\").strip().split(sep)\n\ndef parse(f, header_names, footer_names, group_names, sep=\"|\"):\n \"\"\"Parse an open file into payloads.\n Each payload has a header and footer dictionary using the respective\n names as keys and a groups dictionary parsed from the file.\n Assumes that the file is ordered correctly, i.e. lines of the same\n payload follow each other and group names are unique.\n Group names must also not appear as footer names.\n \"\"\"\n footer = dict(zip(footer_names, parse_row(read_last_line(f), sep)))\n f.seek(0)\n header = dict(zip(header_names, parse_row(next(f), sep)))\n\n def new_payload():\n return {\"header\": header, \"footer\": footer, \"groups\": {}}\n\n payload = new_payload()\n for row in f:\n group, *data = parse_row(row, sep)\n if group in payload[\"groups\"]:\n # this group already exists, must be a new payload\n yield payload\n payload = new_payload()\n try:\n assert len(group_names[group]) == len(data)\n payload[\"groups\"][group] = dict(zip(group_names[group], data))\n except KeyError:\n # probably reached the footer, but better make sure:\n try:\n next(f)\n except StopIteration:\n break\n else:\n raise\n yield payload\n\nif __name__ == \"__main__\":\n group_names = {'A': ('A1ValueKey', 'A2ValueKey', 'A3ValueKey'),\n 'B': ('B1ValueKey', 'B2ValueKey', 'B3ValueKey')}\n header_names = ('HeaderKeyG', 'HeaderKey1', 'HeaderKey2', 'HeaderKey3')\n footer_names = ('FooterKeyG', 'FootKey1', 'FootKey2', 'FootKey3')\n\n with open(\"file1.usr\", \"rb\") as f:\n for payload in parse(f, header_names, footer_names, group_names):\n pprint(payload)\n</code></pre>\n\n<p>This is even a generator, so it can deal with arbitrarily large files (although I would expect <code>pd.read_csv</code> to be more optimized and therefore be faster for large files, as long as the resulting dataframe still fits into memory).</p>\n\n<p>You don't say if you need both the multi-level representation and the payloads, I assumed you only need the latter, for which I think this gives the same output as your code (up to ordering of the dictionaries, since I used Python 3.6):</p>\n\n<pre><code>{'footer': {'FootKey1': 'Footer1',\n 'FootKey2': 'Footer2',\n 'FootKey3': 'Footer3',\n 'FooterKeyG': 'FooterG'},\n 'groups': {'A': {'A1ValueKey': 'Entry1',\n 'A2ValueKey': 'Entry2',\n 'A3ValueKey': 'Entry3'},\n 'B': {'B1ValueKey': 'Entry1',\n 'B2ValueKey': 'Entry2',\n 'B3ValueKey': 'Entry3'}},\n 'header': {'HeaderKey1': 'Header1',\n 'HeaderKey2': 'Header2',\n 'HeaderKey3': 'Header3',\n 'HeaderKeyG': 'HeaderG'}}\n{'footer': {'FootKey1': 'Footer1',\n 'FootKey2': 'Footer2',\n 'FootKey3': 'Footer3',\n 'FooterKeyG': 'FooterG'},\n 'groups': {'A': {'A1ValueKey': 'Eggs',\n 'A2ValueKey': 'Sausage',\n 'A3ValueKey': 'Bacon'},\n 'B': {'B1ValueKey': 'Bread',\n 'B2ValueKey': 'Lettuce',\n 'B3ValueKey': 'Tomato'}},\n 'header': {'HeaderKey1': 'Header1',\n 'HeaderKey2': 'Header2',\n 'HeaderKey3': 'Header3',\n 'HeaderKeyG': 'HeaderG'}}\n{'footer': {'FootKey1': 'Footer1',\n 'FootKey2': 'Footer2',\n 'FootKey3': 'Footer3',\n 'FooterKeyG': 'FooterG'},\n 'groups': {'A': {'A1ValueKey': 'aa', 'A2ValueKey': 'bb', 'A3ValueKey': 'cc'},\n 'B': {'B1ValueKey': 'dd', 'B2ValueKey': 'ee', 'B3ValueKey': 'ff'}},\n 'header': {'HeaderKey1': 'Header1',\n 'HeaderKey2': 'Header2',\n 'HeaderKey3': 'Header3',\n 'HeaderKeyG': 'HeaderG'}}\n{'footer': {'FootKey1': 'Footer1',\n 'FootKey2': 'Footer2',\n 'FootKey3': 'Footer3',\n 'FooterKeyG': 'FooterG'},\n 'groups': {'A': {'A1ValueKey': '4aa',\n 'A2ValueKey': '4bb',\n 'A3ValueKey': '4cc'},\n 'B': {'B1ValueKey': '4dd',\n 'B2ValueKey': '4ee',\n 'B3ValueKey': '4ff'}},\n 'header': {'HeaderKey1': 'Header1',\n 'HeaderKey2': 'Header2',\n 'HeaderKey3': 'Header3',\n 'HeaderKeyG': 'HeaderG'}}\n</code></pre>\n\n<p>Note that I added some <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> and an <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a>, although I'm pretty sure you already know about those.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:46:09.863", "Id": "474064", "Score": "1", "body": "Interesting and smart solution. I'd prefer a validation check in the `except KeyError`, something simple like `if next(f, SENTINEL) is not SENTINEL: raise ValueError() from None`. Additionally `break` would emphasise this relationship more than `pass`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T17:12:31.140", "Id": "474085", "Score": "0", "body": "@Peilonrayz Agreed. Added something along those lines. I'm never sure whether to use `try...except StopIteration` or `next(..., Sentinel)`, though..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T17:29:53.547", "Id": "474091", "Score": "1", "body": "Oh do I agree with that! I think performance-wise `try` would be better here. Readability wise I chose `next(..., SENTINEL)` as it is easier to read in comments. In your above code I think a `try` could be easier to read for most as then there's no weird `SENTINEL`. But all of this comes down to my feelings, and I'm sure a substantial amount of people feel the inverse to me." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T12:22:29.550", "Id": "241551", "ParentId": "241533", "Score": "3" } } ]
{ "AcceptedAnswerId": "241551", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T01:57:33.930", "Id": "241533", "Score": "3", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Data conversion utility with group-wise serialization" }
241533
<p>I'm implementing the <a href="https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression" rel="nofollow noreferrer">closed form</a> of Fibonacci numbers. I figure using a custom data type I can do so without leaving <code>Integer</code>. It isn't more efficient than the "standard" approach as I couldn't figure an efficient way to calculate the power of my custom number type.</p> <p>But sticking to this algorithm I would be interested in best practices to write this. In particular I'm uncertain about the use of <code>Num</code> for my <code>FibNum</code> and the use of <code>fromJust</code>.</p> <pre><code>module Fibo ( fibo ) where import Data.Maybe (fromJust) -- use a data type similar to complex numbers. -- The only irrational number are multiples of sqrt 5 -- which will cancel away in the closed form. data FibNum = FibNum { int::Integer, sq5::Integer } deriving (Show) instance Num FibNum where (+) (FibNum a1 b1) (FibNum a2 b2) = FibNum (a1+a2) (b1 + b2) (*) (FibNum a1 b1) (FibNum a2 b2) = FibNum intSide rootSide where intSide = a1*a2 + 5 * b1 * b2 rootSide = a1*b2 + b1*a2 negate (FibNum a b) = FibNum (negate a) (negate b) fromInteger n = FibNum (fromInteger n) 0 -- no need for abs and sign for now abs _ = undefined signum _ = undefined funit = FibNum 1 0 -- actual phi and psi are (1 + sqrt 5)/2 and (1 - sqrt 5)/2 -- I would prefer to avoid fractions so I divide at the end fphi = FibNum 1 1 fpsi = FibNum 1 (negate 1) -- was originally planning to calculate the binomial coefficients -- but seeing that I just need n relatively simple multiplications -- that seem like unnecessary complication pow :: FibNum -&gt; Integer -&gt; FibNum pow _ 0 = funit pow x 1 = x pow x n = x * pow x (n-1) -- in the closed form the integer part is always 0 divR5 :: FibNum -&gt; Maybe Integer divR5 (FibNum 0 n) = Just n divR5 _ = Nothing fibo :: Integer -&gt; Integer fibo n = flip div p2 . fromJust $ divR5 nom where nom = pow fphi n - pow fpsi n p2 = 2^n </code></pre> <p><em>addendum</em> Thanks a lot for the useful comments. If it's interesting I put my code in following repo <a href="https://github.com/bdcaf/haskell-fibonacci" rel="nofollow noreferrer">https://github.com/bdcaf/haskell-fibonacci</a></p>
[]
[ { "body": "<h1>Opening comments</h1>\n\n<p>I'm not a Haskell expert, but I hope I can offer some helpful comments and critiques.</p>\n\n<p>Overall, I think this is mostly good and idiomatic code. You make good use of pattern matching and have pretty clean definitions of your code.</p>\n\n<p>I'm going to first address style and your questions. I'll then address the performance issue, since it actually isn't that hard to fix.</p>\n\n<h1>Style</h1>\n\n<p>I think most of your style is fine. I just personally prefer to nest <code>where</code> clauses like so</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>foo x y = x' + y' \n where\n x' = 2*x\n y' = 2*y\n</code></pre>\n\n<p>How you do it is up to you.</p>\n\n<h1>Using <code>Num</code></h1>\n\n<p>I don't think there's much wrong with using <code>Num</code> for <code>FibNum</code> to make things easier. I would just go ahead and implement <code>abs</code> and <code>signum</code> if you do, since they aren't too difficult, although you don't <em>have</em> to since you don't export <code>FibNum</code> (which I think is good). However, <code>Num</code> is just an interface and doesn't officially make any promises about how its operations behave (i.e. it doesn't have any laws).</p>\n\n<p>The data type you've defined is the <a href=\"https://en.wikipedia.org/wiki/Ring_(mathematics)#Basic_examples\" rel=\"nofollow noreferrer\">Ring</a>* Z[√5]. I found a library that has a <a href=\"https://hackage.haskell.org/package/numeric-prelude-0.4.3.1/docs/Algebra-Ring.html\" rel=\"nofollow noreferrer\"><code>Ring</code></a> type class which you could implement for your datatype. You could then use this type class's implementation of <code>(^)</code> instead of <code>pow</code> for a speedup (see my comments regarding performance).</p>\n\n<p>Whether you want to be more precise like this is up to you. <code>Num</code> unofficially is a ring, too, and is the more common type class.</p>\n\n<p>As an addendum, since you are using division, you may wish to consider changing your <code>Integer</code>s to <code>Rational</code>s, which would make your type the <a href=\"https://en.wikipedia.org/wiki/Quadratic_field\" rel=\"nofollow noreferrer\">Quadratic Field</a> Q[√5]. There is also a <a href=\"https://hackage.haskell.org/package/numeric-prelude-0.4.3.1/docs/Algebra-Field.html\" rel=\"nofollow noreferrer\"><code>Field</code></a> typeclass.</p>\n\n<p>* Don't worry too much about the abstract algebra here if you aren't familiar. What's more important is understanding the interfaces and the promises they make/laws they obey. For example, the order of operation of addition can be rearranged (known as commutativity) in a Ring and Field. You don't need to know anything more than how to implement the functions required, make sure they satisfy the laws, and how to use the interface (I don't <em>really</em> remember my rings and fields anyway, I just googled around a bit). </p>\n\n<h1>Using <code>fromJust</code></h1>\n\n<p>I think that the usage of <code>fromJust</code> is unnecessary and serves to undermine the fact that <code>divR5</code> returns a <code>Maybe</code>. Below, I offer two alternative options.</p>\n\n<p>I would also consider either renaming <code>divR5</code> to indicate that it doesn't actually divide an arbitrary <code>FibNum</code> by √5, leaving a comment to that effect, or defining it in the <code>where</code> clause of <code>fibo</code> (which is what I would do). If you define it in the <code>where</code> clause, you can't accidentally misuse it elsewhere.</p>\n\n<h2>Return a <code>Maybe</code></h2>\n\n<pre class=\"lang-hs prettyprint-override\"><code>fiboMaybe :: Integer -&gt; Maybe Integer\nfiboMaybe n = (`div` p2) &lt;$&gt; divR5 nom\n where\n nom = pow fphi n - pow fpsi n\n p2 = 2^n\n</code></pre>\n\n<p>I like to use the infix form of <code>fmap</code> (and also I prefer to use <code>div</code> in infix), but you can also explicitly <code>case</code> on the result or use <code>do</code> notation.</p>\n\n<h2>Give a better error message</h2>\n\n<p>If you aren't going to return a <code>Maybe</code>, then you might as well provide a more informative error message than <code>fromJust</code>'s.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>fiboError :: Integer -&gt; Integer\nfiboError n = divR5 nom `div` p2\n where\n nom = pow fphi n - pow fpsi n\n p2 = 2^n\n divR5 (FibNum 0 n) = n\n divR5 _ = error \"fiboError: got nonzero integer part in divR5 (this shouldn't happen)\"\n</code></pre>\n\n<h2>Improving efficiency</h2>\n\n<p>It turns out that it's not too hard to improve your efficiency. If you implement the <code>Ring</code> or <code>Field</code> type class and use the functions provided there, you should see a major speedup. But if you don't want to, we can fix the speed in only a couple lines of code.</p>\n\n<p>The inefficiency in your code comes from your implementation of <code>pow</code>, which, while correct, takes linear time. You can reduce this significantly. Here's how we can fix it. We're going to use the <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Monoid.html#t:Product\" rel=\"nofollow noreferrer\"><code>Product</code> Monoid</a> and the function <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Semigroup.html#v:mtimesDefault\" rel=\"nofollow noreferrer\"><code>mtimesDefault</code></a> from <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Semigroup.html\" rel=\"nofollow noreferrer\"><code>Data.Semigroup</code></a>.</p>\n\n<p>If you aren't familiar with the abstract algebra terminology here, ignore that junk for a second. Here's the lowdown: we're going to take advantage of the fact that for your datatype, multiplication is associative. What does that mean? It means that</p>\n\n<pre><code>(x * y) * z == x * (y * z)\n</code></pre>\n\n<p>i.e. we can move around parentheses in a product without changing its value. If you can do that, you have something known as a Semigroup. That's all a Semigroup is! A Monoid is a Semigroup where you know there's some element that does nothing when you multiply it. In this case, that element is 1:</p>\n\n<pre><code>1 * x == x * 1 == x\n</code></pre>\n\n<p>If you have a <code>Monoid</code> (which <code>FibNum</code> is with respect to the multiplication operation) and want to multiply a number by its self <code>n</code> times, <code>mtimesDefault :: (Integral b, Monoid a) =&gt; b -&gt; a -&gt; a</code> does this more efficiently than the naive solution.</p>\n\n<p>The <code>Product</code> wrapper type takes a <code>Num a</code> and uses its multiplication operation as the Monoid operation. So to get a faster <code>pow</code>, here's all the code we have to write:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.Monoid (Product(..))\nimport Data.Semigroup (mtimesDefault)\n\npowFast :: Integral a =&gt; FibNum -&gt; a -&gt; FibNum\npowFast n exp = getProduct $ mtimesDefault exp (Product n)\n</code></pre>\n\n<p>If we replace <code>pow</code> with <code>powFast</code>, your implementation becomes much faster than the \"standard\" approach too!</p>\n\n<p>Of course, it isn't too hard to write a faster <code>pow</code> function by hand. It's just neat that Haskell has built-in machinery that lets you avoid doing so. If you wanted to figure out how to do it faster by hand, I would hint you to think about exponentiation of regular numbers.</p>\n\n<p>Say I asked you to compute <code>2^50</code> by hand. I claim you don't need to take 50 multiplications to give me an answer. Try and think about how you would do it efficiently, taking advantage of the fact that you're only ever multiplying by 2 and that you multiplication is associative.</p>\n\n<p>Here's a hint:</p>\n\n<blockquote class=\"spoiler\">\n <p> Think about multiplying exponents with the same base. <code>2^x * 2^y = 2^(x+y)</code>. What about <code>2^x * 2^x</code>?</p>\n</blockquote>\n\n<p>and another:</p>\n\n<blockquote class=\"spoiler\">\n <p> For example, suppose you get to <code>2^4 = 16</code>. From here, if you multiply <code>16</code> by itself, you'll get <code>16 * 16 = (2^4) * (2^4) = 2^(2*4) = 2^8</code>. That saved 3 multiplications compared to the naive method of multiplying by 2!</p>\n</blockquote>\n\n<p>You can find the answer in the implementation of <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/src/Data.Semigroup.Internal.html#stimesDefault\" rel=\"nofollow noreferrer\"><code>stimesDefault</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T22:27:30.280", "Id": "241580", "ParentId": "241541", "Score": "3" } } ]
{ "AcceptedAnswerId": "241580", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T08:16:35.773", "Id": "241541", "Score": "1", "Tags": [ "haskell" ], "Title": "Closed form Fibonacci using Integer" }
241541
<p>I started learning Python and wrote my first program. This is a console game based on guessing the number. Can you take a look and tell me if I'm doing it right or give me any advice? Here is the code: <a href="https://github.com/theriseq/GuessTheNumber" rel="nofollow noreferrer">https://github.com/theriseq/GuessTheNumber</a></p> <p>Is it a good way of doing this or can I simplify it?</p> <p>Thank you.</p> <p><strong>main.py</strong></p> <pre class="lang-py prettyprint-override"><code>from can_convert import check import random welcome_msg = """Welcome to GuessTheNumber Game! I\'m thinking of a number between 1 and 100. Can you guess this number? [?] Type \'pass\' to exit game. """ print(welcome_msg) number_to_guess = random.randrange(1, 101) attemps = 0 while True: user_inp = str(input("Your choice: ")) if user_inp != "pass": if check(user_inp): attemps += 1 # print('is int') if int(user_inp) &lt; number_to_guess: print("Your guess is too small.") elif int(user_inp) &gt; number_to_guess: print("Your guess is too high.") else: print("Correct! You won the game!") print(f"Attemps: {attemps}") break else: print('Enter numbers only!') else: break </code></pre> <p><strong>can_convert.py</strong></p> <pre class="lang-py prettyprint-override"><code>def check(to_check): try: int(to_check) return True except ValueError: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T11:46:19.943", "Id": "474042", "Score": "3", "body": "Please edit your title to be on-topic, aka claim what the code does, as opposed to the currently very generic title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T12:03:22.300", "Id": "474046", "Score": "1", "body": "Welcome to CR SE! Alex Povel is right that you need to rename the question, but the question body looks ok, and I'll try to post a response if work's not too busy this morning!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T18:50:38.813", "Id": "474104", "Score": "0", "body": "Technically we need the challenge description to be inside the question body, but a number-guessing-game is as common as FizzBuzz nowadays. Please note this for future questions though, good luck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T02:35:07.680", "Id": "474223", "Score": "0", "body": "@AlexPovel Titles don't make questions on or off-topic. A bad title gets a downvote, but not a close vote." } ]
[ { "body": "<p>Here is a list of found issues, in order of occurrence:</p>\n\n<ul>\n<li>importing from your custom <code>can_convert</code> is fine. You should stick to modularization like that for bigger projects. However, here, it actually seems to be in the way of things. It checks if the string can be converted, but does not actually do any conversion. We later have to do the conversion again anyway. This can be combined.</li>\n<li>Currently, the welcome message and actual <code>random</code> range can deviate. You already know what <code>f</code>-strings are, so they should be used to keep that in line.</li>\n<li>Use <code>randint</code> to include both bounds, as opposed to <code>randrange</code>, which would stop one short of <code>upper_bound</code>, as you already noted.</li>\n<li><code>input</code> will already return a string, no need to convert via <code>str</code>.</li>\n<li>By inverting the logic in checking for <code>\"pass\"</code>, a whole block of indentation can be spared. Just check if <code>user_inp == \"pass\"</code> and <code>break</code> if <code>True</code>. All following code can be one level less indented, since no <code>else</code> statement is required.</li>\n<li><p>Now for the main logic. The <code>try</code> block has moved here, away from the import. Notice that the logic is still the same. However, we assign to <code>number</code> immediately without checking first. If this fails, the <code>except</code> block is triggered.</p>\n\n<ul>\n<li>Note that <code>int(\"2.2\")</code> will also be a <code>ValueError</code> despite <code>\"2.2\"</code>, to humans, clearly being a number. So the error message should specify <code>whole</code> numbers to be more precise.</li>\n<li>The added <code>else</code> block is run if no <code>exception</code> was raised, so in the normal game.</li>\n<li><code>number</code> is now available, so no need to call <code>int</code> conversion repeatedly.</li>\n</ul>\n\n<p>Keep <code>try</code> blocks short and concise and never leave an <code>except</code> statement bare. You did this fine! Lastly, try to not nest <code>try/except</code> blocks.</p></li>\n<li>There was a typo for <code>attempts</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\nupper_bound = 100\nlower_bound = 1\n\nwelcome_msg = f\"\"\"Welcome to GuessTheNumber Game!\nI'm thinking of a number between {lower_bound} and {upper_bound}.\nCan you guess this number?\n\n[?] Type 'pass' to exit game.\n\"\"\"\nprint(welcome_msg)\n\nnumber_to_guess = random.randint(lower_bound, upper_bound)\nattempts = 0\n\nwhile True:\n user_inp = input(\"Your choice: \")\n if user_inp == \"pass\":\n break\n try:\n number = int(user_inp)\n except ValueError:\n print('Enter whole numbers only!')\n else: # no exception occurred\n attempts += 1\n if number &lt; number_to_guess:\n print(\"Your guess is too small.\")\n elif number &gt; number_to_guess:\n print(\"Your guess is too high.\")\n else:\n print(\"Correct! You won the game!\")\n print(f\"Attempts: {attempts}\")\n break\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T11:44:04.260", "Id": "241548", "ParentId": "241547", "Score": "3" } }, { "body": "<p>You've done a great job demoing a variety of patterns and tools. I'll add two more things you could benefit from learning early:</p>\n\n<ul>\n<li><a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">Type</a> <a href=\"https://stackoverflow.com/a/32558710/10135377\">hints</a>. Function headers are almost always clearer with type hints, and you need them if you want to use a tool like <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\">MyPy</a>.</li>\n<li><a href=\"https://stackoverflow.com/a/22493194/10135377\">The main method pattern</a>.</li>\n<li>(Usually I'd also advocate for recursion when someone's demo project is a REPL game like this, but in your case I don't think it would improve this code.)</li>\n</ul>\n\n<p>Other stuff:</p>\n\n<ul>\n<li>Usually it's better to avoid exceptions when you have other options. While you could do what you're doing here by other means, you've done a few things that make me like your <code>check</code> function: It's concise, it bundles away a discrete bit of functionality, and you're catching a narrowly defined exception class.</li>\n<li>Unfortunately, it's a little clunky to have a function that just tells you if <code>int(x)</code> threw an exception, just so you can call <code>int(x)</code> on the next line. You have many other options; I'd be fine with <code>def check (user_input: str) -&gt; Optional[int]:...</code>, but then you <em>must</em> use <code>if x is [not] None:...</code> later. </li>\n<li>Depending exactly what the function in question does, either <code>validate</code> or <code>sanitize</code> would probably be better than <code>check</code>.</li>\n<li>I lied: another new thing to learn: <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\">itertools</a>. In particular, a <code>while</code> loop that increments something is always begging to get replaced with a <code>for</code> loop. In this case, since we want to keep going \"as long as it takes\", we need a lazy infinite iteratable: <code>itertools.count(0)</code>.\n\n<ul>\n<li>In order to make that work, we'll need to separate out the \"that input was invalid, try again\" logic into a separate loop (or recursive function). </li>\n<li>And then if you teach yourself <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generators</a> you could write <code>for (try_number, user_input) in zip(itertools.count(0), yielded_user_input()):...</code>. Fun times!</li>\n</ul></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:41:59.293", "Id": "474062", "Score": "0", "body": "\"Usually it's better to avoid exceptions when you have other options.\", do you have an example? One replacement for exceptions can lead to an abundance of `isinstance`, `hasattr`, `issubclass` or similar checks (*Look Before You Leap*), which is mostly more verbose with little added benefit. See also [here](https://devblogs.microsoft.com/python/idiomatic-python-eafp-versus-lbyl/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:06:37.893", "Id": "474067", "Score": "1", "body": "@AlexPovel Where EAFP may be Python-idiomatic, (1) there are exceptions and (2) it's not my personal style. Consider the difference between `try: dict[k] except KeyError` vs. `dict.get[k]`, where I would prefer the latter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T16:52:54.023", "Id": "474081", "Score": "1", "body": "People throw exceptions and catch exceptions all the time and it's _fine_. But I do claim that you should always _consider_ other options. If what you're trying to say is `if is_valid(x): y(x) else: z()` then you wouldn't want to write `try: y(x) except Barr: z()`. Also, while it seems trite to say \"There are a lot of ways you can do exceptions badly\", people really do make mistakes, and other patterns really do have fewer pitfalls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T17:44:19.320", "Id": "474093", "Score": "0", "body": "Okay, both these are good points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T18:24:02.163", "Id": "474095", "Score": "1", "body": "\"The main method pattern\" links to MyPy, Is that supposed to be a different link?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T18:42:48.957", "Id": "474102", "Score": "0", "body": "@lights0123; Fixed!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:25:45.147", "Id": "241557", "ParentId": "241547", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T11:06:07.237", "Id": "241547", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "number-guessing-game" ], "Title": "Console-based Guess the Number" }
241547
<p>There are many related questions and answers but mostly with JQuery and/or from many years ago.</p> <p>I prepared a version myself, and my question is whether this is currently (2020, hence ECMAScript 6 or similar) an optimal way to preload images in pure JavaScript. It appears to work (note the tests), although not all edge-cases are tested.</p> <pre><code>let preload_imgs = function(src_list, callback) { let loaded = 0; src_list.forEach((src) =&gt; { img = new Image(); img.onload = () =&gt; { if (++loaded == src_list.length &amp;&amp; callback) { callback(); } }; img.onerror = (err) =&gt; { console.log(err); }; img.src = src; }); }; </code></pre> <p>Here is an example usage:</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>let preload_imgs = function(src_list, callback) { let loaded = 0; src_list.forEach((src) =&gt; { img = new Image(); img.onload = () =&gt; { if (++loaded == src_list.length &amp;&amp; callback) { callback(); } }; img.onerror = (err) =&gt; { console.log(err); }; img.src = src; }); }; let urls = ['https://i.picsum.photos/id/1000/5626/3635.jpg', 'https://i.picsum.photos/id/10/2500/1667.jpg', 'https://homepages.cae.wisc.edu/~ece533/images/cat.png', 'https://homepages.cae.wisc.edu/~ece533/images/airplane.png' ]; let starttime = Date.now(); preload_imgs(urls, () =&gt; { console.log("All images preloaded in", Date.now() - starttime, 'ms.'); });</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:58:56.863", "Id": "474066", "Score": "0", "body": "Welcome to code review where we review working code and make suggestions on how to improve the code. We can't tell you if your code is working correctly, we need to assume you have tested it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:23:18.973", "Id": "474068", "Score": "0", "body": "Please verify that your code does what you want it to and come back (also edit your question to reflect your findings), I'm certain I can help you with a cleaner solution :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:43:16.780", "Id": "474070", "Score": "0", "body": "Thanks for the feedback. I of course tested it several times (see in the example snippet too), what I meant is just that maybe there could be some potential problem in a scenario that I haven't thought of. Anyway, I just removed this part because it's not essential." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T19:21:58.597", "Id": "474111", "Score": "0", "body": "To the reviewers: this question doesn't need to be closed for being broken, that reason doesn't apply here. Thank you." } ]
[ { "body": "<p>Firstly, kudo's to you for trying to use vanilla javascript. Great choice.</p>\n<br/>\n<hr />\n<br/>\n<h1> The Question</h1>\n<p>Let us start with your question:</p>\n<blockquote>\n<p>[Is this code] an optimal way to preload images in pure JavaScript?</p>\n</blockquote>\n<p>Sorry, but that is very subjective so I cannot answer that. I am assuming good will, and thus will rather answer the following question I inferred from your original question:</p>\n<blockquote>\n<p>Am I making good use of common best practices?</p>\n</blockquote>\n<p>Now that is a question I can answer, and the simple answer is <strong>no</strong>. Sorry :)</p>\n<p>Ofcourse, I will not leave you an answer without explanation.</p>\n<br/>\n<hr />\n<br/>\n<h1> Consistency and Deliberateness</h1>\n<p>Firstly, the biggest improvement one can make in their life as a programmer would be consistency. Do not listen to the people who argue about single vs double quotes, or tabs vs spaces. As a software engineer myself, I can wholeheartedly say that all that matters is when you make a choice, you stick to it (at least within the project -- you are allowed to change your mind). Most people do not mind style (it often is enforced to a company standard anyway), but whenever you use any function or syntax, a reader would assume you did so deliberately. Why did you choose both <code>var function</code> and <code>x =&gt; y</code>?</p>\n<p>I have to admit that javascript tricked us by allowing <em>three</em> ways of creating functions, but that does not mean you should use them all together. Let us look at the ways and their reasons:</p>\n<h3><code>function name (args) { /*block*/ }</code></h3>\n<p>This is the function declaration statement. This just means that you declare a variable called <code>name</code> and assign the function to it. This was made primarily to support an <em>imperative sequence of steps</em>. It is my personal opinion that it should have been named <code>procedure</code>, because that is what it is.</p>\n<h3><code>var name = function (args) { /* block */ }</code></h3>\n<p>This is actually what happens when you declare a function, so there is no difference between this and the first type of function -- except for the more letters so I see no reason to use this notation. The only difference that could be made is through the <em>storage modifier</em> (i.e. <code>var</code> in this case), which I will tell you about a bit later.</p>\n<h3><code>var name = args =&gt; { /*block*/ }</code></h3>\n<p>This is javascript's <em>lambda</em> syntax. It allows for a very interesting way to write programs, but only if you stop appending blocks to it:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var add = (x, y) =&gt; {\n return x + y;\n};\n// is actually the same as\nvar add = (x, y) =&gt; x + y;\n</code></pre>\n<p>The <em>arrow function</em> (<code>x =&gt; y</code>) is a function that exists of only an expression, with an implied <code>return</code>. But if you use a block, you just turned it into a procedure again which negates the usefulness of the lambda/arrow notation. It can save you a lot of keystrokes, and, if I can add my opinion, looks much more clean.</p>\n<p>Taking this into consideration, your code could look like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function preload_imgs (src_list, callback) {\n let loaded = 0;\n src_list.forEach(function(src) {\n img = new Image();\n img.onload = function() {\n if (++loaded == src_list.length &amp;&amp; callback) {\n callback();\n }\n };\n img.onerror = function(err) {\n console.log(err);\n };\n img.src = src;\n });\n};\n</code></pre>\n<br/>\n<hr />\n<br/>\n<h1> Storage and Mutability</h1>\n<p>Remember the <em>storage modifiers</em> I just talked about? Javascript also has three ways of declaring variables. What a nightmare, right? Well, there is some use to the differences -- have a look:</p>\n<h3><code>var x = ...</code></h3>\n<p>In the beginning there was only <code>var</code>. It is short for <em>variable</em>, and thus should just declare a variable, right? Nope, javascript is weird. I could go on about why it is the weirdest feature ever, but <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\">here is the link about <code>var</code> if you are interested</a>. The main takeaway is that this notation does a lot of stuff behind the scenes, <a href=\"https://www.pluralsight.com/guides/javascript-callbacks-variable-scope-problem\" rel=\"nofollow noreferrer\">making it a common source of bugs</a>. My opinion: don't use it.</p>\n<h3><code>let x = ...</code></h3>\n<p>Everyone who has ever used <code>var</code> probably meant to use <code>let</code>. It does not do any fancy stuff, it creates a variable and assigns a value, except that it is <em>block scoped</em>. This variable is only ever accessible within the confines of the closest block, i.e. anything within <code>{</code> curly brackets <code>}</code>. You use only <code>let</code>, so I assume you know of this advantage but I wanted to clarify it nonetheless.</p>\n<h3><code>const x = ...</code></h3>\n<p>Again, a very autological name: <code>const</code> creates a <em>constant</em>. A constant can only be declared once, and never overwritten. This might sound like a useless trait, but it is actually really important. <a href=\"https://www.geeksforgeeks.org/10-famous-bugs-in-the-computer-science-world/\" rel=\"nofollow noreferrer\">One of the most famous bugs in the world was caused by mutability</a> (no. 4 on the list, probably more) and cost a whopping $60 million. I am not saying that using <code>const</code> will always save you millions of dollars, but it disallows any overwriting of the value, meaning:</p>\n<ul>\n<li>you cannot accidentally overwrite your or anyone else's functions and variables.</li>\n<li>you can guarantee that its value will never change, so you can refer to it anywhere safely -- even in a <code>for</code> within a <code>for</code> within a <code>for</code>.</li>\n<li>AT&amp;T would have lost $60m less.</li>\n</ul>\n<p>Coming back to deliberateness: you declare functions using <code>let</code>, implying you are going to change them, but you are not. I suggest using <code>const</code> to more clearly signal your intentions:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const preload_imgs = function (src_list, callback) {\n let loaded = 0;\n src_list.forEach(function(src) {\n const img = new Image();\n img.onload = function() {\n if (++loaded == src_list.length &amp;&amp; callback) {\n callback();\n }\n };\n img.onerror = function(err) {\n console.log(err);\n };\n img.src = src;\n });\n};\n</code></pre>\n<br/>\n<hr />\n<br/>\n<h1> I <em>promise</em> to help</h1>\n<p>Talking about common best practises, there is one thing many javascript developers will run into. That thing is the internet. A great many developers have already walked this path before you, so you bet the industry has some handy stuff up its sleeves to help you become a better programmer.</p>\n<p>Javascript has a fool-proof way of handling <em>asynchronous</em> tasks, such as preloading an image. For exactly this reason, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"nofollow noreferrer\">promises</a> were implemented. A Promise is a wrapper around an asynchronous task, so we can work with it synchronously. Without going into a lot of detail, let me summarise the most important parts of a Promise:</p>\n<ul>\n<li>A promise allows for attaching &quot;callbacks&quot; for when the wrapped task completes</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>const response = new Promise(request);\nresponse.then(doStuff);\n</code></pre>\n<ul>\n<li>A promise allows for attaching &quot;callbacks&quot; for when the wrapped task fails</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>const response = new Promise(request);\nresponse.catch(handleError);\n</code></pre>\n<p>Can you see a similarity? Creating an Image and attaching <code>onload</code>/<code>onerror</code> callbacks sounds a lot like creating a Promise! Applying this knowledge to your example gives us the following code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Your &quot;preload&quot; function goes as follows\n(src) =&gt; {\n img = new Image();\n img.onload = () =&gt; {\n if (++loaded == src_list.length &amp;&amp; callback) {\n callback();\n }\n };\n img.onerror = (err) =&gt; {\n console.log(err);\n };\n img.src = src;\n}\n// Let's update it\nconst preload = src =&gt; new Promise(function(resolve, reject) {\n const img = new Image();\n img.onload = function() {\n // onload is called with an event, not the image so we\n // want to specifically resolve with img.\n resolve(img);\n }\n img.onerror = reject;\n // onerror is called with the error, so we can directly assign &quot;reject&quot; to it.\n img.src = src;\n});\n</code></pre>\n<p>You might notice the lack of <a href=\"https://en.wikipedia.org/wiki/Free_variables_and_bound_variables\" rel=\"nofollow noreferrer\">&quot;free variables&quot;</a> (foreign variables that do not contribute to the function itself). We do not use <code>loaded</code> or <code>src_list</code> because those alter state / are mutable and are a perfect souce for the $60m bug (actually, this is probably the exact type of function that caused the race condition in their software).</p>\n<p>We have solved the preload function in a very clean way:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const preload = src =&gt; new Promise(function(resolve, reject) {\n const img = new Image();\n img.onload = function() {\n resolve(img);\n }\n img.onerror = reject;\n img.src = src;\n});\n\npreload(&quot;https://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-12/256/thumbs-up.png&quot;);\n .then(img =&gt; console.log(&quot;Preloaded&quot;, img))\n .catch(err =&gt; console.error(&quot;Failed&quot;, err));\n</code></pre>\n<p>BAM! You now have a function that preloads an image, and allows for individual succes and error handling. All we have to do now, is to apply this function to a list of <code>src</code>s.</p>\n<br/>\n<hr />\n<br/>\n<h1>➰ Going in loops</h1>\n<p>You might have thought there were too many ways to declare functions or variables, but wait till you hear in how many ways you can loop over things in javascript!</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration\" rel=\"nofollow noreferrer\">There is <code>for (let i = 0...)</code>, <code>for ... in</code>, <code>for ... of</code>, <code>while</code>, <code>do ... while</code></a>, and we have not even touched on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\">higher order array traversal functions</a>. I am just going to say it: you never really need a <code>for</code> loop. You can solve any array problem with array functions.</p>\n<blockquote>\n<p>Side note: the <code>Array.forEach</code> function you used is a weird function. It is just a slower version of a <code>for</code> loop with different notation, and I just said you never <em>need</em> a <code>for</code> loop. Either use <code>for (const src of src_list)</code> or use <code>map</code> or <code>filter</code>, but never <code>forEach</code> (this is a guideline, if it prohibits you from being productive then go ahead and do it).</p>\n</blockquote>\n<p>For example, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">there is the <code>Array.map</code> function</a>. This function takes a transformer, which goes over every element of the array, and transforms that element yielding a new array. That might sound weird so here is an example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const numbers = [1, 2, 3];\nconst double = x =&gt; x * 2;\nconst doubledNumbers = numbers.map(double);\n// doubledNumbers: [2, 4, 6]\n</code></pre>\n<p>Hmm, taking an array of values and applying a function to every value sounds a lot like what you are trying to do:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// Your old code\nsrc_list.forEach((src) =&gt; {\n img = new Image();\n img.onload = () =&gt; {\n if (++loaded == src_list.length &amp;&amp; callback) {\n callback();\n }\n };\n img.onerror = (err) =&gt; {\n console.log(err);\n };\n img.src = src;\n});\n\n// Using our &quot;preload&quot; function from before\nconst requests = src_list.map(preload);\n// requests: [Promise&lt;Image&gt;, Promise&lt;Image&gt;, Promise&lt;Image&gt;, ...]\n</code></pre>\n<p><em>Whoaaaa, <strong>one</strong> line!</em> But we have not fully refactored yet, because we now have a list of promises that can just resolve at any time and in no particular order. You seem to have understood this problem, but you solved it in a very unsafe way.</p>\n<pre class=\"lang-js prettyprint-override\"><code>let loaded = 0;\n//...\nimg.onload = () =&gt; {\n if (++loaded == src_list.length &amp;&amp; callback) { /* ... */ }\n //...\n}\n</code></pre>\n<p>You keep track of the amount of loaded images in the callback function that triggers when any image is loaded. Pretty clever, but I would bet my house that keeping track of such things in this way will cause bugs. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\" rel=\"nofollow noreferrer\">If you google &quot;wait for all promises javascript&quot;</a>, you learn of a <em>built in</em> function that takes care of all of this for you! <code>Promise.all</code> takes a list of promises, and returns a promise, that rejects when any promise in that list rejects, or resolves when all promises in the list have resolved. That is exactly what you are trying to achieve:</p>\n<pre class=\"lang-js prettyprint-override\"><code>//using the &quot;requests&quot; list we created a couple examples back\nconst done = Promise.all(requests);\ndone\n .then(images =&gt; console.log(&quot;Preloaded all&quot;, images))\n .catch(err =&gt; console.error(&quot;Failed&quot;, err));\n// &gt; Preloaded all [Image, Image, Image, ...]\n</code></pre>\n<br/>\n<hr />\n<br/>\n<h1>⌛ Conclusion</h1>\n<p>Hopefully you now have a better understanding of javascript, and the lovely built-in functions that make these things almost as easy as jquery, if not more. Maybe you even learned a lot of things along the way, maybe you were sighing and moaning because you knew most of this stuff -- as long as you learned anything I consider it a success.</p>\n<p>To summarise:</p>\n<ul>\n<li>Use any kind of function notation but be consistent and deliberate.</li>\n<li>Use <code>const</code> for constants and <code>let</code> for variables (I never even use <code>let</code> at all).</li>\n<li>Use <code>Promise</code>s to wrap asynchronous tasks to allow for really useful manipulation functions and callbacks.</li>\n<li>Familiarise yourself with higher-order functions so you never have to use loops again.</li>\n</ul>\n<p>And voila, the refactored code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const preload = src =&gt; new Promise(function(resolve, reject) {\n const img = new Image();\n img.onload = function() {\n resolve(img);\n }\n img.onerror = reject;\n img.src = src;\n});\n\nconst preloadAll = sources =&gt;\n Promise.all(\n sources.map(\n preload));\n\nconst sources = [\n 'https://i.picsum.photos/id/1000/5626/3635.jpg',\n 'https://i.picsum.photos/id/10/2500/1667.jpg',\n 'https://homepages.cae.wisc.edu/~ece533/images/cat.png',\n 'https://homepages.cae.wisc.edu/~ece533/images/airplane.png'];\n\npreloadAll(sources)\n .then(images =&gt; console.log('Preloaded all', images))\n .catch(err =&gt; console.error('Failed', err));\n</code></pre>\n<p>Preload to your hearts desire.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T08:12:01.650", "Id": "474158", "Score": "0", "body": "Great answer, thank you. Yes, I knew most of this in principle, but still a lot of things became clearer. Just let me ask one small questions regarding this: \"I would bet my house that keeping track of such things in this way will cause bugs.\" Could you explain why, or perhaps just give an example (or just a link to one)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T11:16:07.240", "Id": "474166", "Score": "0", "body": "@gaspar There are two main reasons. [Keeping track of some \"state\" in a loop, allows for this state to be modified and thus either breaking it, or making it loop infinitely](https://en.wikipedia.org/wiki/Infinite_loop). On the other hand, your code would have worked, [but it would have weird effects when you _multi-thread_ your program](https://en.wikipedia.org/wiki/Race_condition#Software) (run the [program in parallel](https://en.wikipedia.org/wiki/Thread_(computing)#Multithreading)). Both these scenarios will come up in your programming career, I assure you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T11:28:35.110", "Id": "474167", "Score": "0", "body": "I see, so basically more of a precaution than a general problem. Thanks very much again @Maanlamp." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T22:21:25.353", "Id": "241578", "ParentId": "241556", "Score": "5" } } ]
{ "AcceptedAnswerId": "241578", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T14:13:04.120", "Id": "241556", "Score": "0", "Tags": [ "javascript", "image", "ecmascript-6" ], "Title": "Best way to preload images with callback on completion with pure JavaScript (ES6)" }
241556
<p>Below is a case class and a companion object with a method <code>putRecord</code> which adds a new row into Hbase using <a href="https://hbase.apache.org/1.1/apidocs/org/apache/hadoop/hbase/client/Put.html" rel="nofollow noreferrer">Put API</a>. This code has some repetitive parts. Is there a way to abstract away the repetitive code</p> <pre><code>case class HbaseRow(_id: Option[String], field1: Option[Array[String]], field2: Option[Array[String]], field3: Option[String], field4: Option[Long]) object HbaseRow { def putRecord(row: HbaseRow): Put = { val put = new Put(Bytes.toBytes(row._id.get)) def addColumn[T](columnName: String,value: T): Put = { val columnFamily:Array[Byte] = Bytes.toBytes("cf") val col: Array[Byte] = Bytes.toBytes(columnName) // Repetative, almost same method call but for different types value match { case v: String =&gt; put.addColumn(columnFamily, col,Bytes.toBytes(v)) case v: Long =&gt; put.addColumn(columnFamily, col,Bytes.toBytes(v)) case v: Boolean =&gt; put.addColumn(columnFamily, col,Bytes.toBytes(v)) case v: Array[String] =&gt; put.addColumn(columnFamily, col,Bytes.toBytes(v.mkString(","))) } } //Repetitive will be tedious as columns increase. row.field1.map(value =&gt; addColumn[Array[String]]("f1",value.mkString(","))) row.field2.map(value =&gt; addColumn[Array[String]]("f2",value.mkString(","))) row.field3.map(value =&gt; addColumn[String]("f3",value)) row.field4.map(value =&gt; addColumn[Long]("f4",value)) put } } </code></pre>
[]
[ { "body": "<p>In <code>def addColumn</code> you can extract bytes and then add them to <code>put</code>:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>val bytes = value match {\n case v: String =&gt; Bytes.toBytes(v)\n case v: Long =&gt; Bytes.toBytes(v)\n case v: Boolean =&gt; Bytes.toBytes(v)\n case v: Array[String] =&gt; Bytes.toBytes(v.mkString(&quot;,&quot;))\n}\nput.addColumn(columnFamily, col, bytes) \n</code></pre>\n<p>I'm not sure that Scala can check generic types in pattern matching, so <code>Array[String]</code> may be checked only for class <code>Array</code>. If it is than the compiler will warn you.</p>\n<p>2nd, if you don't use result, you can use <code>foreach</code> instead of <code>map</code>.</p>\n<p>3rd <code>value.mkString(&quot;,&quot;)</code> is <code>String</code> so value type is also <code>String</code>, not <code>Array[String]</code>. Of course you can simple declare <code>def addColumn(columnName: String, value: Any)</code>, or first create <code>sealed trait ColumnValue</code> and use <code>def addColumn(columnName: String, value: ColumnValue)</code>.</p>\n<p>According to 3rd, you can use:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>List(&quot;f1&quot; -&gt; row.field1, ..., &quot;f4&quot; -&gt; row.field4).foreach {\n // you can use only 2nd case if you handle `Array` in `def addColumn`\n case (columnName, field: Array[_]) =&gt; addColumn(columnName, field.mkString(&quot;,&quot;))\n case (columnName, field) =&gt; addColumn(columnName, field)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T20:40:00.997", "Id": "246053", "ParentId": "241561", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:41:30.880", "Id": "241561", "Score": "3", "Tags": [ "scala" ], "Title": "Scala code to insert a row into Hbase" }
241561
<p><strong>Task</strong></p> <p>I want to be able to generate the <em>permutation matrix</em> that splits a 1D array of consecutive numbers (i.e. even, odd, even, odd, even, odd, ...) into a 1D array where the first half are the evens, and the second half are the odds. So (even1, odd1, even2, odd2, even3, odd3) goes to (even1, even2, even3, odd1, odd2, odd3).</p> <p>For example, with N=6, the permutation matrix would be:</p> <pre><code>M = array([1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1]) </code></pre> <p>You can check that multiplying this with <code>M * array([0, 1, 2, 3, 4, 5]) = array([0, 2, 4, 1, 3, 5])</code>.</p> <p><strong>My approach in pseudocode</strong></p> <p>(Full code below.) This is the mathematically correct way to generate this:</p> <pre><code>I = NxN identity matrix for i in [0:N-1]: if i &lt; N/2: shift the 1 in row i by 2*i to the right if i &gt;= N/2: shift the 1 in row i by 2*(i - N/2)+1 to the right </code></pre> <p>You can see how that works to generate M above.</p> <p><strong>Code (Python)</strong></p> <p>I implement the above pseudocode by using numpy array manipulation (this code is copy-and-pasteable):</p> <pre><code>import numpy as np def permutation_matrix(N): N_half = int(N/2) #This is done in order to not repeatedly do int(N/2) on each array slice I = np.identity(N) I_even, I_odd = I[:N_half], I[N_half:] #Split the identity matrix into the top and bottom half, since they have different shifting formulas #Loop through the row indices for i in range(N_half): # Apply method to the first half i_even = 2 * i #Set up the new (shifted) index for the 1 in the row zeros_even = np.zeros(N) #Create a zeros array (will become the new row) zeros_even[i_even] = 1. #Put the 1 in the new location I_even[i] = zeros_even #Replace the row in the array with our new, shifted, row # Apply method to the second half i_odd = (2 * (i - N_half)) + 1 zeros_odd = np.zeros(N) zeros_odd[i_odd] = 1. I_odd[i] = zeros_odd M = np.concatenate((I_even, I_odd), axis=0) return M N = 8 M = permutation_matrix(N) print(M) Output: array([[1., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0.], [0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 1., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1.]]) </code></pre> <p><strong>My issues</strong></p> <p>I have a feeling that there are more efficient ways to do this. To summarise what I am doing to each matrix:</p> <ol> <li><p>Looping through the rows</p></li> <li><p>At each row, identify where the <code>1</code> needs to be moved to, call it <code>idx</code></p></li> <li><p>Create a separate zeros array, and insert a <code>1</code> into index <code>idx</code></p></li> <li><p>Replace the row we are evaluating with our modified zeros array</p></li> </ol> <p>Is it necessary to split the array in two?</p> <p>Is there an Pythonic way to implement two different functions on two halves of the same array without splitting them up?</p> <p>Is there an approach where I can shift the 1s without needing to create a separate zeros array in memory?</p> <p>Do I even need to loop through the rows?</p> <p>Are there more efficient libraries than <code>numpy</code> for this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T07:34:31.610", "Id": "474157", "Score": "0", "body": "You essentially want to take the sequence 0, 1, 2, 3, 4, 5 and use these as row coords in a sparse-matrix representation." } ]
[ { "body": "<blockquote>\n <p>Are there more efficient libraries than numpy for this?</p>\n</blockquote>\n\n<p>Since permutation matrices are rather sparse, the <code>scipy.sparse</code> library is helpful.\nUsing its <code>coo_matrix</code> <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html\" rel=\"nofollow noreferrer\">method</a> we can build a matrix which contains given values at given indices. </p>\n\n<p>From here it's just a matter of building the right lists of indices.</p>\n\n<pre><code>from itertools import chain\nfrom scipy.sparse import coo_matrix\n\ndef permutation_matrix(n):\n # row and column indices - first even, then odd numbers in the latter\n I, J = range(n), list(chain(range(0, n, 2), range(1, n, 2)))\n # the following also works, if you are so inclined. \n # J = [m*2 + d for d, m in map(lambda k: divmod(k, n//2 + n % 2), range(n))]\n\n return coo_matrix(([1]*n, (I, J)))\n</code></pre>\n\n<p>If needed, we can use the <code>.A</code> property (short for <code>.toarray()</code>) to build a full matrix from this: e.g.\n<code>permutation_matrix(10).A</code>.</p>\n\n<hr>\n\n<p>Why bother with sparse matrices?</p>\n\n<p>Multiplication with sparse matrices will be much faster: e.g. matrix-vector products can be computed in <code>O(n)</code> time instead of <code>O(n^2)</code>.\nSimilarly, the memory requirements for storing these matrices in sparse format is <code>O(n)</code> instead of <code>O(n^2)</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>Is there an approach where I can shift the 1s without needing to\n create a separate zeros array in memory?</p>\n</blockquote>\n\n<p>Sure, <code>numpy.roll</code> does circular shifting:</p>\n\n<pre><code>numpy.roll([1,0,0], 4) == numpy.array([0, 1, 0])\n</code></pre>\n\n<blockquote>\n <p>Is there an Pythonic way to implement two different functions on two\n halves of the same array without splitting them up?</p>\n</blockquote>\n\n<p>Not sure, but you can always cook something up.</p>\n\n<pre><code>from collections import deque\nfrom itertools import chain\n\ndef apply_to_parts(part_selector, funs):\n\n def wrapper(vals):\n results = [deque() for _ in funs]\n\n for ix, val in enumerate(vals):\n part_ix = part_selector(ix, val)\n results[part_ix].append(funs[part_ix](val))\n\n return list(chain(*results))\n\n return wrapper\n\n# multiply elements at even indices by 2\n# divide elements at odd indices by 4 \n# return a list of elements in part 1 followed by elements in part 2\nexample = apply_to_parts(\n lambda ix, val: ix % 2,\n [lambda x:2*x, lambda y: y/4]\n)\n\n# should return [2, 6, 0.5, 1.0]\nexample([1,2,3,4])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T17:10:42.137", "Id": "474083", "Score": "2", "body": "that list comprehension is actual magic, really :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T16:57:37.093", "Id": "241567", "ParentId": "241565", "Score": "7" } }, { "body": "<p>The permutation matrix always has the same form if you look at it the right way. \nTaking the indices of the elements as their identity you basically have the following \"vector of vectors\":</p>\n\n<pre><code>[0, n//2+1, 1, n//2+2, ..., n//2, n]\n</code></pre>\n\n<p>once you realize that it becomes a matter of \"interweaving the two halves of the identity matrix\". <a href=\"https://stackoverflow.com/q/5347065/1803692\">This Stack Overflow question</a> gives an interesting suggestion on how to do that.</p>\n\n<p>This should work just fine for your purposes vastly simplifying the array accesses by virtue of using slicing to a bit more of its potential:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def permutation_matrix(N):\n I = np.identity(N)\n P = np.empty((N,N))\n mid = N//2 if N % 2 == 0 else N//2+1\n P[0::2] = I[:mid]\n P[1::2] = I[mid:]\n return P\n</code></pre>\n\n<p>with this rather satisfying result:</p>\n\n<pre><code>&gt;&gt;&gt; numbers\narray([0, 1, 2, 3, 4, 5])\n&gt;&gt;&gt; numbers.dot(permutation_matrix(6))\narray([0., 2., 4., 1., 3., 5.])\n</code></pre>\n\n<p>introducing the more appropriate <code>mid</code> that uses flooring division even allows handling an uneven amount of numbers:</p>\n\n<pre><code>&gt;&gt;&gt; numbers = np.array([0,1,2,3,4])\n&gt;&gt;&gt; numbers.dot(permutation_matrix(5))\narray([0., 2., 4., 1., 3.])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T17:09:47.547", "Id": "241568", "ParentId": "241565", "Score": "4" } }, { "body": "<p>One way is to the sequence <code>0,1,2,3,4,5</code> or <code>...(N-1)</code> and using these as row coords in a sparse-matrix (CSR) representation:</p>\n\n<pre><code>from scipy.sparse import csr_matrix\n\nN = 6\n\ncsr_matrix(([1]*6, ([0,3,1,4,2,5], [0,1,2,3,4,5] ))).toarray()\n\narray([[1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 1]], dtype=int64)\n</code></pre>\n\n<p>and for general N:</p>\n\n<pre><code>csr_matrix(([1]*N, ([0,3,1,4,2,5], list(range(N)) ))).toarray()\n\narray([[1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 1]], dtype=int64)\n</code></pre>\n\n<p>and a roundrobin iterator to generate the low/hi values:</p>\n\n<pre><code>from itertools import chain, zip_longest, cycle\n\n# If you know N is even, you can get away with this...\nN = 6\n[x for its in zip(range(N//2), range(N//2, N)) for x in its]\n# [0, 3, 1, 4, 2, 5]\n\n# But in the general case, N could be odd, and you need to handle one of the iterators being exhausted first and yielding None...\nN = 7\n[x for its in zip_longest(range(N//2), range(N//2, N)) for x in its if x is not None]\n# [0, 3, 1, 4, 2, 5, 6]\n</code></pre>\n\n<p>(It turned out writing that roundrobin iterator was a world of pain. Could be less grief to use bitwise arithmetic, or imperative code like the other answers.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T07:37:08.527", "Id": "241600", "ParentId": "241565", "Score": "2" } } ]
{ "AcceptedAnswerId": "241567", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T15:59:04.550", "Id": "241565", "Score": "6", "Tags": [ "python", "numpy" ], "Title": "Efficient numpy array manipulation to convert an identity matrix to a permutation matrix" }
241565
<p>When you use React I think that each page uses the <code>useState</code> and <code>useEffect</code> hooks:</p> <ol> <li>Initiate a GET of data from the server, and render the page immediately without data</li> <li>Then (asynchronously) receive the requested data from the server, and set the data into the state which re-renders the page</li> </ol> <p>Each page has a different server URL probably, as well as a different data type.</p> <p>My question is:</p> <ul> <li>Is it conventional to have a separate copy of the <code>useState</code> and <code>useEffect</code> hooks in each page definition?</li> <li>Or is it preferable (because of DRY) to have only one instance of the <code>useState</code> and <code>useEffect</code> hook in the whole application?</li> </ul> <p>I feel that the latter is neat and clever -- and more maintainable because there's no copy-and-pasting -- but I fear that it's too clever, <a href="https://www.osnews.com/story/19266/wtfsm/" rel="nofollow noreferrer">too "WTF?"</a>, unconventional, and not what an experienced React developer expects to see.</p> <p>To achieve the latter I found (see code below, to be reviewed) that I can wrap the hooks into a subroutine that's used/reused to render any/every page.</p> <ul> <li>The method to get data from the server is passed in as a parameter named <code>getData</code></li> <li>The method to render the page is passed in as a parameter named <code>getLayout</code></li> <li>The data type (I'm using TypeScript) is a template parameter named <code>TData</code></li> </ul> <p>This basic simple idea is implemented in the <code>useGetLayout0</code> hook.</p> <p>Overloaded versions of this function support various additional complications:</p> <ul> <li>A parameter may be passed to the <code>getData</code> function</li> <li>A parameter may be passed to the <code>getLayout</code> function</li> <li>A second parameter may be passed to the <code>getData</code> function</li> </ul> <p>An additional wrinkle is <code>newData</code> -- that exists so that it can be passed into a page layout function, so that the page layout function can invoke it to get more data, e.g. so the page can load data incrementally.</p> <p>I hope this makes sense. I've only shown the first two of the functions which invoke this hook method, actually there are as many as there are pages in the application.</p> <p>Is this too clever, would it be better to have <code>useState</code> and <code>useEffect</code>, with different hard-coded (not parameterised) <code>getData</code> functions, copied/distributed/embedded into each page (e.g. each <code>getLayout</code> function)? Would that be what's conventional? Is there an idiomatic or best-practice way to do this?</p> <p>Another "benefit" of this method is that the <code>getLayout</code> is decoupled from the <code>getData</code> -- i.e. the page layout function doesn't know how data is fetched -- that coupling is all in this <code>App.tsx</code> file which defines the routes i.e. the app's URLs.</p> <p>Is there another way to encapsulate this functionality somehow, so that it's reused by every page instead of being copied into every page?</p> <pre class="lang-js prettyprint-override"><code>import React from 'react'; import * as ReactRouter from 'react-router-dom'; import { useLayout, Layout, loadingContents, loadingError } from './PageLayout'; import { Topbar } from './Topbar'; import { Login } from './Login'; import './App.css'; import * as I from "../data"; import * as IO from "../io"; import * as Page from "./Pages"; import * as R from "../shared/urls"; import { AppContext, useMe } from './AppContext'; import { config } from "../config" import { loginUser } from "../io/mock"; import { ErrorMessage } from "./ErrorMessage"; import { NewDiscussion as NewDiscussionElement } from "./Editor"; import { History } from "history"; import { SearchInput } from "../shared/post"; /* This defines the App's routes and the context (like global data) which is available to any chld elements which it creates. */ const App: React.FunctionComponent = () =&gt; { // https://fettblog.eu/typescript-react/context/ and // https://reactjs.org/docs/context.html#updating-context-from-a-nested-component const autologin = config.autologin ? loginUser() : undefined; const [me, setMe] = React.useState&lt;I.UserSummary | undefined&gt;(autologin); document.title = `${config.appname}`; // plus https://reacttraining.com/react-router/web/api/BrowserRouter return ( &lt;AppContext.Provider value={{ me, setMe }}&gt; &lt;ReactRouter.BrowserRouter&gt; &lt;AppRoutes /&gt; &lt;/ReactRouter.BrowserRouter&gt; &lt;/AppContext.Provider&gt; ); } const AppRoutes: React.FunctionComponent = () =&gt; { // https://reacttraining.com/react-router/web/api/Switch return ( &lt;React.Fragment&gt; &lt;Topbar /&gt; &lt;ReactRouter.Switch&gt; &lt;ReactRouter.Route exact path="/index" component={SiteMap} /&gt; &lt;ReactRouter.Route exact path="/" component={Home} /&gt; &lt;ReactRouter.Route exact path="/home" component={Home} /&gt; &lt;ReactRouter.Route exact path={R.route.login} component={Login} /&gt; &lt;ReactRouter.Route exact path={R.route.siteMap} component={SiteMap} /&gt; &lt;ReactRouter.Route exact path={R.route.discussions} component={Discussions} /&gt; &lt;ReactRouter.Route exact path={R.route.newDiscussion} component={NewDiscussion} /&gt; &lt;ReactRouter.Route exact path={R.route.users} component={Users} /&gt; &lt;ReactRouter.Route exact path={R.route.tags} component={Tags} /&gt; &lt;ReactRouter.Route path={R.route.discussionsTagged} component={Discussions} /&gt; &lt;ReactRouter.Route path={R.route.users} component={User} /&gt; &lt;ReactRouter.Route path={R.route.images} component={Image} /&gt; &lt;ReactRouter.Route path={R.route.discussions} component={Discussion} /&gt; &lt;ReactRouter.Route path={R.route.tags} component={Tag} /&gt; &lt;ReactRouter.Route component={NoMatch} /&gt; &lt;/ReactRouter.Switch&gt; &lt;/React.Fragment&gt; ); } type RouteComponentProps = ReactRouter.RouteComponentProps&lt;any&gt;; /* This is a "high-order component", a "custom hook" -- it separates "getting" the data from "presenting" the data. - https://reactjs.org/docs/higher-order-components.html - https://reactjs.org/docs/hooks-custom.html The sequence of events is: 1. Called for the first time 2. Returns hard-coded `renderLayout(loadingContents)` which displays a "Loading..." message 3. useEffect fires and: - Call getData to fetch data from the server - Call getContents to render the data into a Layout instance - Call renderLayout again to show the calculated Layout elements The renderLayout method support different page layouts -- e.g. narrow text, full-screen images, a grid, and with optional extra columns. To support this it's convenient to make a single hard-coded call to renderLayout in any case, but to declare its input parameter type (i.e. the Layout interface) to be flexible/expressive, so that the getContents (i.e. one of the Page functions) can define arbitrarily complex content and layout. - getContents defines the contents of the page by creating a Layout instance which contains elements - renderLayout defines the page's columns within which the elements in the Layout are rendered --- Fetching data is as described at: - https://reactjs.org/docs/hooks-faq.html#how-can-i-do-data-fetching-with-hooks - https://overreacted.io/a-complete-guide-to-useeffect/ - https://www.robinwieruch.de/react-hooks-fetch-data And using a hook with TypeScript: - https://www.carlrippon.com/typed-usestate-with-typescript/ The template supports a parameter of type TParam (which is optional and may be void/undefined). If specified then the parameter is passed to the getData function and to the getContents function. --- Also, as described here ... https://stackoverflow.com/questions/56096560/avoid-old-data-when-using-useeffect-to-fetch-data ... if the parameter value changes then there's a brief wndow before the useEffect hook is run. Therefore the param value is stored in state whenever the data value is stored, and the data value is discarded when it's associated param value doesn't match the current param value. The solution described here ... https://overreacted.io/a-complete-guide-to-useeffect/#but-i-cant-put-this-function-inside-an-effect ... i.e. to "wrap it into the useCallback Hook" was insufficient because it leaves a brief timing hole before the useEffect fires and the data is refetched. */ // this gets data from the server type IoGetDataT&lt;TData, TParam, TParam2 = void&gt; = (param: TParam, param2?: TParam2) =&gt; Promise&lt;TData&gt;; // this defines two exra functions (named `reload` and `newData`) which are passed to the `getLayout` function type Extra&lt;TParam&gt; = { reload: () =&gt; void, newData: (param: TParam) =&gt; Promise&lt;void&gt; }; // this uses data from the server, and optional extra data, to create a Layout object type GetLayoutT&lt;TData, TExtra, TParam&gt; = (data: TData, extra: TExtra &amp; Extra&lt;TParam&gt;) =&gt; Layout; // this value is passed as param to useGetLayout when TParam is void // or I could have implemented a copy-and-paste of useGetLayout without the TParam const isVoid: void = (() =&gt; { })(); // 1st overload, used when TParam is void function useGetLayout0&lt;TData&gt;( getData: IoGetDataT&lt;TData, void&gt;, getLayout: GetLayoutT&lt;TData, {}, void&gt;): React.ReactElement { return useGetLayout&lt;TData, void&gt;(getData, getLayout, isVoid); } // 2nd overload, used when TParam (passed to the IO function) is significant function useGetLayout&lt;TData, TParam&gt;( getData: IoGetDataT&lt;TData, TParam&gt;, getLayout: GetLayoutT&lt;TData, {}, void&gt;, param: TParam): React.ReactElement { return useGetLayout2&lt;TData, TParam, {}&gt;(getData, getLayout, param, {}); } // 3rd overload when there's TExtra parameter data to pass to the page layout function function useGetLayout2&lt;TData, TParam, TExtra extends {}&gt;( getData: IoGetDataT&lt;TData, TParam&gt;, getLayout: GetLayoutT&lt;TData, TExtra, void&gt;, param: TParam, extra: TExtra) : React.ReactElement { return useGetLayout3&lt;TData, TParam, TExtra, void&gt;(getData, getLayout, param, extra); } // 4th overload when there's a second TParam2 parameter passed to the IO function function useGetLayout3&lt;TData, TParam, TExtra extends {}, TParam2&gt;( getData: IoGetDataT&lt;TData, TParam, TParam2&gt;, getLayout: GetLayoutT&lt;TData, TExtra, TParam2&gt;, param: TParam, extra: TExtra) : React.ReactElement { const [prev, setParam] = React.useState&lt;TParam | undefined&gt;(undefined); const [data, setData] = React.useState&lt;TData | undefined&gt;(undefined); const [error, setError] = React.useState&lt;Error | undefined&gt;(undefined); // we pass the reload function to the getLayout function so that it can force a reload e.g. after // posting a new message to the server. We force a reload because nothing has changed on the client -- // not even the URL -- but we want to fetch/refresh the data from the server. // https://stackoverflow.com/questions/46240647/can-i-call-forceupdate-in-stateless-component const [toggle, setToggle] = React.useState&lt;boolean&gt;(true); function reload() { setToggle(!toggle); // toggle the state to force render } // we pass a newData function to the getLayout function so that it can invoke the network I/O function again // with a new parameter (see the ThrottledInput function) and store the new data and the new parameter back here const newData = React.useMemo(() =&gt; { const getDataAgain: (param2: TParam2) =&gt; Promise&lt;void&gt; = (param2: TParam2) =&gt; { const promise = getData(param, param2); const rc: Promise&lt;void&gt; = new Promise&lt;void&gt;((resolve, reject) =&gt; { promise.then((fetched: TData) =&gt; { // the layout function has fetched new data with a new parameter // so redo now what was originally done at the end of useEffect setData(fetched); // setParam(param); resolve(); }) promise.catch(error =&gt; { reject(error); }); }); return rc; } return getDataAgain; }, [getData, param]); // add the reload function to the extra data which we pass as a parameter to the layout function // so that the layout function can call reload() if it wants to const extra2: TExtra &amp; Extra&lt;TParam2&gt; = { ...extra, reload, newData }; React.useEffect(() =&gt; { getData(param) .then((fetched) =&gt; { setData(fetched); setParam(param); }).catch((reason) =&gt; { console.log(`useEffect failed ${reason}`); setError(reason); }); }, [getData, getLayout, param, toggle]); // TODO https://www.robinwieruch.de/react-hooks-fetch-data/#react-hooks-abort-data-fetching const layout: Layout = (data) &amp;&amp; (prev === param) ? getLayout(data, extra2) // render the data : (error) ? loadingError(error) : loadingContents; // else no data yet to render return useLayout(layout); } /* These are page definitions, which have a similar basic structure: - Invoked as a route from AppRoutes - Delegate to useGetLayout There's a different function for each "route" -- i.e. for each type of URL -- i.e. each type of page data and layout. */ const SiteMap: React.FunctionComponent = () =&gt; { return useGetLayout0&lt;I.SiteMap&gt;( IO.getSiteMap, Page.SiteMap ); } // these are used as TExtra types type FetchedIsHtml = { isHtml: boolean }; const Home: React.FunctionComponent = () =&gt; { const isHtml = false; const filename = isHtml ? "home.html" : "home.md"; return useGetLayout2&lt;string, string, FetchedIsHtml&gt;( IO.getPublic, Page.Fetched, filename, { isHtml } ); } </code></pre>
[]
[ { "body": "<p>I don't normally code in JavaScript but here's some problems I see with the code.</p>\n\n<ul>\n<li><p>When skimming your code it's hard to tell where a lot of function's argument and body, end and begin.\nthis is because all arguments, return type and function body are at the same level of indentation.</p>\n\n<blockquote>\n <pre class=\"lang-js prettyprint-override\"><code>function useGetLayout2&lt;TData, TParam, TExtra extends {}&gt;(\n getData: IoGetDataT&lt;TData, TParam&gt;,\n getLayout: GetLayoutT&lt;TData, TExtra, void&gt;,\n param: TParam,\n extra: TExtra)\n : React.ReactElement {\n return useGetLayout3&lt;TData, TParam, TExtra, void&gt;(getData, getLayout, param, extra);\n}\n</code></pre>\n</blockquote>\n\n<p>Whilst you're consistent with this problem, you're not consistent in how it manifests.\nI would at the very least pick one form and stick with it.</p>\n\n<p>In addition to the above it's easy to misread the return type of functions as part of the type of the last argument. Take:</p>\n\n<blockquote>\n <pre class=\"lang-js prettyprint-override\"><code>function useGetLayout0&lt;TData&gt;(\n getData: IoGetDataT&lt;TData, void&gt;,\n getLayout: GetLayoutT&lt;TData, {}, void&gt;): React.ReactElement {\n return useGetLayout&lt;TData, void&gt;(getData, getLayout, isVoid);\n}\n</code></pre>\n</blockquote>\n\n<p>Contrast with:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function useGetLayout0&lt;TData&gt;(\n getData: IoGetDataT&lt;TData, void&gt;,\n getLayout: GetLayoutT&lt;TData, {}, void&gt;,\n): React.ReactElement {\n return useGetLayout&lt;TData, void&gt;(getData, getLayout, isVoid);\n}\n</code></pre>\n\n<p>The trailing comma helps with Git diffs when you need to add another argument to a function.</p></li>\n<li><p>I'm not a fan of how you call <code>React.useMemo</code>, in no way does it look like the lambda is not the only argument to it.</p>\n\n<ul>\n<li>You have not put the start of the lambda on a new line from the opening bracket of the function.</li>\n<li>You have not indented the body of the lambda to show that there are other arguments at the same level.</li>\n</ul>\n\n<blockquote>\n <pre class=\"lang-js prettyprint-override\"><code>const newData = React.useMemo(() =&gt; {\n ...\n}, [getData, param]);\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-js prettyprint-override\"><code>const newData = React.useMemo(\n () =&gt; {\n ...\n },\n [getData, param],\n);\n</code></pre>\n\n<p>The second form allows for more functions to be passed to the function without the need for janky formatting of the arguments.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const newData = React.useMemo(() =&gt; {\n ...\n}, [getData, param], () =&gt; {\n ...\n});\n</code></pre></li>\n<li><p>I'm not a fan of how you're getting <code>newData</code> in <code>useGetLayout3</code>:</p>\n\n<ul>\n<li>I'm not a fan of making <code>const variable</code> and then just <code>return variable</code> the next line.</li>\n<li>Normally there's never a need to manually make a <code>Promise</code>. I've not used JS in a while but I'm pretty sure you can just use <code>getData(...).then(fetched =&gt; {setData(fetched)})</code></li>\n</ul>\n\n<p></p>\n\n<pre><code>const newData = React.useMemo(\n () =&gt; (param2: TParam2) =&gt; getData(param, param2).then(f =&gt; {setData(f)}),\n [getData, param],\n);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T19:22:39.707", "Id": "474211", "Score": "1", "body": "Changing the automated code formatter to \"Prettier\" implemented some of your suggestions (I *was* using the default formatter built-in to VS Code)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T23:02:15.753", "Id": "241582", "ParentId": "241573", "Score": "4" } }, { "body": "<blockquote>\n <p>Is this too clever, would it be better to have <code>useState</code> and <code>useEffect</code>, with different hard-coded (not parameterised) <code>getData</code> functions, copied/distributed/embedded into each page (e.g. each <code>getLayout</code> function)? Would that be what's conventional? Is there an idiomatic or best-practice way to do this?</p>\n</blockquote>\n\n<p>First things fist. Whenever you start using multiple <code>useState</code> and <code>useEffect</code> calls, make sure you keep the state of hooks between those calls in mind. See the <a href=\"https://reactjs.org/docs/hooks-rules.html\" rel=\"nofollow noreferrer\">Rules of Hooks</a>. The bigger your code gets, the easier it is to accidentally break this. To help with this, make sure you keep your code readable so it's easier to spot those mistakes at first glance. The order of the hooks is important and this gets trickier with conditionals.</p>\n\n<p>I don't know much about React, but what little of it I do know is that it encourages to split-up. Files, functions, basically everything should be as small as it could be. Which style (one per page vs one per app) do you think fits this philosophy best? Could you split-out the functionality to its own function, its own file even? Do you ever need to run multiple effects on the same page? Do you ever need to skip effects for performance reasons?</p>\n\n<p>For sources on splitting-up as being encouraged, see:</p>\n\n<ul>\n<li><a href=\"https://redux.js.org/recipes/code-splitting/\" rel=\"nofollow noreferrer\">Redux.js on code splitting</a></li>\n<li><a href=\"https://github.com/airbnb/javascript/tree/master/react#basic-rules\" rel=\"nofollow noreferrer\">Airbnb's React/JSX style guide</a></li>\n<li><a href=\"https://redux.js.org/style-guide/style-guide/#only-one-redux-store-per-app\" rel=\"nofollow noreferrer\">Redux.js' style guide</a></li>\n<li><a href=\"https://reactjs.org/docs/design-principles.html#scheduling\" rel=\"nofollow noreferrer\">React.js on design principles and scheduling</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-11T00:25:27.537", "Id": "478312", "Score": "0", "body": "One file per class seems like a JS thing more than a React thing. All the cool frameworks tutorials, I've read, follow it and so do most of their tools." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T11:13:42.820", "Id": "242034", "ParentId": "241573", "Score": "3" } } ]
{ "AcceptedAnswerId": "242034", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T20:50:14.790", "Id": "241573", "Score": "3", "Tags": [ "react.js", "typescript", "jsx" ], "Title": "How many `useState` and `useEffect` instances is conventional: one per page or one per app?" }
241573
<p>Firstly, I wrote standard snake game, then I decided to increase difficulty and made game with various snake number. My main point was to try the <strong>curses</strong> module, the second - to create game with OOP architecture, maybe apply some design pattern.</p> <p><strong>Questions:</strong></p> <ol> <li>Is <code>curses</code> usage optimal?</li> <li>Should I split <code>game()</code> function some way (move some functionality out of there)?</li> <li>Where is the better place for the <code>directions</code> dictionary - <code>game()</code> function or <code>Snake</code> class from the design point of view?</li> <li>Do you see more suitable/beautiful architecture for this program? May be <code>Game</code> class should be added or something else.</li> </ol> <p><strong>Rules</strong></p> <ul> <li>A player should manage multiple snakes by switching them by keyboard.</li> <li>Every snake has a name matched to key on keyboard: '1' -> <kbd>1</kbd>, '2' -> <kbd>2</kbd>, etc.</li> <li>Snake movements are controlled by arrow keys <kbd>↑</kbd>, <kbd>↓</kbd>, <kbd>→</kbd>,<kbd>←</kbd>.</li> <li>Snakes intersection allowed for simplicity.</li> </ul> <p>The number and starting parameters of snakes are hard coded for simplicity.</p> <pre><code>import curses from random import randint class Snake: def __init__(self, size, coords, g_win, color_pair_num): y, x = coords # The snake coordinates at the beginning self.snk = [(y, x - i) for i in range(size)] self.g_win = g_win self.hght, self.wdth = g_win.getmaxyx() self.key = curses.KEY_RIGHT self.color_pair_num = color_pair_num self.draw() def draw(self): for y, x in self.snk: self.g_win.addch(y, x, curses.ACS_CKBOARD, curses.color_pair(self.color_pair_num)) self.g_win.refresh() def move_head(self, directions): y, x = self.snk[0] dy, dx = directions[self.key] y, x = y + dy, x + dx # Move out of g_win if y &lt; 0 or y &gt; self.hght or x &lt; 0 or x &gt; self.wdth: return # Bites itself if (y, x) in self.snk[2:]: return # The reverse direction movement if (y, x) == self.snk[1]: self.snk = self.snk[::-1] y, x = self.snk[0] y, x = y + dy, x + dx self.snk.insert(0, (y, x)) self.g_win.addch(y, x, curses.ACS_CKBOARD, curses.color_pair(self.color_pair_num)) return (y, x) def move_tail(self): tail_y, tail_x = self.snk.pop() self.g_win.addch(tail_y, tail_x, ' ') def change_active_snake(name, snakes, active, passive): for num, snake in snakes.items(): color = active if num == name else passive snake.color_pair_num = color snake.draw() def game(screen): directions = { curses.KEY_LEFT : (+0, -1), curses.KEY_RIGHT : (+0, +1), curses.KEY_UP : (-1, +0), curses.KEY_DOWN : (+1, +0) } curses.use_default_colors() curses.curs_set(0) food_cnt = 0 speed = 1 hght, wdth = screen.getmaxyx() score_win_width = 15 game_win_width = wdth - score_win_width score_win = curses.newwin(hght, score_win_width, 0, game_win_width) score_win.border() game_win = curses.newwin(hght, game_win_width, 0, 0) game_win.keypad(1) game_win.border() interval = 500 game_win.timeout(interval) game_win.refresh() score_win.refresh() active = 1 passive = 2 curses.init_pair(active, curses.COLOR_RED, -1) curses.init_pair(passive, curses.COLOR_BLUE, -1) x = game_win_width // 2 snakes = { 1 : Snake(3, (int(hght * 0.2), x), game_win, active), 2 : Snake(3, (int(hght * 0.5), x), game_win, passive), 3 : Snake(3, (int(hght * 0.8), x), game_win, passive) } food = None snk_num = 1 while True: score_win.addstr(1, 1, f"Score: {food_cnt}") score_win.addstr(2, 1, f"Speed: {speed}") score_win.refresh() for snk in snakes.values(): if not food: y = randint(1, hght - 2) x = randint(1, game_win_width - 2) game_win.addch(y, x, curses.ACS_CKBOARD) food = (y, x) head = snk.move_head(directions) if head == None: return if head == food: food_cnt += 1 if food_cnt % 5 == 0: interval = int(interval * 0.7) game_win.timeout(interval) speed += 1 food = None else: snk.move_tail() new_key = game_win.getch() if new_key in directions: snakes[snk_num].key = new_key # 48 is the decimal ascii code of '0' # '1' is 49, '2' is 50, etc, so subtract 48 # to get snake name from new_key. elif new_key - 48 in snakes.keys(): snk_num = new_key - 48 change_active_snake(snk_num, snakes, active, passive) game_win.refresh() curses.wrapper(game) </code></pre> <p><strong>Appearance</strong></p> <p><a href="https://i.stack.imgur.com/gQmCx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gQmCx.png" alt="enter image description here"></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T21:39:49.503", "Id": "241574", "Score": "3", "Tags": [ "python", "python-3.x", "design-patterns", "snake-game", "curses" ], "Title": "Snake game with multiple snakes" }
241574
<p>I have an action bar component. It helps do the CRUD operation for different component. Its only job is emit events. The emitted events are listened by the caller component. I am using a switch case logic to emit different events. An input is passed to this component as <code>@Input() itemType: string</code>, which holds the string as to which component called for action, to decide which event to emit. Another input <code>@Input('actionMode') mode: string;</code>, helps the component decide which HTML to display. </p> <p>Here are the two files: <strong>Component.ts</strong></p> <pre><code>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-actions', templateUrl: './actions.page.html', styleUrls: ['./actions.page.scss'], }) export class ActionsPage implements OnInit { @Input('itemType') itemName: string; @Input('actionMode') mode: string; @Output() deleteSummary = new EventEmitter&lt;void&gt;(); @Output() editSummary = new EventEmitter&lt;void&gt;(); @Output() saveSummary = new EventEmitter&lt;void&gt;(); @Output() cancelSummary = new EventEmitter&lt;void&gt;(); @Output() editCompetency = new EventEmitter&lt;void&gt;(); @Output() deleteCompetency = new EventEmitter&lt;void&gt;(); @Output() saveCompetency = new EventEmitter&lt;void&gt;(); @Output() cancelCompetency = new EventEmitter&lt;void&gt;(); constructor() {} ngOnInit() { if (this.mode !== 'question' || 'answer') console.log('Incorrect mode in the action bar'); } onDelete() { switch (this.itemName.toLowerCase()) { case 'summary': this.deleteSummary.emit(); break; case 'competency': this.deleteCompetency.emit(); break; default: } } onEdit() { switch (this.itemName.toLowerCase()) { case 'summary': this.editSummary.emit(); break; case 'competency': this.editCompetency.emit(); break; default: } } onSave() { switch (this.itemName.toLowerCase()) { case 'summary': this.saveSummary.emit(); break; case 'competency': this.saveCompetency.emit(); break; default: } } onCancel() { switch (this.itemName.toLowerCase()) { case 'summary': console.log('emitted Cancel'); this.cancelSummary.emit(); break; case 'competency': this.cancelCompetency.emit(); break; default: } } } </code></pre> <p>The HTML is the following: <strong>Component.html</strong></p> <pre><code>&lt;div *ngIf="mode === 'question'"&gt; &lt;ion-buttons slot="end"&gt; &lt;ion-button slot="end" size="small" color="secondary" (click)="onEdit()" routerDirection="forward"&gt; &lt;ion-icon slot="icon-only" name="create-outline" fill="clear"&gt;Edit&lt;/ion-icon&gt; &lt;/ion-button&gt; &lt;ion-button slot="end" size="small" color="danger" (click)="onDelete()"&gt; &lt;ion-icon slot="icon-only" name="trash-outline" fill="clear"&gt;Delete&lt;/ion-icon&gt; &lt;/ion-button&gt; &lt;/ion-buttons&gt; &lt;/div&gt; &lt;div *ngIf="mode === 'answer'"&gt; &lt;ion-button (click)="onSave()" type="button" color="primary"&gt; &lt;ion-icon slot="start" name="save"&gt;&lt;/ion-icon&gt; Save &lt;/ion-button&gt; &lt;ion-button (click)="onCancel()" color="warning" type="button"&gt; &lt;ion-icon slot="start" name="close-outline"&gt;&lt;/ion-icon&gt; Cancel &lt;/ion-button&gt; &lt;/div&gt; </code></pre> <p><strong>Is this a good way to do it ? Although very readable, but seems to me kind of tedious, especially when the number of components grow.</strong></p> <p>Can I use TypeScript Generics in this case?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T21:42:06.150", "Id": "241575", "Score": "2", "Tags": [ "generics", "angular.js", "typescript", "angular-2+" ], "Title": "Actions component in Angular" }
241575
<p><a href="https://codereview.stackexchange.com/questions/224752/exactlyone-extension-method">Here I go again.</a> I have been finding a fairly common pattern in business logic code. And that pattern looks like this: <code>int sprocketCount = datastore.GetSprocketOrders(parameters).Distinct().Count();</code> I decided I wanted to build <code>DistinctCount()</code> (again from "first principles") as <code>Distinct()</code> will create a second enumerable off of the first before <code>Count()</code> is executed. With that, here are four variations of <code>DistinctCount()</code>:</p> <pre><code>public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source) =&gt; source?.DistinctCount((IEqualityComparer&lt;TSource&gt;)null) ?? throw new ArgumentNullException(nameof(source)); public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, IEqualityComparer&lt;TSource&gt; comparer) { if (source is null) { throw new ArgumentNullException(nameof(source)); } ISet&lt;TSource&gt; set = new HashSet&lt;TSource&gt;(comparer); int num = 0; using (IEnumerator&lt;TSource&gt; enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { // ReSharper disable once AssignNullToNotNullAttribute if (set.Add(enumerator.Current)) { checked { ++num; } } } } return num; } public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { if (source is null) { throw new ArgumentNullException(nameof(source)); } if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } return source.DistinctCount(predicate, null); } public static int DistinctCount&lt;TSource&gt;( this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate, IEqualityComparer&lt;TSource&gt; comparer) { if (source is null) { throw new ArgumentNullException(nameof(source)); } if (predicate is null) { throw new ArgumentNullException(nameof(predicate)); } ISet&lt;TSource&gt; set = new HashSet&lt;TSource&gt;(comparer); int num = 0; foreach (TSource source1 in source) { if (predicate(source1) &amp;&amp; set.Add(source1)) { checked { ++num; } } } return num; } </code></pre> <p>And here are a battery of unit tests:</p> <pre><code>[TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestNull() { int[] nullArray = null; // ReSharper disable once ExpressionIsAlwaysNull Assert.AreEqual(0, nullArray.DistinctCount()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestNullPredicate() { int[] zero = Array.Empty&lt;int&gt;(); Func&lt;int, bool&gt; predicate = null; // ReSharper disable once ExpressionIsAlwaysNull Assert.AreEqual(0, zero.DistinctCount(predicate)); } [TestMethod] public void TestZero() { int[] zero = Array.Empty&lt;int&gt;(); Assert.AreEqual(0, zero.DistinctCount()); } [TestMethod] public void TestOne() { int[] one = { 1 }; Assert.AreEqual(1, one.DistinctCount()); } [TestMethod] public void TestOneWithDuplicate() { int[] oneWithDuplicate = { 1, 1, 1, 1, 1 }; Assert.AreEqual(1, oneWithDuplicate.DistinctCount()); } [TestMethod] public void TestTwo() { int[] two = { 1, 2 }; Assert.AreEqual(2, two.DistinctCount()); } [TestMethod] public void TestTwoWithDuplicate() { int[] twoWithDuplicate = { 2, 1, 2, 1, 2, 2, 1, 2 }; Assert.AreEqual(2, twoWithDuplicate.DistinctCount()); } [TestMethod] public void TestTwoWithDuplicateUsingPredicate() { int[] twoWithDuplicate = { 2, 1, 3, 2, 1, 2, 2, 1, 2, 3 }; Assert.AreEqual(2, twoWithDuplicate.DistinctCount(x =&gt; x &gt; 1)); } [TestMethod] public void TestTwoUsingNullComparer() { int[] two = { 1, 2 }; IEqualityComparer&lt;int&gt; comparer = null; // ReSharper disable once ExpressionIsAlwaysNull Assert.AreEqual(2, two.DistinctCount(comparer)); } [TestMethod] public void TestOneWithDuplicateUsingComparer() { string[] one = { "one", "One", "oNe", "ONE" }; Assert.AreEqual(1, one.DistinctCount(StringComparer.InvariantCultureIgnoreCase)); } [TestMethod] public void TestTwoWithDuplicateUsingPredicateAndComparer() { string[] two = { "one", "two", "One", "Two", "oNe", "TWO", "ONE", "tWo", "three" }; Assert.AreEqual(2, two.DistinctCount(x =&gt; x != "three", StringComparer.InvariantCultureIgnoreCase)); } </code></pre> <p>As always, ooking for overall review - is the code readable, maintainable, performant? Do the tests have the right amount of coverage or are there more particular cases to consider?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T05:25:52.330", "Id": "474151", "Score": "0", "body": "Why one version uses foreach and the other uses while and GetEnumerator?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T18:10:18.070", "Id": "474206", "Score": "0", "body": "@slepic the two versions of Count() in the original source (https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Count.cs) are different in the same fashion. It's a good question." } ]
[ { "body": "<hr>\n\n<p>As slepic in his comment, I also wonder why you use an enumerator in the first and <code>foreach</code> in the second place?</p>\n\n<hr>\n\n<p>You can eliminate <code>null</code> checks in the versions that call other overrides:</p>\n\n<blockquote>\n<pre><code>public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source) =&gt;\n source?.DistinctCount((IEqualityComparer&lt;TSource&gt;)null) ?? throw new ArgumentNullException(nameof(source));\n</code></pre>\n</blockquote>\n\n<p>can be reduced to:</p>\n\n<pre><code>public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source) =&gt; DistinctCount(source, (IEqualityComparer&lt;TSource&gt;)null);\n</code></pre>\n\n<p>And the other to:</p>\n\n<pre><code>public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) =&gt; DistinctCount(source, predicate, null);\n</code></pre>\n\n<hr>\n\n<p>Do you really need <code>num</code>? Couldn't you just return <code>set.Count</code>?</p>\n\n<hr>\n\n<p>By using <code>ToHashSet&lt;T&gt;()</code> directly as show below I only find a minor loss (if any) in performance compared to your versions:</p>\n\n<pre><code> public static class ExtensionsReview\n {\n public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source) =&gt; DistinctCount(source, (IEqualityComparer&lt;TSource&gt;)null);\n\n public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, IEqualityComparer&lt;TSource&gt; comparer)\n {\n if (source is null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n return source.ToHashSet(comparer).Count;\n }\n\n public static int DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) =&gt; DistinctCount(source, predicate, null);\n\n public static int DistinctCount&lt;TSource&gt;(\n this IEnumerable&lt;TSource&gt; source,\n Func&lt;TSource, bool&gt; predicate,\n IEqualityComparer&lt;TSource&gt; comparer)\n {\n if (source is null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n if (predicate is null)\n {\n throw new ArgumentNullException(nameof(predicate));\n }\n\n return source.Where(predicate).ToHashSet(comparer).Count;\n\n }\n }\n</code></pre>\n\n<hr>\n\n<p>According to your tests, I think you should test reference types (classes) with override of <code>Equals()</code>/<code>GetHashCode()</code> (and implementation of <code>IEquatable&lt;T&gt;</code>) with and without a custom comparer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T18:14:08.870", "Id": "474207", "Score": "1", "body": "The enumerator vs. foreach is preserved from the original source for `Count()`: https://github.com/dotnet/runtime/blob/master/src/libraries/System.Linq/src/System/Linq/Count.cs" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T05:48:00.517", "Id": "241598", "ParentId": "241584", "Score": "5" } }, { "body": "<p>Slepic and Henrik are wondering about the use of <code>foreach</code> and enumerator, and I'm too.</p>\n\n<p>Anyway, instead of having different versions with actual implementations for the same purpose (count the distinct elements), you can create one private method with the full implementation, and then, just call back this method on the other methods. </p>\n\n<p>So, the main implementation would be like this : </p>\n\n<pre><code>private static int CountDistinctIterator&lt;TSource&gt;(IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate, IEqualityComparer&lt;TSource&gt; comparer)\n{\n if (source == null) throw new ArgumentNullException(nameof(source));\n\n var set = new HashSet&lt;TSource&gt;(comparer);\n var count = 0;\n foreach (TSource element in source)\n {\n checked\n {\n if (set.Add(element) &amp;&amp; predicate(element))\n {\n count++;\n }\n\n }\n }\n\n return count;\n}\n</code></pre>\n\n<p>Now, it's a matter of calling back this method with the appropriate arguments. </p>\n\n<p>Like this : </p>\n\n<pre><code>public static int CountDistinct&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)\n{\n return CountDistinctIterator&lt;TSource&gt;(source, (s) =&gt; true, null);\n}\n\npublic static int CountDistinct&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, IEqualityComparer&lt;TSource&gt; comparer)\n{\n return CountDistinctIterator&lt;TSource&gt;(source, (s) =&gt; true, comparer);\n}\n\npublic static bool AnyDistinct&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate)\n{\n return CountDistinctIterator&lt;TSource&gt;(source, predicate, null) == 1;\n}\n\npublic static bool AnyDistinct&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)\n{\n return CountDistinctIterator&lt;TSource&gt;(source, (s) =&gt; true, null) == 1;\n}\n</code></pre>\n\n<p>although, for this <code>Distinct</code> I don't see any usage for <code>Func&lt;TSource, bool&gt; predicate</code> except for checking if the element exists or not. As the <code>Distinct</code> would get the unique elements, and if you say <code>element == xxx</code> it'll always return <code>1</code> if exists, and <code>0</code> if not. Unless there is any other uses except this one, in my opinion, I find it beneficial if rename this method: </p>\n\n<pre><code>DistinctCount&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate)\n</code></pre>\n\n<p>to something meaningful other than <code>DistinctCount</code> like for instance <code>DistinctAny</code> which return boolean (true if <code>DistinctCount</code> returns 1, false if 0). </p>\n\n<p><strong>UPDATE :</strong> \nI have changed the methods name from <code>DistinctCount</code> to <code>CountDistinct</code> the reason of this is because the method is <code>Counting</code>, so the Count needs to be first so it would be easier to picked up, the other reason is doing this will make it appear after <code>Count</code> on the intellisense list. I also added <code>AnyDistinct</code> methods which replaced the mentioned method (the one with <code>Func&lt;TSource, bool&gt;</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T17:40:33.267", "Id": "241624", "ParentId": "241584", "Score": "3" } }, { "body": "<p>Just looking at your tests, there's a couple of points to consider...</p>\n<h1>Naming</h1>\n<p>Having <code>Test</code> at the front of every test case is usually redundant (public methods in test classes are tests...). The beginning of the test name is also quite valuable real-estate since your test runner/window is likely to truncate what it displays after a certain number of characters. Consider removing the 'Test'. A better prefix might be the name of the method under test (although you may be using the name of the `TestClass for that, since you don't include that part of your code).</p>\n<h1>Make it clear what you're testing</h1>\n<p>I found your test methods that are testing for exceptions to be less than clear.</p>\n<blockquote>\n<pre><code>[TestMethod]\n[ExpectedException(typeof(ArgumentNullException))]\npublic void TestNullPredicate()\n{\n int[] zero = Array.Empty&lt;int&gt;();\n Func&lt;int, bool&gt; predicate = null;\n\n // ReSharper disable once ExpressionIsAlwaysNull\n Assert.AreEqual(0, zero.DistinctCount(predicate));\n}\n</code></pre>\n</blockquote>\n<p>Initially I skipped over the method annotation and just rest the test code. On the face of it, it look like if there was a <code>null</code> predicate, you are expecting the method to return 0. This seemed odd, however possible behaviour. There's nothing in the test name (such as <code>DistinctCount_NullPredicate_Throws</code>) to indicate what the expected outcome was, then eventually there's the <code>ExpectedException</code> attribute, which explains that actually the test is expecting an <code>ArgumentNullException</code>.</p>\n<p>Having an <code>Assert</code> statement when you're not actually expecting a value to be returned from the call is misleading. It would be better to just call the method (<code>zero.DistinctCount(predicate)</code>). The lack of an assertion helps to make it more obvious that the attributes indicate the success criteria for the test.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T01:55:22.113", "Id": "241690", "ParentId": "241584", "Score": "3" } } ]
{ "AcceptedAnswerId": "241598", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-01T23:59:42.730", "Id": "241584", "Score": "4", "Tags": [ "c#", "unit-testing", "linq", "extension-methods" ], "Title": "DistinctCount extension method" }
241584
<p>I have a small problem with the code below. Although it executes the task perfectly, It's supposed to be more "short" and compact according to the assignment feedback. I was wondering if someone can please help me change my code from its longer version to a more short version that completes the same task...</p> <pre><code>from math import * ask = input("Would you like to buy bunnies, eggs, or elections?: ") if ask == 'bunnies': bunnies = 30 print("Bunnies will cost " + str(bunnies) + " dollars each.") quantity = int(input("How many would you like to buy?: ")) cost1 = bunnies * quantity tax = (0.089 * cost1) final_cost = (cost1 + tax) if final_cost == final_cost &gt; 57.89: discount1 = (0.13 * final_cost) with_discount1 = (final_cost - discount1) print("Your total will be " + str(with_discount1) + " with a discount.") if final_cost == final_cost &lt; 57.89: print("Your total will be " + str(final_cost) + " without a discount") if ask == 'eggs': eggs = 10 print("Eggs will cost " + str(eggs) + " dollars each.") quantity = int(input("How many would you like to buy?: ")) cost2 = eggs * quantity tax = (0.089 * cost2) final_cost2 = (cost2 + tax) if final_cost2 == final_cost2 &gt; 57.89: discount = (0.13 * final_cost2) with_discount = (final_cost2 - discount) print("Your total will be " + str(with_discount) + " with a discount for eggs.") if final_cost2 == final_cost2 &lt; 57.89: print("Your total will be " + str(final_cost2) + " without a discount for eggs") if ask == 'elections': elections = 20 print("Elections will cost " + str(elections) + " dollars.") quantity = int(input("How many are you looking to purchase?: ")) cost3 = quantity * elections tax = (0.089 * cost3) final_cost3 = (cost3 + tax) if final_cost3 == final_cost3 &gt; 57.89: discount2 = (0.13 * final_cost3) withdiscount = (final_cost3 - discounts) print("Your total will be " + str(withdiscount) + " dollars with a discount for elections.") if final_cost3 == final_cost3 &lt; 57.89: print("Your total will be " + str(final_cost3) + " dollars without a discount for elections.") </code></pre>
[]
[ { "body": "<ul>\n<li><p>Using <code>from math import *</code> is highly discouraged. Please always use either:</p>\n\n<ul>\n<li><code>from math import sqrt</code>, or</li>\n<li><code>import math</code> and use <code>math.sqrt</code> instead of <code>sqrt</code>.</li>\n</ul></li>\n<li><p>You are not using <code>math</code> and so the import is not needed.</p></li>\n<li><p>It is commonly recommended to use either f-strings or <code>str.format</code> to format your strings. This is as they make reading the format easier on more complex formats.</p>\n\n<p>In your case you won't see this benefit too much but it would be a good habit to get now, rather than later.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"Bunnies will cost {} dollars each.\".format(bunnies))\nprint(f\"Bunnies will cost {bunnies} dollars each.\")\n</code></pre></li>\n<li><p>Please don't use unnecessary parentheses. This is as they add unneeded clutter to your code.</p></li>\n<li><p>You can simplify the calculation for <code>final_cost</code></p>\n\n<p><span class=\"math-container\">$$\n\\begin{array}{r l}\nc &amp;= bq\\\\\nt &amp;= 0.089c\\\\\nf &amp;= c + t\\\\\nf &amp;= 0.089c + c\\\\\nf &amp;= (0.089 + 1)c\\\\\nf &amp;= 1.089bq\n\\end{array}\n$$</span></p></li>\n<li><p>The statement <code>final_cost == final_cost &gt; 57.89</code> is confusing and only works due to Python splitting the code into two different conditionals connected with an <code>and</code>.</p>\n\n<p>The statement <code>final_cost == final_cost</code> will always be true, and so by all metrics is just bad.</p></li>\n<li><p>Your ifs are missing if the final cost is 57.89 exactly. I assume this is a mistake.</p>\n\n<p>When you have two ifs like this when one is getting half the options and the other is getting the other half it is better to use an <code>if</code> and an <code>else</code> rather than two <code>if</code>s.</p></li>\n<li><p>You don't need to store <code>discount1</code> in a variable, it's just adding lines with no visible benefit.</p></li>\n<li><p>Whilst there's nothing inherently wrong with printing the same string with a slight modification twice, you may be inclined to change it so you only define the structure of the print once.</p></li>\n</ul>\n\n<p>Overall this would get:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>bunnies = 30\nprint(f\"Bunnies will cost {bunnies} dollars each.\")\nquantity = int(input(\"How many would you like to buy?: \"))\nfinal_cost = 1.089 * bunnies * quantity\nif final_cost &gt;= 57.89:\n with_discount = final_cost - 0.13 * final_cost\n print(f\"Your total will be {with_discount} with a discount\")\nelse:\n print(f\"Your total will be {final_cost} without a discount\")\n</code></pre>\n\n<p>From here we can see all the other options have almost exactly the same code. There are only three things that change:</p>\n\n<ol>\n<li>The variable name <code>bunnies</code>.</li>\n<li>The value of the variable <code>bunnies</code></li>\n<li>The name of the item you're buying.</li>\n</ol>\n\n<p>From this we can see that a function would be good.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def price_to_buy(item, price):\n print(f\"{item} will cost {price} dollars each.\")\n quantity = int(input(\"How many would you like to buy?: \"))\n final_cost = 1.089 * price * quantity\n if final_cost &gt;= 57.89:\n with_discount = final_cost - 0.13 * final_cost\n print(f\"Your total will be {with_discount} with a discount\")\n else:\n print(f\"Your total will be {final_cost} without a discount\")\n\n\nask = input(\"Would you like to buy bunnies, eggs, or elections?: \")\nif ask == \"bunnies\":\n price_to_buy(\"Bunnies\", 30)\nif ask == \"eggs\":\n price_to_buy(\"Eggs\", 10)\nif ask == \"elections\":\n price_to_buy(\"Elections\", 20)\n</code></pre>\n\n<h1>Advanced changes</h1>\n\n<p>Whilst the above is probably what your instructor expects from you, there are more ways to improve the code and make it shorter.</p>\n\n<ul>\n<li><p>You can store the name and value in a dictionary, allowing you to condense those ifs into two lines of code.</p>\n\n<p>You may want to use a <code>try</code> and <code>except</code> here to get the code to function the same if you don't enter valid input.</p></li>\n<li>You can use <code>str.title()</code> to make the inputted item's name display in title case.</li>\n<li>You can use an <code>if __name__ == \"__main__\":</code> guard to prevent the code from running when imported, normally by accident.</li>\n<li><p>You can use a turnery to apply the discount, this is basically just an <code>if</code> and <code>else</code> but on one line!</p>\n\n<p>By also using tuple unpacking we can get the preposition (with/without) and the discount percentage in one line.</p></li>\n<li>You can use a <code>try</code> and <code>except</code> to display a nice error message.</li>\n<li>You can use <code>foo -= ...</code> rather than <code>foo = foo - ...</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def price_to_buy(item, price):\n print(f\"{item} will cost {price} dollars each.\")\n value = input(\"How many would you like to buy?: \")\n try:\n quantity = int(value)\n except ValueError:\n print(f\"{value} is not an integer.\")\n return\n cost = 1.089 * price * quantity\n discount, prep = (0.13, \"with\") if cost &gt;= 57.89 else (0, \"without\")\n cost -= discount * cost\n print(f\"Your total will be {cost} {prep} a discount\")\n\n\nPRICES = {\"bunnies\": 30, \"eggs\": 10, \"elections\": 20}\n\nif __name__ == \"__main__\":\n item = input(\"Would you like to buy bunnies, eggs, or elections?: \")\n price_to_buy(item.title(), PRICES[item])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T01:35:07.387", "Id": "474144", "Score": "0", "body": "Thank you for the pointers and for explaining it clearly. Studying this right now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T01:23:02.603", "Id": "241590", "ParentId": "241586", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T00:34:58.363", "Id": "241586", "Score": "2", "Tags": [ "python", "beginner" ], "Title": "Buying bunnies, eggs and elections with tax and a discount" }
241586
<p>I have a list of objects and I would like to see which ones are the most common. It is easy to find <em>the</em> or <em>a</em> most common object using python's <code>Counter</code>, but I haven't found a simple way to find <em>all</em> of the most common objects. The code below is working but I would guess there's a better way to do this.</p> <pre><code>from collections import Counter input_lst = [1, 2, 3, 3, 4, 4, 0, 1] counts = Counter(input_lst) ranked_counts = counts.most_common().copy() first_common_obj = ranked_counts.pop(0) equally_common_objs = [first_common_obj[0]] while ranked_counts: next_obj = ranked_counts.pop(0) if first_common_obj[1] == next_obj[1]: equally_common_objs.append(next_obj[0]) else: break print(equally_common_objs) </code></pre>
[]
[ { "body": "<p>It would be easier, and have better performance, to iterate over <code>Counter.most_common()</code> rather than using <code>.pop(0)</code> lots.</p>\n\n<p>From here you just want to use <code>next</code> until the value is not the same. Which is effectively what you're doing with <code>.pop</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\ninput_lst = [1, 2, 3, 3, 4, 4, 0, 1]\n\ncounts = Counter(input_lst)\nitems = iter(counts.most_common())\nvalue, amount = next(items)\nvalues = [value]\nwhile True:\n value, a = next(items)\n if amount != a:\n break\n values.append(value)\n\nprint(values)\n</code></pre>\n\n<p>This is effectively grouping consecutive values together, and so you can instead use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a> rather than roll your own.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\nfrom itertools import groupby\n\ninput_lst = [1, 2, 3, 3, 4, 4, 0, 1]\n\n_, values = next(groupby(Counter(input_lst).most_common(), lambda i: i[1]))\nvalues = [value for value, _ in values]\nprint(values)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T19:54:09.240", "Id": "474578", "Score": "0", "body": "The first solution hit a StopIteration and then crashed, but the second solution worked for me (Python 3.7.6)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T19:54:39.857", "Id": "474579", "Score": "0", "body": "@jss367 That issue is present in your original code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T20:21:23.577", "Id": "474584", "Score": "0", "body": "@jss367 There is an additional issue that will cause a `StopIteration` error in both my solutions and an `IndexError` in yours. Please properly test your code, before blaming me for causing errors in your code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T02:47:31.227", "Id": "241593", "ParentId": "241591", "Score": "8" } } ]
{ "AcceptedAnswerId": "241593", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T02:11:57.560", "Id": "241591", "Score": "5", "Tags": [ "python" ], "Title": "Find all of the values in a list that are repeated the most" }
241591
<p>I am building a MySQL to Realmdb converter app.</p> <p>I use Entity Framework to deal with MySQL, so below is the code of one of my model classes. I don't want to have multiple classes representing the same object, so instead of creating separate models for EF and Realm, I am using same model for both ORM's. </p> <p>The question is, is there any way to improve it, make cleaner and neat, because I don't like putting [Key] for EF and then [PrimaryKey] for Realm and the same with [Index] and [Indexed]. Also does it affect the performance of reading/writing (having support for both ORM's in one model)</p> <pre><code>using Google.Protobuf.WellKnownTypes; using MySql.Data.EntityFrameworkCore.DataAnnotations; using Realms; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Text; namespace Shared.Models { [Table("phrase")] public class Phrase : RealmObject { [Key] [PrimaryKey] [Column("phrase_id")] public int Id { get; set; } [Column("entry_id")] public int EntryId { get; set; } [Index] [Indexed] [Column("content")] public string Content { get; set; } [Index] [Indexed] [Column("notes")] public string Notes { get; set; } [Column("created_at")] public string CreatedAt { get; set; } [Column("updated_at")] public string UpdatedAt { get; set; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T07:25:03.767", "Id": "474155", "Score": "0", "body": "https://www.entityframeworktutorial.net/code-first/move-configurations-to-seperate-class-in-code-first.aspx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T13:06:33.117", "Id": "474180", "Score": "0", "body": "if is it just the attributes, then you need to create custom attributes, and in your custom attributes, define the EF and Realm attributes and map them to one custom attribute. This is I believe he easiest way to do it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T14:13:51.423", "Id": "474182", "Score": "0", "body": "this post is really useful for your case : https://stackoverflow.com/questions/38503146/combining-multiple-attributes-to-a-single-attribute-merge-attributes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T14:14:05.703", "Id": "474183", "Score": "0", "body": "another approach https://stackoverflow.com/questions/36337249/set-the-default-value-of-designerserializationvisibility-to-hidden" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T06:04:13.727", "Id": "241599", "Score": "2", "Tags": [ "c#", "performance", "database", "entity-framework", "orm" ], "Title": "Sharing model for different ORM's" }
241599
<p>The great <a href="https://codereview.stackexchange.com/a/241481/223279">feedback</a> I got on my first post on Code Review made me wary of code repetition. This code does what it is supposed to, which is to create restrictions for a sprite's possible position on the screen.</p> <p>Is this a neat looking solution, or can it be considered code repetition? </p> <pre><code>public void move(int x, int y) { int maxX = screenWidth - image.getWidth()/2; int minX = image.getWidth() / 2; int maxY = screenHeight - image.getHeight()/2; int minY = image.getHeight() / 2; if (x &gt; maxX) this.x = screenWidth - image.getWidth(); else if (x &lt; minX) this.x = 0; else this.x = x - image.getWidth() / 2; if (y &gt; maxY) this.y = screenHeight - image.getHeight(); else if (y &lt; minY) this.y = 0; else this.y = y - image.getHeight() / 2; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T09:17:30.237", "Id": "474161", "Score": "2", "body": "You certainly can reuse minX and minY more" } ]
[ { "body": "<p>It is possible to refactor your code starting from the definition of your variables:</p>\n\n<blockquote>\n<pre><code>int maxX = screenWidth - image.getWidth()/2;\nint minX = image.getWidth() / 2;\nint maxY = screenHeight - image.getHeight()/2;\nint minY = image.getHeight() / 2;\n</code></pre>\n</blockquote>\n\n<p>You are repeating function calls <code>image.getWidth()</code>, <code>image.getHeight()</code> and divisions by 2 in more than one definition, while you could call store functions calls results and division results in other variables like below:</p>\n\n<pre><code>int width = image.getWidth();\nint height = image.getHeight();\nint minX = width / 2;\nint minY = height / 2;\nint maxX = screenWidth - minX;\nint maxY = screenHeight - minY;\n</code></pre>\n\n<p>The other code you can simplify is the following:</p>\n\n<blockquote>\n<pre><code>if (x &gt; maxX)\n this.x = screenWidth - image.getWidth();\n else if (x &lt; minX)\n this.x = 0;\n else\n this.x = x - image.getWidth() / 2;\n // same behaviour of the above code\n if (y &gt; maxY)\n this.y = screenHeight - image.getHeight();\n else if (y &lt; minY)\n this.y = 0;\n else\n this.y = y - image.getHeight() / 2;\n</code></pre>\n</blockquote>\n\n<p>It is the same code applied one time to width and other time to height : you could define a helper function to be applied two times like below:</p>\n\n<pre><code>private int getNewCoordinate(int c, int l, int max, int min, int maxl) {\n if (c &gt; max) { return maxl - l; }\n if (c &lt; min) { return 0; }\n return c - l / 2;\n}\n</code></pre>\n\n<p>Now if I haven't made confusion with some variable your original code can be written like this:</p>\n\n<pre><code>public void move(int x, int y) {\n int width = image.getWidth();\n int height = image.getHeight();\n int minX = width / 2;\n int minY = height / 2;\n int maxX = screenWidth - minX;\n int maxY = screenHeight - minY;\n\n this.x = getNewCoordinate(x, width , maxX, minX, screenWidth);\n this.y = getNewCoordinate(y, height, maxY, minY, screenHeight); \n}\n\nprivate int getNewCoordinate(int c, int l, int max, int min, int maxl) {\n if (c &gt; max) { return maxl - l; }\n if (c &lt; min) { return 0; }\n return c - l / 2;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T11:01:53.470", "Id": "241607", "ParentId": "241601", "Score": "2" } } ]
{ "AcceptedAnswerId": "241607", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T08:12:01.550", "Id": "241601", "Score": "2", "Tags": [ "java", "collision" ], "Title": "Creating restrictions for a sprite's possible position on the screen" }
241601
<p>For practice purpose, I wrote bubble sort in C++ two styles: C-ish and modern C++ compliant. I would like to have your comments on any point on these implementations.</p> <pre><code>Sorting.h </code></pre> <pre><code>#ifndef SORTING_ALGORITHMS_H #define SORTING_ALGORITHMS_H #include &lt;utility&gt; #include &lt;vector&gt; //#include &lt;iterator&gt; #include &lt;algorithm&gt; namespace etpc { template &lt;class T&gt; void sortBubble(T* pArrHead, std::size_t sArrSize) { for(std::size_t i=0; i&lt;sArrSize-1; i++) { for(std::size_t j=0; j&lt;sArrSize-i-1; j++) { if(pArrHead[j]&gt;pArrHead[j+1]) std::swap(pArrHead[j], pArrHead[j+1]); } } } // May 2, 2020 // Based on the following link // https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#C.2B.2B // typename vs class // https://stackoverflow.com/questions/2023977/difference-of-keywords-typename-and-class-in-templates template &lt;class T&gt; void sortBubble(std::vector&lt;T&gt;&amp; vArrHead) { typename std::vector&lt;T&gt;::iterator begin = std::begin(vArrHead); typename std::vector&lt;T&gt;::iterator end = std::end(vArrHead); while (begin != end--) { for (auto it = begin; it != end; ++it) { if (*(it + 1) &lt; *it) { std::iter_swap(it, it + 1); } } } } } #endif // SORTING_ALGORITHMS_H </code></pre> <pre><code>Main.cpp </code></pre> <pre><code>#include "Sorting/include/Sorting.h" #include &lt;iostream&gt; #include &lt;chrono&gt; #include &lt;iterator&gt; int main() { std::chrono::steady_clock::time_point begin; std::chrono::steady_clock::time_point end; std::ostream_iterator&lt;int&gt; out_it (std::cout,", "); static const int i32Size = 50; int arr[i32Size] = {7804, 50398, 14945, 1814, 51383, 63156, 8432, 58103, 28175, 4339, 8361, 37158, 1529, 43066, 62052, 9591, 13168, 332, 55913, 2418, 48066, 46504, 52922, 39523, 36653, 30402, 9373, 56202, 50539, 41187, 42606, 32278, 63902, 41668, 7505, 46534, 25846, 49739, 63411, 45933, 15042, 6544, 35718, 17035, 34647, 15212, 52690, 64299, 61535, 45071}; begin = std::chrono::steady_clock::now(); etpc::sortBubble&lt;int&gt;(arr, i32Size); end = std::chrono::steady_clock::now(); std::cout &lt;&lt; "Time difference impArray = " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(end - begin).count() &lt;&lt; "[ns]" &lt;&lt; std::endl; std::copy(std::begin(arr), std::end(arr), out_it); std::cout &lt;&lt; '\n'; std::vector&lt;int&gt; v = {7804, 50398, 14945, 1814, 51383, 63156, 8432, 58103, 28175, 4339, 8361, 37158, 1529, 43066, 62052, 9591, 13168, 332, 55913, 2418, 48066, 46504, 52922, 39523, 36653, 30402, 9373, 56202, 50539, 41187, 42606, 32278, 63902, 41668, 7505, 46534, 25846, 49739, 63411, 45933, 15042, 6544, 35718, 17035, 34647, 15212, 52690, 64299, 61535, 45071}; begin = std::chrono::steady_clock::now(); etpc::sortBubble&lt;int&gt;(v); end = std::chrono::steady_clock::now(); std::cout &lt;&lt; "Time difference impVector = " &lt;&lt; std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(end - begin).count() &lt;&lt; "[ns]" &lt;&lt; std::endl; std::copy(std::begin(v), std::end(v), out_it); std::cout &lt;&lt; '\n'; return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T20:29:24.947", "Id": "474214", "Score": "0", "body": "You can still replace `it +1` by `std::next(it)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T20:34:29.357", "Id": "474215", "Score": "0", "body": "It's unclear to me what you are trying to get out of this review, can you elaborate?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T11:16:03.753", "Id": "474241", "Score": "0", "body": "For C-style implementation, coding practises, algorithm-specific recommendation or your personal comments. For modern C++ implementation, does it suit with modern C++, can it be improved etc? @JVApen" } ]
[ { "body": "<p>As you're already working with iterators you might as well accept iterators as arguments instead of the <code>std::vector</code> (as all STL algorithms do). That way it will work with other containers as well, even with raw pointers.</p>\n\n<p>The comparison can also be customized like in <code>std::sort</code>. Maybe the caller wants to sort in descending order or compare structures by some field.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T10:03:22.610", "Id": "241606", "ParentId": "241602", "Score": "5" } } ]
{ "AcceptedAnswerId": "241606", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T08:44:26.883", "Id": "241602", "Score": "1", "Tags": [ "c++", "algorithm", "c++11", "sorting", "c++17" ], "Title": "Bubble Sort Implementation | C-ish and Modern C++" }
241602
<p>I have a legacy piece of code and trying to simplify it. It's very tightly coupled. The problem is one method is called from another and other from another and so on this chain continues. Would someone please help me out to make it better by reviewing it or suggesting any approach or design pattern to handle this type of problem.</p> <pre><code>@Override public Boolean doCvcVerification(TransactionVO tvo) throws SQLException, CommonBaseException { if (processCvc(tvo)) { return doCvv2Verification(tvo); } else { MessageVO mvo = tvo.getRequestMessage(); if (!CommonUtils.isNullOrEmptyStr(mvo.getCvv2Value())) { tvo.setCvc2ResultCode(CvcResult.CVC2_NO_PROCESSED.code()); LGR.info(LGR.isInfoEnabled() ? "i2c CVV2 Result Code [" + tvo.getCvc2ResultCode() + "]" : null); } else { LGR.info(LGR.isInfoEnabled() ? "CVV2 is [NOT FOUND/UN-AVAILABLE] in request message for verification." : null); } return Boolean.FALSE; } } @Override public Boolean processCvc(TransactionVO tvo) throws SQLException, CommonBaseException { String track1 = tvo.getRequestMessage().getTrack1(); String track2 = tvo.getRequestMessage().getTrack2(); boolean track1Present = CommonUtils.isNullOrEmptyStr(track1) ? Boolean.FALSE : Boolean.TRUE; boolean track2Present = CommonUtils.isNullOrEmptyStr(track2) ? Boolean.FALSE : Boolean.TRUE; Boolean serviceResponse; try { // Both tracks track1 &amp; track2 not found if (!track1Present &amp;&amp; !track2Present) { LGR.info(LGR.isInfoEnabled() ? "Both DE-45(Track 1) and DE-35(Track 2) are not present in request. Tag 04.29 will be N" : null); tvo.setCvcPresent(false); buildResponseForCvc(tvo, APPROVED, DescriptionCode.CVC_BOTH_TRACKS_NOT_PRESENT, CvcResult.CVC_NOT_RECEIVED); serviceResponse = Boolean.TRUE; } // Both tracks track1 &amp; track2 found else if (track1Present &amp;&amp; track2Present) { LGR.debug(LGR.isDebugEnabled() ? "Both Tracks are found for Card No. '" + tvo.getMaskedCardNoWithSerial() + "'" : null); int statusTrack1 = parseAndVerifyTrackData(tvo, track1, 1); if (statusTrack1 != HSM_SUCCESS) { int statusTrack2 = parseAndVerifyTrackData(tvo, track2, 2); if ((statusTrack1 == HSM_FAIL &amp;&amp; statusTrack2 == NOT_FOUND) || (statusTrack1 == HSM_FAIL &amp;&amp; statusTrack2 == HSM_FAIL) || ( statusTrack1 == NOT_FOUND &amp;&amp; statusTrack2 == HSM_FAIL)) { populateCvcHsmCode(tvo); serviceResponse = Boolean.FALSE; } else if (statusTrack1 == NOT_FOUND &amp;&amp; statusTrack2 == NOT_FOUND) { buildResponseForCvc(tvo, BAD_CVC1, CvcResult.CVC1_NOT_MATCH_INCOMPLETE_TRACK.descCode(), CvcResult.CVC1_NOT_MATCH_INCOMPLETE_TRACK); serviceResponse = Boolean.FALSE; } else { buildResponseForCvc(tvo, APPROVED, CvcResult.CVC1_MATCH.descCode(), CvcResult.CVC1_MATCH); serviceResponse = Boolean.TRUE; } } else { buildResponseForCvc(tvo, APPROVED, CvcResult.CVC1_MATCH.descCode(), CvcResult.CVC1_MATCH); serviceResponse = Boolean.TRUE; } } // One track either 1 or 2 found else { int statusTrack; int trackNo = track1Present ? 1 : 2; String track = track1Present ? track1 : track2; LGR.debug(LGR.isDebugEnabled() ? "Track " + trackNo + " is found for Card No. '" + tvo.getMaskedCardNoWithSerial() + "'" : null); statusTrack = parseAndVerifyTrackData(tvo, track, trackNo); if (statusTrack == HSM_FAIL) { populateCvcHsmCode(tvo); serviceResponse = Boolean.FALSE; } else if (statusTrack == NOT_FOUND) { buildResponseForCvc(tvo, BAD_CVC1, CvcResult.CVC1_NOT_MATCH_INCOMPLETE_TRACK.descCode(), CvcResult.NULL); serviceResponse = Boolean.TRUE; } else { buildResponseForCvc(tvo, APPROVED, CvcResult.CVC1_MATCH.descCode(), CvcResult.CVC_MATCHED); serviceResponse = Boolean.TRUE; } } return serviceResponse; } catch (SQLException e) { buildResponseForCvc(tvo, DONOT_HONOR, CvcResult.CVC1_NOT_PROCESSED.descCode(), CvcResult.CVC1_NOT_PROCESSED); LGR.warn(e.getMessage(), e); throw e; } } protected int parseAndVerifyTrackData(TransactionVO tvo, String track, int trackNo) throws SQLException, CommonBaseException { int status1 = HSM_FAIL; TrackVO trackVO = parseTrack(tvo, track, trackNo, getTrackFormat()); if (null != trackVO) { status1 = verifyTrackData(tvo, trackVO); // Alternate Track Logic if (status1 != HSM_SUCCESS &amp;&amp; isAlternateTrackPresent() &amp;&amp; null != getOldTrackFormat()) { LGR.warn("CVC1 hasn't been verified by Format [" + getTrackFormat() + "], so verifying it again by Old Format [" + getOldTrackFormat() + "] in Track No." + trackNo); trackVO = parseTrack(tvo, track, trackNo, getOldTrackFormat()); LGR.debug(LGR.isDebugEnabled() ? trackVO + " from Track " + trackNo + " using Old Track Format: " + getOldTrackFormat() : null); int status2 = verifyTrackData(tvo, trackVO); if (status1 == HSM_FAIL &amp;&amp; status2 == NOT_FOUND) { return HSM_FAIL; } else if (status1 == HSM_FAIL &amp;&amp; status2 == HSM_FAIL) { return HSM_FAIL; } else if (status1 == NOT_FOUND &amp;&amp; status2 == HSM_FAIL) { return HSM_FAIL; } else if (status1 == NOT_FOUND &amp;&amp; status2 == NOT_FOUND) { return NOT_FOUND; } else { return status2; } } else { return status1; } } return status1; } protected TrackVO parseTrack(TransactionVO tvo, String track, int trackNo, String trackFormatId) throws SQLException, CommonBaseException { TrackVO trackVO = null; TrackParsingReqVO trackParsingReqVo = new TrackParsingReqVO(tvo.getInstanceId(), track, trackNo, trackFormatId); trackParsingReqVo.setCardBin(tvo.getCardBin()); if (isContactLessTrans(tvo)) { trackParsingReqVo.setIsUseContactlessFormat(true); } TrackParsingRespVO trackParsingRespVo = (TrackParsingRespVO) new TrackParsingUtility().execute(trackParsingReqVo); trackVO = trackParsingRespVo.getTrackVO(); tvo.setTrackServiceCode(trackVO.getServiceCode()); if (trackNo == 1) { tvo.setTrackChFinalName(trackVO.getCardHolderName()); tvo.setTrackChFinalNameModified(CommonBusinessUtils.formTrack(trackVO.getCardHolderName())); LGR.debug(LGR.isDebugEnabled() ? CommonUtils.concatValues("Track ", trackNo, " is tokenized for CardholderName: Original [", tvo.getTrackChFinalName(), "], Modified [", tvo.getTrackChFinalNameModified(), "]") : null); } return trackVO; } protected int verifyTrackData(TransactionVO tvo, TrackVO trackVO) throws SQLException { if (null != trackVO) { if (!CommonUtils.isNullOrEmptyStr(trackVO.getServiceCode())) { String serviceCode = trackVO.getServiceCode().trim(); if (CommonUtils.isNotNullAndValidInt(serviceCode)) { setContactLessTrans(tvo.getRequestMessage(), serviceCode); } else { LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid ServiceCode [" + serviceCode + "]"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } if (!CommonUtils.isNullOrEmptyStr(trackVO.getCvc())) { String cvc = trackVO.getCvc().trim(); if (!CommonUtils.isNotNullAndValidInt(cvc)) { LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid CVC [" + cvc + "]"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } if (!CommonUtils.isNullOrEmptyStr(trackVO.getPanSeqNo())) { String panSeqNo = trackVO.getPanSeqNo().trim(); if (!CommonUtils.isNotNullAndValidInt(panSeqNo)) { LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid PanSeqNo [" + panSeqNo + "]"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } if (!CommonUtils.isNullOrEmptyStr(trackVO.getAtc())) { String atc = trackVO.getAtc().trim(); if (!CommonUtils.isNotNullAndValidInt(atc)) { LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid ATC [" + atc + "]"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } if (!CommonUtils.isNullOrEmptyStr(trackVO.getUn())) { String un = trackVO.getUn().trim(); if (!CommonUtils.isNotNullAndValidInt(un)) { LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid UN [" + un + "]"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } if (!CommonUtils.isNullOrEmptyStr(trackVO.getUnl())) { String unl = trackVO.getUnl().trim(); if (!CommonUtils.isNotNullAndValidInt(unl)) { LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid UNL [" + unl + "]"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } //validates expiration Integer expValidation = validateTrackExpiry(tvo, trackVO.getTrackNo(), trackVO.getExpiryValue()); if (expValidation == HSM_SUCCESS) { if (!validateSecureElements(tvo, trackVO)) { return NOT_FOUND; } else { tvo.setCvcPresent(true); return verifyCvc(tvo, trackVO); } } else { return expValidation; } } else { LGR.error("Incomplete Track-: Null TrackVO"); setHsmRespCode(HSM_DECLINE); return HSM_FAIL; } } @Override protected boolean validateSecureElements(TransactionVO tvo, TrackVO trackVO) { boolean valid = false; try { if ((CommonUtils.isNullOrEmptyStr(trackVO.getCvc()) || CommonUtils.isNullOrEmptyStr(trackVO.getServiceCode())) &amp;&amp; (!tvo.isCardSwiped() || tvo.isCardNotPresentTrans()) &amp;&amp; "1".equals(tvo.getRequestMessage().getCvv2Indicator())) { LGR.info("CVC1/iCVV not received in track data. CVV2 will be evaluated."); valid = true; } else { valid = super.validateSecureElements(tvo, trackVO); } } catch (CommonBaseException e) { LGR.info("Someone introduced a shitty exception in whole hierarchy and I have to catch it here. This is anti pattern. But who follows!"); } return valid; } @Override protected int verifyCvc(TransactionVO tvo, TrackVO trackVo) { if(CommonUtils.isNullOrEmptyStr(trackVo.getCvc())){ return NOT_FOUND; } trackVo.setExpiryDate(CommonDateUtils.parseDate(CommonDateConstants.DATE_FORMAT_yyMM, trackVo.getExpiryValue())); CvcType cvcType = getCvc1Type(tvo); setReceivedCvcType(cvcType); CvcHsmValidation cvcValidator = CvcHsmFactory.getInstance().getCvcHsmValidationObj(cvcType, this, tvo, trackVo); LGR.info(LGR.isInfoEnabled() ? "Validating " + cvcType : null); CvcHsmResponse respCvc = cvcValidator.verifyCvc(); LGR.info(LGR.isInfoEnabled() ? cvcType + " validation response: " + respCvc : null); if (APPROVED.equals(respCvc.getRespCode())) { if (!CommonUtils.isNullOrEmptyStr(trackVo.getExpiryValue())) { tvo.setExpiryDateFromTrans(trackVo.getExpiryValue(), CommonDateConstants.DATE_FORMAT_yyMM); } setCvcValidationStatus(CvcValidationResult.MATCHED); return HSM_SUCCESS; } else { setCvcValidationStatus(CvcValidationResult.NOT_MATCHED); return HSM_FAIL; } } @Override public Boolean doCvv2Verification(TransactionVO tvo) throws SQLException { String cardBin = tvo.getCardBin(); Boolean serviceResponse = Boolean.FALSE; // checking flag of process_cvv2 from table of multi-instance if (CommonBaseConstants.OPTION_YES.equalsIgnoreCase(getCvcValidationDao().getProcessCvv2(cardBin))) { serviceResponse = processCvv2(tvo); } else { LGR.debug(LGR.isDebugEnabled() ? CommonUtils.concatValues( "CVV2 will be processed as normal as process_cvv2 flag in table is either 'N' or null for card bin: ", cardBin) : null); } return serviceResponse; } </code></pre> <p>Complete source code is available at <a href="https://repl.it/@tishytash/TomatoHungryCareware" rel="nofollow noreferrer">repl</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T14:30:43.070", "Id": "474189", "Score": "0", "body": "(`I am unable to make it better anyhow` I have an inkling you don't want to imply what I take that phrase to do.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T14:56:13.430", "Id": "474192", "Score": "0", "body": "`Complete source code is available at …` Um, I didn't get to see *complete source code* even following that hyperlink. But the code there makes me think a review of the code in this question pointless: your problem is **B**igger." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T15:04:38.090", "Id": "474193", "Score": "0", "body": "(One word of warning: Refrain from refactoring before automated unit tests are a) somewhat convincing b) routinely used.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:10:24.397", "Id": "474228", "Score": "0", "body": "@greybeard I have pasted that code here. Yes, I have automated unit tests to verify if anything breaks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:16:44.190", "Id": "474232", "Score": "0", "body": "Your edit added a commendable amount of code to review. It did *not* meet concerns the code is yours to change: Are you a maintainer of (that part of) the project?" } ]
[ { "body": "<p>A small improvement I can make is to remove the <code>if-else</code> blocks with <code>if</code> like the below code , This will improve the readability of the code</p>\n\n<pre><code> if (processCvc(tvo)) {\n return doCvv2Verification(tvo);\n }\n MessageVO mvo = tvo.getRequestMessage();\n if (CommonUtils.isNullOrEmptyStr(mvo.getCvv2Value())){\n LGR.info(LGR.isInfoEnabled() ? \"CVV2 is [NOT FOUND/UN-AVAILABLE] in request message for verification.\" : null);\n return Boolean.FALSE;\n\n }\n tvo.setCvc2ResultCode(CvcResult.CVC2_NO_PROCESSED.code());\n LGR.info(LGR.isInfoEnabled() ? \"CVV2 Result Code [\" + tvo.getCvc2ResultCode() + \"]\" : null);\n return Boolean.FALSE;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:14:18.900", "Id": "474230", "Score": "0", "body": "Thanks. But it's not the only method. The complete source code was present at repl that I just pasted here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T21:54:45.973", "Id": "241632", "ParentId": "241604", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T09:23:33.983", "Id": "241604", "Score": "-1", "Tags": [ "java", "design-patterns" ], "Title": "Legacy Code Refactoring" }
241604
<p>I have class:</p> <pre><code>export class DayValue { date: string; status: string; } </code></pre> <p>and statusToPointsMap:</p> <pre><code> public static map: Map&lt;string, number&gt; = new Map([ ['COMPLETED', 100], ['FAILED', -100], ['SKIPPED', 0], ]); </code></pre> <p>I want to create function which calculates avg result per given period of time, ie:</p> <pre><code>[ [ "2020-05-02", "COMPLETED" ], [ "2020-05-01", "FAILED" ], [ "2020-04-30", "FAILED" ], [ "2020-04-29", "SKIPPED" ], [ "2020-03-13", "SKIPPED" ] ] </code></pre> <p>to (groupped by month)</p> <pre><code>[ ["05-2020",0], [ "04-2020",-40], ["03-2020",0] </code></pre> <p>]</p> <p>or(groupped by year):</p> <pre><code>["2020",-16] </code></pre> <p>I created a function which works as I wanted, but I'm wonder if there is any way to to it smarter? </p> <pre><code> private calculateAvgPerPeriod(values: DayValue[], period: string): any[] { const resultArray = []; from(values).pipe( groupBy(dayValue =&gt; this.datePipe.transform(dayValue.date, period)), mergeMap(group =&gt; group.pipe(toArray())), map(array =&gt; [ this.datePipe.transform(array[0].date, period), array .map(day =&gt; this.statusToPointsMap.get(day.status)) .reduce((prev, curr) =&gt; prev + curr, 0) / array.length ] )) .subscribe(entry =&gt; { resultArray.push(entry); }); return resultArray; } </code></pre>
[]
[ { "body": "<p>You're using RxJS, but your inputs and outputs are plain arrays. It'd be simpler to either consume and return streams or replace RxJS with Lodash/Ramda/Underscore/native array methods/some iteration-based library.</p>\n<p>(If you want to get really fancy or need to use the function in different contexts, you could write a <a href=\"https://ramdajs.com/docs/#transduce\" rel=\"nofollow noreferrer\">transducer</a>.)</p>\n<p>You're using a class, a method and a static property, but it would be sufficient to have a type, a function and a module-local constant. And passing <code>datePipe</code> (or just a <code>Date</code>) and <code>status =&gt; getPointsFromStatusToPointsMap(status)</code> function as arguments would make the dependencies more explicit. But these are more like code style preferences.</p>\n<p>Lastly, you're returning <code>any</code>, but you should always return <code>unknown</code> instead unless you really have to lie to the type system for some reason. And returning <code>[string, number]</code> or <code>[Date, number]</code> would be more convenient for the consumer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-18T12:53:11.350", "Id": "244107", "ParentId": "241605", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T10:02:26.577", "Id": "241605", "Score": "1", "Tags": [ "javascript", "typescript", "rxjs" ], "Title": "Typescript & rxJS group list of object by month/year and map to certain value" }
241605
<p>I am trying to solve a Hackerrank problem <a href="https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem" rel="nofollow noreferrer">Sherlock and Anagrams</a>. I think my code is valid but somehow times out for some of the test cases. Any tips on how to improve its performance? Critique unrelated to performance is welcome as well!</p> <p>Here is my main method which gets a string as an input and returns an integer that represents the number of pairs of substrings of the string that are anagrams of each other:</p> <pre><code>function sherlockAndAnagrams(s) { let substrings = []; let pairs = []; // get all substrings for (let i = 0; i &lt; s.length+1; i++) { for (let j = i+1; j &lt; s.length+1; j++) { substrings.push(s.substring(i, j)); } } // sort substrings so they can be compared using === substrings = substrings.map(sub =&gt; [...sub].sort().join(&quot;&quot;)); // count them by comparing each with each skipping the ones with different length return substrings.reduce((counter, sub, index, arr) =&gt; { return counter += arr.reduce((acc, item, jndex) =&gt; { if (sub.length === item.length &amp;&amp; sub === item &amp;&amp; index !== jndex) { let uid = [index, jndex].sort().join(&quot;&quot;); if (!pairs.includes(uid)) { acc++; pairs.push(uid); } } return acc; }, 0); }, 0); } </code></pre> <p>Here is a shortened version of <a href="https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem" rel="nofollow noreferrer">the problem description</a> as additional context:</p> <blockquote> <p>Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.</p> <p>sherlockAndAnagrams has the following parameter: <em>s</em>: a string</p> <p>It must return an integer that represents the number of anagrammatic pairs of substrings in <em>s</em>. For each query, return the number of unordered anagrammatic pairs.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T11:53:24.390", "Id": "474328", "Score": "0", "body": "@MartinR Stop overcomplicating this. The question was not answered as in solved. I implemented an idea that did not solve the problem. I will not ask a new question about the same thing with similar code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T11:58:16.840", "Id": "474329", "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)*. I have locked the question for a day for now." } ]
[ { "body": "<p><code>comparing each with each</code> means the quadratic time complexity, and <code>skipping the ones with different length</code> does not improve the bottomline.</p>\n\n<p>Sort the set of (sorted) substrings, and the anagrams will form contiguous runs. The run of length <span class=\"math-container\">\\$k\\$</span> produces <span class=\"math-container\">\\$\\dfrac{k(k-1)}{2}\\$</span> pairs.</p>\n\n<hr>\n\n<p>Example:</p>\n\n<p>An original array:</p>\n\n<pre><code>ab\ncde\nxy\ndec\nba\nced\n</code></pre>\n\n<p>After each string has been sorted, it becomes</p>\n\n<pre><code>ab\ncde\nxy\ncde\nab\ncde\n</code></pre>\n\n<p>Now, after the entire array is sorted lexicographically, it becomes</p>\n\n<pre><code>ab\nab\ncde\ncde\ncde\nxy\n</code></pre>\n\n<p>The <code>ab, ab</code> and <code>cde, cde, cde</code> form the contiguous (that is, uninterrupted) runs, of length 2 and 3 respectively.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-30T19:36:40.227", "Id": "490435", "Score": "0", "body": "i have been watching this video (https://youtu.be/3fpSbdzR6Pc?t=768) a few times and googling this formula - I really do not understand how you/he came up to it (I not a computer science student) - can you help me figure this out? what should I research? can you simplify how you got to the formula for me please?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T19:43:56.193", "Id": "241627", "ParentId": "241608", "Score": "2" } }, { "body": "<p>I am a javascript beginner, let me know the ways how I can improve my answer; every suggestion is welcome. </p>\n\n<p>The problem can be divided in two parts:</p>\n\n<ol>\n<li>Part 1 : how to calculate number of pairs from a set of elements</li>\n<li>Part 2 : given one string , extract all the substrings inside the\nmain string and find calculate the number of pairs of strings that\nare anagrams one of the other.</li>\n</ol>\n\n<h2>Part1</h2>\n\n<p>The number of the pairs from a set of <code>n</code> elements can be calculated with the formula npairs = n! / (2 * (n - 2)!) = (n * (n - 1)) / 2, below one function to calculate the number of pairs:</p>\n\n<pre><code>function countPairs(n) {\n return (n * (n - 1)) / 2;\n}\n</code></pre>\n\n<p>The <code>countPairs</code> function will return the numbers of pairs from a set of <code>n</code> elements and it is used in the part2.</p>\n\n<h2>Part2</h2>\n\n<p>To store anagrams you can use a <code>Map</code> structure storing anagrams and their occurrences , so if you have for example two strings <code>ab</code> and <code>ba</code> the <code>map['ab']</code> will be <code>2</code>. Once you stored all the substrings inside your <code>map</code> you will iterate over it to return the sum of the pairs found. So for example if you have in your map <code>map['ab'] = 3</code> (three substring anagrams found) the number of pairs will be determined calling <code>countPairs(3)</code>. If you have for example <code>map['cc'] = 1</code> then it is not possible to create pairs and it will excluded from the calculus of the sum of the pairs. Below the <code>sherlockAndAnagrams</code> function:</p>\n\n<pre><code>function sherlockAndAnagrams(s) {\n const map = new Map();\n const n = s.length;\n for (let i = 0; i &lt; n; ++i) {\n for (let j = i; j &lt; n; ++j) {\n const sub = s.substring(i, j + 1);\n const key = sub.split('').sort().join('');\n if (map.has(key)) {\n map.set(key, map.get(key) + 1); \n } else {\n map.set(key, 1);\n }\n }\n } //done , substrings stored in the map\n\n //Check all map values and calculate number of pairs \n //for every key with an associate value &gt; 1\n let result = 0;\n for (const [key, value] of map) {\n if (value &gt; 1) {\n result += countPairs(value); \n }\n }\n return result;\n}\n</code></pre>\n\n<p>I tried it on the Hackerrank site, passing all tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T17:44:50.343", "Id": "241675", "ParentId": "241608", "Score": "1" } } ]
{ "AcceptedAnswerId": "241627", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T11:20:00.497", "Id": "241608", "Score": "0", "Tags": [ "javascript", "performance", "programming-challenge", "strings" ], "Title": "Sherlock and Anagrams in Javascript" }
241608
<p>I'm a Rust newbie. As a pet project, I decided to implement a simple multi-threaded HTTPS proxy server in Rust which uses the CONNECT protocol. I have tested the code below using my browser.</p> <pre><code>use std::io::prelude::*; // Contains the read/write traits use std::net::{TcpListener, TcpStream}; use std::str; use std::io; use std::thread; const PORT: i32 = 5000; // Function to handle connection fn handle_client(mut stream: TcpStream) { println!("[*] Received connection request from {:?}", stream); // Read the CONNECT request's bytes into the buffer let mut buf = [0; 4096]; // Read the bytes from the stream let nbytes = match stream.read(&amp;mut buf) { Ok(n) =&gt; n, Err(_) =&gt; return () // early return if an error }; println!("[*] Received {} bytes of data", nbytes); // Convert the request to a string let req : &amp;str = match str::from_utf8(&amp;buf) { Ok(s) =&gt; s, Err(_) =&gt; return () // early return if an error }; println!("[*] Received request {}", req); // Split the text on whitespace and get the hostname let website : &amp;str = req.split_whitespace().collect::&lt;Vec&lt;_&gt;&gt;()[1]; println!("[*] Connecting to {}", website); // Open a TCP connection to the website let mut tunnel = match TcpStream::connect(website) { Ok(t) =&gt; t, Err(_) =&gt; return () }; // Send an ack to the client match stream.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") { Ok(_) =&gt; (), Err(_) =&gt; return () }; // Set both sockets to nonblocking mode match stream.set_nonblocking(true) { Ok(()) =&gt; (), Err(_) =&gt; return () }; match tunnel.set_nonblocking(true) { Ok(()) =&gt; (), Err(_) =&gt; return () } let mut stream_buf = [0u8; 4096]; // Buffer containing data received from stream let mut tunnel_buf = [0u8; 4096]; // Buffer containing data received from tunnel let mut stream_nbytes = 0usize; // The number of bytes pending in stream_buf to be written to tunnel let mut tunnel_nbytes = 0usize; // The number of bytes pending in tunnel_buf to be written to stream // Keep copying data back and forth loop { // Read data from stream to be sent to tunnel -- only read if stream_buf is empty if stream_nbytes == 0 { stream_nbytes = match stream.read(&amp;mut stream_buf) { Ok(0) =&gt; return (), // Socket closed Ok(n) =&gt; n, Err(e) if e.kind() == io::ErrorKind::WouldBlock =&gt; 0, // If there is no data, return 0 bytes written Err(_) =&gt; return () }; } // Read data from tunnel to be sent to stream -- only read if tunnel_buf is empty if tunnel_nbytes == 0 { tunnel_nbytes = match tunnel.read(&amp;mut tunnel_buf) { Ok(0) =&gt; return (), // Socket closed Ok(n) =&gt; n, Err(e) if e.kind() == io::ErrorKind::WouldBlock =&gt; 0, // If there is no data, return 0 bytes written Err(_) =&gt; return () }; } // Write data from stream to tunnel if stream_nbytes &gt; 0 { // Pass the slice corresponding to first `stream_nbytes` match tunnel.write(&amp;mut stream_buf[0..stream_nbytes]) { Ok(0) =&gt; return (), // Socket closed Ok(n) if n == stream_nbytes =&gt; stream_nbytes = 0, // If we get equal Ok(_) =&gt; { println!("Cannot write partially :("); return () }, // No support for partial nbytes Err(e) if e.kind() == io::ErrorKind::WouldBlock =&gt; (), // Write the bytes in later Err(_) =&gt; return () } } // Write data from tunnel to stream if tunnel_nbytes &gt; 0 { // Pass the slice corresponding to first `stream_nbytes` match stream.write(&amp;mut tunnel_buf[0..tunnel_nbytes]) { Ok(0) =&gt; return (), // Socket closed Ok(n) if n == tunnel_nbytes =&gt; tunnel_nbytes = 0, // If we get equal Ok(_) =&gt; { println!("Cannot write partially :("); return () }, // No support for partial nbytes Err(e) if e.kind() == io::ErrorKind::WouldBlock =&gt; (), // Write the bytes in later Err(_) =&gt; return () } } } } fn main() -&gt; std::io::Result&lt;()&gt; { // Create a server let local_addr = format!("localhost:{}", PORT); let server = TcpListener::bind(local_addr)?; println!("[*] Listening on port {}", PORT); // Keep spinning and spawn threads for any incoming connections for stream_result in server.incoming() { match stream_result { Ok(stream) =&gt; thread::spawn(move || handle_client(stream)), // Spawn a new thread, ignore the return value because we don't need to join threads _ =&gt; continue }; } Ok(()) } </code></pre> <p>I am looking for critique on the following facets of my code -</p> <ol> <li>Is this idiomatic Rust? It feels quite verbose and convoluted when compared to implementations in other languages. I'm wondering if that is just a feature of Rust or I'm missing something. Is my use of Rust primitives (like slices, arrays, etc.) optimal? Can I refactor the code? </li> <li>Is there a better way to handle errors?</li> <li>Can I improve the performance of the code? Are there better alternatives than threading which are not too complicated to implement? </li> <li>Can I write better comments and improve readability? </li> <li>Can I improve logging?</li> </ol> <p>Feel free to point out anything else that could have been done better. </p>
[]
[ { "body": "<h2>Idiomatic Rust</h2>\n\n<h3>Standard utilities</h3>\n\n<p>Much of your code is contained in the std function <code>std::io::copy</code>, which you can use to avoid handling each side of the pipe:</p>\n\n<pre><code>match io::copy(&amp;mut reader, &amp;mut writer) {\n Ok(0) =&gt; return (),\n Err(e) if e.kind() != io::ErrorKind::WouldBlock =&gt; return (),\n _ =&gt; ()\n}\n</code></pre>\n\n<p>And you can also use a for loop to avoid repeating yourself here:</p>\n\n<pre><code>let pipes = [\n (&amp;stream, &amp;tunnel),\n (&amp;tunnel, &amp;stream)\n];\n\nloop {\n for (mut reader, mut writer) in pipes.iter() {\n // ...\n }\n}\n</code></pre>\n\n<h3>Error Handling</h3>\n\n<p>You have a pattern repeating in your code for handling errors:</p>\n\n<pre><code>let value = match expression {\n Ok(value) =&gt; value,\n Err(_) =&gt; return ()\n};\n</code></pre>\n\n<p>This pattern is actually so common that Rust provides the <a href=\"https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/the-question-mark-operator-for-easier-error-handling.html\" rel=\"nofollow noreferrer\"><code>?</code> operator</a> which behaves the same way:</p>\n\n<pre><code>let values = expression?;\n</code></pre>\n\n<p>Okay, it's actually a little different: When using the <code>?</code> operator, Rust needs to know how to convert the value to your return type. It does this using an implementation of <code>E: Into&lt;ReturnType::Error&gt;</code>, and so your function will need to return a compatible type. For small applications, using a crate like <code>anyhow</code> makes this easy:</p>\n\n<pre><code>use anyhow::*;\n\nfn handle_client(...) -&gt; Result&lt;()&gt; {\n // Read the CONNECT request's bytes into the buffer\n let mut buf = [0; 4096];\n let nbytes = stream.read(&amp;mut buf)?;\n}\n</code></pre>\n\n<p>Now that we are receiving errors from the handler, we can let the user know about them</p>\n\n<pre><code>thread::spawn(move || {\n if let Err(error) = handle_client(stream) {\n error!(\"error while handling stream: {}\", error);\n }\n});\n</code></pre>\n\n<p>Also, returning an error from <code>main</code> uses a default implementation that isn't very user friendly:</p>\n\n<pre><code>Error: Os { code: 10048, kind: AddrInUse, message: \"Only one usage of each socket address (protocol/network address/port) is normally permitted.\" }\n</code></pre>\n\n<p>It might be better to provide a more descriptive error message:</p>\n\n<pre><code>let server = TcpListener::bind((\"localhost\", PORT)).unwrap_or_else(|e| {\n if e.kind() == io::ErrorKind::AddrInUse {\n error!(\"Port {} is already being used by another program\", PORT);\n std::process::exit(1);\n } else {\n panic!(\"{:?}\", e);\n }\n});\n</code></pre>\n\n<h3>Logging</h3>\n\n<p>The [<code>log</code>] crate is a pretty conventional way of writing log messages in Rust - many libraries support it directly, letting you see what's happening inside their code too. Just set up a logger using a crate like [<code>env_logger</code>] and output messages using its' macros.</p>\n\n<pre><code>use log::*;\n\nfn main() {\n env_logger::init();\n // ...\n info!(\"Listening on port {}\", PORT);\n}\n</code></pre>\n\n<h3>And in no particular order...</h3>\n\n<ul>\n<li><code>TcpListener::bind</code> takes a <code>ToSocketAddrs</code>. You can avoid allocating with <code>bind((\"localhost\", PORT))</code>.</li>\n<li>You can write a <code>match</code> with one arm as an <a href=\"https://doc.rust-lang.org/stable/rust-by-example/flow_control/if_let.html\" rel=\"nofollow noreferrer\"><code>if let</code> statement</a></li>\n<li>You can get the 2nd item in an <em>iterator</em> with <code>nth</code>: \n\n<blockquote>\n<pre><code>let website = req\n .split_whitespace()\n .nth(1)\n</code></pre>\n</blockquote></li>\n<li>Personally, I don't use top level imports for items I only use a single time,\npreferring to use <code>let req = std::str::from_utf8(&amp;buf)?;</code></li>\n<li>Speaking of that line, you might want to convert <code>&amp;buf[..nbytes]</code> instead, to\navoid checking the empty part of the buffer.</li>\n</ul>\n\n<h2>Comments</h2>\n\n<p>If you ask me, the code is easier to read with <em>less</em> comments - you should be\ndescribing the conceptual purpose of a block of code. \"Read the bytes from the\nstream\" doesn't tell me anything more about <em>why</em> you are calling <code>stream.read</code>.</p>\n\n<p>Rather, I think this is more helpful</p>\n\n<pre><code>// Read the CONNECT request's bytes into the buffer\nlet mut buf = [0; 4096];\nlet nbytes = stream.read(&amp;mut buf)?;\n</code></pre>\n\n<p>There is also no problem treating log messages as documentation - they can\nteach the reader about the behaviour of the code just as well.</p>\n\n<p>Another example would be the request parsing:</p>\n\n<pre><code>// Split the text on whitespace and get the hostname\nlet website : &amp;str = req.split_whitespace().collect::&lt;Vec&lt;_&gt;&gt;()[1];\n</code></pre>\n\n<p>I can already see that you are splitting the string on whitespace - it says it\nright there in the method name. It's more helpful to know what this line is\ndoing. It could be \"Parse the hostname from the request\", but I'd be happy just\nusing the variable name to document this line.</p>\n\n<p>On the other hand, abbreviations can get in the way of a reader's understanding\n- try to avoid them when they describe an important part of the code:</p>\n\n<pre><code>// Send an acknowledgement to the client\nstream.write_all(b\"HTTP/1.1 200 Connection established\\r\\n\\r\\n\")?;\n</code></pre>\n\n<h3>Performance</h3>\n\n<p>Each thread is currently using a busy loop to wait for data on the sockets, and isn't gaining much in performance from it. You can make it much easier on your computer by adding a small <code>std::thread::sleep</code> between each iteration of the loop.</p>\n\n<p>Even better though: this kind of application is particularly suited to <code>async</code>: The proxy will be able to handle many more clients without choking on the heavyweight threads, and wake up each task the moment data is ready on the socket. With <code>smol</code> and <code>futures</code>, you can write code that'll look nearly identical to the sync code (and actually fix a problem where packets can get dropped if the write socket is full). Altogether, these changes look like this: <a href=\"https://gist.github.com/Plecra/d95f170bc8f42ed80158f3dcc19bcc9a/c6feec657343b05123ba58d56b784846497a64bc#file-proxy-rs-L53\" rel=\"nofollow noreferrer\">proxy.rs</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T17:05:19.417", "Id": "241673", "ParentId": "241611", "Score": "4" } } ]
{ "AcceptedAnswerId": "241673", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T11:51:44.963", "Id": "241611", "Score": "4", "Tags": [ "beginner", "rust", "socket" ], "Title": "HTTPS proxy server in Rust using the CONNECT protocol" }
241611
<p>Hi I am pretty new to programming and I would like you to give me some feedback about my code, how does it look, what could be better. Thank you.</p> <pre><code>A = [] B = [] C = [] PegDict = {'A': A,'B': B,'C': C} #Would it be better to use a two dimensional array? discs = int(input("Podaj ilość dysków: ")) for i in range(discs, 0, -1): A.append(i) movesNeeded = pow(2, discs) - 1 StartingPeg = A.copy() def move(fromm, to): to.append(fromm[-1]) fromm.pop() </code></pre> <p>Moves the smallest disc one peg to the left. This part could be done better i think.</p> <pre><code>def moveLeft(): if A and A[-1] == 1: move(A, C) return if B and B[-1] == 1: move(B, A) return if C and C[-1] == 1: move(C, B) return </code></pre> <p>Moves the smallest disc one peg to the right</p> <pre><code>def moveRight(): if A and A[-1] == 1: move(A, B) return if B and B[-1] == 1: move(B, C) return if C and C[-1] == 1: move(C, A) return </code></pre> <p>Returns key of a peg that is the only valid move target for a cartain peg</p> <pre><code>def PossibleMove(Peg): if Peg: if Peg[-1] != 1: for i in PegDict: x = PegDict[i] if not x: return i elif Peg[-1] &lt; x[-1]: return i </code></pre> <p>Main part</p> <pre><code>moves = 0 while not C == StartingPeg: if discs%2 == 0: moveRight() moves += 1 else: moveLeft() moves += 1 print(A) print(B) print(C) print() for key in PegDict: if PossibleMove(PegDict[key]) != None: fromPeg = PegDict[key] onePossibleMove = PossibleMove(PegDict[key]) if fromPeg: moves += 1 move(fromPeg, PegDict[onePossibleMove]) print(A) print(B) print(C) print() print() print('Moves: '+ str(moves)) print('Minimal number of moves: '+ str(movesNeeded)) </code></pre>
[]
[ { "body": "<h1>PEP-8</h1>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> has many stylistic guidelines that all Python programs should follow.</p>\n\n<ul>\n<li>Naming\n\n<ul>\n<li>functions, methods, and variables should all be <code>snake_case</code>. <code>CapitalWords</code> are reserved for <code>Types</code> and <code>ClassNames</code>. So <code>movesNeeded</code> should be <code>moves_needed</code> and <code>PegDict</code> should be <code>peg_dict</code>, and so on.</li>\n</ul></li>\n<li>Commas\n\n<ul>\n<li>All commas should be followed by exactly one space. <code>{'A': A,'B': B,'C': C}</code> violates this.</li>\n</ul></li>\n<li>Binary operators\n\n<ul>\n<li>Binary operators should be surrounded by one space. You mostly follow this, except for the <code>print('Moves: '+ str(moves))</code> statements at the end.</li>\n</ul></li>\n</ul>\n\n<h1>Exponentiation</h1>\n\n<pre><code>movesNeeded = pow(2, discs) - 1\n</code></pre>\n\n<p>Python has the <code>**</code> operator, for exponentiation. Thus, this could be written slightly more compactly:</p>\n\n<pre><code>moves_needed = 2 ** discs - 1\n</code></pre>\n\n<h1>Initial list generation</h1>\n\n<pre><code>A = []\n\nfor i in range(discs, 0, -1):\n A.append(i)\n</code></pre>\n\n<p>This is a little verbose. You are already using the <code>range()</code> method to generate the disc numbers; you could simply create a list directly from the result:</p>\n\n<pre><code>a = list(range(discs, 0, -1))\n</code></pre>\n\n<h1>Moving a Disc</h1>\n\n<pre><code>def move(fromm, to):\n to.append(fromm[-1])\n fromm.pop()\n</code></pre>\n\n<p>I'm going to assume <code>fromm</code> is not a spelling error, but rather avoiding the <code>from</code> keyword. The PEP-8 recommendation is a trailing underscore: <code>from_</code>. My personal preference is to use synonyms.</p>\n\n<p><code>.pop()</code> returns the item removed from the list, which is the value you used <code>fromm[-1]</code> to retrieve. Therefore, these operations could easily be combine into one statement:</p>\n\n<pre><code>def move(source, destination):\n destination.append(source.pop())\n</code></pre>\n\n<h1>Repeated Code</h1>\n\n<pre><code> print(A)\n print(B)\n print(C)\n print()\n</code></pre>\n\n<p>You've repeated this code twice. Once moving the small disc, once moving a larger disc. Instead of repeating the code, you should move this into a function. Then, if you change how the discs are shown (curses, GUI, ...), you only have to alter the code once.</p>\n\n<pre><code>def print_pegs(a, b, c):\n print(a)\n print(b)\n print(c)\n print()\n</code></pre>\n\n<h1>Iterating over a container</h1>\n\n<pre><code> for key in PegDict:\n if PossibleMove(PegDict[key]) != None:\n fromPeg = PegDict[key]\n onePossibleMove = PossibleMove(PegDict[key])\n</code></pre>\n\n<p>In this code, you are iterating over the <code>PegDict</code>, fetching the keys, and using the key to look up the dictionary value. In fact, you never use the key for anything else. You do not need the key at all, and could simply iterate over the contents of the dictionary:</p>\n\n<pre><code> for peg in peg_dict.values():\n if possible_move(peg) != None:\n from_peg = peg\n one_possible_move = possible_move(peg)\n</code></pre>\n\n<p>But notice we are computing using <code>possible_move(peg)</code> twice. This is inefficient. You should compute the result once, save it in a temporary, and use the temporary variable for further tests and assignments:</p>\n\n<pre><code> for peg in peg_dict.values():\n move = possible_move(peg)\n if move != None:\n from_peg = peg\n one_possible_move = move\n</code></pre>\n\n<h1>More Advanced Changes</h1>\n\n<h2>Left or Right?</h2>\n\n<p>Each iteration, you check if the number of discs was even or odd, and call the <code>moveLeft()</code> or <code>moveRight()</code> function. Since the number of discs is constant, you always make the same choice. You could move this decision out of the loop.</p>\n\n<pre><code>move_smallest_disc = move_left if disc % 2 != 0 else move_right\n\nwhile len(c) != discs: # A simpler termination condition\n\n move_smallest_disc()\n print_pegs(a, b, c)\n moves += 1\n\n ...\n</code></pre>\n\n<p>But I've a different option...</p>\n\n<h2>Cyclic Peg Order</h2>\n\n<p>You always move the smallest disc either:</p>\n\n<ul>\n<li>a -> b -> c -> a -> b -> c</li>\n<li>a -> c -> b -> a -> c -> b</li>\n</ul>\n\n<p>You can keep track of which order you need with a list:</p>\n\n<pre><code> if discs % 2 == 1:\n peg = [a, c, b]\n else:\n peg = [a, b, c]\n</code></pre>\n\n<p>And move the smallest disc from <code>peg[0]</code> to <code>peg[1]</code>, without having to hunt for which peg the smallest disc is on:</p>\n\n<pre><code> move(peg[0], peg[1])\n</code></pre>\n\n<p>And later rotate the <code>peg</code> list:</p>\n\n<pre><code> peg = peg[1:] + peg[:1] # [a, b, c] -&gt; [b, c, a] -&gt; [c, a, b] -&gt; [a, b, c]\n</code></pre>\n\n<p>After moving the smallest disc onto <code>peg[1]</code>, the only possible moves for the larger disc will be <code>peg[0]</code> -> <code>peg[2]</code> or <code>peg[2]</code> -> <code>peg[0]</code>, so you can greatly simplify the possible move determination, by just looking at those two pegs:</p>\n\n<pre><code> source, destination = possible_move(peg[0], peg[2])\n move(source, destination)\n</code></pre>\n\n<h1>Refactored Code</h1>\n\n<pre><code>from pathlib import Path\nimport gettext\ngettext.install('hanoi', Path(__file__).parent)\n\ndef move(source, destination):\n destination.append(source.pop())\n\ndef possible_move(peg1, peg2):\n if peg1 and (not peg2 or peg1[-1] &lt; peg2[-1]):\n return peg1, peg2\n else:\n return peg2, peg1\n\ndef print_pegs(a, b, c):\n print(a)\n print(b)\n print(c)\n print()\n\ndef tower_of_hanoi(discs):\n a = list(range(discs, 0, -1))\n b = []\n c = []\n\n minimum_moves = 2 ** discs - 1\n\n if discs % 2 == 1:\n peg = [a, c, b]\n else:\n peg = [a, b, c]\n\n moves = 0\n while len(c) != discs:\n if moves % 2 == 0:\n move(peg[0], peg[1]) # Smallest disc now on peg[1]\n else:\n source, destination = possible_move(peg[0], peg[2])\n move(source, destination)\n peg = peg[1:] + peg[:1] # Rotate the peg ordering\n\n print_pegs(a, b, c)\n moves += 1\n\n print()\n print(_('Moves:'), moves)\n print(_('Minimal moves:'), minimum_moves)\n\nif __name__ == '__main__':\n discs = int(input(_('Enter the number of disks: ')))\n tower_of_hanoi(discs)\n</code></pre>\n\n<p>If you run <a href=\"https://docs.python.org/3/library/gettext.html#internationalizing-your-programs-and-modules\" rel=\"noreferrer\"><code>pygettext</code></a> on this, you can make a <code>hanoi.pot</code> template file, copy it to <code>hanoi.po</code> and put translations into it:</p>\n\n<pre><code>msgid \"Moves:\"\nmsgstr \"Liczba ruchów:\"\n\nmsgid \"Minimal moves:\"\nmsgstr \"Minimalna liczba ruchów:\"\n\nmsgid \"Enter the number of disks: \"\nmsgstr \"Podaj ilość dysków: \"\n</code></pre>\n\n<p>Run <code>msgfmt</code> on that to generate an <code>hanoi.mo</code> file, and store it the subdirectory: <code>pl/LC_MESSAGES</code>.</p>\n\n<p>Running <code>LANG=\"pl\" ./hanoi.py</code> on my machine, gives:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Podaj ilość dysków: 2\n[2]\n[1]\n[]\n\n[]\n[1]\n[2]\n\n[]\n[]\n[2, 1]\n\n\nLiczba ruchów: 3\nMinimalna liczba ruchów: 3\n</code></pre>\n\n<p>With luck, I haven't butchered the translated strings too badly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T21:02:09.160", "Id": "474216", "Score": "1", "body": "Hi! To me the following is more readable at a glance: `def possible_move(*args): return sorted(args, key=lambda ls: ls[-1] if ls else float('inf'))`, but that may very well simply be a sign of deeper personal issues. Cheers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T21:08:21.000", "Id": "474217", "Score": "1", "body": "You're not wrong. I'm unhappy with my current `possible_moves()`. I'd like to hit the sweet spot between yours & mine, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T21:34:31.793", "Id": "474218", "Score": "1", "body": "@Andrew Compromise: when no-one gets what they want. Reduced it from 10 lines down to 4, but 1 line is just going too far. :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T19:59:06.540", "Id": "241628", "ParentId": "241617", "Score": "6" } } ]
{ "AcceptedAnswerId": "241628", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T14:06:16.550", "Id": "241617", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "tower-of-hanoi" ], "Title": "Tower of Hanoi without recursion" }
241617
<p>My take on this problem for a hobby project.</p> <p>I have an event loop that advances game state and processes user input.</p> <p>Rendering is no concern of this event loop, and is intended to run on a separate thread.</p> <p>The event loop is GUI agnostic and works with a generic <code>GameLogic</code> that must comply with a certain interface. </p> <p>Any feedback is appreciated, either about specific parts of the code or overall design.</p> <p>The event loop:</p> <pre><code>template&lt;typename GameLogic&gt; class EventLoop { public: using GameLogicType = GameLogic; using StateType = typename GameLogic::StateType; using EventType = typename GameLogic::EventType; using StateStoreType = StateStore&lt;StateType&gt;; explicit EventLoop(const GameLogicType &amp;gameLogic) : _gameLogic{std::move(gameLogic)} { } void run() { auto durationFromStart = [realTimeStart = ClockType::now()]() { return std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(ClockType::now() - realTimeStart); }; int simulationSteps{0}; auto state = _gameLogic.initialState(); for (;;) { while ((simulationSteps * framePeriod) &lt; durationFromStart()) { std::vector&lt;EventType&gt; events; _eventQueue.getAllAndClear(std::back_insert_iterator(events)); state = _gameLogic.updateState(state, simulationTimeStep, events.cbegin(), events.cend()); _stateStore.setState(state); ++simulationSteps; } auto lag = (simulationSteps * framePeriod) - durationFromStart(); if (lag &gt; std::chrono::microseconds{0}) std::this_thread::sleep_for(lag); if (_stop) break; } } void sendEvent(EventType e) { _eventQueue.push(std::move(e)); } void stop() { _stop = true; } const StateStoreType &amp;stateStore() const { return _stateStore; } private: static constexpr int frameRate{60}; static constexpr std::chrono::microseconds framePeriod{1'000'000 / frameRate}; static constexpr double simulationTimeToRealTime = 1.0; static constexpr double simulationTimeStep = 1.0 / frameRate / simulationTimeToRealTime; using ClockType = std::chrono::high_resolution_clock; GameLogicType _gameLogic; StateStoreType _stateStore; detail::Queue&lt;EventType&gt; _eventQueue; std::atomic&lt;bool&gt; _stop{false}; }; </code></pre> <p>Helper classes:</p> <pre><code>namespace detail { /** * Event queue for cross-thread data exchange */ template&lt;typename T&gt; class Queue { public: void push(T &amp;&amp;value) { std::lock_guard guard{_mtx}; _queue.push_back(std::forward&lt;T&gt;(value)); } template&lt;typename OutputIt&gt; void getAllAndClear(OutputIt outBegin) { std::lock_guard guard{_mtx}; for (auto &amp;e: _queue) // no exception safety for now... caller must be careful *outBegin++ = std::move(e); _queue.clear(); } private: std::deque&lt;T&gt; _queue; mutable std::mutex _mtx; }; } /** * state container used for cross-thread data exchange */ template&lt;typename StateType&gt; class StateStore { public: void setState(const StateType &amp;state) { std::lock_guard guard{_mtx}; _state = state; } StateType state() const { std::lock_guard guard{_mtx}; return _state; } private: StateType _state; mutable std::mutex _mtx; }; </code></pre> <p>A minimal game logic implementation would be:</p> <pre><code>struct SimpleState { double x; double y; }; struct SimpleEvent { double sx; double sy; }; class SimpleGameLogic { public: using StateType = SimpleState; using EventType = SimpleEvent; explicit SimpleGameLogic(const StateType &amp;initialState) : _initialState{initialState} { } StateType initialState() { return _initialState; } template&lt;typename EventInputIt&gt; SimpleState updateState(const SimpleState &amp;state, double timeStep, EventInputIt eventsBegin, EventInputIt eventsEnd) { (void) timeStep; SimpleState newState{state}; std::for_each(eventsBegin, eventsEnd, [&amp;newState](const SimpleEvent &amp;event) { newState.x = newState.x + event.sx; newState.y = newState.y + event.sy; }); return newState; } private: StateType _initialState; }; </code></pre> <p>The GUI thread interacts with the event loop as follows:</p> <pre><code> // ... using MyEventLoop = EventLoop&lt;SimpleGameLogic&gt;; std::unique_ptr&lt;MyEventLoop&gt; eventLoop; std::thread eventLoopThread; // ... void my_gui_init() { eventLoop = std::make_unique&lt;MyEventLoop&gt;(SimpleGameLogic{}); eventLoopThread = std::thread(&amp;MyEventLoop::run, eventLoop.get()); } void my_gui_quit() { eventLoop-&gt;stop(); eventLoopThread.join(); } void my_gui_user_input_handler(MyGuiInputType input) { MyEventLoop::EventType event = mapUserInput(input); eventLoop-&gt;sendEvent(event); } void my_gui_update_method() { my_gui_render(eventLoop-&gt;state()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T16:14:19.407", "Id": "474197", "Score": "0", "body": "Many gaming keyboards scan for input at 1000 Hz or more. Does this code reduce the handling of that input to 60 Hz? Not that that is necessarily bad, but I hope it would be on purpose if it is the case :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T18:45:53.633", "Id": "474209", "Score": "0", "body": "@MaartenBodewes Thanks for your comment. The frequency of the loop is in principle arbitrary. If we assume the game logic is too heavy to keep up with 1000Hz then the high-freq input would accumulate in the queue and processed in batch every time step... or at least that's my thinking as a non-expert in this field." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T13:31:34.420", "Id": "474408", "Score": "0", "body": "What is the declaration of `eventLoop` within `my_gui_init`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:40:59.773", "Id": "474441", "Score": "0", "body": "@Edward See the re-worked version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:47:34.520", "Id": "474442", "Score": "0", "body": "There is still a problem because now `eventLoop` is local to `my_gui_init()` and inaccessible to the other functions. It would clarify your intent for the code if you make your example into something that actually compiles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T15:36:03.537", "Id": "474561", "Score": "0", "body": "@Edward Sorry, my edit was sloppy. I think it should make more sense now. Keep in mind that the GUI part is intentionally pseudo-code. I think a concrete GUI implementation would be quite out of scope here." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T14:30:33.787", "Id": "241618", "Score": "6", "Tags": [ "c++", "game" ], "Title": "Game event loop for multi-threaded application" }
241618
<p>I am trying to optimize this code for solving a system of ODE. It seems <code>Cython</code> does not speed up the code compared to code using <code>numpy</code>.</p> <p>This the python code using <code>numpy</code>:</p> <pre><code>"""Solve system of ODEs.""" def solver(ode_sys, I, t, integration_method): N = len(t)-1 u = np.zeros((N+1, len(I))) u[0, :] = I dt = t[1] - t[0] for n in range(N): u[n+1, :] = integration_method(u[n, :], t[n], dt, n, ode_sys) return u, t def RK2(u, t, dt, n, ode_sys): K1 = dt * ode_sys(u, t) K2 = dt * ode_sys(u + 0.5 * K1, t + 0.5 * dt) unew = u + K2 return unew def problem1(u, t): return -u + 1.0 from numpy import exp def problem2(u, t): return - u + exp(-2.0 * t) </code></pre> <p>to run the code:</p> <pre><code>def run(ode_sys, N, nperiods=40): I = np.ones(N) time_points = np.linspace(0, nperiods * 2 * np.pi, nperiods * 30 + 1) u, t = solver(ode_sys, I, time_points, RK2) </code></pre> <p><strong>timing</strong></p> <pre class="lang-py prettyprint-override"><code>%timeit run(problem1, 1000, 1000) %timeit run(problem2, 100, 500) </code></pre> <pre class="lang-sh prettyprint-override"><code>418 ms ± 22.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 233 ms ± 79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) </code></pre> <p><strong>My <code>Cython</code> version:</strong> I directly call the functions inside the module to get more speedup</p> <pre><code>%%cython --annotate import numpy as np cimport numpy as np cimport cython ctypedef np.float_t DT cdef extern from "math.h": double exp(double) @cython.boundscheck(False) # turn off bounds checking for this func. @cython.wraparound(False) # Deactivate negative indexing. cpdef solver(ode_sys, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] I, np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] t, integration_method): cdef int N = len(t)-1 cdef np.ndarray[DT, ndim=2, negative_indices=False, mode='c'] u = np.zeros((N+1, len(I))) u[0, :] = I cdef double dt = t[1] - t[0] cdef int n for n in range(N): u[n+1, :] = RK2(u[n, :], t[n], dt, n, ode_sys) return u, t def RK2(np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] u, double t, double dt, int n, ode_sys): cdef np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] K1, K2, unew K1 = dt * problem1(u, t) K2 = dt * problem1(u + 0.5 * K1, t + 0.5 * dt) unew = u + K2 return unew cdef problem1(np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] u, double t): return -u + 1.0 cdef problem2(np.ndarray[DT, ndim=1, negative_indices=False, mode='c'] u, double t): return - u + exp(-2.0 * t) </code></pre> <p><strong>timing:</strong></p> <pre class="lang-py prettyprint-override"><code>%timeit run(problem1, 1000, 1000) # note that to check promlem2 I need to change it inside the modules </code></pre> <pre class="lang-sh prettyprint-override"><code>424 ms ± 8.23 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) </code></pre> <p>Thanks in advance for any guide.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T15:43:49.767", "Id": "241621", "Score": "2", "Tags": [ "python", "cython" ], "Title": "Optimizing the Cython code for solving system of ODEs" }
241621
<p>I have a big collection of MP4 files and an unstable internet connection so I use <a href="https://superuser.com/a/1241089">this batch file</a> to check for the files integrity.</p> <p>Having posted <a href="https://codereview.stackexchange.com/q/241369/223101">this primitive code</a> and received valuable reviews, I decided to take into consideration as much as I can, especially not mixing C code unless when using Windows API and implement the said batch file using that code as the basis.</p> <p>This program works in CMD it takes a path to MP4 location as argument.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;windows.h&gt; #ifndef INVALID_FILE_ATTRIBUTES #define INVALID_FILE_ATTRIBUTES ((DWORD)-1) #endif bool DirectoryExists(const std::string&amp; path) { DWORD present = GetFileAttributesA(path.c_str()); if (present == INVALID_FILE_ATTRIBUTES) return false; if (present &amp; FILE_ATTRIBUTE_DIRECTORY) return true; return false; } std::string replace (const std::string&amp; path) { std::string in = path; std::replace(in.begin(), in.end(), '\\', '/'); return in; } void findVideos (std::string&amp; fspath) { while(*(fspath.rbegin()) =='/') //to get rid of trailing '/' like a user inputs path/to/file//////\\\ fspath.pop_back(); size_t i=1; WIN32_FIND_DATA FindFileData; std::string destpath = fspath + std::string("/")+ std::string("*.mp4"); std::string ffmpegPath = "ffmpeg.exe -v error -f null - -i "; HANDLE hFind = FindFirstFile(destpath.c_str(), &amp;FindFileData); if (hFind != INVALID_HANDLE_VALUE) { do { std::string fullpath = std::string(fspath)+std::string("/")+std::string(FindFileData.cFileName); std::cout&lt;&lt;i&lt;&lt;"-"&lt;&lt;"Checking "&lt;&lt;fullpath&lt;&lt;" for errors"&lt;&lt;std::endl; std::string command = ffmpegPath +std::string("\"")+fullpath+std::string("\""); system(command.c_str()); i++; } while(FindNextFile(hFind, &amp;FindFileData)); } FindClose(hFind); } int main(int argc, char**argv) { const char* path = argv[1]; if (path == nullptr) { std::cout&lt;&lt;"No path provided"&lt;&lt;std::endl; return 0; } else if ( DirectoryExists(path) ) std::cout&lt;&lt;"Provided path is: "&lt;&lt;path&lt;&lt;std::endl; else { std::cout&lt;&lt;"Path doesn't exist"&lt;&lt;std::endl; return 0; } std::string fspath; fspath = replace(path); findVideos (fspath); return 0; } </code></pre> <p>The code is working, I am open to criticism and any way to improve it especially if I work in a professional company and asked to implement such program.</p> <p>EDIT: Please forgive my ignorance about indentation and other programming paradigms, I graduated a year ago and failed to get an internship or a job in the domain. I tried to go with the comments as much as I can after reading some articles about indentations.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T16:45:39.783", "Id": "474199", "Score": "3", "body": "Could you please fix the indentation before receiving your first review? Consistent indentation inside curly braces (whether it's the usual 4 spaces per level, or 2 spaces, or even 1 or 3 or whatever) is important for readability. (But once someone's reviewed the code, it's too late to edit it, because you might invalidate their comments.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T16:50:31.697", "Id": "474200", "Score": "3", "body": "<s>Why do you have code outside a function?</s> Oh, wait, there's just no indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T19:09:06.933", "Id": "474210", "Score": "0", "body": "Do yourself and many others a favor by getting a C/C++ editor that automatically indents for you. There are some that are free, such as Visual Studio Community(https://visualstudio.microsoft.com/vs/community/) and Eclipse (https://www.eclipse.org/downloads/packages/). There are also some that don't cost that much such as CLion by JetBrains https://www.jetbrains.com/. In addition to auto indent, they will help you with auto complete for variables and function names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T19:43:22.497", "Id": "474212", "Score": "2", "body": "I have Visual Studio, but I am using Notepad to learn from scratch, I will read about proper indentation, but my lack of experience is failing me seeing anything catastrophic in my code, please point the unacceptable parts." } ]
[ { "body": "<h2>Missing Header File</h2>\n\n<p>You need to include <code>algorithm</code> so that <code>std::replace()</code> can be accessed.</p>\n\n<h2>Error Checking</h2>\n\n<p>Rather than checking if <code>argv[1]</code> is null, it might be better to use <code>argc</code> in the error check. If <code>argc</code> is not greater than 1 than there is an error. This is what <code>argc</code> is meant to be used for, as well as for a loop control when there are more arguments. It might be good to give an example of the proper program call as part of the error message. </p>\n\n<p>The <code>else</code> that follows the error check is not necessary because of the <code>return</code> statement.</p>\n\n<p>The first <code>return</code> statement in <code>main()</code> should not return zero, it should return 1 to indicate a failure. What might be even better is to include <code>cstdlib</code> and use the system defined symbols <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\">EXIT_SUCCESS and EXIT_FAILURE</a>.</p>\n\n<p>It would be better to report errors to std::cerr.</p>\n\n<pre><code>int main(int argc, char** argv)\n{\n if (argc &lt;= 1)\n {\n std::cerr &lt;&lt; \"No path provided\" &lt;&lt; std::endl;\n return EXIT_FAILURE;\n }\n\n const char* path = argv[1];\n if (!DirectoryExists(path))\n {\n std::cerr &lt;&lt; \"Path doesn't exist\" &lt;&lt; std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout &lt;&lt; \"Provided path is: \" &lt;&lt; path &lt;&lt; std::endl;\n\n std::string fspath;\n fspath = replace(path);\n findVideos(fspath);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<h2>Horizontal Spacing</h2>\n\n<p>A best practice in many programming languages is to put spaces between operators and operands, this makes the code much more readable and maintainable:</p>\n\n<pre><code>void findVideos (std::string&amp; fspath) {\n while (*(fspath.rbegin()) == '/')\n {\n fspath.pop_back();\n }\n\n size_t i = 1;\n WIN32_FIND_DATA FindFileData;\n std::string destpath = fspath + std::string(\"/\") + std::string(\"*.mp4\");\n std::string ffmpegPath = \"ffmpeg.exe -v error -f null - -i \";\n\n HANDLE hFind = FindFirstFile(destpath.c_str(), &amp;FindFileData);\n\n if (hFind != INVALID_HANDLE_VALUE)\n {\n do\n {\n std::string fullpath = std::string(fspath)+std::string(\"/\") + std::string(FindFileData.cFileName);\n std::cout &lt;&lt; i &lt;&lt; \"-\" &lt;&lt; \"Checking \" &lt;&lt; fullpath &lt;&lt; \" for errors\" &lt;&lt; std::endl;\n std::string command = ffmpegPath +std::string(\"\\\"\") + fullpath+std::string(\"\\\"\");\n system(command.c_str());\n i++;\n }\n while(FindNextFile(hFind, &amp;FindFileData));\n }\n FindClose(hFind);\n}\n</code></pre>\n\n<h2>Prefer Modern C++ <code>constexpr</code> Over <code>#define</code></h2>\n\n<p>In C++ creating a constant using <code>constexpr</code> is preferred over a macro because it it type safe and a macro is not type safe.</p>\n\n<pre><code>#ifndef INVALID_FILE_ATTRIBUTES\nconstexpr DWORD INVALID_FILE_ATTRIBUTES = ((DWORD)-1);\n#endif\n</code></pre>\n\n<h2>Indentation</h2>\n\n<p>It would be better not to mix spaces with tabs when indenting. Many programmers use 4 spaces for indenting, by default a tab is 8 spaces. This can lead to inconsistent indentation as demonstrated in the function <code>bool DirectoryExists(const std::string&amp; path)</code> in the question. An IDE such as Visual Studio allows you to set the number of spaces used in a tab to prevent this problem, where <code>notepad</code> does not do this.</p>\n\n<h2>Replace</h2>\n\n<p>It's not clear that the function <code>std::string replace (const std::string&amp; path)</code> since windows understand both the forward and backward slash in file specifications.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:47:38.003", "Id": "474252", "Score": "0", "body": "Thanks for your time and notes taken for all points, just 2 clarifications. std::replace is working with the current file without other includes, I am using Digital Mars as compiler (the same reason I use notepad) to learn about compilers, a task not easy with a 2 GB one like LLVM or MSVC." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:57:59.673", "Id": "474253", "Score": "0", "body": "As for the replace function, at least in my case, giving a path like c:\\Windows\\system32 doesn't work, either replace '\\' by '/' or the path should be like C:\\\\Windows\\\\System32, but is it professional to big software companies like MS, Oracle, Google...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:10:29.027", "Id": "474261", "Score": "1", "body": "If you're learning about compilers a good source might be the Dragon book https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools. Also look into parser generators such as YACC and Bison. Parser generators generally use a push down automata (state machine coupled with a stack)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:32:25.390", "Id": "241663", "ParentId": "241622", "Score": "1" } } ]
{ "AcceptedAnswerId": "241663", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T16:09:03.533", "Id": "241622", "Score": "3", "Tags": [ "c++", "winapi" ], "Title": "Check mp4 integrity in c++" }
241622
<p>I've been trying to make an <code>std::vector</code> of boolean values and I got fed up with the specialization. To get around this, I made a wrapper class around <code>bool</code> and a testsuite to make sure that it compiles and works as expected.</p> <p>It seems to do everything <code>std::vector&lt;bool&gt;</code> does, except, of course, <code>flip()</code>. It also satisfies the container rules so that you can take a reference or a pointer to an element.</p> <p>On to the code:</p> <p><code>vector_safe_bool.hpp</code>:</p> <pre><code>#pragma once // A wrapper class around bool that can be used in std::vector without breaking container rules class vector_safe_bool { bool value; public: vector_safe_bool() = default; vector_safe_bool(bool b) : value{b} {} bool *operator&amp;() noexcept { return &amp;value; } const bool *operator&amp;() const noexcept { return &amp;value; } operator const bool &amp;() const noexcept { return value; } operator bool &amp;() noexcept { return value; } }; </code></pre> <p><code>vsb_test.cpp</code>:</p> <pre><code>#include "vector_safe_bool.hpp" #include &lt;iostream&gt; #include &lt;vector&gt; #if USE_VECTOR_SAFE_BOOL using which_bool = vector_safe_bool; #define TEST_CONTAINER true #else using which_bool = bool; #define TEST_CONTAINER false #endif int main() { // The commented lines work for neither bool nor vector_safe_bool const which_bool t1 = true; // bool *t1p = &amp;t1; const bool *t1cp = &amp;t1; // bool &amp;t1r = t1; const bool &amp;t1cr = t1; // bool &amp;&amp;t1rr = t1; which_bool t2 = true; bool *t2p = &amp;t2; const bool *t2cp = &amp;t2; bool &amp;t2r = t2; const bool &amp;t2cr = t2; // bool &amp;&amp;t2rr = t2; t2++; ++t2; std::vector&lt;which_bool&gt; bv(10, true); #if TEST_CONTAINER for(auto &amp;b : bv) ; #endif for(const auto &amp;b : bv) ; for(auto &amp;&amp;b : bv) ; const std::vector&lt;which_bool&gt; cbv(10, true); #if TEST_CONTAINER for(auto &amp;cb : cbv) ; #endif for(const auto &amp;cb : cbv) ; for(auto &amp;&amp;cb : cbv) ; } </code></pre> <p><code>GNUmakefile</code>:</p> <pre><code>CXX = g++ CXXFLAGS = -Wall -Wextra -Wno-unused-variable -Wno-deprecated -pedantic -std=c++11 all: check test: vsb_test.cpp vector_safe_bool.hpp $(CXX) $(CXXFLAGS) -I. vsb_test.cpp -DUSE_VECTOR_SAFE_BOOL @rm -f a.out $(CXX) $(CXXFLAGS) -I. vsb_test.cpp @rm -f a.out </code></pre> <p>What I'm looking for:</p> <ul> <li>Can I make this more idiomatic? How?</li> <li>Can I make use of features from newer versions of C++?</li> <li>Did I forget any obscure corner-cases?</li> <li>Is there anything that I can make better in the GNUmakefile?</li> <li>Are there any other ways that I could improve this?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T03:27:15.927", "Id": "474224", "Score": "0", "body": "We can make the wrapper as close to `bool` as possible, but there is some limitations (e.g., `decltype`, template parameter deduction, etc.). In the end, there is no way to make `bool` itself usable with `std::vector`, so unfortunately sometimes libraries have to reinvent `std::vector` :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T13:03:10.693", "Id": "474246", "Score": "0", "body": "@L.F. It works for my purposes, but do you see anything that could make it closer to `bool`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T20:20:47.763", "Id": "241629", "Score": "4", "Tags": [ "c++", "c++11", "vectors", "makefile", "make" ], "Title": "std::vector<bool> workaround in C++" }
241629
<h1>Background</h1> <p>I've recently made a contribution to an open source project, <code>ledger-autosync</code>, which is a CLI "to pull down transactions from your bank and create ledger transactions for them".</p> <p>Most of the functions are fairly stand alone which means passing configuration values from the argument parser to the function where it is actually used can be very tedious. For example, in <a href="https://github.com/egh/ledger-autosync/pull/95" rel="nofollow noreferrer">the contribution I made</a>, of 62 lines added, about 55 or so were updating function calls and signatures to pass the new parameter along.</p> <p>I submitted <a href="https://github.com/egh/ledger-autosync/pull/100" rel="nofollow noreferrer">a pull request</a> to use a module to manage the configuration global which I think will simplify things and am seeking a review on the approach used.</p> <h1>My Solution</h1> <p>The approach is to use a <code>config</code> module as a namespace for command line argument values. Then functions that use argument values can access them as attributes of <code>config</code> instead of declaring them in their signature and needing them to be passed along.</p> <h1>My Concerns</h1> <p>I'm worried this global approach will cause issues in ways I can't foresee. One issue I already ran into was the need to update the test suite in order to clear all attributes of <code>config</code> between tests. </p> <p>I'm also worried this approach will make it unclear what command line arguments control a given function, which could make writing tests and understanding the code difficult.</p> <h1>The Code</h1> <p>Below is a working representation of the code. The project this is a part of is quite large and I'm not sure of another coherent way to present everything here. </p> <p><code>config.py</code></p> <pre class="lang-py prettyprint-override"><code># no content </code></pre> <p><code>cli.py</code></p> <pre class="lang-py prettyprint-override"><code>import argparse import datetime as dt import config def run(): parser = argparse.ArgumentParser() parser.add_argument("--date-format") args = parser.parse_args(namespace=config) print_transactions() def print_transactions(): transactions = [(dt.date(2020, 5, 1), 10), (dt.date(2020, 5, 2), 100)] for t in transactions: print(format_transaction(t)) def format_transaction(transaction): return f"{transaction[0]:{config.date_format}}:\t {transaction[1]}" if __name__ == "__main__": run() </code></pre> <p>Example usage: </p> <pre><code>python cli.py --date-format '%Y/%m/%d' </code></pre> <p>Example output:</p> <pre><code>2020/05/01: 10 2020/05/02: 100 </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T20:37:02.847", "Id": "241630", "Score": "2", "Tags": [ "python" ], "Title": "CLI Argument Value Management" }
241630
<p>After learning Javascript for quite some time, I began learning ReactJS and... I am confused with the proper design patterns.</p> <pre><code>import React, { useState } from 'react'; import ReactDOM from 'react-dom'; const Search = ({persons, filter}) =&gt; { const [name, setName] = useState(void 0); function search(event){ event.preventDefault(); filter(event.target.value.toLowerCase()); } return ( &lt;div&gt; &lt;h1&gt;Search&lt;/h1&gt; &lt;form onSubmit={search}&gt; &lt;input onChange={(event) =&gt; search(event)}/&gt; &lt;button type="submit"&gt;Search&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ) } const Persons = ({persons}) =&gt; { function renderPersons(){ const elements = []; persons.forEach(person =&gt; { if(person.show){ elements.push(&lt;li&gt;{person.name} -- his/her telephone number: {person.phone}&lt;/li&gt;); } }); return elements; } return( &lt;ul&gt; {renderPersons()} &lt;/ul&gt; ) } const App = () =&gt; { const [ persons, setPersons ] = useState([ { name: 'Arto Hellas', phone: '040-123456', show: true }, { name: 'Ada Lovelace', phone: '39-44-5323523', show: true }, { name: 'Dan Abramov', phone: '12-43-234345', show: true }, { name: 'Mary Poppendieck', phone: '39-23-6423122', show:true } ]); const [ formInfo, setNewFormInfo ] = useState({name: '', phone: ''}); function addPerson(event){ event.preventDefault(); let able = true; persons.forEach(person =&gt; { // checks if the person's name is already added if(person.name == formInfo.name) able = false; }); if(able) setPersons(persons.concat({name:formInfo.name, phone:formInfo.phone, show:true})); else alert(`${formInfo.name} is already added to the list!`); } function filter(nameToFilter){ if(nameToFilter === ''){ // if the search form is empty, then show everyone setPersons((prev) =&gt; prev.map(person =&gt; ({...person, show:true}))); } else{ const filtered = []; persons.forEach(person =&gt; { if(!person.name.toLowerCase().includes(nameToFilter)) filtered.push({...person, show:false}); else filtered.push({...person}); }); setPersons(filtered); } } return ( &lt;div&gt; &lt;Search persons={persons} filter={filter} /&gt; &lt;h2&gt;Phonebook&lt;/h2&gt; &lt;form onSubmit={addPerson}&gt; &lt;div&gt; name: &lt;input onChange={(event) =&gt; setNewFormInfo({name: event.target.value, phone: formInfo.phone})}/&gt; &lt;br/&gt; number: &lt;input onChange={(event) =&gt; setNewFormInfo({name: formInfo.name, phone: event.target.value})}/&gt; &lt;/div&gt; &lt;div&gt; &lt;button type="submit"&gt;add&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;h2&gt;Persons&lt;/h2&gt; &lt;Persons persons={persons} /&gt; &lt;/div&gt; ) } ReactDOM.render(&lt;App /&gt;, document.getElementById("root")) </code></pre> <p>It works, but I have a feeling the code really is poorly designed; the course I am taking doesn't focus on details and motivates you to self-learn a lot.</p> <p>I do have a specific question, though. Can I make <code>persons</code> a class? I just feel like in larger applications, each person would have methods and more variables; can I hold classes inside of React states instead of <code>dict</code>s?</p>
[]
[ { "body": "<p>There are a bunch of small improvements you can make.</p>\n\n<p>Since you aren't using <code>name</code> or <code>setName</code>, you can remove them and their <code>useState</code> call (consider a linter to warn on unused variables).</p>\n\n<p>You have <code>&lt;form onSubmit={search}&gt;</code>, but the <code>search</code> function does <code>filter(event.target.value.toLowerCase())</code>. Forms don't have <code>.value</code>s, so this will throw an error when the button is pressed. Also, the <code>search</code> function could be confused with the <code>Search</code> component - the difference is only in capitalization, which isn't enough. The button doesn't do anything otherwise, because searching occurs when the input's <code>change</code> event fires. You might consider removing the button completely - this way you can remove the <code>search</code> function and just call <code>filter</code>:</p>\n\n<pre><code>&lt;form&gt;\n &lt;input onChange={event =&gt; filter(event.target.value)} /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>In your code, eveywhere you return JSX at the bottom of a function, there's no trailing <code>;</code> after the final <code>)</code>. This can result in bugs if you ever decided to put the fragment into a variable instead of returning immediately, due to automatic semicolon insertion. Since you're using semicolons everywhere else, consider using them everywhere they're appropriate as well. (again, linting will help with this)</p>\n\n<p>Similarly to the <code>search</code> vs <code>Search</code> above, you also have a <code>persons</code> array and a <code>Persons</code> component. Maybe call the component <code>PersonsList</code> instead, since it creates a <code>&lt;ul&gt;</code>.</p>\n\n<p>Rather than using <code>forEach</code> and conditionally pushing to an array outside, it may be a better idea to construct the array directly by <code>filter</code>ing for elements which match, then <code>.map</code>ping to the individual <code>&lt;li&gt;</code>s. Higher-order functions are great:</p>\n\n<pre><code>const PersonsList = ({ persons }) =&gt; (\n &lt;ul&gt;\n {(\n persons\n .filter(person =&gt; person.show)\n .map(person =&gt; &lt;li&gt;{person.name} -- his/her telephone number: {person.phone}&lt;/li&gt;)\n )}\n &lt;/ul&gt;\n);\n</code></pre>\n\n<p>In <code>addPerson</code>, if you want to check whether any items in an array match a condition, rather than setting a flag outside and conditionally reassigning it while iterating over an array, it's more appropriate to use <code>Array.prototype.some</code>:</p>\n\n<pre><code>const alreadyExists = persons.some(person =&gt; person.name === name);\n</code></pre>\n\n<p>If you <em>were</em> to use your original code, at least <a href=\"https://stackoverflow.com/a/23465314\">use strict equality</a> with <code>===</code> instead of loose equality <code>==</code>.</p>\n\n<p>Also in <code>addPerson</code>, using <code>window.alert</code> is <a href=\"https://ux.stackexchange.com/questions/4518/should-alert-boxes-be-avoided-at-any-cost\">almost never a good choice</a>. It's user-unfriendly, since it completely blocks them from using the rest of the page. It also prevents any other Javascript from executing until the alert is dismissed, which would be a problem if there were anything on the page other than this phone number component. Inform the user of the problem some other way. A very simple tweak would be to add <code>errorMessage</code> to the form's state:</p>\n\n<pre><code>if (!alreadyExists)\n setPersons(persons.concat({ name, phone, show: true }));\nelse\n setNewFormInfo({ name, phone, errorMessage: `${name} is already added to the list!` });\n</code></pre>\n\n<p>and add to the form's JSX:</p>\n\n<pre><code>{(errorMessage &amp;&amp; &lt;div className=\"error\"&gt;{errorMessage}&lt;/div&gt;)}\n</code></pre>\n\n<p>In the <code>filter</code> function, there's no need to check if the input is empty - if it is, everything will be rendered anyway. Feel free to remove that part and make the code simpler.</p>\n\n<p>Also in <code>filter</code>, since you're creating a <code>filtered</code> array by iterating over each element of <code>persons</code> and pushing an element to <code>filtered</code>, using <code>.map</code> would be more appropriate than <code>forEach</code> / <code>if</code> / <code>push</code>:</p>\n\n<pre><code>function filter(nameToFilter) {\n const nameToFilterLower = nameToFilter.toLowerCase();\n setPersons(persons.map(person =&gt;\n ({\n ...person,\n show: person.name.toLowerCase().includes(nameToFilterLower),\n })\n ));\n}\n</code></pre>\n\n<p>If you run the development version, you'll see the warning:</p>\n\n<blockquote>\n <p>Warning: Each child in a list should have a unique \"key\" prop.</p>\n</blockquote>\n\n<p>Without such a prop, each element will have to be re-created each time. See <a href=\"https://stackoverflow.com/questions/34576332/warning-each-child-in-an-array-or-iterator-should-have-a-unique-key-prop-che\">here</a> for an in-depth explanation. Since you're only adding items to the list, easiest fix would be to add <code>&lt;li key={name}</code>.</p>\n\n<p>Putting all of the above together into a live Stack Snippet:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const { useState } = React;\n\nconst Search = ({ filter }) =&gt; {\n return (\n &lt;div&gt;\n &lt;h1&gt;Search&lt;/h1&gt;\n &lt;form&gt;\n &lt;input onChange={event =&gt; filter(event.target.value)} /&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n );\n};\n\nconst PersonsList = ({ persons }) =&gt; (\n &lt;ul&gt;\n {(\n persons\n .filter(person =&gt; person.show)\n .map(({ name, phone }) =&gt; &lt;li key={name} &gt;{name} -- his/her telephone number: {phone}&lt;/li&gt;)\n )}\n &lt;/ul&gt;\n);\n\nconst App = () =&gt; {\n const [persons, setPersons] = useState([\n { name: 'Arto Hellas', phone: '040-123456', show: true },\n { name: 'Ada Lovelace', phone: '39-44-5323523', show: true },\n { name: 'Dan Abramov', phone: '12-43-234345', show: true },\n { name: 'Mary Poppendieck', phone: '39-23-6423122', show: true }\n ]);\n\n const [{ name, phone, errorMessage = '' }, setNewFormInfo] = useState({ name: '', phone: '' });\n function addPerson(event) {\n event.preventDefault();\n\n const alreadyExists = persons.some(person =&gt; person.name === name);\n if (!alreadyExists)\n setPersons(persons.concat({ name, phone, show: true }));\n else\n setNewFormInfo({ name, phone, errorMessage: `${name} is already added to the list!` });\n }\n\n function filter(nameToFilter) {\n const nameToFilterLower = nameToFilter.toLowerCase();\n setPersons(persons.map(person =&gt;\n ({\n ...person,\n show: person.name.toLowerCase().includes(nameToFilterLower),\n })\n ));\n }\n\n return (\n &lt;div&gt;\n &lt;Search filter={filter} /&gt;\n &lt;h2&gt;Phonebook&lt;/h2&gt;\n &lt;form onSubmit={addPerson}&gt;\n &lt;div&gt;\n name: &lt;input onChange={event =&gt; setNewFormInfo({ name: event.target.value, phone })} /&gt;\n &lt;br /&gt;\n number: &lt;input onChange={event =&gt; setNewFormInfo({ name, phone: event.target.value })} /&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;button type=\"submit\"&gt;add&lt;/button&gt;\n &lt;/div&gt;\n {(errorMessage &amp;&amp; &lt;div className=\"error\"&gt;{errorMessage}&lt;/div&gt;)}\n &lt;/form&gt;\n &lt;h2&gt;Persons&lt;/h2&gt;\n &lt;PersonsList persons={persons} /&gt;\n &lt;/div&gt;\n );\n};\nReactDOM.render(&lt;App /&gt;, document.getElementById(\"root\"))</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.error {\n color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script crossorigin src=\"https://unpkg.com/react@16/umd/react.development.js\"&gt;&lt;/script&gt;\n&lt;script crossorigin src=\"https://unpkg.com/react-dom@16/umd/react-dom.development.js\"&gt;&lt;/script&gt;\n&lt;div id=\"root\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<blockquote>\n <p>Can I make persons a class?</p>\n</blockquote>\n\n<p>You <em>can</em>, but React <a href=\"https://reactjs.org/docs/hooks-faq.html#do-i-need-to-rewrite-all-my-class-components\" rel=\"nofollow noreferrer\">highly recommends</a> using hooks (and stateless functional components) when possible. They're easier to make sense of too, IMO.</p>\n\n<blockquote>\n <p>in larger applications, each person would have methods and more variables</p>\n</blockquote>\n\n<p>If you want to encapsulate common functionality for <code>Persons</code>, you can easily do so by putting it into its own file and defining those functions you need inside that file (or by importing them), eg:</p>\n\n<pre><code>// example helper function\nconst transformName = name =&gt; name.toUpperCase();\nexport const PersonsList = ({persons}) =&gt; \n // ...\n &lt;li key={name} &gt;{transformName(name)} -- his/her telephone number: {phone}&lt;/li&gt;\n // ...\n</code></pre>\n\n<p>There are a <a href=\"https://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes\" rel=\"nofollow noreferrer\">few rare cases</a> for which classes must still be used, but none of those circumstances are relevant here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T03:30:55.060", "Id": "241637", "ParentId": "241631", "Score": "2" } } ]
{ "AcceptedAnswerId": "241637", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-02T21:43:36.253", "Id": "241631", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "A simple phonebook in React" }
241631
<p>I am coding a command line based game with 1 player and 2 monsters.</p> <p>Monster attacks player at specified intervals and player takes input from standard input to attack specific monster.</p> <ol> <li><p>I would like your feedback on how I can improve class relationships.</p></li> <li><p>I feel there is strong cohesiveness between monster and player classes. How can we reduce it?</p></li> <li><p>Considering this is a multithreaded application, if I make health parameter as atomic it starts complaining that particular Copy Constructor is implicitly deleted. I understand atomic cannot be copied, so should we write copy and move ctor explicitly?</p></li> <li><p>Same is the case if <code>std::thread</code> is a member variable.</p></li> </ol> <p>Character.h</p> <pre><code>#ifndef CHARACTER_H_ #define CHARACTER_H_ #include &lt;string&gt; class Character { std::string name_; int health_; int attackPower_; public: Character(const std::string&amp; name, int health, int attackPower); virtual ~Character(); virtual void attackOpponent(Character&amp; opponent); bool isAlive() const; const std::string&amp; getName() const; int getHealth() const; }; #endif //CHARACTER_H_ </code></pre> <p>Character.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;mutex&gt; #include "Character.h" std::mutex mtx; Character::Character(const std::string&amp; name, int health, int attackPower) : name_ {name} , health_ {health} , attackPower_ {attackPower} { } Character::~Character() { } void Character::attackOpponent(Character&amp; opponent) { std::lock_guard&lt;std::mutex&gt; lock(mtx); opponent.health_ = std::max(0, opponent.health_ - attackPower_); std::cout &lt;&lt; name_ &lt;&lt; " hits " &lt;&lt; opponent.getName() &lt;&lt; ". "; std::cout &lt;&lt; opponent.getName() &lt;&lt; " health is: " &lt;&lt; opponent.getHealth() &lt;&lt; std::endl; } bool Character::isAlive() const { return health_ &gt; 0; } const std::string&amp; Character::getName() const { return name_; } int Character::getHealth() const { return health_; } </code></pre> <p>Enemy.h</p> <pre><code>#ifndef ENEMY_H_ #define ENEMY_H_ #include "Character.h" class Enemy : public Character { int interval_; public: Enemy(const std::string&amp; name, int initialHealth, int attackPower, int interval); ~Enemy(); virtual void attackOpponent(Character&amp; opponent) override; }; #endif //ENEMY_H_ </code></pre> <p>Enemy.cpp</p> <pre><code>#include &lt;thread&gt; #include &lt;chrono&gt; #include "Enemy.h" Enemy::Enemy(const std::string&amp; name, int initialHealth, int attackPower, int interval) : Character(name, initialHealth, attackPower) , interval_ {interval} { } Enemy::~Enemy() { } void Enemy::attackOpponent(Character&amp; opponent) { std::thread t([&amp;]() { while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(interval_)); if (isAlive() &amp;&amp; opponent.isAlive()) { Character::attackOpponent(opponent); } else { break; } } }); t.detach(); } </code></pre> <p>Dragon.h</p> <pre><code>#ifndef DRAGON_H_ #define DRAGON_H_ #include "Enemy.h" class Dragon : public Enemy { public: Dragon(int initialHealth, int attackPower, int interval); ~Dragon(); }; #endif //DRAGON_H_ </code></pre> <p>Dragon.cpp</p> <pre><code>#include "Dragon.h" Dragon::Dragon(int initialHealth, int attackPower, int interval) : Enemy("Dragon", initialHealth, attackPower, interval) { } Dragon::~Dragon() { } </code></pre> <p>Player.h</p> <pre><code>#ifndef PLAYER_H_ #define PLAYER_H_ #include &lt;string&gt; #include "Character.h" class Player : public Character { public: Player(int initialHealth, int attackPower); ~Player(); }; #endif //PLAYER_H_ </code></pre> <p>Player.cpp</p> <pre><code>#include "Player.h" Player::Player(int initialHealth, int attackPower) : Character("Player", initialHealth, attackPower) { } Player::~Player() { } </code></pre> <p>Game.h</p> <pre><code>#ifndef GAME_H_ #define GAME_H_ #include &lt;vector&gt; #include &lt;string&gt; #include &lt;cassert&gt; #include &lt;algorithm&gt; #include "Enemy.h" #include "Character.h" class Character; class Enemy; class Game { std::vector&lt;Character&gt; players_; std::vector&lt;Enemy&gt; enemies_; public: Game(); ~Game(); void init(); void play(); void startEnemyAttack(); void printScoreCard(); inline Character&amp; getEnemyByName(const std::string&amp; name) { auto it = std::find_if(std::begin(enemies_), std::end(enemies_), [&amp;](auto&amp; o) { return !o.getName().compare(name);}); assert(it != std::end(enemies_) &amp;&amp; "Enemy with matching name not found"); return *it; } std::vector&lt;Character&gt;&amp; getPlayers(); std::vector&lt;Enemy&gt;&amp; getEnemies(); }; #endif //GAME_H_ </code></pre> <p>Game.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;cassert&gt; #include "Game.h" #include "Orc.h" #include "Player.h" #include "Dragon.h" Game::Game() { } Game::~Game() { } void Game::init() { players_.push_back(Player(40, 2)); enemies_.push_back(Orc(7, 1, 1300)); enemies_.push_back(Dragon(20, 3, 2600)); } void Game::play() { startEnemyAttack(); auto player = std::begin(players_); while ((player != std::end(players_)) &amp;&amp; player-&gt;isAlive()) { if (std::none_of(std::begin(enemies_), std::end(enemies_), [](const auto&amp; o){ return o.isAlive(); })) { std::cout &lt;&lt; "Player wins" &lt;&lt; std::endl; break; } std::cout &lt;&lt; "Attack enemy:\n1. Orc\n2. Dragon" &lt;&lt; std::endl; std::cout &lt;&lt; "Please choose enemy to be attacked: "; int choice = 0; std::cin &gt;&gt; choice; switch (choice) { case 1: player-&gt;attackOpponent(getEnemyByName("Orc")); break; case 2: player-&gt;attackOpponent(getEnemyByName("Dragon")); break; default: std::cout &lt;&lt; "Wrong option selecetd." &lt;&lt; std::endl; } } if ((player != std::end(players_)) &amp;&amp; !player-&gt;isAlive()) { std::cout &lt;&lt; "Player lost" &lt;&lt; std::endl; } } void Game::startEnemyAttack() { auto player = std::begin(players_); if (player == std::end(players_)) { return; } for (auto&amp; e : enemies_) { e.attackOpponent(*player); } } std::vector&lt;Character&gt;&amp; Game::getPlayers() { return players_; } std::vector&lt;Enemy&gt;&amp; Game::getEnemies() { return enemies_; } void Game::printScoreCard() { for (auto&amp; player : players_) { std::cout &lt;&lt; player.getName() &lt;&lt; " score is: " &lt;&lt; player.getHealth() &lt;&lt; std::endl; } for (auto&amp; enemy : enemies_) { std::cout &lt;&lt; enemy.getName() &lt;&lt; " score is: " &lt;&lt; enemy.getHealth() &lt;&lt; std::endl; } } </code></pre>
[]
[ { "body": "<p>Some observations:</p>\n\n<blockquote>\n<pre><code>Character::Character(const std::string&amp; name, int health, int attackPower)\n : name_ {name}\n , health_ {health}\n , attackPower_ {attackPower}\n{\n}\n</code></pre>\n</blockquote>\n\n<p>Consider using <code>std::string name</code> to enable move semantics:</p>\n\n<pre><code>Character::Character(std::string name, int health, int attackPower)\n : name_ {std::move(name)}\n , health_ {health}\n , attackPower_ {attackPower}\n{\n}\n</code></pre>\n\n<blockquote>\n<pre><code>Character::~Character()\n{\n}\n</code></pre>\n</blockquote>\n\n<p>This should really be defined directly in-class.</p>\n\n<blockquote>\n<pre><code>const std::string&amp; Character::getName() const\n{\n return name_;\n}\n\nint Character::getHealth() const\n{\n return health_;\n}\n</code></pre>\n</blockquote>\n\n<p>Just call them <code>name</code> and <code>health</code>.</p>\n\n<blockquote>\n<pre><code>Enemy::~Enemy()\n{\n}\n</code></pre>\n</blockquote>\n\n<p>You don't need to explicitly override virtual destructors in derived classes.</p>\n\n<blockquote>\n<pre><code>void Enemy::attackOpponent(Character&amp; opponent)\n{\n std::thread t([&amp;]() {\n while (true)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(interval_));\n if (isAlive() &amp;&amp; opponent.isAlive())\n {\n Character::attackOpponent(opponent);\n }\n else\n {\n break;\n } \n }\n });\n t.detach();\n}\n</code></pre>\n</blockquote>\n\n<p>You're introducing data race here. There is no synchronization mechanism.</p>\n\n<p>You are completely changing the semantics of <code>Character::attackOpponent</code> here, so overriding is inappropriate. Leave <code>attackOpponent</code> as-is and rename this to something like <code>start_attack</code>. <code>interval</code> should be stored as a <code>std::chrono::duration</code> to begin with, for clarity. The <code>detach</code> is also prone to lifetime problems.</p>\n\n<blockquote>\n<pre><code>class Dragon : public Enemy\n{\npublic:\n Dragon(int initialHealth, int attackPower, int interval);\n ~Dragon();\n};\n\nclass Player : public Character\n{\npublic:\n Player(int initialHealth, int attackPower);\n ~Player();\n};\n</code></pre>\n</blockquote>\n\n<p>Are these classes really necessary?</p>\n\n<blockquote>\n<pre><code>class Character;\nclass Enemy;\n</code></pre>\n</blockquote>\n\n<p>These forward declaration are redundant because you have already included the definitions of the classes.</p>\n\n<blockquote>\n<pre><code>inline Character&amp; getEnemyByName(const std::string&amp; name)\n{\n auto it = std::find_if(std::begin(enemies_), std::end(enemies_), \n [&amp;](auto&amp; o) { return !o.getName().compare(name);});\n\n assert(it != std::end(enemies_) &amp;&amp; \"Enemy with matching name not found\");\n\n return *it;\n}\n</code></pre>\n</blockquote>\n\n<p>In-class definitions are already inline. Missing <code>const</code>. Use the <code>==</code> operator instead of directly calling the <code>compare</code> function:</p>\n\n<pre><code>auto it = std::find_if(\n enemies_.begin(), enemies_.end(),\n [&amp;] (const auto&amp; o) {\n return o.getName() == name;\n }\n);\n</code></pre>\n\n<blockquote>\n<pre><code>Game::Game()\n{\n}\n\nGame::~Game()\n{\n}\n\nvoid Game::init()\n{\n players_.push_back(Player(40, 2));\n enemies_.push_back(Orc(7, 1, 1300));\n enemies_.push_back(Dragon(20, 3, 2600));\n}\n</code></pre>\n</blockquote>\n\n<p>Remove the destructor. The <code>init</code> function is probably what you should be doing in the constructor:</p>\n\n<pre><code>Game::Game()\n : players_{Player{40, 2}}\n , enemies_{Orc{7, 1, 1300}, Dragon{20, 3, 2600}}\n{\n}\n</code></pre>\n\n<blockquote>\n<pre><code>auto player = std::begin(players_);\nwhile ((player != std::end(players_)) &amp;&amp; player-&gt;isAlive())\n</code></pre>\n</blockquote>\n\n<p><code>player</code> doesn't change, so ...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T13:37:14.440", "Id": "474933", "Score": "0", "body": "I understand Dragon, Orc, Player classes are not necessary. I am having difficulty in providing synchronization. If I introduce start_attack function, it will take opponent object and invoke attack_opponent in Character class. I guess start_attack will be present in Character as well? How should I use mutex or any other exclusion technique on health of individual characters? When I join on threads it blocks until Dragon kills player or himself gets killed, so I used detach. Is there a way to redesign this and avoid detach?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T10:07:35.327", "Id": "241990", "ParentId": "241635", "Score": "2" } }, { "body": "<p>Here are some things that may help you improve your program. The other review gives some good suggestions about the code itself, so this review will mostly focus on fundamental design issues.</p>\n\n<h2>Think carefully about threads</h2>\n\n<p>How many threads are really needed here? At the moment, the program launches one thread per enemy which seems rather extravagant. I think it's more likely that all enemies could operate on a single thread. One way to do that would be to push enemy objects (or <code>std::shared_ptr</code>s to them) onto a <a href=\"https://en.cppreference.com/w/cpp/container/priority_queue\" rel=\"nofollow noreferrer\"><code>std::priority_queue</code></a> with their calculated deadline time as the ordering such that the shortest remaining duration is always at the front of the queue. Generically, this is called <a href=\"https://en.cppreference.com/w/cpp/container/priority_queue\" rel=\"nofollow noreferrer\"><em>Earliest Deadline First (EDF) scheduling</em></a>. </p>\n\n<h2>Think carefully about classes</h2>\n\n<p>At the moment, there is a base <code>Character</code> class. Then a <code>Player</code> class that derives from that, and also an <code>Enemy</code> class which is further derived as <code>Orc</code> and <code>Dragon</code> classes. However, there really isn't anything special about any of them in that they operate 99% the same way. I'd suggest instead that you have one underlying <code>Character</code> and then derive a computer-controlled character from that. They could be either enemies or players. Differentiate them via data members rather than by class types. It will lead to a much cleaner design and better flexibility as well.</p>\n\n<h2>Think of the user</h2>\n\n<p>The code somewhat optimistically contains a <code>std::vector&lt;Character&gt;</code> (emphasizing that the <code>Player</code> object is probably useless as mentioned above) but how will multiple players actually play? Do you anticipate having five human players sharing a single keyboard? The answer to this is important because it helps to determine how threading might be done. If the answer is that there's really only one human-controlled player, then it's quite simple. However, if there are really intended to be more than one player sharing the keyboard, you will almost certainly need to use a mechanism other than <code>std::cin &gt;&gt; choice</code> to get input.</p>\n\n<h2>Avoid <em>object slicing</em></h2>\n\n<p>Right now, the code contains a <code>std::vector&lt;Enemy&gt;</code>. However, it is populated with further derived <code>Dragon</code> and <code>Orc</code> classes. In this case, as mentioned immediately above, the classes are functionally identical so it doesn't cause a problem but if the classes were somehow different, we could easily encounter all of the <a href=\"https://en.wikipedia.org/wiki/Object_slicing\" rel=\"nofollow noreferrer\">problems of object slicing</a>. See <a href=\"https://codereview.stackexchange.com/questions/56363/casting-base-to-derived-class-according-to-a-type-flag/56380#56380\">this answer</a> for how to use polymorphism and <code>std::unique_ptr</code> to preserve derived object behavior.</p>\n\n<h2>A worked example</h2>\n\n<p>See <a href=\"https://codereview.stackexchange.com/questions/243640/multithreaded-console-based-monster-battle-with-earliest-deadline-first-schedule\">Multithreaded console-based monster battle with earliest-deadline-first scheduler</a> for a worked example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T18:15:38.360", "Id": "243570", "ParentId": "241635", "Score": "2" } }, { "body": "<p>I'm not that great with threads, parallel programming so I won't comment about them... However, as for design decisions; I've taken your code and wrote my own version. I wouldn't say that the code that I'm about to present to you as an example is 100% bug proof. It does currently run and compile producing some interesting results! This has more to do with class hierarchies, the relationships between them, and their differences. I used a CRTP structure. I gave the Character classes the ability to assign function pointers for <code>attack</code> and <code>defending</code> which can be created by the user to be able to customize how they want a specific character or enemy type to perform an attack or to defend. I did not program any &quot;game logic&quot; but I have randomly generated a player where the user can choose between 3 types (no need to inherit here from the player class), and to randomly generate 3 different kinds of enemies (which are inherited)... Here's my version of the code that you can use for a reference and build off of. As for writing the game logic (that's for you to build and design), as for threading and parallel programming, it's beyond what I can explain. I can write some code that does it, but explaining it is not my strong suit! The code is quite long so I split it into 2 files due to some of the overloaded operators that I had to write for easier printing. Make sure to read the comments in the code too... it shows where I had made some design decisions, and where I modified the input values.</p>\n<p><strong>main.cpp</strong></p>\n<pre><code>#include &quot;Game.h&quot;\n\nint main() {\n try {\n Game game; \n game.run(); \n }\n catch (const std::exception&amp; e) {\n std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>Here's a potential output since the number of enemies is randomly generated...\n<strong>Output</strong></p>\n<pre><code>Welcome to Dungeon Raid!\nChoose your character type\n1 - Human:\n2 - Dwarven:\n3 - Elven:\n3\n\nMain Player Info:\nElven\nlevel:45\nhealth: 5493.489746\nattack: 919.298096\ndefense: 970.807129\nresponse: 91.92981\ndelay: 97.08071\nrecover: 746.64215\n\nOrc_000\nlevel:71\nhealth: 9015.84277\nattack: 2291.32764\ndefense: 2364.90454\nresponse: 229.13277\ndelay: 236.49046\nrecover: 1225.37927\n\nOrc_001\nlevel:58\nhealth: 7145.38623\nattack: 1581.78455\ndefense: 1630.08899\nresponse: 158.17845\ndelay: 163.00890\nrecover: 971.15802\n\nOrc_002\nlevel:36\nhealth: 5356.60059\nattack: 723.04858\ndefense: 653.49048\nresponse: 72.30486\ndelay: 65.34905\nrecover: 728.03699\n\nTroll_000\nlevel:29\nhealth: 4248.76318\nattack: 458.06143\ndefense: 453.84021\nresponse: 45.80614\ndelay: 45.38402\nrecover: 577.46637\n\nTroll_001\nlevel:92\nhealth: 13566.97852\nattack: 4404.49219\ndefense: 4765.45508\nresponse: 440.44922\ndelay: 476.54550\nrecover: 1843.94226\n\nOrc_003\nlevel:74\nhealth: 9432.72852\nattack: 2752.44165\ndefense: 2504.81201\nresponse: 275.24417\ndelay: 250.48120\nrecover: 1282.03979\n\nOrc_004\nlevel:29\nhealth: 4301.33301\nattack: 426.52374\ndefense: 492.74667\nresponse: 42.65237\ndelay: 49.27467\nrecover: 584.61139\n\nTroll_002\nlevel:100\nhealth: 14677.85352\nattack: 5369.20947\ndefense: 5856.85938\nresponse: 536.92096\ndelay: 585.68597\nrecover: 1994.92578\n\nTroll_003\nlevel:47\nhealth: 6805.82422\nattack: 1253.68689\ndefense: 1255.42249\nresponse: 125.36869\ndelay: 125.54225\nrecover: 925.00677\n</code></pre>\n<p>...and now for the actual classes to make it all work.</p>\n<p><strong>Game.h</strong></p>\n<pre><code>#pragma once\n\n// error handling\n#include &lt;exception&gt;\n\n// numerics, algorithms, properties, limits\n#include &lt;algorithm&gt;\n#include &lt;cstdint&gt;\n#include &lt;limits&gt;\n#include &lt;numeric&gt;\n#include &lt;random&gt;\n#include &lt;type_traits&gt;\n\n// string and stream libraries\n#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n\n// containers\n#include &lt;array&gt;\n//#include &lt;vector&gt;\n#include &lt;concurrent_vector.h&gt;\n#include &lt;concurrent_priority_queue.h&gt;\n\n\n// memory, threads, etc.\n#include &lt;memory&gt;\n#include &lt;mutex&gt;\n#include &lt;thread&gt;\n\n// When adding a new type: must update operators\nenum class PlayerType {\n HUMAN = 1,\n DWARVEN,\n ELVEN\n};\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, PlayerType&amp; type);\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; in, const PlayerType&amp; type);\n\n// When adding a new type: must update operators\nenum class EnemyType {\n GOBLIN = 1,\n ORC,\n TROLL\n};\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, EnemyType&amp; type);\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const EnemyType&amp; type);\n\nstruct CharacterInfo {\n std::uint32_t level_; \n float health_; \n float attack_power_; \n float defense_; \n\n float time_response_; // range [0,1] // same as speed or how fast they can attack\n float time_delay_; // range [0,1] // time delay before next attack\n float recovery_rate_; // range [0,1] // how fast they can recover, regain health, etc...\n\n CharacterInfo();\n CharacterInfo(std::uint32_t level, float health, float attackPower, float defense,\n float timeResponse, float timeDelay, float recoverRate);\n \n CharacterInfo(const CharacterInfo&amp; other);\n CharacterInfo&amp; operator=(const CharacterInfo&amp; other);\n\n};\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, CharacterInfo&amp; info);\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const CharacterInfo&amp; info);\n\nclass Character;\ntypedef float(*AttackFunc)(Character* attacker, Character* defender, float time_response);\ntypedef void(*DefendOrBlockFunc)(Character* defender, Character* attacker, float time_response);\n\ntemplate&lt;class T&gt;\nclass EntityID {\nprotected:\n explicit EntityID(std::string&amp; id) {\n static int i = 0;\n std::stringstream strValue;\n strValue &lt;&lt; std::setw(3) &lt;&lt; std::setfill('0') &lt;&lt; std::to_string(i++);\n id.append(&quot;_&quot; + strValue.str());\n }\n virtual ~EntityID() = default;\n};\n\nclass Character {\nprotected:\n std::string id_ = &quot;&quot;;\n AttackFunc attack_;\n CharacterInfo info_;\n DefendOrBlockFunc defend_;\n\n explicit Character(CharacterInfo&amp; info, const std::string&amp; id = &quot;&quot;)\n : info_{ info }, id_{std::move(id)} {}\n\npublic:\n virtual ~Character() = default;\n Character* operator()() { return this; }\n CharacterInfo* info() { return &amp;info_; }\n\n std::string&amp; id() { return id_; }\n float health() const { return info_.health_; }\n float attackPower() const { return info_.attack_power_; }\n float defense() const { return info_.defense_; }\n float response() const { return info_.time_response_; }\n float delay() const { return info_.time_delay_; }\n float recovery() const { return info_.recovery_rate_; }\n\n void assignAttack(AttackFunc func) { attack_ = func; }\n void assignBlock(DefendOrBlockFunc func) { defend_ = func; }\n\n inline virtual void healthModifier(const Character&amp; other) {\n auto power = other.attackPower();\n this-&gt;info_.health_ -= (power - this-&gt;info_.defense_);\n }\n\n float attack(Character* defender, float time_response) { return attack_(this, defender, time_response); }\n void defend(Character* attacker, float time_response) { return defend_(this, attacker, time_response); }\n };\n\ntemplate&lt;typename Ty&gt;\nconst std::string nameOfCharacterType(Ty type) {\n std::stringstream name;\n name &lt;&lt; type;\n return name.str();\n}\n\nclass Player final : public Character, EntityID&lt;Player&gt; {\n PlayerType player_type_;\npublic:\n Player(CharacterInfo&amp; info, PlayerType type, const std::string&amp; name = &quot;Player&quot; )\n : Character(info, std::move(name)), EntityID(id()), player_type_{ type } \n {}\n virtual ~Player() = default;\n \n Player* operator()() { return this; }\n \n inline virtual void healthModifier(const Character&amp; other) override {\n // modify as desired... leave blank for default\n }\n \n PlayerType type() const { return player_type_; }\n};\n\nclass Enemy : public Character {\n EnemyType enemy_type_;\nprotected:\n Enemy(CharacterInfo&amp; info,EnemyType type, const std::string&amp; name = &quot;Enemy&quot;)\n : Character(info, std::move(name)), enemy_type_{ type } {}\n \npublic:\n virtual ~Enemy() = default;\n inline virtual void healthModifier(const Character&amp; other) override {\n // modify as desired... leave blank for default\n } \n Enemy* operator()() { return this; }\n EnemyType type() const { return enemy_type_; }\n};\n\nclass Goblin final : public Enemy, EntityID&lt;Goblin&gt; { // remove final if you want to derive from Goblin\npublic:\n Goblin(CharacterInfo&amp; info, EnemyType type, const std::string&amp; name = &quot;Goblin&quot;)\n : Enemy(info, type, std::move(name)), EntityID(id()) {}\n virtual ~Goblin() = default;\n Goblin* operator()() { return this; }\n virtual void healthModifier(const Character&amp; other) override {\n // modify as desired... leave blank for default\n }\n};\n\nclass Orc final : public Enemy, EntityID&lt;Orc&gt; { // remove final if you want to derive from Orc\npublic:\n Orc(CharacterInfo&amp; info, EnemyType type, const std::string&amp; name = &quot;Orc&quot;)\n : Enemy(info, type, std::move(name)), EntityID(id()) {}\n virtual ~Orc() = default;\n Orc* operator()() { return this; }\n virtual void healthModifier(const Character&amp; other) override {\n // modify as desired... leave blank for default\n }\n};\n\nclass Troll final : public Enemy, EntityID&lt;Troll&gt; { // remove final if you want to derive from Troll\npublic:\n Troll(CharacterInfo&amp; info, EnemyType type, const std::string&amp; name = &quot;Troll&quot;)\n : Enemy(info, type, std::move(name)), EntityID(id()) {}\n virtual ~Troll() = default;\n Troll* operator()() { return this; }\n virtual void healthModifier(const Character&amp; other) override {\n // modify as desired... leave blank for default\n }\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Player&amp; player);\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Orc&amp; orc);\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Troll&amp; troll);\n\n// define your attack and defense functions for the function pointers here! Or create a lambda within the initialize function.\n\nclass Game {\n std::unique_ptr&lt;Player&gt; player_;\n std::vector&lt;std::unique_ptr&lt;Enemy&gt;&gt; enemies_;\n\n std::random_device rd;\n std::mt19937 gen{ rd() };\n\npublic:\n Game() {\n initialize();\n }\n\n void initialize() {\n std::cout &lt;&lt; &quot;Welcome to Dungeon Raid!\\n&quot;;\n createPlayer();\n generateRandomEnemies();\n\n // here is where you would assign the attack and defence function pointers:\n // player_-&gt;assignAttack();\n // player_-&gt;assignBlock();\n\n /*for (auto&amp; e : enemies_) {\n e-&gt;assignAttack();\n e-&gt;assignBlock();\n }*/\n\n }\n\n void run() {\n // main loop, user input, game logic here\n \n // for testing purposes, let's just print out our player and enemy info as lists:\n std::cout &lt;&lt; &quot;\\nMain Player Info:\\n&quot; &lt;&lt; player_-&gt;type() &lt;&lt; '\\n' &lt;&lt; *player_-&gt;info() &lt;&lt; '\\n';\n\n for (auto&amp; e : enemies_) {\n std::cout &lt;&lt; e-&gt;id() &lt;&lt; '\\n' &lt;&lt; *e-&gt;info() &lt;&lt; std::endl;\n }\n\n }\n\nprivate:\n void createPlayer() {\n PlayerType type;\n CharacterInfo playerInfo;\n \n retrievePlayerInfo(type, playerInfo);\n this-&gt;player_.reset(new Player{ playerInfo, type, nameOfCharacterType(type) });\n }\n\n void showPlayerChoice(PlayerType&amp; type) {\n std::cout &lt;&lt; &quot;Choose your character type\\n&quot;;\n std::cout &lt;&lt; &quot;1 - Human:\\n&quot;\n &lt;&lt; &quot;2 - Dwarven:\\n&quot;\n &lt;&lt; &quot;3 - Elven:\\n&quot;;\n std::string str;\n std::getline(std::con, str);\n std::uint32_t val = std::stoi(str); // can improve this to fix invalid input types...\n type = static_cast&lt;PlayerType&gt;(val);\n }\n\n void retrievePlayerInfo(PlayerType&amp; type, CharacterInfo&amp; playerInfo) {\n bool properType = false;\n\n do {\n if (!properType)\n showPlayerChoice(type);\n\n switch (type) {\n case PlayerType::HUMAN: {\n playerInfo = generateRandomStats(); // CharacterInfo{ 1, 10, 4, 3, 0.7f, 0.5f, 0.4f };\n properType = true; break;\n }\n case PlayerType::DWARVEN: {\n playerInfo = generateRandomStats(); // CharacterInfo{ 1, 12, 4, 4, 0.5f, 0.3f, 0.6f };\n properType = true; break;\n }\n case PlayerType::ELVEN: {\n playerInfo = generateRandomStats(); // CharacterInfo{ 1, 9, 3, 3, 0.8f, 0.2f, 0.7f };\n properType = false; break;\n }\n default: {\n properType = false; break;\n }\n }\n } while (!properType);\n }\n\n void generateRandomEnemies() {\n std::uniform_int_distribution&lt;std::uint32_t&gt; enemyCountDist{ 5, 20 }; // 5 to 20 enemies\n std::uint32_t enemyCount = enemyCountDist(gen);\n enemies_.resize(enemyCount);\n\n std::uniform_int_distribution&lt;std::uint32_t&gt; enemyTypeDist{ 1, 3 }; // 1 = Goblin, 2 = Orc, 3 = Troll\n \n EnemyType type;\n CharacterInfo enemyInfo;\n for (unsigned i = 0; i &lt; enemyCount; i++) {\n type = static_cast&lt;EnemyType&gt;( enemyTypeDist(gen) );\n\n switch (type) {\n case EnemyType::GOBLIN: {\n enemyInfo = generateRandomStats(); // CharacterInfo{ 1, 5, 2, 3, 0.9f, 0.2f, 0.9f };\n this-&gt;enemies_[i].reset(new Goblin{ enemyInfo, type });\n }\n case EnemyType::ORC: {\n enemyInfo = generateRandomStats(); // CharacterInfo{ 1, 7, 5, 8, 0.3f, 0.4f, 0.6f };\n this-&gt;enemies_[i].reset(new Orc{ enemyInfo, type });\n break;\n }\n case EnemyType::TROLL: {\n enemyInfo = generateRandomStats(); // CharacterInfo{ 1, 14, 5, 8, 0.3f, 0.4f, 0.6f };\n this-&gt;enemies_[i].reset(new Troll{ enemyInfo, type });\n break;\n }\n } \n }\n }\n\n CharacterInfo generateRandomStats() {\n // Generate a Random level in the range of [1,20] for the player\n std::uniform_int_distribution&lt;std::uint32_t&gt; randomLevelDist(1, 100);\n std::uint32_t randomLevel = randomLevelDist(gen);\n\n // Character states will be based on the curve of the level\n // Generate Random Stats: Level 1 base health = 100\n // Health Range = ((Base Health * Multiplyer) + (Base Health * Level)) / BaseHealth \n const float baseHealth = 10.0f; \n auto baseMinMultiplyer = 1.2f;\n auto baseMaxMultiplyer = 1.5f;\n auto baseLevelHealth = (baseHealth * randomLevel); \n\n auto lowerRange = baseHealth * baseMinMultiplyer * baseLevelHealth;\n auto upperRange = baseHealth * baseMaxMultiplyer * baseLevelHealth;\n std::uniform_real_distribution&lt;float&gt; dist(lowerRange, upperRange);\n auto randomHealth = dist(gen);\n\n // Attack &amp; Defense Range = 50% of health \n auto healthPercentage = randomHealth * 0.5f;\n lowerRange /= randomLevel;\n upperRange /= randomLevel;\n \n std::uniform_real_distribution&lt;float&gt; randomAttackDefenceDist(healthPercentage / upperRange, healthPercentage / lowerRange); \n auto randomAttack = randomAttackDefenceDist(gen) * randomLevel;\n auto randomDefense = randomAttackDefenceDist(gen) * randomLevel;\n\n // Time Response and Delay is based off of attack and defense where recovery is based off of health\n auto randomResponse = randomAttack * 0.1f;\n auto randomDelay = randomDefense * 0.1f;\n auto randomRecovery = randomHealth * 0.271828f * 0.5f; // 0.271828 approximate e/10\n\n // Create our Info\n return CharacterInfo{ randomLevel, randomHealth, randomAttack, randomDefense, randomResponse, randomDelay, randomRecovery };\n }\n};\n</code></pre>\n<p><strong>Game.cpp</strong></p>\n<pre><code>#include &quot;Game.h&quot;\n\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, PlayerType&amp; type) {\n std::uint32_t val{ 0 };\n in &gt;&gt; val;\n type = static_cast&lt;PlayerType&gt;(val);\n return in;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const PlayerType&amp; type) {\n std::string str;\n switch (type) {\n case PlayerType::HUMAN:\n str = &quot;Human&quot;;\n break;\n case PlayerType::DWARVEN:\n str = &quot;Dwarven&quot;;\n break;\n case PlayerType::ELVEN:\n str = &quot;Elven&quot;;\n break;\n default:\n str = &quot;Unknown&quot;;\n break;\n }\n return out &lt;&lt; str;\n}\n\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, EnemyType&amp; type) {\n std::uint32_t val{ 0 };\n in &gt;&gt; val;\n type = static_cast&lt;EnemyType&gt;(type);\n return in;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const EnemyType&amp; type) {\n std::string str;\n switch (type) {\n case EnemyType::GOBLIN:\n str = &quot;Goblin&quot;;\n break;\n case EnemyType::ORC:\n str = &quot;Orc&quot;;\n break;\n case EnemyType::TROLL:\n str = &quot;Troll&quot;;\n break;\n default:\n str = &quot;Unknown&quot;;\n break;\n }\n return out;\n}\n\nCharacterInfo::CharacterInfo() : \n level_{ 0 },\n health_{ 0 },\n attack_power_{ 0 },\n defense_{ 0 },\n time_response_{ 0.0f },\n time_delay_{ 0.0f },\n recovery_rate_{ 0.0f }\n{}\n\nCharacterInfo::CharacterInfo( std::uint32_t level, float health, \n float attackPower, float defense, \n float timeResponse, float timeDelay, float recoveryRate) :\n level_{level},\n health_{health},\n attack_power_{attackPower},\n defense_{defense},\n time_response_{timeResponse},\n time_delay_{timeDelay},\n recovery_rate_{recoveryRate}\n{}\n\nCharacterInfo::CharacterInfo(const CharacterInfo&amp; other) {\n this-&gt;level_ = other.level_;\n this-&gt;health_ = other.health_;\n this-&gt;attack_power_ = other.attack_power_;\n this-&gt;defense_ = other.defense_;\n this-&gt;time_response_ = other.time_response_;\n this-&gt;time_delay_ = other.time_delay_;\n this-&gt;recovery_rate_ = other.recovery_rate_;\n}\n\nCharacterInfo&amp; CharacterInfo::operator=(const CharacterInfo&amp; other) {\n this-&gt;level_ = other.level_;\n this-&gt;health_ = other.health_;\n this-&gt;attack_power_ = other.attack_power_;\n this-&gt;defense_ = other.defense_;\n this-&gt;time_response_ = other.time_response_;\n this-&gt;time_delay_ = other.time_delay_;\n this-&gt;recovery_rate_ = other.recovery_rate_;\n return *this;\n}\n\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; in, CharacterInfo&amp; info) {\n in &gt;&gt; info.level_;\n in &gt;&gt; info.health_;\n in &gt;&gt; info.attack_power_;\n in &gt;&gt; info.defense_;\n in &gt;&gt; info.time_response_;\n in &gt;&gt; info.time_delay_;\n in &gt;&gt; info.recovery_rate_;\n return in;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const CharacterInfo&amp; info) { \n out &lt;&lt; &quot;level:&quot; &lt;&lt; info.level_ &lt;&lt; '\\n';\n out.setf(std::ios::floatfield, std::ios::fixed);\n out &lt;&lt; &quot;health: &quot; &lt;&lt; std::setw(3) &lt;&lt; std::setfill('0') &lt;&lt; info.health_ &lt;&lt; '\\n'\n &lt;&lt; &quot;attack: &quot; &lt;&lt; std::setw(3) &lt;&lt; std::setfill('0') &lt;&lt; info.attack_power_ &lt;&lt; '\\n'\n &lt;&lt; &quot;defense: &quot; &lt;&lt; std::setw(3) &lt;&lt; std::setfill('0') &lt;&lt; info.defense_ &lt;&lt; '\\n'\n &lt;&lt; &quot;response: &quot; &lt;&lt; std::setprecision(5) &lt;&lt; std::setfill('0') &lt;&lt; info.time_response_ &lt;&lt; '\\n'\n &lt;&lt; &quot;delay: &quot; &lt;&lt; std::setprecision(5) &lt;&lt; std::setfill('0') &lt;&lt; info.time_delay_ &lt;&lt; '\\n'\n &lt;&lt; &quot;recover: &quot; &lt;&lt; std::setprecision(5) &lt;&lt; std::setfill('0') &lt;&lt; info.recovery_rate_ &lt;&lt; std::endl;\n return out;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Player&amp; player) {\n out &lt;&lt; &quot;ID: &quot; &lt;&lt; player.id() &lt;&lt; '\\n'\n &lt;&lt; player.info() &lt;&lt; std::endl;\n return out;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Orc&amp; orc) {\n out &lt;&lt; &quot;ID: &quot; &lt;&lt; orc.id() &lt;&lt; '\\n'\n &lt;&lt; orc.info() &lt;&lt; std::endl;\n return out;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Troll&amp; troll) {\n out &lt;&lt; &quot;ID: &quot; &lt;&lt; troll.id() &lt;&lt; '\\n'\n &lt;&lt; troll.info() &lt;&lt; std::endl;\n return out;\n}\n</code></pre>\n<p>If you look at the generated output, you can see that <code>Goblin</code>, <code>Orc</code>, <code>Troll</code> are their own class, but through inheritance, they are all enemy objects and enemy objects are a form of a Character. Even the Player is a Character. However, <code>Character</code> and <code>Enemy</code> themselves are abstract types. The <code>CRTP</code> that is used helps in the aide of generating unique IDs for them in the form of an <code>std::string</code>. Every time a new <code>Orc</code> is generated the id value is incremented based on the number of orcs, but this doesn't affect the number id for the Trolls or Goblins, however, we can easily store all of these into a single vector. Using <code>unique_ptr</code>'s helps with cleaning up memory. Now it's just a matter of making sure that your threads and access to read/write within your containers are synchronized and concurrent. Intel has a nice threading library, you can just search for <code>tbb</code> as it's a part of their IDEs, but they do have an open-source - free version of the <code>tbb</code> library via <code>apache's</code> licenses for download. At the time of this post, here is their active link: <a href=\"https://software.intel.com/content/www/us/en/develop/tools/threading-building-blocks.html\" rel=\"nofollow noreferrer\">Intel:TBB</a>. This should be able to help you with your threading and parallel programming concerns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:05:30.353", "Id": "482795", "Score": "0", "body": "_\"I've taken your code and wrote my own version.\"_ I think you should post this answer as a new review instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:53:34.283", "Id": "482807", "Score": "0", "body": "@G. Sliepen I wasn't asking for it to be reviewed. It's not 100% without bugs, it can be optimized and improved for readability, it should be wrapped in a namespace, etc... I'm currently limited to C++17 since I don't have access to a C++20 compiler with its latest features. My intent is centered around the underlying CRTP structure that I used to illustrate my thought process in the design decisions. With C++20, a good 30% of this can be refactored and simplified. This wasn't meant to \"critique\" all of their concerns. It's specific to the coupling and decoupling of the related classes..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:59:45.167", "Id": "482808", "Score": "0", "body": "@G.Sliepen Basically I covered points `1` & `2` from the OP's concerns using my example as one way of resolving this issue! The Player and Enemy Type classes are related as in that they are all Characters, however, Player and Enemy are two distinct types... Now, as for a Troll, Golbin, Orc, Dragon, etc... they are each their own types, but they are all enemies. Now, I didn't implement one, but an NPC would be another type that would inherit from Character but would be separate from Player and Enemy or Monster types... The CRTP pattern helps with this shown through the designated IDs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:06:13.463", "Id": "482816", "Score": "1", "body": "Sure, it is a good way of showing an alternative way to implement OP's game. But this answer itself is worthy of review. I see some issues, like no input validation, that could be addressed, which would turn it into an even better answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:29:24.580", "Id": "482838", "Score": "0", "body": "@G.Sliepen True. I had worked on that for a few hours just to get the boilerplate framework functioning... I'm sure there are plenty of corners and edge-case issues... I don't think it would be something that I would invest a lot of time in. I do have other projects with a much higher priority... Who knows, maybe one day I might have it reviewed... but as for right now it has to take a back seat..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T11:55:20.990", "Id": "245746", "ParentId": "241635", "Score": "1" } } ]
{ "AcceptedAnswerId": "241990", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T01:03:58.870", "Id": "241635", "Score": "8", "Tags": [ "c++", "object-oriented", "c++11", "game", "multithreading" ], "Title": "Command line based game with players and monsters" }
241635
<p>I am new to Rust, began learning a few days ago. I have written a simple csv_sorter based off of one I had written for a class previously. Everything runs fine and I have gotten my expected results. I do not know all of the Rust conventions, and am unsure what I may be doing wrong, or what can be done differently.</p> <p>Would anyone be willing to review my code? Please point out any bad design, poor optimizations, or alternative ideas. (Note, I still want to follow the structure of file > struct > list > output <a href="https://github.com/HammerAPI/rustcode/tree/master/csv_sorter" rel="noreferrer">https://github.com/HammerAPI/rustcode/tree/master/csv_sorter</a></p> <pre><code>use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::process; // Person struct to hold relevant data #[derive(Debug)] struct Person { first_name: String, last_name: String, street: String, city: String, state: String, zip_code: String, } // Person constructor impl Person { fn new(first_name: String, last_name: String, street: String, city: String, state: String, zip_code: String) -&gt; Person { Person { first_name, last_name, street, city, state, zip_code, } } } /** * Processes command-line arguments * * # Description * This function processes the passed-in command line arguments and attempts * to open and create valid input/output files from the names given. * * # Arguments * * `args` - A string array of command-line arguments. * * # Returns * * A tuple of the input file and output file if they are found, else errors. */ fn arg_parser(args: &amp;[String]) -&gt; Result&lt;(File, File), &amp;'static str&gt; { // Exit if too many or too few arguments were passed if args.len() != 3 { return Err("Usage: 'cargo run [input file] [output file]"); } // Get the input file let input_file = match File::open(format!("{}{}", "src/", &amp;args[1])) { Err(why) =&gt; panic!("\ncouldn't open file: {}", why), Ok(file) =&gt; file, }; // Get the output file let output_file = match File::create(format!("{}{}", "src/", &amp;args[2])) { Err(why) =&gt; panic!("\ncouldn't create file: {}", why), Ok(file) =&gt; file, }; // Return both files as a tuple Ok((input_file, output_file)) } /** * Builds a list of Person structs * * # Description * This function reads the input file line by line and creates a Person * struct based on the line's contents. It then adds that struct to a vector * and repeats for every line in the file. The final vector contains every * Person struct read in from the file. * * # Arguments * * `input_file` - The input file to read from. * * # Returns * * A vector of type Person containing all Person structs from the file. */ fn build_person_vec(input_file: &amp;mut File) -&gt; Vec&lt;Person&gt; { let mut person_vec: Vec&lt;Person&gt; = Vec::new(); let reader = BufReader::new(input_file); for line in reader.lines() { let line = line.unwrap(); let data: Vec&lt;&amp;str&gt; = line.split(", ").collect(); let p = Person::new(String::from(data[0].trim()), String::from(data[1].trim()), String::from(data[2].trim()), String::from(data[3].trim()), String::from(data[4].trim()), String::from(data[5].trim())); person_vec.push(p); } person_vec } /** * Sorts the list of Person structs * * # Description * Sorts via Selection Sort. * * # Arguments * * `person_vec` - A vector containing Person structs. */ fn sort_person_vec(person_vec: &amp;mut Vec&lt;Person&gt;) { for i in 0..person_vec.len() { let mut lowest = i; for j in (i + 1)..person_vec.len() { // Temporary variables to hold first and last names let j_last = &amp;person_vec[j].last_name.to_lowercase(); let j_first = &amp;person_vec[j].first_name.to_lowercase(); let low_last = &amp;person_vec[lowest].last_name.to_lowercase(); let low_first = &amp;person_vec[lowest].first_name.to_lowercase(); // Swap by last name or first name if last names are equal if (j_last &lt; low_last) || (j_last == low_last &amp;&amp; j_first &lt; low_first){ lowest = j; } } person_vec.swap(lowest, i); } } /** * Writes data to the output file * * # Description * Writes all Person structs to the output file, catching errors if the file * is not available to be written to. * * # Arguments * * `person_vec` - A vector containing Person structs. * * `output_file` - The file to write to. */ fn write_to_file(person_vec: &amp;mut Vec&lt;Person&gt;, output_file: &amp;mut File) { for p in person_vec { // Format the peron's information as a string let info = format!("{}, {}, {}, {}, {}, {}\n", p.first_name, p.last_name, p.street, p.city, p.state, p.zip_code); // Write to output file match output_file.write_all(info.as_bytes()) { Err(why) =&gt; panic!("\ncouldn't write to file: {}", why), Ok(_) =&gt; (), } } } fn main() { let args: Vec&lt;String&gt; = env::args().collect(); // Get the input and output files let (mut input_file, mut output_file) = arg_parser(&amp;args).unwrap_or_else(|err| { println!("\nError: {}", err); process::exit(1); }); let mut person_vec = build_person_vec(&amp;mut input_file); sort_person_vec(&amp;mut person_vec); write_to_file(&amp;mut person_vec, &amp;mut output_file); }<span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:13:54.187", "Id": "474229", "Score": "0", "body": "Not worth an additional answer, but your comments on `struct Person` and `impl Person` are not doc-comments (use `///` for those), also the one on `impl Person` actually seems to apply only to `Person::new`, so should be moved there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:15:29.137", "Id": "474231", "Score": "0", "body": "Also, your block doc-comments aren't parsed correctly by VS Code/rust-analyzer. Not sure if it's a bug or if your formatting isn't valid." } ]
[ { "body": "<p>From my limited Rust knowledge: (I'm a beginner too; let's learn together)</p>\n\n<h1>Compilation</h1>\n\n<p>I had to add <code>use std::env</code> to compile the code. Is that a copy-paste error?</p>\n\n<h1>Formatting</h1>\n\n<p>Your code deviates from the official <a href=\"https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/guide.md\" rel=\"nofollow noreferrer\">Rust Style Guide</a> in a few aspects:</p>\n\n<ul>\n<li><p>Separate items and statements by either zero or one blank lines (i.e., one or two newlines). (<a href=\"https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/guide.md#blank-lines\" rel=\"nofollow noreferrer\">Blank lines</a>)</p></li>\n<li><p>Indentation of function parameters / arguments:</p>\n\n<pre><code>- fn new(first_name: String, last_name: String,\n- street: String, city: String, state: String,\n- zip_code: String) -&gt; Person {\n-\n+ fn new(\n+ first_name: String,\n+ last_name: String,\n+ street: String,\n+ city: String,\n+ state: String,\n+ zip_code: String,\n+ ) -&gt; Person {\n</code></pre>\n\n\n\n<pre><code>- let p = Person::new(String::from(data[0].trim()),\n- String::from(data[1].trim()),\n- String::from(data[2].trim()),\n- String::from(data[3].trim()),\n- String::from(data[4].trim()),\n- String::from(data[5].trim()));\n+ let p = Person::new(\n+ String::from(data[0].trim()),\n+ String::from(data[1].trim()),\n+ String::from(data[2].trim()),\n+ String::from(data[3].trim()),\n+ String::from(data[4].trim()),\n+ String::from(data[5].trim()),\n+ );\n</code></pre>\n\n\n\n<pre><code>- let info = format!(\"{}, {}, {}, {}, {}, {}\\n\",\n- p.first_name, p.last_name, p.street, p.city,\n- p.state, p.zip_code);\n+ let info = format!(\n+ \"{}, {}, {}, {}, {}, {}\\n\",\n+ p.first_name, p.last_name, p.street, p.city, p.state, p.zip_code\n+ );\n</code></pre></li>\n<li><p>Spacing before <code>{</code>:</p>\n\n<pre><code>- if (j_last &lt; low_last) || (j_last == low_last &amp;&amp; j_first &lt; low_first){\n+ if (j_last &lt; low_last) || (j_last == low_last &amp;&amp; j_first &lt; low_first) {\n</code></pre></li>\n</ul>\n\n<p>You can apply these formatting guidelines by running <code>rustfmt</code>. (I found these by using <code>rustfmt --check</code>, which prints a diff.)</p>\n\n<h1>Constructor</h1>\n\n<p>In my opinion, <code>Person::new</code> is unnecessary. This:</p>\n\n<pre><code>Person::new(a, b, c, d, e, f)\n</code></pre>\n\n<p>is not more readable than</p>\n\n<pre><code>Person {\n first_name: a,\n last_name: b,\n street: c,\n city: d,\n state: e,\n zip_code: f,\n}\n</code></pre>\n\n<h1><code>Result::expect</code></h1>\n\n<p>These <code>match</code> expressions:</p>\n\n<blockquote>\n<pre><code>// Get the input file\nlet input_file = match File::open(format!(\"{}{}\", \"src/\", &amp;args[1])) {\n Err(why) =&gt; panic!(\"\\ncouldn't open file: {}\", why),\n Ok(file) =&gt; file,\n};\n\n// Get the output file\nlet output_file = match File::create(format!(\"{}{}\", \"src/\", &amp;args[2])) {\n Err(why) =&gt; panic!(\"\\ncouldn't create file: {}\", why),\n Ok(file) =&gt; file,\n};\n</code></pre>\n</blockquote>\n\n<p>can be simplified with <a href=\"https://doc.rust-lang.org/std/result/enum.Result.html#method.expect\" rel=\"nofollow noreferrer\"><code>Result::expect</code></a>:</p>\n\n<pre><code>let input_file = File::open(format!(\"src/{}\", &amp;args[1])).expect(\"Couldn't open file\");\nlet output_file = File::create(format!(\"src/{}\", &amp;args[2])).expect(\"Couldn't create file\");\n</code></pre>\n\n<p>Similarly:</p>\n\n<blockquote>\n<pre><code>// Write to output file\nmatch output_file.write_all(info.as_bytes()) {\n Err(why) =&gt; panic!(\"\\ncouldn't write to file: {}\", why),\n Ok(_) =&gt; (),\n}\n</code></pre>\n</blockquote>\n\n<p>becomes</p>\n\n<pre><code>output_file\n .write_all(info.as_bytes())\n .expect(\"Couldn't write to file\");\n</code></pre>\n\n<p>Note that <code>expect</code> uses <code>fmt::Debug</code> to print the error information. If you want to use <code>fmt::Display</code> (as your original code does), you can use <code>unwrap_or_else</code> instead of <code>expect</code>, per <a href=\"https://codereview.stackexchange.com/questions/241636/rust-csv-sorter-code-lookover/241640#comment474227_241640\">comment</a>:</p>\n\n<pre><code>.unwrap_or_else(|err| panic!(\"Couldn't open file: {}\", err))\n</code></pre>\n\n<h1>Sorting</h1>\n\n<p>You can reinventing the wheel here:</p>\n\n<blockquote>\n<pre><code>fn sort_person_vec(person_vec: &amp;mut Vec&lt;Person&gt;) {\n for i in 0..person_vec.len() {\n let mut lowest = i;\n\n for j in (i + 1)..person_vec.len() {\n // Temporary variables to hold first and last names\n let j_last = &amp;person_vec[j].last_name.to_lowercase();\n let j_first = &amp;person_vec[j].first_name.to_lowercase();\n let low_last = &amp;person_vec[lowest].last_name.to_lowercase();\n let low_first = &amp;person_vec[lowest].first_name.to_lowercase();\n\n // Swap by last name or first name if last names are equal\n if (j_last &lt; low_last) || (j_last == low_last &amp;&amp; j_first &lt; low_first) {\n lowest = j;\n }\n }\n person_vec.swap(lowest, i);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The lexical comparison feature of tuples can be used here:</p>\n\n<pre><code>fn sort_person_vec(person_vec: &amp;mut Vec&lt;Person&gt;) {\n person_vec.sort_by_key(|person| {\n (\n person.last_name.to_lowercase(),\n person.first_name.to_lowercase(),\n )\n });\n}\n</code></pre>\n\n<h1><code>eprintln!</code></h1>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code>println!(\"\\nError: {}\", err);\n</code></pre>\n</blockquote>\n\n<p>shouldn't be printed to <code>stderr</code>:</p>\n\n<pre><code>eprintln!(\"\\nError: {}\", err);\n</code></pre>\n\n<h1>Error handling</h1>\n\n<p>Consider validating the data in <code>build_person_vec</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:05:20.877", "Id": "474227", "Score": "2", "body": "It should be noted that `.expect(\"Couldn't open file\")` will format the error using `fmt::Debug`, not `fmt::Display` like the original code. If you want to stick with `fmt::Display`, you could do `.unwrap_or_else(|err| panic!(\"Couldn't open file: {}\", err))` instead (still better than the match)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:23:32.723", "Id": "474234", "Score": "0", "body": "@Joe Thanks. I've edited the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:29:48.553", "Id": "474236", "Score": "0", "body": "You're welcome. The parenthetical \"(as `panic!` does)\" isn't quite correct, as `panic!` will use the format you specify (i.e., with `{:?}` instead of `{}` it would also use `fmt::Display`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T10:19:51.940", "Id": "474238", "Score": "1", "body": "@Joe Sorry, I've fixed that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T13:09:49.877", "Id": "474247", "Score": "0", "body": "Wow! Thank you so much for the detailed response. This is all incredibly helpful information, and your statements are crystal clear. I had no idea about `rustfmt` ! \nAnd yes, the `use std::env;` was a copy paste error- my bad!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T04:20:04.723", "Id": "241640", "ParentId": "241636", "Score": "6" } }, { "body": "<p>As always, I recommend using <a href=\"https://github.com/rust-lang/rust-clippy#as-a-cargo-subcommand-cargo-clippy\" rel=\"nofollow noreferrer\">clippy</a> for help. Running it, we get the following output:</p>\n\n<pre><code>warning: you seem to be trying to use match for destructuring a single pattern. Consider using `if let`\n --&gt; src/main.rs:188:9\n |\n188 | / match output_file.write_all(info.as_bytes()) {\n189 | | Err(why) =&gt; panic!(\"\\ncouldn't write to file: {}\", why),\n190 | | Ok(_) =&gt; (),\n191 | | }\n | |_________^ help: try this: `if let Err(why) = output_file.write_all(info.as_bytes()) { panic!(\"\\ncouldn't write to file: {}\", why) }`\n</code></pre>\n\n<p>So that's the first change we can make.</p>\n\n<pre><code>/**\n * # CSV Sorter\n *\n * ## Author: Daniel Hammer\n *\n * ### Date: 2020/5/2\n *\n * ### Description:\n * This program reads in a CSV composed of information about people, such as\n * names and addresses. It then stores each entry into a struct, and those\n * structs into a vector. The vector is sorted by last name (or first, if\n * last names are identical) and the newly sorted data is written to an\n * output file.\n */\n</code></pre>\n\n<p>For module-level documentation, use <code>//!</code> instead of <code>/**</code>.</p>\n\n<pre><code>fn arg_parser(args: &amp;[String]) -&gt; Result&lt;(File, File), &amp;'static str&gt; {\n</code></pre>\n\n<p>You really shouldn't return strings as your error type—they don't implement <a href=\"https://doc.rust-lang.org/std/error/trait.Error.html\" rel=\"nofollow noreferrer\">Error</a>, so they don't play nicely with other stuff. Use an error handling crate instead, such as anyhow (or implement it yourself).</p>\n\n<pre><code>// Person constructor\nimpl Person {\n fn new(first_name: String, last_name: String,\n street: String, city: String, state: String,\n zip_code: String) -&gt; Person {\n\n Person {\n first_name,\n last_name,\n street,\n city,\n state,\n zip_code,\n }\n }\n}\n</code></pre>\n\n<p><code>// Person constructor</code> is a useless comment. Remove it. And for that matter, there's no need for a constructor like this at all—and it's hard to remember the parameter order. Just fill in the <code>Person</code> struct manually.</p>\n\n<pre><code> let input_file = match File::open(format!(\"{}{}\", \"src/\", &amp;args[1])) {\n Err(why) =&gt; panic!(\"\\ncouldn't open file: {}\", why),\n Ok(file) =&gt; file,\n };\n\n // Get the output file\n let output_file = match File::create(format!(\"{}{}\", \"src/\", &amp;args[2])) {\n Err(why) =&gt; panic!(\"\\ncouldn't create file: {}\", why),\n Ok(file) =&gt; file,\n };\n</code></pre>\n\n<p>Don't format paths like that, use <a href=\"https://doc.rust-lang.org/std/path/struct.Path.html#method.join\" rel=\"nofollow noreferrer\">Path::join</a> instead.</p>\n\n<pre><code>let data: Vec&lt;&amp;str&gt; = line.split(\", \").collect();\n</code></pre>\n\n<p>You don't need to allocate a vector for that, just use Iterators directly (see my final code for my implementation).</p>\n\n<pre><code>fn sort_person_vec(person_vec: &amp;mut [Person]) {\n</code></pre>\n\n<p>Just implement <code>Ord</code> on <code>Person</code> so you can just call <code>person_vec.sort()</code>.</p>\n\n<pre><code>/**\n * Writes data to the output file\n *\n * # Description\n * Writes all Person structs to the output file, catching errors if the file\n * is not available to be written to.\n *\n * # Arguments\n * * `person_vec` - A vector containing Person structs.\n * * `output_file` - The file to write to.\n */\nfn write_to_file(person_vec: &amp;mut Vec&lt;Person&gt;, output_file: &amp;mut File) {\n\n for p in person_vec {\n\n // Format the peron's information as a string\n let info = format!(\"{}, {}, {}, {}, {}, {}\\n\",\n p.first_name, p.last_name, p.street, p.city,\n p.state, p.zip_code);\n\n // Write to output file\n match output_file.write_all(info.as_bytes()) {\n Err(why) =&gt; panic!(\"\\ncouldn't write to file: {}\", why),\n Ok(_) =&gt; (),\n }\n }\n}\n</code></pre>\n\n<p>Rust uses <code>///</code> documentation comments (vs <code>//!</code> for modules), not <code>/**</code>. When you run <code>cargo doc</code> or publish your crate, this documentation won't get carried over. It's also not common to use a Description header in Rust, as that's implied. And there's no need to say what each argument is if that's all you're gonna say: it's obvious that the parameter <code>person_vec</code> of type <code>&amp;mut Vec&lt;Person&gt;</code> is a <code>Vec</code> of <code>Person</code>s. Additionally, there's no need for <code>person_vec</code> to be mutable, or even a <code>Vec</code> at all. Instead, you should accept a <code>&amp;[Person]</code>. There's also no reason for <code>output_file</code> to be a file—what if you want to send it over the network instead or compress it (e.g. gzip) before writing it? You should accept a <code>&amp;mut impl Write</code> instead.</p>\n\n<pre><code>let info = format!(\"{}, {}, {}, {}, {}, {}\\n\",\n p.first_name, p.last_name, p.street, p.city,\n p.state, p.zip_code);\n</code></pre>\n\n<p>is probably written better with a <code>fmt::Display</code> implementation.</p>\n\n<p>In general, you should also not create <code>BufReader</code>s/<code>BufWriter</code>s within a function that reads or writes stuff. Leave the caller to do that.</p>\n\n<p><a href=\"https://gist.github.com/lights0123/23b3cded6ee039db2ce0ac5c8677a37c\" rel=\"nofollow noreferrer\">Final code</a>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>//! # CSV Sorter\n//!\n//! This program reads in a CSV composed of information about people, such as\n//! names and addresses. It then stores each entry into a struct, and those\n//! structs into a vector. The vector is sorted by last name (or first, if\n//! last names are identical) and the newly sorted data is written to an\n//! output file.\n\nuse std::cmp::Ordering;\nuse std::env;\nuse std::fs::File;\nuse std::io::{BufRead, BufReader, BufWriter, Write};\nuse std::path::PathBuf;\nuse std::process;\n\n/// Person struct to hold relevant data\n#[derive(Debug, PartialEq, Eq)]\nstruct Person {\n first_name: String,\n last_name: String,\n street: String,\n city: String,\n state: String,\n zip_code: String,\n}\n\nimpl Ord for Person {\n fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering {\n (\n self.last_name.to_lowercase(),\n self.first_name.to_lowercase(),\n )\n .cmp(&amp;(\n other.last_name.to_lowercase(),\n other.first_name.to_lowercase(),\n ))\n }\n}\n\nimpl PartialOrd for Person {\n fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; {\n Some(self.cmp(other))\n }\n}\n\n///\n/// Processes command-line arguments\n///\n/// # Description\n/// This function processes the passed-in command line arguments and attempts\n/// to open and create valid input/output files from the names given.\n///\n/// # Arguments\n/// * `args` - A string array of command-line arguments.\n///\n/// # Returns\n/// * A tuple of the input file and output file if they are found, else errors.\n///\nfn arg_parser(args: &amp;[String]) -&gt; Result&lt;(File, File), &amp;'static str&gt; {\n // Exit if too many or too few arguments were passed\n if args.len() != 3 {\n return Err(\"Usage: 'cargo run [input file] [output file]\");\n }\n\n // Get the input file\n let input_file = File::open(PathBuf::from(\"src\").join(&amp;args[1])).expect(\"Couldn't open file\");\n let output_file =\n File::create(PathBuf::from(\"src\").join(&amp;args[2])).expect(\"Couldn't create file\");\n\n // Return both files as a tuple\n Ok((input_file, output_file))\n}\n\n///\n/// Builds a list of Person structs\n///\n/// # Description\n/// This function reads the input file line by line and creates a Person\n/// struct based on the line's contents. It then adds that struct to a vector\n/// and repeats for every line in the file. The final vector contains every\n/// Person struct read in from the file.\n///\n/// # Returns\n/// * A vector of type Person containing all Person structs from the file.\nfn build_person_vec(reader: &amp;mut impl BufRead) -&gt; Vec&lt;Person&gt; {\n let mut person_vec: Vec&lt;Person&gt; = Vec::new();\n\n for line in reader.lines() {\n let line = line.unwrap();\n\n let mut data = line.split(',').map(|s| s.trim());\n\n let p = Person {\n first_name: String::from(data.next().unwrap()),\n last_name: String::from(data.next().unwrap()),\n street: String::from(data.next().unwrap()),\n city: String::from(data.next().unwrap()),\n state: String::from(data.next().unwrap()),\n zip_code: String::from(data.next().unwrap()),\n };\n person_vec.push(p);\n }\n person_vec\n}\n\n///\n/// Writes data to the output file\n///\n/// Writes all Person structs to the output file, catching errors if the file\n/// is not available to be written to.\nfn write_to_file(person_vec: &amp;[Person], output_file: &amp;mut impl Write) {\n for p in person_vec {\n let info = format!(\n \"{}, {}, {}, {}, {}, {}\\n\",\n p.first_name, p.last_name, p.street, p.city, p.state, p.zip_code\n );\n\n output_file\n .write_all(info.as_bytes())\n .expect(\"Couldn't write to file\");\n }\n}\n\nfn main() {\n let args: Vec&lt;String&gt; = env::args().collect();\n\n // Get the input and output files\n let (input_file, output_file) = arg_parser(&amp;args).unwrap_or_else(|err| {\n eprintln!(\"\\nError: {}\", err);\n process::exit(1);\n });\n\n let mut person_vec = build_person_vec(&amp;mut BufReader::new(&amp;input_file));\n\n person_vec.sort();\n\n write_to_file(&amp;person_vec, &amp;mut BufWriter::new(output_file));\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T17:33:15.873", "Id": "241674", "ParentId": "241636", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T01:18:01.640", "Id": "241636", "Score": "7", "Tags": [ "beginner", "csv", "rust" ], "Title": "Rust CSV Sorter Code Lookover" }
241636
<p>In some of my past c++ projects, I would sometimes end up having to use a multidimensional array. However, I often would spend more than a needed amount of time on how to store the multidimensional array.so as a result, I decided to create a multidimensional array c++ class. here is the code</p> <p>mdarray.hh</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;cstdint&gt; #include &lt;vector&gt; #include &lt;iterator&gt; #include &lt;cmath&gt; #include &lt;type_traits&gt; template &lt;typename T, std::uint64_t N&gt; class multidimensional_array { std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt; _data{0}; template &lt;typename Size1, typename... Sizes&gt; void _resize(const Size1 &amp;size1, const Sizes &amp;... sizes) { _data.resize(size1); for (auto &amp;item : _data) { item.resize(sizes...); } } template &lt;typename Size1&gt; void _resize(const Size1 &amp;size1) { _data.resize(size1); } public: // iterators using iterator = typename std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt;::iterator; using const_iterator = typename std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt;::const_iterator; // constructers multidimensional_array() = default; virtual ~multidimensional_array() = default; template &lt;typename... Sizes&gt; multidimensional_array(const Sizes &amp;... sizes) { resize(sizes...); } multidimensional_array( const std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt; &amp;Items) : _data(Items) {} // access to data public: std::vector&lt;T&gt; data() { return _data; } T *raw_data() { return _data.begin()-&gt;raw_data(); } multidimensional_array&lt;T, N - 1&gt; &amp;operator[](std::uint64_t index) { return _data.at(index); } public: // access to size std::uint64_t size() { return _data.size(); } template &lt;typename... Sizes&gt; void resize(const Sizes &amp;... sizes) { static_assert(sizeof...(sizes) &lt;= N, "the number of parameters is more the number of dimensions"); _resize(sizes...); } template &lt;typename Size&gt; void resize(const Size &amp;size1) { _resize(size1); } // helper functions public: void fill(iterator first, iterator last, const T &amp;item) { for (; first != last; first++) { first-&gt;fill(first-&gt;begin(), first-&gt;end(), item); } } void fill(const T &amp;item) { fill(begin(), end(), item); } template &lt;typename F&gt; void for_each(F &amp;&amp;function) { for (auto &amp;item : _data) { item.for_each(function); } } // iterators public: iterator begin() noexcept { return _data.begin(); } const_iterator cbegin() const noexcept { return _data.cbegin(); } iterator end() noexcept { return _data.end(); } const_iterator cend() const noexcept { return _data.cend(); } }; // class for 1d array template &lt;typename T&gt; class multidimensional_array&lt;T, 1&gt; { private: std::vector&lt;T&gt; _data{0}; public: // iterators using iterator = typename std::vector&lt;T&gt;::iterator; using const_iterator = typename std::vector&lt;T&gt;::const_iterator; // constructers multidimensional_array(const std::uint64_t &amp;size) : _data(size){}; multidimensional_array(const std::vector&lt;T&gt; &amp;Items) : _data(Items){}; multidimensional_array() = default; virtual ~multidimensional_array() = default; template &lt;typename Size&gt; multidimensional_array(const Size &amp;size1) { resize(size1); } // access to data public: std::vector&lt;T&gt; &amp;data() { return _data; } T *raw_data() { return _data.data(); } T &amp;operator[](std::uint64_t index) { return _data.at(index); } // helper functions public: void fill(iterator first, iterator last, const T &amp;item) { for (; first != last; first++) { *first = item; } } void fill(const T &amp;item) { fill(begin(), end(), item); } template &lt;typename F&gt; void for_each(F &amp;&amp;function) { for (auto &amp;item : _data) { function(item); } } public: // access to size std::uint64_t size() { return _data.size(); } template &lt;typename Size&gt; void resize(const Size &amp;size1) { _data.resize(size1); } // iterator public: iterator begin() noexcept { return _data.begin(); } const_iterator cbegin() const noexcept { return _data.cbegin(); } iterator end() noexcept { return _data.end(); } const_iterator cend() const noexcept { return _data.cend(); } }; </code></pre>
[]
[ { "body": "<pre><code>std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt; _data{0};\n</code></pre>\n\n<p>What does this line do? (Possible hint: <code>{0}</code> is a braced initializer sequence consisting of a single <code>int</code>, and <code>int</code> is implicitly convertible to <code>multidimensional_array&lt;T, N-1&gt;</code>. Or is this an anti-hint? Can you tell, without asking a compiler?)</p>\n\n<p>If you want to create an empty vector, just use <code>vector</code>'s default constructor:</p>\n\n<pre><code>std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt; _data;\n</code></pre>\n\n<p>or convert from an empty initializer-list:</p>\n\n<pre><code>std::vector&lt;multidimensional_array&lt;T, N - 1&gt;&gt; _data = {};\n</code></pre>\n\n<p>See <a href=\"https://quuxplusone.github.io/blog/2019/02/18/knightmare-of-initialization/\" rel=\"noreferrer\">\"The Knightmare of Initialization in C++.\"</a></p>\n\n<hr>\n\n<pre><code>virtual ~multidimensional_array() = default;\n</code></pre>\n\n<p>Yikes! Why does this class need a vtable? Are you intending to inherit from it? Please don't!</p>\n\n<hr>\n\n<pre><code> template &lt;typename Size1, typename... Sizes&gt;\n void _resize(const Size1 &amp;size1, const Sizes &amp;... sizes) {\n _data.resize(size1);\n for (auto &amp;item : _data) {\n item.resize(sizes...);\n }\n }\n template &lt;typename Size1&gt;\n void _resize(const Size1 &amp;size1) {\n _data.resize(size1);\n }\n</code></pre>\n\n<p>If you're allowed to use C++17 <code>if constexpr</code>, then you can write this without the \"recursion\", as:</p>\n\n<pre><code>template&lt;class... Sizes&gt;\nvoid _resize(size_t head, Sizes... tail) {\n _data.resize(head);\n if constexpr (sizeof...(tail) != 0) {\n for (auto&amp;&amp; elt : _data) {\n elt.resize(tail...);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>template &lt;typename... Sizes&gt;\nmultidimensional_array(const Sizes &amp;... sizes) {\n resize(sizes...);\n}\n</code></pre>\n\n<p>This constructor should be marked <code>explicit</code>. Otherwise, declarations like these will compile without complaint:</p>\n\n<pre><code>multidimensional_array&lt;int, 1&gt; a = 3;\nmultidimensional_array&lt;int, 1&gt; b {3};\n</code></pre>\n\n<p>In fact, you should probably forbid constructing a <code>multidimensional_array&lt;T, N&gt;</code> with any number of size parameters other than <code>N</code>. And in fact, to avoid the ambiguity of</p>\n\n<pre><code>multidimensional_array&lt;int, 1&gt; b {3};\n</code></pre>\n\n<p>entirely, let's just use a <a href=\"https://quuxplusone.github.io/blog/2018/06/21/factory-vs-conversion/\" rel=\"noreferrer\">factory method</a> instead of a constructor. Result:</p>\n\n<pre><code>template&lt;class T, size_t N&gt;\nclass multidimensional_array {\npublic:\n template&lt;class... Sizes,\n std::enable_if_t&lt;sizeof...(Sizes) == N, int&gt; = 0,\n std::enable_if_t&lt;(std::is_same_v&lt;Sizes, size_t&gt; &amp;&amp; ...), int&gt; = 0,\n &gt;\n static multidimensional_array with_dimensions(Sizes... sizes) {\n multidimensional_array a;\n a.resize(sizes...);\n return a;\n }\n [...]\n};\n\nauto a1 = multidimensional_array&lt;int, 1&gt;::with_dimensions(2);\nauto a2 = multidimensional_array&lt;int, 1&gt;{0, 0};\nauto a3 = multidimensional_array&lt;int, 2&gt;::with_dimensions(3, 3);\n</code></pre>\n\n<p>Consider what should happen if the caller passes dimensions (0,0) or (-1,-1) or so on.</p>\n\n<hr>\n\n<pre><code>std::vector&lt;T&gt; data() { return _data; }\n</code></pre>\n\n<p>It is surprising that <code>data()</code> returns a <em>copy</em> of the data; that's not how <code>std::vector::data()</code> or <code>std::array::data()</code> work. I would expect to see also an overload of <code>data()</code> for const arrays:</p>\n\n<pre><code>std::vector&lt;T&gt;&amp; data() { return _data; }\nconst std::vector&lt;T&gt;&amp; data() const { return _data; }\n</code></pre>\n\n<p>...oh wait, except that <em>doesn't work at all</em>, because <code>_data</code> is not a <code>vector&lt;T&gt;</code>; it's a <code>vector&lt;multidimensional_array&lt;T,N-1&gt;&gt;</code>.</p>\n\n<p>The moral of this story is that you should always test your code! C++ templates especially, because if you don't instantiate them, you'll never know if they even type-check at all.</p>\n\n<pre><code>T *raw_data() { return _data.begin()-&gt;raw_data(); }\n</code></pre>\n\n<p>This compiles, but is extremely scary, because it sounds (to me) like it ought to give a view onto a contiguous array of <code>(Sizes * ...)</code> objects of type <code>T</code>, but really it only gives a view onto the first linear \"row\" of the data; the rest of the data is stored somewhere else, non-contiguous with that row.</p>\n\n<p>In fact, I would recommend that you not provide the <code>data()</code> accessor either, because the C++20 STL adds a notion of \"contiguous container\" which is triggered by seeing if the container has a plausible-looking <code>.data()</code> method (e.g. <code>vector</code>, <code>array</code>, <code>string</code>). Since your container is non-contiguous, you should probably avoid the word <code>.data()</code> — the same way you'd avoid the word <code>.begin()</code> for something that didn't return an iterator.</p>\n\n<hr>\n\n<pre><code>T &amp;operator[](std::uint64_t index) { return _data.at(index); }\n</code></pre>\n\n<p>should have a <code>const</code> overload too. And you should almost certainly use <code>size_t</code>, not <code>uint64_t</code>, just to be idiomatic and to match the <code>size_type</code> of <code>std::vector</code>.</p>\n\n<hr>\n\n<pre><code>void for_each(F &amp;&amp;function)\n</code></pre>\n\n<p>Consider providing a <code>const</code> overload of <code>for_each</code>.</p>\n\n<p>The STL-ese way of passing a callback is just <code>F function</code> — pass by value — because usually the function is just a stateless lambda or something equally cheap to copy. If the caller really wants pass-by-reference, all they have to do is wrap their function in <code>std::ref</code>.</p>\n\n<hr>\n\n<p>Consider adding a <code>static_assert(N &gt;= 2)</code> to the primary template. <code>N==0</code> should be a hard error.</p>\n\n<p>Your repetition of <code>public:</code> is harmless but unidiomatic. We generally just have one big <code>public:</code> section and one big <code>private:</code> section (and personally I put them in that order, but reasonable people may vary on that).</p>\n\n<hr>\n\n<p>Quick, off the top of your head, which parts of your design break when you instantiate <code>multidimensional_array&lt;bool, 2&gt;</code>? Which parts break <em>unsalvageably?</em></p>\n\n<p>Write unit tests! Pay particular attention to <code>const</code> — like, write a test that verifies that <code>a[3] = b[3]</code> compiles when <code>b</code> is const (but not when <code>a</code> is const).</p>\n\n<p>Hmm, that reminds me: did you <em>want</em> <code>a[3] = b[3]</code> to compile? I should be able to assign the entire array at once <code>a = b</code>, and I should be able to assign one <code>T</code> object at a time <code>a[i][j] = t</code>, but should I also be able to assign one <em>row</em> at a time <code>a[i] = r</code>?</p>\n\n<p>What about this?</p>\n\n<pre><code>auto mat = multidimensional_array&lt;int, 2&gt;::with_dimensions(3, 3);\nmat[0].resize(2);\n\n// Is `mat` now a 3x3 array with one corner cut out?\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T04:43:12.173", "Id": "241642", "ParentId": "241638", "Score": "5" } } ]
{ "AcceptedAnswerId": "241642", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T03:52:03.730", "Id": "241638", "Score": "1", "Tags": [ "c++" ], "Title": "Multidimensional array made in c++" }
241638
<p>I was trying out some variation in implementation of a leetcode example and was surprised by the runtimes. I was expecting it would be better to use <code>map()</code> than classic grandpa style <code>for</code>-loop</p> <p>In short the problem is to find if a value in the list is smaller or larger than a threshold value</p> <p><a href="https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/" rel="nofollow noreferrer">https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/</a></p> <h2>Here are the three implementations:</h2> <h2>72 ms 13.8 MB</h2> <p>Map over the input list and generate the list of bool</p> <pre><code>class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -&gt; List[bool]: m=max(candies)-extraCandies return list(map( lambda x: x&gt;=m, candies)) </code></pre> <h2>40 ms 14 MB</h2> <p>For-loop and <code>append()</code> to list</p> <pre><code>class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -&gt; List[bool]: m=max(candies)-extraCandies ans=[] for x in candies: ans.append(x&gt;=m) return ans </code></pre> <h2>28 ms 13.6 MB</h2> <p>Use <code>+</code> to append to list</p> <pre><code>class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -&gt; List[bool]: m=max(candies)-extraCandies ans=[] for x in candies: ans+=[(x&gt;=m)] return ans </code></pre> <p>Why is <code>append()</code> slower than <code>+</code> and is there some oversight in the <code>map()</code> solution which slows it down?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T06:49:22.767", "Id": "474226", "Score": "0", "body": "In addition you might try to resize the list to a proper size at start." } ]
[ { "body": "<p>You ask whether there is an oversight in the <code>map</code> solution, slowing it down.\nThere is, in the form of <code>lambda</code>.\nWhen passing <code>lambda</code> objects, <code>map</code> is slowed down, as <a href=\"https://stackoverflow.com/a/40948713/11477374\">shown here</a>.\nPassing proper function objects does not have the same restrictions.</p>\n\n<p>Other than that, I was unable to confirm the large performance discrepancy you found between <code>append</code> (40ms) and <code>__iadd__</code>/<code>+=</code> (28ms).\nIn the below tests, <code>append</code> is <em>faster</em> than <code>+=</code> by (just) about 2 percent.\nThat is negligible.</p>\n\n<p>Below, five versions of your function are tested.\nNext to <code>kidsWithCandies_map_builtin</code>, which uses the <code>ge</code> function of the <code>operator</code> module to get a <code>callable</code> <code>ge(a, b)</code> that returns the same as <code>a &gt;= b</code>, the arguably most Pythonic approach is also tested, list comprehension.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict, namedtuple\nfrom operator import ge\nfrom pprint import pprint as pp\nfrom timeit import timeit\nfrom typing import List\n\ncandy_distribution = namedtuple(\n \"CandyDistribution\", [\"candies\", \"extra_candies\", \"solution\"]\n)\n\ncandy_distributions = [\n candy_distribution([2, 3, 5, 1, 3], 3, [True, True, True, False, True]),\n candy_distribution([4, 2, 1, 1, 2], 1, [True, False, False, False, False]),\n candy_distribution([12, 1, 12], 10, [True, False, True]),\n]\n\n\ndef kidsWithCandies_map_lambda(candies: List[int], extraCandies: int) -&gt; List[bool]:\n\n threshold = max(candies) - extraCandies\n return list(map(lambda x: x &gt;= threshold, candies))\n\n\ndef kidsWithCandies_map_builtin(candies: List[int], extraCandies: int) -&gt; List[bool]:\n\n threshold = max(candies) - extraCandies\n thresholds = [threshold] * len(candies)\n return list(map(ge, candies, thresholds))\n\n\ndef kidsWithCandies_append(candies: List[int], extraCandies: int) -&gt; List[bool]:\n\n threshold = max(candies) - extraCandies\n ans = []\n for x in candies:\n ans.append(x &gt;= threshold)\n return ans\n\n\ndef kidsWithCandies_iadd(candies: List[int], extraCandies: int) -&gt; List[bool]:\n\n threshold = max(candies) - extraCandies\n ans = []\n for x in candies:\n ans += [(x &gt;= threshold)]\n return ans\n\n\ndef kidsWithCandies_comprehension(candies: List[int], extraCandies: int) -&gt; List[bool]:\n\n threshold = max(candies) - extraCandies\n return [element &gt;= threshold for element in candies]\n\n\nfunctions_to_runtimes = defaultdict(int)\n\n\nfor func in (\n kidsWithCandies_map_lambda,\n kidsWithCandies_map_builtin,\n kidsWithCandies_append,\n kidsWithCandies_iadd,\n kidsWithCandies_comprehension,\n):\n for candy_supply in candy_distributions:\n args = (candy_supply.candies, candy_supply.extra_candies)\n assert candy_supply.solution == func(*args)\n functions_to_runtimes[func.__name__] += timeit(\"func(*args)\", globals=globals())\n\nfunctions_to_runtimes = { # sort by value, ascending\n k: v for k, v in sorted(functions_to_runtimes.items(), key=lambda item: item[1])\n}\n\npp(functions_to_runtimes)\n</code></pre>\n\n<p>with an output of</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>{'kidsWithCandies_append': 2.2671058810083196,\n 'kidsWithCandies_comprehension': 2.3766544990066905,\n 'kidsWithCandies_iadd': 2.3180257579660974,\n 'kidsWithCandies_map_builtin': 2.9652103499975055,\n 'kidsWithCandies_map_lambda': 3.658640267996816}\n</code></pre>\n\n<p>So while there is not much of a difference between <code>append</code>, <code>comprehension</code> and in-place addition (<code>+=</code>), <code>map</code> is much improved by <em>not</em> using a lambda.</p>\n\n<p>The most non-grandpa style approach is the list comprehension. <code>map</code> was even originally supposed to be <a href=\"https://www.artima.com/weblogs/viewpost.jsp?thread=98196\" rel=\"nofollow noreferrer\">dropped from Python 3</a>; as such (but this is speculation), one can suspect that all the performance love and care went towards (list) comprehensions, <code>append</code> and <code>+=</code>. Others have tried <a href=\"https://stackoverflow.com/a/6407222/11477374\">here</a>, but <code>map</code>, as a built-in, seems hard to introspect.</p>\n\n<p>I omitted space complexity considerations because these seem similar for all approaches.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T11:54:42.437", "Id": "241655", "ParentId": "241639", "Score": "6" } } ]
{ "AcceptedAnswerId": "241655", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T04:09:42.187", "Id": "241639", "Score": "4", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Why is append() slower than + and is there some oversight in the map() solution which slows it down?" }
241639
<p>I produced below code and soon it became outdated due to the blocking nature of it's loops which I can't see how to avoid that.</p> <p>Work-flow summery</p> <ol> <li><p>Client send a request to "/" to get a list of JS objects via JSON format. Few hundred thousand records of them. Array A</p></li> <li><p>First script should retrieve translation documents for above records, translations are also obviously in few hundred thousand set. In this stage it does a network call and retrieves those. Array B</p></li> <li><p>Then needed Array A should be retrieved via Mysql DB.</p></li> <li><p>Then sorts Array A and Array B and bind those together in a very long loop. (Blocks code)</p></li> <li><p>Then submits the reformatted result to client. </p></li> </ol> <pre><code>router.get("/", async function (req, res) { CustomModel.count({}) // this is database call via sequelize-hierarchy library .then(async (count) =&gt; { await common .getLanguages(config.urls.languages_cat_endpoint) // this is a outside API call which retreives few hundred thousand records of JSON objects .then((langs) =&gt; { common.afterFindHook(CustomModel, langs.data); // This code registers a hook and it will get triggers when line findAll calls, and it pass above set of JSON objects as an arguments }) .catch((e) =&gt; { console.log(e); common.sendResponse(res, 500, "Internal Server Error"); return; }); CustomModel.findAll({ // BLOCKING code due to above 4th step. Another call via sequelize-hierarchy library, it will trigger above afterFindHook and sort-&gt;find-&gt;bind each language JSON object to each row. Few hundred thousand records here where: { status: true }, hierarchy: true, order: [["position", "DESC"]], }) .then(function (result) { res.send(result); // This is where the real result submitted to client. res.end(); }) .catch((error) =&gt; { common.sendResponse(res, 500, error); }); }) .catch((e) =&gt; { console.log(e); common.sendResponse(res, 500, "Internal Server Error"); return; }); }); </code></pre> <p>I'm aware there are lot of optimizations can be done to speed up the request, or reduce the time to prepare the request however I'm not interested on that. </p> <p>My question here is how to remove and refactor only event-loop blocking code. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T04:27:53.173", "Id": "241641", "Score": "1", "Tags": [ "array", "node.js", "event-handling", "express.js" ], "Title": "How to refactor below nodejs code to unblock event-loop?" }
241641
<h1>Introduction</h1> <p>I am a Rust novice. So far, I have finished reading the first 15 chapters of <a href="https://doc.rust-lang.org/stable/book/" rel="nofollow noreferrer"><em>The Rust Programming Language</em></a> (a.k.a. the book). Here's my first big Rust project &mdash; Tic Tac Toe.</p> <p>Each invocation of the program starts a session, in which the scores of two players O and X are tracked on an internal scoreboard. The program starts with a session menu, which supports a bunch of commands. For example, the <code>scoreboard</code> command displays the scores, and the <code>start</code> command starts a game (optionally specifying who is the first player). Once a game is started, the board is displayed, and the players are asked to enter their move. See the Example Session below for more information.</p> <p>I have run <code>rustfmt</code> and <code>clippy</code> on my code, and improved my code according to their feedback. I would like to have a code review, since I want to become aware of my mistakes and avoid making them again. See the Specific Concerns below for more information.</p> <h1>Code</h1> <p><strong>src/board.rs</strong></p> <pre><code>use std::fmt; use std::hash::Hash; use std::iter; use std::str; use std::usize; use itertools::Itertools; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Player { Nought, Cross, } impl Player { pub fn toggle(self) -&gt; Player { match self { Player::Nought =&gt; Player::Cross, Player::Cross =&gt; Player::Nought, } } } impl fmt::Display for Player { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { match self { Player::Nought =&gt; write!(f, "O"), Player::Cross =&gt; write!(f, "X"), } } } impl str::FromStr for Player { type Err = ParsePlayerError; fn from_str(s: &amp;str) -&gt; Result&lt;Self, Self::Err&gt; { match s { "O" =&gt; Ok(Player::Nought), "X" =&gt; Ok(Player::Cross), _ =&gt; Err(ParsePlayerError {}), } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ParsePlayerError {} #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Cell { Occupied(Player), Vacant, } impl Cell { fn is_occupied(self) -&gt; bool { !self.is_vacant() } fn is_vacant(self) -&gt; bool { match self { Cell::Occupied(_) =&gt; false, Cell::Vacant =&gt; true, } } } impl fmt::Display for Cell { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { match self { Cell::Occupied(player) =&gt; write!(f, "{}", player), Cell::Vacant =&gt; write!(f, " "), } } } // a position on the board // 1 2 3 // 4 5 6 // 7 8 9 #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Pos { pos: usize, } impl Pos { pub fn new(pos: usize) -&gt; Option&lt;Pos&gt; { if (1..=Board::SIZE).contains(&amp;pos) { Some(Pos { pos }) } else { None } } pub fn get(self) -&gt; usize { self.pos } } impl fmt::Display for Pos { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { write!(f, "{}", self.get()) } } pub struct Board { // row-major layer cells: [Cell; Board::SIZE], } impl Board { pub const WIDTH: usize = 3; pub const SIZE: usize = Board::WIDTH * Board::WIDTH; pub fn new() -&gt; Board { Board { cells: [Cell::Vacant; Board::SIZE], } } pub fn place(&amp;mut self, pos: Pos, player: Player) -&gt; Result&lt;(), PlaceError&gt; { let cell = &amp;mut self.cells[pos.get() - 1]; match *cell { Cell::Occupied(player) =&gt; Err(PlaceError { pos, occupied_by: player, }), Cell::Vacant =&gt; { *cell = Cell::Occupied(player); Ok(()) } } } pub fn wins(&amp;self, player: Player) -&gt; bool { self.rows().any(|row| occupied_by(row, player)) || self.columns().any(|column| occupied_by(column, player)) || self .diagonals() .any(|diagonal| occupied_by(diagonal, player)) } pub fn is_draw(&amp;self) -&gt; bool { self.is_complete() &amp;&amp; !self.wins(Player::Nought) &amp;&amp; !self.wins(Player::Cross) } fn rows(&amp;self) -&gt; impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt; { self.cells.chunks(Board::WIDTH).map(|chunk| chunk.iter()) } fn columns(&amp;self) -&gt; impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt; { (0..Board::WIDTH).map(move |n| self.cells.iter().skip(n).step_by(Board::WIDTH)) } fn diagonals(&amp;self) -&gt; impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt; { // major and minor have the same type let major = iter::once( self.cells .iter() .skip(0) .step_by(Board::WIDTH + 1) .take(Board::WIDTH), ); let minor = iter::once( self.cells .iter() .skip(Board::WIDTH - 1) .step_by(Board::WIDTH - 1) .take(Board::WIDTH), ); major.chain(minor) } fn is_complete(&amp;self) -&gt; bool { self.cells.iter().all(|cell| cell.is_occupied()) } } impl fmt::Display for Board { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { writeln!(f, "+{}+", ["---"; Board::WIDTH].join("+"))?; for row in self.rows() { writeln!(f, "| {} |", row.format(" | "))?; writeln!(f, "+{}+", ["---"; Board::WIDTH].join("+"))?; } Ok(()) } } fn occupied_by&lt;'a, I: Iterator&lt;Item = &amp;'a Cell&gt;&gt;(mut cells: I, player: Player) -&gt; bool { cells.all(|cell| *cell == Cell::Occupied(player)) } #[derive(Debug, Eq, PartialEq)] pub struct PlaceError { pub pos: Pos, pub occupied_by: Player, } #[cfg(test)] mod tests { use super::*; #[test] fn player_toggle() { assert_eq!(Player::Nought, Player::Cross.toggle()); assert_eq!(Player::Cross, Player::Nought.toggle()); } #[test] fn player_display() { assert_eq!("O", format!("{}", Player::Nought)); assert_eq!("X", format!("{}", Player::Cross)); } #[test] fn player_parse() { assert_eq!(Ok(Player::Nought), "O".parse()); assert_eq!(Ok(Player::Cross), "X".parse()); assert!("".parse::&lt;Player&gt;().is_err()); assert!("a".parse::&lt;Player&gt;().is_err()); assert!("o".parse::&lt;Player&gt;().is_err()); assert!("XXX".parse::&lt;Player&gt;().is_err()); } #[test] fn cell() { assert!(Cell::Occupied(Player::Nought).is_occupied()); assert!(Cell::Occupied(Player::Cross).is_occupied()); assert!(!Cell::Vacant.is_occupied()); assert!(!Cell::Occupied(Player::Nought).is_vacant()); assert!(!Cell::Occupied(Player::Cross).is_vacant()); assert!(Cell::Vacant.is_vacant()); } #[test] fn cell_display() { assert_eq!("O", format!("{}", Cell::Occupied(Player::Nought))); assert_eq!("X", format!("{}", Cell::Occupied(Player::Cross))); assert_eq!(" ", format!("{}", Cell::Vacant)); } #[test] fn pos() { assert_eq!(1, Pos::new(1).unwrap().get()); assert_eq!(4, Pos::new(4).unwrap().get()); assert_eq!(9, Pos::new(9).unwrap().get()); assert!(Pos::new(0).is_none()); assert!(Pos::new(10).is_none()); assert!(Pos::new(usize::MAX).is_none()); } #[test] fn board_new() { let board = Board::new(); assert_eq!([Cell::Vacant; 9], board.cells); } #[test] fn board_place() { let mut board = Board::new(); board.place(Pos::new(1).unwrap(), Player::Nought).unwrap(); assert_eq!( [ Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Vacant, ], board.cells ); board.place(Pos::new(5).unwrap(), Player::Cross).unwrap(); board.place(Pos::new(9).unwrap(), Player::Nought).unwrap(); assert_eq!( [ Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Vacant, Cell::Vacant, Cell::Occupied(Player::Nought), ], board.cells ); assert_eq!( PlaceError { pos: Pos::new(1).unwrap(), occupied_by: Player::Nought, }, board .place(Pos::new(1).unwrap(), Player::Cross) .unwrap_err() ); } #[test] fn board_display() { assert_eq!( "\ +---+---+---+\n\ | | | |\n\ +---+---+---+\n\ | | | |\n\ +---+---+---+\n\ | | | |\n\ +---+---+---+\n\ ", format!("{}", Board::new()), ); } #[test] fn board_rows() { let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; let mut rows = board.rows(); let mut row = rows.next().unwrap(); assert_eq!(Cell::Occupied(Player::Nought), *row.next().unwrap()); assert_eq!(Cell::Occupied(Player::Cross), *row.next().unwrap()); assert_eq!(Cell::Vacant, *row.next().unwrap()); assert!(row.next().is_none()); let mut row = rows.next().unwrap(); assert_eq!(Cell::Occupied(Player::Cross), *row.next().unwrap()); assert_eq!(Cell::Vacant, *row.next().unwrap()); assert_eq!(Cell::Occupied(Player::Nought), *row.next().unwrap()); assert!(row.next().is_none()); let mut row = rows.next().unwrap(); assert_eq!(Cell::Vacant, *row.next().unwrap()); assert_eq!(Cell::Occupied(Player::Nought), *row.next().unwrap()); assert_eq!(Cell::Occupied(Player::Cross), *row.next().unwrap()); assert!(row.next().is_none()); assert!(rows.next().is_none()); } #[test] fn board_columns() { let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; let mut columns = board.columns(); let mut column = columns.next().unwrap(); assert_eq!(Cell::Occupied(Player::Nought), *column.next().unwrap()); assert_eq!(Cell::Occupied(Player::Cross), *column.next().unwrap()); assert_eq!(Cell::Vacant, *column.next().unwrap()); assert!(column.next().is_none()); let mut column = columns.next().unwrap(); assert_eq!(Cell::Occupied(Player::Cross), *column.next().unwrap()); assert_eq!(Cell::Vacant, *column.next().unwrap()); assert_eq!(Cell::Occupied(Player::Nought), *column.next().unwrap()); assert!(column.next().is_none()); let mut column = columns.next().unwrap(); assert_eq!(Cell::Vacant, *column.next().unwrap()); assert_eq!(Cell::Occupied(Player::Nought), *column.next().unwrap()); assert_eq!(Cell::Occupied(Player::Cross), *column.next().unwrap()); assert!(column.next().is_none()); assert!(columns.next().is_none()); } #[test] fn board_diagonals() { let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; let mut diagonals = board.diagonals(); let mut diagonal = diagonals.next().unwrap(); assert_eq!(Cell::Occupied(Player::Nought), *diagonal.next().unwrap()); assert_eq!(Cell::Vacant, *diagonal.next().unwrap()); assert_eq!(Cell::Occupied(Player::Cross), *diagonal.next().unwrap()); assert!(diagonal.next().is_none()); let mut diagonal = diagonals.next().unwrap(); assert_eq!(Cell::Vacant, *diagonal.next().unwrap()); assert_eq!(Cell::Vacant, *diagonal.next().unwrap()); assert_eq!(Cell::Vacant, *diagonal.next().unwrap()); assert!(diagonal.next().is_none()); assert!(diagonals.next().is_none()); } #[test] fn board_is_complete() { let board = Board { cells: [Cell::Occupied(Player::Cross); 9], }; assert!(board.is_complete()); let board = Board { cells: [Cell::Vacant; 9], }; assert!(!board.is_complete()); let board = Board { cells: [ Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; assert!(!board.is_complete()); } #[test] fn board_wins() { let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; assert!(!board.wins(Player::Nought)); assert!(!board.wins(Player::Cross)); let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Nought), ], }; assert!(board.wins(Player::Nought)); assert!(!board.wins(Player::Cross)); } #[test] fn board_is_draw() { let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Cross), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Vacant, Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; assert!(!board.is_draw()); let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Nought), ], }; assert!(!board.is_draw()); let board = Board { cells: [ Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), Cell::Occupied(Player::Nought), Cell::Occupied(Player::Cross), ], }; eprintln!("{}", board); assert!(board.is_draw()); } } </code></pre> <p><strong>src/game.rs</strong></p> <pre><code>use std::io; use crate::board::{Board, Player, Pos}; use crate::utility; pub enum Result { Win(Player), Draw, } pub struct Game { board: Board, first_player: Player, resigned: Option&lt;Player&gt;, } impl Game { pub fn new(first_player: Player) -&gt; Game { Game { board: Board::new(), first_player, resigned: Option::None, } } pub fn run(&amp;mut self) -&gt; Result { let mut current_player = self.first_player; loop { self.process_move(current_player); if let Some(player) = self.resigned { utility::clear_screen(); print!("{}", self.board); let winner = player.toggle(); println!("{} wins by resignation.", winner); return Result::Win(winner); } else if self.board.wins(current_player) { utility::clear_screen(); print!("{}", self.board); println!("{} wins.", current_player); return Result::Win(current_player); } else if self.board.is_draw() { utility::clear_screen(); print!("{}", self.board); println!("It's a draw."); return Result::Draw; } current_player = current_player.toggle() } } fn process_move(&amp;mut self, player: Player) { loop { utility::clear_screen(); print!("{}", self.board); println!("[{}] Enter your move: ('help' for help)", player); let mut input = String::new(); io::stdin() .read_line(&amp;mut input) .expect("Failed to read input"); let input = input.trim(); match input { "help" =&gt; { println!(); self.display_move_help(player); continue; } "resign" =&gt; { self.resigned = Some(player); break; } _ =&gt; {} } if let Err(message) = input .parse() .or_else(|_| Err("Invalid move".to_owned())) .and_then(|pos| Pos::new(pos).ok_or_else(|| "Invalid position".to_owned())) .and_then(|pos| { self.board.place(pos, player).or_else(|place_error| { Err(format!( "Position {} occupied by {}", place_error.pos, place_error.occupied_by )) }) }) { eprintln!("{}", message); continue; } break; } } fn display_move_help(&amp;self, player: Player) { print!( "\ Supported commands: \n\ \n\ - help: display help screen \n\ \n\ - resign: resign the game \n\ \n\ - 1-9: place {} on the specified position\n\ \n\ * +---+---+---+ \n\ * | 1 | 2 | 3 | \n\ * +---+---+---+ \n\ * | 4 | 5 | 6 | \n\ * +---+---+---+ \n\ * | 7 | 8 | 9 | \n\ * +---+---+---+ \n\ ", player ); } } #[cfg(test)] mod tests { use super::*; #[test] fn game_new() { let game = Game::new(Player::Nought); assert_eq!( "\ +---+---+---+\n\ | | | |\n\ +---+---+---+\n\ | | | |\n\ +---+---+---+\n\ | | | |\n\ +---+---+---+\n\ ", format!("{}", game.board) ); assert_eq!(Player::Nought, game.first_player); assert!(game.resigned.is_none()); } } </code></pre> <p><strong>src/session.rs</strong></p> <pre><code>use std::collections::HashMap; use std::io; use crate::board::Player; use crate::game::{Game, Result}; use crate::utility; pub struct Session { scores: HashMap&lt;Player, u32&gt;, first_player: Player, } impl Session { const DEFAULT_FIRST_PLAYER: Player = Player::Cross; pub fn new() -&gt; Session { Session { scores: [(Player::Nought, 0), (Player::Cross, 0)] .iter() .copied() .collect(), first_player: Session::DEFAULT_FIRST_PLAYER, } } pub fn run(&amp;mut self) { loop { utility::clear_screen(); println!("Enter command: ('help' for help)"); let mut input = String::new(); io::stdin() .read_line(&amp;mut input) .expect("Failed to read input"); match input.trim() { "exit" | "quit" =&gt; break, "help" =&gt; { println!(); self.display_help(); } "reset" =&gt; self.reset_scores(), "scoreboard" =&gt; { println!(); self.display_scoreboard(); } input if input.starts_with("start") =&gt; { self.process_start(input); } _ =&gt; { eprintln!("Invalid command."); } } } } fn display_help(&amp;self) { print!( "\ Supported commands: \n\ \n\ - exit: quit the session \n\ \n\ - help: display help screen \n\ \n\ - quit: quit the session \n\ \n\ - reset: reset scores \n\ \n\ - scoreboard: display scores \n\ \n\ - start: start a new game \n\ \n\ - start O/X: start a new game, with the specified first player \n\ " ); } fn display_scoreboard(&amp;self) { println!("Scoreboard:"); let mut entries: Vec&lt;_&gt; = self.scores.iter().collect(); entries.sort_unstable_by(|&amp;(_, score_a), &amp;(_, score_b)| score_b.cmp(score_a)); for (player, score) in entries { println!(); println!("- {}: {}", player, score); } } fn reset_scores(&amp;mut self) { for score in self.scores.values_mut() { *score = 0; } } fn process_result(&amp;mut self, result: Result) { match result { Result::Win(player) =&gt; *self.scores.get_mut(&amp;player).unwrap() += 1, Result::Draw =&gt; {} } } fn process_start(&amp;mut self, input: &amp;str) { let args: Vec&lt;_&gt; = input.split_whitespace().collect(); if !args.starts_with(&amp;["start"]) || args.len() &gt; 2 { eprintln!("Invalid command."); return; } if args.len() == 2 { self.first_player = match args[1].parse() { Ok(player) =&gt; player, Err(_) =&gt; { eprintln!("Invalid player."); return; } } } let mut game = Game::new(self.first_player); self.process_result(game.run()); self.first_player = self.first_player.toggle(); } } #[cfg(test)] mod tests { use super::*; #[test] fn session_new() { let session = Session::new(); assert_eq!(2, session.scores.len()); assert_eq!(Some(&amp;0), session.scores.get(&amp;Player::Nought)); assert_eq!(Some(&amp;0), session.scores.get(&amp;Player::Cross)); } } </code></pre> <p><strong>src/utility.rs</strong></p> <pre><code>pub fn clear_screen() { print!("\n\n"); } </code></pre> <p><strong>src/lib.rs</strong></p> <pre><code>mod board; mod game; mod session; mod utility; use session::Session; pub fn run() { let mut session = Session::new(); session.run(); } </code></pre> <p><strong>src/main.rs</strong></p> <pre><code>fn main() { tic_tac_toe::run(); } </code></pre> <p><strong>Cargo.toml</strong></p> <pre class="lang-none prettyprint-override"><code>[package] name = "tic-tac-toe" version = "0.1.0" authors = ["L. F."] edition = "2018" [dependencies] itertools = "0.9.0" </code></pre> <h1>Example Session</h1> <pre class="lang-none prettyprint-override"><code>Enter command: ('help' for help) help Supported commands: - exit: quit the session - help: display help screen - quit: quit the session - reset: reset scores - scoreboard: display scores - start: start a new game - start O/X: start a new game, with the specified first player Enter command: ('help' for help) scoreboard Scoreboard: - O: 0 - X: 0 Enter command: ('help' for help) start X +---+---+---+ | | | | +---+---+---+ | | | | +---+---+---+ | | | | +---+---+---+ [X] Enter your move: ('help' for help) 5 +---+---+---+ | | | | +---+---+---+ | | X | | +---+---+---+ | | | | +---+---+---+ [O] Enter your move: ('help' for help) 2 +---+---+---+ | | O | | +---+---+---+ | | X | | +---+---+---+ | | | | +---+---+---+ [X] Enter your move: ('help' for help) 4 +---+---+---+ | | O | | +---+---+---+ | X | X | | +---+---+---+ | | | | +---+---+---+ [O] Enter your move: ('help' for help) 6 +---+---+---+ | | O | | +---+---+---+ | X | X | O | +---+---+---+ | | | | +---+---+---+ [X] Enter your move: ('help' for help) 7 +---+---+---+ | | O | | +---+---+---+ | X | X | O | +---+---+---+ | X | | | +---+---+---+ [O] Enter your move: ('help' for help) resign +---+---+---+ | | O | | +---+---+---+ | X | X | O | +---+---+---+ | X | | | +---+---+---+ X wins by resignation. Enter command: ('help' for help) scoreboard Scoreboard: - X: 1 - O: 0 Enter command: ('help' for help) start +---+---+---+ | | | | +---+---+---+ | | | | +---+---+---+ | | | | +---+---+---+ [O] Enter your move: ('help' for help) 2 +---+---+---+ | | O | | +---+---+---+ | | | | +---+---+---+ | | | | +---+---+---+ [X] Enter your move: ('help' for help) 5 +---+---+---+ | | O | | +---+---+---+ | | X | | +---+---+---+ | | | | +---+---+---+ [O] Enter your move: ('help' for help) 4 +---+---+---+ | | O | | +---+---+---+ | O | X | | +---+---+---+ | | | | +---+---+---+ [X] Enter your move: ('help' for help) 1 +---+---+---+ | X | O | | +---+---+---+ | O | X | | +---+---+---+ | | | | +---+---+---+ [O] Enter your move: ('help' for help) 9 +---+---+---+ | X | O | | +---+---+---+ | O | X | | +---+---+---+ | | | O | +---+---+---+ [X] Enter your move: ('help' for help) 6 +---+---+---+ | X | O | | +---+---+---+ | O | X | X | +---+---+---+ | | | O | +---+---+---+ [O] Enter your move: ('help' for help) 8 +---+---+---+ | X | O | | +---+---+---+ | O | X | X | +---+---+---+ | | O | O | +---+---+---+ [X] Enter your move: ('help' for help) 7 +---+---+---+ | X | O | | +---+---+---+ | O | X | X | +---+---+---+ | X | O | O | +---+---+---+ [O] Enter your move: ('help' for help) 3 +---+---+---+ | X | O | O | +---+---+---+ | O | X | X | +---+---+---+ | X | O | O | +---+---+---+ It's a draw. Enter command: ('help' for help) scoreboard Scoreboard: - X: 1 - O: 0 Enter command: ('help' for help) quit </code></pre> <h1>Specific Concerns</h1> <ul> <li><p>I organized my code according to the <a href="https://doc.rust-lang.org/stable/book/ch12-03-improving-error-handling-and-modularity.html" rel="nofollow noreferrer">Refactoring to Improve Modularity and Error Handling</a> section of the book, but <strong>src/lib.rs</strong> and <strong>src/main.rs</strong> feel vacuous. Is this considered good design?</p></li> <li><p>Compared to other implementation of Tic Tac Toe, my implementation seems extremely complicated. Am I over-engineering everything? Do I need to adhere more to the KISS principle?</p></li> <li><p>I used <code>impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt;</code> as the return type of <code>Board::rows</code>, <code>Board::columns</code>, and <code>Board::diagonals</code>, because their implementations use different kinds of iterators. Is it OK to unify the return types like this?</p></li> <li><p>I used a bit of functional programming in <strong>game.rs</strong>, which I'm not very familiar with:</p> <pre><code>if let Err(message) = input .parse() .or_else(|_| Err("Invalid move".to_owned())) .and_then(|pos| Pos::new(pos).ok_or_else(|| "Invalid position".to_owned())) .and_then(|pos| { self.board.place(pos, player).or_else(|place_error| { Err(format!( "Position {} occupied by {}", place_error.pos, place_error.occupied_by )) }) }) </code></pre> <p>I took a lot of time to write this, and it seems elusive. Should I simplify it?</p></li> </ul> <p>Suggestions on all aspects of the code will be highly appreciated!</p> <p>(Cross-posted to the official Rust Programming Language Forum: <a href="https://users.rust-lang.org/t/rust-novices-tic-tac-toe/41999?u=l.f" rel="nofollow noreferrer">Rust Novice’s Tic Tac Toe</a>)</p>
[]
[ { "body": "<p>You've already done a good job cleaning things up, and running <code>clippy</code> puts you far ahead of other code I've seen. I'll be writing recommendations for other stuff you could add to make it nicer for the user, but is in no way necessary.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn new() -&gt; Session {\n Session {\n scores: [(Player::Nought, 0), (Player::Cross, 0)]\n .iter()\n .copied()\n .collect(),\n first_player: Session::DEFAULT_FIRST_PLAYER,\n }\n}\n</code></pre>\n\n<p>Just mentioning that <a href=\"https://docs.rs/maplit/1.0.2/maplit/macro.hashmap.html\" rel=\"nofollow noreferrer\"><code>maplit</code></a> has a macro to do this all in one. As I said earlier, there's no reason to do so, but it's an option.</p>\n\n<p>&nbsp;</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn run(&amp;mut self) {}\nfn display_help(&amp;self) {}\n</code></pre>\n\n<p>I'd refactor this to define the commands and their help messages in one, and then just iterate over them to print help and match input. You could do a <code>.map(str::len).max()</code> to get the largest command for right aligning. I'd also get rid of the extra space in between each entry.</p>\n\n<p>However, if you want an even cooler selection menu, I'd check out <a href=\"https://docs.rs/dialoguer/0.6.2/dialoguer/struct.Select.html\" rel=\"nofollow noreferrer\"><code>dialoguer</code></a>. It will allow you to select what you want with up and down arrows to select an option:\n<a href=\"https://i.stack.imgur.com/Uz5V8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Uz5V8.png\" alt=\"Selection prompt\"></a></p>\n\n<p>&nbsp;</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn rows(&amp;self) -&gt; impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt; {}\nfn columns(&amp;self) -&gt; impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt; {}\nfn diagonals(&amp;self) -&gt; impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt; {}\n</code></pre>\n\n<p>Those should return <code>Iterator</code>s over <code>Cell</code>s, not <code>&amp;Cell</code>s. Just throw a <code>.copied()</code> at the end. You can then remove <code>occupied_by</code>'s lifetime stuff.</p>\n\n<p>&nbsp;</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn wins(&amp;self, player: Player) -&gt; bool {\n self.rows().any(|row| occupied_by(row, player))\n || self.columns().any(|column| occupied_by(column, player))\n || self\n .diagonals()\n .any(|diagonal| occupied_by(diagonal, player))\n}\n</code></pre>\n\n<p>Instead of asking if someone won, ask <em>who</em> won. See if the row is <a href=\"https://docs.rs/itertools/0.9.0/itertools/trait.Itertools.html#method.all_equal\" rel=\"nofollow noreferrer\"><code>all_equal</code></a>, and if so, return that <code>Player</code>. You'll probably be using <a href=\"https://doc.rust-lang.org/std/option/enum.Option.html#method.or_else\" rel=\"nofollow noreferrer\"><code>Option::or_else</code></a> for that.</p>\n\n<p>&nbsp;</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Debug, Eq, PartialEq)]\npub struct PlaceError {\n pub pos: Pos,\n pub occupied_by: Player,\n}\n</code></pre>\n\n<p>Error types should implement <a href=\"https://doc.rust-lang.org/std/error/trait.Error.html\" rel=\"nofollow noreferrer\"><code>Error</code></a>.</p>\n\n<blockquote>\n <p>I organized my code according to the Refactoring to Improve Modularity and Error Handling section of the book, but src/lib.rs and src/main.rs feel vacuous. Is this considered good design?</p>\n</blockquote>\n\n<p>Yes, it allows people to use it in many different use cases. Someone could take it and then embed it in their own games program that bundles a bunch of games together.</p>\n\n<blockquote>\n <p>Am I over-engineering everything?</p>\n</blockquote>\n\n<p>Yeah you are. Tic-tac-toe, by definition, has two players. And you enforce that through the use of the <code>Player</code> enum. Then, you go and use a <code>HashMap</code> to store scores. There's no need to do this. Just store the X and O scores as two integers.</p>\n\n<blockquote>\n <p>I used <code>impl Iterator&lt;Item = impl Iterator&lt;Item = &amp;Cell&gt;&gt;</code> as the return type of <code>Board::rows</code>, <code>Board::columns</code>, and <code>Board::diagonals</code>, because their implementations use different kinds of iterators. Is it OK to unify the return types like this?</p>\n</blockquote>\n\n<p>Yes! Do things like that whenever you can.</p>\n\n<p>&nbsp;</p>\n\n<pre><code>if let Err(message) = input\n .parse()\n .or_else(|_| Err(\"Invalid move\".to_owned()))\n .and_then(|pos| Pos::new(pos).ok_or_else(|| \"Invalid position\".to_owned()))\n .and_then(|pos| {\n self.board.place(pos, player).or_else(|place_error| {\n Err(format!(\n \"Position {} occupied by {}\",\n place_error.pos, place_error.occupied_by\n ))\n })\n })\n</code></pre>\n\n<p>Replace <code>.or_else(|_| Err(\"Invalid move\".to_owned()))</code> with <code>.map_err(|_| \"Invalid move\".to_owned())</code>. Even better, use <a href=\"https://docs.rs/anyhow/1.0.28/anyhow/\" rel=\"nofollow noreferrer\"><code>anyhow</code></a>'s <code>.with_context()</code>, because <code>String</code>s aren't the best error type as they don't implement <a href=\"https://doc.rust-lang.org/std/error/trait.Error.html\" rel=\"nofollow noreferrer\"><code>Error</code></a>.</p>\n\n<p>Here's that part rewritten with <code>anyhow</code>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use anyhow::{bail, Context};\nif let Err(message) = input\n .parse()\n .context(\"Invalid move\")\n .and_then(|pos| Pos::new(pos).context(\"Invalid position\"))\n .and_then(|pos| self.board.place(pos, player).map_err(Into::into))\n{\n eprintln!(\"{:#}\", message);\n continue;\n}\n</code></pre>\n\n<p>That depends on implementing <code>Error</code> for <code>PlaceError</code>:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>impl fmt::Display for PlaceError {\n fn fmt(&amp;self, f: &amp;mut Formatter&lt;'_&gt;) -&gt; fmt::Result {\n write!(f, \"Position {} occupied by {}\", self.pos, self.occupied_by)\n }\n}\nimpl std::error::Error for PlaceError {}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T21:07:04.600", "Id": "241902", "ParentId": "241643", "Score": "2" } }, { "body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/241902/188857\">lights0123's excellent answer</a>:</p>\n\n<blockquote>\n<pre><code>fn is_vacant(self) -&gt; bool {\n match self {\n Cell::Occupied(_) =&gt; false,\n Cell::Vacant =&gt; true,\n }\n}\n</code></pre>\n</blockquote>\n\n<p>can be simplified with <a href=\"https://doc.rust-lang.org/std/macro.matches.html\" rel=\"nofollow noreferrer\"><code>matches!</code></a>:</p>\n\n<pre><code>fn is_vacant(self) -&gt; bool {\n matches!(self, Cell::Vacant)\n}\n</code></pre>\n\n<p>or, with <code>Eq</code>,</p>\n\n<pre><code>fn is_vacant(self) -&gt; bool {\n self == Cell::Vacant\n}\n</code></pre>\n\n<p><code>is_vacant</code> and <code>is_occupied</code> also probably make more sense as <code>pub</code> functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T13:03:11.663", "Id": "242002", "ParentId": "241643", "Score": "1" } } ]
{ "AcceptedAnswerId": "241902", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T05:52:34.353", "Id": "241643", "Score": "7", "Tags": [ "beginner", "game", "tic-tac-toe", "rust" ], "Title": "Rust Novice's Tic Tac Toe" }
241643
<p>A project to automate file organization in Linux using Python. I've always wanted to do this project way before I know how to code. Now that I did, I want to improve it even more.</p> <p>Used Language: Python.</p> <p>Compatible System: Linux.</p> <p>Used Modules: OS Module. </p> <p><strong>How it works</strong>: When you save/move/copy a file to one of the main directories(ex: Downloads, Documents...etc), it will automatically move it to its specified directory. It will use both extension and the 2/3 letter code that I provide at the beginning of the file name. It will run in the background once I open my computer.</p> <p>The program works only on files only, not directories (I don't usually have them and when I do, I want to do it personally).</p> <p><strong>Questions</strong>:</p> <ol> <li>How readable my code is?</li> <li>Are there any logical errors that I'm not aware of?</li> <li>How to improve it?</li> <li>Is there a better way to approach the problem? </li> <li>Overall, how would you rate it out of 10?</li> </ol> <p>Thank you in advance.</p> <hr> <p><strong>CODE</strong></p> <p>FileOrganizer.py:</p> <pre><code>#!/usr/bin/env python import os import time import os.path from random import randint from ExtraInfo import types, locations, docs, working_directories class FileOrganizer: def __init__(self, directory_path): self.directory_path = directory_path def path_maker(self, root, file_name): """(str, str) -&gt; str Returns a string containing the full path of a file, from root of the file and its name. &gt;&gt;&gt; path_maker("/home/hama/Downloads", "area.cpp") "/home/hama/Downloads/area.cpp" &gt;&gt;&gt; path_maker("/home/hama/Downloads/", "FuzzBuzz.py") "/home/hama/Downloads/FuzzBuzz.py" """ return os.path.join(root, file_name) def extension_finder(self, path): """(str) -&gt; str Takes in a string of full path of a file. If exists, returns a string of its extension, else returns False. &gt;&gt;&gt; extension_finder("/home/hama/Downloads/area.cpp") ".cpp" &gt;&gt;&gt; extension_finder("/home/hama/Downloads/FuzzBuzz.py") ".py" """ if os.path.exists(path): if os.path.isfile(path): return os.path.splitext(path)[1] return False def category_selector(self, extension): """(str) -&gt; str Takes in a string of an extension of a file. If not False, returns the category of the extension, else returns False. Precondition: The extension must be in one of the categories. &gt;&gt;&gt; category_selector(".cpp") "programming-files" &gt;&gt;&gt; category_selector(".mp4") "video" """ if extension != False: for category in types: if extension in types[category]: return category break return False def get_prefix(self, path): """(str) -&gt; str Takes in a string of full path of a file. If it is one of the doc categories returns the first 3 characters of name of the file, else 2. Precondition: A prefix of a specific directory should be provided at the beginning of the name of the file. &gt;&gt;&gt; get_prefix("/home/hama/Downloads/umaMath-week11.pdf") "uma" &gt;&gt;&gt; get_prefix("/home/hama/Downloads/pyFuzzBuzz.py") "py" """ prefix = os.path.basename(path) if self.category_selector(self.extension_finder(path)) not in docs: return prefix[:2] else: return prefix[:3] def get_original_name(self, path): """(str) -&gt; str Takes in a string of full path of a file. returns a string of the original file name without any prefix. Precondition: A prefix of a specific directory should be provided at the beginning of the name of the file. &gt;&gt;&gt; get_original_name("/home/hama/Downloads/umaMath-week11.pdf") "Math-week11.pdf" &gt;&gt;&gt; get_original_name("/home/hama/Downloads/pyFuzzBuzz.py") "FuzzBuzz.py" """ file_name = os.path.basename(path) if self.category_selector(self.extension_finder(path)) not in docs: return file_name[2:] else: return file_name[3:] def random_name_generator(self, path): """(str) -&gt; str Takes in a string of full path of a file. Generates a random integer at the end of the name of the file, the returns the new name. &gt;&gt;&gt; random_name_generator("/home/hama/Downloads/umaMath-week11.pdf") "Math-week11.pdf" &gt;&gt;&gt; random_name_generator("/home/hama/Downloads/pyFuzzBuzz.py") "FuzzBuzz.py" """ file_name = os.path.splitext(path)[0] extension = os.path.splitext(path)[1] return f"""{file_name}-{randint(1, 250) % randint(1, 250)}{extension}""" def copy(self, file_source, destination_root): """(str, str) -&gt; str Returns a string containing the full path of the newly moved file, from a full path of a file and root of the destination. Note: If a file with the same name already exists, a new name will be generated. &gt;&gt;&gt; copy("/home/hama/Downloads/area.cpp", "/home/hama/Codes/C++/") "/home/hama/Codes/C++/area.cpp" &gt;&gt;&gt; copy("/home/hama/Downloads/FuzzBuzz.py", "/home/hama/Codes/Python/") "/home/hama/Codes/Python/FuzzBuzz.py" """ if not os.path.exists(self.path_maker(destination_root, self.get_original_name(file_source))): file_name = os.path.basename(file_source) file_destination = self.path_maker( destination_root, self.get_original_name(file_source)) os.system(f"cp -pa {file_source} {file_destination}") return file_destination else: file_name = self.random_name_generator(self.path_maker( destination_root, self.get_original_name(file_source))) file_destination = self.path_maker(destination_root, file_name) os.system(f"cp -pa {file_source} {file_destination}") return file_destination # Activated on these directories paths = [FileOrganizer(f"{directory}") for directory in working_directories] while True: for path in paths: # Get the files and directories in the root directory. for root, directories, files in os.walk(path.directory_path): root, directories, files = root, directories, files break # List the files in the directory list_of_files = [] for file in files: list_of_files.append(path.path_maker(root, file)) # Loop through the files and copy each one of them. proccess = True for file in list_of_files: if proccess: current_file = file file_category = path.category_selector( path.extension_finder(current_file)) if file_category in locations: if locations[file_category].get(path.get_prefix(current_file)) != None: destination_root = locations[file_category].get( path.get_prefix(current_file)) # Check if there is a whitespace in the path, cause it cause infinite loop. if not (" " in current_file): new_file_destination = path.copy( current_file, destination_root) else: continue if os.path.exists(new_file_destination): os.remove(current_file) # Check if the file is moved and the proccess is done, otherwise wait until it is done. if not os.path.exists(current_file) and os.path.exists(new_file_destination): proccess = True else: proccess = False while not proccess: if not os.path.exists(current_file) and os.path.exists(new_file_destination): proccess = True else: proccess = False time.sleep(10) time.sleep(5) # By: Hama # Software Engineer to be. </code></pre> <hr> <p>ExtraInfo.py:</p> <pre><code>#!/usr/bin/env python types = { 'audio': ['.wpl', '.wma', '.wav', '.ogg', '.mpa', '.mp3', '.mid', '.midi', '.cda', '.aif'], 'database': ['.csv', '.dat', '.db', '.dbf', 'log', '.mdb', '.sav', 'sqlite', '.sql', '.tar', '.xml'], 'fonts': ['.fnt', '.fon', '.otf', '.ttf'], 'image': ['.ai', '.bmp', '.gif', '.ico', '.jpeg', '.jpg', '.png', '.ps', '.psd', '.svg', '.tif', '.tiff'], 'doc-presentation': ['.key', '.odp', '.pps', '.ppt', '.pptx'], 'internet': ['.asp', '.srt', '.aspx', '.cer', '.cfm', '.cgi', '.htm', '.jsp', '.part', '.rss', '.xhtml', '.torrent'], 'programming-files': ['.c', '.class', '.cpp', '.cs', '.h', '.java', '.pl', '.sh', '.swift', '.vb', '.php', '.html', '.css', '.js', '.py'], 'doc-spreadsheet': ['.ods', '.xls', '.xlsm', '.xlsx'], 'video': ['.3g2', '.3gp', '.avi', '.flv', '.h264', '.264', '.m4v', '.mkv', '.mov', '.mp4', '.mpg', '.mpeg', '.rm', '.swf', '.vob', '.wmv'], 'doc-word': ['.doc', '.docx', '.odt', '.rtf', '.tex', '.wpd'], 'doc-pdf': ['.pdf', '.epub', '.mobi'], 'text': ['.txt'] } locations = { 'audio': {'na': '/home/hama/Music/Others'}, 'database': {'na': '/home/hama/Documents/Others/Database'}, 'fonts': {'na': '/home/hama/Documents/Others/Fonts'}, 'internet': {'na': "/home/hama/Documents/Others/Internet-Related"}, 'image': {'my': '/home/hama/Pictures/Myself', 'ot': '/home/hama/Pictures/Others', 'wa': '/home/hama/Pictures/Wallpapers'}, 'video': {'my': '/home/hama/Videos/Myself', 'ot': '/home/hama/Videos/Others', 'mv': '/home/hama/Videos/Movies', 'tu': '/home/hama/Videos/Tutorials', 'se': '/home/hama/Videos/Series'}, 'programming-files': {'ot': '/home/hama/Codes/Others', 'wb': '/home/hama/Codes/Web', 'cp': '/home/hama/Codes/C++', 'py': '/home/hama/Codes/Python'}, 'doc-spreadsheet': {'bop': "/home/hama/Documents/Books/Programming-Books", 'bon': "/home/hama/Documents/Books/Novels", 'boo': "/home/hama/Documents/Books/Others", 'duc': "/home/hama/Documents/Documents/Spreadsheet", 'tmp': "/home/hama/Documents/Temp", 'uot': "/home/hama/Documents/UKH/Undergraduate-I/Other-Documents", 'uma': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Engineering-Mathematics-II", 'udl': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Introduction-to-Digital-Logic-&amp;-Electronics", 'usp': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Structured-Programming", 'uen': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/English-Composition-II"}, 'doc-presentation': {'bop': "/home/hama/Documents/Books/Programming-Books", 'bon': "/home/hama/Documents/Books/Novels", 'boo': "/home/hama/Documents/Books/Others", 'duc': "/home/hama/Documents/Documents/Presentations", 'tmp': "/home/hama/Documents/Temp", 'uot': "/home/hama/Documents/UKH/Undergraduate-I/Other-Documents", 'uma': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Engineering-Mathematics-II", 'udl': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Introduction-to-Digital-Logic-&amp;-Electronics", 'usp': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Structured-Programming", 'uen': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/English-Composition-II"}, 'doc-word': {'bop': "/home/hama/Documents/Books/Programming-Books", 'bon': "/home/hama/Documents/Books/Novels", 'boo': "/home/hama/Documents/Books/Others", 'duc': "/home/hama/Documents/Documents/Word", 'tmp': "/home/hama/Documents/Temp", 'uot': "/home/hama/Documents/UKH/Undergraduate-I/Other-Documents", 'uma': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Engineering-Mathematics-II", 'udl': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Introduction-to-Digital-Logic-&amp;-Electronics", 'usp': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Structured-Programming", 'uen': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/English-Composition-II"}, 'doc-pdf': {'bop': "/home/hama/Documents/Books/Programming-Books", 'bon': "/home/hama/Documents/Books/Novels", 'boo': "/home/hama/Documents/Books/Others", 'duc': "/home/hama/Documents/Documents/PDF", 'tmp': "/home/hama/Documents/Temp", 'uot': "/home/hama/Documents/UKH/Undergraduate-I/Other-Documents", 'uma': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Engineering-Mathematics-II", 'udl': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Introduction-to-Digital-Logic-&amp;-Electronics", 'usp': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/Structured-Programming", 'uen': "/home/hama/Documents/UKH/Undergraduate-I/Semester-II/English-Composition-II"}, 'text': {'tx': "/home/hama/Documents/Documents/PDF"} } docs = ['doc-spreadsheet', 'doc-presentation', 'doc-word', 'doc-pdf'] working_directories = ["/home/hama/Downloads/", "/home/hama/Documents/", "/home/hama/Codes/", "/home/hama/Desktop/", "/home/hama/Music/", "/home/hama/Pictures/", "/home/hama/Videos/"] </code></pre> <hr> <p>script.sh:</p> <pre><code>#!/bin/bash nohup python3 -u /home/hama/Codes/Python/FileAutomationV1.0/FileOrganizer.py &amp; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T08:50:36.243", "Id": "474314", "Score": "1", "body": "Just a note: if you want this to run in the background and react to file activity on Linux, look into inotify. There's at least one Python wrapper for it. It'll be both faster than the polling you're doing now, and use fewer resources when nothing has changed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T06:26:08.157", "Id": "474383", "Score": "0", "body": "Thank you, of course, it is one of the things that I needed." } ]
[ { "body": "<p>Addressing your questions:</p>\n\n<ol>\n<li><p>Readability</p>\n\n<p>The docstrings are generally fine. Not too long, not too short.</p>\n\n<ul>\n<li><p>Type hints:</p>\n\n<p>Your type hints should not go into the first line of the docstring. That line is reserved for a brief description of the function.\nType hints go into the function signature directly, for example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def path_maker(self, root: str, file_name: str) -&gt; str:\n \"\"\"Brief description.\n\n More.\n \"\"\"\n pass\n</code></pre></li>\n<li><p>PEP8:</p>\n\n<p>You followed conventions for the most part, which is good. Remaining points are:</p>\n\n<ul>\n<li>module names are <code>snake_case</code>, that is <code>ExtraInfo</code> should be <code>extra_info</code>. Note how at the time of writing, SE's syntax highlighting for Python flags your <code>ExtraInfo</code> module as a class instead.</li>\n<li>Globals are <code>UPPERCASE</code>, i.e. <code>types, locations, docs, working_directories</code> become <code>TYPES, LOCATIONS, DOCS, WORKING_DIRECTORIES</code>.</li>\n</ul></li>\n</ul></li>\n<li><p>Logical Errors</p>\n\n<ul>\n<li><p><code>break</code> is unreachable in <code>category_selector</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if extension != False:\n for category in types:\n if extension in types[category]:\n return category\n break\n return False\n</code></pre>\n\n<p>and <code>if extension != False</code> can just be <code>if extension</code>.</p></li>\n</ul></li>\n</ol>\n\n<p>3./4. How to improve it and a better approach</p>\n\n<p>Enter <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib</code></a>.\nThis module will be the single biggest improvement you can afford yourself in regards to your code.\nIt will get rid of the filthy string manipulations of <code>os.path</code>.\nPaths will be treated as proper objects and the code will probably run OS-agnostically.</p>\n\n<p>All of this assumes <code>from pathlib import Path</code>.</p>\n\n<p>Without actually rewriting the entire thing for you, here are a couple of examples for the achievable simplifications:</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>os.path.join(root, file_name)\n</code></pre>\n\n<p>is turned into a method on a <code>Path</code>-like object:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>root.join(file_name)\n</code></pre>\n\n<p>To borrow one of your doctests:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>root = Path(\"home\", \"hama\", \"Downloads\")\nfile_name = Path(\"area.cpp\")\nroot.joinpath(file_name)\n</code></pre>\n\n<p>will output</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>PosixPath('home/hama/Downloads/area.cpp')\n</code></pre>\n\n<p>on Unix.\nNote the <code>*args</code> approach I took in declaring <code>Path()</code>.\nNo slashes used.\nThis gets rid of confusion about forward- and backward-slashes, so your script can run on any OS you want.\nYou can also pass your normal strings, like <code>home/hama/Downloads/area.cpp</code>, or iterables of string like lists.\n<code>pathlib</code> understands a great deal of these.</p>\n\n<p><code>file_name</code> can even be whatever <em>path</em> you would want, not just a single name.\nThis includes relative parts, aka <code>..</code>.\nThen can then be resolved using the <code>resolve</code> method.</p>\n\n<hr>\n\n<p>In <code>extension_finder</code>,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if os.path.exists(path):\n if os.path.isfile(path):\n return os.path.splitext(path)[1]\n return False\n</code></pre>\n\n<p>can be simplified using</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>path.suffix\n</code></pre>\n\n<p>If <code>path</code> is a directory, the <code>.suffix</code> attribute will be an empty string.\nYou could then just rely on the empty string behaving falsy in boolean contexts.\nThe only thing you do with <code>extension_finder</code> is feeding it into <code>category_selector</code>.\nMore on that method later.</p>\n\n<p>Note that, given the method name, <code>extension_finder</code>, I feel like it is not that method's responsibility to check for file existence.\nYou be the judge of that.\nFor existence checking, <code>Path</code> objects have <code>is_file()</code>, which includes <code>exists()</code> functionality.</p>\n\n<p>Also note how for that function, you pass <code>self</code> and <code>path</code>, but do not use <code>self</code>.\nThis method is a prime candidate for a <code>staticmethod</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef extension_finder(path: Path) -&gt; str:\n \"\"\"Returns a path's file suffix.\n\n &gt;&gt;&gt; extension_finder(\"/home/hama/Downloads/area.cpp\")\n \".cpp\"\n &gt;&gt;&gt; extension_finder(\"/home/hama/Downloads/FuzzBuzz.py\")\n \".py\"\n \"\"\"\n\n return path.suffix\n</code></pre>\n\n<p>Now that this method was simplified so strongly through the excellent <code>pathlib</code> capabilities, it stands to question whether you want to keep it around at all.\nIn this form, I vote for no.</p>\n\n<hr>\n\n<p>The logic in <code>category_selector</code> could then just be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for category in types:\n if extension in types[category]:\n return category\n</code></pre>\n\n<p><code>extension</code> can now be an empty string, and as such is never found in <code>types[category]</code>. So that works as before.\nThe <code>return False</code> is now omitted.\nIf no match is found, the loop falls through and the function returns its default, <code>None</code>, which behaves like <code>False</code> in the boolean checks involving <code>category_selection</code>.</p>\n\n<p>Note that if you want to retain the current behaviour, i.e. returning a special object, not an empty string from <code>extension_finder</code> if no <code>extension</code> was found, I suggest using <code>None</code> over <code>False</code>.\nSame goes for <code>category_selector</code> here.\nA return of <code>None</code> for a category makes much more sense: no category was found.\nReturning <code>False</code> behaves similarly, but is less clear.</p>\n\n<hr>\n\n<p><code>get_prefix</code> and <code>get_original_name</code> are duplicate code, they are each other's opposite.\nReally, only one method is required.\nThis method could be called <code>split_custom_prefix</code> and return a tuple for you to unpack.\nIt can look like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>stem = path.stem\nif self.category_selector(self.extension_finder(path)) not in docs:\n split = 2\nelse:\n split = 3\n\nreturn stem[:split], stem[split:]\n</code></pre>\n\n<p>where <code>stem</code> is the filename without the <em>last</em> extension.</p>\n\n<p>Note that <code>2</code> and <code>3</code> are magic numbers.\nYou should find a way to avoid them, and codify their meaning into variables or logic with meaningful names.\nTowards this, among many other things, you could look to <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"noreferrer\"><code>enum</code></a>.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>for root, directories, files in os.walk(path.directory_path):\n root, directories, files = root, directories, files\n break\n</code></pre>\n\n<p>is an interesting one.\nYou do not use <code>directories</code> later on.\nName such variables <code>_</code>, as per convention, to signal that you have to accept an argument in that position but do not actually use it.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>root, directories, files = root, directories, files\n</code></pre>\n\n<p>Did you code this at 3 AM? ;)\nThis line can just be deleted.</p>\n\n<p>I am not aware of an <code>os.walk</code> equivalent in <code>pathlib</code>.\nIf you really require the former, here is a better approach:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>root, directories, files = next(os.walk(path.directory_path))\n</code></pre>\n\n<p>using <code>next</code> to trigger the <code>generator</code> object returned by <code>os.walk</code> once.</p>\n\n<hr>\n\n<p>I am a fan of inverting logic like this</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if not (\" \" in current_file):\n new_file_destination = path.copy(\n current_file, destination_root)\nelse:\n continue\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if \" \" in current_file:\n continue\nnew_file_destination = path.copy(current_file, destination_root)\n</code></pre>\n\n<p>Gets rid of <code>else</code> (indentation) and is easier to understand.</p>\n\n<hr>\n\n<p>Lastly, avoid globals.\nIt is strange for the class to access globals.\nYou can assign these as instance or class attributes, whatever fits better.\nFor your categories, all instances can share the information, so class attribute it is.\nLook into the <code>property</code> decorator to play around with this.\nFor example, this allows you to make the attributes immutable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T12:04:24.543", "Id": "474244", "Score": "2", "body": "Superb effort on explaining issues and promoting a different library for solution. Thank you for this detailed and comprehensive answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T19:55:01.553", "Id": "474273", "Score": "2", "body": "I cannot thank you enough for the effort on explaining those. It was my first project, I just needed a good review like that, I will definitely go over them and improve them. Regarding pathlib, I was not aware of that module which seems to make my journey easier. Again thank you for your help and time." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T09:24:01.757", "Id": "241649", "ParentId": "241644", "Score": "22" } }, { "body": "<p>I agree with all the points mentioned in the <a href=\"https://codereview.stackexchange.com/a/241649/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/223083/alex-povel\">@AlexPovel</a> and I am not going to repeat them.</p>\n\n<p>One thing that struck me as odd is that you have this class called <code>FileOrganizer</code>, but all it does is give you convenience functions for dealing with paths. What it explicitly does <em>not</em> do is organize your files! That is left as stand-alone code outside of the class.</p>\n\n<p>I would make the moving code part of the class. This means that your global file type data structures should probably be class attributes. Afterwards you could do:</p>\n\n<pre><code>file_organizers = [FileOrganizer(path) for path in paths]\nwhile True:\n for file_organizer in file_organizers:\n file_organizer.organize()\n time.sleep(5)\n</code></pre>\n\n<p>Currently you are also running a loop until the file copying has finished, checking every 10 seconds if the file is there yet. I would either go <a href=\"https://docs.python.org/3/library/asyncio-subprocess.html\" rel=\"nofollow noreferrer\">fully asynchronous</a> (and keep track of files currently being copied) or use <a href=\"https://docs.python.org/3/library/subprocess.html\" rel=\"nofollow noreferrer\"><code>subprocess.run</code></a> (Python 3.5+), which will only return once the command has completed.</p>\n\n<p>The method could look something like this:</p>\n\n<pre><code>import subprocess\n\nclass FileOrganizer:\n\n ...\n\n def move(self, file, destination):\n ... # get the right names\n subprocess.run([\"cp\", \"-pa\", file, destination])\n if os.path.exists(destination):\n os.remove(file)\n else:\n print(f\"Moving {file} failed.\")\n return destination\n\n def organize(self):\n # Get the files and directories in the root directory.\n root, directories, files = next(os.walk(self.directory_path))\n root = Path(root)\n # List the files in the directory\n files = (root.joinpath(file) for file in files if \" \" not in file)\n\n # Loop through the files and copy each one of them.\n for file in files:\n file_category = self.category_selector(file.suffix)\n location = self.locations.get(file_category)\n if location is None:\n print(\"{file_category} is not a valid category\")\n continue\n prefix = self.get_prefix(file)\n destination_root = location.get(prefix)\n if destination_root is None:\n print(f\"{prefix} is not a valid prefix\")\n continue\n self.move(file, destination_root)\n</code></pre>\n\n<p>Note that I added some debug output so it gets easier to see what the script is doing. You might want to move that to a log file using the <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> module eventually.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T19:59:12.837", "Id": "474275", "Score": "1", "body": "Thank you for your suggestion. Yes, I had a big problem dealing with that, I looked for it but couldn't find a proper way that I would understand. Thus, I didn't look over that enough. Since I understand yours very well, I will fix that as well. Thank you again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T13:02:19.207", "Id": "241657", "ParentId": "241644", "Score": "7" } }, { "body": "<p>Aside from what others have already said, the main thing that jumps out at me is that you're polling for changes, which is wasteful.</p>\n\n<p>On Linux, the proper solution is to use some bindings to the <code>inotify</code> API so you can receive <code>IN_CLOSE_WRITE</code> and <code>IN_MOVED_TO</code> events on the directories you're watching. That way, your monitor process can sleep indefinitely and the kernel will wake it when there's work to do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T20:01:22.537", "Id": "474276", "Score": "0", "body": "Great information that I just needed. Yes, I was worked up about the program crashes due to its infinite loop and always running. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T05:32:26.653", "Id": "474296", "Score": "1", "body": "This answer could be improved with a link to the inotify module: https://pypi.org/project/inotify/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T06:24:25.883", "Id": "474382", "Score": "0", "body": "Thank you, it will be helpful for sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:11:57.413", "Id": "474467", "Score": "0", "body": "@DigitalTrauma I would have, but I remembered that, last time I checked, inotify bindings were in a bit of a transitional state and I didn't have time to track down which one was the current recommended one." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:23:33.177", "Id": "241676", "ParentId": "241644", "Score": "8" } } ]
{ "AcceptedAnswerId": "241649", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T07:20:38.870", "Id": "241644", "Score": "8", "Tags": [ "python", "python-3.x", "linux", "automation" ], "Title": "File Automation Using Python On Linux" }
241644
<h1>Generating documentation for VBA code</h1> <p>The goal of this exercise to is create an application which can read module files created in VBA project and generate markdown documentation for them.</p> <h2>Key features</h2> <ul> <li>User should be able to pass <strong>standard module (bas)</strong> based on which markdown file is created.</li> </ul> <h2>Limitations</h2> <ul> <li><p>There are more more types than just <strong>standard module (bas)</strong> in VBA project. For now, they are not supported.</p></li> <li><p>Entry point of application (<code>main</code>) is yet not defined.</p></li> </ul> <h2>Project structure</h2> <pre><code>vba-doc-py │ module_parser.py │ module_parser_tests.py │ method_parser.py │ method_parser_tests.py │ module_doc.py │ module_doc_tests.py </code></pre> <h2>Code</h2> <p><strong>module_parser.py</strong></p> <pre class="lang-py prettyprint-override"><code>import module_doc class ModuleParser(): """This parser is responsible for extracting information from raw VBA code which later, can be used for generating markdown document.""" def make(self, code): lines = code.split('\n') for ln in lines: if 'Attribute VB_Name' in ln: dbl_qut = ln.index('\"') + 1 name = ln[dbl_qut: ln.rindex('\"')] doc = module_doc.ModuleDoc(name) elif 'Public Sub' in ln or 'Public Function' in ln: doc.addMethod(self.__get_method_name(ln), self.__get_args(ln)) return doc.build() def __get_method_name(self, ln): method_type = 'Sub' if ' Sub ' in ln else 'Function' name_start = len(f'Public {method_type} ') open_parenthesis = ln.index('(') return ln[name_start:open_parenthesis] def __get_args(self, ln): open_parentheses = ln.index('(') close_parentheses = ln.rindex(')') if self.__no_args(open_parentheses, close_parentheses): return '' # Remove surrounding parentheses args = ln[open_parentheses + 1: close_parentheses] args_list = args.split(', ') output = [] AS_KEYWORD = ' As ' for item in args_list: as_keyword_start = item.index(AS_KEYWORD) arg_type = item[as_keyword_start + len(AS_KEYWORD):] output.append(arg_type) return output def __no_args(self, open_parentheses, close_parentheses): return open_parentheses + 1 == close_parentheses def __remove(self, text, start_index, count): """Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.""" return text[:start_index] + text[start_index + count:] </code></pre> <p><strong>method_parser.py</strong></p> <pre class="lang-py prettyprint-override"><code>class MethodParser(): """Class responsible for parsing VBA methods (both Sub and Function) and turning them into specified markdown format.""" def make(self, code): return f'# {self.__get_method_name(code)}\n\n```vb\n{code}\n```' def __get_method_name(self, ln): method_type = 'Sub' if ' Sub ' in ln else 'Function' name_start = len(f'Public {method_type} ') open_parentheses = ln.index('(') return ln[name_start:open_parentheses] </code></pre> <p><strong>module_doc.py</strong></p> <pre class="lang-py prettyprint-override"><code>class ModuleDoc(): """Represents markdown document on the module level.""" def __init__(self, name): self.name = name self.subs = {} def addMethod(self, name, args): self.subs.update({name: args}) def build(self): output = '# ' + self.name + ' module\n\n' if len(self.subs) &gt; 0: output += ('# Methods\n\n' '|Name|Description|\n' '|-|-|\n') for name in self.subs: output += f'|[{name} ({self.__format_args(self.subs[name])})](./{name}.md)||\n' return output def __format_args(self, args): if isinstance(args, list): return ', '.join(args) else: return args </code></pre> <h2>Conclusion</h2> <p>I'm working mainly with C#/VBA and that is mostly a style which I apply here, because it is the style which I know best. Also I'm aware that Python most definitely have it's own <strong>style</strong> which I'm looking forward to explore.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T09:21:40.923", "Id": "241648", "Score": "2", "Tags": [ "python", "python-3.x", "vba", "markdown" ], "Title": "Generating markdown documentation for VBA code" }
241648
<p>I need to write a function that accepts a function as argument, if this function is new, adds it to an array otherwise do not add it. </p> <p>I assigned a property a my function <em>StoreFunctions</em> and use it as the private storage space, is this an acceptable way to do it? I tested it with function <code>c</code> and <code>d</code>, I did get the correct results back.</p> <pre><code>function StoreFunctions(func) { if (StoreFunctions.funcArray.includes(func)) return 'function already added'; else { StoreFunctions.funcArray.push(func); return 'a new function is added';} } StoreFunctions.funcArray = []; function c() {return 1}; function d() {return 2}; console.log(StoreFunctions(c)); console.log(StoreFunctions(d)); console.log(StoreFunctions(c)); </code></pre>
[]
[ { "body": "<p>It <em>works</em>, but it's weird, and the variable intended for use only inside the function isn't private, which is potentially confusing and potentially unsafe.</p>\n\n<p>Functions, being objects, can have arbitrary key-value pairs assigned to them, so you <em>can</em> put properties on it like you're doing. It's not unheard of. Usually, this sort of thing is reserved for <strong>static</strong> properties and methods which are <em>associated</em> with the class/function, but don't make sense as <em>instance</em> methods, and are meant for use by outside consumers. For a trivial example, the below function exposes a <code>canEat</code> property:</p>\n\n<pre><code>function Person() {\n}\nPerson.canEat = ['Apple', 'Banana', 'Carrot'];\nPerson.prototype.eat = function(food) {\n if (!Person.includes(food)) {\n throw new Error('Invalid food');\n }\n // do stuff depending on what argument is\n}\n</code></pre>\n\n<p>Maybe it'll change over time, so users of <code>Person</code> can check <code>Person.canEat</code> before calling <code>eat</code>. But this is all intended for <em>users</em> of Person.</p>\n\n<p>Another example of a useful static property on a function intended for outside use is <code>Number.MAX_SAFE_INTEGER</code>.</p>\n\n<p>But if a property isn't meant to be used outside of the function, putting it on the function itself both sabotages the variable's privacy <em>and</em> is confusing (because a reader may well expect that a property accessible anywhere may be intended for use anywhere, which isn't what you mean).</p>\n\n<p>If you want the function to be able to store data persistently and for itself only, you can use a closure instead. Here's one option:</p>\n\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 storeFunctions = (() =&gt; {\n const funcArray = [];\n return (func) =&gt; {\n if (funcArray.includes(func))\n return 'function already added';\n else {\n funcArray.push(func);\n return 'a new function is added';\n }\n }\n})();\n\nfunction c() { return 1 };\nfunction d() { return 2 };\nconsole.log(storeFunctions(c));\nconsole.log(storeFunctions(d));\nconsole.log(storeFunctions(c));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Professional Javascript often uses <em>modules</em> to organize code, in which case the IIFE is not needed - instead, have the module that defines the <code>storeFunctions</code> declare an array <em>private to that module</em>, and export the function:</p>\n\n<pre><code>const funcArray = [];\nexport const storeFunctions = (func) =&gt; {\n if (funcArray.includes(func))\n return 'function already added';\n else {\n funcArray.push(func);\n return 'a new function is added';\n }\n};\n</code></pre>\n\n<pre><code>import { storeFunctions } from './storeFunctions';\nfunction c() {return 1};\nfunction d() {return 2};\nconsole.log(StoreFunctions(c));\nconsole.log(StoreFunctions(d));\nconsole.log(StoreFunctions(c));\n</code></pre>\n\n<p>The above is what I'd prefer. For any non-trivial script, modules make organizing code much easier.</p>\n\n<p>Another note on your code - unless you need a collection with rearrangeable indicies, rather than using an array and iterating over it with <code>.includes</code>, it would probably be more appropriate to use a Set, which is a generic collection of values and whose lookup time with <code>.has</code> is an order of complexity faster than an array's <code>.includes</code>.</p>\n\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 storeFunctions = (() =&gt; {\n const funcSet = new Set();\n return (func) =&gt; {\n if (funcSet.has(func))\n return 'function already added';\n else {\n funcSet.add(func);\n return 'a new function is added';\n }\n }\n})();\n\nfunction c() { return 1 };\nfunction d() { return 2 };\nconsole.log(storeFunctions(c));\nconsole.log(storeFunctions(d));\nconsole.log(storeFunctions(c));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T22:15:31.300", "Id": "474286", "Score": "0", "body": "A well-detailed answer, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T11:47:14.300", "Id": "241653", "ParentId": "241651", "Score": "1" } } ]
{ "AcceptedAnswerId": "241653", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T10:33:25.233", "Id": "241651", "Score": "0", "Tags": [ "javascript" ], "Title": "Is it acceptable to use a function property as its own private storage?" }
241651
<p>Goal: find total number of elements in a nested iterable of arbitrary depth. My shot:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def deeplen(item, iterables=(list, tuple, dict, np.ndarray)): # return 1 and terminate recursion when `item` is no longer iterable if isinstance(item, iterables): if isinstance(item, dict): item = item.values() return sum(deeplen(subitem) for subitem in item) else: return 1 </code></pre> <p>Naturally there are more iterables than shown, but these cover the vast majority of use cases; more can be added, with per-istance treatment if needed (e.g. <code>dict</code>), so the approach is <em>extendable</em>.</p> <p>Any better approaches? Can be in: (1) performance; (2) readability; (3) generality (more iterables)</p> <hr> <p><strong>Performance test</strong>:</p> <pre class="lang-py prettyprint-override"><code>def test_deeplen(iters=200): def _make_bignest(): arrays = [np.random.randn(100, 100), np.random.uniform(30, 40, 10)] lists = [[1, 2, '3', '4', 5, [6, 7]] * 555, {'a': 1, 'b': arrays[0]}] dicts = {'x': [1, {2: [3, 4]}, [5, '6', {'7': 8}] * 99] * 55, 'b': [{'a': 5, 'b': 3}] * 333, ('k', 'g'): (5, 9, [1, 2])} tuples = (1, (2, {3: np.array([4., 5.])}, (6, 7, 8, 9) * 21) * 99, (10, (11,) * 5) * 666) return {'arrays': arrays, 'lists': lists, 'dicts': dicts, 'tuples': tuples} def _print_report(bignest, t0): t = time() - t0 print("{:.5f} / iter ({} iter avg, total time: {:.3f}); sizes:".format( t / iters, iters, t)) print("bignest:", deeplen(bignest)) print(("{} {}\n" * len(bignest)).format( *[x for k, v in bignest.items() for x in ((k + ':').ljust(8), deeplen(v))])) bignest = _make_bignest() t0 = time() for _ in range(iters): deeplen(bignest) _print_report(bignest, t0) </code></pre> <pre class="lang-py prettyprint-override"><code>&gt;&gt; test_deeplen(1000) 0.02379 / iter (1000 iter avg, total time: 23.786); sizes: bignest: 53676 arrays: 10010 lists: 13886 dicts: 17170 tuples: 12610 </code></pre>
[]
[ { "body": "<p>A possible solution can be implemented in terms of two different paradigms.</p>\n\n<h2>Look Before You Leap (LBYL)</h2>\n\n<p>You can test if an object supports a certain <em>interface</em> using <code>collections.abc</code>, where <code>abc</code> stands for Abstract Base Classes.\nThe module provides the <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable\" rel=\"noreferrer\"><code>Iterable</code> class</a>.\nIf an object is an instance of that class, it can be considered iterable.\nHow the object handles this under the hood, we do not care for.\nThis can be used to test for iterables.</p>\n\n<p>Secondly, there is <code>Mapping</code> to detect types like <code>dict</code>s.\nThis can go where you currently test for <code>isinstance(item, dict)</code>.</p>\n\n<p>Checking if an object supports what you plan on doing to or with it is the <em>Look Before You Leap</em> style.\nUnfortunately, this approach is slower than before.\nHowever, the loss in performance is justifiable in the face of the gained value.\nYou can now support <em>any</em> iterable anyone can throw at you, and shift the responsibility of handling the actual iteration to them.\nOtherwise, you would have to add every conceivable iterable to <code>iterables=(..)</code>.\nYou already noticed that this is not feasible.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections.abc import Iterable, Mapping\n\ndef deeplen_lbyl(item):\n \"\"\"Returns the number of non-iterable items in arbitrarily nested iterators.\n \"\"\"\n if isinstance(item, Iterable) and not isinstance(item, str):\n if isinstance(item, Mapping):\n item = item.values()\n return sum(deeplen_lbyl(subitem) for subitem in item)\n else:\n return 1\n</code></pre>\n\n<h2>Easier to ask for forgiveness than permission (EAFP)</h2>\n\n<p>This is an alternative approach, relying on just going ahead and letting things fail, then catching expected errors and handling them.\nIt is often considered the Pythonic one.\nIts large advantage is its flexibility.\nIf there is a large number of both allowed and disallowed situations, adding all allowed situations to some sort of whitelist (like <code>isinstance</code>) can be tedious.\nThis is where the ABCs helped in the <em>LBYL</em> style above.\nThe <em>EAFP</em> style does not rely on ABCs or probing for interfaces.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def deeplen_eafp(item):\n \"\"\"Returns the number of non-iterable items in arbitrarily nested iterators.\n \"\"\"\n try:\n iter(item)\n except TypeError:\n return 1\n\n if isinstance(item, str):\n return 1\n\n try:\n item = item.values()\n except AttributeError:\n pass\n\n return sum(deeplen_eafp(subitem) for subitem in item)\n</code></pre>\n\n<p>In the <code>Iterable</code> class description, it says that calling <code>iter</code> is the only save way of detecting an iterable.\nSo this is what is done here.\nNote that there is also <a href=\"https://stackoverflow.com/a/61139278/11477374\">a different viewpoint to that</a>.</p>\n\n<p><code>TypeError</code> is raised if the object did not like being iterated over.</p>\n\n<p>Now, <code>str</code> passes both <code>isinstance</code> and <code>iter</code> checks, so the guard clause is needed here, too.\nIt is required to avoid infinite recursion, since <code>str</code> would remain infinitely iterable.</p>\n\n<p>If the <code>values()</code> attribute is not available, a <code>Mapping</code>-like object is not present.\nAccordingly, <code>AttributeError</code> is raised, and we keep the original <code>item</code>.</p>\n\n<h2>Performance</h2>\n\n<p>Python has, unlike other languages, cheap error handling. A <code>try</code> block is cheap if it does not raise an exception.\nHowever, the more we run into walls blindly, the more errors are thrown out the behind in the <code>try</code> blocks.\nThis is slowing that approach down.</p>\n\n<hr>\n\n<p>I did not touch your <code>test_deeplen</code> function.\nUsing it, all three (yours and the two presented here) functions return the same output.</p>\n\n<p><code>deeplen_lbyl</code> and <code>deeplen_eafp</code> are equally slower than your function, in the ballpark:</p>\n\n<pre><code>deeplen_lbyl:\n 0.02510 / iter (10 iter avg, total time: 0.251); sizes:\n bignest: 53676\n arrays: 10010\n lists: 13886\n dicts: 17170\n tuples: 12610\n\ndeeplen_eafp:\n 0.02497 / iter (10 iter avg, total time: 0.250); sizes:\n bignest: 53676\n arrays: 10010\n lists: 13886\n dicts: 17170\n tuples: 12610\n\ndeeplen from question:\n 0.01695 / iter (10 iter avg, total time: 0.170); sizes:\n bignest: 53676\n arrays: 10010\n lists: 13886\n dicts: 17170\n tuples: 12610\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T20:13:24.917", "Id": "474364", "Score": "1", "body": "Quality answer. Follow-up: how do we know if \"any\" iterable will be accounted for correctly? Can't one make a custom type that is like `dict` in that, when iterated over, doesn't return 'values' - but unlike `dict`, values can't be accessed via `.values()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T10:40:08.567", "Id": "474393", "Score": "0", "body": "Good question, I had similar concerns. I believe that the test for `isinstance(..., Mapping)` is not passed if `values` is not available in the first place. Having a mapping but not implementing the callable `values` attribute seems strange. I urge you to ask a new question about this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T01:28:47.977", "Id": "475850", "Score": "1", "body": "From a real use-case: arrays can be quite expensive for all our `deeplen` versions; the following gives a big speedup: `if isinstance(item, np.ndarray): return item.size`. (P.S. I ultimately went with your LBYL, for its clarity and generality)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-20T09:13:12.650", "Id": "476109", "Score": "0", "body": "Real use-case 2.0: `eafp` is more reliable via `try-iter` - the small performance difference is of no consequence majority time anyway. Pretty sure the final winner is **deeplen_eafp + numpy check**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T02:34:09.217", "Id": "476232", "Score": "0", "body": "Could you rerun tests with `iters=1000`? I just noticed you used `=10`, which is quite small and may have yielded misleading results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:30:48.567", "Id": "476432", "Score": "1", "body": "@OverLordGoldDragon On my machine, running it with `1000` does not change anything, and the relations between the three remain the same, see also here: https://repl.it/repls/SevereHonorableRelationalmodel" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T14:01:50.027", "Id": "476439", "Score": "1", "body": "Strange, I've even benchmarked on a [Colab VM](https://colab.research.google.com/) CPU - guess 'vanilla' does win on some machines after all. I originally included `_deeplen_fast` and `_deeplen_full`, former accessible via `deeplen(fast=True)` but dropped it after new benchmarks - guess it's an option worth noting." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T13:52:12.143", "Id": "241660", "ParentId": "241654", "Score": "5" } }, { "body": "<p>Below is a faster and more general algorithm than in posted alternatives:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nfrom collections.abc import Mapping\n\ndef deeplen(item):\n if isinstance(item, np.ndarray):\n return item.size\n try:\n list(iter(item))\n except:\n return 1\n if isinstance(item, str):\n return 1\n if isinstance(item, Mapping):\n item = item.values()\n return sum(deeplen(subitem) for subitem in item)\n</code></pre>\n\n<p><strong>Advantages</strong>:</p>\n\n<ol>\n<li><p><em>Speed</em>: <code>.size</code> for Numpy arrays is much faster than recursive-iterative <code>len</code>. Also, there isn't much performance difference between the original <code>deeplen</code> and current <code>deeplen</code> (if excluding <code>.size</code> advantage), but <code>deeplen_lbyl</code> is slowest by 40% (tested w/ <code>iters=1000</code> on <code>bignest</code>).</p></li>\n<li><p><em>Generality</em>: neither <code>isinstance(, Iterable)</code> nor <code>try-iter</code> are sufficient to determine whether <code>item</code> is 'truly' iterable; some objects (e.g. TensorFlow <a href=\"https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py#L266\" rel=\"nofollow noreferrer\"><code>Tensor</code></a>) support creating <em>generators</em> but not <em>consuming</em> them without <a href=\"https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/map_fn.py#L47\" rel=\"nofollow noreferrer\">dedicated methods</a> for iterating. It does become a question of whose <code>len</code> we're measuring, since an arbitrarily-sized <code>Tensor</code> will count as <code>1</code> per above algorithm - if this isn't desired, then object-specific treatment is required.</p></li>\n</ol>\n\n<p>Credit to @AlexPovel for originally suggesting <code>try-iter</code> and <code>isinstance(, Mapping)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:35:17.357", "Id": "476433", "Score": "1", "body": "Interesting! I know nothing of `Tensor`, but it not responding to the `iter` built-in is strange (as it's [\"the only reliable way to determine whether an object is iterable\"](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable). But there's perhaps a reason I am unaware of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-22T13:59:42.820", "Id": "476438", "Score": "1", "body": "@AlexPovel Update #3 [here](https://codereview.stackexchange.com/questions/242369/deep-map-python) gives some explanation; TL;DR - just like `list` and `dict` have different \"access specifiers\" (`__getitem__`), a `Tensor` has one of its own that has no Pythonic equivalent (not bracket-able), requiring a method. `list(iter())` ensures `item` is _Python-iterable_ - and if it isn't, `deeplen` will have trouble." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T02:33:11.443", "Id": "242679", "ParentId": "241654", "Score": "2" } } ]
{ "AcceptedAnswerId": "241660", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T11:51:35.430", "Id": "241654", "Score": "3", "Tags": [ "python", "python-3.x", "iterator" ], "Title": "Deep len, Python" }
241654
<p>I have made a text-based Snakes and Ladders game in Java with only simple concepts like Scanner and Arrays. I don't know how to use different methods or to use inheritance to make the code shorter. Can anyone please advise me on how to write it efficiently?</p> <p>Some specific things I want to do are:</p> <ol> <li>You will notice that the code for printing the board is repeated a lot. Can that be made into a method to avoid the repetition?</li> <li>After each player's turn, I am using a very long if-else-if ladder to check if the player has landed on a snake. Can that long ladder be shortened?</li> </ol> <p>I have attached an image of the output:</p> <p><a href="https://i.stack.imgur.com/ItAhi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ItAhi.png" alt="Output"></a></p> <pre><code>import java.util.Scanner; public class Project { public static void board() { /**This is a game of 4-player Snakes_&amp;_Ladders which uses * Arrays to construct the board. For the dice, Math.random() * has been used. */ Scanner sc=new Scanner(System.in); char retry='y'; System.out.println("Enter \'Start\' to start the game:"); do { String start=sc.nextLine(); System.out.println("The game will start in :"); for(short x=5; x&gt;=1; x--) { System.out.println(x); for(long i=-9999999; i&lt;=9999999; i++);//To add a delay } System.out.println("\f---------------------------------"); System.out.println("Welcome to Java Snakes &amp; Ladders!"); System.out.println("---------------------------------\n"); System.out.println("Rules:"); System.out.println("--&gt; This is similar to the Snakes &amp; Ladders game played by many people."); System.out.println("--&gt; This is a four-player game."); System.out.println("--&gt; There will be a 10x10 board containing some snakes and ladders."); System.out.println("--&gt; The players will take turns to roll a dice."); System.out.println("--&gt; The player will move ahead according to the number rolled."); System.out.println("--&gt; If a player lands on a ladder, he will be able to climb it and go ahead!!"); System.out.println("--&gt; But if a player lands on a snake, he will have to go back!!"); System.out.println("--&gt; The game will go on until a player reaches 100.\n"); System.out.println("Enter Player 1's name:"); String player1=sc.nextLine();//Input player 1's name System.out.println("Enter Player 2's name:"); String player2=sc.nextLine();//Input player 2's name System.out.println("Enter Player 3's name:"); String player3=sc.nextLine();//Input player 3's name System.out.println("Enter Player 4's name:"); String player4=sc.nextLine();//Input player 4's name System.out.println("\f"); int[] board=new int[100];//To store the numbers of the boxes String[] p1=new String[100];//To store player-1's position String[] p2=new String[100];//To store player-2's position String[] p3=new String[100];//To store player-3's position String[] p4=new String[100];//To store player-4's position String[] SnakesnLadders=new String[101];//To store the Snakes and Ladders int order=0;//To specify if the boxes in the row are descending or ascending int t=99;//Index of the numbers in board array int s_and_l=99;//Index of SnakesnLadders array int p1_val=0;//Position of player-1 int p2_val=0;//Position of player-2 int p3_val=0;//Position of player-3 int p4_val=0;//Position of player-4 for (int fill=99; fill&gt;=0; fill--) { //This loop is for filling all the arrays SnakesnLadders[fill]=" "; //Snakes if(fill==99-1)SnakesnLadders[fill]=" Slip to 2"; if(fill==91-1)SnakesnLadders[fill]=" Slip to 75"; if(fill==87-1)SnakesnLadders[fill]=" Slip to 24"; if(fill==49-1)SnakesnLadders[fill]=" Slip to 23"; if(fill==17-1)SnakesnLadders[fill]=" Slip to 3"; if(fill==51-1)SnakesnLadders[fill]=" Slip to 47"; if(fill==37-1)SnakesnLadders[fill]=" Slip to 29"; //Ladders if(fill==19-1)SnakesnLadders[fill]=" Climb to 80"; if(fill==4-1)SnakesnLadders[fill]=" Climb to 14"; if(fill==55-1)SnakesnLadders[fill]=" Climb to 63"; if(fill==33-1)SnakesnLadders[fill]=" Climb to 83"; if(fill==82-1)SnakesnLadders[fill]=" Climb to 97"; if(fill==16-1)SnakesnLadders[fill]=" Climb to 25"; if(fill==9-1)SnakesnLadders[fill]=" Climb to 39"; p1[fill]=""; p2[fill]=""; p3[fill]=""; p4[fill]=""; board[fill]=fill+1;//Numbers of boxes } System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++) { //This loop is for the rows /*The below if-elseif blocks are to check if *the row numbers are in ascending or descending order. */ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++) { System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++) { if(order==0) { if(boardj==1) { if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1) { if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } for(long chance=1; chance&gt;=0; chance++) { //Main loop which runs until a player reaches 100 t=99; s_and_l=99; order=0; if((chance-1)%4==0) { //Player 1's block System.out.println("It is "+player1+"\'s turn:"); System.out.println("Enter \'Roll\' to roll the dice:"); char pause=sc.next().charAt(0); System.out.println("\f"); int dice=(int)(Math.random()*6+1);//To generate a number betwween 1 &amp; 6 p1_val=p1_val+dice; if(p1_val==100) { System.out.println("=================="); System.out.println(player1+" WON!!"); System.out.println("=================="); System.out.println("It was a great game!!"); break; } else if(p1_val&gt;100) { System.out.println("You rolled more than you require to reach 100!!"); System.out.println("You can't move ahead!!"); p1_val=p1_val-dice; } for (int pfill=0; pfill&lt;100; pfill++) { p1[pfill]=" ";//To refill the board } p1[p1_val-1]=" \u278A"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++) { if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++) { System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++) { if(order==0) { if(boardj==1) { if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } System.out.println("Roll = "+dice); if(SnakesnLadders[p1_val-1]!=" ") { //Snakes if(p1_val==99) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 2!!"); p1_val=2; } if(p1_val==91) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 75!!"); p1_val=75; } if(p1_val==87) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 24!!"); p1_val=24; } if(p1_val==51) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 47!!"); p1_val=47; } if(p1_val==49) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 23!!"); p1_val=23; } if(p1_val==37) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 29!!"); p1_val=29; } if(p1_val==17) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 3!!"); p1_val=3; } //Ladders if(p1_val==82) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 97!!"); p1_val=97; } if(p1_val==55) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 63!!"); p1_val=63; } if(p1_val==33) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 83!!"); p1_val=83; } if(p1_val==19) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 80!!"); p1_val=80; } if(p1_val==16) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 25!!"); p1_val=25; } if(p1_val==9) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 39!!"); p1_val=39; } if(p1_val==4) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 14!!"); p1_val=14; } t=99; s_and_l=99; order=0; for(long i=-99099999; i&lt;=9999999; i++); System.out.print("\f"); for (int pfill=0; pfill&lt;100; pfill++){ p1[pfill]=" "; } p1[p1_val-1]=" \u278A"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } } } else if(chance%2==0 &amp;&amp; chance%4!=0) { System.out.println("It is "+player2+"\'s turn:"); System.out.println("Enter \'Roll\' to roll the dice:"); char pause=sc.next().charAt(0); System.out.println("\f"); int dice=(int)(Math. random()*6+1); p2_val=p2_val+dice; if(p2_val==100) { System.out.println("=================="); System.out.println(player2+" WON!!"); System.out.println("=================="); System.out.println("It was a great game!!"); break; } else if(p2_val&gt;100) { System.out.println("You rolled more than you require to reach 100!!"); System.out.println("You can't move ahead!!"); p2_val=p2_val-dice; } for (int pfill=0; pfill&lt;100; pfill++){ p2[pfill]=" "; } p2[p2_val-1]=" \u278B"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } System.out.println("Roll = "+dice); if(SnakesnLadders[p2_val-1]!=" ") { //Snakes if(p2_val==99) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 2!!"); p2_val=2; } if(p2_val==91) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 75!!"); p2_val=75; } if(p2_val==87) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 24!!"); p2_val=24; } if(p2_val==51) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 47!!"); p2_val=47; } if(p2_val==49) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 23!!"); p2_val=23; } if(p2_val==37) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 29!!"); p2_val=29; } if(p2_val==17) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 3!!"); p2_val=3; } //Ladders if(p2_val==82) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 97!!"); p2_val=97; } if(p2_val==55) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 63!!"); p2_val=63; } if(p2_val==33) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 83!!"); p2_val=83; } if(p2_val==19) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 80!!"); p2_val=80; } if(p2_val==16) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 25!!"); p2_val=25; } if(p2_val==9) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 39!!"); p2_val=39; } if(p2_val==4) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 14!!"); p2_val=14; } t=99; s_and_l=99; order=0; for(long i=-99099999; i&lt;=9999999; i++); System.out.print("\f"); for (int pfill=0; pfill&lt;100; pfill++){ p2[pfill]=" "; } p2[p2_val-1]=" \u278B"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } } } else if((chance+1)%4==0){ System.out.println("It is "+player3+"\'s turn:"); System.out.println("Enter \'Roll\' to roll the dice:"); char pause=sc.next().charAt(0); System.out.println("\f"); int dice=(int)(Math. random()*6+1); p3_val=p3_val+dice; if(p3_val==100) { System.out.println("=================="); System.out.println(player3+" WON!!"); System.out.println("=================="); System.out.println("It was a great game!!"); break; } else if(p3_val&gt;100) { System.out.println("You rolled more than you require to reach 100!!"); System.out.println("You can't move ahead!!"); p3_val=p3_val-dice; } for (int pfill=0; pfill&lt;100; pfill++){ p3[pfill]=" "; } p3[p3_val-1]=" \u278C"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } System.out.println("Roll = "+dice); if(SnakesnLadders[p3_val-1]!=" ") { //Snakes if(p3_val==99) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 2!!"); p3_val=2; } if(p3_val==91) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 75!!"); p3_val=75; } if(p3_val==87) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 24!!"); p3_val=24; } if(p3_val==51) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 47!!"); p3_val=47; } if(p3_val==49) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 23!!"); p3_val=23; } if(p3_val==37) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 29!!"); p3_val=29; } if(p3_val==17) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 3!!"); p3_val=3; } //Ladders if(p3_val==82) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 97!!"); p3_val=97; } if(p3_val==55) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 63!!"); p3_val=63; } if(p3_val==33) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 83!!"); p3_val=83; } if(p3_val==19) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 80!!"); p3_val=80; } if(p3_val==16) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 25!!"); p3_val=25; } if(p3_val==9) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 39!!"); p3_val=39; } if(p3_val==4) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 14!!"); p3_val=14; } t=99; s_and_l=99; order=0; for(long i=-99099999; i&lt;=9999999; i++); System.out.print("\f"); for (int pfill=0; pfill&lt;100; pfill++){ p3[pfill]=" "; } p3[p3_val-1]=" \u278C"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } } } else if(chance%4==0) { System.out.println("It is "+player4+"\'s turn:"); System.out.println("Enter \'Roll\' to roll the dice:"); char pause=sc.next().charAt(0); System.out.println("\f"); int dice=(int)(Math. random()*6+1); p4_val=p4_val+dice; if(p4_val==100) { System.out.println("=================="); System.out.println(player4+" WON!!"); System.out.println("=================="); System.out.println("It was a great game!!"); break; } else if(p4_val&gt;100) { System.out.println("You rolled more than you require to reach 100!!"); System.out.println("You can't move ahead!!"); p4_val=p4_val-dice; } for (int pfill=0; pfill&lt;100; pfill++){ p4[pfill]=" "; } p4[p4_val-1]=" \u278D"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } System.out.println("Roll = "+dice); if(SnakesnLadders[p4_val-1]!=" ") { //Snakes if(p4_val==99) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 2!!"); p4_val=2; } if(p4_val==91) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 75!!"); p4_val=75; } if(p4_val==87) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 24!!"); p4_val=24; } if(p4_val==51) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 47!!"); p4_val=47; } if(p4_val==49) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 23!!"); p4_val=23; } if(p4_val==37) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 29!!"); p4_val=29; } if(p4_val==17) { System.out.println("Oh no You landed on a snake!!!"); System.out.println("You Slip to 3!!"); p4_val=3; } //Ladders if(p4_val==82) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 97!!"); p4_val=97; } if(p4_val==55) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 63!!"); p4_val=63; } if(p4_val==33) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 83!!"); p4_val=83; } if(p4_val==19) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 80!!"); p4_val=80; } if(p4_val==16) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 25!!"); p4_val=25; } if(p4_val==9) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 39!!"); p4_val=39; } if(p4_val==4) { System.out.println("WOW! You landed on a ladder!!!"); System.out.println("You Climb to 14!!"); p4_val=14; } t=99; s_and_l=99; order=0; for(long i=-99099999; i&lt;=9999999; i++); System.out.print("\f"); for (int pfill=0; pfill&lt;100; pfill++){ p4[pfill]=" "; } p4[p4_val-1]=" \u278D"; System.out.println("\u278A --&gt;"+player1+"\t\t\u278B --&gt;"+player2+"\t\t\u278C --&gt;"+player3+"\t\t\u278D --&gt;"+player4); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); for (int boardi=1; boardi&lt;=10; boardi++){ if(boardi%2==0) { t=t-9; s_and_l=s_and_l-9; order=1; } else if(boardi!=1) { t=t-11; s_and_l=s_and_l-11; order=0; } for (long boardj=1; boardj&lt;=10; boardj++){ System.out.print(p1[t]+p2[t]+"\t"+board[t]+p3[t]+p4[t]+"\t|"); if(order==1)t++; else if(order==0)t--; } System.out.println(""); for (long boardj=1; boardj&lt;=10; boardj++){ if(order==0) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l-1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1) { if(boardj==1){ if(SnakesnLadders[s_and_l]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|"); else System.out.print("\t"+SnakesnLadders[s_and_l]+"\t|\t"); } else if(SnakesnLadders[s_and_l+1]!=" ") System.out.print(SnakesnLadders[s_and_l]+"\t|"); else System.out.print(SnakesnLadders[s_and_l]+"\t|\t"); } if(order==1)s_and_l++; else if(order==0)s_and_l--; } System.out.println(""); for (int dash=1; dash&lt;=161; dash++) System.out.print("-"); System.out.println(""); } } } } System.out.println(""); System.out.println("Press y or Y to retry."); System.out.println("Enter any other character to exit "); retry=sc.next().charAt(0); System.out.println("\f"); }while(retry=='y' || retry=='Y'); System.out.println("Thank You."); } } </code></pre>
[]
[ { "body": "<p>It took me several hours to rework your code. I admire how much effort you put into your code. I couldn't have written that application as one huge method.</p>\n\n<p>The Unicode characters you used for player numbers were sans serif, which didn't work well with a non-proportional console font. I changed them to Unicode characters that were monospace.</p>\n\n<p>When I create a Java application, I use the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"noreferrer\">model / view / controller</a> pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.</p>\n\n<p>The first thing I did was to create a model of the game. I started by creating a <code>Player</code> class. This class holds the name, marker, and board position for each of the players.</p>\n\n<pre><code>public class Player {\n\n private int boardPosition;\n\n private final String name;\n private final String marker;\n\n public Player(String name, String marker) {\n this.name = name;\n this.marker = marker;\n this.boardPosition = 0;\n }\n\n public int getBoardPosition() {\n return boardPosition;\n }\n\n public void setBoardPosition(int boardPosition) {\n this.boardPosition = boardPosition;\n }\n\n public String getName() {\n return name;\n }\n\n public String getMarker() {\n return marker;\n }\n}\n</code></pre>\n\n<p>Next, I created a <code>BoardPosition</code> class to hold the position from 1 - 100, a snake position, or a ladder position. If the snake position or ladder position is zero, it's a normal square. If not, it's either a snake or a ladder.</p>\n\n<pre><code>public class BoardPosition {\n\n private final int position;\n\n private int ladderPosition;\n private int snakePosition;\n\n public BoardPosition(int position) {\n this.position = position;\n this.ladderPosition = 0;\n this.snakePosition = 0;\n }\n\n public int getLadderPosition() {\n return ladderPosition;\n }\n\n public String getLadderPositionText() {\n return \"Climb to \" + ladderPosition;\n }\n\n public void setLadderPosition(int ladderPosition) {\n this.ladderPosition = ladderPosition;\n }\n\n public int getSnakePosition() {\n return snakePosition;\n }\n\n public String getSnakePositionText() {\n return \"Slip to \" + snakePosition;\n }\n\n public void setSnakePosition(int snakePosition) {\n this.snakePosition = snakePosition;\n }\n\n public boolean isLadder() {\n return ladderPosition &gt; 0;\n }\n\n public boolean isSnake() {\n return snakePosition &gt; 0;\n }\n\n public int getPosition() {\n return position;\n }\n}\n</code></pre>\n\n<p>These two classes are plain Java classes that hold the information for a player and a board position, respectively. By creating classes, you don't have to manage multiple parallel arrays.</p>\n\n<p>Finally, I created a <code>Board</code> class to hold 100 board positions. This class uses a factory pattern to create each of the board positions and put them in one board array. </p>\n\n<pre><code>public class Board {\n\n private int cellCount;\n\n private BoardPosition[] board;\n\n public Board() {\n this.cellCount = 100;\n board = new BoardPosition[cellCount];\n generateBoard();\n }\n\n private void generateBoard() {\n initalizeBoard();\n setupSnakes();\n setupLadders();\n }\n\n private void initalizeBoard() {\n for (int i = 0; i &lt; cellCount; i++) {\n BoardPosition boardPosition = \n new BoardPosition(i + 1);\n board[i] = boardPosition;\n }\n }\n\n private void setupSnakes() {\n int[] position = \n { 99, 91, 87, 51, 49, 37, 17 };\n int[] snakePosition = \n { 2, 75, 24, 47, 23, 29, 3 };\n\n for (int i = 0; i &lt; position.length; i++) {\n BoardPosition boardPosition = \n board[position[i] - 1];\n boardPosition.setSnakePosition(\n snakePosition[i]);\n }\n }\n\n private void setupLadders() {\n int[] position = \n { 82, 55, 33, 19, 16, 9, 4 };\n int[] ladderPosition = \n { 97, 63, 83, 80, 25, 39, 14 };\n\n for (int i = 0; i &lt; position.length; i++) {\n BoardPosition boardPosition = \n board[position[i] - 1];\n boardPosition.setLadderPosition(\n ladderPosition[i]);\n }\n }\n\n public BoardPosition[] getBoard() {\n return board;\n }\n\n public int getCellCount() {\n return cellCount;\n }\n}\n</code></pre>\n\n<p>I reworked your game code to use many methods that each (hopefully) do one thing and do it correctly.</p>\n\n<p>Here's the entire, runnable, code for your game. All together, it's about half the size of your original code. Any duplication of code is deliberate for documentation purposes.</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class SnakesAndLadders {\n\n public static void main(String[] args) {\n SnakesAndLadders sl = new SnakesAndLadders();\n sl.playGame();\n }\n\n public void playGame() {\n Board board = new Board();\n Scanner sc = new Scanner(System.in);\n\n char retry = 'y';\n do {\n displayIntroduction();\n Player[] players = getPlayers(sc);\n boolean isGameActive = true;\n while (isGameActive) {\n waitForDisplay(sc);\n displayPlayers(players);\n displayBoard(board, players);\n isGameActive = playRound(sc, \n board, players);\n }\n retry = getPlayAgainResponse(sc);\n } while (retry == 'y');\n\n System.out.println();\n System.out.println(\"Thank you for playing.\");\n sc.close();\n }\n\n private void displayIntroduction() {\n System.out.println(\"-----------------------\"\n + \"----------\");\n System.out.println(\"Welcome to Java Snakes \"\n + \"&amp; Ladders!\");\n System.out.println(\"------------------------\"\n + \"---------\\n\");\n System.out.println(\"Rules:\");\n System.out.println(\"--&gt; This is similar to the \"\n + \"Snakes &amp; Ladders game played by many \"\n + \"people.\");\n System.out.println(\"--&gt; This is a four-player \"\n + \"game.\\n\");\n System.out.println(\"--&gt; There will be a 10x10 \"\n + \"board containing some snakes and \"\n + \"ladders.\\n\");\n System.out.println(\"--&gt; The players will take \"\n + \"turns rolling one six-sided die.\");\n System.out.println(\"--&gt; The player will move \"\n + \"ahead according to the \"\n + \"number rolled.\\n\");\n System.out.println(\"--&gt; If a player lands on \"\n + \"a ladder, he will be able to climb \"\n + \"it and go ahead!!\");\n System.out.println(\"--&gt; But if a player lands \"\n + \"on a snake, he will have to go back!!\\n\");\n System.out.println(\"--&gt; The players start at 0.\");\n System.out.println(\"--&gt; The game continues \"\n + \"until one player reaches 100.\\n\");\n }\n\n private Player[] getPlayers(Scanner sc) {\n int numberOfPlayers = 4;\n Player[] players = new Player[numberOfPlayers];\n String[] markers = { \"\\u2460\", \"\\u2461\", \n \"\\u2462\", \"\\u2463\" };\n\n for (int i = 0; i &lt; numberOfPlayers; i++) {\n System.out.print(\"Enter Player \");\n System.out.print(i + 1);\n System.out.print(\"'s name: \");\n String name = sc.nextLine().trim();\n Player player = new Player(name, markers[i]);\n players[i] = player;\n }\n\n return players;\n }\n\n private boolean playRound(Scanner sc, Board board, \n Player[] players) {\n for (int turn = 0; turn &lt; players.length; turn++) {\n Player player = players[turn];\n int die = getDieRoll(sc, player, turn);\n\n int position = player.getBoardPosition();\n position += die;\n\n int finalPosition = board.getCellCount();\n if (position == finalPosition) {\n declareWinner(player);\n return false;\n } else if (position &gt; finalPosition) {\n displayOvershoot();\n } else {\n movePlayer(board, player, position);\n }\n }\n return true;\n }\n\n private void declareWinner(Player player) {\n System.out.println(\"==================\");\n System.out.println(player.getName() + \" Won!!\");\n System.out.println(\"==================\");\n System.out.println(\"It was a great game!!\");\n System.out.println();\n }\n\n private void displayOvershoot() {\n System.out.println(\"You rolled more than \"\n + \"you require to reach 100!!\");\n System.out.println(\"You can't move ahead!!\");\n }\n\n private void movePlayer(Board board, Player player, \n int position) {\n BoardPosition[] squares = board.getBoard();\n BoardPosition square = squares[position - 1];\n if (square.isSnake()) {\n displayPosition(position);\n displaySnakePosition(square);\n player.setBoardPosition(\n square.getSnakePosition());\n } else if (square.isLadder()) {\n displayPosition(position);\n displayLadderPosition(square);\n player.setBoardPosition(\n square.getLadderPosition());\n } else {\n displayPosition(position);\n player.setBoardPosition(position);\n }\n }\n\n private void displaySnakePosition(BoardPosition square) {\n System.out.println(\"Oh no. You landed \"\n + \"on a snake!!!\");\n System.out.print(\"You slip to \");\n System.out.print(square.getSnakePosition());\n System.out.println(\"!!\");\n }\n\n private void displayLadderPosition(BoardPosition square) {\n System.out.println(\"Wow! You landed \"\n + \"on a ladder!!!\");\n System.out.print(\"You climb to \");\n System.out.print(square.getLadderPosition());\n System.out.println(\"!!\");\n }\n\n private void displayPosition(int position) {\n System.out.print(\"You landed on square \");\n System.out.print(position);\n System.out.println(\".\");\n }\n\n private int getDieRoll(Scanner sc, Player player, \n int turn) {\n System.out.println();\n System.out.print(\"It is \");\n System.out.print(addApostrophe(player.getName()));\n System.out.println(\" turn.\");\n System.out.print(\"Press Enter to \"\n + \"roll the dice:\");\n sc.nextLine();\n\n // Generate a number between 1 &amp; 6\n int die = (int) (Math.random() * 6 + 1);\n System.out.println(\"You rolled a \" + die + \".\");\n return die;\n }\n\n private char getPlayAgainResponse(Scanner sc) {\n char retry;\n System.out.println();\n System.out.println(\"Enter y to replay game.\");\n System.out.println(\"Enter any other character \"\n + \"to exit.\");\n retry = sc.nextLine().charAt(0);\n return Character.toLowerCase(retry);\n }\n\n private void waitForDisplay(Scanner sc) {\n System.out.println();\n System.out.print(\"Press Enter to display board: \");\n sc.nextLine();\n }\n\n private void displayPlayers(Player[] players) {\n System.out.println();\n for (int i = 0; i &lt; players.length; i++) {\n Player player = players[i];\n String marker = player.getMarker();\n String name = player.getName();\n System.out.println(\"Player \" + marker \n + \" --&gt; \" + name); \n }\n }\n\n private void displayBoard(Board board, \n Player[] players) {\n int cellWidth = 16;\n int cellCount = board.getCellCount();\n int cells = (int) Math.sqrt(cellCount);\n displayDashLine(cellWidth, cells);\n\n for (int i = 0; i &lt; cells; i += 2) {\n cellCount = displayCells(board, players, \n cells, cellWidth, cellCount, -1);\n displayDashLine(cellWidth, cells);\n cellCount = displayCells(board, players, \n cells, cellWidth, cellCount, +1);\n displayDashLine(cellWidth, cells);\n }\n }\n\n private void displayDashLine(int cellWidth, int cells) {\n int width = cellWidth * cells + 1;\n for (int dash = 1; dash &lt;= width; dash++) {\n System.out.print(\"-\");\n }\n System.out.println();\n }\n\n private int displayCells(Board board, Player[] players,\n int cells, int cellWidth, int cellCount, \n int increment) {\n int temp = calculateStartingCell(cells, \n cellCount, increment);\n displayPositionNumber(board, cells, cellWidth, \n increment, temp);\n\n temp = calculateStartingCell(cells, \n cellCount, increment);\n displayPositionText(board, cells, cellWidth, \n increment, temp);\n\n temp = calculateStartingCell(cells, \n cellCount, increment);\n displayPositionPlayer(board, players, cells, \n cellWidth, increment, temp);\n\n return cellCount - cells; \n }\n\n private void displayPositionNumber(Board board, \n int cells, int cellWidth, int increment, \n int temp) {\n for (int i = 0; i &lt; cells; i++) {\n temp += increment;\n BoardPosition boardPosition = \n board.getBoard()[temp];\n\n if (i == 0) {\n System.out.print(\"|\");\n }\n\n int position = boardPosition.getPosition();\n String text = Integer.toString(position);\n String s = generateTextLine(text, cellWidth);\n System.out.print(s);\n }\n System.out.println();\n }\n\n private void displayPositionText(Board board, \n int cells, int cellWidth, int increment, \n int temp) {\n for (int i = 0; i &lt; cells; i++) {\n temp += increment;\n BoardPosition boardPosition = \n board.getBoard()[temp];\n\n if (i == 0) {\n System.out.print(\"|\");\n }\n\n String text = \"\";\n if (boardPosition.isSnake()) {\n text = boardPosition.getSnakePositionText();\n } else if (boardPosition.isLadder()) {\n text = boardPosition.getLadderPositionText();\n }\n String s = generateTextLine(text, cellWidth);\n System.out.print(s);\n }\n System.out.println();\n }\n\n private void displayPositionPlayer(Board board, \n Player[] players, int cells, \n int cellWidth, int increment, int temp) {\n for (int i = 0; i &lt; cells; i++) {\n temp += increment;\n\n if (i == 0) {\n System.out.print(\"|\");\n }\n\n String text = \"\";\n for (int j = 0; j &lt; players.length; j++) {\n Player player = players[j];\n if (player.getBoardPosition() == (temp + 1)) {\n text += player.getMarker() + \" \";\n }\n }\n text = text.trim();\n String s = generateTextLine(text, cellWidth);\n System.out.print(s);\n }\n System.out.println();\n }\n\n\n private int calculateStartingCell(int cells, \n int cellCount, int increment) {\n int temp = cellCount;\n if (increment &gt; 0) {\n temp -= cells + 1;\n }\n return temp;\n }\n\n private String generateTextLine(String text, int cellWidth) {\n String output = \"\";\n\n int spaces = (cellWidth - text.length()) / 2;\n output += createBlankString(spaces);\n\n output += text;\n\n int width = cellWidth - spaces - text.length() - 1;\n output += createBlankString(width);\n\n output += \"|\";\n return output;\n }\n\n private String createBlankString(int width) {\n String output = \"\";\n for (int i = 0; i &lt; width; i++) {\n output += \" \";\n }\n return output;\n }\n\n private String addApostrophe(String name) {\n char last = name.charAt(name.length() - 1);\n if (last == 's') {\n return name + \"'\";\n } else {\n return name + \"'s\";\n }\n }\n\n public class Board {\n\n private int cellCount;\n\n private BoardPosition[] board;\n\n public Board() {\n this.cellCount = 100;\n board = new BoardPosition[cellCount];\n generateBoard();\n }\n\n private void generateBoard() {\n initalizeBoard();\n setupSnakes();\n setupLadders();\n }\n\n private void initalizeBoard() {\n for (int i = 0; i &lt; cellCount; i++) {\n BoardPosition boardPosition = \n new BoardPosition(i + 1);\n board[i] = boardPosition;\n }\n }\n\n private void setupSnakes() {\n int[] position = \n { 99, 91, 87, 51, 49, 37, 17 };\n int[] snakePosition = \n { 2, 75, 24, 47, 23, 29, 3 };\n\n for (int i = 0; i &lt; position.length; i++) {\n BoardPosition boardPosition = \n board[position[i] - 1];\n boardPosition.setSnakePosition(\n snakePosition[i]);\n }\n }\n\n private void setupLadders() {\n int[] position = \n { 82, 55, 33, 19, 16, 9, 4 };\n int[] ladderPosition = \n { 97, 63, 83, 80, 25, 39, 14 };\n\n for (int i = 0; i &lt; position.length; i++) {\n BoardPosition boardPosition = \n board[position[i] - 1];\n boardPosition.setLadderPosition(\n ladderPosition[i]);\n }\n }\n\n public BoardPosition[] getBoard() {\n return board;\n }\n\n public int getCellCount() {\n return cellCount;\n }\n }\n\n public class BoardPosition {\n\n private final int position;\n\n private int ladderPosition;\n private int snakePosition;\n\n public BoardPosition(int position) {\n this.position = position;\n this.ladderPosition = 0;\n this.snakePosition = 0;\n }\n\n public int getLadderPosition() {\n return ladderPosition;\n }\n\n public String getLadderPositionText() {\n return \"Climb to \" + ladderPosition;\n }\n\n public void setLadderPosition(int ladderPosition) {\n this.ladderPosition = ladderPosition;\n }\n\n public int getSnakePosition() {\n return snakePosition;\n }\n\n public String getSnakePositionText() {\n return \"Slip to \" + snakePosition;\n }\n\n public void setSnakePosition(int snakePosition) {\n this.snakePosition = snakePosition;\n }\n\n public boolean isLadder() {\n return ladderPosition &gt; 0;\n }\n\n public boolean isSnake() {\n return snakePosition &gt; 0;\n }\n\n public int getPosition() {\n return position;\n }\n }\n\n public class Player {\n\n private int boardPosition;\n\n private final String name;\n private final String marker;\n\n public Player(String name, String marker) {\n this.name = name;\n this.marker = marker;\n this.boardPosition = 0;\n }\n\n public int getBoardPosition() {\n return boardPosition;\n }\n\n public void setBoardPosition(int boardPosition) {\n this.boardPosition = boardPosition;\n }\n\n public String getName() {\n return name;\n }\n\n public String getMarker() {\n return marker;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T23:23:45.727", "Id": "241687", "ParentId": "241656", "Score": "7" } } ]
{ "AcceptedAnswerId": "241687", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T12:57:35.287", "Id": "241656", "Score": "4", "Tags": [ "java", "game" ], "Title": "Text-based Snakes and Ladders" }
241656
<p>I'm still new to programming and I'm not confident about this code. I recently created this File Organizer that organizes files in folders based on their extensions. How can I make this code cleaner? </p> <pre><code># File Organizer - organizes file in folders based on their extensions. # 03/05/2020 import shutil, os root_path = "C:\\YourDesiredPath" os.chdir(root_path) dirfiles = os.listdir(root_path) class FileOrganizer(): # store extensions and folder names mydir = {} def name_folder(self): for file in dirfiles: ext = os.path.splitext(file)[1] if ext != '': # if file has an extension self.mydir[ext] = (ext + " FOLDER").upper() def create_folder(self): for folder in list(self.mydir.values()): if not os.path.isdir(folder): os.mkdir(os.path.join(root_path,folder)) def organize_files(self): for file in dirfiles: # for files iterated, check if it matches the ext and move it to ext folder for ext in [*self.mydir]: if file.endswith(ext): try: shutil.move(file,self.mydir[ext]) except : print(f"{file} already exists in {self.mydir[ext]}") file_organizer = FileOrganizer() file_organizer.name_folder() file_organizer.create_folder() file_organizer.organize_files() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T06:58:44.050", "Id": "474305", "Score": "1", "body": "You might want to take a look at [this question](https://codereview.stackexchange.com/questions/241644/file-automation-using-python-on-linux) from the same day. It seems to be similar to what you are doing, albeit not the same. The answers contain general tips that apply to your problem as well." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T13:30:24.313", "Id": "241658", "Score": "1", "Tags": [ "python", "python-3.x", "object-oriented", "file-system" ], "Title": "File organizer based on extensions" }
241658
<p>I'm writing a code that, starting from an XML file:</p> <ul> <li>stores the index of child elements of a tag and the child elements as key, values in a dictionary (function <code>get_xml_by_tag_names</code>);</li> <li>deletes keys whose values contain a certain string (the specific text size) and puts these keys and the corresponding values into a second dictionary (def <code>search_delete_append</code>);</li> <li>joins, for each dictionary, the dict values and extracts their text(def <code>main</code>);</li> <li>replaces certain values with "" (def <code>main</code>);</li> <li>counts the occurrences of specific regex I specify (def <code>find_regex</code>).</li> </ul> <p>The <code>main</code> function is problematic, as I need help cleaning it up, the regex are too many and I want to create a function for each regex inside the main function. Would it be a good option?</p> <pre><code>import re from xml.dom import minidom from xml.etree import ElementTree as ET def get_xml_by_tag_names(xml_path, tag_name_1, tag_name_2): data = {} xml_tree = minidom.parse(xml_path) item_group_nodes = xml_tree.getElementsByTagName(tag_name_1) for idx, item_group_node in enumerate(item_group_nodes): cl_compile_nodes = item_group_node.getElementsByTagName(tag_name_2) for _ in cl_compile_nodes: data[idx]=[item_group_node.toxml()] return data def find_regex(regex, text): lista = [] for x in text: matches_prima = re.findall(regex, x) lunghezza = len(matches_prima) lista.append(lunghezza) print("The number of {} matches is ".format(regex), sum(lista)) def find_regex_fasi(regex, text): matches_fasi = re.findall(regex, text) print("Numero di corpo minore è", len(matches_fasi)) def search_delete_append(dizionario, dizionariofasi): deletekeys = [] insertvalues = [] for k in dizionario: for v in dizionario[k]: if "7.489" in v: deletekeys.append(k) dizionariofasi[k] = v for item in deletekeys: del dizionario[item] def main(): dict_fasi = {} data = get_xml_by_tag_names('output2.xml', 'new_line', 'text') search_delete_append(data, dict_fasi) testo = [] for value in data.values(): myxml = ' '.join(value) tree = ET.fromstring(myxml) tmpstring = ' '.join(text.text for text in tree.findall('text')) for to_remove in ("&lt;", "&gt;", ".", ",", ";", "-", "!", ":", "’", "?", "&lt;&gt;", "=", "|", "(", ")"): tmpstring = tmpstring.replace(to_remove, "") testo.append(tmpstring) #testo = ''.join(testo) print(testo) find_fase_12T_leo = re.compile(r"\]\s*AN\s*1\s*([\w\s]+)da\s*cui\s*2\s*([\w\s]+)da\s*cui\s*T") #find_prima = re.compile(r"\]\s*prima(?!\S)") find_fase_base_2 = re.compile(r"\]\s([\w\s]+)\s[→]\sT") # ] parole → T find_fase_base_3 = re.compile(r"\]\s*([\w\s]+)\s*da\scui\sT") # ] parole da cui T find_fase_12 = re.compile(r"\]\s1\s([\w\s]+)\s2\s([\w\s]+[^T])") # ] 1 parole 2 parole (esclude T) find_fase_prima_12 = re.compile(r"\]\s+prima\s+1\s+([\w\s]+)\s+2([\w\s]+[^T])") # ] prima 1 parole 2 parole (esclude T) find_fase_prima_123 = re.compile(r"\]\sprima\s1\s([\w\s]+)\s2([\w\s]+)\s3([\w\s]+)") find_fase_prima_123T = re.compile(r"\]\sprima\s1\s([\w\s]+)\s2([\w\s]+)\s3\sT") #prima 1 parole 2 parole 3t find_fase_prima_1freccia2 = re.compile(r"\]\s+prima\s1\s([\w\s]+)\s[→]\s2([\w\s]+[^T])") #] prima 1 parola → 2 parola FIND_FASE12T = re.compile(r"\]\s1\s([\w\s]+)\s2\sT") FIND_FASE123T_OPZ2 = re.compile(r"\]\s*prima\s*1([\w\s]+)\s*2([\w\s][^3|^3T]+) ") FIND_FASE123T = re.compile(r"\]\s*1([\w\s]+)\s*2([\w\s]+)\s3\sT") FIND_FASE_123FRECCIAT = re.compile(r"\]\s1\s([\w\s]+)\s2([\w\s]+)\s→\sT") FIND_FASE_1FRECCIA23T = re.compile(r"\]\s1\s([\w\s]+)\s→\s2([\w\s]+)\s(T|3\sT)") FIND_FASE_FRECCIA1F2FT = re.compile(r"\]\s1\s([\w\s]+)\s→\s2([\w\s]+)\s→\s(T|3\sT)") FIND_FASE_PRIMA_123FRECCIAT = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*2([\w\s]+)\s*→\s*T") FIND_FASE_PRIMA_1FRECCIA23T = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)\s*(T|3\sT)") FIND_FASE_PRIMA_FRECCIA1F2FT = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)\s*→\s*(T|3\sT)") FIND_FASE_PRIMA_1FRECCIA2 = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*→\s*2([\w\s]+)") FIND_FASE_PRIMA_12345T = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*2([\w\s]+)\s*3([\w\s]+)\s*4([\w\s]+)\s*5\sT") FIND_FASE_PRIMA_12345T_OPZ2 = re.compile(r"\]\s*prima\s*1\s*([\w\s]+)\s*2([\w\s]+)\s*3([\w\s]+)\s*4([\w\s][^5|^5\sT]+)") FIND_FASE_12345T = re.compile(r"\]\s*1\s*([\w\s]+)\s*2([\w\s]+)\s*3([\w\s]+)\s*4([\w\s]+)\s*5\sT") #find_da = re.compile(r"\]\s*da(?!\S)") #find_da_cui = re.compile(r"\]\s*([\w\s]+)\s*da\scui") #find_sps = re.compile(r"\]\s*([\w\s]+)\s*sps") #find_su = re.compile(r"\]\s*([\w\s]+)\s*su") #find_as = re.compile(r"\]\s*([\w\s]+)\s*as") #find_ins = re.compile(r"\]\s*([\w\s]+)\s*ins") #find_segue = re.compile(r"\]\s*([\w\s]+)\s*segue") find_regex(FIND_FASE12T, testo) find_regex(find_fase_12T_leo, testo) #find_regex(find_prima, testo) find_regex(find_fase_base_2, testo) find_regex(find_fase_base_3, testo) find_regex(find_fase_12, testo) find_regex(find_fase_prima_12, testo) find_regex(find_fase_prima_123, testo) find_regex(find_fase_prima_123T, testo) find_regex(find_fase_prima_1freccia2, testo) #find_regex(find_da, testo) #find_regex(find_da_cui, testo) #find_regex(find_sps, testo) #find_regex(find_su, testo) #find_regex(find_as, testo) #find_regex(find_ins, testo) #find_regex(find_segue, testo) ################# testo_fasi = [] values = [x for x in dict_fasi.values()] myxml_fasi = ' '.join(values) find_CM = re.compile(r"10\.238") find_regex_fasi(find_CM, myxml_fasi) #quanti CM ci sono? #print(myxml_fasi) for x in dict_fasi.values(): xxx= ''.join(x) tree2 = ET.fromstring(xxx) tmpstring2 = ' '.join(text.text for text in tree2.findall('text')) for to_remove in ("&lt;", "&gt;", ".", ",", ";", "-", "!", ":", "’", "?", "&lt;&gt;", "=", "|", "(", ")"): tmpstring2 = tmpstring2.replace(to_remove, "") testo_fasi.append(tmpstring2) #testo_fasi = ''.join(testo_fasi) print(testo_fasi) find_regex(FIND_FASE12T, testo_fasi) find_regex(FIND_FASE123T_OPZ2, testo_fasi) find_regex(FIND_FASE123T, testo_fasi) find_regex(FIND_FASE_1FRECCIA23T, testo_fasi) find_regex(FIND_FASE_123FRECCIAT, testo_fasi) find_regex(FIND_FASE_FRECCIA1F2FT, testo_fasi) find_regex(FIND_FASE_PRIMA_1FRECCIA23T, testo_fasi) find_regex(FIND_FASE_PRIMA_123FRECCIAT, testo_fasi) find_regex(FIND_FASE_PRIMA_FRECCIA1F2FT, testo_fasi) find_regex(FIND_FASE_PRIMA_1FRECCIA2, testo_fasi) find_regex(FIND_FASE_PRIMA_12345T, testo_fasi) find_regex(FIND_FASE_PRIMA_12345T_OPZ2, testo_fasi) find_regex(FIND_FASE_12345T, testo_fasi) find_regex(find_fase_12T_leo, testo_fasi) #find_regex(find_prima, testo_fasi) find_regex(find_fase_base_2, testo_fasi) find_regex(find_fase_base_3, testo_fasi) find_regex(find_fase_12, testo_fasi) find_regex(find_fase_prima_12, testo_fasi) find_regex(find_fase_prima_123, testo_fasi) find_regex(find_fase_prima_123T, testo_fasi) find_regex(find_fase_prima_1freccia2, testo_fasi) #find_regex(find_da, testo_fasi) #find_regex(find_da_cui, testo_fasi) #find_regex(find_sps, testo_fasi) #find_regex(find_su, testo_fasi) #find_regex(find_as, testo_fasi) #find_regex(find_ins, testo_fasi) #find_regex(find_segue, testo_fasi) if __name__ == "__main__": main() </code></pre> <p>I know it's half in Italian right now, but I need to keep it for now for my clarity.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T14:31:51.723", "Id": "474250", "Score": "0", "body": "Hey. Could you reduce this to a minimal working example? Perhaps include a valid minimal input and the corresponding output too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T14:34:05.943", "Id": "474251", "Score": "0", "body": "Should I provide it even if everything is working?" } ]
[ { "body": "<p><strong>We should only use as many variables as needed</strong></p>\n\n<p>For example,</p>\n\n<pre><code>values = [x for x in dict_fasi.values()]\nmyxml_fasi = ' '.join(values)\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>myxml_fasi = ' '.join(dict_fasi.values())\n</code></pre>\n\n<hr>\n\n<p><strong>We can reduce the number of strings created</strong></p>\n\n<pre><code>for to_remove in (\"&lt;\", \"&gt;\", \".\", \",\", \";\", \"-\", \"!\", \":\", \"’\", \"?\", \"&lt;&gt;\", \"=\", \"|\", \"(\", \")\"):\n tmpstring2 = tmpstring2.replace(to_remove, \"\")\n</code></pre>\n\n<p>could be </p>\n\n<pre><code>tmpstring2 = ''.join(c for c in tmpstring2\n if c not in set(\"|=?-&lt;&gt;’(!.:,;\"))\n</code></pre>\n\n<p>The first creates a new string with each iteration. \nN.b. after deleting <code>&lt;</code> and <code>&gt;</code>, there won't be any <code>&lt;&gt;</code> in the text.</p>\n\n<hr>\n\n<p><strong>Separating input/output from processing functions</strong></p>\n\n<p>I'd try to limit interaction with the world to as few functions as possible. For example I would not expect a function named <code>find_regex_fasi</code> to print anything to the console (or elsewhere). I'd make it return its results and do the printing inside <code>main</code>.</p>\n\n<hr>\n\n<pre><code>find_fase_12T_leo = re.compile(r\"\\]\\s*AN\\s*1\\s*([\\w\\s]+)da\\s*cui\\s*2\\s*([\\w\\s]+)da\\s*cui\\s*T\")\n#find_prima = re.compile(r\"\\]\\s*prima(?!\\S)\")\nfind_fase_base_2 = re.compile(r\"\\]\\s([\\w\\s]+)\\s[→]\\sT\") # ] parole → T\nfind_fase_base_3 = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*da\\scui\\sT\") # ] parole da cui T\nfind_fase_12 = re.compile(r\"\\]\\s1\\s([\\w\\s]+)\\s2\\s([\\w\\s]+[^T])\") # ] 1 parole 2 parole (esclude T)\nfind_fase_prima_12 = re.compile(r\"\\]\\s+prima\\s+1\\s+([\\w\\s]+)\\s+2([\\w\\s]+[^T])\") # ] prima 1 parole 2 parole (esclude T)\nfind_fase_prima_123 = re.compile(r\"\\]\\sprima\\s1\\s([\\w\\s]+)\\s2([\\w\\s]+)\\s3([\\w\\s]+)\")\nfind_fase_prima_123T = re.compile(r\"\\]\\sprima\\s1\\s([\\w\\s]+)\\s2([\\w\\s]+)\\s3\\sT\") #prima 1 parole 2 parole 3t\nfind_fase_prima_1freccia2 = re.compile(r\"\\]\\s+prima\\s1\\s([\\w\\s]+)\\s[→]\\s2([\\w\\s]+[^T])\") #] prima 1 parola → 2 parola\nFIND_FASE12T = re.compile(r\"\\]\\s1\\s([\\w\\s]+)\\s2\\sT\")\nFIND_FASE123T_OPZ2 = re.compile(r\"\\]\\s*prima\\s*1([\\w\\s]+)\\s*2([\\w\\s][^3|^3T]+) \")\nFIND_FASE123T = re.compile(r\"\\]\\s*1([\\w\\s]+)\\s*2([\\w\\s]+)\\s3\\sT\")\nFIND_FASE_123FRECCIAT = re.compile(r\"\\]\\s1\\s([\\w\\s]+)\\s2([\\w\\s]+)\\s→\\sT\")\nFIND_FASE_1FRECCIA23T = re.compile(r\"\\]\\s1\\s([\\w\\s]+)\\s→\\s2([\\w\\s]+)\\s(T|3\\sT)\")\nFIND_FASE_FRECCIA1F2FT = re.compile(r\"\\]\\s1\\s([\\w\\s]+)\\s→\\s2([\\w\\s]+)\\s→\\s(T|3\\sT)\")\nFIND_FASE_PRIMA_123FRECCIAT = re.compile(r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*→\\s*T\")\nFIND_FASE_PRIMA_1FRECCIA23T = re.compile(r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*→\\s*2([\\w\\s]+)\\s*(T|3\\sT)\")\nFIND_FASE_PRIMA_FRECCIA1F2FT = re.compile(r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*→\\s*2([\\w\\s]+)\\s*→\\s*(T|3\\sT)\")\nFIND_FASE_PRIMA_1FRECCIA2 = re.compile(r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*→\\s*2([\\w\\s]+)\")\nFIND_FASE_PRIMA_12345T = re.compile(r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*3([\\w\\s]+)\\s*4([\\w\\s]+)\\s*5\\sT\")\nFIND_FASE_PRIMA_12345T_OPZ2 = re.compile(r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*3([\\w\\s]+)\\s*4([\\w\\s][^5|^5\\sT]+)\")\nFIND_FASE_12345T = re.compile(r\"\\]\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*3([\\w\\s]+)\\s*4([\\w\\s]+)\\s*5\\sT\")\n\n#find_da = re.compile(r\"\\]\\s*da(?!\\S)\")\n#find_da_cui = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*da\\scui\")\n#find_sps = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*sps\")\n#find_su = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*su\")\n#find_as = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*as\")\n#find_ins = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*ins\")\n#find_segue = re.compile(r\"\\]\\s*([\\w\\s]+)\\s*segue\")\nfind_regex(FIND_FASE12T, testo)\nfind_regex(find_fase_12T_leo, testo)\n#find_regex(find_prima, testo)\nfind_regex(find_fase_base_2, testo)\nfind_regex(find_fase_base_3, testo)\nfind_regex(find_fase_12, testo)\nfind_regex(find_fase_prima_12, testo)\nfind_regex(find_fase_prima_123, testo)\nfind_regex(find_fase_prima_123T, testo)\nfind_regex(find_fase_prima_1freccia2, testo)\n#find_regex(find_da, testo)\n#find_regex(find_da_cui, testo)\n#find_regex(find_sps, testo)\n#find_regex(find_su, testo)\n#find_regex(find_as, testo)\n#find_regex(find_ins, testo)\n#find_regex(find_segue, testo)\n</code></pre>\n\n<p>can become something like</p>\n\n<pre><code>find_phase_regexes = {\n k: re.compile(v) for k, v in {\n \"12T_leo\": r\"\\]\\s*AN\\s*1\\s*([\\w\\s]+)da\\s*cui\\s*2\\s*([\\w\\s]+)da\\s*cui\\s*T\",\n \"prima\": r\"\\]\\s*prima(?!\\S)\",\n \"base_2\": r\"\\]\\s([\\w\\s]+)\\s[→]\\sT\", # ] parole → T\n \"base_3\": r\"\\]\\s*([\\w\\s]+)\\s*da\\scui\\sT\", # ] parole da cui T\n \"12\": r\"\\]\\s1\\s([\\w\\s]+)\\s2\\s([\\w\\s]+[^T])\", # ] 1 parole 2 parole (esclude T)\n \"prima_12\": r\"\\]\\s+prima\\s+1\\s+([\\w\\s]+)\\s+2([\\w\\s]+[^T])\", # ] prima 1 parole 2 parole (esclude T)\n \"prima_123\": r\"\\]\\sprima\\s1\\s([\\w\\s]+)\\s2([\\w\\s]+)\\s3([\\w\\s]+)\",\n \"prima_123T\": r\"\\]\\sprima\\s1\\s([\\w\\s]+)\\s2([\\w\\s]+)\\s3\\sT\", #prima 1 parole 2 parole 3t\n \"prima_1freccia2\": r\"\\]\\s+prima\\s1\\s([\\w\\s]+)\\s[→]\\s2([\\w\\s]+[^T])\", #] prima 1 parola → 2 parola\n \"12T\": r\"\\]\\s1\\s([\\w\\s]+)\\s2\\sT\",\n \"123T_OPZ2\": r\"\\]\\s*prima\\s*1([\\w\\s]+)\\s*2([\\w\\s][^3|^3T]+) \",\n \"123T\": r\"\\]\\s*1([\\w\\s]+)\\s*2([\\w\\s]+)\\s3\\sT\",\n \"123FRECCIAT\": r\"\\]\\s1\\s([\\w\\s]+)\\s2([\\w\\s]+)\\s→\\sT\",\n \"1FRECCIA23T\": r\"\\]\\s1\\s([\\w\\s]+)\\s→\\s2([\\w\\s]+)\\s(T|3\\sT)\",\n \"FRECCIA1F2FT\": r\"\\]\\s1\\s([\\w\\s]+)\\s→\\s2([\\w\\s]+)\\s→\\s(T|3\\sT)\",\n \"PRIMA_123FRECCIAT\": r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*→\\s*T\",\n \"PRIMA_1FRECCIA23T\": r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*→\\s*2([\\w\\s]+)\\s*(T|3\\sT)\",\n \"PRIMA_FRECCIA1F2FT\": r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*→\\s*2([\\w\\s]+)\\s*→\\s*(T|3\\sT)\",\n \"PRIMA_1FRECCIA2\": r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*→\\s*2([\\w\\s]+)\",\n \"PRIMA_12345T\": r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*3([\\w\\s]+)\\s*4([\\w\\s]+)\\s*5\\sT\",\n \"PRIMA_12345T_OPZ2\": r\"\\]\\s*prima\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*3([\\w\\s]+)\\s*4([\\w\\s][^5|^5\\sT]+)\",\n \"12345T\": r\"\\]\\s*1\\s*([\\w\\s]+)\\s*2([\\w\\s]+)\\s*3([\\w\\s]+)\\s*4([\\w\\s]+)\\s*5\\sT\",\n }.items()\n}\n\nfor k, v in find_phase_regexes.items():\n find_regex(v, testo)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T16:18:18.443", "Id": "241669", "ParentId": "241659", "Score": "3" } }, { "body": "<h3>str.maketrans and str.translate</h3>\n\n<p><code>str.maketrans()</code> is much faster than:</p>\n\n<pre><code> for to_remove in (\"&lt;\", \"&gt;\", \".\", \",\", \";\", \"-\", \"!\", \":\", \"’\", \"?\", \"&lt;&gt;\", \"=\", \"|\", \"(\", \")\"):\n tmpstring = tmpstring.replace(to_remove, \"\")\n</code></pre>\n\n<p>Instead:</p>\n\n<pre><code># create the table once at the beginning of main or globally\ntable = str.maketrans({c:None for c in \"&lt;&gt;.,;-!:’?=|()\"})\n\n# then do this instead of the for-loop\ntmpstring = tmpstring.translate(table)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T07:05:24.530", "Id": "241737", "ParentId": "241659", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T13:47:13.367", "Id": "241659", "Score": "1", "Tags": [ "python", "regex", "xml" ], "Title": "Python function to find specific regex in the text of an XML document" }
241659
<p>Here is a class to store global parameters of any type with static methods Set() and Get()</p> <ol> <li>What do you like and don't like about the implementation?</li> <li>How would you make it to work from multiple threads?</li> </ol> <pre><code>class Parameters { public: template&lt;typename T&gt; static void Set(std::string id, const T&amp; value) { auto&amp; parameters = GetInstance(); parameters.params[id] = std::any {value}; } template&lt;typename T&gt; static std::optional&lt;T&gt; Get(std::string id) { auto&amp; parameters = GetInstance(); auto it = parameters.params.find(id); if(it == parameters.params.end()) { return std::nullopt; } try { return std::any_cast&lt;T&gt;(it-&gt;second); } catch(std::bad_any_cast&amp;) { return std::nullopt; } } private: static Parameters&amp; GetInstance() { static Parameters parameters; return parameters; } Parameters() = default; Parameters(const Parameters&amp;) = delete; Parameters(Parameters&amp;&amp;) = delete; private: std::map&lt;std::string, std::any&gt; params; }; </code></pre> <p>usage example</p> <pre><code> Parameters::Set&lt;int&gt;("five", 5); std::optional&lt;int&gt; x = Parameters::Get&lt;int&gt;("five"); // 5 std::optional&lt;int&gt; y = Parameters::Get&lt;int&gt;("six"); // no value </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:21:40.560", "Id": "474262", "Score": "0", "body": "At the moment I see 2 things which might get the question closed, the first is that there is no code showing how to use this class, which would make it off-topic because there is not enough context to review the code. Do you have a unit test that you wrote to test this that you could add to the question? Asking about how to make this multi threaded is also off-topic, we review working code, we can't tell you how to add features. Please see out guidelines at https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T19:41:51.950", "Id": "474269", "Score": "0", "body": "\"How would you make it to work from multiple threads?\" It's a singleton, are you sure this is wise?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T06:45:34.303", "Id": "474303", "Score": "0", "body": "First step making something work in a concurrent setting: define semantics." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T06:51:29.813", "Id": "474304", "Score": "0", "body": "[no code showing how to use this class](https://codereview.stackexchange.com/q/241662/#comment474262_241662) irritated me given `usage example`, but pacmaninbw is right: in what kind of situation is it of advantage to be able to invent IDs \"post compile-time\"?" } ]
[ { "body": "<p>This got too long to be a comment, so posting an answer.</p>\n\n<p>We don't know your use case, so it's hard to know whether you are the 1 in 1,000,000 who actually needs something like this. But most likely this is a bad idea.</p>\n\n<ol>\n<li><p>You could get the name wrong. Using string for variable identifiers is error prone. Probably most programmers run into this at some point. A better thing to do is to (either redesign completely or) use strings with compile-time constant identifiers.</p></li>\n<li><p>You could get the type wrong. That is, you could set type A and try to get type B. <code>std::any</code> will catch most of (all of?) these mistakes at runtime (altho your callers cannot tell if they tried the wrong type or the wrong name), but you won't be able to sleep at night because you'll worry that there is some code path you haven't tested that gets this wrong. When the compiler type checks your program, it checks every code path! That lets you rest easy... Can you redesign this to check at compile time? That's non trivial; it would be much easier to use the normal variables we all know and love.</p></li>\n<li><p>You said these parameters are global. Does that mean you are putting your existing globals into a struct of globals? A lot of code bases have something like this, but a real fix would be get rid of all the globals altogether. Or get rid of some of the uses to make progress.</p></li>\n<li><p>This seems pretty slow if the alternative is to use variables that are \"looked up\" at compile time.</p></li>\n<li><p>This is relatively easy to make thread safe (add locks as necessary), but imo difficult to make \"thread useful\" because you cannot distinguish between (a key that will never be in the map) and (a key that is about to be in the map). If all the sets happen before all the gets, then maybe this doesn't matter to you.</p></li>\n</ol>\n\n<p>Again, I don't know your use case, but could you use a strongly typed struct of parameters instead? I.e. no <code>std::map</code> and no <code>std::any</code>, but instead members (that may be optionals or sets) for each parameter/key?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T08:43:50.663", "Id": "474312", "Score": "0", "body": "thanks for the answer! I need to rethink to use this code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:47:27.737", "Id": "241666", "ParentId": "241662", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:17:43.160", "Id": "241662", "Score": "-1", "Tags": [ "c++", "c++17" ], "Title": "A singleton class to store global parameters" }
241662
<p>I am new to Python (and to programming). I tried to implement this game in Python and took some help from the code reviews of similar questions posted on this website.</p> <pre><code># rock paper scissors game import random import sys choices = ["rock", "paper", "scissors"] def check_victory(computer_choice, user_choice): if user_choice == computer_choice: return "tie" elif computer_choice == "rock" and user_choice == "paper": return "won" elif computer_choice == "paper" and user_choice == "scissors": return "won" elif computer_choice == "scissors" and user_choice == "rock": return "won" else: return "lost" def play(): # get input from user user_choice = None while user_choice not in choices: user_choice = input("Enter your choice: ") # check if user wants to quit if user_choice == "quit": sys.exit() computer_choice = random.choice(choices) # output result print(f"Computer choose: {computer_choice}") print("You " + check_victory(computer_choice, user_choice), end="\n\n") if __name__ == "__main__": while True: play() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>overall this code looks nice and tidy, and it passes <code>pylint</code> with minimal errors which is a good start!</p>\n\n<p>Some observations:</p>\n\n<p>If you're returning in an <code>if</code> block you don't need to use <code>elif</code> and/or <code>else</code> since on match the code will never continue. I'd probably use <code>or</code> instead of 3 <code>elif</code> statements to avoid having the `return \"won\" repeated. And maybe carry the result in a variable - this allows you to set a default and avoid one test. So something like:</p>\n\n<pre><code>def check_victory(computer_choice, user_choice):\n result = \"lost\"\n if user_choice == computer_choice:\n result = \"tie\"\n if computer_choice == \"rock\" and user_choice == \"paper\" or \\\n computer_choice == \"paper\" and user_choice == \"scissors\" or \\\n computer_choice == \"scissors\" and user_choice == \"rock\":\n result = \"won\"\n return result\n</code></pre>\n\n<p>Another thing might be to replace some of the descriptive comments with docstrings - less important in a small program, but a useful habit to get into for more complex projects later on.</p>\n\n<p>Finally since you're using f-strings for the first print, you could use them for both?</p>\n\n<pre><code>print(f\"Computer choose: {computer_choice}\")\nprint(f\"You {check_victory(computer_choice, user_choice)}\\n\\n\")\n</code></pre>\n\n<p>Only other things are 'features' like documenting the choices available, providing 'shortcuts' like r/p/s etc - but those are 'optional extras' and nothing to do with the code quality!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T16:20:13.303", "Id": "241670", "ParentId": "241665", "Score": "5" } } ]
{ "AcceptedAnswerId": "241670", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:43:17.033", "Id": "241665", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "game", "rock-paper-scissors" ], "Title": "Rock, paper, scissors in Python 3" }
241665
<p>I'm trying to learn Clojure coming from a Java background. I have written a simple implementation of Conway's game of life in both Clojure and Java, trying to keep the overall structure of the code as similar as possible to make them easy to compare.</p> <p>I'm measuring the number of simulation steps per second and my Java version can easily go as high as 1000 steps per second, but my clojure version barely hits 4 steps per second.</p> <p>This is my first non trivial clojure program and I think the problem must be me not using clojure correctly rather than clojure being this much slower. Can any Clojure pros here tell me where I'm going wrong?</p> <p>I'm using seesaw for the Clojure version and regular Swing for the java version.</p> <p>I know there are faster algorithms for Conway's game of life but right now I'm mostly interested in trying to get to grips with how Clojure works and thought the naive algo would be the best starting point.</p> <p>Clojure version:</p> <pre><code>(ns gol.core (:gen-class) (:use seesaw.core seesaw.color seesaw.graphics)) (def wCells 100) (def hCells 100) (def cellSize 5) (def cellColor (color 0 255 0)) (def statusBarHeight 20) (def windowWidth (* wCells cellSize)) (def windowHeight (+ statusBarHeight (* hCells cellSize))) (def frameCap 30) (def maxFrameDuration (quot 1000 frameCap)) (defn vec2d [sx sy fun] (mapv (fn[x](mapv (fn[y] (fun x y)) (range sx))) (range sy))) (def globalBoard (atom (vec2d wCells hCells (fn [x y] (rand-int 2))))) (def lastTime (atom (System/currentTimeMillis))) (defn neighbors [board p] (let [x (first p) y (second p) xrange (range (dec x) (+ 2 x)) yrange (range (dec y) (+ 2 y))] (for [i xrange j yrange :let [q [(mod i wCells) (mod j hCells)] ] :when (not= p q)] (get-in board q)))) (defn gol [board p] (let [v (get-in board p) n (count (filter pos? (neighbors board p)))] (cond (= n 3) 1 (and (= v 1) (= n 2)) 1 :else 0))) (defn fps [] (let [previous @lastTime current (System/currentTimeMillis) diff (- current previous) toSleep (- maxFrameDuration diff)] (when (pos? toSleep) (Thread/sleep toSleep)) (reset! lastTime (System/currentTimeMillis)) (double (/ 1000 (- (System/currentTimeMillis) previous))))) (defn painter [c g] (let [board @globalBoard xrange (range 0 wCells) yrange (range 0 hCells) red (color 255 0 0) blue (color 0 0 255)] (.setColor g red) (.drawRect g 0 0 windowWidth (- windowHeight statusBarHeight)) (.setColor g cellColor) (doseq [i xrange j yrange :when (= 1 (get-in board [i j]))] (.fillRect g (* cellSize i) (* cellSize j) cellSize cellSize)) (.setColor g blue) (.drawString g (str "Simulations per second: " (fps)) 50 (- windowHeight 5)) (reset! globalBoard (vec2d wCells hCells (fn [x y] (gol board [x y])))) )) (def m-canvas (canvas :id :mcanvas :background :black :paint painter)) (defn -main [&amp; args] (invoke-later (-&gt; (frame :title "Game Of Life", :width (+ 3 windowWidth), :height (inc windowHeight), :content m-canvas, ; :on-close :exit ) show!) ) ) (def t (timer (fn [e] (repaint! m-canvas)) :delay 1)) </code></pre> <p>Java version:</p> <pre><code>package gol; import java.awt.Color; import java.awt.Graphics; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JPanel; public class GOL { private static final int wCells = 100; private static final int hCells = 100; private static final int cellSize = 5; private static final Color cellColor = new Color(0,255,0); private static final int statusBarHeight = 20; private static final int windowWidth = wCells * cellSize; private static final int windowHeight = statusBarHeight + (hCells * cellSize); private static final int frameCap = 10; private static final int maxFrameDuration = 1000/frameCap; private static int[][] globalBoard = new int[wCells][hCells]; static { Random rng = new Random(); for (int i = 0;i&lt;wCells;i++) { for (int j = 0;j&lt;hCells;j++) { globalBoard[i][j] = rng.nextInt(2); } } } private static long lastTime = System.currentTimeMillis(); private static int gol(int[][] board, int x, int y) { int v = board[x][y]; int n = 0; for (int i = x-1;i&lt;x+2;i++) { for (int j = y-1;j&lt;y+2;j++) { int ii = (wCells+i)%wCells; int jj = (hCells+j)%hCells; int b = board[ii][jj]; if (!(ii == x &amp;&amp; jj == y) &amp;&amp; b == 1) { n++; } } } if (n==3) return 1; if (v==1 &amp;&amp; n == 2) return 1; return 0; } private static double fps() { long previous = lastTime; long diff = System.currentTimeMillis() - previous; long toSleep = maxFrameDuration - diff; if (toSleep &gt; 0) { try { Thread.sleep(toSleep); } catch (InterruptedException e) { e.printStackTrace(); } } lastTime = System.currentTimeMillis(); return 1000.0 / (System.currentTimeMillis()-previous); } static class GUI extends JPanel { public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, windowWidth, windowHeight); g.setColor(Color.RED); g.drawRect(0, 0, windowWidth, windowHeight-statusBarHeight); g.setColor(cellColor); for (int i = 0;i&lt;wCells;i++) { for (int j = 0;j&lt;hCells;j++) { if (globalBoard[i][j] == 1) { g.fillRect(i*cellSize, j*cellSize, cellSize, cellSize); } } } g.setColor(Color.BLUE); g.drawString("Simulations per second: "+fps(), 50, windowHeight - 5); int[][] newBoard = new int[wCells][hCells]; for (int i = 0;i&lt;wCells;i++) { for (int j = 0;j&lt;hCells;j++) { newBoard[i][j] = gol(globalBoard, i, j); } } globalBoard = newBoard; } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setTitle("Game Of Life"); frame.setBounds(0, 0, windowWidth+3, windowHeight); frame.setContentPane(new GUI()); frame.setVisible(true); new Timer().schedule(new TimerTask() { public void run() { frame.repaint(); } }, 0, 1); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:31:07.633", "Id": "474265", "Score": "0", "body": "Have you attempted to profile the clojure version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:50:03.233", "Id": "474267", "Score": "1", "body": "I did, after finding some reflection warnings I added a type hint of ^java.awt.Graphics to the g argument in painter and now I'm finding most of the time in the clojure version is being spend in the .fillRect method. The java version also calls this method but the clojure version seems to be spenidng an order of magnitude more time there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:54:53.017", "Id": "474268", "Score": "0", "body": "You might want to improve the question by adding the profile information." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T15:49:34.230", "Id": "241667", "Score": "2", "Tags": [ "java", "comparative-review", "clojure" ], "Title": "Why does my Clojure implementation of Conway's Game of Life run so much slower than my Java implementation?" }
241667
<p>I have been playing around with python and made myself a hangman game.</p> <p>Questions:</p> <ol> <li><p>How readable my code is?</p></li> <li><p>Are there any logical errors that I'm not aware of?</p></li> <li><p>How to improve it?</p></li> <li><p>Is there a better way to approach the problem?</p></li> <li><p>Overall, how would you rate it out of 10?</p></li> </ol> <hr> <pre><code>import json, random, urllib.request def get_word(): url = urllib.request.urlopen("https://raw.githubusercontent.com/sindresorhus/mnemonic-words/master/words.json") words = json.loads(url.read()) random_word = random.choice(words) return random_word saved_word = [] word = get_word() saved_word = word length = len(word) tries = 4 def drawing(t): draw = {0: ''' ---------- | | | O | /|\\ | / \\ | ----- ''', 1: ''' ---------- | | | O | /|\\ | / \\ ----- ''', 2: ''' | | | O | /|\\ | / \\ ----- ''', 3: ''' O /|\\ / \\ ----- ''', 4: ''' O /|\\ / \\ ''' } d = draw[t] print(d) def what_range(width): # checks how many letters should be covered depending on the length of the word if width &lt;= 3: return 2 elif 3 &lt; width &lt; 6: return 3 else: return 4 def mixer(w): # creates the blanks on the word m = "" item = list(w) width = what_range(length) for z in range(width): n = random.randint(0, length - 1) if str(n) in m: while str(n) in m: n = random.randint(0, length - 1) if str(n) not in m: m = m + str(n) item.pop(n) item.insert(n, "_") print("".join(item)) return "".join(item) def find_letter(numbers, item, letter): i = list(item) for number in numbers: i.pop(number) i.insert(number, letter) return "".join(i) word = mixer(word) completed = False while not completed: letter = input("enter a letter: ") n = 0 nums = [] if letter in saved_word: for l in saved_word: if l == letter: nums.append(n) n += 1 else: tries -= 1 print(f"Tries: {tries}") drawing(tries) if tries != 0: word = find_letter(nums, word, letter) print(word) if word == saved_word: print("You WIN!") completed = True else: print(f"You FAILED!\nThe word was {saved_word}") exit() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T17:25:09.667", "Id": "474260", "Score": "0", "body": "Please change your question title to a brief description what your code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:28:14.750", "Id": "474264", "Score": "0", "body": "Have you tested the code and does it work as expected? `Are there any logical errors that I'm not aware of?`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T18:34:48.723", "Id": "474266", "Score": "0", "body": "Sorry, I have tested the code and it does work as I expected it, but would like to know if there are any other ways I can improve my coding, or is it readable." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T16:24:54.170", "Id": "241671", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Feedback on hangman game about coding style" }
241671
<p><strong><em>Description</em></strong></p> <p>I've developed an application which use <a href="https://github.com/axios/axios" rel="nofollow noreferrer">axios</a> to communicate with the <a href="https://developer.paypal.com/docs/api/overview/" rel="nofollow noreferrer">PayPal API</a>. PayPal has a <a href="https://developer.paypal.com/docs/checkout/reference/server-integration/setup-sdk/#set-up-the-environment" rel="nofollow noreferrer">NodeJS SDK</a>, but unfortunately this doesn't support the <code>Subscription API</code>, so I'm using <code>axios</code> to handle the <code>API</code> requests.</p> <p>The code is working well, but I want improve the <code>Access Token</code> logic. Essentially the <code>PayPal</code> token expiry is 1 hour, and I don't want to get a new token each time I perform a request.</p> <p>So I've used a mechanism that allows me to store the token in my own database and through the <code>interceptors</code> of <code>Axios</code> I retrieve that token. If the token is expired, I get a new one.</p> <p><strong><em>Code</em></strong></p> <p>First of all, I've declared the <code>axios</code> instance, I don't want use the global instance 'cause I could reuse <code>axios</code> for other <code>API</code> payment gateways such as <code>Stripe</code>:</p> <pre><code>const qs = require('qs'); const axios = require('axios'); const tokenUtils = require('./token-utils'); const baseURL = 'https://api.sandbox.paypal.com'; let instance = axios.create({ baseURL }) </code></pre> <p>then I defined the <code>interceptors</code> which is something like a <code>middleware</code> and is executed before any request:</p> <pre><code>instance.interceptors.response.use( // Return response as no errors raised function (response) { return response }, function (error) { const errorResponse = error.response; // Check if token is expired if (isTokenExpiredError(errorResponse)) { return resetTokenAndReattemptRequest(error) } // Error was not generated by the expired token return Promise.reject(error); } ) </code></pre> <p>then I have the <code>isTokenExpiredError</code> which simply checks if the token is expired looking at the <code>http</code> status code:</p> <pre><code>function isTokenExpiredError(errorResponse) { return (errorResponse.status == 401) ? true : false; } </code></pre> <p>Next, I have the <code>resetTokenAndReattemptRequest</code> function which actually checks if the token is expired and eventually gets a new one:</p> <pre><code>let isAlreadyFetchingAccessToken = false; async function resetTokenAndReattemptRequest(error) { try { const { response } = error; // Get the stored token const accessToken = await tokenUtils.getResetToken(); // Start the token generation task // Add the failed request to the subscriber const retryOriginalRequest = new Promise(resolve =&gt; { addSubscriber(newToken =&gt; { response.config.headers.Authorization = 'Bearer ' + newToken; resolve(axios(response.config)); }); }); // There are no fetchint token request and the access token is expired (no length) if (!isAlreadyFetchingAccessToken &amp;&amp; accessToken === "") { isAlreadyFetchingAccessToken = true; const response = await axios({ method: 'POST', url: `${baseURL}/v1/oauth2/token`, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Credentials': true }, data: qs.stringify({ grant_type: 'client_credentials' }), auth: { username: "your paypal client id", password: "your paypal secret id" } }); // An error happened when asking for a new token if (!response.data) { return Promise.reject(error); } const newToken = response.data.access_token; // Store generated token in db for a next usage tokenUtils.saveToken(newToken); isAlreadyFetchingAccessToken = false; onAccessTokenFetched(newToken); } return retryOriginalRequest; } catch (err) { return Promise.reject(err); } } </code></pre> <p>I commented the whole code, hoping to be much clear as possible, feel free to ask any question eventually. Essentially, a failed request is added to the <code>subscribers</code> which is handled by the following:</p> <pre><code>let subscribers = []; function addSubscriber(callback) { subscribers.push(callback); } </code></pre> <p>each subscribed <code>request</code> is execute after the token generation by:</p> <pre><code>function onAccessTokenFetched(accessToken) { subscribers.forEach(callback =&gt; callback(accessToken)); subscribers = []; } </code></pre> <p>So an <code>API</code> request will look like this:</p> <pre><code>instance.get( `${baseURL}/v1/billing/subscriptions/I-0SUB6KG4203B`) .then(response =&gt; { console.log(response.data); return response.data; }).catch((error) =&gt; { console.log('error'); return null; }); </code></pre> <p>I also have a <code>tokenUtils</code> which contains two function:</p> <ul> <li>getAccessToken: get the token stored from a database</li> <li>storeAccessToken: store a token to the db</li> </ul> <p>I've also uploaded the full code <a href="https://gofile.io/?c=gF6OVG" rel="nofollow noreferrer">here</a>, you may take a look.</p>
[]
[ { "body": "<h2>General Thoughts</h2>\n\n<p>I haven't used the paypal API before but did obtain credentials and ran the code. I don't see much that would improve the logic to fetch the token but do see small improvements that can be made.</p>\n\n<h2>Review</h2>\n\n<p>A common convention is to have constants in <code>ALL_CAPS</code> - so <code>baseURL</code> can be converted to <code>BASE_URL</code> E.g. per <a href=\"https://google.github.io/styleguide/jsguide.html#naming-constant-names\" rel=\"nofollow noreferrer\">Google JS style guide</a>, <a href=\"https://airbnb.io/javascript/#naming--uppercase\" rel=\"nofollow noreferrer\">airbnb style guide</a>. While it isn't totally immutable unless frozen it signifies to readers that it should not be modified.</p>\n\n<p>For more information on the topic, see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Constants\" rel=\"nofollow noreferrer\">the MDN documentation about constants</a>, as well as answers to <a href=\"https://stackoverflow.com/q/40291766/1575353\">this SO question</a>.</p>\n\n<p>A more appropriate name than <code>isTokenExpiredError</code> would be <code>isResponseUnauthenticated</code> since the 401 error means \"<em>Authentication failed due to invalid authentication credentials.</em>\"<sup><a href=\"https://developer.paypal.com/docs/api/reference/api-responses/#http-status-codes\" rel=\"nofollow noreferrer\">1</a></sup></p>\n\n<blockquote>\n<pre><code>return (errorResponse.status == 401) ? true : false;\n</code></pre>\n</blockquote>\n\n<p>This is overly verbose - it could be simplified to:</p>\n\n<pre><code>return (errorResponse.status == 401)\n</code></pre>\n\n<p>There is only one usage of <code>errorResponse</code> after it is assigned - it can be eliminated by substituting <code>error.response</code> in the one place it is used.</p>\n\n<p>The variable <code>subscribers</code> could be truncated with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\" rel=\"nofollow noreferrer\"><code>.length = 0</code></a> in <code>onAccessTokenFetched()</code> and then be declared with <code>const</code> because it wouldn't be re-assigned. This helps avoid accidental re-assignment in the future when the code is expanded.</p>\n\n<p>The request made with <code>axios()</code> to get the token could be simplified using <a href=\"https://github.com/axios/axios#axiosposturl-data-config\" rel=\"nofollow noreferrer\"><code>axios.post(url[, data[, config]])</code></a></p>\n\n<pre><code>const response = await axios.post(`${baseURL}/v1/oauth2/token`, data, {...})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T08:50:40.833", "Id": "474908", "Score": "0", "body": "Thanks for your answer! I just have some questions:\n1. Should be all the constants `ALL_CAPS`? Even those inside the methods?\n2. Could you suggest a specific folder name convention where I can add this `Axios` interceptors?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T23:53:52.830", "Id": "474967", "Score": "1", "body": "1. I would only use that for hard-coded values, which likely won’t change ever, and not other variables even if they shouldn’t be reassigned - e.g. an array like `subscribers`. 2. You could make a wrapper that returns/exports `axios` Or `instance`- maybe call it `axios-instance`, `axios-wrapper` or something similar" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T08:38:33.350", "Id": "474986", "Score": "0", "body": "Thansk for your suggests I've appreciated" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T00:13:01.240", "Id": "241978", "ParentId": "241679", "Score": "1" } } ]
{ "AcceptedAnswerId": "241978", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T19:22:00.960", "Id": "241679", "Score": "4", "Tags": [ "javascript", "node.js", "api", "axios", "ecmascript-8" ], "Title": "Access token regeneration for Axios requests" }
241679
<p>I made a script to start something akin to a "session" in which I start services and open tcp and udp ports in the firewall in order to work with, for example, a full stack project, and stop and close the corresponding services and ports once I'm done using them.</p> <p>When I call the script, I place the services with the <code>-s</code> options and the ports with <code>-p</code>. After the <code>-s</code> option I input all the services in I want to start and then likewise with the ports. You can skip the services and/or the ports.</p> <p>When I start the script, it starts the services via <code>systemctl start</code> and opens the ports via <code>ufw allow</code>. Then it pauses and awaits a key press after which it stops the services and closes the ports.</p> <p>The services on my system are managed by Systemctl. The firewall software I use is Uncomplicated Firewall (UFW).</p> <p>Usage: <code>./start -s service1 service2 -p port1 port2</code></p> <p>Example: <code>./start -s postgresql httpd -p WWW</code></p> <pre><code>#!/bin/bash if [ $EUID != 0 ]; then sudo "$0" "$@" exit $? fi flag= services=() ports=() while [ -n "$1" ]; do case "$1" in -s) flag="SERVICE" ;; -p) flag="PORT" ;; *) case $flag in SERVICE) services+=($1) ;; PORT) ports+=($1) ;; esac ;; esac shift done # Starts the services and opens the ports start() { for serv in ${services[*]}; do echo "Starting service $serv" systemctl start $serv done for port in ${ports[*]}; do echo "Opening port $port" ufw allow $port &amp;&gt; /dev/null done } # Stops the services and closes the ports finish() { for serv in ${services[*]}; do echo "Stopping service $serv" systemctl stop $serv done for port in ${ports[*]}; do echo "Closing port $port" ufw deny $port &amp;&gt; /dev/null done } # Catch ^c and terminal close signals: trap finish 0 start echo echo "Awaiting interruption..." echo while :; do read -t 1 -n 1 -s PASSWORD if [ $? = 0 ] ; then break fi done </code></pre> <p>I'm looking for feedback, mainly to see if I could improve this productive waste of time.</p> <p>The new things I learned by doing this script were:</p> <ul> <li>The parsing of options (-s and -p) with <code>case ... in</code> and <code>shift</code>;</li> <li>The use of <code>trap</code>;</li> <li>The "press key to continue" loop.</li> </ul> <p>The only caveat I found was that even though I use <code>trap</code> to detect when the script dies it does not work if the terminal it runs on closes, leaving the services started. It doesn't work either if the signal I trap are <code>SIGINT</code> and <code>SIGCHLD</code>.</p> <p>Thanks for reading.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T19:39:52.123", "Id": "241680", "Score": "3", "Tags": [ "bash", "shell" ], "Title": "Systemctl services start and UFW ports allow script" }
241680
<p>Just for the sake of practice, I've decided to write a code for polynomial regression with Gradient Descent</p> <p>Code:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from scipy.optimize import approx_fprime as gradient class polynomial_regression(): def __init__(self,degrees): self.degree = degrees self.weights = np.random.randn(degrees+1) self.training_loss = [] self.loss_type = None def predict(self, x: float): output = 0 for i in range(len(self.weights)-1): output += (x**(i+1) * self.weights[i]) return output + self.weights[-1] def fit(self,X: '1 dim array',y: '1 dim array',epochs,lr,loss,ridge=False,reg_rate=0.1): training_loss = [] if loss == 'MSE': loss = MSE self.loss_type = 'MSE' elif loss == 'RMSE': loss = RMSE self.loss_type = 'RMSE' else: raise Exception('Undefined loss function') for epoch in range(epochs): self.weights -= lr*gradient(self.weights, MSE, [np.sqrt(np.finfo(float).eps)/100]*len(self.weights), X, y, ridge, reg_rate ) training_loss.append(MSE(self.weights,X,y)) self.training_loss = training_loss def MSE(w,X,y,ridge=False,reg_rate=0.1): total = 0 weights = w[:-1] bias = w[-1] for i in range(len(X)): total += (np.dot(weights,[X[i]**(p+1) for p in range(len(weights))]) + bias - y[i])**2 if ridge == False: return (1/len(X)) * total else: return (1/len(X)) * total + reg_rate*((w**2).sum()) def RMSE(w,X,y,ridge=False, reg_rate = 0.1): total = 0 weights = w[:-1] bias = w[-1] for i in range(len(X)): total += (np.dot(weights,[X[i]**(p+1) for p in range(len(weights))]) + bias - y[i])**2 if ridge == False: return np.sqrt((1/len(X)) * total) else: return np.sqrt((1/len(X)) * total) + reg_rate*((w**2).sum()) def build_graph(X,y,model): plt.figure(figsize=(20,8)) #Scatter plot of the dataset and the plot of the model's predictions plt.subplot(1,2,1) plt.scatter(X,y) X.sort() plt.plot(X,model.predict(X),c='red') plt.title('Model',size=20) #Curve of the training loss plt.subplot(1,2,2) plt.plot(np.arange(len(model.training_loss)),model.training_loss,label=f'{model.loss_type} loss') plt.legend(prop={'size': 20}) plt.title('Training loss',size=20) </code></pre> <p>Several tests </p> <pre><code> rng = np.random.RandomState( 1) x = (np.linspace(1,5,100)) y = 3*x + 10 + rng.rand(100) x = x/10 y = y/10 degree = 1 epochs = 120 learning_rate = 0.9 model = polynomial_regression(degree) model.fit(x, y, epochs, learning_rate, loss='MSE', ridge=False,) build_graph(x,y,model) </code></pre> <p>Output </p> <p><a href="https://i.stack.imgur.com/7CBqw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7CBqw.png" alt="enter image description here"></a></p> <p>And now with more complex dataset</p> <pre><code>rng = np.random.RandomState( 1) x = (np.linspace(1,5,100)) y = (10*np.cos(x) + rng.rand(100)) x = x/10 y = y/10 degree = 3 epochs = 8*10**3 learning_rate = 0.9 model = polynomial_regression(degree) model.fit(x, y, epochs, learning_rate, loss='MSE', ridge=False,) build_graph(x,y,model) </code></pre> <p>Output</p> <p><a href="https://i.stack.imgur.com/IMbuO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IMbuO.png" alt="enter image description here"></a></p> <p>Notes:</p> <ol> <li><p>You might wonder why I moved functions for MSE and RMSE out of the class. The main reason is because <code>approx_fprime</code> (I renamed it as <code>gradient</code>, for clarity) requires loss function to place an array of variables for which we calculate the gradient as the first argument (see the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.approx_fprime.html" rel="noreferrer">documentation</a>). If I am to move <code>MSE</code> and <code>RMSE</code> into the class, the first argument, of course, will be <code>self</code>.</p></li> <li><p>Admittedly, Gradient Descent is <a href="https://stats.stackexchange.com/questions/350130/why-is-gradient-descent-so-bad-at-optimizing-polynomial-regression">not</a> the best choice for optimizing polynomial functions. However, I would still prefer to use it here, just for the sake of solidifying my understanding of how GD works.</p></li> <li><p>For more complex dataset (when we'd need to use higher degrees of polynomial), the model converges <strong>very slowly</strong> (see the training loss for the second dataset). If possible, I would like you to elaborate a bit on what might be the reason.</p></li> </ol> <h2><strong>What can be improved?</strong></h2> <p>Any suggestions will be welcome: algorithm efficiency/code style/naming conventions, or anything else you can come up with. Thanks!</p>
[]
[ { "body": "<h2>Encoding polynomials</h2>\n\n<p>According to your code, you represent a polynomial \n<span class=\"math-container\">$$\\sum\\limits_{k=0}^{n} a_kx^k$$</span> as <code>[a_1, ..., a_n, a_0]</code> which is odd to my eyes.</p>\n\n<p>The most common way to represent a polynomial is probably<code>[a_n, ..., a_1, a_0]</code>. Then for example your <code>predict</code> function becomes</p>\n\n<pre><code>def predict(self, x: float):\n return np.vander([x], len(self.weights)).dot(self.weights)\n</code></pre>\n\n<p>which is vectorised (by using <code>.dot</code>), so it should be a bit faster.\nOn the other hand, we can vectorise it further by allowing vectorial inputs:</p>\n\n<pre><code>def predict(self, x):\n return np.vander(x, len(self.weights)).dot(self.weights)\n</code></pre>\n\n<p>This allows us to evaluate things like <code>predict(np.array([-1, 0, 1]))</code>.</p>\n\n<p>One consequence is that in your error calculation code you can write something like</p>\n\n<pre><code>mean_sq_error = ((predict(X) - y)**2).mean()\n</code></pre>\n\n<p>which is vectorised and easy to read.</p>\n\n<h2>Calculating the gradients</h2>\n\n<p>In (the euclidean norm) <code>norm_2</code> polynomial fitting reduces to finding <code>weights</code> such that the value of </p>\n\n<pre><code>norm_2(vander(x).dot(weights) - y)\n</code></pre>\n\n<p>is minimal. The minimum point doesn't change if we compose <code>norm_2</code> by some non-decreasing function from the left, so e.g. using any of</p>\n\n<pre><code>norm_2_sq = (^ 2) . norm_2\nmse_norm = (* 1/n) . (^ 2) . norm_2\nrmse_norm = (^ 1/2) . mse_norm\n</code></pre>\n\n<p>will result in the same minimum points. The most natural of these is arguably <code>norm_2_sq</code>.</p>\n\n<p>Let us generalize using this norm. Given a matrix <code>A</code>, and a vector <code>b</code>, we'd like to find <span class=\"math-container\">$$\\operatorname{argmin}_x \\| Ax - b \\|_2^2,$$</span> \nbut <span class=\"math-container\">$$\\| Ax - b \\|_2^2 = (Ax -b)^T (Ax-b) = x^TA^TAx - x^TA^Tb -b^TAx-b^Tb,$$</span>\nso its gradient is\n<span class=\"math-container\">$$\n2x^T A^T A - 2b^TA.\n$$</span>\nIf you want, you can use this to calculate the gradients of <code>mse</code>, <code>rmse</code> using the chain rule. You don't need to use <code>approx_fprime</code>.</p>\n\n<p>On the other hand, since its second derivative, <code>2A'A &gt;= 0</code>, our functional is convex, so it takes its global minimum at the zero of its gradient, i.e. the solution of the so-called normal equation:\n<span class=\"math-container\">$$\nx^T A^TA = b^TA \\quad \\Leftrightarrow \\quad A^TA x = A^T b.\n$$</span></p>\n\n<p>As a practice problem, you can solve this equation using some iterative method (e.g. the conjugate gradient method).</p>\n\n<h2>General comments</h2>\n\n<p>The general consensus is that function names should be written in <code>snake_case</code>, class names in <code>CamelCase</code></p>\n\n<p>There are a few unnecessary spaces <code>RandomState( 1)</code>, parentheses <code>x = (np.linspace(1,5,100))</code>. <code>class PolynomialRegression:</code> is sufficient (no <code>()</code> needed).</p>\n\n<p>Given the ML context, I would reserve <code>weights</code>, <code>bias</code> for denoting the weights of a(n affine-) linear mapping. </p>\n\n<p>Despite writing</p>\n\n<pre><code> if loss == 'MSE':\n loss = MSE\n self.loss_type = 'MSE'\n elif loss == 'RMSE':\n loss = RMSE\n self.loss_type = 'RMSE'\n</code></pre>\n\n<p>you hard-coded <code>MSE</code> a few lines later.</p>\n\n<p>Tangentially related: <code>globals()[loss]</code> would be the method named by the value of <code>loss</code>, assuming this method is defined globally.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T22:34:22.163", "Id": "241685", "ParentId": "241682", "Score": "5" } }, { "body": "<ul>\n<li><p><code>MSE</code> and <code>RMSE</code> are suspiciously similar. Shouldn't</p>\n\n<pre><code>def RMSE(w,X,y,ridge=False, reg_rate = 0.1):\n return np.sqrt(MSE(w,X,y,ridge=False, reg_rate = 0.1))\n</code></pre>\n\n<p>suffice?</p></li>\n<li><p><code>MSE</code> could be streamlined:</p>\n\n<pre><code> ....\n retval = (1/len(X)) * total\n if ridge:\n retval += reg_rate*((w**2).sum())\n return retval\n</code></pre></li>\n<li><p>The loop</p>\n\n<pre><code> for i in range(len(X)):\n total += (np.dot(weights,[X[i]**(p+1) for p in range(len(weights))]) + bias - y[i])**2\n</code></pre>\n\n<p>raised some brows on the first reading. Indexing <code>y</code> with <code>i</code> - which enumerates <code>X</code> - is very suspicious. Is there any precondition on lengths of <code>X</code> and <code>y</code>?</p>\n\n<p>Looking at your tests it appears that <span class=\"math-container\">\\$y_i = f(X_i)\\$</span>, so they are of the same length indeed. I strongly recommend to make it explicit, maybe by passing a list of tuples <code>x, y</code> rather than two disconnected lists. I am not a numpy expert, so I can't say how it may affect performance.</p>\n\n<p>Similarly, I am not sure that <code>len(weights)</code> is a good choice for an inner comprehension. <code>degrees</code> seems much more natural.</p>\n\n<p>In any case, indexing here is anti-pythonic. Consider</p>\n\n<pre><code> for arg, val in zip(X, y):\n total += (np.dot(weights,[arg**(p+1) for p in range(degrees + 1)]) + bias - val)**2\n</code></pre></li>\n<li><p>I would like to see the tests exercising <code>ridge = True</code> case. If you don't expect to ever use this case, do not pass <code>ridge</code> argument to <code>fit</code> at all.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T00:38:37.917", "Id": "241689", "ParentId": "241682", "Score": "1" } } ]
{ "AcceptedAnswerId": "241685", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T20:12:43.987", "Id": "241682", "Score": "5", "Tags": [ "python", "machine-learning" ], "Title": "Polynomial regression with Gradient Descent: Python" }
241682
<p>This code is for procedural terrain generation in a game. The generation happens in form of a grid of so called "chunks". Each chunk has the same size and has its column and row index in the grid associated with it. The grid of chunks expands into the negative dimension as well. The chunk data itself is a 2D array of char values.</p> <p>Now to actually render the terrain, I have a "window" around the player. That window is larger than a couple of chunks and this window also has a char array for the terrain data. It's important that the window does not necessarily need to be snapped to the grid!</p> <p>What this function does now is copy the corresponding parts of the chunks and insert the data into the window array at the right place. The code is currently quite inefficient because after a lot of trouble with more sophisticated approaches, I am effectively looping through the entire window once for each chunk. Then I have four IFs that ensure that only the pixels are copied that actually are inside the window.</p> <pre><code>void ExtWindow::RecalculateWindow(ExtWorld world, Point2D window_center, int width, int height, CharGridAcc window_data) { // Size of a chunk const int chunk_w = world.chunk_w; const int chunk_h = world.chunk_h; // Window borders int left_border = window_center.x - width / 2; int top_border = window_center.y - height / 2; int right_border = window_center.x + width / 2; int bottom_border = window_center.y + height / 2; // Find the minimal and maximal needed chunk indices int min_chunk_x = left_border / chunk_w; if (left_border &lt; 0) // Correction for negative positions min_chunk_x--; int max_chunk_x = right_border / chunk_w; if (right_border &lt; 0) // Correction for negative positions max_chunk_x--; int min_chunk_y = top_border / chunk_h; if (top_border &lt; 0) // Correction for negative positions min_chunk_y--; int max_chunk_y = bottom_border / chunk_h; if (bottom_border &lt; 0) // Correction for negative positions max_chunk_y--; // Loop through every required chunk for (int chunk_x = min_chunk_x; chunk_x &lt;= max_chunk_x; chunk_x++) for (int chunk_y = min_chunk_y; chunk_y &lt;= max_chunk_y; chunk_y++) { // Minimal and maximal pixels for both axis for the current chunk // The pixels are in the real coordinate system int chunk_min_pixel_x = chunk_x * chunk_w; int chunk_min_pixel_y = chunk_y * chunk_h; int chunk_max_pixel_x = (chunk_x + 1) * chunk_w; int chunk_max_pixel_y = (chunk_y + 1) * chunk_h; // Generate the chunk data CharGridAcc cur_chunk = world.AquireChunk(chunk_x, chunk_y)-&gt;GetData(); // Loop through the entire window (since this happens for every chunk, that is obviously unperformant on large windows) for (int x = 0; x &lt; width; x++) for (int y = 0; y &lt; height; y++) { // The current real world pixel coordinate int true_pixel_x = left_border + x; int true_pixel_y = top_border + y; // Several IFs that effectively constrain the segment below to only execute for // those pixels in the chunk that are actually part of the window if (true_pixel_x &gt;= chunk_min_pixel_x) if (true_pixel_y &gt;= chunk_min_pixel_y) if (true_pixel_x &lt; chunk_max_pixel_x) if (true_pixel_y &lt; chunk_max_pixel_y) { int pixel_in_chunk_x = true_pixel_x - chunk_min_pixel_x; int pixel_in_chunk_y = true_pixel_y - chunk_min_pixel_y; window_data[x][y] = cur_chunk[pixel_in_chunk_x][pixel_in_chunk_y]; } } } } </code></pre> <p>Does someone have an idea how to optimize this? Is there some sort of standard algorithm for such a task that requires cropping from multiple sources? Huge thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T22:01:31.053", "Id": "474283", "Score": "1", "body": "What is the definition of `CharGridAcc`? What does `GetData()` return?" } ]
[ { "body": "<p>Much of your work with X values can be lifted out of the Y loops, since they are invariant within the Y loop. This means that all the calculations of the various <code>pixel_x</code> values should be done before starting .</p>\n\n<p>Also the four nested <code>if</code> statements could be a bit cleaner as one big <code>if</code>. However, the two conditions that test the X values should be done before the Y loop, since if they are true the Y loop won't do anything.</p>\n\n<p>The conditions with that if can be handled before the loop starts by adjusting the loop starting and/or end values. This is similar to clipping graphics at the edge of a screen (or window). For example, if <code>true_pixel_x</code> is less than <code>chunk_min_pixel_x</code>, your loop won't do anything. If you start <code>x</code> at an appropriate value that condition can be skipped entirely.</p>\n\n<pre><code>int x = left_border &lt; chunk_min_pixel_x ? chunk_min_pixel_x - left_border : 0;\n</code></pre>\n\n<p>What that does is if the first X value will be out of range, we start <code>x</code> at the first value that is in range, otherwise we start at 0.</p>\n\n<p>Similar conditions can be done to determine the end X, start Y, and end Y values. Once that is done then your loop won't have any extra conditions in it and you won't need the <code>if</code> check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T18:48:56.140", "Id": "474360", "Score": "0", "body": "Oh wow! For some reason I never got that starting and ending at an appropiate X/Y correctly. I tried with the min/max function but you gave me the push into the right direction. The performance improvement is extreme. From 6500ms on an extreme case (when I generate massive terrain for a preview map) down to literally 0, aka below my benchmark resolution. Guess I can improve further with what you said, but that probably is premature optimization already. Huge thanks in every case.\n\nAm still new here. Is it recommended to post your optimized solution you have achieved with the help of users?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T22:08:57.467", "Id": "241684", "ParentId": "241683", "Score": "2" } } ]
{ "AcceptedAnswerId": "241684", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T21:39:51.590", "Id": "241683", "Score": "1", "Tags": [ "c++" ], "Title": "Cropping a window out of chunks" }
241683
<p>Some time ago, <a href="https://codereview.stackexchange.com/questions/240706/posix-bsd-extensions-implementation-of-shuf1">I implemented <code>shuf(1)</code></a>, but it had an issue: <a href="https://github.com/ibara/shuf/issues/1" rel="nofollow noreferrer">it ignored nul characters in the input</a>.</p> <p>This new version tries to solve this problem (but uses the double of memory).</p> <p><code>shuf(1)</code> shuffles the lines of the files given as arguments or the standard input (if no argument was provided) and print it. If the <code>-n NUM</code> option were given, prints <code>NUM</code> random lines from the files.</p> <pre><code>#include &lt;err.h&gt; #include &lt;errno.h&gt; #include &lt;fcntl.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #ifdef LIBBSD #include &lt;bsd/stdlib.h&gt; #include &lt;bsd/unistd.h&gt; #endif /* The buffer structure */ struct Buffer { char *chars; /* array of characters in the buffer */ char **linebeg; /* array of pointers to beginning of lines in chars[] */ char **lineend; /* array of pointers to end of lines in chars[] */ size_t maxchars; /* size of the array of characters */ size_t maxlines; /* size of the array of lines */ size_t nchars; /* number of characters in the buffer */ size_t nlines; /* number of lines in the buffer */ }; static int readfile(int fd, struct Buffer *buf); static void getlines(struct Buffer *buf); static void shuf(struct Buffer *buf, size_t nshuf); static void printbuf(struct Buffer *buf, size_t nshuf); static size_t getnshuf(const char *s); static void usage(void); /* sortnsearch: read a file into memory, sort it by lines and search a line */ int main(int argc, char *argv[]) { int c; int fd; int exitval; size_t nshuf; char *filename; struct Buffer buf = {NULL, NULL, NULL, 0, 0, 0, 0}; nshuf = 0; while ((c = getopt(argc, argv, "n:")) != -1) { switch (c) { case 'n': nshuf = getnshuf(optarg); if (nshuf == 0) errx(EXIT_FAILURE, "%s: invalid number of lines", optarg); break; default: usage(); break; } } argc -= optind; argv += optind; exitval = EXIT_SUCCESS; fd = STDIN_FILENO; filename = "stdin"; do { if (*argv) { if (**argv == '-' &amp;&amp; **(argv+1) == '\0') { fd = STDIN_FILENO; } else if ((fd = open(*argv, O_RDONLY)) == -1) { warn("%s", *argv); exitval = EXIT_FAILURE; argv++; continue; } filename = *argv++; } if (readfile(fd, &amp;buf) == -1) { warn("%s", *argv); exitval = EXIT_FAILURE; } if (fd != STDIN_FILENO) (void)close(fd); } while (*argv); getlines(&amp;buf); if (nshuf == 0 || nshuf &gt; buf.nlines) nshuf = buf.nlines; shuf(&amp;buf, nshuf); printbuf(&amp;buf, nshuf); free(buf.chars); free(buf.linebeg); free(buf.lineend); return exitval; } /* read file fd into memory in buf-&gt;chars */ static int readfile(int fd, struct Buffer *buf) { char tmpbuf[BUFSIZ], *tmp; size_t size = buf-&gt;maxchars; ssize_t n; while ((n = read(fd, tmpbuf, sizeof tmpbuf)) != 0 &amp;&amp; n != -1) { if (n + buf-&gt;nchars &gt;= size) { size = buf-&gt;maxchars + sizeof tmpbuf; /* overflow check */ if (size &lt;= buf-&gt;maxchars) { (void)free(buf-&gt;chars); errc(EXIT_FAILURE, EOVERFLOW, NULL); } if ((tmp = realloc(buf-&gt;chars, size)) == NULL) { (void)free(buf-&gt;chars); err(EXIT_FAILURE, "realloc"); } buf-&gt;chars = tmp; buf-&gt;maxchars = size; } memcpy(buf-&gt;chars + buf-&gt;nchars, tmpbuf, n); buf-&gt;nchars += n; } if (n == -1) return -1; return 1; } /* get beginnings end ends of lines from buf-&gt;chars into buf-&gt;linebeg and buf-&gt;lineend */ static void getlines(struct Buffer *buf) { size_t i; size_t size; char **tmp; if ((buf-&gt;linebeg = reallocarray(NULL, BUFSIZ, sizeof *buf-&gt;linebeg)) == NULL) err(EXIT_FAILURE, "realloc"); if ((buf-&gt;lineend = reallocarray(NULL, BUFSIZ, sizeof *buf-&gt;lineend)) == NULL) err(EXIT_FAILURE, "realloc"); buf-&gt;linebeg[buf-&gt;nlines++] = buf-&gt;chars; buf-&gt;maxlines = size = BUFSIZ; for (i = 0; i &lt; buf-&gt;nchars; i++) { if (buf-&gt;chars[i] == '\n' || i == buf-&gt;nchars - 1) { if (buf-&gt;nlines + 1 &gt;= size) { size = buf-&gt;maxlines &lt;&lt; 1; if ((tmp = reallocarray(buf-&gt;linebeg, size, sizeof *buf-&gt;linebeg)) == NULL) err(EXIT_FAILURE, "realloc"); buf-&gt;linebeg = tmp; if ((tmp = reallocarray(buf-&gt;lineend, size, sizeof *buf-&gt;lineend)) == NULL) err(EXIT_FAILURE, "realloc"); buf-&gt;lineend = tmp; buf-&gt;maxlines = size; } buf-&gt;lineend[buf-&gt;nlines-1] = buf-&gt;chars+i+1; buf-&gt;linebeg[buf-&gt;nlines++] = buf-&gt;chars+i+1; } } buf-&gt;lineend[--buf-&gt;nlines] = buf-&gt;chars+i+1; } /* shuffle buf-&gt;linebeg and buf-&gt;lineend parallelly */ static void shuf(struct Buffer *buf, size_t nshuf) { size_t i, j; char *tmp; for (i = buf-&gt;nlines-1; i &gt; 0 &amp;&amp; nshuf &gt; 0; i--, nshuf--) { j = arc4random_uniform(i + 1); tmp = buf-&gt;linebeg[i]; buf-&gt;linebeg[i] = buf-&gt;linebeg[j]; buf-&gt;linebeg[j] = tmp; tmp = buf-&gt;lineend[i]; buf-&gt;lineend[i] = buf-&gt;lineend[j]; buf-&gt;lineend[j] = tmp; } } /* print at most nshuf lines */ static void printbuf(struct Buffer *buf, size_t nshuf) { while (nshuf-- &gt; 0) write(STDOUT_FILENO, buf-&gt;linebeg[nshuf], buf-&gt;lineend[nshuf] - buf-&gt;linebeg[nshuf]); } /* return number from s */ static size_t getnshuf(const char *s) { size_t n; char *endp; n = strtoull(s, &amp;endp, 10); if (errno == ERANGE || endp == s || *endp != '\0') return 0; return (size_t) n; } /* show usage */ static void usage(void) { (void)fprintf(stderr, "usage: shuf [-n number] [file...]\n"); exit(EXIT_FAILURE); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T00:29:11.327", "Id": "241688", "Score": "1", "Tags": [ "c", "shuffle", "posix" ], "Title": "Implementation of GNU shuf(1) now supporting nul characters" }
241688
<p>Answers to <a href="https://stackoverflow.com/q/61382568/3904031">this</a> explain why I can't reliably get <code>int</code> type arrays. While there are some workarounds I have a hunch there's a better, cleaner or otherwise "less tricky" way to get these hexagonal arrays of dots arranged in this spiral pattern than the way I've done it by using several conditions.</p> <p>Is my hunch correct?</p> <p><strong>Note:</strong> <code>hexit_60()</code> and <code>get_points()</code> are used in different ways in other places so I don't want to combine them.</p> <p><strong>Context:</strong> This is used in a simulation and plotting routine for points in reciprocal space of a hexagonal lattice as part of a diffraction calculator.</p> <p><a href="https://i.stack.imgur.com/JLs3v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JLs3v.png" alt="hexagonal array of dots"></a></p> <pre><code>import numpy as np import matplotlib.pyplot as plt def hexit_60(n_max): pairs = [] if n_max &gt;= 0: pairs.append(np.zeros(2, dtype=int)[:, None]) if n_max &gt;= 1: # https://stackoverflow.com/q/61382568/3904031 trap 0*[n] because casts to float seq = [1, 0, -1] p0 = np.hstack((seq, seq[::-1])) N = len(p0) p1 = np.hstack((p0[N-2:], p0[:N-2])) pairs.append(np.stack((p0, p1), axis=0)) for n in range(2, n_max+1): seq = np.arange(n, -n-1, -1, dtype=int) p0 = np.hstack((seq, (n-1)*[-n], seq[::-1], (n-1)*[n])) N = len(p0) p1 = np.hstack((p0[N-2*n:], p0[:N-2*n])) pairs.append(np.stack((p0, p1), axis=0)) if len(pairs) &gt; 0: pairs = np.hstack(pairs) else: pairs = None return pairs def get_points(a, n_max): vecs = a * np.array([[1.0, 0.0], [0.5, 0.5*np.sqrt(3)]]) pairs = hexit_60(n_max = n_max) if isinstance(pairs, np.ndarray): points = (pairs[:, None]*vecs[..., None]).sum(axis=0) else: points = None return points fig = plt.figure() for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]): ax = fig.add_subplot(2, 3, i+1) # plt.subplot(2, 3, i+1) ax.set_title('n_max: ' + str(n_max)) points = get_points(a=1.0, n_max=n_max) if isinstance(points, np.ndarray): x, y = points ax.scatter(x, y) ax.plot(x, y, '-k', linewidth=0.5) ax.set_xlim(-4.2, 4.2) ax.set_ylim(-4.2, 4.2) ax.set_aspect('equal') plt.show() </code></pre>
[]
[ { "body": "<h1>return early</h1>\n\n<p>For the special case, <code>n_max == -1</code>, you can return early</p>\n\n<pre><code>def hexit_60(n_max):\n if n_max == -1:\n return None\n</code></pre>\n\n<p>This allows you to simplify the loop a lot</p>\n\n<h1>special case</h1>\n\n<p>the part before the <code>for</code>-loop can be included in the main loop by taking one of the other answers to your <code>int</code> question, and use casting.</p>\n\n<h1>reverse</h1>\n\n<p>The reverse of <code>seq</code> is also the negative. If you extract the <code>(n-1)*[-n]</code> to another variable, you can make this a lot clearer.</p>\n\n<h1><code>np.roll</code></h1>\n\n<p><code>np.hstack((p0[N-2*n:], p0[:N-2*n]))</code> is equivalent to <code>np.roll(p0, 2 * n)</code></p>\n\n<h1>generator</h1>\n\n<p>You can make the <code>hexit_60</code> into a generator, even further simplifying it</p>\n\n<pre><code>def hexit_60_gen(n_max):\n if n_max == -1:\n return\n yield np.zeros(2, dtype=int)[:, None]\n for n in range(1, n_max + 1):\n seq = np.arange(-n, n + 1, dtype=int)\n middle = np.array((n - 1) * [-n], dtype=int)\n p0 = np.hstack((-seq, middle, seq, -middle,))\n p1 = np.roll(p0, 2 * n)\n yield np.vstack((p0, p1))\n</code></pre>\n\n<p>This code is a lot clearer to read to me.</p>\n\n<p>It generates the same points:</p>\n\n<pre><code>all(\n np.array_equal(\n hexit_60(n_max), np.hstack(list(hexit_60_gen(n_max)))\n )\n for n_max in range(10)\n)\n</code></pre>\n\n<h1>get_points</h1>\n\n<p>You need to adapt this slightly:</p>\n\n<pre><code>def get_points_gen(a, n_max):\n vecs = a * np.array([[1.0, 0.0], [0.5, 0.5 * np.sqrt(3)]])\n pairs = list(hexit_60_gen(n_max=n_max))\n if pairs:\n return (np.hstack(pairs)[:, None] * vecs[..., None]).sum(axis=0)\n</code></pre>\n\n<p>if <code>pairs</code> is empty, this returns <code>None</code> implicitly.</p>\n\n<p>The one thing I would is replace <code>[0.5, 0.5 * np.sqrt(3)]</code> by</p>\n\n<pre><code>angle = np.pi / 3 # diagonal\n[np.cos(angle), np.sin(angle)]\n</code></pre>\n\n<p>So you don't have as many magic numbers in the code</p>\n\n<h1>draw_hexagon</h1>\n\n<p>can be simplified with a slight reordering and a <code>continue</code></p>\n\n<pre><code>def draw_hexagon():\n fig = plt.figure()\n for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):\n ax = fig.add_subplot(2, 3, i+1)\n # plt.subplot(2, 3, i+1)\n ax.set_title('n_max: ' + str(n_max))\n points = get_points_gen(a=1.0, n_max=n_max)\n ax.set_xlim(-4.2, 4.2)\n ax.set_ylim(-4.2, 4.2)\n if points is None:\n continue\n x, y = points\n ax.scatter(x, y)\n ax.plot(x, y, '-k', linewidth=0.5)\n ax.set_aspect('equal')\n plt.show()\n</code></pre>\n\n<p>This latest part can be made a bit cleaner, using the principles of clean architecture, but this is good enough, or a bit more parametrized, but this is good enough.</p>\n\n<p>-- </p>\n\n<h1>alternative approach</h1>\n\n<p>Instead of the approach of the <code>hexit_60</code>, you can have a function to assemble the first side of the hexagon, and then apply rotations to this:</p>\n\n<pre><code>ANGLE = np.pi / 3\nCOS_ANGLE = np.cos(ANGLE)\nSIN_ANGLE = np.sin(ANGLE)\nROTATION_MATRIX = [[COS_ANGLE, -SIN_ANGLE], [SIN_ANGLE, COS_ANGLE]]\n</code></pre>\n\n<p>Then to get one side, using <code>np.linspace</code> to do the interpolation:</p>\n\n<pre><code>def side_points(n):\n if n == 0:\n return np.array([[0], [0]])\n p0 = np.array([n, 0])\n p1 = n * np.array([COS_ANGLE, SIN_ANGLE])\n return np.linspace(p0, p1, n, endpoint=False).T\n</code></pre>\n\n<p>And then the rotations is a simple generator</p>\n\n<pre><code>def rotations(side):\n yield side\n if np.array_equal(side, np.array([[0], [0]])):\n return\n for _ in range(5):\n side = np.dot(ROTATION_MATRIX, side)\n yield side\n</code></pre>\n\n<p>Note that this can be easily adjusted to any regular polygon, by adjusting the angle, and passing in the appropriate cosinus, sinus and or rotation_matrix as function parameter instead of using the global</p>\n\n<pre><code>from functools import lru_cache\n\n\n@lru_cache(None)\ndef cos_angle(sides):\n return np.cos(2 * np.pi / sides)\n\n\n@lru_cache(None)\ndef sin_angle(sides):\n return np.sin(2 * np.pi / sides)\n\n\n@lru_cache(None)\ndef rotation_matrix(sides):\n return np.array(\n [\n [cos_angle(sides), -sin_angle(sides)],\n [sin_angle(sides), cos_angle(sides)],\n ]\n )\n\n\ndef side_points(n, sides=6):\n if n == 0:\n return np.array([[0], [0]])\n p0 = np.array([n, 0])\n p1 = n * np.array([cos_angle(sides), sin_angle(sides)])\n return np.linspace(p0, p1, n, endpoint=False).T\n\n\ndef rotations(side, sides=6):\n yield side\n if np.array_equal(side, np.array([[0], [0]])):\n return\n rot = rotation_matrix(sides)\n for _ in range(sides - 1):\n side = np.dot(rot, side)\n yield side\n\n\ndef points(n_max, sides=6):\n return np.hstack(\n list(\n itertools.chain.from_iterable(\n rotations(side_points(n, sides), sides)\n for n in range(n_max + 1)\n )\n )\n )\n</code></pre>\n\n<p>Then drawing the polygon is simply:</p>\n\n<pre><code>def draw_polygon(sides=6):\n fig = plt.figure()\n for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):\n ax = fig.add_subplot(2, 3, i + 1)\n # plt.subplot(2, 3, i+1)\n ax.set_title(\"n_max: \" + str(n_max))\n ax.set_xlim(-4.2, 4.2)\n ax.set_ylim(-4.2, 4.2)\n if n_max &lt; 0:\n continue\n all_points = points(n_max, sides=sides)\n ax.scatter(*all_points)\n ax.plot(*all_points, \"-k\", linewidth=0.5)\n ax.set_aspect(\"equal\")\n return fig\n</code></pre>\n\n<blockquote>\n<pre><code>draw_polygon(7)\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/avnmE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/avnmE.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T08:03:27.480", "Id": "474307", "Score": "1", "body": "Wow! This will take me a bit of time to review but I can tell already it's very helpful, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T18:47:35.693", "Id": "474359", "Score": "1", "body": "Nice answer. You don't show the actual call to `draw_polygon` that was used to make the plots. Are they supposed to be seven (7) sided polygons?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T19:43:30.570", "Id": "474363", "Score": "0", "body": "that is a 7-sided polygon indeed. I added the call in the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T03:09:33.357", "Id": "474369", "Score": "0", "body": "Gee I can't keep up with the progress in your answer. :-) But the original post already solved my problem soI think in this case no need to hold out for further answers, this one's super, above, beyond etc.!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T07:15:09.033", "Id": "241697", "ParentId": "241691", "Score": "4" } } ]
{ "AcceptedAnswerId": "241697", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T02:21:36.230", "Id": "241691", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Getting hexagonal arrays of dots arranged in this spiral pattern" }
241691
<p>God sidetracked by this question: <a href="https://codereview.stackexchange.com/q/241362/507">“Rock-Paper-Scissors Tournament”</a></p> <p>Which led me to the <a href="https://open.kattis.com/problems/magicalmysteryknight" rel="nofollow noreferrer">"Knight's Tour" problem</a>.</p> <p>Initially did a brute force solution. This worked for most of the test. But timed out for the last test. No matter how I added quick exits to the brute force solution could not pass the last test. So did some googling and implemented a heuristic solution on the "Diamond" Square partial solution (Dr. Roget in 1840 who extended it from Euler’s).</p> <p>The full code is <a href="https://github.com/Loki-Astari/Kattis/tree/master/KnightTour" rel="nofollow noreferrer">here</a></p> <h2>SquareDiamond.h</h2> <pre><code>#ifndef THORSANVIL_CONTEST_KNIGHTTOUR_SQUAREDIAMOND_H #define THORSANVIL_CONTEST_KNIGHTTOUR_SQUAREDIAMOND_H /* * This is a heuristic to solve the knight tour. * As such it does not always work. * * If the problem space already has a lot of squares already defined. * it is likely to fall outside the scope of the heuristics and cause it * to fail quickly. * * If the problem space is sparse then this algorithm works very well, * though not perfectly (as the defined points must fall inside the * diamond square patter perfectly). * * We are using a symmetric already solved version * of the knights tour as developed by Dr Roget in 1840. * * In this solution the board is divided into 4 quarters * Each quarter has four routes (each route covers 4 squares). * See sd.gif included with this project. * * So we now have 16 routes (4 routes per quarter). Each can be run forward or backwards. * * So given a starting point, we run the route forward then backward. * At the end we work out what other routes can be reached (A maximum of 7 other routes * you can not jump back to the same route all other poisition in the current route * will have been used). * * So this effectively this reduces the problem to 16 vertices. * Each vertices is connected to 7 other vertices. */ #include &lt;vector&gt; namespace ThorsAnvil::Contest::KnightTour { class Board; class SquareDiamond { private: // Possible moves a knight can move. static std::pair&lt;int, int&gt; constexpr pos[8] = {{-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}}; // The 16 routes. // The chessboard is numbered 1-64. // Bottom left is 1. // Numbers increase by 1 left to right. // Numbers increase by 8 bottom to top. static int constexpr cells[17][4] = { {-1, -1, -1, -1}, // row 0 is invalid and used as spacing. // We index from 1 to make things more logical. { 1, 11, 28, 18}, { 2, 12, 27, 17}, { 3, 20, 26, 9}, { 4, 19, 25, 10}, { 5, 15, 32, 22}, { 6, 16, 31, 21}, { 7, 24, 30, 13}, { 8, 23, 29, 14}, {33, 43, 60, 50}, {34, 44, 59, 49}, {35, 52, 58, 41}, {36, 51, 57, 42}, {37, 47, 64, 54}, {38, 48, 63, 53}, {39, 56, 62, 45}, {40, 55, 61, 46} }; // Map from a chess square to a route. static int constexpr squreToCellData[65] = { -1, 1, 2, 3, 4, 5, 6, 7, 8, 3, 4, 1, 2, 7, 8, 5, 6, 2, 1, 4, 3, 6, 5, 8, 7, 4, 3, 2, 1, 8, 7, 6, 5, 9, 10, 11, 12, 13, 14, 15, 16, 11, 12, 9, 10, 15, 16, 13, 14, 10, 9, 12, 11, 14, 13, 16, 15, 12, 11, 10, 9, 16, 15, 14, 13 }; Board&amp; board; using CellRoute = std::vector&lt;int&gt;; using CellRoutePair = std::pair&lt;CellRoute, CellRoute&gt;; CellRoutePair getRoute(int square); bool runTour(int currentMove, std::vector&lt;int&gt; const&amp; route, int routePos, int x, int y); bool runTour(int currentMove, int x, int y); bool runTour(int currentMove); public: SquareDiamond(Board&amp; board) : board(board) {} bool runTour(int x, int y) {return runTour(1, x, y);} }; } #endif </code></pre> <h2>SquareDiamond.cpp</h2> <pre><code>#include "squarediamond.h" #include "board.h" #include &lt;algorithm&gt; using namespace ThorsAnvil::Contest::KnightTour; // Given a square // Find the route and calculate the path forward and backwards. SquareDiamond::CellRoutePair SquareDiamond::getRoute(int square) { int cell = squreToCellData[square]; int const* cellPtr = cells[cell]; auto find = std::find(cellPtr, cellPtr + 4, square); auto offset = find - cellPtr; std::vector&lt;int&gt; r1(4); std::vector&lt;int&gt; r2(4); for(int loop = 0; loop &lt; 4; ++loop) { r1[loop] = cellPtr[(4 + offset + loop) % 4]; r2[loop] = cellPtr[(4 + offset - loop) % 4]; } return std::make_pair(r1, r2); } bool SquareDiamond::runTour(int currentMove, std::vector&lt;int&gt; const&amp; route, int routePos, int x, int y) { // Make sure the move is basically valid. if (!board.validMove(currentMove, x, y)) { return false; } // Update the board. Board::BoardUpdate update(board, currentMove, x, y); if (!update) { // If this is not a semi-magic board then exit immediately. return false; } if (routePos != 4) { // We are not at the end of a route // So go to the next square in the root. int next = route[routePos]; int newX = (next - 1) % 8; int newY = (next - 1) / 8; if(runTour(currentMove + 1, route, routePos + 1, newX, newY)) { update.setOk(); return true; } return false; } // We are at the end of a route. // So try and find the next route to run for(auto const&amp; p: pos) { int newX = x + std::get&lt;0&gt;(p); int newY = y + std::get&lt;1&gt;(p); if (newX &lt; 0 || newX &gt;= 8 || newY &lt; 0 || newY &gt;= 8) { continue; } if (runTour(currentMove + 1, newX, newY)) { update.setOk(); return true; } } // If no other routes work just returned to false. return false; } bool SquareDiamond::runTour(int currentMove, int x, int y) { if (currentMove == 65) { return true; } int square = y * 8 + x + 1; CellRoutePair routes = getRoute(square); return runTour(currentMove, std::get&lt;0&gt;(routes), 1, x, y) || runTour(currentMove, std::get&lt;1&gt;(routes), 1, x, y); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T04:31:13.040", "Id": "241692", "Score": "1", "Tags": [ "c++", "programming-challenge" ], "Title": "Knight Tour Heuristic" }
241692
<p>I came across this issue in the problem titled: <a href="https://www.hackerrank.com/contests/acm-vit-cpp/challenges/another-prime-problem/problem" rel="nofollow noreferrer">Another Prime Problem</a>. Here's my solution with JavaScript which passed test case-1, but for other test cases it led to timeout.</p> <pre><code>function processData(input) { input=input.split('\n'); input.shift(); for(var i=0;i&lt;input.length;i++){ values(input[i]); } } function values(num){ var sum=0; num=num.split(' '); for(var i=num[0];i&lt;=num[1];i++){ for(var j=2;j&lt;=i;j++){ if(i%j==0 &amp;&amp; isprime(j)){ sum+=j; } } } console.log(sum) } function isprime(val){ let flag=1; for(var i=2;i&lt;val;i++){ if(val%i==0){ flag=0; } } if(flag==1){ return true; } else{ return false; } } </code></pre> <p>What's the issue in this code that leads to timeout?</p> <p>The above program has a very bad time complexity, I guess due to multiple loops and functions, but not being much experienced with algorithms this is only solution I can think of right now. Any help would be appreciated.</p> <p>Additional info:</p> <p>Problem statement in a nutshell: find the sum of prime factors of each number in the range [X,Y].</p> <p>Input Format: The first line contains T denoting the total number of testcases. First line of each testcase contains two integers X and Y.</p> <p>Constraints: 1 ≤ T ≤ 10000 2 ≤ X ≤ Y ≤ 10^5</p> <p>Output Format: Sum of prime factors of each number in the range [X, Y].</p> <p>Currently my code calculates the sum of primes (i know this cause I'm able to pass first test case) but the remainder of test cases lead to Timeout.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T15:01:13.640", "Id": "474351", "Score": "1", "body": "When trying to check 9999899999, what information is to be expected from divisors beyond 99999?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T15:44:05.030", "Id": "474354", "Score": "1", "body": "Welcome to CodeReview@SE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T15:45:43.747", "Id": "474355", "Score": "0", "body": "@greybeard edited.." } ]
[ { "body": "<p>An immediate problem is that <code>is_prime()</code> is expensive, and you call it too many times. Prepare a sufficiently large list of primes in advance (and use a sieve for that).</p>\n\n<p>This will give you a certain performance boost, but I am positive it will not be enough to avoid timeouts. The real problem is with the algorithm: you try to factorize the numbers, and the factorization is hard.</p>\n\n<p>Instead of bruteforcing, do the math homework: how many numbers in the range have a prime <span class=\"math-container\">\\$p\\$</span> as a factor? Hint: if there are <code>N</code> of them, they'd contribute <code>N * p</code> to the answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T20:58:47.340", "Id": "241725", "ParentId": "241695", "Score": "2" } } ]
{ "AcceptedAnswerId": "241725", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T05:59:33.197", "Id": "241695", "Score": "2", "Tags": [ "javascript", "programming-challenge", "primes", "timeout" ], "Title": "Hackerrank problem -\"Another Prime Problem\"" }
241695
<p>I am have created a predicate builder that takes predicates (functions with a single input and produce a boolean) and can chain them using boolean logic, so AND, OR and NOT. It is inspired by the Java <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html" rel="nofollow noreferrer"><code>Predicate</code> class</a>. This is mostly to practice my TypeScript, so general feedback is of course appreciated. However, I am interested in few points:</p> <ul> <li>Naming. I don't like the <code>Builder</code> suffix here as it doesn't seem to fit. Although, I cannot exactly explain why it feels wrong. Partly, I'm used to builders producing an object as a result, not to be containers for the logic that will be later applied. This seems more of a Functor. Furthermore "predicate" is the mathematical and general term for a function of type <code>(x: any) =&gt; boolean</code>, so I don't want to name the class that way. Java gets away with it because it has functional interfaces.</li> <li>Repetition. When using <code>.and()</code> and <code>.or()</code> the return is the same aside from the operator being used. This feels off. When I add a new method like <code>.xor()</code>, then on one hand, I don't want to repeat this. On the other, <code>.xor()</code> will not be implemented using a single operator. There should be a way to generalise the logic that I simply don't see.</li> <li>Overloaded methods. Since you can't actually have method overloading in TypeScript/JavaScript you need to accept all possible signatures and sort out what to do in the method. Is <code>.extractPredicate()</code> a decent way to go about this in my case? Or is there something more idiomatic or clearer?</li> </ul> <pre><code>interface Predicate&lt;T&gt; { (x: T) : boolean } class PredicateBuilder&lt;T&gt; { condition: Predicate&lt;T&gt;; constructor(condition: Predicate&lt;T&gt;) { this.condition = condition; } public and(input: PredicateBuilder&lt;T&gt; | Predicate&lt;T&gt;): PredicateBuilder&lt;T&gt; { const p: Predicate&lt;T&gt; = this.condition; const q: Predicate&lt;T&gt; = this.extractCondition(input); return new PredicateBuilder((x: T) =&gt; p(x) &amp;&amp; q(x)); } public or(input: PredicateBuilder&lt;T&gt; | Predicate&lt;T&gt;): PredicateBuilder&lt;T&gt; { const p: Predicate&lt;T&gt; = this.condition; const q: Predicate&lt;T&gt; = this.extractCondition(input); return new PredicateBuilder((x: T) =&gt; p(x) || q(x)); } public not(): PredicateBuilder&lt;T&gt; { return new PredicateBuilder((x: T) =&gt; !this.condition(x)); } public apply(x: T): boolean { return this.condition(x); } private extractCondition(input: PredicateBuilder&lt;T&gt; | Predicate&lt;T&gt;): Predicate&lt;T&gt; { let condition: Predicate&lt;T&gt;; if ("condition" in input) { condition = input.condition; } else { condition = input; } return condition; } } </code></pre> <p><a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgApQgE2AukA8AKgHzIDeAUMsgBQAeAXMoQJTJMBGA9lwDYRwQFAL4UKCXnADOUtBmy5IAIQCuwXpmhFSlagi4hsYYAabosOPBG0BuMXoNSwUFQjBcoNfYeDHTci0VrEjZdamQwAAtgKQA6byMTEGQAXmQE3yS7alEqZAAHFQ5eHGRBTBpQQrAzeUtlNQ0tEmQAHwCFK20WWsCrVXVNKG1yPIcQJwLezoIWtKiY+INEg2zw70mAR2n64NJ56LiIOmdEMABhZcyDSpBqljsx5AwwFShkkAgAdw7dgabPPQmKxUqR8vQ2AAySHITYQh55XLUQrFUoeW7VHZBf5DEbtcwzPY9X7Yxq4lphcaTfJYrpzCKHJY+PwgNZUsCw2mzfYMxbHU5uS7MpIYlRgBFPF5vD7fEn9MnQGhA5hsFJgiFtdpwugsBE5ewFIolBDIEBcMA0YkEv4K4YUyUQV7vU2y62kwaK5UgtXIACECziGRZ8LWSMNqJNcHy+V4AE8vcTuHwBMlKc9HdLeYGrsGdaGDfkoMAAG5WZD8qBnIUrECimpyhoeu2kfF1ILdLl7UbhZD8DlBpKd2xPYAwWgAIgHBnHyFAs7uYtCT3GNdS8+qTJrbOQwnLvCkKDTK+uyTSVTF27D1ClzqnrMRIjEAHonyoQL4IhAnFIxBsOXA3SsIcQBUABbDhoB5OhQWQaDSAAFgARjsP9kA4QDIGAsCIKgKCYOg-BkHggBmR5ULgHFoDXT4fgwiBKOGEDwMgmgALbKwEVQjgGOo112MbAF8CYnDiBodD+IgCVUPPDk0nggAmR4XwAQQAOQAESfAB5AAlZApBUaM41AABzMo0NtMRpAPKALXHZSykMZAlFoDhbRYccABoIhcCBPLyCjLJ7WJyjEhiWCeEKjPjGSIolazoDslzymQByxPcryfJUPy8m4oLwhCwxWPCyKoxjGKF3FCh4pkRKaHs5APGc1yMu85xsv86hAqbSL0TypsIuCsq4zrOLHgS2z6pcpq0rcgbMvanLqH6gFes8bqAUGgrhoq+5qqUp81M03T9MM8rTPMws+kgKzasmhqUpcmgrsJDy2t8zqygY0qivE67JNK6LRv226bKSxzMFS2gXt2N6sqWtDvqGoq2P+rbqCi8rgZqsH6ocpqnphoI4cWz6NqGNaxLo9HkExkbYpBigJvBmboYkkmPtypGCvRVHXsBrGGYlF9VK0whQbq8czQ5ZTMvgfcEfJ6BIuly0Bfpyqxol+7pecuW4AVz6Vop4LVZpundsXRmKBgN83CSMo7otSQIN4JgnCLEATO8458ggNwsCYQRY28s4VANoOQFjJcAEhUNAqQzLSAADAASMhff9yBIZSXOyjccPeGQAB+ZBx1QZSAGVK5nJhxwAMWUgBJAAZcddzr9OXYgXhhHHCgY8zgPMCYdOh+z0QY7Dg3qFHshp975O7BjgeNmTWJeC4EyaATkyEWEIA" rel="nofollow noreferrer">Playground Link including a small set of unit tests</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T11:59:39.337", "Id": "475564", "Score": "1", "body": "In general, I like it. The Builder naming bugs me a bit, but it's not my point here. The `extractCondition`-Thing is somewhat, meh. The simplest and cleanest here would be: `return new PredicateBuilder((x: T) => p(x) || input.aply(x))` and get rid of the allowed `Predicate<T>` type as parameter. I'd think that would be more consistent. As you want some, let's say static method, to construct you a PredicateBuilder object and pass on this throughout the \"API\"" } ]
[ { "body": "<p>As pointed out as a comment, I was unhappy about the <code>extractCondition</code> function.\nThis function handles, variables which do conform your <code>Predicate&lt;T&gt;</code> type. Which is fine, but I think this doesn't belong here.\nBecause a <code>Predicate</code> should have an <code>accept</code> or, if we talk about the Java implementation, <code>test</code> function.\nThis is not given when we can pass on <em>any</em> random function which do return a <code>boolean</code>. But does not conform our design of a <code>Predicate</code>.</p>\n\n<p>Next <em>naming</em>, the <code>PredicateBuilder</code> seems okay-ish, but it feels wrong. As it isn't a builder in the classical sense.\nFurthermore we have to work around functional interfaces, and this is I think the main pain point. To achieve this I would propose to rename the <code>Predicate&lt;T&gt;</code> interface, as it should be describing what a Predicate holds (a function which takes a parameter and returns a boolean). Therefore the name <code>Predicate</code> is available again and should be used instead of <code>PredicateBuilder</code>.</p>\n\n<p>The repetition regarding <code>and</code>, <code>or</code>, etc... feels also some kind off. But I think that's because you always do <code>extractCondition</code> and other stuff (I've eliminated this in my suggestion, as the Java Predicate implementation does basically the same). Plus I've create a static method <code>Predicate#of(...)</code> to <em>easier</em> \"get\" a new Predicate. This reduces the mess a bit, but changing the operands is also still a bit clumsy, in my opinion.</p>\n\n<p>Oh and btw. I've felt free to use arrow functions :-)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>interface InternalPredicate&lt;T&gt; {\n (x: T) : boolean\n}\n\nclass Predicate&lt;T&gt; {\n constructor(private condition: InternalPredicate&lt;T&gt;) {}\n\n public static of = &lt;T&gt;(condition: InternalPredicate&lt;T&gt;) =&gt; {\n return new Predicate(condition);\n }\n\n public and = (input: Predicate&lt;T&gt;): Predicate&lt;T&gt; =&gt;\n Predicate.of((x: T) =&gt; this.apply(x) &amp;&amp; input.apply(x));\n\n public or = (input: Predicate&lt;T&gt;): Predicate&lt;T&gt; =&gt;\n Predicate.of((x: T) =&gt; this.apply(x) || input.apply(x));\n\n public not = (): Predicate&lt;T&gt; =&gt;\n Predicate.of((x: T) =&gt; !this.apply(x));\n\n public apply = (x: T): boolean =&gt; this.condition(x);\n}\n</code></pre>\n\n<p>Those are my two cents to the Predicate implementation, feel free to discuss them with me.</p>\n\n<p>Alternative solution to eliminate the <code>InternalPredicate</code> and to support functions which are booleans:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>type PredicateType&lt;T&gt; = (x: T) =&gt; boolean;\n\nclass Predicate&lt;T&gt; {\n constructor(private condition: PredicateType&lt;T&gt;) {}\n\n private static isInstance = &lt;T&gt;(input: Predicate&lt;T&gt; | PredicateType&lt;T&gt;): Predicate&lt;T&gt; =&gt; (input instanceof Predicate) ? input : Predicate.of(input);\n\n public static of = &lt;T&gt;(condition: PredicateType&lt;T&gt;) =&gt; new Predicate(condition);\n\n public and = (input: Predicate&lt;T&gt; | PredicateType&lt;T&gt;): Predicate&lt;T&gt; =&gt;\n Predicate.of((x: T) =&gt; this.apply(x) &amp;&amp; Predicate.isInstance(input).apply(x));\n\n public or = (input: Predicate&lt;T&gt; | PredicateType&lt;T&gt;): Predicate&lt;T&gt; =&gt;\n Predicate.of((x: T) =&gt; this.apply(x) || Predicate.isInstance(input).apply(x));\n\n public not = (): Predicate&lt;T&gt; =&gt;\n Predicate.of((x: T) =&gt; !this.apply(x));\n\n public apply = (x: T): boolean =&gt; this.condition(x);\n}\n</code></pre>\n\n<p>It comes pretty close the the <code>extractCondition</code> approach, but the main difference here is, that a new instance is created if the input is a <em>raw</em> function. This adds up to be more robust to changes and being less error prone. Another advantage is, we don't care about how the predicate internally works, we're just in charge of returning a predicate based on the input. This clears up the use case of the function a bit more. </p>\n\n<p><strong>EDIT</strong>: As discussed in the comments, it is <em>nicer</em> to merge the private <code>isInstance</code> function into the static <code>of</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:27:36.997", "Id": "475572", "Score": "1", "body": "Good points all around. The `of` static was something I was considering but wasn't sure about. You've convinced me it's a good idea. I'm not exactly sold on the `InternalPredicate` name but...the problem is that there are two things here - a predicate *function* and this predicate *class*. Both being a predicate in concept but can't use the same name because it'd be confusing. `Internal`, on the other hand sounds like you shouldn't be using it. I'm leaning towards having a `PredicateFn` or `PredicateFunction` instead. It's more accurate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:27:42.453", "Id": "475573", "Score": "1", "body": "At any rate, it's important for me to be able to handle both a function an an object being passed in. It's part of why I did this - I wanted to find a good way to handle similar situations. So, I'd want to be able to call `isOne.or(x => x === \"two\")` as well as `isOne.or(isTwo)` (asuming `isX` are class instances). So, either join together existing predicates as well as create new ones without having to do `isOne.or(Predicate.of(x => x === \"two\"))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:44:44.963", "Id": "475576", "Score": "0", "body": "Regarding the `PredicateFn` naming, yes, `InternalPredicate` may sound off as well. But would it be an option to convert the interface to a type? Like `type PredicateType<T> = (x: T) => boolean` naming it could be: `PredicateFunction`, `TypePredicate` or what ever you desire to fit the most. Alright, I thought you would say, that handling _any_ functions is a must. To comply with this, how about a function, which checks if the input is either of type `PredicateFunction` or an instance of `Predicate` itself. If the later, just return as is otherwise use the `of` function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T14:17:53.203", "Id": "475585", "Score": "1", "body": "Yes, that sounds better. It's an improved version of `extractCondition`, which I also dislike, by the way. So, it could be inverted to just produce an instance any time. So something like a `input => typeof input === \"function\" ? Predicate.of(input) : input`. (or reverse the check and see if it's an instance). Thinking further, this can be folded into `of` itself so it either calls the constructor or returns the input to ensure smoother interface. Would [something like this make sense](https://www.shorturl.at/prxI0)? (shortened URL to TS playground)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T14:22:19.283", "Id": "475586", "Score": "0", "body": "That's the solution I'd have expected in the first place! Makes the API for the `Predicate` clear and structured." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T15:24:43.557", "Id": "475589", "Score": "1", "body": "I'd wait until tomorrow to accept to not discourage any other feedback. Given that it took 10 days to get any feedback, I'm not exactly hopeful but still." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T13:07:56.793", "Id": "242339", "ParentId": "241698", "Score": "2" } } ]
{ "AcceptedAnswerId": "242339", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T07:56:56.267", "Id": "241698", "Score": "1", "Tags": [ "object-oriented", "typescript" ], "Title": "Predicate class implementation in TypeScript" }
241698
<p>I have the below code. I have list of status which contain may contain 4 values. R,UR,DO,NDO</p> <p>based on this list. i need to convert to Y,N values</p> <p>If list contains R the Readstatus="Y" </p> <p>If list contains UR the Readstatus="N" </p> <p>If both the ReadStatus="Y,N"</p> <p>If list contains DO the DoneStatus="Y" </p> <p>If list contains NDO the DoneStatus="N" If both the DoneStatus="Y,N"</p> <p>the below code works but its too ugly. is there any thing i can change</p> <pre><code> Dim Readstatus As String = "" Dim DoneStatus As String = "" If Not String.IsNullOrEmpty(Status) Then Dim listStatus = Status.Split(",").ToList() If listStatus.Contains("R") Then Readstatus = "Y" End If If listStatus.Contains("UR") Then If String.IsNullOrEmpty(Readstatus) Then Readstatus = "N" Else Readstatus = Readstatus &amp; ",N" End If End If If listStatus.Contains("DO") Then DoneStatus = "Y" End If If listStatus.Contains("NDO") Then If String.IsNullOrEmpty(DoneStatus) Then DoneStatus = "N" Else DoneStatus = DoneStatus &amp; ",N" End If End </code></pre>
[]
[ { "body": "<p>It's interesting to notice that when you parse your input, you break a comma-separated string into a list of values. The end result of your code can be achieved much more cleanly if you take a similar (but inverted) approach, i.e. generate a <em>list</em> of values and then have the comma-separated string generated from that list.</p>\n\n<p>It's counterintuitive for the logical branching in your code to be significantly more complex than the logical branching in your description of the behavior. These should map one to one. You can just translate your pseudocode logic exactly as is. </p>\n\n<p>The reason your code ended up being more complex is because you needed to add the whole \"add a comma or don't\" logic to it - which can be avoided by relying on <code>String.Join</code>, which performs that logic for you, as long as you supply it with a collection of values.</p>\n\n<blockquote>\n <p>If list contains R the Readstatus=\"Y\"<br>\n If list contains UR the Readstatus=\"N\" </p>\n</blockquote>\n\n<p></p>\n\n<pre><code>Dim readStatusList As New List(Of String)\n\nIf listStatus.Contains(\"R\") Then\n readStatusList.Add(\"Y\")\nEnd If\nIf listStatus.Contains(\"UR\") Then\n readStatusList.Add(\"N\")\nEnd If\n\nDim readStatus As String = String.Join(\",\", readStatusList)\n</code></pre>\n\n<p>The exact same applies to the \"done\" status:</p>\n\n<blockquote>\n <p>If list contains DO the Donestatus=\"Y\"<br>\n If list contains NDO the Donestatus=\"N\" </p>\n</blockquote>\n\n<p></p>\n\n<pre><code>Dim doneStatusList As New List(Of String)\n\nIf listStatus.Contains(\"DO\") Then\n doneStatusList.Add(\"Y\")\nEnd If\nIf listStatus.Contains(\"NDO\") Then\n doneStatusList.Add(\"N\")\nEnd If\n\nDim doneStatus As String = String.Join(\",\", doneStatusList)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T10:27:37.410", "Id": "474392", "Score": "0", "body": "Yes that does look much cleaner. and readable thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T09:40:26.853", "Id": "241743", "ParentId": "241700", "Score": "1" } } ]
{ "AcceptedAnswerId": "241743", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T09:44:25.087", "Id": "241700", "Score": "1", "Tags": [ ".net", "vb.net" ], "Title": "String Concatenation and Comparison" }
241700
<p>My friend is taking a C++ course and it inspired me to write my own version of the "Rock, Paper, Scissors" assignment he was given in order to help ease me back into coding. I don't have any people other than said friend that can offer input on it, so I was hoping y'all could give me some.</p> <p>I am prepared for harsh criticism.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;limits&gt; void printLine (std::string text) { std::cout &lt;&lt; text + '\n'; return; } //Allows for easy creation and output of menu/text boxes class TextBox { std::string title; std::string footer; std::string banner; std::vector&lt;std::string&gt; lines; bool numbered; bool hasFooter; bool built; bool reRender; void makeBanner () { std::string newBanner; newBanner = "**"; int lineLength = getLineLength(); for (int i = 0; i &lt; lineLength; i++) { newBanner = newBanner + "*"; } banner = newBanner; return; } int getLineLength () { int longestString = title.size(); for (int i = 0; i &lt; lines.size(); i++) { if (lines[i].size() &gt; longestString) { longestString = lines[i].size(); } } if (hasFooter &amp;&amp; (longestString &lt; footer.size())) { longestString = footer.size(); } return longestString; } void renderLines () { int lineLength = getLineLength() - 2; for (int i = 0; i &lt; lines.size(); i++) { int lineLengthDifference = lineLength - lines[i].size(); for (int x = 0; x &lt; lineLengthDifference; x++) { lines[i] = lines[i] + ' '; } lines[i] = '*' + lines[i] + '*'; } return; } void buildTextBox () { if (numbered) { for (int i = 0; i &lt; lines.size(); i++) { lines[i] = "[" + std::to_string(i) + "] - " + lines[i]; } } makeBanner(); int lineLength = getLineLength(); int lineLengthDifference = lineLength - title.size(); int leftSpacing, rightSpacing; leftSpacing = rightSpacing = lineLengthDifference / 2; if ((lineLengthDifference % 2) &gt; 0) { rightSpacing++; } std::string leftPadding = "*"; std::string rightPadding = "*"; //set left padding for (int i = 0; i &lt; leftSpacing; i++) { leftPadding = leftPadding + ' '; } //set right padding for (int i = 0; i &lt; rightSpacing; i++) { rightPadding = ' ' + rightPadding; } //center title in * title = leftPadding + title + rightPadding; //render lines renderLines(); if (hasFooter) { int lineLength = getLineLength() - 2; int lineLengthDifference = lineLength - footer.size(); int leftSpacing, rightSpacing; leftSpacing = rightSpacing = lineLengthDifference / 2; if ((lineLengthDifference % 2) &gt; 0) { rightSpacing++; } std::string leftPadding = "*"; std::string rightPadding = "*"; //set left padding for (int i = 0; i &lt; leftSpacing; i++) { leftPadding = leftPadding + ' '; } //set right padding for (int i = 0; i &lt; rightSpacing; i++) { rightPadding = ' ' + rightPadding; } //center footer in * footer = leftPadding + footer + rightPadding; } built = true; return; } public: TextBox () { reset(); return; } void resetLines () { lines.clear(); reRender = true; return; } void reset () { title = "No Title Set"; footer = ""; hasFooter = false; numbered = false; built = false; reRender = false; return; } void isNumbered (bool changed) { numbered = changed; return; } bool isNumbered () { return numbered; } std::vector&lt;std::string&gt; getLines () { return lines; } void setTitle (std::string newTitle) { title = newTitle; return; } void setFooter (std::string newFooter) { hasFooter = true; footer = newFooter; return; } void addLine (std::string line) { lines.push_back(line); return; } void print () { if (!built) { buildTextBox(); } if (reRender) { renderLines(); } printLine(banner); printLine(title); printLine(banner); for (int i = 0; i &lt; lines.size(); i++) { printLine(lines[i]); } printLine(banner); if (hasFooter) { printLine(footer); printLine(banner); } return; } }; TextBox buildMainMenu () { //instantiate a new TextBox TextBox textBox; //tell the text box to number the lines textBox.isNumbered(true); //set title of the text box textBox.setTitle("You must choose a sign with which to attack your opponent."); //add lines to the text box textBox.addLine("Rock. This sign defeats scissors, but will lose against paper."); textBox.addLine("Paper. Paper will defeat rock, Scissors, however, will beat it handily."); textBox.addLine("Scissors. Scissors defeats paper, but stands no chance against rock."); //add a footer to the text box textBox.setFooter("Which symbol will you carry into battle?"); return textBox; } TextBox buildContinueMenu () { //instantiate a new TextBox TextBox textBox; //set title of the text box textBox.setTitle("Results"); textBox.setFooter("Would you like to play again? [0] - Yes / [1] - No"); return textBox; } TextBox buildThankYouBox () { TextBox textBox; textBox.setTitle("Thanks for playing!"); textBox.addLine("Written By:"); textBox.addLine("Tim Andrus"); return textBox; } int getAiAttack () { std::srand(std::time(0)); int attack = std::rand() % 3; return attack; } void calculateWinner (int playerAttack, int &amp;aiAttack, int &amp;result) { //input /**************** * 0 = rock * * 1 = paper * * 2 = scissors * ****************/ //output /**************** * 0 = tie * * 1 = win * * 2 = loss * ****************/ aiAttack = getAiAttack(); //not a tie if (playerAttack != aiAttack) { //player win conditions if ( //player rock : ai scissors = win (playerAttack == 0 &amp;&amp; aiAttack == 2) || //player paper : ai rock = win (playerAttack == 1 &amp;&amp; aiAttack == 0) || //player scissors : ai paper = win (playerAttack == 2 &amp;&amp; aiAttack == 1) ) { result = 1; //player loss } else { result = 2; } } return; } std::string getAttackText (int attackValue) { std::string text = ""; switch (attackValue) { case 0: text = "rock"; break; case 1: text = "paper"; break; case 2: text = "scissors"; break; } return text; } std::string getResultText (int resultValue) { std::string text = ""; switch (resultValue) { case 0: text = "tied"; break; case 1: text = "won"; break; case 2: text = "lost"; break; } return text; } int main() { TextBox mainMenu = buildMainMenu(); TextBox continueMenu = buildContinueMenu(); TextBox thankYou = buildThankYouBox(); bool continueGame = true; bool continueInputIsValid = false; int playerAttack = 0; int aiAttack = 0; int result = 0; int playerContinue = 0; std::string playerAttackText = ""; std::string aiAttackText = ""; std::string resultText = ""; do { mainMenu.print(); std::cin &gt;&gt; playerAttack; //check if attack is 0 - 2 if (!((playerAttack &gt;= 0) &amp;&amp; (playerAttack &lt;= 2)) || std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); continue; } calculateWinner(playerAttack, aiAttack, result); playerAttackText = getAttackText(playerAttack); aiAttackText = getAttackText(aiAttack); resultText = getResultText(result); continueMenu.addLine("You " + resultText + "!"); continueMenu.addLine("You chose " + playerAttackText + "."); continueMenu.addLine("Your opponent chose " + aiAttackText + "."); do { continueMenu.print(); std::cin &gt;&gt; playerContinue; if (!((playerContinue &gt;= 0) &amp;&amp; (playerContinue &lt;= 1)) || std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); continue; } continueInputIsValid = true; //player chose not to play agian if (playerContinue != 0) { continueGame = false; } } while (!continueInputIsValid); continueMenu.resetLines(); } while (continueGame); thankYou.print(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T21:59:19.107", "Id": "474365", "Score": "3", "body": "It looks double spaced, I can hardly fit any meaningful code on my laptop screen at once." } ]
[ { "body": "<p>There's good news and bad news. The good news is that it looks fairly complete. The bad news is that it's overly long, hard to read, lacking in consistency, and doesn't make sense in a lot of places.</p>\n\n<p>I don't know what guideline you're using with regards to newlines, but this looks like you're using way too much of it:</p>\n\n<pre><code>makeBanner();\n\nint lineLength = getLineLength();\n\nint lineLengthDifference = lineLength - title.size();\n\nint leftSpacing, rightSpacing;\n\nleftSpacing = rightSpacing = lineLengthDifference / 2;\n</code></pre>\n\n<p>Those really don't need an extra line between them.</p>\n\n<pre><code>TextBox mainMenu = buildMainMenu();\n\nTextBox continueMenu = buildContinueMenu();\n\nTextBox thankYou = buildThankYouBox();\n\nbool continueGame = true;\n\nbool continueInputIsValid = false;\n\nint playerAttack = 0;\n\nint aiAttack = 0;\n\nint result = 0;\n\nint playerContinue = 0;\n\nstd::string playerAttackText = \"\";\n\nstd::string aiAttackText = \"\";\n\nstd::string resultText = \"\";\n</code></pre>\n\n<p>Those definitely don't need blank lines between them. No wonder your code is 502 lines. If you have two different blocks, I can understand why you'd separate them with a new line. After all, they're cheap and easily used as a separator. But you're not using them as a separator.</p>\n\n<p>The following alternative for your last block would still use much whitespace, but it would at least make more sense:</p>\n\n<pre><code>TextBox mainMenu = buildMainMenu();\nTextBox continueMenu = buildContinueMenu();\nTextBox thankYou = buildThankYouBox();\n\nbool continueGame = true;\nbool continueInputIsValid = false;\n\nint playerAttack = 0;\nint aiAttack = 0;\nint result = 0;\nint playerContinue = 0;\n\nstd::string playerAttackText = \"\";\nstd::string aiAttackText = \"\";\nstd::string resultText = \"\";\n</code></pre>\n\n<p>See? Extra newlines can be useful, but use them too much and your code will look like a tangled mess.</p>\n\n<p>You keep talking about an AI in your code. There is no AI. An AI is a form of intelligence, something capable of learning or problem solving. Something vaguely resembling human behaviour. Rock-Paper-Scissors is simply too simple to qualify for that. Especially if you're looking at how your program determines its move:</p>\n\n<pre><code>int getAiAttack ()\n{\n std::srand(std::time(0));\n int attack = std::rand() % 3;\n return attack;\n}\n</code></pre>\n\n<p>It's a pseudo-random attack. No perception, no learning, no intelligence. By the way, you shouldn't be re-seeding the <code>srand</code> function here. Do that once, at the start of your program. While it may look to you that the current solution will increase the randomness, it will actually decrease it. Try playing 3 sets of 3 (restart the program after every set) with your current solution and with the seed moved and notice the difference.</p>\n\n<p>You got a good start with your textboxes, but their current usage is cumbersome.</p>\n\n<p>Your logic boils down to:</p>\n\n<pre><code>do \n{\n //menu &amp; user input\n //validate user input\n //calculate winner\n //set texts\n //more text\n\n do\n {\n //more user input\n //validate more user input\n\n //convert validation result\n\n } while (!continueInputIsValid);\n //reset\n} while (continueGame);\n</code></pre>\n\n<p>Also rather cumbersome, but not bad for a beginner. Your choice of how to set-up menus is impacting your programming style though. Try to rebuild the functions so, that lines like</p>\n\n<pre><code> continueMenu.addLine(\"You \" + resultText + \"!\");\n continueMenu.addLine(\"You chose \" + playerAttackText + \".\");\n continueMenu.addLine(\"Your opponent chose \" + aiAttackText + \".\");\n</code></pre>\n\n<p>are either taken care of by the functions returning those values (so no intermediate variables are required), or handled by a new function handling it all at once. Perhaps that function is going to need other functions (in OO design: methods), but it doesn't belong here immediately in the loop.</p>\n\n<p>You also have a lot of odd text-to-string conversions going on:</p>\n\n<pre><code>//player rock : ai scissors = win\n(playerAttack == 0 &amp;&amp; aiAttack == 2)\n\nresult = 1;\n\n case 0:\n text = \"rock\";\n\n case 0:\n text = \"tied\";\n</code></pre>\n\n<p>Have you considered using <a href=\"https://stackoverflow.com/a/32536024/1014587\">Enums</a> instead? That would improve the readability and ease-of-programming a lot.</p>\n\n<p>Your code is at this in-between stage, between straight programming and object-oriented. Create a Game class, a Player class (with a Player1 and Computer or Player1 and Player2 instance) and you can almost copy piece by piece from your current program to your new program. Yet it would look a lot cleaner, especially since this allows you to easily split-up your code. <code>Player.h</code>, <code>Player.c</code>, <code>Textbox.h</code>, <code>Textbox.c</code>, <code>Game.h</code>, <code>Game.c</code> and a main file to combine it all in.</p>\n\n<p>Once you've done that, you'll notice it's also easier to modify the current code to any other simple game. Number guessing, hangman, perhaps even tic-tac-toe.</p>\n\n<p>Oh, as a side-note: there's a typo in your comment here:</p>\n\n<pre><code>//player chose not to play agian\n ^\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T12:23:32.967", "Id": "241707", "ParentId": "241702", "Score": "12" } }, { "body": "<p>This answer focuses on the text box functionality.</p>\n\n<h1>Review</h1>\n\n<blockquote>\n<pre><code>std::string footer;\nbool hasFooter;\n</code></pre>\n</blockquote>\n\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> instead:</p>\n\n<pre><code>std::optional&lt;std::string&gt; footer;\n</code></pre>\n\n<blockquote>\n<pre><code>void printLine (std::string text)\n{\n std::cout &lt;&lt; text + '\\n';\n return;\n}\n</code></pre>\n</blockquote>\n\n<p>Consider using <code>std::string_view</code> and stream the <code>\\n</code> separately to avoid allocations. The <code>return</code> can also be elided in <code>void</code> functions:</p>\n\n<pre><code>void print_line(std::string_view text)\n{\n std::cout &lt;&lt; text &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p>In fact, I don't think you need this function at all.</p>\n\n<blockquote>\n<pre><code>void makeBanner ()\n{\n\n std::string newBanner;\n\n newBanner = \"**\";\n\n int lineLength = getLineLength();\n\n for (int i = 0; i &lt; lineLength; i++)\n {\n newBanner = newBanner + \"*\";\n }\n\n banner = newBanner;\n\n return;\n}\n</code></pre>\n</blockquote>\n\n<p>This function is too complex. Use the <code>(count, character)</code> constructor of <code>std::string</code>. Use <code>std::size_t</code> for line lengths. It is also more readable to make it a free function and return the string instead of modifying in place:</p>\n\n<pre><code>std::string make_banner(std::size_t line_length)\n{\n return std::string(line_length + 2, '*');\n}\n</code></pre>\n\n<blockquote>\n<pre><code>int getLineLength ()\n{\n int longestString = title.size();\n\n for (int i = 0; i &lt; lines.size(); i++)\n {\n if (lines[i].size() &gt; longestString)\n {\n longestString = lines[i].size();\n }\n }\n\n if (hasFooter &amp;&amp; (longestString &lt; footer.size()))\n {\n longestString = footer.size();\n }\n\n return longestString;\n}\n</code></pre>\n</blockquote>\n\n<p>Add <code>const</code> to the function. You can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/max_element\" rel=\"nofollow noreferrer\"><code>std::max_element</code></a> here:</p>\n\n<pre><code>std::size_t max_length() const\n{\n auto result = title.size();\n if (!lines.empty()) {\n auto it = std::max_element(lines.begin(), lines.end(),\n [](const auto&amp; lhs, const auto&amp; rhs) {\n return lhs.size() &lt; rhs.size();\n });\n result = std::max(result, it-&gt;size());\n }\n if (footer) {\n result = std::max(result, footer-&gt;size());\n }\n}\n</code></pre>\n\n<blockquote>\n<pre><code>std::vector&lt;std::string&gt; getLines ()\n{\n return lines;\n}\n</code></pre>\n</blockquote>\n\n<p>Use <code>const &amp;</code> to prevent copying:</p>\n\n<pre><code>const auto&amp; get_lines() const\n{\n return lines;\n}\n</code></pre>\n\n<h1>Redesign</h1>\n\n<p>Here is my version of the text box functionality:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;string&gt;\n#include &lt;string_view&gt;\n#include &lt;vector&gt;\n\nnamespace detail {\n template &lt;typename RanIt&gt;\n std::size_t max_length(RanIt first, RanIt last)\n {\n auto it = std::max_element(\n first, last,\n [](std::string_view lhs, std::string_view rhs) {\n return lhs.size() &lt; rhs.size();\n }\n );\n return it == last ? 0 : it-&gt;size();\n }\n}\n\nclass TextBox {\npublic:\n template &lt;typename RanIt&gt;\n explicit TextBox(RanIt first, RanIt last)\n {\n lines.reserve(last - first + 2);\n\n auto length = detail::max_length(first, last);\n\n lines.emplace_back(length + 2, '*');\n std::transform(\n first, last,\n std::back_inserter(lines),\n [&amp;](std::string_view sv) {\n auto padding = length - sv.size();\n return '*' + std::string(sv) + std::string(padding, ' ') + '*';\n }\n );\n lines.emplace_back(length + 2, '*');\n }\n\n const auto&amp; rendered_lines() const\n {\n return lines;\n }\nprivate:\n std::vector&lt;std::string&gt; lines;\n};\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/tflCxnflQ6k4Y1V0\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n\n<p>Some notes:</p>\n\n<ul>\n<li><p>I opted for an immutable design. The text box is built once, and the lines aren't modified. This makes code easier to reason about.</p></li>\n<li><p>No reuse of variables (as you do with <code>lines</code> in your version).</p></li>\n<li><p>Instead of storing the original content, I rendered once and stored the result only.</p></li>\n<li><p>More simplistic &mdash; features such as titles, footers, etc. are omitted.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T09:07:02.537", "Id": "241869", "ParentId": "241702", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T10:13:45.333", "Id": "241702", "Score": "9", "Tags": [ "c++", "rock-paper-scissors" ], "Title": "Please harshly judge my C++ Rock Paper Scissors" }
241702
<p>So, here is my code for converting musical notes stored in a text file to WAV. You can see an example of its output <a href="https://gitlab.com/FlatAssembler/notestorawsoundconverter" rel="nofollow noreferrer">here</a>.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;cmath&gt; #include &lt;map&gt; std::map&lt;std::string,float&gt; notes; int sampleRate=44100; int main(int argc,char **argv) { notes["a"]=220; notes["as"]=233; notes["b"]=247; notes["C"]=262; notes["Cs"]=277; notes["D"]=293; notes["Ds"]=311; notes["E"]=329; notes["F"]=349; notes["Fs"]=370; notes["G"]=391; notes["Gs"]=415; notes["A"]=440; notes["As"]=466; notes["H"]=493; notes["C5"]=523; notes["Cs5"]=554; notes["D5"]=587; notes["Ds5"]=622; notes["E5"]=659; if (argc&lt;2) { std::cerr&lt;&lt;"Please supply the text file with notes as an argument." &lt;&lt;std::endl; return 1; } std::ifstream input(argv[1]); if (argc&gt;2) sampleRate=atoi(argv[2]); if (!input) { std::cerr&lt;&lt;"Can't open \"" &lt;&lt;argv[1] &lt;&lt;"\" for reading!" &lt;&lt;std::endl; return 1; } FILE *wav=std::fopen("output.wav","wb"); if (!wav) { std::cerr &lt;&lt;"Can't open \"output.wav\" for output!" &lt;&lt;std::endl; return 1; } bool isLittleEndian; int testNumber=0x10; std::fwrite(&amp;testNumber,sizeof(int),1,wav); std::fclose(wav); wav=std::fopen("output.wav","rb"); char testCharacter=0; std::fread(&amp;testCharacter,1,1,wav); std::fclose(wav); if (testCharacter==0x10) //The logic is: if the C library uses big endian for writing binary files, now "testCharacter" will still contain 0. isLittleEndian=true; else isLittleEndian=false; wav=std::fopen("output.wav","wb"); if (isLittleEndian) std::fprintf(wav,"RIFF"); //ASCII for 0x52494646, the magic number that WAV files start with. else std::fprintf(wav,"RIFX"); //Big endian WAV file starts with magic number 0x52494658, or, in ASCII, "RIFX". int32_t ChunkSize=36+8*sampleRate*2; std::fwrite(&amp;ChunkSize,4,1,wav); std::fprintf(wav,"WAVEfmt "); //The beginning of the header. int32_t Subchunk1Size=16; //PCM header is always 16 bytes. std::fwrite(&amp;Subchunk1Size,4,1,wav); int16_t AudioFormat=1; //PCM format. std::fwrite(&amp;AudioFormat,2,1,wav); int16_t NumChannels=1; //MONO audio. std::fwrite(&amp;NumChannels,2,1,wav); int32_t SampleRate=sampleRate; std::fwrite(&amp;SampleRate,4,1,wav); int32_t ByteRate=2*sampleRate; //Since we are using 16 bits per sample, and "sampleRate" samples per second. std::fwrite(&amp;ByteRate,4,1,wav); int16_t BlockAlign=2; //Each block is two bytes. std::fwrite(&amp;BlockAlign,2,1,wav); int16_t BitsPerSample=16; std::fwrite(&amp;BitsPerSample,2,1,wav); std::fprintf(wav,"data"); while (!input.eof()) { std::string currentNote; input &gt;&gt;currentNote; if (currentNote.length()==0) break; std::string durationString=""; int i=0; while ((currentNote[i]&gt;='0' &amp;&amp; currentNote[i]&lt;='9') || currentNote[i]=='.') { durationString+=currentNote.substr(i,1); i++; } std::cerr &lt;&lt;"Read note name \"" &lt;&lt;currentNote &lt;&lt;"\", the duration string is: " &lt;&lt;durationString &lt;&lt;std::endl; int noteDuration=3*sampleRate/std::stof(durationString); std::string fullNoteName=currentNote.substr(i); std::cerr &lt;&lt;"Playing note \"" &lt;&lt;fullNoteName &lt;&lt;"\" for " &lt;&lt;noteDuration &lt;&lt;" samples." &lt;&lt;std::endl; for (int i=0; i&lt;noteDuration; i++) { float currentFrequency=notes[fullNoteName]; float baseFrequency=sin(2*M_PI*currentFrequency*i/sampleRate)*16384; float secondHarmony=sin(2*M_PI*2*currentFrequency*i/sampleRate+M_PI/4)*4096; float thirdHarmony=sin(2*M_PI*3*currentFrequency*i/sampleRate+M_PI/2)*1024; float fourthHarmony=sin(2*M_PI*4*currentFrequency*i/sampleRate+M_PI/2)*512; float currentAmplitude=(baseFrequency+secondHarmony+thirdHarmony+fourthHarmony)*std::exp(-(float)(2*i+sampleRate)/(sampleRate)); //Attenuation. int16_t numberToBeWritten=(fullNoteName=="P")?(0):(currentAmplitude); numberToBeWritten+=std::rand()%256-128; //A bit of noise makes it sound better. std::fwrite(&amp;numberToBeWritten,2,1,wav); } } std::fclose(wav); } </code></pre> <p>So, what do you think about it?</p>
[]
[ { "body": "<ul>\n<li><p>Don't put everything in <code>main</code>.</p></li>\n<li><p>Prefer an initializer list map constructor:</p>\n\n<pre><code>std::map&lt;std::string,float&gt; notes {\n {\"a\", 220},\n {\"as\", 233},\n ....\n};\n</code></pre></li>\n<li><p>Testing endianness is kinda convoluted. Consider <code>htons</code>: network byte order is big endian.</p>\n\n<pre><code>bool is_little_endian()\n{\n uint16_t x = 0x0055;\n uint16_t y = htons(x);\n return x != y;\n}\n</code></pre></li>\n<li><p><code>while (!inpit.eof())</code> <a href=\"https://stackoverflow.com/a/5605159/3403834\">is wrong</a>.</p></li>\n<li><p>It is very unclear how the input file is formatted. In any case, manual testing for numbers and decimal points is likely unnecessary and error prone. <code>std::strtof</code> will do everything you want with the way less effort and better reliability.</p></li>\n<li><p>I am not that versed in music to figure out what is going on with those harmonies. It looks suspicious that the phase shift is <span class=\"math-container\">\\$\\dfrac{\\pi}{4}\\$</span> for the second harmony, and <span class=\"math-container\">\\$\\dfrac{\\pi}{2}\\$</span> for the third and fourth. Also, the amplitudes of those harmonies look like magic numbers. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T20:31:07.417", "Id": "241724", "ParentId": "241705", "Score": "3" } } ]
{ "AcceptedAnswerId": "241724", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T10:48:08.533", "Id": "241705", "Score": "3", "Tags": [ "c++", "music" ], "Title": "Converting musical notes to WAV" }
241705
<p>I'm currently trying to learn C from the K&amp;R book, reading through and attempting the exercises. I came across exercise 1-12 yesterday and was a little stumped but managed to complete it. I was wondering if someone on here would help me improve it, and also guide me on how to approach testing something like this too.</p> <p>The exercise is to write a program which "prints input one word per line".</p> <pre><code>#include &lt;stdio.h&gt; #define TRUE 1 #define FALSE 0 int main(){ int c, previous_space; previous_space = FALSE; while ( (c = getchar()) != EOF ){ if ( c == ' ' || c == '\n' || c == '\t' ){ if ( previous_space == FALSE ){ putchar('\n'); } previous_space = TRUE; } else{ putchar(c); previous_space = FALSE; } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T14:58:44.393", "Id": "474349", "Score": "1", "body": "@greybeard I'll add that in now! Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T15:38:09.587", "Id": "474352", "Score": "0", "body": "Welcome to CodeReview@SE." } ]
[ { "body": "<p>A few points to consider.</p>\n\n<ol>\n<li><p>C99 added an actual Boolean type, named <code>_Bool</code>, with constants name <code>_True</code> and <code>_False</code>. By including <code>&lt;stdboolh.h&gt;</code>, you get aliases for those spelled <code>bool</code>, <code>true</code> and <code>false</code>. So unless you need to continue using C89, you might consider using these instead of defining your own names and such.</p></li>\n<li><p>When you have a value that's conceptually Boolean in nature (e.g., your <code>previous_space</code>) I'd treat it as a Boolean, so to test if it's <code>false</code>, I'd prefer to use <code>if (!previous_space)</code>.</p></li>\n<li><p>Rather than explicitly checking for every possible white-space character in-line, I'd prefer to move that check into a separately little function of its own. Only this is such a common requirement that the standard library already provides <code>isspace</code>, so (at least in real code) it's generally preferred to <code>#include &lt;ctype.h&gt;</code>, and us that (but the book probably hasn't introduced this yet, so I wouldn't worry about it a whole lot just yet).</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T19:04:03.533", "Id": "241722", "ParentId": "241706", "Score": "3" } }, { "body": "<p><strong>Algorithmic flaw: Input begins with space</strong></p>\n\n<p>Input that begins with <code>' '</code> prints a new-line. No point in that.</p>\n\n<pre><code>// int previous_space;\n// previous_space = FALSE; \nint previous_space = TRUE;\n</code></pre>\n\n<p>Or better with <code>bool</code></p>\n\n<pre><code>bool previous_space = true;\n</code></pre>\n\n<p><strong>Input might not end with a <code>'\\n'</code></strong></p>\n\n<p>A <em>line</em> in C:</p>\n\n<blockquote>\n <p>each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined</p>\n</blockquote>\n\n<p>If code wants to handle the case where input does not end with white-space before the <code>EOF</code>, post-loop code is needed.</p>\n\n<p><strong>Other white-spaces</strong></p>\n\n<p>Aside from OP's 3 listed, there are other white-space characters (carriage return, form-feed, vertical tab, ...), all discernible with <code>isspace()</code>.</p>\n\n<p>(See similar idea in <a href=\"https://codereview.stackexchange.com/a/241722/29485\">@Jerry Coffin</a>)</p>\n\n<p><strong><code>int c</code></strong></p>\n\n<p>Good use of an <code>int</code> instead of <code>char</code> to save the return value from <code>gethar()</code>. Avoided that rookie mistake.</p>\n\n<p><strong>Alternative</strong></p>\n\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(void) {\n bool previous_space = true;\n int c;\n\n while ((c = getchar()) != EOF) {\n if (isspace(c)) {\n if (!previous_space) {\n putchar('\\n');\n }\n previous_space = true;\n } else {\n putchar(c);\n previous_space = false;\n }\n }\n if (!previous_space) {\n putchar('\\n');\n }\n\n return 0;\n}\n</code></pre>\n\n<p><strong>Conceptual simplification</strong></p>\n\n<p>Use the inverse flag like <code>bool need_line_feed = false;</code> to reduce <code>!</code> use in the <code>if()</code>s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T20:44:55.153", "Id": "241780", "ParentId": "241706", "Score": "2" } } ]
{ "AcceptedAnswerId": "241780", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T11:35:15.310", "Id": "241706", "Score": "3", "Tags": [ "algorithm", "c", "design-patterns" ], "Title": "Print input one word per line (K&R 1-12 exercise) attempt" }
241706
<p>In my project I have the following base interfaces used through the application:</p> <pre class="lang-java prettyprint-override"><code>interface Node { /* ... */ } interface NodeService&lt;T&gt; { /* ... */ } </code></pre> <p>Concrete classes might look as follows:</p> <pre class="lang-java prettyprint-override"><code>class User implements Node { /* ... */ } class UserService implements NodeService&lt;User&gt; { /* ... */ } class Entity implements Node { /* ... */ } class EntityService implements NodeService&lt;Entity&gt; { /* ... */ } </code></pre> <p>In the end I want to have a <code>Map&lt;String, Class&lt;? extends NodeService&lt;Node&gt;&gt;&gt;</code> that in the case above might look as follows:</p> <pre><code>Map{ User=UserService.class, Entity=EntityService.class } </code></pre> <p>My current solution has the following approach:</p> <ol> <li>Using the Reflections library find all classes implementing <code>NodeService</code></li> <li>Iterate over all generic interfaces of said classes until we find the <code>NodeService</code> interface</li> <li>Access its first and single generic type argument</li> <li>Cast the type to a class and map it to its simple name</li> <li>Build a tuple (using vavr in this case) containing the simple name and the service class we found in step 1</li> <li>Flatten the result and collect the tuples into a map</li> </ol> <pre class="lang-java prettyprint-override"><code>@SuppressWarnings({"unchecked", "rawtypes"}) final Map&lt;String, Class&lt;? extends NodeService&lt;Node&gt;&gt;&gt; nodeServices = new Reflections(BackendApplication.class.getPackageName()) .getSubTypesOf(NodeService.class).stream() .map( serviceClass -&gt; Stream.of(serviceClass.getGenericInterfaces()) .filter(ParameterizedType.class::isInstance) .map(ParameterizedType.class::cast) .filter(type -&gt; type.getRawType().equals(NodeService.class)) .map(ParameterizedType::getActualTypeArguments) .map(typeArguments -&gt; typeArguments[0]) .filter(Class.class::isInstance) .map(Class.class::cast) .map(Class::getSimpleName) .map(nodeClass -&gt; Tuple.of(nodeClass, (Class) serviceClass)) .collect(Collectors.toSet())) .flatMap(Collection::stream) .collect(Collectors.toMap(Tuple2::_1, Tuple2::_2)); </code></pre> <p>I am surprised that this works in the first place but the code is ridiculously complex and I am looking for suggestions on how to rewrite this. Some of my biggest pain points are the handling of the classes generic interfaces even though in the end I'm only interested in a single one of them making the stream in the middle introduce unnecessary nesting. Furthermore the way I attempt to navigate to the correct type is really bothering me as well.</p> <p>Thus I am open for your input on how to improve this chunk of code.</p> <p>The performance of this snippet is surprisingly good. I am mainly looking for input on the readability and refactoring this to make it much more maintainable, even at the cost of performance since this will be only invoked once during the application lifecycle.</p>
[]
[ { "body": "<p>Should we expect that there are services that have a different type parameter? Because otherwise just a <code>Set</code> of services may suffice, or you can simply remove the <code>Service</code> part of the name during the mapping. This is an obvious thing from the example, but I'm not sure how far the example matches your actual code.</p>\n\n<p>What I often see when streams are used is that suddenly the split up into methods is forsaken. For instance, in my code I would first build a list of services and then create a map out of it. I don't think that an intermediate list would do much w.r.t. performance here (the number of services will be limited, loading the classes will take much more time, and the streaming will have intermediate representations as well), and the code would clearly be simplified. Method chaining can be nice, but please don't overdo it.</p>\n\n<p>Similarly, a method that tests if a class implements an interface can be clearly split out:</p>\n\n<pre><code>Stream.of(serviceClass.getGenericInterfaces())\n .filter(ParameterizedType.class::isInstance)\n .map(ParameterizedType.class::cast)\n .filter(type -&gt; type.getRawType().equals(NodeService.class))\n</code></pre>\n\n<p>And actually, if you do that and look for code you will find <code>NodeService.class.isAssignableFrom(clazz)</code>. The part is well programmed but please do use library functions when they are available.</p>\n\n<p>All of above may not do much with regards to performance, but taking it into account should definitely help with the readability. Currently you had to describe what the code does in the question description. That should not be necessary for well programmed / documented code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T13:14:16.660", "Id": "474342", "Score": "0", "body": "With regards to your first paragraph: each services that handles any type T exposes itself to the map by implementing `NodeService<T>` and will always be responsible for the type `T`. Dropping the `Service` part of the name was something I thought about as well but it would enforce a particular naming scheme of those exposed services. Something that I wanted to not enfore in the first place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T13:22:28.210", "Id": "474345", "Score": "0", "body": "I guess you can reason either way, but in the end I guess that one is subjective. It would also be slightly brittle when it comes to spelling things wrong, but that should show up during testing for normal code. I had a similar command interface and registry but it was easier as I didn't rely on type parameters and used an abstract class instead. Do note that I had some issues with it: during debugging any change resulted in hot code replace failing, so I had to make a manual map in the end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T23:48:32.120", "Id": "474367", "Score": "0", "body": "Toned my answer down a bit. That was too negative - maybe because I don't like programming with streams much. It hurts readability too much in my opinion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T19:07:03.697", "Id": "474450", "Score": "0", "body": "Don't worry, I was mainly waiting for further input by others until I eventually came up with an entirely different solution similar to you approach from the comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T19:15:23.107", "Id": "474451", "Score": "0", "body": "Cool, glad to have been of help." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T13:08:12.533", "Id": "241709", "ParentId": "241708", "Score": "2" } }, { "body": "<p>Today I was able to simplify my approach by introducing a default method into the <code>NodeService</code> interface and leverage Springs dependency injection for lists. The interface looks as follows:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface NodeService&lt;T extends Node&gt; {\n @SuppressWarnings(\"rawtypes\")\n default String getNodeType() {\n return ((Class)\n ((ParameterizedType) getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0])\n .getSimpleName();\n }\n\n /* ... */\n}\n</code></pre>\n\n<p>The respective class using this method to find the respective service ended up like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@RequiredArgsConstructor\npublic class Query implements GraphQLQueryResolver {\n private final List&lt;NodeService&lt;?&gt;&gt; nodeServices;\n\n public Node node(final String id) {\n try {\n val nodeId = NodeId.fromString(id);\n return nodeServices.stream()\n .filter(service -&gt; service.getNodeType().equals(nodeId.getType()))\n ./* ... */;\n } catch (final IllegalArgumentException e) {\n /* ... */\n }\n }\n\n /* ... */\n}\n</code></pre>\n\n<p>Of course I haven't mapped the services to a map as initially wanted, but this would be trivial with the newly introduced method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T18:54:23.320", "Id": "241773", "ParentId": "241708", "Score": "0" } } ]
{ "AcceptedAnswerId": "241773", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T12:37:41.673", "Id": "241708", "Score": "3", "Tags": [ "java", "reflection", "spring" ], "Title": "Find all classes A that implement B<T> and aggregate both A and T to build a map out of them" }
241708
<p>I have implemented an LFU cache and I'm looking for ways to make my code more idiomatic. </p> <pre><code> [dependencies] linked_hash_set = "0.1.3" </code></pre> <pre><code>//! A Least Frequently Used Cache implementation //! //! //! //! //! # Examples //! //! ``` //! extern crate lfu; //! use lfu::LFUCache; //! //! # fn main() { //! let mut lfu = LFUCache::new(2); //initialize an lfu with a maximum capacity of 2 entries //! lfu.set(2, 2); //! lfu.set(3, 3); //! lfu.set(3, 30); //! lfu.set(4,4); //We're at fully capacity. Purge (2,2) since it's the least-recently-used entry, then insert the current entry //! assert_eq!(lfu.get(&amp;2), None); //! assert_eq!(lfu.get(&amp;3), Some(&amp;30)); //! //! # } //! ``` use std::collections::HashMap; use std::hash::Hash; use linked_hash_set::LinkedHashSet; use std::rc::Rc; use std::fmt::Debug; use std::ops::Index; #[derive(Debug)] pub struct LFUCache&lt;K: Hash + Eq, V&gt; { values: HashMap&lt;Rc&lt;K&gt;, ValueCounter&lt;V&gt;&gt;, frequency_bin: HashMap&lt;usize, LinkedHashSet&lt;Rc&lt;K&gt;&gt;&gt;, capacity: usize, min_frequency: usize, } #[derive(Debug)] struct ValueCounter&lt;V&gt; { value: V, count: usize, } impl&lt;V&gt; ValueCounter&lt;V&gt; { fn value(&amp;self) -&gt; &amp;V { return &amp;self.value; } fn count(&amp;self) -&gt; usize { return self.count; } fn inc(&amp;mut self) { self.count += 1; } } impl&lt;K: Hash + Eq, V&gt; LFUCache&lt;K, V&gt; { pub fn new(capacity: usize) -&gt; LFUCache&lt;K, V&gt; { if capacity == 0 { panic!("invalid capacity") } LFUCache { values: HashMap::new(), frequency_bin: HashMap::new(), capacity, min_frequency: 0, } } pub fn contains(&amp;self, key: &amp;K) -&gt; bool { return self.values.contains_key(key); } pub fn len(&amp;self) -&gt; usize { self.values.len() } pub fn remove(&amp;mut self, key: K) -&gt; bool { let key = Rc::new(key); if let Some(value_counter) = self.values.get(&amp;Rc::clone(&amp;key)) { let count = value_counter.count(); self.frequency_bin.entry(count).or_default().remove(&amp;Rc::clone(&amp;key)); self.values.remove(&amp;key); } return false; } /// Returns the value associated with the given key (if it still exists) /// The method is mutable because it internally updates the frequency of the accessed key pub fn get(&amp;mut self, key: &amp;K) -&gt; Option&lt;&amp;V&gt; { if !self.contains(&amp;key) { return None; } let key = self.values.get_key_value(key).map(|(r, _)| Rc::clone(r)).unwrap(); self.update_frequency_bin(Rc::clone(&amp;key)); self.values.get(&amp;key).map(|x| x.value()) } fn update_frequency_bin(&amp;mut self, key: Rc&lt;K&gt;) { let value_counter = self.values.get_mut(&amp;key).unwrap(); let bin = self.frequency_bin.get_mut(&amp;value_counter.count).unwrap(); bin.remove(&amp;key); let count = value_counter.count(); value_counter.inc(); if count == self.min_frequency &amp;&amp; bin.is_empty() { self.min_frequency += 1; } self.frequency_bin.entry(count + 1).or_default().insert(key); } fn evict(&amp;mut self) { let least_frequently_used_keys = self.frequency_bin.get_mut(&amp;self.min_frequency).unwrap(); let least_recently_used = least_frequently_used_keys.pop_front().unwrap(); self.values.remove(&amp;least_recently_used); } pub fn set(&amp;mut self, key: K, value: V) { let key = Rc::new(key); if let Some(value_counter) = self.values.get_mut(&amp;key) { value_counter.value = value; self.update_frequency_bin(Rc::clone(&amp;key)); return; } if self.len() &gt;= self.capacity { self.evict(); } self.values.insert(Rc::clone(&amp;key), ValueCounter { value, count: 1 }); self.min_frequency = 1; self.frequency_bin.entry(self.min_frequency).or_default().insert(key); } } impl&lt;'a, K: Hash + Eq, V&gt; Iterator for &amp;'a LFUCache&lt;K, V&gt; { type Item = (Rc&lt;K&gt;, &amp;'a V); fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { for (k, v) in self.values.iter() { return Some((Rc::clone(k), &amp;v.value)); } return None; } } impl&lt;K: Hash + Eq, V&gt; Index&lt;K&gt; for LFUCache&lt;K, V&gt; { type Output = V; fn index(&amp;self, index: K) -&gt; &amp;Self::Output { return self.values. get(&amp;Rc::new(index)). map(|x| x.value()).unwrap(); } } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let mut lfu = LFUCache::new(20); lfu.set(10, 10); lfu.set(20, 30); assert_eq!(lfu.get(&amp;10).unwrap(), &amp;10); assert_eq!(lfu.get(&amp;30), None); } #[test] fn test_lru_eviction() { let mut lfu = LFUCache::new(2); lfu.set(1, 1); lfu.set(2, 2); lfu.set(3, 3); assert_eq!(lfu.get(&amp;1), None) } #[test] fn test_key_frequency_update() { let mut lfu = LFUCache::new(2); lfu.set(1, 1); lfu.set(2, 2); lfu.set(1, 3); lfu.set(10, 10); assert_eq!(lfu.get(&amp;2), None); assert_eq!(lfu[10], 10); } #[test] fn test_lfu_indexing() { let mut lfu: LFUCache&lt;i32, i32&gt; = LFUCache::new(2); lfu.set(1, 1); assert_eq!(lfu[1], 1); } #[test] fn test_lfu_deletion() { let mut lfu = LFUCache::new(2); lfu.set(1, 1); lfu.set(2, 2); lfu.remove(1); assert_eq!(lfu.get(&amp;1), None); lfu.set(3, 3); lfu.set(4, 4); assert_eq!(lfu.get(&amp;2), None); assert_eq!(lfu.get(&amp;3), Some(&amp;3)); } #[test] fn test_duplicates() { let mut lfu = LFUCache::new(2); lfu.set(&amp;1, 1); lfu.set(&amp;1, 2); lfu.set(&amp;1, 3); assert_eq!(lfu[&amp;1], 3); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:39:03.607", "Id": "474431", "Score": "0", "body": "Is the deterministic behaviour of your cache important? Keeping track of insertion order has a considerable overhead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:39:34.823", "Id": "474432", "Score": "0", "body": "@Plecra yup, it evicts the the least recently used item if there's a tie in frequency" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:44:53.303", "Id": "474433", "Score": "0", "body": "@Plecra I just realized my type design is pretty dumb because it takes ownerhship in the `get()` method :( I don't see an easy fix short of rewriting the whole thing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T18:12:26.733", "Id": "474444", "Score": "0", "body": "@Plecra actually, there *is* an easy fix :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T14:52:23.277", "Id": "241712", "Score": "2", "Tags": [ "rust" ], "Title": "Rust - LFU cache" }
241712
<p>Hi guys below is my code to generate random long unique Ids, I use System.nanoTime to generate long Id but now to make sure that it doesn't clash in the database with previously created Id I get all Id's in the DB then check if it already exists and increment the value. Can you please review and advice if I need to enhance it.</p> <p>code:</p> <pre class="lang-java prettyprint-override"><code>public class UserIdFactoryImpl { @Autowired private SessionFactory sessionFactory; public Long buildUserId() { long generatedValue = System.nanoTime() / 100000; long userId; if (existingUserIds().contains(generatedValue)) { long incrementUserId = generatedValue; ++incrementUserId; userId = incrementUserId; } else { userId = generatedValue; } return userId; } public List&lt;Long&gt; existingUserIds() { List&lt;UserEntity&gt; allUsers = getAllUsers(); return allUsers.stream().map(UserEntity::getUserId).collect(Collectors.toList()); } public List&lt;UserEntity&gt; getAllUsers() { String users = "from UserEntity"; Session currentSession = sessionFactory.getCurrentSession(); Query query = currentSession.createQuery(users); query.setFirstResult(0); query.setMaxResults(100); return query.getResultList(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T17:25:38.403", "Id": "474357", "Score": "7", "body": "Why don't you either use a serial value generated by the database, or a GUID? Generating user IDs this way seems to be odd." } ]
[ { "body": "<h2>Code review</h2>\n\n<pre><code>UserIdFactoryImpl\n</code></pre>\n\n<p>Why is this called <code>Impl</code> if it does <strong>not</strong> extend an interface? Why isn't it <code>final</code> or do you want to allow subclassing? It doesn't seem designed for that...</p>\n\n<hr>\n\n<pre><code>public Long buildUserId() {\n</code></pre>\n\n<p>Any reason why this returns a boxed <code>Long</code> instead of a <code>long</code>? Is this something to do with Spring maybe? Always prefer <code>long</code> if an object is not required. </p>\n\n<p>Furthermore, on systems that allow multithreading I would expect a <code>synchronized</code> modifier to be present.</p>\n\n<hr>\n\n<pre><code>long generatedValue = System.nanoTime() / 100000;\n</code></pre>\n\n<p>Nano time is probably not doing what you think it does:</p>\n\n<blockquote>\n <p>This method can only be used to measure elapsed time and is not\n related to any other notion of system or wall-clock time. The value\n returned represents nanoseconds since some fixed but arbitrary origin\n time (perhaps in the future, so values may be negative). The same\n origin is used by all invocations of this method in an instance of a\n Java virtual machine; other virtual machine instances are likely to\n use a different origin.</p>\n \n <p>This method provides nanosecond precision, but not necessarily\n nanosecond resolution (that is, how frequently the value changes) - no\n guarantees are made except that the resolution is at least as good as\n that of <code>currentTimeMillis()</code>.</p>\n \n <p>Differences in successive calls that span greater than approximately\n 292 years (263 nanoseconds) will not correctly compute elapsed time\n due to numerical overflow.</p>\n \n <p>The values returned by this method become meaningful only when the\n difference between two such values, obtained within the same instance\n of a Java virtual machine, is computed.</p>\n</blockquote>\n\n<p>So the way you are using it to generate user ID's - which will probably live quite long - is <strong>very very</strong> dangerous.</p>\n\n<p>The value <code>100000</code> should be a constant and should be explained. It is not clear why this magic value is present.</p>\n\n<p>When dividing by 100000 you are not even getting to the millisecond requirements of the Java runtime. Worse, you are stripping off more than 16 bits from the 64 bit long value. This means that you are left with less than 48 bits that are hopefully unique. If you take the birthday bound in mind then you may understand that the chances of collision are pretty high just for this.</p>\n\n<p>Even worse, a 100 microseconds precission (which is what you are looking at if I'm not mistaken) is an awfully large window to get collisions in. You could even restart the VM in that amount of time, and there is nothing that prevents the system to start all over.</p>\n\n<hr>\n\n<pre><code>if (existingUserIds().contains(generatedValue)) {\n</code></pre>\n\n<p>Any reason why this is not a <code>while</code> loop? Why would a value + 1 <strong>not</strong> collide with an earlier value?</p>\n\n<hr>\n\n<pre><code>long userId;\n</code></pre>\n\n<p>Ah, finally something I'm happy with: you haven't initiated the variable where it is not required. You could have made it <code>final</code>, but the opinions on that are divided. I must admit that I like doing that for highly secure code (and UID generation may be part of that, I suppose).</p>\n\n<hr>\n\n<pre><code>++incrementUserId;\n</code></pre>\n\n<p>I think <code>incrementUserId++</code> would be more clear here, there is no difference w.r.t. functionality. But seriously, what's wrong with the one-liner</p>\n\n<pre><code>userId = generatedValue + 1;\n</code></pre>\n\n<p>so you can remove the variable altogether?</p>\n\n<hr>\n\n<pre><code>public List&lt;Long&gt; existingUserIds() {\n</code></pre>\n\n<p>I'm not sure I like this. A factory is should not be used to retrieve existing user ID's, so it should not be a <code>public</code> method. Same for the next method, which doesn't even return <code>UserId</code> values`!</p>\n\n<hr>\n\n<pre><code>query.setMaxResults(100);\n</code></pre>\n\n<p>Wait, what? <code>100</code> is a magic value here, I don't know why that value isn't configurable. And seriously, I hate to be the engineer handling more than 100 users on your system. Why set a maximum in the first place: maybe the system will slow down if the list gets too large, but that's still better than making the code fail, <em>right</em>?</p>\n\n<h2>Verdict</h2>\n\n<p>This tries to solve a problem that has already been solved. Just create a random UUID of 128 bits (-6 bits used as overhead). Because those UUID's use so many bits the chance of creating a duplicate are negligible.</p>\n\n<pre><code>UUID uuid = UUID.randomUUID();\n</code></pre>\n\n<p>And that's it. Use <code>toString()</code> if you want to have the string representative instead. You can also retrieve the value as two 64 bit long values (returning the most &amp; least significant 64 bits of course).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T00:21:37.327", "Id": "241727", "ParentId": "241715", "Score": "5" } }, { "body": "<p>Adding to Maarten Bodewes' answer, checking if a user ID exists by loading all user identifiers from database and checking if the ID exists in the result set is extremely inefficient and as Maarten mentioned, limiting the result set to 100 makes the implementation incorrect.</p>\n\n<p>The correct way for this particular implmentation is to create a method <code>private boolean userIdExists(long userId)</code> and check if the query \"<code>SELECT userId from USERS where userId = :id</code>\" returns zero or more rows.</p>\n\n<p>And make note, all this user ID generation code needs to be run inside a database transaction to prevent concurrent execution from inserting two identical identifiers.</p>\n\n<p>But still, use an UUID or a database generated numeric identifier that is automatically generated when a row is inserted to the user table.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T08:23:35.017", "Id": "241740", "ParentId": "241715", "Score": "2" } }, { "body": "<p>As Maarten and Torben already pointed out, creating a user id that way is a terrible idea. I'd like to go one step further and add, that <strong>creating</strong> a userId as a primary key technical identifier for a table is generally a terrible idea.</p>\n\n<p>Leave this to the database. About every database out there offers you the possibility to declare the column as some kind of auto value, may it be random ids, incrementing values or whichever solution. Don't do this in code <strong>at all</strong>. Save the object, read back the modified object, and <em>magic</em> it suddenly has an id.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:49:53.670", "Id": "474416", "Score": "0", "body": "thanks guys for suggestion really appreciate your reviews I have made some changes in my code now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T08:36:34.103", "Id": "241741", "ParentId": "241715", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T17:18:17.763", "Id": "241715", "Score": "1", "Tags": [ "java", "spring", "hibernate" ], "Title": "User Id generator" }
241715
<p>fairly new to playing around with proxy servers. Wrote a really simple one with Express to help keep some API keys secret so that my front-end app can query the GitHub API. Definitely feels a bit clunky, but is working so far. I really haven't done performance testing before but the way this is implemented it seems like > 1 second round trip. I was wondering if anyone wouldn't mind taking a look and giving me some hints at some basic ways I could improve the performance. One thing I saw come up a few times was piping he request from the endpoint directly back to the requester, but so far I haven't been able to get that to work. Granted I haven't made a huge effort at that.</p> <p>The proxy server itself is set up as follows:</p> <pre class="lang-js prettyprint-override"><code>// Express: ^4.17.1 const express = require('express'); const bodyParser = require('body-parser'); const axios = require('axios'); require('dotenv').config(); // Initialize app const app = express(); const port = process.env.PORT || 3000; // Configuration app.use(bodyParser.json({ type: 'application/json' })) // Constants const id = process.env.GITHUB_CLIENT_ID; const secret = process.env.GITHUB_CLIENT_SECRET; const params = `?client_id=${id}&amp;client_secret=${secret}` // Route(s) app.post('/profile', (req, res) =&gt; { const { username } = req.body; const endpoint = `https://api.github.com/users/${username}${params}`; axios({ method: 'get', url: endpoint, }) .then(response =&gt; { res.status(200) res.send(response.data) }) .catch(error =&gt; { console.log('Error with Axios profile res: ', error) res.send({ error }) }) return }) app.post('/repos', (req, res) =&gt; { const { username } = req.body; const endpoint = `https://api.github.com/users/${username}/repos${params}&amp;per_page=100`; axios({ method: 'get', url: endpoint, }) .then(response =&gt; { res.status(200) res.send(response.data) }) .catch(error =&gt; { console.log('Error with Axios repos res: ', error) res.send({ error }) }) return }) // App is initialized using app.listen </code></pre> <p>On the frontend we have React, making requests that are proxied tot my server, where they pick up the API keys, and then the server makes a request to the endpoint on the GitHub API. The front-end is responsible for passing a username along to the endpoint. The relevant front-end code is as follows:</p> <pre class="lang-js prettyprint-override"><code>function getProfile(username) { return fetch('api/profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'username': username }) }) .then(res =&gt; res.json()) .then(profile =&gt; { if (profile.message) { throw new Error(getErrorMsg(profile.message, username)) } return profile }) } function getRepos(username) { return fetch('api/repos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'username': username }) }) .then(res =&gt; res.json()) .then(repos =&gt; { if (repos.message) { throw new Error(getErrorMsg(repos.message, username)) } return repos }) } </code></pre> <p>I can post the React code as well if necessary but it seems like React is not where a bottleneck would be originating - but I'm pretty green at this so that might be mistaken thinking on my part. </p> <p>There are two requests being fired from the React application simultaneously, the end goal being a general comparison of two GitHub users. I've done this without the proxy and things definitely felt snappier, and I haven't really refactored anything on the front-end aside from pointing the requests at the proxy instead of directly at the GitHub API.</p> <p>Thanks in advance for any tips!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T03:40:34.673", "Id": "474370", "Score": "1", "body": "You aren't doing anything expensive anywhere in the code. If you experience sluggishness, I bet it's just due to ping, which is unavoidable, not due to code issues" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:24:51.717", "Id": "474429", "Score": "0", "body": "Ok cool. Because I haven't ever really done legitimate performance testing, and given the scale of this application, I thought I would ask before digging into trying to time the requests. It didn't seem inherently expensive, but the little I read about piping requests directly back to front-end sounded like it would make at least part of the request's journey more direct. Thanks for taking a look." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T17:46:12.740", "Id": "241716", "Score": "1", "Tags": [ "javascript", "react.js", "http", "proxy" ], "Title": "Proxy server performance improvements?" }
241716
<p>I am a relatively new programmer. I am trying to use <code>iter</code> and <code>cycle</code> to cycle over a list (key) and 'pair' each item with each consecutive item in the second list (message). The code below works as expected, producing the desired pairs and stopping when it is done. It does not, however, execute that last <code>print</code> statement ('Okay, it worked!') because it hits 'StopIteration' instead.</p> <p>I can see some kludgy ways to get around this, but how can I more neatly "handle" the StopIteration and have the code "continue"?</p> <pre><code> key = [3, 1, 20] message = ['a', 'b', 'c', 'd', 'e', 'f'] print(key) print(message) print('\n') # Try making a for loop that cycles through the key and iterates # over the message m = iter(message) for k in cycle(key): print(f'{k}:{next(m)}') print('Okay, it worked!') <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T04:04:01.077", "Id": "474372", "Score": "2", "body": "Please include any indispensable imports. Show the kludgy code - with non-working code (only), your question is [off topic](https://codereview.stackexchange.com/help/on-topic). When editing the post, anyway, add a newline at the end of a trailing `~~~` (or `\\`\\`\\``) line." } ]
[ { "body": "<p>Creating a \"manual\" iterator using <code>iter</code> and then calling <code>next</code> can be tricky, as you found out.\nOnce an iterator is exhausted, it raises a <code>StopIteration</code> to signal its end.\nIf you do not catch that in a <code>try/except</code> block, your program will exit ungracefully.</p>\n\n<p>Luckily, <code>message</code>, being a list, is perfectly iterable without being explicit about it.\nSimply using it in a <code>for</code> loop will do the <code>iter</code>/<code>next</code> magic for you, and the loop will exit once <code>StopIteration</code> is reached, without error.</p>\n\n<p><code>zip</code> is a built-in so you can iterate over multiple iterables at once.\n<code>zip</code> will iterate until the shortest of the passed iterables is exhausted.\nThis can be tricky if you <em>expect</em> the iterables to be of the same length.\nThere is currently talk about a <code>strict</code> flag in the Python ideas mailing list, which would throw errors if <code>strict=True</code> and the iterables are of different lengths.</p>\n\n<p>Assuming you meant to include <code>from itertools import cycle</code>, alongside <code>cycle</code>, of course <code>message</code> is exhausted first.\n<code>cycle</code> being infinite, this suprises no one in this case.\nThe <code>for</code> loop then simply ends after the last <code>message</code> element.</p>\n\n<p>This hopefully does what you want to do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import cycle\n\nkeys = [3, 1, 20]\nmessage = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n\nprint(keys, message, sep=\"\\n\", end=\"\\n\" * 2)\n\nfor key, letter in zip(cycle(keys), message):\n print(f\"{key}: {letter}\")\n\nprint(\"Okay, it worked!\")\n</code></pre>\n\n<hr>\n\n<p>This is more like your version, needlessly verbose.\nNever do this in reality!\nHowever, it can help you understand what is going on in your case:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import cycle\n\nkeys = [3, 1, 20]\nmessage = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n\nprint(keys, message, sep=\"\\n\", end=\"\\n\" * 2)\n\nmessage_iter = iter(message)\n\nfor key in cycle(keys):\n try:\n print(f\"{key}: {next(message_iter)}\")\n except StopIteration:\n break # Break out of infinite loop\n\nprint(\"Okay, it worked!\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T18:24:53.130", "Id": "474358", "Score": "1", "body": "This code solves my problem, and gives me some perspective on iter, thanks. I had tried zip first actually, but run into the problem of the shorter list \"running out\". This solves that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T18:14:54.230", "Id": "241719", "ParentId": "241717", "Score": "6" } } ]
{ "AcceptedAnswerId": "241719", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-04T18:05:25.570", "Id": "241717", "Score": "1", "Tags": [ "python", "iteration" ], "Title": "Iterate over a short list, pairing the elements with the sequential elements of a longer list" }
241717
<p>I've decided to learn Python about 2 weeks ago, been going through various books and videos, and I've decided to try my hand at programming a Tic Tac Toe game. I was somewhat successful (it doesn't recognize if there's already a mark in a certain spot and allows overwriting of already placed marks) and I was wondering if any more experienced programmers could give me some general feedback about how I could do things better, and how to prevent overwriting of previously placed mark.</p> <pre><code> board = ['-'] * 9 def print_board(): print (board[0] + '|' + board[1] + '|' + board[2]) print (board[3] + '|' + board[4] + '|' + board[5]) print (board[6] + '|' + board[7] + '|' + board[8]) legalMoves = [1,2,3,4,5,6,7,8,9] print_board() turnCount = 0 def move(): move = int(input('Pick a number 1-9:')) while move not in legalMoves: print('Illegal move') move = int(input('Pick a number 1-9:')) marks = ['X','O'] if turnCount % 2 == 0: board[move - 1] = marks[1] else: board[move - 1] = marks[0] while True: if board[0] == board[1] == board[2] == 'X'\ or board[3] == board[4] == board[5] == 'X'\ or board[6] == board[7] == board[8] == 'X'\ or board[0] == board[3] == board[6] == 'X'\ or board[1] == board[4] == board[7] == 'X'\ or board[2] == board[5] == board[8] == 'X'\ or board[0] == board[4] == board[8] == 'X'\ or board[2] == board[4] == board[6] == 'X' \ or board[0] == board[1] == board[2] == 'O' \ or board[3] == board[4] == board[5] == 'O' \ or board[6] == board[7] == board[8] == 'O' \ or board[0] == board[3] == board[6] == 'O' \ or board[1] == board[4] == board[7] == 'O' \ or board[2] == board[5] == board[8] == 'O' \ or board[0] == board[4] == board[8] == 'O': print('Victory') break else: move() print_board() turnCount = turnCount + 1 </code></pre>
[]
[ { "body": "<p><strong>Here are my notes:</strong></p>\n\n<p>your printBoard function has code repetition, you can see there is a pattern 0 1 2, 3 4 5, 6 7 8, so you can do a for loop, example:</p>\n\n<pre><code>for i in range(3):\n print (board[i * 3] + '|' + board[i * 3 + 1] + '|' + board[i * 3 + 2])\n</code></pre>\n\n<p>your legalMoves list is not required, because it's just numbers from 1 to 9, so you can check against that example: <code>if n &gt;= 1 and n &lt;= 9: #accepted</code></p>\n\n<p>\"move = int(input('Pick a number 1-9:'))\", you need to check for the input first if it can be converted to int or not to prevent the user from breaking your program if non int string value was typed, and to do that you can store the input in a string then check against it to be an int or not example:</p>\n\n<pre><code>def isInt(strInt):\n for c in strInt:\n if c not in \"0123456789\": return False\n return True\n\nn = input()\nif isInt(n): move = int(n)\n</code></pre>\n\n<p>and your checks inside the while loop can be shortened to using for loop instead, you can see a pattern in those cells positions, so if you want to check horizontally, yoou need to do, example:</p>\n\n<pre><code>for i in range(3):\n if board[i * 3] == board[i * 3 + 1] == board[i * 3 + 2] and board[i * 3] != \"-\":\n # do something\n</code></pre>\n\n<p>and vertically</p>\n\n<pre><code>for i in range(3):\n if board[i] == board[i + 3] == board[i + 6] and board[i] != \"-\":\n # do something\n</code></pre>\n\n<p>and diagonally</p>\n\n<pre><code> if (board[0] == board[4] == board[8] or board[2] == board[4] == board[6]) and board[4] != \"-\":\n</code></pre>\n\n<p>without checking for \"X\" or \"O\", you just need to check for \"-\"</p>\n\n<p>you need also to prevent the user from overwriting an already filled cell, example</p>\n\n<pre><code>if board[move - 1] != \"-\":\n print(\"Pls choose an empty cell\")\n</code></pre>\n\n<p>you need also to check for tie, because not all time you get a winner example if your main loop I mean the one for each user correct move which are 9 moves, if it reaches the end and there is no winner then it's a tie, and you should let the user know.</p>\n\n<p>That's it, you can improve your code now, I hope you like my feedBack, also I have written a full solution, you can find it in your <a href=\"https://stackoverflow.com/questions/61603764/total-beginner-wrote-a-tic-tac-toe-game-in-python-and-would-like-some-feedback/61604049#61604049\"><strong>question</strong></a> in Stack Overflow, and if you have any question, I will be happy to answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T04:21:49.720", "Id": "474375", "Score": "1", "body": "There is `1 <= n <= 9`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T12:24:33.743", "Id": "474403", "Score": "0", "body": "@greybeard yes thanks, I have edited my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T02:52:47.913", "Id": "474731", "Score": "0", "body": "Thank you so much Sam, I really appreciate it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T12:15:32.123", "Id": "474794", "Score": "0", "body": "You are welcome Marlo, I'm glad I could help!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T02:20:29.017", "Id": "241732", "ParentId": "241730", "Score": "2" } } ]
{ "AcceptedAnswerId": "241732", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T01:36:09.923", "Id": "241730", "Score": "1", "Tags": [ "python", "tic-tac-toe" ], "Title": "Total beginner Tic Tac Toe game in Python" }
241730
<p>I am calculating a likelihood surface for a modified negative binomial distribution with two parameters: mean <code>R</code> and dispersion <code>k</code> (the probability distribution is 'modified' to account for total size distributions of networks, so cant use inherent MLE (i.e. <code>MASS::fitdistr</code>)). Thus, I'm running simulated data through the various functions below to obtain a point estimate and confidence interval.</p> <p>Since the MLE of <code>k</code> is predicated on <code>R</code>, I am using <a href="https://stats.stackexchange.com/questions/28671/what-is-the-exact-definition-of-profile-likelihood">profile likelihood</a> My approach to this is by creating a matrix of <code>R</code> and <code>k</code> values, then getting the log-likelihood of each permutation and finding where it is maximized.</p> <p>The current code achieves my goal of calculating a point estimate and confidence interval, but is very time consuming - <strong>I don't know if the speed is just inherent with R having to calculate the math for each permutation, or if there is a way to improve the speed through code.</strong> With a simulated dataset of length 500, it takes about 30 minutes. I am simulating data from lengths of 50 to 2000 several hundred times times, so imagine some of them will have to run for hours. Improving the speed will save critical days. </p> <p>The below functions calculate the likelihood surface across a range of <code>R</code> and <code>k</code> values. The function <code>surflike_yn</code> is the time consuming process, as it runs the other functions for each combination of <code>R</code> and <code>k</code>. </p> <p><strong>My question is how to improve the performance/time of these functions.</strong> I typically use R for much simpler processes and have never needed to truly consider performance until now. </p> <pre><code>#Probability distribution nb_yn &lt;- function(y,n,R,k) { logpyn &lt;- log(n) - log(y) + lgamma(k*y+y-n) - lgamma(k*y) - lgamma(y-n+1) + log((R/k)^(y-n)/(1+R/k)^(k*y+y-n)) return(logpyn) } # Likelihood function like_yn&lt;- function(simdata,r1,k1){ runs &lt;- nrow(simdata) liks &lt;- rep(1,runs) for(z in 1:runs){ liks[z] &lt;- nb_yn(simdata[z,1],simdata[z,2],r1,k1) } sum(liks) } # Calculate likelihood surface (***this is the time consuming step***) surflike_yn&lt;- function(simdata,Rrange,krange){ likesurf &lt;- data.frame(matrix(NA, nrow=length(Rrange),length(krange))) for(i in 1:length(Rrange)){ for(j in 1:length(krange)){ likesurf[i,j] &lt;- like_yn(simdata,Rrange[i],krange[j]) } } likesurf } #Get point and CI estimates surfests_yn&lt;-function(likesurf,likesurf_max,conf.interval){ chiV&lt;-qchisq(conf.interval/100, df=1)/2 prfk &lt;- apply(likesurf,2,function(x){max(x)}) prfk2 &lt;- krange[prfk-max(prfk)&gt;-chiV] prfR &lt;- apply(likesurf,1,function(x){max(x)}) prfR2 &lt;- Rrange[prfR-max(prfR)&gt;-chiV] output &lt;- matrix(NA,2,3) output[1,1] &lt;- Rrange[sum(seq(1,length(Rrange))%*%likesurf_max)] output[1,2] &lt;- min(prfR2) output[1,3] &lt;- max(prfR2) output[2,1] &lt;- krange[sum(likesurf_max%*%seq(1,length(krange)))] output[2,2] &lt;- min(prfk2) output[2,3] &lt;- ifelse(max(prfk2)==max(krange),Inf,max(prfk2)) colnames(output) &lt;- c("point_est","lower_ci","upper_ci"); rownames(output) &lt;- c("R","k") return(output) } </code></pre> <p>Below, I am providing code that I use to simulate data to run these functions (<em>this does not necessarily need review</em>; I use these functions in other processes which is why they may not be optimized)</p> <p>My simulated data are a two column matrix. The first column are the size distributions (Y), the second is how many values this is conditioned on (i.e. P(Y|n) if two networks cant be unambiguously teases apart - n is almost always 1 in practice)</p> <pre><code>#Set up R and k "search grid" for profile likelihood Rlow=0.05; Rhigh=1.05; Rrange=seq(Rlow,Rhigh,by=0.01) klow=0.04; khigh=55; krange=seq(klow,khigh,by=0.01) #Generate dummy data with R=0.5 and k=0.25 and ALL index cases=1 #Brancing process function bp &lt;- function(gens=20, init.size=1, offspring, ...){ Z &lt;- list(); Z[[1]] &lt;- init.size; i &lt;- 1 while(sum(Z[[i]]) &gt; 0 &amp;&amp; i &lt;= gens) { Z[[i+1]] &lt;- offspring(sum(Z[[i]]), ...) i &lt;- i+1 } return(Z) } #generate data (n=100) set.seed(2020) ind&lt;-replicate(100,bp(offspring=rnbinom, size=0.25,mu=0.5)) clust&lt;-t(data.frame(lapply(ind,function(x) sum(unlist(x))))) Yn &lt;- cbind(clust,rep(1,times=length(clust))) #2 x n matrix will all index cases=1 #Calculate surface likelihoods and parameter estimates start_time &lt;- Sys.time() surf &lt;- surflike_yn(Yn,Rrange,krange) end_time &lt;- Sys.time() duration &lt;- end_time - start_time surf_max &lt;- surf==max(surf) surfests_yn(surf,surf_max,95) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T11:56:33.327", "Id": "474401", "Score": "0", "body": "Hi @greybeard - `like_yn()` should be the second function listed in the first code block. Please let me know if it isn't showing up, it appears on my end. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T20:00:38.250", "Id": "474454", "Score": "1", "body": "(By the looks of it, I didn't copy from code block to my IDE quite successfully.)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T01:47:05.073", "Id": "241731", "Score": "1", "Tags": [ "performance", "r" ], "Title": "Profile maximum likelihood programming in R" }
241731
<p>I am building an API server in golang with mongodb. My <code>main.go</code> file looks something like this:</p> <pre class="lang-golang prettyprint-override"><code>func main() { r := mux.NewRouter() question := r.PathPrefix("/question").Subrouter() question.HandleFunc("", handler.PostQuestion).Methods("POST") question.HandleFunc("/{id}", handler.UpdateQuestion).Methods("PUT") question.HandleFunc("/{id}", handler.DeleteQuestion).Methods("DELETE") question.HandleFunc("/{id}", handler.GetQuestion).Methods("GET") r.HandleFunc("/questions", handler.GetAllQuestions).Methods("GET") if err := http.ListenAndServe(":8080", r); err != nil { log.Fatalf("could not listen on port 8080 %v", err) } } </code></pre> <p>Every handler has some logic which changes data in MongoDB. Regardless of what I am doing with the question collection, this is common in all the handlers.</p> <pre class="lang-golang prettyprint-override"><code>client, _ := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017")) ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) err := client.Connect(ctx) if err != nil { panic(err) } defer client.Disconnect(ctx) collection := client.Database("myapp").Collection("questions") </code></pre> <p>These functions are in <code>handler/handler.go</code>.</p> <p>As you can see, I am using the official Mongo driver. What is the best kind of refactor which can be done?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:32:57.163", "Id": "474430", "Score": "0", "body": "Is the title any better?" } ]
[ { "body": "<p>You say this is common in all handlers:</p>\n\n<pre><code>client, _ := mongo.NewClient(options.Client().ApplyURI(\"mongodb://127.0.0.1:27017\"))\nctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\nerr := client.Connect(ctx)\nif err != nil {\n panic(err)\n}\n\ndefer client.Disconnect(ctx)\ncollection := client.Database(\"myapp\").Collection(\"questions\")\n</code></pre>\n\n<p>So this means you're connecting and disconnecting to MongoDB <em>for each request</em>. That's incredibly wasteful. The MongoDB client is safe for concurrent use, so you can reuse the connection. Because I see code like this:</p>\n\n<pre><code>question.HandleFunc(\"\", handler.PostQuestion).Methods(\"POST\")\n</code></pre>\n\n<p>I know your handler functions are methods, so why not add the client to your handler type:</p>\n\n<pre><code>type yourHandler struct {\n coll *mongo.Collection\n}\n</code></pre>\n\n<p>Then, in your handlers you can simply access:</p>\n\n<pre><code>func (h *yourHandler) PostQuestion(w http.ResponseWriter, r *http.Request) {\n if err := h.coll.InsertOne(r.Context(), ...); err != nil {\n // write error response\n return\n }\n}\n</code></pre>\n\n<p>Now your main function will look a bit different, seeing as we're not disconnecting the mongo client in the handler anymore, and we're not using a context with an arbitrary timeout. I suggest something like this:</p>\n\n<pre><code>func main() {\n // create the base context, the context in which your application runs\n ctx, cfunc := context.WithCancel(ctx.Background())\n defer cfunc()\n client, err := mongo.NewClient(\n options.Client().ApplyURI(\"mongodb://127.0.0.1:27017\"))\n if err != nil {\n log.Fatalf(\"Error creating mongo client: %+v\", err)\n }\n defer client.Disconnect(ctx) // add disconnect call here\n if err := client.Connect(ctx); err != nil {\n log.Fatalf(\"Failed to connect to MongoDB: %+v\", err)\n }\n // set collection on handler\n handler.coll = client.Database(\"myapp\").Collection(\"questions\")\n // rest of the code here\n}\n</code></pre>\n\n<p>So now, whenever the main function returns, the application context is cancelled (which is used to connect the client), and <code>client.Disconnect</code> is called. The handler has access to the collection you're using, removing a lot of duplicate code, and removing the overhead of constantly connecting and disconnecting to MongoDB.</p>\n\n<p>Inside your handler, I'm not using <code>context.WithTimeout(context.Background(), 10*time.Second)</code>. Instead I'm using the request context, which means once the request context is cancelled, the query context is. You could still set a time-limit if you want:</p>\n\n<pre><code>func (h *yourHandler) PostQuestion(w http.ResponseWriter, r *http.Request) {\n // context expires if request context does, or times out in 3 seconds\n ctx, cfunc := context.WithTimeout(r.Context(), time.Second * 3)\n defer cfunc() // good form to add this\n if err := h.coll.InsertOne(ctx, ...); err != nil {\n // error response etc...\n return\n }\n // success response\n}\n</code></pre>\n\n<p>Currently our handler requires the field <code>coll</code> to be of the type <code>*mongo.Collection</code>, which makes it harder to test your code. Instead, you might want to change that field to take an interface:</p>\n\n<pre><code>//go:generate go run github.com/golang/mock/mockgen -destination mocks/collection_interface_mock.go -package mocks your.module.io/path/to/handler/package Collection\ntype Collection interface{\n InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)\n Name() string\n // all methods you need\n}\n</code></pre>\n\n<p>In your unit tests, you can now inject a mock collection interface, that you can control, allowing you to simulate error returns, etc...</p>\n\n<p>Instead of exposing the <code>coll</code> field on your handler, then, you'll also want to create a constructor function to inject the dependencies of what I have in the main function above (<code>handler.coll = ...</code>):</p>\n\n<pre><code>package service\n\ntype Collection interface{} // interface as above, with go generate comment\n\ntype handler struct {\n coll Collection\n}\n\nfunc NewHandler(c Collection) *handler {\n return &amp;handler{\n coll: c,\n }\n}\n</code></pre>\n\n<p>I'll leave you with this as a starting point. Just one thing I've not yet mentioned: you're using <code>log.Fatalf</code> when <code>http.ListenAndServe</code> returns an error. That's fine. Why are you using <code>panic(err)</code> when <code>client.Connect(ctx)</code> fails?</p>\n\n<p>Panic is something you should avoid as much as possible. Especially here: it adds very little (to no) value: the only information a panic dump will yield is whereabouts in the mongo package something went awry. You don't control that package, so just <code>log.Fatalf(\"Mongo error: %+v\", err)</code> is to be preferred.</p>\n\n<hr>\n\n<h3>More details</h3>\n\n<p>Seeing as your handler functions are actually functions in a package, rather than methods (which I initially thought they were):</p>\n\n<p>I'd refactor the <code>handler</code> package to contain a constructor, and have the actual handler functions as methods on a type. Something like:</p>\n\n<pre><code>package handler\n\ntype Collection interface{\n InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error)\n Name() string\n // and so on\n}\n\n// main handler type\ntype Handler struct {\n coll Collection\n}\n\n// New returns the handler\nfunc New(c Collection) *Handler {\n return &amp;Handler{\n coll: c,\n }\n}\n\nfunc (h *Handler) PostQuestion(w http.ResponseWriter, r *http.Request) {\n if err := h.coll.InsertOne(r.Context(), ...); err != nil {\n log.Errorf(\"Insert question error: %+v\", err)\n // write response\n return\n }\n // success response\n}\n</code></pre>\n\n<p>From your <code>main</code> package, this will look like this:</p>\n\n<pre><code>func main() {\n ctx, cfunc := context.WithCancel(ctx.Background())\n defer cfunc()\n client, err := mongo.NewClient(\n options.Client().ApplyURI(\"mongodb://127.0.0.1:27017\"))\n if err != nil {\n log.Fatalf(\"Error creating mongo client: %+v\", err)\n }\n defer client.Disconnect(ctx) // add disconnect call here\n if err := client.Connect(ctx); err != nil {\n log.Fatalf(\"Failed to connect to MongoDB: %+v\", err)\n }\n // create handler with collection injected\n myHandler := handler.New(client.Database(\"myapp\").Collection(\"questions\"))\n\n // configure router to call methods on myHandler as handler functions\n // the handlers will now have access to the collection we've set up here\n r := mux.NewRouter() \n\n question := r.PathPrefix(\"/question\").Subrouter()\n question.HandleFunc(\"\", myHandler.PostQuestion).Methods(\"POST\")\n // and so on\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T11:31:04.300", "Id": "474786", "Score": "0", "body": "Thank you for your kind reply. I am relatively new to the golang (coming from the python) and your answer is very insightful. One question. When you did `handler.coll = ...` in main.go. Did you mean `yourHandler.coll`? Because I have a package of the same name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T11:32:25.687", "Id": "474788", "Score": "0", "body": "And when I do `handler.MyHandler.coll = ...`, the linter complaints `type handler.MyHandler has no field or method collection`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T12:47:48.200", "Id": "474797", "Score": "0", "body": "@SantoshKumar If `handler` is a package name, then your handler functions clearly are just functions, not receiver functions/methods. Declare a type in the handler package, have a `New` function in htere to which you pass the collection (constructor style injection), and then assign (e.g. `myHandler := handler.New(collection)`). Then replace handler functions with methods (`handler.PostQuestion` -> `myHandler.PostQuestion`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T12:57:51.197", "Id": "474799", "Score": "0", "body": "Added a bit more details to the answer, showing what the type in the handler package would look like, and how to use it in your `main` func. Accessing a type `handler.MyHandler.coll` isn't correct (you access fields on an instance, not on a type name). the `coll` field is (rightfully) not exported, and cannot be set from the `main` package, so you'll need to pass that dependency via a constructor (like I did)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T17:40:18.447", "Id": "474833", "Score": "0", "body": "I am getting an error at Collection interface definition. On `bson.M` I'm getting `expected type, found '.'` Is this the same signature from [mongo docs](https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo?tab=doc#Collection.InsertOne), because in Mongo docs, InsertOne returns two value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-09T08:17:13.253", "Id": "474906", "Score": "0", "body": "@SantoshKumar Yes, the `Collection` interface has to contain the methods from the `mongo.Collection` type. I'll update the answer to reflect this. Keep in mind, this is code review, not a copy-paste ready refactor of your code, so there's likely to be other issues/omissions. It's a starting point. I've not tested a single line of this code" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T09:10:12.553", "Id": "241870", "ParentId": "241739", "Score": "3" } } ]
{ "AcceptedAnswerId": "241870", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T07:56:40.440", "Id": "241739", "Score": "1", "Tags": [ "performance", "beginner", "go", "mongodb" ], "Title": "connection to mongodb in golang" }
241739
<h2>Question</h2> <p>I feel like my code could be more elegant/more pythonic/faster, but I can't think of too much more to improve. So, I've come to the internet to see what more can be done with standard python.</p> <h2>What my code does</h2> <p>My code counts anagrams for each word in a list of words. For example:</p> <pre><code>post, spot stop, tops </code></pre> <p>are four of the words in my list and since all are anagrams of each other, each word should map to the number 4 in a dictionary. Specifically I'm counting the size of the anagram group each word would fit in. The output for a few words would look something like the following then:</p> <pre><code>{'1-2-3': 1, '1980s': 1, '1990s': 1, ... ... 'top': 1, 'topic': 2, 'topics': 1, 'topped': 1, 'tops': 4, 'tory': 2, 'total': 1, 'totals': 1, 'touch': 1, 'tough': 2, ... ... 'zone': 1, 'zones': 1, 'zurich': 1} </code></pre> <h2>My code</h2> <pre><code>from itertools import permutations from collections import Counter def get_variants(word): return map(lambda t: "".join(t), set(permutations(word))) def count_anagrams(words): anagram_counts = {w: 1 for w in words} word_counters = list(map(Counter, words)) for i, (word, counter) in enumerate(zip(words, word_counters)): for other_word, other_counter in zip(words[i+1:], word_counters[i+1:]): if counter == other_counter: anagram_counts[word] += 1 anagram_counts[other_word] += 1 return anagram_counts </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:04:17.877", "Id": "474410", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h1>Performance (Language independent)</h1>\n\n<p>The permutations scale factorially with the word length and your loop code squares quadratically with the number of words. \nBoth are really bad scaling factors.\nThe nice thing to realize, that all equivalent anagrams map to the same multiset.\nThere are python libraries for multisets, but already with the built-in tools you can go a long way.\nTwo strings are equivalent, under \"Anagram-relation\", if they are the same after sorting. We will treat the sorted string as representation of our Anagram equivalence class. Since strings are immutable you can even use these represantions directly as dictionary keys.</p>\n\n<p>Your code becomes then quite short</p>\n\n<pre><code>from collections import defaultdict\n\ndef count_anagrams(words):\n result = defaultdict(list)\n for word in words:\n result[''.join(sorted(word))].append(word)\n return dict(result)\n</code></pre>\n\n<p>This scales linearly with word number and (n * log(n)) with word length. (Under the assumption that dictionary insertion is O(1) and <code>sorted</code> uses a reasonable sorting algorithm.).</p>\n\n<p>The output of</p>\n\n<pre><code>count_anagrams(['stop', 'test', 'post'])\n</code></pre>\n\n<p>is then </p>\n\n<pre><code>{'opst': ['stop', 'post'], 'estt': ['test']}\n</code></pre>\n\n<p>You can change it to your needs by transforming it to your desired output with <code>len</code> etc.</p>\n\n<p>If you want to convert it to the exact same form as you have it, one example function would be:</p>\n\n<pre><code>def convert_output(words_in_anagram_class):\n return {word: len(words)\n for words in words_in_anagram_class.values() \n for word in words}\n</code></pre>\n\n<p>Then you can call <code>convert_output(count_anagrams(words))</code>. If you want to, you can combine these two functions into one.\n(Although this is IMHO a far less useful representation of your data.)</p>\n\n<h1>Small stuff (Python nitpicks)</h1>\n\n<p><code>map</code> can and should be replaced with comprehensions. Especially if you cast the result into a list.\n<code>[f(x) for x in iterable]</code> is far nicer to read than <code>list(map(f, iterable))</code>.\nIf you really want a generator, there are also generator expressions\n<code>(f(x) for x in iterable)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T12:32:55.313", "Id": "474404", "Score": "0", "body": "Why use a sorted string rather than a counter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T13:14:05.450", "Id": "474406", "Score": "2", "body": "Conceptional problem: I don't get exactly what you want. Could you expand? Technical problem: You cannot use a counter as dict key." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T13:25:26.253", "Id": "474407", "Score": "0", "body": "So, my code has the original word, rather than the sorted version as the key and then the corresponding value would be the length (or the list of anagrams in your case). Using that key, you could either compare counters, or the sorted word. Why use one rather than the other? In general, what do I do if I want the actual word (unsorted) as the key?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:29:08.047", "Id": "474421", "Score": "3", "body": "Nice solution. To get the format the OP wants, you just need 2 passes.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:53:37.300", "Id": "474434", "Score": "0", "body": "@MaartenFabré Thank you very much. ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:31:49.060", "Id": "474471", "Score": "0", "body": "@Luapulu If I am understanding what you are asking, you cannot use the counter because ['opts', 'spot', 'stop', 'tops'] might not be the only group of four words that are anagrams of one another, so 4 would not be a unique key for them. You don't need to use the sorted word as a key, you simply need to use some canonical key. The sorted word just happens to be a convenient canonicalization of any of the words in the group." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T09:13:51.000", "Id": "474502", "Score": "0", "body": "I'm not suggesting that one should use the length as the key as in {4: [\"tops\", ...]}. My question was why the canonical form should be the sorted word, rather than a counter, especially because I think they were intended to be used as multisets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T09:16:09.453", "Id": "474503", "Score": "0", "body": "To answer my own question: counters can't be used to implement the linear scaling algorithm shown above. Since linear scaling is better than quadratic scaling (comparing each word to every other word), you're better off using the sorted word. Then, as @MaartenFabré suggests, you can do a second pass to achieve the same format as I had originally. Edit: conceivably, you could convert the counter to a string or something like that and use that as a key, but that seems unnecessarily complicated." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T11:59:43.463", "Id": "241748", "ParentId": "241744", "Score": "9" } }, { "body": "<p>Additionally to mcocdawc's <a href=\"https://codereview.stackexchange.com/a/241748/123200\">answer</a>, since what I mean is too much for a comment</p>\n\n<p>You need an intermediate stage. \nYou used the list of Counters for this. But then to find anagrams in the list is expensive. A dict would be a better way, and a <code>collections.Counter</code> is especially made for this purpose. Now you just need to find an acceptable representation of your word to discern anagrams. mcocdawc suggested the sorted string, since 2 anagrams result in the same response if you sort the letters. An alternative is the <code>frozenset</code> of the items of a Counter. I suspect the sorted list will be faster, but you'll need to test that.</p>\n\n<p>Based on mcocdawc, but without the intermediate lists:</p>\n\n<pre><code>def count_anagrams(words):\n counter = Counter()\n intermediate = {}\n for word in words:\n intermediate_key = ''.join(sorted(word))\n# intermediate_key = tuple(sorted(word)) # alternatively\n# intermediate_key = frozenset(Counter(word).items()) # alternatively\n counter[intermediate_key] += 1\n intermediate[word] = intermediate_key \n return {\n word: counter[intermediate_key]\n for word, intermediate_key in intermediate.items()\n }\n</code></pre>\n\n<p>I'm not saying this is better/faster than mcocdawc's answer, but I think the intermediate structure is closer to </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T13:20:49.953", "Id": "241820", "ParentId": "241744", "Score": "3" } } ]
{ "AcceptedAnswerId": "241748", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T09:43:16.607", "Id": "241744", "Score": "5", "Tags": [ "python", "performance", "python-3.x" ], "Title": "More elegant way to count anagrams in Python?" }
241744
<p>The goal is to find the longest peak in a sequence of numbers. A peak is defined to be a strictly increasing elements until a tip is found and then a strictly decreasing elements.</p> <p>e.g. (1): 3, 2, 1, 2, 3, 4, 3, 0, 10, 0, 1, 2, 2, 1, 0</p> <p>1, 2, 3, 4, 3, 0 is a peak; 0, 10, 0 is a peak; 0, 1, 2, 2, 1, 0 is <strong>NOT</strong> a peak (there is no tip);</p> <p>e.g. (2): 1, 3, 2 is a peak</p> <p>e.g. (3): 1, 2, 3 is NOT a peak</p> <p>I'm trying to do so without backtracking - i.e. without finding a peak and then going outwards from it both back and front. </p> <p>Here's a code I came up with</p> <pre><code>def longestPeak(array): longest = peakStart = peakEnd = 0 peakArrived = False for i in range(1, len(array) - 1): # Check for peak if array[i-1] &lt; array[i] and array[i] &gt; array[i+1]: peakArrived = True if len(array) == 3: # special case return 3 # Check for end if array[i] &lt;= array[i+1] and array[i] &lt; array[i-1]: peakEnd = i elif array[i+1] &lt; array[i] and i+2 == len(array): peakEnd = i+1 # Check for longest if peakArrived and peakEnd &gt; peakStart and peakEnd - peakStart + 1 &gt; longest: longest = peakEnd - peakStart + 1 peakArrived = False # Check for start if array[i] &lt; array[i+1] and array[i] &lt;= array[i-1]: peakStart = i elif array[i] &gt; array[i-1] and i == 1: peakStart = 0 return longest </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T17:32:54.817", "Id": "474573", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a new question instead." } ]
[ { "body": "<p>Are you sure that solution is correct? By your description of the problem, I would have expected the result for an input <code>[1, 6, 4, 7, 6, 6, 5]</code> to be <code>3</code>, but your solution produces <code>5</code>.</p>\n\n<p>Your solution is interesting -- that drew me to this question. I find that code looking at adjacent elements when iterating and accumulating an optimal value is a code smell in algorithms. It typically makes a solution significantly more difficult to read and debug. Usually, you should only look at as few values in each iteration as possible -- and I believe it's sufficient to look only at the current value <em>whilst keeping the previous handy</em>.</p>\n\n<pre><code> if array[i-1] &lt; array[i] and array[i] &gt; array[i+1]:\n</code></pre>\n\n<p>This confers the additional benefit of removing the random access requirement for the input; that is, removing the <code>__getitem__</code> dependency (<code>array[i]</code> is actioned as <code>type( array ).__getitem__( array, i )</code>). Whilst you've indicated that the input should be an array by the parameter name, one of Python's strengths is its duck-typing. There's no fundamental reason why the algorithm could not, or should not, apply more generically to any <code>Iterable[int]</code>. My solutions below will additionally work with input (contrived, I grant you) <code>( x for x in ( 0, 1, 0 ) )</code>. If your minimum Python version requirement is sufficiently high, I would personally add a type hint to the argument, but that's usually deemed overkill.</p>\n\n<pre><code> if len(array) == 3: # special case\n return 3\n</code></pre>\n\n<p>A special case that isn't an edge-value of a data-type (e.g. <code>0</code> for an unsigned integer) is an immediate code smell.</p>\n\n<pre><code> for i in range(1, len(array) - 1):\n</code></pre>\n\n<p>Skipping the end (and usually the start) of a sequence in an accumulation/optimisation problem is a smell. Avoid if possible.</p>\n\n<p>The problem can be modeled by a state-machine. On each iteration of the array elements, you begin in one of four states: starting, floor, climbing, descending. You begin in the starting state and once the first element is seen immediately transition to floor. The floor represents a state in which you're neither climbing nor descending. This occurs when you've reached some plateau and haven't climbed out of it. The climbing state is self-descriptive. You begin descending once you have passed a peak having made a climb. The longest seen peak can only end whilst in a descending state. You seemed in your solution to try and defer the recalculations of the longest seen peak until you've left the peak. This isn't necessary -- if you descend further downwards, you can always carry on increasing the value of the longest seen peak.</p>\n\n<p>Here is a descriptive algorithm:</p>\n\n<pre><code>import enum\n\nclass TrekState( enum.Enum ):\n Begin = 0\n Floor = 1\n Climb = 2\n Descend = 3\n\nclass Trek:\n def __init__( self ):\n self.state = TrekState.Begin\n self.counter = 0\n self.longest = 0\n\n def advance( self, i ):\n # update new state of our trek\n if self.state == TrekState.Begin:\n self.state = TrekState.Floor\n self.counter = 1\n else:\n previous = self.previous\n\n if self.state == TrekState.Floor:\n if previous &lt; i:\n self.state = TrekState.Climb\n self.counter += 1\n elif self.state == TrekState.Climb:\n if previous &lt; i:\n self.counter += 1\n elif previous &gt; i:\n self.state = TrekState.Descend\n self.counter += 1\n else: # previous == i\n self.state = TrekState.Floor\n self.counter = 1\n elif self.state == TrekState.Descend:\n if previous &lt; i:\n self.state = TrekState.Climb\n self.counter = 2\n elif previous &gt; i:\n self.counter += 1\n else: # previous == i\n self.state = TrekState.Floor\n self.counter = 1 \n\n # update longest and previous\n if self.state == TrekState.Descend:\n self.longest = max( self.counter, self.longest )\n self.previous = i \n\ndef updatedLongestPeak( seq ):\n trek = Trek()\n for i in seq:\n trek.advance( i ) \n return trek.longest\n</code></pre>\n\n<p>. A more concise version of the above, replacing object constructs with a more unstructured style, and some manual optimisations:</p>\n\n<pre><code>def verboseLongestPeak( seq ):\n state = counter = longest = 0\n\n for i in seq:\n counter += 1\n if state == 0:\n state = 1\n elif state == 1:\n if previous &lt; i:\n state = counter = 2\n elif state == 2:\n if previous &gt; i:\n state = 3\n elif previous == i:\n state = 1\n elif state == 3:\n if previous &lt; i:\n state = counter = 2\n elif previous == i:\n state = 1\n\n if state == 3:\n longest = max( counter, longest )\n previous = i\n\n return longest\n</code></pre>\n\n<p>. If you were to go for a solution of the latter's style, it would be essential to provide comments on the meaning of each state value.</p>\n\n<p>Neither solution is verified to be correct.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T17:11:38.757", "Id": "474572", "Score": "0", "body": "I tested your code and it seems to work on most test cases. You're right I had a bug - I fixed it though... So will update the code. States is a very clear way to represent the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T18:55:47.673", "Id": "474575", "Score": "0", "body": "Great answer! I did not want to answer for a fear of inadequateness. You absolutely proved that hunch right. Good insights on those subtler code smells, a lesson on state machines (very readable at that) *and* showcasing `enum.Enum`, by which I was recently profoundly confused (*what could that be good for?...*). Really enjoyed it and learned a lot, thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T22:59:16.537", "Id": "241787", "ParentId": "241745", "Score": "5" } }, { "body": "<p>Here's a fix for the code bug, and also removal of the special case handling:</p>\n\n<pre><code>def longestPeak(array):\n longest = peakStart = peakEnd = 0\n peakArrived = False\n for i in range(1, len(array) - 1):\n # Check for peak\n if array[i-1] &lt; array[i] and array[i] &gt; array[i+1]:\n peakArrived = True\n # Check for end\n if array[i] &lt;= array[i+1] and array[i] &lt; array[i-1]:\n peakEnd = i\n elif array[i+1] &lt; array[i] and i+2 == len(array):\n peakEnd = i+1\n # Check for longest\n if peakArrived and peakEnd &gt; peakStart:\n if peakEnd - peakStart + 1 &gt; longest:\n longest = peakEnd - peakStart + 1\n peakArrived = False\n # Check for start\n if array[i] &lt; array[i+1] and array[i] &lt;= array[i-1]:\n peakStart = i\n elif array[i] &gt; array[i-1] and i == 1:\n peakStart = 0\n\n return longest\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T08:04:13.533", "Id": "241863", "ParentId": "241745", "Score": "1" } }, { "body": "<p>I agree with the reviewers before me. Yet I feel like there has to be a more readable solution, one without so many cases. For the sake of simplicity of description, I assume the input is a list, but the code works for any iterable.</p>\n\n<h2>Compressing the input</h2>\n\n<p>All the information about the input list needed for this problem is contained in a list of the differences of the consecutive terms of the input. I.e. We only need the height differences. In fact, we only need the <em>sign</em> of these: <code>-, o, +</code>.</p>\n\n<p>Then a peak is a (non-zero) number of <code>+</code>'s followed by a (non-zero) number of <code>-</code>'s.</p>\n\n<p>Sublists starting with <code>+</code> will be called mountains. These are potential peaks. </p>\n\n<h2>The proposed algorithm</h2>\n\n<p>We can use an algorithm which is the repetition of the following two steps:</p>\n\n<ol>\n<li>Find a mountain. </li>\n<li>Climb the mountain, while recording its length.</li>\n</ol>\n\n<p>Finding a mountain amounts to consuming the input until we find a '+'.</p>\n\n<p>By climbing the mountain we mean that we'll move up as far as we can, then we'll move down as far as we can. I.e. consume as many <code>+</code> as possible, then consume as many <code>-</code> as possible.</p>\n\n<p>At the end of a climbing step if we've moved up at least once, and down at least once, then we've just climbed a peak of length\n<code>plusses + minuses + 1</code>. Otherwise we passed no peak.</p>\n\n<p>So we repeat these two steps while there are still signs left for us to consume.</p>\n\n<h2>Implementation</h2>\n\n<p>Consuming an iterable while a condition holds calls for <code>itertools.dropwhile</code>, but we need to record the number of items dropped, so we implement <code>drop_while</code>.</p>\n\n<pre><code>from itertools import chain, tee, islice\nfrom operator import sub\n\nfrom typing import Callable, Iterator, Iterable, TypeVar, Tuple\n\nT = TypeVar('T')\n\ndef drop_while(condition: Callable[[T], bool], iterator: Iterator[T]) -&gt; Tuple[Iterator[T], int]:\n \"\"\" A variation of dropwhile that\n consumes its input iterator while condition holds,\n then it returns the remainder of the iterator and the number of elements consumed\n \"\"\"\n num_dropped = 0\n\n for i in iterator:\n if condition(i):\n num_dropped += 1\n else:\n return chain([i], iterator), num_dropped\n\n return iterator, num_dropped\n</code></pre>\n\n<p>Once we have this function, everything falls into place easily.</p>\n\n<pre><code>def max_peak_length(nums: Iterable[int]) -&gt; int:\n \"\"\" Returns the maximal peak length from an iterable.\n\n max_peak_length([6,6,1,8,3,2,1])) == 5\n \"\"\"\n def peak_lengths(nums: Iterable[int]) -&gt; Iterator[int]:\n \"\"\" Returns the length of the peaks of an iterable as an iterator.\n\n First we calculate the differences between successive heights,\n then we go through them repeating the following two actions in order:\n - find the first mountain start, i.e. positive height difference\n - climb a mountain\n - count the number of consecutive '+' elements, then\n - count the number of consecutive '-' elements\n - we traversed a peak if both of these are positive\n The peaks' length is their sum +1\n \"\"\"\n\n # Iterator of height differences. Only their sign will be used.\n\n it1, it2 = tee(nums)\n it = map(sub, islice(it1, 1, None), it2)\n\n while True:\n # Skip to the first +.\n it, skipped_len = drop_while(lambda x: x &lt;= 0, it)\n\n # Skip through and count consecutive +'s then -'s.\n it, plusses = drop_while(lambda x: x &gt; 0, it)\n it, minuses = drop_while(lambda x: x &lt; 0, it)\n\n # If we traversed a true peak.\n if plusses &gt; 0 and minuses &gt; 0:\n yield plusses + minuses + 1\n\n else:\n # If the iterator is empty, stop.\n if skipped_len == 0 and plusses == 0 and minuses == 0:\n break\n\n yield 0\n\n # to avoid failing on inputs without mountains\n yield 0\n\n return max(peak_lengths(nums))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T22:04:38.420", "Id": "474710", "Score": "1", "body": "your solution fails for inputs of lists of length 0 or 1. it also exhibits some of the same problems as OP's (skipping first element and failing to work with generic iterables). `nums[1:]` may look harmless, but it produces a _copy_ of (almost) the entirety of the list. i usually consider micro-optimisations a waste of time in Python, but degrading performance from O(1) space to O(n) space for no gain is grossly inefficient. there is some good insight to be found here, but i don't like the solution as it currently stands." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T22:37:23.577", "Id": "474716", "Score": "1", "body": "@two_pc_turkey_breast_mince Thank you very much. If there are no mountains in the list, the original code fails, due to `max` getting an empty input. Thanks for the `nums[1:]` comment. The same is achievable using `tee` and `islice`. Code should be good to go. Works on iterables too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T23:04:50.913", "Id": "474720", "Score": "1", "body": "thanks, differential testing is always comforting :)!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T14:04:18.993", "Id": "241881", "ParentId": "241745", "Score": "1" } } ]
{ "AcceptedAnswerId": "241787", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T10:15:11.520", "Id": "241745", "Score": "6", "Tags": [ "python", "array" ], "Title": "Longest Peak without backtracking" }
241745
<p>I could like to read a file from a specified offset to a certain number of bytes in a file. I would pass the filename, the offset, the number of bytes as an argument. The constraint is should use only read, write, open, and close system call. Could anyone say whether the code would handle the test case of bytes > buf_size and partial reads? I am beginner in Linux. Thanks a ton.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;unistd.h&gt; #include&lt;sys/types.h&gt; #include&lt;error.h&gt; #include&lt;errno.h&gt; #include&lt;fcntl.h&gt; #define buf_size 512 int main(int argc, char *argv[]) { int bytes; int offset; int fd; int i = 0; int length = 0; ssize_t read_bytes; char *file; char buf[buf_size]; char *bufp; if (argc != 4) error(1, 0, "Too many or less than the number of arguments"); file = argv[1]; offset = atoi(argv[2]); bytes = atoi(argv[3]); fd = open(file, O_RDONLY); if (fd == -1) error(1, errno, "Error while opening the file\n"); read(fd, buf, offset); do { read_bytes = read(fd, buf, bytes); if (read_bytes == -1) error(1, errno, "Error while reading the file\n"); if (read_bytes == 0) return 0; for (i = 0; i &lt; bytes; i++) putchar(buf[i]); if (close(fd) == -1) error(1, 0, "Error while closing the file\n"); } while (read_bytes != 0); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T11:32:53.650", "Id": "474397", "Score": "0", "body": "@pacmaninbw Thanks. I tested it, it works fine. Will there be any suggestions to improve the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T11:39:56.327", "Id": "474400", "Score": "0", "body": "The line ``read(fd, buf, offset);`` will fail if offset is bigger than buf_size (corrupt the stack), you should do this read in chunks of buf_size. The rest should be all right on first look but from a performance point of view, buf_size should be 4K or a multiple thereof." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:06:36.697", "Id": "474411", "Score": "2", "body": "So you've verified the following \"Could anyone say whether the code would handle the test case of bytes > buf_size and partial reads\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:07:17.823", "Id": "474412", "Score": "1", "body": "Because it doesn't look like it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:22:04.223", "Id": "474413", "Score": "0", "body": "@Mast Yes, I misunderstood it. Thanks." } ]
[ { "body": "<h2>Bug</h2>\n\n<p>In this loop the file is closed, this means that on the next iteration of the loop the read will fail.</p>\n\n<pre><code> do {\n read_bytes = read(fd, buf, bytes);\n if (read_bytes == -1)\n error(1, errno, \"Error while reading the file\\n\");\n if (read_bytes == 0)\n return 0;\n for (i = 0; i &lt; bytes; i++)\n putchar(buf[i]);\n if (close(fd) == -1)\n error(1, 0, \"Error while closing the file\\n\");\n } while (read_bytes != 0);\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that applies here. The Single Responsibility Principle states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>There are at least 2 possible functions in <code>main()</code>.<br>\n - Parse the command line arguments<br>\n - Read the file using the offset and size </p>\n\n<h2>The Code is Not Portable</h2>\n\n<p>The header files <code>error.h</code> and <code>unistd.h</code> are not portable, and any code that derives from them such as the function <code>error()</code> do not port to systems such as windows. In the case of <code>error()</code> it would be better to report the error to <code>stderr</code> using <code>fprintf()</code> and since this is in <code>main()</code> <code>return 1;</code> or if <code>stdlib.h</code> is included <code>return EXIT_FAILURE;</code>. Note that while <code>error()</code> is not portable, <code>perror()</code> is portable since it is part of the C programming standard.</p>\n\n<h2>Understandable Error Messages</h2>\n\n<p>It is quite common to have a check on <code>argc</code>, but the error message provided usually provides the correct calling of the program as an example. The error message <code>Too many or less than the number of arguments</code> really doesn't tell the user enough, such as what arguments are missing, and what order they should be in.</p>\n\n<pre><code> if (argc != 4)\n {\n fprintf(stderr, \"Usage: readbytes Offset Bytes to read\");\n return EXIT_FAILURE; // since stdlib.h is included\n }\n</code></pre>\n\n<h2>More User Friendly</h2>\n\n<p>The program could be a little more user friendly if it was more flexible, rather than expecting Offset as <code>argv[2]</code> and Bytes to Read as <code>argv[3] Use -O for</code>offset<code>and -B for</code>Bytes to Read`.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T12:31:28.390", "Id": "241750", "ParentId": "241746", "Score": "2" } } ]
{ "AcceptedAnswerId": "241750", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T11:20:55.477", "Id": "241746", "Score": "-2", "Tags": [ "c", "linux", "unix" ], "Title": "The code reads the file from the specified offset to the specified number of bytes. How to handle errors of partial reads in reading a file" }
241746
<p>I was wondering about the Array built in methods in java 8. As there is no specific method other than <code>Arrays.binarySearch</code>. So for multidimensional array I wrote following method.</p> <pre><code>public int[] search(Integer[][] mat,int key) { int r=0,c=0; for(Integer[] a:mat) { if(Arrays.asList(a).contains(key)){ c = Arrays.asList(a).indexOf(key); break; } else r++; } return new int[]{r+1,c+1}; } </code></pre> <h1>checking</h1> <pre><code> Integer[][] mat = {{1,2,3,99},{4,5,6,57},{7,8,9,89},{10,11,12,13}}; int [] rc = new int[2]; rc = search(mat, 8); System.out.println(Arrays.toString(rc)); rc = search(mat, 9); System.out.println(Arrays.toString(rc)); rc = search(mat,10); System.out.println(Arrays.toString(rc)); rc = search(mat, 1); System.out.println(Arrays.toString(rc)); </code></pre> <h1>output</h1> <pre><code>[3, 2] [3, 3] [4, 1] [1, 1] </code></pre> <p>I would like a review of efficiency and general code quality. Also any improvements I can do to make it better.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:51:09.813", "Id": "474417", "Score": "0", "body": "Hello, have you tested your method ? It will always return a wrong result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:08:16.827", "Id": "474418", "Score": "0", "body": "consider the output" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:17:44.607", "Id": "474419", "Score": "0", "body": "Ok, but you are returning the couple of indexes in your array adding `1` to every index, so if you want to use the corresponding element you have to subtract 1 from both elements of the returned array before using them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:29:31.567", "Id": "474422", "Score": "0", "body": "see first eg key = 8 ans = [3,2] third row and 2 second column I'm not getting what are you saying" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:35:59.553", "Id": "474425", "Score": "0", "body": "`mat[3, 2]` = 12, while `mat[2, 1]` = 8, you have to subtract 1 from both the elements of the returning array of your method. The array indices always start from 0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:47:14.873", "Id": "474426", "Score": "0", "body": "I mean , every search will return a result based on a 0 start index array including `binarySearch`, if this is the behaviour you want you could specify it in your question." } ]
[ { "body": "<p>A few things to mention:</p>\n\n<p>As has been mentioned, you're using 1-based indexing instead of 0-based indexing. 0-based is much more intuitive, since most implementations, of indexing in most programming languages, use 0-based indexing.</p>\n\n<p>You're using the <code>Arrays.asList</code> twice for each iteration of the loop. This increases the inefficiency.</p>\n\n<p>Calling <code>indexOf</code> inside the loop is basically creating another loop and doesn't gain anything a <code>for</code> loop wouldn't give you.</p>\n\n<p>I think the name of your method could be better. <code>search</code> indicates all you want is the value. However you're returning the indexes. Therefore <code>indexesOf</code> might be more appropriate, and more in fitting with similar methods in other collections.</p>\n\n<p>Your method is hard coded for <code>int</code>. This isn't very extensible. A generic version would probably be more fitting.</p>\n\n<p>You're returning an <code>int[]</code>. This doesn't really tell anyone what this is supposed to represent. I would suggest a class(<code>Indexes</code>) to hold the indexes would allow you to represent them with a name that will immediately let the user know what it represents.</p>\n\n<p>You haven't made any provision to handle failed searches.</p>\n\n<p>It looks to me that the 2D array is basically a matrix. Therefore I would suggest labeling the indexes as such(row,column).</p>\n\n<p>The <code>Indexes</code> class would look like this:</p>\n\n<pre><code>public class Indexes {\n int row = 0;\n int col = 0;\n\n public Indexes(int row, int col) {\n this.row = row;\n this.col = col;\n }\n\n public Indexes() {\n }\n\n public int getRow() {\n return row;\n }\n\n public void setRow(int row) {\n this.row = row;\n }\n\n public int getCol() {\n return col;\n }\n\n public void setCol(int col) {\n this.col = col;\n }\n @Override\n public String toString(){\n return String.format(\"[%d, %d]\",row,col);\n }\n}\n</code></pre>\n\n<p>A generified version with the points I mentioned could look something like this:</p>\n\n<pre><code>public static&lt;T&gt; Indexes indexesOf(T[][] arr, T value){\n for(int row = 0; row &lt; arr.length; ++row){\n for(int col = 0; col &lt; arr[row].length; ++col){\n if(arr[row][col].equals(value)){\n return new Indexes(row,col);\n }\n }\n }\n return new Indexes(-1,-1);\n}\n</code></pre>\n\n<h2>EDIT Alternative code based on OP's comments</h2>\n\n<pre><code>static final int DEFAULT_RETURN_VALUE = -1;\npublic static&lt;T&gt; Indexes indexesOf(T[][] arr, T value){\n for(int row = 0; row &lt; arr.length; ++row){\n int col = indexOf(arr[row],value);\n if(col &gt; DEFAULT_RETURN_VALUE){\n return new Indexes(row,col);\n }\n }\n return new Indexes(DEFAULT_RETURN_VALUE,DEFAULT_RETURN_VALUE);\n}\npublic static&lt;T&gt; int indexOf(T[] arr, T value){\n for(int i = 0; i &lt; arr.length; ++i){\n if(arr[i].equals(value)){\n return i;\n }\n }\n return DEFAULT_RETURN_VALUE;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T19:51:42.040", "Id": "474453", "Score": "0", "body": "I think `Location` might be a better name for `Indexes`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T20:06:43.713", "Id": "474456", "Score": "0", "body": "There are probably quite a few different names that could be applied. I think the point is having a name that indicates what values it holds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T06:59:54.520", "Id": "474490", "Score": "0", "body": "I got your point about repeated use of `asList` and zero based indexing . any other suggestions. I used asList because I don't wanted to explicit searching code that you mentioned above" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T15:29:45.077", "Id": "474560", "Score": "0", "body": "@AashishPawar - As my answer explains indexOf is hiding an internal loop. The effect is exactly the same as my code. The performance with just the loop is actually better, since it doesn't copy the arrays into a list. If you want the same simplicity, extract the inner into a function and call it from the outer loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T06:07:12.620", "Id": "474601", "Score": "0", "body": "Sorry, but saying `Arrays.asList()` was *very* inefficient is simply wrong. There will be a new `Arrays$ArrayList` inner class created for each call, but this is just a simple wrapper around the array. Yes, you could spare a few CPU cycles by reusing the result, but there is only constant (O(1)) runtime for this call. It is especially *not* creating a copy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T18:14:35.543", "Id": "474688", "Score": "0", "body": "Either way it still is introducing inefficiency to the code. On benchmarks I've seen it could be as much as 10-20%." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T18:54:06.500", "Id": "241772", "ParentId": "241752", "Score": "3" } } ]
{ "AcceptedAnswerId": "241772", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:07:26.523", "Id": "241752", "Score": "2", "Tags": [ "java", "array", "search" ], "Title": "Searching in Multidimensional Array" }
241752
<p>In a Python Bottle server using SQLite, I noticed that doing a DB commit after each INSERT <strong>is not efficient: it <a href="https://www.sqlite.org/faq.html#q19" rel="nofollow noreferrer">can use 100ms</a> after each client request</strong>. Thus I wanted to improve this in <a href="https://stackoverflow.com/questions/61600356/how-to-commit-db-changes-in-a-flask-or-bottle-app-efficiently">How to commit DB changes in a Flask or Bottle app efficiently? </a>. </p> <p>I finally came to this solution, which is more or less a "debounce"-like method: <strong>if multiple SQL <code>INSERT</code> happen during a 10-second timeframe, group all of them in a single DB commit</strong>.</p> <p>What do you think of the following code? <strong>Is it safe to do like this?</strong></p> <p>(Note: I know that the use of a <code>global</code> variable should be avoided, and replaced by a <code>class</code> / object with attributes, etc. I'll do this, but this part is not really on topic here).</p> <pre><code>import bottle, sqlite3, random, threading, time @bottle.route('/') def index(): global committhread c = db.cursor() c.execute('INSERT INTO test VALUES (?)', (random.randint(0, 10000),)) c.close() if not committhread: print('Calling commit()...') committhread = threading.Thread(target=commit) committhread.start() else: print('A commit is already planned.') return 'hello' def commit(): global committhread print("We'll commit in 10 seconds.") time.sleep(10) # I hope this doesn't block/waste CPU here? db.commit() print('Committed.') committhread = None db = sqlite3.connect('test.db', check_same_thread=False) db.execute("CREATE TABLE IF NOT EXISTS test (a int)") committhread = None bottle.run(port=80) </code></pre> <p>If you run this code, opening <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> once will plan a commit 10 seconds later. If you reopen <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> multiple times, less than 10 seconds later, you will see that <strong>it will be grouped in the same commit,</strong> as desired.</p> <hr> <p>Note: this method is not <em>"Do it every 10 seconds"</em> (this would be a classic timer), but rather: <em>"Do it 10 seconds later; if another INSERT comes in the meantime, do all of them together"</em>. If there is no <code>INSERT</code> during 60 minutes, with my method it won't do anything at all. With a timer it would still periodically call a function (and notice there's nothing to do).</p> <p>Worth reading too: <a href="https://stackoverflow.com/questions/52142645/how-to-improve-sqlite-insert-performance-in-python-3-6">How to improve SQLite insert performance in Python 3.6? </a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:58:17.280", "Id": "474427", "Score": "0", "body": "Your link says commits may be slow because they go to disk. Is your disk really the bottleneck in your program? Disks are a lot slower than CPUs, but I imagine for most servers they can keep up with connections especially if you are not writing a lot of data" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:06:07.480", "Id": "474428", "Score": "0", "body": "It's probably both CPU and disk. Since losing 100ms after each request is not an option (I spent days optimizing the requests/page generation to be fast, less than 30ms, so I don't want just a logging in the DB to ruin all these efforts :)), I'm looking for a solution to do a commit only every few INSERTs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:05:52.137", "Id": "474435", "Score": "0", "body": "Have you measured it taking 100ms? Even in abysmal conditions, I would expect sqlite to rarely hit 5ms using a disk from the last 5 ish year (doing small inserts)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:16:33.940", "Id": "474436", "Score": "0", "body": "@sudorm-rfslash I analyzed timing for many lines of my code, and I measured numbers like 79ms 60ms 84ms for the `db.commit()` part (low-end server) so the order of magnitude is 100ms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:19:10.500", "Id": "474437", "Score": "0", "body": "That's surprising to me but I guess if you measured it then I'm wrong" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:29:26.210", "Id": "474438", "Score": "0", "body": "@sudorm-rfslash It is somehow consistent with https://www.sqlite.org/faq.html#q19: *Actually, SQLite will easily do 50,000 or more INSERT statements per second on an average desktop computer. But it will only do a few dozen transactions per second.* I'm maybe in a worse case because of an old disk and slow CPU." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T04:36:26.277", "Id": "474480", "Score": "0", "body": "I would first ask myself why I am wrapping single query in a transaction. Single query Is wrapped in an implocit transaction And there Is no benefit from starting an explicit one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T07:24:48.790", "Id": "474491", "Score": "0", "body": "@slepic are you speaking about the `c = db.cursor()`? IIRC this does not create an overhead (or if it does it's less than 0.1ms)" } ]
[ { "body": "<blockquote>\n <p>What do you think of the following code? Is it safe to do like this?</p>\n</blockquote>\n\n<p>In my opinion, it is not. So many things could go wrong.</p>\n\n<p>One example: in this code there is no <strong>exception handling</strong>. If your program crashes for any reason, your routine may not be triggered. Fix: add an exception handler that does some cleanup, <strong>commits</strong> and closes the DB. Or better yet, just do that commit in the <code>finally</code> block.</p>\n\n<p>By the way the <a href=\"https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.close\" rel=\"nofollow noreferrer\">doc</a> says this about the <code>close</code> function:</p>\n\n<blockquote>\n <p>This closes the database connection. Note that this does not\n automatically call commit(). If you just close your database\n connection without calling commit() first, your changes will be lost!</p>\n</blockquote>\n\n<p>So it is a good idea to commit systematically.</p>\n\n<blockquote>\n <p>time.sleep(10) # I hope this doesn't block/waste CPU here?</p>\n</blockquote>\n\n<p><code>time.sleep</code> blocks the calling thread. It is useless anyway because what you want here is a <strong>timer</strong>, not a thread. You can have a timer routine that runs every <em>n</em> seconds to perform a given task. But you should still have a commit in the <code>finally</code> block, so that all pending changes are written to the DB when the program ends, even after an exception.</p>\n\n<p>Now to discuss the functionality more in depth:<br />\nYou say:</p>\n\n<blockquote>\n <p>In a Python Bottle server using SQLite, I noticed that doing a DB\n commit after each INSERT is not efficient: it can use 100ms after each\n client request.</p>\n</blockquote>\n\n<p>That may not be 'efficient' but if I have to choose between slow and safe there is no hesitation. Have you actually <strong>measured</strong> how long it takes on your own environment ?</p>\n\n<p>On Stack Overflow <a href=\"https://stackoverflow.com/q/61600356/6843158\">you wrote</a>:</p>\n\n<blockquote>\n <p>I optimized my server to serve pages very fast (10ms), and it would be\n a shame to lose 100ms because of DB commit.</p>\n</blockquote>\n\n<p>While I applaud your obsession with performance, does 100 ms really make a difference to your users ? It normally takes more than 100 ms to load a page or even refresh a portion of it using Ajax or a websocket. The latency resides in the network transport. I don't know how your application is structured but my priority would be to deliver as little traffic as possible to the users. Websocket + client-side JS should do.</p>\n\n<p>Perhaps using a <strong>different storage</strong> medium could improve IO performance. If you are not using a SSD drive, maybe you could consider it or at least test it.</p>\n\n<p>Before writing code like this I would really try to exhaust all possibilities, but it is better (more reliable) to let SQLite handle things using the options that already exist. What have you tried so far ?</p>\n\n<p>Would this be acceptable to you ?</p>\n\n<pre><code>PRAGMA schema.synchronous = OFF \n</code></pre>\n\n<blockquote>\n <p>With synchronous OFF (0), SQLite continues without syncing as soon as\n it has handed data off to the operating system. If the application\n running SQLite crashes, the data will be safe, but the database might\n become corrupted if the operating system crashes or the computer loses\n power before that data has been written to the disk surface. On the\n other hand, commits can be orders of magnitude faster with synchronous\n OFF.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://www.sqlite.org/pragma.html#pragma_synchronous\" rel=\"nofollow noreferrer\">PRAGMA Statements</a></p>\n\n<p>There is a risk of corruption in case of power loss but this is no worse than what you are doing. If on the other hand data integrity is more important you should stick to a full commit after every operation.</p>\n\n<p>You should also have a look at <a href=\"https://www.sqlite.org/wal.html\" rel=\"nofollow noreferrer\">Write-Ahead Logging</a>. This may interest you if there are concurrent writes to your database. Otherwise opening the DB in EXCLUSIVE mode may bring some benefits (see the PRAGMA page for details).</p>\n\n<p>More detailed discussions:</p>\n\n<ul>\n<li><a href=\"https://www.sqlite.org/atomiccommit.html\" rel=\"nofollow noreferrer\">Atomic Commit In SQLite</a> </li>\n<li><a href=\"https://www.sqlite.org/fasterthanfs.html\" rel=\"nofollow noreferrer\">35% Faster Than The Filesystem</a> </li>\n</ul>\n\n<hr>\n\n<p>Last but not least: <strong>transactions</strong>. SQLite starts an implicit transaction automatically every time you run a SQL statement and commits it after execution. You could initiate the BEGIN &amp; COMMIT TRANSACTION statements yourself. So if you have a number or related writes, regroup them under one single transaction. Thus you do one commit for the whole transaction instead of one transaction per statement (there is more consistency too: in case an error occurs in the middle of the process you won't be left with orphaned records).</p>\n\n<p>There are quite many things you can try until you find the mix that is right for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T18:24:53.087", "Id": "474445", "Score": "0", "body": "Thank you very much for your detailed answer. You're right: there are many other things to try before doing my `do it in 10 seconds, and group all further INSERT in the same commit` method. I just tried your PRAGMA suggestion, and this `c.execute('PRAGMA journal_mode = OFF')` gives a massive improvement. `c.execute('PRAGMA synchronous = OFF'); ` makes it asynchronous so when we measure it's 0 ;) So it's probably done \"when the current process has some spare time\" and it's perfect for my needs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T18:31:13.277", "Id": "474446", "Score": "0", "body": "A little remark about *time.sleep blocks the calling thread. It is useless anyway because what you want here is a timer, not a thread. You can have a timer routine that runs every n seconds to perform a given task*. My method is slightly different though: it's not \"do it every 10 seconds\" (this would be a classic timer), but rather: \"do it 10 sec later; if another INSERT comes in the meantime, do all of them together\". If there is no INSERT during 60 minutes, with my method it won't do anything at all. With a timer it would still periodically call a function (and notice there's nothing to do)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T18:55:54.260", "Id": "474448", "Score": "0", "body": "Last thing: with `synchronous = OFF`, will the OS (Linux) write to disk as soon it has time to do it, or are there cases in which the OS will wait several minutes before doing it?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:00:24.180", "Id": "241765", "ParentId": "241753", "Score": "3" } } ]
{ "AcceptedAnswerId": "241765", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:17:35.743", "Id": "241753", "Score": "1", "Tags": [ "python", "multithreading", "database", "sqlite", "bottle" ], "Title": "SQLite and Python: commit once every 10 seconds maximum, and not after every client request" }
241753
<p>Is there a more elegant way to ensure that <code>colnames(output)</code> of a <code>output</code> R dataframe retains the original column variable names in the referenced sample dataset <code>data</code>? So that I can eliminate the 2 <code>gsub()</code> lines of code, which rename my column names back to my original variable names. My R code, which can be run, is as follows</p> <pre><code>library(mvtnorm) library(tidyverse) muvec = apply(data, 2, mean) #data is passed as R dataframe sigma = cov(data) df = 10 n = 10 output &lt;- as.data.frame( lapply(1:n, function(x) rep(muvec, each=10) + rmvt(10, sigma=sigma, df=df))) %&gt;% select (sort(names(.))) #looped function output assigns arbitrary variable names X1 and X2, instead of original variable names apple and pear colnames(output) = gsub("X1", "apple", colnames(output)) colnames(output) = gsub("X2", "pear", colnames(output)) print(output) </code></pre> <p><code>data</code> as follows</p> <pre><code>+-------+-------+ | apple | pear | +-------+-------+ | 0.18 | 0.05 | | 0.22 | 0.03 | | 0.21 | 0.03 | | 0.11 | 0 | | 0.15 | 0.03 | | 0.13 | 0.01 | | 0.03 | 0.01 | | 0 | 0 | | -0.06 | -0.01 | | -0.09 | -0.02 | +-------+-------+ </code></pre>
[]
[ { "body": "<p>The most efficient way that I can think of is creating a function with <code>rmvt</code> which takes an additional argument to decide whether column names should be assigned based on the input (<em>i.e.</em> <code>sigma</code>) or not. If <code>TRUE</code>, before returning the results of <code>rmvt</code> function, it assigns the original names. See below (I used <code>airquality</code> dataset to make a reproducible example);</p>\n\n<pre class=\"lang-r prettyprint-override\"><code>library(mvtnorm)\nlibrary(dplyr)\n\ndat &lt;- na.omit(datasets::airquality)[1:2,1:2]\n\nmuvec = apply(dat, 2, mean) #data is passed as R dataframe\nsigma = cov(dat)\ndf = 10\nn = 2\n\nrmvt.names &lt;- function(n, sigma = diag(2), df = 1, delta = rep(0, nrow(sigma)),\n type = c(\"shifted\", \"Kshirsagar\"), names = FALSE){\n out &lt;- rmvt(n, sigma, df, delta, type)\n if (names) { colnames(out) &lt;- colnames(sigma) }\n return(out)\n}\n\nlapply(1:n, function(x) \n rep(muvec, each=10) + rmvt.names(10, sigma=sigma, df=df, names = T)) %&gt;%\n as.data.frame() %&gt;% \n select (sort(names(.)))\n\n#&gt; Ozone Ozone.1 Solar.R Solar.R.1\n#&gt; 1 37.47822 45.06226 139.286427 248.496571\n#&gt; 2 40.59224 42.78024 184.128243 215.635423\n#&gt; 3 33.03107 35.89953 75.247397 116.553211\n#&gt; 4 28.07207 28.48342 3.837864 9.761237\n#&gt; 5 38.15097 39.46869 148.974039 167.949166\n#&gt; 6 44.04143 42.68460 233.796536 214.258203\n#&gt; 7 36.54224 40.53313 125.808217 183.277053\n#&gt; 8 37.37606 38.77892 137.815314 158.016502\n#&gt; 9 43.99939 37.11836 233.191196 134.104332\n#&gt; 10 37.63792 32.28113 141.586044 64.448253\n</code></pre>\n\n<p><sup>Created on 2020-05-06 by the <a href=\"https://reprex.tidyverse.org\" rel=\"nofollow noreferrer\">reprex package</a> (v0.3.0)</sup></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T19:12:44.570", "Id": "241831", "ParentId": "241754", "Score": "2" } } ]
{ "AcceptedAnswerId": "241831", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T14:55:52.123", "Id": "241754", "Score": "3", "Tags": [ "r", "simulation" ], "Title": "Ensure that column names in output retain original variable names, instead of using arbitrary X1, X2, etc" }
241754
<p>I see in old code two function that uses same switch like this:</p> <pre><code>private string GetPath(Charts chartType) { switch (chartType) { case Charts.Revenue: return "/../.."; case Charts.Risk: return "/../some"; //UPDATE case Charts.Sales return "/123/xxx" default: throw new NotImplementedException($"{chartType} is not implemented yet!"); } } public IStrategy GetStrategy(RequestDto request) { if (!Enum.TryParse&lt;Charts&gt;(request.GraphType, true, out var chartType)) { throw new ArgumentException($"Unknown value for {nameof(RequestDto.GraphType)}", nameof(RequestDto.GraphType)); } var path = GetPath(chartType); switch (chartType) { case Charts.Revenue: case Charts.Risk: return new BarChartStrategy(path, _component1, _component2); //UPDATE case Charts.Sales return new PieChartStrategy(path, _component1, _component2); default: throw new NotImplementedException($"Charts.{chartType} is not implemented yet!"); } } </code></pre> <p>Is there a more elegant form, more OOP form for these two switch? Thanks</p> <p>UPDATE: I clirify my scenario. I can have multiple stretegy for chart, like BarChartStrategy, CircleChartStrategy, TreeChartStrategy. Revenue and Risk uses BarChartStrategy, but others can use different strategies.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:31:33.330", "Id": "474423", "Score": "4", "body": "Welcome to Code Review. Please always post complete and real code, or else we can not make a proper review. Please do not update your original code when an answer is submitted - because that will invalidate the answer(s). You're welcome to make an update below your original code - starting with **UPDATE** that clearly signals that it's new stuff - thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T19:02:56.127", "Id": "474449", "Score": "2", "body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look a the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T15:08:53.147", "Id": "474559", "Score": "0", "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)." } ]
[ { "body": "<p>If <code>GetPath</code> is used in multiple places, then I believe it would better to leave it as is, otherwise, you'll have to change every method that reference it. If this is the only method that is used in then combine it like this : </p>\n\n<pre><code>public IStrategy GetStrategy(RequestDto request)\n{\n if (!Enum.TryParse&lt;Charts&gt;(request.GraphType, true, out var chartType))\n {\n throw new ArgumentException($\"Unknown value for {nameof(RequestDto.GraphType)}\", nameof(RequestDto.GraphType));\n }\n\n switch (chartType)\n {\n case Charts.Revenue:\n return new BarChartStrategy(\"/../..\", _component1, _component2);\n case Charts.Risk:\n return new BarChartStrategy(\"/../some\", _component1, _component2);\n default:\n throw new NotImplementedException($\"Charts.{chartType} is not implemented yet!\");\n }\n}\n</code></pre>\n\n<p>This way you can manage both the path and also the <code>BarChartStrategy</code> in the same place. \nand since the path is stored in <code>BarChartStrategy</code> property, you can always retrieve it from any active instance. Which eliminate the need of <code>GetPath</code> in the first place. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:43:45.623", "Id": "241764", "ParentId": "241755", "Score": "2" } }, { "body": "<p>Good question, and it has a classic OOP answer:</p>\n\n<pre><code>public IStrategy GetStrategy(RequestDto request) =&gt; \n ChartType.TryParse(request.GraphType, out var chartType) \n ? chartType.Strategy(_component1, _component2)\n : throw new ArgumentException();\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>public class ChartType\n{\n static readonly Dictionary&lt;string, ChartType&gt; All = \n new Dictionary&lt;string, ChartType&gt;(StringComparer.OrdinalIgnoreCase);\n public static bool TryParse(string text, out ChartType type) =&gt;\n All.TryGetValue(text, out type);\n\n public static readonly ChartType Revenue = new ChartType(cc =&gt; new BarChartStrategy(\"/../..\", cc));\n public static readonly ChartType Risk = new ChartType(cc =&gt; new BarChartStrategy(\"/../some\", cc));\n public static readonly ChartType Sales = new ChartType(cc =&gt; new PieChartStrategy(\"/123/xxx\", cc));\n\n ChartType(Func&lt;IComponent[], IStrategy&gt; factory, [CallerMemberName] string name = null)\n {\n All[name] = this;\n Factory = factory;\n }\n\n Func&lt;IComponent[], IStrategy&gt; Factory { get; }\n public IStrategy Strategy(params IComponent[] components) =&gt;\n Factory(components);\n}\n</code></pre>\n\n<p>Not so many people could read OOP code these days though. It looks like an overkill for the snippet you have, but it scales up very well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T06:43:24.990", "Id": "474487", "Score": "0", "body": "\"Not so many people could read OOP code these days though.\" In C#?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T06:55:00.927", "Id": "474488", "Score": "1", "body": "OOP in C# is a pretty rarely thing. Some other languages could be a way more efficient, but high-condensity FP usually wins when language and qualification allows. Generally speaking, there is no high demand in precise modeling which only OOP could provide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T07:58:00.410", "Id": "474494", "Score": "0", "body": "Hi @DmitryNogin, thx very much. This is a real clean Factory pattern in C#. One question. Cai I use Lazy<ChartType> to not instantiate all charts class but only when it is used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T14:36:11.750", "Id": "474554", "Score": "0", "body": "@GlaucoCucchiar `ChartType` is just a factory (a named one) as well as `Lazy<T>` given what I see here. You probably won't win much by using two levels of nested factories. Message [me](https://www.linkedin.com/in/dnogin/) in case you are interested in sharing some real code which could be different :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T04:11:55.493", "Id": "241796", "ParentId": "241755", "Score": "2" } } ]
{ "AcceptedAnswerId": "241796", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:03:47.917", "Id": "241755", "Score": "0", "Tags": [ "c#", "object-oriented" ], "Title": "Double switch C#" }
241755
<p>I recieve this array in my controller:</p> <pre><code>"sort" =&gt; array:6 [ 0 =&gt; array:2 [ "id" =&gt; "153" "sort" =&gt; "2" ] 1 =&gt; array:2 [ "id" =&gt; "152" "sort" =&gt; "1" ] 2 =&gt; array:2 [ "id" =&gt; "154" "sort" =&gt; "3" ] 3 =&gt; array:2 [ "id" =&gt; "166" "sort" =&gt; "4" ] 4 =&gt; array:2 [ "id" =&gt; "155" "sort" =&gt; "5" ] 5 =&gt; array:2 [ "id" =&gt; "156" "sort" =&gt; "6" ] ] </code></pre> <p>I have made this and it works:</p> <pre><code>foreach ($request['sort'] as $model) { Model::where('id', $model['id'])-&gt;update(['sort' =&gt; $model['sort']]); } </code></pre> <p>There is probably a better way to do this.... This will make so many requests on DB how many items there are inside that array.... Anyone has better ideas? Maybe there is a way to make that update all at once so there is only one request on DB?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T04:18:36.953", "Id": "474479", "Score": "0", "body": "You can write custom SQL query to handle them all at once, but such query would be really ugly. Updating multiple rows with one query Is only simple if all rows take the same update values (or rules to compute them based on previous values, ie increment operation). If Its not slowing requests Down significantly, I wouldnt bother at this point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T05:15:48.467", "Id": "474481", "Score": "0", "body": "True.. I'll leave this as it is." } ]
[ { "body": "<blockquote>\n <p><em>\"Premature optimization is the root of all evil.\"</em></p>\n</blockquote>\n\n<p>As long as this code works and causes no problem, nothing should be really done. Trying to \"improve\" it, most likely you will cause a severe harm to readability, maintainability and - ironically - performance. </p>\n\n<p>The only thing could be suggested out of the blue is to wrap the loop in a <em>transaction</em>. It will be a sensible move by itself, and and also could improve the speed in case of some certain settings of the database engine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:49:00.870", "Id": "474443", "Score": "0", "body": "So you would say: There is no some better way than this... leave it as it is." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T16:28:42.767", "Id": "241762", "ParentId": "241757", "Score": "4" } } ]
{ "AcceptedAnswerId": "241762", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T15:40:41.550", "Id": "241757", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "What would be the best way to update data from associative array?" }
241757
<p>This is an assignment known as a Cachelab from CMU 15-213. The full writeup for the lab can be found <a href="http://csapp.cs.cmu.edu/3e/cachelab.pdf" rel="nofollow noreferrer">here</a>, the handout I'm working against - <a href="http://csapp.cs.cmu.edu/3e/cachelab-handout.tar" rel="nofollow noreferrer">here</a>. All in all, the task is to emulate a cache, given the amount of block bits, set bits and associativity, run it against a sample valgrind-generated input, output the statistics on hits, misses and evictions. For evictions, LRU should be used. We don't care about actual memory contents in this lab, so we're not doing anything with them. We also don't care about instruction cache, so all the operations with it are ignored.</p> <p>The code functions correctly. As it's my first C program longer than 20 lines, I'm wondering how bad it is in terms of splitting responsibilities between functions, making code easy to read and understand, making the program flow easy enough to follow, following general practices of writing in C, subtle bugs, usage of <code>calloc</code>, <code>free</code>, naming, etc. The trick is that as I don't know much of good coding practices in C, I don't really know what to ask specifically. Basically, I'm asking if you'd do anything different, and if so, what, how and why?</p> <p>Code (<code>csim.c</code>):</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; #include &lt;stddef.h&gt; #include &lt;getopt.h&gt; #include &lt;limits.h&gt; // #include "cachelab.h" extern int errno; typedef enum { LOAD, STORE, MODIFY, INSTRUCTION, UNKNOWN, END, // special value to indicate that we reached the end of tracefile } access_mode_t; enum lookup_result { HIT = 1, MISS = 2, EVICTION = 4, }; typedef struct options_t { bool help; bool verbose; unsigned long s; unsigned long E; unsigned long b; char *tracefile; } options_t; typedef struct cache_stats_t { int misses; int hits; int evictions; } cache_stats_t; typedef struct operation_t { unsigned long address; access_mode_t access_mode; unsigned long size; } operation_t; access_mode_t mode_char_to_access_mode(char mode) { switch (mode) { case 'M': return MODIFY; case 'L': return LOAD; case 'S': return STORE; case 'I': return INSTRUCTION; default: return UNKNOWN; } } char access_mode_to_mode_char(access_mode_t mode) { switch (mode) { case MODIFY: return 'M'; case LOAD: return 'L'; case STORE: return 'S'; case INSTRUCTION: return 'I'; default: return 0; } } void parse_options(int argc, char *argv[], options_t *options) { int ch; while ((ch = getopt(argc, argv, "hvs:E:b:t:")) != -1) { switch (ch) { case 'h': options-&gt;help = true; break; case 'v': options-&gt;verbose = true; break; // no error handling in cases below case 's': options-&gt;s = strtoul(optarg, NULL, 16); break; case 'E': options-&gt;E = strtoul(optarg, NULL, 16); break; case 'b': options-&gt;b = strtoul(optarg, NULL, 16); break; case 't': options-&gt;tracefile = optarg; break; default: printf("Invalid option!\n"); exit(1); } } }; void usage() { printf("Usage: csim [-hv] -s &lt;num&gt; -E &lt;num&gt; -b &lt;num&gt; -t &lt;file&gt;\n"); printf("Options:\n"); printf(" -h Print this help message.\n"); printf(" -v Optional verbose flag.\n"); printf(" -s &lt;num&gt; Number of set index bits.\n"); printf(" -E &lt;num&gt; Number of lines per set.\n"); printf(" -b &lt;num&gt; Number of block offset bits.\n"); printf(" -t &lt;file&gt; Trace file.\n"); printf("\n"); printf("Example:\n"); printf(" linux&gt; csim -s 4 -E 1 -b 4 -t traces/yi.trace\n"); exit(1); } void file_open_r(FILE **f, char* filename) { *f = fopen(filename, "r"); if (errno != 0) { perror(""); exit(errno); } } void file_close(FILE *f) { fclose(f); } void load_next_operation(FILE *f, operation_t *operation) { char mode; unsigned long address; unsigned long size; // fixme: no error handling here if (fscanf(f, " %c %lx,%lx\n", &amp;mode, &amp;address, &amp;size) == EOF) { operation-&gt;access_mode = END; return; }; access_mode_t access_mode = mode_char_to_access_mode(mode); operation-&gt;address = address; operation-&gt;access_mode = access_mode; operation-&gt;size = size; } typedef struct cache_line_t { bool valid; unsigned long tag; unsigned long last_accessed; } cache_line_t; // returns either a cache_line_t* if value is found in cache, or NULL if it's a cache miss cache_line_t* cache_hit_line(cache_line_t *set, unsigned long associativity, unsigned long tag) { for (unsigned long i = 0; i &lt; associativity; i++) { if ((set[i].tag == tag) &amp;&amp; set[i].valid) return &amp;set[i]; } return NULL; } // returns a cache_line_t* pointing to line to be evicted cache_line_t *cache_get_eviction_candidate(cache_line_t *set, unsigned long associativity) { cache_line_t *result = &amp;set[0]; unsigned long least_last_accessed = ULONG_MAX; for (unsigned long i = 0; i &lt; associativity; i++) { if (set[i].last_accessed &lt; least_last_accessed) { least_last_accessed = set[i].last_accessed; result = &amp;set[i]; } } return result; } // returns either a pointer to a valid line, or a NULL if an eviction has to happen cache_line_t *cache_get_write_candidate(cache_line_t *set, unsigned long associativity) { for (unsigned long i = 0; i &lt; associativity; i++) { if (!set[i].valid) { return &amp;set[i]; } } return NULL; } void cache_write_line(cache_line_t *line, unsigned long tag, unsigned long epoch) { line-&gt;last_accessed = epoch; line-&gt;valid = true; line-&gt;tag = tag; } int cache_lookup(cache_line_t *set, unsigned long associativity, unsigned long tag, unsigned long epoch) { int result = 0; cache_line_t *target_line; if ((target_line = cache_hit_line(set, associativity, tag)) != NULL) { result |= HIT; cache_write_line(target_line, tag, epoch); // refresh the epoch for correct LRU functioning } else { result |= MISS; if ((target_line = cache_get_write_candidate(set, associativity)) == NULL) { target_line = cache_get_eviction_candidate(set, associativity); result |= EVICTION; } cache_write_line(target_line, tag, epoch); } return result; } void verbose_output_operation(operation_t *operation) { printf("%c %lx,%lx", access_mode_to_mode_char(operation-&gt;access_mode), operation-&gt;address, operation-&gt;size); } void verbose_output_lookup_result(int lookup_result) { if ((lookup_result &amp; MISS) == MISS) printf(" miss"); if ((lookup_result &amp; EVICTION) == EVICTION) printf(" eviction"); if ((lookup_result &amp; HIT) == HIT) printf(" hit"); } void verbose_output_end() { printf("\n"); } void store_lookup_result_stats(cache_stats_t *cache_stats, int lookup_result) { if ((lookup_result &amp; MISS) == MISS) cache_stats-&gt;misses++; if ((lookup_result &amp; EVICTION) == EVICTION) cache_stats-&gt;evictions++; if ((lookup_result &amp; HIT) == HIT) cache_stats-&gt;hits++; } void calculate_cache_stats(cache_stats_t *cache_stats, char *tracefile, unsigned long set_bits, unsigned long associativity, unsigned long block_bits, bool verbose) { unsigned long set_count = 1u &lt;&lt; set_bits; cache_line_t cache[set_count][associativity]; for (unsigned long i = 0; i &lt; set_count; i++) for (unsigned long j = 0; j &lt; associativity; j++) cache[i][j] = (cache_line_t) {0, 0}; unsigned long block_mask = (1u &lt;&lt; block_bits) - 1; unsigned long set_mask = ((1u &lt;&lt; set_bits &lt;&lt; block_bits) - 1) ^block_mask; unsigned long tag_mask = ~0u ^block_mask ^set_mask; unsigned long epoch = 0; operation_t *operation = malloc(sizeof(operation_t)); unsigned long operation_set; unsigned long operation_tag; FILE *fp; file_open_r(&amp;fp, tracefile); load_next_operation(fp, operation); while (operation-&gt;access_mode != END) { operation_set = (operation-&gt;address &amp; set_mask) &gt;&gt; block_bits; operation_tag = (operation-&gt;address &amp; tag_mask) &gt;&gt; set_bits &gt;&gt; block_bits; // workhorse cache_line_t *set = cache[operation_set]; int last_lookup_result; if (verbose) verbose_output_operation(operation); switch (operation-&gt;access_mode) { case LOAD: case STORE: last_lookup_result = cache_lookup(set, associativity, operation_tag, epoch); if (verbose) verbose_output_lookup_result(last_lookup_result); store_lookup_result_stats(cache_stats, last_lookup_result); break; case MODIFY: // modify is essentially load+store for (int i = 0; i &lt; 2; i++) { last_lookup_result = cache_lookup(set, associativity, operation_tag, epoch); if (verbose) verbose_output_lookup_result(last_lookup_result); store_lookup_result_stats(cache_stats, last_lookup_result); } break; case INSTRUCTION: break; case UNKNOWN: default: printf("Unknown operation, aborting...\n"); file_close(fp); free(operation); exit(1); } if (verbose) verbose_output_end(); epoch++; load_next_operation(fp, operation); }; file_close(fp); free(operation); } int main(int argc, char *argv[]) { options_t *options = calloc(1, sizeof(options_t)); parse_options(argc, argv, options); if (options-&gt;help) usage(); cache_stats_t *cache_stats = calloc(1, sizeof(cache_stats_t)); calculate_cache_stats(cache_stats, options-&gt;tracefile, options-&gt;s, options-&gt;E, options-&gt;b, options-&gt;verbose); // below function is included from cachelab.h, but it's rather uninteresting. // printSummary(cache_stats-&gt;hits, cache_stats-&gt;misses, cache_stats-&gt;evictions); printf("hits:%d misses:%d evictions:%d\n", cache_stats-&gt;hits, cache_stats-&gt;misses, cache_stats-&gt;evictions); free(options); free(cache_stats); return 0; } </code></pre> <p>Sample input file (<code>traces/yi.trace</code>):</p> <pre><code> L 10,1 M 20,1 L 22,1 S 18,1 L 110,1 L 210,1 M 12,1 </code></pre> <p>Sample run:</p> <pre><code>./csim -s 2 -E 2 -b 3 -t traces/yi.trace hits:3 misses:6 evictions:2 </code></pre> <p><code>CMakeLists.txt</code>:</p> <pre><code>cmake_minimum_required(VERSION 3.10) project(cachelab) set(SOURCES csim.c) set(TARGET csim) add_executable(${TARGET} ${SOURCES}) target_include_directories(${TARGET} PRIVATE .) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:10:18.857", "Id": "241766", "Score": "2", "Tags": [ "c", "homework", "cache" ], "Title": "Parametrized cache simulation in C" }
241766
<p>I have a very large JSON Lines File with 4.000.000 Rows, and I need to convert several events from every row. The resulted CSV File contains 15.000.000 rows. How can I optimize this script?</p> <p>I'm using Powershell core 7 and it takes around 50 hours to complete the conversion.</p> <p>My Powershell script:</p> <pre><code>$stopwatch = [system.diagnostics.stopwatch]::StartNew() $totalrows = 4000000 $encoding = [System.Text.Encoding]::UTF8 $i = 0 $ig = 0 $output = @() $Importfile = "C:\file.jsonl" $Exportfile = "C:\file.csv" if (test-path $Exportfile) { Remove-Item -path $Exportfile } foreach ($line in [System.IO.File]::ReadLines($Importfile, $encoding)) { $json = $line | ConvertFrom-Json foreach ($item in $json.events.items) { $CSVLine = [pscustomobject]@{ Key = $json.Register.Key CompanyID = $json.id Eventtype = $item.type Eventdate = $item.date Eventdescription = $item.description } $output += $CSVLine } $i++ $ig++ if ($i -ge 30000) { $output | Export-Csv -Path $Exportfile -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append $i = 0 $output = @() $minutes = $stopwatch.elapsed.TotalMinutes $percentage = $ig / $totalrows * 100 $totalestimatedtime = $minutes * (100/$percentage) $timeremaining = $totalestimatedtime - $minutes Write-Host "Events: Total minutes passed: $minutes. Total minutes remaining: $timeremaining. Percentage: $percentage" } } $output | Export-Csv -Path $Exportfile -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append $stopwatch.Stop() </code></pre>
[]
[ { "body": "<p>There's a good article about <em>performance</em> to get your started: <a href=\"https://blogs.technet.microsoft.com/ashleymcglone/2017/07/12/slow-code-top-5-ways-to-make-your-powershell-scripts-run-faster/\" rel=\"nofollow noreferrer\"><em>Slow Code: Top 5 ways to make your Powershell scripts run faster</em></a>; at first sight, here are applicable both parts of <em>Problem #2 &amp; #3: Appending stuff</em>:</p>\n\n<ul>\n<li>Appending to files: <code>Export-CSV -Append</code> repeats roughly 133 times (= <code>4E+6/30E+3</code> i.e. <code>4E+6</code> rows written in chunks of <code>30E+3</code> rows each) which <strong>could</strong> considerably worsen performance for big output file;</li>\n<li>Appending to arrays: (<strong>heart of the matter</strong>) <em>when the <code>+=</code> operator is used, it's actually destroying the array and creating a new one</em> (<a href=\"https://mcpmag.com/articles/2017/09/28/create-arrays-for-performance-in-powershell.aspx\" rel=\"nofollow noreferrer\">source</a>).</li>\n</ul>\n\n<p>To eliminate appending to arrays, you can use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netcore-3.1\" rel=\"nofollow noreferrer\">.NET array list object</a> as follows (merely a hint): replace</p>\n\n<ul>\n<li><code>$output = @()</code> with <code>$output = [System.Collections.ArrayList]::new()</code>, and</li>\n<li><code>$output += $CSVLine</code> with <code>[void]$output.Add($CSVLine)</code>.</li>\n</ul>\n\n<p>Note: do not compute one-purpose variable <code>$CSVLine</code> at all; instead, use</p>\n\n<pre><code>[void]$output.Add(\n [pscustomobject]@{\n Key = $json.Register.Key\n CompanyID = $json.id\n Eventtype = $item.type\n Eventdate = $item.date\n Eventdescription = $item.description\n })\n</code></pre>\n\n<p>Read the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=netcore-3.1#remarks\" rel=\"nofollow noreferrer\">remark about the generic <code>List&lt;T&gt;</code> class</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netcore-3.1#performance-considerations\" rel=\"nofollow noreferrer\">Performance Considerations</a> as well:</p>\n\n<blockquote>\n <p>In deciding whether to use the <code>List&lt;T&gt;</code> or <code>ArrayList</code> class, both of\n which have similar functionality, remember that the <code>List&lt;T&gt;</code> class\n performs better in most cases and is type safe. <em>If a reference type\n is used for type <code>T</code> of the <code>List&lt;T&gt;</code> class, the behavior of the two\n classes is identical</em>.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-16T15:47:35.490", "Id": "242404", "ParentId": "241767", "Score": "3" } } ]
{ "AcceptedAnswerId": "242404", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:26:29.207", "Id": "241767", "Score": "4", "Tags": [ "json", "csv", "powershell" ], "Title": "Converting JSON to CSV using powershell" }
241767
<p>I am a beginner to java and I've coded the Game of Life! For those not familiar, the game entails creating a grid of specified dimensions with each box in the grid being either dead or alive. The grid starts with a random dead or alive state for each box. New generations have new dead/alive boxes based on the following conditions: If there are 3 alive boxes neighbouring any dead box, it becomes alive. If there are less than 2 alive boxes neighbouring an alive box, that box dies. It also dies if there are more than 3 alive boxes around it.</p> <p>The way I am approaching this is by making a <code>boolean[][]</code> array grid with true representing an alive box and false representing a dead one. The view class takes this boolean grid and turns it into a grid of boxes that are either coloured white or red (white = dead)(red = alive).</p> <p>Game Class:</p> <pre><code>import java.util.Arrays; import java.util.Random; public class Game { private boolean[][] grid; private int genCount; private int width; private int height; public Game(int i, int j) { genCount = 0; if (i &lt; 1 || j &lt; 1) { throw new IllegalArgumentException("grid too small!"); } if (i &gt; 100 || j &gt; 100) { throw new IllegalArgumentException("grid too big!"); } width = i; height = j; grid = new boolean[j][i]; } public int getWidth() { return width; } public int getHeight() { return height; } public boolean[][] getGrid() { return grid; } public void setGrid(boolean[][] grid) { this.grid = grid; } public int getGen() { return genCount; } public void setGen(int gen) { this.genCount = gen; } public void randomGrid(double probability) { Random r = new Random(); for (int j = 0; j &lt; height; j++) { for (int i = 0; i &lt; width; i++) { grid[j][i] = Math.random() &lt; probability; } } } public boolean[][] makeCopy() { // making a copy of the current grid, avoiding aliasing. boolean[][] nGrid = new boolean[height][width]; for (int j = 0; j &lt; height; j++) { for (int i = 0; i &lt; width; i++) { nGrid[j][i] = grid[j][i]; } } return nGrid; } public void newGen() { boolean[][] nGrid = makeCopy(); for (int j = 0; j &lt; height; j++) { for (int i = 0; i &lt; width; i++) { if (grid[j][i] == false) { // new life, due to having 3 neighbours! if (getNeighbours(j, i) == 3) { nGrid[j][i] = true; } } else { // isolation death! if (getNeighbours(j, i) &lt;= 1) { nGrid[j][i] = false; } // overcrowing death! if (getNeighbours(j, i) &gt;= 4) { nGrid[j][i] = false; } } } } genCount++; grid = nGrid; } public int getNeighbours(int j, int i) { int count = 0; int jMax = grid[0].length - 1; int iMax = grid[1].length - 1; // checking up, down, right, left, allowing wrapping if ((j &lt; jMax &amp;&amp; grid[j + 1][i]) || (j == jMax &amp;&amp; grid[0][i])) { count++; } if ((j &gt; 0 &amp;&amp; grid[j - 1][i]) || (j == 0 &amp;&amp; grid[jMax][i])) { count++; } if ((i &lt; iMax &amp;&amp; grid[j][i + 1]) || (i == iMax &amp; grid[j][0])) { count++; } if ((i &gt; 0 &amp;&amp; grid[j][i - 1]) || (i == 0 &amp;&amp; grid[j][iMax])) { count++; } // checking diagonals, allowing wrapping if ((j &lt; jMax &amp;&amp; i &lt; iMax &amp;&amp; grid[j + 1][i + 1]) || (j == jMax &amp;&amp; i &lt; iMax &amp;&amp; grid[0][i + 1]) || (j &lt; jMax &amp;&amp; i == iMax &amp;&amp; grid[j + 1][0]) || (j == jMax &amp;&amp; i == iMax &amp;&amp; grid[0][0])) { count++; } if ((j &lt; jMax &amp;&amp; i &gt; 0 &amp;&amp; grid[j + 1][i - 1]) || (j == jMax &amp;&amp; i &gt; 0 &amp;&amp; grid[0][i - 1]) || (j &lt; jMax &amp;&amp; i == 0 &amp;&amp; grid[j + 1][iMax]) || (j == jMax &amp;&amp; i == 0 &amp;&amp; grid[0][iMax])) { count++; } if ((j &gt; 0 &amp;&amp; i &lt; iMax &amp;&amp; grid[j - 1][i + 1]) || (j == 0 &amp;&amp; i &lt; iMax &amp;&amp; grid[jMax][i + 1]) || (j &gt; 0 &amp;&amp; i == iMax &amp;&amp; grid[j - 1][0]) || (j == 0 &amp;&amp; i == iMax &amp;&amp; grid[jMax][0])) { count++; } if ((j &gt; 0 &amp;&amp; i &gt; 0 &amp;&amp; grid[j - 1][i - 1]) || (j == 0 &amp;&amp; i &gt; 0 &amp;&amp; grid[jMax][i - 1]) || (j &gt; 0 &amp;&amp; i == 0 &amp;&amp; grid[j - 1][iMax]) || (j == 0 &amp;&amp; i == 0 &amp;&amp; grid[jMax][iMax])) { count++; } return count; } } </code></pre> <p>View Class:</p> <pre><code>import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class View extends JPanel { public void paint(Graphics g) { Game game = new Game(10, 10); game.randomGrid(0.2); game.newGen(); boolean[][] grid = game.getGrid(); g.setColor(Color.red); for (int j = 0; j &lt; game.getHeight(); j++) { for (int i = 0; i &lt; game.getWidth(); i++) { g.drawRect(100 + (50 * i), 100 + (50 * j), 50, 50); if (grid[j][i]) { g.fillRect(100 + (50 * i), 100 + (50 * j), 50, 50); } } } } public static void main(String[] args) { JFrame frame = new JFrame(); frame.getContentPane().add(new View()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1000, 1000); frame.setVisible(true); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T17:59:33.813", "Id": "474574", "Score": "0", "body": "Aside from general code design, you might also be interested in [methods of optimizing the game of life itself](https://stackoverflow.com/questions/40485/optimizing-conways-game-of-life)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T17:35:09.143", "Id": "474828", "Score": "0", "body": "That \"overcrowing death\" seems rather horrible! :)" } ]
[ { "body": "<p>You are not assigning default values to the fields and you <em>are</em> splitting game logic and UI. That's a good start.</p>\n\n<pre><code>public Game(int i, int j) {\n</code></pre>\n\n<p>In a public function or constructor I expect clearly named parameters.</p>\n\n<pre><code>if (i &gt; 100 || j &gt; 100) {\n throw new IllegalArgumentException(\"grid too big!\");\n}\n</code></pre>\n\n<p>So a grid of 101 cells is too big if <code>i = 1</code> and <code>j = 101</code> but a field of 10 thousand cells is not too big if <code>i = 100</code> and <code>j = 100</code>? I'd return specific errors for the <code>width</code> and <code>height</code> parameters.</p>\n\n<pre><code>width = i;\n</code></pre>\n\n<p>Generally we simply use <code>this.width = width</code> instead, so we don't have to come up with a different variable name.</p>\n\n<pre><code>public boolean[][] getGrid() {\n return grid;\n}\n</code></pre>\n\n<p>Beware of exposing your state. The reference to the grid is copied, but the arrays are mutable! Either clone or expose the state in another way (e.g. using an enumerator or by referencing grid cells separately using coordinates).</p>\n\n<pre><code>public void setGen(int gen) {\n this.genCount = gen;\n}\n</code></pre>\n\n<p>It's a bit weird that you can set the <code>genCount</code> during the game of life. Again, <code>setGen</code> and <code>gen</code> may not really be clear to the user. <code>gen</code> may also have any value apparently, allowing the object instance to have an invalid state. I'd rename <code>genCount</code> to <code>generation</code>, so away with <code>gen</code> altogether and remove this setter.</p>\n\n<pre><code>public void randomGrid(double probability) {\n</code></pre>\n\n<p>This is OK-ish, but I prefer to check if probabilities are between 0 and 1 inclusive (yeah, I know, Java is rather heavy on boilerplate code).</p>\n\n<pre><code>public boolean[][] makeCopy() {\n</code></pre>\n\n<p>This seems near identical to <code>getGrid</code>. But more importantly, if I make a copy of a game then I don't expect a grid in return. This method is in dire need to be made <code>private</code> anyway.</p>\n\n<pre><code>boolean[][] nGrid = new boolean[height][width];\n</code></pre>\n\n<p>Just <code>newGrid</code> is only 2 characters extra. Don't overly skim on characters (and possibly learn how to touch type).</p>\n\n<pre><code>for (int i = 0; i &lt; width; i++) {\n nGrid[j][i] = grid[j][i];\n}\n</code></pre>\n\n<p>Use <code>System.arrayCopy()</code> at least for the inner loop instead.</p>\n\n<pre><code>if (grid[j][i] == false) {\n</code></pre>\n\n<p>Ugh, here are the <code>i</code> and <code>j</code> again, but now <code>j</code> is the X-coordinate while it was the width before and <code>i</code> is the Y-coordinate.</p>\n\n<p>Furthermore, what about two constants? <code>DEAD = false</code> and <code>ALIVE = true</code>? Using an enum is also possible (<code>enum Cell { DEAD, ALIVE; }</code>), so that <code>false</code> and <code>true</code> cannot even be used anymore.</p>\n\n<pre><code>if (getNeighbours(j, i) == 3) {\n</code></pre>\n\n<p>This I like, good method name, and a method that is sorely needed here.</p>\n\n<pre><code>genCount++;\ngrid = nGrid;\n</code></pre>\n\n<p>Lovely, side effects right at the end where they belong.</p>\n\n<hr>\n\n<p>As for <code>getNeighbours</code>, let's simplify things a bit using modular arithmetic...</p>\n\n<pre><code>private static final boolean ALIVE = true;\n\nprivate int getNeighbours(int x, int y) {\n int count = 0;\n\n // iterate over all neighbouring cells as a square\n for (int dx = -1; dx &lt;= 1; dx++) {\n for (int dy = -1; dy &lt;= 1; dy++) {\n // skip cell itself\n if (dx == 0 &amp;&amp; dy == 0) {\n continue;\n }\n\n // get coordinates for neighbour\n int nx = Math.floorMod(x + dx, width);\n int ny = Math.floorMod(y + dy, height);\n\n if (grid[nx][ny] == ALIVE) {\n count++;\n }\n }\n }\n\n return count;\n}\n</code></pre>\n\n<p>Note that <code>floorMod</code> is the modulus operation while <code>%</code> is the remainder operation which will return <code>-1</code> if the left operand is <code>-1</code>. That's not what you want, you want <code>width - 1</code> or <code>height - 1</code> instead.</p>\n\n<p>Now I hope that looks a bit easier on the eye. You may want to rename <code>dx</code> to <code>deltaX</code> and <code>nx</code> to <code>neighbouringX</code> or something like that, but there is such a thing as overdoing it too. For local vars you may be a bit less strict (fields and parameters are more important for sure).</p>\n\n<p>Note that I didn't know that the game of life uses wrapping, but that's another matter I guess. I'll not go on about the strategy design pattern, that might be a bit too deep.</p>\n\n<hr>\n\n<p>I think your design would look better if you split your game of life into a <code>Game</code> and <code>Grid</code> class. That way the method naming would be much easier.</p>\n\n<hr>\n\n<p>Finally, currently your game of life only operates when redrawing the window (or <code>JFrame</code> in Swing talk). That's of course not how it should be, it should be running on a timer and/or using buttons.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T22:13:31.923", "Id": "474474", "Score": "1", "body": "I'm glad you focused on the Game class. I focused on the GUI. I like both our answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T09:27:21.917", "Id": "474508", "Score": "4", "body": "\"So a grid of 101 cells is too big if i = 1 and j = 101 but a field of 10 thousand cells is not too big if i = 100 and j = 100? That cannot be right?\" Can't it? If the UI only has space to show 100 cells horizontally, and 100 cells vertically, that sounds about right to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T10:29:28.403", "Id": "474518", "Score": "6", "body": "@PaulD.Waite Sure thing, but then I would have an error message saying that it is too wide or too high rather than \"too big\". I'll adjust the wording accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T01:23:44.770", "Id": "474596", "Score": "0", "body": "\"(and possibly learn how to touch type)\" What do you mean by this? I'm used to touch typing meaning being able to type without looking at the keyboard, but I'm not sure how that applies to the clarity of using easier to understand variable names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T04:28:57.453", "Id": "474598", "Score": "2", "body": "BTW, the whole makeCopy() method could simply be replaced with \"return grid.clone()\"." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T21:54:53.337", "Id": "241783", "ParentId": "241768", "Score": "20" } }, { "body": "<p>I made some modifications to your <code>View</code> class and created this GUI.</p>\n\n<p><a href=\"https://i.stack.imgur.com/uNKv9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uNKv9.png\" alt=\"Life GUI\"></a></p>\n\n<p>I couldn't get the <code>Game</code> class to cycle through generations. Maybe I missed something. I didn't see where the <code>Game</code> class needed any changes.</p>\n\n<p>Here are the changes I made to your <code>View</code> class.</p>\n\n<ol>\n<li><p>I started the GUI on the <a href=\"https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html\" rel=\"noreferrer\">Event Dispatch Thread</a> (EDT) by calling the <code>SwingUtilities</code> <code>invokeLater</code> method. This ensures that the Swing components are created and updated on the EDT.</p></li>\n<li><p>I put the painting code in the <code>paintComponent</code> method. I called <code>super.paintComponent</code> to maintain the Swing paint chain. I removed all code that wasn't painting code.</p></li>\n<li><p>I put <code>@Override</code> annotations on all of the methods I overrode. That way, the compiler will possibly tell me if there's a problem with my method calls.</p></li>\n<li><p>I scaled the <code>JPanel</code> to a more reasonable size. Some of us still have tiny monitors. I got rid of most of the magic numbers.</p></li>\n</ol>\n\n<p>Here's the <code>View</code> class code.</p>\n\n<pre><code>import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\n\npublic class View extends JPanel implements Runnable {\n\n private static final long serialVersionUID = 1L;\n\n private boolean[][] grid;\n\n private int margin;\n private int squareWidth;\n\n private Game game;\n\n public View() {\n this.game = new Game(10, 10);\n this.game.randomGrid(0.2);\n this.grid = game.getGrid();\n\n this.margin = 50;\n this.squareWidth = 32;\n int width = squareWidth * 10 + margin + margin;\n this.setPreferredSize(new Dimension(width, width));\n }\n\n @Override\n public void run() {\n JFrame frame = new JFrame(\"Conway's Game of Life\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n frame.getContentPane().add(new View());\n frame.pack();\n frame.setLocationByPlatform(true);\n frame.setVisible(true);\n\n Thread thread = new Thread(new Timer(game, this));\n thread.start();\n } \n\n public void setGrid(boolean[][] grid) {\n this.grid = grid;\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n\n int generation = game.getGen();\n String text = \"Generation: \" + generation;\n g.setColor(Color.BLACK);\n g.drawString(text, 10, 30);\n\n g.setColor(Color.red);\n for (int j = 0; j &lt; grid.length; j++) {\n for (int i = 0; i &lt; grid[j].length; i++) {\n int x = margin + (squareWidth * i);\n int y = margin + (squareWidth * j);\n g.drawRect(x, y, squareWidth, squareWidth);\n if (grid[j][i]) {\n g.fillRect(x, y, squareWidth, squareWidth);\n }\n }\n }\n\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new View());\n }\n\n} \n</code></pre>\n\n<p>I created a new Timer class to update the GUI every 5 seconds. Since the GUI never changed, I put a <code>System.out.println</code> method in the timer loop to make sure it was running.</p>\n\n<p>You can change the 5 second delay if you wish.</p>\n\n<pre><code>import javax.swing.SwingUtilities;\n\npublic class Timer implements Runnable {\n\n private volatile boolean running;\n\n private Game game;\n\n private View view;\n\n public Timer(Game game, View view) {\n this.game = game;\n this.view = view;\n this.running = true;\n }\n\n @Override\n public void run() {\n while (running) {\n sleep(5000L);\n game.newGen();\n updateView();\n// System.out.println(\"running\");\n }\n }\n\n private void sleep(long duration) {\n try {\n Thread.sleep(duration);\n } catch (InterruptedException e) {\n // Deliberately left empty\n }\n }\n\n private void updateView() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n view.setGrid(game.getGrid());\n view.repaint();\n }\n });\n }\n\n public synchronized void setRunning(boolean running) {\n this.running = running;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T22:06:17.923", "Id": "474473", "Score": "0", "body": "It only performs the game of life in the redraw (e.g. resize) in the original. Cool to see an answer that focuses on the GUI, mine focuses on the game engine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T20:23:35.077", "Id": "474585", "Score": "0", "body": "So by minimizing and reshowing repeatly, the game runs faster?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T22:05:07.817", "Id": "241784", "ParentId": "241768", "Score": "11" } }, { "body": "<p>I would recommend changing how your grid is represented in memory.\nImagine you have a 10000x10000 grid and just 1 cell at coordinates (5,5) that's alive.</p>\n\n<p>If you use an array to store that information, you have to create thousands upon thousands of data points pretty much all of which basically say nothing but “nothing to see here”. Dead cells are the default and therefore there's not really much we need to hold in memory about them.</p>\n\n<p>So let's use a HashSet that only stores the alive cells. If the HashSet contains a given coordinate, the corresponding cell is alive. Otherwise the HashSet returns false, meaning it is dead. Now you can have a virtually infinite grid which, especially if mostly empty (as a Game of Life usually is), hardly needs any memory.</p>\n\n<p>My Java is super rusty so consider the following something like pseudo code, but you get the idea:</p>\n\n<pre><code>public class Coordinate {\n public int x, y;\n\n// Just to make it even clearer than I thought it was: \n// There is more work to do in this code snippet, like overriding equals() and hashCode(). \n// This code is just to demonstrate the concept, not an actual full implementation.\n\n}\n\npublic class Grid {\n private HashSet grid;\n\n public void setAlive(Coordinate c) {\n grid.add(c);\n }\n\n public void setDead(Coordinate c) {\n grid.remove(c);\n }\n\n public boolean isAlive(Coordinate c){\n return grid.contains(c);\n }\n\n public int getNumberOfNeighbours(Coordinate c){\n ...\n }\n}\n</code></pre>\n\n<p>Obviously you can now continue to encapsulate other grid-specific functions and make your Game class simpler and better readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T11:21:09.387", "Id": "474531", "Score": "3", "body": "To fully realize the benefits of this approach, you should also modify `newGen()` to only iterate over the neighbors of cells in the previous generation's HashSet, so that its runtime will be proportional to the number of live cells regardless of how far apart they are. (A slight complication is that doing this naively may result in redundantly processing the same cell multiple times if it has several live neighbors. One way to avoid that is to have a first pass that just counts the neighbors of each cell and stores them in a HashMap, and a second pass that updates the state based on that.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T16:27:31.997", "Id": "474567", "Score": "0", "body": "I just created a chess game that uses the same approach. I like the idea that you use `Coordinate`, but to avoid confusion I'd call that `Position` instead (as a position has an x- and y-coordinate). Furthermore, `HashSet` is just an implementation of `Set` (and in this case you'd use `Set<Position>` of course. Beware that `Set<Position>` requires `Position.equals` and `Position.hashCode` to be implemented (!). The approach is valid, but it does take a bit more advanced programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T17:10:16.267", "Id": "474571", "Score": "0", "body": "@MaartenBodewes Which is why I added that the code snippet should be considered pseudo code to get the idea across ;) And to me a position can also be “above” or “top” so I found coordinate slightly more fitting, but whatever, the main goal was to explain the concept, not to provide copy-and-pastable code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T16:05:25.747", "Id": "474678", "Score": "1", "body": "An entry in a hash set containing a coordinate object requires at an absolute minimum 32 bits (one reference) for the hash entry and 128 bits for the object (two words overhead and two 32 bit fields). In an array, the state can be represented as a single bit. A game of life where only one in 160 cells are active wouldn't be very interesting, so you're probably not optimising for a representative use case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T19:59:06.217", "Id": "474694", "Score": "0", "body": "@PeteKirkham Interesting. I wasn't quite sure how much memory the HashSet solution would actually take which is why I changed my wording from “strongly suggest” to “recommend” in a later edit. I didn't expect it to be this bad, especially since I had been introduced to this approach at university (for this usecase, the Game of Life). But if you have gliders flying off into space the grid can become quite expansive and still mostly empty and there's no need to dynamically extend the grid, right? (Plus one still gets the benefit of only having to iterate over actually existing cells.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T22:30:03.150", "Id": "474713", "Score": "0", "body": "I think you need to override equals() and hashCode() on the coordinate class for this to work reasonably well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T22:33:11.670", "Id": "474714", "Score": "0", "body": "@PeteKirkham The size of a boolean is dependent on the implementation of the virtual machine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T10:56:04.940", "Id": "474778", "Score": "0", "body": "@Taemyr yes, it's common to use bit operations on an array of integers; outside of Java you can use SIMD instructions to compute multiple cells at once." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T09:10:00.217", "Id": "241809", "ParentId": "241768", "Score": "8" } }, { "body": "<p>A few quick notes on newGen(). The main one is you're calling getNeighbours twice in the cell-was-alive case, meaning you're doing double the work to count them when the value can't change. So you should only call it once and save the result in a variable, and since you're going to need the count in all cases so you can do it once before the <code>if</code>:</p>\n\n<pre><code> for (int j = 0; j &lt; height; j++) {\n for (int i = 0; i &lt; width; i++) {\n int neighbours = getNeighbours(j, i);\n</code></pre>\n\n<p>I'd then continue with the 'alive' case since it's the 'true' case, but that doesn't really matter. Sticking with what you had, this becomes</p>\n\n<pre><code> if (grid[j][i] == false) {\n // new life, due to having 3 neighbours!\n if (neighbours == 3) {\n nGrid[j][i] = true;\n }\n } else {\n // isolation death!\n if (neighbours &lt;= 1) {\n nGrid[j][i] = false;\n }\n // overcrowing death!\n if (neighbours &gt;= 4) {\n nGrid[j][i] = false;\n }\n }\n</code></pre>\n\n<p>But as it stands you're copying the grid and then setting or resetting it for changes whereas we do explicitly know whether each cell is dead or alive in the conditions. If we change this to:</p>\n\n<pre><code> if (grid[j][i] == false) {\n // new life, due to having 3 neighbours!\n if (neighbours == 3) {\n nGrid[j][i] = true;\n } else {\n // still dead\n nGrid[j][i] = false;\n }\n } else {\n // isolation death!\n if (neighbours &lt;= 1) {\n nGrid[j][i] = false;\n } else if (neighbours &gt;= 4) {\n // overcrowing death!\n nGrid[j][i] = false;\n } else {\n // still alive\n nGrid[j][i] = true;\n }\n }\n</code></pre>\n\n<p>then we're always setting the cell in nGrid, meaning you no longer need to copy the old grid: you can just allocate an empty array instead.</p>\n\n<pre><code> // in newGen(), replacing the call to makeCopy()\n boolean[][] nGrid = new boolean[height][width];\n</code></pre>\n\n<p>Or we could simplify this condition further:</p>\n\n<pre><code> if (grid[j][i] == false) {\n // new life if 3 neighbours, else dead\n nGrid[j][i] = (neighbours == 3);\n } else {\n // still alive if 2 or 3 neighbours, else dead\n nGrid[j][i] = (neighbours == 2) || (neighbours == 3);\n }\n</code></pre>\n\n<p>or even flipping the logic slightly:</p>\n\n<pre><code> // New cell is alive if it has three neighbours, regardless whether it was\n // dead or alive before, or if it was already alive and has two neighbours.\n nGrid[j][i] = (neighbours == 3) || (grid[j][i] &amp;&amp; (neighbours == 2));\n</code></pre>\n\n<p>although I appreciate the previous way is a clearer statement of the rules.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T13:29:58.343", "Id": "241821", "ParentId": "241768", "Score": "2" } }, { "body": "<p>I can't speak to the Java-related aspects of your solution, but you've got one problem that would be an issue in any language: you're performing far more dynamic allocation than necessary.</p>\n\n<p>In your case, you know exactly how much space you need: two grids of <code>width*height</code> space each. Instead of allocating a new grid every generation, just allocate the space you need at game startup. With each generation, swap which one represents the current state, and which one represents the next state. You can do this by allocating <code>grid</code> as a three-dimensional array, or by allocating two <code>grid</code>s and swapping references, or whatever other method you think is easiest.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T16:25:35.340", "Id": "474680", "Score": "0", "body": "You can get away with one grid width*height and two working arrays of size width; update one row at a time, write back to the grid one row behind the one you're calculating so you don't affect the calculation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T19:29:06.887", "Id": "474692", "Score": "1", "body": "Interesting optimization direction.\nBut beware at implementation specifics here: as one cell update depends on all its neighbours previous state, updating *one* row requires retaining knowledge of previous state of *three* rows (the one being currently updated, and the two neighbouring rows).\nOne would therefore need kind of a moving (potentially rolling) window.\nBut, I guess, no need of a \"working copy\" of the row being currently being updated, that we would need then to copy back to the array: updates could be done in-place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T20:26:01.510", "Id": "474701", "Score": "0", "body": "@PeteKirkham, a rolling update like you describe saves even more space, but it comes at a cost: shared access to the grid is much harder. The grid representing the current generation is only in a consistent state between updates, rather than always being in a consistent state." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T21:23:39.697", "Id": "241838", "ParentId": "241768", "Score": "3" } } ]
{ "AcceptedAnswerId": "241783", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-05T17:27:18.280", "Id": "241768", "Score": "12", "Tags": [ "java", "game-of-life" ], "Title": "Coded the Game of Life" }
241768