body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am attempting to complete the coin flip streaks problem from <strong>automate the boring stuff with python.</strong> My code works fine but my only concern is the phrasing of the task.</p> <p>Does the question want us to find the number of samples <strong>(100 flips)</strong> that contain at least one streak and divide that by the total number of samples <strong>(10,000)</strong></p> <p>Or are we supposed to find the total number of streaks (6H or 6T) in all samples and divide that by 10,000?</p> <p>My solution was for the first option but I make no distinction between one streak and several.</p> <p>My code and the question are listed below.</p> <h2>Coin Flip Streaks</h2> <blockquote> <p>For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.</p> <p>Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.</p> </blockquote> <pre><code>import random import re totalRuns = 0 streakScore = 0 def coinFips(): global streakScore,totalRuns # Return results into a single string for regular expressions results = '' for i in range(100): value = random.randint(0, 1) if value == 0: results += &quot;H&quot; elif value == 1: results += &quot;T&quot; # Use regular expressions to check results sting match = re.findall(r'(HHHHHH|TTTTTT)', results) if len(match) &gt; 0: streakScore = streakScore + 1 totalRuns = totalRuns + 1 for i in range(10000): coinFips() print(&quot;The Chance of a streak is: {}%&quot;.format(round(streakScore/totalRuns * 100))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T02:25:26.830", "Id": "498201", "Score": "0", "body": "What results do you get? Should be around 80.7%" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T02:27:59.280", "Id": "498202", "Score": "0", "body": "Around 80%, which according to other post I read that is correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T02:52:47.073", "Id": "498203", "Score": "0", "body": "for programming challenge type questions, please include the link to original as well :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T19:46:08.430", "Id": "498249", "Score": "0", "body": "Your reading seems correct. In the context of the question it doesn't matter how many streaks the string has. It only matters that a streak is there." } ]
[ { "body": "<h2>The assignment</h2>\n<blockquote>\n<p>Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails.</p>\n</blockquote>\n<p>Now this requirement you didn't match, so your program doesn't contain the required functionality, <em>even</em> if it does match the required result.</p>\n<p>Note that there is a bit of a problem with the assignment, as you might see a streak of 7 as two streaks of 6, or a streak of 12 as two streaks of 6. I presume, given the assignment, that you may use any streak of 6 <em>or more</em>. This is not what your program currently does, by the way; <em>I presume from the code that a streak of 12 will be seen as two streaks of 6.</em></p>\n<p>[EDIT] <strong>Rereading the question, it seems that you do match the assignment, if you assume that the &quot;often&quot; part depends on how often the streak of 6 comes up in the randomly generated distributions, instead of in one distribution</strong>. That seems to be the case if I take the rest of the context in, but the assignment isn't stated very clearly.</p>\n<blockquote>\n<p>our program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it.</p>\n</blockquote>\n<p>You fail to meet this requirement: you haven't specified two methods, which is generally the way you would split things up in programming.</p>\n<blockquote>\n<p>Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row.</p>\n</blockquote>\n<p>So if you'd create the method that counts the streaks, and the streak count is higher than <code>0</code> then you would increase the counter. You do that perfectly :)</p>\n<p>As indicated, you haven't separated it from the main functionality. Worse, you update global variables from a function.</p>\n<p>If this course is about structured programming then you might fail even though your application is likely to generate the right answer.</p>\n<h2>Code review</h2>\n<pre><code>totalRuns = 0 \nstreakScore = 0\n</code></pre>\n<p>This is fine, but in that case you need to update them from global code. If not the variables should be local to a function.</p>\n<pre><code>def coinFips():\n</code></pre>\n<p>This method name is misspelled. Does the method really only perform coin flips? If so, shouldn't there be a parameter that indicates how many? And return an array of results?</p>\n<pre><code>global streakScore,totalRuns\n</code></pre>\n<p>Every time you type <code>global</code>, you should wonder if it really helps design / readability, and refrain from using globals if it does not. I would add a space before <code>totalRuns</code>, but that's kind of personal.</p>\n<pre><code>results = ''\n</code></pre>\n<p>Why not use a (character) array instead? That way you can assign it the right size from the start and then fill it by indexing the coin flip...</p>\n<pre><code>for i in range(100):\n</code></pre>\n<p><code>100</code> is a literal, a so called &quot;magic value&quot;. Here you should use a parameter (or, in other cases, a constant).</p>\n<pre><code># Use regular expressions to check results sting\n</code></pre>\n<p>Another spelling mistake. Spelling mistakes are not terrible, but if you make too many they act as red flags to a reviewer. They are more likely to take a deeper look.</p>\n<pre><code>match = re.findall(r'(HHHHHH|TTTTTT)', results)\n</code></pre>\n<p>It will probably not be terribly performant, but it is a nice way to test and easy to program. But note the problem indicated in the first section of the review.</p>\n<p>Instead you probably want to use something like <code>([H]{6,}|[T]{6,})</code>. Also, you'll find that regular expressions are hard to parameterize (what if you want to use 7 or any other number instead of 6?). Some kind of state machine would impress me (even) more.</p>\n<pre><code>print(&quot;The Chance of a streak is: {}%&quot;.format(round(streakScore/totalRuns * 100)))\n</code></pre>\n<p>Here too much is happening for me. The calculation should be on it's own line. If your function ends with <code>)))</code> then your application is getting too much LISP like if you ask me. You can also see that it is getting too cramped because you suddenly don't use spacing around the operator <code>/</code> anymore.</p>\n<hr />\n<p>The other lines seem fine to me. There isn't <em>too</em> much happening on them except for the last line - which is good. And the variable naming seems fine too. Spacing and readability are fine. The application code is concise too.</p>\n<p>Conclusion: you are well on your way, but the part where you &quot;divide-and-conquer&quot; is lacking. This is not much of a problem in the above code of course, but it may become a problem for larger, more complex systems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T02:44:50.167", "Id": "499106", "Score": "0", "body": "Or summed up, more methods, more constants, more parameters, fewer globals." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T21:28:08.767", "Id": "253146", "ParentId": "252776", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T02:08:41.873", "Id": "252776", "Score": "1", "Tags": [ "python", "programming-challenge", "regex", "random", "mathematics" ], "Title": "Coin Flip Streaks script" }
252776
<p>I did an OOP to make 2048 using Matplotlib visualization. The <code>color</code> dictionary is for setting different colors to each number in the game.</p> <p>There are two classes written here: <code>App2048</code>, through which we add interactivity and we run the app, and <code>CellObject</code>, which is for the cell/square that will have a value/number. objects of <code>CellObject</code> can update itself visually, if the value/number changes, through the method <code>update</code>. There are <code>n*n</code> <code>CellObject</code> objects in the game.</p> <p>The algorithm for the swipe (left/right/up/down) is done through methods in <code>App2048</code>. When we swipe left, for example, we want all numbers 'move' to the left, this can be done by changing the values/numbers in the cells. But before changing the values, we must make Python to decide which direction the numbers will move. To do that, we track the movement of the cursor while the mouse button is hold, then if we reach some point P where the vector from the initial point to that last point P has length at least 0.5, then Python will analyze the tendency of the direction of the vector. For example: a vector of (0.1, 1) clearly indicates 'UP' direction because it tends to move north, if the vector is (0.8, -0.1) then it indicates 'RIGHT' direction, etc.</p> <p>When the condition of swiping (left/right/up/down) is met, then the app object will perform the <code>go_left</code>/ <code>go_right</code>/<code>go_up</code>/<code>go_down</code> method, in which the numbers in the cells are updated to show movement. The algorithm: we move the numbers first, without accounting the 'combined two equal numbers'. After moving, then we find adjacent pairs with same numbers and then combined them according to the direction of the swipe, and then moving the numbers again just like we did just before finding adjacent pairs. After swipe, if the values are changed then we will set a new number, 2 or 4, to a randomly picked zero valued cell thorugh <code>add_new_value</code> method.</p> <p>The <code>solvable</code> method is to check whether or not we can still make a movement. It checks if we still have zero valued cell, or if there is at least one adjacent pair with same numbers.</p> <p>The <code>solved_or_lost</code> method is quite clear.</p> <hr /> <pre><code>import random import math import matplotlib.pyplot as plt from matplotlib.patches import Rectangle color = {0: (0,0,0,0), 2: (0, 0.5, 0, 0.5), 4: (0, 0.5, 0, 1), 8: (0, 1, 0, 0.5), \ 16: (0, 1, 0, 1), 32: (0, 0, 0.5, 0.5), 64: (0, 0, 0.5, 1), 128: (0, 0, 1, 0.5), \ 256: (0, 0, 1, 1), 512: (0.75, 0, 0, 0.5), 1024: (0.75, 0, 0, 1), 2048: (1, 0, 0, 1)} class App2048: def __init__(self, n): self.n = n self.fig, self.axes = plt.subplots() self.axes.axis('scaled') self.axes.set_xlim(0, n+1); self.axes.set_ylim(0, n+1) self.cells = [] for i in range(1,n+1): row_cells = [] for j in range(1, n+1): cell = CellObject(i, j, 0, \ self.fig, self.axes) row_cells.append(cell) self.cells.append(row_cells) self.cells_2 = [] for row in self.cells: self.cells_2.extend(row) c1 = random.sample(self.cells_2, 1)[0] c2 = random.sample(self.cells_2, 1)[0] while c2 == c1: c2 = random.sample(self.cells_2, 1)[0] c1.value = 2; c1.update() c2.value = 2; c2.update() self.connect() self.press = False self.path = [] self.win = False plt.show() def on_press(self, event): pos = event.xdata, event.ydata if None not in pos: self.press = True self.path.append(pos) def on_motion(self, event): if self.press: pos = event.xdata, event.ydata if None not in pos: self.path.append(pos) else: self.path.clear() self.press = False return None dx = self.path[-1][0] - self.path[0][0] dy = self.path[-1][1] - self.path[0][1] vector_length = math.sqrt((dx**2) + (dy**2)) direction = None if vector_length &gt;= 0.5: if abs(dx) &gt; abs(dy): if dx &gt; 0: direction = 'right' elif dx &lt; 0: direction = 'left' elif abs(dy) &gt; abs(dx): if dy &gt; 0: direction = 'up' elif dy &lt; 0: direction = 'down' if direction != None: self.press = False self.path.clear() previous_values = self.values if direction == 'up': self.go_up() elif direction == 'down': self.go_down() elif direction == 'right': self.go_right() else: self.go_left() if self.changed(previous_values): self.add_new_value() self.solved_or_lost() def on_release(self, event): pos = event.xdata, event.ydata self.press = False self.path.clear() def solvable(self): current_values = self.values if 0 in current_values: return True else: for i in range(self.n): for j in range(self.n): if j+1 &lt;= self.n-1: if self.cells[i][j].value == self.cells[i][j+1].value: return True if 0 &lt;= j-1: if self.cells[i][j].value == self.cells[i][j-1].value: return True if i+1 &lt;= self.n-1: if self.cells[i][j].value == self.cells[i+1][j].value: return True if 0 &lt;= i-1: if self.cells[i][j].value == self.cells[i-1][j].value: return True def solved_or_lost(self): current_values = self.values if (2048 in current_values) and (not self.win): self.axes.set_title('WIN', color= 'blue') self.fig.canvas.draw() self.win = True return True elif self.solvable(): return False else: self.axes.set_title('LOSE', color = 'red') self.fig.canvas.draw() plt.pause(2) plt.close() @property def values(self): return [cell.value for cell in self.cells_2] def changed(self, previous_values): current_values = self.values return current_values != previous_values def add_new_value(self): new_number = random.sample([2,2,2,2,2,2,2,4,4,4], 1)[0] random_cell = random.sample([cell for cell in self.cells_2 if cell.value==0], \ 1)[0] random_cell.value = new_number random_cell.update(draw=True) def go_up(self): for j in range(self.n): positives = [self.cells[self.n-1-i][j].value for i in range(self.n) if self.cells[self.n-1-i][j].value &gt; 0] for i in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for i in range(len(positives)): self.cells[self.n-1-i][j].value = positives[i]; self.cells[self.n-1-i][j].update(draw=False) self.fig.canvas.draw() for j in range(self.n): positives = [self.cells[self.n-1-i][j] for i in range(self.n) if self.cells[self.n-1-i][j].value &gt; 0] for i in range(len(positives)-1): if self.cells[self.n-1-i][j].value == self.cells[self.n-2-i][j].value: self.cells[self.n-1-i][j].value = 2*self.cells[self.n-2-i][j].value self.cells[self.n-2-i][j].value = 0 self.cells[self.n-1-i][j].update(draw=False); self.cells[self.n-2-i][j].update(draw=False) positives = [self.cells[self.n-1-i][j].value for i in range(self.n) if self.cells[self.n-1-i][j].value &gt; 0] for i in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for i in range(len(positives)): self.cells[self.n-1-i][j].value = positives[i]; self.cells[self.n-1-i][j].update(draw=False) self.fig.canvas.draw() def go_down(self): for j in range(self.n): positives = [self.cells[i][j].value for i in range(self.n) if self.cells[i][j].value &gt; 0] for i in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for i in range(len(positives)): self.cells[i][j].value = positives[i]; self.cells[i][j].update(draw=False) self.fig.canvas.draw() for j in range(self.n): positives = [self.cells[i][j] for i in range(self.n) if self.cells[i][j].value != 0] for i in range(len(positives)-1): if self.cells[i][j].value == self.cells[i+1][j].value: self.cells[i][j].value = 2*self.cells[i+1][j].value self.cells[i+1][j].value = 0 self.cells[i][j].update(draw=False); self.cells[i+1][j].update(draw=False) positives = [self.cells[i][j].value for i in range(self.n) if self.cells[i][j].value &gt; 0] for i in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for i in range(len(positives)): self.cells[i][j].value = positives[i]; self.cells[i][j].update(draw=False) self.fig.canvas.draw() def go_left(self): for i in range(self.n): positives = [self.cells[i][j].value for j in range(self.n) if self.cells[i][j].value &gt; 0] for j in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for j in range(len(positives)): self.cells[i][j].value = positives[j]; self.cells[i][j].update(draw=False) self.fig.canvas.draw() for i in range(self.n): positives = [self.cells[i][j] for j in range(self.n) if self.cells[i][j].value &gt; 0] for j in range(len(positives)-1): if self.cells[i][j].value == self.cells[i][j+1].value: self.cells[i][j].value = 2*self.cells[i][j+1].value self.cells[i][j+1].value = 0 self.cells[i][j].update(draw=False); self.cells[i][j+1].update(draw=False) positives = [self.cells[i][j].value for j in range(self.n) if self.cells[i][j].value &gt; 0] for j in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for j in range(len(positives)): self.cells[i][j].value = positives[j]; self.cells[i][j].update(draw=False) self.fig.canvas.draw() def go_right(self): for i in range(self.n): positives = [self.cells[i][self.n-1-j].value for j in range(self.n) if self.cells[i][self.n-1-j].value &gt; 0] for j in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for j in range(len(positives)): self.cells[i][self.n-1-j].value = positives[j]; self.cells[i][self.n-1-j].update(draw=False) self.fig.canvas.draw() for i in range(self.n): positives = [self.cells[i][self.n-1-j] for j in range(self.n) if self.cells[i][self.n-1-j].value &gt; 0] for j in range(len(positives)-1): if self.cells[i][self.n-1-j].value == self.cells[i][self.n-2-j].value: self.cells[i][self.n-1-j].value = 2*self.cells[i][self.n-2-j].value self.cells[i][self.n-2-j].value = 0 self.cells[i][self.n-1-j].update(draw=False); self.cells[i][self.n-2-j].update(draw=False) positives = [self.cells[i][self.n-1-j].value for j in range(self.n) if self.cells[i][self.n-1-j].value &gt; 0] for j in range(self.n): self.cells[i][j].value = 0; self.cells[i][j].update(draw=False) for j in range(len(positives)): self.cells[i][self.n-1-j].value = positives[j]; self.cells[i][self.n-1-j].update(draw=False) self.fig.canvas.draw() def connect(self): self.fig.canvas.mpl_connect('button_press_event', self.on_press) self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) self.fig.canvas.mpl_connect('button_release_event', self.on_release) class CellObject: def __init__(self, row, col, value, fig, axes): self.row = row self.col = col self.value = value self.fig, self.axes = fig, axes self.start() def start(self): if self.value == 0: self.ec = (0,0,0,0.1) self.text_color = (0,0,0,0) else: self.ec = (0,0,0,1) self.text_color = (1,1,1,1) self.fc = color[self.value] self.center = [self.col, self.row] self.rect = Rectangle([self.col-0.5, self.row-0.5], \ width = 1, height = 1, fc = self.fc, ec = self.ec, \ linewidth = 2) self.text = self.axes.text(self.col, self.row, str(self.value), \ color = self.text_color, \ ha = 'center', va = 'center', \ fontweight = 'bold') self.axes.add_patch(self.rect) self.fig.canvas.draw() def update(self, draw = False): if self.value == 0: self.ec = (0,0,0,0.1) self.text_color = (0,0,0,0) else: self.ec = (0,0,0,1) self.text_color = (1,1,1,1) self.fc = color[min(self.value, 2048)] self.rect.set_fc(self.fc) self.rect.set_ec(self.ec) self.text.set_color(self.text_color) self.text.set_text(str(self.value)) if draw: self.fig.canvas.draw() if __name__ == '__main__': n = 8 app = App2048(n) </code></pre> <hr /> <p><em>Tutorial video:</em> <a href="https://youtu.be/GLTZCLn7WM0" rel="nofollow noreferrer">https://youtu.be/GLTZCLn7WM0</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T10:40:22.590", "Id": "252782", "Score": "3", "Tags": [ "python", "game", "matplotlib", "2048" ], "Title": "2048 in Matplotlib" }
252782
<p>For example if the numbers are: 5 + 3 * 7 + 10 * 2 * 3 + 1 % 11</p> <p>then it would multiply and add all the numbers giving 397 and divide by 11 giving 36.09 so therefore it must output 1.</p> <p>My code works in this scenario but if I do more larger numbers it doesn't seem to work. This is what I have</p> <pre><code>#include &lt;iostream&gt; using std::cout; using std::cin; int main() { int num1, num2; char opp = 'a'; cout &lt;&lt; &quot;Firt nubmer&quot;; cin &gt;&gt; num1; while (opp != '%') { cin &gt;&gt; opp; cin &gt;&gt; num2; if (opp == '+') { num1 += num2; } else if (opp == '*') { num1 *= num2; } else { cout &lt;&lt; num1 &lt;&lt; &quot; &quot; &lt;&lt; num2 &lt;&lt; std::endl; num1 %= num2; } } cout &lt;&lt; num1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T15:28:19.730", "Id": "498234", "Score": "0", "body": "Welcome to the Code Review Community, currently there isn't enough detail in the question about the problem statement. Please add the description from the programming challenge and a link to the programming challenge. You might want to look at the programming challenge tag for some examples of well asked question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T13:19:53.120", "Id": "252784", "Score": "1", "Tags": [ "c++", "programming-challenge" ], "Title": "(from codeabbey) This code is supposed to add or multiply a bunch of numbers and at the end divide by a certain number and outpout the decimals" }
252784
<p>I was solving the following <a href="https://www.hackerrank.com/challenges/itertools-combinations/problem" rel="nofollow noreferrer">problem</a> on HackerRank.</p> <p>Here's my solution -</p> <pre><code>from itertools import combinations a = input() ls = list(map(str, a.split())) for i in range(1, int(ls[1])+1): ls2 = [] ls2 = list(map(&quot;&quot;.join, combinations(ls[0], i))) for elem in ls2: ls2[ls2.index(elem)] = &quot;&quot;.join(sorted(elem)) ls2.sort() for char in ls2: print(char) </code></pre> <p>But I feel it's not very efficient as it uses 2 Lists and 2 nested loops.</p> <p>Any suggestions as to how can I improve the code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T19:21:46.343", "Id": "498248", "Score": "1", "body": "In my experience, you should always avoid explicit loops when looking for performance. So that's never a bad first step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T04:05:12.503", "Id": "498267", "Score": "0", "body": "Understood thanks @Juho" } ]
[ { "body": "<p>Nice solution, these are my suggestions:</p>\n<ul>\n<li><strong>Parsing the input</strong>: in Python 3 the function <code>input</code> always returns a string, so the mapping can be removed. In Python 2, you can use <code>raw_input</code>.</li>\n<li><strong>Naming</strong>: <code>ls</code> is too generic. In this case, a suggestion is to take the names from the problem description. From:\n<pre><code>a = input()\nls = list(map(str, a.split()))\n</code></pre>\nTo:\n<pre><code>S, k = input().split()\n</code></pre>\n</li>\n<li><strong>Sort in advance</strong>: the problem requires to output the combinations in lexicographic sorted order. The <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"noreferrer\">doc</a> says:</li>\n</ul>\n<blockquote>\n<p>The combination tuples are emitted in lexicographic ordering according\nto the order of the input iterable. So, if the input iterable is\nsorted, the combination tuples will be produced in sorted order.</p>\n</blockquote>\n<p>So, instead of sorting each combination, it's enough sorting the input <code>S</code> at the beginning and all the combinations will be automatically sorted.</p>\n<ul>\n<li><strong>Use the output of</strong> <code>itertools.combinations</code>: the output of <code>itertools.combinations</code> is an iterable or tuples, which can be used in a for-loop to print the combinations one by one. The only change is to convert the tuple to a string, and can be done with <code>string.join</code>.</li>\n</ul>\n<h2>Revised code</h2>\n<pre><code>from itertools import combinations\n\nS, k = input().split()\nS_sorted = ''.join(sorted(S))\nfor i in range(1, int(k)+1):\n for c in combinations(S_sorted, i):\n print(''.join(c))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T16:25:24.863", "Id": "498240", "Score": "0", "body": "Thanks you for sharing this approach :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T16:06:40.160", "Id": "252788", "ParentId": "252786", "Score": "4" } } ]
{ "AcceptedAnswerId": "252788", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T14:57:07.127", "Id": "252786", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "HackerRank itertools.combinations()" }
252786
<p>Dears<br /> I have following component</p> <pre><code>import React from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { filterTransactionsByDates } from 'Utils/functions'; import {ReactComponent as BilanceIcon} from 'assets/icons/balanceDashboardIcon.svg'; import { ReactComponent as IncomeIcon } from 'assets/icons/incomeDashboardIcon.svg'; import { ReactComponent as SavingsIcon } from 'assets/icons/savingsDashboardIcon.svg'; import { ReactComponent as ExpensesIcon } from 'assets/icons/expensesDashboardIcon.svg'; import SingleSummaryField from 'components/UI/SingleSummaryField' const Wrapper = styled.div` width: 96%; height: 100%; display: flex; flex-flow: column; gap: 21px; ` const Row = styled.div` display: flex; flex-flow: row; gap: 21px; ` const BudgetSummary = ({ budgetSummary }) =&gt; { const {expensesSum, incomesSum, balance} = budgetSummary; return ( &lt;Wrapper&gt; &lt;Row&gt; &lt;SingleSummaryField amount={balance} name=&quot;Balance&quot;&gt; &lt;BilanceIcon /&gt; &lt;/SingleSummaryField&gt; &lt;SingleSummaryField amount={incomesSum} name=&quot;Income&quot;&gt; &lt;IncomeIcon /&gt; &lt;/SingleSummaryField&gt; &lt;/Row&gt; &lt;Row&gt; &lt;SingleSummaryField amount={1000} name=&quot;Savings&quot;&gt; &lt;SavingsIcon /&gt; &lt;/SingleSummaryField&gt; &lt;SingleSummaryField amount={0 - expensesSum} name=&quot;Expenses&quot;&gt; &lt;ExpensesIcon /&gt; &lt;/SingleSummaryField&gt; &lt;/Row&gt; &lt;/Wrapper&gt; ); }; BudgetSummary.propTypes = { budgetSummary: PropTypes.shape({ expensesSum: PropTypes.number.isRequired, incomesSum: PropTypes.number.isRequired, balance: PropTypes.number.isRequired, }), }; const getBudgetSummary = createSelector( (state) =&gt; state.expenses.expenses, (state) =&gt; state.incomes.incomes, (state) =&gt; state.datesRange.datesRange, (expenses, incomes, datesRange) =&gt; { const filteredExpenses = filterTransactionsByDates(expenses, datesRange); const filteredIncomes = filterTransactionsByDates(incomes, datesRange); const expensesSum = filteredExpenses.reduce((sum, currentTransaction) =&gt; { return sum + currentTransaction.amount; },0); const incomesSum = filteredIncomes.reduce((sum, currentTransaction) =&gt; { return sum + currentTransaction.amount; }, 0); const balance = incomesSum - expensesSum; return { expensesSum: expensesSum, incomesSum: incomesSum, balance: balance, }; } ) const mapState = (state) =&gt; { return { budgetSummary: getBudgetSummary(state) } } export default connect(mapState)(BudgetSummary); </code></pre> <p>What do you think about providing data to the component ? Do you think that method which is being used right now is fine or it would be better to separate the logic to some kind of container component or maybe shall I create separate component which will handle only js operations on data ?</p>
[]
[ { "body": "<p>Cześć Łukasz,</p>\n<p>I'd personally move some of the logic to the separate file. Eg. <code>getBudgedSummary</code>.That way, Your component will be more readable and easier to test.</p>\n<p>btw,\ninstead of <code>expensesSum: expensesSum</code>, You can simply go for <code>expensesSum</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T12:17:09.183", "Id": "252821", "ParentId": "252790", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T16:21:38.610", "Id": "252790", "Score": "1", "Tags": [ "javascript", "react.js", "jsx" ], "Title": "react component optimization" }
252790
<p>The problem says:</p> <blockquote> <p>You are given an array <em>a</em> of length 2<em>n</em>. Consider a partition of array <em>a</em> into two subsequences <em>p</em> and <em>q</em> of length <em>n</em> each (each element of array <em>a</em> should be in exactly one subsequence: either in <em>p</em> or in <em>q</em>).<br /> Let's sort <em>p</em> in non-decreasing order, and <em>q</em> in non-increasing order, we can denote the sorted versions by <em>x</em> and <em>y</em>, respectively. Then the cost of a partition is defined as <em>f(p,q)=∑i=1ⁿ|xi−yi|</em>.<br /> Find the sum of <em>f(p,q)</em> over all correct partitions of array <em>a</em>. Since the answer might be too big, print its remainder modulo 998244353.</p> <p>Input:<br /> The first line contains a single integer <em>n</em> (1≤<em>n</em>≤150000). The second line contains 2<em>n</em> integers <em>a1,a2,…,a2n</em> (1≤<em>ai</em>≤10^9) — elements of array <em>a</em>.</p> <p>Output:<br /> Print one integer — the answer to the problem, modulo 998244353.</p> </blockquote> <p>My solution generates all combinations of size <em>n</em> from <em>a</em>, then goes through each pair of combinations that complement each other, sorts them, and finally calculates the cost. Here is the code:</p> <pre><code>import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class Main { public static void main(String []args) { Scanner in = new Scanner(System.in); // reads the values int k = in.nextInt(); int[] input = new int[2 * k]; for (int i = 0; i &lt; 2 * k; i++) { input[i] = in.nextInt(); } List&lt;int[]&gt; combinations = new ArrayList(); int[] indices = new int[k]; //generates all valid combinations of size k, choosing k for(int i = 0; (indices[i] = i) &lt; k - 1; i++); combinations.add(getCombination(input, indices)); for (;;) { int i; for (i = k - 1; i &gt;= 0 &amp;&amp; indices[i] == input.length - k + i; i--); if (i &lt; 0) { break; } indices[i]++; for (++i; i &lt; k; i++) { indices[i] = indices[i - 1] + 1; } combinations.add(getCombination(input, indices)); } //for depugging //combinations.forEach(e -&gt; System.out.println(Arrays.toString(e))); //int[] temp1, temp2; //goes through all pairs that complement each other and calculates the cost for each int theSum = 0; for (int i = 0, j = combinations.size() - 1; i &lt; combinations.size() &amp;&amp; j &gt;= 0; i++, j--) { // temp1 = combinations.get(i); // temp2 = combinations.get(j); Arrays.sort(combinations.get(i)); Arrays.sort(combinations.get(j)); reverse(combinations.get(j)); //for debugging //System.out.println(Arrays.toString(temp1) + &quot;, &quot; + Arrays.toString(temp2)); theSum += cost(combinations.get(i), combinations.get(j)); } System.out.println(theSum % 998244353); } public static int[] getCombination(int[] input, int[] indices) { int[] result = new int[indices.length]; for (int i = 0; i &lt; indices.length; i++) result[i] = input[indices[i]]; return result; } public static int cost(int[] x, int[] y) { int sum = 0; for (int i = 0; i &lt; x.length; i++) { sum += Math.abs(x[i] - y[i]); } return sum; } public static void reverse(int[] array) { for(int i = 0; i &lt; array.length / 2; i++) { int temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } } } </code></pre> <p>The memory usage exceeded 512 MB and I don't know if I should change the data structures, or the algorithms, or both. I would appreciate any suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T20:54:27.353", "Id": "498254", "Score": "0", "body": "__Hint__. Sort the array. Prove (or at least convince yourself) that no matter what the partition is, the guys from the top half do not compete against each other. They always contribute with as `+`, and the guys from the bottom half alway contribute with `-`. I hope it is enough to come up with the fast solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T07:13:05.993", "Id": "498350", "Score": "0", "body": "Welcome to CodeReview@SE. Code indentation still is weird. You present `for`s controlling empty statements (`for(int i = 0; (indices[i] = i) < k - 1; i++);`, `for (i = k - 1; i >= 0 && indices[i] == input.length - k + i; i--);`) - most likely not what you intend." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T07:14:42.203", "Id": "498351", "Score": "0", "body": "To the best of your knowledge: Does the code presented work as intended? How did you establish confidence in it?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T19:08:48.500", "Id": "252793", "Score": "2", "Tags": [ "java" ], "Title": "Codeforces problem Java code optimization" }
252793
<p>I need to write a maximum function so that it finds that longest word in the Ternary Search Tree and prints it.</p> <p>This is what I have done so far. I have words in the tree such as &quot;canvas&quot;, &quot;cats&quot; &quot;van&quot; but it prints None any way.</p> <pre><code>def maximum(self): if self.root == None: return 0 ptr = self.root self.maxLengthTST(ptr) def maxLengthTST(self,ptr): if ptr.left == None: return if ptr.next == None: return if ptr.right == None: return return max(self.maxLengthTST(ptr.left), self.maxLengthTST(ptr.next)+1, self.maxLengthTST(ptr.right)); def max( a, b, c): max = 0 if a &gt;= b and a &gt;= c: max = a elif b &gt;= a and b &gt;= c: max = b else: max = c return max </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T21:58:14.700", "Id": "498256", "Score": "3", "body": "`maximum` does not return anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T23:59:24.393", "Id": "498261", "Score": "1", "body": "Welcome to Code Review! Unfortunately this question is _off-topic_ because this site is for reviewing **working** code. Please [take the tour](https://codereview.stackexchange.com/tour) and read up at our [help center](https://codereview.stackexchange.com/help/on-topic). When the code works then feel free to [edit] the post to include it for a review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T21:20:45.840", "Id": "252797", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Ternary Search Tree find max word" }
252797
<h2>Problem Statement</h2> <blockquote> <p>Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p> </blockquote> <p><a href="https://i.stack.imgur.com/qJvLp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qJvLp.png" alt="enter image description here" /></a></p> <pre><code>Example 1: Input: digits = &quot;23&quot; Output: [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;] Example 2: Input: digits = &quot;&quot; Output: [] Example 3: Input: digits = &quot;2&quot; Output: [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;] </code></pre> <h2>My Solution</h2> <p>A simple DFS based approach. Ignore some comments that are for my learning purposes (for similar problems to able to code it fast).</p> <pre><code>#include &lt;array&gt; #include &lt;string&gt; #include &lt;vector&gt; class Solution { private: // any auxilliary fields to help us (the &quot;fluff&quot; in the problem) std::array&lt;std::string_view, 10&gt; mappings = { &quot;0&quot;, &quot;1&quot;, &quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;, &quot;jkl&quot;, &quot;mno&quot;, &quot;pqrs&quot;, &quot;tuv&quot;, &quot;wxyz&quot;}; // note that 0 and 1 have the digits since // that makes the most sense // private functions that (may) do the heavy lifting std::string_view getLettersMapping(char digit) { return mappings[digit - '0']; } void dfs(std::vector&lt;std::string&gt; &amp;combinations, std::string_view digits, std::string &amp;s, size_t curr_idx, const size_t &amp;N) { // base case if (curr_idx == N) { // last digit's combination has already been explored, so simply append it // to our set of combinations and return combinations.push_back(s); return; } // determine current mapping digit auto letters = getLettersMapping(digits[curr_idx]); // for that particular digit, generate all the possible combinations by // recursing for each possible digit in the next index. for (const auto &amp;ch : letters) { // note that passing the string s by reference saves space, // but now we need to modify it by adding the letter and then removing the // latest added later after the recursive call s.push_back(ch); dfs(combinations, digits, s, curr_idx + 1, N); s.pop_back(); } } public: std::vector&lt;std::string&gt; letterCombinations(std::string digits) { // in the main function, we develop the answer, call the &quot;magic&quot; // recursion/DFS function, and return the answer std::vector&lt;std::string&gt; ans; if (digits.empty() || digits.size() == 0) { return ans; } std::string s; dfs(ans, digits, s, 0, digits.size()); return ans; } }; </code></pre> <hr /> <p>Any suggestions for my code? Also, I'm still learning the more &quot;modern&quot; features of C++ (anything from C++17 onwards), so any such advice would be very welcome :)</p>
[]
[ { "body": "<h1>Make <code>mappings</code> <code>static constexpr</code></h1>\n<p>This mapping should never be changed, so ideally it should be <code>constexpr</code>. You also need only one instance of it, so it should be marked <code>static</code> as well (also, <code>constexpr</code> requires this). So:</p>\n<pre><code>static constexpr std::array&lt;const std::string_view, 10&gt; mappings = {\n ...\n};\n</code></pre>\n<p>This also means <code>getLetterMappings()</code> can be made <code>static constexpr</code>, and in fact you can make <code>dfs()</code> <code>static constexpr</code> as well, although the <code>constexpr</code> part doesn't do much there.</p>\n<h1>Redundant check for empty input</h1>\n<p>Why do you check both <code>digits.empty()</code> and <code>digits.size() == 0</code>? Those expressions are equivalent. I would just check for <code>digits.empty()</code>.</p>\n<h1>Unnecessary parameters <code>curr_idx</code> and <code>N</code></h1>\n<p>Since you are passing the input digits to <code>dfs()</code> as a <code>std::string_view</code> by value, you don't need the parameters <code>curr_idx</code> and <code>N</code>. Just pass a modified version of <code>digits</code> to recursive calls to <code>dfs()</code>, like so:</p>\n<pre><code>void dfs(std::vector&lt;std::string&gt; &amp;combinations, std::string_view digits, std::string &amp;s) {\n if (digits.empty()) {\n combinations.push_back(s);\n return;\n }\n\n auto letters = getLettersMapping(digits.front());\n\n for (const auto &amp;ch : letters) {\n s.push_back(ch);\n dfs(combinations, digits.substr(1), s);\n s.pop_back();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T13:31:24.723", "Id": "252823", "ParentId": "252798", "Score": "3" } } ]
{ "AcceptedAnswerId": "252823", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T22:39:05.180", "Id": "252798", "Score": "4", "Tags": [ "c++" ], "Title": "Leetcode 17 : Letter Combinations of a Phone Number" }
252798
<p>I am new to programming / <code>R</code> and new to writing <code>functions</code>. I am working through the book <code>R for Data Science</code> and am on the following exercise:</p> <p><code>Implement your own version of every() using a for loop.</code></p> <p>In case you're unaware, the <code>every</code> function from <code>purrr</code> does the following:</p> <p><code>Do every element of a list satisfy a predicate?</code></p> <p>Here is the function I came up with:</p> <pre><code>every_2 &lt;- function(x, fun) { output &lt;- vector(&quot;logical&quot;, length(x)) output2 &lt;- vector(&quot;logical&quot;, length = 1L) for (i in seq_along(x)) { output[[i]] &lt;- fun(x[[i]]) if (sum(output) &lt; length(output)){ output2 &lt;- FALSE } else { output2 &lt;- TRUE } } output2 } </code></pre> <p>Using the following numeric vector:</p> <pre><code>test_vec &lt;- 1:100 </code></pre> <p>The output matches that of the original <code>every</code> function.</p> <pre><code>every(test_vec, function(x) {x &gt; 0}) # TRUE every(test_vec, function(x) {x &gt; 100}) # FALSE every(test_vec, is.character) # FALSE every(test_vec, is.numeric) # TRUE every_2(test_vec, function (x) {x &gt; 0}) # TRUE every_2(test_vec, function(x) {x &gt; 100}) # FALSE every_2(test_vec, is.character) # FALSE every_2(test_vec, is.numeric) # TRUE </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T22:47:11.043", "Id": "252799", "Score": "2", "Tags": [ "beginner", "r" ], "Title": "Implemented my own version of every() from {purrr}" }
252799
<p>I am trying to implement the Euler–Maruyama method and use it to solve the Ornstein–Uhlenbeck process. I am basing my code on the <a href="https://en.wikipedia.org/wiki/Euler%E2%80%93Maruyama_method" rel="noreferrer">wikipedia page</a> where a python implementation is shown. More generally I'm trying to get to grips with stochastic differential equations in c++.</p> <p>This is my code</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;random&gt; #include &lt;vector&gt; #include &lt;cmath&gt; using namespace std; int num_sims = 5; double t_init = 3; double t_end = 7; int N = 1000; float dt = (float)(t_end - t_init) / N; double y_init = 0; double c_theta = 0.7; double c_mu = 1.5; double c_sigma = 0.06; double dW ( double dt ){ normal_distribution&lt;double&gt; distribution( dt , sqrt(dt) ); random_device rd; default_random_engine generator(rd()); return distribution(generator); } double mu( double y, double t ){ return c_theta * (c_mu - y); } int main() { vector&lt;double&gt; ts; for (double t = t_init; t &lt; t_end + dt; t += dt){ ts.push_back(t); } vector&lt;double&gt; ys(N+1, 0); ys[0] = y_init; for (int h = 0; h &lt; num_sims; h+=1){ for (int i = 1; i &lt; ts.size(); i+=1 ){ double t = (i - 1) * dt; double y = ys[i - 1]; ys[i] = y + mu(y, t) * dt + c_sigma * dW(dt); cout &lt;&lt; h &lt;&lt; '\t' &lt;&lt; ys[i] &lt;&lt; endl; } } return 0; } </code></pre> <p>This code seems to work well when I plot the results in python. My question is if this code can be written in a more efficient way? I feel like I should be using the boost packages on some level, and also maybe structures. I'm quite new to c++, so maybe my translation of the python code is a bit too word for word.</p>
[]
[ { "body": "<h1>Make constants <code>constexpr</code></h1>\n<p>You can tell C++ that some of your variables are constast by marking them <code>const</code>. If the constants can be computed at compile time, you can even mark them <code>constexpr</code>. Doing this helps the compiler generated more optimal code and will result in an error if you accidentily do try to modify a constant. So:</p>\n<pre><code>constexpr int num_sims = 5;\nconstexpr double t_init = 3.0;\n...\n</code></pre>\n<h1>Mark variables and functions <code>static</code> where appropriate</h1>\n<p>If a variable or function is not used by any other source files, you should mark them <code>static</code>. This again might help the compiler produce more efficient code, and can prevent conflicts with other variables and functions with identical names in other source files in your project. It looks like everything except <code>main()</code> can be made <code>static</code>.</p>\n<h1>Optimize random number generation</h1>\n<p>You are using the right functions to create normal distributed random numbers, but the way you have written it, it will instantiate a new distribution, random device and generator for each call to <code>dW()</code>. You only need to create them once. To do this, move everything except the return statement out of the function (and make them static):</p>\n<pre><code>static normal_distribution&lt;double&gt; distribution(dt, sqrt(dt));\nstatic random_device rd;\nstatic default_random_engine generator(rd());\n\nstatic double dW(double dt) {\n return distribution(generator);\n}\n</code></pre>\n<h1>Use <code>N</code> consistently</h1>\n<p>You created a constant for the number of datapoints you are generating. Once you have done that, use it consistently everywhere. Don't start mixing <code>N</code>, <code>ts.size()</code> and other ways to calculate the size of the array, since this might result in slight differences that will cause problems. For example, floating point values have a limited precision, and because of that the following <code>for</code>-loop might actually run more or less than <code>N</code> iterations:</p>\n<pre><code>for (double t = t_init; t &lt; t_end + dt; t += dt) {\n</code></pre>\n<p>Use <code>N</code> consistently:</p>\n<pre><code>for (int i = 0; i &lt; N; ++i) {\n ts.push_back(t_init + i * dt);\n}\n\n...\n\nfor (int h = 0; h &lt; num_sims; ++h) {\n for (int i = 1; i &lt; N; ++i) {\n ...\n</code></pre>\n<p>Alternatively, you could also use <code>ts.size()</code> everywhere, as long as you are consistent. In that case, the line to change is:</p>\n<pre><code>vector&lt;double&gt; ys(ts.size());\n</code></pre>\n<p>Note that <code>ys</code> doesn't need to be one larger than <code>ts</code>, and you don't need to initialize it with zeroes, as you will overwrite all values anyway.</p>\n<h1>Use <code>++</code> to increment counters</h1>\n<p>It's customary in C and C++ to use the <code>++</code> and <code>--</code> operators to increment and decrement counters. And since it can give a slight performance benefit in some cases, prefer to use the prefix version to the postfix version if there is no difference to the result. So:</p>\n<pre><code>for (int i = ...; ...; ++i)\n</code></pre>\n<h1>Avoid using <code>std::endl</code></h1>\n<p>You should <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">avoid using <code>std::endl</code></a> and use <code>'\\n'</code> instead. The former is equivalent to the latter, but it will also force a flush of the output, which is often unnecessary and might slow down your application.</p>\n<h1>Do you need <code>std::vector</code>s at all?</h1>\n<p>You are storing the time and y-coordinates of the datapoints in the vectors <code>ts</code> and <code>ys</code>, but you never read them back. The only thing you use is the value of <code>y</code> of the previous timestep, but this could easily be held in a single variable:</p>\n<pre><code>int main() {\n for (int h = 0; h &lt; num_sims; ++h) {\n double y = y_init;\n\n for (int i = 0; i &lt; N; ++i) {\n double t = i * dt;\n y += mu(y, t) * dt + c_sigma * dW(dt);\n cout &lt;&lt; h &lt;&lt; '\\t' &lt;&lt; y &lt;&lt; '\\n';\n }\n }\n}\n</code></pre>\n<h1>Avoid unnecessary complexity</h1>\n<blockquote>\n<p>I feel like I should be using the boost packages on some level, and also maybe structures.</p>\n</blockquote>\n<p>This problem absolutely doesn't need Boost packages nor <code>struct</code>s. Follow the <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS principle</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T10:34:09.077", "Id": "252814", "ParentId": "252800", "Score": "5" } } ]
{ "AcceptedAnswerId": "252814", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-28T23:18:09.747", "Id": "252800", "Score": "5", "Tags": [ "c++", "random", "c++14", "numerical-methods" ], "Title": "Using Euler-Maruyama method to solve Ornstein-Uhlenbeck equation (SDE)" }
252800
<p>I am trying to get a signal name to print when getting a signal number. I actually have :</p> <pre><code>char* getsig(int sig){ switch (sig) { case SIGKILL: return &quot;SIGKILL&quot;; case SIGSTOP: return &quot;SIGSTOP&quot;; case SIGTERM: return &quot;SIGTERM&quot;; case SIGTRAP: return &quot;SIGTRAP&quot;; case SIGABRT: return &quot;SIGABRT&quot;; case SIGALRM: return &quot;SIGALARM&quot;; case SIGSEGV: return &quot;SIGSEGV&quot;; case SIGQUIT: return &quot;SIGQUIT&quot;; case SIGINT: return &quot;SIGINT&quot;; case SIGCHLD: return &quot;SIGCHLD&quot;; case SIGCONT: return &quot;SIGCONT&quot;; case SIGPIPE: return &quot;SIGPIPE&quot;; case SIGFPE: return &quot;SIGFPE&quot;; case SIGILL: return &quot;SIGILL&quot;; case 0: return &quot;[NO SIGNAL TO DELIVER]&quot;; default: return &quot;UNKN&quot;; } } </code></pre> <p>I can see that this is wrong : I have no certitude that those char* names will be stored in data section on every compiler. I am certain that there is a clean way of doing such a thing, but I cannot find it on the internet. Do anyone has an idea of how I could do this task the beautiful way?</p> <h3>Edit</h3> <p>The final aim is to print a potential signal delivered by a <code>ptrace(PTRACE_CONT, ...);</code> call, e.g: <code>printf(&quot;ptrace(PTRACE_CONT); [delivered %s]\n&quot;, getsig(data));</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T04:55:39.947", "Id": "498268", "Score": "1", "body": "https://stackoverflow.com/a/55511300/10281456" } ]
[ { "body": "<p>The way to do this in C is to define an array, and use designated array initializers to ensure the correct mapping between number and string, like so:</p>\n<pre><code>static const char *signames[] = {\n [SIGKILL] = &quot;SIGKILL&quot;,\n [SIGSTOP] = &quot;SIGSTOP&quot;,\n ...\n [0] = &quot;[NO SIGNAL TO DELIVER]&quot;,\n};\n\nconst char *getsig(int sig) {\n if (sig &lt; 0 || sig &gt;= sizeof(signames) / sizeof(*signames) || !signames[sig])\n return &quot;UNKN&quot;;\n\n return signames[sig];\n}\n</code></pre>\n<p>Note that it is hard to make this portable; the list of available signals varies by operating system, and some don't even have the concept of signals. Some operating systems and/or standard libraries might already have some function to convert signal numbers to strings, if you target a specific platform and don't care about compatibility, you might consider using that.</p>\n<p>Note that <a href=\"https://man7.org/linux/man-pages/man3/strsignal.3.html\" rel=\"nofollow noreferrer\"><code>strsignal()</code></a> should be available on any POSIX platform, although it gives you a more human readable string like &quot;Killed&quot; instead of &quot;SIGKILL&quot;.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T13:49:53.083", "Id": "252825", "ParentId": "252802", "Score": "4" } } ]
{ "AcceptedAnswerId": "252825", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T01:36:28.933", "Id": "252802", "Score": "4", "Tags": [ "c", "linux", "signal-processing" ], "Title": "Get signal name from signal number" }
252802
<p>Here is some code I wrote to add, remove, and change user names and passwords in .htpasswd with PHP:</p> <pre><code>function adduser($user, $pass) { try { $htpasswd = '.htpasswd'; //$hash = '{SHA}'.crypt($pass, base64_encode($pass)); $hash = crypt_apr1_md5($pass); //APR1-MD5 $contents = $user . ':' . $hash; $lines = explode(PHP_EOL, file_get_contents($htpasswd)); // get .htpasswd print('&lt;h4&gt;input:&lt;/h4&gt;&lt;pre&gt;'.print_r(implode(PHP_EOL, $lines),true).'&lt;/pre&gt;'); $exists = false; foreach($lines as $line){ $existing_user = explode( ':', $line ); if ($existing_user[0] == $user) { //checks if user exists $contents = str_replace($line, $contents, $lines); //changes password for user $contents = implode(PHP_EOL, $contents); $exists = true; if ($pass == '') { // removes user if password is empty $contents = str_replace($line, '', $lines); //removes user $contents = array_filter($contents); // cleans empty space in array $contents = implode(PHP_EOL, $contents); $exists = true; } } } if ($exists == false) { $contents = implode(PHP_EOL, $lines) . PHP_EOL . $contents; } file_put_contents($htpasswd, $contents); print('&lt;h4&gt;output:&lt;/h4&gt;&lt;pre&gt;'.print_r($contents,true).'&lt;/pre&gt;'); }catch(Exception $e) { echo '&lt;h3&gt;fail: &lt;/h3&gt;' . $e-&gt;getMessage(); } } if(isset($_GET['user'])){ adduser($_GET['user'], $_GET['pass']); echo '&lt;h3&gt;success&lt;/h3&gt;'; }else{ $htpasswd = '.htpasswd'; $lines = explode(PHP_EOL, file_get_contents($htpasswd)); // get .htpasswd print('&lt;h4&gt;.htpasswd:&lt;/h4&gt;&lt;pre&gt;'.print_r(implode(PHP_EOL, $lines),true).'&lt;/pre&gt;'); echo '&lt;h3&gt;no user set&lt;/h3&gt;'; } </code></pre> <p>I would love to streamline it and clean it up.</p>
[]
[ { "body": "<p>For the sake of your code and mine, I hope that the usernames cannot contain any colons since that is the delimiting character between usernames and passwords!</p>\n<p>I have a bias toward regex because I have a fair handle on it and I enjoy the utility and brevity that it affords my scripts. I also don't (personally) enjoy all of the imploding and exploding going on in your script.</p>\n<p>The search pattern is the same for cases of deleting and updating -- only the replacement text is changed. My search pattern will look for an <strong>optional</strong> leading newline character/sequence with <code>\\R</code>, then search for an identical match of the username followed by a colon, then match the remainder of the line of text. This line-consuming pattern means that if replacing with an empty string, then there will be no blank line in the file; alternatively, if updating, then a leading EOL character/sequence will be prepended (don't worry, I <code>ltrim()</code> later).</p>\n<p>The single <code>preg_replace()</code> call will record the number of replacements that it makes. The number will be either 0 or 1 since the fourth parameter limits the replacements to 1 anyhow. If there were no replacements made, then logically we know that a new line is to be appended to the end of the file.</p>\n<p>At the end of the custom function, I am going the extra step of returning the action that was successfully undertaken. The will give better information in the output.</p>\n<p><code>isset()</code> can receive multiple arguments, so I added the pass element as well since it is expected with the submission.</p>\n<p>I am using <code>printf()</code> to output the mix of literal and dynamic text -- I find that it helps to make the code more readable.</p>\n<p>Untested Code:</p>\n<pre><code>function editHtpasswordRow(string $user, string $pass): string\n{\n $file = '.htpasswd';\n if ($pass === '') {\n $newRow = '';\n $action = 'Delete';\n } else {\n $newRow = PHP_EOL . $user . ':' . crypt_apr1_md5($pass);\n $action = 'Update';\n }\n\n $content = preg_replace(\n '/\\R?^' . preg_quote($user, '/') . ':.*/mu',\n $newRow,\n file_get_contents($file),\n 1,\n $count\n );\n\n if (!$count &amp;&amp; $newRow) {\n $content .= PHP_EOL . $newRow;\n $action = 'Insert';\n }\n file_put_contents($file, ltrim($content));\n return $action;\n}\n\nif (isset($_POST['user'], $_POST['pass'])) {\n printf(\n '&lt;h3&gt;%s of %s was successful&lt;/h3&gt;',\n editHtpasswordRow($_POST['user'], $_POST['pass']), \n htmlspecialchars($_POST['user'])\n );\n} else {\n echo '&lt;h4&gt;Fetched .htpasswd content:&lt;/h4&gt;&lt;pre&gt;' . file_get_contents('.htpasswd') . '&lt;/pre&gt;';\n}\n</code></pre>\n<hr />\n<p>Edit: I missed something that YourCommonSense spotted... You should be using <code>$_POST</code> when writing to the filesystem. <code>$_GET</code> is for reading and <code>$_POST</code> is for writing. I'll update my snippet now, +1 his post, and advise you to use his html form.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T12:15:14.437", "Id": "252820", "ParentId": "252804", "Score": "2" } }, { "body": "<p>Here is my version based on two personal preferences: I hate scroll bars and I hate repititions. Hence I prefer everything typed once and also I like my code being fully visible in the default code area on Stack Overflow.</p>\n<ul>\n<li>for this reason I removed that double spacing which just hurts my eyes</li>\n<li>also I removed the try catch which is a cargo cult code that makes no sense. I was never able to understand what's the point in writing a try catch that's the only job is to echo the error message when without a try catch PHP will do exactly the same - echo the error message</li>\n<li>also I removed the code repetitions such as mentioning the filename in a dozen places</li>\n<li>also I changed the algorithm, to make it add a user line only once</li>\n<li>I also removed that uncertainty when we can't make our mind whether we are working with an array or with a text</li>\n<li>I also changed the function name as it doesn't only add a user</li>\n<li>and some other improvements such as following the HTTP guidelines and the ability to choose the hashing algorithm without using inline comments</li>\n</ul>\n<p>here it goes</p>\n<pre><code>&lt;?php\n$filename = &quot;.htpasswd&quot;;\nif (isset($_POST['user'])) {\n manage_htpasswd($_POST['user'], $_POST['pass'], $filename);\n header(&quot;Location: &quot;.$_SERVER['REQUEST_URI']);\n exit;\n}\nfunction manage_htpasswd($user, $pass, $filename, $algo = 'crypt_apr1_md5')\n{\n $lines = file($filename);\n foreach ($lines as $i =&gt; $line) {\n $existing_user = explode(':', $line);\n if ($existing_user[0] === $user) {\n unset($lines[$i]);\n break;\n }\n }\n if ($pass) {\n $lines[] = &quot;$user:&quot; . $algo($pass) . PHP_EOL;\n }\n file_put_contents($filename, $lines);\n}\n?&gt;\n&lt;form method=&quot;post&quot;&gt;\n User: &lt;input type=&quot;text&quot; name=&quot;user&quot;&gt;&lt;br&gt;\n Pass:&lt;input type=&quot;text&quot; name=&quot;pass&quot;&gt;&lt;br&gt;\n &lt;input type=&quot;submit&quot;&gt;\n&lt;/form&gt;\n&lt;h4&gt;&lt;?= $filename ?&gt;:&lt;/h4&gt;\n&lt;pre&gt;\n&lt;?= file_get_contents($filename) ?&gt;\n&lt;/pre&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T04:08:54.193", "Id": "498340", "Score": "0", "body": "So instead of updating a row, you delete it then append it to the end of the file. Fair enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T04:10:38.627", "Id": "498341", "Score": "1", "body": "@mickmackusa yeah I was thinking how to get rid of that found/not found business :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T04:15:33.837", "Id": "498342", "Score": "0", "body": "I think I like your non-regex versus my regex technique. Perhaps use `strstr()` with a `true` param instead of exploding to create `$existing_user` from an array (this way you don't even need to declare the variable). Your snippet is still making iterated function calls, but it does return early -- looks pretty clean to me and built with flexibility in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T01:58:17.797", "Id": "498658", "Score": "0", "body": "$lines[] = \"$user:\" . $algo($pass); doesn't create a new line. It needs to be: $lines[] = \"$user:\" . $algo($pass) . PHP_EOL; no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T04:21:58.523", "Id": "498669", "Score": "0", "body": "@tony surely it does. Like I said, we need to move from that uncertainty, whether we are working with array or text. In favor of arrays. And [] in terms of arrays is exactly that: a new line" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:02:07.427", "Id": "498674", "Score": "0", "body": "@YourCommonSense - it's not creating a new line on my end when I use it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:07:58.593", "Id": "498675", "Score": "0", "body": "@tony but how does it look? what new line you are talking about? An empty line after the new line? but why would you need that empty line? Your PHP_EOL adds an **empty** line *after* the new line with a user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:22:20.787", "Id": "498676", "Score": "0", "body": "@YourCommonSense - https://imgur.com/a/xSnqL8C user1, 2, 3 were added using my code, newuser4, 5, 6 were added using your code. It is not possible to remove them this way either. Adding . PHP_EOL; fixes this problem, but as you said, we want to get away from that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:31:31.827", "Id": "498679", "Score": "1", "body": "@tony wait. indeed it does that. let me check" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:37:46.263", "Id": "498681", "Score": "1", "body": "@tony I beg my pardon. yes, my bad. there must be a PHP_EOL. So, when we are moving from a text to an array, every line in this array holds a new line symbol. when file_put_contents converts an array back to text, it just glues all the lines together. if a line holds a new line symbol, then the next one occurs on the new line. But once the line doesn't have a new line at the end, then the next line is glued to it. So every line should have a new line at the end. Means we have to add it to the new line." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T17:23:11.927", "Id": "252829", "ParentId": "252804", "Score": "3" } } ]
{ "AcceptedAnswerId": "252829", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T03:07:32.310", "Id": "252804", "Score": "4", "Tags": [ "php", "file-system", "crud", ".htaccess" ], "Title": "Adding, removing, and changing user names and passwords in .htpasswd with PHP" }
252804
<p>I used <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow noreferrer">ANSI escape code</a> for printing colorful text to the terminal.</p> <p>How can I improve it in any way with regard to OOP, programming style, and if there's a better and concise way to write any of the functions?</p> <h2>Directory Tree:</h2> <p>I named it <em>cerminal</em> :p as in colorful terminal.</p> <pre><code>cerminal/ ├── __init__.py ├── util.py ├── colors.py </code></pre> <h1>Code</h1> <ul> <li><h3><code>__init__.py</code></h3> <pre class="lang-py prettyprint-override"><code>from cerminal.colors import BackgroundColor, FontColor, FontStyle from cerminal.utils import cprint, get_color_codes </code></pre> </li> <li><h3><code>colors.py</code></h3> <pre class="lang-py prettyprint-override"><code>type_error = &quot;Expected an int or str type but given {} type&quot; def _condition_for_int(color): return (isinstance(color, int) and (color &gt;= 0 and color &lt; 256)) or ( color.isnumeric() and (int(color) &gt;= 0 and int(color) &lt; 256) ) class Color: accepted_color_alias = { &quot;black&quot;, &quot;red&quot;, &quot;green&quot;, &quot;yellow&quot;, &quot;blue&quot;, &quot;magenta&quot;, &quot;cyan&quot;, &quot;white&quot;, } RESET = &quot;\033[0m&quot; class FontColor(Color): &quot;&quot;&quot; Font color class &quot;&quot;&quot; black = &quot;\033[30m&quot; red = &quot;\033[31m&quot; green = &quot;\033[32m&quot; yellow = &quot;\033[33m&quot; blue = &quot;\033[34m&quot; magenta = &quot;\033[35m&quot; cyan = &quot;\033[36m&quot; white = &quot;\033[37m&quot; @classmethod def get_color(self, color, value=&quot;&quot;, add_reset=True): if not isinstance(color, (int, str)): raise TypeError(type_error.format(type(color).__name__)) _reset = self.RESET * add_reset if _condition_for_int(color): return &quot;\033[38;5;{}m{}{}&quot;.format(color, value, _reset) if color not in self.accepted_color_alias: raise ValueError(&quot;Unknown color given {}&quot;.format(color)) return getattr(self, color) + str(value) + _reset class BackgroundColor(Color): &quot;&quot;&quot; Background colors class &quot;&quot;&quot; black = &quot;\033[40m&quot; red = &quot;\033[41m&quot; green = &quot;\033[42m&quot; yellow = &quot;\033[43m&quot; blue = &quot;\033[44m&quot; magenta = &quot;\033[45m&quot; cyan = &quot;\033[46m&quot; white = &quot;\033[47m&quot; @classmethod def get_color(self, color, value, add_reset=True): if not isinstance(color, (int, str)): raise TypeError(type_error.format(type(color).__name__)) _reset = self.RESET * add_reset if _condition_for_int(color): return &quot;\033[48;5;{}m{}{}&quot;.format(color, value, _reset) if color not in self.accepted_color_alias: raise ValueError(&quot;Unknown color given {}&quot;.format(color)) return getattr(self, color) + str(value) + _reset class FontStyle(Color): &quot;&quot;&quot; Font style class &quot;&quot;&quot; bold = &quot;\033[1m&quot; italic = &quot;\033[3m&quot; underline = &quot;\033[4m&quot; @classmethod def get_style(self, style, value=&quot;&quot;, add_reset=True): if not isinstance(value, str): raise TypeError(&quot;Only str type allowed&quot;) return getattr(self, style) + value + self.RESET * add_reset #s = f'{FontColor.get_color(&quot;red&quot;, &quot;STOP&quot;)} {BackgroundColor.get_color(&quot;cyan&quot;, &quot;danger&quot;)}' # print(s) # print(FontStyle.get_style('underline', 'HEllO')) </code></pre> <p>Output from the commented lines at the end of the file          <img src="https://i.stack.imgur.com/5hycp.png" width="500" height="100" /></p> </li> <li><h3><code>utils.py</code></h3> <pre class="lang-py prettyprint-override"><code>from colors import Color, FontStyle, FontColor, BackgroundColor import sys from time import sleep def cprint( text, color=None, background=None, bold=False, italic=False, underline=False, end=&quot;\n&quot;, ): &quot;&quot;&quot; prints the given text to stdout with color `color` and `background` resets back to normal after printing. Supported colors are 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'. &quot;&quot;&quot; _reset = Color.RESET bg = &quot;&quot; if background is None else _set_background(background) font_color = &quot;&quot; if color is None else _set_color(color) font_style = _set_font_style(bold=bold, italic=italic, underline=underline) output_style = bg + font_color + font_style sys.stdout.write(output_style) sys.stdout.write(text) sys.stdout.write(_reset + end) def _set_color(color): &quot;&quot;&quot; For setting color of the cursor with `color`. Accepted colors alias are 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'. Can also gives an values between 0 to 255. Check `get_color_codes()` for more info. &quot;&quot;&quot; return FontColor.get_color(color, add_reset=False) def _set_background(color): &quot;&quot;&quot; Returns the background of the cursor with color `color` ansi esacape code. Accepted colors alias are 'black', 'red', 'green','yellow', 'blue', 'magenta', 'cyan', 'white'. Can also gives an values between 0 to 255. &quot;&quot;&quot; return BackgroundColor.get_color(color, add_reset=False) def _set_font_style(**styles): return &quot;&quot;.join( [ FontStyle.get_style(style, add_reset=False) for style, cond in styles.items() if cond ] ) def get_color_codes(animation=False, background=False): &quot;&quot;&quot; prints color codes in it's respective color, used for visual reference. &quot;&quot;&quot; ansi_code = &quot;\033[48;5;{}m{}&quot; if background else &quot;\033[38;5;{}m{}&quot; v = 0.1 if animation else 0 for i in range(32): for j in range(8): sleep(v) code = str(i * 8 + j) sys.stdout.write(ansi_code.format(code, code.ljust(4))) sys.stdout.write(&quot;\033[0m&quot;) sys.stdout.write(&quot;\n&quot;) #cprint(&quot;hello world&quot;, color=&quot;123&quot;, bold=True, italic=True) # get_color_codes(background=True) </code></pre> <p>The output from commented lines at the end of the file</p> </li> </ul> <p>             <img src="https://i.stack.imgur.com/Pq6sr.png" width="200" height="350"/></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T06:24:40.980", "Id": "498346", "Score": "0", "body": "What do you expect in a review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T06:43:44.747", "Id": "498347", "Score": "0", "body": "How can I improve it in any way with regard to OOP, programming style, and if there's a better and concise way to write any of the functions. @AryanParekh" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T06:56:58.497", "Id": "498348", "Score": "0", "body": "You can [edit] your question and add that, it helps reviewers :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T07:00:36.700", "Id": "498349", "Score": "0", "body": "@AryanParekh Edited the question. Sorry new to codereview. Thank you." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T06:09:45.670", "Id": "252808", "Score": "0", "Tags": [ "python" ], "Title": "Printing colourful text to terminal" }
252808
<p>Assume we are given a <code>number</code> and a <strong>prime</strong> <code>p</code>. The goal is to count all <em>subnumbers</em> of <code>number</code> that are divisible by <code>p</code>. A <em>subnumber</em> of <code>number</code> is formed of any number of consecutive digits in the decimal representation of <code>number</code>. Here is my solution:</p> <pre class="lang-py prettyprint-override"><code>number = input() p = int(input()) print([int(number[i : j]) % p for i in range(len(number)) for j in range(i + 1, len(number) + 1)].count(0)) </code></pre> <p>Can this solution be made faster?</p> <p><a href="https://quera.ir/problemset/contest/6398/%D8%B9%D8%AF%D8%AF%20%D8%AF%D8%B1%20%D8%B9%D8%AF%D8%AF" rel="nofollow noreferrer">Here</a> is the original source of the problem.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T10:34:13.080", "Id": "498277", "Score": "0", "body": "If this is a programming challenge, you can add the `programming-challenge` tag" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T12:14:54.580", "Id": "498291", "Score": "0", "body": "Thanks. Should be in the question, I did that already. Please also add the problem limits there. I'd have to rely on Google's translation to get it right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T09:59:12.297", "Id": "502593", "Score": "1", "body": "I think you should mention that the length of the string is about 10^6 and the size of p is about 10^9" } ]
[ { "body": "<p>Let <span class=\"math-container\">\\$N_{i,j}\\$</span> be the subnumber of <span class=\"math-container\">\\$N\\$</span> from the <span class=\"math-container\">\\$i\\$</span>th digit (excluded) to the <span class=\"math-container\">\\$j\\$</span>th digit (included). Here, the first digit is the least significant one.</p>\n<p>Let <span class=\"math-container\">\\$R_i = N \\bmod 10^i \\$</span>. We have <span class=\"math-container\">\\$R_j-R_i=N_{i,j} * 10^i, 0\\leq i &lt; j \\leq D(N)\\$</span>, where <span class=\"math-container\">\\$D(N)\\$</span> is the number of digits in <span class=\"math-container\">\\$N\\$</span>. There are two cases.</p>\n<ul>\n<li>If <span class=\"math-container\">\\$p \\nmid 10\\$</span>, then\n<span class=\"math-container\">$$p \\mid N_{i,j} \\Leftrightarrow p\\mid N_{i,j} * 10^i \\Leftrightarrow p\\mid R_j-R_i \\Leftrightarrow R_j \\equiv R_i \\pmod{p}$$</span></li>\n</ul>\n<p>In this case, we can compute <span class=\"math-container\">\\$R_i\\bmod p\\$</span> for all <span class=\"math-container\">\\$i=0,\\ldots,D(N)\\$</span>, group them by values, count the number of pairs in each group and then take the sum. (Note: the implementation can simply count the size of each group <span class=\"math-container\">\\$|G|\\$</span> using <code>itertools.Counter</code> and compute the number of pairs <span class=\"math-container\">\\$C_{|G|}^2\\$</span>)</p>\n<ul>\n<li>If <span class=\"math-container\">\\$p\\mid 10\\$</span>, we have either <span class=\"math-container\">\\$p = 2\\$</span> or <span class=\"math-container\">\\$p = 5\\$</span>. In this case,\n<span class=\"math-container\">$$p \\mid N_{i,j} \\Leftrightarrow p \\mid N_{i+1} $$</span>\nHere, <span class=\"math-container\">\\$N_{i+1}\\$</span> is the <span class=\"math-container\">\\$(i+1)\\$</span>th digit of <span class=\"math-container\">\\$N\\$</span>. In other words, if <span class=\"math-container\">\\$p \\mid N_{i+1} \\$</span> holds, <span class=\"math-container\">\\$p \\mid N_{i,j}\\$</span> holds for all <span class=\"math-container\">\\$j\\$</span> s.t. <span class=\"math-container\">\\$i&lt;j\\leq D(N)\\$</span>. It is easy to show that the final result is\n<span class=\"math-container\">$$\\sum_{0\\leq i &lt; D(N),\\,p\\,\\mid\\, N_{i+1}}(D(N)-i)$$</span></li>\n</ul>\n<p>The time complexity of this algorithm is <span class=\"math-container\">\\$\\Theta(D(N))=\\Theta(\\log N)\\$</span>, which is better than the <span class=\"math-container\">\\$\\Theta(D(N)^4)\\$</span> solution in OP (see comments for explanation). Note that the runtime of the actual program depends on your implementation.</p>\n<p>You may try to implement this approach yourself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T07:54:18.303", "Id": "498354", "Score": "0", "body": "@GZ0 Although I know what you mean, completely, but my goal is to correct everything here. Consider \\$ N = 123456 \\$. Now what are \\$ R_{3} \\$, \\$ R_{6} \\$ and \\$ N_{36}\\$? I think we should assume another identity when both \\$ i \\$ and \\$ j \\$ are greater than or equal to \\$ D(N) \\$. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T08:23:10.467", "Id": "498359", "Score": "0", "body": "@MohammadAliNematollahi I slightly updated the notations and text to avoid potential confusions. As defined in my post, \\$R_3 = N \\bmod 10^3 = 456, R_6 = N \\bmod 10^6 = 123456, N_{3,6}=123\\$. \\$R_i\\$ is the last \\$i\\$ digits. \\$N_{3,6}\\$ is the 3rd (excluded) to 6th digit (included), starting from the right side of \\$N\\$ (note that the indexing starts with 1). So \\$j\\$ can be equal to \\$D(N)\\$. For this problem, we only need to consider \\$i, j\\$ such that \\$0\\leq i < j \\leq D(N)\\$ in the notation \\$N_{i,j}\\$. The other cases are not of our interest here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T13:04:31.030", "Id": "498465", "Score": "0", "body": "GZ0 I changed my code due to your instructions. Now, it passes more tests but yet there are several tests with \"time limit exceeded\" error. Where can I put my code in order to be checked by you... Thanks in advance..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T09:30:48.130", "Id": "498689", "Score": "0", "body": "You can create a follow-up post and refer to this one. Meanwhile, @superbrain had implemented this (not sure why our previous exchanges in the comments were gone) so he should be able to help you as well. I think the most important aspect is the computation of \\$R_i \\bmod p\\$. You need to do it incrementally rather than computing from scratch (so that the time complexity of each computation is \\$\\Theta(1)\\$, not \\$\\Theta(D(n))\\$)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-15T15:23:26.500", "Id": "502437", "Score": "0", "body": "I posted my new code [here](https://codereview.stackexchange.com/questions/254749/revised-counting-subnumbers-divisible-by-a-given-prime). Can you take a look?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T17:28:52.827", "Id": "252830", "ParentId": "252811", "Score": "4" } } ]
{ "AcceptedAnswerId": "252830", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T09:07:46.683", "Id": "252811", "Score": "-1", "Tags": [ "python", "programming-challenge" ], "Title": "Counting subnumbers divisible by a given prime" }
252811
<p>What are the pros and cons of each option, considering long-term implications (increasing the number of functions / parameters, other developers taking over, etc.)?</p> <p><strong>Option 1</strong>: removes the need to pass <code>foo</code> and <code>bar</code> to each method, but will create nested functions that are hard to follow.</p> <pre class="lang-js prettyprint-override"><code>const myFunction = ({foo, bar}) =&gt; { const results = [] const function1 = () =&gt; { return foo + bar; } const function2 = () =&gt; { return foo * bar; } const res1 = function1(); const res2 = function2(); results.push(res1, res2); } </code></pre> <p><strong>Option 2</strong>: you pass the parameters to each function, but remove the nesting, which in my opinion makes it more readable.</p> <pre class="lang-js prettyprint-override"><code>const function1 = ({foo, bar}) =&gt; { return foo + bar; } const function2 = ({foo, bar}) =&gt; { return foo * bar; } const myFunction = ({foo, bar}) =&gt; { const results = [] const res1 = function1({foo, bar}); const res2 = function2({foo, bar}); results.push(res1, res2); } </code></pre> <p>I would prefer to know how to improve my functional approaches here. Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T10:50:35.737", "Id": "498278", "Score": "0", "body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](http://meta.codereview.stackexchange.com/q/1709/41243)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T10:59:46.217", "Id": "498279", "Score": "0", "body": "Thank you, @Vogel612." } ]
[ { "body": "<h1>Option 1</h1>\n<p>The nested function is not bad (depending on the situation). Of course, they bring more complexity and reduces extensibility. But in some cases, you wish to bundle some function that works with the main function output (well, it's not very different from the class).</p>\n<p>Of course you should return object instead of the list for the usage convenience:</p>\n<pre><code>const myFunction = ({foo, bar}) =&gt; {\n return {\n function1() {\n return foo + bar\n },\n function2() {\n return foo * bar;\n }\n }\n}\nmyFunction().function1()\n</code></pre>\n<blockquote>\n<p>To sum up, this design can simplify usage in some cases. However, the worst thing about this pattern is that these functions are not extendible and you can't use partial functionality (like using only <code>function1</code>). In most cases, I recommend avoiding this unless you are writing a library/helper function and which to simplify usage by attaching other chain function to the main output (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\">fetch</a> is a good example).</p>\n</blockquote>\n<h2>Option 2</h2>\n<p>Regarding the second option, it works fine as long as your function is not too complex and you don't have too many parameters. You can partially solve the issue with a lot of parameters using <a href=\"https://www.typescriptlang.org/\" rel=\"nofollow noreferrer\">TypeScript</a> (because you can statically describe them).</p>\n<p>However, if possible I recommend changing logic a bit. Instead of requiring all parameters why don't you require the output of functions? Then you can have multiple functions which return different output + you can also write your own implementation for one part. This option opens a way for unlimited possibilities.</p>\n<p><em>Example:</em></p>\n<pre class=\"lang-js prettyprint-override\"><code>const myFunction = ({foo, bar}) =&gt; {\n return [\n foo,\n bar\n ]\n}\n\nmyFunction({\n foo: function1(),\n bar: function1(),\n})\n\n// You can &quot;extend&quot; this function:\nmyFunction({\n foo: function1(),\n bar: myCustomFunction(),\n})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T11:04:55.627", "Id": "498280", "Score": "0", "body": "Interesting. The problem wouldn't really be extensibility, these are just functions like \"getUsersA\", \"getUsersB\", etc. that just need to be encapsulated. I'm afraid that later on it will require even more parameters, so multiple changes would have to be done. Functions will most likely not be required to be ran individually. All require parameters like \"limit=\". But I couldn't provide a concrete example so I moved the question to Stackoverflow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T10:39:06.523", "Id": "252815", "ParentId": "252812", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T09:50:10.647", "Id": "252812", "Score": "0", "Tags": [ "javascript", "functional-programming" ], "Title": "Readability vs. maintainability: nested functions" }
252812
<p>I am learning python from CS106. Please review my code for Khan Sole Academy, I think my code not efficient. Please add critique and advice for beginner like me.</p> <h3>About Code</h3> <p>Generate 2 random numbers and add those numbers. If the user supplied answer is correct, row will increase by 1, goal is 3. If answer is false, row will be reset to zero.</p> <h3>Question From Assignment CS106</h3> <blockquote> <p>Your program should be able to generate simple addition problems that involve adding two 2-digit integers (i.e., the numbers 10 through 99). The user should be asked for an answer to each problem. Your program should determine if the answer was correct or not, and give the user an appropriate message to let them know. Your program should keep giving the user problems until the user has gotten 3 problems correct in a row.<br /> (Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specify a constant in your program)</p> </blockquote> <pre><code> import random MIN_NUM = 10 MAX_NUM = 99 row = 0 def main(): &quot;&quot;&quot; Pre Condition: Generate random number. Additional num 1 and num 2 Post Condition : Check user answers. If answer correct add row, if incorrect reset row to zero &quot;&quot;&quot; row = 0 while row &lt; 3: # number generator num_1 = random.randint(MIN_NUM, MAX_NUM) num_2 = random.randint(MIN_NUM, MAX_NUM) print(&quot;What is &quot; + str(num_1) + &quot; + &quot; + str(num_2) + &quot; ?&quot;) total = num_1 + num_2 #user answer user_input = int(input(&quot;Your answer: &quot;)) # Check user answer # if answer is incorrect, reset row to zero if user_input == total: row += 1 print(&quot;Correct! You've gotten &quot; + str(row) +&quot; correct in a row &quot;) else: print(&quot;Incorrect. The expected answer is &quot; + str(total)) row = 0 if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<p>Actually, your code is efficient - it does exactly what it is supposed to do, and does not take any extra steps.</p>\n<p>There are a few other issues, of the kind that are expected from a new coder in the process of learning, so here are some tips:</p>\n<h2>Global <code>row</code> variable</h2>\n<p>In Python, if you declare a variable outside of a function and then one with the same name inside a function (by assigning it value, as you do with <code>row</code>), you create a new variable, that &quot;overshadows&quot; the global one.</p>\n<p>Basically, the top <code>row</code> in you code is never used, instead, <code>main</code> has its own local copy.</p>\n<p>But that is ok, because you don't need a global <code>row</code> variable any way.<br />\nAs a general practice it is best to avoid global variables completely.<br />\nThere are very few cases where they are needed, especially in object oriented languages like Python.</p>\n<h2><a href=\"https://realpython.com/python-string-formatting/\" rel=\"noreferrer\">String formatting</a></h2>\n<p>When you want to compose a string from multiple parts, including values in variables you should use formatting instead of string concatenation with '+'.</p>\n<p>It is a more robust method allowing for prettier output, and makes your code more readable and more convenient to modify should the need arise.<br />\nAlso, if you are putting together a lot of parts, this will be more efficient.</p>\n<p>If you are using Python 3.6 or newer, you can do this:</p>\n<pre><code>print(f&quot;What is {num_1} + {num_2} ?&quot;)\n...\nprint(f&quot;Correct! You've gotten {row} correct in a row.&quot;)\n</code></pre>\n<p>If you are on an older version of Python, you can do this:</p>\n<pre><code>print(&quot;What is {} + {} ?&quot;.format(num_1, num_2))\n...\nprint(f&quot;Correct! You've gotten {} correct in a row.&quot;.format(row))\n</code></pre>\n<p>As you can see, you no longer have to convert numbers to strings manually, the formatting function will do it for you!</p>\n<h2>Pay attention to hints in questions</h2>\n<p>You have used constants for range of random numbers, but not for the maximum number of correct answers in a row.</p>\n<p>The question almost requires you use a constant by saying:</p>\n<blockquote>\n<p>(Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specify a constant in your program)</p>\n</blockquote>\n<p>In general, numbers that have meaning but are written as is directly in the code (like the number of correct answers) are called &quot;magic numbers&quot; and are considered bad practice.</p>\n<p>Just add at the top:</p>\n<pre><code>MAX_IN_ROW = 3\n</code></pre>\n<p>And use <code>MAX_IN_ROW</code> everywhere else in the code you need to check this value.</p>\n<h2>Input validation</h2>\n<p>This may be an advanced topic you have not covered yet, but as a rule of thumb all programs must guard against bad or invalid user input.</p>\n<p>Some questions, especially on time constrained exams tell you to omit such checks, but if not explicitly instructed to do so, and if you can, you should check all input before using it.</p>\n<p>For this question, exception handling would be appropriate:</p>\n<pre><code>try:\n user_input = int(input(&quot;Your answer: &quot;))\nexcept ValueError:\n print(&quot;Invalid answer! You must type a positive decimal number.&quot;)\n continue\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T13:04:24.080", "Id": "252822", "ParentId": "252813", "Score": "7" } } ]
{ "AcceptedAnswerId": "252822", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T10:08:32.237", "Id": "252813", "Score": "3", "Tags": [ "python", "beginner", "random" ], "Title": "Math Random Addition" }
252813
<p>The code bellow is code of &quot;Hello&quot; message handler. It works, but I really don't like as it looks. The &quot;hello&quot; protocol contains three messages:</p> <ol> <li>client -&gt; server: diffie-hellman client public parameters</li> <li>server -&gt; client: diffie-hellman server public parameters</li> <li>client -&gt; server: used data</li> </ol> <p>Could you please review the code. Any comments are welcome.</p> <pre><code>public class HelloHandler implements Runnable { final private static int MSG_TIMEOUT = 5000; // Response receive timeout in milliseconds final private static Server server = Server.getInstance(); final private static Logger logger = server.getLogger(); final private static ClientsRepository repository = server.getClientsRepository(); final private static Map&lt;SocketAddress, HelloHandler&gt; handlers = new ConcurrentHashMap&lt;SocketAddress, HelloHandler&gt;(); final private SocketAddress address; private DatagramPacket keyExchange = null; private DatagramPacket userData = null; private CipherPair ciphers; /* * Handles all hello messages * This method runs in context of the main thread (server) */ public static void handle(DatagramPacket packet) { SocketAddress address = packet.getSocketAddress(); byte type = PacketParser.getHeader(packet); if (type == DH_EXCH) { //DH exchange starts if (handlers.containsKey(address) || repository.containsKey(address)) { logAndSend(REJECT, &quot;Already active&quot;, address); return; } HelloHandler handler = new HelloHandler(packet); handlers.put(address, handler); server.getExecutor().execute(handler); return; } if (type == USER) { //user sent it's data HelloHandler handler = handlers.get(address); if (handler == null) { logAndSend(TIMEOUT, &quot;Timeout&quot;, address); return; } handler.handleUser(packet); } } private HelloHandler(DatagramPacket packet) { keyExchange = packet; address = packet.getSocketAddress(); } private void handleUser(DatagramPacket packet) { if (userData == null) userData = packet; } @Override public void run() { DatagramPacket packet; try { packet = processKeyExchange(); server.send(packet); keyExchange = null; // help GC packet = waitForPacket(); if (!server.isRunning()) return; if (packet == null) { logAndSend(TIMEOUT, &quot;Timeout&quot;, address); return; } packet = processUserData(); if (packet != null) server.send(packet); return; } catch (NullPointerException | IOException e) { // we cannot be here logger.severe(&quot;Hello handler: &quot; + e.getMessage()); return; } catch (IllegalMessageException e) { logAndSend(ILLEGAL_MSG, e.getMessage(), address); return; } finally { handlers.remove(address); } } private DatagramPacket waitForPacket() { // Use the simplest polling long timeOutTime = System.currentTimeMillis() + MSG_TIMEOUT; boolean timeOut = false; while (userData == null &amp;&amp; !timeOut &amp;&amp; server.isRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) {}; timeOut = System.currentTimeMillis() &gt;= timeOutTime; } return userData; } /* * Process first message (key exchange) sent by client * throws IllegalMessageException if we cannot get public key from message */ private DatagramPacket processKeyExchange() throws NullPointerException, IOException, IllegalMessageException { try { Message&lt;DHPublicKeyParams&gt; message = PacketParser.parse(keyExchange, DHPublicKeyParams.class); DHPublicKeyParams clientKeyExchangeParams = message.getData(); SecurityHelper security = SecurityHelper.getInstance(); DHPublicKeyParams serverKeyExchangeParams = security.getPublicKeyParams(); ciphers = security.finalizeAggreement(clientKeyExchangeParams); return PacketBuilder.build(DH_EXCH, serverKeyExchangeParams, address); } catch (InvalidKeyException | InvalidKeySpecException e) { throw new IllegalMessageException(e); } }; /* * Currently it is a dummy method that shows that we can read encrypted data */ private DatagramPacket processUserData() throws NullPointerException, IOException, IllegalMessageException { Message&lt;UserData&gt; message = PacketParser.parse(userData, ciphers.getReadCipher(), UserData.class); System.out.println(message.getData().toString()); repository.put(message.getData()); return null; }; /* * logs error and send response to client */ private static void logAndSend(byte type, String text, SocketAddress address) { logger.warning(buildMessage(text, address)); server.send(PacketBuilder.build(type, text, address)); }; private static String buildMessage(String text, SocketAddress address) { StringBuilder sb = new StringBuilder(); sb.append(&quot;Hello handler: &quot;); sb.append(text); sb.append(&quot; form: &quot;); sb.append(Util.sockAddrToString(address)); return sb.toString(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:27:59.337", "Id": "498407", "Score": "0", "body": "Two things without reviewing the whole thing: StringBuilder only buys you something when using a loop or if you have an unknown number of parts. And `System.currentTimeMillis` is *wall-clock time*, meaning it observes time changes (leap seconds, daylight saving etc.). You either want an `Instant`, or `System.nanotime`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:55:56.023", "Id": "498426", "Score": "0", "body": "@Bobby Thanks for the comments. I will change the code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T15:45:36.520", "Id": "252826", "Score": "2", "Tags": [ "java", "server" ], "Title": "Message handler" }
252826
<p>I have created a test, also the interfaces to be implemented for each test case based on user's role because I think it would make it easier to understand what the test case will and should do, also forces each test that has similar requirements to have consistent method naming. I want to make sure what I did is a best practice before I implement them to all my test cases.</p> <p>To have a better sight of what am I doing, please have a look at this folder structure.</p> <p><a href="https://i.stack.imgur.com/tE3MH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tE3MH.png" alt="visual explanation, folder structure" /></a></p> <p>Based on that, I have implemented them in one class, the file looks like this. It applies to other test cases like <code>Showing</code>, <code>Updating</code>, <code>Destroying</code>, <code>Uploading</code>, and so on...</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace Tests\Feature\Specialization; use App\Models\Specialization; use App\Models\User; use Database\Seeders\SpecializationSeeder; use Database\Seeders\RolesAndPermissionSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Spatie\Permission\PermissionRegistrar; use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByCustomer; use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByEmployee; use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByInternal; use Tests\_Interfaces\Feature\Basic\Indexable\IndexableByModerator; use Tests\_Interfaces\Feature\Basic\NotIndexable\NotIndexableByGuest; use Tests\TestCase; class SpecializationIndexTest extends TestCase implements IndexableByCustomer, IndexableByEmployee, IndexableByInternal, IndexableByModerator, NotIndexableByGuest { use RefreshDatabase; public function setUp(): void { parent::setUp(); $this-&gt;app-&gt;make(PermissionRegistrar::class)-&gt;registerPermissions(); $this-&gt;seed(RolesAndPermissionSeeder::class); $this-&gt;seed(SpecializationSeeder::class); } public function testIndexShouldBeInaccessibleByGuest() { $this -&gt;getJson(route('specializations.index')) -&gt;assertUnauthorized() -&gt;assertJsonMissing(Specialization::first()-&gt;toArray()); } public function testIndexShouldBeAccessibleByInternal() { $user = User::factory()-&gt;createOne()-&gt;assignRole('internal'); $this-&gt;actingAs($user, 'api') -&gt;getJson(route('specializations.index')) -&gt;assertOk() -&gt;assertJsonFragment(Specialization::first()-&gt;toArray()); } public function testIndexShouldBeAccessibleByModerator() { $user = User::factory()-&gt;createOne()-&gt;assignRole('moderator'); $this-&gt;actingAs($user, 'api') -&gt;getJson(route('specializations.index')) -&gt;assertOk() -&gt;assertJsonFragment(Specialization::first()-&gt;toArray()); } public function testIndexShouldBeAccessibleByCustomer() { $user = User::factory()-&gt;createOne()-&gt;assignRole('customer'); $this-&gt;actingAs($user, 'api') -&gt;getJson(route('specializations.index')) -&gt;assertOk() -&gt;assertJsonFragment(Specialization::first()-&gt;toArray()); } public function testIndexShouldBeAccessibleByEmployee() { $user = User::factory()-&gt;createOne()-&gt;assignRole('employee'); $this-&gt;actingAs($user, 'api') -&gt;getJson(route('specializations.index')) -&gt;assertOk() -&gt;assertJsonFragment(Specialization::first()-&gt;toArray()); } } </code></pre> <p>So the question is, is this a good idea to have interfaces for tests? Or should I avoid it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T04:44:31.837", "Id": "498343", "Score": "1", "body": "Other then forcing some method names over many tests, I don't see the point. Maybe if implementation of those methods is the same across many tests then you may implement traits instead, but the interface seems rather useless, is it typehinted anywhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T04:49:14.633", "Id": "498344", "Score": "1", "body": "For an interface to be useful, someone must call it's methods not knowing the actual class. Here the tests runner calls public methods starting with test* or marked as a test explicitly with an annotation. It doesn't really care whether those interfaces are implemented, it just cares that the class is a test case child." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T12:54:15.320", "Id": "498368", "Score": "0", "body": "Yes yes.. I ended up deleting them because the file started to bloat everytime I add new requirements to the test. Well, I do have to remember them (the method name, and the requirements) tho since now didn't have autocompletion, to keep my test tidy and make sure not skipping any." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-25T09:44:27.607", "Id": "500686", "Score": "0", "body": "I tend to use interfaces when I have a base class to make sure that child classes have correct methods. But, unlike what you are doing, those methods are support methods and if nothing is set then methods from the parent class are used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T08:45:01.190", "Id": "531315", "Score": "0", "body": "Could you please share what these interfaces include?" } ]
[ { "body": "<p>I'm not sure what you're using these interfaces for, but I can see all the tests have the same code and the only thing is changing is the role. Why not using <a href=\"https://phpunit.de/manual/3.7/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers\" rel=\"nofollow noreferrer\">phpunit data provider</a> instead?</p>\n<p>The code will be like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// for the guest case, you can leave it as it is.\n\n/**\n * @dataProvider roles\n */\n public function testIndexShouldBeAccessibleBySupportedRoles($role)\n {\n $user = User::factory()-&gt;createOne()-&gt;assignRole($role);\n \n\n $this-&gt;actingAs($user, 'api')\n -&gt;getJson(route('specializations.index'))\n -&gt;assertOk()\n -&gt;assertJsonFragment(Specialization::first()-&gt;toArray());\n }\n public function roles()\n {\n return [\n ['internal'],\n ['customer'],\n ['employee'],\n ['moderator'],\n ];\n }\n</code></pre>\n<p>When you want to test a new role, all you have to do is adding the new role to the <code>roles</code> provider.</p>\n<p>So my answer to your question is <strong>No</strong>\nThe tests shouldn't care about your app implementations details, by using these interfaces you're coupling your tests to your app. And for every new role you have to create:</p>\n<ul>\n<li>A test for the new role.</li>\n<li>a new interface.\nand if you decide to change your interface name, you must change all tests that are implementing this interface.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T09:36:35.170", "Id": "269324", "ParentId": "252827", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T15:51:05.107", "Id": "252827", "Score": "2", "Tags": [ "php", "laravel", "phpunit" ], "Title": "Is it okay to use interfaces on tests?" }
252827
<p>I created an algorithm that helps me merging a payload into a given fixed object, in other words</p> <p>this payload</p> <pre class="lang-json prettyprint-override"><code>const requestPayload = { &quot;customer_email&quot;: &quot;me@domain.com&quot;, &quot;customer_name&quot;: &quot;unit test&quot;, &quot;customer_firstname&quot;: &quot;unit&quot;, &quot;customer_lastname&quot;: &quot;test&quot;, &quot;customer_phone&quot;: &quot;123456789&quot;, &quot;customer_ts&quot;: &quot;11.10.2020 12:37:39&quot;, &quot;sc_device_type&quot;: &quot;mobile&quot;, &quot;sc_url&quot;: &quot;http://www.domain.com&quot; } </code></pre> <p>with this setup/settings</p> <pre class="lang-json prettyprint-override"><code>const settings = { &quot;n&quot;: 10002, &quot;api_key&quot;: &quot;pk_f434ea5e9c31906639b31076b24805be7a&quot;, &quot;email&quot;: &quot;customer_email&quot;, &quot;name&quot;: &quot;customer_name&quot;, &quot;device&quot;: &quot;sc_device_type&quot;, &quot;url&quot;: &quot;sc_url&quot;, &quot;object1&quot;: { &quot;device&quot;: &quot;sc_device_type&quot;, }, &quot;object2&quot;: { &quot;devices&quot;: { &quot;device&quot;: &quot;sc_device_type&quot; } }, &quot;array1&quot;: [{ &quot;email&quot;: &quot;customer_email&quot;, &quot;name&quot;: &quot;customer_name&quot; }], &quot;array2&quot;: [{ &quot;emails&quot;: [ &quot;customer_email&quot; ], &quot;name&quot;: &quot;customer_name&quot; }], &quot;array3&quot;: [4, &quot;customer_email&quot;,&quot;customer_name&quot;,&quot;customer_ts&quot;] } </code></pre> <p>should output</p> <pre class="lang-json prettyprint-override"><code>{ &quot;n&quot;: 10002, &quot;api_key&quot;: &quot;pk_f434ea5e9c31906639b31076b24805be7a&quot;, &quot;email&quot;: &quot;me@domain.com&quot;, &quot;name&quot;: &quot;unit test&quot;, &quot;device&quot;: &quot;mobile&quot;, &quot;url&quot;: &quot;http://www.domain.com&quot;, &quot;object1&quot;: { &quot;device&quot;: &quot;mobile&quot; }, &quot;object2&quot;: { &quot;devices&quot;: { &quot;device&quot;: &quot;mobile&quot; } }, &quot;array1&quot;: [{ &quot;email&quot;: &quot;me@domain.com&quot;, &quot;name&quot;: &quot;unit test&quot; }], &quot;array2&quot;: [{ &quot;emails&quot;: [ &quot;me@domain.com&quot; ], &quot;name&quot;: &quot;unit test&quot; }], &quot;array3&quot;: [ 4, &quot;me@domain.com&quot;, &quot;unit test&quot;, &quot;11.10.2020 12:37:39&quot; ] } </code></pre> <hr /> <p><strong>Code works fine</strong>, but I wonder if anyone can help me with hints if I can make the code a bit better.</p> <p>This is my 3rd refactored code, as I've started with a huge and terrible code, and only now I've added support to replace <code>Arrays</code>. As I'm new here, would love to take advantage of your expertise </p> <pre class="lang-javascript prettyprint-override"><code>const templateParse = (entry) =&gt; { // TODO: add later, so we can pass a value like 'TML|DATE|yyyy-mm-dd' and will output '2020-11-29' (using today's date) return entry } const getTypeOfValue = v =&gt; Array.isArray(v) ? 'array' : typeof v const replaceValue = (originalValue, dataToMerge, encodeOutput) =&gt; { if (typeof originalValue === 'string' &amp;&amp; originalValue.indexOf('TMPL') === 0) { return templateParse(originalValue) } else { // check if property exist, use original value if not const mergedValue = Object.prototype.hasOwnProperty.call(dataToMerge, originalValue) ? dataToMerge[originalValue] : originalValue return encodeOutput ? encodeURI(mergedValue) : mergedValue } } const mergeArrayData = (originalValue, dataToMerge, encodeOutput) =&gt; { const arrayOutput = [] const mergedArray = mergeCustomFields(originalValue, dataToMerge, encodeOutput) for (i in mergedArray) { arrayOutput.push(mergedArray[i]) } return arrayOutput } const mergeCustomFields = (customFields, dataToMerge, encodeOutput = false) =&gt; { const mergeFields = {} for (key in customFields) { const v = customFields[key] const t = getTypeOfValue(v) if (t === 'array') { mergeFields[key] = mergeArrayData(v, dataToMerge, encodeOutput) } else if (t === 'object') { mergeFields[key] = mergeCustomFields(v, dataToMerge, encodeOutput) } else { // string or number mergeFields[key] = replaceValue(v, dataToMerge, encodeOutput) } } return mergeFields } </code></pre> <p>and I'll call as <code>mergeCustomFields(settings, requestPayload)</code> having the option to pass <code>true</code> to encode values that might have unicode chars...</p>
[]
[ { "body": "<p><strong>Naming</strong> Your variable names aren't quite as precise as they could be.</p>\n<ul>\n<li><p>Single-letter variables in particular should be avoided in most cases, except perhaps for the <code>i</code> of a <code>for</code> loop.</p>\n</li>\n<li><p><code>mergeCustomFields</code> performs the algorithm over an object. <code>mergeArrayData</code> performs the algorithm over an array. Maybe call them <code>mergeArray</code> and <code>mergeObject</code>.</p>\n</li>\n<li><p><code>template</code> (which you're already using in some places) is a great precise name for the data structure, much better than <code>originalValue</code> IMO.</p>\n</li>\n</ul>\n<p><strong>Use <code>startsWith</code> to check if a string starts with another string</strong> - it's cleaner and easier to make sense of than an <code>indexOf</code> check against 0. (If you're worried about browser compatibility, use a polyfill, as always - keep the source code as reaadable as possible.)</p>\n<p><strong>Overly defensive code</strong> is verbose, weird, and usually an indicator of an issue earlier in the pipeline. Do you <em>really</em> need to do</p>\n<pre><code>const mergedValue = Object.prototype.hasOwnProperty.call(dataToMerge, originalValue) ? dataToMerge[originalValue] : originalValue\n</code></pre>\n<p>? If at all possible, consider changing it to something like:</p>\n<pre><code>const mergedValue = dataToMerge[originalValue] ?? originalValue\n</code></pre>\n<p>(Even if you aren't using <code>hasOwnProperty</code> anymore, if you have code that has a chance of creating objects with a <code>hasOwnProperty</code> key that does <em>not</em> refer to <code>Object.prototype.hasOwnProperty</code>, you should consider if there are ways to refactor it so that isn't an edge case that you have to keep in mind)</p>\n<p><strong>Extract the transformation of a single value into a standalone function</strong> - this will help separate concerns and will allow for a great improvement with <code>.map</code>, used below.</p>\n<p><strong>Always declare variables before using them</strong> - <code>for (key in customFields) {</code> creates a global <code>key</code> variable, or will throw an error in strict mode. (Another section with this same problem: <code>for (i in mergedArray) {</code>) Consider <a href=\"https://eslint.org/docs/rules/no-undef\" rel=\"noreferrer\">using a linter</a> to automatically prompt you to fix these sorts of mistakes. (Use <code>for (const key in customFields) {</code> instead). But both of these sections have better methods available:</p>\n<p><strong>To create an array by transforming every element from another array, use <code>.map</code></strong> instead of iterating over indicies and using <code>.push</code>:</p>\n<pre><code>const mergeArray = arr =&gt; arr.map(transformValue);\n</code></pre>\n<p><strong>Use <code>Object.entries</code> to get the key and the value from an object at once</strong>, instead of iterating over the keys and separately extracting the values.</p>\n<pre><code>const mergeObject = (customFields) =&gt; {\n const mergeFields = {}\n for (const [key, value] of Object.entries(customFields)} {\n mergeFields[key] = transformValue(value);\n }\n return mergeFields\n}\n</code></pre>\n<p>You could also consider using <code>Object.fromEntries</code> and mapping the original object's entries, which I think is even more appropriate when transforming all the values of one object (see below). But first, there's something else to consider that you might've noticed are missing from the above snippets. You're passing along <code>dataToMerge</code> and <code>encodeOutput</code> to every single function, but both of those variables are only ultimately used inside the <code>replaceValue</code> function. Consider either passing the <code>replaceValue</code> function instead, created with two constant parameters bound to it already, or declaring all the functions such that they have scope of a <code>replaceValue</code> function that has scope of the two needed values:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const requestPayload={customer_email:\"me@domain.com\",customer_name:\"unit test\",customer_firstname:\"unit\",customer_lastname:\"test\",customer_phone:\"123456789\",customer_ts:\"11.10.2020 12:37:39\",sc_device_type:\"mobile\",sc_url:\"http://www.domain.com\"},settings={n:10002,api_key:\"pk_f434ea5e9c31906639b31076b24805be7a\",email:\"customer_email\",name:\"customer_name\",device:\"sc_device_type\",url:\"sc_url\",object1:{device:\"sc_device_type\"},object2:{devices:{device:\"sc_device_type\"}},array1:[{email:\"customer_email\",name:\"customer_name\"}],array2:[{emails:[\"customer_email\"],name:\"customer_name\"}],array3:[4,\"customer_email\",\"customer_name\",\"customer_ts\"]};\nconst templateParse = (entry) =&gt; {\n // TODO: add later, so we can pass a value like 'TML|DATE|yyyy-mm-dd' and will output '2020-11-29' (using today's date)\n return entry\n}\nconst getTypeOfValue = v =&gt; Array.isArray(v) ? 'array' : typeof v\n\nconst mergePayload = (template, replacements, encodeOutput = false) =&gt; {\n const replaceValue = (originalValue) =&gt; {\n if (typeof originalValue === 'string' &amp;&amp; originalValue.startsWith('TMPL')) {\n return templateParse(originalValue)\n } else {\n // check if property exist, use original value if not\n const mergedValue = replacements[originalValue] ?? originalValue\n return encodeOutput ? encodeURI(mergedValue) : mergedValue\n }\n };\n const mergeArray = arr =&gt; arr.map(mergeValue);\n const mergeValue = (value) =&gt; {\n const t = getTypeOfValue(value)\n return t === 'array'\n ? mergeArray(value)\n : t === 'object'\n ? mergeObject(value)\n : replaceValue(value);\n };\n const mergeObject = customFields =&gt; Object.fromEntries(\n Object.entries(customFields).map(\n ([key, value]) =&gt; [key, mergeValue(value)]\n )\n );\n return mergeObject(template);\n};\n\nconsole.log(mergePayload(settings, requestPayload));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>That's the version I'd prefer - <em>were it not for the JSON approach mentioned below</em>.</p>\n<p>There's one potential pitfall which may or may not be something to worry about: <code>typeof null</code> will give <code>object</code>. If <code>null</code> is a possible value in the template, change the <code>getTypeOfValue</code> function to account for it. (you could return <code>'null'</code> or whatever you wanted, anything but <code>'object'</code>, so that <code>mergeObject</code> later doesn't throw)</p>\n<p>But this whole thing could be made much simpler by exploiting the naturally recursive nature of <code>JSON.stringify</code>, and using a reviver function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const requestPayload={customer_email:\"me@domain.com\",customer_name:\"unit test\",customer_firstname:\"unit\",customer_lastname:\"test\",customer_phone:\"123456789\",customer_ts:\"11.10.2020 12:37:39\",sc_device_type:\"mobile\",sc_url:\"http://www.domain.com\"},settings={n:10002,api_key:\"pk_f434ea5e9c31906639b31076b24805be7a\",email:\"customer_email\",name:\"customer_name\",device:\"sc_device_type\",url:\"sc_url\",object1:{device:\"sc_device_type\"},object2:{devices:{device:\"sc_device_type\"}},array1:[{email:\"customer_email\",name:\"customer_name\"}],array2:[{emails:[\"customer_email\"],name:\"customer_name\"}],array3:[4,\"customer_email\",\"customer_name\",\"customer_ts\"]};\n\nconst mergePayload = (template, replacements) =&gt; JSON.parse(\n JSON.stringify(template),\n (key, value) =&gt; replacements[value] ?? value\n);\n \n\nconsole.log(mergePayload(settings, requestPayload));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T22:15:49.403", "Id": "252835", "ParentId": "252832", "Score": "8" } } ]
{ "AcceptedAnswerId": "252835", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T20:20:46.900", "Id": "252832", "Score": "6", "Tags": [ "javascript" ], "Title": "Merging values into an object" }
252832
<p>My code is structured so that I create an ellipse through my first three points of data. Then I go through each next row, and if the point falls outside the ellipse, I record the minimum distance between the point and ellipse. These points have datetime associated with it so I can only keep points 10 minutes old in my ellipse (so it doesn't get too big). The code works great until I have to process 100K+ of observations. Then the process time goes from minutes to hours. My question is, is there any part of my for loop portion of code that I can restructure to cut process time? I vectorized what I could (I think), and I know taking conditions out of for loop helps but now sure how to do it. Code below for reference. Any help is greatly appreciated.</p> <pre><code>library(sp) library(cluster) #create new empty column in dataframe df$Distances &lt;- NA #get first three points and fit an ellipse around it FlashPoints &lt;- cbind(df$Lat[1:3],df$Long[1:3]) EllipseShape &lt;- ellipsoidhull(FlashPoints) EllipseShape #get set of points that represent ellipse EllipsePoints &lt;- predict(EllipseShape) EllipseGroup &lt;- cbind(EllipsePoints[,2],EllipsePoints[,1]) #function to check if the next flashpoint (xp, yp) belongs to the ellipse with parameters a,b,... with tolerance eps onEllipse &lt;- function (xp, yp, a, b, x0, y0, alpha, eps=1e-3) { return(abs((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 - 1) &lt;= eps) } #function to check if the point (xp, yp) is inside the ellipse with parameters a,b,... insideEllipse &lt;- function (xp, yp, a, b, x0, y0, alpha) { return((cos(alpha)*(xp-x0)+sin(alpha)*(yp-y0))^2/a^2+(sin(alpha)*(xp-x0)-cos(alpha)*(yp-y0))^2/b^2 &lt;= 1) } #loop from row 4 to last row for (i in 4:nrow(df)){ #get location of next point nextFlash &lt;- cbind(df$Long[i],df$Lat[i]) #Establish/Re-establish parameters xp &lt;- df$Lat[i] yp &lt;- df$Long[i] x0 &lt;- EllipseShape$loc[1] # centroid locations y0 &lt;- EllipseShape$loc[2] eg &lt;- eigen(EllipseShape$cov) axes &lt;- sqrt(eg$values) alpha &lt;- atan(eg$vectors[1,1]/eg$vectors[2,1]) # angle of major axis with x axis a &lt;- sqrt(EllipseShape$d2) * axes[1] # major axis length b &lt;- sqrt(EllipseShape$d2) * axes[2] # minor axis length #Check to see if next point is outside the ellipse, then get distance. If it is, add to distance list if((insideEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE) &amp;&amp; onEllipse(xp, yp, a, b, x0, y0, alpha)==FALSE){ nextDist &lt;- min(spDistsN1(EllipseGroup, nextFlash, longlat = TRUE)) df$Distances[i] &lt;- nextDist #Omit points 10 minutes old from group movingGroup &lt;- subset(df[1:i,], difftime(df$DateTime[1:i],df$DateTime[i],units = &quot;mins&quot;)&lt;10) movingTstorm FlashPoints &lt;- cbind(movingGroup$Lat[1:i],movingGroup$Long[1:i]) FlashPoints #Fit an ellipse around flashpoints EllipseShape &lt;- ellipsoidhull(FlashPoints) EllipseShape #Get set of points that make an ellipse EllipsePoints &lt;- predict(EllipseShape) EllipseGroup &lt;- cbind(EllipsePoints[,2],EllipsePoints[,1]) } next(i) } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:06:48.753", "Id": "498386", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-29T20:57:26.930", "Id": "252834", "Score": "2", "Tags": [ "performance", "r" ], "Title": "How to make my code with for/if loop more efficient in R" }
252834
<p>here's the updated version of the <a href="https://codereview.stackexchange.com/questions/252685/bash-zsh-function-that-cd-to-the-root-of-git-tree">code</a> for being reviewed. Fixes:</p> <ul> <li>&quot;private&quot; <code>_cg</code> function</li> <li>functions definition as <code>cg() {}</code></li> <li>general clean-up</li> </ul> <pre><code>#!/bin/bash # cd to the root of the current git directory # If $PWD is submodule, will cd to the root of the top ancestor # It requires to stay in the current directory, if the root is . or unknown, # and use cd only once, to have a way to do `cd -` cg() { _cg() { local top; top=&quot;$(git rev-parse --show-cdup)&quot; top=&quot;${top:-./}&quot; local super_root; super_root=&quot;$(git rev-parse --show-superproject-working-tree)&quot; if [[ &quot;$super_root&quot; ]]; then printf '%s' &quot;$top../&quot; ( cd &quot;$top../&quot; &amp;&amp; _cg || return ) fi printf '%s' &quot;$top&quot; } local git_root git_root=&quot;$(_cg)&quot; [[ &quot;x${git_root}&quot; != &quot;x./&quot; ]] &amp;&amp; cd &quot;${git_root}&quot; &amp;&amp; return || return 0 } </code></pre>
[]
[ { "body": "<p>This is looking great. Thanks for incorporating the previous improvements and coming back for another round of review. I noticed a few new things this time:</p>\n<ul>\n<li>What does <code>printf '%s'</code> do for you that <code>echo -n</code> wouldn't? Using <code>printf</code> when you're just passing through a string seems a little odd to me. It should work either way, but <code>printf</code> would be more idiomatic for C where <code>echo</code> is much more common in shell scripts.</li>\n<li>Adding the <code>x</code> constants in the comparison <code>[[ &quot;x${git_root}&quot; != &quot;x./&quot; ]]</code> are not needed. Using the double square brackets deals with the disappearing variables. You would need the extra <code>x</code> for <code>[</code> comparisons because empty arguments become non-existant arguments which causes an error when you try to compare the non-existant to something.</li>\n<li>I would use <code>-n</code> in the <code>if [[ &quot;$super_root&quot; ]]; then</code> line like so: <code>if [[ -n &quot;$super_root&quot; ]]; then</code> to make clear what you're trying to do there.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T21:44:05.797", "Id": "521719", "Score": "0", "body": "I just found that didn't come back with \"thank you\". Thank you very much for your help! And the objectives behind the implementations: 1) I feel like `echo -n` is less portable than `printf`, that's why I stuck to it; 2) Thank you, I've learned something new; 3) perfectly makes sense too!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T16:36:33.550", "Id": "252854", "ParentId": "252838", "Score": "1" } } ]
{ "AcceptedAnswerId": "252854", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T09:44:34.493", "Id": "252838", "Score": "1", "Tags": [ "bash", "git", "zsh" ], "Title": "Updated bash/zsh function that cd to the root of git tree" }
252838
<p>I have been building an API in Go, which I want to link to a <code>Postgres</code> SQL table. I have always used <code>NoSQL</code> previously but thought it would be good to try a <code>SQL</code> database.</p> <p>Here are my structs</p> <pre><code>type Activity struct { Activity string `json:&quot;activity&quot;` Payload Payload `json:&quot;payload&quot;` } type Payload struct { UserID string `json:&quot;userId&quot;` Duration int `json:&quot;duration&quot;` Type string `json:&quot;type&quot;` Date int `json:&quot;date&quot;` } </code></pre> <p>Based on the above I thought it would be good to have a table for payload which was made via the following query.</p> <pre><code>CREATE TABLE payload ( userid SERIAL PRIMARY KEY, duration INT, type TEXT, date INT ); </code></pre> <p>and then created the activity table like the following:</p> <pre><code>CREATE TABLE activity ( activity TEXT PRIMARY KEY SELECT userid, duration, type, date FROM payload; ); </code></pre>
[]
[ { "body": "<p>None of your columns are marked non-nullable. This is important for data integrity.</p>\n<p><code>duration</code> and <code>date</code> both seem mis-represented as <code>int</code>. You're in PostgreSQL, so read <a href=\"https://www.postgresql.org/docs/current/datatype-datetime.html\" rel=\"nofollow noreferrer\">https://www.postgresql.org/docs/current/datatype-datetime.html</a> and then consider instead</p>\n<ul>\n<li><code>interval</code> for <code>duration</code>, and</li>\n<li><code>date</code> for <code>date</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T15:04:04.313", "Id": "252847", "ParentId": "252839", "Score": "1" } } ]
{ "AcceptedAnswerId": "252847", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T10:02:06.877", "Id": "252839", "Score": "1", "Tags": [ "sql", "go", "postgresql" ], "Title": "Creating SQL Table from a Go Struct" }
252839
<p>I am trying to resolve following problem. Please advice which part of the code can be improved.</p> <p>Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.</p> <p>Example: Given the below binary tree and sum = 22,</p> <pre><code> 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 </code></pre> <p>return true, as there exist a root-to-leaf path 5-&gt;4-&gt;11-&gt;2 which sum is 22.</p> <p>Implementation:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; typedef struct stTree { struct stTree * left; struct stTree * right; int value; } stTree; struct stTestCase { stTree *root; int sum; bool result; }; stTree* createNode(int value, stTree *leftNode, stTree *rightNode) { stTree *node = malloc(sizeof *node); if (!node) abort(); node-&gt;left = leftNode; node-&gt;right = rightNode; node-&gt;value = value; return node; } bool hasPathSum(const stTree *root, int sum) { if (!root) return false; if (!root-&gt;left &amp;&amp; !root-&gt;right) { if (sum == root-&gt;value) return true; else return false; } return (hasPathSum(root-&gt;left, sum - root-&gt;value) | hasPathSum(root-&gt;right, sum - root-&gt;value)); } static stTree* findBottomLeft(stTree *node) { while (node-&gt;left) node = node-&gt;left; return node; } void freeTree(stTree *node) { if (!node) return true; stTree *bottomLeft = findBottomLeft(node); while (node) { if (node-&gt;right) { bottomLeft-&gt;left = node-&gt;right; bottomLeft = findBottomLeft(bottomLeft); } stTree *old = node; node = node-&gt;left; free(old); } } int main(void) { struct stTestCase test_cases[3]={ { createNode(5, createNode(4, createNode(11, createNode(7, NULL, NULL), createNode(2, NULL, NULL)), NULL), createNode(8, createNode(13, NULL, NULL), createNode(4, NULL, createNode(1, NULL, NULL)))), 22, true }, { createNode(5, createNode(1, createNode(11, createNode(3, NULL, NULL), createNode(2, NULL, NULL)), NULL), createNode(7, createNode(13, NULL, NULL), createNode(4, NULL, createNode(1, NULL, NULL)))), 22, false }, { createNode(12, createNode(4, createNode(11, createNode(7, NULL, NULL), createNode(51, NULL, NULL)), NULL), createNode(8, createNode(13, NULL, NULL), createNode(4, NULL, createNode(6, NULL, NULL)))), 22, false } }; for(int i=0; i&lt;3; i++) { if (hasPathSum(test_cases[i].root, test_cases[i].sum) == test_cases[i].result) printf(&quot;test case [%d], PASS\n&quot;, i); else printf(&quot;test case [%d], FAIL\n&quot;, i); freeTree(test_cases[i].root); } } </code></pre> <p>RESULT:</p> <p>test case [0], PASS</p> <p>test case [1], PASS</p> <p>test case [2], PASS</p>
[]
[ { "body": "<p>We don't normally do this in real (non-toy) programs:</p>\n<blockquote>\n<pre><code>stTree *node = malloc(sizeof *node);\nif (!node) abort();\n</code></pre>\n</blockquote>\n<p>It's convenient and probably okay for a simple exercise like this, though.</p>\n<hr />\n<p>Code of the form <code>if (c) then return true; else return false;</code> simplifies to just <code>return c;</code>, so we can reduce</p>\n<pre><code> if (sum == root-&gt;value)\n return true;\n else\n return false;\n</code></pre>\n<p>to just</p>\n<pre><code> return sum == root-&gt;value;\n</code></pre>\n<p>I think we can do better than that, if we're happy to consider an empty tree as having a sum of zero:</p>\n<pre><code>bool hasPathSum(const stTree *node, int sum)\n{\n if (!node) {\n return sum == 0;\n }\n\n sum -= node-&gt;value;\n return hasPathSum(node-&gt;left, sum) || hasPathSum(node-&gt;right, sum);\n}\n</code></pre>\n<p>Notice that I've used <code>||</code> rather than <code>|</code> in my version - there's no need to continue looking once we've found a successful result. Also, because this function is recursive, the name <code>root</code> is misleading for the parameter - it could be any node, and it's only the root in the top-level call.</p>\n<hr />\n<blockquote>\n<pre><code>void freeTree(stTree *node)\n{\n if (!node) return true;\n</code></pre>\n</blockquote>\n<p>That's a simple error - can't return a value from a function declared <code>void(...)</code>. That suggests you're not enabling enough compiler warnings.</p>\n<hr />\n<p>Good to see unit tests. I'm not sure I'd pile all the test data together like that - I'd probably create a small function for each test, so that each test is independent. Consider using one of the available test frameworks to help relieve the repetitive work of testing.</p>\n<p>When writing tests, it's a good idea to write the smallest test you can think of (e.g. the null tree) as the first test, and start with it failing (so you know the test works). Then make it pass, and write the next simplest failing tests (tree with one node - make sure you test calls that should return different values).</p>\n<p>Here's how I would begin (using Google Test, which is C++, but it's easy to test C code by using <code>extern &quot;C&quot;</code>):</p>\n<pre><code>#include &lt;gtest/gtest.h&gt;\n\nextern &quot;C&quot; {\n struct stTree;\n\n stTree* createNode(int value, stTree *leftNode, stTree *rightNode);\n bool hasPathSum(const stTree *node, int sum);\n void freeTree(stTree *node);\n}\n\nTEST(PathSum, empty)\n{\n stTree *tree = NULL;\n EXPECT_FALSE(hasPathSum(tree, 1));\n EXPECT_TRUE(hasPathSum(tree, 0));\n}\n\nTEST(PathSum, one_node)\n{\n stTree *tree = createNode(2, NULL, NULL);\n EXPECT_FALSE(hasPathSum(tree, 0));\n EXPECT_TRUE(hasPathSum(tree, 2));\n}\n\nTEST(PathSum, two_nodes)\n{\n stTree *tree = createNode(2, NULL,\n createNode(3, NULL, NULL));\n EXPECT_FALSE(hasPathSum(tree, 0));\n EXPECT_TRUE(hasPathSum(tree, 2));\n EXPECT_TRUE(hasPathSum(tree, 5));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T06:56:17.593", "Id": "498445", "Score": "0", "body": "Thanks. So what would you do to allocate memory in real life software." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T08:43:24.417", "Id": "498452", "Score": "1", "body": "The allocation would be exactly the same. It's the `abort()` that would be different - we'd hope to be able to recover gracefully. That would mean returning a null pointer from that function, so that the caller could choose how to deal with the problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T13:31:03.960", "Id": "252844", "ParentId": "252840", "Score": "2" } }, { "body": "<p>Good code.</p>\n<p>A few comments:</p>\n<p>I'd recommend getting into the habit of always using {..} after an if etc, even when they are not required. It's very easy to add code to a clause after an if, and forget to add the braces, so breaking the program. So instead of</p>\n<pre><code>if (!node) abort();\n</code></pre>\n<p>I'd write</p>\n<pre><code>if (!node) \n{ abort();\n}\n</code></pre>\n<p>freeTree() seems a bit complex to me. This seems simpler:</p>\n<pre><code>void freeTree(stTree *node)\n{ if ( node)\n { freeTree( node-&gt;left);\n freeTree( node-&gt;right);\n free( node);\n }\n}\n</code></pre>\n<p>There are two occurrences of the number of test cases in the program. It would be easy to forget to change at least one of them when you add/delete a test case. This could be eliminated by having the definition read</p>\n<pre><code>struct stTestCase test_cases[]={\n</code></pre>\n<p>(ie let the compiler figure out how many there are)\nand then the loop could be</p>\n<pre><code>int ncases = sizeof test_cases / sizeof test_cases[0];\n for(int i=0; i&lt;ncases; i++)\n</code></pre>\n<p>Your main is declared to return an int, but has no return statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T14:36:10.363", "Id": "252934", "ParentId": "252840", "Score": "1" } } ]
{ "AcceptedAnswerId": "252844", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T10:14:24.337", "Id": "252840", "Score": "1", "Tags": [ "c", "binary-tree" ], "Title": "Find Binary Tree Path Sum" }
252840
<p>I know my solution works, but I would like to know if the function can be simplified so that the loop is not called twice. Is there a way to pass the properties to be run through as parameters in the function?</p> <p>My given data structure looks like (in which <code>totalQuantities</code> and <code>typeQuantities</code> might contain an uncertain amount of objects):</p> <pre><code>data = [ { &quot;totalQuantities&quot;: [ { &quot;ammount&quot;: 23 } ], &quot;typeQuantities&quot;: [ { &quot;type&quot;: { &quot;id&quot;: 0, &quot;name&quot;: &quot;Test&quot; }, &quot;singleQuantities&quot;: [ { &quot;ammount&quot;: 45 } ] } ] } ] </code></pre> <p>My desired output is:</p> <pre><code>values = [ {type: 'Total', ammount1: 23}, {type: 'Test1', ammount1: 45} ] </code></pre> <p>And my solution - of which I'm wondering if there is another way to do so - is:</p> <pre><code>transformData(data) { const values = []; // loop through totalQuantities const objTotal: any = {}; objTotal.type = 'Total'; for (let i = 0; i &lt; data.totalQuantities.length; i++) { const name = 'ammount' + (i + 1).toString(); objTotal[name] = data.totalQuantities[i].ammount; } values.push(objTotal); // loop through each element of singleQuantities data.typeQuantities.map(element =&gt; { const obj: any = {}; obj.type = element.type.name; for (let i = 0; i &lt; element.singleQuantities.length; i++) { const name = 'ammount' + (i + 1).toString(); obj[name] = element.singleQuantities[i].ammount; } values.push(obj); }); return values; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T15:48:58.183", "Id": "498372", "Score": "1", "body": "You have a typo: **ammount** instead of **amount**." } ]
[ { "body": "<p>It looks like you're using TypeScript. TypeScript is great - it can turn difficult-to-debug runtime errors into trivially fixable compile errors. But for this sort of type checking to work:</p>\n<p><strong>Don't use <code>any</code></strong>, since it effectively disables type checking for that expression. TSLint rule: <a href=\"https://palantir.github.io/tslint/rules/no-any/\" rel=\"nofollow noreferrer\"><code>no-any</code></a>. Better to think about what the data structure will be, and type the expression appropriately.</p>\n<p><strong>Proper spelling</strong> is more professional and helps prevent bugs. Consider changing all the occurrences of <code>ammount</code> to <code>amount</code>.</p>\n<p><strong>Use an array instead of numerically indexed properties in an object</strong>, if at all possible - it'll make more sense as a data structure and will make iteration over it easier. For example, instead of having something like:</p>\n<pre><code>{type: 'Total', ammount1: 23, ammount2: 99, ammount3: 555},\n</code></pre>\n<p>would it be possible to tweak the user of the object to accept instead:</p>\n<pre><code>{type: 'Total', amounts: [23, 99, 555]}\n</code></pre>\n<p>? If I were you, I'd exert a significant amount of effort into making this change possible; it'd be a good structural improvement.</p>\n<p><strong>Use <code>.map</code> only when constructing an array by transforming every element of another array</strong> - if what you do inside the map is <em>side-effects</em> like <code>.push</code>, it would be more appropriate to use a generic iteration method like <code>.forEach</code>. But using <code>.map</code> and returning an object will make the code easier:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data=[{totalQuantities:[{amount:23}],typeQuantities:[{type:{id:0,name:\"Test\"},singleQuantities:[{amount:45}]}]}];\n\nconst transformData = (data) =&gt; {\n const objTotal = {\n type: 'total',\n amounts: data.totalQuantities.map(({ amount }) =&gt; amount)\n };\n const typeQuantitiesObjs = data.typeQuantities.map(element =&gt; ({\n type: element.type.name,\n amounts: element.singleQuantities.map(({ amount }) =&gt; amount)\n }));\n return [objTotal, ...typeQuantitiesObjs];\n};\n\nconsole.log(transformData(data[0]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>TypeScript works really well when all of your data transformation is <em>pure</em>, as done in the above snippet. When you construct arrays and objects outright instead of mutating them inside a loop, TypeScript can often infer the resulting types automatically, which means that the code doesn't have much type-related syntax, and can look just like JavaScript (and so is easy to read) - <em>despite still being type-safe</em>.</p>\n<blockquote>\n<p>so that the loop is not called twice</p>\n</blockquote>\n<p>I think the two data sources are too different for this to be done in an easy-to-understand way: one uses <code>type: 'total'</code>, the other uses <code>type: element.type.name,</code>. Also, one uses <code>.totalQuantities</code> to get the quantities, and the other uses <code>.singleQuantities</code>.</p>\n<p>While it would be <em>possible</em> to refactor to avoid the repetition of <code>{ type: .., amounts: ... }</code>, it would look somewhat convoluted; I wouldn't recommend it, it'll be harder to make sense of at a glance.</p>\n<p>If the output objects must contain <code>amount1</code> etc instead of a single array, I'd make a helper function that can transform an array of input quantities objects into a properly formatted object with <code>Object.fromEntries</code>, then call that function for both the <code>total</code> and the <code>typeQuantities</code>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data=[{totalQuantities:[{amount:23}],typeQuantities:[{type:{id:0,name:\"Test\"},singleQuantities:[{amount:45}]}]}];\n\nconst getAmounts = quantities =&gt; Object.fromEntries(\n quantities.map(\n ({ amount }, i) =&gt; ['amount' + (i + 1), amount]\n )\n);\nconst transformData = (data) =&gt; {\n const objTotal = {\n type: 'total',\n ...getAmounts(data.totalQuantities)\n };\n const typeQuantitiesObjs = data.typeQuantities.map(element =&gt; ({\n type: element.type.name,\n ...getAmounts(element.singleQuantities)\n }));\n return [objTotal, ...typeQuantitiesObjs];\n};\n\nconsole.log(transformData(data[0]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T07:07:13.087", "Id": "498447", "Score": "0", "body": "Thank you very much for your input. I surely agree with you on the typing and spelling. Unluckily the output has to be an object like '{type: 'Total', amount1: 23, amount2: 99, amount3: 555}' because it is passed on to a table which requires this kind of structure. Anyway it helps a lot to see that even more experienced coders recommend to keep a certain value of readability to the code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T15:21:23.023", "Id": "498473", "Score": "0", "body": "If the data is used for display immediately instead of being passed along to some other data processor, having separate `amount1` etc properties sounds fine to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T07:19:56.753", "Id": "498533", "Score": "0", "body": "Thank you! You're solution looks much more structured than mine - that was, what I was looking for" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T15:15:47.580", "Id": "252849", "ParentId": "252841", "Score": "5" } } ]
{ "AcceptedAnswerId": "252849", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T12:14:43.857", "Id": "252841", "Score": "2", "Tags": [ "javascript", "beginner" ], "Title": "Javascript - Loop through datastructure" }
252841
<p>I was working on new function with Pandas DataFrame. It's meant to sort values by column name but exclude specific rows from sorting and return sorted dataframe with that has rows with preserved positions.</p> <p>E.g. I have a DataFrame</p> <pre><code> Name marks rank1 Tom 10 rank2 Jack 30 rank3 nick 50 rank4 juli 5 </code></pre> <p>So I created a function (not finalized, but the idea)</p> <pre class="lang-py prettyprint-override"><code>def sort_df_values(df, column_names, ascending=False, fixed_categories=None): if fixed_categories is not None and fixed_categories: original_positions = {name: position for position, name in enumerate(df.index.values) if name in fixed_categories} original_positions = dict(sorted(original_positions.items(), key=operator.itemgetter(1), reverse=True)) excluded = df.loc[fixed_categories] included = [name for name in list(df.index) if name not in fixed_categories] new_df = df.loc[included].sort_values(column_names, ascending=ascending) result = pd.concat([new_df, excluded]) new_index_values = list(result.index.values) while original_positions: val, old_position = original_positions.popitem() print(val, old_position) for current_position, name in enumerate(new_index_values): if name == val: new_index_values.insert(old_position, new_index_values.pop(current_position)) break result = result.reindex(new_index_values) else: result = df.sort_values(column_names, ascending=ascending) return result </code></pre> <p>And then I call it like this:</p> <pre class="lang-py prettyprint-override"><code>sort_df_values(df, ['marks'], fixed_categories=['rank3']) </code></pre> <p>The result is correct, I sort all data, but I preserve the excluded rows positions:</p> <pre><code> Name marks rank2 Jack 30 rank1 Tom 10 rank3 nick 50 rank4 juli 5 </code></pre> <p>Is there any better option on how to do this? Maybe there is already some feature in pandas that could help me out on this one?</p> <p>DataFrame example:</p> <pre class="lang-py prettyprint-override"><code>{'Name': {'rank1': 'Tom', 'rank2': 'Jack', 'rank3': 'nick', 'rank4': 'juli'}, 'marks': {'rank1': 10, 'rank2': 30, 'rank3': 50, 'rank4': 5}} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T01:04:53.313", "Id": "498432", "Score": "0", "body": "Can you share the data in a more convenient format?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T06:58:33.913", "Id": "498446", "Score": "0", "body": "@AMC added example" } ]
[ { "body": "<p>When using <code>pandas</code> leverage on functions in API almost every function is vectorized.</p>\n<p>You can break down your problem into categories.</p>\n<ul>\n<li>If <code>fixed</code> is <code>None</code> just sort w.r.t given <code>column_names</code>.</li>\n<li>Else sort w.r.t given <code>column_names</code> but filter filter <code>fixed</code> indices.</li>\n<li>insert <code>fixed</code> at previous positions.</li>\n</ul>\n<pre><code>def sort_values(df, column_names, ascending=False, fixed=None):\n if fixed is None:\n return df.sort_values(column_names, ascending=ascending)\n idx = df.index.get_indexer(fixed).tolist()\n s_df = df.sort_values(column_names, ascending=ascending).T\n keep_cols = s_df.columns.difference(fixed, sort=False)\n out = s_df[keep_cols]\n for (loc, name) in zip(idx, fixed):\n out.insert(loc, name, s_df[name])\n return out.T\n</code></pre>\n<p><strong>Note:</strong> <code>fixed</code> should be a <code>list</code>.</p>\n<h3>Example runs:</h3>\n<pre><code>fixed = ['rank3']\nsort_values(df, ['marks'], ascending=False, fixed=fixed)\n\n# Name marks\n# rank2 Jack 30\n# rank1 Tom 10\n# rank3 nick 50 # rank3 position fixed.\n# rank4 juli 5\n\nfixed = ['rank2', 'rank3']\nsort_values(df, ['marks'], ascending=True, fixed=fixed) # ascending order.\n\n# sorted in ascending order\n# Name marks\n# rank4 juli 5\n# rank2 Jack 30 # rank2 position fixed\n# rank3 nick 50 # rank3 position fixed\n# rank1 Tom 10\n</code></pre>\n<h3>Code Review</h3>\n<ul>\n<li><h3><code>PEP-8</code> Violations</h3>\n<ul>\n<li><code>E501</code> - Lines longer than 79 characters. You have many lines with length greater than 79 characters.</li>\n</ul>\n</li>\n</ul>\n<pre><code># Examples\noriginal_positions = {name: position for position, name in enumerate(df.index.values) if name in fixed_categories}\n# Can be refactored as below \noriginal_positions = {\n name: position\n for position, name in enumerate(df.index.values)\n if name in fixed_categories\n}\n\noriginal_positions = dict(sorted(original_positions.items(), key=operator.itemgetter(1), reverse=True))\n# Can be refactored as below\noriginal_positions = dict(\n sorted(\n original_positions.items(), key=operator.itemgetter(1), reverse=True\n )\n)\n</code></pre>\n<hr />\n<p>You can use <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">pep8online</a><sup>*</sup> to check if your code is in accordance with PEP-8 standard.</p>\n<p>You can use <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\"><strong><code>black</code></strong></a><sup>*</sup> (code formatting tool)</p>\n<pre><code>black --line-length 79 your_file.py\n</code></pre>\n<hr />\n<p><sub><sub>* I'm not affiliated to <code>pep8online</code> and <code>black</code>.</sub></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T14:01:46.777", "Id": "500060", "Score": "0", "body": "Thanks very much for the good idea that is sound good what I was looking for. Regarding pep8, I know, this was just a dummy code :) But thanks for the note!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T13:49:52.097", "Id": "253573", "ParentId": "252842", "Score": "1" } } ]
{ "AcceptedAnswerId": "253573", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T13:10:11.217", "Id": "252842", "Score": "1", "Tags": [ "python", "sorting", "pandas" ], "Title": "Pandas DataFrame.sort_values() new method to exclude by row name" }
252842
<p>I've been learning C++ for a while. I wrote <a href="https://codereview.stackexchange.com/questions/193840/bank-management-system">this</a> app sometimes ago. The feedback that I got for that app was quite helpful. Now I rewrote the app using the new knowledge that I acquired while learning. This app has been complied with MSVC std-c++14. I want to learn writing efficient code with as <strong>little memory usage</strong> as possible with <strong>zero try...catch</strong> block (if possible). Any suggestions on these aspects or any other area are appreciated.</p> <p><strong>bankdata.h</strong></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;fstream&gt; #include &quot;defines.h&quot; class BankData { public: BankData(); BankData(const char* name, const AccountType&amp; acType, const long double&amp; balance); BankData(const BankData&amp; src) = default; BankData(BankData&amp;&amp; src) noexcept = default; BankData&amp; operator=(const BankData&amp; other) = default; BankData&amp; operator=(BankData&amp;&amp; other) noexcept = default; ~BankData() = default; bool operator==(const unsigned long&amp; acNum) const; bool operator==(const char* name) const; operator std::string() const; public: const char* getName() const; void setName(const char* name); AccountType getAcType() const; void setAcType(const AccountType&amp; acType); long double getBalance() const; void setBalace(const long double&amp; balace); unsigned long getAcNum() const; void setAcNum(const unsigned long&amp; acNum); std::ofstream&amp; prepareForStore(std::ofstream&amp; ofs) const; public: static unsigned long getAccountCount(); static void setAccountCount(const unsigned long&amp; count); private: char m_name[MAX_STR_LEN]; AccountType m_acType; long double m_balance; unsigned long m_acNum; private: static unsigned long sm_acNum; }; </code></pre> <p><strong>BankData.cc</strong></p> <pre><code>#include &lt;cstring&gt; #include &lt;sstream&gt; #include &quot;bankdata.h&quot; unsigned long BankData::sm_acNum = 0UL; BankData::BankData() : m_acNum(0UL), m_name(&quot;&quot;), m_acType(AccountType::CURRENT), m_balance(0.0L) { } BankData::BankData(const char* name, const AccountType&amp; acType, const long double&amp; balance) : m_acType(acType), m_balance(balance) { ++BankData::sm_acNum; this-&gt;m_acNum = BankData::sm_acNum; strcpy_s(this-&gt;m_name, MAX_STR_LEN, name); } bool BankData::operator==(const unsigned long&amp; acNum) const { return this-&gt;m_acNum == acNum; } bool BankData::operator==(const char* name) const { return std::strcmp(this-&gt;m_name, name) == 0; } BankData::operator std::string() const { std::ostringstream oss; oss &lt;&lt; &quot;Account Number:&quot; &lt;&lt; TAB &lt;&lt; this-&gt;m_acNum &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Account Holder:&quot; &lt;&lt; TAB &lt;&lt; this-&gt;m_name &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Account Type:&quot; &lt;&lt; TAB &lt;&lt; accountTypeToString(this-&gt;m_acType) &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Account Balance&quot; &lt;&lt; TAB &lt;&lt; this-&gt;m_balance; return oss.str(); } const char* BankData::getName() const { return this-&gt;m_name; } void BankData::setName(const char* name) { strcpy_s(this-&gt;m_name, MAX_STR_LEN, name); } AccountType BankData::getAcType() const { return this-&gt;m_acType; } void BankData::setAcType(const AccountType&amp; acType) { this-&gt;m_acType = acType; } long double BankData::getBalance() const { return this-&gt;m_balance; } void BankData::setBalace(const long double&amp; balace) { this-&gt;m_balance = balace; } unsigned long BankData::getAcNum() const { return this-&gt;m_acNum; } void BankData::setAcNum(const unsigned long&amp; acNum) { this-&gt;m_acNum = acNum; } std::ofstream&amp; BankData::prepareForStore(std::ofstream&amp; ofs) const // serialization { ofs &lt;&lt; this-&gt;m_acNum &lt;&lt; ';' &lt;&lt; this-&gt;m_name &lt;&lt; '\0' &lt;&lt; accountTypeToChar(this-&gt;m_acType) &lt;&lt; ';' &lt;&lt; this-&gt;m_balance; return ofs; } unsigned long BankData::getAccountCount() { return BankData::sm_acNum; } void BankData::setAccountCount(const unsigned long&amp; count) { BankData::sm_acNum = count; } </code></pre> <p><strong>bankmanager.h</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;string&gt; #include &quot;bankdata.h&quot; #include &quot;defines.h&quot; class BankManager final { public: BankManager(); BankManager(const BankManager&amp; src) = delete; BankManager(BankManager&amp;&amp; src) noexcept = delete; BankManager&amp; operator=(const BankManager&amp; other) = delete; BankManager&amp; operator=(BankManager&amp;&amp; other) noexcept = delete; ~BankManager() = default; operator std::string() const; public: bool createNewAccount(const char* name, const AccountType&amp; acType, const long double&amp; balance); bool deleteAccount(const unsigned long&amp; acNum, const char* name); bool updateBalance(const unsigned long&amp; acNum, const char* name, const long double&amp; balance); bool updateAccountInfo(const unsigned long&amp; acNum, const char* name, const char* newName); bool updateAccountInfo(const unsigned long&amp; acNum, const char* name, const AccountType&amp; acType); bool updateAccountInfo(const unsigned long&amp; acNum, const char* name, const char* newName, const AccountType* acType); bool accountExists(const unsigned long&amp; acNum) const; bool accountExists(const char* name) const; const BankData&amp; getBankData(const unsigned long&amp; acNum) const; BankData&amp; getBankData(const unsigned long&amp; acNum); bool isEmpty() const; std::string to_string() const; bool store() const; bool load(); private: size_t indexOf(const unsigned long&amp; acNum) const; private: std::vector&lt;BankData&gt; m_bankInfo{}; }; </code></pre> <p><strong>BankManager.cc</strong></p> <pre><code>#include &lt;algorithm&gt; #include &lt;utility&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; #include &lt;fstream&gt; #include &lt;cstdlib&gt; #include &quot;bankmanager.h&quot; #include &quot;defines.h&quot; static const char* storeFileName = &quot;v8.dat&quot;; bool BankManager::createNewAccount(const char* name, const AccountType&amp; acType, const long double&amp; balance) { if (this-&gt;accountExists(name)) { return false; } this-&gt;m_bankInfo.push_back(BankData(name, acType, balance)); // move constructor is called return true; } bool BankManager::deleteAccount(const unsigned long&amp; acNum, const char* name) { if (!this-&gt;accountExists(acNum) || !this-&gt;accountExists(name)) { return false; } this-&gt;m_bankInfo.erase(this-&gt;m_bankInfo.begin() + this-&gt;indexOf(acNum)); return true; } bool BankManager::updateBalance(const unsigned long&amp; acNum, const char* name, const long double&amp; balance) { if (!this-&gt;accountExists(acNum) || !this-&gt;accountExists(name)) { return false; } BankData&amp; clientData = this-&gt;getBankData(acNum); long double curBalance = clientData.getBalance(); curBalance += balance; clientData.setBalace(curBalance); return true; } bool BankManager::updateAccountInfo(const unsigned long&amp; acNum, const char* name, const char* newName) { return this-&gt;updateAccountInfo(acNum, name, newName, nullptr); } bool BankManager::accountExists(const char* name) const { return std::find(this-&gt;m_bankInfo.begin(), this-&gt;m_bankInfo.end(), name) != this-&gt;m_bankInfo.end(); } size_t BankManager::indexOf(const unsigned long&amp; acNum) const { return std::find(this-&gt;m_bankInfo.begin(), this-&gt;m_bankInfo.end(), acNum) - this-&gt;m_bankInfo.begin(); } BankData&amp; BankManager::getBankData(const unsigned long&amp; acNum) { size_t pos = this-&gt;indexOf(acNum); return this-&gt;m_bankInfo.at(pos); } bool BankManager::isEmpty() const { return this-&gt;m_bankInfo.empty(); } std::string BankManager::to_string() const { return this-&gt;operator std::string(); } bool BankManager::store() const // serialization { std::ofstream ofs(storeFileName, std::ios::binary | std::ios::out); // not a good approach since we may have big chunk of data so we create file each time we invoke store() if (!ofs.good() || !ofs.is_open()) // what would be a better option? { return false; } ofs &lt;&lt; this-&gt;m_bankInfo.size() &lt;&lt; '*' &lt;&lt; BankData::getAccountCount() &lt;&lt; '*'; for (const BankData&amp; b : this-&gt;m_bankInfo) { b.prepareForStore(ofs) &lt;&lt; '*'; } ofs.close(); return true; } bool BankManager::load() // deserialization; only call once at app initialization { std::ifstream ifs(storeFileName, std::ios::in | std::ios::binary); if (!ifs.good() || !ifs.is_open()) { return false; } std::string tmp; std::getline(ifs, tmp, '*'); // vSize size_t vSize = std::stoull(tmp); std::getline(ifs, tmp, '*'); // count unsigned long acCount = std::stoul(tmp); BankData::setAccountCount(acCount); for (size_t i = 0UL; i &lt; vSize; i++) { std::getline(ifs, tmp, ';'); acCount = std::stoul(tmp); // acNum, in this case BankData b; b.setAcNum(acCount); std::getline(ifs, tmp, '\0'); // name b.setName(tmp.c_str()); std::getline(ifs, tmp, ';'); // acType AccountType acType = charToAccountType(tmp[0]); b.setAcType(acType); std::getline(ifs, tmp, '*'); // balance long double balance = std::stold(tmp); b.setBalace(balance); this-&gt;m_bankInfo.push_back(std::move(b)); // 'b' is not a r-value, so we cast it one } return true; } const BankData&amp; BankManager::getBankData(const unsigned long&amp; acNum) const { //return const_cast&lt;const BankData&amp;&gt;(this-&gt;getBankData(acNum)); // won't work since it's gonna cause overflow // return a const version of BankData&amp; size_t pos = this-&gt;indexOf(acNum); return this-&gt;m_bankInfo.at(pos); } bool BankManager::updateAccountInfo(const unsigned long&amp; acNum, const char* name, const AccountType&amp; acType) { return this-&gt;updateAccountInfo(acNum, name, nullptr, &amp;acType); } bool BankManager::updateAccountInfo(const unsigned long&amp; acNum, const char* name, const char* newName, const AccountType* acType) { if (name == nullptr &amp;&amp; acType == nullptr) { return false; } if (!this-&gt;accountExists(acNum) || !this-&gt;accountExists(name)) { return false; } BankData&amp; clientData = this-&gt;getBankData(acNum); if (newName != nullptr) { clientData.setName(newName); } if (acType != nullptr) { clientData.setAcType(*acType); } return true; } bool BankManager::accountExists(const unsigned long&amp; acNum) const { return std::find(this-&gt;m_bankInfo.begin(), this-&gt;m_bankInfo.end(), acNum) != this-&gt;m_bankInfo.end(); } BankManager::BankManager() { if (existsFile(storeFileName)) { if (!this-&gt;load()) { std::exit(EXIT_FAILURE); } } } BankManager::operator std::string() const { std::ostringstream oss; for (size_t i = 0UL; i &lt; this-&gt;m_bankInfo.size(); i++) { oss &lt;&lt; this-&gt;m_bankInfo.at(i).getAcNum() &lt;&lt; std::setw(28) &lt;&lt; this-&gt;m_bankInfo.at(i).getName() &lt;&lt; std::setw(25) &lt;&lt; accountTypeToChar(this-&gt;m_bankInfo.at(i).getAcType()) &lt;&lt; std::setw(39) &lt;&lt; this-&gt;m_bankInfo.at(i).getBalance() &lt;&lt; '\n'; } return oss.str(); } </code></pre> <p><strong>displayui.h</strong></p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;vector&gt; class DisplayUI final { public: DisplayUI() = delete; explicit DisplayUI(void(*clearFunc)()); DisplayUI(const DisplayUI&amp; src) = delete; DisplayUI(DisplayUI&amp;&amp; src) noexcept = delete; DisplayUI&amp; operator=(const DisplayUI&amp; other) = delete; DisplayUI&amp; operator=(DisplayUI&amp;&amp; other) noexcept = delete; ~DisplayUI() = default; public: char mainMenu() const; void coverMenu() const; void accountStatusMenu(const std::string&amp; accFormatStr) const; void allAccountMenu(const std::string&amp; accListFormatStr) const; void clearScreen() const; void printTransectionHeader(const char* str) const; std::string&amp; getHeadingMenuString(const char* menuName, char character, size_t len, std::string&amp; out) const; private: void (*m_clear)(); }; </code></pre> <p><strong>DisplayUI.cc</strong></p> <pre><code>#include &lt;cstring&gt; #include &lt;string&gt; #include &lt;conio.h&gt; // _getch() #include &lt;iomanip&gt; #include &lt;sstream&gt; #include &lt;utility&gt; #include &quot;displayui.h&quot; #include &quot;defines.h&quot; char DisplayUI::mainMenu() const { sleepFor(300); this-&gt;clearScreen(); char options[] = &quot;12345678&quot;; char ret = '\0'; const char* menuHeaders[MENU_HEADER_ARRAY_LEN] = { &quot;CREATE AN ACCOUNT&quot;, &quot;DIPOSIT AMOUNT&quot;, &quot;WITHDRAW AMOUNT&quot;, &quot;BALANCE ENQUIRE&quot;, &quot;VIEW LIST OF ALL ACCOUNT HOLDERS&quot;, &quot;CLOSE AN ACCOUNT&quot;, &quot;MODIFY AN ACCOUNT&quot;, &quot;EXIT&quot; }; std::cout &lt;&lt; CARRIAGE_RETURN &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;MAIN MENU&quot; &lt;&lt; DOUBLE_NEWLINE; for (size_t i = 0UL; i &lt; MENU_HEADER_ARRAY_LEN; i++) { std::cout &lt;&lt; DOUBLE_TAB &lt;&lt; '0' &lt;&lt; i + 1 &lt;&lt; &quot; &quot; &lt;&lt; menuHeaders[i] &lt;&lt; DOUBLE_NEWLINE; } do { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Please select &lt;1-8&gt; to operate:&quot; &lt;&lt; DOUBLE_TAB; ret = _getch(); size_t optionsLen = std::strlen(options); for (size_t i = 0UL; i &lt; optionsLen; i++) { if (options[i] == ret) { return ret; } } } while (true); } void DisplayUI::coverMenu() const { std::cout &lt;&lt; TEN_NEWLINE &lt;&lt; TRIPPLE_TAB &lt;&lt; &quot;Welcome to BankManager v2.0: A Banking Management System by Alex&quot; &lt;&lt; DOUBLE_NEWLINE &lt;&lt; TRIPPLE_TAB &lt;&lt; &quot;Please Press 'Enter' To Continue...&quot; &lt;&lt; TRIPPLE_NEWLINE &lt;&lt; TRIPPLE_TAB; std::cin.get(); sleepFor(2000); this-&gt;clearScreen(); } void DisplayUI::accountStatusMenu(const std::string&amp; accFormatStr) const { std::string temp; std::cout &lt;&lt; CARRIAGE_RETURN &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; this-&gt;getHeadingMenuString(&quot;ACCOUNT STATUS&quot;, '-', 5UL, temp) &lt;&lt; TRIPPLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; accFormatStr &lt;&lt; NEWLINE; } void DisplayUI::allAccountMenu(const std::string&amp; accListFormatStr) const { char heading[] = &quot;List of All the Account Holders&quot;; size_t headingLen = std::strlen(heading); std::string space(headingLen * 3, '-'); std::cout &lt;&lt; TRIPPLE_NEWLINE &lt;&lt; std::setw(headingLen * 2) &lt;&lt; heading &lt;&lt; std::setw(headingLen * 2) &lt;&lt; DOUBLE_NEWLINE &lt;&lt; space &lt;&lt; NEWLINE &lt;&lt; &quot;Ac No.&quot; &lt;&lt; std::setw(20) &lt;&lt; &quot;Name&quot; &lt;&lt; std::setw(30) &lt;&lt; &quot;Type&quot; &lt;&lt; std::setw(38) &lt;&lt; &quot;Amount&quot; &lt;&lt; NEWLINE &lt;&lt; space &lt;&lt; NEWLINE &lt;&lt; accListFormatStr &lt;&lt; space &lt;&lt; NEWLINE; } void DisplayUI::clearScreen() const { this-&gt;m_clear(); } void DisplayUI::printTransectionHeader(const char* str) const { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Enter the amount to &quot; &lt;&lt; str &lt;&lt; ':' &lt;&lt; TAB; } DisplayUI::DisplayUI(void(*clearFunc)()) : m_clear(clearFunc) { } std::string&amp; DisplayUI::getHeadingMenuString(const char* menuName, char character, size_t len, std::string&amp; out) const { std::ostringstream oss; oss &lt;&lt; std::move(std::string(len, character)) &lt;&lt; menuName &lt;&lt; std::move(std::string(len, character)); out = std::move(oss.str()); return out; } </code></pre> <p><strong>bankmanagerapp.h</strong></p> <pre><code>#pragma once #include &quot;bankmanager.h&quot; #include &quot;displayui.h&quot; class BankManagerApp final { public: BankManagerApp() = delete; explicit BankManagerApp(void(*clearFunc)()); BankManagerApp(const BankManagerApp&amp; src) = delete; BankManagerApp(BankManagerApp&amp;&amp; src) noexcept = delete; BankManagerApp&amp; operator=(const BankManagerApp&amp; other) = delete; BankManagerApp&amp; operator=(BankManagerApp&amp;&amp; other) noexcept = delete; ~BankManagerApp(); public: void run(); private: void createNewAccount(); void updateBalance(const unsigned long&amp; acNum, const char* name, bool deposit=true); void showAccountStatus(const unsigned long&amp; acNum) const; void showAllAccounts() const; void updateAccountInfo(const unsigned long&amp; acNum, const char* name); void deleteAccount(const unsigned long&amp; acNum, const char* name); void getAccoutInfo(unsigned long&amp; acNum, std::string&amp; name) const; private: BankManager* m_ptrBM; DisplayUI* m_ptrDisUI; }; </code></pre> <p><strong>BankManagerApp.cc</strong></p> <pre><code>#include &lt;cctype&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &quot;bankmanagerapp.h&quot; #include &quot;defines.h&quot; BankManagerApp::BankManagerApp(void(*clearFunc)()) : m_ptrBM(new BankManager()), m_ptrDisUI(new DisplayUI(clearFunc)) { // this may throw std::bad_alloc // how to overcome this without checking if these two // pointers are nullptr or not for each function call? } BankManagerApp::~BankManagerApp() { delete this-&gt;m_ptrBM; delete this-&gt;m_ptrDisUI; } void BankManagerApp::run() { this-&gt;m_ptrDisUI-&gt;coverMenu(); bool continueProgram = true; while (continueProgram) { char userChoice = this-&gt;m_ptrDisUI-&gt;mainMenu(); unsigned long acNum = 0UL; std::string name; switch (userChoice) { case '1': this-&gt;createNewAccount(); break; case '2': this-&gt;getAccoutInfo(acNum, name); if (acNum != 0UL) { this-&gt;updateBalance(acNum, name.c_str()); } break; case '3': this-&gt;getAccoutInfo(acNum, name); if (acNum != 0UL) { this-&gt;updateBalance(acNum, name.c_str(), false); } break; case '4': this-&gt;getAccoutInfo(acNum, name); if (acNum != 0UL) { this-&gt;showAccountStatus(acNum); std::cin.ignore(); } break; case '5': this-&gt;showAllAccounts(); std::cin.ignore(); break; case '6': this-&gt;getAccoutInfo(acNum, name); if (acNum != 0UL) { this-&gt;deleteAccount(acNum, name.c_str()); } break; case '7': this-&gt;getAccoutInfo(acNum, name); if (acNum != 0UL) { this-&gt;updateAccountInfo(acNum, name.c_str()); } break; case '8': continueProgram = false; this-&gt;m_ptrBM-&gt;store(); // we store any everything at the end of program; since a CLI app shouldn't be closed using 'X' button, we don't break; // need to store the data after each transaction or modification of the user data } // however, this is &quot;not&quot; a good idea since program can terminate for other reasons, so we won't get any unsaved data } // nonetheless, for this simple app I think it is okay } void BankManagerApp::createNewAccount() { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); std::vector&lt;std::string&gt; accountInfo{}; std::string temp; std::cout &lt;&lt; CARRIAGE_RETURN &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; this-&gt;m_ptrDisUI-&gt;getHeadingMenuString(&quot;Register New Account&quot;, '*', 5UL, temp); do { std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Enter the Name of the Account Holder:&quot; &lt;&lt; DOUBLE_TAB; std::getline(std::cin, temp); // account name if (this-&gt;m_ptrBM-&gt;accountExists(temp.c_str())) { std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;The person already has account!&quot; &lt;&lt; NEWLINE; sleepFor(1000); this-&gt;m_ptrDisUI-&gt;clearScreen(); } } while (temp.compare(&quot;&quot;) == 0 || this-&gt;m_ptrBM-&gt;accountExists(temp.c_str())); accountInfo.push_back(std::move(temp)); do { std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Enter the Type &lt;C/S/F&gt;:&quot; &lt;&lt; DOUBLE_TAB &lt;&lt; DOUBLE_TAB; std::getline(std::cin, temp); // account type if (temp[0] == 'C' || temp[0] == 'S' || temp[0] == 'F') { break; } } while (true); accountInfo.push_back(std::move(temp)); do { std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Enter the Amount:&quot; &lt;&lt; DOUBLE_TAB &lt;&lt; DOUBLE_TAB; std::getline(std::cin, temp); // balance } while (temp.compare(&quot;&quot;) == 0 || !isFloat(temp)); accountInfo.push_back(std::move(temp)); if (!this-&gt;m_ptrBM-&gt;createNewAccount( accountInfo.at(0).c_str(), charToAccountType(accountInfo.at(1)[0]), std::stold(accountInfo.at(2)))) { std::cout &lt;&lt; &quot;couldn't create account\n&quot;; } else { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; TRIPPLE_TAB &lt;&lt; &quot;Record Updated!!!&quot;; } } void BankManagerApp::updateBalance(const unsigned long&amp; acNum, const char* name, bool deposit) { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); std::string temp; const char* msg = deposit ? &quot;Deposit to Account&quot; : &quot;Withdraw from Account&quot;; long double balance = 0.0L; std::cout &lt;&lt; TRIPPLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; this-&gt;m_ptrDisUI-&gt;getHeadingMenuString(msg, '*', 5UL, temp); const BankData&amp; clientData = this-&gt;m_ptrBM-&gt;getBankData(acNum); temp = std::move(static_cast&lt;std::string&gt;(clientData)); this-&gt;m_ptrDisUI-&gt;accountStatusMenu(temp); do { this-&gt;m_ptrDisUI-&gt;printTransectionHeader(deposit ? &quot;DEPOSIT&quot; : &quot;WITHDRAW&quot;); std::getline(std::cin, temp); } while (temp.compare(&quot;&quot;) == 0 || !isFloat(temp)); balance = std::stold(temp); if (!deposit) { balance *= -1L; // to make negative // balance -= balance * 2 -&gt; make positive } if (!this-&gt;m_ptrBM-&gt;updateBalance(acNum, name, balance)) { std::cout &lt;&lt; &quot;couldn't update balance\n&quot;; } else { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; TRIPPLE_TAB &lt;&lt; &quot;Record Updated!!!&quot;; } } void BankManagerApp::showAccountStatus(const unsigned long&amp; acNum) const { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); const BankData&amp; clientData = this-&gt;m_ptrBM-&gt;getBankData(acNum); std::string temp(std::move(static_cast&lt;std::string&gt;(clientData))); this-&gt;m_ptrDisUI-&gt;accountStatusMenu(temp); } void BankManagerApp::showAllAccounts() const { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); std::string temp(std::move(this-&gt;m_ptrBM-&gt;to_string())); this-&gt;m_ptrDisUI-&gt;allAccountMenu(temp); } void BankManagerApp::updateAccountInfo(const unsigned long&amp; acNum, const char* name) { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); std::string temp; const char* options[2] = { &quot;Account holder's name&quot;, &quot;Account type&quot; }; std::cout &lt;&lt; TRIPPLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; this-&gt;m_ptrDisUI-&gt;getHeadingMenuString(&quot;Modify An Account Information&quot;, '*', 5UL, temp); for (int i = 0; i &lt; 2; i++) { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Please press &quot; &lt;&lt; i + 1 &lt;&lt; &quot; to edit &quot; &lt;&lt; options[i] &lt;&lt; NEWLINE; } int userChoice = 0; do { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; ROOT_SYMBOL; std::getline(std::cin, temp); if (temp[0] == '1' || temp[0] == '2') { break; } } while (true); userChoice = temp[0] - '0'; switch (userChoice) { case 1: { do { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Please enter new name:&quot; &lt;&lt; TAB; std::getline(std::cin, temp); } while (temp.compare(&quot;&quot;) == 0); } break; case 2: { do { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Enter enter new account type &lt;C/S/F&gt;:&quot; &lt;&lt; DOUBLE_TAB &lt;&lt; DOUBLE_TAB; std::getline(std::cin, temp); if (temp[0] == 'C' || temp[0] == 'S' || temp[0] == 'F') { break; } } while (true); } break; default: return; } std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Press \&quot;M\&quot; to modify again&quot; &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Press \&quot;S\&quot; save and exit&quot; &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Press \&quot;N\&quot; to exit without saving&quot;; char userResponse = '\0'; std::string temp2; // is there a way to avoid this? since I can't use 'temp' here which is holding value we need later do { std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; ROOT_SYMBOL; std::getline(std::cin, temp2); if (temp2[0] == 'M' || temp2[0] == 'S' || temp2[0] == 'N') { break; } } while (true); userResponse = temp2[0]; switch (userResponse) { case 'M': this-&gt;updateAccountInfo(acNum, name); break; case 'S': { bool res = userChoice == 1 ? this-&gt;m_ptrBM-&gt;updateAccountInfo(acNum, name, temp.c_str()) : this-&gt;m_ptrBM-&gt;updateAccountInfo(acNum, name, charToAccountType(temp[0])); if (!res) { std::cout &lt;&lt; &quot;couldn't update account information\n&quot;; } else { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; TRIPPLE_TAB &lt;&lt; &quot;Record Updated!!!&quot;; } } break; default: return; } } void BankManagerApp::deleteAccount(const unsigned long&amp; acNum, const char* name) { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); if (!this-&gt;m_ptrBM-&gt;deleteAccount(acNum, name)) { std::cout &lt;&lt; &quot;couldn't delete account\n&quot;; } else { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; TRIPPLE_TAB &lt;&lt; &quot;Record Updated!!!&quot;; } } void BankManagerApp::getAccoutInfo(unsigned long&amp; acNum, std::string&amp; name) const { sleepFor(500); this-&gt;m_ptrDisUI-&gt;clearScreen(); std::string tmp; do { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Please enter the account number:&quot; &lt;&lt; DOUBLE_TAB; std::getline(std::cin, tmp); } while (tmp.compare(&quot;&quot;) == 0 || !isDigit(tmp)); acNum = std::stoul(tmp); do { std::cout &lt;&lt; DOUBLE_NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Please enter the account holder's name:&quot; &lt;&lt; DOUBLE_TAB; std::getline(std::cin, name); } while (name.compare(&quot;&quot;) == 0); if (!this-&gt;m_ptrBM-&gt;isEmpty()) { if (!this-&gt;m_ptrBM-&gt;accountExists(acNum) || !this-&gt;m_ptrBM-&gt;accountExists(name.c_str())) { acNum = 0UL; name.clear(); std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;Not found!&quot; &lt;&lt; NEWLINE; sleepFor(1000); } } else { acNum = 0UL; name.clear(); std::cout &lt;&lt; NEWLINE &lt;&lt; DOUBLE_TAB &lt;&lt; &quot;No account has been created!\n&quot;; sleepFor(1000); } } </code></pre> <p><strong>defines.h</strong></p> <pre><code>#pragma once #include &lt;chrono&gt; #include &lt;thread&gt; #include &lt;cctype&gt; #include &lt;regex&gt; #include &lt;fstream&gt; constexpr size_t MAX_STR_LEN = 30UL; constexpr size_t MENU_HEADER_ARRAY_LEN = 8UL; constexpr const char* DOUBLE_NEWLINE = &quot;\n\n&quot;; constexpr char NEWLINE = '\n'; constexpr char TAB = '\t'; constexpr const char* TEN_NEWLINE = &quot;\n\n\n\n\n\n\n\n\n\n&quot;; constexpr const char* TRIPPLE_NEWLINE = &quot;\n\n\n&quot;; constexpr const char* DOUBLE_TAB = &quot;\t\t&quot;; constexpr const char* TRIPPLE_TAB = &quot;\t\t\t&quot;; constexpr char CARRIAGE_RETURN = '\r'; constexpr const char* ROOT_SYMBOL = &quot;&gt;&gt;&gt; &quot;; enum class AccountType { CURRENT, SAVINGS, FIXED }; static void sleepFor(unsigned long milSec) { std::this_thread::sleep_for(std::chrono::milliseconds(milSec)); } static AccountType charToAccountType(char c) { return c == 'C' ? AccountType::CURRENT : c == 'S' ? AccountType::SAVINGS : AccountType::FIXED; } static char accountTypeToChar(const AccountType&amp; accType) { return accType == AccountType::CURRENT ? 'C' : accType == AccountType::SAVINGS ? 'S' : 'F'; } static const char* accountTypeToString(const AccountType&amp; accType) { return accType == AccountType::CURRENT ? &quot;CURRENT&quot; : accType == AccountType::SAVINGS ? &quot;SAVINGS&quot; : &quot;FIXED&quot;; } static bool isDigit(const std::string&amp; str) { std::string::const_iterator cit = str.cbegin(); while (cit != str.end() &amp;&amp; std::isdigit(*cit)) { ++cit; } return !str.empty() &amp;&amp; cit == str.end(); } static bool isFloat(const std::string&amp; str) { std::regex pattern(&quot;[0-9]*\\.?[0-9]+$&quot;); return std::regex_match(str, pattern); } static bool existsFile(const char* name) { std::ifstream ifs(name); return ifs.good(); } </code></pre> <p><strong>main.cc</strong></p> <pre><code>#if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #include &lt;Windows.h&gt; #include &quot;bankmanagerapp.h&quot; static void clear() // os dependent { COORD topLeft{ 0, 0 }; HANDLE console = ::GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; ::GetConsoleScreenBufferInfo(console, &amp;screen); ::FillConsoleOutputCharacterA(console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &amp;written); ::FillConsoleOutputAttribute(console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &amp;written); ::SetConsoleCursorPosition(console, topLeft); } int main(int argc, const char* argv[]) { BankManagerApp app(clear); app.run(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:20:21.130", "Id": "498406", "Score": "0", "body": "Do you have any reason for not using `std::string` in `bankdata.h`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:34:32.493", "Id": "498409", "Score": "0", "body": "@theProgrammer I could use `const std::string&` but I read somewhere (don't remember the source right now), that they could create temporary r-values. Correct me if I'm wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T05:09:53.867", "Id": "498438", "Score": "0", "body": "@AJ yes, use `string_view`." } ]
[ { "body": "<p>In general in the new versions of c++, to be more precise on 17, <strong>const char</strong>* can be changed to <strong>std::string_view</strong>. Is an easy change and your code will be more up to date.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:38:36.623", "Id": "498410", "Score": "0", "body": "Thanks. This could be an option but didn't want to upgrade to std-c++17 just for this only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T05:07:22.777", "Id": "498436", "Score": "0", "body": "@AJ What are the downsides of upgrading to C++17? Moreover, using `string_view` is safer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T05:09:27.060", "Id": "498437", "Score": "0", "body": "This is a good point, but if you add **why** using `string_view` would be better, your answer will be better." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:13:47.690", "Id": "252863", "ParentId": "252843", "Score": "0" } }, { "body": "<h2>Unnecessay <code>*this</code></h2>\n<p>The use of <code>*this</code> is both unnecessary and reductant. when you call a member function with an object of the class, it implicitly calls it with the object as its first argument, this can simply be explained as thus\n<code>BankData(*this, args)</code></p>\n<p>so the extra-qualification just makes the code unreadable and adds no gain.</p>\n<h2>Prefer <code>std::string</code> to <code>const char*</code></h2>\n<p>const char* pointer is error-prone, I can't seem to understand why you are favoring error-proned <code>const char*</code> to <code>std::string</code>, your <code>BankData</code> constructor copies elements of the argument <code>name</code> to <code>m_name</code> which could have been simply written as m_name = name</p>\n<h2>No need for a destructor</h2>\n<p>BankData includes a destructor which is unnecessary, a destructor is only needed when you acquire a resource e.g lock, memory etc. Your class doesn't do any of those so no need of declaring it, also copy assignment and move assignment are not needed, let the compiler do the job for you.</p>\n<h2>Overload <code>operator&lt;&lt;</code> instead of calling std::string:</h2>\n<p>I tried calling <code>operator&lt;&lt;</code> for BankData class only for me to realize it was not implemented, you alternatively implemented <code>std::string()</code>. I believe <code>std::cout &lt;&lt; my_bankdata</code> is more elegant and simple to understand than <code>std::string(my_bankdata)</code></p>\n<h2>reduce your setters and getters</h2>\n<p><code>AccountType</code> is currently an enum class, you don't need a setter and getter here, setters and getters are mostly used when you want to protect the class from invalid data, in this case, setters and getters should be removed, since users of the class would only initialize the account type with members of the enum class.</p>\n<p>As a side note:\nInstead of checking both account number and account name, define <code>operator==</code> that compares two bankdata.</p>\n<h2>Too many indirection</h2>\n<p><code>getBankData(acNum)</code> calls <code>indexOf(accNum)</code>, if you defined an <code>operator==</code>, getBankData can be found easily with <code>std::find.</code> Note <code>std::find</code> returns an iterator pointing to the element or off-the-end iterator if it wasn't found.</p>\n<p>Instead of set and get for balance data member, have a function balance that returns a reference and const reference to balance. Updating the balace would simply be\n<code>clientData.balance += bal</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T20:02:22.053", "Id": "252865", "ParentId": "252843", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T13:28:04.900", "Id": "252843", "Score": "2", "Tags": [ "c++" ], "Title": "Bank Management System v2.0 using OOP in C++" }
252843
<p>I am solving the following <a href="https://www.hackerrank.com/challenges/python-lists/problem" rel="nofollow noreferrer">HackerRank problem</a>:</p> <blockquote> <p>Consider a list (list = []). You can perform the following commands:</p> <ul> <li><code>insert i e</code>: Insert integer e at position i.</li> <li><code>print</code>: Print the list.</li> <li><code>remove e</code>: Delete the first occurrence of integer e.</li> <li><code>append e</code>: Insert integer e at the end of the list.</li> <li><code>sort</code>: Sort the list.</li> <li><code>pop</code>: Pop the last element from the list.</li> <li><code>reverse</code>: Reverse the list.</li> </ul> <p>Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.</p> </blockquote> <p>My solution was:</p> <pre><code>if __name__ == '__main__': N = int(input()) my_list = [] commands = dict( insert=lambda i,v: my_list.insert(i,v), print=lambda: print(my_list), remove=lambda e: my_list.remove(e), append=lambda v: my_list.append(v), sort=lambda: my_list.sort(), pop=lambda: my_list.pop(), reverse=lambda: my_list.reverse() ) for _ in range(N): command, *args = input().split() commands[command](*list(map(int, args))) </code></pre> <p>I did find another solution (I didn't write it) that seems cleaner than mine:</p> <pre><code>n = input() l = [] for _ in range(n): s = raw_input().split() cmd = s[0] args = s[1:] if cmd !=&quot;print&quot;: cmd += &quot;(&quot;+ &quot;,&quot;.join(args) +&quot;)&quot; eval(&quot;l.&quot;+cmd) else: print l </code></pre>
[]
[ { "body": "<p>Suggestions:</p>\n<ul>\n<li>Most of your <code>lambda</code>s are unnecessary wrappers around perfectly fine functions, so I'd just use the latter instead.</li>\n<li>The <code>list</code> in <code>(*list(map(...)))</code> is unnecessary, just unpack the iterable that <code>map</code> gets you.</li>\n<li>There's nothing else in your code, so importing it doesn't give you anything, so you'd just run the script, so <code>if __name__ == '__main__':</code> is rather pointless.</li>\n<li>I'd read the number of commands only when I need it, not early.</li>\n<li>I find <code>my_list</code> unnecessarily verbose, a commonly used name is <code>lst</code>.</li>\n<li>Indent the <code>dict</code> arguments by the standard four spaces instead of eight.\nSo, rewritten:</li>\n</ul>\n<pre><code>lst = []\n\ncommands = dict(\n insert=lst.insert,\n print=lambda: print(lst),\n remove=lst.remove,\n append=lst.append,\n sort=lst.sort,\n pop=lst.pop,\n reverse=lst.reverse\n)\n\nfor _ in range(int(input())):\n command, *args = input().split()\n commands[command](*map(int, args))\n</code></pre>\n<p>As shown in some other solutions in the discussion, we can use <code>getattr</code> instead of building our own <code>dict</code> serving pretty much the same purpose. I didn't see anyone using its default parameter, though, which can neatly cover the <code>print</code> command:</p>\n<pre><code>lst = []\nfor _ in range(int(input())):\n command, *args = input().split()\n getattr(lst, command, lambda: print(lst))(*map(int, args))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:31:15.927", "Id": "498408", "Score": "0", "body": "Thanks for the answer! About the `if ... __main __` it was just copy paste from hackerrank." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:22:32.857", "Id": "252864", "ParentId": "252852", "Score": "1" } } ]
{ "AcceptedAnswerId": "252864", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T15:54:34.057", "Id": "252852", "Score": "1", "Tags": [ "python", "programming-challenge", "array", "comparative-review" ], "Title": "Perform various actions on a list" }
252852
<h1><a href="https://github.com/Zoran-Jankov/Remote-Computer-File-Transfer" rel="nofollow noreferrer"><strong>Remote-Computer-File-Transfer</strong></a></h1> <p>I have created a PowerShell script, , for remote computers file transfer, for computers that only support <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-psdrive?view=powershell-7.1" rel="nofollow noreferrer"><code>New-PSDrive</code></a> cmdlet, and I would like someone to take look at my code and give me guidelines on what I am doing the wrong way and what I am doing right.</p> <h2>The Script</h2> <h3>Description</h3> <p>This script transfers files to remote computers. In <code>Files-Paths.txt</code> file user can write full paths to files for transfer, and in <code>Remote-Computers.txt</code> user can write list of remote computers to which files are transferred, ether by hostname or IP address. Script generates detailed log file and report that is sent via email to system administrators.</p> <pre><code>#Clears the contents of the DNS client cache Clear-DnsClientCache #Loading script configuration $Settings = Get-Content &quot;$PSScriptRoot\Settings.cfg&quot; | ConvertFrom-StringData $PSScriptRoot #Defining network drive thru which files will be to transferred $NetworkDrive = &quot;T&quot; [System.Object[]]$FileList = Get-Content -Path $Settings.FileList [System.Object[]]$ComputerList = Get-Content -Path $Settings.ComputerList $SuccessfulTransfers = 0 $FailedTransfers = 0 Import-Module &quot;$PSScriptRoot\Modules\Write-Log.psm1&quot; Import-Module &quot;$PSScriptRoot\Modules\Start-FileTransfer.psm1&quot; Import-Module &quot;$PSScriptRoot\Modules\Send-EmailReport.psm1&quot; Write-Log -Message $Settings.LogTitle -NoTimestamp Write-Log -Message $Settings.LogSeparator -NoTimestamp #Get credential from user input Write-Log -Message &quot;Enter username and password&quot; $Credential = Get-Credential Write-Log -Message (&quot;User &quot; + $Credential.UserName + &quot; has entered credentials&quot;) foreach($File in $FileList) { if (Test-Path -Path $File) { Write-Log -Message &quot;Successfully checked $File file - ready for transfer&quot; } else { $Message = &quot;Failed to access $File file - it does not exist.`nScript stopped - MISSING FILE ERROR&quot; Write-Log -Message $Message Write-Log -Message $Settings.LogSeparator -NoTimestamp Send-EmailReport -Settings $Settings -FinalMessage $Message Exit } } Write-Log -Message &quot;Successfully accessed all files - ready for transfer&quot; #Start file transfer foreach ($Computer in $ComputerList) { if (Test-Connection -TargetName $Computer -Quiet -Count 1) { Write-Log -Message &quot;Successfully connected to $Computer remote computer&quot; $Partition = $Settings.Partition $NetworkPath = &quot;\\$Computer\$Partition$&quot; if (New-PSDrive -Name $NetworkDrive -Persist -PSProvider &quot;FileSystem&quot; -Root $NetworkPath -Credential $Credential) { Write-Log -Message &quot;Successfully mapped network drive to $Partition partition on the $Computer remote computer&quot; Start-FileTransfer -FileList $FileList -Destination ($NetworkDrive + &quot;:\&quot; + $Settings.TransferFolder) | ` ForEach-Object { $SuccessfulTransfers += $_.Successful $FailedTransfers += $_.Failed } Remove-PSDrive -Name $NetworkDrive } else { Write-Log -Message &quot;Failed to map network drive to C partition on the $Computer remote computer&quot; $FailedTransfers += $FileList.Length Write-Log -Message &quot;Canceld file transfer to $Computer remote computer&quot; } } else { Write-Log -Message &quot;Failed to connected to $Computer remote computer&quot; $FailedTransfers += $FileList.Length Write-Log -Message &quot;Canceld file transfer to $Computer remote computer&quot; } } if($SuccessfulTransfers -gt 0) { Write-Log -Message &quot;Successfully transferred $SuccessfulTransfers files&quot; } if ($FailedTransfers -gt 0) { Write-Log -Message &quot;Failed to transfer $FailedTransfers files&quot; } if(($SuccessfulTransfers -gt 0 ) -and ($FailedTransfers -eq 0)) { $Message = &quot;Successfully transferred all files&quot; } elseif (($SuccessfulTransfers -gt 0 ) -and ($FailedTransfers -gt 0)) { $Message = &quot;Successfully transferred some files with some failed&quot; } elseif (($SuccessfulTransfers -eq 0 ) -and ($FailedTransfers -gt 0)) { $Message = &quot;Failed to transfer any file&quot; } Write-Log -Message $Message Write-Log -Message $Settings.LogSeparator -NoTimestamp #Sends email with detailed report and deletes temporary report log file Send-EmailReport -Settings $Settings -FinalMessage $Message </code></pre> <h2>Write-Log function</h2> <h3>Description</h3> <p>Creates a log entry with timestamp and message passed thru a parameter Message, and saves the log entry to log file, to report log file, and writes the same entry to console. In <code>Settings.cfg</code> file paths to report log and permanent log file are contained, and option to turn on or off whether a console output, report log and permanent log should be written. If <code>Settings.cfg</code> file is absent it loads the default values. Depending on the <code>NoTimestamp</code> parameter, log entry can be written with or without a timestamp. Format of the timestamp is <code>yyyy.MM.dd. HH:mm:ss:fff</code>, and this function adds &quot; - &quot; after timestamp and before the main message.</p> <pre><code>function Write-Log { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = &quot;A string message to be written as a log entry&quot;)] [string] $Message, [Parameter(Mandatory = $false, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = &quot;A switch parameter if present timestamp is disabled in log entry&quot;)] [switch] $NoTimestamp = $false ) begin { if (Test-Path -Path &quot;.\Settings.cfg&quot;) { $Settings = Get-Content &quot;.\Settings.cfg&quot; | ConvertFrom-StringData $LogFile = $Settings.LogFile $ReportFile = $Settings.ReportFile $WriteTranscript = $Settings.WriteTranscript -eq &quot;true&quot; $WriteLog = $Settings.WriteLog -eq &quot;true&quot; $SendReport = $Settings.SendReport -eq &quot;true&quot; } else { $LogFile = &quot;.\Log.log&quot; $ReportFile = &quot;.\Report.log&quot; $WriteTranscript = $true $WriteLog = $true $SendReport = $false } if (-not (Test-Path -Path $LogFile)) { New-Item -Path $LogFile -ItemType File } if ((-not (Test-Path -Path $ReportFile)) -and $SendReport) { New-Item -Path $ReportFile -ItemType File } } process { if (-not($NoTimestamp)) { $Timestamp = Get-Date -Format &quot;yyyy.MM.dd. HH:mm:ss:fff&quot; $LogEntry = &quot;$Timestamp - $Message&quot; } else { $LogEntry = $Message } if ($WriteTranscript) { Write-Verbose $LogEntry -Verbose } if ($WriteLog) { Add-content -Path $LogFile -Value $LogEntry } if ($SendReport) { Add-content -Path $ReportFile -Value $LogEntry } } } </code></pre> <h2>Start-FileTransfer</h2> <h3>Description</h3> <p>Transfers files from the list to destination folder. Log errors and actions while files are transferred.</p> <pre><code>function Start-FileTransfer { [CmdletBinding(SupportsShouldProcess = $true)] [OutputType([PSCustomObject])] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = &quot;List od file full names fot transfer&quot;)] [System.Object[]] $FileList, [Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = &quot;Full path to file transfer folder&quot;)] [string] $Destination ) process { $SuccessfulTransfers = 0 $FailedTransfers = 0 foreach($File in $FileList) { #File name extraction from file full path $FileName = Split-Path $File -leaf try { Copy-Item -Path $File -Destination $Destination -Force } catch { Write-Log -Message (&quot;Failed to transfer $FileName file to $Destination folder `n&quot; + $_.Exception) $FailedTransfers ++ continue } $TransferDestination = Join-Path -Path $Destination -ChildPath $FileName if(Test-Path -Path $TransferDestination) { Write-Log -Message &quot;Successfully transferred $FileName file to $Destination folder&quot; $SuccessfulTransfers ++ } } New-Object -TypeName psobject -Property @{ Successful = $SuccessfulTransfers Failed = $FailedTransfers } } } </code></pre> <h2>Send-EmailReport</h2> <h3>Description</h3> <p>This function sends a report log file, Report.log, as an attachment to defined email address. settings are defined.</p> <pre><code>function Send-EmailReport { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = &quot;Email settings&quot;)] [System.Object[]] $Settings, [Parameter(Mandatory = $false, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = &quot;Additional variable information to be sent in the mail body&quot;)] [string] $FinalMessage ) process { if ($Settings.SendReport -eq 'true') { $Body = $Settings.Body + &quot;`n&quot; + $FinalMessage Send-MailMessage -SmtpServer $Settings.SmtpServer ` -Port $Settings.Port ` -To $Settings.To ` -From $Settings.From ` -Subject $Settings.Subject ` -Body $Body ` -Attachments $Settings.ReportFile Remove-Item -Path $Settings.ReportFile } } } </code></pre> <h2>Setting file</h2> <pre><code>LogTitle = *********************************************** Remote Computer File Transfer PowerShell Script Log ************************************************ LogSeparator = ****************************************************************************************************************************************************** WriteTranscript = true WriteLog = true SendReport = true LogFile = .\\Log.log ReportFile = .\\Report.log FileList = .\\File-Paths.txt ComputerList = .\\Computer-List.txt Partition = C TransferFolder = Target\Folder SmtpServer = smtp.mail.com Port = 25 To = system.administrators@company.com From = powershell@company.com Subject = Remote Computer File Transfer Report Body = This is an automated message sent from PowerShell script. Remote Computer File Transfer PowerShell Script has finished executing. </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:21:43.047", "Id": "252857", "Score": "1", "Tags": [ "powershell", "network-file-transfer" ], "Title": "Remote computer file transfer with PowerShell script" }
252857
<p>I wrote a simple prime number program that checks if a number is prime or not using sieve of eratosthenes, I also wrote an optimized version that only generates the <code>sieve_arr</code> when the <code>val</code> exceeds the length of <code>sieve_arr</code>.</p> <h2>sieve.py</h2> <pre><code># sieve.py from array import array from math import sqrt def sieve(n=80): &quot;&quot;&quot;Sieve of Erathosthenes&quot;&quot;&quot; sieve_arr = array('i', [True for _ in range(n+1)]) sieve_arr_length = len(sieve_arr) for i in range(2, int(sqrt(sieve_arr_length)) + 1): if sieve_arr[i]: for j in range(i + i, n + 1, i): sieve_arr[j] = False; return sieve_arr </code></pre> <h2>prime.py</h2> <pre><code># prime.py import timeit from array import array from sieve import sieve sieve_arr = array('i') def isprime(val): global sieve_arr if val &gt;= len(sieve_arr): sieve_arr = sieve(val * 2) return sieve_arr[val] def isprime2(val): return sieve(val)[val] if __name__ == '__main__': TEST1 = ''' from prime import isprime for i in range(1, 10001): isprime(i) ''' TEST2 = ''' from prime import isprime2 for i in range(1, 10001): isprime2(i) ''' tt1 = timeit.repeat(stmt=TEST2, repeat = 5, number=1) print('prime Time taken: ', min(tt1)) tt2 = timeit.repeat(stmt=TEST1, repeat = 5, number=1) print('Optimized prime Time taken: ', min(tt2)) </code></pre> <p>I ran the test and had the following results</p> <pre><code>prime Time taken: 9.446519022000302 Optimized prime Time taken: 0.002043106000201078 </code></pre> <p>Note: I didn't check for 0 and 1 in <code>isprime()</code> and <code>isprime2()</code> which aren't prime number, I wrote the code with performance in mind.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:38:47.050", "Id": "498389", "Score": "1", "body": "Interesting. I didn't know that 0 and 1 are prime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:41:11.223", "Id": "498392", "Score": "0", "body": "They aren't, I was mostly writing it for performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T01:05:40.713", "Id": "498433", "Score": "0", "body": "Why use `array`, instead of basic lists?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T05:27:40.160", "Id": "498440", "Score": "0", "body": "I don't understand the rationale behind this `sieve_arr = sieve(val * 2)`, If you want to check `val` is prime or not, generate values until `val` why `val*2`? If you want to check if a number is prime or not, why use sieve of Eratosthenes in the first place? Check this out [`Primality test, 6k+1 optimization python code`](https://en.wikipedia.org/wiki/Primality_test#Python_Code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T05:38:07.750", "Id": "498442", "Score": "0", "body": "Further optimizing your code change this to `for j in range(i + i, n + 1, i)` -> `for j in range(i * i, n + 1, i)`. Read about it [`Sieve of Eratosthenes`](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Overview)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T07:41:00.723", "Id": "498450", "Score": "1", "body": "Since Python 3.8 you can use [math.isqrt](https://docs.python.org/3/library/math.html#math.isqrt) instead of `int(math.sqrt(...))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T11:10:30.683", "Id": "498789", "Score": "0", "body": "@Ch3steR The rationale seems to be similar to how `list.append` overallocates in order to make subsequent calls instant. This overcomputes to make subsequent calls instant. That's the optimization, and why that's so much faster in their test." } ]
[ { "body": "<p>Your sieve can be optimized further. Pull the case for <code>i = 2</code> outside of the <code>for</code> loop and then change the <code>for</code> loop to only check odd indexes. Also use slice assignment instead of a nested loop. This code is 10x faster (&lt;100ms to sieve primes to 1M compared to &gt;1s for your sieve).</p>\n<pre><code>def sieve2a(n=80):\n &quot;&quot;&quot;Sieve of Erathosthenes&quot;&quot;&quot;\n\n sieve_arr = [True]*n\n sieve_arr[0] = sieve_arr[1] = False\n \n sieve_arr[4::2] = [False]*len(range(4, len(sieve_arr), 2))\n for i in range(3, int(sqrt(len(sieve_arr))) + 1, 2):\n if sieve_arr[i]:\n sieve_arr[i*i::i] = [False]*len(range(i*i, len(sieve_arr), i))\n\n return sieve_arr\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T14:22:44.000", "Id": "498712", "Score": "0", "body": "What's the purpose of `sieve_arr[0] = sieve_arr[1] = False`? Seems to be an attempt to correctly support n=0 and n=1, but if I try those, it of course crashes with an IndexError." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T03:45:27.947", "Id": "498771", "Score": "0", "body": "@superbrain, Its just to keep the array in synch, so `sieve_arr[n]` is True if `n` is prime." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T07:24:01.337", "Id": "252875", "ParentId": "252858", "Score": "3" } }, { "body": "<h1>Built-in functions</h1>\n<p>As mentioned by Marc, Since Python 3.8 you can use <a href=\"https://docs.python.org/3/library/math.html#math.isqrt\" rel=\"nofollow noreferrer\">math.isqrt</a>. This is faster. It is also guaranteed to be accurate when the size of the argument exceeds the number of bits of mantissa in a float.</p>\n<h1>Type coercion</h1>\n<pre><code>sieve_arr = array('i', [True for _ in range(n+1)])\n</code></pre>\n<p>Your array is declared to hold <code>'i'</code> values: integers. But you are trying to storing boolean values in the array. This necessitates an unnecessary conversion from <code>True</code> and <code>False</code> to <code>1</code> and <code>0</code>.</p>\n<h1>Underused variable</h1>\n<p>The value <code>sieve_arr_length</code> is used once. It effectively holds <code>n + 1</code>.\nIn fact, <code>sieve_arr_length = n + 1</code> might be a more efficient way to initialize it, rather than asking the array for its length. Then instead of recomputing <code>n+1</code> each time the <code>j</code> loop starts, you could simply use <code>sieve_arr_length</code>.</p>\n<h1>Special case even numbers</h1>\n<p>Every even number greater than 2 is not prime. There is no need to check for these. You could simply start your <code>i</code> loop at <code>3</code>, instead of <code>2</code>, and go up by twos to check only the odd numbers greater than 1.</p>\n<p>Starting the <code>j</code> loop at <code>i+i</code>, or <code>i*2</code> is an optimization, but not enough of one. By the time you're checking <code>13</code>, you've already eliminated <code>3*13</code>, <code>5*13</code>, <code>7*13</code>, and <code>11*13</code> because you've eliminated multiples of smaller primes. You can simply start at <code>i*i</code>.</p>\n<p>Plus, if you're only checking the odd prime candidates (because you've special-cased the even), you don't need to eliminate <code>14*13</code>, <code>16*13</code>, <code>18*13</code> and so on, because those are guaranteed to be even. Your step size can be <code>2*i</code>, and eliminate half of the redundant assignments.</p>\n<pre><code> # Odd prime candidate sieve ...\n for i in range(3, isqrt(sieve_arr_length) + 1, 2):\n if sieve_arr[i]:\n for j in range(i * i, sieve_arr_length, 2 * i):\n sieve_arr[j] = 0;\n</code></pre>\n<h1>Memory</h1>\n<p>The <code>array('i', ...)</code> uses 4 or 8 (depending on architecture) bytes per element in the array. <a href=\"https://codereview.stackexchange.com/a/252875/100620\">RootTwo's solution</a> uses a <code>list</code> structure, instead of the <code>array</code>. This will increase the amount of storage required for the sieve, since a list must store a pointer in each list element.</p>\n<p>Using a <code>bytearray</code> instead of an <code>array('i', ...)</code> would reduce your memory usage, down to 1 byte per sieve element, allowing you to maintain a larger sieve.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def ajneufeld_bytearray(n=80):\n &quot;&quot;&quot;Sieve of Erathosthenes&quot;&quot;&quot;\n\n prime = bytearray((0, 1)) * ((n + 1) // 2)\n prime[1] = 0\n prime[2] = 1\n for i in range(3, isqrt(n) + 1, 2):\n if prime[i]:\n prime[i*i::2*i] = bytes(len(range(i*i, n, 2*i)))\n\n return prime\n</code></pre>\n<p>You can further pack 8 flags into each byte, dramatically decreasing the size of your sieve even further, but this bit packing would be complex to implement yourself. Fortunately it has already been done as a nice package: <a href=\"https://pypi.org/project/bitarray/\" rel=\"nofollow noreferrer\"><code>bitarray</code></a>.</p>\n<h1>bitarray implementation</h1>\n<p>The <code>bitarray</code> package has nice bitslice assignment operators. RootTwo's slice assignment:</p>\n<pre><code>sieve_arr[i*i::i] = [False]*len(range(i*i, len(sieve_arr), i))\n</code></pre>\n<p>is much easier with <code>bitarray</code>. The equivalent statement would be:</p>\n<pre><code>sieve_arr[i*i::i] = False\n</code></pre>\n<p>assigning <code>False</code> to each bit in the slice.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from bitarray import bitarray\nfrom math import isqrt\n\ndef ajneufeld(n=80):\n &quot;&quot;&quot;Sieve of Erathosthenes&quot;&quot;&quot;\n\n prime = bitarray(n)\n prime.setall(False)\n prime[3::2] = True\n\n prime[2] = True\n for candidate in range(3, isqrt(n) + 1, 2):\n if prime[candidate]:\n prime[candidate*candidate::2*candidate] = False\n\n return prime\n</code></pre>\n<p>Test code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib.pyplot as plt\nfrom timeit import timeit\nfrom sys import getsizeof\n\nif __name__ == '__main__':\n\n candidates = (theprogrammer, roottwo, ajneufeld_bytearray, ajneufeld_bitarray)\n limits = [10, 30, 100, 300, 1000, 3000, 10_000, 30_000, 100_000, 300_000]\n\n print(&quot;Memory usage:&quot;)\n for candidate in candidates:\n result = candidate(100_000)\n print(f&quot; {candidate.__name__:19} {getsizeof(result):6}&quot;)\n\n fig, ax = plt.subplots()\n\n for candidate in candidates:\n times = [ timeit(lambda: candidate(limit), number=1) for limit in limits ]\n ax.plot(limits, times, '-+', label=candidate.__name__)\n\n ax.legend()\n plt.xscale('log')\n plt.yscale('log')\n plt.show()\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>\nMemory usage:\n theprogrammer 400068\n roottwo 800056\n ajneufeld_bytearray 100057\n ajneufeld_bitarray 12564\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/hpUXo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hpUXo.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:20:23.183", "Id": "498640", "Score": "0", "body": "Woow. This is a great improvement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T23:08:50.910", "Id": "498760", "Score": "0", "body": "IIRC, using `bitarray` would nearly double the access time compared to a regular `list` or `bytearray`. You may want to explicitly mention that time-memory trade-off when you introduce `bitarray`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T23:58:35.790", "Id": "498762", "Score": "2", "body": "@GZ0 `bytearray` is only better that `bitarray` for sieves from 30_000 to 3_000_000. `bitarray` leads at the smaller sizes and larger sizes (on my laptop, Python 3.8 64-bit, bitarray 1.6.1) . Agreed, access to individual bits should be slower than to bytes, but L1 & L2 cache sizes probably start to play a role, and using 1/8th the memory gives `bitarray` an advantage there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:42:39.233", "Id": "498803", "Score": "0", "body": "Correct me if am wrong, I don't think in a list, elements holds a pointer to the next element. A list uses array as its internal structure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:26:14.827", "Id": "498853", "Score": "0", "body": "@theProgrammer A Python `list` is an array of object _references_. The same object can be stored in many different variables or structures (like lists, dictionaries, tuples). Internally, this is accomplished via pointers. A `list` is implemented (CPython) as an array of object pointers. Not to be confused with a linked list, where each object has a pointer to the next. Try calling `sys.getsizeof(x)` for lists of different sizes. The result will depend only on `len(x)`, regardless of the size or kind of each element in the list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:57:06.307", "Id": "498864", "Score": "0", "body": "As you said, `it is an array of object references`, then I think there is no overhead of an additional pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:12:14.337", "Id": "498866", "Score": "0", "body": "@theProgrammer Yes. Object references are pointers. Ergo, Python lists are implemented as an array of pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:25:38.483", "Id": "498869", "Score": "0", "body": "Run `from array import array; from sys import getsizeof; print(getsizeof(array('i', [0]*10)) - getsizeof(array('i', [0]*9)), getsizeof([0]*10) - getsizeof([0]*9))` and you get `4 8`, demonstrating that an `array('i',...)` uses 4 bytes per integer, the list uses 8 bytes per element. Double the memory. The output in my post shows 400068 for your `array('i', ...)` implementation, and `800056` for RootTwo's list implementation. Double the memory. The [`documentation`](https://docs.python.org/3/library/array.html) title: \"Efficient arrays of numeric values_\"! You think \"list has no overhead\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T10:07:35.297", "Id": "498922", "Score": "0", "body": "Great resource @AJNeufeld." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T21:17:50.770", "Id": "252953", "ParentId": "252858", "Score": "5" } } ]
{ "AcceptedAnswerId": "252875", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:26:08.743", "Id": "252858", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "sieve-of-eratosthenes" ], "Title": "Sieve of eratosthenes: My optimized version" }
252858
<p><strong>Updated</strong> (at the bottom)</p> <p>I am attempting to write a Python program where I have to create a sorting algorithm <strong>without</strong> the assistance of the built-ins (like the <code>sort()</code> function). I used the <code>def</code> keyword to create the <code>sorting_function()</code> (the code bits in this paragraph will make more sense once you see my code) so all I have to do at the end is call the <code>sorting_function</code>(<strong>P.S.</strong> <em>this is where the</em> <code>original_list</code> <em><strong>needs</strong> to be passed as a parameter</em>). My code <em>(almost)</em> works, but my concern is, <strong>how</strong> do I pass the <code>original_list</code> (or the user's input) as a parameter of the function? Instead of having my program edited by the user (where they have to go to the bottom of the program to insert the numbers of their list) for it to work? Also, silly me, the user is still going to edit the program, but it's easier and <strong>required</strong> to pass the <code>original_list</code> as a parameter of the <code>sorting_algorithm</code> function.</p> <p>I also thought it would be helpful for you to know that I have <strong>no prior coding experience</strong> and that this is my <strong>first</strong> code in any programming language, so this may not be the most efficient code.</p> <p>My code is as follows (my explanations might be too long, but I need to do this for clarity's sake. If any of my explanations are wrong/vague, please don't hesitate to correct me):</p> <pre><code>def sorting_algorithm(numbers): #this is the function in which the code will be written and upon completion, should be called on. sorted_list = [] #the sorted_list variable is assigned to an empty list, which is where the sorted numbers will be stored. index = 0 #the index starts from zero because, to effectively sort the numbers, the counting must start from the first number in the list. comparison_number = 1 #this is a comparison variable used for comparing the numbers in the list. while numbers: if numbers[index] == numbers[-1] and numbers[index] &lt;= comparison_number: #if the program reaches the last number in the list and it is smaller than the comparison_number (which is 1) sorted_list.append(numbers.pop(index)) #then that number is put into the sorted_list's '[]'. index = 0 #the index stays at zero for each if, elif and else statements as only one of these conditions can be true. elif numbers[index] == numbers[-1]: #if the program reaches the last number in the list, index = 0 #then the position of the index should be returned to '0'. comparison_number += 1 #the comparison number will also go up by one because numbers (from the list) are being compared to the comparison number (which, again is 1) elif numbers[index] &lt;= comparison_number: #if the number (under analysis) is less than or equals to comparison_number sorted_list.append(numbers.pop(index)) #then that number can be placed into the sorted_list's '[]'. index = 0 #the index is again returned to the first number in the list so it (the number) can be analyzed. comparison_number += 1 #the comparison_number goes up by one again because another number has been compared and added to the sorted_list's '[]'. else: index += 1 #if none of the above conditions apply to the number(s) in the list, return sorted_list #then the program will move onto the next number and the loop will restart! Also, I'm not entirely sure #if the return sorted_list line is needed. sorting_algorithm() #this is how to call on the function, I believe. original_list = [123, 85, 9587, 0, 453, 7, 63] #this is where the user can/will input the numbers of their list. print(&quot;The unsorted list: {}&quot;.format(original_list)) #I had to look at some examples of code to figure this out, I'm still not sure what '{}' is for... original_list = sorting_algorithm(original_list) ##but this will take the numbers of the list and go through the loop and put the numbers in ascending order. print(&quot;And the sorted list: {}&quot;.format(original_list)) #at last, this line will print out the sorted list of numbers. </code></pre> <p>Note: I know that the names of my variables are really long (I used entire words to identify my vars), but it's easier for me to go back and know what those variables do. I'm very sorry if this is annoying to some of you, but since <em>this is my first Python code</em>, I believe it is essential for me to do this to achieve optimal clarity.</p> <p>I hope my question isn't too vague, and if I can provide any further details, please let me know.</p> <hr /> <p><strong>UPDATE:</strong></p> <p>After a couple of hours of trial and error I have (I think) finally figured out a better way to write this code. And the list is a parameter for my function! Thank you for all the help I got!!</p> <pre><code>def sorting_algorithm(list): for index in range(1, len(list)): current = list[index] while index &gt; 0 and list[index - 1] &gt; current: list[index] = list[index - 1] index = index - 1 list[index] = current return list print(&quot;the sorted list is&quot;, (sorting_algorithm([45, 14, 1, 7, 98, 23, 102, 57]))) </code></pre> <p>Could someone please let me know why I need the <code>return list</code> statement before printing the <em>sorted</em> list (I believe it's line 8)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:59:53.707", "Id": "498395", "Score": "1", "body": "There are numerous sorting algorithm e.g insertion sort, merge sort, quicksort. Why don't you implement them instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:07:04.163", "Id": "498396", "Score": "0", "body": "@theProgrammer I'm not sure how I would do that. Are these sorting algorithms you've provided above, built-in to Python? Or are you saying that I should use the method of one of these algorithms to optimize my code? I'm sorry if I'm completely missing your point here, but I brand new to this language, so please pardon my mistakes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:14:53.880", "Id": "498397", "Score": "0", "body": "Python implements `Tim-sort`. You can reimplement insertion sort, it is fairly easy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:17:06.167", "Id": "498399", "Score": "0", "body": "I believe theProgrammer is trying to direct you to tried-and-proven sorting algorithms, because writing your own sorting algorithm \"from scratch\" is likely to result in bad code (either incorrect, slow, or both). It has nothing to do with the language, and more with reinventing a particularly tricky (and very well studied) wheel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:18:49.360", "Id": "498400", "Score": "0", "body": "@tucuxi thank you for the clarification!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:19:05.880", "Id": "498401", "Score": "0", "body": "@theProgrammer thanks to you as well!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:20:21.450", "Id": "498402", "Score": "0", "body": "but is it possible for one of you to provide some sample code for this? so I can get a better understanding (as I'm more of a visual person)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:22:17.360", "Id": "498403", "Score": "0", "body": "@esker-luminous If you're looking for good resources, You can check out [this](https://www.youtube.com/user/mikeysambol) person." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:26:51.863", "Id": "498404", "Score": "3", "body": "@AryanParekh Thank you! I will make sure to check this channel out in detail when I have time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T00:05:30.480", "Id": "498428", "Score": "0", "body": "_My code (almost) works, but my concern is, how do I pass the original_list (or the user's input) as a parameter of the function?_ I'm not sure I understand. Your previous sentence was _ this is where the original_list needs to be passed as a parameter_, too, so I'm confused." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T10:45:31.957", "Id": "498460", "Score": "0", "body": "@esker-luminous you implemented insertion sort, that's really nice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T16:22:31.043", "Id": "498477", "Score": "0", "body": "@AMC we don't need to worry about that anymore, I think the second code is the best I can do for the assignment. Also what I was trying to say there was: I need to pass the original_list for the sorting_algorithm function. It was really confusing and I think I have confused people here as well, and I am really sorry about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T16:23:16.860", "Id": "498478", "Score": "0", "body": "@theProgrammer Yes, it took me a while, but I got it sorted out. Thank you for your help, I really appreciated it!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:49:09.197", "Id": "252860", "Score": "3", "Tags": [ "performance", "beginner", "python-3.x", "sorting", "reinventing-the-wheel" ], "Title": "Sorting Algorithm (from scratch) in Python" }
252860
<p>Last week I was challenged in a technical interview with a code challenge about threads and efficiency. The challenged required to create a service to detect whether an ID had been already seen or not. The requirements were simple:</p> <ul> <li>Return true or false if a given id was already seen or not</li> <li>Duplicates are not allowed, this is critical</li> <li>False positives can be tolerated at a maximum error rate of less than 1%</li> <li>Must be thread safe to call</li> <li>No 3rd party packages can be used</li> <li>create the implementation as efficiently as possible in both locking, memory usage, and cpu usage</li> </ul> <p>I was provided with the following code:</p> <pre><code>public interface IDuplicateDetectionService { bool Seen(int id); } public class Service : IDuplicateDetectionService { public bool Seen(int id) { if (id &lt; 0) { throw new ArgumentOutOfRangeException(nameof(id)); } } } </code></pre> <p>My solution was this:</p> <pre><code>public class Service : IDuplicateDetectionService { private readonly HashSet&lt;int&gt; _itemsSeen = new HashSet&lt;int&gt;(); private readonly object _lock = new object(); public bool Seen(int id) { if (id &lt; 0) { throw new ArgumentOutOfRangeException(nameof(id)); } if (_itemsSeen.Contains(id)) { return true; } lock(_lock) { return _itemsSeen.Add(id) == false; } } } </code></pre> <p>And the test code this:</p> <pre><code>private void Test() { //Arrange var maxDegreeOfParalellism = 1000; var idCount = 1000000; var successfulCalls = 0; var failedCalls = 0; var ids = Enumerable.Range(1, idCount); var servie = new Service(); var testService = new Action&lt;int&gt;(id =&gt; { var seen= service.Seen(id); if (seen == false) { Interlocked.Increment(ref successfulCalls); } else { Interlocked.Increment(ref failedCalls); } }); // Act Parallel.ForEach( ids, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParalellism }, currentId =&gt; testService(currentId)); // Assert Assert.Equal(idCount, successfulCalls); Assert.Equal(0, failedCalls); } </code></pre> <p>The code worked and the test passed, however, I don't think I matched the expectations. To begin with, I don't understand the requirement stating <strong>error rate of less than 1%</strong>, on the other hand, I don't know how to refactor that code so that it satisfies the conditions.</p> <p>I didn't get possitive feedback, which is fine, but I didn't get what a possible solution would be, which I would have liked to get. I would like to learn how that case could be solved following the given requirements.</p> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:47:44.663", "Id": "498411", "Score": "0", "body": "Implementation looks fine for me. But the test doesn't cover the `true` scenario." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:59:48.693", "Id": "498413", "Score": "0", "body": "Yes, I don`t realize how to test the failure scenario, where I get that 1% of failures.\nI don't also quite understand how to improve that in terms of efficiency.\nThanks for taking a look!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T20:11:13.097", "Id": "498414", "Score": "2", "body": "1%? Implement it with `HashSet` and locks but make as less lock time as possible in terms of performance e.g. reader/writer lock. Then return `true` if writer lock was already taken regardless of `id` value. Here's possible false positive. Compare performance with the 1st implementation then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T20:21:52.703", "Id": "498415", "Score": "0", "body": "Ok, that's interesting! Thanks for the suggestion, I'll give it a try and will come back with the results" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:03:52.347", "Id": "498418", "Score": "0", "body": "I added the refactored code. After carefully evaluating your advise, it made a lot of sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:09:50.730", "Id": "498420", "Score": "0", "body": "Not a thread-safe. `_itemsSeen.Contains(id)` can be called while `_itemsSeen.Add(id)` is working. Imagine 2 threads: (1) Checks `_isLocked` which is false; (2) set `isLocked` to true and execute `_itemsSeen.Add(id)`; (1) at the same time calls `_itemsSeen.Contains(id)`. Oops. :) Tip is [here](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement), you need just to wisefully use `Monitor` class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:11:10.747", "Id": "498421", "Score": "0", "body": "i know, It is an early check, however, Add would return false if the key was present.\nSo basically there is no sense in getting into the lock if the key was there, and since I am only adding, worst case is what you mentioned. Does it make sense?\nTaking a look at you tip now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:19:33.940", "Id": "498422", "Score": "1", "body": "`Monitor.Enter` and `Monitor.Exit` are your friends here :) What is reader/writer lock: any Thread can read while writer lock is not taken, no Thread can write while reader lock is taken. How to write if reader lock always taken (hot activity)? Hold new readers to enter while all old readers finish their jobs and take the writer lock then. Another tip: You probably need more than two different (independent) locks to implement it. Now you have only one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:25:58.690", "Id": "498423", "Score": "0", "body": "I see, I am trying to understand and digest your proposal. I know it is a pain, but would you mind writing some fachade code? I am strugling at it right now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:33:57.880", "Id": "498424", "Score": "0", "body": "Ok :) don't hurry up but read this carefully: [`ReaderWriterLock`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?view=netframework-4.8). Then to understand it implement own with `Monitor` to meet the challenge requirements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T07:52:21.357", "Id": "498451", "Score": "2", "body": "I don't understand, the test code seems wrong to me. You have 10,000 _unique_ ids so you're expecting 0 duplicates so `successfulCalls` should be close to 0. Your solution is also wrong. `TryAdd` returns true if the item was *added* so you should be returning `!itemsSeen.TryAdd(...`. Am I missing something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T12:15:23.750", "Id": "498462", "Score": "0", "body": "That test is the basic one serving as an example. Regarding `TryAdd`, you are right, I just made a mistake when created the snippet. I'll edit the answer with the latest version of the code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T19:12:38.863", "Id": "252862", "Score": "5", "Tags": [ "c#", "thread-safety" ], "Title": "Thread safe optimized list" }
252862
<p>I am relatively new to java and I am trying to set up a class with non-trivial setters, but I wonder if setting an instance variable via another one is allowed/good practice?</p> <pre><code>public class Pdf { private byte[] bytearray; private String name; private PDDocument pddocument; private int lastPage; public Pdf() { super(); } public Pdf(String name, byte[] bytearray) { super(); this.name = name; this.bytearray = bytearray; } public String getName(String name) { return name; } public void setName(String name) { this.name = name; } public byte[] getBytearray() { return bytearray; } public void setBytearray(byte[] bytearray) { this.bytearray = bytearray; } public PDDocument getPddocument() { return pddocument; } public void setPddocument() { PDDocument pddocument = null; try { pddocument = org.apache.pdfbox.pdmodel.PDDocument.load(this.bytearray); } catch (IOException e) { e.printStackTrace(); } this.pddocument = pddocument; } public int getLastPage() { return lastPage; } public void setLastPage() { this.lastPage = this.pddocument.getNumberOfPages()-1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T02:25:26.870", "Id": "498434", "Score": "1", "body": "Well, setting the value of an instance using another to do it isn't IN GENERAL a bad practice, it depends on the context. I really think it is a hard topic; now, you can use UML diagrams to give you an idea about were are you and what are you doing. Please recur to standard like design instead of doing exotic things if you're learning." } ]
[ { "body": "<p>Allowed?</p>\n<p>Yes. There seems to be nothing technically wrong with your code.</p>\n<p>Good practice?\nNo.</p>\n<p>Specifically, in your example code <code>setPddocument</code> is not actually a setter.</p>\n<p>It is a load / initialize function, that does not set a value in the object, but instead performs an operation under the assumption a certain value (<code>bytearray</code>) has already been set.</p>\n<p>It would be better off named <code>init</code> or <code>load</code>, and you probably should set up some code to check if there is a valid array, throwing a different exception in that case. (Like <a href=\"https://docs.oracle.com/javame/config/cldc/opt-pkgs/api/daapi-3.4/com/oracle/deviceaccess/InvalidStateException.html\" rel=\"noreferrer\">InvalidStateException</a>).</p>\n<p><code>setLastPage</code> is also more of an initializer then a setter.</p>\n<p>There, you have no error checking at all, so if it is called before <code>setPddocument</code> your program will crash.</p>\n<p>While it is possible to have non-trivial setters that modify several instance variables, the general rule of thumb is: if it does not receive a value from outside to do its job, it is not a setter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T23:11:43.040", "Id": "498427", "Score": "2", "body": "IllegalStateException, not InvalidStateException. The latter sounds a bit like .NET." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T22:11:38.320", "Id": "498904", "Score": "0", "body": "@Lev M.hey, thanks for a really helpful answer. Would not it be better - instead of creating an init function - to put the code initalizing PdDocument into the getter as @Ralf Kleberhoff is doing with `getLastPage()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T23:10:17.867", "Id": "498906", "Score": "1", "body": "@krenkz Ralf's version of `getLastPage` does not initialize anything. It just capitalizes on the fact that we can always get last page from a loaded PDF document, so you don't really need an instance varibale to hold a duplicate of that information. But in which getter would you load the whole PDF document? And why would you want to load it more than once? The idea behind intializer functions is to perform a potentially heavy operation that needs to be done only once in the object's life time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T23:13:06.723", "Id": "498907", "Score": "1", "body": "@krenkz it is acceptable to have getters that don't actually retrieve data from instance variables or don't have corresponding setter. A `getXXX` function can calculate the information based on data provided by nested object, as in the `getLastPage` example, or some fields may be immutable (not allowed to change after initialization). But as a general rule the only time you initialize anything in a getter, is in the signleton pattern with a static `getInstance` style function." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T21:09:15.760", "Id": "252867", "ParentId": "252866", "Score": "12" } }, { "body": "<ol>\n<li><p>From the code I can see that your <code>Pdf</code> class has no meaning without\n<code>bytearray</code>. So better way should be like remove the default\nconstructor from the class. So that user will always be allowed to\ncreate an object of PDF class with parameterized constructor.\nResulting he/she will have to pass bytearray always. So you will\nnever land in a situation where it is null or state is invalid.</p>\n</li>\n<li><p>Method <code>setBytearray</code> you can use to change the data and you can\nthrow exception if user pass null in setter. But I would rather say\ndon't have a setter for it and make it immutable class (by marking\nclass final and making all class members immutable). And for every\nnew document create a new Object.</p>\n</li>\n<li><p>Rather change <code>setPddocument</code> to <code>loadPddocument</code>, in-order to make\nit a relatable name. As method is loading PDF document from the\nbytearray.</p>\n</li>\n<li><p>On call to <code>getLastPage</code> and <code>getPddocument</code> you can check, if\n<code>pddocument</code> is null load it first and return (size/object) else\nreturn (size/object) from existing loaded <code>pddocument</code>.</p>\n</li>\n<li><p>Variables name should be corrected. Ex. <code>pddocument</code> should be\nrather <code>pdDocument</code>. And <code>bytearray</code> should be <code>byteArray</code>.</p>\n</li>\n<li><p>Method <code>getName</code> should not have input parameter.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T04:50:41.727", "Id": "252872", "ParentId": "252866", "Score": "2" } }, { "body": "<p>In addition to @notescrew's answer:</p>\n<p>Look at your <code>Pdf</code> class from a user's point of view.</p>\n<p>I'd like to write</p>\n<pre><code>Pdf pdf = new Pdf(&quot;MyDoc&quot;, bytes);\nPDDocument doc = pdf.getPddocument();\nint lastPage = pdf.getLastPage();\n</code></pre>\n<p>Your current version forces me to insert some strange setter calls:</p>\n<pre><code>Pdf pdf = new Pdf(&quot;MyDoc&quot;, bytes);\npfd.setPddocument();\nPDDocument doc = pdf.getPddocument();\nsetLastPage();\nint lastPage = pdf.getLastPage();\n</code></pre>\n<p>When I've created an object and supplied every necessary information (my preferred way: through your two-argument constructor), I want to be able to use all methods and get consistent results.</p>\n<p>For the rare cases where you really want to have an externally-visible initialization, make sure to keep track of your instance's state and throw an IllegalStateException if your user is requesting something depending on a not-yet-done initialization. But that introduces a complexity of its own, so in 99% of cases, it's better to have classes do the necessary initializations themself.</p>\n<p>My version of your class would be:</p>\n<pre><code>public class Pdf {\n\n private byte[] bytearray;\n private String name;\n private PDDocument pddocument;\n\n public Pdf(String name, byte[] bytearray) {\n super();\n this.name = name;\n this.bytearray = bytearray;\n this.pddocument = PDDocument.load(bytearray);\n }\n\n public String getName() {\n return name;\n }\n\n public byte[] getBytearray() {\n return bytearray;\n }\n\n public PDDocument getPddocument() {\n return pddocument;\n }\n\n public int getLastPage() {\n return pddocument.getNumberOfPages()-1;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T09:12:39.877", "Id": "498457", "Score": "1", "body": "If byteArray is expected to change ofter and not the PDDocument not always read it one might consider a lazy evaluation strategy where getPddocument calls PDDocument.load if needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T09:24:05.553", "Id": "498458", "Score": "1", "body": "@Taemyr For that use case, you're right. But then I'd question whether it's useful to create a `Pdf` instance from the `byteArray`, if it isn't expected to be used as PDF document, only as byte array. So I supposed the use case to \"always\" include access to the PDF document." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T02:29:11.990", "Id": "498516", "Score": "0", "body": "+1 Also, since your rewritten class is effectively immutable, it might be useful to document that and to enforce it by making the member variables (and the class itself) `final`. Immutability can be a useful property, but only if users of your class know about it and can rely on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T04:49:30.213", "Id": "498520", "Score": "1", "body": "The class as written is not effectively immutable. It leaks `bytearray` from both the constructor and the getter. It may also leak `Pddocument`, as I'm not aware of whether or not that class is immutable. The `Pdf` class is also extensible, which means that subclasses may break immutability. At the very least, to be immutable Pdf would need defensive copies of `bytearray` in both the constructor and the getter, and the class must be made `final`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T09:05:18.973", "Id": "252877", "ParentId": "252866", "Score": "7" } } ]
{ "AcceptedAnswerId": "252867", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T20:47:03.387", "Id": "252866", "Score": "6", "Tags": [ "java", "classes" ], "Title": "Setters dependent on other instance variables in Java" }
252866
<p>(This is using <a href="https://nextjs.org/" rel="nofollow noreferrer">NextJs</a> but there was no tag for that available)</p> <p>I'm building a form backend service, similar to <a href="https://formspree.io/" rel="nofollow noreferrer">Formspree</a>. The user can create a form however they like on their frontend and submit it to my API endpoint to be collected and stored. This becomes tricky when needing to handle files as well as plain body fields. The code I have below seems to work fine but it has become excessively messy.</p> <pre><code>import nextConnect from 'next-connect'; import bodyParser from 'body-parser'; import { nanoid } from 'nanoid'; import multer from 'multer'; import aws from 'aws-sdk'; import multerS3 from 'multer-s3'; import middleware from '../../../../middlewares/middleware'; import trimObject from '../../../../helpers/trimObject'; import runMiddleware from '../../../../helpers/runMiddleware'; import { MAX_FILE_SIZE, USER_FILE_LIMIT } from '../../../../constants'; const spacesEndpoint = new aws.Endpoint('nyc3.digitaloceanspaces.com'); const s3 = new aws.S3({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, // Set access key here secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, endpoint: spacesEndpoint, }); const handler = nextConnect(); handler.use(middleware); export const config = { api: { bodyParser: false, }, }; // Catch posts submissions handler.post(async (req, res) =&gt; { try { // Get the form and make sure it exists const { formId } = req.query; const form = await req.db.collection('forms').findOne({ _id: formId }); if (!form) { return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=404`); } // Get the form creator and subscription level const user = await req.db.collection('users').findOne({ _id: form._creator, }); if (!user) { return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=404`); } let isFileUploadAllowed = false; // Determine if the form is multipart const isMultipart = req.headers['content-type'].toLocaleLowerCase().startsWith('multipart/form-data'); if (isMultipart) { // Get the file sizes of all the users files const userFiles = await req.db.collection('files').aggregate( [ { $match: { _owner: form._creator } }, { $group: { _id: null, totalSize: { $sum: '$size', }, }, }, ], ).toArray(); // Check that the user hasn't exceed thier file upload limit const totalFileSize = userFiles.length &amp;&amp; userFiles[0].totalSize; if (totalFileSize &lt; USER_FILE_LIMIT) { isFileUploadAllowed = true; } } // Create the transaction const session = req.dbClient.startSession(); try { const transactionOptions = { readPreference: 'primary', readConcern: { level: 'local' }, writeConcern: { w: 'majority' }, }; const transactionResults = await session.withTransaction(async () =&gt; { const submissionId = nanoid(); // Is multipart form and fileupload allowed if (isFileUploadAllowed &amp;&amp; isMultipart) { await runMiddleware( req, res, multer({ limits: { fileSize: MAX_FILE_SIZE }, storage: multerS3({ s3, bucket: process.env.AWS_S3_BUCKET, acl: 'public-read', key(_, file, cb) { cb(null, `${user._id}/${form._id}/${submissionId}/${file.originalname}`); }, }), }).array('_file', 5), ); // Create File objects and insert them let files = []; req.files.forEach((file) =&gt; { const { key, size, originalname } = file; files = [...files, { name: originalname, key, size, _id: nanoid(), _created: new Date(), _submission: submissionId, _form: form._id, _owner: form._creator, }]; }); await req.db.collection('files').insert(files, { session }); } else if (isMultipart) { // Is multipart form and fileupload not allowed, errors if any files attached await runMiddleware( req, res, multer().none(), ); } else { // Is not multipart form form await runMiddleware( req, res, bodyParser.urlencoded({ extended: false }), ); } // Create Submission object const body = trimObject(req.body); const submission = { ...body, _id: submissionId, _created: new Date(), _form: formId, }; await req.db.collection('submissions').insertOne(submission, { session }); }, transactionOptions); // Transaction was successful, send to thank you apge if (transactionResults) { return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/thanks`); } return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=500`); } catch (e) { // Error when uploading files if (e instanceof multer.MulterError) { // Files included when not allowed if (e.code === 'LIMIT_UNEXPECTED_FILE') { return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=400`); } // Any other error uploading file (most likely file size) return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=413`); } // Error not caused by file uploads return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=500`); } finally { await session.endSession(); } } catch (e) { // Catch all send to 500 error invalid page return res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=500`); } }); // Catch all other methods handler.all(async (req, res) =&gt; res.redirect(302, `${process.env.NEXT_PUBLIC_WEB_URI}/invalid?error=405`)); export default handler; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T22:22:02.783", "Id": "252868", "Score": "1", "Tags": [ "node.js", "api", "form", "mongodb" ], "Title": "NextJS API endpoint for a 'form backend' service" }
252868
<p>This is the first real program I have written in rust. What started as a clean piece of rust code, turned into a lifetime monstrosity when I decided to make my <code>enum</code>s and <code>struct</code>s use <code>&amp;str</code> instead of <code>String</code>. The algorithm implemented is irrelevant; I just need help making my code more idiomatic and clean. Here is (quite simple) my code:</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap; use std::hash::{Hash, Hasher}; #[derive(Debug, PartialEq, Eq)] struct BasicBlock&lt;'a&gt; { block_id: u32, code: Vec&lt;IRCode&lt;'a&gt;&gt;, preds: Vec&lt;Box&lt;BasicBlock&lt;'a&gt;&gt;&gt;, succs: Vec&lt;Box&lt;BasicBlock&lt;'a&gt;&gt;&gt;, } #[derive(Debug, PartialEq, Eq)] enum IRCode&lt;'a&gt; { Basic { value: &amp;'a str, btype: Type, id: u32, }, Quadruple { op: Op, params: Vec&lt;IRCode&lt;'a&gt;&gt;, location: Storage&lt;'a&gt;, }, // and some more... } #[derive(Debug, PartialEq, Eq)] enum Type { TVarRef, // and some more... } #[derive(Debug, PartialEq, Eq)] enum Storage&lt;'a&gt; { Temp { name: &amp;'a str }, } #[derive(Debug, PartialEq, Eq)] enum Op { Add, Sub, } impl&lt;'a&gt; Hash for BasicBlock&lt;'a&gt; { fn hash&lt;H: Hasher&gt;(&amp;self, state: &amp;mut H) { self.block_id.hash(state); } } #[derive(Debug)] struct SSA&lt;'a&gt; { count: HashMap&lt;&amp;'a str, u32&gt;, current_def: HashMap&lt;&amp;'a str, HashMap&lt;Box&lt;&amp;'a BasicBlock&lt;'a&gt;&gt;, Box&lt;IRCode&lt;'a&gt;&gt;&gt;&gt;, } impl&lt;'a&gt; SSA&lt;'a&gt; { fn new() -&gt; SSA&lt;'a&gt; { SSA { count: HashMap::new(), current_def: HashMap::new(), } } fn new_variable(&amp;mut self, name: &amp;'a str, block: &amp;'a BasicBlock&lt;'a&gt;) -&gt; &amp;Box&lt;IRCode&lt;'a&gt;&gt; { // If `name` is not in `count`, insert `(name, 0)`; else increment the count *self.count.entry(name).or_insert(0) += 1; self.current_def.entry(name).or_insert(HashMap::new()); self.current_def.get_mut(&amp;name).unwrap().insert( Box::new(block), Box::new(IRCode::Basic { value: name, btype: Type::TVarRef, id: *self.count.get(&amp;name).unwrap(), }), ); self.current_def.get(&amp;name).unwrap().get(&amp;block).unwrap() } } fn main() { // very simple test case let mut ssa = SSA::new(); let bb0 = BasicBlock { block_id: 0, code: vec![], preds: vec![], succs: vec![], }; println!(&quot;{:?}&quot;, ssa.new_variable(&quot;foo&quot;, &amp;bb0)); println!(&quot;{:?}&quot;, ssa); } </code></pre> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T09:11:02.423", "Id": "498454", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:56:45.877", "Id": "498682", "Score": "2", "body": "Why do you want to use &str instead of String in these cases? The best way of approaching this will depend on what you are trying to accomplish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T00:41:14.480", "Id": "498765", "Score": "0", "body": "@WinstonEwert -- I had some trouble using String (that is what I initially used). Also, I've heard `&str` is better for just looking into strings (not modifying them)." } ]
[ { "body": "<p>Hello and welcome to the Rust community.</p>\n<p>After a single read of your code, I have a couple comments.</p>\n<ul>\n<li>your problems with <code>&amp;str</code> as well as keying by <code>block_id</code> would be best remedied by putting interners in <code>SSA</code>. The best interner choice would be <a href=\"https://crates.io/crates/string-interner\" rel=\"nofollow noreferrer\"><code>string-interner</code></a> or <a href=\"https://crates.io/crates/internment\" rel=\"nofollow noreferrer\"><code>internment</code></a>.</li>\n<li>in <code>fn new_variable</code>, you have repeated lookups for the same entry of <code>current_def</code>. LLVM will be unable to optimize out repeated accesses to HashMap. This may slow us down by something like 120~200ns per invocation of the function, because one <code>HashMap</code> lookup takes approx. 40~70ns.</li>\n<li>you have <code>Vec&lt;Box&lt;...&gt;&gt;</code> and <code>HashMap&lt;Box&lt;...&gt;,Box&lt;...&gt;&gt;</code>. This inclusion of <code>Box</code> within another container immediately raises a flag in the mind of a Rust programmer that the code is not cleaned up. Wrapping in <code>Box</code> does not provide anything over wrapping in <code>Vec</code>, <code>HashMap</code> or any other container. All wraps provide unique ownership with memory indirection. To illustrate with an example, <code>Box&lt;[T]&gt;</code> is almost like <code>Vec</code> in that both are owned dynamic-length slices (indexable memory ranges) except that <code>Box&lt;[T]&gt;</code> does not allow any overprovisioning of memory (<code>Vec</code> can have capacity above length).</li>\n<li>the <code>SSA::current_def</code> type expression is basically as long as your average tweet. Break down complex types longer than 30-40 characters into smaller definitions.</li>\n</ul>\n<p>We will begin by changing <code>SSA</code> and <code>fn new_variable</code>, with new structure <code>SSADef</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Debug)]\nstruct SSA&lt;'a&gt; {\n content: HashMap&lt;&amp;'a str, SSADef&lt;'a&gt;&gt;,\n}\n\n#[derive(Debug)]\nstruct SSADef&lt;'a&gt; {\n count: u32,\n current_def: HashMap&lt;&amp;'a BasicBlock&lt;'a&gt;, IRCode&lt;'a&gt;&gt;,\n}\n\nimpl&lt;'a&gt; SSA&lt;'a&gt; {\n fn new() -&gt; SSA&lt;'a&gt; {\n SSA { content: HashMap::new() }\n }\n\n fn new_variable&lt;'s&gt;(&amp;'s mut self, name: &amp;'a str, block: &amp;'a BasicBlock&lt;'a&gt;) -&gt; &amp;'s IRCode&lt;'a&gt; {\n // If `name` is not in `content`, insert `SSADef::new()`\n let def = self.content.entry(name).or_insert_with(SSADef::new);\n // Increment the count\n def.count += 1;\n def.current_def.entry(block).or_insert(\n IRCode::Basic {\n value: name,\n btype: Type::TVarRef,\n id: def.count,\n }\n )\n }\n}\n\nimpl&lt;'a&gt; SSADef&lt;'a&gt; {\n fn new() -&gt; SSADef&lt;'a&gt; {\n SSADef {\n count: 0,\n current_def: HashMap::new(),\n }\n }\n}\n</code></pre>\n<p>One minor observation: you can derive <code>Default</code> for <code>SSA</code> and <code>SSADef</code> and call <code>default</code> from both <code>new</code>s. This will put <code>0</code>s and empty <code>HashMap</code>s and other default values in the fields of these structures.</p>\n<p>We add the <code>StringInterner</code>. I assume the deeper functionality will always have easy access to top level <code>SSA</code>, and consequently easy access to the interner. If not, we can use some other crate such as <code>internment</code> which provides an appropriate API.</p>\n<p>Changing the <code>BasicBlock</code>s for interning is left as an exercise for the reader. We arrive at the following code, which has very few <code>'a</code>s left. This is all I can do without knowledge of the algorithm, I believe:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::collections::HashMap;\nuse std::hash::{Hash, Hasher};\n\nuse string_interner::{StringInterner, DefaultSymbol as Sym};\n\n#[derive(Debug, PartialEq, Eq)]\nstruct BasicBlock {\n block_id: u32,\n code: Vec&lt;IRCode&gt;,\n preds: Vec&lt;BasicBlock&gt;,\n succs: Vec&lt;BasicBlock&gt;,\n}\n\n#[derive(Debug, PartialEq, Eq)]\nenum IRCode {\n Basic {\n value: Sym,\n btype: Type,\n id: u32,\n },\n Quadruple {\n op: Op,\n params: Vec&lt;IRCode&gt;,\n location: Storage,\n },\n // and some more...\n}\n\n#[derive(Debug, PartialEq, Eq)]\nenum Type {\n TVarRef,\n // and some more...\n}\n\n#[derive(Debug, PartialEq, Eq)]\nenum Storage {\n Temp { name: Sym },\n}\n\n#[derive(Debug, PartialEq, Eq)]\nenum Op {\n Add,\n Sub,\n}\n\nimpl Hash for BasicBlock {\n fn hash&lt;H: Hasher&gt;(&amp;self, state: &amp;mut H) {\n self.block_id.hash(state);\n }\n}\n\n#[derive(Debug, Default)]\nstruct SSA&lt;'a&gt; {\n content: HashMap&lt;Sym, SSADef&lt;'a&gt;&gt;,\n interner: StringInterner,\n}\n\n#[derive(Debug, Default)]\nstruct SSADef&lt;'a&gt; {\n count: u32,\n current_def: HashMap&lt;&amp;'a BasicBlock, IRCode&gt;,\n}\n\nimpl&lt;'a&gt; SSA&lt;'a&gt; {\n fn new() -&gt; SSA&lt;'a&gt; {\n SSA::default()\n }\n\n fn new_variable&lt;'s&gt;(&amp;'s mut self, name: &amp;'a str, block: &amp;'a BasicBlock) -&gt; &amp;'s IRCode {\n let name_sym = self.interner.get_or_intern(name);\n // If `name` is not in `content`, insert `SSADef::new()`\n let def = self.content.entry(name_sym).or_insert_with(SSADef::new);\n // Increment the count\n def.count += 1;\n def.current_def.entry(block).or_insert(\n IRCode::Basic {\n value: name_sym,\n btype: Type::TVarRef,\n id: def.count,\n }\n )\n }\n}\n\nimpl&lt;'a&gt; SSADef&lt;'a&gt; {\n fn new() -&gt; SSADef&lt;'a&gt; {\n SSADef::default()\n }\n}\n\nfn main() {\n // very simple test case\n let mut ssa = SSA::new();\n let bb0 = BasicBlock {\n block_id: 0,\n code: vec![],\n preds: vec![],\n succs: vec![],\n };\n println!(&quot;{:?}&quot;, ssa.new_variable(&quot;foo&quot;, &amp;bb0));\n println!(&quot;{:?}&quot;, ssa);\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T19:43:09.387", "Id": "499227", "Score": "0", "body": "Thanks for the great answer! I was wondering if I had another `IRCode` variant that had a field that was supposed to be a reference to a `BasicBlock`, would I add a lifetime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T15:35:58.937", "Id": "499304", "Score": "0", "body": "@xilpex you would best add `Rc<BasicBlock>` (or `Arc`) or a symbol from an interner." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T11:16:18.357", "Id": "252981", "ParentId": "252869", "Score": "3" } }, { "body": "<p>Peter Blackson has offered a lot of good points.</p>\n<p>Here, I'll focus on one particular issue: your use of references and lifetimes. In particular, you store &amp;str and &amp;BasicBlock in your data structures. This is not a good idea. You should use plain String and BasicBlock.</p>\n<p>To see why, let's make a slight change to your code:</p>\n<pre><code> fn build_ssa() -&gt; SSA \n // very simple test case\n let mut ssa = SSA::new();\n let bb0 = BasicBlock {\n block_id: 0,\n code: vec![],\n preds: vec![],\n succs: vec![],\n };\n ssa.new_variable(&amp;format!(&quot;&amp;{}&quot;, 12), &amp;bb0);\n ssa\n}\n</code></pre>\n<p>You'll find that this won't work. The <code>bb0</code> BasicBlock will be destroyed at the end of the <code>build_ssa function</code>. The string created by the format macro will be destroyed at the end of that line. Both will prevent you from returning the SSA struct from this function.</p>\n<p>That's why you most likely want to have SSA take ownership of both the <code>BasicBlock</code>s and strings. To do so, use <code>String</code> and <code>BasicBlock</code> rather than <code>&amp;str</code> and <code>&amp;BasicBlock</code>.</p>\n<p>Now, you've heard that you should use <code>&amp;str</code> when you only need to read the string and not modify it. Here, however, you want to store the string in the SSA. Functions that store values will usually need to take ownership of the value, and not merely take a reference.</p>\n<p>Now, there is a use case for the sort of structure you did here. That's when you want to share memory between two data structures. For example, if your SSA was produced following an AST, you might want to share memory used for the strings since they probably appear in both your AST and your SSA. On the other hand, you might not, since you plausibly want to throw away your AST when you are finished with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T00:18:15.610", "Id": "499097", "Score": "0", "body": "*For example, if your SSA was produced following an AST* -- I'm getting the feeling you know that algo I am implementing :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T17:20:42.730", "Id": "499217", "Score": "0", "body": "@xiipex, well there is very little other reason to be building an SSA :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T04:44:32.147", "Id": "253019", "ParentId": "252869", "Score": "3" } } ]
{ "AcceptedAnswerId": "252981", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T22:33:53.713", "Id": "252869", "Score": "4", "Tags": [ "beginner", "rust" ], "Title": "Rust - Need help making code idiomatic and clean (with lifetimes)" }
252869
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. As <a href="https://codereview.stackexchange.com/a/252751/231235">Toby Speight's answer</a> mentioned, some self-checking unit tests are needed to verify the correctness of <code>arithmetic_mean</code> function. There are numerous possible ways to construct test iterables and let's focused on <code>std::vector</code> case here first. I am trying to implement a <code>test_vectors_generator</code> which can generate vectors with specific pattern to help the testing tasks of <code>arithmetic_mean</code> function. In the previous question <a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a>, I tried to construct nested <code>std::vector</code> which elements are all filled the same given value with <code>n_dim_vector_generator</code> template function. Besides the case that all elements are with the same value, I've check the question like <a href="https://stackoverflow.com/q/17694579/6667035">use std::fill to populate vector with increasing numbers</a> which discusses the methods for filling sequential values into <code>std::vector</code> so that the vector like <code>{0, 1, 2, 3, ..., 99}</code> is easy to created with <a href="https://stackoverflow.com/a/17694667/6667035">Oleksandr Karaberov's answer</a>. I want to take a further step to create a set of vectors as follows easily with the given conditions <code>start_num=0, end_num=1, step=1, element_count=3</code>.</p> <pre><code>{0, 0, 0} {0, 0, 1} {0, 1, 0} {0, 1, 1} {1, 0, 0} {1, 0, 1} {1, 1, 0} {1, 1, 1} </code></pre> <p><strong>The usage description</strong></p> <p>There are four parameters in <code>test_vectors_generator</code> template function, the first one is a start iteration number of each element, the second one is a end iteration number of each element, the third one is a step size and the fourth one is the element count of each <code>std::vector</code>. In other words, a series <code>std::vector</code> can be created with <code>test_vectors_generator(start_num, end_num, step_num, element_count)</code>. Another usage example is like <code>test_vectors_generator(1, 3, 1, 3)</code> and its output is:</p> <pre><code>{1, 1, 1} {1, 1, 2} {1, 1, 3} {1, 2, 1} {1, 2, 2} {1, 2, 3} {1, 3, 1} {1, 3, 2} {1, 3, 3} {2, 1, 1} ... {3, 1, 1} {3, 1, 2} {3, 1, 3} {3, 2, 1} {3, 2, 2} {3, 2, 3} {3, 3, 1} {3, 3, 2} {3, 3, 3} </code></pre> <p><strong>The experimental implementation</strong></p> <pre><code>namespace ts { template&lt;class T&gt; requires (!is_iterable&lt;T&gt;) constexpr auto test_vectors_generator(T start, T end, T step, std::size_t element_count) { if (element_count == 1) { std::list&lt;std::vector&lt;T&gt;&gt; output(((end - start) / step) + 1); T i = 0; // incrementor std::for_each(output.begin(), output.end(), [&amp;](auto&amp; item) { i+=step; item = std::vector&lt;T&gt;{ i }; }); return output; } else { std::list&lt;std::vector&lt;T&gt;&gt; output{}; auto test_vectors = test_vectors_generator(start, end, step, element_count - 1); std::for_each(test_vectors.begin(), test_vectors.end(), [&amp;](const auto item) { for (T i = start; i &lt;= end; i += step) { auto new_element = item; new_element.push_back(i); output.push_back(new_element); } }); return output; } } } </code></pre> <p>The used <code>is_iterable</code> concept:</p> <pre><code>template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; </code></pre> <p><strong>Test cases</strong></p> <ol> <li>Test cases of <code>test_vectors_generator</code> template function</li> </ol> <p>With the previous question <a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, the contents of <code>std::vector</code> can print out with <code>recursive_print</code> template function. As the result,</p> <pre><code>typedef int TestType; TestType start_num = 1; TestType end_num = 3; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); recursive_print(vectors_for_test); </code></pre> <pre><code>Level 0: Level 1: 1 1 1 Level 1: 1 1 2 Level 1: 1 1 3 Level 1: 1 2 1 Level 1: 1 2 2 Level 1: 1 2 3 Level 1: 1 3 1 Level 1: 1 3 2 Level 1: 1 3 3 Level 1: 2 1 1 ... Level 1: 3 1 1 Level 1: 3 1 2 Level 1: 3 1 3 Level 1: 3 2 1 Level 1: 3 2 2 Level 1: 3 2 3 Level 1: 3 3 1 Level 1: 3 3 2 Level 1: 3 3 3 </code></pre> <ol start="2"> <li>Test cases for <code>arithmetic_mean</code></li> </ol> <p>With <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a> tool, the <code>arithmetic_mean</code> template function can be tested with the following code.</p> <pre><code>BOOST_AUTO_TEST_CASE(test_vectors_generator_char) { typedef char TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_int) { typedef int TestType; TestType start_num = 1; TestType end_num = 3; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_short) { typedef short TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_long) { typedef long TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_long_long_int) { typedef long long int TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_unsigned_char) { typedef unsigned char TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_float) { typedef float TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_double) { typedef double TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_vectors_generator_long_double) { typedef long double TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; auto vectors_for_test = ts::test_vectors_generator(start_num, end_num, step_num, 3); for (auto&amp; each_test_vector : vectors_for_test) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } </code></pre> <p><a href="https://godbolt.org/z/P9xzcK" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>Using <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a> and <code>test_vectors_generator</code> to test <code>arithmetic_mean</code> template function.</p> </li> <li><p>Why a new review is being asked for?</p> <p>I am not sure if it is a good idea to create test cases for <code>arithmetic_mean</code> template function like this. I think that it's hard to test various configuration completely. If there is any further possible improvement, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T02:08:04.060", "Id": "252870", "Score": "1", "Tags": [ "c++", "recursion", "boost", "c++20" ], "Title": "A non-nested test_vectors_generator Function for arithmetic_mean Function Testing in C++" }
252870
<h2>Context</h2> <p>I was making a Convolutional Neural Network from scratch in Python. I completed making it .... It works fine ... The only thing is that it takes a lot of time as the size of the input grows.</p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np import math class ConvolutionalNeuralNetwork(): def __init__(self, num_of_filters, kernel_shape, stride): self.num_of_filters = num_of_filters self.kernel_shape = kernel_shape self.stride = stride self.kernels = [] # Initialize for i in range(self.num_of_filters): self.kernel = np.random.uniform(-1, 1, size=[3,3]) self.kernels.append(self.kernel) self.kernels = np.array(self.kernels) def ElementWiseAddition(self, images): if np.array(images).shape[0] == 1: return images[0] resultant_image = images[0] for image in images[1:]: resultant_image = np.add(image, resultant_image) resultant_image = resultant_image.astype(float) resultant_image /= 2.0 return resultant_image def GetOutput(self, x): filter_maps = [] for filter_n in range(self.num_of_filters): kernel_n_filter_maps = [] for image in x: filter_map = [] for i in range(0, (image.shape[0]-3)+1, self.stride): row = [] for j in range(0, (image.shape[1]-3)+1, self.stride): piece = image[i:i+3, j:j+3] value = np.sum(np.multiply(self.kernels[filter_n], piece)) # Apply Softmax Activation if value &lt; 0.0: value = 0 row.append(value) filter_map.append(row) kernel_n_filter_maps.append(filter_map) filter_maps.append(self.ElementWiseAddition(kernel_n_filter_maps)) return np.array(filter_maps) input = np.random.uniform(-1, 1, size=[512, 4, 4]) ConvolutionalNN = ConvolutionalNeuralNetwork(1028, [3,3], stride=1) output = ConvolutionalNN.GetOutput(input) print(output.shape) </code></pre> <p>How can I make this code consume less time and make it more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T05:11:07.087", "Id": "498439", "Score": "0", "body": "What does your code do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T06:02:09.943", "Id": "498443", "Score": "0", "body": "@AryanParekh The code is an implementation of Convolutional Neural Network" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T18:17:06.753", "Id": "498487", "Score": "0", "body": "I think what @ayan wants to know is what is the output of the code. I am a newbie myself. I ran your code in spyder and I can't make sense of the massive arrays of numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:18:52.377", "Id": "498596", "Score": "0", "body": "Yes @RoniSaiba is correct, it is very unclear as to what your code does, [edit] your question and add more details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:51:46.717", "Id": "498608", "Score": "0", "body": "@AryanParekh sorry but if you are not aware of Convolutional Neural Network, then you cannot understand the question I can't explain what it is in the question as it is a very vast topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:52:22.617", "Id": "498609", "Score": "0", "body": "@RoniSaiba sorry but if you are not aware of Convolutional Neural Network, then you cannot understand the question. I can't explain what it is in the question as it is a very vast topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:56:57.297", "Id": "498612", "Score": "0", "body": "@NITINAGARWAL Yes, I do not understand what convolutional neural networks are. However, to help you, others need to know what you are providing as an input to the network (or code) as well as what is the expected output. It is like saying '5' without saying 'if i provide the input 5 to the function x/5 i get the output 5.'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T19:00:22.423", "Id": "498622", "Score": "0", "body": "@NITINAGARWAL The question lacks a lot of details. Yes, a neural network but what for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:32:33.347", "Id": "498680", "Score": "0", "body": "@AryanParekh It is just a neural network implementation. It can be used for any task you want it for" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T04:55:49.063", "Id": "252873", "Score": "1", "Tags": [ "python", "python-3.x", "machine-learning", "neural-network" ], "Title": "Implementing Convolutional Neural Network" }
252873
<p>Please find my code for securely checking Haveibeenpwned for breached passwords</p> <p>This code will only send a partial HASH over the internet (using HTTPS) and the second part of the HASH will be checked on the users side. Therefore, the full password will never be seen by anyone including haveibeenpwned</p> <pre><code>import hashlib import urllib.request def check_password(firstHash, lateHash): link = f&quot;https://api.pwnedpasswords.com/range/{firstHash}&quot; f = urllib.request.urlopen(link) for line in f.readlines(): searchedHash, hashCount = str(line, &quot;utf-8&quot;).strip().split(&quot;:&quot;) if searchedHash.lower() == lateHash.lower(): return (f&quot;This password has been breached {hashCount} time(s)&quot;) return (&quot;This password has not been breached&quot;) def hash_password(password): encoded_password = password.encode(&quot;UTF-8&quot;) SHA1Hash = hashlib.sha1() SHA1Hash.update(encoded_password) return SHA1Hash.hexdigest() def main(): password = input(&quot;Please enter your password: &quot;) fullHash = hash_password(password) firstHash, lateHash = fullHash[0:5], fullHash[5:] print(check_password(firstHash, lateHash)) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T11:29:10.820", "Id": "252880", "Score": "1", "Tags": [ "hash" ], "Title": "HaveIBeenPwned API" }
252880
<p>I created a simple quiz about HTML,CSS,JS it works fine but as always there is a lot of space for improvement in my code that's why I would love some feedback from you guys.<br></p> <pre><code>'use strict'; // ######################################################## // ######################################################## // ######################################################## // MAIN FUNCTIONALITY const questionNumber = document.querySelector('.question-number'); let quizType; let currentQuestionNuber = 1; let goodAnswers = 0; const displayCurrentQuestionNumber = () =&gt; { questionNumber.textContent = `${currentQuestionNuber}/5`; }; displayCurrentQuestionNumber(); // ######################################################## // ######################################################## // ######################################################## // START QUIZ - DISPLAYING QUESTIONS AND ANSWERS const htmlBtn = document.querySelector('.quiz-type__html'); const cssBtn = document.querySelector('.quiz-type__css'); const jsBtn = document.querySelector('.quiz-type__js'); const menu = document.querySelector('.menu'); const questionsBox = document.querySelector('.questions-box'); const resultsBox = document.querySelector('.result-box'); const quizTitle = document.querySelector('.quiz-title'); htmlBtn.addEventListener('click', () =&gt; { startQuiz('html'); }); cssBtn.addEventListener('click', () =&gt; { startQuiz('css'); }); jsBtn.addEventListener('click', () =&gt; { startQuiz('js'); }); const startQuiz = (type) =&gt; { quizType = type; quizTitle.textContent = quizType; setAnswersColor(); menu.classList.add('swipeLeft'); questionsBox.classList.add('swipeFromRight'); draftQuestion(); }; // different background color for different technology const setAnswersColor = () =&gt; { let answerBgc; if (quizType === 'html') { answerBgc = 'pink-red'; } else if (quizType === 'css') { answerBgc = 'teal'; } else { answerBgc = 'orange'; } for (let i = 0; i &lt; answers.children.length; i++) { answers.children[i].classList.add(`${answerBgc}`); } }; // ######################################################## // ######################################################## // ######################################################## // END QUIZ - HIDE QUESTIONS AND ANSWERS, SHOW RESULT const resultScore = document.querySelector('.correct-answers'); const hideQuestionsBox = () =&gt; { questionsBox.classList.toggle('display-none'); }; const showResultsBox = () =&gt; { resultsBox.classList.toggle('display-none'); }; const endGame = () =&gt; { hideQuestionsBox(); showResultsBox(); if (goodAnswers &gt;= 3) resultScore.textContent = `Well done you answered ${goodAnswers}/5 correctly`; else resultScore.textContent = `You need to work a little because you answered ${goodAnswers}/5 questions correctly`; }; // ######################################################## // ######################################################## // ######################################################## // DRAFTING QUESTIONS const answers = document.querySelector('.questions-box__answers'); const question = document.querySelector('.question'); let htmlQuestions = { questions: [ 'HTML stands for?', 'How is document type initialized in HTML5?', 'Which of the following HTML Elements is used for making any text bold ?', 'Which of the following HTML element is used for creating an unordered list?', 'How many heading tags are there in HTML5?', 'Which of the following attributes is used to add link to any element?', 'Web pages starts with which of the following tag?', ], a: [ 'Hyper Text Markup Language', '&lt;/DOCTYPE HTML&gt;', '&lt;p&gt;', '&lt;ui&gt;', '2', 'link', '&lt;html&gt;', ], b: [ 'High Text Markup Language', '&lt;/DOCTYPE&gt;', '&lt;i&gt;', '&lt;b&gt;', '3', 'href', '&lt;Title&gt;', ], c: [ 'Hyper Tabular Markup Language', '&lt;!DOCTYPE HTML&gt;', '&lt;li&gt;', '&lt;em&gt;', '6', 'ref', '&lt;body&gt;', ], d: [' None of these', '&lt;/DOCTYPE html&gt;', '&lt;b&gt;', '&lt;ul&gt;', '5', 'src', '&lt;form&gt;'], goodAnswer: [ 'Hyper Text Markup Language', '&lt;!DOCTYPE HTML&gt;', '&lt;b&gt;', '&lt;ul&gt;', '6', 'href', '&lt;html&gt;', ], }; let cssQuestions = { questions: [ 'What property do you use to create spacing between HTML elements?', 'What is the property used to set the class’s text color?', 'CSS stands for?', 'What property would you use to create space between the element’s border and inner content?', 'What property do you use to set the background color?', 'how do you give it a particular style when the user hovers over the element?', 'How to set the style for a specific HTML element with an id of “special”?', ], a: [ 'margin', 'text-color', 'Cascading Style Sheets', 'margin', 'color', ':onHover', '#special{ }', ], b: [ 'spacing', 'text', 'Canvas Styling System', 'spacing', 'background-color', ':hover', '.special{ }', ], c: [ 'padding', 'color', 'Cascade Style System', 'padding', 'background', ':mouseOver', 'id.special{ }', ], d: [ 'border', 'font-color', 'Cascading Style System', 'border', 'bg-color', ':active', 'element.id.special{ }', ], goodAnswer: [ 'margin', 'color', 'Cascading Style Sheets', 'padding', 'background-color', ':hover', '#special{ }', ], }; let jsQuestions = { questions: [ 'To insert a JavaScript into an HTML page, which tag is used?', 'How to append a value to an array of Java Script?', 'Which of the following function of String object executes the search for a match between a regular expression and a specified string?', 'Which built-in method calls a function for each element in the array?', 'How can we check the length of an array?', 'How to log text in console?', 'Which variable definition is correct', ], a: [ `&lt;script='java'&gt;`, 'arr[arr.length] = value', 'concat()', 'for', 'length(arr)', 'console.log()', 'var 1a', ], b: [ '&lt;javascript&gt;', 'arr[arr.length-1] = value', 'includes()', 'loop', 'arr.length', 'clog()', 'let 1a', ], c: [ '&lt;script&gt;', 'arr[arr.length+1] = new Arrays()', 'match()', 'while', 'arr.length()', 'console.text()', 'let a1', ], d: [ '&lt;js&gt;', 'arr[arr.length*1] = value', 'test', 'forEach', 'arr(length)', 'print()', 'int a ', ], goodAnswer: [ '&lt;script&gt;', 'arr[arr.length] = value', 'match()', 'forEach', 'arr.length', 'console.log()', 'let a1', ], }; function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } let randomNumber; let answeredQuestions = []; const draftQuestion = () =&gt; { randomNumber = getRandomInt(7); if (quizType === 'html') { if (!answeredQuestions.includes(randomNumber)) { question.textContent = htmlQuestions.questions[randomNumber]; answers.children[0].textContent = htmlQuestions.a[randomNumber]; answers.children[1].textContent = htmlQuestions.b[randomNumber]; answers.children[2].textContent = htmlQuestions.c[randomNumber]; answers.children[3].textContent = htmlQuestions.d[randomNumber]; answeredQuestions.push(randomNumber); } else { draftQuestion('html'); } } else if (quizType === 'css') { if (!answeredQuestions.includes(randomNumber)) { question.textContent = cssQuestions.questions[randomNumber]; answers.children[0].textContent = cssQuestions.a[randomNumber]; answers.children[1].textContent = cssQuestions.b[randomNumber]; answers.children[2].textContent = cssQuestions.c[randomNumber]; answers.children[3].textContent = cssQuestions.d[randomNumber]; answeredQuestions.push(randomNumber); } else { draftQuestion('css'); } } else { if (!answeredQuestions.includes(randomNumber)) { question.textContent = jsQuestions.questions[randomNumber]; answers.children[0].textContent = jsQuestions.a[randomNumber]; answers.children[1].textContent = jsQuestions.b[randomNumber]; answers.children[2].textContent = jsQuestions.c[randomNumber]; answers.children[3].textContent = jsQuestions.d[randomNumber]; answeredQuestions.push(randomNumber); } else { draftQuestion('js'); } } }; // ######################################################## // ######################################################## // ######################################################## // CHECK IN ANSWER IS GOOD OR NOT const isGoodAnswer = (answer) =&gt; { if (quizType === 'html') { if (answer.textContent === htmlQuestions.goodAnswer[randomNumber]) return true; return false; } else if (quizType === 'css') { if (answer.textContent === cssQuestions.goodAnswer[randomNumber]) return true; return false; } if (answer.textContent === jsQuestions.goodAnswer[randomNumber]) return true; return false; }; for (let i = 0; i &lt; answers.children.length; i++) { answers.children[i].addEventListener('click', () =&gt; { if (isGoodAnswer(answers.children[i])) { goodAnswers++; } if (currentQuestionNuber === 5) endGame(); else { currentQuestionNuber++; displayCurrentQuestionNumber(); draftQuestion(); } }); } </code></pre> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;style/main.css&quot;&gt; &lt;title&gt;Quiz&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;div class=&quot;menu&quot;&gt; &lt;h2&gt;Quiz&lt;/h2&gt; &lt;p&gt;Web site technologies&lt;/p&gt; &lt;p&gt;Select quiz &lt;/p&gt; &lt;div class=&quot;quiz-type&quot;&gt; &lt;div class=&quot;quiz-type__html&quot;&gt;HTML&lt;/div&gt; &lt;div class=&quot;quiz-type__css&quot;&gt;CSS&lt;/div&gt; &lt;div class=&quot;quiz-type__js&quot;&gt;JavaScript&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;questions-box&quot;&gt; &lt;h3 class='quiz-title'&gt;&lt;/h3&gt; &lt;p class='question'&gt;&lt;/p&gt; &lt;p class=&quot;question-number&quot;&gt;&lt;/p&gt; &lt;div class=&quot;questions-box__answers&quot;&gt; &lt;a class=&quot;questions-box__answer&quot;&gt;&lt;/a&gt; &lt;a class=&quot;questions-box__answer&quot;&gt;&lt;/a&gt; &lt;a class=&quot;questions-box__answer&quot;&gt;&lt;/a&gt; &lt;a class=&quot;questions-box__answer&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;result-box display-none&quot;&gt; &lt;h3&gt;RESULTS&lt;/h3&gt; &lt;p class=&quot;correct-answers&quot;&gt;aa&lt;/p&gt; &lt;/div&gt; &lt;/main&gt; &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <pre><code>@import url(&quot;https://fonts.googleapis.com/css2?family=Poppins:wght@300;500;600&amp;display=swap&quot;); *, *::after, *::before { padding: 0; margin: 0; -webkit-box-sizing: border-box; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body { background-color: #111010; height: 100vh; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } main { background-color: #fffbfc; padding: 10rem 20rem; border-radius: 5px; overflow: hidden; position: relative; } main .menu { text-align: center; -webkit-transition: all 1s; transition: all 1s; } main .menu h2 { font-size: 2rem; font-weight: 600; color: black; } main .menu p { font-size: 1rem; font-weight: 300; color: #353535; margin-bottom: 1.3rem; } main .menu .quiz-type { display: -webkit-box; display: -ms-flexbox; display: flex; } main .menu .quiz-type div { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 1rem 2rem; border-radius: 5px; cursor: pointer; font-size: 0.8rem; font-weight: 600; color: white; } main .menu .quiz-type div:not(:first-child) { margin-left: 0.2rem; } main .menu .quiz-type__html { background-color: #d81159; } main .menu .quiz-type__html:hover { background-color: #bd0f4f; } main .menu .quiz-type__css { background-color: #008f8f; } main .menu .quiz-type__css:hover { background-color: teal; } main .menu .quiz-type__js { background-color: #fbb13c; } main .menu .quiz-type__js:hover { background-color: #fba823; } main .questions-box { padding: 3rem 10rem; width: 100%; height: 100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translateX(200%) translateY(-50%); transform: translateX(200%) translateY(-50%); -webkit-transition: all 1s; transition: all 1s; text-align: center; } main .questions-box .quiz-title { font-size: 1.7rem; font-weight: 600; color: black; text-transform: uppercase; } main .questions-box .question { font-size: 1rem; font-weight: bold; color: #1b1b1b; margin-bottom: 1.3rem; margin-top: 2.5rem; } main .questions-box .question-number { position: absolute; top: 3rem; left: 3rem; font-weight: bold; font-size: 1.2rem; } main .questions-box__answer { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; outline: none; display: block; color: White; font-weight: 300; border-radius: 5px; padding: 1rem 0; cursor: pointer; } main .questions-box__answer:not(:first-child) { margin-top: 0.7rem; } main .result-box { padding: 3rem 10rem; width: 100%; height: 100%; position: absolute; top: 0; left: 0; text-align: center; } main .result-box h3 { font-size: 1.7rem; font-weight: 600; color: black; } main .result-box .correct-answers { margin-top: 2.5rem; } .swipeLeft { -webkit-transform: translateX(-200%); transform: translateX(-200%); } .swipeFromRight { -webkit-transform: translateX(-50%) translateY(-50%) !important; transform: translateX(-50%) translateY(-50%) !important; } .pink-red { background-color: #d81159; } .pink-red:hover { background-color: #bd0f4f; } .teal { background-color: #008f8f; } .teal:hover { background-color: teal; } .orange { background-color: #faa00f; } .orange:hover { background-color: #dc8904; } .display-none { display: none; } </code></pre>
[]
[ { "body": "<p>Well, the code is not bad.</p>\n<p>JS:</p>\n<pre><code>htmlBtn.addEventListener('click', () =&gt; {\n startQuiz('html');\n});\n</code></pre>\n<p>could be shortened to</p>\n<pre><code>htmlBtn.addEventListener('click', () =&gt; startQuiz('html'));\n</code></pre>\n<p>or</p>\n<pre><code>const showResultsBox = () =&gt; {\n resultsBox.classList.toggle('display-none');\n};\n</code></pre>\n<p>to</p>\n<pre><code>const showResultsBox = () =&gt; resultsBox.classList.toggle('display-none');\n</code></pre>\n<p>CSS:</p>\n<pre><code>display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n</code></pre>\n<p>are you sure You need to use all of those prefixes ? Isn't <code>display: flex</code> enough ?</p>\n<pre><code> background-color: #d81159; \n</code></pre>\n<p>is used twice. Create a selector that covers multiple elements instead of repeating the code :)</p>\n<p>Aditionally:</p>\n<ul>\n<li>I'd add the colors declarations to the separate file :)</li>\n<li>I heard that it's better to get the elements in JS by <code>getElementByID()</code> (if possible) because it's faster but I'm not 100% sure about that. Maybe it's worth taking a look :)</li>\n<li>Your quiz-type-buttons are <code>divs</code> which is a mistake because of the accessibility standards. They should be regular <code>button</code>s so that screen readers understand what's going on</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T15:38:26.673", "Id": "252886", "ParentId": "252881", "Score": "1" } } ]
{ "AcceptedAnswerId": "252886", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T12:05:46.713", "Id": "252881", "Score": "1", "Tags": [ "javascript" ], "Title": "Quiz game in JS" }
252881
<p>The code generates a list containing all possible combinations of the items of an array. Every triplet of items contains two operands and the third item containing <code>&quot;-0.0&quot;</code> or <code>null</code>, depending on the result of the given <code>BiFunction</code> applied to the operands. The list then is printed out, with additions for better readabilty (<code>null</code>s are not printed, operation signs are inserted). The output looks like</p> <pre><code> ... -0.0 * -30.0 = -0.0 * -5.0 = -0.0 * -0.0 = -0.0 * 0.0 = -0.0 -0.0 * 6.0 = -0.0 -0.0 * 40.0 = -0.0 ... </code></pre> <p>There are tho methods intended to be used in a real project, they are marked with &quot;(meant to be used in a real project)&quot;. Regarding formatting, it's my deliberate choice to write <code>if</code>s with a single nested statement without curly braces -- I hate to read code written in a sparse manner, when I can see only 3 substantial lines of code on the screen, and I never write such a code.</p> <p>I'd like to know:</p> <ol> <li>if the provided code conforms to the best practices regarding style (naming conventions, formatting etc);</li> <li>Is there a smarter, neater solution for the task;</li> <li>Are the comments intelligible enough (among others, my English is a concern);</li> <li>What is the &quot;right&quot; way to check if a double value is <code>-0</code> (marked with &quot;???&quot;)</li> </ol> <p>The code:</p> <pre><code>package forquadruple.streamsandlambdas; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; /** * 20.12.01 14:49:05 * Builds and tests a list with the Cartesian products of the given operands * that are String representations of double values. * The list should consist of triplets of Strings, where each triplet * includes a pair of string representations of two double operands, and the third item of the triplet * should depend on the result of the given {@code BiFunction&lt;Double, Double, Double&gt; function} applied to the operands.&lt;br&gt; * If the result of the function is -0, the third item of the triplet should contain &quot;-0.0&quot;, * otherwise it should be {@code null}, * in other words, for any n&lt;pre&gt; * triplet[n*3 + 2] = * (function(triplet[n*3], triplet[n*3 + 1]) == -0 ? &quot;-0.0&quot; : null) * &lt;/pre&gt; * for example, for multiplication the list may contain the following triplets: * &lt;pre&gt; * &quot;0&quot;, &quot;-5&quot;, &quot;-0&quot;, * &quot;5&quot;, &quot;-5&quot;, null, * &lt;/pre&gt; */ public class TestListGeneration { private static final char[] OP_SIGNS = new char[] {'+', '-', '*', '/'}; private static final String[] OPERANDS = new String[] { &quot;-Infinity&quot;, &quot;-30.0&quot;, &quot;-5.0&quot;, &quot;-0.0&quot;, &quot;0.0&quot;, &quot;6.0&quot;, &quot;40.0&quot;, &quot;Infinity&quot;, &quot;NaN&quot;, }; public static void main(String[] args) { new TestListGeneration().testGeneration(); } /** * Build some sample lists and print their contents */ private void testGeneration() { final List&lt;String&gt; list = new ArrayList&lt;&gt;(); final int sectionSize = (OPERANDS.length * OPERANDS.length + 1) * 3; // To know when to add a gap between different operations // add lists for different operatins list.addAll(cartesianSquareWithMinusZeros(OPERANDS, (a, b) -&gt; a + b)); // add sums of operands list.add(&quot;&quot;); list.add(&quot;&quot;); list.add(&quot;&quot;); // Just a gap between operations, for better readability list.addAll(cartesianSquareWithMinusZeros(OPERANDS, (a, b) -&gt; a - b)); list.add(&quot;&quot;); list.add(&quot;&quot;); list.add(&quot;&quot;); list.addAll(cartesianSquareWithMinusZeros(OPERANDS, (a, b) -&gt; a * b)); list.add(&quot;&quot;); list.add(&quot;&quot;); list.add(&quot;&quot;); list.addAll(cartesianSquareWithMinusZeros(OPERANDS, (a, b) -&gt; a / b)); list.add(&quot;&quot;); list.add(&quot;&quot;); list.add(&quot;&quot;); printTheList(list, sectionSize); } /** * (meant to be used in a real project) * Builds a list of all possible pairs of operands (their Cartesian square) * supplemented with &quot;-0.0&quot; (if the result of the given operation applied to the operands is -0) * or with null (in all other cases). * @param operands -- an array containing string representations of double operands * @param operatoin -- the operation whose result affects the third * @return the resulting list */ public List&lt;String&gt; cartesianSquareWithMinusZeros(String[] operands, BiFunction&lt;Double, Double, Double&gt; operatoin) { final List&lt;String&gt; result = new ArrayList&lt;&gt;(); Arrays.stream(OPERANDS).forEach(s1 -&gt; { Arrays.stream(OPERANDS).forEach(s2 -&gt; { result.add(s1); result.add(s2); result.add(isMinusZero(s1, s2, operatoin)? &quot;-0.0&quot; : null); }); } ); return result; } /** * (meant to be used in a real project) * Checks whether the given operation applied to the given operands results in -0 * @param op1str -- 1st operand as a String * @param op2str -- 2nd operand as a String * @param operation -- the operation to perform on the operands * @return true, if the result of the operation is -0, false otherwise */ private boolean isMinusZero(String op1str, String op2str, BiFunction&lt;Double, Double, Double&gt; operation) { final double op1 = Double.parseDouble(op1str); final double op2 = Double.parseDouble(op2str); // ??? is there a neater way to check if a value is -0? return Double.doubleToLongBits(operation.apply(op1, op2)) == 0x8000_0000_0000_0000L; } /** * Prints the list, just to watch the contents of the list * @param list * @param sectionSize */ private void printTheList(final List&lt;String&gt; list, final int sectionSize) { String s = &quot;&quot;; char opSign = '+'; for (int i = 0; i &lt; list.size(); ) { if (i % sectionSize &gt;= sectionSize - 3) // Just a gap between operations, for better readability opSign = ' '; // Will be an empty line else opSign = OP_SIGNS[i / sectionSize]; // Will be a line with the operands and (perhaps) say(&quot;%9s %s %9s %s %s&quot;, list.get(i++), opSign, list.get(i++), // Operands separated by the operation sign opSign == ' ' ? ' ' : '=', // and perhaps accompanied with the result (s = list.get(i++)) == null? &quot;&quot;: s); // replace nulls with empty strings } } /** print to console, just for convenience */ public static void say() { System.out.println(); } public static void say(Object o) { System.out.println(o); } public static void say(String format, Object... args) { System.out.println(String.format(format, args)); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>There's no reason to use <code>Arrays#stream</code> to iterate an array. It's slower and requires all captured locals to be final, as opposed to a simple <code>for (String s1 : OPERANDS)</code> which compiles directly to a normal for loop.</p>\n</li>\n<li><p>'Operation' is misspelled several times</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T00:07:11.157", "Id": "253199", "ParentId": "252882", "Score": "1" } } ]
{ "AcceptedAnswerId": "253199", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T12:59:20.710", "Id": "252882", "Score": "2", "Tags": [ "java", "lambda" ], "Title": "Building a list from the Catresian square of an array" }
252882
<p><a href="https://arxiv.org/pdf/2009.07047v1.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/2009.07047v1.pdf</a></p> <p>I don't have a lot of experience in building a network model. I would like to build the <code>Encoder</code> and <code>Generator</code> network model from the above article.</p> <p>Here is my attempt :</p> <pre><code>import torch.nn as nn class ResnetBlock(nn.Module): def __init__(self, dim, norm_layer, activation=nn.ReLU(False), kernel_size=3): super().__init__() pw = (kernel_size - 1) // 2 self.conv_block = nn.Sequential( nn.ReflectionPad2d(pw), norm_layer(nn.Conv2d(dim, dim, kernel_size=kernel_size)), activation, nn.ReflectionPad2d(pw), norm_layer(nn.Conv2d(dim, dim, kernel_size=kernel_size)), ) def forward(self, x): y = self.conv_block(x) out = x + y return out class Encoder(nn.Module): &quot;&quot;&quot; Network used for the VAE (Encoder) as well as in the GAN (i.e. Discriminator). In other words, it is the same architecture as the image discriminator. Attributes: num_features (int) : &quot;&quot;&quot; def __init__(self, num_features): super().__init__() self.encoder = nn.Sequential( nn.Conv2d(num_features, 256, knernel_size=7, stride=1) nn.Conv2d(256, 128, knernel_size=4, stride=2) nn.Conv2d(128, 64, knernel_size=4, stride=2) ) self.resnet_block = ResnetBlock(64, kernel_size=3) def forward(self, x): out = self.encoder(x) out = self.resnet_block(out) return out class Generator(nn.Module): def __init__(self, num_features): super().__init__() self.resnet_block = ResnetBlock(64, kernel_size=3) self.generator = nn.Sequential( nn.Conv2d(64, 128, knernel_size=4, stride=2) nn.Conv2d(128, 256, knernel_size=4, stride=2) nn.Conv2d(256, num_features, knernel_size=7, stride=1) ) def forward(self, x): out = self.resnet_block(x) out = self.generator(x) return out </code></pre> <p>I am not sure the model Encoder and Generator are properly well coded according to</p> <p><a href="https://i.stack.imgur.com/w4kA0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w4kA0.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T14:25:22.603", "Id": "498576", "Score": "0", "body": "Hey Alex, if you're not sure your code works, sadly it means it's not a good fit for this site. The goal of a code review is to review code that works, otherwise it's not so much reviewing as writing the code for you. You could start by comparing the table in the article to the one generated by ` model.summary()` , it might help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T14:32:21.050", "Id": "498577", "Score": "0", "body": "@IEatBagels I am not saying the code doesn't work. I am saying I need help reviewing the code in itself. I am not sure if the `Encoder` and `Generator` are well defined corresponding the detailed structure network. This is only where I need help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:13:43.373", "Id": "498602", "Score": "1", "body": "I understand your point. The thing is, you do not know if it works as expected (the expected architecture being the paper's one). In this case, it's not so much a code review as to help you figure out if your code does what it's supposed to do, which is off-topic. I think this just isn't the right fit for CodeReview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T13:40:34.663", "Id": "498707", "Score": "1", "body": "Have you run the code and does it work as expected? If you have run the code can you please supply the test cases? One of the ways we could help is to point out test cases that you haven't tried." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T13:32:57.577", "Id": "252883", "Score": "2", "Tags": [ "python", "ai", "neural-network" ], "Title": "Generator and Encoder network model" }
252883
<h1>Introduction</h1> <hr /> <p>I have just started learning templates and experimenting with function pointers. I wanted to create an event system that met a couple of goals:</p> <ul> <li>Event types are PODs, and do <strong>not</strong> inherit from a base 'Event' class</li> <li>External API is simple, no binding or passing in lambdas etc.</li> <li>No explicit registering of event types by user, any POD struct like object should work</li> </ul> <p>The implementation currently works, however hasn't been heavily tested. The code will be used in my small &quot;game engine&quot; project, done purely as a learning exercise.</p> <h2>Focus</h2> <hr /> <p>I am most interested in the way I am storing and calling the functions. I wanted a way to store any arbitrary event type that met the conditions described above.</p> <p>I'm not convinced on the way I am handling the <code>ListenerHandle</code>s which are solely used to enable the <code>remove_listener</code> feature. However this is of less concern to me than my previous point.</p> <h2>Future</h2> <hr /> <ul> <li>Multithreading/Async</li> <li>Delayed event queues</li> </ul> <h1>Usage</h1> <hr /> <p>I'll start with what it looks like to use the API, I am relatively happy with this aspect:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;EventManager.h&quot; const int key_w = 87; struct CollisionEvent { int x; int y; }; struct KeyPressEvent { int key_code; }; class InputHandler { public: InputHandler() { EventManager::listen&lt;KeyPressEvent&gt;(this, &amp;InputHandler::on_key_press); } private: void on_key_press(KeyPressEvent* event) { // ... } }; void handle_collision(CollisionEvent* event) { // ... } int main() { InputHandler input_handler; EventManager::fire&lt;KeyPressEvent&gt;(key_w); ListenerHandle handle = EventManager::listen&lt;CollisionEvent&gt;(&amp;handle_collision); EventManager::fire&lt;CollisionEvent&gt;(10, 3); EventManager::remove_listener(handle); } </code></pre> <h1>Implementation</h1> <hr /> <p>It is implemented in a single header <code>EventManager.h</code>, and is roughly ~140 lines without whitespace. I will divide each part into its own block for readability.</p> <h3><code>ListenerHandle</code></h3> <hr /> <p>A <code>ListenerHandle</code> is returned to the user upon registering an event callback. Each callback function is uniquely associated with one handle, allowing users to remove their callback.</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;cassert&gt; #include &lt;cstdint&gt; #include &lt;vector&gt; #include &lt;memory&gt; #include &lt;functional&gt; #include &lt;queue&gt; typedef std::uint32_t EventID; class ListenerHandle { public: ListenerHandle(std::uint32_t sparse_index = 0u, std::uint32_t dense_index = 0u, std::uint32_t version = 0u, EventID event_id = 0u) : m_sparse_index(sparse_index), m_dense_index(dense_index), m_version(version), m_event_id(event_id) {} public: std::uint32_t m_sparse_index; std::uint32_t m_dense_index; std::uint32_t m_version; EventID m_event_id; friend class EventManager; template&lt;typename T&gt; friend struct CallbackContainer; }; </code></pre> <h3><code>CallbackContainer</code></h3> <hr /> <p>A callback container is used to store each callback of the same event type (i.e from the example above, all <code>KeyPressEvent</code> callbacks would be stored together in an instance of <code>CallbackContainer</code>).</p> <p>A sparse set is used to track which <code>ListenerHandle</code> belongs to which callback. Each index in the sparse-set is versioned, so you can only remove the callback originally associated with your handle.</p> <pre class="lang-cpp prettyprint-override"><code>struct CallbackContainerBase { virtual void remove_callback(const ListenerHandle&amp; handle) = 0; }; template&lt;typename T&gt; struct CallbackContainer : CallbackContainerBase { CallbackContainer(EventID event_id) : event_id{ event_id } {} std::vector&lt;std::function&lt;void(T*)&gt;&gt; callbacks; std::vector&lt;ListenerHandle&gt; handles; EventID event_id; std::vector&lt;ListenerHandle&gt; sparse; std::vector&lt;std::uint32_t&gt; dense; std::queue&lt;std::uint32_t&gt; free_sparse_indices; template&lt;typename T_Function&gt; auto add_callback(T_Function callback)-&gt;ListenerHandle; void remove_callback(const ListenerHandle&amp; handle) override; }; template&lt;typename T&gt; inline void CallbackContainer&lt;T&gt;::remove_callback(const ListenerHandle&amp; handle) { assert(handle.m_version == sparse[handle.m_sparse_index].m_version); sparse[handle.m_sparse_index].m_version++; std::uint32_t remove_index = sparse[handle.m_sparse_index].m_dense_index; std::uint32_t last_index = callbacks.size() - 1; dense[remove_index] = dense[last_index]; sparse[dense[remove_index]].m_dense_index = remove_index; std::swap(callbacks[remove_index], callbacks[last_index]); free_sparse_indices.push(handle.m_sparse_index); callbacks.pop_back(); dense.pop_back(); } template&lt;typename T&gt; template&lt;typename T_Function&gt; inline auto CallbackContainer&lt;T&gt;::add_callback(T_Function callback) -&gt; ListenerHandle { std::uint32_t sparse_index; if (free_sparse_indices.empty()) { sparse_index = callbacks.size(); sparse.emplace_back(sparse_index, sparse_index, 0u, event_id); } else { sparse_index = free_sparse_indices.front(); free_sparse_indices.pop(); } dense.push_back(sparse_index); callbacks.emplace_back(callback); return sparse[sparse_index]; } </code></pre> <h3><code>EventManager</code></h3> <hr /> <p>This is the class that users interact with, a trivial system is used to create run-time available IDs to identify event types, which act as indexes into the vector of <code>CallbackContainer</code>'s.</p> <p>Each <code>CallbackContainer</code> is stored as its base <code>CallbackContainerBase</code> to allow for the storage of any arbitrary type, and then casted to the correct type when needed.</p> <pre class="lang-cpp prettyprint-override"><code> class EventManager { using CallbackContainers = std::vector&lt;std::unique_ptr&lt;CallbackContainerBase&gt;&gt;; public: template&lt;typename T, typename T_Function&gt; static auto listen(T_Function callback)-&gt;ListenerHandle; template&lt;typename T, typename T_Instance, typename T_Function&gt; static auto listen(T_Instance* instance, T_Function callback)-&gt;ListenerHandle; static void remove_listener(const ListenerHandle&amp; handle); template&lt;typename T, typename... T_Args&gt; static void fire(T_Args...args); private: template&lt;typename T&gt; static auto get_event_id()-&gt;EventID; template&lt;typename T&gt; static auto register_event()-&gt;EventID; private: static inline CallbackContainers s_callbacks; static inline EventID s_next_event_id{ 0u }; }; template&lt;typename T, typename T_Function&gt; inline ListenerHandle EventManager::listen(T_Function callback) { return static_cast&lt;CallbackContainer&lt;T&gt;*&gt;(s_callbacks[get_event_id&lt;T&gt;()].get())-&gt;add_callback(callback); } template&lt;typename T, typename T_Instance, typename T_Function&gt; inline ListenerHandle EventManager::listen(T_Instance* instance, T_Function callback) { return static_cast&lt;CallbackContainer&lt;T&gt;*&gt;(s_callbacks[get_event_id&lt;T&gt;()].get())-&gt;add_callback([instance, callback](T* event) { (instance-&gt;*callback)(event); }); } inline void EventManager::remove_listener(const ListenerHandle&amp; handle) { s_callbacks[handle.m_event_id]-&gt;remove_callback(handle); } template&lt;typename T, typename ...T_Args&gt; inline void EventManager::fire(T_Args ...args) { T event{ args... }; auto&amp; callbacks = static_cast&lt;CallbackContainer&lt;T&gt;*&gt;(s_callbacks[get_event_id&lt;T&gt;()].get())-&gt;callbacks; for (auto&amp; callback : callbacks) callback(&amp;event); } template&lt;typename T&gt; inline EventID EventManager::get_event_id() { static EventID event_id = register_event&lt;T&gt;(); return event_id; } template&lt;typename T&gt; inline EventID EventManager::register_event() { s_callbacks.emplace_back(std::make_unique&lt;CallbackContainer&lt;T*&gt;&gt;(s_next_event_id)); return s_next_event_id++; } </code></pre> <p>Thank you for your time, it is greatly appreciated!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T14:10:07.283", "Id": "252884", "Score": "6", "Tags": [ "c++", "game", "c++17", "event-handling" ], "Title": "C++ Event System - Game Engine" }
252884
<p>I am using Log4j2 for logging. Multiple operations return success code. If status <code>0</code> is received, it means operation is successful, else failed. If operation is successfully, I log <code>&quot;*** is successfully.&quot;</code> and if it fails I logs <code>&quot;*** failed with status : &quot; + status</code>. This is kind of repetitive in code.</p> <pre><code>public class ReadCallbackManager { //Log Object private static final Logger LOGGER = LogManager.getLogger(ReadCallbackManager.class); private static ReadCallback readCallback; private static final int SUCCESS_STATUS = 0; public int setHook(final ICallback aCallBack) { readCallback = new ReadCallback(aCallBack); final int status = readCallback.setHook(); if (status == SUCCESS_STATUS) { LOGGER.info(&quot;Read callback hook is set successfully!!!&quot;); } else { LOGGER.info(&quot;Read Callback hook set failed with status : &quot; + status); } return status; } } </code></pre> <p>So I though to create a wrapper around the Logger class to handle this if else condition as below:</p> <pre><code>public final class BacStacLogger { public static final int SUCCESS_STATUS = 0; //Log Object private Logger logger; public BacStacLogger(final Class&lt;?&gt; className) { if (logger == null) { logger = LogManager.getLogger(className); } } public void infoHookByStatus(final int status, final String successMessage, final String failureMessage) { if (status == SUCCESS_STATUS) { logger.info(successMessage); } else { logger.info(failureMessage + &quot; : &quot; + status); } } } </code></pre> <p>And I have updated my previous code as :</p> <pre><code>public class ReadCallbackManager { //Log Object private static final ProjectLogger LOGGER = ProjectLogger(ReadCallbackManager.class); private static ReadCallback readCallback; public int setHook(final ICallback aCallBack) { readCallback = new ReadCallback(aCallBack); final int status = readCallback.setHook(); LOGGER.infoHookByStatus(status, &quot;Read hook set successfully.&quot;, &quot;Read hook set failed.&quot;); return status; } } </code></pre> <p>Would you please provide your comments on it? Or if required, any improvements?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T15:47:07.133", "Id": "498476", "Score": "2", "body": "You might be over thinking this. To my eyes, it feels like you replaced an `if` statement with a lot more code. If it is not a matter of relevance may be consider logging the `status` directly `LOGGER.info(\"Read callback hook response \" + status);` On the encapsulation itself, I think that is a good solution if you anticipate future uses, for now I'd keep it simple." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T17:44:43.610", "Id": "498483", "Score": "0", "body": "Side note: You are using the name `LOGGER`, indicating that you consider it to be a constant. According to the Google Java Style Guide: \"*Constants are static final fields whose contents are deeply immutable and **whose methods have no detectable side effects.** This includes primitives, Strings, immutable types, and immutable collections of immutable types.* (...)\" A `Logger` object has a side effect and is therefore not a constant. [Source](https://google.github.io/styleguide/javaguide.html#s5.2.4-constant-names) - with logger as an explicit example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T17:49:39.613", "Id": "498485", "Score": "0", "body": "@Bhaskar In some cases it's easier to change your requirements than the code, I totally agree with you! I would recommend posting that as an answer. If needed, the message can even contain \"success: true\" or \"success: false\" by evaluating the boolean value within the log message. Also, avoid string concatenation in logging, use this instead: `logger.info(\"Read callback hook response: {}, success: {}\", status, status == SUCCESS_STATUS)`" } ]
[ { "body": "<p>There are a few remarks that come to my mind.</p>\n<h2>Simplifying the logic</h2>\n<p>In your sample code, the two different log strings for success and failure don't differ too much. So I guess the following strings might be acceptable to you as well:</p>\n<pre><code>&quot;Setting read callback hook: successful&quot;\n&quot;Setting read callback hook: FAILED with status nnn&quot;\n</code></pre>\n<p>Then you can create a static method <code>statusText(int status)</code> e.g. in a <code>Utils</code> class that returns <code>&quot;successful&quot;</code> for status==0 and <code>&quot;FAILED with status nnn&quot;</code> in all other cases. If I understood correctly, such a <code>statusText()</code> method should be re-usable all over your application, assuming that 0 always means success.</p>\n<p>And then you can do the logging like:</p>\n<pre><code>LOGGER.info(&quot;Setting read callback hook: &quot; + Utils.statusText(status));\n</code></pre>\n<p>But there are a few other issues:</p>\n<h2>Log Levels</h2>\n<p>Log4J has different log levels, and you shouldn't ignore that aspect. Depending on the consequences, a failure should typically get the ERROR level, at least the WARN level. So, in case of a non-zero status, <code>LOGGER.error()</code> seems to be a better choice.</p>\n<p>INFO is meant for messages useful to the system administrator running the site. Messages targetting the developer should get a lower level, typically DEBUG or TRACE. I guess, the success of setting some callback isn't important to the system admin. The admin typically only wants to see things needing his/her special attention. So, I'd change the success case to <code>LOGGER.debug()</code>.</p>\n<p>Of course, then my <code>statusText()</code> solution no longer fits, as that doesn't support different log levels.</p>\n<h2>Why not Exceptions?</h2>\n<p>Your code sticks to the 1970s status code pattern to communicate failure (return an integer where some values mean success and others mean failure). By the 1990s, the software industry had learned that error handling can be done in a better way using exceptions.</p>\n<p>So, instead of returning <code>int</code> values and forcing each and every layer of your software to check for the success results, throw an exception if something like setting a callback failed. By embracing exceptions as the signal of failure, your code typically becomes</p>\n<ul>\n<li>cleaner,</li>\n<li>more readable,</li>\n<li>more compact,</li>\n<li>more focussed on the main task instead of the failures</li>\n<li>and more robust.</li>\n</ul>\n<p>The simple guidelines for exceptions are:</p>\n<ul>\n<li>If a method can't fulfill its job (whatever you defined that job to be), it throws an exception.</li>\n<li>If a method returns normally, the caller can rely on the fact it has successfully done its job.</li>\n<li>You catch an exception only if you know a way how to continue successfully even after an internal failure, e.g. by retrying.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T19:21:56.080", "Id": "252895", "ParentId": "252885", "Score": "3" } } ]
{ "AcceptedAnswerId": "252895", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T15:08:48.253", "Id": "252885", "Score": "1", "Tags": [ "java", "logging" ], "Title": "Logging conditionally repetitively in code" }
252885
<p>I'm currently working on a live keyboard demo on unity. I've animated every key but my script spans over 2000 lines. I'm fairly happy with my script but I know theres better ways to do it.</p> <p>I have defined functions and if statements for each and every key.</p> <p>I'll post my code below</p> <pre class="lang-cs prettyprint-override"><code>private Animator Alpha1Press; private Animator Alpha2Press; private Animator Alpha3Press; private Animator Alpha4Press; private Animator Alpha5Press; private Animator Alpha6Press; private Animator Alpha7Press; private Animator Alpha8Press; private Animator Alpha9Press; private Animator Alpha0Press; public void playAlpha1() { Alpha1Press.SetBool(&quot;Alpha1Pressed&quot;, true); } public void stopAlpha1() { Alpha1Press.SetBool(&quot;Alpha1Released&quot;, true); } public void playAlpha2() { Alpha2Press.SetBool(&quot;Alpha2Pressed&quot;, true); } public void stopAlpha2() { Alpha2Press.SetBool(&quot;Alpha2Released&quot;, true); } public void playAlpha3() { Alpha3Press.SetBool(&quot;Alpha3Pressed&quot;, true); } public void stopAlpha3() { Alpha3Press.SetBool(&quot;Alpha3Released&quot;, true); } public void playAlpha4() { Alpha4Press.SetBool(&quot;Alpha4Pressed&quot;, true); } public void stopAlpha4() { Alpha4Press.SetBool(&quot;Alpha4Released&quot;, true); } public void playAlpha5() { Alpha5Press.SetBool(&quot;Alpha5Pressed&quot;, true); } public void stopAlpha5() { Alpha5Press.SetBool(&quot;Alpha5Released&quot;, true); } public void playAlpha6() { Alpha6Press.SetBool(&quot;Alpha6Pressed&quot;, true); } public void stopAlpha6() { Alpha6Press.SetBool(&quot;Alpha6Released&quot;, true); } public void playAlpha7() { Alpha7Press.SetBool(&quot;Alpha7Pressed&quot;, true); } public void stopAlpha7() { Alpha7Press.SetBool(&quot;Alpha7Released&quot;, true); } public void playAlpha8() { Alpha8Press.SetBool(&quot;Alpha8Pressed&quot;, true); } public void stopAlpha8() { Alpha8Press.SetBool(&quot;Alpha8Released&quot;, true); } public void playAlpha9() { Alpha9Press.SetBool(&quot;Alpha9Pressed&quot;, true); } public void stopAlpha9() { Alpha9Press.SetBool(&quot;Alpha9Released&quot;, true); } public void playAlpha0() { Alpha0Press.SetBool(&quot;Alpha0Pressed&quot;, true); } public void stopAlpha0() { Alpha0Press.SetBool(&quot;Alpha0Released&quot;, true); } public void animations() { // ... if (Input.GetKeyDown(KeyCode.Alpha1)) { Alpha1Press.SetBool(&quot;Alpha1Released&quot;, false); playAlpha1(); } if (Input.GetKeyUp(KeyCode.Alpha1)) { Alpha1Press.SetBool(&quot;Alpha1Pressed&quot;, false); stopAlpha1(); } if (Input.GetKeyDown(KeyCode.Alpha2)) { Alpha2Press.SetBool(&quot;Alpha2Released&quot;, false); playAlpha2(); } if (Input.GetKeyUp(KeyCode.Alpha2)) { Alpha2Press.SetBool(&quot;Alpha2Pressed&quot;, false); stopAlpha2(); } if (Input.GetKeyDown(KeyCode.Alpha3)) { Alpha3Press.SetBool(&quot;Alpha3Released&quot;, false); playAlpha3(); } if (Input.GetKeyUp(KeyCode.Alpha3)) { Alpha3Press.SetBool(&quot;Alpha3Pressed&quot;, false); stopAlpha3(); } if (Input.GetKeyDown(KeyCode.Alpha4)) { Alpha4Press.SetBool(&quot;Alpha4Released&quot;, false); playAlpha4(); } if (Input.GetKeyUp(KeyCode.Alpha4)) { Alpha4Press.SetBool(&quot;Alpha4Pressed&quot;, false); stopAlpha4(); } if (Input.GetKeyDown(KeyCode.Alpha5)) { Alpha5Press.SetBool(&quot;Alpha5Released&quot;, false); playAlpha5(); } if (Input.GetKeyUp(KeyCode.Alpha5)) { Alpha5Press.SetBool(&quot;Alpha5Pressed&quot;, false); stopAlpha5(); } if (Input.GetKeyDown(KeyCode.Alpha6)) { Alpha6Press.SetBool(&quot;Alpha6Released&quot;, false); playAlpha6(); } if (Input.GetKeyUp(KeyCode.Alpha6)) { Alpha6Press.SetBool(&quot;Alpha6Pressed&quot;, false); stopAlpha6(); } if (Input.GetKeyDown(KeyCode.Alpha7)) { Alpha7Press.SetBool(&quot;Alpha7Released&quot;, false); playAlpha7(); } if (Input.GetKeyUp(KeyCode.Alpha7)) { Alpha7Press.SetBool(&quot;Alpha7Pressed&quot;, false); stopAlpha7(); } if (Input.GetKeyDown(KeyCode.Alpha8)) { Alpha8Press.SetBool(&quot;Alpha8Released&quot;, false); playAlpha8(); } if (Input.GetKeyUp(KeyCode.Alpha8)) { Alpha8Press.SetBool(&quot;Alpha8Pressed&quot;, false); stopAlpha8(); } if (Input.GetKeyDown(KeyCode.Alpha9)) { Alpha9Press.SetBool(&quot;Alpha9Released&quot;, false); playAlpha9(); } if (Input.GetKeyUp(KeyCode.Alpha9)) { Alpha9Press.SetBool(&quot;Alpha9Pressed&quot;, false); stopAlpha9(); } if (Input.GetKeyDown(KeyCode.Alpha0)) { Alpha0Press.SetBool(&quot;Alpha0Released&quot;, false); playAlpha0(); } if (Input.GetKeyUp(KeyCode.Alpha0)) { Alpha0Press.SetBool(&quot;Alpha0Pressed&quot;, false); stopAlpha0(); } // ... } </code></pre> <p>What's a more effective way to write this? I'm a firm believer in the DRY principle and this is simply TOO much</p> <p>EDIT: Image of my keyboard<a href="https://i.stack.imgur.com/5hlqW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5hlqW.jpg" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:26:27.233", "Id": "498496", "Score": "2", "body": "To anyone in the close vote queue: note that [the post has been improved](https://codereview.stackexchange.com/posts/252887/revisions)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T21:16:21.717", "Id": "498754", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ how to make this on-topic? Post full code? I want to help OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T21:25:37.797", "Id": "498755", "Score": "0", "body": "@aepot The general consensus is that [\"_you, as someone who didn't write that code, have no right to do that_\"](https://codereview.meta.stackexchange.com/a/974/120114). You've already helped the OP. Unless the OP deletes the question, you should maintain the reputation you've earned from your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T21:33:41.087", "Id": "498756", "Score": "0", "body": "Essential parts of your code are still missing from the question and honestly I doubt this question could/should be salvaged. Perhaps a smaller (actual) project could be used to learn new things that carry over to this project. Perhaps a numeric pad as stand-alone version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T22:13:49.803", "Id": "498758", "Score": "1", "body": "@SᴀᴍOnᴇᴌᴀ I think only moderators and cleaning bot can delete the answered questions (OP can't). Btw, that makes sense regarding to licensing issue. Thanks!" } ]
[ { "body": "<p>That moment when you know Unity better than C#. I'm on other side: I know nothing about Unity (except docs that I've read while writing this review) but know C# well. Let's merge our knowledge.</p>\n<ul>\n<li><p><code>Animator</code> is a single animation engine, in other words <code>GetComponent&lt;Animator&gt;()</code> always returns the same value, thus you need only one variable to store it.</p>\n</li>\n<li><p><code>KeyCode</code> is <code>enum</code> (<a href=\"https://docs.unity3d.com/ScriptReference/KeyCode.html\" rel=\"noreferrer\">link</a>) thus you can iterate it with a loop.</p>\n</li>\n<li><p>string in format <code>&lt;KeyCode&gt;+&lt;Pressed/Released&gt;</code> is good to concatenate these two parts.</p>\n</li>\n</ul>\n<p>The refactored copy of your whole script:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class keyboard : MonoBehaviour\n{\n private Animator animator;\n\n void Start()\n {\n animator = GetComponent&lt;Animator&gt;();\n }\n\n private string BoolToPressed(bool state)\n {\n return state ? &quot;Pressed&quot; : &quot;Released&quot;;\n }\n\n private void PlayKey(KeyCode keyCode, bool state)\n {\n animator.SetBool(keyCode + BoolToPressed(!state), false);\n animator.SetBool(keyCode + BoolToPressed(state), true);\n }\n\n private void animations()\n {\n for (KeyCode k = KeyCode.Backspace; k &lt;= KeyCode.Menu; k++)\n {\n if (Input.GetKeyDown(k))\n PlayKey(k, true);\n else\n if (Input.GetKeyUp(k))\n PlayKey(k, false);\n }\n }\n\n void Update()\n {\n animations();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T11:05:15.607", "Id": "498695", "Score": "0", "body": "Great solution! It worked out really well for the majority of buttons! But some them where left out.. Some miscellaneous such as **Tilde**, **Underscore** and **Å, Ä, Ö**. I don't know which keys they represent on your keyboard but I'll edit the post and attach an image of them. Also some command buttons such as **CAPS, LEFT CTRL, RIGHT ALT GR and RIGHT CTRL** Neither does my **arrows**(up,down,left,right).\n\nAll of these chars have the same issue, the debugger claims their boolean parameters for pressed and released doesnt exist but they do. How can I solve this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T11:14:42.670", "Id": "498696", "Score": "1", "body": "@Kemura refer to `KeyCode` documentation link in my post. You should rename some button animation actions e.g. `ArrowUpPress`/`ArrowUpReleased` to `UpArrowPress`/`UpArrowReleased`, `ÄReleased` to `QuoteReleased`, etc. Must be easy, just make names of animations to match names of buttons in enumeration." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:33:43.553", "Id": "252898", "ParentId": "252887", "Score": "5" } } ]
{ "AcceptedAnswerId": "252898", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T15:56:03.683", "Id": "252887", "Score": "2", "Tags": [ "c#", "game", "animation", "unity3d" ], "Title": "Unity animations code" }
252887
<p>I am trying to create a simple Python project. It's a minigame about guessing a number.</p> <p>It's a game where the computer will pick a random number from 1 to 10.</p> <ul> <li>The player needs to guess it correctly.</li> <li>Every wrong attempt will give you a clue.</li> <li>3 clues and the player will lose.</li> </ul> <p>I've built the code and it works just fine. Here's the code :</p> <pre class="lang-py prettyprint-override"><code>total = 0 guessme = 0 def GuessNum(guess): global total global guessme prime = [2, 3, 5, 7] if total == 0: randnum = random.randint(1,10) guessme = randnum total += 1 if guess == guessme: print(&quot;You are correct!&quot;) guessme = 0 total = 0 else: if total == 1: if guessme % 2 == 0: print(&quot;The number is even&quot;) else: print(&quot;The number is odd&quot;) elif total == 2: if guessme &gt; 5: print(&quot;The number is greater than 5&quot;) else: print(&quot;The number is smaller than 5&quot;) elif total == 3: if guessme in prime: print(&quot;The number is prime&quot;) else: print(&quot;The number is not a prime&quot;) else: guessme = 0 total = 0 print(&quot;You failed to guess the number.&quot;) </code></pre> <p>Are there ways to make this code much more efficient or shorter? I am still new at programming so I would love to learn new things.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T18:09:56.443", "Id": "498486", "Score": "0", "body": "How are you taking input from the user? Also since you are using a function try to use return instead of global variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T20:51:55.163", "Id": "498494", "Score": "1", "body": "Printing `The number is smaller than 5` when the number is 5 is, hm, tricky." } ]
[ { "body": "<p>The code is fairly okay and readable. Since you highlighted <code>performance</code>, my review would not touch on some areas that are lacking.</p>\n<h2>Prefer <code>random.random()</code> to generate pseudorandom numbers</h2>\n<pre><code>import timeit\n\ntest1 = '''\nimport random\nrandom.randint(1,10)\n'''\n\ntest2= '''\nimport random\nint(10 * random.random())\n'''\n\ntt1 = timeit.repeat(stmt=test1, repeat=5, number=1)\nprint('randint time taken: ', min(tt1))\n\ntt2 = timeit.repeat(stmt=test2, repeat=5, number=1)\nprint('random.random() time taken: ', min(tt2))\n\n</code></pre>\n<p>On running the above program, the following results were gotten. NOTE: The results might vary on your computer, but there is still some difference.</p>\n<pre><code>randint time taken = 2.1700000005546375e-06\n\nrandom.random() time taken = 6.056000074750045e-06\n\n</code></pre>\n<p>Though the difference is insignificant, it might mean a lot when the range increases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T19:17:16.840", "Id": "252894", "ParentId": "252888", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T17:04:47.610", "Id": "252888", "Score": "3", "Tags": [ "python", "performance", "beginner" ], "Title": "Guess a Number Game" }
252888
<p>I am writing a part of the program where speed matters the most. In that part I am creating <a href="https://en.wikipedia.org/wiki/Color_space" rel="nofollow noreferrer">color spaces</a> like RGB and other. In-fact I wrote these 2 structs.</p> <pre><code>struct RGB { unsigned char r; unsigned char g; unsigned char b; } struct ARGB { unsigned char a; unsigned char r; unsigned char g; unsigned char b; } </code></pre> <p>And I will have like 10 structs like this for different spaces and I have to do operator overloading for all of them, so I did something like this. I created a <code>struct ColorSpace&lt;Type,Child&gt;</code> here is the code</p> <pre><code>// // Created by Hrant Nurijanyan on 01.12.20. // template&lt;typename T, typename C&gt; struct ColorSpace { const T* cbegin() const { return static_cast&lt;const C*&gt;(this)-&gt;arr.cbegin(); } const T* cend() const { return static_cast&lt;const C*&gt;(this)-&gt;arr.cend(); } const T* begin() const { return cbegin(); } const T* end() const { return cend(); } T* begin() { return static_cast&lt;C*&gt;(this)-&gt;arr.begin(); } T* end() { return static_cast&lt;C*&gt;(this)-&gt;arr.end(); } [[nodiscard]] size_t size() const { return std::distance(begin(),end()); } const T&amp; operator[](unsigned int i) const { return *(begin() + i); } T&amp; operator[](unsigned int i) { return *(begin() + i); } C&amp; operator=(const C&amp; rhs) { std::copy(rhs.begin(), rhs.end(), begin()); return static_cast&lt;C&amp;&gt;(*this); } C&amp; operator=(const T&amp; rhs) { std::fill(begin(), end(), rhs); return static_cast&lt;C&amp;&gt;(*this); } C operator+(const C&amp; rhs) const{ C result; std::transform(rhs.begin(),rhs.end(),begin(),result.begin(),std::plus&lt;&gt;()); return result; } C operator-(const C&amp; rhs) const{ C result; std::transform(begin(),end(),rhs.begin(),result.begin(),std::minus&lt;&gt;()); return result; } C operator*(const C&amp; rhs) const{ C result; std::transform(begin(),end(),rhs.begin(),result.begin(),std::multiplies&lt;&gt;()); return result; } C operator/(const C&amp; rhs) const{ C result; std::transform(begin(),end(),rhs.begin(),result.begin(),std::divides&lt;&gt;()); return result; } C&amp; operator+=(const C&amp; rhs) { std::transform(begin(),end(),rhs.begin(),begin(),std::plus&lt;&gt;()); return static_cast&lt;C&amp;&gt;(*this); } C&amp; operator-=(const C&amp; rhs) { std::transform(begin(),end(),rhs.begin(),begin(),std::minus&lt;&gt;()); return static_cast&lt;C&amp;&gt;(*this); } C&amp; operator*=(const C&amp; rhs) { std::transform(begin(),end(),rhs.begin(),begin(),std::multiplies&lt;&gt;()); return static_cast&lt;C&amp;&gt;(*this); } C&amp; operator/=(const C&amp; rhs) { std::transform(begin(),end(),rhs.begin(),begin(),std::divides&lt;&gt;()); return static_cast&lt;C&amp;&gt;(*this); } bool operator==(const C&amp; rhs) const { return std::equal(begin(),end(),rhs.begin()); } bool operator!=(const C&amp; rhs) const { return !std::equal(begin(),end(),rhs.begin()); } }; </code></pre> <p>And then I updated my structs like this</p> <pre><code>struct RGB : ColorSpace&lt;unsigned char, RGB&gt; { union { std::array&lt;unsigned char,3&gt; arr; struct { unsigned char r; unsigned char g; unsigned char b; }; }; }; </code></pre> <p>As you can see I used CRTP to overload operators for each of the color space without much code. I just need to know is my implementation of <code>struct ColorSpace</code> the most performant? I need like super-speed. Please note <strong>I use Clang</strong> and target platforms are <em>iOS</em> <em>Android</em> <em>Linux</em>. P.S. I know that I am doing type-punning here in child structs, but that does not really matter...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:06:53.140", "Id": "498500", "Score": "0", "body": "Are you sure about that implementation? It uses a lot of wrapping arithmetic, of course in plain C++ there is not much choice, but in ARM NEON (which you are targeting) there is serious support for saturating arithmetic, which is a reasonable choice when manipulating colors (wrapping looks much worse)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:15:43.643", "Id": "498501", "Score": "0", "body": "the thing is that I am not, and I am open to any suggestions. I've had a look into ARM Neon SIMD commands, but after completing their tutorial, I was getting faster results without using neon rather than using..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:15:52.303", "Id": "498502", "Score": "0", "body": "link to the tutorial https://developer.arm.com/solutions/os/android/developer-guides/neon-intrinsics-getting-started-on-android" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:28:42.587", "Id": "498503", "Score": "1", "body": "It is not so straightforward to efficiently implement operations on these small structures, largely because one of them is too few to fill a vector register with, so the vectorization cannot be nicely put into a box and be abstracted away. Naturally I don't know how you wrote that code, but that is a common problem - and of course that can also be reviewed in a separate question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T18:08:40.503", "Id": "252891", "Score": "1", "Tags": [ "c++", "performance", "overloading", "simd" ], "Title": "Boost speed optimizations,C++ operator overloading" }
252891
<p>I'm writing a very simple CRUD application, and I'm wondering if the way I'm using <code>static</code> methods throughout the code makes sense. I'd very much like to simplify the code if possible.</p> <p>Any feedback and criticism is very much welcome!</p> <pre class="lang-php prettyprint-override"><code> &lt;?php class Database { private const DB_DSN = &quot;127.0.0.1&quot;; private const DB_USER = &quot;root&quot;; private const DB_PASSWORD = &quot;root&quot;; private const DB_NAME = &quot;testDB&quot;; private const DB_PORT = 8889; static function connect() { return new PDO( &quot;mysql:host=&quot;.self::DB_DSN.&quot;;port=&quot;.self::DB_PORT. &quot;;dbname=&quot;.self::DB_NAME, self::DB_USER, self::DB_PASSWORD, array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION), ); } static function create() { $pdo = new PDO( &quot;mysql:host=&quot;.self::DB_DSN.&quot;;port=&quot;.self::DB_PORT, self::DB_USER, self::DB_PASSWORD, array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION), ); $pdo-&gt;exec(&quot;CREATE DATABASE IF NOT EXISTS &quot;.self::DB_NAME); return self::connect(); } } class User { private const TABLE_NAME = &quot;users&quot;; public $uid; public $username; public $email; public $hash; public $created; public $verified; public $pdo; private function __construct() { } public static function signUp($pdo, $username, $email, $password) { if (self::exists($pdo, $username)) { return false; } $hash = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo-&gt;prepare(&quot;INSERT INTO `users` SET `username`=?, `email`=?, `hash`=?&quot;); $stmt-&gt;execute([$username, $email, $hash]); return self::fromUId($pdo, $pdo-&gt;lastInsertId()); } public static function login($pdo, $username, $password) { if (!self::exists($pdo, $username)) { return false; } $stmt = $pdo-&gt;prepare(&quot;SELECT * FROM `users` WHERE `username` = ?&quot;); $stmt-&gt;execute([$username]); $user = $stmt-&gt;fetchObject(&quot;User&quot;); $user-&gt;pdo = $pdo; return password_verify($password, $user-&gt;hash) ? $user : false; } public static function exists($pdo, $username) { $stmt = $pdo-&gt;prepare(&quot;SELECT `uid` FROM `users` WHERE `username` = ?&quot;); $stmt-&gt;execute([$username]); return $stmt-&gt;fetch(PDO::FETCH_COLUMN); } public static function fromUId($pdo, $uid) { $stmt = $pdo-&gt;prepare(&quot;SELECT * FROM `users` WHERE `uid` = ?&quot;); $stmt-&gt;execute([$uid]); $user = $stmt-&gt;fetchObject(&quot;User&quot;); $user-&gt;pdo = $pdo; return $user; } public function verify() { $stmt = $this-&gt;pdo-&gt;prepare(&quot;UPDATE `users` SET `verified` = 1 WHERE `uid` = ?&quot;); if ($stmt-&gt;execute([$this-&gt;uid])) { $this-&gt;verified = true; return true; } else { return false; } } } $db = Database::create(); $db-&gt;exec( &quot;CREATE TABLE IF NOT EXISTS `users` ( `uid` int NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(100) NOT NULL UNIQUE, `email` varchar(100) NOT NULL UNIQUE, `verified` boolean DEFAULT 0, `hash` varchar(255) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )&quot; ); $db-&gt;exec( &quot;CREATE TABLE IF NOT EXISTS `images` ( `id` int NOT NULL PRIMARY KEY AUTO_INCREMENT, `uid` int NOT NULL, `image` varchar(255) NOT NULL, `like_count` int NOT NULL DEFAULT 0 )&quot; ); $user = User::signUp($db, 'JohnDoe', 'john.doe@sample.org', '12345'); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T19:36:38.067", "Id": "498490", "Score": "0", "body": "Welcome to Code Review! Is `User::verify()` used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T20:13:45.263", "Id": "498491", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Not yet! It will be called once the user has clicked on a link I would send him." } ]
[ { "body": "<h1>Main question</h1>\n<blockquote>\n<p>I'm wondering if the way I'm using static methods throughout the code makes sense.</p>\n</blockquote>\n<p>It seems to be fine to me, though the need to pass the PDO object around seems excessive. A better approach might be to have a static member property or getter method to access that object when needed. Otherwise the <a href=\"https://www.tutorialspoint.com/design_pattern/singleton_pattern.htm\" rel=\"nofollow noreferrer\">singleton pattern</a> could be used - have a static method to get an instance (e.g. of the Database object) when needed which can store a static property on the class.</p>\n<p>Initially I thought the connections in the <code>Database</code> methods <code>connect</code> and <code>create</code> were redundant but they aren’t. One could possibly abstract the common parts there though.</p>\n<p>As <a href=\"https://stackoverflow.com/a/19986035/1575353\">@YourCommonSense suggested in a stack overflow answer</a> the connection could be reused in the ‘create()‘ method:</p>\n<pre><code>static function create() {\n $pdo = new PDO(\n &quot;mysql:host=&quot;.self::DB_DSN.&quot;;port=&quot;.self::DB_PORT,\n self::DB_USER,\n self::DB_PASSWORD,\n array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION),\n );\n $pdo-&gt;exec(&quot;CREATE DATABASE IF NOT EXISTS &quot;.self::DB_NAME);\n $pdo-&gt;query(&quot;use &quot; . self::DB_NAME);\n return $pdo;\n</code></pre>\n<h1>Other review points</h1>\n<h2>General</h2>\n<p>The code makes good use of constants and setting the scope on them. Have you looked at the <a href=\"https://www.php-fig.org/psr\" rel=\"nofollow noreferrer\">PHP Standards Recommendations</a>? I'd suggest <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a> and <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>.</p>\n<h2>Suggestions</h2>\n<h3>Method visibility</h3>\n<p>Per PSR-12 <a href=\"https://www.php-fig.org/psr/psr-12/#44-methods-and-functions\" rel=\"nofollow noreferrer\">4.4</a></p>\n<blockquote>\n<p>Visibility MUST be declared on all methods.</p>\n</blockquote>\n<p>This is done for the methods in the <code>User</code> class but not the methods in the <code>Database</code> class.</p>\n<h3><code>return</code>ing early</h3>\n<p>Most methods do a good job of calling <code>return</code> when certain conditions are met in order to prevent other calls from happening and this keeps indentation levels at a minimum.</p>\n<p>In the <code>User</code> method <code>verify</code> the last lines are as follows:</p>\n<blockquote>\n<pre><code>if ($stmt-&gt;execute([$this-&gt;uid])) {\n $this-&gt;verified = true;\n return true;\n} else {\n return false;\n}\n</code></pre>\n</blockquote>\n<p>In this case the <code>else</code> is not needed - the <code>return false</code> can be moved out one level:</p>\n<pre><code>if ($stmt-&gt;execute([$this-&gt;uid])) {\n $this-&gt;verified = true;\n return true;\n}\nreturn false;\n</code></pre>\n<p>This could also be written with reversed logic:</p>\n<pre><code>if (!$stmt-&gt;execute([$this-&gt;uid])) {\n return false;\n}\n$this-&gt;verified = true;\nreturn true;\n</code></pre>\n<p>If those lines in the case where <code>execute</code> returned a <code>true</code>thy value were longer then the decreased indentation level would help readability.</p>\n<p>Note the <a href=\"https://www.php.net/manual/en/pdostatement.execute.php#81681\" rel=\"nofollow noreferrer\">highest voted user contributed note on the documentation for <code>pdostatement::execute</code></a></p>\n<blockquote>\n<p>Hopefully this saves time for folks: one should use $count = $stmt-&gt;rowCount() after $stmt-&gt;execute() in order to really determine if any an operation such as ' update ' or ' replace ' did succeed i.e. changed some data.\nJean-Lou Dupont.</p>\n</blockquote>\n<p>Perhaps a better condition is <a href=\"https://www.php.net/manual/en/pdostatement.rowcount.php\" rel=\"nofollow noreferrer\"><code>$stmt-&gt;rowCount()</code></a> after <code>execute()</code> is called.</p>\n<h3>Array syntax</h3>\n<p>There isn't anything wrong with using <code>array()</code> but as of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP 7 has Active support for versions 7.4 and 7.3</a>, and since PHP 5.4 arrays can be declared with <a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a> - which is used in the static methods in the <code>User</code> class but not in the <code>Database</code> class methods.</p>\n<h3>Documentation</h3>\n<p>It is wise to add <a href=\"https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md\" rel=\"nofollow noreferrer\">docblocks</a> above each method - as you saw I had to ask in a comment about the <code>verify</code> method. With ample documentation others (as well as your future self) can get a summary of what a method does, what inputs and outputs it may have, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:53:39.390", "Id": "498499", "Score": "0", "body": "Thank you so much for your time and advice! I'll definitely make use of your suggestions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:33:39.913", "Id": "498526", "Score": "1", "body": "the problem with create is that it would use a connect method that would try to connect to a non-exitent database" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:41:42.363", "Id": "498528", "Score": "1", "body": "and the problem with returning early is that it makes absolutely no sense to return anything from checking the execute() result, simply because for the given code it will **never** return anything as execute will never return false ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:50:14.650", "Id": "252900", "ParentId": "252892", "Score": "1" } }, { "body": "<h3>On the Database class</h3>\n<p>In my experience, a language layer never creates a database. It would require a <code>create database</code> privilege for one thing. Although it's sort of OK for the local environment but would you like your <em>live</em> application to connect the database under the root account? I highly doubt so.</p>\n<p>Hence I find the create() method superfluous. But just for sake of refactoring I would make the connect method to accept a parameter that would tell it to use or not to use the <code>dbname</code> DSN argument so it could connect with or without setting the database.</p>\n<p>What I would rather add to the database class is a handy &quot;prepare and execute in one go&quot; method like:</p>\n<pre><code>public function query($sql, $data = []) {\n $stmt = $this-&gt;pdo-&gt;prepare($sql);\n $stmt-&gt;execute($data);\n return $stmt;\n}\n</code></pre>\n<p>as it will make <em>all</em> methods of the User class to lose a lot of weight. As a general rule, when you see repetitive code, think of creating a function to do all the repetitions in one go.</p>\n<p>Also it would make sense to make <code>$pdo</code> a public property of the database class.</p>\n<h3>Now to the User class</h3>\n<p>First of all, I think that all your doubts with static class is for naught. Yes, in theory it's simple to call <code>User::something()</code> from anywhere without the need to pass around the instance of the user class. But... you need to pass around the instance of PDO anyway! The same problem, different angle.</p>\n<p>So you can make your code much cleaner and doubtless by making all methods dynamic, and putting the pdo (or rather a Database class) instance inside. Then you will have to pass around the instance of the user class instead of the instance of the PDO class.</p>\n<p>Another repetition that can be spotted is two methods that select a user by username. That's nearly identical code! Always try to reuse the code that already exists in your class. Moreover, for some reason login method runs these two identical queries one after another. But why? Is once not enough?</p>\n<p>Another problem is signup function. It's a no-go when it just silently returns false when a user exists. It should be vocal about that. The generic solution is to throw a custom built exception that can be caught and conveyed to the user.</p>\n<p>On the return values: Most of time it's not needed. After all, what would you do with that return value from the verify() method?</p>\n<p>On the names: it is Better to be more explicit with the function names. &quot;verify&quot; is ambiguous - you never can tell what does it verify and why. The same goes for &quot;exists&quot;.</p>\n<h3>The ActiveRecord vs. DataMapper controversy</h3>\n<p>From the way you are asking, I can tell you already feel the ambiguity of your class, which serves for two purposes at once, being both a user and a <em>User persistence layer</em>. That's always so with the ActiveRecord pattern to which your class belongs even if you don't probably realize that. You even tried to mae a distinction between these two roles, where static methods are manipulating the database and dynamic methods and properties are manipulating the class data.</p>\n<p>You need to make just a logical step further and separate these roles explicitly. A better approach to be considered is to split this class in two - User class and a UserMapper class, where the latter one would do all the database work.</p>\n<h3>the Username controversy</h3>\n<p>As long as there is an email to identify the user, there is <strong>absolutely no sense</strong> in using a dedicated username field. In practice, it adds helluvalot of confusion. A user signs up with a user name and n email, then forgets it and signs up again with email as a username and everything becomes so entangled that it makes it really hard for the support staff. Make it only email to identify the user and get rid of that username nonsense completely. In case you plan to use it as a display name <strong>then</strong> make it a display name that is not used in the login process at all.</p>\n<h3>The code</h3>\n<p>So according to the above suggestion I would create three classes. The User itself</p>\n<pre><code>&lt;?php\nclass User {\n public $uid;\n public $username;\n public $email;\n public $hash;\n public $created;\n public $verified;\n\n public function login($password)\n {\n return password_verify($password, $this-&gt;hash);\n }\n\n}\n</code></pre>\n<p>A class with a custom exception</p>\n<pre><code>class UserException Extends InvalidArgumentException {}\n</code></pre>\n<p>And a UserMapper class</p>\n<pre><code>class UserMapper\n{\n private $db;\n private $table = 'users';\n private $class = 'User';\n\n public function __construct(Database $db) {\n $this-&gt;db = $db;\n }\n public function signUp($email, $password)\n {\n if ($this-&gt;getByEmail($email)) {\n throw new UserException(&quot;User already exists&quot;);\n }\n $hash = password_hash($password, PASSWORD_DEFAULT);\n $sql = &quot;INSERT INTO `$this-&gt;table` SET `email`=?, `hash`=?&quot;;\n $this-&gt;db-&gt;query($sql, [$email, $hash]);\n return $this-&gt;getById($this-&gt;db-&gt;pdo-&gt;lastInsertId());\n }\n public function getByEmail($email)\n {\n $sql = &quot;SELECT * FROM `$this-&gt;table` WHERE `email` = ?&quot;;\n return $this-&gt;db-&gt;query($sql, [$email])-&gt;fetchObject($this-&gt;class);\n }\n public function getById($uid)\n {\n $sql = &quot;SELECT * FROM `$this-&gt;table` WHERE `uid` = ?&quot;;\n return $this-&gt;db-&gt;query($sql, [$uid])-&gt;fetchObject($this-&gt;class);\n }\n public function setVerified()\n {\n $sqk = &quot;UPDATE `$this-&gt;table` SET `verified` = 1 WHERE `uid` = ?&quot;;\n $this-&gt;db-&gt;query($sql, [$this-&gt;uid]);\n }\n}\n</code></pre>\n<p>then it can be used like this</p>\n<pre><code>$userMapper = new UserMapper($db);\ntry {\n $user = UserMapper-&gt;signUp('john.doe@sample.org', '12345');\n} catch (UserException $e) {\n $error = $e-&gt;getMessage;\n // show it back to user, etc\n}\n\n$user = $userMapper-&gt;getByEmail($_POST['email']);\nif ($user &amp;&amp; $user-&gt;login($_POST['password'])) {\n // authorize\n} else {\n // invalid login or password\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T07:46:11.420", "Id": "252921", "ParentId": "252892", "Score": "6" } } ]
{ "AcceptedAnswerId": "252900", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T18:33:23.230", "Id": "252892", "Score": "4", "Tags": [ "php", "object-oriented", "mysql", "pdo", "static" ], "Title": "API for SQL queries with PHP PDO" }
252892
<p>While working through a challenge in the beginning of a book I'm reading. I wanted to make my first program more versatile in its responses while trying to fix any exceptions that it was throwing at me. I'm not really sure how well I've made it and I'm looking for any advice on where I can improve it. Here is the program:</p> <pre><code> def agelist(r1= 1, r2= 250): return[item for item in range(r1, r2+1)] z = agelist() def agecheck(x): agelimit = input(&quot;I'm sorry, please enter a valid number for your age.&quot;) q = int(agelimit) if q in z: paymentmethod2(q) elif q not in z: agecheck(q) def paymentmethod(x): print(&quot;Here is your receipt. Thanks and have a great day!&quot;) def paymentmethod2(x): payment2 = input(&quot;Please enter either a 1 for Cash or 2 for Credit.&quot;) y = int(payment2) if y == 1: print(&quot;Thanks! Have a nice day!&quot;) elif y == 2: print(&quot;Thanks! Have a nice day!!&quot;) else: paymentmethod2(y) def savingspace(x): x = int(payment) if x == 1: paymentmethod(x) elif x == 2: paymentmethod(x) else: paymentmethod2(x) while True: try: age1 = int(input(&quot;I see you'd like to buy some cigarettes. How old are you?&quot;)) except ValueError: print(&quot;Sorry, I didn't understand that.&quot;) continue else: break age = int(age1) if age in z: if age &lt; 21: if age &gt;= 13: print(&quot;You're too young to buy these things!&quot;) print(&quot;Go find something else to buy.&quot;) else: print(&quot;This isn't a place for you son.&quot;) print(&quot;Come back with your parents next time.&quot;) elif age &lt; 125: if age &lt;= 40: print(&quot;Sorry for the trouble. Pesky new laws in this county make us have to check.&quot;) payment= input(&quot;How'd you like to pay? Press 1 on the numpad for Cash or 2 for Credit.&quot;) savingspace(payment) else: print(&quot;Those good ol' cowboys amiright hehe, wouldn't be Texas without em!&quot;) payment= input(&quot;How'd you like to pay? Press 1 on the numpad for Cash or 2 for Credit.&quot;) savingspace(payment) else: print(&quot;Out of respect for your ancient being; I will forget what I saw here. Take your cigarettes and go.&quot;) elif age not in z: agecheck(age) input() </code></pre> <p>This is how I tried to fix my errors before I read chocolate's post.</p> <pre><code>z = range(1, 251) #specifies range of integers that this program will use def agecheck(x): #function allows age to be corrected to a number in z list. My while loops are cause a bit of a mess, but it works kinda. while True: try: agelimit = input(&quot;Voided, please enter a valid number for your age again.&quot;) q = int(agelimit) if q in z: paymentmethod2(q) elif q not in z: agecheck(q) except ValueError: print(&quot;Please choose a number below 250.&quot;) continue else: break def paymentmethod(x): #funtion which receives param from savingspace function and prints closing str print(&quot;Here is your receipt. Thanks and have a great day!&quot;) def paymentmethod2(x): #final function is called when an int other than 1 or 2 is passed to savingspace(x) payment2 = input(&quot;Please enter either a 1 for Cash or 2 for Credit.&quot;) #requests input to be either 1 or 2 y = int(payment2) if y == 1: print(&quot;Thanks! Have a nice day!&quot;) elif y == 2: print(&quot;Thanks! Have a nice day!!&quot;) else: paymentmethod2(y) #if input isnt 1 or 2, calls itself with a different variable to fix #for some reason entering a non integer at this point bounces it back to the while loop where payment is defined?? def savingspace(x): #function I used to save space in program and sort the input provided x = int(payment) if x == 1: paymentmethod(x) elif x == 2: paymentmethod(x) #if payment is 1 or 2, calls paymentmethod(x) function else: paymentmethod2(x) #if its any other number, calls paymentmethod2(x) to fix input while True: #Beginning of program: asks &amp; defines age and loops if input is not an integer try: age = int(input(&quot;I see you'd like to buy some cigarettes. How old are you?&quot;)) except ValueError: print(&quot;Sorry, I didn't understand that.&quot;) continue else: break #takes age and sorts it to print str based on user's input if age in z: #checks if user's age is valid based on number list defined by function z if age &lt; 21: if age &gt;= 13: print(&quot;You're too young to buy these things!&quot;) print(&quot;Go find something else to buy.&quot;) else: print(&quot;This isn't a place for you son.&quot;) print(&quot;Come back with your parents next time.&quot;) elif age &lt; 125: if age &lt;= 40: print(&quot;Sorry for the trouble. Pesky new laws in this county make us have to check.&quot;) while True: #loop handles ValueError exception when a non integer is input try: payment= input(&quot;How'd you like to pay? Press 1 on the numpad for Cash or 2 for Credit.&quot;) #sets payment pref as variable savingspace(payment)#passes payment pref variable to function which sorts the payment var except ValueError: print(&quot;Sorry only 1 or 2 is allowed to be input.&quot;) continue else: break else: print(&quot;Those good ol' cowboys amiright hehe, wouldn't be Texas without em!&quot;) while True: #same as above try: payment= input(&quot;How'd you like to pay? Press 1 on the numpad for Cash or 2 for Credit.&quot;) savingspace(payment) except ValueError: print(&quot;Sorry only 1 or 2 is allowed to be input.&quot;) continue else: break else: print(&quot;Out of respect for your ancient being; I will forget what I saw here. Take your cigarettes and go.&quot;) elif age not in z: #if the number provided isn't valid in list; calls function agecheck to ensure a valid input agecheck(age) input() #so the program doesnt just shut off after the last response </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T00:46:29.663", "Id": "498513", "Score": "0", "body": "Provide more context, what does the program do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T01:14:10.113", "Id": "498514", "Score": "0", "body": "Thanks, by that do you mean that I should add comments on which parts do what and how it all flows together?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T14:18:43.683", "Id": "498575", "Score": "1", "body": "Hi parapuffer. You should add the problem your code solves in your post (the *context*), otherwise it's hard for reviewers to see exactly what you want your code to do" } ]
[ { "body": "<p>I'll add the rest of my comments in when I have time, but here's some stuff:</p>\n<hr />\n<p>You can replace...</p>\n<pre><code>def agelist(r1= 1, r2= 250):\n return[item for item in range(r1, r2+1)]\nz = agelist()\n</code></pre>\n<p>...with:</p>\n<pre><code>z = range(1, 251)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T01:15:44.287", "Id": "498515", "Score": "0", "body": "Thanks, I'm not too knowledgeable yet on all of the built in functions so I appreciate the help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T04:56:12.493", "Id": "498521", "Score": "1", "body": "No, it's `z = range(1, 251)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T15:08:00.370", "Id": "498580", "Score": "0", "body": "@Chocolate -- Whoops, you're right." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:40:30.493", "Id": "252904", "ParentId": "252897", "Score": "0" } }, { "body": "<ol>\n<li><p>Instead of using <code>range</code> to define a list of numbers, use the <code>&lt;</code>, <code>&gt;</code> and <code>=</code> operators to save efficiency.</p>\n</li>\n<li><p>In many of your functions, you've given then an argument that the function doesn't use at all, which only wastes efficiency.</p>\n</li>\n<li><p>Instead of the redundant</p>\n</li>\n</ol>\n<pre><code>if y == 1:\n print(&quot;Thanks! Have a nice day!&quot;)\nelif y == 2:\n print(&quot;Thanks! Have a nice day!&quot;)\n</code></pre>\n<p>You can do:</p>\n<pre><code>if y in [1, 2]:\n print(&quot;Thanks! Have a nice day!&quot;)\n</code></pre>\n<p>and same goes for the others.</p>\n<ol start=\"4\">\n<li><p>Instead of defining <code>age1</code>, and then defining another variable, <code>age</code>, to store the exact same value, and never using <code>age1</code> again,\nsimply use the <code>age1</code> <em>(which I renamed to <code>age</code>)</em>.</p>\n</li>\n<li><p>You can define a function that will take care of retrieving a valid age from the user.</p>\n</li>\n</ol>\n<p>Here is the implementation:</p>\n<pre><code>def get_age():\n while True:\n try:\n age = int(input(&quot;How old are you? &quot;))\n except ValueError:\n print(&quot;Sorry, I didn't understand that. &quot;)\n continue\n if 250 &lt; age or age &lt; 1:\n print(&quot;I'm sorry, please enter a valid number for your age.&quot;)\n continue\n return age\n\ndef paymentmethod():\n print(&quot;Here is your receipt. Thanks and have a great day!&quot;)\n\ndef paymentmethod2():\n print(&quot;Thanks! Have a nice day!!&quot;)\n\ndef savingspace(x):\n if x == '1':\n paymentmethod()\n else:\n paymentmethod2()\n\nprint(&quot;I see you'd like to buy some cigarettes.&quot;)\nage = get_age()\nif age &lt; 13:\n print(&quot;This isn't a place for you son.&quot;)\n print(&quot;Come back with your parents next time.&quot;)\nelif age &lt; 21:\n print(&quot;You're too young to buy these things!&quot;)\n print(&quot;Go find something else to buy.&quot;)\nelif age &lt; 125:\n if age &lt; 40:\n print(&quot;Sorry for the trouble. Pesky new laws in this county make us have to check.&quot;)\n else:\n print(&quot;Those good ol' cowboys amiright hehe, wouldn't be Texas without em!&quot;)\n while True:\n payment = input(&quot;How'd you like to pay? Press 1 on the numpad for Cash or 2 for Credit. &quot;)\n if payment in ['1', '2']:\n savingspace(payment)\n break\n print(&quot;Please enter a valid number.&quot;)\nelse:\n print(&quot;Out of respect for your ancient being; I will forget what I saw here. Take your cigarettes and go.&quot;)\ninput()\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T05:21:56.173", "Id": "498522", "Score": "2", "body": "I prefer `if not 1 <= age <= 250:` over `if 250 < age or age < 1:`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T05:28:39.510", "Id": "498523", "Score": "0", "body": "Wow your version makes much more sense than mine and fixes the issues I was having. I didn't realize that I could shorten the while loop you used for payment like that. The fix I tried ended up looping back in on itself whenever a function after it had a wrong input. Thanks a lot" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:15:01.850", "Id": "498525", "Score": "0", "body": "Would `y in (1, 2)` be even more idiomatic than `y in [1, 2]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T07:34:24.520", "Id": "498536", "Score": "0", "body": "`x in range(0, 10)` isn't much slower than `0 <= x < 10`. `x in range(0, 20000000000)` is still a constant-time operation. So long as this isn't happening in a tight loop, speed shouldn't be a concern. (Clarity might be, though, so I agree with that _suggestion_ – just not the rationale.) Edit: The original answer was building a list, from a `range`, so you _are_ right; I'm leaving this comment in the hopes it might be useful to others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T12:56:19.880", "Id": "498564", "Score": "0", "body": "@wizzwizz4 You're wrong. What I provided is 10 times faster than `range`. Of course, human may not be able to feel the difference at all, but using the `time.perf_counter` function show the difference clearly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T18:26:25.127", "Id": "498614", "Score": "0", "body": "@Chocolate A ten-times-longer constant-time microseconds-long operation is irrelevant next to _file I/O_ (e.g. `input`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T19:11:48.973", "Id": "498624", "Score": "0", "body": "@wizzwizz4 Well, take it from [Lord Voldemort](https://puzzling.stackexchange.com/questions/104332/is-equality-possible/104362#comment294934_104362) :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T19:24:38.220", "Id": "498626", "Score": "0", "body": "@Chocolate Oh, believe me, I have to restrain myself from the urge to optimise. But replacing that `input` call with direct `sys.stdin` access would be a _much_ bigger saving." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T04:55:40.777", "Id": "252914", "ParentId": "252897", "Score": "3" } } ]
{ "AcceptedAnswerId": "252914", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:24:08.033", "Id": "252897", "Score": "4", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Beginner cigarette questioning program" }
252897
<p><strong>Program description:</strong></p> <blockquote> <p>A program accepts a list (<code>uTable</code>). The list consists of at least 4 different lists (rows), each with 7 elements (cells). Check whether the value in <code>[7]</code> is zero and assign a new random variable to it on the basis of what <code>[3]</code> is: 1, 2, 3, 4 or 5. A <code>chance</code> should be used to calculate the chance of the assigning operation. A cell should be updated using <code>sheet_store.update_cell(i, k, value)</code>. A check for admin permissions should be included (<code> if adminId in admins:</code>).</p> </blockquote> <p><strong>My solution:</strong></p> <pre><code> if adminId in admins: uTable = sheet_store.get_all_values() for i in range(len(uTable)): row = uTable[i] if (row[7] == '0'): chance = random.uniform(0, 1) if (row[3] == '5'): if chance &lt;= 0.05: print('5 EXECUTED!') sheet_store.update_cell(i+1, 8, 1) elif (row[3] == '4'): random_1 = randint(1, 3) if chance &lt;= 0.1: print('4 EXECUTED!') sheet_store.update_cell(i+1, 8, random_1) elif (row[3] == '3'): random_2 = randint(1, 5) if chance &lt;= 0.4: print('3 EXECUTED!') sheet_store.update_cell(i+1, 8, random_2) elif (row[3] == '2'): random_3 = randint(1, 10) if chance &lt;= 0.6: print('2 EXECUTED!') sheet_store.update_cell(i+1, 8, random_3) elif (row[3] == '1'): random_4 = randint(1, 20) if chance &lt;= 1: print('1 EXECUTED!') sheet_store.update_cell(i+1, 8, random_4) return True else: return False </code></pre> <p><strong>Input: (TABLE IS TRANSFERRED AS LIST) (Row and column with index <code>0</code> are not included)</strong></p> <pre><code>0 1 2 3 4 5 6 7 1 артифак 0 5 незвестен a_1.jpg 07/08/20/15/30 0 2 Съедобный предмет 1 3 бафф a_2.jpg 0 3 описание 2 4 неизвестен a_3.jpg время обновления 1 4 Отличный компан 3 2 компаньон 7 </code></pre> <p><strong>Runtime:</strong></p> <pre><code>1 EXECUTED! 2 EXECUTED! success 0.5s </code></pre> <p>Is there any way to improve the code and make the program run faster? Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:53:35.437", "Id": "498530", "Score": "2", "body": "Please choose a better title for your question. The convention on this site is to describe the program's purpose in the title. Without this convention, every question here would be \"can this program be made faster, cleaner\", which would be confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T08:40:10.083", "Id": "498539", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:28:36.703", "Id": "498678", "Score": "0", "body": "I've changed the title to make it more specific. Next time please follow the indications provided by RolandIllig and BCdotWEB in the comments." } ]
[ { "body": "<p>These are my suggestions regarding performances:</p>\n<h2>Generate random numbers only if needed</h2>\n<p>The new value for the column 7 can be generated after you are sure that needs to be updated. From:</p>\n<pre><code>elif (row[3] == '4'):\n random_1 = randint(1, 3)\n if chance &lt;= 0.1:\n print('4 EXECUTED!')\n sheet_store.update_cell(i+1, 8, random_1)\n</code></pre>\n<p>To:</p>\n<pre><code>elif (row[3] == '4'):\n if chance &lt;= 0.1:\n print('4 EXECUTED!')\n sheet_store.update_cell(i+1, 8, randint(1, 3))\n</code></pre>\n<p>In this way, the new random value is generated only if <code>chance&lt;=0.1</code>. Same for the other cases.</p>\n<h2>API call cost</h2>\n<p>I assume that you are using <a href=\"https://gspread.readthedocs.io/en/latest/index.html\" rel=\"nofollow noreferrer\">gspread</a>. The doc says:</p>\n<blockquote>\n<p>Under the hood, gspread uses Google Sheets API v4. Most of the time\nwhen you call a gspread method to fetch or update a sheet gspread\nproduces one HTTP API call.</p>\n</blockquote>\n<p>Given this statement, your code sends 1 API call with <code>get_all_values()</code> and 1 APIs call for each row to update with <code>update_cell()</code>. In the worst case, there are 5 API calls.</p>\n<p>One suggestion is to generate the list of all new values for the column 7 and send a single update call with <a href=\"https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Worksheet.update\" rel=\"nofollow noreferrer\">update()</a>, so that the total number of API calls will be reduced to 2.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:43:39.580", "Id": "252919", "ParentId": "252899", "Score": "2" } } ]
{ "AcceptedAnswerId": "252919", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:48:05.303", "Id": "252899", "Score": "1", "Tags": [ "python", "python-3.x", "google-sheets" ], "Title": "Updating Google Sheets table efficiently" }
252899
<p>This code is supposed to be the &quot;user&quot; system for my app. This will ask you what you want to do...</p> <p>If you want to add a user, remove a user or check the list of saved users. With this I learned how to open and edit text files. And my goal doing projects is keep on learning and maybe someday I will be able to work or professionally use Python.</p> <p>This code is working at the moment, but I wanted to know if is too basic or too complicated with some more professional eyes on it (please consider my 3 weeks knowledge).</p> <pre><code>snames = list() f_n = (open('names.txt')).read() print(&quot;Welcome to NAME.app&quot;) ################## USER LOGG IN ####################### while True: name = input(&quot;\n - Insert name to logg in \n - ADD to save new user \n - LIST to see saved users \n - REMOVE to delete a user \n - EXIT to finish \n ...&quot;) if name.lower() == &quot;add&quot;: n_input = input(&quot;Name:&quot;) with open('names.txt', 'a') as f: f.write(n_input + '\n') f.close() continue elif name.lower() == &quot;list&quot;: with open('names.txt') as f: print(f.read().splitlines()) elif name in f_n: print(&quot;Logged as&quot;, name.upper()) nxt = input('Welcome, press enter to continue \n') if nxt == '': break elif name.lower() == 'remove': rem = input(&quot;Insert user name to remove \n ...&quot;) with open('names.txt', 'r+') as f: l=f.readlines() l=[z for z in l if rem not in z] with open('names.txt', 'w') as f: f.writelines(l) elif name.lower() == &quot;exit&quot;: exit() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T00:44:33.390", "Id": "498512", "Score": "1", "body": "Why not convert name to it's lower equivalent before testing it. `name = name.lower()`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:26:24.687", "Id": "498570", "Score": "1", "body": "That's true, what would you rather. read the code and have every `.lower()` in each place or `name = name.lower()`. For me was much better to put it on every single place to I would know what's doing (better readability) But maybe I'm wrong and people prefer as you put it!! Let me know." } ]
[ { "body": "<p>First thing I notice is that this...</p>\n<pre><code>nxt = input('Welcome, press enter to continue \\n')\nif nxt == '':\n break\n</code></pre>\n<p>...could just be:</p>\n<pre><code>input('Welcome, press enter to continue')\n</code></pre>\n<p>It doesn't seem like you're using <code>nxt</code> for anything else so there's no need to store a value for it, especially if you just want the user to hit <kbd>enter</kbd>.</p>\n<hr />\n<p>Next, you never do <code>f_n.close()</code> which can cause some issues with the file (e.g., it doesn't save or something weird happens with the garbage collector system, etc.).</p>\n<p>You might want to replace...</p>\n<pre><code>elif name.lower() == &quot;exit&quot;:\n exit()\n</code></pre>\n<p>...with:</p>\n<pre><code>elif name.lower() == &quot;exit&quot;:\n f_n.close()\n exit()\n</code></pre>\n<p>The same should be done with the file in the first <code>elif</code>. Something I also noticed about this is that <code>f_n</code> is the same file as <code>f</code>. You shouldn't need to keep opening it; just use the <code>f_n</code> variable.</p>\n<hr />\n<p>Instead of...</p>\n<pre><code>if name.lower() == &quot;add&quot;:\n n_input = input(&quot;Name:&quot;)\n with open('names.txt', 'a') as f:\n f.write(n_input + '\\n')\n f.close()\n continue\n</code></pre>\n<p>...with:</p>\n<pre><code>if name.lower() == &quot;add&quot;:\n n_input = input(&quot;Name:&quot;)\n with open('names.txt', 'a') as f:\n f.write(n_input + '\\n')\n f.close()\n</code></pre>\n<p>You don't need to say <code>continue</code> because the rest of the <code>while</code> loop is just <code>elif</code>s.</p>\n<hr />\n<p>In terms of overall code style, mostly good, but there are a few things you might want to keep in mind:</p>\n<ol>\n<li>Put spaces around equals signs for readability (e.g., use <code>n = 10</code> instead of <code>n=10</code>).</li>\n<li>It's spelled &quot;log&quot; not &quot;logg.&quot;</li>\n<li>I don't see a usage of <code>snames</code>, so is it really necessary?</li>\n<li>The first comment in your code looks rather odd. Maybe just say <code># USER LOGIN</code> , use a simple block comment, or, if you have to:</li>\n</ol>\n<pre><code>##############\n# USER LOGIN #\n##############\n</code></pre>\n<hr />\n<p>Hope this helps! If I think of something else, I'll edit it in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T12:10:29.623", "Id": "498555", "Score": "0", "body": "That's great thank you very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T12:28:20.620", "Id": "498559", "Score": "0", "body": "That's great thank you very much!\n1- I notice that I can get rid of the \"Nxt\" variable nothing changes. As you said is useless. But if I get rid of \"Break\" the program won't leave the first menu into the second, I need that break to exit the first While loop and jump straight into the second.\n\n2- I don't really understand your second point. f_n is a variable just made to open and read the file. while f is just the way everybody uses \"With open('...') as f\". If I would like to get rid of f_n variable how would I replace it? In for example: \n\nElif name in f_n:\n\nThis really helped TY!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T15:09:12.240", "Id": "498581", "Score": "0", "body": "You don't need to use `with open() as f`. You can just refer to `f_n` without making a new variable `f`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T15:10:50.823", "Id": "498582", "Score": "0", "body": "@AlejandroTrinchero -- Essentially, you're opening the same file multiple times which is not necessary. The lines that you have inside your `with open() as f` can just be outside the `with` and use the variable `f_n` instead of `f`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:08:52.480", "Id": "498600", "Score": "0", "body": "So basically what you mean is that I can use the variable `f_n` instead of `open() as f` so I only have one variable that opens the file? Or anyway I need to `open() as` replacing the variable `f` with `f_n` which already is a variable that opens the file? Sorry I'm just trying to get my head around that. Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T18:03:26.020", "Id": "498613", "Score": "0", "body": "@AlejandroTrinchero -- Instead of `with open('names.txt', 'a') as f: f.write(n_input + '\\n')`, just write `f_n.write(n_input + '\\n'` and don't use `with` at the top with `f_n` because that will close the file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T19:47:57.263", "Id": "498630", "Score": "0", "body": "` f_n.write(n_input + '\\n')\nAttributeError: 'list' object has no attribute 'write' ` \nThat's what I get when I try. Could be because `f_n` is a variable for `.read().splitlines()`? Or because I use `with open()...` at the very begin." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T21:24:50.370", "Id": "498635", "Score": "1", "body": "@AlejandroTrinchero -- Yes, the first reason. Maybe even just get rid of f_n and use the file as you do in the rest of your code." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:35:25.820", "Id": "252903", "ParentId": "252901", "Score": "2" } }, { "body": "<p>Here is the review:</p>\n<hr />\n<ol>\n<li><em>Always</em> use <code>with</code> when opening a file, there are no exceptions. If you use <code>.read()</code>, when the user enters, for example, <code>&quot;Jan&quot;</code>, while the <code>names.txt</code> file doesn't have has <code>&quot;Jan&quot;</code>, but has <code>&quot;Jannet&quot;</code>, the program will still return <code>True</code> for <code>&quot;Jan&quot; in f_n</code>. You can fix the problem using <code>.splitlines()</code> instead:</li>\n</ol>\n<pre><code>f_n = (open('names.txt')).read()\n</code></pre>\n<p>to</p>\n<pre><code>with open('names.txt', 'r') as r:\n f_n = r.read().splitlines()\n</code></pre>\n<hr />\n<ol start=\"2\">\n<li>You can drastically improve the readability of a multi-line string using triple-quotes.</li>\n</ol>\n<pre><code>menu = &quot;\\n - Insert name to logg in \\n - ADD to save new user \\n - LIST to see saved users \\n - REMOVE to delete a user \\n - EXIT to finish \\n ...&quot;\n</code></pre>\n<p>to</p>\n<pre><code>menu = &quot;&quot;&quot;\\\n- Insert name to log in\n- ADD to save new user\n- LIST to see saved users\n- REMOVE to delete a user\n- EXIT to finish\n... &quot;&quot;&quot;\n</code></pre>\n<hr />\n<ol start=\"3\">\n<li>You do not need to assign an input statement to a variable in order for it to pause the program until the user presses ENTER.</li>\n</ol>\n<pre><code>nxt = input('Welcome, press enter to continue \\n')\nif nxt == '':\n break\n</code></pre>\n<p>to</p>\n<pre><code>input('Welcome, press enter to continue \\n')\n</code></pre>\n<hr />\n<ol start=\"4\">\n<li>Since the <code>continue</code> isn't necessary, as none of the <code>elif</code> statements will execute if the program reaches that point anyway. Also, there is no need to use <code>.close()</code>, as the file handler does it for you:</li>\n</ol>\n<pre><code> if name.lower() == &quot;add&quot;:\n n_input = input(&quot;Name:&quot;)\n with open('names.txt', 'a') as f:\n f.write(n_input + '\\n')\n f.close()\n continue\n</code></pre>\n<p>to</p>\n<pre><code> if name.lower() == &quot;add&quot;:\n n_input = input(&quot;Name:&quot;)\n with open('names.txt', 'a') as f:\n f.write(n_input + '\\n')\n</code></pre>\n<hr />\n<ol start=\"5\">\n<li>You can increase the efficiency of your code by directly iteration through a given generator, instead of turning the generator into a list first. To detect whether two strings are equal or not, using the <code>not in</code> operator is prone to cause bugs. For example, <code>'Bob' not in 'Bobble'</code> returns <code>False</code>, but they are different strings. Instead, use the <code>!=</code> operator, as <code>'Bob' != 'Bobble'</code> returns <code>True</code>:</li>\n</ol>\n<pre><code> elif name.lower() == 'remove':\n rem = input(&quot;Insert user name to remove \\n ...&quot;)\n with open('names.txt', 'r+') as f:\n l = f.readlines()\n l = [z for z in l if rem not in z]\n with open('names.txt', 'w') as f:\n f.writelines(l)\n</code></pre>\n<p>to</p>\n<pre><code> elif name.lower() == 'remove':\n rem = input(&quot;Insert user name to remove \\n ...&quot;)\n with open('names.txt', 'r+') as f:\n l = [z for z in f if z != rem]\n with open('names.txt', 'w') as f:\n f.writelines(l)\n</code></pre>\n<hr />\n<p>Altogether:</p>\n<pre><code>snames = list()\nwith open('names.txt', 'r') as r:\n f_n = r.read().splitlines()\n\nprint(&quot;Welcome to NAME.app&quot;)\nmenu = &quot;&quot;&quot;\\\n- Insert name to logg in\n- ADD to save new user\n- LIST to see saved users\n- REMOVE to delete a user\n- EXIT to finish\n... &quot;&quot;&quot;\n\n################## USER LOGG IN #######################\nwhile True:\n name = input(menu)\n if name.lower() == &quot;add&quot;:\n n_input = input(&quot;Name:&quot;)\n with open('names.txt', 'a') as f:\n f.write(n_input + '\\n')\n elif name.lower() == &quot;list&quot;:\n with open('names.txt') as f:\n print(f.read().splitlines())\n elif name in f_n:\n print(&quot;Logged as&quot;, name.upper())\n input('Welcome, press enter to continue \\n')\n elif name.lower() == 'remove':\n rem = input(&quot;Insert user name to remove \\n ... &quot;)\n with open('names.txt', 'r') as f:\n l = [z for z in f if z != rem]\n with open('names.txt', 'w') as f:\n f.writelines(l)\n elif name.lower() == &quot;exit&quot;:\n exit()\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T12:52:23.933", "Id": "498563", "Score": "0", "body": "1- Using always 'with' is something for the functionality or just for easier reading. Splitlines\nsounds great! didn't know that thank you.\n2- I was looking for ages how to write the menu like that in the text editor. I was annoying\neven for me.\n3- Why should I get rid of the break? I suppose is because I didn't show the second part that\nit's a second while loop.\n4- It is now better if I close and open the file to avoid problems with saving and loading new\ndata in the file? as I'm using the same file for all the functions in the main menu." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:00:55.013", "Id": "498565", "Score": "0", "body": "5- I see your point of getting rid of Not in, but that is the only way that my code would work\ntried all different sorts of codes but that's the only functional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:08:36.337", "Id": "498567", "Score": "0", "body": "@AlejandroTrinchero 1- Using `with` is much safer, and it closed the file for us. 2- Great! 3- Oh, there's a second part? Here at Code Review we expect to be given the full working code. 4- Yes. Again, the `with open` statement closes it for you. 5- That's funny... perhaps in one of the strings you have a trailing whitespace? Try printing `f` *(and maybe also `rem`)* to see if there are any strings with a trailing whitespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:21:39.800", "Id": "498569", "Score": "0", "body": "Yes, sorry about that, but I didn't even start the **second part** so I didn't want to say anything:). That's great didn't know that `with open` as well closed the file. I'll keep on trying with the `!=` because it's true is much better, and as well I might learn how to use it properly haha. TY!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T23:49:49.087", "Id": "252908", "ParentId": "252901", "Score": "0" } }, { "body": "<p>Code after the opinions.\nThank you very much for taking the time, I understand most of your points which makes me happy that I'm not too lost. Soon second part of my project another menu.</p>\n<pre><code> with open('names.txt', 'r') as r :\n f_n = r.read().splitlines()\nprint(&quot;Welcome to NAME.app&quot;)\n##############\n# USER LOGIN #\n##############\nwhile True:\n name = input(&quot;&quot;&quot;\n \\n - Insert name to logg in\n \\n - ADD to save new user\n \\n - LIST to see saved users\n \\n - REMOVE to delete a user\n \\n - EXIT to finish\n \\n - ...&quot;&quot;&quot;)\n\n name = name.lower()\n\n if name == &quot;add&quot;:\n n_input = input(&quot;Name:&quot;)\n with open('names.txt', 'a') as f:\n f.write(n_input + '\\n')\n f.close()\n\n elif name == &quot;list&quot;:\n with open('names.txt') as f:\n print(f.read().splitlines())\n f.close()\n\n elif name in f_n:\n print(&quot;Logged as&quot;, name.upper())\n input('Welcome, press enter to continue \\n')\n break\n\n elif name == 'remove':\n rem = input(&quot;Insert user name to remove \\n ...&quot;)\n with open('names.txt', 'r+') as f:\n l = f.readlines()\n l = [z for z in l if rem not in z]\n with open('names.txt', 'w') as f:\n f.writelines(l)\n\n elif name == &quot;exit&quot;:\n r.close()\n exit()\n</code></pre>\n<ul>\n<li>Removed NXT variable kept break to jump into next loop, second part of project.</li>\n<li>Added .close() to files to avoid problems saving, etc.</li>\n<li>Removed useless pieces of code that were left during building.</li>\n<li>Added .splitlines() to improve the accuracy of the users log in. And changed open for with open.</li>\n<li>Checked spaces between code like x=x and fixed readability.</li>\n<li>Changed <code>name.lower()</code> on every <code>elif</code> for <code>name = name.lower()</code></li>\n</ul>\n<p>Again thank you very much for the patience and help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:35:58.713", "Id": "498573", "Score": "3", "body": "That's great! Don't forget to select one answer to click on the checkmark to close this case :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:17:18.433", "Id": "252931", "ParentId": "252901", "Score": "1" } } ]
{ "AcceptedAnswerId": "252908", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:52:23.880", "Id": "252901", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "file-system" ], "Title": "Python - First project user system" }
252901
<p>I've been learning C# for 2 month and in the process of writing a quiz via file i/o. I want to know if there is a better way to getting the questions and answers rather than using switch statement so that it does not look too cluttered. I've tried using fields and properties but I don't know how to implement them into getting the lines in the txt. I've been using switch statement to get the array of the lines and the program work.</p> <p>Here is a simple of my program:</p> <pre><code> public class QuestionUI { String[] fileName = File.ReadAllLines(@&quot;TraviaQuestion.txt&quot;); private String [] NO_OF_ANSWERS = new string[5]; private String[] NO_OF_QUESTIONS = new String[5]; public void Questions(int num) { NO_OF_QUESTIONS[0] = fileName[0]; switch(num) { case 1: { Console.WriteLine(&quot;\n&quot; + NO_OF_QUESTIONS[0]); GetAnswer(1); break; } } } public void GetAnswer(int num) { switch (num) { case 1: { Console.WriteLine(NO_OF_ANSWERS[0] = fileName[1]); Console.WriteLine(NO_OF_ANSWERS[0] = fileName[2]); break; } } } public void GetCorrectAnswer(String input, int num) { switch (num) { case 1: { if (input.ToUpper() != &quot;B&quot;) { Console.WriteLine(&quot;Incorrect!&quot;); GetExplanation(1); } else { Console.WriteLine(&quot;Correct!&quot;); } break; } } } public void GetExplanation(int num) { switch(num) { case 1: { Console.WriteLine(fileName[6]); break; } } } public void ReadQuestionFile() { String input; Questions(1); input = Console.ReadLine(); GetCorrectAnswer(input,1); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:14:02.160", "Id": "498638", "Score": "0", "body": "Yes there is a better way. This is not C. C# is object oriented. But it's not possible to help you without understanding how your program is supposed to work. How is the flow and what is `num`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T21:57:13.623", "Id": "252902", "Score": "1", "Tags": [ "c#" ], "Title": "Decluttering quiz game" }
252902
<p>There is a remote resource containing datasets arranged by time, data is static and doesnt change. Whenever we are going to fetch anything from there we will be saving it in our cache. User might request a data for a particular time period, lets say from 1st Jan 2019 to 1st Jan 2020. If data is not cached, then we request it from remote resource, in case only part of data is cached, then we need to request what is missing. There is a function which calculates missing intervals, and I think that it looks too verbose. Would be nice to get some suggestions for a better solution. Thanks.</p> <pre><code> @SneakyThrows public static ArrayList&lt;TimeSpan&gt; difference(TimeSpan requested, TimeSpan cached){ ArrayList&lt;TimeSpan&gt; missingIntervals = new ArrayList&lt;&gt;(); //requested period is within cached if (requested.getFrom().compareTo(cached.getFrom()) &gt;= 0 &amp;&amp; requested.getTo().compareTo(cached.getTo()) &lt;= 0){ missingIntervals = null; //requested period is before or after cached } else if (requested.getTo().compareTo(cached.getFrom()) &lt;= 0 || requested.getFrom().compareTo(cached.getTo()) &gt;= 0){ missingIntervals.add(requested); // requested start and end dates are outside of cached range } else if (requested.getFrom().compareTo(cached.getFrom()) &lt;= 0 &amp;&amp; requested.getTo().compareTo(cached.getTo()) &gt;= 0){ missingIntervals.add(new TimeSpan(requested.getFrom(),cached.getFrom())); missingIntervals.add(new TimeSpan(cached.getTo(),requested.getTo())); // requested start date is before cached period } else if (requested.getFrom().compareTo(cached.getFrom()) &lt; 0 &amp;&amp; requested.getTo().compareTo(cached.getTo()) &lt;= 0 &amp;&amp; requested.getTo().compareTo(cached.getFrom()) &gt; 0){ missingIntervals.add(new TimeSpan(requested.getFrom(),cached.getFrom())); // requested end date is after cached period } else if (requested.getTo().compareTo(cached.getTo()) &gt;= 0 &amp;&amp; requested.getFrom().compareTo(cached.getFrom()) &gt;= 0 &amp;&amp; requested.getFrom().compareTo(cached.getTo()) &lt; 0){ missingIntervals.add(new TimeSpan(cached.getTo(),requested.getTo())); } return missingIntervals; } </code></pre> <p>Here is a TimeSpan class:</p> <pre><code>public class TimeSpan { public TimeSpan(Date from, Date to) throws Exception{ if(from.compareTo(to) &gt;= 0){ throw new Exception(&quot;Start date cannot be greater then end date&quot;); } this.from = from; this.to = to; } private final Date from; private final Date to; </code></pre> <p>}</p>
[]
[ { "body": "<p>I would suggest moving this method into the <code>TimeSpan</code> class. Let a <code>TimeSpan</code> tell you about its overlaps. Don't interrogate it for internal details and then figure it out for yourself. Private helper methods will make the <code>compareTo</code> calls more readable.</p>\n<p>Assorted other thoughts:</p>\n<p>A checked exception is probably not right here. I'd suggest preferring <code>IllegalArgumentException</code>, since that's what the problem is. Using a more specific exception than <code>Exception</code> is highly recommended.</p>\n<p>Returning early would be preferable to assigning a return value and only returning once. That is a holdover from <code>C</code>, which only allowed a single return.</p>\n<p>It's generally preferable to use the <code>List</code> variable type when you don't care about the type of list you're using.</p>\n<p>Traditionally, variables are defined at the top of a class, not the bottom.</p>\n<p>Traditionally, whitespace is added between <code>if</code> and <code>(</code>, and between <code>)</code> and <code>{</code>.</p>\n<p>The <code>Date</code> class already has an <code>after()</code> method, which would make the <code>TimeSpan</code> constructor cleaner.</p>\n<p>Your error message in the constructor is incorrect. The from date also cannot be equal to the to date.</p>\n<p>You should strongly consider using <code>java.time</code> instead of the <code>java.util</code> time classes. They are effectively deprecated.</p>\n<p>Returning <code>null</code> is probably strictly worse than returning an empty collection, though it's difficult to say that authoritatively without seeing the client code.</p>\n<p>If you made all these changes, your code might look something like:</p>\n<pre><code>public final class TimeSpan {\n\n private final Date from;\n private final Date to;\n\n public TimeSpan(Date from, Date to) throws IllegalArgumentException {\n if (!from.before(to)) {\n throw new IllegalArgumentException(&quot;Start date cannot be greater than or equal to end date&quot;);\n }\n this.from = from;\n this.to = to;\n }\n\n /**\n * Subtracts the timeSpan argument from this TimeSpan. This will result in a list of between\n * zero and two TimeSpans, ordered by start time.\n * @param timeSpan the span to subtract from this timespan. May not be null.\n * @return a list of TimeSpans covering the time that is in this timespan and not the argument timespan. Will\n * never return null.\n */\n public List&lt;TimeSpan&gt; minus(TimeSpan timeSpan) {\n // This TimeSpan is completely inside the argument.\n if (timeSpan.contains(this.from) &amp;&amp; timeSpan.contains(this.to)) {\n return Collections.emptyList();\n }\n\n // This TimeSpan is either fully before or fully after argument\n if (this.endsBeforeOrAt(timeSpan) || this.startsAfterOrAt(timeSpan)) {\n return listOf(this); // only OK because this class is immutable\n }\n\n // This TimeSpan starts before and ends inside the argument\n if (timeSpan.contains(this.to)) {\n return listOf(new TimeSpan(this.from, timeSpan.from));\n }\n\n // This TimeSpan starts inside and ends after argument\n if (timeSpan.contains(this.from)) {\n return listOf(new TimeSpan(timeSpan.to, this.to));\n }\n\n // This TimeSpan starts before and ends after argument\n List&lt;TimeSpan&gt; results = new ArrayList&lt;&gt;();\n results.add(new TimeSpan(this.from, timeSpan.from));\n results.add(new TimeSpan(timeSpan.to, this.to));\n return results;\n }\n\n private boolean endsBeforeOrAt(TimeSpan timeSpan) {\n return this.to.compareTo(timeSpan.from) &lt;= 0;\n }\n\n private boolean startsAfterOrAt(TimeSpan timeSpan) {\n return this.from.compareTo(timeSpan.to) &gt;= 0;\n }\n\n private boolean contains(Date date) {\n return (this.from.compareTo(date) &gt;= 0) &amp;&amp; (this.to.compareTo(date) &lt;= 0);\n }\n\n // If you're using Guava, replace this with Lists.of()\n private static List&lt;TimeSpan&gt; listOf(TimeSpan timeSpan) {\n List&lt;TimeSpan&gt; results = new ArrayList&lt;&gt;();\n results.add(timeSpan);\n return results;\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T01:42:36.287", "Id": "252911", "ParentId": "252905", "Score": "2" } } ]
{ "AcceptedAnswerId": "252911", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T22:42:10.640", "Id": "252905", "Score": "3", "Tags": [ "java", "datetime", "interval" ], "Title": "Calculating difference between cached period and requested" }
252905
<p>I'm using C++11 with <a href="https://github.com/SmingHub/Sming" rel="nofollow noreferrer">https://github.com/SmingHub/Sming</a>. It has no support of <code>std</code> lib or exceptions. I wanted to use <code>Either</code> monad to return an error or result from my functions. I implemented it using class hierarchy. I'm not a native C++ dev so I would be glad for the code review.</p> <pre><code>#pragma once template &lt;class L, class R&gt; class Either { virtual bool isLeft(); virtual bool isRight(); virtual bool matchLeft(L&amp; x); virtual bool matchRight(R&amp; x); }; template &lt;class L, class R&gt; class Left : public Either&lt;L, R&gt; { public: L left; Left(L left): left(left) {} constexpr bool isLeft() { return true; } constexpr bool isRight() { return false; } bool matchLeft(L&amp; x) { x = left; return true; } bool matchRight(R&amp; x) { return false; } }; template &lt;class L, class R&gt; class Right : public Either&lt;L, R&gt; { public: R right; Right(R right): right(right) {} constexpr bool isLeft() { return false; } constexpr bool isRight() { return true; } bool matchLeft(L&amp; x) { return false; } bool matchRight(R&amp; x) { x = right; return true; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T03:39:42.957", "Id": "498517", "Score": "2", "body": "Welcome to Code Review! Could you include an example showing the intended use case? It often helps reviewers if they know how a particular piece of code is intended to be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T10:23:55.830", "Id": "498552", "Score": "0", "body": "My main idea here was to use it for error handling. So functions could return an result or error (not exception). For example function to sign in user could return a `UserSession` object or error (user not found, invalid password, user disabled etc.)" } ]
[ { "body": "<p>Your <code>Either</code>-monad suffers from a fatal flaw:</p>\n<p>It is impossible to return an <code>Either</code> which might be either possibility.</p>\n<p>You can only return a <code>Left</code> or a <code>Right</code>, an <code>Either</code> must per force be a pointer or reference to one of those.</p>\n<p>Without help from the compiler in automatically deducing a return-type of <code>Either&lt;T, U&gt;</code> if it finds returns of a combination of <code>Either&lt;T, U&gt;</code>, <code>Left&lt;T&gt;</code> and <code>Right&lt;U&gt;</code> sufficient to deduce <code>T</code> and <code>U</code>, or at least adding pattern-matching, <code>Left</code> and <code>Right</code> are pretty much useless.</p>\n<p>In the end, that just leaves <code>Either</code>, which is now only a poor-mans substitute for full-fledged <a href=\"//en.cppreference.com/w/cpp/utility/variant\" rel=\"nofollow noreferrer\"><code>std::variant</code></a> of two.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:29:10.133", "Id": "498643", "Score": "0", "body": "My intention was to return only one of those two. And I cannot use std::variant in my case (no `std` lib)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:36:25.970", "Id": "498644", "Score": "0", "body": "The problem is that an `Either` is not a complete type. Thus, you can return a `Left`, or a `Right`, but never an `Either`. Which robs the class of about all utility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:45:11.590", "Id": "498647", "Score": "0", "body": "Well, you can construct the `Left`/`Right` in some other memory (dynamic allocation? some reserved static memory? whatever) and then return a pointer to that. But that's a lot of indirection for an either. Implementing a simple tagged-union like `std::variant` (we're in C++11 anyway, so that doesn't exist yet) isn't very hard." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T20:41:25.543", "Id": "252949", "ParentId": "252909", "Score": "1" } }, { "body": "<p>This class is conceptually flawed because the only way to extract the values from it is by (copy) assignment. This makes it less useful than we'd like:</p>\n<pre><code>Either&lt;err_type, res_type&gt; *result = some_function(); // notice the pointer; more on this later\nif(result-&gt;isLeft()) {\n some_type error; // what if there's no obvious and cheap way to create an &quot;empty&quot; object of this type?\n // why do I have to state the type again?\n result-&gt;matchLeft(error); // what if there is no copy assignment operator= on some_type (e.g. it holds some exclusive resource)?\n // what if the copy assignment is expensive (e.g. it's a container)?\n // why is this not an expression?\n std::cerr &lt;&lt; error &lt;&lt; &quot;\\n&quot;; // or however you're doing output\n} else {\n other_type value;\n result-&gt;matchRight(value);\n std::cout &lt;&lt; value &lt;&lt; &quot;\\n&quot;;\n}\ndelete result; // argh!\n</code></pre>\n<p>We can take a page out of the standard library's book (<code>std::get_if</code>) and make <code>matchLeft</code> and <code>matchRight</code> into <code>getIfLeft</code> and <code>getIfRight</code>, which return nullable pointers.</p>\n<pre><code>template&lt;class L, class R&gt; \nstruct Either // note that all of these members are private; you either need to add public: or replace class with struct\n{\n // without const, these can't be called on const Eithers\n virtual bool isLeft() const = 0; // can actually be implemented in terms of getIfLeft, so doesn't really need to be virtual at all\n virtual bool isRight() const = 0; // otherwise, I think you need to make these all *pure* virtual, or else you'll get linker errors\n\n virtual L *getIfLeft() = 0;\n virtual R *getIfRight() = 0;\n // we'd also want const Either -&gt; pointer to const versions, because these functions currently can't be called on const Eithers\n\n virtual ~Either() = default; // very, VERY severe omission! deleting an Either through a pointer without this is UB!\n};\n</code></pre>\n<p><code>*result-&gt;getIfLeft()</code> is now an lvlaue of type <code>L</code>. The caller no longer has to construct a dummy object or restate the type, and the <code>L</code> no longer needs to be copy-assigned, and we need many fewer lines. Note that we've basically just reinvented <code>dynamic_cast</code>.</p>\n<pre><code>Either&lt;some_type, other_type&gt; *result = some_function();\n\n// now shorter, more to the point\nif(result-&gt;isLeft()) std::cerr &lt;&lt; *result-&gt;getIfLeft() &lt;&lt; &quot;\\n&quot;;\nelse std::cout &lt;&lt; *result-&gt;getIfRight() &lt;&lt; &quot;\\n&quot;;\n// also acceptable\nif(auto error = result-&gt;getIfLeft()) std::cerr &lt;&lt; *error &lt;&lt; &quot;\\n&quot;;\nelse if(auto value = result-&gt;getIfRight()) std::cout &lt;&lt; *value &lt;&lt; &quot;\\n&quot;;\n\ndelete result;\n</code></pre>\n<p>The other issue is using virtual inheritance for this in the first place. That means the only way to use this class is through pointers, probably with dynamic allocation, which is easy to get wrong (I forgot to write the <code>delete</code>s in this answer at first; you forgot to make the destructor <code>virtual</code>; <code>some_function</code> above <em>probably</em> has to to contain a <code>new</code>, so we <em>probably</em> should <code>delete</code> it, but maybe <code>some_function</code> returns a pointer to some preallocated memory that it reuses, or maybe it does something else, so it's hard to automatically know how to handle the memory...). A more direct way to do this is the classic (old as C) &quot;tagged union&quot;.</p>\n<p><code>std::variant</code> is a general purpose tagged union, but it doesn't exist in C++11 and you say you don't even have the STL available. Implementing a pared down version involves a <code>union</code>, which is interesting to handle properly, but the point is that the end result acts like &quot;just a value&quot; and doesn't require the user code to know how to manage memory.</p>\n<pre><code>// you say you don't have the std namespace available\n// if you really don't have std::move or std::forward, just write them yourself\nenum class either_side { left, right };\nstruct left_tag_t {}; struct right_tag_t {};\ntemplate&lt;class L, class R&gt;\nclass either {\n // self explanatory\n either_side tag;\n union {\n L left;\n R right;\n };\n\n public:\n // &quot;in-place&quot; constructors: according to the tag, initialize with whatever arguments\n template&lt;class... U&gt;\n either(left_tag_t, U&amp;&amp;... args) : tag(either_side::left), left(std::forward&lt;U&gt;(args)...) { }\n template&lt;class... U&gt;\n either(right_tag_t, U&amp;&amp;... args) : tag(either_side::right), right(std::forward&lt;U&gt;(args)...) { }\n // may want std::initializer_list &quot;forwarding&quot; constructors, too\n\n // initialize by type\n either(L x) : either(left_tag_t(), std::move(x)) { }\n either(R x) : either(right_tag_t(), std::move(x)) { }\n\n // sometimes we don't know which variant member to initialize immediately\n // so we leave the union uninitialized and then placement-new into it\n either(either const &amp;other) : tag(other.tag) {\n if(tag == either_side::left) new(&amp;left) L(other.left);\n else new(&amp;right) R(other.right);\n }\n either(either &amp;&amp;other) : tag(other.tag) {\n if(tag == either_side::left) new(&amp;left) L(std::move(other.left));\n else new(&amp;right) R(std::move(other.right));\n }\n // and when we need to destroy the object, we must explicitly call the destructor\n either &amp;operator=(either const &amp;other) {\n if(tag == either_side::left &amp;&amp; other.tag == either_side::left) left = other.left;\n else if(tag == either_side::right &amp;&amp; other.tag == either_side::right) right = other.right;\n else if(tag == either_side::left &amp;&amp; other.tag == either_side::right) {\n left.~L();\n // NOT exception safe! if this constructor were to throw and ~either to be called during the unwinding\n // then ~either would see the tag set but neither object constructed\n // and would try to destroy it a second time\n // ...but you say we don't have exceptions, so I suppose we can be sloppy (the standard library's solution is to add a third tag meaning &quot;empty because of exception&quot; to std::variant)\n new(&amp;right) R(other.right);\n } else {\n right.~R();\n new(&amp;left) L(other.left);\n }\n tag = other.tag;\n }\n either &amp;operator=(either &amp;&amp;other) {\n if(tag == either_side::left &amp;&amp; other.tag == either_side::left) left = std::move(other.left);\n else if(tag == either_side::right &amp;&amp; other.tag == either_side::right) right = std::move(other.right);\n else if(tag == either_side::left &amp;&amp; other.tag == either_side::right) {\n left.~L();\n new(&amp;right) R(std::move(other.right));\n } else {\n right.~R();\n new(&amp;left) L(std::move(other.left));\n }\n tag = other.tag;\n }\n ~either() {\n if(tag == either_side::left) left.~L();\n else right.~R();\n }\n\n L *get_if_left() { return tag == either_side::left ? &amp;left : nullptr; }\n L const *get_if_left() const { return tag == either_side::left ? &amp;left : nullptr; }\n R *get_if_right() { return tag == either_side::right ? &amp;right : nullptr; }\n R const *get_if_right() const { return tag == either_side::right ? &amp;right : nullptr; }\n bool is_left() const { return bool(get_if_left()); }\n bool is_right() const { return bool(get_if_right()); }\n};\n// hopefully, all that's correct (emphasis on the hopefully)\n</code></pre>\n<p>Ta-da!</p>\n<pre><code>// all uses of std:: definitions are for demonstrative purposes\nstruct user_session {\n std::string user_name;\n long user_id;\n long session_id;\n std::fstream data_file; // or whatever you're using\n user_session(std::string user_name, long user_id, long session_id, std::fstream data_file)\n : user_name(std::move(user_name)), user_id(user_id), session_id(session_id), data_file(std::move(data_file))\n { }\n};\n\neither&lt;std::string, user_session&gt; acquire_session(long user_id) {\n std::stringstream builder;\n builder &lt;&lt; &quot;User&quot; &lt;&lt; user_id;\n std::string name = builder.str();\n if(std::rand() &amp; 1) return {left_tag_t(), &quot;Computer says no&quot;};\n try {\n std::fstream data(name);\n return {right_tag_t(), std::move(name), user_id, std::rand(), std::move(data)};\n } catch(...) {\n return {left_tag_t(), &quot;IO error&quot;};\n }\n // no wacky allocations for either\n}\nint main() {\n auto result = acquire_session(std::rand());\n if(auto *error = result.get_if_left()) {\n std::cerr &lt;&lt; *error &lt;&lt; &quot;\\n&quot;;\n return EXIT_FAILURE;\n }\n std::cout &lt;&lt; result.get_if_right()-&gt;user_name &lt;&lt; &quot;\\n&quot;;\n // either is correctly destroyed automatically\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:42:47.813", "Id": "252957", "ParentId": "252909", "Score": "1" } } ]
{ "AcceptedAnswerId": "252957", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-01T23:52:57.370", "Id": "252909", "Score": "1", "Tags": [ "c++", "c++11", "monads" ], "Title": "Either monad in C++11" }
252909
<p>The searching algorithm that I created is dependent upon the sorting algorithm (which many of you have seen in my previous question). I believe that the sorting algorithm can't be better (for beginner-level programmers like me) but I would like to know what you think about my descriptions for the <strong>searching algorithm</strong>.</p> <p>I would appreciate your insight on the commented sections of my code (again, for the searching algorithm). And if there are any other changes I can make, please don't hesitate to let me know.</p> <pre><code>def sorting_algorithm(list): for index in range(1, len(list)): current = list[index] while index &gt; 0 and list[index - 1] &gt; current: list[index] = list[index - 1] index = index - 1 list[index] = current return list print(&quot;the sorted list is&quot;, (sorting_algorithm([45, 14, 1, 7, 98, 23, 102, 57]))) #SEARCHING ALGORITHM CODE: def searching_algorithm(list, num): fir = 0 #the first number of the list. las = len(list)-1 #the last number of the list. i = -1 #the index is at the last number of the list. while (fir &lt;= las) and (i == -1): #the first number is less than or equals to the last number and the #index is at -1 (so the last number). mid = (fir + las) // 2 #the middle number is equal to the first num divided by the last number #but without the remainder part. if list[mid] == num: #if the middle number of the list equals the number i = mid #then the index is moved to the middle number of the list. else: #if that isn't true then we move on to the following condition. if num&lt;list[mid]: #if the number is less than the middle number of the list las = mid -1 #then the index moves one to the right. else: #if that isn't true either, then move on to the following condition. fir = mid +1 #then the program will conclude that the number is the greater than #the middle number. return i print(&quot;your number is at index&quot;,searching_algorithm([1, 7, 14, 23, 45, 57, 98, 102], 23)) </code></pre>
[]
[ { "body": "<ul>\n<li><p>The code is overcommented. Most of the comments do not add any value. They explain <em>what</em> the code is doing, which is obvious; the good comment shall explain <em>why</em> and <em>how</em> the code is doing what it is doing. Some of them are outright wrong, e.g.</p>\n<pre><code> #the middle number is equal to the first num divided by the last number\n</code></pre>\n<p>Say what? Nothing is divided by the last number!</p>\n<p>In any case, try to avoid comments. A presence of an explanatory comment means the failure to express yourself in the code.</p>\n</li>\n<li><p>As mentioned in the comment (no pun intended), the code implements a binary search.</p>\n<pre><code> (fir + las) // 2\n</code></pre>\n<p>is all right in Python with its arbitrarily long integers; in most other languages, which deal with the native integers, computing <code>fir + (las - fir) / 2</code> is indeed preferable.</p>\n</li>\n<li><p>Testing for <code>i == -1</code> looks smelly. Most of the times <code>i</code> remains <code>-1</code>, and it only gets the meaningful value when the target number is found. When the condition</p>\n<pre><code> list[mid] == num\n</code></pre>\n<p>is satisfied, it is a time to <code>break</code> the loop, or even <code>return i</code> right away.</p>\n</li>\n<li><p><strong>Detour</strong>.</p>\n<p>Returning <code>-1</code> when the target number is not there is not right. All the work your function have done is suddenly discarded. Don't be discouraged: you are in the good company. <code>bsearch</code> from the standard C library makes the same blunder.</p>\n<p>It is very helpful to return an insertion point instead: where the target number would have been. See how <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\"><code>bisect.bisect_left()</code></a> does it right (ditto for C++ <code>std::lower_bound</code>).</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T05:58:03.337", "Id": "498524", "Score": "0", "body": "Return -1 is quite bad, -1 is an index which points to the last item in a `list`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T15:37:15.340", "Id": "498586", "Score": "0", "body": "@vnp Thank you for your honest analysis. I really appreciate it and I will make sure to use this for future reference :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T15:55:18.940", "Id": "498590", "Score": "0", "body": "@esker-luminous don't forget to accept an answer to close a question. Looking forward to more projects from you. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:04:21.607", "Id": "498592", "Score": "0", "body": "I did NOT know I had to accept an answer to resolve the question. Thank you again @theProgrammer!! But I guess I'll have to wait a couple of days to choose which explanation is the best for my problem (or like which one helped me the best). But if there is only this one answer, then I'll accept it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T05:26:55.453", "Id": "252916", "ParentId": "252910", "Score": "3" } }, { "body": "<p>First off great attempt for a new programmer. I see that you have implemented the binary search for your searching algorithm and the insertion sort for your sorting algorithm.</p>\n<p>For your commenting issue; you don't want to write word for word what each line of code is doing. Like <code>fir = 0 # the first number of the list</code> you don't need to write this as this is common sense, the same goes for <code>i = -1 # the index is at the last number of the list</code>. Another example of what you should NOT do is this: <code>if num &lt; list[mid]: # if the number is less than the middle number of the list</code>- this may provide clarity to you, but for some people it's not necessary to see. So you should keep these kind of things for your own reference (wherever you're writing this code, be it IDLE, PyCharm etc.), not publish on platforms like these (where believe me, you will be critiqued).</p>\n<p>You should maybe just add a comment at the top of a chuck of code explaining what that code is going to do. Remember to be concise rather than writing paragraphs about what each line of code is doing. Your program is quite small so it's a little hard to find various examples, but that's ok we can just use what we have.</p>\n<p>For example:</p>\n<pre><code>#write here what this 'chunk' or 'block' of code is for in ONE sentence here\nwhile (fir &lt;= las) and (i == -1): \n mid = (fir + las) // \n if list[mid] == num:\n i = mid\n else:\n if num&lt;list[mid]:\n las = mid -1\n else:\n fir = mid +1\n</code></pre>\n<p>And yes sometimes it's better to over-explain than under-explain but SOMETIMES you just need to put the most basic and raw facts out there (try not to give TOO much detail!).</p>\n<p>Again, I commend you for great try (for a beginner) and hope this answer was able to give you some perspective as to how you should use comments!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:53:03.713", "Id": "498610", "Score": "0", "body": "Thank you for your insight! This was definitely helpful for how I should be commenting. Appreciate it :))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:53:52.060", "Id": "498611", "Score": "0", "body": "@esker-luminous Glad I could help!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:44:01.287", "Id": "252943", "ParentId": "252910", "Score": "2" } } ]
{ "AcceptedAnswerId": "252916", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T00:29:29.673", "Id": "252910", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "binary-search", "insertion-sort" ], "Title": "Sorting and Searching Algorithm" }
252910
<p>I've made a memory match game, where the users can draw each card. When the program is ran, there would be a canvas that allows the user to draw in. When the user is done drawing, they can press ENTER, and another fresh canvas will appear.</p> <p>The user may repeat the process, drawing as many card designs as needed, and when enough card designs are drawn, press ENTER without drawing anything, and the memory match game will begin.</p> <p>Here is a sped-up demonstration how it works:</p> <p><a href="https://i.stack.imgur.com/w7lZM.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w7lZM.gif" alt="enter image description here" /></a></p> <p>My code:</p> <pre><code>import pygame from time import sleep from random import shuffle, choice ROWS = 5 COLUMNS = 8 pygame.init() wn = pygame.display.set_mode((435, 500)) class CreateShape: def __init__(self, x, y, w, h): self.rect = pygame.Rect(x, y, w, h) self.drawing = False self.color = (255, 0, 0) self.cors = [] def under(self, pos): return self.rect.collidepoint(pos) def draw(self): pygame.draw.rect(wn, (255, 255, 255), self.rect) for cor in self.cors: if len(cor) &gt; 2: pygame.draw.polygon(wn, self.color, cor) def create(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: if shape.under(event.pos): shape.cors.append([]) shape.drawing = True elif event.type == pygame.MOUSEBUTTONUP: shape.drawing = False elif event.type == pygame.MOUSEMOTION: if shape.under(event.pos): if shape.drawing: shape.cors[-1].append(event.pos) elif event.type == pygame.KEYDOWN: return self.cors wn.fill((0, 0, 0)) shape.draw() pygame.display.update() class Card: def __init__(self, x, y, w, h, shape, original): self.x = x self.y = y self.w = w self.h = h self.card_color = (200, 200, 200) self.shape_color = (255, 0, 0) self.rect = pygame.Rect(x, y, w, h) self.shape = shape self.original = original self.turned = False def flip(self): self.turned = not self.turned def clicked(self, pos): return self.rect.collidepoint(pos) def draw(self): pygame.draw.rect(wn, self.card_color, self.rect) if self.turned: for shape in self.shape: pygame.draw.polygon(wn, self.shape_color, shape) class Deck: def __init__(self, x, y, w, h, rows, cols, score_keeper, shapes=[], space=5): shapes *= 2 self.turned = [] self.cards = [] index = 0 while len(shapes) &lt; rows * cols: shapes += [choice(shapes)] * 2 shuffle(shapes) for i in range(rows): for j in range(cols): shapey = [[[c[0] / 2, c[1] / 2] for c in s] for s in shapes[index]] card_x, card_y = x + j * (w + space), y + i * (h + space) cors_x = sorted([cor[0] for shape in shapey for cor in shape]) cors_y = sorted([cor[1] for shape in shapey for cor in shape]) max_x, min_x = cors_x[0], cors_x[-1] max_y, min_y = cors_y[0], cors_y[-1] shaper = [[(i + card_x - min_x + (w - max_x + min_x) / 2, j + card_y - min_y + (h - max_y + min_y) / 2) for i, j in shape] for shape in shapey] self.cards.append(Card(card_x, card_y, w, h, shaper, shapes[index])) index += 1 def check_equal(self, c1, c2): for shape1, shape2 in zip(c1.original, c2.original): for s1, s2 in zip(shape1, shape2): for cor1, cor2 in zip(s1, s2): if cor1 != cor2: return False return True def clicked(self, pos): for card in self.cards: if card.clicked(pos): card.flip() if card.turned: self.turned.append(card) else: self.turned.remove(card) if len(self.turned) == 2: self.draw() pygame.display.update() sleep(0.5) if self.check_equal(*self.turned): for card in self.turned: self.cards.remove(card) score.add() else: for card in self.turned: card.flip() score.remove() self.turned.clear() def draw(self): for card in self.cards: card.draw() class Score: def __init__(self, x, y, size=40): self.x = x self.y = y self.size = size self.font = pygame.font.SysFont('Arial', size) self.total = 0 def add(self, amt=10): self.total += amt def remove(self, amt=5): self.total -= amt def draw(self): text = self.font.render(f'Score: {self.total}', False, (255, 255, 255)) wn.blit(text, (self.x, self.y)) shapes = [] for i in range(ROWS * COLUMNS // 2): shape = CreateShape(168, 200, 100, 100) my_shape = shape.create() if not my_shape: break shapes.append(my_shape) score = Score(20, 20) deck = Deck(20, 90, 45, 65, ROWS, COLUMNS, score, shapes) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: deck.clicked(event.pos) wn.fill((0, 0, 0)) deck.draw() score.draw() pygame.display.update() </code></pre> <p>I believe my <code>check_equal</code> function can be greatly simplified, as all it does is return wehther two lists <em>(<code>c1</code> and <code>c2</code>)</em> of lists of tuples are equal:</p> <pre><code>def check_equal(self, c1, c2): for shape1, shape2 in zip(c1.original, c2.original): for s1, s2 in zip(shape1, shape2): for cor1, cor2 in zip(s1, s2): if cor1 != cor2: return False return True </code></pre> <h3>Can you please point out where in my code can be simpliflied, and where can I improve the efficiency of it?</h3> <p><strong>Bug reports will also be greatly appreciated!</strong></p>
[]
[ { "body": "<p><code>check_equal()</code> can be greatly simplified:</p>\n<pre><code>def check_equal(self, c1, c2):\n return c1.original is c2.original\n</code></pre>\n<p>The main code creates a list of shapes. <code>Deck.__init__()</code> uses <code>shapes *= 2</code> to double the list of shapes. That is, <code>shapes</code> now contains two copies of each shape. Actually, it contains two references to the same shape. Then a <code>Card</code> is made from each shape, which stores the shape in <code>Card.original</code>. So you can use <code>is</code> to check if the cars have the same shape.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T13:03:06.393", "Id": "498703", "Score": "0", "body": "Awesome! ------" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T09:00:38.953", "Id": "252976", "ParentId": "252912", "Score": "1" } } ]
{ "AcceptedAnswerId": "252976", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T01:51:51.330", "Id": "252912", "Score": "1", "Tags": [ "python", "performance", "beginner", "pygame" ], "Title": "Draw-Your-Own-Cards One-file Memory Match Game" }
252912
<p>I have been working on implementing rate limiter in Java. Following is my approach.</p> <p>I have used 'sliding window with counters' technique to implement this rate limiter. What I do is instead of rate limiting per second I rate limit per minute. This allows me to create 60 buckets (one for each minute) for each hour for each user. Any time the user has crossed the threshold I reject the requests.</p> <p>Reason for adopting this approach is that it can easily scale to any number of users as each user can have at most 60 buckets keeping track of the number of requests. After every hour the buckets are refreshed.</p> <p>Please take a look at this and let me know what's good and what's bad about this approach.</p> <p>Steps:</p> <ol> <li>First we will use a HashMap to store the number of requests for every user.</li> <li>For every user, fill up the map with 60 fixed minute slots.</li> <li>For every request timestamp we will truncate it to the closest rounded minute just passed. <ul> <li>if the current timestamp is within the current minute then <ul> <li>we increment the counter for current minute if the current request is within the limit</li> <li>we reject the request if it has exceeded the rate limit</li> </ul> </li> <li>if the new timestamp has passed the current minute then create the new minute key and set the counter to 1</li> <li>if the current timestamp is in the next hour then delete the entries from the previous hour and create new set of 60 minute slots. Whenever we step into a new hour, all the minute slots are recycled.</li> </ul> </li> </ol> <pre><code> public class RateLimitService { private static final long MILLIS_IN_SECOND = 1000; private static final long MILLIS_IN_MIUTE = 60000; private static final long MILLIS_IN_HOUR = 3600000; private static final long MILLIS_IN_DAY = 86400000; private static final int RATE_LIMIT_PER_MIN = 3; private static final int RATE_LIMIT_PER_HOUR = 10; private static Map&lt;Long, ConcurrentSkipListMap&lt;Long, Integer&gt;&gt; limitMap = new HashMap&lt;Long, ConcurrentSkipListMap&lt;Long, Integer&gt;&gt;(); private static Map&lt;Long, Integer&gt; requestCounterHourly = new HashMap&lt;Long, Integer&gt;(); public static void main(String[] args) { RateLimitService rls = new RateLimitService(); rls.test(); } private void test() { System.out.println(&quot;=============================&quot;); System.out.println(String.format(&quot;Max reqs in minute: %d | Max reqs in hour: %d&quot;, RATE_LIMIT_PER_MIN, RATE_LIMIT_PER_HOUR)); System.out.println(&quot;=============================&quot;); Long userId = 1L; refreshMinuteSlots(userId, System.currentTimeMillis()); long reqT = System.currentTimeMillis(); int sleepTime = 10000; for (int i=0; i&lt;6; i++) { reqT = System.currentTimeMillis(); boolean isAllowed = isAllowed(reqT, 1L); System.out.println(String.format(&quot;Req at %d allowed? %s (totalRequestsInHour: %d) &quot;, reqT, isAllowed, requestCounterHourly.get(userId))); sleepTime *= 2; // exponential sleep(sleepTime); } System.out.println(&quot;=============================&quot;); printTimes(limitMap.get(userId)); System.out.println(&quot;=============================&quot;); } private void sleep(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean isAllowed(Long reqT, Long userId) { ConcurrentSkipListMap&lt;Long, Integer&gt; times = limitMap.get(userId); Long truncatedMin = truncate(reqT, ChronoUnit.MINUTES); // truncate to the beginning of minute if (times != null) { Long truncatedHour = truncate(reqT, ChronoUnit.HOURS); // truncate to the beginning of hour Long truncatedDay = truncate(reqT, ChronoUnit.DAYS); // truncate to the beginning of the day if ((truncatedMin - truncatedDay &gt;= MILLIS_IN_DAY) || (truncatedMin - truncatedHour &gt;= MILLIS_IN_HOUR)) { refreshMinuteSlots(userId, reqT); requestCounterHourly.put(userId, 0); } } else { refreshMinuteSlots(userId, reqT); } times = limitMap.get(userId); // Reject if greater than rate limit threshold if ((times.get(truncatedMin) &gt;= RATE_LIMIT_PER_MIN) || (requestCounterHourly.getOrDefault(userId, 0) &gt;= RATE_LIMIT_PER_HOUR)) { return false; } System.out.println(String.format(&quot;Putting reqT %d in the bucket %d&quot;, reqT, truncatedMin)); times.put(truncatedMin, times.get(truncatedMin) + 1); limitMap.put(userId, times); requestCounterHourly.put(userId, requestCounterHourly.getOrDefault(userId, 0) + 1); return true; } /* * Truncates the timestamp to the closest time unit. * */ private Long truncate(Long time, ChronoUnit unit) { SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-MM-dd'T'HH:mm:ss'Z'&quot;); sdf.setTimeZone(TimeZone.getTimeZone(&quot;UTC&quot;)); Date date = new Date(time); String dateStr = sdf.format(date); Instant instant = Instant.parse(dateStr); Instant returnValue = instant.truncatedTo(unit); return returnValue.toEpochMilli(); } /* Add new set of minute slots. * * @param userId * @param reqT */ private void refreshMinuteSlots(Long userId, Long reqT) { Long minofDay = truncate(reqT, ChronoUnit.HOURS); // start min of the hour ConcurrentSkipListMap&lt;Long, Integer&gt; times = new ConcurrentSkipListMap&lt;Long, Integer&gt;(); for (int i=0; i&lt;=59; i++) { // add rounded minutes in an hour to the map times.put(minofDay, 0); minofDay += MILLIS_IN_MIUTE; } limitMap.put(userId, times); } /* * Prints the current requests numbers from the map. */ private void printTimes(ConcurrentSkipListMap&lt;Long, Integer&gt; times) { System.out.println(&quot;Current state of the times for user...&quot;); for (Long time : times.keySet()) { System.out.println(time + &quot; : &quot; + times.get(time)); } } } </code></pre>
[]
[ { "body": "<h2>You can uses the <code>java.util.concurrent.TimeUnit</code> to calculate the number of x</h2>\n<p>Java offers a class that convert time into other units.</p>\n<p>In your case, you can replace, if you want, the hardcoded constants.</p>\n<pre class=\"lang-java prettyprint-override\"><code> private static final long MILLIS_IN_SECOND = TimeUnit.SECONDS.toMillis(1); //1000\n private static final long MILLIS_IN_MIUTE = TimeUnit.MINUTES.toMillis(1); //60000\n private static final long MILLIS_IN_HOUR = TimeUnit.HOURS.toMillis(1);//3600000\n private static final long MILLIS_IN_DAY = TimeUnit.DAYS.toMillis(1);//86400000\n</code></pre>\n<h2>You can omit the values in the right diamond operator</h2>\n<p>Since you already defined the values in the left diamond operator, you can add an empty one in the right.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Map&lt;String, String&gt; values = new HashMap&lt;String, String&gt;();\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Map&lt;String, String&gt; values = new HashMap&lt;&gt;();\n</code></pre>\n<h2>Use <code>java.io.PrintStream#printf</code> instead of <code>java.io.PrintStream#println</code> when you have to concatenate</h2>\n<p><code>java.io.PrintStream#printf</code> offer you to use <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Formatter.html\" rel=\"nofollow noreferrer\">patterns</a> to build the string without concatenating it manually. The only downside is you will be forced to add the break line character yourself; in java you can use the <code>%n</code> to break the line (portable between various platforms) or uses the traditional <code>\\n</code> / <code>\\r\\n</code>.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println(String.format(&quot;Max reqs in minute: %d | Max reqs in hour: %d&quot;, RATE_LIMIT_PER_MIN, RATE_LIMIT_PER_HOUR));\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>System.out.printf(&quot;Max reqs in minute: %d | Max reqs in hour: %d%n&quot;, RATE_LIMIT_PER_MIN, RATE_LIMIT_PER_HOUR);\n</code></pre>\n<h2>Always use the primitives when possible</h2>\n<p>When you know that it's impossible to get a null value with the number, try to use the primitives; this can prevent the unboxing of the value in some case.</p>\n<h2><code>RateLimitService#refreshMinuteSlots</code> method</h2>\n<p>In my opinion, you can use the <code>java.time.Instant#ofEpochMilli</code> to convert the timestamp into an <code>java.time.Instant</code>; I can be wrong on this, but I don’t see the advantages of formatting a date to reconvert it to an instant since the <code>java.lang.System#currentTimeMillis</code> already return the timestamp in UTC.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static long truncate(long time, ChronoUnit unit) {\n SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-MM-dd'T'HH:mm:ss'Z'&quot;);\n sdf.setTimeZone(TimeZone.getTimeZone(&quot;UTC&quot;));\n Date date = new Date(time);\n String dateStr = sdf.format(date);\n\n Instant instant = Instant.parse(dateStr);\n Instant returnValue = instant.truncatedTo(unit);\n\n return returnValue.toEpochMilli();\n}\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static long truncate(long time, ChronoUnit unit) {\n Instant instant = Instant.ofEpochMilli(time);\n Instant returnValue = instant.truncatedTo(unit);\n return returnValue.toEpochMilli();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T23:38:27.243", "Id": "498761", "Score": "0", "body": "Thank you very much for your feedback. Very much appreciated. What do you think from the logical point of view? Will this be easy to scale out? Is there a better alternative for this? Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T12:21:52.750", "Id": "499052", "Score": "0", "body": "Sorry for the late answer, in my opinion, this can be a good implementation. Your code is separated in methods and can be refactored if need be. For the implementation, I personally didn't find another way to do the problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T21:45:04.293", "Id": "252954", "ParentId": "252915", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T05:22:43.900", "Id": "252915", "Score": "4", "Tags": [ "java", "security" ], "Title": "Rate Limiter implementation in Java" }
252915
<p>Currently, we plan to perform an intensive SQLite DB migration code in Android. We really want to avoid from having any bad impact (data corruption) on existing users.</p> <p>Can anyone help me to take a look, whether our code is flawless? Is there any room of improvement, to further enhance the robustness of the code?</p> <p>Our objectives are as follow :-</p> <ol> <li>Change <code>type</code> INTEGER to <code>type</code> INTEGER NOT NULL</li> <li>Change <code>reminder_type</code> INTEGER to <code>reminder_type</code> INTEGER NOT NULL</li> <li>Change <code>reminder_repeat</code> INTEGER to <code>reminder_repeat</code> INTEGER NOT NULL</li> <li>Change <code>reminder_day_of_week_bitwise</code> INTEGER to <code>reminder_day_of_week_bitwise</code> INTEGER NOT NULL</li> <li>Change <code>uuid</code> TEXT to <code>uuid</code> TEXT NOT NULL</li> <li>Change CREATE INDEX <code>index_plain_note_uuid</code> ON <code>plain_note</code> (<code>uuid</code>) to CREATE UNIQUE INDEX <code>index_plain_note_uuid</code> ON <code>plain_note</code> (<code>uuid</code>)</li> <li>Drop column <code>theme</code></li> <li>Drop column <code>key</code></li> </ol> <p>If you have spotted any error. Please kindly let me know. Thank you.</p> <p>p/s Currently, the <code>VACUUM</code> code is not workable. We are still figuring out a way to do so.</p> <hr /> <p>Here's our complete migration code.</p> <pre><code>package com.yocto.wenote.repository.migration; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import androidx.annotation.NonNull; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; import com.yocto.wenote.model.DayOfWeekBitwise; import com.yocto.wenote.model.PlainNote; import com.yocto.wenote.reminder.Reminder; import com.yocto.wenote.reminder.Repeat; import java.util.HashSet; import java.util.Set; import static com.yocto.wenote.Utils.generateUUID; import static com.yocto.wenote.Utils.isNullOrEmpty; public class Migration_22_23 extends Migration { public Migration_22_23() { super(22, 23); } // (1) Change `type` INTEGER to `type` INTEGER NOT NULL // (2) Change `reminder_type` INTEGER to `reminder_type` INTEGER NOT NULL // (3) Change `reminder_repeat` INTEGER to `reminder_repeat` INTEGER NOT NULL // (4) Change `reminder_day_of_week_bitwise` INTEGER to `reminder_day_of_week_bitwise` INTEGER NOT NULL // (5) Change `uuid` TEXT to `uuid` TEXT NOT NULL // (6) Change CREATE INDEX `index_plain_note_uuid` ON `plain_note` (`uuid`) to CREATE UNIQUE INDEX `index_plain_note_uuid` ON `plain_note` (`uuid`) // (7) Drop column `theme` // (8) Drop column `key` @Override public void migrate(@NonNull SupportSQLiteDatabase database) { // Ensure existing data are non null and no conflict. ensureNoNullNoUniqueConflict(database); // Create our desired table schema in a temporary `plain_note_new`. This is a table with // correct NOT NULL constraint, and WITHOUT unwanted columns (`theme` and `key`). database.execSQL(&quot;CREATE TABLE `plain_note_new` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `label` TEXT, `title` TEXT, `body` TEXT, `type` INTEGER NOT NULL, `color_index` INTEGER NOT NULL, `custom_color` INTEGER NOT NULL, `locked` INTEGER NOT NULL, `pinned` INTEGER NOT NULL, `checked` INTEGER NOT NULL, `archived` INTEGER NOT NULL, `trashed` INTEGER NOT NULL, `sticky` INTEGER NOT NULL, `sticky_icon` INTEGER NOT NULL, `order` INTEGER NOT NULL, `searched_string` TEXT, `reminder_type` INTEGER NOT NULL, `reminder_timestamp` INTEGER NOT NULL, `reminder_repeat` INTEGER NOT NULL, `reminder_end_timestamp` INTEGER NOT NULL, `reminder_active_timestamp` INTEGER NOT NULL, `reminder_last_timestamp` INTEGER NOT NULL, `reminder_repeat_frequency` INTEGER NOT NULL, `reminder_day_of_week_bitwise` INTEGER NOT NULL, `created_timestamp` INTEGER NOT NULL, `modified_timestamp` INTEGER NOT NULL, `trashed_timestamp` INTEGER NOT NULL, `synced_timestamp` INTEGER NOT NULL, `uuid` TEXT NOT NULL)&quot;); // Copy existing table `plain_note` to temporary table `plain_note_new`. database.execSQL(&quot;INSERT INTO `plain_note_new` SELECT `id`, `label`, `title`, `body`, `type`, `color_index`, `custom_color`, `locked`, `pinned`, `checked`, `archived`, `trashed`, `sticky`, `sticky_icon`, `order`, `searched_string`, `reminder_type`, `reminder_timestamp`, `reminder_repeat`, `reminder_end_timestamp`, `reminder_active_timestamp`, `reminder_last_timestamp`, `reminder_repeat_frequency`, `reminder_day_of_week_bitwise`, `created_timestamp`, `modified_timestamp`, `trashed_timestamp`, `synced_timestamp`, `uuid` FROM `plain_note`&quot;); // Turn OFF foreign key constraint so that dropping existing table `plain_note` will not // drop other tables' content which contain column // `plain_note_id` INTEGER NOT NULL, FOREIGN KEY(`plain_note_id`) REFERENCES `plain_note`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE database.execSQL(&quot;PRAGMA foreign_keys = OFF&quot;); // Drop indices associated with existing table `plain_note` explicitly. database.execSQL(&quot;DROP INDEX `index_plain_note_archived`&quot;); database.execSQL(&quot;DROP INDEX `index_plain_note_label`&quot;); database.execSQL(&quot;DROP INDEX `index_plain_note_sticky`&quot;); database.execSQL(&quot;DROP INDEX `index_plain_note_trashed`&quot;); database.execSQL(&quot;DROP INDEX `index_plain_note_uuid`&quot;); // Drop existing table `plain_note`. database.execSQL(&quot;DROP TABLE `plain_note`&quot;); // Rename temporary table `plain_note_new` to table `plain_note`. database.execSQL(&quot;ALTER TABLE `plain_note_new` RENAME TO `plain_note`&quot;); // Rebuild the indices for table `plain_note`. database.execSQL(&quot;CREATE INDEX `index_plain_note_archived` ON `plain_note` (`archived`)&quot;); database.execSQL(&quot;CREATE INDEX `index_plain_note_label` ON `plain_note` (`label`)&quot;); database.execSQL(&quot;CREATE INDEX `index_plain_note_sticky` ON `plain_note` (`sticky`)&quot;); database.execSQL(&quot;CREATE INDEX `index_plain_note_trashed` ON `plain_note` (`trashed`)&quot;); database.execSQL(&quot;CREATE UNIQUE INDEX `index_plain_note_uuid` ON `plain_note` (`uuid`)&quot;); // Turn ON foreign key constraint. database.execSQL(&quot;PRAGMA foreign_keys = ON&quot;); // TODO: We aren't sure how to perform vacuum due to the following error. // &quot;Cannot vacuum from within a transaction&quot; // https://stackoverflow.com/questions/65103059/android-room-how-to-perform-vacuum-after-performing-massive-table-migration // Reclaim disk space. database.execSQL(&quot;VACUUM&quot;); } private void ensureNoNullNoUniqueConflict(SupportSQLiteDatabase database) { Cursor queryCursor = null; try { queryCursor = database.query(&quot;SELECT id, type, reminder_type, reminder_repeat, reminder_day_of_week_bitwise, uuid, searched_string FROM plain_note ORDER BY id ASC&quot;); queryCursor.moveToFirst(); int idIndex = -1; int typeIndex = -1; int reminderTypeIndex = -1; int reminderRepeatIndex = -1; int reminderDayOfWeekBitwiseIndex = -1; int uuidIndex = -1; int searchStringIndex = -1; final String ID = &quot;id&quot;; final String TYPE = &quot;type&quot;; final String REMINDER_TYPE = &quot;reminder_type&quot;; final String REMINDER_REPEAT = &quot;reminder_repeat&quot;; final String REMINDER_DAY_OF_WEEK_BITWISE = &quot;reminder_day_of_week_bitwise&quot;; final String UUID = &quot;uuid&quot;; final String SEARCHED_STRING = &quot;searched_string&quot;; if (!queryCursor.isAfterLast()) { idIndex = queryCursor.getColumnIndex(ID); typeIndex = queryCursor.getColumnIndex(TYPE); reminderTypeIndex = queryCursor.getColumnIndex(REMINDER_TYPE); reminderRepeatIndex = queryCursor.getColumnIndex(REMINDER_REPEAT); reminderDayOfWeekBitwiseIndex = queryCursor.getColumnIndex(REMINDER_DAY_OF_WEEK_BITWISE); uuidIndex = queryCursor.getColumnIndex(UUID); searchStringIndex = queryCursor.getColumnIndex(SEARCHED_STRING); } if (idIndex == -1 || typeIndex == -1 || reminderTypeIndex == -1 || reminderRepeatIndex == -1 || reminderDayOfWeekBitwiseIndex == -1 || uuidIndex == -1 || searchStringIndex == -1 ) { // Abort. throw new java.lang.RuntimeException(); } final Set&lt;String&gt; uuids = new HashSet&lt;&gt;(); for (; !queryCursor.isAfterLast(); queryCursor.moveToNext()) { boolean typeUpdateRequired = false; boolean reminderTypeUpdateRequired = false; boolean reminderRepeatUpdateRequired = false; boolean reminderDayOfWeekBitwiseUpdateRequired = false; boolean uuidUpdateRequired = false; final long id = queryCursor.getLong(idIndex); // Ensure NOT NULL. if (queryCursor.isNull(typeIndex)) { typeUpdateRequired = true; } // Ensure NOT NULL. if (queryCursor.isNull(reminderTypeIndex)) { reminderTypeUpdateRequired = true; } // Ensure NOT NULL. if (queryCursor.isNull(reminderRepeatIndex)) { reminderRepeatUpdateRequired = true; } // Ensure NOT NULL. if (queryCursor.isNull(reminderDayOfWeekBitwiseIndex)) { reminderDayOfWeekBitwiseUpdateRequired = true; } String uuid = queryCursor.getString(uuidIndex); // Ensure NOT NULL. if (isNullOrEmpty(uuid)) { uuid = generateUUID(); uuidUpdateRequired = true; } // Ensure UNIQUE. while (uuids.contains(uuid)) { uuid = generateUUID(); uuidUpdateRequired = true; } uuids.add(uuid); ContentValues contentValues; if (typeUpdateRequired || reminderTypeUpdateRequired || reminderRepeatUpdateRequired || reminderDayOfWeekBitwiseUpdateRequired || uuidUpdateRequired) { contentValues = new ContentValues(); } else { // Nothing to update. Continue next record. continue; } if (typeUpdateRequired) { if (queryCursor.isNull(searchStringIndex)) { contentValues.put(TYPE, PlainNote.Type.Text.code); } else { contentValues.put(TYPE, PlainNote.Type.Checklist.code); } } if (reminderTypeUpdateRequired) { contentValues.put(REMINDER_TYPE, Reminder.Type.None.code); } if (reminderRepeatUpdateRequired) { contentValues.put(REMINDER_REPEAT, Repeat.None.code); } if (reminderDayOfWeekBitwiseUpdateRequired) { contentValues.put(REMINDER_DAY_OF_WEEK_BITWISE, DayOfWeekBitwise.NIL_DAY_OF_WEEK_BITWISE.bitwise); } if (uuidUpdateRequired) { contentValues.put(UUID, uuid); } database.update(&quot;plain_note&quot;, SQLiteDatabase.CONFLICT_REPLACE, contentValues, &quot;id = ?&quot;, new Object[]{id}); } } finally { if (queryCursor != null) { queryCursor.close(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T13:34:40.747", "Id": "498572", "Score": "0", "body": "Did you write tests for your migration?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T14:13:51.997", "Id": "498574", "Score": "0", "body": "Pretty valid question. Although I have never try to write test for migration and not sure how good it is to prevent bug, guess I need to give it a try, as this round of migration is pretty risky." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:20:58.243", "Id": "252917", "Score": "0", "Tags": [ "android", "sqlite" ], "Title": "Is my Android Room SQLite migration code written without flaw, as I wish to have 0 impact on my existing users?" }
252917
<p>I started Python 3 days ago. This user login code is the first project I completed, not following along with a tutorial. The idea is that you can create a user and login with it. I am wondering if there are ways to make this code much more efficient or shorter. If it needs anything, I'd love to learn new things.</p> <pre class="lang-py prettyprint-override"><code>def choices(): print(&quot;Please choose what you would like to do.&quot;) choice = int(input(&quot;For Signing Up Type 1 and For Signing In Type 2: &quot;)) if choice == 1: print(&quot;Please Provide&quot;) username = str(input(&quot;Username: &quot;)) f = open(&quot;usernames.txt&quot;, 'r') info = f.read() if username in info: print(&quot;Username unavailable. Please Try Again.&quot;) return print(choices()) f.close() password = str(input(&quot;Password: &quot;)) f = open(&quot;passwords.txt&quot;, 'r') info1 = f.read() f.close() f = open(&quot;usernames.txt&quot;, 'w') info = info + &quot; &quot; + username f.write(info) f.close() f = open(&quot;passwords.txt&quot;, 'w') info1 = info1 + &quot; &quot; + password f.write(info1) f.close() print(&quot;Congratulations! You have successfully created an account. You may now login in.&quot;) return print(choices()) elif choice == 2: print(&quot;Please Provide&quot;) username = str(input(&quot;Username: &quot;)) f = open(&quot;usernames.txt&quot;, 'r') info = f.read() if username in info: password = str(input(&quot;Password: &quot;)) f = open(&quot;passwords.txt&quot;, 'r') info1 = f.read() if password in info1: print(&quot;Welcome Back &quot; + username + &quot;!&quot;) else: print(&quot;Your password is incorrect. Please try again.&quot;) return print(choices()) else: print(&quot;Your username is either incorrect or nonexistent. You can either try again or create a new account.&quot;) return print(choices()) else: raise TypeError print(choices()) </code></pre>
[]
[ { "body": "<h2>Use <code>with</code> to handle file operations</h2>\n<p>A common way to handle files is by creating a file instance with <code>open</code> statement and closing it when you are done with the handler, while this would work, it is prone to error. What if you forget to close the file? It leads to either the file not saving or the handler might be corrupted with garbage. <code>with</code> automatically closes the file once operations on it are done. A simple example is as follow</p>\n<pre><code>with open('usernames.txt', 'r') as f:\n f.read()\n</code></pre>\n<h2>Recursion is expensive</h2>\n<p>Your <code>choices</code> function uses recursion which might become expensive. Recursion creates temporaries in the stack frame and as it recur more and more, your stack frame might eventually be filled, though it can be elegant to solve a problem with recursion, limit it usage. Any function that can be written recursively can also be written with an iterative approach. Iterative approach tends to be faster and does not create temporaries</p>\n<h2>Consider reducing the complexity of <code>choices</code></h2>\n<p>Right now <code>choice</code> does way too much, signs up a user and also login a user. Your functions should do just one thing and do it very well. The name <code>choices</code> is very misleading, from the name, I would expect it to make a choice or rather I make a choice among a list of values, rather is suprisingly signs up and login a user. Avoid function side-effect. Function side-effect is when a function promises one thing and does another.</p>\n<h2>Use a dictionary pair</h2>\n<p>I really think a dictionary is needed in this scenario. Dictionaries as we all know are very fast. Storing a key-value pair of username and password makes the code clean and easy to reason about.</p>\n<h2>Detour</h2>\n<ol>\n<li><p>You might want to use <code>open('filename.txt', 'a')</code> when you want to append to a file, using 'w' overwrites the content of the file and is similar to calling <code>truncate</code> on the file.</p>\n</li>\n<li><p>When you want to recieve string input, no need for this statement <code>str(input(&quot;Enter&quot;))</code>, input automatically recieves strings.</p>\n</li>\n<li><p>Avoid variable names suchh as <code>f</code></p>\n</li>\n</ol>\n<p>This is an editted version of the code</p>\n<pre><code>def signup():\n with open(&quot;usernames.txt&quot;, 'r') as user:\n usernames = user.read().splitlines()\n with open(&quot;passwords.txt&quot;, 'r') as pwd:\n passwords = pwd.read().splitlines()\n \n info = dict(zip(usernames, passwords))\n\n print(&quot;Please Provide&quot;)\n username = input(&quot;Username: &quot;)\n while username in info.keys():\n print(&quot;Username unavailable. Please Try Again.&quot;)\n username = input(&quot;Username: &quot;) \n password = input(&quot;Password: &quot;) \n \n with open(&quot;usernames.txt&quot;, 'a') as user:\n user.write(username + '\\n')\n with open(&quot;passwords.txt&quot;, 'a') as pwd:\n pwd.write(password + '\\n')\n \n print(&quot;Congratulations! You have successfully created an account. You may now login in.&quot;)\n\ndef login():\n with open(&quot;usernames.txt&quot;, 'r') as user:\n usernames = user.read().splitlines()\n with open(&quot;passwords.txt&quot;, 'r') as pwd:\n passwords = pwd.read().splitlines()\n \n info = dict(zip(usernames, passwords))\n username = input(&quot;Username: &quot;))\n password = input(&quot;Password: &quot;))\n\n if info.get(username, None) is None:\n print(&quot;Your username is either incorrect or nonexistent. You can either try again or create a new account.&quot;)\n signup()\n return\n\n if password != info[username]:\n print(&quot;Your password is incorrect. Please try again.&quot;)\n return\n\n print(&quot;Welcome Back &quot; + username + &quot;!&quot;) \n\nif __name__ == '__main__':\n print(&quot;Please choose what you would like to do.&quot;)\n choice = int(input(&quot;For Signing Up Type 1 and For Signing In Type 2: &quot;))\n if choice == 1:\n signup()\n elif choice == 2:\n login()\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T07:45:45.020", "Id": "252920", "ParentId": "252918", "Score": "2" } }, { "body": "<p>ere are the points in your code that needs to be fixed:</p>\n<ol>\n<li><p>Calling a function inside that function would sooner or later result in a <code>RecursionError</code> error. instead, use <code> while</code> loop,\nand a <code>break</code> statement for when a user successfully logs in. Whenever invalid information is given,\nthe <code>continue</code> statement will make the program jump to the top of the <code>while</code> loop again.</p>\n</li>\n<li><p><em>Always</em> use a <code>with</code> statement over simply assigning an <code>open</code> function to a variable.</p>\n</li>\n<li><p>It is unnecessary to convert the user's input to an integer, especially when it is prone to cause a<code>ValueError</code> when the user inputs any characters tat aren't digits.</p>\n</li>\n<li><p>There is no need to convert the user's input into a string, as the input will be of string type by default. Doing so only wastes efficiency.</p>\n</li>\n<li><p>Checking if a string is in a file in its single-string form will cause bugs. For example, if your file is currently:</p>\n</li>\n</ol>\n<pre><code>Sally Bobby Timmy Bobble Deusovi Bubbler Ention\n</code></pre>\n<p>and the user inputs <code>&quot;Bob&quot;</code>, the program will assume that <code>&quot;Bob&quot;</code> is among the usernames.\nInstead of spaces as the delimiter, which can cause confusion when a user inputs their last name, use line breaks <code>\\n</code>,\nand convert the file's content into a list of names before checking if the user's input is valid.</p>\n<p>Here is the full implementation:</p>\n<pre><code>def choices():\n while True:\n print(&quot;Please choose what you would like to do.&quot;)\n choice = input(&quot;For Signing Up Type 1 and For Signing In Type 2: &quot;)\n if choice == '1':\n print(&quot;Please Provide&quot;)\n username = input(&quot;Username: &quot;)\n with open(&quot;usernames.txt&quot;, 'r') as f:\n info = f.read()\n if username in info:\n print(&quot;Username unavailable. Please Try Again.&quot;)\n continue\n password = input(&quot;Password: &quot;)\n with open(&quot;passwords.txt&quot;, 'r') as f:\n info1 = f.read()\n with open(&quot;usernames.txt&quot;, 'w') as f:\n info = f'{info}\\n{username}'\n f.write(info)\n with open(&quot;passwords.txt&quot;, 'w') as f:\n info1 = f&quot;{info1}\\n{password}&quot;\n f.write(info1)\n print(&quot;Congratulations! You have successfully created an account. You may now login in.&quot;)\n elif choice == '2':\n print(&quot;Please Provide&quot;)\n username = input(&quot;Username: &quot;)\n with open(&quot;usernames.txt&quot;, 'r') as f:\n info = f.read().splitlines()\n if username in info:\n password = input(&quot;Password: &quot;)\n with open(&quot;passwords.txt&quot;, 'r') as f:\n info1 = f.read().splitlines()\n if password in info1:\n print(f&quot;Welcome Back {username}!&quot;)\n break\n print(&quot;Your password is incorrect. Please try again.&quot;)\n else:\n print(&quot;Your username is either incorrect or nonexistent. You can either try again or create a new account.&quot;)\n else:\n print(&quot;Invalid option.&quot;)\nchoices()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T18:28:43.230", "Id": "252945", "ParentId": "252918", "Score": "0" } } ]
{ "AcceptedAnswerId": "252920", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T06:27:56.497", "Id": "252918", "Score": "4", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Beginner Python User Login System" }
252918
<p>I am trying to pretty print the directory structure defined in a <code>JSON</code>. I do have a solution using <strong>recursion</strong> but I'm looking for <strong>feedback</strong> on how this solution can be improved or if there's any <strong>better approach</strong>.</p> <h3>Problem Statement</h3> <p>A deeply nested directory contains following information:</p> <ol> <li>Name</li> <li>Data (can be an array of sub directories or file content)</li> </ol> <p><strong>Desired output:</strong> Print the directory structure in below format:</p> <pre><code>root_dir |__dir_a |____file_00.txt |____dir_b |______dir_c |________file_01.txt |________file_02.txt |________file_03.txt |________file_04.txt |______file_05.txt |______file_06.txt |____dir_d |______file_07.txt |______file_08.txt </code></pre> <h3>Solution:</h3> <p>My idea is to <strong>traverse data recursively</strong> till a file is not found (because beyond it there is no further nesting) and keep pushing directories and files in an array which would then be pretty printed with help of template literals.</p> <p><strong>P.S.</strong> I don't want to reverse the arrays twice, how can I fix that?</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>const indentation = 2; const flatDirStructure = []; const dirStructure = [ { name: 'root_dir', data: [ { name: 'dir_a', data: [ { name: 'file_00.txt', data: 'file_00 content' }, { name: 'dir_b', data: [ { name: 'dir_c', data: [ { name: 'file_01.txt', data: 'file_01 content' }, { name: 'file_02.txt', data: 'file_02 content' }, { name: 'file_03.txt', data: 'file_03 content' }, { name: 'file_04.txt', data: 'file_04 content' } ] }, { name: 'file_05.txt', data: 'file_05 content' }, { name: 'file_06.txt', data: 'file_06 content' } ] }, { name: 'dir_d', data: [ { name: 'file_07.txt', data: 'file_07 content' }, { name: 'file_08.txt', data: 'file_08 content' } ] } ] } ] } ]; const flattenDirStructure = (data, depth) =&gt; { if (typeof data === 'string') { return true; } else { data.reverse().forEach(({ name, data }) =&gt; { const isFile = flattenDirStructure(data, depth + indentation); flatDirStructure.push({ name, depth, isFile, }); }); return false; } }; const prettyPrint = () =&gt; { const output = []; flatDirStructure.reverse().forEach(({ name, depth }) =&gt; { const indentation = new Array(depth).fill('_').join(''); output.push(`${indentation ? '|' : ''}${indentation}${name}`); }); console.log(output.join(`\n`)); } flattenDirStructure(dirStructure, 0); prettyPrint();</code></pre> </div> </div> </p>
[]
[ { "body": "<p>You could take a single loop without reversing the array and hand over the prefix for the next level indentation.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const\n print = (data, indentation, prefix = '') =&gt; data\n .map(({ name, data }) =&gt; Array.isArray(data)\n ? prefix + name + '\\n' + print(data, indentation, (prefix || '|') + '_'.repeat(indentation))\n : prefix + name\n )\n .join('\\n'),\n dirStructure = [{ name: 'root_dir', data: [{ name: 'dir_a', data: [{ name: 'file_00.txt', data: 'file_00 content' }, { name: 'dir_b', data: [{ name: 'dir_c', data: [{ name: 'file_01.txt', data: 'file_01 content' }, { name: 'file_02.txt', data: 'file_02 content' }, { name: 'file_03.txt', data: 'file_03 content' }, { name: 'file_04.txt', data: 'file_04 content' }] }, { name: 'file_05.txt', data: 'file_05 content' }, { name: 'file_06.txt', data: 'file_06 content' }] }, { name: 'dir_d', data: [{ name: 'file_07.txt', data: 'file_07 content' }, { name: 'file_08.txt', data: 'file_08 content' }] }] }] }],\n result = print(dirStructure, 2);\n\n console.log(result);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T09:42:00.090", "Id": "498551", "Score": "0", "body": "Really neat and concise solution!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T08:10:34.380", "Id": "252923", "ParentId": "252922", "Score": "1" } }, { "body": "<p>Nina has a good solution but I'm not a fan of the code style. Most IDE formatters and/or linters would complain.</p>\n<p>This is a rewrite of it.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const dirStructure = [{\n name: 'root_dir',\n data: [{\n name: 'dir_a',\n data: [{name: 'file_00.txt', data: 'file_00 content'}, {\n name: 'dir_b',\n data: [{\n name: 'dir_c',\n data: [{name: 'file_01.txt', data: 'file_01 content'}, {name: 'file_02.txt', data: 'file_02 content'}, {name: 'file_03.txt', data: 'file_03 content'}, {name: 'file_04.txt', data: 'file_04 content'}]\n }, {name: 'file_05.txt', data: 'file_05 content'}, {name: 'file_06.txt', data: 'file_06 content'}]\n }, {name: 'dir_d', data: [{name: 'file_07.txt', data: 'file_07 content'}, {name: 'file_08.txt', data: 'file_08 content'}]}]\n }]\n}]\n\nconst format = (data, i, pre = '') =&gt; data.map(({name, data}) =&gt; {\n // data is an array then it's a sub directory and needs a recursive call\n if (Array.isArray(data)) return `${pre}${name}\\n${format(data, i, `${pre || '|'}${'_'.repeat(i)}`)}`\n return `${pre}${name}`\n}).join('\\n')\n\nconsole.log(format(dirStructure, 2))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T01:16:55.330", "Id": "253108", "ParentId": "252922", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T07:59:32.847", "Id": "252922", "Score": "2", "Tags": [ "javascript", "recursion", "json" ], "Title": "Pretty print directory structure in a JSON recursively" }
252922
<p>I am trying to resolve following problem to improve my DS knowledge. Please advice which part of the code can be improved.</p> <blockquote> <p>You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API:</p> <p>record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. You should be as efficient with time and space as possible.</p> </blockquote> <p><strong>Code explanation:</strong></p> <p>I choose linked list with single pointer (prev) to keep transaction logs. I suppose it would be called Stack Linked List.</p> <p><code>stProduct</code> -&gt; linked list node</p> <p><code>stProdStack</code> -&gt; struct to keep database information, namely ll tail and size (N)</p> <p><code>record()</code> examines db information struct <code>tail</code> pointer and <code>order_id</code> within range, then calls actual method to add node to the list: <code>add_product()</code>.</p> <p>I did not implement unit testing due to limited time to seat on.</p> <p><em>PARDON MY ENGLISH xD</em></p> <p><strong>Code:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; //backward/stack linked list for storing transaction action log typedef struct stProduct { struct stProduct * prev; unsigned int order_id; } stProduct; typedef struct stProdStack { struct stProduct * tail; unsigned int size; } stProdStack; stProduct* add_product(stProduct *tail, unsigned int order_id) { stProduct *product = malloc(sizeof *product); if (!product) return NULL; product-&gt;order_id = order_id; product-&gt;prev = tail; return product; } bool record(stProdStack *stListInfo, unsigned int order_id) { if (!stListInfo) return false; stProduct *tail = add_product(stListInfo-&gt;tail, order_id); if (tail) { stListInfo-&gt;tail = tail; return true; } else { return false; } } unsigned int get_last(const stProdStack *stListInfo, unsigned int i) { if (!stListInfo) return 0; if (i &gt; stListInfo-&gt;size) return 0; stProduct *current = stListInfo-&gt;tail; for (int j = 0; j &lt; i - 1; j++) { current = current-&gt;prev; } return current-&gt;order_id; } int main(void) { unsigned int N = 100; stProdStack product_stack = { NULL, N }; for (unsigned int i = 0; i &lt; 300; i++) { if (!record(&amp;product_stack, 1000 + i)) { printf(&quot;transaction log record failed\n&quot;); break; } } printf(&quot;10th last product ID: %u\n&quot;, get_last(&amp;product_stack, 10)); } </code></pre> <p><strong>Result:</strong> 10th last product ID: 1290</p>
[]
[ { "body": "<ul>\n<li><p>The code doesn't fulfill the requirements. You are supposed to log <em>the last <code>N</code></em> orders. Instead you log all of them. The old orders shall be removed from the list as it grows beyond <code>N</code>.</p>\n</li>\n<li><p>Bug. The list is initialized with the <code>size</code> being set to <code>N</code>. However, at the beginning it may contain less than <code>N</code> elements. In the scenario</p>\n<pre><code> List is empty\n An order is added\n get_last(2) is called\n</code></pre>\n<p>the loop</p>\n<pre><code> for (int j = 0; j &lt; i - 1; j++)\n {\n current = current-&gt;prev;\n }\n</code></pre>\n<p>is guaranteed to access a null pointer.</p>\n</li>\n<li><p>The above loop complexity is <span class=\"math-container\">\\$O(N)\\$</span>.</p>\n</li>\n</ul>\n<p>All that said, I recommend to use not a list, but a circular buffer. No need to malloc anything, and <code>get_last</code> is executed in <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T19:20:38.770", "Id": "252947", "ParentId": "252925", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T11:26:43.053", "Id": "252925", "Score": "1", "Tags": [ "c", "interview-questions" ], "Title": "Record transaction log" }
252925
<p>I'm working on an application that allows users edit/fix XML. A part of this is to format the XML for better readability.</p> <p>As the XML might be invalid, the existing methods I found for formatting (like <code>XmlWriter</code> or <code>XDocument</code>) don't work for me.<br /> There might be all sorts of problems with the XML, although the most common is unescaped special characters.</p> <pre><code>public static string FormatXml(string xml) { var tags = xml .Split('&lt;') .Select(tag =&gt; tag.TrimEnd().EndsWith(&quot;&gt;&quot;) ? tag.TrimEnd() : tag); //Trim whitespace between tags, but not at the end of values var previousTag = tags.First(); //Preserve content before the first tag, e.g. if the initial &lt; is missing var formattedXml = new StringBuilder(previousTag); var indention = 0; foreach (var tag in tags.Skip(1)) { if (previousTag.EndsWith(&quot;&gt;&quot;)) { formattedXml.AppendLine(); if (tag.StartsWith(&quot;/&quot;)) { indention = Math.Max(indention - 1, 0); formattedXml.Append(new string('\t', indention)); } else { formattedXml.Append(new string('\t', indention)); if (!tag.EndsWith(&quot;/&gt;&quot;)) { indention++; } } } else { indention = Math.Max(indention - 1, 0); } formattedXml.Append(&quot;&lt;&quot;); formattedXml.Append(tag); previousTag = tag; } return formattedXml.ToString(); } </code></pre> <p>Sofar the method produces reasonable output for all cases I came up with.</p> <p>I'm mostly worried that I missed some special cases of valid XML that would get messed up.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T15:01:51.887", "Id": "498579", "Score": "0", "body": "Is the `xml` passed to the method before or after the user edit the xml?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:13:40.333", "Id": "498594", "Score": "0", "body": "@Heslacher: The method is invoked by the user through a 'Format XML' button." } ]
[ { "body": "<p>There's a test suite of 2000 test cases available at <a href=\"https://www.w3.org/XML/Test/\" rel=\"noreferrer\">https://www.w3.org/XML/Test/</a> - try it out.</p>\n<p>From a quick glance, it's not clear to me how you're handling content within comments or CDATA sections - which might be well-formed XML, or it might be something approximating to well-formed XML.</p>\n<p>Another comment is that messing with whitespace is dangerous in mixed content. With inline markup (bold, italic etc) preserving whitespace as written may be important.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T10:23:33.090", "Id": "498694", "Score": "0", "body": "+1 I have a look a the test cases. Mixed content might be problematic. In my specific use case it's not a concern, but generally my code would need some major cases to handle this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:36:56.107", "Id": "252938", "ParentId": "252926", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T11:36:09.467", "Id": "252926", "Score": "2", "Tags": [ "c#", "xml" ], "Title": "Format potentially invalid XML" }
252926
<p>This problem is from <a href="https://adventofcode.com/2020/" rel="nofollow noreferrer">https://adventofcode.com/2020/</a> day 1.</p> <p>I need to find the N entries of <code>inputs</code> that sum to 2020 and then multiply those N numbers together.</p> <pre><code>inputs = [1721, 979, 366, 299, 675, 1456] </code></pre> <p>I have 2 cases <code>N = 2</code> and <code>N = 3</code></p> <p>I have done this with list comprehension</p> <p>N = 2 :</p> <pre><code>main = print $ head [ i * j | i &lt;- inputs , j &lt;- inputs , i+j == 2020] </code></pre> <p>N = 3 :</p> <pre><code>main = print $ head [ i * j * k | i &lt;- inputs , j &lt;- inputs , k &lt;- inputs , i+j+k == 2020] </code></pre> <p>But it scales badly, if y need <code>N = 100</code> that's a lot of <code>&lt;-</code>.</p> <p>So I have done this :</p> <pre><code>solution n = foldl1 (*) $ head [ x | x &lt;- sequence $ replicate n inputs , (foldl1 (+) x == 2020 )] main = print $ solution 3 </code></pre> <p>I wonder if there is a more idiomatic way to do this and if there is a way of using list comprehension with N variables ?</p> <p><strong>Note</strong> : I know that with these solutions, the same entries can be used multiple times, and I am ok with it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:22:04.310", "Id": "498598", "Score": "0", "body": "Welcome to Code Review! Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:11:50.227", "Id": "498601", "Score": "1", "body": "Thank you for the welcome :) Does the title match the standard better ?" } ]
[ { "body": "<p>While the code certainly works, I wouldn't necessarily call it idiomatic. Haskell's safety and robustness stems from its types, and the type signatures are completely missing. Sure, it works fine. However, all integers are <a href=\"https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#verbatim-49\" rel=\"nofollow noreferrer\"><code>Integer</code> by default</a>, a type that has some nice properties (arbitrary large numbers) and some drawbacks (sub par performance compared to <code>Int</code>).</p>\n<p>However, to introduce type signatures, we need a function. The third variant introduces a fine candidate: <code>solution</code>.</p>\n<pre><code>solution :: Int -&gt; Int\nsolution n = foldl1 (*) $ head [ x | x &lt;- sequence $ replicate n inputs , (foldl1 (+) x == 2020 )]\n</code></pre>\n<p>Now that we have a safe foundation and get type errors if we do anything unexpected, let's have a look at the code and the used functions. <code>foldl1 (*)</code> is <code>product</code> and <code>foldl1 (+)</code> is <code>sum</code>, although both alternatives act slightly different on an empty list.. Yes, both functions will use <code>foldr</code> internally, but that is fine. If we are going for strictness, then we want to use <code>foldl1'</code> instead, but that's not necessary with numbers from my experience. Also, <code>sequence . replicate</code> is <code>replicateM</code> (from <code>Control.Monad</code>), and the parentheses around <code>fold1 (+) x == 2020</code> aren't necessary. Note that <a href=\"https://hackage.haskell.org/package/hlint\" rel=\"nofollow noreferrer\"><code>hlint</code></a> will report those changes, too.</p>\n<p>So without changing the original algorithm, we end up at</p>\n<pre><code>import Control.Monad (replicateM)\n\ninputs :: [Int]\ninputs = [ ... ]\n\nsolution :: Int -&gt; Int\nsolution n = product $ head [ xs | xs &lt;- replicateM n inputs\n , sum xs == 2020]\n\nmain :: IO ()\nmain = print $ solution 3\n</code></pre>\n<p>Note that we changed <code>x</code> to <code>xs</code>, as we're not dealing with a single element, but instead with lists. This new variant ticks all the boxes:</p>\n<ul>\n<li>it has <strong>explicit</strong> types on its top-level structures ✔</li>\n<li>it uses named variants of <code>fold</code>s (<code>product</code> for <code>foldl (*) 1</code>, <code>sum</code> for <code>foldl (+) 0</code>) ✔</li>\n<li>it uses typical naming (<code>xs</code> for lists) ✔</li>\n<li>it splits functionality into reasonable parts (<code>main</code> and <code>solution</code>) ✔</li>\n</ul>\n<p>However, there's nothing wrong with your old variant, as it was semantically equivalent (except for empty intermediate lists). If I was to solve AoC, I would have used a similar script-style Haskell format, except for <code>solution</code>'s type; I'd use <code>[Int] -&gt; Int</code> or even <code>[Int] -&gt; Maybe Int</code> instead to interact with <code>map read . lines &lt;$&gt; readFile &quot;inputs&quot;</code>. But that's personal preference.</p>\n<p>And last but not least: Your choice to use the list monad to easily check all <span class=\"math-container\">\\$n\\$</span> combinations was really nice!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T20:49:53.057", "Id": "252950", "ParentId": "252927", "Score": "1" } }, { "body": "<h2>The library gives you all idioms you need</h2>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List\nmain=print.product.head.\n filter((2020==).sum).subsequences$\n [1721,979,366,299,675,1456]\n</code></pre>\n<p><a href=\"https://tio.run/##FcSxDsIgEADQ3a9wcKgJuRS0EAY2R//AdMD2TIlAkTu@H9M3vM3TF2PsPaSyVz4/PHt4BuJT8iG7UkNmKHVf28KwoV/hEyJjHQY1qtG5K1BLR2/CX8O8IF1e0igprLHiprVQ1gptJiHvk557/wM\" rel=\"nofollow noreferrer\" title=\"tio.run/#haskell\">Try it online!</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T18:16:22.780", "Id": "498732", "Score": "0", "body": "I want only sub-sequences of size N, so using `subsequences` and filter on the size seams a little overkill to me. But I didn't know this one, Thanks !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:12:53.893", "Id": "252995", "ParentId": "252927", "Score": "1" } } ]
{ "AcceptedAnswerId": "252950", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T11:58:02.360", "Id": "252927", "Score": "2", "Tags": [ "performance", "haskell", "community-challenge" ], "Title": "AdventOfCode Day 1 : find X element matching a criteria in haskell" }
252927
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252870/231235">A non-nested test_vectors_generator Function for arithmetic_mean Function Testing in C++</a> and <a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Besides <code>std::vector</code> test cases generated from <code>test_vectors_generator</code> template function, I am trying to implement <code>std::deque</code> and <code>std::list</code> test cases with <code>test_deques_generator</code> and <code>test_lists_generator</code> functions.</p> <p><strong>The usage description</strong></p> <p>Similar to the usage of <code>test_vectors_generator</code>, there are also four parameters in both <code>test_deques_generator</code> function and <code>test_lists_generator</code> function. The first one is a start iteration number of each element, the second one is a end iteration number of each element, the third one is a step size and the fourth one is the element count of each container.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation of <code>test_deques_generator</code> and <code>test_lists_generator</code> functions are as below.</p> <pre><code>namespace ts { //... template&lt;class T&gt; requires (!is_iterable&lt;T&gt;) constexpr auto test_deques_generator(T start, T end, T step, std::size_t element_count) { if (element_count == 1) { std::list&lt;std::deque&lt;T&gt;&gt; output(((end - start) / step) + 1); T i = 0; // incrementor std::for_each(output.begin(), output.end(), [&amp;](auto&amp; item) { i+=step; item = std::deque&lt;T&gt;{ i }; }); return output; } else { std::list&lt;std::deque&lt;T&gt;&gt; output{}; auto test_deques = test_deques_generator(start, end, step, element_count - 1); std::for_each(test_deques.begin(), test_deques.end(), [&amp;](const auto item) { for (T i = start; i &lt;= end; i += step) { auto new_element = item; new_element.push_back(i); output.push_back(new_element); } }); return output; } } template&lt;class T&gt; requires (!is_iterable&lt;T&gt;) constexpr auto test_lists_generator(T start, T end, T step, std::size_t element_count) { if (element_count == 1) { std::list&lt;std::list&lt;T&gt;&gt; output(((end - start) / step) + 1); T i = 0; // incrementor std::for_each(output.begin(), output.end(), [&amp;](auto&amp; item) { i+=step; item = std::list&lt;T&gt;{ i }; }); return output; } else { std::list&lt;std::list&lt;T&gt;&gt; output{}; auto test_deques = test_lists_generator(start, end, step, element_count - 1); std::for_each(test_deques.begin(), test_deques.end(), [&amp;](const auto item) { for (T i = start; i &lt;= end; i += step) { auto new_element = item; new_element.push_back(i); output.push_back(new_element); } }); return output; } } } </code></pre> <p>The used <code>is_iterable</code> concept:</p> <pre><code>template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; </code></pre> <p><strong>Test cases</strong></p> <ol> <li>Test cases of <code>test_deques_generator</code> and <code>test_lists_generator</code> template functions</li> </ol> <p>The <code>recursive_print</code> template function (refer to the previous question <a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>) is also used here. The output of <code>recursive_print(ts::test_deques_generator(1, 3, 1, 3));</code> is as follows.</p> <pre><code>Level 0: Level 1: 1 1 1 Level 1: 1 1 2 Level 1: 1 1 3 Level 1: 1 2 1 Level 1: 1 2 2 Level 1: 1 2 3 Level 1: 1 3 1 Level 1: 1 3 2 Level 1: 1 3 3 Level 1: 2 1 1 Level 1: 2 1 2 Level 1: 2 1 3 Level 1: 2 2 1 Level 1: 2 2 2 Level 1: 2 2 3 Level 1: 2 3 1 Level 1: 2 3 2 Level 1: 2 3 3 Level 1: 3 1 1 Level 1: 3 1 2 Level 1: 3 1 3 Level 1: 3 2 1 Level 1: 3 2 2 Level 1: 3 2 3 Level 1: 3 3 1 Level 1: 3 3 2 Level 1: 3 3 3 </code></pre> <p>The output of <code>recursive_print(ts::test_lists_generator(1, 3, 1, 3));</code> is as follows.</p> <pre><code>Level 0: Level 1: 1 1 1 Level 1: 1 1 2 Level 1: 1 1 3 Level 1: 1 2 1 Level 1: 1 2 2 Level 1: 1 2 3 Level 1: 1 3 1 Level 1: 1 3 2 Level 1: 1 3 3 Level 1: 2 1 1 Level 1: 2 1 2 Level 1: 2 1 3 Level 1: 2 2 1 Level 1: 2 2 2 Level 1: 2 2 3 Level 1: 2 3 1 Level 1: 2 3 2 Level 1: 2 3 3 Level 1: 3 1 1 Level 1: 3 1 2 Level 1: 3 1 3 Level 1: 3 2 1 Level 1: 3 2 2 Level 1: 3 2 3 Level 1: 3 3 1 Level 1: 3 3 2 Level 1: 3 3 3 </code></pre> <ol start="2"> <li>Test cases for <code>arithmetic_mean</code> template function</li> </ol> <p>With <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a> tool, the <code>std::deque</code> and <code>std::list</code> test cases for <code>arithmetic_mean</code> template function can be implemented as the following code.</p> <pre><code>BOOST_AUTO_TEST_CASE(test_deques_generator_char) { typedef char TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_int) { typedef int TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_short) { typedef short TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_long) { typedef long TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_long_long_int) { typedef long long int TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_unsigned_char) { typedef unsigned char TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_float) { typedef float TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_double) { typedef double TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_deques_generator_long_double) { typedef long double TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_deques_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_char) { typedef char TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_int) { typedef int TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_short) { typedef short TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_long) { typedef long TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_long_long_int) { typedef long long int TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_unsigned_char) { typedef unsigned char TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_float) { typedef float TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_double) { typedef double TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(test_lists_generator_long_double) { typedef long double TestType; TestType start_num = 1; TestType end_num = 50; TestType step_num = 1; for (auto&amp; each_test_vector : ts::test_lists_generator(start_num, end_num, step_num, 3)) { // Generate expected_value double expected_value = 0; for (auto&amp; each_item : each_test_vector) { expected_value += each_item; } expected_value = expected_value / static_cast&lt;double&gt;(each_test_vector.size()); BOOST_TEST(expected_value == arithmetic_mean(each_test_vector)); } BOOST_TEST(true); } </code></pre> <p><a href="https://godbolt.org/z/Y68nK3" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>Note: The compiling output from Godbolt is <code>&lt;Compilation failed&gt;</code> and the error message is <code>Killed - processing time exceeded</code>. This seems to be caused by <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a> tool is too large.</p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252870/231235">A non-nested test_vectors_generator Function for arithmetic_mean Function Testing in C++</a> and <a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The <code>std::deque</code> test cases and <code>std::list</code> test cases for <code>arithmetic_mean</code> template function have been added.</p> </li> <li><p>Why a new review is being asked for?</p> <p>I am trying to verify the correctness of <code>arithmetic_mean</code> template function as complete as possible, including various container, various element type. If there is any suggestion or possible improvement of these test cases, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Make the desired container type a template parameter</h1>\n<p>You are duplicating a lot of code, when the only thing that changes is the type of container that your are returning. You should make the container type a template parameter, for example like so:</p>\n<pre><code>template&lt;template&lt;class...&gt; class Container = std::vector, class T&gt; requires (!is_iterable&lt;T&gt;)\nconstexpr auto test_generator(T start, T end, T step, std::size_t element_count)\n{\n ...\n std::list&lt;Container&lt;T&gt;&gt; output;\n ...\n}\n</code></pre>\n<p>Then you can write:</p>\n<pre><code>auto data = test_generator&lt;std::deque&gt;(0, 10, 1, 3);\n</code></pre>\n<p>The template template parameter is not as flexible as you might think though, for example you cannot use a custom container class that is not a template itself, nor can you easily say you want to use a non-standard allocator for the container. You can also do what the STL does for container adapters, like <a href=\"https://en.cppreference.com/w/cpp/container/queue/queue\" rel=\"noreferrer\"><code>std::queue</code></a> for example:</p>\n<pre><code>template&lt;class T, class Container = std::vector&lt;T&gt;&gt; requires (!is_iterable&lt;T&gt;)\nconstexpr auto test_generator(T start, T end, T step, std::size_t element_count)\n{\n ...\n std::list&lt;Container&gt; output;\n ...\n}\n</code></pre>\n<p>Then you have to use it like so:</p>\n<pre><code>auto data = test_generator&lt;int, std::deque&lt;int&gt;&gt;(0, 10, 1, 3);\n</code></pre>\n<p>You can also add another <code>requires</code> check for the container type of course.</p>\n<h1>Consider a non-recursive implementation</h1>\n<p>Your implementation uses recursion; each recursion builds a list with an <code>element_count</code> of one less than the previous one. It doesn't look very efficient to me; every layer except the outer one builds a list that you discard afterwards. You can instead generate the desired list without using recursion at all, by just writing a cascaded counter (think of how a <a href=\"https://en.wikipedia.org/wiki/Tally_counter\" rel=\"noreferrer\">mechanical tally counter</a> works). Here is a possible implementation:</p>\n<pre><code>template&lt;class T, class Container = std::vector&lt;T&gt;&gt;\nconstexpr auto test_generator(T start, T end, T step, std::size_t element_count)\n{\n std::list&lt;Container&gt; output;\n\n Container counters;\n std::fill_n(std::back_inserter(counters), element_count, start);\n\n while (true) {\n output.push_back(counters);\n\n std::size_t n_reset{};\n for (auto &amp;counter: counters) {\n counter += step;\n\n if (counter &lt;= end)\n break;\n\n counter = start;\n if (++n_reset == element_count)\n return output;\n }\n }\n}\n</code></pre>\n<p>The only difference is that this implementation stores the values in the opposite order as your implementation, but that should not be too hard to change if necessary.</p>\n<h1>Consider writing a <code>std::generator</code> instead</h1>\n<p>What if, instead of a <code>std::list&lt;Container&lt;T&gt;&gt;</code>, you would want a <code>std::vector&lt;Container&lt;T&gt;&gt;</code>? What if you want to avoid having to store the whole result before being able to iterate through it? It would be even more flexible if you wrote a real generator function, like:</p>\n<pre><code>template&lt;class T, class Container = std::vector&lt;T&gt;&gt; requires(...)\nstd::generator&lt;Container&gt; test_generator(T start, T end, T step, std::size_t element_count)\n{\n Container counters;\n std::fill_n(std::back_inserter(counters), element_count, start);\n\n while (true) {\n co_yield counters;\n\n std::size_t n_reset{};\n for (auto &amp;counter: counters) {\n counter += step;\n\n if (counter &lt;= end)\n break;\n\n counter = start;\n if (++n_reset == element_count)\n return;\n }\n }\n}\n</code></pre>\n<p>And then you could use it like so:</p>\n<pre><code>for (auto vec: test_generator(1, 3, 1, 3)) {\n for (auto el: vec)\n std::cout &lt;&lt; el &lt;&lt; &quot; &quot;;\n std::cout &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p>You could also make this work for older versions of C++ if you make <code>test_generator</code> a <code>class</code> that has <code>begin()</code> and <code>end()</code> functions that return iterators.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T12:12:43.533", "Id": "498797", "Score": "0", "body": "Good review! I wonder if `std::ranges::iota_view` could be used here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T18:45:32.317", "Id": "252946", "ParentId": "252930", "Score": "4" } } ]
{ "AcceptedAnswerId": "252946", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T12:50:49.883", "Id": "252930", "Score": "6", "Tags": [ "c++", "recursion", "unit-testing", "boost", "c++20" ], "Title": "Non-nested std::deque and std::list Generator Function for arithmetic_mean Function Testing in C++" }
252930
<p>In <code>sort(arr)</code>, I want to sort an array. Children must be beneath their parent. And children of the same parent are sorted using <code>orderPos</code> value. I guess the complexity of this algorithm is quite high, is there a way to make it more performant for very long lists?<br /> (the language used here is typescript)</p> <pre><code> interface data { id:number; parentPK:number; orderPos:string; children: data[] } function sort(arr:data[]) { const sorted : data[] = []; let parent: data = {children: [] , id : 0 , orderPos:'0' , parentPK:0} ; let i = 1; // detect parent of all , parent pk is -1 , assumes theres only one root element whose parent id is -1 arr.forEach(x =&gt; { if (x.parentPK == -1) { parent = x; sorted.push(x); arr.splice(arr.indexOf(x), 1); return; } }); // root element is now first in the array // get root's children and place them beneath their parent (sorted by orderPos) let temp: data[] = arr .filter(x =&gt; x.parentPK === (parent &amp;&amp; parent.id)) .sort((a, b) =&gt; parseInt(a.orderPos, 10) - parseInt(b.orderPos, 10)); sorted.push(...temp); temp.forEach(x =&gt; parent.children.push(x)); while (i &lt; arr.length - 1) { // new parent parent = sorted[sorted.indexOf(parent) + 1]; // place children beneath parent temp = arr.filter(x =&gt; x.parentPK === (parent &amp;&amp; parent.id)).sort((a, b) =&gt; parseInt(a.orderPos, 10) - parseInt(b.orderPos, 10)); temp.forEach(x =&gt; parent.children.push(x)); sorted.splice(sorted.indexOf(parent) + 1, 0, ...temp); i++; } return sorted; } let array : data[] = [ { id: 4, parentPK : 1, orderPos:'100' , children:[]}, {id:1, parentPK : -1, orderPos:'1', children:[] }, { id:2, parentPK : 1, orderPos:'51',children:[] }, {id:3, parentPK : 2, orderPos:'1',children:[] }, {id:5, parentPK : 2, orderPos:'10',children:[] } ] let sortedArray = sort(array) console.log('sorted array : ',sortedArray.map(element =&gt; [element.id, element.parentPK,element.orderPos] )) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T19:40:29.520", "Id": "498628", "Score": "0", "body": "@CertainPerformance, My bad. I edited the code in the link you've provided , I will correct code in the question too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:39:12.093", "Id": "498646", "Score": "2", "body": "Thanks, the question makes good sense now!" } ]
[ { "body": "<ol>\n<li>The main improvement that can be made in the algorithm is recognizing that you can reduce more expensive sorting (and make the algorithm a lot easier to understand at a glance) by arranging the data into a structure indexed by the parent ID first. This operation is <code>O(n)</code>. (In contrast, sorting is <code>O(n log n)</code>) The data structure will look like:</li>\n</ol>\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>// This is not runnable, I'm just using a snippet to hide this long code\nconst itemsByParentId = {\n // Key: parent ID\n \"1\": [\n // Value: Array of children which have that ID as a parent (parentPK)\n {\n \"id\": 4,\n \"parentPK\": 1,\n \"orderPos\": \"100\",\n \"children\": []\n }, {\n \"id\": 2,\n \"parentPK\": 1,\n \"orderPos\": \"51\",\n \"children\": []\n }],\n \"2\": [{\n \"id\": 3,\n \"parentPK\": 2,\n \"orderPos\": \"1\",\n \"children\": []\n }, {\n \"id\": 5,\n \"parentPK\": 2,\n \"orderPos\": \"10\",\n \"children\": []\n }],\n \"-1\": [{\n \"id\": 1,\n \"parentPK\": -1,\n \"orderPos\": \"1\",\n \"children\": []\n }]\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Then:</p>\n<ol start=\"2\">\n<li><p>For each subarray (where all elements with the same parent are grouped together), sort it by <code>orderPos</code> (there's no getting around the <code>O(n log n)</code> complexity here)</p>\n</li>\n<li><p>Make a function that, given a parent, finds child elements in the data structure with that parent ID (<code>O(1)</code>), pushes them to the output array (<code>O(n)</code>), and recursively iterates over its children, depth-first, as the algorithm requires.</p>\n</li>\n</ol>\n<pre><code>function sort(arr: data[]) {\n const itemsByParentId: {\n [id: number]: Array&lt;data&gt;;\n } = {};\n // (1) Group by parent ID\n for (const item of arr) {\n if (!itemsByParentId[item.parentPK]) {\n itemsByParentId[item.parentPK] = [];\n }\n itemsByParentId[item.parentPK].push(item);\n }\n // (2) Sort each subarray\n for (const childrenArr of Object.values(itemsByParentId)) {\n childrenArr.sort((a, b) =&gt; Number(a.orderPos) - Number(b.orderPos));\n }\n // (3) Recursively add parents and their children, depth-first\n const sorted: data[] = [];\n const addParent = (parent: data) =&gt; {\n sorted.push(parent);\n if (!itemsByParentId[parent.id]) {\n return;\n }\n for (const child of itemsByParentId[parent.id]) {\n parent.children.push(child);\n addParent(child)\n }\n };\n addParent(itemsByParentId[-1][0]);\n return sorted;\n}\n</code></pre>\n<p>Live snippet of the compiled code:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sort(arr) {\n const itemsByParentId = {};\n for (const item of arr) {\n if (!itemsByParentId[item.parentPK]) {\n itemsByParentId[item.parentPK] = [];\n }\n itemsByParentId[item.parentPK].push(item);\n }\n for (const childrenArr of Object.values(itemsByParentId)) {\n childrenArr.sort((a, b) =&gt; Number(a.orderPos) - Number(b.orderPos));\n }\n const sorted = [];\n const addParent = (parent) =&gt; {\n sorted.push(parent);\n if (!itemsByParentId[parent.id]) {\n return;\n }\n for (const child of itemsByParentId[parent.id]) {\n parent.children.push(child);\n addParent(child);\n }\n };\n addParent(itemsByParentId[-1][0]);\n return sorted;\n}\nlet array = [{ id: 4, parentPK: 1, orderPos: '100', children: [] }, { id: 1, parentPK: -1, orderPos: '1', children: [] }, { id: 2, parentPK: 1, orderPos: '51', children: [] }, { id: 3, parentPK: 2, orderPos: '1', children: [] }, { id: 5, parentPK: 2, orderPos: '10', children: [] }];\nlet sortedArray = sort(array);\n\nconsole.log('sorted array : ',sortedArray.map(element =&gt; [element.id, element.parentPK,element.orderPos] ))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For a review of your existing code:</p>\n<p><strong>Put each statement on its own line</strong>, usually - this significantly improves readability and means that readers of the code don't have to scroll horizontally.</p>\n<p><strong>Indent when starting a new block, and indent when chaining methods off an expression above</strong> - for similar reasons to above, it makes it a lot easier to pick up on the logic at a glance. (Also use the same indentation across the same block.) There are many IDEs which will automatically format your code to adhere to some sort of standard like this. They're well worth using.</p>\n<p><strong>parentPK?</strong> Currently, an object's <code>parentPK</code> value links to another object's <code>id</code> value. I'm not sure what these objects represent in your wider script, but you might consider if it would be clearer if the <code>parentPK</code> property was named <code>parentID</code> or <code>idOfParent</code> instead, to make the link clearer.</p>\n<p><strong>Declare variables close to where they'll be used</strong>, to reduce cognitive overhead. For example, rather than:</p>\n<pre><code>let parent;\nlet i = 1;\n// many lines of code that doesn't reference i\nwhile (i &lt; arr.length - 1) {\n</code></pre>\n<p>you'll usually want to do</p>\n<pre><code>let parent;\n// many lines of code that doesn't reference i\nlet i = 1;\nwhile (i &lt; arr.length - 1) {\n</code></pre>\n<p>You could also consider a <code>for</code> loop, since you increment <code>i</code> at the end:</p>\n<pre><code>for (let i = 1; i &lt; arr.length - 1; i++) {\n</code></pre>\n<p><strong>Use strict equality</strong> with <code>===</code> and <code>!==</code> - avoid <code>!=</code> and <code>==</code>, since they have <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">strange coercion rules</a> a reader of the script should not have to have memorized in order to understand the logic.</p>\n<p><strong><code>return</code> does nothing in a <code>forEach</code> callback</strong> except terminate the <em>current</em> callback. It doesn't stop further callbacks from running. If you want to find the index of an element with a particular property in an array, use <code>findIndex</code>:</p>\n<pre><code>const rootIndex = arr.findIndex(item =&gt; item.parentPK === 1);\nsorted.push(arr[rootIndex]);\narr.splice(rootIndex, 1);\n</code></pre>\n<p><strong>Unnecessary comparison?</strong> I think <code>parent</code> will always exist, so the <code>.filter(x =&gt; x.parentPK === (parent &amp;&amp; parent.id))</code> check of <code>parent</code> first is superfluous. (If it might not exist, then you could simplify with optional chaining: <code>x.parentPK === parent?.id</code>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T23:08:03.590", "Id": "252958", "ParentId": "252937", "Score": "3" } } ]
{ "AcceptedAnswerId": "252958", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:18:10.260", "Id": "252937", "Score": "4", "Tags": [ "javascript", "algorithm", "sorting", "typescript", "complexity" ], "Title": "Performant Sort function for big arrays" }
252937
<p>I have programmed a A* Pathfinding algorithm in the Console. I would now like to know if there are any things that I could do to improve the time it takes, to find a path. Right now it takes around 80ms.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; </code></pre> <p>Those are the necessary Using directories</p> <pre><code>class Node { public bool wall; //Ist die Node eine Wand public bool start; //Ist die Node die Start-Node public bool end; //Ist die Node die End-Node public Node previous; //Vorherige Node / weg zu dieser Node public int x, y; // X und Y position public int g, h, f; //G = Distance from starting node / H = Distance from end node / F = G + H public Node(int x, int y) //Initialsierung { this.x = x; this.y = y; } } class Map { public int Width { get; private set; } public int Height { get; private set; } public Node start; public Node end; public Node[,] map; public readonly List&lt;Node&gt; searching = new List&lt;Node&gt;(); //Auch offene Liste gennant public readonly List&lt;Node&gt; searched = new List&lt;Node&gt;(); //Auch geschlossene Liste gennant public Map(int wi, int he) //Initialisierung { Width = wi; Height = he; map = new Node[wi, he]; for (int i = 0; i &lt; Width; i++) { for (int j = 0; j &lt; Height; j++) { map[i, j] = new Node(i, j); //Generisch Initialisiert } } } public void SetStart(int x, int y) //Setzt den Startpunkt { map[x, y].start = true; map[x, y].end = false; map[x, y].g = 0; start = map[x, y]; } public void SetEnd(int x, int y) //Setzt den Endpunkt { map[x, y].end = true; map[x, y].start = false; map[x, y].h = 0; end = map[x, y]; } public void SetWalls(List&lt;int[]&gt; walls) //Setzt die Wände an Ihre Positionen { for (int i = 0; i &lt; walls.Count; i++) { map[walls[i][0], walls[i][1]].wall = true; } } private void CalculateGCost(int x, int y, Node previous) //Errechnet die G Cost / die Distanz zu dem Startpunkt { int cost = 10; if (!map[x, y].start &amp;&amp; !map[x, y].end) { if (previous.x != x &amp;&amp; previous.y != y) //neu { cost += 4; } map[x, y].g = previous.g + cost; map[x, y].previous = previous; } } public void CalculateAllHCost() //Errechnet für die ganze Karte die H Cost / die Distanz zu dem Endpunkt { for (int i = 0; i &lt; Width; i++) { for (int j = 0; j &lt; Height; j++) { CalculateHCost(i, j); } } } private void CalculateHCost(int x, int y) //Errechnet für dieses eine Feld die H Cost / die Distanz zu dem Endpunkt { if (map[x, y] != end) { int xstep = Math.Abs(end.x - x); //Wie weit das ende von dem jetzigen Punkt in der X Achse entfernt ist int ystep = Math.Abs(end.y - y); //Wie weit das ende von dem jetzigen Punkt in der Y Achse entfernt ist map[x, y].h = (xstep + ystep) * 10; //Beides zusammen ist die Insgesamte entfernung } } private void CalculateFCost(int x, int y) =&gt; map[x, y].f = map[x, y].g + map[x, y].h; //F Cost ist H Cost + G Cost public void StartPathFinding() //Startet den Algorithmus { searching.Add(start); //Fügt die Start Node der offenen liste Searching hinzu. ShowMap(); Search(); } private void PathFinding(int x, int y) //Findet die benachbarten Nodes und fügt sie in die offene Liste hinzu, wenn sie dort nicht schon sind mit einem besseren vorgänger. { for (int i = -1; i &lt; 2; i++) { for (int j = -1; j &lt; 2; j++) { if ((x + i &gt;= 0 &amp;&amp; x + i &lt; Width) &amp; (y + j &gt;= 0 &amp;&amp; y + j &lt; Height)) { if (!map[x + i, y + j].wall) { if (map[x + i, y + j].g == 0 &amp; !map[x + i, y + j].start) { map[x + i, y + j].previous = map[x, y]; searching.Add(map[x + i, y + j]); } else if (map[x + i, y + j].g &gt; map[x, y].g + (i == 0 &amp;&amp; j == 0 ? 10 : 14)) { map[x + i, y + j].previous = map[x, y]; Node t = searched.Find(item =&gt; item.x == x + i &amp;&amp; item.y == y + j); searched.Remove(t); searching.Add(map[x + i, y + j]); } } } } } } private void Search() //Das Herzstück des Algorithmus, der die Anweisungen gibt, wie der Weg gefunden wird { Node node; do { foreach (var item in searching) //Für jede Node in der offenen Liste { CalculateGCost(item.x, item.y, item.previous); //Berechnet die G Cost / die Distanz zu dem Startpunkt CalculateFCost(item.x, item.y); //Berechnet die F Cost / die Distanz zu dem Startpunkt + die Distanz zu dem Endpunkt } int lowestF = searching.Min(c =&gt; c.f); //Sucht die niedrigste F Cost List&lt;Node&gt; nodes = searching.FindAll(c =&gt; c.f == lowestF); //Sucht in der offenen Liste nach den Nodes mit der niedrigsten F Cost int lowestH = nodes.Min(c =&gt; c.h); //Sucht unter den niedrigsten F Cost Nodes nach der niedrigsten H Cost node = nodes.Find(c =&gt; c.h == lowestH); //Wählt die Node mit der niedrigsten F und H Cost aus if (node == end) //Sollte die Node zufälligerweise die End-Node sein, wird die Suche nach der End-Node abgebrochen (weil sie gefunden wurde) { break; } PathFinding(node.x, node.y); //Sucht für die Node mit der niedrigsten F und H Cost die Nachbarn und fügt sie der offenen Liste hinzu searching.Remove(node); //Entfernt die Node von der offenen Liste searched.Add(node); //und fügt sie der geschlossenen Liste hinzu } while (searching.Count != 0 &amp;&amp; node != end); //Sollte die End-Node gefunden werden oder die offene Liste leer sein, ist ein fehler aufgetreten oder die End-Node wurde gefunden } public void ShowMap() //Zeigt die Karte an { for (int i = 0; i &lt; Width; i++) { for (int j = 0; j &lt; Height; j++) { Console.SetCursorPosition(i, j); if (map[i, j].start) { Console.ForegroundColor = ConsoleColor.Blue; //Makiert den Start mit einer blauen Schriftfarbe } else if (map[i, j].end) { Console.ForegroundColor = ConsoleColor.Yellow; //Makiert das Ende mit einer gelben Schriftfarbe } else { Console.ForegroundColor = ConsoleColor.Gray; //Alles andere wird mit einer grauen Schriftfarbe geschrieben } Console.WriteLine(map[i, j].wall | map[i, j].end | map[i, j].start ? &quot;X&quot; : &quot; &quot;); //Schreibt ein X wenn es sich bei dem Feld um eine Wand / das Ende / den Start handelt } } } public void ShowPath(Node node) //Malt den schnellsten Weg von der Start-Node zu der End-Node an. { System.Threading.Thread.Sleep(100); Console.SetCursorPosition(node.x, node.y); Console.BackgroundColor = ConsoleColor.White; Console.WriteLine(&quot;X&quot;); Console.BackgroundColor = ConsoleColor.Black; if (node != start) { ShowPath(node.previous); //Zeigt die nächste Node in der Reihe } else { Console.SetCursorPosition(0, Height + 1); //Die Reihe ist fertig, es wird an das ende der Map gesetzt um weiter Infos auf der Konsole auszugeben ohne die Karte zu überschreiben } } } class Program { static void Main(string[] args) { Console.ReadKey(true); int counter = 0; //Wieviele Linien es gibt int longestLine = 0; //Die Längste Linie string line; //Was die Linie beinhaltet List&lt;int[]&gt; walls = new List&lt;int[]&gt;(); //Die Wände, die durch die Input Text Datei gesetzt wurden int[] start = new int[2]; //Start-Node Koordinaten int[] end = new int[2]; //End-Node Koordinaten System.IO.StreamReader file = new System.IO.StreamReader(@&quot;PUT THE PATH TO YOUR TXT FILE HERE&quot;); while ((line = file.ReadLine()) != null) { if (line.Length &gt; longestLine) { longestLine = line.Length; //Guckt nach der längsten Linie (Die breite der Karte) } int counter2 = 0; foreach (char x in line) { if (x == 'X') //Sollte ein &quot;X&quot; angegeben sein, bedeutet das, dass dort eine Wand gestzt werden muss { walls.Add(new int[] { counter2, counter }); } else if (x == 'S') //Sollte ein &quot;S&quot; angegeben sein, bedeutet das, dass dort der Startpunkt / die Start-Node gesetzt werden muss { start[0] = counter2; start[1] = counter; } else if (x == 'E') //Sollte ein &quot;E&quot; angegeben sein, bedeutet das, dass dort der Endpunkt / die End-Node gesetzt werden muss { end[0] = counter2; end[1] = counter; } counter2++; } counter++; //Guckt nach der Anzahl der Linien (Die Höhe der Karte) } Map map = new Map(longestLine, counter); //Karte wird Initialisiert map.SetStart(start[0], start[1]); //Start wird gesetzt map.SetEnd(end[0], end[1]); //Ende wird gesetzt map.SetWalls(walls); //Wände werden gesetzt System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); map.CalculateAllHCost(); //Alle H Costs werden berechnet map.StartPathFinding(); //Der Algorithmus startet sw.Stop(); map.ShowMap(); map.ShowPath(map.end); Console.WriteLine(&quot;The Path took {0} ms to calculate&quot;, sw.ElapsedMilliseconds); foreach (Node node in map.searched) { Console.WriteLine(&quot;{0,-6} : G = {1,-4}| H = {2,-4}| F = {3,-4}&quot;, node.x + &quot;, &quot; + node.y, node.g, node.h, node.f); //Alle untersuchten Nodes werden einmal aufgeführt } Console.ReadKey(true); } } </code></pre> <p>Im sorry that all my Comments are in german, but the code should still be readable. Somewhere in the Main Method you have to Specify a Path to a txt file, that is used as the map.</p> <pre><code>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X X XX X X X X X XXX X X X X X X X X XXXXXXXXXXXXX XXXXXXX X XX XX X X X X XXX XX X X X X X X XXXX X X X E XXXXXX X X X X XXXXXXX X X XX XXXX X X X X X X X X X X X X XXXXXXXXXXXX X X X XXXXXXXXXXXX X X XXXX XXXX X X XXXXX X X X X XXXXXS X X X X X X X X X X X XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </code></pre> <p>you can copy this map into the txt file and youll have the same one as I do.</p> <p>I hope you can help me or give me feedback on the overall quality of the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T22:36:26.507", "Id": "498645", "Score": "0", "body": "1) `if-else-if-else-if` => `switch-case`. 2) 3 bools start, wall, end => `enum` with cell type. 3) split path and map logic, map should contain only cell types, nodes - dedicated for paths." } ]
[ { "body": "<p>I cannot comment on the pathfinding algorithm yet because i don't remember how it should work. But your ellapsed time capture includes <code>ShowMap</code> and that isnt part of the algorithm. <code>ShowMap</code>is the most time consuming part of your time measurement, so i suggest you remove that and re-measure.\nIf you havent yet, you can use the built in performance profiler in Visual Studio.</p>\n<p>This image shows the hot path in your application.\n<a href=\"https://i.stack.imgur.com/mxW83.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mxW83.png\" alt=\"enter image description here\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T15:24:14.170", "Id": "253960", "ParentId": "252939", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:51:10.053", "Id": "252939", "Score": "2", "Tags": [ "c#", "pathfinding" ], "Title": "A* Pathfinding Algorithm" }
252939
<p>I'm brand-new (just joined today) to code review and I am super excited to share my tic tac toe game code with all of you! Please let me know what I could fix up in my program to make it more efficient. Thanks in advance!</p> <p>P.S. I'm also not sure how to add an actual board to this game (an actual board rather than the way I have done here)</p> <p>Code:</p> <pre><code>import time # Initialize board board = {1: ' ', 2: ' ', 3: ' ', 4: ' ', 5: ' ', 6: ' ', 7: ' ', 8: ' ', 9: ' '} # Initialize variables count = 0 # counter to track number of filled slots winner = False # boolean to check if anyone won play = True # boolen to check if the game should continue tie = False # boolean to check if there is a tie curr_player = '' # variable to store current player identifier player_details = [] # list to store player identifier and marker # Helper functions def get_player_details(curr_player): &quot;&quot;&quot;Function to get player identifier and marker&quot;&quot;&quot; if curr_player == 'A': return ['B', 'O'] else: return ['A', 'X'] def print_board(): &quot;&quot;&quot;Function to print the board&quot;&quot;&quot; for i in board: print(i, ':', board[i], ' ', end='') if i % 3 == 0: print() def win_game(marker, player_id): &quot;&quot;&quot;Function to check for winning combination&quot;&quot;&quot; if board[1] == marker and board[2] == marker and board[3] == marker or \ board[4] == marker and board[5] == marker and board[6] == marker or \ board[7] == marker and board[8] == marker and board[9] == marker or \ board[1] == marker and board[4] == marker and board[7] == marker or \ board[2] == marker and board[5] == marker and board[8] == marker or \ board[3] == marker and board[6] == marker and board[9] == marker or \ board[1] == marker and board[5] == marker and board[9] == marker or \ board[3] == marker and board[5] == marker and board[7] == marker: print_board() time.sleep(1) print(&quot;Player&quot;, player_id, &quot;wins!&quot;) return True else: return False def insert_input(slot_num, marker): &quot;&quot;&quot;Function for capturing user inputs&quot;&quot;&quot; while board[slot_num] != ' ': print(&quot;spot taken, pick another no.&quot;) slot_num = int(input()) board[slot_num] = marker def play_again(): &quot;&quot;&quot;Function to check if player wants to play again&quot;&quot;&quot; print(&quot;Do you want to play again?&quot;) play_again = input() if play_again.upper() == 'Y': for z in board: board[z] = ' ' return True else: print(&quot;Thanks for playing. See you next time!&quot;) return False # Main program while play: print_board() player_details = get_player_details(curr_player) curr_player = player_details[0] print(&quot;Player {}: Enter a number between 1 and 9&quot;.format(curr_player)) input_slot = int(input()) # Inserting 'X' or 'O' in desired spot insert_input(input_slot, player_details[1]) count += 1 # Check if anybody won winner = win_game(player_details[1], curr_player) if count == 9 and not winner: print(&quot;It's a tie!!&quot;) tie = True print_board() # Check if players want to play again if winner or tie: play = play_again() if play: curr_player = '' count = 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T18:52:52.553", "Id": "498619", "Score": "0", "body": "Most of the points I would love to review can be found [here](https://codereview.stackexchange.com/questions/252681/tic-tac-toe-game-in-python-beginner/252720#252720) do check it out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T18:57:47.947", "Id": "498621", "Score": "0", "body": "@theProgrammer thanks, ill check it out ASAP" } ]
[ { "body": "<p>Your <code>board</code> dictionary can be simplified from</p>\n<pre><code>board = {1: ' ', 2: ' ', 3: ' ',\n 4: ' ', 5: ' ', 6: ' ',\n 7: ' ', 8: ' ', 9: ' '}\n</code></pre>\n<p>to a <code>dict</code> comprehension:</p>\n<pre><code>board = {n: ' ' for n in range(1, 10)}\n</code></pre>\n<p>Your <code>win_game</code> function can be greatly simplified, from</p>\n<pre><code>def win_game(marker, player_id):\n &quot;&quot;&quot;Function to check for winning combination&quot;&quot;&quot;\n if board[1] == marker and board[2] == marker and board[3] == marker or \\\n board[4] == marker and board[5] == marker and board[6] == marker or \\\n board[7] == marker and board[8] == marker and board[9] == marker or \\\n board[1] == marker and board[4] == marker and board[7] == marker or \\\n board[2] == marker and board[5] == marker and board[8] == marker or \\\n board[3] == marker and board[6] == marker and board[9] == marker or \\\n board[1] == marker and board[5] == marker and board[9] == marker or \\\n board[3] == marker and board[5] == marker and board[7] == marker:\n\n print_board()\n time.sleep(1)\n print(&quot;Player&quot;, player_id, &quot;wins!&quot;)\n return True\n\n else:\n return False\n</code></pre>\n<p>to</p>\n<pre><code>def win_game(marker, player_id):\n &quot;&quot;&quot;Function to check for winning combination&quot;&quot;&quot;\n if board[1] == board[2] == board[3] == marker or \\\n board[4] == board[5] == board[6] == marker or \\\n board[7] == board[8] == board[9] == marker or \\\n board[1] == board[4] == board[7] == marker or \\\n board[2] == board[5] == board[8] == marker or \\\n board[3] == board[6] == board[9] == marker or \\\n board[1] == board[5] == board[9] == marker or \\\n board[3] == board[5] == board[7] == marker:\n print_board()\n time.sleep(1)\n print(&quot;Player&quot;, player_id, &quot;wins!&quot;)\n return True\n return False\n</code></pre>\n<p>You see, the <code>else</code> statement is not necessary, as the <code>return</code> statement will make the program jump out of the function. Also, as you can probably tell,</p>\n<pre><code>a == 1 and b == 1 and c == 1\n</code></pre>\n<p>is the same as</p>\n<pre><code>a == b == c === 1\n</code></pre>\n<hr />\n<p>The unnecessary <code>else</code> statement applies to your other functions as well</p>\n<p>For <code>get_player_details</code>:</p>\n<pre><code>def get_player_details(curr_player):\n &quot;&quot;&quot;Function to get player identifier and marker&quot;&quot;&quot;\n if curr_player == 'A':\n return ['B', 'O']\n else:\n return ['A', 'X']\n</code></pre>\n<p>to</p>\n<pre><code>def get_player_details(curr_player):\n &quot;&quot;&quot;Function to get player identifier and marker&quot;&quot;&quot;\n if curr_player == 'A':\n return ['B', 'O']\n return ['A', 'X']\n</code></pre>\n<p>For <code>play_again</code>:</p>\n<pre><code>def play_again():\n &quot;&quot;&quot;Function to check if player wants to play again&quot;&quot;&quot;\n print(&quot;Do you want to play again?&quot;)\n play_again = input()\n\n if play_again.upper() == 'Y':\n for z in board:\n board[z] = ' '\n return True\n else:\n print(&quot;Thanks for playing. See you next time!&quot;)\n return False\n</code></pre>\n<p>to</p>\n<pre><code>def play_again():\n &quot;&quot;&quot;Function to check if player wants to play again&quot;&quot;&quot;\n print(&quot;Do you want to play again?&quot;)\n play_again = input()\n if play_again.upper() == 'Y':\n for z in board:\n board[z] = ' '\n return True\n print(&quot;Thanks for playing. See you next time!&quot;)\n return False\n</code></pre>\n<p>In your <code>print_board</code> function, you can increase the readability of your print statement with a formatted string. Using <code>not</code> instead of <code>== 0</code> is considered more pythonic:</p>\n<pre><code>def print_board():\n &quot;&quot;&quot;Function to print the board&quot;&quot;&quot;\n for i in board:\n print(i, ':', board[i], ' ', end='')\n if i % 3 == 0:\n print()\n</code></pre>\n<p>to</p>\n<pre><code>def print_board():\n &quot;&quot;&quot;Function to print the board&quot;&quot;&quot;\n for i in board:\n print(f'{i} : {board[i]} ', end='')\n if not i % 3:\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:15:02.070", "Id": "498603", "Score": "0", "body": "thanks. this is exactly the kind of help I was looking for!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T09:53:38.950", "Id": "498691", "Score": "0", "body": "@Chocolate Maybe this is better:\n`return ['B', 'O'] if curr_player == 'A' else ['A', 'X']`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:20:14.887", "Id": "498729", "Score": "0", "body": "While removing such `else`s, there's an argument to keep them for better code readability. This is purely a personal preference, though." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T17:11:54.260", "Id": "252942", "ParentId": "252940", "Score": "7" } }, { "body": "<p>It's good to separate concerns.</p>\n<p><code>play_again()</code> currently does all of the following:</p>\n<ul>\n<li>collects input.</li>\n<li>decides if it is 'Y' or not 'Y'.</li>\n<li>clears the board</li>\n<li>displays a goodbye</li>\n<li>tells the caller whether the player wants to restart.</li>\n</ul>\n<p>Meanwhile, the caller (the main loop):</p>\n<ul>\n<li>decides whether to continue (the while loop)</li>\n<li>resets the current player</li>\n</ul>\n<p>I would simplify <code>play_again()</code> to just collect input and return whether it is a Yes or No. (I would make it handle &quot;y&quot; as well as &quot;Y&quot;, and maybe loop back and ask again if they don't give an answer that it Y, y, N, n, Q, or q.)</p>\n<p>I would move the code to clear the board and reset the current player so they were next to each other, and not in <code>play_again()</code>.</p>\n<hr />\n<p>Perhaps later, as you understand the concepts of Object Orientation, I would move much of the code into a <code>Board</code> class - it would understand win conditions, how to represent the board as a string, and how to reset the board (or maybe main() would just throw away the instance and construct a new one), without dealing with any of the input or output.</p>\n<hr />\n<blockquote>\n<p>P.S. I'm also not sure how to add an actual board to this game (an actual board rather than the way I have done here)</p>\n</blockquote>\n<p>If that means to have a graphical user interface, rather than the pure text, then it isn't possible just with Python's standard libraries. You would need to find one of the many GUI frameworks that work with Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T15:21:05.710", "Id": "498723", "Score": "0", "body": "Thank you for this, will make sure to use your suggestions!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T03:16:12.817", "Id": "252968", "ParentId": "252940", "Score": "1" } }, { "body": "<p>All this looking up markers and identifiers calls out for simplification. Just call the players 'X' and 'O' rather than 'A' and 'B'.</p>\n<p>You don't need to check all the possible win conditions; if there is a win, it must have involved the current play.</p>\n<p>Much of your booleans are unnecessary; rather than setting the boolean to the result of a function, then exiting if True, just exit if the function returns True. Then move the win announcement out of the function checking for a win.</p>\n<p>The function name <code>win_game</code> is written as verb, when it's actually an interrogative. <code>check_win</code> is clearer.</p>\n<p>The line <code>print(&quot;Player&quot;, player_id, &quot;wins!&quot;)</code> doesn't put spaces in. It will print <code>PlayerAwins!</code> or <code>PlayerBwins!</code>.</p>\n<pre><code>def print_board():\n &quot;&quot;&quot;Function to print the board&quot;&quot;&quot;\n for i in board:\n print(i, ':', board[i], ' ', end='')\n if i % 3 == 0:\n print()\n\n\ndef check_win(player, move):\n &quot;&quot;&quot;Function to check for winning combination&quot;&quot;&quot;\n for vertical in range(4):\n if board[(3*vertical + move - 1)%9+1] != player:\n break\n if vertical == 3:\n return True\n for horizontal in range(4):\n square = move + horizontal\n if (square-1)//3 &gt; (move-1)//3:\n square = square - 3\n if board[square] != player:\n break\n if horizontal == 3:\n return True\n #if you don't understand what's going on in the \n # above lines, work through a few cases\n if ( (board[1] == board[5] == board[9] == player) or\n (board[3] == board[5] == board[7] == player) ):\n return True\n return False\n\n\ndef insert_input(slot_num, player):\n &quot;&quot;&quot;Function for capturing user inputs&quot;&quot;&quot;\n while board[slot_num] != ' ':\n print(&quot;spot taken, pick another no.&quot;)\n slot_num = int(input())\n board[slot_num] = player\n\n\ndef play_again():\n &quot;&quot;&quot;Function to check if player wants to play again&quot;&quot;&quot;\n print(&quot;Do you want to play again?&quot;)\n play_again = input()\n\n if play_again.upper() == 'Y':\n for z in board:\n board[z] = ' '\n return True\n else:\n print(&quot;Thanks for playing. See you next time!&quot;)\n return False\n\n\n# Main program\ncount = 0 \nwhile True:\n count +=1\n print_board()\n\n print(&quot;Player {}: Enter a number between 1 and 9&quot;.format(curr_player))\n input_slot = int(input())\n\n # Inserting 'X' or 'O' in desired spot\n insert_input(input_slot, player)\n\n\n # Check if anybody won\n if check_win(player, move):\n #If you really want to keep the names A and B, \n #insert the following line:\n #player = {'O':'B', 'X','A'}[player]\n print_board()\n time.sleep(1)\n print(&quot;Player &quot;, player, &quot; wins!&quot;)\n if play_again():\n curr_player = 'X'\n count = 0\n else break \n if count == 9:\n print(&quot;It's a tie!!&quot;)\n print_board()\n if play_again():\n curr_player = 'X'\n count = 0\n else break \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T15:26:49.610", "Id": "498725", "Score": "0", "body": "Thanks @Acccumulation for your insight on this! Will make sure to use your suggestions as well " } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T06:34:52.543", "Id": "252972", "ParentId": "252940", "Score": "1" } } ]
{ "AcceptedAnswerId": "252942", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T16:53:15.383", "Id": "252940", "Score": "10", "Tags": [ "python", "performance", "beginner", "python-3.x", "tic-tac-toe" ], "Title": "Tic Tac Toe Game using Python" }
252940
<p>I'm not sure what <code>%s</code> means in Python strings. I came across this line of code somewhere a while ago: <code>print(&quot;On your journey to %s, you drove at an average speed of %s miles per hour.&quot; % (where, speed))</code> and I just came across a question with the following line: <code>print(&quot;The&quot;, count, &quot;prime number is %s&quot; %index)</code>. And how come neither of the above examples had to use <code>+</code> to combine the strings and integers (presumably) and how come they didn't use <code>str</code> to covert the integers (again presumably...could be floats) to string format?? I am SO confused...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T23:40:48.143", "Id": "498650", "Score": "0", "body": "Welcome to Code Review! Unfortunately this question is _off-topic_ because this site is for reviewing **working** code. Please [take the tour](https://codereview.stackexchange.com/tour) and read up at our [help center](https://codereview.stackexchange.com/help/on-topic). When you have working code then feel free to [edit] the post to include it for a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T23:42:55.137", "Id": "498654", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Sorry about that. But thanks for the heads-up." } ]
[ { "body": "<p>As already said, this question is <em>off-topic</em> but it's not a stupid question, so don't get discouraged. This question isn't applicable to this platform as it is not an issue you're having with your code. If you could provide your code and then ask what <code>%s</code> means, it would make more sense, as I can see what you are trying to do (and if you're using %s correctly).</p>\n<p>But for clarity's sake, <code>%s</code> in Python is really just used for inserting and possibly formatting a string (it saves time with <strong>casting</strong> and <strong>concatenating</strong>; two very important terms!).</p>\n<p>The following links may provide more helpful and thorough insights into <code>%s</code>:</p>\n<ul>\n<li><p><a href=\"https://careerkarma.com/blog/python-what-does-s-mean/\" rel=\"nofollow noreferrer\">https://careerkarma.com/blog/python-what-does-s-mean/</a></p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/997797/what-does-s-mean-in-a-python-format-string\">https://stackoverflow.com/questions/997797/what-does-s-mean-in-a-python-format-string</a></p>\n</li>\n</ul>\n<p>Keep in mind: this platform is for reviewing and sorting problems for <strong>code</strong>. No surprises, as the first section of the link is &quot;<em>codereview</em>.stackexchange.com&quot;</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T00:04:19.317", "Id": "498656", "Score": "0", "body": "Thank you for your time. I will make sure to look over the website in order to fully understand the meaning of %s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T01:35:06.400", "Id": "498657", "Score": "0", "body": "@pgrm_geek If you need help with non-working code or if you have questions, stack overflow is good. However, you should be warned that people are a lot meaner over there." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T23:58:55.627", "Id": "252962", "ParentId": "252959", "Score": "-1" } } ]
{ "AcceptedAnswerId": "252962", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T23:17:01.197", "Id": "252959", "Score": "-4", "Tags": [ "python", "strings" ], "Title": "What does %s mean in a python strings?" }
252959
<p>I tried implementing a state machine in C.<br /> This is for a Stratosphere Balloon and I wanted to use a state machine to make it better.<br /> This will be later implemented in ARM CMSIS.</p> <p>The state function doesn't really do anything yet. And the <code>while(1)</code> loops will be replaced by the <code>sbRepeat</code> transition code.</p> <pre><code>#ifndef _SB_FSM #define _SB_FSM /** * Transition codes * used to navigate from current to the next state */ typedef enum state_transitions { sbStartupTrans, sbSelfTestTrans, sbStartupOK, sbErr, sbSelfTestOK, sbFlightStartOK, sbAscendOK, sbDescendOK, sbRecoveryOK, sbEndOK, sbAny, sbRepeat }sbTransition; /** * State Definitions */ typedef enum states { sbIdle, sbSelfTest, sbStartup, sbFlightStart, sbAscend, sbDescend, sbRecovery, sbError, sbEnd, } sbState; /** * State Transition definitions * when it encounter &lt;trans&gt; move to &lt;state&gt; State */ typedef struct state_trans { sbTransition trans; sbState state; }sbStateTrans; /** * State Definition * @param name - Name of the State * @param func - Function Handler of the State * @param transitions - Allowed Transition definitions */ typedef struct state_def { char name[255]; sbTransition (*func)(void); sbStateTrans transitions[16]; }sbStateDef; sbTransition sbIdleState(void); sbTransition sbSelfTestState(void); sbTransition sbStartupState(void); sbTransition sbFlightStartState(void); sbTransition sbAscendState(void); sbTransition sbDescendState(void); sbTransition sbRecoveryState(void); sbTransition sbErrorState(void); sbTransition sbEndState(void); sbState fetchNextState(sbState, sbTransition); /** * Structure: {&lt;state name&gt;, &lt;function pointer&gt; , transitions{{&lt;encounters&gt; -&gt; &lt;next state&gt;}} */ static sbStateDef states[9] = { {&quot;Idle&quot;, sbIdleState, {{sbStartupTrans, sbStartup}, {sbSelfTestTrans, sbSelfTest}}}, {&quot;Self Test&quot;, sbSelfTestState, {{sbStartupTrans, sbStartup}, {sbErr, sbIdle}}}, {&quot;Startup&quot;, sbStartupState, {{sbStartupOK, sbFlightStart}, {sbErr, sbIdle}}}, {&quot;Flight Start&quot;, sbFlightStartState, {{sbFlightStartOK, sbAscend}, {sbErr, sbError}}}, {&quot;Ascend&quot;, sbAscendState, {{sbAscendOK, sbDescend}, {sbErr, sbError}, {sbRepeat, sbAscend}}}, {&quot;Descend&quot;, sbDescendState, {{sbDescendOK, sbRecovery}, {sbErr, sbError}, {sbRepeat, sbDescend}}}, {&quot;Recovery&quot;, sbRecoveryState, {{sbRecoveryOK, sbEnd}, {sbErr, sbError}, {sbRepeat, sbRecovery}}}, {&quot;Error&quot;, sbErrorState, {{sbRepeat, sbError}}}, {&quot;End&quot;, sbEndState, {}} }; #endif </code></pre> <p>This is the .c file</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &quot;sb_fsm.h&quot; /** * Idle state to take commands * @returns sbTransition - Transition code */ sbTransition sbIdleState(void) { int err = 1; while(1) { char *input = malloc(255 * sizeof(char)); printf(&quot;Idle State\n&quot;); printf(&quot;&gt; &quot;); scanf(&quot;%s&quot;, input); getc(stdin); if (strcmp(input, &quot;startup&quot;) == 0){ return sbStartupTrans; } else if (strcmp(input, &quot;selftest&quot;) == 0) { return sbSelfTestTrans; } else if (strcmp(input, &quot;help&quot;) == 0) { printf(&quot;&lt;startup&gt; : Initialize the startup procedure\n&quot;); printf(&quot;&lt;selftest&gt; : Initialize module check\n&quot;); continue; } printf(&quot;\ntype 'help' to get the commands\n&quot;); } } /** * Self Test or Self Diagnosis Check to test if all the * components are working well * &lt;br&gt; * Returns &lt;sbSelfTestOK&gt; on success, * &lt;sbErr&gt; on failure * @returns sbTransition - Transition code */ sbTransition sbSelfTestState(void) { int err = 0; while (1) { printf(&quot;Self Test\n&quot;); if (err == 0) { return sbStartupTrans; } else if (err == 1) { return sbErr; } } } sbTransition sbStartupState(void) { int err = 0; while (1) { printf(&quot;Startup State\n&quot;); if (err == 0) { return sbStartupOK; } else { return sbErr; } } } sbTransition sbFlightStartState(void) { int err = 0; while (1) { printf(&quot;Flight Start\n&quot;); if (err == 0) { return sbFlightStartOK; } else { return sbErr; } } } sbTransition sbAscendState(void) { int err = 0; printf(&quot;Ascend State\n&quot;); if (err == 0) { return sbAscendOK; } else if (err == 1) { return sbRepeat; } else { return sbErr; } } sbTransition sbDescendState(void) { int err = 0; while (1) { printf(&quot;Descend State\n&quot;); if (err == 0) { return sbDescendOK; } else { return sbErr; } } } sbTransition sbRecoveryState(void) { int err = 0; while (1) { printf(&quot;Recovery State\n&quot;); if (err == 0) { return sbRecoveryOK; } else { return sbErr; } } } sbTransition sbErrorState(void) { int err = 0; while (1) { printf(&quot;Error State\n&quot;); return sbAny; } } sbTransition sbEndState(void) { printf(&quot;Accepted\n&quot;); char *input = malloc(255 * sizeof(char)); while(1) { printf(&quot;&gt; &quot;); scanf(&quot;%s&quot;, input); getc(stdin); if (strcmp(input, &quot;restart&quot;) == 0) { return sbEndOK; } } return sbErr; } sbState fetchNextState(sbState state, sbTransition ret) { int i,j; i = 0; while (i &lt; sizeof(states[state].transitions)/sizeof(sbStateTrans)) { if (ret == states[state].transitions[i].trans) { return states[state].transitions[i].state; } i++; } return sbError; } </code></pre> <p>This is the main.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;sb_fsm.h&quot; #include &lt;unistd.h&gt; void delay(unsigned long ms); int main(void) { sbState curr_state = sbIdle; sbTransition (*run_func)(void); while (1) { sbTransition ret = states[curr_state].func(); curr_state = fetchNextState(curr_state, ret); delay(500); } return 0; } void delay(unsigned long ms) { usleep(ms * 1000); } </code></pre> <p>Hoping on getting some advice on how to improve it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T07:43:21.143", "Id": "498686", "Score": "0", "body": "I'm assuming \"ARM CMSIS\" means a bare metal Cortex M embedded system with microcontroller? Or is this for a high end, PC-like ARM?" } ]
[ { "body": "<p>Implementing state machines with a table with function pointers is very common. The table should however be read-only and preferably stored in flash. This does however seem to be some PC-like ARM with Linux?</p>\n<p>The design with a centralized state transition decision-maker is particularly important and your program is well-written there. Picking next state, based on the result from the previous, should be done at one single place in the program, not in each individual state (&quot;stateghetti programming&quot;). With a centralized decision-maker, you can also easily implement a safe mode for the program where it goes upon certain critical errors.</p>\n<p>Regarding the state machine/array:</p>\n<ul>\n<li><code>typedef enum state_transitions</code> - the enum tag <code>state_transitions</code> is useless and can be removed.</li>\n<li>At the end of <code>sbState</code> enum, include a member for size such as <code>sbStates</code> or what you wish to call it. Then change the <code>states[9]</code> to <code>states[]</code> and <code>static_assert(sizeof states/sizeof *states == sbStates, &quot;states data inconsistent&quot;);</code> to guarantee data integrity.</li>\n<li>Assuming <code>char name[255];</code> will never change, then 255 bytes per array item is wasteful. A <code>char*</code> to a string literal will save loads of read-only memory over this.</li>\n<li><code>states</code> should be <code>const</code>.</li>\n</ul>\n<p>So you could instead have something like:</p>\n<pre><code>static const sbStateDef states[] = {\n [sbIdle] = {&quot;Idle&quot;, sbIdleState, {{sbStartupTrans, sbStartup}, {sbSelfTestTrans, sbSelfTest}}},\n [sbSelfTest] = {&quot;Self Test&quot;, sbSelfTestState, {{sbStartupTrans, sbStartup}, {sbErr, sbIdle}}},\n ...\n};\nstatic_assert(sizeof states/sizeof *states == sbStates, &quot;states data inconsistent&quot;); // C11\n</code></pre>\n<p>You can do similar with <code>transitions</code>. Overall, designated array initializers like above, that make use of the enum is strongly recommended for readability and data integrity.</p>\n<p>General comments:</p>\n<ul>\n<li>Never define variables in header files, ever. If you ever find yourself with the need to define a variable in a header, something has gone fundamentally wrong in your program design. In this case you could probably put both the allocation of the state machine and the calling code in main.c.</li>\n<li>All the <code>while(1)</code> loops mean that you can't change states... I'm assuming this is just place-holders? Such loops are unacceptable in a hosted multi-process system such as Linux. You should probably consider porting this to pthreads and put the thread to sleep when it isn't working.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:31:56.270", "Id": "498747", "Score": "0", "body": "Thank you very very much for the review and the advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:46:33.633", "Id": "498751", "Score": "0", "body": "I will use the ARM Cortex M Boards for my project and many of the things will be reworked later on.\nThis is indeed very very helpful to get used to design patterns. I just got into C and this is very useful to better know more professional design patterns.\n\nI will change the code accordingly.\nThe `while(1);` is indeed just a placeholder.\nespecially the advice with the `state` array is very helpful. I did not really know if this is good coding style.\n\nWould you say that the general design is good?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T21:06:10.113", "Id": "498753", "Score": "0", "body": "And really thanks for taking time and writing a review and advice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T07:32:24.890", "Id": "498776", "Score": "0", "body": "@SL7Bot This code that you have written can't be used in bare metal microcontrollers - you have written code for a PC. So my review is assuming that a PC will be used. The advise to use pthreads is made assuming you'd use Linux." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T20:19:04.763", "Id": "498978", "Score": "0", "body": "Yeah many of the used functions are just as placeholders, like the scanf()\nI will then rework the whole thing to fit in onto a microcontroller" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T08:40:47.553", "Id": "252975", "ParentId": "252960", "Score": "1" } } ]
{ "AcceptedAnswerId": "252975", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-02T23:28:37.387", "Id": "252960", "Score": "1", "Tags": [ "beginner", "c", "state-machine" ], "Title": "Simple state machine" }
252960
<p>UPDATE: I have added:</p> <ul> <li>a play-again option</li> <li>score keeping thing</li> <li>difficulty levels</li> </ul> <p>**(but I still need help with the functions part).</p> <p>I don't feel it's necessary to explain what my code does, as it is pretty self-explanatory. I have the entire program completed, but I need to put some of the components of the program into functions. I don't know how to do this. I also need to add a play again option (I have done this before, but for some reason this particular code isn't working...).</p> <pre><code>import random #variables: score = 0 play = True while play: while True: try: difficulty = int(input(&quot;Give me a number between 1 and 3 (these are the difficulty levels) \n\n 1 = easy \n 2 = medium \n 3 = hard \n\n&quot;)) except: print(&quot;This is not a number!&quot;) continue if difficulty &gt; 3 or difficulty &lt; 1: print(&quot;That's an invalid input, please re-enter your number&quot;) continue break number = random.randint(1, 10 * difficulty) attempts = 0 guess = 0 while guess != number and attempts &lt; 3: attempts += 1 print(&quot;attempt number &quot; + str(attempts)) while True: try: guess = int(input(&quot;Guess what number I am thinking of &quot;)) except: print(&quot;That's not a number!&quot;) continue if guess &gt; 10 * difficulty or guess &lt; 1: print(&quot;That's an invalid input, please re-enter your number.&quot;) continue break if guess == number: print(&quot;You guessed it correct!&quot;) score += 1 elif abs(guess - number) == 1: print(&quot;You're hot on the trail!&quot;) elif abs(guess - number) &lt;= 3: print(&quot;You're getting warmer...&quot;) else: print(&quot;You're freezing cold!!&quot;) if attempts == 3 and guess != number: print(&quot;Oops! You've run out of guesses!&quot;) print(&quot;The number I was thinking of was &quot; + str(number) + &quot;.&quot;) print(&quot;Your final score is &quot; + str(score)) text = input(&quot;If you want to play again, type 'yes' &quot;) if text != &quot;yes&quot;: play = False print(&quot;Ok, thank you for playing!&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:12:50.800", "Id": "498728", "Score": "0", "body": "`I have done this before, but for some reason this particular code isn't working...` Does the code work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:04:47.187", "Id": "498743", "Score": "0", "body": "I've actually got it figured out @theProgrammer but thanks for taking the time to look at my question!" } ]
[ { "body": "<p>Here are a few quick comments and suggestions to start with. Rather than rewriting everything, I will start from what you wrote.</p>\n<ul>\n<li><p>The try/except statements at the bottom make no sense. A try is used to attempt to execute one or more lines of code that might trigger an exception (e.g. dividing by zero, trying to access an array element that is out of range, etc.). A break statement will never cause an exception, so the continue statement will never be executed. It behaves as if you just said &quot;break&quot; without the try/except and without the continue.</p>\n</li>\n<li><p>Ignoring the above issue, your code is written to make two passes through the loop (attempts == 1 and attempts == 2). If you were hoping to go through the loop 3 times, then you should start with attempts = 0 or else use attempts &lt;= 3 in the while statement. In all, if your try/except statement would be removed, you would ask for the number 6 times (3 times in each loop, 2 times through the loop).</p>\n</li>\n<li><p>There is a concept called DRY (Don't Repeat Yourself). When you see repeated code, that is where a function makes sense. You take out the repeated code, put it in a function, and then call the function from the main loop. I extracted the code that was repetitive into a function. You will have to pass the number into the function so that it can tell if the user was correct. Then, you want the function to return whether the guess was correct.</p>\n</li>\n<li><p>Next, rewrite your main body to take advantage of the function. I will change your WHILE loop into two separate loops: the outer loop to see if the user wants to play a game, and the inner loop to give them three attempts to get it correct. I'll do it in a mix of pseudocode (ALL CAPS) and real Python, leaving the final details for you.</p>\n</li>\n</ul>\n<pre><code>\n import random\n\n def get_user_guess(number):\n guess = int(input(\"Guess what number I am thinking of: \"))\n if guess == number:\n correct_guess = True\n print(\"You guessed it correct!\")\n elif guess > number:\n correct_guess = False\n print(\"Guess lower!\")\n else:\n correct_guess = False\n print(\"Guess higher!\")\n return correct_guess\n\n\n while True:\n\n number = random.randint(1, 10)\n guessed_correctly = False\n\n # This loop will give the user three attempts, but break out of the loop if they guess correctly\n for attempt in range(1, 4):\n PRINT ATTEMPT NUMBER\n if get_user_guess(number): # This is the same as \"if get_user_guess(number) is True\"\n guessed_correctly = True\n break\n \n if not guessed_correctly:\n print(\"Sorry...)\n \n ASK USER IF THEY WANT TO PLAY AGAIN\n IF NO:\n break\n # otherwise, it will go through the loop again with a new game\n</code></pre>\n<p>There are a few other potential changes, but these are the major ones.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T19:56:09.417", "Id": "498741", "Score": "0", "body": "thank you for this! will make sure ot use your suggestions to make my program better!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T03:46:32.050", "Id": "252970", "ParentId": "252964", "Score": "1" } }, { "body": "<p>I'm not <em>exactly</em> sure what you're asking but with my best guess, I'll give it a try.</p>\n<p>What you should be turning into functions (in my opinon)</p>\n<ol>\n<li><p>&quot;bad&quot; inputs (such as 'a', 'b' etc. or '%', '*' etc.); error trapping algorithm chunk\nof code into a function.</p>\n</li>\n<li><p><code>&quot;You're hot on the trail&quot;</code> etc.) block of code can also be converted\nto a function.</p>\n</li>\n</ol>\n<p>My <strong>biggest</strong> concern with your program is the following:</p>\n<p><code>if text != &quot;yes&quot;: </code> then <code> play = False</code> - Why <em>just</em> &quot;yes&quot;?? <strong>Why not</strong> &quot;yes&quot; <em>and</em> &quot;Yes&quot;?</p>\n<p>What if the user inputs &quot;Yes&quot; - with a capital &quot;Y&quot; instead of &quot;yes&quot; - with a lower-case &quot;y&quot;? (I tried this by the way, and this was the output: <code>&quot;Ok, thank you for playing!&quot;</code>). For them (the user) they're indicating that they want to have another try at the game, but due to your code's incompetence for a variety of options (like &quot;Yes&quot; or &quot;yes&quot; - for replaying, &quot;No&quot; or &quot;no&quot; - for NOT replaying). Please solve this problem.</p>\n<p>Now to your more imperative problem (the functions), I can give it a shot.</p>\n<p>Note: You should aim for <strong>maximum clarity</strong> if you want your code to be re-used by others, or to make it easier to read and understand (not just for others but for you as well!).</p>\n<pre><code>if guess &gt; 10 * difficulty or guess &lt; 1:\n print(&quot;That's an invalid input, please re-enter your number.&quot;)\n # ⬆ this particular line!! ⬆\n continue\n break\n</code></pre>\n<p>You didn't specify <em>WHY</em> the input is invalid, you stated the obvious by saying &quot;It's an invalid input&quot;...be concise and again, aim for MAXIMUM clarity.</p>\n<p>Note: I did abbreviate some of the variable/function names just for saving time.</p>\n<p>Anyway, here's how I would've done this:</p>\n<pre><code>import random\n\n#variables:\nsc = 0\npl = True\n\n# &quot;bad&quot; input loop function.\ndef get_num(diff): \n\n while True:\n try:\n gs = int(input(&quot;Guess what number I am thinking of &quot;))\n except:\n print(&quot;Please enter a NUMBER. Letters (a, b...) and symbols (#, %...) are not appropriate vales.&quot;)\n continue\n\n if gs &gt; 10 * diff or gs &lt; 1:\n print(&quot;Your number is not in the right range, please re-enter your number!&quot;)\n continue\n return gs\n\n# &quot;hot and cold&quot; function\ndef temp_func(gs, num):\n\n if gs == num:\n print(&quot;CORRECT!&quot;)\n return True\n elif abs(gs - num) == 1:\n print(&quot;HOT!&quot;)\n return False\n elif abs(gs - num) &lt;= 3:\n print(&quot;WARM&quot;)\n return False\n else:\n print(&quot;COLD!&quot;)\n return False\n\nwhile pl:\n while True:\n try:\n diff = int(input(&quot;Give me a number between 1 and 3 &quot;\n &quot;(these are the difficulty levels) \\n\\n 1 = easy \\n 2 = medium \\n 3 = hard \\n\\n&quot;))\n except:\n print(&quot;This is not a number!&quot;)\n continue\n\n if diff &gt; 3 or diff &lt; 1:\n print(&quot;That's an invalid input, please re-enter your number&quot;)\n continue\n break\n\n num = random.randint(1, 10 * diff)\n\n attmp = 0\n gs = 0\n\n while gs != num and attmp &lt; 3:\n attmp += 1\n print(&quot;attempt number &quot; + str(attmp))\n\n gs = get_num(diff)\n\n did_win = temp_func(gs, num)\n if did_win:\n sc += 1\n break\n\n if attmp == 3 and gs != num:\n print(&quot;Oops! You've run out of guesses!&quot;)\n print(&quot;The number I was thinking of was &quot; + str(num) + &quot;.&quot;)\n\n print(&quot;Your final score is &quot; + str(sc))\n\n txt = input(&quot;If you want to play again, type 'yes' &quot;)\n if txt != &quot;yes&quot;:\n pl = False\n print(&quot;TYPE GOODBYE MESSAGE HERE&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:03:34.040", "Id": "498742", "Score": "0", "body": "Ok wow @eker-luminous you're either a mind reader or you're just a super genius person. That is exactly what I needed!! Thanks a lot! Also, I'm sorry about my incompetent line of code, will make sure to fix that up (or attempt to)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:05:42.940", "Id": "498744", "Score": "0", "body": "No worries, just keep the bold parts of my answer in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:09:34.780", "Id": "498745", "Score": "0", "body": "Nice answer @esker-luminous." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:45:10.330", "Id": "498750", "Score": "0", "body": "Thank you @theProgrammer. I'm trying to help others while they help me :))" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T19:53:25.663", "Id": "253000", "ParentId": "252964", "Score": "2" } } ]
{ "AcceptedAnswerId": "253000", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T00:21:16.423", "Id": "252964", "Score": "0", "Tags": [ "python", "beginner", "game" ], "Title": "Random Number Guessing Game Code Efficiency - Python" }
252964
<p>The following function sets a query for MongoDB, but that's not very important. It takes 2 arguments <code>key</code> can be either <code>-</code> which comes from an empty search by the user in the front end, or any other <code>string</code>. Select can be either <code>sample</code> or <code>all</code></p> <p>So it's a switch like this:</p> <pre><code> | / \ /\ /\ </code></pre> <p>In my head at least.</p> <p>But the code looks terribly bad, so something may be wrong, any tip or trick is welcome:</p> <pre><code>function setQuery(key, select){ const project = {&quot;$project&quot;:{&quot;_id&quot;:0, &quot;quote&quot;:1} } if (key===&quot;-&quot;){ return select===&quot;sample&quot; ? [{&quot;$sample&quot;:{&quot;size&quot;:5}}, project ] : [{$match:{quote:{$ne:null}}}, project] } else { //if key is not - (is a word) const reg = new RegExp(key, 'i') const userText = { &quot;$match&quot;:{&quot;quote&quot;:{ &quot;$regex&quot;: reg } }} return select===&quot;sample&quot; ? [userText, {&quot;$sample&quot;:{&quot;size&quot;:5}}, project] : [userText, project] } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T02:46:16.937", "Id": "498666", "Score": "0", "body": "Just forgot 2 `return`s. Sorry. Think it's ok now? @CertainPerformance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T02:46:49.560", "Id": "498667", "Score": "1", "body": "Oh, that makes sense. Yep, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T02:47:55.410", "Id": "498668", "Score": "0", "body": "@CertainPerformance thank you. Was really helpful, cause I forgot how ternary ops worked" } ]
[ { "body": "<p>I think the clearest way to approach this would be to define all the array items up front, to separate out the somewhat convoluted data boilerplate from the branch logic. Also, every query contains <code>project</code> at the end, so to decrease repetitiveness (and to increase the distinction between the different branches later), you might make a function for it.</p>\n<pre><code>function setQuery(key, select) {\n // Not sure what these should be called, there's probably a more precise name than `matchers`\n const matchers = {\n project: {$project:{_id:0, quote:1} },\n sample: {$sample:{size:5}},\n any: {$match:{quote:{$ne:null}}},\n text: { $match:{quote:{ $regex: new RegExp(key, 'i') } }},\n };\n const makeProjectQuery = (...initials) =&gt; [...initials, matchers.project];\n\n if (key === &quot;-&quot;) {\n return makeProjectQuery(select === &quot;sample&quot; ? matchers.sample : matchers.any);\n } else {\n // Then key is a word; search for it\n return select === &quot;sample&quot;\n ? makeProjectQuery(matchers.text, matchers.sample)\n : makeProjectQuery(matchers.text);\n }\n}\n</code></pre>\n<p>It's a few more lines, but I think it's easier to make sense of at a glance. Plus, if you ever needed to expand the functionality of this section, it would be a pretty natural extension to add something to <code>matchers</code> and add conditions for it in the lower body.</p>\n<p>The code could be further condensed, but it would come at the sake of readability.</p>\n<h2>Review</h2>\n<p>Some suggestions regarding your original code:</p>\n<p><strong>Only quote property names when necessary</strong> - leaving out the <code>&quot;</code>s results in less syntax noise and is a bit easier to read and write.</p>\n<p><strong>Indent code properly</strong> - two statements that are at the same level in a block should have the same indentation level - this makes the control flow clearer. Similarly, when ending a block, consider putting the <code>}</code> on the next line - being able to pick up on the locations where blocks begin and end at a glance is very important. Lots of IDEs can automatically indent code for you, they're well worth it.</p>\n<p><strong>Consider using spaces around operators</strong>, especially in complicated code. <code>select === &quot;sample&quot;</code> is easier to recognize at a glance than <code>select===&quot;sample&quot;</code> (especially if more operators become involved later)</p>\n<p><strong>When one branch differs from another only in a single expression, consider the conditional operator</strong> instead of repeating everything else around the expression. (eg, replace with something like <code>select === &quot;sample&quot; ? matchers.sample : matchers.any</code> as above) You don't <em>have</em> to use the conditional operator - sometimes it's clearer without it - but it's something to think about in that sort of situation.</p>\n<p><strong>Good comments</strong> use natural language that flows while reading the code out loud.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T18:06:13.297", "Id": "498731", "Score": "0", "body": "Amazing, thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T04:49:37.070", "Id": "252971", "ParentId": "252965", "Score": "1" } } ]
{ "AcceptedAnswerId": "252971", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T01:53:47.227", "Id": "252965", "Score": "1", "Tags": [ "javascript" ], "Title": "Setting a query for MongoDB" }
252965
<p>I'm new to this, but after learning some of this in class I decided to try my hand at creating a program to get the info from a Zybooks signature which stores the run data for your project. it takes a string in the format (MM/DD..signature..MM/DD) (It does not like when the signature does not follow this syntax)</p> <p>Signature ex:</p> <blockquote> <p>11/8.. U - - - - - - - - |2 |2 |2 |6 ..11/8</p> </blockquote> <blockquote> <p>10/28.. W - - - - - |1 |10 ..10/28</p> </blockquote> <blockquote> <p>11/8.. U - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |4 |4 |4 |7 |0 |0 |0 - - - - - |4 |4 |4 |7 |4 |7 |5 |8 |9 |9 |9 |9 |9 |9 |9 |12 |12 |12 |14 - - - - - - - |14 |14 |14 - - - - - |16 - - - - - - - - - - - - - |16 |13 |16 |16 |16 |16 |13 - - |17 - - |17 - - |19 |19 - - - |19 |19 |17 |17 |19 - |19 |19 |19 |17 |19 - |19 |17 |17 |19 |19 |19 |17 |19 |18 - - - |18 - - - |20 |20 - - ..11/8</p> </blockquote> <p>It gets the data from the signature and then gives you to option to print the stats or save the signature. Well, here's the code.</p> <pre><code>from datetime import datetime import os months_of_year = {&quot;1&quot;: &quot;January&quot;, &quot;2&quot;: &quot;February&quot;, &quot;3&quot;: &quot;March&quot;, &quot;4&quot;: &quot;April&quot;, &quot;5&quot;: &quot;May&quot;, &quot;6&quot;: &quot;June&quot;, &quot;7&quot;: &quot;July&quot;, &quot;8&quot;: &quot;August&quot;, &quot;9&quot;: &quot;September&quot;, &quot;10&quot;: &quot;October&quot;, &quot;11&quot;: &quot;November&quot;, &quot;12&quot;: &quot;December&quot;} days_of_week = {&quot;U&quot;: &quot;Sunday&quot;, &quot;M&quot;: &quot;Monday&quot;, &quot;T&quot;: &quot;Tuesday&quot;, &quot;W&quot;: &quot;Wednesday&quot;, &quot;R&quot;: &quot;Thursday&quot;, &quot;F&quot;: &quot;Friday&quot;, &quot;S&quot;: &quot;Saturday&quot;} def check_save_file(): &quot;&quot;&quot; checks if save.txt exists, if not creates it &quot;&quot;&quot; if not os.path.isfile('save.txt'): file = open('save.txt', 'w') file.close() def save_to_file(inp): with open('save.txt', 'a') as file: file.write(&quot;X&quot;*20) # Header file.write(&quot;\n&quot;) cur_date = datetime.now() # Date info for save (printed onto same line?) file.write(str(cur_date.month)) file.write(&quot;/&quot;) file.write(str(cur_date.day)) file.write(&quot;/&quot;) file.write(str(cur_date.year)) file.write(&quot;\n&quot;) file.write(inp) # Actual signature data (should be 2 indices from header ex: 2 then 4) file.write(&quot;\n&quot;) file.write(&quot;Y&quot;*20) file.write(&quot;\n&quot;) # Footer def read_from_file(): &quot;&quot;&quot; :return: returns tuple where (0 = list, lines)(1 = int, save_count)(2= dic, saves)(3 = list, date) &quot;&quot;&quot; save_count = 0 saves = {} date = [] with open('save.txt', 'r') as file: lines = file.readlines() # puts save into list w/ lines if len(lines) == 0: # If there are no lines, we have no save data return &quot;No save data&quot; for index, line in enumerate(lines): # Want to get index and line for every line in lines if line[0] == &quot;X&quot;: # if the 0th index is 'X' it is a header save_count += 1 saves[save_count] = index # Puts save_count as the key and the index save_count points to as a value index += 1 date.append(lines[index]) return lines, save_count, saves, date def read_save(save_num, lines, saves): &quot;&quot;&quot; :param save_num: int :param lines: list :param saves: dic return tuple where 0 = date and 1 = stored signature :return: &quot;&quot;&quot; return lines[saves[save_num] + 1], lines[saves[save_num] + 2] def pull_header(usr_str): &quot;&quot;&quot; Pulls the header from parameter usr_str, and returns a tuple with 0: the header, and 1:The length of the header &quot;&quot;&quot; c = 0 header = &quot;&quot; while usr_str[c] != usr_str[c + 1] or usr_str[c] != &quot;.&quot;: # Goes until .. header += usr_str[c] c += 1 header += &quot;..&quot; return header, len(header) # returns the header abd the length of the header def pull_footer(usr_str): &quot;&quot;&quot; Pulls the footer from the parameter usr_str, reverses it for input into get_date, and returns a tuple with 0: The reversed footer, and 1:The negated length of it &quot;&quot;&quot; c = -1 footer = &quot;&quot; while usr_str[c] != usr_str[c - 1] or usr_str[c] != &quot;.&quot;: # Goes backwards until .. footer += usr_str[c] c -= 1 footer = footer[::-1] # reverses the footer for use in get_date footer += &quot;..&quot; return footer, -len(footer) # returns the header and the |distance form the end (DEPRECIATED)| def get_date(header): &quot;&quot;&quot; This function returns a date given a string with the format &quot;MM/DD..&quot; &quot;&quot;&quot; c = 0 month = &quot;&quot; day = &quot;&quot; suffix = &quot;&quot; while header[c] != &quot;/&quot;: # every thing before the / month += header[c] c += 1 c += 1 while header[c] != &quot;.&quot;: # Everything until the . day += header[c] c += 1 if int(day[-1]) == 1 and int(day) != 11: # suffixes based on the number suffix = &quot;st&quot; elif int(day[-1]) == 2 and int(day) != 12: suffix = &quot;nd&quot; elif int(day[-1]) == 3 and int(day) != 13: suffix = &quot;rd&quot; elif (int(day[-1]) == 0) or (int(day[-1]) &gt; 3) or (11 &lt;= int(day) &lt;= 13): suffix = &quot;th&quot; month = months_of_year[month] date = &quot;%s the %s%s&quot; % (month, day, suffix) return date def date_div(header, footer): &quot;&quot;&quot; This functions calculates how many days the assignment took, given the header and the footer of the signature &quot;&quot;&quot; d_s = &quot;&quot; m_s = &quot;&quot; start = header end = footer start = start[:-2] # removes the suffix &quot;..&quot; end = end[:-2] start = start.split(&quot;/&quot;) # splits the date into a list at the &quot;/&quot; M= 0 ,D = 1 end = end.split(&quot;/&quot;) month_div = int(end[0]) - int(start[0]) # calculate the start and end differences day_div = int(end[1]) - int(start[1]) if day_div &gt; 1: d_s = &quot;s&quot; if month_div &gt; 1: m_s = &quot;s&quot; if month_div == 0: if day_div == 0: return &quot;You completed it on the same day!&quot; elif day_div != 0: return &quot;You completed it in %d day%s&quot; % (day_div, d_s) elif month_div != 0: if day_div == 0: return &quot;You completed it in %d month%s&quot; % (month_div, m_s) elif day_div != 0: return &quot;You completed it in %d month%s and %d day%s&quot; % (month_div, m_s, day_div, d_s) def translate_sig(usr_str, index): &quot;&quot;&quot; This functions returns a string, and an integer representing the type of run, when given a string(usr_str) and an integer index &quot;&quot;&quot; if usr_str[index].isalpha(): # If the character at the index is Alphabetical, stands for day of the week return days_of_week[usr_str[index]], 0 elif usr_str[index] == &quot;-&quot;: # Stands for Ran in develop mode return 1, 1 elif usr_str[index] == &quot;|&quot;: # This followed by an number represents ran in submit mode, followed by the score score = &quot;&quot; index += 1 while usr_str[index] != &quot; &quot;: # Since each entry is separated by a space, Just read until whitespace score += usr_str[index] index += 1 return score, 2 else: pass def print_stats(dev_count, sub_count, date_dif, average, hi_score): &quot;&quot;&quot; This function prints the statistics of your Lab, given dev_count, sub_count, date_dif, average, and hi_score &quot;&quot;&quot; format_str = &quot;{text:40}|{num:4}&quot; # Using fields I just learned print(&quot;Stats&quot;) print(&quot;-&quot; * 20) print(format_str.format(text=&quot;Number of times ran in Dev Mode:&quot;, num=dev_count)) print() print(format_str.format(text=&quot;Number of times ran in Submit Mode:&quot;, num=sub_count)) print() print(format_str.format(text=&quot;Total runs:&quot;, num=dev_count + sub_count)) print() print(format_str.format(text=&quot;Average score:&quot;, num=average)) print() print(format_str.format(text=&quot;Highest score:&quot;, num=hi_score)) print() print(date_dif) def calc_avg_score(score_lst): &quot;&quot;&quot; Calculates the average score, given an list of scores &quot;&quot;&quot; length = len(score_lst) sc_add = 0 for score in score_lst: sc_add += int(score) average = sc_add / length return round(average, 2) # returns the average rounded by two places def save_menu(sig): &quot;&quot;&quot; :param sig: The signature (str) :return: returns a signature or 1, representing no need to cont. &quot;&quot;&quot; op = &quot;&quot; while op != 'q': print(&quot;Enter 1 for save, Enter 2 for load, q for Quit.&quot;) op = input() print() if op == '1': print(&quot;Starting Save&quot;) save_to_file(sig) print(&quot;Finished&quot;) print() return 1 elif op == '2': lines, save_count, save, save_date = read_from_file() # get variables from the returned tuple print(&quot;Current Saves&quot;) for key in save.keys(): # for every save in the save.txt prints attached # and date print(&quot;Save#: {}, Save Date: {}&quot;.format(key, save_date[key - 1])) print() print(&quot;Enter save # to load save&quot;) save_num = int(input()) print() date, sig = read_save(save_num, lines, save) print(&quot;-&quot;*30) print(&quot;Date = {}&quot;.format(date)) print(&quot;Signature = {}&quot;.format(sig)) print() print(&quot;Do want to translate this signature? (y/n)&quot;) trans_save = None cont = None while trans_save is None: # continue until input is y or n trans_save = input() if trans_save.lower() == 'y': cont = True elif trans_save.lower() == 'n': cont = False else: print(&quot;Invalid Operation&quot;) if cont: # returns the signature minus newline return sig[:-1] else: return 1 elif op == 'q': pass else: print(&quot;Invalid Operation&quot;) def main(): &quot;&quot;&quot; Main block of the problem, &quot;&quot;&quot; check_save_file() fin = None done = None nvalid = True print(&quot;Copy and paste the signature below (MM/DD..SIG..MM/DD)&quot;) sig = input().strip() # Get the signature and strip any trailing whitespace while nvalid: # Try to see if sig is valid by checking if it has a proper header (Assumes sig is invalid) try: pull_header(sig) except: # Should catch any errors print(&quot;Invalid Signature&quot;) sig = input().strip() else: nvalid = False while not fin: if not done: header = pull_header(sig) # Tuple (Header , distance fromm start) footer = pull_footer(sig) # Tuple (Footer , distance from end) print(&quot;Date Started: %s.&quot; % (get_date(header[0]))) print() index = header[1] # starting point is taken after the header finishes c = 1 sub_count = 0 dev_count = 0 score_lst = [] while sig[index] != &quot;.&quot;: # Until the program reaches &quot;.&quot; indicating the beginning of the footer, continue translating op = translate_sig(sig, index) if op is not None: # This is none if the index is whitespace if op[-1] == 0: # For new date print(&quot;|%s| Day - %s&quot; % (c, op[0])) print() elif op[-1] == 1: # Develop Mode print(&quot;%s |Ran in develop mode, no score&quot; % c) dev_count += 1 c += 1 print() elif op[-1] == 2: # Submit Mode print(&quot;%s |Ran in submit mode, score = %s&quot; % (c, op[0])) sub_count += 1 c += 1 score_lst.append(int(op[0])) # adds score into score_lst print() index += 1 print(&quot;Date of last run: %s.&quot; % (get_date(footer[0]))) done = True print() stat = &quot;&quot; get_stat = None get_saves = None cont = None # Should only be true if another translation is called while not fin and not cont: print(&quot;Do you want to see further statistics(1) or save/load(2) (1, 2, q to quit)&quot;) while stat != 'q': # If 1 is entered show stats if 2 is entered call save_menu() if q is entered exit stat = input() if stat.lower() == '1': get_stat = True stat = 'q' elif stat.lower() == '2': get_saves = True stat = 'q' elif stat.lower() == 'q': fin = True else: print(&quot;Not a valid option&quot;) # print this and return to top of loop if not == y or n print(&quot;Enter a new Option&quot;) print() if get_stat: print() average = calc_avg_score(score_lst) time_taken = date_div(header[0], footer[0]) max_score = max(score_lst) print_stats(dev_count=dev_count, sub_count=sub_count, date_dif=time_taken, average=average, hi_score=max_score) # prints stats get_stat = False if get_saves: print() do_op = save_menu(sig) if do_op != 1: # if the opcode is anything but 1 treat is as a signature and restart the program sig = do_op done = False fin = None cont = True get_saves = False stat = &quot;&quot; if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Now, since I'm new to this I'm pretty sure that this isn't perfect, so I'd like to know how I would be able to improve it? (It's very long as well so would there be any way for me to shorten it?) This is my first question here so I'm also pretty sure I've broken some rule or convention to posting on stack Exchange (could you let me know if I have?)so sorry about that. Thank You!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T12:34:00.347", "Id": "498700", "Score": "1", "body": "Since the signatures are always the same layout you can use `str.split()` to split strings. Eg. `[header, signature, footer] = usr_str.split('..')`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T12:40:47.997", "Id": "498701", "Score": "1", "body": "Take a look at https://docs.python.org/3/library/datetime.html#module-datetime and https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior for working with dates and time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T12:44:32.630", "Id": "498702", "Score": "1", "body": "And again, for analyzing the sig, I'd use `arr = sig.split(' ')`, `arr[0]` has the first letter and then you can loop through the rest of the array and check for lenght or first element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T13:10:04.007", "Id": "498704", "Score": "0", "body": "In `read_from_file`: `index += 1; date.append(lines[index])` --> `date.append(lines[index+1])`. (Is this even what you want to do?) Do not change your iterator variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T13:25:18.060", "Id": "498705", "Score": "0", "body": "@Swedgin That sounds like the start of a good answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T13:40:18.603", "Id": "498706", "Score": "0", "body": "@Graipher I thought so too when writing it, but didn't want to rewrite the whole program, hence these small pointers as a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T14:49:34.260", "Id": "498714", "Score": "0", "body": "@Swedgin Partial answers are perfectly fine on CodeReview!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T15:23:33.957", "Id": "498724", "Score": "2", "body": "@Graipher Oh I see, did not know that. Maybe I'll write something up tonight," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:42:32.990", "Id": "498730", "Score": "0", "body": "Thanks! The way I wanted to do `read_from_file`: was to get the important info to print from the file, the date line and the save# of each so I could print them in `save_menu` I thought since I get the save # from the header, and the date line is the line after the header, I would just append the next line to a list with all of the dates. Is there a better way to do that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:24:15.227", "Id": "498746", "Score": "0", "body": "@Swedgin I just realized I could tag people to my comments and I cant edit my earlier comment anymore ;-;" } ]
[ { "body": "<p>For starters, I want to say that you've got the gist of what to do but don't know the Python language that good which results in this lengthy code.</p>\n<p>I've rewrote the first part of your program, the part that analyzes the signature. Later on, I'll take a look at the second part.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n &quot;&quot;&quot;\n Main block of the problem,\n &quot;&quot;&quot;\n check_save_file() ## --&gt; not needed, do this when trying to read from a file\n fin = None\n done = None\n\n #################################\n # BLOCK INPUT, I'd move this to seperate function or use regex\n #################################\n nvalid = True\n print(&quot;Copy and paste the signature below (MM/DD..SIG..MM/DD)&quot;)\n sig = input().strip() # Get the signature and strip any trailing whitespace\n while nvalid: # Try to see if sig is valid by checking if it has a proper header (Assumes sig is invalid)\n try:\n pull_header(sig)\n except: # Should catch any errors\n print(&quot;Invalid Signature&quot;)\n sig = input().strip()\n else:\n nvalid = False\n\n ###############################\n\n while not fin:\n ################################################################\n # BLOCK ANALYZE\n ################################################################\n if not done:\n\n ## I'd use datetime functionality\n\n header = pull_header(sig) # Tuple (Header , distance fromm start)\n footer = pull_footer(sig) # Tuple (Footer , distance from end)\n print(&quot;Date Started: %s.&quot; % (get_date(header[0])))\n print()\n\n index = header[1] # starting point is taken after the header finishes\n c = 1\n sub_count = 0\n dev_count = 0\n score_lst = []\n while sig[index] != &quot;.&quot;: # Until the program reaches &quot;.&quot; indicating the beginning of the footer, continue translating\n op = translate_sig(sig, index) ## I like the use of a tuple to return the state and score\n if op is not None: # This is none if the index is whitespace\n\n ## But why op[-1] instead of op[1]? You know it's a tuple with 2 elements.\n\n if op[-1] == 0: # For new date\n print(&quot;|%s| Day - %s&quot; % (c, op[0]))\n\n print()\n elif op[-1] == 1: # Develop Mode\n print(&quot;%s |Ran in develop mode, no score&quot; % c)\n dev_count += 1\n c += 1\n print()\n elif op[-1] == 2: # Submit Mode\n print(&quot;%s |Ran in submit mode, score = %s&quot; % (c, op[0]))\n sub_count += 1\n c += 1\n score_lst.append(int(op[0])) # adds score into score_lst\n print()\n index += 1\n print(&quot;Date of last run: %s.&quot; % (get_date(footer[0])))\n done = True\n print()\n ################################################################\n</code></pre>\n<p>This is how I'd do it</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport re\nfrom datetime import datetime\n\nDAYS_OF_WEEK = {\n &quot;U&quot;: &quot;Sunday&quot;,\n &quot;M&quot;: &quot;Monday&quot;,\n &quot;T&quot;: &quot;Tuesday&quot;,\n &quot;W&quot;: &quot;Wednesday&quot;,\n &quot;R&quot;: &quot;Thursday&quot;,\n &quot;F&quot;: &quot;Friday&quot;,\n &quot;S&quot;: &quot;Saturday&quot;,\n}\n\n\ndef date_to_string(date: datetime):\n # datetime object to string\n suffix = &quot;th&quot; ## by declaring this as 'th' you don't need to check for 11, 12 and 13\n if date.day == 1:\n suffix = &quot;st&quot;\n elif date.day == 2:\n suffix = &quot;nd&quot;\n elif date.day == 3:\n suffix = &quot;rd&quot;\n\n return &quot;{0:%B} the {0:%d}{1}&quot;.format(date, suffix)\n\n\ndef main():\n\n ## BLOCK INPUT\n\n # regex for matching signatures\n sig_regex = re.compile(&quot;(\\d{0,2}\\/\\d{0,2})\\.{2}.+\\.{2}(\\d{0,2}\\/\\d{0,2})&quot;)\n\n print(&quot;Copy and paste the signature below (MM/DD..SIG..MM/DD)&quot;)\n\n # while no match, keep asking for input\n while not (sig_regex.match(sig := input().strip())):\n print(&quot;Invalid Signature&quot;)\n\n # split input into header, body and footer\n [header, body, footer] = sig.split(&quot;..&quot;)\n body = body.strip()\n\n print(f&quot;Got valid signature:\\nhead:\\t{header}\\nbody:\\t{body}\\nfooter:\\t{footer}&quot;)\n\n ## BLOCK ANALYZE\n\n # get the start date in format MM/dd\n start_date = datetime.strptime(header, &quot;%m/%d&quot;)\n print(f&quot;Date Started: {date_to_string(start_date)}\\n&quot;)\n\n score_list = []\n\n # split the body into seperate elements\n body_arr = body.split(&quot; &quot;)\n\n # check the first element\n if body_arr[0] in DAYS_OF_WEEK.keys():\n\n print(f&quot;|1| Day - {DAYS_OF_WEEK[body_arr[0]]}&quot;)\n\n # iterate over the rest of the elements\n for index, run in enumerate(body_arr[1:]):\n if run[0] == &quot;-&quot;:\n print(f&quot;{index+1} |Ran in develop mode, no score&quot;)\n elif run[0] == &quot;|&quot;:\n score_list.append(int(run[1:]))\n print(f&quot;{index+1} |Ran in submit mode, score = {score_list[-1]}&quot;)\n\n # get the start date in format MM/dd\n end_date = datetime.strptime(footer, &quot;%m/%d&quot;)\n print(f&quot;\\nDate Ended: {date_to_string(end_date)}&quot;)\n\n print(f&quot;\\nScore list: {score_list}&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>Notes:</p>\n<ol>\n<li>The regex can probably be better, but I'm no expert in that. (I use <a href=\"https://regexr.com/\" rel=\"nofollow noreferrer\">https://regexr.com/</a> to test)</li>\n<li>If you want, you can split <code>main</code> into several subfunctions. (eg. input, body extraction, header/footer eval)</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:37:25.130", "Id": "498824", "Score": "1", "body": "Welcome to the Code Review Community, while you have made two meaningful observation you may be missing the point of code review. This site is quite different from stack overflow. The goal here is to help the original poster improve their code, not re-write their code for them. It is far more important to provide explanations for why they should change their code and much less important to provide the correct code. You might want to read through [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer). A good answer might not contain any code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:01:20.217", "Id": "498831", "Score": "0", "body": "@Swedgin Thanks! I was trying to look at the documentation for the re but I found the syntax really confusing. One thing I guess I didn't go over well in my question is that the Day of the week Marker can appear anywhere in the signature, once a day. I didn't know `:=` was a thing but after reading about it seems really useful. Thanks again! I'll use this to learn a bit more :>" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:25:22.397", "Id": "253035", "ParentId": "252966", "Score": "1" } } ]
{ "AcceptedAnswerId": "253035", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T02:06:04.317", "Id": "252966", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Beginner python program to get data from string" }
252966
<p>Today I'm researching how to provide data to UIKit component when using Combine pipeline.</p> <p>I could see tons of tutorials about how to use SwiftUI + Combine from internet, but not found anyone helpful stuff about UIKit + Combine.</p> <p>Well, I list one approach here, I put some data works in <code>WebService</code> and mean time receive the data in <code>ViewController</code> with Combine pipeline and provide them as the data source of tableView.</p> <p>But I could see the <code>fetchData()</code> is mixed in <code>ViewController</code> now, it should be wonderful if I could put it into <code>WebService</code> and isolate the data pipeline operation with <code>ViewController</code>.</p> <p>So what is the better way to provide the data to UIKit component when using Combine pipeline like <code>dataTaskPublisher</code>? Is my current approach the common way to do it?</p> <h2>Approach 1</h2> <h3>WebService.swift</h3> <pre><code>import Combine import UIKit enum HTTPError: LocalizedError { case statusCode case post } enum FailureReason: Error { case sessionFailed(error: HTTPError) case decodingFailed case other(Error) } struct Response: Codable { let statusMessage: String? let success: Bool? let statusCode: Int? } class WebService { private var requests = Set&lt;AnyCancellable&gt;() private var decoder: JSONDecoder = { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return decoder }() private var session: URLSession = { let config = URLSessionConfiguration.default config.allowsExpensiveNetworkAccess = false config.allowsConstrainedNetworkAccess = false config.waitsForConnectivity = true config.requestCachePolicy = .reloadIgnoringLocalCacheData return URLSession(configuration: config) }() func createPublisher&lt;T: Codable&gt;(for url: URL) -&gt; AnyPublisher&lt;T, FailureReason&gt; { return session.dataTaskPublisher(for: url) .tryMap { output in guard let response = output.response as? HTTPURLResponse, response.statusCode == 200 else { throw HTTPError.statusCode } return output.data } .decode(type: T.self, decoder: decoder) .mapError { error in switch error { case is Swift.DecodingError: return .decodingFailed case let httpError as HTTPError: return .sessionFailed(error: httpError) default: return .other(error) } } .eraseToAnyPublisher() } func getPetitionsPublisher(for url: URL) -&gt; AnyPublisher&lt;Petitions, FailureReason&gt; { createPublisher(for: url) } } </code></pre> <h2>ViewController</h2> <pre><code>import Combine import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView = UITableView() var petitions = [PetitionViewModel]() let webService = WebService() private var cancellableSet = Set&lt;AnyCancellable&gt;() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground title = &quot;Petitions&quot; navigationItem.rightBarButtonItem = UIBarButtonItem(title: &quot;Credits&quot;, style: .plain, target: self, action: #selector(rightBarButtonTapped)) tableView.delegate = self tableView.dataSource = self // tableView.register(UITableViewCell.self, forCellReuseIdentifier: &quot;cell&quot;) tableView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tableView) let g = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ tableView.leadingAnchor.constraint(equalTo: g.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: g.trailingAnchor), tableView.topAnchor.constraint(equalTo: g.topAnchor), tableView.bottomAnchor.constraint(equalTo: g.bottomAnchor) ]) } override func viewWillAppear(_ animated: Bool) { let url = WhiteHouseClient.petitions.url print(&quot;url: \(url)&quot;) fetchData(for: url) print(&quot;viewWillAppear&quot;) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return petitions.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: &quot;cell&quot;) ?? UITableViewCell(style: .subtitle, reuseIdentifier: &quot;cell&quot;) cell.accessoryType = .disclosureIndicator let petition = petitions[indexPath.row] cell.textLabel?.text = petition.name cell.detailTextLabel?.text = petition.body return cell } @objc func rightBarButtonTapped() { let ac = UIAlertController(title: &quot;Credits&quot;, message: &quot;the data comes from the We The People API of the Whitehouse.&quot;, preferredStyle: .alert) ac.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default)) present(ac, animated: true) } func fetchData(for url: URL) { webService.getPetitionsPublisher(for: url) .receive(on: DispatchQueue.main) .sink(receiveCompletion: { status in switch status { case .finished: break case .failure(let error): print(error) break } }) { [unowned self] petitions in self.petitions = petitions.results.map(PetitionViewModel.init) DispatchQueue.main.async { self.tableView.reloadData() } }.store(in: &amp;self.cancellableSet) } } </code></pre>
[]
[ { "body": "<p>Instead of <code>let webService = WebService()</code>, suppose your viewController took a function that creates/returns the publisher when needed: <code>var makePublisher: () -&gt; AnyPublisher&lt;[PetitionViewModel], FailureReason&gt;</code>, so the vc can call it lazily, perhaps in viewWillAppear. Now the vc doesn't know anything about the webService, and it could easily be wired up to a test publisher with static responses.</p>\n<p>But be careful about viewWillAppear: it's possible that it can be called more than once, (and also that you never get viewDidAppear, or you're not onscreen when the fetch returns) and consider renaming your <code>fetchData(for: url)</code> method - it doesn't <em>directly</em> fetch data, it creates a new subscription and <em>adds</em> it to the cancellableSet. If you mean to tear down and recreate the pipeline on each viewWillAppear, consider storing the cancellable in its own property, so you can have at most 1 of them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T02:50:30.693", "Id": "499250", "Score": "0", "body": "My original idea is to separate data stream operation with ViewController into different file. So the View will not involve the data logic. Then there is a `createPublisher ` in WebService.swift file. For the second point, `fetchData()` has passed the data to VC's property `self.petitions = petitions` in sink's closure. I put data call in `viewWIllAppear` as user could switch between pages, when they go back, this page could be refreshed again. Yes, I notice the risk `you're not onscreen when the fetch returns` you said, so which method I should place them in case to avoid this risk?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T14:35:49.333", "Id": "253179", "ParentId": "252967", "Score": "0" } }, { "body": "<p>This looks fine. A bunch of minor observations:</p>\n<ul>\n<li><p><code>WebService.swift</code> should import <code>Foundation</code>, not <code>UIKit</code>. A network layer should not be imposing any platform-specific constraints.</p>\n</li>\n<li><p><code>T</code> in <code>createPublisher</code> only needs to conform to <code>Decodable</code>. Do not impose unnecessary conformance requirements.</p>\n</li>\n<li><p>The <code>getPetitionsPublisher</code> doesn't belong in <code>WebService</code>. We would want to avoid entangling the <code>WebService</code> with any particular model type, such as <code>Petitions</code>. I would pull this out and move it to its own extension. Or, better, since this isn't doing anything other than specializing the generic, just specify the data type in <code>fetchData</code>, and <code>getPetitionsPublisher</code> is rendered completely unnecessary and can be deleted. But, avoid coupling a network layer with specific model types, if you can.</p>\n</li>\n<li><p>I would also rename <code>FailureReason</code> with something that indicates the domain and type of the failure, e.g. <code>WebServiceError</code>.</p>\n</li>\n<li><p>I would also rename the generic <code>createPublisher</code> to <code>publisher</code> or <code>webServicePublisher</code>, to follow standard naming conventions. Apple does not use a verb in their publisher methods, and I would suggest following that convention.</p>\n</li>\n<li><p>Given that <code>WebService</code> is creating a <code>URLSession</code>, make sure to invalidate the session when you are done with it. Otherwise, you will leak.</p>\n<pre><code>class WebService {\n private let decoder: JSONDecoder = ...\n private let session: URLSession = ...\n\n deinit {\n session.finishTasksAndInvalidate()\n }\n ...\n}\n</code></pre>\n<p>Note, you are not using <code>requests</code>, so that property can be removed.</p>\n</li>\n<li><p>You might also consider making <code>WebService</code> a singleton, rather than repeating reinstantiating it.</p>\n</li>\n<li><p>You might define a protocol for the <code>WebService</code>. That way, when writing unit tests, you can stub the web service.</p>\n<pre class=\"lang-swift prettyprint-override\"><code>enum WebServiceError: Error {\n case sessionFailed(error: HTTPError)\n case decodingFailed\n case other(Error)\n}\n\nprotocol WebServiceInterface {\n func publisher&lt;T: Decodable&gt;(for url: URL) -&gt; AnyPublisher&lt;T, WebServiceError&gt;\n}\n\nclass WebService {\n private let decoder: JSONDecoder = ...\n private let session: URLSession = ...\n\n deinit {\n session.finishTasksAndInvalidate()\n }\n}\n\n// MARK: - WebServiceInterface\n\nextension WebService: WebServiceInterface {\n func publisher&lt;T: Decodable&gt;(for url: URL) -&gt; AnyPublisher&lt;T, WebServiceError&gt; {\n session.dataTaskPublisher(for: url)\n .tryMap { output in\n guard\n let response = output.response as? HTTPURLResponse,\n 200 ..&lt; 300 ~= response.statusCode\n else {\n throw HTTPError.statusCode\n }\n return output.data\n }\n .decode(type: T.self, decoder: decoder)\n .mapError { error in\n switch error {\n case is Swift.DecodingError: return .decodingFailed\n case let httpError as HTTPError: return .sessionFailed(error: httpError)\n default: return .other(error)\n }\n }\n .eraseToAnyPublisher()\n }\n}\n</code></pre>\n<p>And then the class that is using the web service can specify the interface:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>private var webService: WebServiceInterface = WebService()\n</code></pre>\n</li>\n<li><p>Note, I would suggest considering all values in the range of 200..&lt;300 as success. Your current web service might only return 200, but in reality, all 2xx codes are success.</p>\n</li>\n<li><p>In <code>fetchData</code>,</p>\n<ul>\n<li>Your second <code>case</code> does not need a break;</li>\n<li>Since you are really only trying to handle a single case, you should probably use <code>if case let</code> syntax;</li>\n<li>When calling <code>sink</code>, I might suggest the <code>sink { completion in ... } receiveValue { value in ... }</code> syntax as enabled by <a href=\"https://github.com/apple/swift-evolution/blob/main/proposals/0279-multiple-trailing-closures.md\" rel=\"nofollow noreferrer\">SE-0279 Multiple Trailing Closures</a>. It avoids that messy <code>sink { status in ... } } ) { ... }</code> syntax.</li>\n<li>One should not use <code>unowned</code> with asynchronous methods because, while it avoids keeping a strong reference, if the view controller was dismissed by the time the closure was called, your code would crash. Use <code>weak</code> if you want to avoid strong references with asynchronous closures. Only use <code>unowned</code> in cases where you know that the captured object can never be deallocated by the time the closure is called.</li>\n<li>You are dispatching the reload of the table view to the main queue, but not the update to the model. If your closure was being called on a background thread, then both the model update and the reload of the table should be inside the dispatch to the main queue. Or, because you already have a <code>.receive(on: DispatchQueue.main)</code>, the dispatch to the main queue is now redundant.</li>\n</ul>\n<p>Thus:</p>\n<pre><code>func fetchData(for url: URL) {\n webService.publisher(for: url)\n .receive(on: DispatchQueue.main)\n .sink { completion in\n if case .failure(let error) = completion {\n print(error)\n }\n } receiveValue: { [weak self] (petitions: Petitions) in\n self?.petitions = petitions.results.map(PetitionViewModel.init)\n self?.tableView.reloadData()\n }.store(in: &amp;cancellables)\n}\n</code></pre>\n</li>\n<li><p>I'm not sure why you are mapping the <code>petitions.results</code> to <code>PetitionViewModel.init</code>. You have not shared your model declarations, so we cannot comment on that, but generally we would have the decoder do that conversion for us.</p>\n</li>\n<li><p>In <code>viewWillAppear</code>, make sure to call <code>super</code>.</p>\n</li>\n<li><p>I might suggest breaking <code>ViewController</code> into some extensions. E.g., you might move <code>UITableViewDataSource</code> and <code>UITableViewDelegate</code> conformance into extensions, and move the private utility methods into their own private extension. It makes it easier to grok which methods are being used for what purpose and which are private. Also, as you working on your view controller, you can collapse sections unrelated to what you that. I would also break the <code>viewDidLoad</code> into logical functions, so a reader does not get lost in the details.</p>\n<p>For example:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>class ViewController: UIViewController {\n private var tableView = UITableView()\n private var petitions: [PetitionViewModel] = []\n private var webService: WebServiceInterface = WebService()\n private var cancellables: = Set&lt;AnyCancellable&gt;()\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n configureViews()\n }\n\n override func viewWillAppear(_ animated: Bool) {\n super.viewWillAppear(animated)\n\n fetchData(for: WhiteHouseClient.petitions.url)\n }\n}\n\n// MARK: - Private utility methods\n\nprivate extension ViewController {\n func configureViews() {\n view.backgroundColor = .systemBackground\n title = &quot;Petitions&quot;\n navigationItem.rightBarButtonItem = UIBarButtonItem(title: &quot;Credits&quot;, style: .plain, target: self, action: #selector(didTapRightBarButton(_:)))\n\n configureTableView()\n }\n\n func configureTableView() {\n tableView.delegate = self\n tableView.dataSource = self\n tableView.register(SubtitleCell.self, forCellReuseIdentifier: &quot;PetitionCell&quot;)\n tableView.translatesAutoresizingMaskIntoConstraints = false\n view.addSubview(tableView)\n\n let guide = view.safeAreaLayoutGuide\n NSLayoutConstraint.activate([\n tableView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),\n tableView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),\n tableView.topAnchor.constraint(equalTo: guide.topAnchor),\n tableView.bottomAnchor.constraint(equalTo: guide.bottomAnchor)\n ])\n }\n\n @objc func didTapRightBarButton(_ sender: UIBarButtonItem) { ... }\n\n func fetchData(for url: URL) { ... }\n}\n\n// MARK: - UITableViewDataSource\n\nextension ViewController: UITableViewDataSource {\n func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { ...}\n\n func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { ... }\n}\n\n// MARK: - UITableViewDelegate\n\nextension ViewController: UITableViewDelegate { }\n</code></pre>\n</li>\n<li><p>You have commented out the registration of the cell identifier. That means that you have lost any cell reuse capabilities. I would define a <code>UITableViewCell</code> subclass that is configured the way you would like it, and reuse that.</p>\n</li>\n<li><p>You might consider giving <code>rightBarButtonTapped</code> a <code>sender</code> parameter, which is a <code>UIBarButtonItem</code>. It makes it easier, at a glance, to understand what it is doing. I might call it <code>didTapRightBarButton</code> to follow standard naming conventions, too.</p>\n</li>\n<li><p>You might consider abstracting the <code>fetchData</code> routine out of the view controller, especially as the view controller grows in complexity.</p>\n<p>View controllers are best limited to view-related code. Business logic, interaction with network API, interaction with data stores, etc., are best contained within a UI-independent object that can be more easily unit tested.</p>\n</li>\n</ul>\n<p>Despite the plethora of observations above, I think you had a good start. But hopefully the above gives you some ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:42:55.453", "Id": "501239", "Score": "0", "body": "Thanks, though it is a lot of things I could improve, I'd like to go through each of them and especially for the unit test part." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:34:00.993", "Id": "254143", "ParentId": "252967", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T02:21:42.607", "Id": "252967", "Score": "4", "Tags": [ "swift", "ios", "uikit" ], "Title": "Better way to provide data to UIKit component from Combine pipeline" }
252967
<p>In spite of all the POSIX shell disadvantages, I am still sticking with it and I love its portability.</p> <p>Recently, I was searching for a way of code re-use, which turns out to be structured programming and input validation = Yes, in a POSIX shell script.</p> <hr /> <p>Let me begin with the simpler.</p> <h3><code>is_integer()</code> + <code>is_exit_code()</code></h3> <pre class="lang-sh prettyprint-override"><code>is_integer () { case &quot;${1#[+-]}&quot; in (*[!0123456789]*) return 1 ;; ('') return 1 ;; (*) return 0 ;; esac } is_exit_code () { is_integer &quot;$1&quot; &amp;&amp; case &quot;$1&quot; in ([+-]*) return 1 ;; esac &amp;&amp; [ &quot;$1&quot; -le 255 ] } </code></pre> <hr /> <p>Here, I continue on with further chained functions.</p> <h3><code>print_error()</code> + <code>print_error__exit()</code></h3> <pre class="lang-sh prettyprint-override"><code>print_error () { if ! { [ $# -eq 2 ] &amp;&amp; [ -n &quot;$1&quot; ] &amp;&amp; [ -n &quot;$2&quot; ]; } then printf '%b\n' &quot;Some longer error message.&quot; exit 1 fi printf '%b\n' \ &quot;${color_red}Error occurred$tput_reset&quot; \ &quot;Error heading: $color_yellow$1$tput_reset&quot; \ &quot;Error message: $2&quot; } &gt;&amp;2 print_error__exit () { if ! { [ $# -eq 2 ] &amp;&amp; [ -n &quot;$1&quot; ] &amp;&amp; [ -n &quot;$2&quot; ]; } &amp;&amp; ! { [ $# -eq 3 ] &amp;&amp; [ -n &quot;$1&quot; ] &amp;&amp; [ -n &quot;$2&quot; ] &amp;&amp; is_exit_code &quot;$3&quot; &amp;&amp; [ &quot;$3&quot; -ge 1 ]; } then printf '%b\n' &quot;Some longer error message.&quot; exit 1 fi print_error &quot;$1&quot; &quot;$2&quot; exit &quot;${3:-1}&quot; } &gt;&amp;2 </code></pre> <hr /> <p>So, in this bare example, the chains go up like this:</p> <ol> <li><p><code>print_error__exit ()</code> <code>print_error ()</code>;</p> </li> <li><p><code>print_error__exit ()</code> <code>is_exit_code ()</code> <code>is_integer ()</code>.</p> </li> </ol> <hr /> <p>Despite I am quite confident, these examples work as they should, one never knows, a maybe different point of view would shed a different light on my process.</p>
[]
[ { "body": "<p>Your code looks nice. I give some additional advice.</p>\n<ol>\n<li>You can debug by calling the <code>source</code> command in your terminal (REPL).</li>\n<li>You can divide the common codes and the main codes by writing the <code>source</code> in the main code.</li>\n<li>Take care of an enormous number. The number <code>99999999999999999999999999999999999999999999999999</code>, and so on.</li>\n<li>The action of writing some function is not functional programming but structured programming. The functional programming paradigm is like the idea of stream and pipe. Then, if you do not know functional programming, you may practice functional programming.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T05:50:18.660", "Id": "515865", "Score": "0", "body": "I removed the `functional-programming` tag, thanks for tips." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-30T05:40:04.820", "Id": "261406", "ParentId": "252974", "Score": "3" } } ]
{ "AcceptedAnswerId": "261406", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T07:49:08.207", "Id": "252974", "Score": "0", "Tags": [ "validation", "posix", "sh" ], "Title": "Attempt on basic input validation and functional programming in a POSIX shell" }
252974
<p>I have the following code which takes an array that might have duplicate <code>id</code>s and will merge the <code>items</code> of those duplicate, and keep only one element per id which contains all the items of all elements with the same id.</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>array = [{ id: 1, items: [1, 2, 3] }, { id: 2, items: [1, 2] }, { id: 1, items: [4] }, { id: 3, items: [1] }, ]; const mergeLines = (a) =&gt; { const processedIds = []; const finalResult = []; a.forEach((element) =&gt; { const elementId = element.id; if (processedIds.indexOf(elementId) === -1) { const occurences = a.filter((el) =&gt; el.id === elementId); if (occurences.length &gt; 1) { const allItems = occurences.reduce((acc, curr) =&gt; { acc = acc.concat(curr.items); return acc; }, []); element = { ...element, items: allItems }; finalResult.push(element); } else { finalResult.push(element); } processedIds.push(elementId); } }); return finalResult; }; console.log(mergeLines(array));</code></pre> </div> </div> </p> <p>I feel this code can be optimized much further to 0(n)</p>
[]
[ { "body": "<p>A short review;</p>\n<ul>\n<li>This code looks incredibly complicated for what you want to achieve, sometimes a few <code>for</code> loops beat the functional approach</li>\n<li><code>array</code> is a global variable (not <code>var</code> or <code>set</code> or <code>const</code>), that is a bad thing</li>\n<li>If a function is not inline, I would encourage you to use the <code>function</code> keyword</li>\n<li>I am not sure <code>mergeLines</code> is a great name, perhaps <code>mergeIds</code> ?</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>array = [{\n id: 1,\n items: [1, 2, 3]\n },\n {\n id: 2,\n items: [1, 2]\n },\n {\n id: 1,\n items: [4]\n },\n {\n id: 3,\n items: [1]\n },\n];\n\nfunction mergeIds(list){\n const out = [];\n for(entry of list){\n const existingEntry = out.find(o =&gt; o.id === entry.id);\n if(existingEntry){\n existingEntry.items = existingEntry.items.concat(entry.items);\n } else {\n out.push(entry);\n }\n }\n \n return out;\n}\n\nconsole.log(mergeIds(array));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T11:53:06.357", "Id": "498699", "Score": "0", "body": "Thank you so much for the advice! I appreciate your time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T10:31:10.890", "Id": "252979", "ParentId": "252978", "Score": "3" } }, { "body": "<p>You can reduce the computational complexity to <code>O(n)</code> by putting the intermediate arrays into an object indexed by <code>id</code>. This way, for every array item, you just need to look up the <code>id</code> property on the object, and don't need to search through every item in the array for a possible match:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>array = [{\n id: 1,\n items: [1, 2, 3]\n },\n {\n id: 2,\n items: [1, 2]\n },\n {\n id: 1,\n items: [4]\n },\n {\n id: 3,\n items: [1]\n },\n];\n\nconst mergeIds = (list) =&gt; {\n const subarrsById = {};\n for (const { id, items } of list) {\n if (!subarrsById[id]) {\n subarrsById[id] = { id, items: [...items] };\n } else {\n subarrsById[id].items.push(...items);\n }\n }\n return Object.values(subarrsById);\n}\n\nconsole.log(mergeIds(array));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>One caveat - this will result in the output array being sorted by ascending array index, rather than by order of occurrence in the original array (because that's how object keys are arranged). If that's an issue, you can use a <code>Map</code> instead.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>array = [{\n id: 1,\n items: [1, 2, 3]\n },\n {\n id: 2,\n items: [1, 2]\n },\n {\n id: 1,\n items: [4]\n },\n {\n id: 3,\n items: [1]\n },\n];\n\nconst mergeIds = (list) =&gt; {\n const subarrsById = new Map();\n for (const { id, items } of list) {\n if (!subarrsById.has(id)) {\n subarrsById.set(id, { id, items: [...items] });\n } else {\n subarrsById.get(id).items.push(...items);\n }\n }\n return [...subarrsById.values()];\n}\n\nconsole.log(mergeIds(array));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>A suggestion regarding your original code:</p>\n<blockquote>\n<pre><code> processedIds.indexOf(elementId) === -1\n</code></pre>\n</blockquote>\n<p>When you want to check if an array contains an element, it's more natural to use <code>.includes</code> rather than an <code>.indexOf</code> check against -1.</p>\n<p>Also, when creating a collection of processed primitives (like the IDs here), and you need to regularly check that collection to see if a particular primitive has been processed yet, consider using a Set and <code>Set#has</code> (<code>O(1)</code>) instead of an array and <code>Array#includes</code> (<code>O(n)</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T14:27:50.137", "Id": "498713", "Score": "0", "body": "Love `const { id, items } of list`, nice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:04:47.533", "Id": "498727", "Score": "0", "body": "Thank you so much for all the details!! I am indebted!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T14:15:58.527", "Id": "252985", "ParentId": "252978", "Score": "3" } } ]
{ "AcceptedAnswerId": "252979", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T09:46:36.883", "Id": "252978", "Score": "3", "Tags": [ "javascript", "performance", "complexity" ], "Title": "Merge arrays in objects in array based on property" }
252978
<p>This is my first attemp with Lua.</p> <p>I decided to create this class, because it have lots of &quot;tweaks&quot; and &quot;tricks&quot;.</p> <p>I want to know if I did it as best practices Lua ways.</p> <p>My Lua version is 5.4.1</p> <pre><code>require &quot;math&quot; Complex = { IMAGINARY_CHAR = &quot;i&quot; } function Complex:new(r, i) o = { r = r, i = i } setmetatable(o, self) self.__index = self return o end function Complex:__newindex(r, i) end function Complex:__unm() return Complex:new( -self.r, -self.i ) end function Complex:__add(other) if type(other) == &quot;number&quot; then return Complex:new( self.r + other, self.i ) else return Complex:new( self.r + other.r, self.i + other.i ) end end function Complex:__sub(other) return self:__add(- other); end function Complex:__mul(other) if type(other) == &quot;number&quot; then return Complex:new( self.r * other, self.i * other ) else return Complex:new( self.r * other.r - self.i * other.i, self.i * other.r + self.r * other.i ) end end function Complex:__eq(other) return self.r == other.r and self.i == other.i end function Complex:__lt(other) -- incorrect but for sorting if self.r == other.r then return self.i &lt; other.i else return self.r &lt; other.r end end function Complex:tostring(i) if type(i) ~= &quot;string&quot; then i = &quot;i&quot; end if self.r == 0 and self.i == 0 then return &quot;( 0 )&quot; elseif self.i == 0 then return &quot;( &quot; .. self.r .. &quot; )&quot; -- elseif self.r == 0 then -- return &quot;( &quot; .. i .. self.i .. &quot; )&quot; else return &quot;( &quot; .. self.r .. &quot; + &quot; .. i .. self.i .. &quot; )&quot; end end function Complex:__tostring(i) return self:tostring(self.IMAGINARY_CHAR) end function Complex:abs2() return self.r * self.r + self.i * self.i end function Complex:abs() return math.sqrt(self:abs2()) end -- =================================================================== Complex.IMAGINARY_CHAR = &quot;j&quot; -- Electrical notation x = Complex:new(0, 10) y = Complex:new(-5, 5) print(x) print(y) print(x:abs()) print(y:abs()) print(x + y) print(x - y) print(x + 12) print(x - 12) print(x == y) print(x ~= y) print(x ~= x) print(x ~= x) print(x &lt; y) print(x &gt; y) print(x &lt;= y) print(x &gt;= y) </code></pre>
[]
[ { "body": "<p>Possible improvements:</p>\n<ul>\n<li>localise functions of the <code>math</code> library, and sometimes, <code>self.r</code> and <code>self.i</code>. It will reduce the number of table lookups, improving the performance, and will make the expressions simpler,</li>\n<li>define <code>__call</code> metamethod for <code>Complex</code>. It will allow you to replace <code>Complex:new(x, y)</code> with <code>Complex(x, y)</code>,</li>\n<li>the 'constructor' should correctly handle cases when it is called with one parameter (<code>Complex(5)</code> = 5 + 0i). It can be achieved with a 'nullsafe operator' emulated as <code>local a = user_input or value_if_null</code>,</li>\n<li>in can also be mage more concise, using the fact that <code>setmetatable</code> returns the table,</li>\n<li><code>__newindex</code> metamethod is not needed here, unless you want to set the absolute value or phase with code like <code>c.abs = 1</code> or <code>code.arg = pi</code>. In addition, the arguments to <code>__newindex</code> are the table, the absent key and value set to it,</li>\n<li>you can emulate the ternary operator in Lua with <code>and</code> and <code>or</code>, which allows to write more concise code: <code>local a = condition and on_success or on_failure</code>,</li>\n<li>your arithmetic metamethods should handle the cases when the first argument (<code>self</code>) is a number,</li>\n<li>you can define <code>conjugate</code> method and <code>__div</code> metamethod for division,</li>\n<li>to square a table element, I'd rather recommend using <code>^</code> rather than multiplying by self. It will save table lookups,</li>\n<li>you can define methods for polar coordinates and <code>__pow</code> metamethod for Euler's and de Moivre's formulae,</li>\n<li>the <code>__lt</code> metamethod can be simplified using boolean operations,</li>\n<li><code>Complex:tostring()</code> can be simplified using 'ternary' operators, also handling of negative imaginary parts can be improved,</li>\n<li>whether to put the <em>i</em> before or after the imaginary part and whether to surround a complex number with parentheses can be customisable,</li>\n<li>the expression tests can be automated somewhat with <code>load()</code> function.</li>\n</ul>\n<p>The improved code:</p>\n<pre class=\"lang-lua prettyprint-override\"><code>local math = require 'math'\nlocal pi, sin, cos, atan2 = math.pi, math.sin, math.cos, math.atan2\nlocal sqrt, exp, ln = math.sqrt, math.exp, math.log\nlocal floor, abs = math.floor, math.abs\n\nComplex = {\n IMAGINARY_CHAR = 'i'\n}\n\nfunction Complex:new(r, i)\n self.__index = self\n return setmetatable({r = r, i = i or 0}, self)\nend\n\nsetmetatable(Complex, {\n __call = function (tbl, r, i)\n return Complex:new(r, i)\n end}\n)\n\nfunction Complex:__unm()\n return Complex(-self.r, -self.i)\nend\n\nfunction Complex:__add(other)\n return type(self) == 'number' and Complex(self + other.r, other.i)\n or type(other) == 'number' and Complex(self.r + other, self.i)\n or Complex(self.r + other.r, self.i + other.i)\nend\n\nfunction Complex:__sub(other)\n return self + (-other);\nend\n\nfunction Complex:__mul(other)\n return type(self) == 'number' and Complex(self * other.r, self * other.i)\n or type(other) == 'number' and Complex(self.r * other, self.i * other)\n or Complex(self.r * other.r - self.i * other.i, self.i * other.r + self.r * other.i)\nend\n\nfunction Complex:conjugate()\n return Complex(self.r, -self.i)\nend\n\nfunction Complex:__div(denominator)\n -- https://www.mesacc.edu/~scotz47781/mat120/notes/complex/dividing/dividing_complex.html\n local conjugate = type(denominator) == 'number' and Complex(denominator) or denominator:conjugate()\n local new_numerator, new_denominator = self * conjugate, denominator * conjugate\n -- new_denominator is real.\n return Complex(new_numerator.r / new_denominator.r, new_numerator.i / new_denominator.r)\nend\n\nfunction Complex:abs2()\n return self.r ^ 2 + self.i ^ 2\nend\n\nfunction Complex:abs()\n return sqrt(self:abs2())\nend\n\nfunction Complex:polar(abs, arg)\n return Complex(abs * cos(arg), abs * sin(arg))\nend\n\nfunction Complex:arg()\n return atan2(self.i, self.r)\nend\n\nfunction Complex:exp()\n local abs = exp(self.r)\n return Complex(abs * cos(self.i), abs * sin(self.i))\nend\n \nfunction Complex:__pow(power)\n -- Euler:\n local x = type(self) == 'number' and self or self.i == 0 and self.r &gt; 0 and self.r or nil\n if x then\n return (power * ln(x)):exp()\n else\n -- de Moivre:\n local n = type(power) == 'number' and power or power.i == 0 and power.r or nil\n if n and floor(n) == n then\n local abs, arg = self:abs(), self:arg()\n return Complex:polar(abs ^ n, n * arg)\n end\n end\nend\n\nfunction Complex:__eq(other)\n return\n self.r == other.r and\n self.i == other.i\nend\n\nfunction Complex:__lt(other)\n -- incorrect but for sorting:\n return self.r &lt; other.r or self.r == other.r and self.i &lt; other.i\nend\n\nfunction Complex:tostring(i, prefix, parentheses)\n local im = type(i) == 'string' and i or 'i'\n local r, i = self.r, self.i\n \n local str = ((r ~= 0 or i == 0) and r or '')\n .. (r ~= 0 and i &gt; 0 and ' + ' or '')\n .. (i &lt; 0 and ' - ' or '')\n .. (i ~= 0 and (prefix and im .. abs(i) or abs(i) .. im) or '')\n if parentheses then\n str = '(' .. str .. ')'\n end\n return str\nend\n\nfunction Complex:__tostring(i)\n return self:tostring(self.IMAGINARY_CHAR, self.PREFIX, self.PARENTHESES)\nend\n\n-- ===================================================================\n\nComplex.IMAGINARY_CHAR = 'j' -- electrical notation.\nComplex.PREFIX = true\nComplex.PARENTHESES = true\n\nlocal context = {\n Complex = Complex,\n x = Complex(0, 10),\n y = Complex(-5, 5),\n z = Complex(5),\n pi = pi\n}\n\nlocal cases = {\n 'x', 'y', 'z', 'x:abs()',\n 'x + y', 'x - y', 'x + 12', 'x - 12', '12 + x', '12 - x',\n 'x * y', 'y * 12', '2 * x',\n 'y:conjugate()', 'x / y', 'y / y', 'x / 5', '5 / x', '5 / x * x',\n 'y:abs()', 'y:arg() / pi * 180', 'Complex:polar(2, pi / 4)', 'y:exp()', 'x ^ 2', '2 ^ x',\n 'x == y', 'x ~= y', 'x &lt; y', 'x &gt; y', 'x &lt;= y', 'x &gt;= y'\n}\nfor _, expr in ipairs(cases) do\n print(expr, assert(load('return ' .. expr, nil, 't', context))())\nend\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:39:47.167", "Id": "498786", "Score": "0", "body": "Thanks a lot. Did not know ternary operations returns underline types. Do you think `_sub` shall be implemented in this way or just copy paste `_add` - second will be faster? Isn't `^` slow operation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T07:58:58.230", "Id": "498915", "Score": "1", "body": "I think that `__sub` will be faster as `return Complex(self.r - subtrahend.r, self.i - subtrahend.i)` than `return self + (-subtrahend)`: one function call fewer.\n\nI tested squaring on my PC: under Lua 5.1 and 5.2 squaring by multiplication was slightly faster. Under Lua 5.3, power was about 40% faster. Haven't got Lua 5.4." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T06:32:37.740", "Id": "253022", "ParentId": "252982", "Score": "4" } } ]
{ "AcceptedAnswerId": "253022", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T12:12:52.737", "Id": "252982", "Score": "4", "Tags": [ "lua", "complex-numbers" ], "Title": "Complex number class in Lua" }
252982
<p>I want to implement <a href="https://en.wikipedia.org/wiki/Color_space" rel="nofollow noreferrer">color space</a> logic.</p> <p>So I started with creating some structs:</p> <pre><code>struct RGB { unsigned char r,g,b; }; struct ARGB { unsigned char a,r,g,b; }; struct HSL { float h,s,l; }; struct Lab { float l,a,b; }; </code></pre> <p>As you can see, I have different color spaces in my program: the <a href="https://en.wikipedia.org/wiki/RGB_color_model" rel="nofollow noreferrer">RGB</a> and <a href="https://en.wikipedia.org/wiki/CIE_1931_color_space" rel="nofollow noreferrer">CIEXYZ</a>. Then I realized that I have to do operator overloading for all of the structs (color models), so I started thinking about creating a <em>base <code>struct ColorModel</code></em> which has to somehow do all the operator overloading. But I can't have any virtual functions =&gt; pointers to <code>vtable</code>, as it will increase the size of any pixel and imagine what will be the size of a picture in my ram? So I decided to do some <code>template metaprogramming</code>, <a href="https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">CRTP</a> to be more specific. I created my base struct like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;array&gt; namespace color_space { template&lt;int Space, typename T, typename C&gt; struct ColorModel { static constexpr int SPACE = Space; ColorModel() { std::fill(begin(), end(), 0); }; ColorModel(const ColorModel&amp; other) { std::copy(other.begin(), other.end(), begin()); } ColorModel(ColorModel&amp;&amp; other) noexcept { std::move(other.begin(), other.end(), begin()); } ColorModel(const std::initializer_list&lt;T&gt;&amp; l) { std::copy(l.begin(), l.end(), begin()); } explicit ColorModel(const T&amp; elem) { std::fill(begin(), end(), elem); } const T* cbegin() const { return static_cast&lt;const C*&gt;(this)-&gt;components.cbegin(); } const T* cend() const { return static_cast&lt;const C*&gt;(this)-&gt;components.cend(); } const T* begin() const { return cbegin(); } const T* end() const { return cend(); } T* begin() { return static_cast&lt;C*&gt;(this)-&gt;components.begin(); } T* end() { return static_cast&lt;C*&gt;(this)-&gt;components.end(); } size_t size() const { return std::distance(begin(), end()); } const T&amp; operator[](unsigned int i) const { return *(begin() + i); } T&amp; operator[](unsigned int i) { return *(begin() + i); } ColorModel&amp; operator=(const ColorModel&amp; rhs) { std::copy(rhs.begin(), rhs.end(), begin()); return *this; } ColorModel&amp; operator=(ColorModel&amp;&amp; rhs) noexcept { std::move(rhs.begin(), rhs.end(), begin()); return *this; } ColorModel&amp; operator=(const T&amp; rhs) { std::fill(begin(), end(), rhs); return *this; } ColorModel&amp; operator=(T&amp;&amp; rhs) noexcept { std::fill(begin(), end(), rhs); return *this; } ColorModel&amp; operator+=(const ColorModel&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::plus&lt;&gt;()); return *this; } ColorModel&amp; operator+=(ColorModel&amp;&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::plus&lt;&gt;()); return *this; } ColorModel&amp; operator+=(const T&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem += rhs; }); return *this; } ColorModel&amp; operator+=(T&amp;&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem += rhs; }); return *this; } ColorModel&amp; operator-=(const ColorModel&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::minus&lt;&gt;()); return *this; } ColorModel&amp; operator-=(ColorModel&amp;&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::minus&lt;&gt;()); return *this; } ColorModel&amp; operator-=(const T&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem -= rhs; }); return *this; } ColorModel&amp; operator-=(T&amp;&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem -= rhs; }); return *this; } ColorModel&amp; operator*=(const ColorModel&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::multiplies&lt;&gt;()); return *this; } ColorModel&amp; operator*=(ColorModel&amp;&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::multiplies&lt;&gt;()); return *this; } ColorModel&amp; operator*=(const T&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem *= rhs; }); return *this; } ColorModel&amp; operator*=(T&amp;&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem *= rhs; }); return *this; } ColorModel&amp; operator/=(const ColorModel&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::divides&lt;&gt;()); return *this; } ColorModel&amp; operator/=(ColorModel&amp;&amp; rhs) { std::transform(begin(), end(), rhs.begin(), begin(), std::divides&lt;&gt;()); return *this; } ColorModel&amp; operator/=(const T&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem /= rhs; }); return *this; } ColorModel&amp; operator/=(T&amp;&amp; rhs) { std::for_each(begin(), end(), [&amp;](T&amp; elem) { elem /= rhs; }); return *this; } ColorModel operator+(const ColorModel&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::plus&lt;&gt;()); return result; } ColorModel operator+(ColorModel&amp;&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::plus&lt;&gt;()); return result; } ColorModel operator+(const T&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] + rhs; } return result; } ColorModel operator+(T&amp;&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] + rhs; } return result; } ColorModel operator-(const ColorModel&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::minus&lt;&gt;()); return result; } ColorModel operator-(ColorModel&amp;&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::minus&lt;&gt;()); return result; } ColorModel operator-(const T&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] - rhs; } return result; } ColorModel operator-(T&amp;&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] - rhs; } return result; } ColorModel operator*(const ColorModel&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::multiplies&lt;&gt;()); return result; } ColorModel operator*(ColorModel&amp;&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::multiplies&lt;&gt;()); return result; } ColorModel operator*(const T&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] * rhs; } return result; } ColorModel operator*(T&amp;&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] * rhs; } return result; } ColorModel operator/(const ColorModel&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::divides&lt;&gt;()); return result; } ColorModel operator/(ColorModel&amp;&amp; rhs) const { ColorModel result; std::transform(begin(), end(), rhs.begin(), result.begin(), std::divides&lt;&gt;()); return result; } ColorModel operator/(const T&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] / rhs; } return result; } ColorModel operator/(T&amp;&amp; rhs) const { ColorModel result; #pragma clang loop vectorize(enable) for (int i = 0; i &lt; size(); ++i) { result[i] = (*this)[i] / rhs; } return result; } bool operator==(const ColorModel&amp; rhs) const { return std::equal(begin(), end(), rhs.begin(), rhs.end()); } bool operator!=(const ColorModel&amp; rhs) const { return !(*this == rhs); } }; template&lt;int Space, typename T, typename C&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const ColorModel&lt;Space, T, C&gt;&amp; space) { for (const T&amp; component: space) { os &lt;&lt; component &lt;&lt; &quot; &quot;; } return os; } </code></pre> <p>And my structs will be implemented like this:</p> <pre><code>struct RGB : ColorModel&lt;0,unsigned char, RGB&gt; { union { std::array&lt;unsigned char,3&gt; components; struct { unsigned char r,g,b; } } // Base constructors call }; </code></pre> <p>I would be very grateful if you review this implementation of operator overloading.</p> <p>P.S. The first argument <code>int Space</code> in the template argument list will be used after. I am going to write a logic to convert from one space to another, but that is a different question.</p>
[]
[ { "body": "<p>I'm not sure it's safe to <code>union</code> a standard array and a struct like that. I would make <code>r</code>, <code>g</code> and <code>b</code> be member <em>functions</em> instead:</p>\n<pre><code>unsigned char&amp; r() { return components[0]; }\nunsigned char const&amp; r() const { return components[0]; }\n</code></pre>\n<p>(You could make <code>r</code>, <code>g</code> and <code>b</code> members be references into <code>components</code>, but compilers might reserve distinct space for them, and you wouldn't be able to use the default compiler-generated copy/move constructor and assignment).</p>\n<p>Detailed review:</p>\n<blockquote>\n<pre><code>size_t size() const {\n</code></pre>\n</blockquote>\n<p><code>size_t</code> is in the <code>std</code> namespace, and you need to include one of the header files that defines it.</p>\n<pre><code>#include &lt;cstddef&gt;\nstd::size_t size() const {\n</code></pre>\n<p>Looking at the implementation, it might be better to write <code>size()</code> in terms of the template parameter <code>C</code>. That would mean it could be declared <code>constexpr</code>, which could help compilers to optimise the arithmetic operators.</p>\n<p>The arithmetic operators are all likely to overflow in use - you might want to implement some saturating arithmetic for the values to be useful in real image-processing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T19:27:40.693", "Id": "498738", "Score": "0", "body": "Thank you! May I ask you to review it again after I apply your suggestions? Or shall I ask it as a different question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:39:01.190", "Id": "498784", "Score": "0", "body": "It's generally best to ask as a new question. Two reasons: you can't expect me to still be available, and you really want more than one reviewer to give you the best range of suggestions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T16:16:08.330", "Id": "252991", "ParentId": "252983", "Score": "1" } } ]
{ "AcceptedAnswerId": "252991", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T13:00:37.637", "Id": "252983", "Score": "2", "Tags": [ "c++", "inheritance", "template-meta-programming", "overloading", "color" ], "Title": "Colour-model classes using CRTP" }
252983
<p>I was hoping someone could review my C++ console based noughts and crosses (Tic Tac Toe) application. I have not looked at any other documentation, this is purely programmed from the top of my head. Can you tell me what I've done well, what I haven't done well, and suggest any improvements I can make to it. If you decide to run this program ensure C++ 17 is specified (not that you need to be told that). Please treat it how it's supposed to be treated. I haven't included validation for inputs.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;utility&gt; #include &lt;algorithm&gt; void Displaygrid(const std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;&amp;grid) { std::for_each(grid.begin(), grid.end(), [&amp;](auto pairVec) { std::for_each(pairVec.begin(), pairVec.end(), [&amp;](auto pair) { if (pair.second != '-') { std::cout &lt;&lt; pair.second &lt;&lt; &quot; &quot;; } else { std::cout &lt;&lt; pair.first &lt;&lt; &quot; &quot;; } } ); std::cout &lt;&lt; &quot;\n&quot;; }); } bool CheckForAWinner(const std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;&amp;grid, const unsigned char key) { if (grid.at(0).at(0).second == key &amp;&amp; grid.at(0).at(1).second == key &amp;&amp; grid.at(0).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(1).at(0).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(1).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(2).at(0).second == key &amp;&amp; grid.at(2).at(1).second == key &amp;&amp; grid.at(2).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(0).at(0).second == key &amp;&amp; grid.at(1).at(0).second == key &amp;&amp; grid.at(2).at(0).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(0).at(1).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(2).at(1).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(0).at(2).second == key &amp;&amp; grid.at(1).at(2).second == key &amp;&amp; grid.at(2).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(0).at(0).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(2).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(2).at(0).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(0).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (grid.at(2).at(0).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(0).at(2).second == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else { return false; } } bool ClaimSquare(std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;&amp; grid, int move, const unsigned char player) { for (auto&amp; vec : grid) { auto validSquare = std::find_if(vec.begin(), vec.end(), [&amp;](auto pair) { return pair.first == move; }); if (validSquare != vec.end()) { if (validSquare-&gt;second == '-') { validSquare-&gt;second = player; return true; } else { std::cout &lt;&lt; &quot;This square has already been claimed. Choose a different square!&quot; &lt;&lt; std::endl; return false; } } } } void PlayerMove(std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;&amp; grid, unsigned char player) { int move = 0; do { move = 0; Displaygrid(grid); std::cout &lt;&lt; player &lt;&lt; &quot; turn: &quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Enter a number on the grid (e.g. 1): &quot;; std::cin &gt;&gt; move; } while (ClaimSquare(grid, move, player) == false); } void PlayNoughtsAndCrosses() { const unsigned char player1 = 'O'; const unsigned char player2 = 'X'; std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;grid = { {std::make_pair(1,'-'), std::make_pair(2,'-'), std::make_pair(3,'-') }, {std::make_pair(4,'-'), std::make_pair(5,'-'), std::make_pair(6,'-') }, {std::make_pair(7,'-'), std::make_pair(8,'-'), std::make_pair(9,'-') } }; do { PlayerMove(grid, player1); if (CheckForAWinner(grid, player1)) { break; } PlayerMove(grid, player2); } while (CheckForAWinner(grid, player2) == false); } int main() { PlayNoughtsAndCrosses(); } </code></pre>
[]
[ { "body": "<h2>Overview</h2>\n<p>Not much in the way of OO design.<br />\nNot required but unusual for C++ application. With a bit of abstraction you can make multiple types of player all able to play the game (thus you could have a normal user or a computer plater play the game (see blow)).</p>\n<h2>Design</h2>\n<p>Your grid seems a bit over complex:</p>\n<pre><code>std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;grid =\n{\n {std::make_pair(1,'-'), std::make_pair(2,'-'), std::make_pair(3,'-') },\n {std::make_pair(4,'-'), std::make_pair(5,'-'), std::make_pair(6,'-') },\n {std::make_pair(7,'-'), std::make_pair(8,'-'), std::make_pair(9,'-') }\n};\n</code></pre>\n<p>Each time you need to find a square you search the grid. I mean its not that bad as the grid is very small. But you could have made that very easy by simply having an array of 9 squares and indexing directly into it.</p>\n<pre><code>char grid[9] = {'-', ....};\n</code></pre>\n<p>It would have made printing different but getting the square would be a lot simpler.</p>\n<pre><code>grid[move - 1] returns the square you are looking for.\n</code></pre>\n<p>Even if you had gone for a simple 2D array:</p>\n<pre><code>char grid[3][3] = {{'-', ....};\n</code></pre>\n<p>Then access to the square would have been:</p>\n<pre><code>grid[(move - 1) / 3][(move - 1) % 3] returns the square you are looking for.\n</code></pre>\n<h2>Code Review</h2>\n<p>Looks like you could have designed the game loop in a simpler way:</p>\n<pre><code>const unsigned char player1 = 'O';\nconst unsigned char player2 = 'X';\ndo \n{\n PlayerMove(grid, player1);\n\n if (CheckForAWinner(grid, player1)) \n {\n break;\n }\n\n PlayerMove(grid, player2);\n} \nwhile (CheckForAWinner(grid, player2) == false);\n</code></pre>\n<p>Why not use a loop that switch between players?</p>\n<pre><code>int currentPlayer = 1;\nconst unsigned char player[2] = {'O', 'X'};\ndo \n{\n currentPlayer = (currentPlayer + 1) % 2;\n PlayerMove(grid, player[currentPlayer]);\n} \nwhile (CheckForAWinner(grid, player[currentPlayer]) == false);\n</code></pre>\n<hr />\n<p>You have the same line twice:</p>\n<pre><code>else if (grid.at(2).at(0).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(0).at(2).second == key) {\n std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl;\n return true;\n}\nelse if (grid.at(2).at(0).second == key &amp;&amp; grid.at(1).at(1).second == key &amp;&amp; grid.at(0).at(2).second == key) {\n std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl;\n return true;\n}\n</code></pre>\n<hr />\n<p>Not sure the <code>std::for_each()</code> is best here. Why not use a range based for?</p>\n<pre><code>void Displaygrid(const std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;&amp;grid)\n{\n std::for_each(grid.begin(), grid.end(), [&amp;](auto pairVec) \n {\n std::for_each(pairVec.begin(), pairVec.end(), [&amp;](auto pair) \n</code></pre>\n<p>Like this:</p>\n<pre><code>void Displaygrid(const std::vector&lt;std::vector&lt;std::pair&lt;int, unsigned char&gt;&gt;&gt;&amp;grid)\n{\n for(auto const&amp; row: grid) {\n for(auto const&amp; cell: row) { \n</code></pre>\n<h2>OO Design</h2>\n<pre><code>class Grid\n{\n // Interface for board here:\n};\nclass Player\n{\n public:\n virtual ~Player() {}\n virtual int getNextMove(Grid const&amp; grid) = 0;\n};\n\nclass Game\n{\n public:\n Game(Grid&amp; board, Player&amp; p1, Player&amp; p2);\n Player&amp; play(); // Play the game return a ref to winner.\n};\n\nclass Human: public Player\n{\n public:\n virtual int getNextMove(Grid const&amp; grid)\n {\n // Ask user for their move (like your app above).\n }\n};\n\nclass Robot: public Player\n{\n public:\n virtual int getNextMove(Grid const&amp; grid)\n {\n // Your AI code here.\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T18:46:24.923", "Id": "498734", "Score": "0", "body": "Thanks very much for your suggestions! The reason I didn’t use a RAW 2D array of chars and used a std::vector of std::vector of std::pairs instead is because I needed a way to access the grid coordinate and store the O or X at the coordinate, using the coordinate as the key to access the value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T20:35:17.920", "Id": "498749", "Score": "0", "body": "@Martin what should `Game.play` return in the case of a draw?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T12:55:41.443", "Id": "498800", "Score": "0", "body": "For the life of me I am unable to execute your OOP design for my program. I understand virtual functions and abstract classes to achieve dynamic polymorphism, however, I can't code this logically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:57:40.330", "Id": "498845", "Score": "0", "body": "@GeorgeAustinBradley Create a [gist](https://gist.github.com/) and show me what you have done so far." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:59:00.470", "Id": "498846", "Score": "0", "body": "Hi Martin York. I've submitted through another code review post here: If you could review it. I based it on your design with a few modifications. https://codereview.stackexchange.com/questions/253050/noughts-crosses-tic-tac-toe-oop-design" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:48:47.317", "Id": "252997", "ParentId": "252992", "Score": "4" } } ]
{ "AcceptedAnswerId": "252997", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T16:34:58.870", "Id": "252992", "Score": "4", "Tags": [ "c++", "tic-tac-toe", "c++17" ], "Title": "Noughts and Crosses (Tic Tac Toe) C++ Console Application" }
252992
<p>Can someone review my code and provide feedback. For context in column A will be a status message of &quot;OK&quot; or &quot;NOK&quot; and this little function just counts the number of times this appear so I can update a label in another procedure. Not too sure if this is the most efficient way of doing this because looping will create delay going row by row if the data set is very large as in the main procedure this function will be called to update the label is in a loop so depending on the size of the data it can be small or very large and will trigger this function for each row.</p> <pre><code>Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim OK As Long Dim NOK As Long Dim i As Long Dim uploadMsg As String If StartRow = 0 And EndRow = 0 Then Exit Function With WS For i = StartRow To EndRow If .Range(&quot;A&quot; &amp; i).value = &quot;OK&quot; Then OK = OK + 1 Else If .Range(&quot;A&quot; &amp; i).value &lt;&gt; vbNullString Then NOK = NOK + 1 End If End If Next i End With If OK &lt; 2 Then uploadMsg = OK &amp; &quot; OK row, &quot; Else uploadMsg = OK &amp; &quot; OK rows, &quot; End If If NOK &lt; 2 Then uploadMsg = uploadMsg &amp; NOK &amp; &quot; NOK row&quot; Else uploadMsg = uploadMsg &amp; NOK &amp; &quot; NOK rows&quot; End If If strMsg &lt;&gt; vbNullString Then UploadStatus = strMsg &amp; &quot; &quot; &amp; uploadMsg Else UploadStatus = uploadMsg End If End Function </code></pre>
[]
[ { "body": "<p>Don't reinvent the wheel. Your homemade function will <em>never</em> be as fast as the built in functions.</p>\n<pre><code>Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String\n Dim OK As Long\n Dim NOK As Long\n Dim uploadMsg As String\n \n If StartRow = 0 And EndRow = 0 Then \n Exit Function\n End If\n \n OK = WorksheetFunction.CountIf(&quot;A&quot; &amp; StartRow &amp; &quot;:A&quot; &amp; EndRow, &quot;OK&quot;)\n NOK = WorksheetFunction.CountIf(&quot;A&quot; &amp; StartRow &amp; &quot;:A&quot; &amp; EndRow, &quot;NOK&quot;)\n\n uploadMsg = ResultStringer(OK &amp; &quot;OK&quot;)\n uploadMsg = uploadMsg &amp; ResultStringer(NOK &amp; &quot;NOK&quot;)\n \n If strMsg &lt;&gt; vbNullString Then\n UploadStatus = strMsg &amp; &quot; &quot; &amp; uploadMsg\n Else\n UploadStatus = uploadMsg\n End If\n\nEnd Function\n\nPrivate Function ResultStringer(ByVal Count As Long, ByVal ID as String) as String\n\n If Count &gt; 1 Then\n ResultStringer = Count &amp; ID &amp; &quot; rows, &quot;\n Else\n ResultStringer = Count &amp; ID &amp; &quot; row, &quot;\n End If\n\nEnd Function \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:35:56.203", "Id": "498802", "Score": "0", "body": "I got type miss match and object required errors from your answer when I tested it. I posted a modified version fixing the errors below for completeness. Thanks for the suggestion using countif." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:54:03.803", "Id": "498805", "Score": "0", "body": "It was \"air coded\", so that's not surprising. Glad you go it working. Be sure to click the check-mark of the answer that helped you the _most_" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:30:01.677", "Id": "252996", "ParentId": "252993", "Score": "3" } }, { "body": "<p>This is a refined solution based on the answer above as I found few errors when testing like type miss match and object required.</p>\n<pre><code>Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String\nDim OK As Long\nDim NOK As Long\nDim uploadMsg As String\n \nIf StartRow = 0 And EndRow = 0 Then\n   Exit Function\nEnd If\n\n With WS.Application.WorksheetFunction\n    OK = .CountIf(Range(&quot;A&quot; &amp; StartRow &amp; &quot;:A&quot; &amp; EndRow), &quot;OK&quot;)\n    NOK = .CountIf(Range(&quot;A&quot; &amp; StartRow &amp; &quot;:A&quot; &amp; EndRow), &quot;NOK&quot;)\nEnd With\nuploadMsg = ResultStringer(OK, &quot;OK&quot;)\nuploadMsg = uploadMsg &amp; &quot;, &quot; &amp; ResultStringer(NOK, &quot;NOK&quot;)\n \nIf strMsg &lt;&gt; vbNullString Then\n   UploadStatus = strMsg &amp; &quot; &quot; &amp; uploadMsg\nElse\n   UploadStatus = uploadMsg\nEnd If\n \nEnd Function\nFunction ResultStringer(ByVal Count As Long, StatusID As String) As String\n \n  If Count &gt; 1 Then\n    ResultStringer = Count &amp; &quot; &quot; &amp; StatusID &amp; &quot; rows&quot;\n  Else\n    ResultStringer = Count &amp; &quot; &quot; &amp; StatusID &amp; &quot; row&quot;\n  End If\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:34:13.257", "Id": "253037", "ParentId": "252993", "Score": "1" } }, { "body": "<p>Personally, I would not worry about the pluralizing and use <code>row(s)</code> in the message. The <code>iif</code> can be used to simplify the code.</p>\n<pre><code>Function UploadStatus2(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String\n Dim Target As Range\n With WS\n On Error Resume Next\n Set Target = .Range(.Cells(StartRow, &quot;A&quot;), .Cells(EndRow, &quot;A&quot;))\n If Err.Number &lt;&gt; 0 Then Exit Function\n On Error GoTo 0\n End With\n Dim OK As Long, NOK As Long\n \n With WorksheetFunction\n OK = .CountIf(Target, &quot;OK&quot;)\n NOK = .CountIf(Target, &quot;NOK&quot;)\n UploadStatus2 = .TextJoin(&quot; &quot;, True, strMsg, OK, &quot;OK&quot;, &quot;row&quot; &amp; IIf(OK &gt; 1, &quot;s&quot;, &quot;&quot;), &quot;,&quot;, _\n NOK, &quot;OK&quot;, &quot;row&quot; &amp; IIf(NOK &gt; 1, &quot;s&quot;, &quot;&quot;))\n End With\n \nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T16:18:21.183", "Id": "499202", "Score": "0", "body": "thanks I think this is the most elegant way of combining everything and also efficient thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T22:15:29.390", "Id": "253063", "ParentId": "252993", "Score": "1" } } ]
{ "AcceptedAnswerId": "253063", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T17:08:14.790", "Id": "252993", "Score": "1", "Tags": [ "vba" ], "Title": "Count the status messages in a column VBA" }
252993
<p>I am solving this problem on SPOJ but I am getting Time Limit Exceeded Error. <a href="https://www.spoj.com/problems/HMRO/" rel="nofollow noreferrer">https://www.spoj.com/problems/HMRO/</a></p> <blockquote> <p>At the end of year 2004, the regional agencies of the Polish Military Recruitment Office (known as WKU in Polish) is sending a call to all boys born in 1984. Every recruit has his personal 11-digit identification number (PESEL, format: YYMMDDXXXXX, where YYMMDD is the date of birth, and XXXXX is a zero-padded integer smaller than 100000). Every agency of the Military Recruitment Office has its own code (MRO, format: a place code consisting of 3 upper case letters and a one-digit number). But this year the army underwent some reforms and not all boys at conscription age are going to be recruited. The list of closed down MRO points is as follows: the code of the closed down MRO is followed by the code of some other MRO, to which all the recruits are now going to be assigned. The list of recruits contains their PESEL codes. Your task is to prepare the complete list of recruits and determine the codes of their new MRO-s.</p> <h3>Input</h3> <pre><code>s [the number of tests &lt;= 10] p [the number of boys at conscription age &lt;= 100000] PESEL and MRO code z [the number of closed down MRO points &lt;= 100000] old_code new_code [old_code - the code of closed down MRO, new_code - its new MRO code] p [the number of recruits &lt;= 100000] PESEL [PESEL code of recruit] [empty line] [next tests] </code></pre> <h3>Output</h3> <pre><code>one PESEL and MRO code per line in the order of input [empty line between tests] [other results] </code></pre> <h3>Example</h3> <pre><code>Input: 1 4 84101011111 GDA1 84010122222 GDA2 84010233333 GDA2 84020255555 GDY1 1 GDA2 GDA1 3 84101011111 84010122222 84020255555 Output: 84101011111 GDA1 84010122222 GDA1 84020255555 GDY1 </code></pre> </blockquote> <p>Here is my code on Ideone with its input and output</p> <p><a href="https://ideone.com/h1RAiS" rel="nofollow noreferrer">https://ideone.com/h1RAiS</a></p> <p>anyway here is the code too. It seems to be working on the test cases I made myself but it is giving me TLE on spoj. Could you give me any suggestion how I can improve it?</p> <pre><code> #include &lt;iostream&gt; #include &lt;unordered_map&gt; #define BIG long long using namespace std; class RECRUIT { private: string x, y; string oMRO, nMRO; BIG pesel; string mro; unordered_map&lt;BIG, string&gt; PM; //(Pesel, MRO) unordered_map&lt;string, string&gt; mroNP; //MRO Node and Parent, keep a track of which mro is changed by which, in the beginning parent of each node is itself public: void insertPM(BIG p, string m) {PM.insert({p, m});} //insert pesel+mro the map PM (pesel, mro) void insertMroNP(string m1, string m2) {mroNP.insert({m1, m2});} void ReadMRO() {cin &gt;&gt; oMRO &gt;&gt; nMRO; if(!CHECK(oMRO, nMRO)) UNION(x, y);} void Print(BIG p) {cout &lt;&lt; p &lt;&lt; &quot; &quot; &lt;&lt; FIND(PM[p]) &lt;&lt; endl;} //Disjoing Set Union string FIND(string a) { if(mroNP[a] == a) return a; else return FIND(mroNP[a]); } void UNION(string a, string b) { mroNP[a] = b; } bool CHECK(string a, string b) { x = FIND(a); y = FIND(b); return x == y; //if they are equal do nothing else UNION(a, b); } //DSU ends here void PrintPM() {for(auto&amp;k : PM) cout &lt;&lt; k.first &lt;&lt; &quot; &quot; &lt;&lt; k.second &lt;&lt; endl;} void PrintNP() {for(auto&amp;k : mroNP) cout &lt;&lt; k.first &lt;&lt; &quot; &quot; &lt;&lt; k.second &lt;&lt; endl;} }; int main() { RECRUIT R; BIG pesel; string mro; int i, j; int t, n, m, p; cin &gt;&gt; t; for(i = 0; i &lt; t; i++) { cin &gt;&gt; n; //Read the number of boys at conscription age for(j = 0; j &lt; n; j++) {cin &gt;&gt; pesel &gt;&gt; mro; R.insertPM(pesel, mro); R.insertMroNP(mro, mro);} cin &gt;&gt; m; for(j = 0; j &lt; m; j++) {R.ReadMRO();} cin &gt;&gt; p; for(j = 0; j &lt; p; j++) {cin &gt;&gt; pesel; R.Print(pesel);} // R.PrintPM(); //Print pesel + mro (testing purpose) // R.PrintNP(); //Print node mro + parent mro (testing purpose) cout &lt;&lt; endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T18:46:34.323", "Id": "498735", "Score": "0", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/252998/revisions#rev-arrow-4d3ea767-591a-4a29-b84e-2ea4eb8652a1) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T15:30:43.553", "Id": "505583", "Score": "0", "body": "This question is incomplete. To help reviewers give you better answers, please [edit] to add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.codereview.stackexchange.com/q/1226)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T18:16:33.967", "Id": "252998", "Score": "0", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded" ], "Title": "HMRO - Help the Military Recruitment Office" }
252998
<p>Just wanted to share my Narcissistic Numbers Program with y'all (not sure if it's good, but I gave it my best). Hope you like it!</p> <p>This program prints out all the narcissistic numbers from the smallest number and biggest number's range. Ex. in the 1-100 range, only the narcissistic numbers will show on the console.</p> <p>Some of you may be wondering, &quot;<em>What the hell are narcissistic numbers??</em>&quot; Once you go through a number of examples, I'm sure they won't be as bad as they sound (no pun intended). Narcissistic numbers are also known as Armstrong numbers, though I'm going to use the term 'narcissistic' rather than 'Armstrong' to avoid being inconsistent and flipping back and forth.</p> <p><strong>Overview:</strong> Narcissistic numbers are numbers that are equivalent to the sum of the cubes of their digits (3-digit numbers). This definition's verbose structure confused me, but after looking through a couple of examples, it made much more sense.</p> <hr /> <p><strong>Procedure:</strong> (this is only applicable to 3-Digit Numbers)</p> <ul> <li>Pick a number: 153</li> </ul> <p>FYI: I broke the definition down into my own steps.</p> <ul> <li>I split the number up into its individual digits; 1, 5 and 3</li> <li>or you can just identify which digits the number (153 in this case) is composed of; 1, 5 and 3</li> </ul> <p>Both ways bear the same result, but I tend to over-complicate things, so you can choose which way to use.</p> <ul> <li>Now that all the digits are split up, we need to cube them all (separately) like this: [1⋅1⋅1] + [5⋅5⋅5] + [3⋅3⋅3]; I included the square brackets for clarity's sake.</li> </ul> <p>If you're <em>not</em> using brackets, then make sure you're following the <em>BEDMAS</em> rules.</p> <p>If you simply calculate the following in a calculator: <code>1⋅1⋅1 + 5⋅5⋅5 + 3⋅3⋅3</code>, then the result you will get is: <code>1025</code>.</p> <hr /> <p>I believe I have provided a thorough enough over-view as to what narcissistic numbers are. Now, I hope the code will be easier for many people to understand.</p> <p>The code is as follows:</p> <pre><code>import time initial_time = time.time() # initializing 's_number' (the smallest number) and 'l_num' (the largest number) s_number = 100 l_number = 500 for number in range(s_number, l_number + 1): # order of the numbers order = len(str(number)) # initializing sum sum = 0 var = number while var &gt; 0: digit = var % 10 sum += digit ** order var //= 10 # setting restrictions for program if number == sum: print(number) total_time = time.time() - initial_time print('Time to complete task:',total_time) </code></pre> <p>If there's anything to change/add to make the program more efficient/better please don't hesitate to let me know. I would appreciate your insight on this project.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T00:08:34.097", "Id": "498763", "Score": "1", "body": "_Narcissistic numbers are numbers that are equivalent to the sum of the cubes of their digits_ - is only true for 3-digit numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T00:16:02.120", "Id": "498764", "Score": "0", "body": "@ack thanks for reminding me of this. I totally forgot to specify that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T04:05:15.577", "Id": "498772", "Score": "2", "body": "Huh? How did you get 1025?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:37:25.297", "Id": "498783", "Score": "0", "body": "The code is okay, nothing much to review, as a side note, you might want to reduce your use of python keywords such as `sum`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:10:41.757", "Id": "498806", "Score": "0", "body": "@superbrain when I put the numbers in the order the way I showed in the example I did get 1025." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:11:09.917", "Id": "498807", "Score": "0", "body": "@theProgrammer I keep forgetting to do that. Thanks!" } ]
[ { "body": "<p>Nice solution, it's already efficient and easy to understand. Few general suggestions:</p>\n<ul>\n<li><strong>Avoid calling a variable <code>sum</code></strong>: <code>sum</code> is a built-in function in Python, calling a variable <code>sum</code> prevents you from using such function.</li>\n<li><strong><code>time.perf_counter</code> vs <code>time.time</code></strong>: running your code I get <code>0.0</code> running time on Windows, which doesn't provide a useful information. Use <a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"noreferrer\">time.perf_counter</a> to get a better precision.</li>\n<li><strong>Make a function and return a result</strong>: if you wrap the code in a function it is easier to reuse and test. Additionally, instead of printing the numbers, add them to a list and return the final result. Printing only the result is typically faster than printing the numbers one by one.</li>\n<li><strong>Armstrong numbers</strong>: a narcissistic number is also called <a href=\"https://en.wikipedia.org/wiki/Narcissistic_number\" rel=\"noreferrer\">Armstrong number</a> and <a href=\"https://oeis.org/A005188\" rel=\"noreferrer\">here</a> there is an efficient approach that I slightly modified to fit this question:\n<pre><code>from itertools import combinations_with_replacement\n\ndef armstrong(n):\n numbers = []\n order = len(str(n))\n for k in range(1, order):\n a = [i ** k for i in range(10)]\n for b in combinations_with_replacement(range(10), k):\n x = sum(map(lambda y: a[y], b))\n if x &gt; 0 and tuple(int(d) for d in sorted(str(x))) == b:\n numbers.append(x)\n return sorted(numbers)\n</code></pre>\n</li>\n</ul>\n<p>Extending the definition of Narcissistic number to:</p>\n<blockquote>\n<p>An n-digit number that is the sum of the nth powers of its digits</p>\n</blockquote>\n<p>The Narcissistic numbers till 1000000 are:</p>\n<pre><code>1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834\n</code></pre>\n<p><strong>Runtime:</strong></p>\n<pre><code> n=1_000_000 n=10_000_000\nOriginal: 3.374 s 40.26 s\nArmstrong: 0.036 s 0.098 s\n</code></pre>\n<p><strong>Full code:</strong></p>\n<pre><code>import time\nfrom itertools import combinations_with_replacement\n\n\ndef original(n):\n numbers = []\n for number in range(1, n):\n order = len(str(number))\n total_sum = 0\n var = number\n while var &gt; 0:\n digit = var % 10\n total_sum += digit ** order\n var //= 10\n if number == total_sum:\n numbers.append(number)\n return numbers\n\n\ndef armstrong(n):\n numbers = []\n order = len(str(n))\n for k in range(1, order):\n a = [i ** k for i in range(10)]\n for b in combinations_with_replacement(range(10), k):\n x = sum(map(lambda y: a[y], b))\n if x &gt; 0 and tuple(int(d) for d in sorted(str(x))) == b:\n numbers.append(x)\n return sorted(numbers)\n\n# Correctness\nassert original(1000) == armstrong(1000)\n\n# Benchmark\nn = 1_000_000\n\ninitial_time = time.perf_counter()\noriginal(n)\ntotal_time = time.perf_counter() - initial_time\nprint(f'Original: {round(total_time, 3)} s')\n\ninitial_time = time.perf_counter()\narmstrong(n)\ntotal_time = time.perf_counter() - initial_time\nprint(f'Armstrong: {round(total_time, 3)} s')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T12:25:37.830", "Id": "498799", "Score": "0", "body": "That's great! Compared to my response this again proves that algorithmic optimization is definitely more important than everything more low-level." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:47:06.553", "Id": "498804", "Score": "0", "body": "Actually found a problem in your code ... it only works if n is a power of 10. Otherwise, your code cuts off too early. (try for n=99999)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:25:43.010", "Id": "498808", "Score": "0", "body": "Thank you so much for your detailed response @Marc. I'm still shocked as to how fast your program ran for '10 000 000'!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:01:49.170", "Id": "498812", "Score": "1", "body": "@Finomnis thanks and you are right, good catch. I guess would be enough to find the numbers till order+1 and add them to the result only if `<=n`, but I'll leave it up to OP ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:13:12.100", "Id": "498818", "Score": "1", "body": "@esker-luminous I am glad I could help! But as stated in my answer it's not my solution. It's from [here](https://oeis.org/A005188), specifically from \"Chai Wah Wu\". I just slightly adapted it to your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:24:53.360", "Id": "498822", "Score": "2", "body": "@Marc I understand that. But I appreciate you taking the time to read and answer my question (plus, u found that link and took the time to modify it, so thank you!!) " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T01:58:01.963", "Id": "499102", "Score": "0", "body": "@esker-luminous when you are satisfied with the answers, please consider choosing an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T15:27:11.453", "Id": "499184", "Score": "0", "body": "@Marc will do, just didn't have the time to check up on here." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T03:36:53.317", "Id": "253017", "ParentId": "253003", "Score": "6" } }, { "body": "<p>For the beginning, I rewrote your code to be a function, which makes it much easier for me to do rapid prototyping:</p>\n<pre><code>from time import perf_counter\n\ndef find_narcissistic_numbers(limit_low, limit_high):\n results = []\n for number in range(limit_low, limit_high + 1):\n\n # order of the numbers\n order = len(str(number))\n\n # initializing sum\n sum = 0\n\n var = number\n while var &gt; 0:\n digit = var % 10\n sum += digit ** order\n var //= 10\n\n # setting restrictions for program\n if number == sum:\n results.append(number)\n\n return results\n\ndef benchmark(method):\n t_start = perf_counter()\n result = method(100, 500000)\n t_end = perf_counter()\n print(f'{method.__name__}\\t {1000*(t_end-t_start):.2f} ms')\n if result != [153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084]:\n print(f'{method.__name__} failed! Result incorrect!')\n\nbenchmark(find_narcissistic_numbers)\n</code></pre>\n<p>Which currently gives me</p>\n<pre><code>find_narcissistic_numbers 1047.52 ms\n</code></pre>\n<p>With that as a starting point, my ideas are:</p>\n<ul>\n<li>try to find algorithmic improvements. That might be hard because the problem is already quite simple.</li>\n<li>benchmark each part of this code, try to find more efficient alternatives for e.g. <code>len(str())</code></li>\n<li>port the critical part of the code to rust (using pyo3) for improved performance</li>\n</ul>\n<hr />\n<h2>First round</h2>\n<p>I tried to combine calculating <code>order</code> and splitting the number into digits in one operation. Sadly, it did not yield any performance gain.</p>\n<pre><code>def find_narcissistic_numbers(limit_low, limit_high):\n results = []\n for number in range(limit_low, limit_high + 1):\n\n i = number\n\n digits = []\n while i &gt; 0:\n digits.append(i % 10)\n i //= 10\n\n order = len(digits)\n\n sum_value = 0\n for digit in digits:\n sum_value += digit ** order\n\n if number == sum_value:\n results.append(number)\n\n return results\n</code></pre>\n<pre><code>find_narcissistic_numbers 1050.50 ms\n</code></pre>\n<hr />\n<h2>Second round</h2>\n<p>After thinking about it more, I don't find any other optimization points. I think your original algorithm is quite the optimum.</p>\n<p>So to get any further performance increase, we need to start at a lower level of performance optimization.</p>\n<p>Python is in its nature quite a slow language, as it has an entire interpretation layer in between its commands and actual hardware. Therefore it would be beneficial to extract the critical code to another language that compiles directly to native bytecode and uses features like vectorization.</p>\n<p>Those are the most promising options in my opinion, as they fulfill that criterium and can be used to implement python functions:</p>\n<ul>\n<li>C</li>\n<li>C++</li>\n<li>Rust</li>\n</ul>\n<p>I personally find Rust to be the most convenient function to write Python code, as it automatically makes sure that all the memory management is done right.</p>\n<p>I use this skeleton to write the Rust function for Python:\n<a href=\"https://github.com/Finomnis/PythonCModule\" rel=\"nofollow noreferrer\">https://github.com/Finomnis/PythonCModule</a></p>\n<p>lib.rs:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use pyo3::prelude::*;\nuse pyo3::wrap_pyfunction;\n\n\n#[pyfunction]\nfn find_narcissistic_numbers_rust(_py: Python, limit_low: u32, limit_high: u32) -&gt; PyResult&lt;Vec&lt;u32&gt;&gt; {\n let mut results = vec![];\n\n for number in limit_low..=limit_high {\n let mut digits = vec![];\n\n let mut i = number;\n while i &gt; 0 {\n digits.push(i%10);\n i /= 10;\n }\n\n let order = digits.len() as u32;\n\n let sum = digits.iter().fold(0, |acc, x| acc + x.pow(order));\n\n if number == sum {\n results.push(number);\n }\n }\n\n Ok(results)\n}\n\n\n/// A Python module implemented in Rust.\n#[pymodule]\nfn __lib(_py: Python, m: &amp;PyModule) -&gt; PyResult&lt;()&gt; {\n m.add_function(wrap_pyfunction!(find_narcissistic_numbers_rust, m)?)?;\n Ok(())\n}\n</code></pre>\n<p>python:</p>\n<pre><code>from time import perf_counter\nfrom narcissisticNumbersRustModule import find_narcissistic_numbers_rust\n\ndef benchmark(method):\n t_start = perf_counter()\n result = method(100, 500000)\n t_end = perf_counter()\n print(f'{method.__name__}\\t {1000*(t_end-t_start):.2f} ms')\n if result != [153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084]:\n print(f'{method.__name__} failed! Result incorrect!')\n\nbenchmark(find_narcissistic_numbers_rust)\n</code></pre>\n<p>Result:</p>\n<pre><code>find_narcissistic_numbers_rust 84.00 ms\n</code></pre>\n<p>So that's about ~12 times faster!</p>\n<hr />\n<h2>Third round</h2>\n<p>Seeing Marc's answer made it painfully clear that algorithmic optimization is by far the most important part and should always be done first.</p>\n<p>I ran his code on my machine, to be able to compare it with my attempts:</p>\n<pre><code>def armstrong(limit_low, limit_high):\n numbers = []\n order = len(str(limit_high))\n for k in range(1, order+1):\n a = [i ** k for i in range(10)]\n for b in combinations_with_replacement(range(10), k):\n x = sum(map(lambda y: a[y], b))\n if x &gt; 0 and tuple(int(d) for d in sorted(str(x))) == b:\n numbers.append(x)\n return sorted(filter(lambda x: limit_low &lt;= x &lt;= limit_high, numbers))\n</code></pre>\n<p>And the result was:</p>\n<pre><code>armstrong 20.71 ms\n</code></pre>\n<p>Optimizing in hardware efficiency, by using a faster programming language or utilizing hardware features, only ever gives you a linear speedup.\nAlgorithmic optimization, however, has the chance to move your algorithm into a different complexity class, which can boost the speed exponentially. Literally exponentially, not a figure of speech.</p>\n<p>Now that we know the better algorithm, let's see if we can squeeze a little bit of juice out by porting it to Rust: (sorry, i'm just really in love with Rust recently :D )</p>\n<pre><code>use pyo3::prelude::*;\nuse pyo3::wrap_pyfunction;\n\nuse std::iter;\nuse itertools::Itertools;\n\nstruct CombinationsWithReplacementIterator {\n current: Vec&lt;u32&gt;\n}\n\nimpl Iterator for CombinationsWithReplacementIterator {\n type Item = Vec&lt;u32&gt;;\n\n fn next(&amp;mut self) -&gt; Option&lt;Vec&lt;u32&gt;&gt; {\n let mut overflow = true;\n\n for element in self.current.iter_mut().rev() {\n if *element == 9 {\n *element = 0;\n } else {\n *element += 1;\n overflow = false;\n break;\n }\n }\n\n let mut prev_element = 0;\n for element in self.current.iter_mut() {\n if *element &lt; prev_element {\n *element = prev_element;\n }\n prev_element = *element;\n }\n\n if overflow {\n None\n } else {\n Some(self.current.clone())\n }\n }\n}\n\nfn combinations_with_replacement(order: usize) -&gt; CombinationsWithReplacementIterator {\n CombinationsWithReplacementIterator{current:iter::repeat(0).take(order).collect()}\n}\n\n#[pyfunction]\nfn armstrong_rust(_py: Python, limit_low: u32, limit_high: u32) -&gt; PyResult&lt;Vec&lt;u32&gt;&gt; {\n let mut results = vec![];\n\n let order = limit_high.to_string().len() as u32;\n\n for current_order in 1..=order {\n let power_table: Vec&lt;u32&gt; = (0..10).map(|x:u32| x.pow(current_order)).collect();\n\n for combination in combinations_with_replacement(current_order as usize) {\n let number: u32 = combination.iter().map(|&amp;x| power_table[x as usize]).sum();\n let mut number_digits = vec![];\n {\n let mut i = number;\n while i &gt; 0 {\n number_digits.push(i%10);\n i /= 10;\n }\n }\n\n if number_digits.iter().sorted().zip(combination.iter()).all(|(a,b)| *a == *b) {\n results.push(number);\n }\n }\n }\n\n Ok(results.into_iter().filter(|&amp;x| x&gt;=limit_low &amp;&amp; x&lt;=limit_high).sorted().collect())\n}\n\n/// A Python module implemented in Rust.\n#[pymodule]\nfn __lib(_py: Python, m: &amp;PyModule) -&gt; PyResult&lt;()&gt; {\n m.add_function(wrap_pyfunction!(armstrong_rust, m)?)?;\n Ok(())\n}\n</code></pre>\n<p>Result:</p>\n<pre><code>armstrong_rust 2.73 ms\n</code></pre>\n<hr />\n<h2>Summary</h2>\n<ul>\n<li>Algorithmic optimizations are always highest priority</li>\n<li>When best algorithm is established, further low level optimization can be done</li>\n</ul>\n<p>Performance comparison:</p>\n<pre><code>find_narcissistic_numbers 1047.52 ms\nfind_narcissistic_numbers_rust 84.00 ms\narmstrong 20.71 ms\narmstrong_rust 2.73 ms\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:29:54.207", "Id": "498809", "Score": "1", "body": "Thank you for this explanation! I will make sure to use suggestions from your and Marc's code. Really appreciate it :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:50:18.363", "Id": "253026", "ParentId": "253003", "Score": "3" } } ]
{ "AcceptedAnswerId": "253017", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-03T23:02:06.677", "Id": "253003", "Score": "6", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "3-Digit Narcissistic Numbers Program - Python " }
253003
<p>I want to write read savefile function with smart pointers and SDL2. I have little expirience with smart pointers and just want to ask is my code good, correct and no memory leaks.</p> <p>this is my code:</p> <pre><code>std::shared_ptr&lt;SDL_RWops&gt; saveFile; </code></pre> <p>--</p> <pre><code>int GameEngine::ReadSave() { int Highlevel; //Open file for reading in binary saveFile = std::shared_ptr&lt;SDL_RWops&gt;(SDL_RWFromFile( &quot;data/save.txt&quot;, &quot;r&quot; ), SDL_RWclose); //File does not exist if( saveFile.get() == NULL ){ printf( &quot;Warning: Unable to open file! SDL Error: %s\n&quot;, SDL_GetError() ); Highlevel = 0; //Create file for writing saveFile = std::shared_ptr&lt;SDL_RWops&gt;(SDL_RWFromFile( &quot;data/save.txt&quot;, &quot;w+&quot; ), SDL_RWclose); if( saveFile.get() != NULL ){ printf( &quot;New save file created!\n&quot; ); //Initialize data SDL_RWwrite( saveFile.get(), &amp;Highlevel, sizeof(int), 1 ); } else { printf( &quot;Error: Unable to create savefile! SDL Error: %s\n&quot;, SDL_GetError() ); } } else{ //Load data printf( &quot;Reading save file...!\n&quot; ); SDL_RWread( saveFile.get(), &amp;Highlevel, sizeof(int), 1 ); } return Highlevel; } </code></pre>
[]
[ { "body": "<p>Your idea to wrap the result of <code>SDL_RWFromFile</code> in a smart pointer is a good idea. I recommend a few improvements:</p>\n<hr />\n<p>Factor out the opening-and-wrapping operations into a named function. For example:</p>\n<pre><code>auto OpenFile(const char *fname, const char *mode) {\n return std::shared_ptr&lt;SDL_RWops&gt;(SDL_RWFromFile(fname, mode), SDL_RWclose);\n}\n</code></pre>\n<hr />\n<pre><code>if( saveFile.get() == NULL ){\n</code></pre>\n<p>Your whitespace is all messed up here; and also, you should generally treat smart pointers the same way you'd treat regular pointers. Avoid using <code>.get()</code> and <code>.reset()</code> and so on, unless you have a specific reason you need to emphasize the &quot;object-ness&quot; of the smart pointer. Keep it simple by writing:</p>\n<pre><code>saveFile = OpenFile(&quot;data/save.txt&quot;, &quot;r&quot;);\nif (saveFile == nullptr) {\n printf(&quot;Warning: Unable to open savefile! SDL Error: %s\\n&quot;, SDL_GetError());\n Highlevel = 0;\n saveFile = OpenFile(&quot;data/save.txt&quot;, &quot;w+&quot;);\n if (saveFile == nullptr) {\n printf(&quot;Error: Unable to create savefile! SDL Error: %s\\n&quot;, SDL_GetError());\n } else {\n printf(&quot;New save file created!\\n&quot;);\n SDL_RWwrite(saveFile.get(), &amp;Highlevel, sizeof(Highlevel), 1);\n }\n} else {\n printf(&quot;Reading save file...!\\n&quot;);\n SDL_RWread(saveFile.get(), &amp;Highlevel, sizeof(Highlevel), 1);\n}\n</code></pre>\n<p>I notice that you are not checking the return value of <a href=\"https://wiki.libsdl.org/SDL_RWread\" rel=\"nofollow noreferrer\"><code>SDL_RWread</code></a> for errors. That's not great.</p>\n<p>Have you considered throwing an exception on failure, instead of using <code>printf</code> to report directly to the user? This would certainly streamline your code:</p>\n<pre><code>if (auto f = OpenFile(&quot;data/save.txt&quot;, &quot;r&quot;)) {\n printf(&quot;Reading save file...\\n&quot;);\n if (SDL_RWread(f.get(), &amp;Highlevel, sizeof(Highlevel), 1) != 1) {\n throw std::runtime_error(std::string(&quot;Save file format error: &quot;) + SDL_GetError());\n }\n} else if (auto f = OpenFile(&quot;data/save.txt&quot;, &quot;w+&quot;)) {\n printf(&quot;Writing new save file...\\n&quot;);\n Highlevel = 0;\n SDL_RWwrite(f.get(), &amp;Highlevel, sizeof(Highlevel), 1);\n} else {\n throw std::runtime_error(std::string(&quot;Unable to create save file: &quot;) + SDL_GetError());\n}\n</code></pre>\n<hr />\n<p>Finally, <code>shared_ptr</code> is overkill here because you never have more than one &quot;owner&quot; of the open file. You should certainly rewrite <code>OpenFile</code> to return a <code>unique_ptr</code> — a type which you can still implicitly convert to <code>shared_ptr</code> if you do ever need shared ownership of the file. See <a href=\"https://quuxplusone.github.io/blog/2020/01/24/openssl-part-1/#work-with-smart-pointers-by-default\" rel=\"nofollow noreferrer\">&quot;OpenSSL client and server from scratch, part 1&quot;</a>; it's basically this:</p>\n<pre><code>struct RWCloser { void operator()(SDL_RWops *p) const { SDL_RWclose(p); } };\n\nusing UniqueRWops = std::unique_ptr&lt;SDL_RWops, RWCloser&gt;;\n\nUniqueRWops OpenFile(const char *fname, const char *mode) {\n return UniqueRWops(SDL_RWFromFile(fname, mode));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:52:18.293", "Id": "498811", "Score": "1", "body": "It's also possible to overload `std::default_delete` for `SDL_RWops`, like in [this question](https://stackoverflow.com/questions/20283685/specialise-stddefault-delete-for-stdshared-ptr)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T21:50:17.533", "Id": "498902", "Score": "1", "body": "`std::default_delete` is not a customization point and should not be customized by the programmer. It's a library facility, like `std::less`. `std::less` _is_ the lifting of `a<b` into a functor; `std::default_delete` _is_ the lifting of `delete p` into a functor. It shall not be customized. If you want to specialize `unique_ptr<T,D>` with a custom `D`, just do that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T03:47:28.320", "Id": "253018", "ParentId": "253004", "Score": "2" } } ]
{ "AcceptedAnswerId": "253018", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T00:01:47.883", "Id": "253004", "Score": "1", "Tags": [ "c++", "pointers", "sdl" ], "Title": "How to use smart pointers with SDL2 (SDL_RWops)?" }
253004
<p>Though many have done it the other way around, I have not seen such code in many places. And, to be honest, I don't know why this cluster of <code>if</code>-statements, <code>for</code>-loops and <code>while</code>-loops works!</p> <pre><code>def parse_int(string): numbers = {'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':17,'eighteen':18,'nineteen':19,'twenty':20,'thirty':30,'forty':40,'fifty':50,'sixty':60,'seventy':70,'eighty':80,'ninety':90,'eighty-six': 86, 'thirty-one': 31, 'forty-three': 43, 'forty-two': 42, 'fifty-eight': 58, 'sixty-seven': 67, 'thirty-two': 32, 'thirty-five': 35, 'seventy-nine': 79, 'thirty-four': 34, 'fifty-seven': 57, 'twenty-nine': 29, 'eighty-nine': 89, 'ninety-four': 94, 'seventy-eight': 78, 'ninety-one': 91, 'forty-one': 41, 'sixty-two': 62, 'twenty-eight': 28, 'eighty-eight': 88, 'seventy-seven': 77, 'forty-seven': 47, 'eighty-five': 85, 'eighty-three': 83, 'fifty-two': 52, 'eighty-two': 82, 'fifty-five': 55, 'twenty-seven': 27, 'seventy-four': 74, 'thirty-seven': 37, 'twenty-six': 26, 'sixty-six': 66, 'eighty-four': 84, 'sixty-four': 64, 'forty-eight': 48, 'fifty-four': 54, 'eighty-one': 81, 'thirty-three': 33, 'forty-four': 44, 'fifty-nine': 59, 'thirty-eight': 38, 'forty-six': 46, 'sixty-nine': 69, 'sixty-one': 61, 'sixty-three': 63, 'ninety-eight': 98, 'seventy-six': 76, 'seventy-one': 71, 'ninety-three': 93, 'fifty-three': 53, 'fifty-six': 56, 'seventy-five': 75, 'eighty-seven': 87, 'ninety-seven': 97, 'ninety-six': 96, 'ninety-nine': 99, 'twenty-one': 21, 'twenty-five': 25, 'ninety-five': 95, 'thirty-nine': 39, 'sixty-eight': 68, 'thirty-six': 36, 'twenty-four': 24, 'seventy-three': 73, 'seventy-two': 72, 'ninety-two': 92, 'twenty-three': 23, 'twenty-two': 22, 'forty-nine': 49, 'sixty-five': 65, 'fifty-one': 51, 'forty-five': 45} powers = {'vigintitrillion': 1000000000000000000000000000000000000000000000000000000000000000000000000, 'septillion': 1000000000000000000000000, 'nonillion': 1000000000000000000000000000000, 'tredecillion': 1000000000000000000000000000000000000000000, 'vigintiquadrillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000, 'decillion': 1000000000000000000000000000000000, 'billion': 1000000000, 'duovigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000, 'thousand': 1000, 'duodecillion': 1000000000000000000000000000000000000000, 'septemdecillion': 1000000000000000000000000000000000000000000000000000000, 'vigintinonillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'octillion': 1000000000000000000000000000, 'quinvigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000, 'octodecillion': 1000000000000000000000000000000000000000000000000000000000, 'novemdecillion': 1000000000000000000000000000000000000000000000000000000000000, 'trigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'quindecillion': 1000000000000000000000000000000000000000000000000, 'duotrigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'quattuordecillion': 1000000000000000000000000000000000000000000000, 'quadrillion': 1000000000000000, 'vigintiseptillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'vigintillion': 1000000000000000000000000000000000000000000000000000000000000000, 'untrigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'centillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'undecillion': 1000000000000000000000000000000000000, 'vigintunillion': 1000000000000000000000000000000000000000000000000000000000000000000, 'million': 1000000, 'septvigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'vigintisextillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'vigintiduoillion': 1000000000000000000000000000000000000000000000000000000000000000000000, 'sextillion': 1000000000000000000000, 'octovigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'nonvigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'sexdecillion': 1000000000000000000000000000000000000000000000000000, 'vigintoctillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'sexvigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'trevigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000, 'unvigintillion': 1000000000000000000000000000000000000000000000000000000000000000000, 'hundred': 100, 'quattuorvigintillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000, 'quintillion': 1000000000000000000, 'googol': 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 'vigintiquintrillion': 1000000000000000000000000000000000000000000000000000000000000000000000000000000} result=0 a=string.split(&quot; &quot;) b=[] for c in a: if c in numbers: b.append(c) elif c in powers: b[-1]+=&quot; &quot;+c elif c==&quot;and&quot;: continue else: print(&quot;INVALID WORD:&quot;,c) return(None) for d, e in enumerate(b): if len(e.split(&quot; &quot;))==1: b[d]=numbers[e] else: b[d]=e.split(&quot; &quot;) b[d][0]=numbers[b[d][0]] f=1 while f&lt;len(b[d]): b[d][f]=powers[b[d][f]] f+=1 if not(isinstance(b[0],int)): while len(b[0])&gt;2: b[0][1]*=b[0][2] b[0].pop(2) while len(b)&gt;0: if len(b)==1: if isinstance(b[0],int): result+=b[0] b.pop(0) else: while len(b[0])&gt;1: b[0][0]*=b[0][1] b[0].pop(1) result+=b[0][0] b.pop(0) else: if isinstance(b[1],int): b[1]+=b[0][0]*b[0][1] b.pop(0) else: while len(b[1])&gt;2: b[1][1]*=b[1][2] b[1].pop(2) if b[0][1]&lt;b[1][1]: b[1][0]+=b[0][0]*b[0][1] b.pop(0) else: result+=b[0][0]*b[0][1] b.pop(0) return(result) </code></pre>
[]
[ { "body": "<p>Instead of the loooooooooooooooong series of <code>0</code>s for the numbers, you can use <code>**</code> to increase readability.</p>\n<p><code>return None</code> can be reduced to just <code>return</code>. Since the <code>len()</code> function will never will never return a negative value,\n<code>while len(b) &gt; 0:</code> is the equivalent of just <code>while len(b):</code></p>\n<pre><code>def parse_int(string):\n numbers = {'zero': 0,\n 'one': 1,\n 'two': 2,\n 'three': 3,\n 'four': 4,\n 'five': 5,\n 'six': 6,\n 'seven': 7,\n 'eight': 8,\n 'nine': 9,\n 'ten': 10,\n 'eleven': 11,\n 'twelve': 12,\n 'thirteen': 13,\n 'fourteen': 14,\n 'fifteen': 15,\n 'sixteen': 16,\n 'seventeen': 17,\n 'eighteen': 18,\n 'nineteen': 19,\n 'twenty': 20,\n 'twenty-one': 21,\n 'twenty-two': 22,\n 'twenty-three': 23,\n 'twenty-four': 24,\n 'twenty-five': 25,\n 'twenty-six': 26,\n 'twenty-seven': 27,\n 'twenty-eight': 28,\n 'twenty-nine': 29,\n 'thirty': 30,\n 'thirty-one': 31,\n 'thirty-two': 32,\n 'thirty-three': 33,\n 'thirty-four': 34,\n 'thirty-five': 35,\n 'thirty-six': 36,\n 'thirty-seven': 37,\n 'thirty-eight': 38,\n 'thirty-nine': 39,\n 'forty': 40,\n 'forty-one': 41,\n 'forty-two': 42,\n 'forty-three': 43,\n 'forty-four': 44,\n 'forty-five': 45,\n 'forty-six': 46,\n 'forty-seven': 47,\n 'forty-eight': 48,\n 'forty-nine': 49,\n 'fifty': 50,\n 'fifty-one': 51,\n 'fifty-two': 52,\n 'fifty-three': 53,\n 'fifty-four': 54,\n 'fifty-five': 55,\n 'fifty-six': 56,\n 'fifty-seven': 57,\n 'fifty-eight': 58,\n 'fifty-nine': 59,\n 'sixty': 60,\n 'sixty-one': 61,\n 'sixty-two': 62,\n 'sixty-three': 63,\n 'sixty-four': 64,\n 'sixty-five': 65,\n 'sixty-six': 66,\n 'sixty-seven': 67,\n 'sixty-eight': 68,\n 'sixty-nine': 69,\n 'seventy': 70,\n 'seventy-one': 71,\n 'seventy-two': 72,\n 'seventy-three': 73,\n 'seventy-four': 74,\n 'seventy-five': 75,\n 'seventy-six': 76,\n 'seventy-seven': 77,\n 'seventy-eight': 78,\n 'seventy-nine': 79,\n 'eighty': 80,\n 'eighty-one': 81,\n 'eighty-two': 82,\n 'eighty-three': 83,\n 'eighty-four': 84,\n 'eighty-five': 85,\n 'eighty-six': 86,\n 'eighty-seven': 87,\n 'eighty-eight': 88,\n 'eighty-nine': 89,\n 'ninety': 90,\n 'ninety-one': 91,\n 'ninety-two': 92,\n 'ninety-three': 93,\n 'ninety-four': 94,\n 'ninety-five': 95,\n 'ninety-six': 96,\n 'ninety-seven': 97,\n 'ninety-eight': 98,\n 'ninety-nine': 99}\n powers = {'hundred': 10 ** 2,\n 'thousand': 10 ** 3,\n 'million': 10 ** 6,\n 'billion': 10 ** 9,\n 'quadrillion': 10 ** 15,\n 'quintillion': 10 ** 18,\n 'sextillion': 10 ** 21,\n 'septillion': 10 ** 24,\n 'octillion': 10 ** 27,\n 'nonillion': 10 ** 30,\n 'decillion': 10 ** 33,\n 'undecillion': 10 ** 36,\n 'duodecillion': 10 ** 39,\n 'tredecillion': 10 ** 42,\n 'quattuordecillion': 10 ** 45,\n 'quindecillion': 10 ** 48,\n 'sexdecillion': 10 ** 51,\n 'septemdecillion': 10 ** 54,\n 'octodecillion': 10 ** 57,\n 'novemdecillion': 10 ** 60,\n 'vigintillion': 10 ** 63,\n 'vigintunillion': 10 ** 66,\n 'unvigintillion': 10 ** 66,\n 'duovigintillion': 10 ** 69,\n 'vigintiduoillion': 10 ** 69,\n 'vigintitrillion': 10 ** 72,\n 'trevigintillion': 10 ** 72,\n 'vigintiquadrillion': 10 ** 75,\n 'quattuorvigintillion': 10 ** 75,\n 'quinvigintillion': 10 ** 78,\n 'vigintiquintrillion': 10 ** 78,\n 'vigintisextillion': 10 ** 81,\n 'sexvigintillion': 10 ** 81,\n 'vigintiseptillion': 10 ** 84,\n 'septvigintillion': 10 ** 84,\n 'octovigintillion': 10 ** 87,\n 'vigintoctillion': 10 ** 87,\n 'vigintinonillion': 10 ** 90,\n 'nonvigintillion': 10 ** 90,\n 'trigintillion': 10 ** 93,\n 'untrigintillion': 10 ** 96,\n 'duotrigintillion': 10 ** 99,\n 'googol': 10 ** 100,\n 'centillion': 10 ** 303}\n \n result = 0\n a = string.split(&quot; &quot;)\n b = []\n \n for c in a:\n if c in numbers:\n b.append(c)\n elif c in powers:\n b[-1] += &quot; &quot; + c\n elif c == &quot;and&quot;:\n continue\n else:\n print(&quot;INVALID WORD:&quot;,c)\n return\n\n for d, e in enumerate(b):\n if len(e.split(&quot; &quot;)) == 1:\n b[d] = numbers[e]\n else:\n b[d] = e.split(&quot; &quot;)\n b[d][0] = numbers[b[d][0]]\n f = 1\n while f &lt; len(b[d]):\n b[d][f] = powers[b[d][f]]\n f += 1\n \n if not(isinstance(b[0], int)):\n while len(b[0]) &gt; 2:\n b[0][1] *= b[0][2]\n b[0].pop(2)\n \n while len(b):\n if len(b) == 1:\n if isinstance(b[0], int):\n result += b[0]\n b.pop(0)\n else:\n while len(b[0]) &gt; 1:\n b[0][0] *= b[0][1]\n b[0].pop(1)\n result += b[0][0]\n b.pop(0)\n else:\n if isinstance(b[1], int):\n b[1] += b[0][0] * b[0][1]\n b.pop(0)\n else:\n while len(b[1]) &gt; 2:\n b[1][1] *= b[1][2]\n b[1].pop(2)\n \n if b[0][1] &lt; b[1][1]:\n b[1][0] += b[0][0] * b[0][1]\n b.pop(0)\n else:\n result += b[0][0] * b[0][1]\n b.pop(0)\n \n return result\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T06:03:09.027", "Id": "498773", "Score": "0", "body": "Instead of writing `10 ** 15` use `1e15`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:15:02.560", "Id": "498835", "Score": "0", "body": "Thanks a lot for the neat formatting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:32:22.693", "Id": "498840", "Score": "0", "body": "@Chocolate How did measure the efficiency? I `timeit`'ed both give exact same results. Can you share how you benchmarked?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:16:53.097", "Id": "498850", "Score": "0", "body": "@Chocolate Ran same code but couldn't reproduce same results(twice as fast). `10**15` is a tad faster than `1e15`. But that difference doesn't even matter IMO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:44:54.617", "Id": "498860", "Score": "0", "body": "@Ch3steR Oh, in the world of programming, every micro second counts!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:54:00.870", "Id": "498863", "Score": "0", "body": "@Chocolate You can re-run your code twice or thrice and you would find a difference of some nano-seconds in each run. The difference is so insignificant. Just like the difference here -- `10**15` -> `0.028200558001117315`, `10e15` -> `0.028008842004055623`. If those nanoseconds matter then choose some other languages like `C`, `C++` maybe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:01:00.183", "Id": "498865", "Score": "0", "body": "You can reproduce above results here [`repl.it` link](https://repl.it/@gurukiran07/ExpertReliableBooleanvalue). Using `timeit` sometimes `10**15` is faster sometimes `1e15` is faster sometimes. In Cpython3.8.5 `1e15` is faster(in most of the runs) tho." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T14:49:44.467", "Id": "499299", "Score": "0", "body": "@Ch3steR: It is not about efficiency, it is about correct and wrong. `1e15` is a float and it is wrong. `10**15` is an int of unlimited precision. `1e30 == 10**30` gives `False`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T15:29:58.873", "Id": "499303", "Score": "0", "body": "@stefan Agreed. With `1e30` python might be hitting floating point precision limits. `10**x` is better I reckon or use `decimal.Decimal` or `fraction.Fraction`." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:21:24.203", "Id": "253014", "ParentId": "253006", "Score": "1" } } ]
{ "AcceptedAnswerId": "253014", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T00:08:30.287", "Id": "253006", "Score": "2", "Tags": [ "python", "programming-challenge", "parsing", "functional-programming", "iteration" ], "Title": "Extract values from English numerals, e.g. \"nine million and one\"" }
253006
<p>A component displays a list of values and I'm trying to hide everything about how those values are gotten, essentially divorcing concerns about state away from the component itself so that in the future any changes to which API data is fetched from, what store is used, etc won't effect the component.</p> <p>First, is this a good idea at all or should mount/unmount actions be handled directly in the component?</p> <p>Second, if it is a good approach, how is my implementation? I'm feeling comfortable in JS but am not an expert</p> <p>ContentList.js:</p> <pre><code>import React from 'react' import './ContentList.css' import { ContentCardContainer } from '../ContentCard/ContentCard' import { getPostSummaries } from '../../Utils/ContentAPI' import { Grid } from '@material-ui/core' export function ContentListContainer(props) { const posts = getPostSummaries() return &lt;ContentList posts={posts} /&gt; } function ContentList(props) { return ( &lt;div className='content-list'&gt; &lt;Grid container &gt; {props.posts.map((post, id) =&gt; &lt;Grid item xs={12} sm={12} lg={6}&gt; &lt;ContentCardContainer key={id} id={id} title={post.title} summary={post.summary} link={'post/' + post.title} /&gt; &lt;/Grid&gt; )} &lt;/Grid&gt; &lt;/div&gt; ) } </code></pre> <p>ContentApi.js:</p> <pre><code>import { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { setContent, setSummaries } from '../Store/Actions' import axios from 'axios' const apiRoot = '/api' export const getPostByID = (id) =&gt; { const dispatch = useDispatch() useEffect(() =&gt; { axios.get(apiRoot+'/post', {params: {id}}) .then(resp =&gt; dispatch(setContent(resp.data.content))) .catch(() =&gt; dispatch(setContent(''))) return () =&gt; dispatch(setContent('')) }, []) return useSelector(state =&gt; state.content) } export const getPostSummaries = () =&gt; { const dispatch = useDispatch() useEffect(() =&gt; { axios.get(apiRoot+'/post-summaries') .then(resp =&gt; dispatch(setSummaries(resp.data.posts))) .catch(() =&gt; dispatch(setSummaries([])) ) }, []) return useSelector(state =&gt; state.summaries) } </code></pre>
[]
[ { "body": "<p>The general approach looks just fine. The logic behind data retrieval isn't entirely related to the rendering of components, so putting it into a custom hook instead makes good sense, especially if other components might need the data as well.</p>\n<p>A few suggestions:</p>\n<ul>\n<li>React recommends that the function names of custom hooks <a href=\"https://reactjs.org/docs/hooks-custom.html#extracting-a-custom-hook\" rel=\"nofollow noreferrer\">start with <code>use</code></a>, to clearly indicate that it's a hook and that other hooks (like <code>useEffect</code>) can be used inside it.</li>\n<li>If other components might need to use the summaries as well, or if this component may get completely unmounted and then re-mounted again, consider whether you can use the summaries that were retrieved previously instead of fetching them again. (Or maybe you <em>do</em> want to fetch them again regardless - think about what you want.)</li>\n<li>There doesn't really appear to be error handling, other than <code>setSummaries([])</code>. It would be more user friendly to indicate to the user if there's an error (and, at least in the development environment, to log the error).</li>\n<li>Having both a <code>ContentListContainer</code> and a <code>ContentList</code> seems odd, since <code>ContentListContainer</code> is empty except for the custom hook call. If you aren't planning to add more stuff to the container, consider removing <code>ContentListContainer</code> entirely and putting the hook call into <code>ContentList</code> instead.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T01:23:20.320", "Id": "498766", "Score": "0", "body": "`ContainerList` is a holdover from when all the processing happened in the component and I wanted to split display logic from program logic. Definitely would make sense to merge them back together if there's no additional logic" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T01:17:09.700", "Id": "253010", "ParentId": "253008", "Score": "1" } } ]
{ "AcceptedAnswerId": "253010", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T00:30:22.450", "Id": "253008", "Score": "1", "Tags": [ "javascript", "react.js", "redux" ], "Title": "Abstracting async hooks out from components" }
253008
<p>I would ideally like to add event listeners to a single group of elements, <code>topLevelDesktopNavDropdownItems</code> , in some kind of object syntax like {event: function, event: function}. Or is there another way to do this? Here is my current code:</p> <pre><code>topLevelDesktopNavDropdownItems.forEach( element =&gt; element.addEventListener('mouseenter', topLevelNavItemMouseOver) ); topLevelDesktopNavDropdownItems.forEach( element =&gt; element.addEventListener('mouseleave', topLevelNavItemMouseOut) ); topLevelDesktopNavDropdownItems.forEach( element =&gt; element.addEventListener('keydown', topLevelNavItemLinkKeyDown) ); </code></pre>
[]
[ { "body": "<p>Instead of iterating over the same array 3 times, iterate over it once:</p>\n<pre><code>topLevelDesktopNavDropdownItems.forEach((element) =&gt; {\n element.addEventListener('mouseenter', topLevelNavItemMouseOver);\n element.addEventListener('mouseleave', topLevelNavItemMouseOut);\n element.addEventListener('keydown', topLevelNavItemLinkKeyDown);\n});\n</code></pre>\n<p>If you think that's too repetitive, you can put the listeners into an object and iterate over the object:</p>\n<pre><code>const handlers = {\n mouseenter: topLevelNavItemMouseOver,\n mouseleave: topLevelNavItemMouseOut,\n keydown: topLevelNavItemLinkKeyDown,\n};\nfor (const element of topLevelDesktopNavDropdownItems) {\n for (const [event, handler] of Object.entries(handlers)) {\n element.addEventListener(event, handler);\n }\n}\n</code></pre>\n<p>A couple suggestions regarding naming:</p>\n<ul>\n<li><p>The <code>mouseover</code> event is not the same thing as the <code>mouseenter</code> event, Similarly, <code>mouseleave</code> is not exactly the same as <code>mouseout</code>. (One version propagates via bubbling/capturing, the other doesn't. If the elements have children, this makes a big difference.) For precision, consider naming the handlers exactly the same as the event they're listening for.</p>\n</li>\n<li><p>If you have lots of handlers like this, prefixing them all with <code>topLevelNavItem</code> may get undesirably verbose. To isolate their scope to hopefully make the prefixes less necessary, consider defining them inside a function:</p>\n</li>\n</ul>\n<pre><code>const addDropdownListeners = () =&gt; {\n const mouseOverHandler = (event) =&gt; {\n // ...\n };\n // ...\n</code></pre>\n<p>Or define them inline with the object:</p>\n<pre><code>const dropdownHandlers = {\n mouseenter: (event) =&gt; {\n // ...\n }\n // ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:11:25.130", "Id": "498767", "Score": "0", "body": "Thank you very much. This was all great stuff. I went with your first suggestion of only iterating over the array once, fixed my function names to use mouseenter/leave to reflect their true purpose, and tightened up my naming conventions a bit. Thank you again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:01:26.257", "Id": "253013", "ParentId": "253011", "Score": "2" } } ]
{ "AcceptedAnswerId": "253013", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T01:48:32.453", "Id": "253011", "Score": "0", "Tags": [ "javascript" ], "Title": "Is there a condensed way of adding multiple event listeners each with different functions to the same group of elements?" }
253011
<p>Below code is for Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number my task to reach the lowest time complexity I tried it differently, but I cannot reach the lowest time complexity - please help, and I am running it on an online compiler.</p> <pre><code>class Solution: def primesum(self, A): # write your method here n = A return self.findPrimePair(A) def findPrimePair(self,n): isPrime = [0] * (n+1) isPrime = [True for i in range(n + 1)] self.SieveOfEratosthenes(n, isPrime) for i in range(0,n): if (isPrime[i] and isPrime[n - i]): return i,n-i return 0,0 def SieveOfEratosthenes(self,n, isPrime): isPrime[0] = isPrime[1] = False p=2 while(p*p &lt;= n): if (isPrime[p] == True): i = p*p while(i &lt;= n): isPrime[i] = False i += p p += 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:14:02.283", "Id": "498768", "Score": "1", "body": "You have no detail at all. We have no idea what your code is supposed to do, no idea what the time constraints are, or what your project is. I will be forced to give a -1 (unless you edit it, that is)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:53:14.197", "Id": "498769", "Score": "0", "body": "Sorry, I am a beginner; I am learning now. I tried my best to give the details(i edited the code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-09T13:24:33.963", "Id": "499423", "Score": "0", "body": "Welcome to Code Review! The original title, which stated your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. I've edited it to help you; please check that I haven't misrepresented your code!" } ]
[ { "body": "<blockquote>\n<pre><code>def primesum(self, A):\n # write your method here\n n = A \n return self.findPrimePair(A)\n</code></pre>\n</blockquote>\n<p>The variable <code>n</code> is never used, so delete that line. And the comment is obsolete.</p>\n<hr />\n<blockquote>\n<pre><code> isPrime = [0] * (n+1) \n isPrime = [True for i in range(n + 1)]\n</code></pre>\n</blockquote>\n<p>Why not simply initialise to all true? I.e.</p>\n<pre><code> isPrime = [True] * (n+1) \n</code></pre>\n<hr />\n<blockquote>\n<pre><code> self.SieveOfEratosthenes(n, isPrime)\n for i in range(0,n): \n if (isPrime[i] and isPrime[n - i]): \n return i,n-i\n</code></pre>\n</blockquote>\n<p>If we arrange for <code>SieveOfEratosthenes()</code> to return a <code>set</code>, then we don't need to test every single number:</p>\n<pre><code>primes = generate_primes(n)\nfor i in primes:\n if n-i in primes: return i, n-i\n</code></pre>\n<hr />\n<p>The sieve itself is doing more work than it needs to. For example, after removing all the even numbers, we can advance by 2*p each iteration, since every other value would be even.</p>\n<hr />\n<p>Style-wise, I see a lot of unnecessary parentheses and some redundant comparisons. For example, this line has both:</p>\n<blockquote>\n<pre><code> if (isPrime[p] == True): \n</code></pre>\n</blockquote>\n<p>We would normally write that simply as</p>\n<pre><code> if isPrime[p]:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T12:11:01.357", "Id": "253033", "ParentId": "253012", "Score": "1" } } ]
{ "AcceptedAnswerId": "253033", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:00:18.370", "Id": "253012", "Score": "-1", "Tags": [ "python", "time-limit-exceeded" ], "Title": "Find pairs of primes that sum to specified even number" }
253012
<p>I saw another user post their implementation of C++ TicTacToe game and thought what a coincidence! I was just in the process of making one myself after picking up <em>Programming Principles and Practice Using C++, Second Edition</em> by Bjarne.</p> <p>Would be very grateful if someone could give my code a fresh pair of eyes! Thank you!</p> <pre><code>#include &quot;iostream&quot; #include&lt;string&gt; #include&lt;algorithm&gt; #include &lt;cmath&gt; using namespace std; // Note: This version uses bit manipulation. // Think of the board as a 18-bit integer where ever 2 bits is a cell of the board // // Example: // 00 00 00 00 00 00 00 00 00 // top-left top-middle top-right ... bottom-left bottom-middle bottom-right // Key: // 00 = empty 10 = X 01 = O class TicTacToe { int board = 0; int turn_count = 0; public: bool is_over = false; char turn = 'X'; void prompt_move() { cout &lt;&lt; &quot;It's your turn, &quot; &lt;&lt; turn &lt;&lt; &quot;. Enter a number 0-9 to move.\n&quot;; }; bool player_move(int selected_move) { if(!cell_contains(selected_move) &amp;&amp; !is_over) { board += (turn=='X') ? (1 &lt;&lt; (selected_move)*2) : (2 &lt;&lt; (selected_move)*2); turn_count++; is_over = has_winner(); return true; } else { cout &lt;&lt; &quot;Oops! You can't move there.&quot; &lt;&lt; &quot;\n&quot;; return false; } }; void switch_turn() { turn = turn=='X' ? 'O' : 'X'; }; void set_turn(char player) { turn = player; }; void announce_move(int selected_move) { cout &lt;&lt; turn &lt;&lt; &quot; moved to position &quot; &lt;&lt; selected_move &lt;&lt; &quot;\n\n&quot;; }; void congratulate_winner() { cout &lt;&lt; &quot;Congratulations, &quot; &lt;&lt; turn &lt;&lt; &quot;! You won! Play again? (1-Yes / 0-No) \n&quot;; }; void print_board() { string output; bool bit_manip; for(int i=0; i&lt;3;++i) { for(int j=0;j&lt;3;j++) { // Left side styling if(j%3==2) cout &lt;&lt; &quot;| &quot;; if(j%3==1) cout &lt;&lt; &quot; &quot;; // Fill with value (if applicable) if(cell_contains(i*3+j,'X')) { cout &lt;&lt; 'X'; } else if(cell_contains(i*3+j,'O')) { cout &lt;&lt; 'O'; } else { cout &lt;&lt; ' '; } // Right side styling if(j%3==0) cout &lt;&lt; &quot; |&quot;; if(j%3==1) cout &lt;&lt; &quot; &quot;; } cout &lt;&lt; &quot;\n&quot;; if(i&lt;2) cout &lt;&lt; &quot;-------------&quot; &lt;&lt; &quot;\n&quot;; } }; bool cell_contains(int i, char val = ' ') { if(val=='X') { return ((board &amp; (1 &lt;&lt; i*2))!=0); } else if(val=='O') { return ((board &amp; (2 &lt;&lt; i*2))!=0); } else { return ((board &amp; (3 &lt;&lt; i*2))!=0); } return false; } // This win-checker functions by looping through the rows, columns, and diagonals bool has_winner() { if(turn_count&lt;5) return false; int row; int column; int diagonalL = 0; int diagonalR = 0; for(int i=0; i&lt;3; i++) { row = 0; column = 0; for(int j=0;j&lt;3;j++) { row += cell_contains(i*3+j,'X') ? 1 : cell_contains(i*3+j,'O') ? -1 : 0; column += cell_contains(i+j*3,'X') ? 1 : cell_contains(i+j*3,'O') ? -1 : 0; } diagonalL += cell_contains(i*4,'X') ? 1 : cell_contains(i*4,'O') ? -1 : 0; diagonalR += cell_contains(2+2*i,'X') ? 1 : cell_contains(2+2*i,'O') ? -1 : 0; if(abs(row)==3) return true; if(abs(column)==3) return true; } if(abs(diagonalL)==3) return true; if(abs(diagonalR)==3) return true; return false; }; // Gets player input. Could be improved with more error-checking. int get_input() { int inp; cin &gt;&gt; inp; return inp; }; }; int main() { TicTacToe game; int selected_move; bool was_valid; char previous_winner; while(!game.is_over) { game.print_board(); game.prompt_move(); selected_move = game.get_input(); game.announce_move(selected_move); was_valid = game.player_move(selected_move); if(game.is_over) { previous_winner = game.turn; game.print_board(); game.congratulate_winner(); selected_move = game.get_input(); game = TicTacToe(); game.set_turn(previous_winner=='X' ? 'O' : 'X'); } else if(was_valid) game.switch_turn(); } cout &lt;&lt; &quot;GG!&quot;; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:39:39.273", "Id": "498785", "Score": "0", "body": "Your code has a bug, it displays the board infinitely on taking user input, you might want to fix that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T04:53:23.350", "Id": "499114", "Score": "0", "body": "Your program doesn't work. The second I saw `int board = 0` I knew. This is because `int` doesn't have a fixed width. Your program would work on a 32-bit platform but horribly fail on a 64-bit one because the width of `int` changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T05:17:46.970", "Id": "499116", "Score": "0", "body": "@theProgrammer Try changing the platform to 32/86" } ]
[ { "body": "<p>In terms of game play there are few things to fix:</p>\n<ul>\n<li>If the number entered is not in [0-8] (and not [0,9]!) an exception should be thrown</li>\n<li>If one does not want to play an other game, the program should stop.</li>\n</ul>\n<p>In terms of design your code is very clear, congrats! Two things worth precising though:</p>\n<ul>\n<li><p>You could make more use of the <code>const</code> specifier for functions that don't change the state of the game (like anouncers).</p>\n</li>\n<li><p>you should stay away from <code>using namespace std</code>, as it is considered as a bad practice that is prone to more errors than benefits.</p>\n</li>\n</ul>\n<p>Here is a functional code that integrates some of these changes:</p>\n<pre><code>#include &quot;iostream&quot;\n#include&lt;string&gt;\n#include&lt;algorithm&gt;\n#include &lt;cmath&gt;\nusing namespace std;\n\n// Note: This version uses bit manipulation.\n// Think of the board as a 18-bit integer where ever 2 bits is a cell of the board\n//\n// Example:\n// 00 00 00 00 00 00 00 00 00\n// top-left top-middle top-right ... bottom-left bottom-middle bottom-right\n// Key:\n// 00 = empty 10 = X 01 = O\nclass TicTacToe\n{\n unsigned int board = 0;\n unsigned int turn_count = 0;\npublic:\n bool is_over = false;\n char turn = 'X';\n\n void prompt_move()\n {\n cout &lt;&lt; &quot;It's your turn, &quot; &lt;&lt; turn &lt;&lt; &quot;. Enter a number 0-8 to move.\\n&quot;;\n }\n\n bool player_move(unsigned int selected_move)\n {\n if(!cell_contains(selected_move) &amp;&amp; !is_over)\n {\n board += (turn=='X') ? (1 &lt;&lt; (selected_move)*2) : (2 &lt;&lt; (selected_move)*2);\n turn_count++;\n is_over = has_winner();\n return true;\n }\n else {\n cout &lt;&lt; &quot;Oops! You can't move there.&quot; &lt;&lt; &quot;\\n&quot;;\n return false;\n }\n }\n\n void switch_turn()\n {\n turn = turn=='X' ? 'O' : 'X';\n }\n\n void set_turn(char player){\n turn = player;\n }\n\n void announce_move(int selected_move)\n {\n cout &lt;&lt; turn &lt;&lt; &quot; moved to position &quot; &lt;&lt; selected_move &lt;&lt; &quot;\\n\\n&quot;;\n }\n\n void congratulate_winner()\n {\n cout &lt;&lt; &quot;Congratulations, &quot; &lt;&lt; turn &lt;&lt; &quot;! You won!\\n&quot;;\n }\n\n void ask_if_play_again()\n {\n cout &lt;&lt; &quot;Play again? (1-Yes / 0-No)&quot; &lt;&lt; std::endl;\n unsigned int inp;\n cin &gt;&gt; inp;\n if(inp == 1) this-&gt;is_over = false;\n else if(inp == 0) this-&gt;is_over = true;\n else throw std::runtime_error(&quot;Number should be 0 or 1&quot;);\n }\n\n void print_board() {\n string output;\n bool bit_manip;\n for(int i=0; i&lt;3;++i) {\n for(int j=0;j&lt;3;j++) {\n // Left side styling\n if(j%3==2) cout &lt;&lt; &quot;| &quot;;\n if(j%3==1) cout &lt;&lt; &quot; &quot;;\n // Fill with value (if applicable)\n if(cell_contains(i*3+j,'X')) {\n cout &lt;&lt; 'X';\n } else if(cell_contains(i*3+j,'O')) {\n cout &lt;&lt; 'O';\n } else {\n cout &lt;&lt; ' ';\n }\n // Right side styling\n if(j%3==0) cout &lt;&lt; &quot; |&quot;;\n if(j%3==1) cout &lt;&lt; &quot; &quot;;\n }\n cout &lt;&lt; &quot;\\n&quot;;\n if(i&lt;2) cout &lt;&lt; &quot;-------------&quot; &lt;&lt; &quot;\\n&quot;;\n }\n };\n bool cell_contains(int i, char val = ' ') {\n if(val=='X') {\n return ((board &amp; (1 &lt;&lt; i*2))!=0);\n } else if(val=='O') {\n return ((board &amp; (2 &lt;&lt; i*2))!=0);\n } else {\n return ((board &amp; (3 &lt;&lt; i*2))!=0);\n }\n return false;\n }\n // This win-checker functions by looping through the rows, columns, and diagonals\n bool has_winner() {\n if(turn_count&lt;5) return false;\n int row;\n int column;\n int diagonalL = 0;\n int diagonalR = 0;\n for(int i=0; i&lt;3; i++) {\n row = 0;\n column = 0;\n for(int j=0;j&lt;3;j++) {\n row += cell_contains(i*3+j,'X') ? 1 : cell_contains(i*3+j,'O') ? -1 : 0;\n column += cell_contains(i+j*3,'X') ? 1 : cell_contains(i+j*3,'O') ? -1 : 0;\n }\n diagonalL += cell_contains(i*4,'X') ? 1 : cell_contains(i*4,'O') ? -1 : 0;\n diagonalR += cell_contains(2+2*i,'X') ? 1 : cell_contains(2+2*i,'O') ? -1 : 0;\n if(abs(row)==3) return true;\n if(abs(column)==3) return true;\n }\n if(abs(diagonalL)==3) return true;\n if(abs(diagonalR)==3) return true;\n return false;\n }\n // Gets player input. Could be improved with more error-checking.\n unsigned int get_input() {\n int inp;\n cin &gt;&gt; inp;\n if(inp &gt; 8) throw std::runtime_error(&quot;Number should be in [0;9]&quot;);\n return inp;\n }\n};\n\nint main() {\n TicTacToe game;\n int selected_move;\n bool was_valid;\n char previous_winner;\n while(!game.is_over)\n {\n game.print_board();\n game.prompt_move();\n selected_move = game.get_input();\n game.announce_move(selected_move);\n was_valid = game.player_move(selected_move);\n if(game.is_over)\n {\n previous_winner = game.turn;\n game.print_board();\n game.congratulate_winner();\n game.ask_if_play_again();\n } else if(was_valid) game.switch_turn();\n }\n cout &lt;&lt; &quot;GG!&quot;;\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T23:15:44.063", "Id": "253151", "ParentId": "253015", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T02:27:16.127", "Id": "253015", "Score": "2", "Tags": [ "c++" ], "Title": "My TicTacToe attempt in C++ Console [Intermediate]" }
253015
<p>I'd like to have a generic way for validating user provided email with a bias toward ease of use. Does the following do so in a clear way for implementations that have the <code>URL</code> interface available? The sample input below is only intended to exercise the range of expected input and demonstrate it works. The UI is not in scope and varies separately--the solution is only intended to provide input validation with usable feedback for implementations.</p> <p>Any feedback welcome on the style, approach, etc.</p> <pre><code>function validEmail(input=''){ const emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i; let email, url, valid = false, error, same = false; try{ email = input.trim(); // handles punycode, etc using browser's own maintained implementation url = new URL('http://'+email); let urlderived = `${url.username}@${url.hostname}`; same = urlderived === email; valid = emailPatternInput.test( email ); if(!valid) throw new Error('invalid email pattern on input:' + email); valid = emailPatternUrl.test( urlderived ); if(!valid) throw new Error('invalid email pattern on url:' + urlderived); }catch(err){ error = err; }; return {email, url, same, valid, error}; } [ 'user+this@はじめよう.みんな' , 'stuff@things.eu' , 'stuff@things' , 'user+that@host.com' , 'Jean+François@anydomain.museum','هيا@יאללה' , '试@例子.测试.مثال.آزمایشی' , 'not@@really' , 'no' ].forEach(email=&gt;console.log(validEmail(email), email)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-07T14:39:38.230", "Id": "499168", "Score": "0", "body": "Unless you are writing a library yourself, you should use a library for this, there are so many rules and gotchas in email validation. And if you are writing a library yourself, then you should check out your competition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T03:32:50.020", "Id": "499259", "Score": "0", "body": "Given the lack of competency and the failure of existing solutions in place across the internet I made this solution. It is the only one of its type and works reliably as demonstrated by the exercising of code as shown in the samples. Relegating responsibility to solutions provided by others is a logical fallacy and reflects poor exercise of due diligence with respect to the work. I disagree and it is for these reasons. Thanks for the comment nonetheless. It affords us and opportunity to challenge this common assertion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T14:24:12.550", "Id": "499297", "Score": "1", "body": "A competent implementation should follow the email address RFC; https://stackoverflow.com/a/1373724/7602" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T09:04:34.173", "Id": "501671", "Score": "0", "body": "[\"If you really need to be sure an email address is valid, you’ll need to send an email to it that contains a code or link for the recipient to perform a second authentication step. And if you’re doing that, then there is little point in using a regex that may reject valid email addresses.\"](http://www.regular-expressions.info/email.html)" } ]
[ { "body": "<p>I would avoid the habit of declaring multiple variables in the same line. In most cases, they're hard to read especially when they get long. The only one exception I'd do this would be if everything is short enough to read, like your <code>let</code> line. But that one has other issues as well: why the two <code>false</code>s? and why initialize with <code>false</code> when they end up as other types (string for <code>email</code> and <code>url</code>, and an <code>Error</code> instance for <code>error</code>)?</p>\n<p>A general rule for <code>try-catch</code> is to only use it for <em>unexpected errors</em>, like for calls to other functions. Never use it as a control structure. In your case, you're using thrown errors to bail out of the block. Throwing an error inside your own <code>try-catch</code> is an anti-pattern. It's better to use a conditional instead.</p>\n<p>Then theres the inconsistent use of syntax, like the use of template literals here but not there, or the one-time assignments to a <code>let</code> which can just be a <code>const</code>, etc.</p>\n<p>Now, doing away with the <code>try-catch</code>, the only thing that's complex is the relationship between <code>error</code> and <code>valid</code>. Everything else is just a value resulting from an expression, which in the following example... is just a series of <code>const</code>.</p>\n<p>In your code, you compute validity twice and determine which error to use based on which check failed. This probably led to the strange complexity in your version of the code, you had to bail out with your error before it did the next check. But you can flip it around. You can use the check to determine the error. Then define <code>valid</code> based on the presence or absence of that error.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validEmail(input = '') {\n const inputPattern = /^[^@]{1,64}@[^@]{4,253}$/\n const emailPattern = /^[^@]{1,64}@[a-z][a-z0-9\\.-]{3,252}$/i\n const email = input.trim()\n \n // handles punycode, etc using browser's own maintained implementation\n const url = new URL(`http://${email}`)\n const urlDerived = `${url.username}@${url.hostname}`\n\n // Same-ness is the same regardless of errors. Bumping up.\n const same = urlDerived === email;\n \n // Test for incorrectness, null if ok.\n const error = !inputPattern.test(email) ? new Error(`invalid email pattern on input: ${email}`)\n : !emailPattern.test(urlDerived) ? new Error(`invalid email pattern on url: ${urlDerived}`)\n : null\n \n // The presence/absence of the error determines validity.\n const valid = !Boolean(error)\n \n return { email, url, same, valid, error }\n}\n\n[\n 'user+this@はじめよう.みんな',\n 'stuff@things.eu',\n 'stuff@things',\n 'user+that@host.com',\n 'Jean+François@anydomain.museum',\n 'هيا@יאללה',\n '试@例子.测试.مثال.آزمایشی',\n 'not@@really',\n 'no'\n].forEach(email =&gt; console.log(validEmail(email), email));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T08:12:43.773", "Id": "498778", "Score": "1", "body": "Perhaps it would help your argument to share that [using `const` over `let` can help avoid bugs with accidental reassignment](https://softwareengineering.stackexchange.com/a/278653/244085)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:11:47.570", "Id": "498779", "Score": "0", "body": "Thanks Joseph, this is useful feedback. The try-catch is initially used to trap unexpected _user_ input errors. I can short-circuit by throwing errors where their input doesn't match the url and the URL interface will throw errors as well depending on input and sequence, using the same general type for all errors in a UI. Valid and same are different comparisons to expose for implementations for use in messaging to the user UI--that separates the concern while removing the need to do the same operation (message the UI and discard the result is the expected use)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T07:20:12.600", "Id": "253023", "ParentId": "253020", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T05:21:52.467", "Id": "253020", "Score": "2", "Tags": [ "javascript", "validation", "email" ], "Title": "user-facing email validation" }
253020
<p>The title says it all, I have written two scripts to calculate dates to test my abilities in programming, one from scratch, without [DateTime], New-TimeSpan and even [math]::Ceiling, and it's really long and complex, and there is a max error of one inherited from algorithm, the other uses builtin and it's significantly shorter than the former, I use PowerShell 7.1 x64 on Windows 10, confirmed they are both working, though I haven't tested them on lower versions of PowerShell.</p> <p>The purpose of the question is to shorten their code, make them more efficient without changing their logic and method, feel free to contribute if you think you can improve them, now I will post them below:</p> <p>Without Built-in:</p> <pre><code> $Culture=@( [PSCustomObject]@{Format='yyyy-MM-dd';Regex='\d{4}\-0?([2-9]|1[0-2]?)\-(0?(3[01]|[12][0-9]|[1-9]))'} [PSCustomObject]@{Format='yyyy/MM/dd';Regex='\d{4}\/0?([2-9]|1[0-2]?)\/(0?(3[01]|[12][0-9]|[1-9]))'} [PSCustomObject]@{Format='MM/dd/yyyy';Regex='0?([2-9]|1[0-2]?)\/(0?(3[01]|[12][0-9]|[1-9]))\/\d{4}'} [PSCustomObject]@{Format='MMM dd, yyyy';Regex='[A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9])), \d{4}'} [PSCustomObject]@{Format='dd MMM, yyyy';Regex='(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3}, \d{4}'} [PSCustomObject]@{Format='MMMM dd, yyyy';Regex='[A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9])), \d{4}'} [PSCustomObject]@{Format='dd MMMM, yyyy';Regex='(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3,9}, \d{4}'} [PSCustomObject]@{Format='yyyy, MMM dd';Regex='\d{4}, [A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9]))'} [PSCustomObject]@{Format='yyyy, MMMM dd';Regex='\d{4}, [A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9]))'} ) $months=@( [PSCustomObject]@{Month='January';Days=31;Number=1} [PSCustomObject]@{Month='February';Days=28;Number=2} [PSCustomObject]@{Month='March';Days=31;Number=3} [PSCustomObject]@{Month='April';Days=30;Number=4} [PSCustomObject]@{Month='May';Days=31;Number=5} [PSCustomObject]@{Month='June';Days=30;Number=6} [PSCustomObject]@{Month='July';Days=31;Number=7} [PSCustomObject]@{Month='August';Days=31;Number=8} [PSCustomObject]@{Month='September';Days=30;Number=9} [PSCustomObject]@{Month='October';Days=31;Number=10} [PSCustomObject]@{Month='November';Days=30;Number=11} [PSCustomObject]@{Month='December';Days=31;Number=12} ) function Identify { PARAM ( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] [System.String] $string, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] [System.String] $regex ) $string -eq ($string| Select-String -pattern $regex).matches.value } function Leapdays { PARAM ( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $date ) Process { [int]$years=$date.year if ($date.month -le 2) { $years-=1} return $years / 4 - $years / 100 + $years / 400 } } function ParseDate { Param( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $string, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] $format ) if ($format -eq 'yyyy-MM-dd'){ $Year=$string.Split(&quot;-&quot;)[0] -as [int] $Month=$string.Split(&quot;-&quot;)[1] -as [int] $Day=$string.Split(&quot;-&quot;)[2] -as [int] } elseif ($format -eq 'yyyy/MM/dd'){ $Year=$string.Split(&quot;/&quot;)[0] -as [int] $Month=$string.Split(&quot;/&quot;)[1] -as [int] $Day=$string.Split(&quot;/&quot;)[2] -as [int] } elseif ($format -eq 'MM/dd/yyyy'){ $Year=$string.Split(&quot;/&quot;)[2] -as [int] $Month=$string.Split(&quot;/&quot;)[0] -as [int] $Day=$string.Split(&quot;/&quot;)[1] -as [int] } elseif ($format -eq 'MMM dd, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -like $string.split( )[0]+&quot;*&quot;}).number -as [int] $Day=$string.Split( )[1] -as [int] } elseif ($format -eq 'dd MMM, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -like $string.split( )[1]+&quot;*&quot;}).number -as [int] $Day=$string.Split( )[0] -as [int] } elseif ($format -eq 'MMMM dd, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -eq $string.split( )[0]}).number -as [int] $Day=$string.Split( )[1] -as [int] } elseif ($format -eq 'dd MMMM, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -eq $string.split( )[1]}).number -as [int] $Day=$string.Split( )[0] -as [int] } elseif ($format -eq 'yyyy, MMM dd'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[0] -as [int] $Month=($months | Where-Object{$_.Month -like $string.split( )[1]+&quot;*&quot;}).number -as[int] $Day=$string.Split( )[2] -as [int] } elseif ($format -eq 'yyyy, MMMM dd'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[0] -as [int] $Month=($months | Where-Object{$_.Month -eq $string.split( )[1]}).number -as [int] $Day=$string.Split( )[2] -as [int] } [PSCustomObject]@{Year=$Year;Month=$Month;Day=$Day} } function Diff-Date { PARAM( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $date1, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] $date2 ) for ($i=0;$i -lt $Culture.count;$i++) { if (Identify $date1 $Culture[$i].Regex) { $date1=ParseDate $date1 $Culture[$i].Format break } } for ($i=0;$i -lt $Culture.count;$i++) { if (Identify $date2 $Culture[$i].Regex) { $date2=ParseDate $date2 $Culture[$i].Format break } } $month1=0 $month2=0 for ($i=0;$i -lt $date1.month-1;$i++) { $month1+=$months[$i].Days } for ($i=0;$i -lt $date2.month-1;$i++) { $month2+=$months[$i].Days } $totaldays1=$date1.year*365+$(Leapdays $date1)+$month1+$date1.day $totaldays2=$date2.year*365+$(Leapdays $date2)+$month2+$date2.day $diffdate = $totaldays2 - $totaldays1 if ($diffdate -lt [int]$diffdate) {$diffdate = [int]$diffdate} elseif ($diffdate -gt [int]$diffdate) {$diffdate = [int]$diffdate+1} return $diffdate } $date1=Read-Host &quot;Input Start Date&quot; if (-not $date1) { $date1=&quot;1999-04-10&quot; } Write-Host $date1 $date2=Read-Host &quot;Input End Date&quot; if (-not $date2) { $date2=(Get-Date -DisplayHint Date -Format &quot;yyyy-MM-dd&quot; | Out-String).TrimEnd() } Write-Host $date2 Diff-Date $date1 $date2 </code></pre> <p>With Builtin</p> <pre><code>function D-Days { PARAM( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $date1, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] $date2 ) $date1=[DateTime]$date1 $date2=[DateTime]$date2 $ddate=New-TimeSpan -Start $date1 -End $date2 $date1=$date1.ToString(&quot;MMMM dd, yyyy&quot;) $date2=$date2.ToString(&quot;MMMM dd, yyyy&quot;) $length=([string]$ddate.days).length $ddate=$ddate.ToString(&quot;d&quot;*$length) Write-Output &quot;Start date is: $date1, End date is: $date2, Date difference is: $ddate days&quot; } $date1=Read-Host &quot;Input Start Date&quot; if (-not $date1) { $date1=&quot;1999-04-10&quot; } Write-Host $date1 $date2=Read-Host &quot;Input End Date&quot; if (-not $date2) { $date2=(Get-Date -DisplayHint Date -Format &quot;yyyy-MM-dd&quot; | Out-String).TrimEnd() } Write-Host $date2 D-Days $date1 $date2 </code></pre> <p>Major Update: I have revised the leapdays function used to count leap days before date, in the script without builtin, it completely eliminated the max error of 1 day, by output an integer leap days to any input, like how leap days work in reality, the idea is very simple, four/4-century/100+cycle/400, where four means nearest multiple of four less than or equal to year, century is century of that year (2000 is the end of 20th century, sorry but the start of 21 century is 2001 and so on...because there is no A.D. 0), and cycle is nearest multiple of 400 less than or equal to year, now I know of [math]::floor to get only quotient, but I decided against using it in the script without built-in, so here is the script:</p> <pre><code> $Culture=@( [PSCustomObject]@{Format='yyyy-MM-dd';Regex='\d{4}\-0?([2-9]|1[0-2]?)\-(0?(3[01]|[12][0-9]|[1-9]))'} [PSCustomObject]@{Format='yyyy/MM/dd';Regex='\d{4}\/0?([2-9]|1[0-2]?)\/(0?(3[01]|[12][0-9]|[1-9]))'} [PSCustomObject]@{Format='MM/dd/yyyy';Regex='0?([2-9]|1[0-2]?)\/(0?(3[01]|[12][0-9]|[1-9]))\/\d{4}'} [PSCustomObject]@{Format='MMM dd, yyyy';Regex='[A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9])), \d{4}'} [PSCustomObject]@{Format='dd MMM, yyyy';Regex='(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3}, \d{4}'} [PSCustomObject]@{Format='MMMM dd, yyyy';Regex='[A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9])), \d{4}'} [PSCustomObject]@{Format='dd MMMM, yyyy';Regex='(0?(3[01]|[12][0-9]|[1-9])) [A-Za-z]{3,9}, \d{4}'} [PSCustomObject]@{Format='yyyy, MMM dd';Regex='\d{4}, [A-Za-z]{3} (0?(3[01]|[12][0-9]|[1-9]))'} [PSCustomObject]@{Format='yyyy, MMMM dd';Regex='\d{4}, [A-Za-z]{3,9} (0?(3[01]|[12][0-9]|[1-9]))'} ) $months=@( [PSCustomObject]@{Month='January';Days=31;Number=1} [PSCustomObject]@{Month='February';Days=28;Number=2} [PSCustomObject]@{Month='March';Days=31;Number=3} [PSCustomObject]@{Month='April';Days=30;Number=4} [PSCustomObject]@{Month='May';Days=31;Number=5} [PSCustomObject]@{Month='June';Days=30;Number=6} [PSCustomObject]@{Month='July';Days=31;Number=7} [PSCustomObject]@{Month='August';Days=31;Number=8} [PSCustomObject]@{Month='September';Days=30;Number=9} [PSCustomObject]@{Month='October';Days=31;Number=10} [PSCustomObject]@{Month='November';Days=30;Number=11} [PSCustomObject]@{Month='December';Days=31;Number=12} ) function Identify { PARAM ( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] [System.String] $string, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] [System.String] $regex ) $string -eq ($string| Select-String -pattern $regex).matches.value } function Leapdays { PARAM ( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $date ) Process { [int]$years=$date.year if ($date.month -le 2) { $years-=1} if ($years % 4 -eq 0) {$leap=$years/4} else {while ($years % 4 -ne 0) {$years-=1} $leap=$years/4} if ($years % 100 -eq 0) {$century=$years/100} else {while ($years % 100 -ne 0) {$years-=4} $century=$years/100} if ($years % 400 -eq 0) {$cycle=$years/400} else {while ($years % 400 -ne 0) {$years-=100} $cycle=$years/400} $leap=$leap-$century+$cycle $leap } } function ParseDate { Param( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $string, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] $format ) if ($format -eq 'yyyy-MM-dd'){ $Year=$string.Split(&quot;-&quot;)[0] -as [int] $Month=$string.Split(&quot;-&quot;)[1] -as [int] $Day=$string.Split(&quot;-&quot;)[2] -as [int] } elseif ($format -eq 'yyyy/MM/dd'){ $Year=$string.Split(&quot;/&quot;)[0] -as [int] $Month=$string.Split(&quot;/&quot;)[1] -as [int] $Day=$string.Split(&quot;/&quot;)[2] -as [int] } elseif ($format -eq 'MM/dd/yyyy'){ $Year=$string.Split(&quot;/&quot;)[2] -as [int] $Month=$string.Split(&quot;/&quot;)[0] -as [int] $Day=$string.Split(&quot;/&quot;)[1] -as [int] } elseif ($format -eq 'MMM dd, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -like $string.split( )[0]+&quot;*&quot;}).number -as [int] $Day=$string.Split( )[1] -as [int] } elseif ($format -eq 'dd MMM, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -like $string.split( )[1]+&quot;*&quot;}).number -as [int] $Day=$string.Split( )[0] -as [int] } elseif ($format -eq 'MMMM dd, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -eq $string.split( )[0]}).number -as [int] $Day=$string.Split( )[1] -as [int] } elseif ($format -eq 'dd MMMM, yyyy'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[2] -as [int] $Month=($months | Where-Object{$_.Month -eq $string.split( )[1]}).number -as [int] $Day=$string.Split( )[0] -as [int] } elseif ($format -eq 'yyyy, MMM dd'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[0] -as [int] $Month=($months | Where-Object{$_.Month -like $string.split( )[1]+&quot;*&quot;}).number -as[int] $Day=$string.Split( )[2] -as [int] } elseif ($format -eq 'yyyy, MMMM dd'){ $string=$string -replace &quot;,&quot; $Year=$string.Split( )[0] -as [int] $Month=($months | Where-Object{$_.Month -eq $string.split( )[1]}).number -as [int] $Day=$string.Split( )[2] -as [int] } [PSCustomObject]@{Year=$Year;Month=$Month;Day=$Day} } function Diff-Date { PARAM( [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=0)] $date1, [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position=1)] $date2 ) for ($i=0;$i -lt $Culture.count;$i++) { if (Identify $date1 $Culture[$i].Regex) { $date1=ParseDate $date1 $Culture[$i].Format break } } for ($i=0;$i -lt $Culture.count;$i++) { if (Identify $date2 $Culture[$i].Regex) { $date2=ParseDate $date2 $Culture[$i].Format break } } $month1=0 $month2=0 for ($i=0;$i -lt $date1.month-1;$i++) { $month1+=$months[$i].Days } for ($i=0;$i -lt $date2.month-1;$i++) { $month2+=$months[$i].Days } $totaldays1=($date1.year-1)*365+$(Leapdays $date1)+$month1+$date1.day $totaldays2=($date2.year-1)*365+$(Leapdays $date2)+$month2+$date2.day $diffdate = $totaldays2 - $totaldays1 return $diffdate } $date1=Read-Host &quot;Input Start Date&quot; if (-not $date1) { $date1=&quot;1999-04-10&quot; } Write-Host $date1 $date2=Read-Host &quot;Input End Date&quot; if (-not $date2) { $date2=(Get-Date -DisplayHint Date -Format &quot;yyyy-MM-dd&quot; | Out-String).TrimEnd() } Write-Host $date2 Diff-Date $date1 $date2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:34:10.693", "Id": "498782", "Score": "2", "body": "in the 2nd code section ... why are you using date _strings_ instead of keeping everything as datetime _objects_? you really otta not EVER use date strings unless they are absolutely needed. stay with date objects until you need to do otherwise ... and even then, try to only use data strings for display." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:42:03.927", "Id": "498787", "Score": "0", "body": "@Lee_Dailey Well, I thought my code is clear and comprehensive enough, I only need New-TimeSpan to make the code working, but you see I also use Write-Output, the thing is I find the output of Write-Output line awkward and ugly if I don't format the variables, and I really didn't find a way to format [datetime] and [timespan]..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T10:36:49.580", "Id": "498788", "Score": "2", "body": "you can format things _for display_ as needed. something like `$TimeStamp.ToString('yyyy-MM-dd')` with as much detail as you need. just keep the objects _as datetime objects_ for any other use. only go to datetime _strings_ when you want to display things or send them to a file." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T09:14:22.960", "Id": "253024", "Score": "1", "Tags": [ "beginner", "programming-challenge", "datetime", "powershell" ], "Title": "PowerShell - Calculating date difference between two given dates in days without builtin and with builtin" }
253024
<h2>Problem description.</h2> <p>I have JSON which comes in bad shape:</p> <pre><code>data = [ {&quot;ids&quot;: [1]}, {&quot;ids&quot;: [3, 4]}, {&quot;ids&quot;: [1, 2]}, {&quot;ids&quot;: [4]}, {&quot;ids&quot;: [3]}, {&quot;ids&quot;: [2]}, ] # LD. List of dictionaries. </code></pre> <p>I want it to get in shape, like this:</p> <pre><code>expected = [ [{&quot;ids&quot;: [1]}, {&quot;ids&quot;: [2]}], # Length = 1 [{&quot;ids&quot;: [3, 4]}, {&quot;ids&quot;: [1, 2]}], # Length = 2 ] # LOLD. List is now list-of-lists of dictionaries. </code></pre> <p>To simplify the problem, we can remove the dictionaries of a single kv-pair, keeping in mind that we must reconstruct it later:</p> <pre><code># in [ [3, 4], [1, 2], [1], [4], [3], [2] ] # out [ [[3, 4], [1, 2]] [[1], [4], [3], [2]] ] </code></pre> <p>This is very easy. <code>assemble . op . disassemble $ data</code>:</p> <pre class="lang-py prettyprint-override"><code>def main(ids): return [list(x) for x in assemble(cardinality_groups(disassemble(ids)))] def cardinality_groups(lol): return [list(group) for _, group in groupby(sorted(lol, key=len), key=len)] def assemble(data): return [tag_datum(x) for x in data] def tag_datum(datum): return [{&quot;ids&quot;: x} for x in datum] def disassemble(ids): return [x['ids'] for x in ids] </code></pre> <h1>but</h1> <p>I insist, it must be simpler, purer! Although, I am not sure if Python sports the amenities to make things prettier. So please suggest functionality present in other languages.</p> <p>I am curious about two ways the program can expand here, and some other things:</p> <ol> <li>By the complexity and nesting of the data. Data can take the form of any JSON found in the wild. Here we simply descend a few levels down.</li> <li>By the operation performed: Here grouping by cardinality solved the issue. In another world we want no two sets to intersect. Is there any more complex operations, what are they, and do they break anything?</li> <li>Assembly-disassembly symmetry. The two should be each other's inverse, so can I deduce one from the other, thus not having to code it. Does any language provide such tools?</li> <li>Beyond typing, are there any languages that support describing how data looks when it comes in, and how it will look when it comes out? Not just the top-level type, but the shape of the data the code works with at that level of abstraction. My presumption is that many programs lend well to this type of reasoning.</li> <li>I don't like <code>f(g(h(x)))</code>. I like <code>f . g . h $ x</code>--it's purer. It really bothers that I can't do something like this in Python, or JavaScript--two of the most popular languages! Consequently, I frequently find myself doing either:</li> </ol> <pre><code>someValue = dostuff(someInput) valueIsNowSlightlyChanged = doMoreStuff(someValue) iAmLosingTrack = doStuffMoreNow(valueIsNowSlightlyChanged) final = wtf(iAmLosingTrack) return final </code></pre> <p>Or variations thereof. At this point I don't feel like using either language. Doing things this way isn't, of course, isn't always going to be possible, but I don't even get the opportunity. Am I confused, or do I have a point, and you possibly a solution to my supposed confusion?</p> <h1>\0.</h1> <p>This code was originally written for a <a href="https://stackoverflow.com/questions/65131342/list-of-dicts-group-without-intersection-by-list-keys/65132744#65132744">question</a> on StackOverflow. I believe that I found a neat way to do it in comparison to the rest. Regardless, I must assume that I don't have the only good solution. Do you have an example?</p> <p>Feel free to interpret my questions liberally. Apologies if some is beyond the scope of this forum. I appreciate any pointers to literature on these topics, as well as all your impressions.</p> <p>Please also let me know if I am unclear. Thank you!</p>
[]
[ { "body": "<p>You can avoid <code>assemble</code>, <code>disassemble</code>, <code>tag_datum</code> if you leverage on <code>key</code> param of both <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a> and <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\"><code>sorted</code></a> and condense them into one simple function.</p>\n<h3>Build a custom function for <em>key</em> param</h3>\n<p>Write a function to return the length of each <em>value</em> in the dictionary.</p>\n<pre><code>val_len = lambda x: len(x['ids'])\n</code></pre>\n<p>Now pass this as argument for <em>key</em> in both <code>itertools.groupby</code> and <code>sorted</code></p>\n<pre><code>from itertools import groupby\n\ndef transform(data):\n sorted_data = sorted(data, key=val_len)\n return [list(group) for _, group in groupby(sorted_data, key=val_len)]\n\ntransform(data) # data taken from question itself.\n# [[{'ids': [1]}, {'ids': [4]}, {'ids': [3]}, {'ids': [2]}],\n# [{'ids': [3, 4]}, {'ids': [1, 2]}]]\n</code></pre>\n<h3>Details</h3>\n<pre><code>sorted_data = sorted(data, key=val_len) # sorts data based the length of\n # the value of 'ids'\n# [{'ids': [1]}, ---|\n# {'ids': [4]}, |-- group with length 1\n# {'ids': [3]}, |\n# {'ids': [2]}, ---|\n\n# {'ids': [3, 4]},---|-- group with length 2\n# {'ids': [1, 2]}]---|\n\ngroupby(sorted_data, key=val_len) # groups data based on the length of \n # the value of 'ids'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:29:10.613", "Id": "253045", "ParentId": "253027", "Score": "3" } } ]
{ "AcceptedAnswerId": "253045", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T10:02:21.937", "Id": "253027", "Score": "1", "Tags": [ "python", "python-3.x", "functional-programming", "language-design" ], "Title": "Operations on nested data" }
253027
<p>I am a Windows power user, a system tweaker, my idol is Leanardo da Vinci, and now I want to be a hacker. I am extremely new to programming, but I really am a fast learner if I am interested in the subject, now I use PowerShell to hone my programming skills, I have only started learning PowerShell less than a month ago, and here is a script I have written without help dozen days ago to find lcm to test my skill.</p> <p>This function accepts a string of numbers seperated by comma &quot;,&quot;, finds the lcm of the series of numbers and returns it, I have confirmed it is working on PowerShell 7.1 x64 on Windows 10, I want to know if it can be shortened and still maintain human readability and clarity, without changing its logic, feel free to answer if you can help me improve it.</p> <p>The Script:</p> <pre><code>Function Find-LCM { PARAM ( [Parameter(ValueFromPipeline=$true)] [System.String]$String, [System.Double]$Number ) $array=@() [System.Double]$product=1 $Numbers = $String.Split(&quot;,&quot;) foreach ($Number in $Numbers) { $sqrt=[math]::sqrt($number) $Factor=2 $count=0 while ( ($Number % $Factor) -eq 0) { $count+=1 $Number=$Number/$Factor if (($array | Where-Object {$_ -eq $Factor}).count -lt $count) { $array+=$Factor } } $count=0 $Factor=3 while ($Factor -le $sqrt) { while ( ($Number % $Factor) -eq 0) { $count+=1 $Number=$Number/$Factor if (($array | Where-Object {$_ -eq $Factor}).count -lt $count) { $array+=$Factor } } $Factor+=2 $count=0 } if ($array -notcontains $Number) { $array+=$Number } } foreach($arra in $array) {$product = $product * $arra} $product } </code></pre> <p>Edit: deleted $maxfactor=[math]::sqrt($number) line and revised prime factorization loop condition to while ($factor -le $number), I did so because when using square root as max factor to factorise 1920 it outputed 15 as a prime factor which is wrong, now it's fixed.</p> <p>ReEdit: reimplemented square root as prime factorise while loop condition</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T10:02:35.773", "Id": "253028", "Score": "1", "Tags": [ "beginner", "programming-challenge", "mathematics", "powershell" ], "Title": "PowerShell - Find Least Common Multiple of a series of numbers" }
253028
<p>I am extremely new to programming, and I am a really fast learner if I am interested, I have only started using PowerShell in less than a month, to improve my programming skill, this is a script I have written a few days ago, to do what I said in title, I developped it all by myself, completely without help(because when I asked for help online, no one ever bothered to deliver), as a self-imposed challenge.</p> <p>Like I said, the script converts numbers in the form of English nouns to Arabic numeric values, I am on Windows 10 x64 using PowerShell 7.1 and have confirmed it is working, without bugs, here I will post this:&quot;thirty-seven million eight hundred ninety-one thousand six hundred ninety-three&quot; as sample input, it will correctly output this number 37891693, the goal of this question is to shorten the code while still maintain readability and clarity, without changing the logic, feel free to contribute if you'd like to help me improve my progamming skills, now I will post the script below:</p> <pre><code> function Str-Num { param( [Parameter(ValueFromPipeline=$true)] [System.String]$String, [System.Double]$number, [System.Double]$digit ) Process{ $lt100 = @{ 'Zero'=0 'One'=1 'Two'=2 'Three'=3 'Four'=4 'Five'=5 'Six'=6 'Seven'=7 'Eight'=8 'Nine'=9 'Ten'=10 'Eleven'=11 'Twelve'=12 'Thirteen'=13 'Fourteen'=14 'Fifteen'=15 'Sixteen'=16 'Seventeen'=17 'Eighteen'=18 'Nineteen'=19 'Twenty'=20 'Thirty'=30 'Forty'=40 'Fifty'=50 'Sixty'=60 'Seventy'=70 'Eighty'=80 'Ninety'=90 } $gt100 =@{ 'Thousand'=1e3 'Million'=1e6 'Billion'=1e9 'Trillion'=1e12 'Quadrillion'=1e15 'Quintillion'=1e18 'Sextillion'=1e21 'Septillion'=1e24 'Octillion'=1e27 'Nonillion'=1e30 'Decillion'=1e33 'Undecillion'=1e36 'Duodecillion'=1e39 'Tredecillion'=1e42 'Quattuordecillion'=1e45 'Quindecillion'=1e48 'Sexdecillion'=1e51 'Septendecillion'=1e54 'Octodecillion'=1e57 'Novemdecillion'=1e60 'Vigintillion'=1e63 'Googol'=1e100 'Centillion'=1e303 } $number=0 $digit=0 [System.Boolean]$negative=$false [System.Boolean]$decimal=$false if ($string -match '\-') {$string = $string -replace &quot;-&quot;, &quot; &quot;} if ($string -match ' and ') {$string = $string -replace &quot; and &quot;, &quot; &quot;} if ($string.split( )[0] -eq &quot;Negative&quot;) { $string = $string -replace &quot;Negative &quot; $negative=$true } if ($gt100.Keys -contains($string.split( )[0]) -or $string.split( )[0] -eq &quot;Hundred&quot;) { $string = &quot;one &quot; + $string} $count = $string.split( ).count for ($i=0;$i -lt $count;$i++) { $word = $string.split( )[$i] if ($decimal -eq $false) { if ($lt100.Keys -contains($word)){ $digit+=$lt100.$word } elseif ($word -eq &quot;Hundred&quot; -and $digit -ne 0) { $digit*=100 } elseif ($gt100.Keys -contains($word)) { $number+=$digit*$gt100.$word $digit=0 } } if ($word -eq &quot;point&quot;) { $decimal = $true $point=$i } if ($decimal -eq $true -and $lt100.Keys -contains $word) { $number+=$lt100.$word * [math]::pow(10,-($i-$point)) } } $number=$number+$digit if ($negative -eq $true) {$number=-$number} Return &quot;$number&quot; } } $string = Read-Host &quot;Please input string&quot; Str-Num $string </code></pre> <p>Update: I expanded the script to output non-garbage if informal pronounciation of years is inputed(i.e. input &quot;nine eighty-one&quot; output 981, input &quot;one oh sixty-six&quot; output 1066, input &quot;one oh oh one&quot; output 1001, input &quot;nineteen eighty four&quot; output 1984, input &quot;twenty twenty&quot; output 2020, and input &quot;ninety nine ninety nine&quot; output 9999); I did this because someone made a joking comment below, it really annoyed me... Now I will post it below:</p> <pre><code> function Str-Num { param( [Parameter(ValueFromPipeline=$true)] [System.String]$String, [System.Double]$number, [System.Double]$digit ) Process{ $lt100 = @{ 'Oh'=0 'Zero'=0 'One'=1 'Two'=2 'Three'=3 'Four'=4 'Five'=5 'Six'=6 'Seven'=7 'Eight'=8 'Nine'=9 'Ten'=10 'Eleven'=11 'Twelve'=12 'Thirteen'=13 'Fourteen'=14 'Fifteen'=15 'Sixteen'=16 'Seventeen'=17 'Eighteen'=18 'Nineteen'=19 'Twenty'=20 'Thirty'=30 'Forty'=40 'Fifty'=50 'Sixty'=60 'Seventy'=70 'Eighty'=80 'Ninety'=90 } $gt100 =@{ 'Thousand'=1e3 'Million'=1e6 'Billion'=1e9 'Trillion'=1e12 'Quadrillion'=1e15 'Quintillion'=1e18 'Sextillion'=1e21 'Septillion'=1e24 'Octillion'=1e27 'Nonillion'=1e30 'Decillion'=1e33 'Undecillion'=1e36 'Duodecillion'=1e39 'Tredecillion'=1e42 'Quattuordecillion'=1e45 'Quindecillion'=1e48 'Sexdecillion'=1e51 'Septendecillion'=1e54 'Octodecillion'=1e57 'Novemdecillion'=1e60 'Vigintillion'=1e63 'Googol'=1e100 'Centillion'=1e303 } $number=0 $digit=0 [System.Boolean]$negative=$false [System.Boolean]$decimal=$false [System.Boolean]$invalid=$false if ($string -match '\-') {$string = $string -replace &quot;-&quot;, &quot; &quot;} if ($string -match ' and ') {$string = $string -replace &quot; and &quot;, &quot; &quot;} if ($string.split( )[0] -eq &quot;Negative&quot;) { $string = $string -replace &quot;Negative &quot; $negative=$true } if ($gt100.Keys -contains($string.split( )[0]) -or $string.split( )[0] -eq &quot;Hundred&quot;) { $string = &quot;one &quot; + $string} $count = $string.split( ).count if ($count -eq 2 -or $count -eq 3 -or $count -eq 4){ $n=0 $array = $string.split( ) foreach ($arra in $array){ if ($lt100.Keys -contains($arra)){ $n+=1 } } if ($n -eq $count) { if ($count -eq 2) { if ($lt100.($string.split( )[0]) -lt 20 -or $lt100.($string.split( )[1]) -ge 10){ $fault=$string $string=$string.split( )[0]+&quot; Hundred &quot;+$string.split( )[1] $invalid=$true } } elseif ($count -eq 3 -or $count -eq 4) { $fault=$string $invalid=$true if ($count -eq 3){ $string=$string.split( )[0]+&quot; Hundred &quot;+$string.split( )[1]+&quot; &quot;+$string.split( )[2] } elseif ($count -eq 4) { if ($lt100.($string.split( )[0]) -ge 20){ $string=$string.split( )[0]+&quot; &quot;+$string.split( )[1]+&quot; Hundred &quot;+$string.split( )[2]+&quot; &quot;+$string.split( )[3] } elseif ($lt100.($string.split( )[0]) -lt 10){ $string=$string.split( )[0]+&quot; Thousand &quot;+$string.split( )[1]+&quot; &quot;+$string.split( )[2]+&quot; &quot;+$string.split( )[3] } } } if ($invalid -eq $true) { Write-Warning &quot;Invalid expression detected, $fault is not a valid expression for numbers, it has been recognized as an English informal way to pronounce years;$fault has been adjusted to this valid expression: $string so this program can process it.&quot; } } } $count = $string.split( ).count for ($i=0;$i -lt $count;$i++) { $word = $string.split( )[$i] if ($decimal -eq $false) { if ($lt100.Keys -contains($word)){ $digit+=$lt100.$word } elseif ($word -eq &quot;Hundred&quot; -and $digit -ne 0) { $digit*=100 } elseif ($gt100.Keys -contains($word)) { $number+=$digit*$gt100.$word $digit=0 } } if ($word -eq &quot;point&quot;) { $decimal = $true $point=$i } if ($decimal -eq $true -and $lt100.Keys -contains $word) { $number+=$lt100.$word * [math]::pow(10,-($i-$point)) } } $number=$number+$digit if ($negative -eq $true) {$number=-$number} Return &quot;$number&quot; } } $string = Read-Host &quot;Please input string&quot; Str-Num $string </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T11:55:59.360", "Id": "498791", "Score": "0", "body": "what's the output from `nine eighty one`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T05:18:32.100", "Id": "498912", "Score": "0", "body": "What? Somebody made a nonsensical comment when I was away? @OhMyGoodness, are you serious? You know that saying, garbage in, garbage out, my algorithm is designed to convert valid English number expressions to numerical values, the informal way of pronouncing years is wrong, invalid, nonsense, sorry, but garbage is garbage, but did you think I couldn't implement it? You underestimated me.." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T11:27:13.340", "Id": "253030", "Score": "1", "Tags": [ "beginner", "programming-challenge", "converting", "powershell", "numbers-to-words" ], "Title": "PowerShell - Convert English words describing numbers to their values in Arabic numeral" }
253030
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252605/231235">std::deque and std::list Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a>. The only thing different in the previous implemented <code>n_dim_vector_generator</code>, <code>n_dim_array_generator</code>, <code>n_dim_deque_generator</code> and <code>n_dim_list_generator</code> functions is the type of container. After checking <a href="https://codereview.stackexchange.com/a/252946/231235">G. Sliepen's answer</a> in the question <a href="https://codereview.stackexchange.com/q/252930/231235">Non-nested std::deque and std::list Generator Function for arithmetic_mean Function Testing in C++</a>, I found that there is a way to implement a more generic template function <code>n_dim_container_generator</code>.</p> <p><strong>The usage description</strong></p> <p>For example, <code>auto test_vector = n_dim_container_generator&lt;std::vector, 2, 3, int&gt;(1);</code> is expected to create a &quot;test_vector&quot; object which type is <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code>. The content of this <code>test_vector</code> should as same as the following code.</p> <pre><code>std::vector&lt;int&gt; vector1; vector1.push_back(1); vector1.push_back(1); vector1.push_back(1); std::vector&lt;std::vector&lt;int&gt;&gt; test_vector; test_vector.push_back(vector1); test_vector.push_back(vector1); test_vector.push_back(vector1); </code></pre> <p>There are five key parameters in the usage of <code>n_dim_container_generator</code>. With the mentioned example above, the first one <code>std::vector</code> is the type of the container in output structure, the second one <code>2</code> represents the nested layers, the third parameter <code>3</code> represents the element count in each layer, the fourth parameter <code>int</code> represents the type of base elements and the final one <code>1</code> represents the base element input which would be filled in.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation of <code>n_dim_container_generator</code> template function is as follows.</p> <pre><code>template&lt;template&lt;class...&gt; class Container = std::vector, std::size_t dim, std::size_t times, class T&gt; constexpr auto n_dim_container_generator(T input) { if constexpr (dim == 0) { return input; } else { Container&lt;decltype(n_dim_container_generator&lt;Container, dim - 1, times, T&gt;(input))&gt; output; output.resize(times); std::fill(std::begin(output), std::end(output), n_dim_container_generator&lt;Container, dim - 1, times, T&gt;(input)); return output; } } </code></pre> <p><strong>Test cases</strong></p> <p>With the <code>recursive_print</code> template function (refer to the previous question <a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>), the <code>n_dim_container_generator</code> template function could be tested as the following code.</p> <pre><code>auto test_vector = n_dim_container_generator&lt;std::vector, 2, 3, int&gt;(1); recursive_print(test_vector); </code></pre> <p>The output is as below.</p> <pre><code>Level 0: Level 1: 1 1 1 Level 1: 1 1 1 Level 1: 1 1 1 </code></pre> <p>In order to make sure the functionality of <code>n_dim_container_generator</code>, the various test cases have been implemented.</p> <ol> <li>The use cases of <code>std::vector</code></li> </ol> <p>With <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="noreferrer">Boost.Test</a> tool, the various use cases of nested <code>std::vector</code> structure are implemented as below.</p> <pre><code>BOOST_AUTO_TEST_CASE(vector_test_1dimension_char) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_int) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_short) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_long) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_long_long_int) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_unsigned_char) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_float) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_double) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_1dimension_long_double) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_char) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_int) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_short) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_long) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_long_long_int) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_unsigned_char) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_float) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_double) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_2dimension_long_double) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_char) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_int) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_short) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_long) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_long_long_int) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_unsigned_char) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_float) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_double) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_3dimension_long_double) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_char) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_int) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_short) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_long) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_long_long_int) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_unsigned_char) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_float) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_double) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_4dimension_long_double) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_char) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_int) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_short) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_long) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_long_long_int) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_unsigned_char) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_float) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_double) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_5dimension_long_double) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_char) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_int) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_short) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_long) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_long_long_int) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_unsigned_char) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_float) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_double) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_6dimension_long_double) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_char) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_int) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_short) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_long) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_long_long_int) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_unsigned_char) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_float) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_double) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_7dimension_long_double) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_char) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_int) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_short) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_long) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_long_long_int) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_unsigned_char) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_float) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_double) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_8dimension_long_double) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_char) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_int) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_short) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_long) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_long_long_int) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_unsigned_char) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_float) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_double) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(vector_test_9dimension_long_double) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } </code></pre> <p><a href="https://godbolt.org/z/ffPbvW" rel="noreferrer">A Godbolt link (<code>std::vector</code> part) is here.</a></p> <p>Note: The compiling output from Godbolt is <code>&lt;Compilation failed&gt;</code> and the error messages are <code>Killed - processing time exceeded</code> and <code>virtual memory exhausted: Cannot allocate memory</code>. This issue seems to be caused by <a href="https://www.boost.org/doc/libs/1_72_0/libs/test/doc/html/index.html" rel="noreferrer">Boost.Test</a> tool is too large and the multidimensional container structure is too complex. If the enough memory and compile time resource is available, the test output is like:</p> <pre><code>Running 90 test cases... *** No errors detected </code></pre> <ol start="2"> <li>The use cases of <code>std::deque</code> and <code>std::list</code></li> </ol> <p>When it comes to the cases of <code>std::deque</code> and <code>std::list</code>, the test code can get based on the above code by replacing the keyword <code>vector</code> into <code>deque</code> and <code>list</code>. The result can be checked as follows.</p> <pre><code>BOOST_AUTO_TEST_CASE(deque_test_1dimension_char) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_int) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_short) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_long) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_long_long_int) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_unsigned_char) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_float) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_double) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(deque_test_1dimension_long_double) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } </code></pre> <pre><code>BOOST_AUTO_TEST_CASE(list_test_1dimension_char) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_int) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_short) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef short TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_long) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_long_long_int) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long long int TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_unsigned_char) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef unsigned char TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_float) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef float TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_double) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE(list_test_1dimension_long_double) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef long double TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } </code></pre> <p><a href="https://godbolt.org/z/E75e8f" rel="noreferrer">A Godbolt link is here.</a></p> <p>Furthermore, with <a href="https://www.boost.org/doc/libs/1_74_0/libs/test/doc/html/boost_test/tests_organization/test_cases/test_organization_templates.html#ref_BOOST_AUTO_TEST_CASE_TEMPLATE" rel="noreferrer">Test case template with automated registration</a>, the various element type can be listed in <code>boost::mpl::list</code> and the test cases can be generated automatically.</p> <pre><code>typedef boost::mpl::list&lt;char, int, short, long, long long int, unsigned char, unsigned int, unsigned short int, unsigned long int, float, double, long double&gt; test_types; BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_1dimension, T, test_types) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_2dimension, T, test_types) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_3dimension, T, test_types) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_4dimension, T, test_types) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_5dimension, T, test_types) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_6dimension, T, test_types) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_7dimension, T, test_types) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_8dimension, T, test_types) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_9dimension, T, test_types) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(vector_test_10dimension, T, test_types) { constexpr int nested_layer = 10; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::vector, nested_layer, element_count, TestType&gt;(input)) == (n_dim_vector_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_1dimension, T, test_types) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_2dimension, T, test_types) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_3dimension, T, test_types) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_4dimension, T, test_types) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_5dimension, T, test_types) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_6dimension, T, test_types) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_7dimension, T, test_types) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_8dimension, T, test_types) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_9dimension, T, test_types) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(deque_test_10dimension, T, test_types) { constexpr int nested_layer = 10; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::deque, nested_layer, element_count, TestType&gt;(input)) == (n_dim_deque_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_1dimension, T, test_types) { constexpr int nested_layer = 1; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_2dimension, T, test_types) { constexpr int nested_layer = 2; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_3dimension, T, test_types) { constexpr int nested_layer = 3; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_4dimension, T, test_types) { constexpr int nested_layer = 4; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_5dimension, T, test_types) { constexpr int nested_layer = 5; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_6dimension, T, test_types) { constexpr int nested_layer = 6; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_7dimension, T, test_types) { constexpr int nested_layer = 7; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_8dimension, T, test_types) { constexpr int nested_layer = 8; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_9dimension, T, test_types) { constexpr int nested_layer = 9; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } BOOST_AUTO_TEST_CASE_TEMPLATE(list_test_10dimension, T, test_types) { constexpr int nested_layer = 10; constexpr int element_count = 3; typedef T TestType; TestType input = 1; BOOST_TEST((n_dim_container_generator&lt;std::list, nested_layer, element_count, TestType&gt;(input)) == (n_dim_list_generator&lt;nested_layer, TestType&gt;(input, element_count))); BOOST_TEST(true); } </code></pre> <p><a href="https://godbolt.org/z/6d1hdY" rel="noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/252605/231235">std::deque and std::list Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am trying to implement a <code>n_dim_container_generator</code> function which can generate various container type arbitrary nested iterables in this question.</p> </li> <li><p>Why a new review is being asked for?</p> <p>Although there are a lot of test cases above, I still think that it is hard to verify <code>n_dim_container_generator</code> template function. There are too many possible usages and if there is any potential defect existed, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Template vs. function parameters</h1>\n<p>Template parameters should normally be used for things that affect the type of the result, but not for other things. The template parameter <code>times</code> does not affect the type of the result, so it can just be a regular function parameter:</p>\n<pre><code>template&lt;template&lt;class...&gt; class Container = std::vector, std::size_t dim, class T&gt;\nconstexpr auto n_dim_container_generator(T input, std::size_t times)\n{\n if constexpr (dim == 0)\n {\n return input;\n }\n else\n {\n Container&lt;decltype(n_dim_container_generator&lt;Container, dim - 1, T&gt;(input, times))&gt; output;\n output.resize(times);\n std::fill(std::begin(output), std::end(output), n_dim_container_generator&lt;Container, dim - 1, T&gt;(input, times));\n return output;\n }\n}\n</code></pre>\n<h1>Avoid unnecessary default initialization</h1>\n<p>By calling <code>output.resize(times)</code>, you force the container to default construct all elements, right before you overwrite all elements. The solution is to use <code>reserve()</code> instead, and <code>push_back()</code> the elements you want to add:</p>\n<pre><code>output.reserve(times);\nstd::fill_n(std::back_inserter(output), times, n_dim_container_generator&lt;Container, dim - 1, T&gt;(input, times));\n</code></pre>\n<h1>Avoid repetition</h1>\n<p>You are repeating the recursive call to the function with <code>dim - 1</code> twice, once to get its return type and once to actually get a value. You can avoid the repetition by just getting a value first:</p>\n<pre><code>auto element = n_dim_container_generator&lt;Container, dim - 1, T&gt;(input, times);\nContainer&lt;decltype(element)&gt; output;\noutput.reserve(times);\nstd::fill_n(std::back_inserter(output), times, element);\n</code></pre>\n<h1>Make use of the constructors that fill the container for you</h1>\n<p>The constructors of <code>std::vector</code>, <code>std::list</code> and <code>std::deque</code> all have an overload that take a <code>count</code> and a <code>const T &amp;element</code> as an argument, and will construct a container with the given element repeated <code>count</code> times. That's exactly what you are trying to do manually. So you can just make use of those constructors and write:</p>\n<pre><code>template&lt;template&lt;class...&gt; class Container = std::vector, std::size_t dim, class T&gt;\nconstexpr auto n_dim_container_generator(T input, std::size_t times)\n{\n if constexpr (dim == 0)\n {\n return input;\n }\n else\n {\n return Container(times, n_dim_container_generator&lt;Container, dim - 1, T&gt;(input, times));\n }\n}\n</code></pre>\n<h1>Non-deducible template parameters without a default value must come before template parameters with a default value</h1>\n<p>You gave the template parameter <code>Container</code> a default value, but you can actually never write something like:</p>\n<pre><code>auto data = n_dim_container_generator&lt;2&gt;(1, 3);\n</code></pre>\n<p>To fix this, make sure <code>std::size_t dim</code> comes first:</p>\n<pre><code>template&lt;std::size_t dim, template&lt;class...&gt; class Container = std::vector, class T&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:27:11.003", "Id": "498823", "Score": "0", "body": "My first interpretation of \"*repeating the call*\" was that the run-time work was being performed twice, rather than repeating the source code for it in non-evaluated context as argument to `decltype()`. I wish I could suggest a better wording for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:48:20.140", "Id": "498861", "Score": "0", "body": "@TobySpeight Maybe \"call expression\"? But yeah, I couldn't find something better either." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:34:12.270", "Id": "253039", "ParentId": "253032", "Score": "4" } } ]
{ "AcceptedAnswerId": "253039", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T12:09:00.900", "Id": "253032", "Score": "5", "Tags": [ "c++", "recursion", "unit-testing", "boost", "c++20" ], "Title": "A Various Container Type Arbitrary Nested Iterable Generator Function Implementation in C++" }
253032
<p>I have a function that takes a falling car's location &amp; velocity as well as the world gravity. The world has a floor, ceiling, and walls that are in fixed positions. The car's x &amp; y velocity can't change once it's airborne, but gravity does force the car down. I'm trying to find exactly which plane the car will land on first.</p> <p>This is my current solution, which actually works just fine:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;math.h&gt; // Vector stuff typedef struct vector { double x; double y; double z; } Vector; static inline Vector add(Vector vec1, Vector vec2) { return (Vector){vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z}; } static inline Vector multiply(Vector vec1, Vector vec2) { return (Vector){vec1.x * vec2.x, vec1.y * vec2.y, vec1.z * vec2.z}; } static inline double dot(Vector vec1, Vector vec2) { return vec1.x * vec2.x + vec1.y * vec2.y + vec1.z * vec2.z; } static inline double magnitude(Vector vec) { return sqrt(dot(vec, vec)); } static inline Vector double_to_vector(double num) { return (Vector){num, num, num}; } // find the falling car's landing plane int find_landing_plane(Vector car_location, Vector *car_velocity, double *gravity) { Vector l = car_location; Vector v = *car_velocity; Vector V_simulation_dt = double_to_vector(simulation_dt); double g = *gravity * simulation_dt; if (fabs(l.y) &gt;= 5120) return 5; // this is a special exception while (1) { if (magnitude(v) &lt; 2300) // 2300 = terminal velocity v.z = v.z + g; l = add(l, multiply(v, V_simulation_dt)); // there must be a better way to do this... if (l.x &gt;= 4080) return 0; // wall if (l.x &lt;= -4080) return 1; // wall if (l.y &gt;= 5110) return 2; // wall if (l.y &lt;= -5110) return 3; // wall if (l.z &gt;= 2030) return 4; // ceiling if (l.z &lt;= 20) return 5; // floor } } </code></pre> <p>I'm new to C, but I do have a few years of programming experience... SURELY there's a better way to do this? I was thinking perhaps something to do with the trajectory formula, or just a way to make the if statements nicer to look at would also be great.</p>
[]
[ { "body": "<h1>Don't hardcode values</h1>\n<p>There are lots of magic values that you are using in your code, from the terminal velocity, the wall coordinates to the numbering of the walls. Try to give everything a name: declare constants for the coordinates and terminal velocity, and create an enum for the six faces of the enclosing box:</p>\n<pre><code>enum Face {\n FACE_RIGHT,\n FACE_LEFT,\n FACE_BACK,\n FACE_FRONT,\n FACE_TOP,\n FACE_BOTTOM,\n};\n\nstatic const double terminal_velocity = 2300;\nstatic const double right_wall_position = 4080;\n...\n</code></pre>\n<p>It's a little bit more typing, but there are several benefits. In particular, it makes the code more self-documenting. Consider the return type of <code>find_landing_plane()</code>:</p>\n<pre><code>enum Face find_landing_plane(...) {\n ...\n if (l.x &gt; right_wall_position)\n return FACE_RIGHT;\n ...\n}\n</code></pre>\n<p>You also don't need to add a comment to this line anymore:</p>\n<pre><code>if (magnitude(v) &lt; terminal_velocity)\n</code></pre>\n<h1>Consider using arrays to avoid repetition</h1>\n<p>You could get rid of the repeated <code>if</code>-statements by treating the vector as an array, and also having an array to encode the positions of the planes. It would look like this:</p>\n<pre><code>static const double plane_positions[6] = {4080, -4080, 5110, -5110, 2030, 20};\n...\nenum Face find_landing_plane(Vector car_location, Vector *car_velocity, double *gravity)\n{\n ...\n while (1)\n {\n // update l\n ...\n \n double *l_vec = &amp;l.x;\n\n for (int i = 0; i &lt; 6; i++) {\n if (i % 2 == 0 ? l_vec[i / 2] &gt;= plane_positions[i] : l_vec[i / 2] &lt;= plane_positions[i])\n return i;\n }\n }\n} \n</code></pre>\n<p>However, I'm not sure it is all that better, as it uses a complex expression and no longer uses the enum values by name, making it harder to understand and easier to make mistakes.</p>\n<h1>Solve the problem analytically</h1>\n<p>Finding the plane the car hits by updating the position in a loop is inefficient. The problem can be solved analytically. The trajectory the car follows is a parabola up to the point the terminal velocity is reached. You can solve for time the parabola intersects each of the the six planes, and also solve for the time the terminal velocity is reached. If the earliest time found that is not in the past is a plane, you know that plane was hit first. If the earliest time is when the terminal velocity is reached, you then now that the rest of the trajectory is a straight line, so you can then do the even easier step of solving for the intersection of a straight line with six planes.</p>\n<p>This is more code to write, although here you could also make an array with the parameters describing each of the six planes, and use a <code>for</code>-loop to check for the intersection with each of them. The advantage is that it should be much more efficient and much more precise (consider that you have a bias in your algorithm when the car hits very close to a corner).</p>\n<h1>Add a better description of the special exception</h1>\n<p>Why is <code>fabs(l.y) &gt; 5120</code> special? You commented that it is an exception, but that still doesn't tell me why. Why is it 5120 (consider making a constant for that as well), and why do you need to handle this case at all, when it looks like the rest of the code would handle that fine?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:00:26.180", "Id": "498880", "Score": "0", "body": "`fabs(l.y) > 5120` is special because the field isn't a perfect cuboid, and there are two, small extra shapes extending from the main ones. I'm calling them 'shapes' bc they're a little funky, but they have a flat floor so I just say if the car is in one of them then recover on the floor" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:06:45.080", "Id": "498884", "Score": "0", "body": "Also, are there any performance benefits for not using hardcoded values? Every microsecond counts, due to the nature of the program that this is apart of" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:42:47.037", "Id": "498891", "Score": "0", "body": "You say `You can solve for time the parabola intersects each of the the six planes,` and I'm probably going to do that, but... what's the name of the formula to find that? Thanks -_-" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:43:25.327", "Id": "498892", "Score": "0", "body": "Would I just use a 3d quadratic equation or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:52:17.410", "Id": "498895", "Score": "2", "body": "You probably could, but since the planes are axis aligned, I would just consider the `x`, `y` and `z` components separately. That way, it just becomes 3 2D problems (`x,t`, `y,t` and `z,t`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T21:17:12.143", "Id": "498898", "Score": "0", "body": "This looks great! I'll accept your answer once I've got a prototype in the works - it shouldn't take long, a day at most" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:21:47.133", "Id": "253056", "ParentId": "253034", "Score": "5" } } ]
{ "AcceptedAnswerId": "253056", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T12:47:13.880", "Id": "253034", "Score": "5", "Tags": [ "beginner", "c" ], "Title": "Find plane (walls, floor, ceiling) that a falling car will land on" }
253034
<p>I have to do some check/match elements with conditions. A have a list of conditions, each with a specific ID. I've put for each of my elements an array with the ids of their respective affirmative conditions.</p> <p>Some elements can share a condition. The goal is to, everytime a condition is &quot;checked&quot; by the user, the code filter the array with all elements, showing only the ones that attend the conditions.</p> <p>I've made this function. But I don't know if its the &quot;best&quot; way..</p> <p>this.selectedConditions is already maped by ID</p> <p>Any help?</p> <hr /> <pre><code>private filterElements(){ let filtered: any[] = []; originalArray.forEach( item =&gt; { let isPossibility: boolean = true; for (let i = 0; i &lt; this.selectedConditions.length; i++) { if( item.condition_matrix.indexOf( this.selectedConditions[i] ) === -1 ){ isPossibility = false; break; } } if( isPossibility ){ filtered.push(item); } }); this.outputArray = filtered; if(this.outputArray.length === 0){ this.outputArray.push( { &lt;a_filler_object&gt; } ); } } </code></pre> <hr /> <p>Elements list example:</p> <pre><code>elements: [ { name: 'el1', condition_matrix: [1,2] }, { name: 'el2', condition_matrix: [2,3] }, { name: 'el3', condition_matrix: [2,1] } ] </code></pre> <p>Conditions list example:</p> <pre><code>conditions: [ { id: 1 name: 'cond1' }, { id: 2 name: 'cond2' }, { id: 3 name: 'cond3' } ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:48:40.913", "Id": "498826", "Score": "1", "body": "I'd suggest putting the code first and the example data after that. Looking at the example data makes the question look hypothetical, which is off-topic for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T16:20:18.587", "Id": "498829", "Score": "0", "body": "@pacmaninbw edited. Thx buddy" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:44:43.510", "Id": "498842", "Score": "1", "body": "Welcome to Code Review! I have rolled back Rev 3 → 2. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>It looks like you're using TypeScript, so a couple pointers:</p>\n<p><strong>Avoid <code>any</code></strong> - <code>any</code> effectively disables type-checking, which defeats the whole point of using TypeScript. Better to type variables properly:</p>\n<pre><code>let filtered: Array&lt;{ name: string; condition_matrix: Array&lt;number&gt;; }&gt; = [];\n</code></pre>\n<p>Or, even better, let TypeScript infer the types automatically when possible, by transforming the data <em>all at once</em> with array methods (see below). No need to denote types when TS can infer them automatically - eg <code>let isPossibility: boolean = true;</code> can be just <code>let isPossibility = true;</code></p>\n<p><strong>Avoid <code>let</code>, prefer <code>const</code></strong> - see <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">here</a>, using <code>const</code> indicates that the variable will never be reassigned, which reduces cognitive overhead.</p>\n<p><strong>Semantic array methods</strong> While <code>for</code> loops <em>work</em>, they should only be used as a last resort, when other array methods aren't appropriate. Here, rather than <code>break</code>ing inside a <code>for</code> loop to check if an item passes a condition, it would be better to use <code>.some</code>. Also, rather than <code>.push</code>ing to an outer array based on the condition, use <code>.filter</code> instead:</p>\n<pre><code>this.outputArray = originalArray.filter(\n item =&gt; this.selectedConditions.some(\n condition =&gt; item.condition_matrix.includes(condition)\n )\n);\n</code></pre>\n<p>(Better to use <code>.includes</code> than to use an <code>indexOf</code> check against 0)</p>\n<p>Or:</p>\n<p><strong>Time complexity</strong> If performance is an issue and you have a lot of conditions, rather than iterating all of the conditions each time, consider constructing a Set of all of the <code>selectedConditions</code> first; <code>Set#has</code> is <code>O(1)</code>, which is an improvement over iterating over arrays with <code>O(n)</code>.</p>\n<pre><code>const allConditions = new Set(this.selectedConditions);\n</code></pre>\n<p><strong>Conditions list typo?</strong> The data structure in your code is an array of objects, but you're using <code>item.condition_matrix.indexOf( this.selectedConditions[i] )</code>. Did you mean:</p>\n<pre><code>item.condition_matrix.indexOf( this.selectedConditions[i].id )\n</code></pre>\n<p>?</p>\n<p>(If so, and you want to use the Set method, map to IDs first:</p>\n<pre><code>const allConditions = new Set(\n this.selectedConditions.map(({ id ]) =&gt; id)\n);\n</code></pre>\n<p>)</p>\n<p><strong>Side-effects?</strong> The result of the whole function is to <em>set</em> a value (to <code>this.outputArray</code>). Is this required? Code is generally easiest to understand and reason about when it does not contain side-effects. Imagine seeing some code you haven't looked at before, and compare:</p>\n<pre><code>this.calculate();\nconsole.log('Result:', this.result);\n</code></pre>\n<p>vs</p>\n<pre><code>console.log('Result:', this.calculate());\n</code></pre>\n<p>The second is easier to make sense of because the method is used for its <em>return value</em> instead of for its side-effects (which, to understand, you'd have to read through the method to find).</p>\n<p>Could your <code>filterElements</code> method return a value instead of assigning to <code>this.outputArray</code>?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T14:57:28.647", "Id": "253040", "ParentId": "253038", "Score": "5" } } ]
{ "AcceptedAnswerId": "253040", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T13:38:10.130", "Id": "253038", "Score": "4", "Tags": [ "javascript", "array" ], "Title": "Improving a filter array function, to match elements and conditions" }
253038
<p>Can you please share your thoughts on the following simple httphelper in Go? Thanks in advance. I mainly would like to know whether returning a channel of a custom type seems like a good idea and if so , how could I improve it for only receive chans.</p> <pre><code>package services import ( &quot;bytes&quot; &quot;encoding/json&quot; &quot;io/ioutil&quot; &quot;net/http&quot; &quot;time&quot; ) type HHResult struct { Result string StatusCode int Error error } type IHttpHelper interface { Request(method string, url string, headers map[string][]string, payload interface{}) chan HHResult RequestWithOptions(method string, url string, headers map[string][]string, payload interface{}) chan HHResult } var singleton IHttpHelper type HttpHelper struct{} func (h *HttpHelper) Request(method string, url string, headers map[string][]string, payload interface{}) chan HHResult { var result chan HHResult = make(chan HHResult) go func(output chan HHResult) { payl, err := json.Marshal(payload) if err != nil { result &lt;- HHResult{ Result: &quot;&quot;, StatusCode: 0, Error: err, } } req, err := http.NewRequest(method, url, bytes.NewReader(payl)) client := http.Client{ Timeout: time.Second * 30, } resp, err := client.Do(req) if err != nil { result &lt;- HHResult{ Result: &quot;&quot;, StatusCode: 0, Error: err, } } respbytes, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() result &lt;- HHResult{ Result: string(respbytes), StatusCode: resp.StatusCode, Error: nil, } }(result) return result } func (h *HttpHelper) RequestWithOptions(method string, url string, headers map[string][]string, payload interface{}, timeout int) chan HHResult { var result chan HHResult = make(chan HHResult) go func(output chan&lt;- HHResult) { payl, err := json.Marshal(payload) if err != nil { result &lt;- HHResult{ Result: &quot;&quot;, StatusCode: 0, Error: err, } } req, err := http.NewRequest(method, url, bytes.NewReader(payl)) client := http.Client{ Timeout: time.Second * timeout, } resp, err := client.Do(req) if err != nil { result &lt;- HHResult{ Result: &quot;&quot;, StatusCode: 0, Error: err, } } respbytes, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() result &lt;- HHResult{ Result: string(respbytes), StatusCode: resp.StatusCode, Error: nil, } }(result) return result } func NewHttpHelper() IHttpHelper { if singleton == nil { singleton = &amp;HttpHelper{} } return singleton } </code></pre> <h2>Example of usage</h2> <pre><code>func main() { helper := services.NewHttpHelper() res := &lt;-helper.Request(&quot;GET&quot;, &quot;https://jsonplaceholder.typicode.com/users/1&quot;, nil, nil) if res.Error != nil { fmt.Println(res.Error.Error()) return } fmt.Println(res.StatusCode) fmt.Println(res.Result) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:20:16.733", "Id": "498851", "Score": "0", "body": "Can you explain what your code is trying to do? `IHttpHelper` and `RequestWithOptions` aren't particularly descriptive names" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:33:25.120", "Id": "498855", "Score": "0", "body": "they are just a wrapper on top of http operations. I want to GET, POST , etc from and endpoint and get a channel back with the response" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:34:58.433", "Id": "498856", "Score": "0", "body": "Can you add a small example of a function that would use this then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:41:31.583", "Id": "498859", "Score": "0", "body": "I have added a usage sample." } ]
[ { "body": "<p>Listing in order the things I made note of/changed looking through your code:</p>\n<ol>\n<li><p><code>output chan HHResult</code> is declared but never used in <code>go funcs(output chan HHResult)</code>. It's fine that it's not used, the go func has access to <code>Result</code> in the parent function, but you don't need to declare it if it's not needed.</p>\n</li>\n<li><p>The <code>headers</code> map argument is never used either.</p>\n</li>\n<li><p>Looking at <code>Request</code> and <code>RequestWithOptions</code> they're the same function except for the variable timeout. <code>Request</code> can be a small wrapper that just sets a default timeout then calls the more general function</p>\n</li>\n<li><p>Similarly, you repeatedly return the same <code>HHResult</code> only substituting which <code>err</code> is used so that can be pulled into it's own function <code>sendErr(chan, err)</code></p>\n</li>\n<li><p>Any exported function or type (any that start with capital letters) should be commented</p>\n</li>\n<li><p>If you look in the <code>net/http</code> package you'll see it's standard to capitalize <code>HTTP</code> in variable names. Same with <code>JSON</code>.</p>\n</li>\n<li><p>Bugs:</p>\n</li>\n</ol>\n<p>a. One bug in your code is you send JSON via <code>http.Request</code> but you don't actually set the <code>Content-Type</code> to <code>application/json</code> which can cause issues with how your request is interpreted on the other end</p>\n<p>b. Another bug is that the error in <code>respbytes, err := ioutil.ReadAll(resp.Body)</code> is never used and you actually return <code>nil</code> for it whether or not you could actually read the body.</p>\n<p>c. <code>Timeout: time.Second * 30</code> throws an error</p>\n<ol start=\"8\">\n<li><p>As written, I don't see the need for the <code>IHTTPHelper</code> interface. <code>HttpHelper</code> has the only two methods used hanging directly from the struct and there's no way to inject a different type implementing the same interface into any of your code. As is <code>HttpHelper</code> alone does everything you need.</p>\n</li>\n<li><p>Purely stylistically, I think some of the variable names like <code>HHResults</code> are confusing and rewrote them</p>\n</li>\n</ol>\n<hr />\n<pre><code>package services\n\nimport (\n &quot;bytes&quot;\n &quot;encoding/json&quot;\n &quot;io/ioutil&quot;\n &quot;net/http&quot;\n &quot;time&quot;\n)\n\n// HelperResponse is the response returned by an HTTPHelper.Request()\ntype HelperResponse struct {\n Result string\n StatusCode int\n Error error\n}\n\n// HTTPHelper hangs Request and RequestWithTimeout methods\ntype HTTPHelper struct{}\n\nvar singleton *HTTPHelper\n\n// NewHTTPHelper returns a pointer to the HTTPHelper singleton\nfunc NewHTTPHelper() *HTTPHelper {\n if singleton == nil {\n singleton = &amp;HTTPHelper{}\n }\n return singleton\n}\n\nfunc sendErr(out chan HelperResponse, err error) {\n out &lt;- HelperResponse{\n Result: &quot;&quot;,\n StatusCode: 0,\n Error: err,\n }\n}\n\n// Request wraps RequestWithTimeout with default 30 second timeout\nfunc (h *HTTPHelper) Request(method string, url string, payload interface{}) (out chan HelperResponse) {\n return h.RequestWithTimeout(method, url, payload, 30)\n}\n\n// RequestWithTimeout returns Response, StatusCode, and any Errors from an http request\nfunc (h *HTTPHelper) RequestWithTimeout(method string, url string, payload interface{}, timeout int) (out chan HelperResponse) {\n go func() {\n payloadJSON, err := json.Marshal(payload)\n if err != nil {\n sendErr(out, err)\n }\n\n req, err := http.NewRequest(method, url, bytes.NewReader(payloadJSON))\n req.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)\n\n client := http.Client{Timeout: time.Second * time.Duration(timeout)}\n\n resp, err := client.Do(req)\n if err != nil {\n sendErr(out, err)\n }\n\n respBytes, err := ioutil.ReadAll(resp.Body)\n defer resp.Body.Close()\n\n out &lt;- HelperResponse{\n Result: string(respBytes),\n StatusCode: resp.StatusCode,\n Error: err,\n }\n }()\n\n return out\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:44:19.320", "Id": "498893", "Score": "1", "body": "Your comments are awesome. Ill rewrite this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:48:54.740", "Id": "498894", "Score": "1", "body": "One more note, you'll see in my rewrite I used named returns (`out` specifically) in the function definition. If you haven't seen that before it saves one line but is pretty much a stylistic choice, not required" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:30:17.417", "Id": "253060", "ParentId": "253041", "Score": "1" } } ]
{ "AcceptedAnswerId": "253060", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:00:20.617", "Id": "253041", "Score": "1", "Tags": [ "go", "http" ], "Title": "Simple http helper in Go" }
253041
<p>I have a database object that has a field called <code>workdays</code>, it's a array boolean that contains 7 elements representing whether the user is active on the corresponding day.</p> <p>I need to save this array into the database, I thought the bets way would be to convert the boolean array into a integer (bits) array and convert that into an integer which can be saved in the DB.</p> <p>this is what I came up with, but I feel like I'm doing it the unnecessarily long way.</p> <p>How can this be improved upon ?</p> <pre><code> function serializeDays(days: boolean[]): number { // use (days || []) to avoid null pointer exception // concat it with Array(7).fill(false) to fill in missing values const d1 = (days || []).concat(Array(7).fill(false)).slice(0, 7); // map the boolean values to int values const d2 = d1.map(d =&gt; (d ? 1 : 0)); // join the array to string const d3 = d2.join(&quot;&quot;); // parse the string into base 10 from base 2 const n = parseInt(d3, 2); return n; } function parseDays(days: number): boolean[] { // use (days || 0) to avoid null pointer exception // convert the base 10 integer into base 2 const d1 = (days || 0).toString(2); // split the string into an array // reverse it, concat it with Array(7).fill(0), reverse it again // this is just to zerofill the array from the left side const d2 = d1.split(&quot;&quot;).reverse().concat(Array(7).fill(0)).slice(0, 7).reverse(); // parse the values from strings to actual integers to boolean const d3 = d2.map(d =&gt; (parseInt(d, 10) ? true : false)); return d3; } // monday to friday serializeDays([true, true, true, true, true, false, false]); // outputs 124 parseDays(124); // outputs [true, true, true, true, true, false, false] <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Binary Math</h2>\n<p>Using string to do integer maths is very slow. You can use bitwise operators to encode and decode bit fields.</p>\n<h2>Encode bool array to int</h2>\n<p>The first function sets the low bit depending on the boolean. Each iteration the bits set are shifted to the left. The result is that the first array item is the highest bit (bit 7) and the last day is the lowest bit (bit 1)</p>\n<h2>Decode int to bool array</h2>\n<p>The second uses bitwise AND <code>&amp;</code> to mask out all but the bit position required and adds a boolean to an array depending on the state of the bit.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// high bit is first item in days eg 0b1000000 is day[0]\nfunction serializeDays(days) { \n return days.reduce((bin, day) =&gt; (bin &lt;&lt; 1) + (!!day), 0);\n} \n\nfunction parseDays(bitField) {\n var bit = 7, days = [];\n while (bit) { days.push((bitField &amp; (1 &lt;&lt; --bit)) !== 0) }\n return days;\n}\n \n \nconsole.log(serializeDays([true,false,true,false,true,false,true]).toString(2)); \nconsole.log(parseDays(0b1010101).join(\",\")); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:13:21.210", "Id": "498833", "Score": "0", "body": "Thank you for the feedback, the reason I didn't bitwise operators is because it's one of my weak points, since I don't have a strong (any actually) background in CS" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T16:52:59.297", "Id": "253048", "ParentId": "253044", "Score": "1" } }, { "body": "<p><strong>Unnecessary alternation</strong> You're using TypeScript, which is great - TypeScript will forbid calling functions with improperly typed parameters. That is, you don't have to worry about:</p>\n<pre><code>serializeDays();\n</code></pre>\n<p>because one parameter which is an array of booleans is <strong>required</strong>. The array will always exist, so:</p>\n<pre><code>// use (days || []) to avoid null pointer exception\n</code></pre>\n<p>isn't necessary - using <code>days</code> alone is sufficient. (This same thing applies to the <code>parseDays</code> argument)</p>\n<p><strong>Use meaningful variable names</strong> - <code>d1</code>, <code>d2</code>, and <code>d3</code> aren't as informative as they could be. Give them names that accurately represent what they contain, and (when it doesn't make things hard to read) reduce the number of declared variables and <em>chain</em> off of previous expressions instead (see below).</p>\n<p><strong>parseDays argument name</strong> is <code>days: number</code>. But <code>serializeDays</code> takes an argument of <code>days: boolean[]</code>. Consider using a different variable name, maybe <code>binaryDaysFromDB</code>.</p>\n<p><strong>Array construction</strong> can be done more concisely by creating an array of length 7, and then mapping it to 0 or 1 depending on <code>days[i]</code>. If the item exists, its boolean will be used; if the item doesn't exist, it'll be <code>undefined</code>, and <code>false</code> will be used.</p>\n<p>Since both <code>serializeDays</code> and <code>parseDays</code> require the construction of an array of length 7 which then gets filled based on its index, abstract that part into a function:</p>\n<pre><code>const makeArrOf7 = mapper =&gt; Array.from(\n { length: 7 },\n (_, i) =&gt; mapper(i)\n)\nfunction serializeDays(days: boolean[]) {\n const binaryDays = makeArrOf7(i =&gt; Number(days[i] || 0))\n .join('');\n return parseInt(binaryDays, 2);\n}\n</code></pre>\n<p>When turning a number from the database back into an array of booleans, reversing, filling, then reversing again isn't necessary. The logic being implemented is to change, eg, <code>'110'</code> into <code>[0, 0, 0, 0, 1, 1, 0]</code> - this can be achieved very easily by using <code>padStart</code> to pad the start of the string until it's length 7.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const makeArrOf7 = mapper =&gt; Array.from(\n { length: 7 },\n (_, i) =&gt; mapper(i)\n)\nfunction serializeDays(days) {\n const binaryDays = makeArrOf7(i =&gt; Number(days[i] || 0))\n .join('');\n return parseInt(binaryDays, 2);\n}\n\nfunction parseDays(binaryDaysFromDB) {\n const daysStr = binaryDaysFromDB\n .toString(2)\n .padStart(7, '0')\n .split('');\n return makeArrOf7(i =&gt; daysStr[i] === '1');\n}\n\nconsole.log(serializeDays([true, true, true, true, true, false, false])); // outputs 124\nconsole.log(parseDays(124).join(',')); // outputs [true, true, true, true, true, false, false]\n\nconsole.log(serializeDays([false, true, true]));\nconsole.log(parseDays(48).join(','));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<p>All that said:</p>\n<p><strong>This is a very strange thing to want to do</strong>. Why not just save the arrays directly, without any transformation? Unless you have a really good reason to save numbers instead of arrays, I'd prefer using the original arrays, they make a whole lot more sense, have no chance of bugs introduced via calculations, and require no additional code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:21:08.267", "Id": "498836", "Score": "0", "body": "Thank you for the great answer, I do agree with what you said, as for why I chose to do it this way: honestly I don't know why :p, I guess I felt it was cleaner this way ¯\\\\_(ツ)_/¯" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T16:55:35.800", "Id": "253049", "ParentId": "253044", "Score": "1" } } ]
{ "AcceptedAnswerId": "253049", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T15:27:06.220", "Id": "253044", "Score": "1", "Tags": [ "javascript", "typescript" ], "Title": "Convert boolean array to integer in Typescript" }
253044
<p>I'm getting started with React, so I took a React tutorial for creating a simple to-do list app.</p> <p>After finishing it, I read <a href="https://reactjs.org/docs/thinking-in-react.html" rel="nofollow noreferrer">&quot;Thinking in React&quot;</a>, and tried to improve what I did during tutorial based on that article.</p> <p>This is my original code from tutorial: package.json:</p> <pre><code>{ &quot;name&quot;: &quot;todo-initial&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;private&quot;: true, &quot;dependencies&quot;: { &quot;@testing-library/jest-dom&quot;: &quot;^5.11.6&quot;, &quot;@testing-library/react&quot;: &quot;^11.2.2&quot;, &quot;@testing-library/user-event&quot;: &quot;^12.2.2&quot;, &quot;nanoid&quot;: &quot;^3.1.18&quot;, &quot;prop-types&quot;: &quot;^15.7.2&quot;, &quot;react&quot;: &quot;^17.0.1&quot;, &quot;react-dom&quot;: &quot;^17.0.1&quot;, &quot;react-scripts&quot;: &quot;4.0.1&quot;, &quot;web-vitals&quot;: &quot;^0.2.4&quot; }, &quot;scripts&quot;: { &quot;start&quot;: &quot;react-scripts start&quot;, &quot;build&quot;: &quot;react-scripts build&quot;, &quot;test&quot;: &quot;react-scripts test&quot;, &quot;eject&quot;: &quot;react-scripts eject&quot; }, &quot;eslintConfig&quot;: { &quot;extends&quot;: [ &quot;react-app&quot;, &quot;react-app/jest&quot; ] }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot; ], &quot;development&quot;: [ &quot;last 1 chrome version&quot;, &quot;last 1 firefox version&quot;, &quot;last 1 safari version&quot; ] }, &quot;devDependencies&quot;: { &quot;babel-eslint&quot;: &quot;^10.1.0&quot;, &quot;eslint-config-airbnb&quot;: &quot;^18.2.1&quot;, &quot;eslint-plugin-import&quot;: &quot;^2.22.1&quot;, &quot;eslint-plugin-jsx-a11y&quot;: &quot;^6.4.1&quot;, &quot;eslint-plugin-react&quot;: &quot;^7.21.5&quot;, &quot;eslint-plugin-react-hooks&quot;: &quot;^4.0.0&quot; }, &quot;keywords&quot;: [], &quot;description&quot;: &quot;&quot; } </code></pre> <p>usePrevious.js:</p> <pre><code>import { useEffect, useRef } from &quot;react&quot;; export default function usePrevious(value) { const ref = useRef(); useEffect(() =&gt; { ref.current = value; }); return ref.current; } </code></pre> <p>index.js:</p> <pre><code>import React from &quot;react&quot;; import ReactDOM from &quot;react-dom&quot;; import &quot;./index.css&quot;; import App from &quot;./App&quot;; const DATA = [ { id: &quot;todo-0&quot;, name: &quot;Eat&quot;, completed: true }, { id: &quot;todo-1&quot;, name: &quot;Sleep&quot;, completed: false }, { id: &quot;todo-2&quot;, name: &quot;Repeat&quot;, completed: false } ]; ReactDOM.render( &lt;React.StrictMode&gt; &lt;App tasks={DATA} /&gt; &lt;/React.StrictMode&gt;, document.querySelector(&quot;#root&quot;) ); </code></pre> <p>index.css:</p> <pre><code>body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, &quot;Roboto&quot;, &quot;Oxygen&quot;, &quot;Ubuntu&quot;, &quot;Cantarell&quot;, &quot;Fira Sans&quot;, &quot;Droid Sans&quot;, &quot;Helvetica Neue&quot;, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; } /* RESETS */ *, *::before, *::after { box-sizing: border-box; } *:focus { outline: 3px dashed #228bec; } html { font: 62.5% / 1.15 sans-serif; } h1, h2 { margin-bottom: 0; } ul { list-style: none; padding: 0; } button { border: none; margin: 0; padding: 0; width: auto; overflow: visible; background: transparent; color: inherit; font: inherit; line-height: normal; -webkit-font-smoothing: inherit; -moz-osx-font-smoothing: inherit; -webkit-appearance: none; } button::-moz-focus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } input[type=&quot;text&quot;] { border-radius: 0; } body { width: 100%; max-width: 68rem; margin: 0 auto; font: 1.6rem/1.25 Arial, sans-serif; background-color: #f5f5f5; color: #4d4d4d; } @media screen and (min-width: 620px) { body { font-size: 1.9rem; line-height: 1.31579; } } /*END RESETS*/ /* GLOBAL STYLES */ .form-group &gt; input[type=&quot;text&quot;] { display: inline-block; margin-top: 0.4rem; } .btn { padding: 0.8rem 1rem 0.7rem; border: 0.2rem solid #4d4d4d; cursor: pointer; text-transform: capitalize; } .btn.toggle-btn { border-width: 1px; border-color: #d3d3d3; } .btn.toggle-btn[aria-pressed=&quot;true&quot;] { text-decoration: underline; border-color: #4d4d4d; } .btn__danger { color: #fff; background-color: #ca3c3c; border-color: #bd2130; } .btn__filter { border-color: lightgrey; } .btn__primary { color: #fff; background-color: #000; } .btn-group { display: flex; justify-content: space-between; } .btn-group &gt; * { flex: 1 1 49%; } .btn-group &gt; * + * { margin-left: 0.8rem; } .label-wrapper { margin: 0; flex: 0 0 100%; text-align: center; } .visually-hidden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); white-space: nowrap; } [class*=&quot;stack&quot;] &gt; * { margin-top: 0; margin-bottom: 0; } .stack-small &gt; * + * { margin-top: 1.25rem; } .stack-large &gt; * + * { margin-top: 2.5rem; } @media screen and (min-width: 550px) { .stack-small &gt; * + * { margin-top: 1.4rem; } .stack-large &gt; * + * { margin-top: 2.8rem; } } .stack-exception { margin-top: 1.2rem; } /* END GLOBAL STYLES */ .todoapp { background: #fff; margin: 2rem 0 4rem 0; padding: 1rem; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 2.5rem 5rem 0 rgba(0, 0, 0, 0.1); } @media screen and (min-width: 550px) { .todoapp { padding: 4rem; } } .todoapp &gt; * { max-width: 50rem; margin-left: auto; margin-right: auto; } .todoapp &gt; form { max-width: 100%; } .todoapp &gt; h1 { display: block; max-width: 100%; text-align: center; margin: 0; margin-bottom: 1rem; } .label__lg { line-height: 1.01567; font-weight: 300; padding: 0.8rem; margin-bottom: 1rem; text-align: center; } .input__lg { padding: 2rem; border: 2px solid #000; } .input__lg:focus { border-color: #4d4d4d; box-shadow: inset 0 0 0 2px; } [class*=&quot;__lg&quot;] { display: inline-block; width: 100%; font-size: 1.9rem; } [class*=&quot;__lg&quot;]:not(:last-child) { margin-bottom: 1rem; } @media screen and (min-width: 620px) { [class*=&quot;__lg&quot;] { font-size: 2.4rem; } } .filters { width: 100%; margin: unset auto; } /* Todo item styles */ .todo { display: flex; flex-direction: row; flex-wrap: wrap; } .todo &gt; * { flex: 0 0 100%; } .todo-text { width: 100%; min-height: 4.4rem; padding: 0.4rem 0.8rem; border: 2px solid #565656; } .todo-text:focus { box-shadow: inset 0 0 0 2px; } /* CHECKBOX STYLES */ .c-cb { box-sizing: border-box; font-family: Arial, sans-serif; -webkit-font-smoothing: antialiased; font-weight: 400; font-size: 1.6rem; line-height: 1.25; display: block; position: relative; min-height: 44px; padding-left: 40px; clear: left; } .c-cb &gt; label::before, .c-cb &gt; input[type=&quot;checkbox&quot;] { box-sizing: border-box; top: -2px; left: -2px; width: 44px; height: 44px; } .c-cb &gt; input[type=&quot;checkbox&quot;] { -webkit-font-smoothing: antialiased; cursor: pointer; position: absolute; z-index: 1; margin: 0; opacity: 0; } .c-cb &gt; label { font-size: inherit; font-family: inherit; line-height: inherit; display: inline-block; margin-bottom: 0; padding: 8px 15px 5px; cursor: pointer; touch-action: manipulation; } .c-cb &gt; label::before { content: &quot;&quot;; position: absolute; border: 2px solid currentColor; background: transparent; } .c-cb &gt; input[type=&quot;checkbox&quot;]:focus + label::before { border-width: 4px; outline: 3px dashed #228bec; } .c-cb &gt; label::after { box-sizing: content-box; content: &quot;&quot;; position: absolute; top: 11px; left: 9px; width: 18px; height: 7px; transform: rotate(-45deg); border: solid; border-width: 0 0 5px 5px; border-top-color: transparent; opacity: 0; background: transparent; } .c-cb &gt; input[type=&quot;checkbox&quot;]:checked + label::after { opacity: 1; } </code></pre> <p>App.js:</p> <pre><code>import PropTypes from &quot;prop-types&quot;; import React, { useEffect, useRef, useState } from &quot;react&quot;; import { nanoid } from &quot;nanoid&quot;; import usePrevious from &quot;./usePrevious&quot;; import Todo from &quot;./components/Todo&quot;; import Form from &quot;./components/Form&quot;; import FilterButton from &quot;./components/FilterButton&quot;; const FILTER_MAP = { All: () =&gt; true, Active: (task) =&gt; !task.completed, Completed: (task) =&gt; task.completed }; const FILTER_NAMES = Object.keys(FILTER_MAP); function App({ tasks }) { const [currentTasks, setTasks] = useState(tasks); const [filter, setFilter] = useState(&quot;All&quot;); const headingRef = useRef(null); const taskLength = usePrevious(currentTasks.length); const toggleTaskCompleted = (id) =&gt; { const updatedTasks = [...currentTasks]; const toggledTask = updatedTasks.find((task) =&gt; task.id === id); toggledTask.completed = !toggledTask.completed; setTasks(updatedTasks); }; const deleteTodo = (id) =&gt; { setTasks(currentTasks.filter((task) =&gt; task.id !== id)); }; const editTodo = (id, newName) =&gt; { const updatedTasks = [...currentTasks]; const changedTask = updatedTasks.find((task) =&gt; task.id === id); changedTask.name = newName; setTasks(updatedTasks); }; const updateFilter = (filterName) =&gt; { setFilter(filterName); }; const taskList = currentTasks .filter(FILTER_MAP[filter]) .map((task) =&gt; ( &lt;Todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggleCompleted={toggleTaskCompleted} deleteTodo={deleteTodo} editTodo={editTodo} /&gt; )); const filterList = FILTER_NAMES.map((name) =&gt; ( &lt;FilterButton key={name} text={name} setFilter={updateFilter} isPressed={name === filter} /&gt; )); const addTask = (name) =&gt; { const newTask = { id: `todo-${nanoid()}`, name, completed: false }; setTasks((storedTasks) =&gt; [...storedTasks, newTask]); }; const tasksNoun = taskList.length === 1 ? &quot;task&quot; : &quot;tasks&quot;; const headingText = `${taskList.length} ${tasksNoun} remaining`; useEffect(() =&gt; { if (currentTasks.length - taskLength === -1) { headingRef.current.focus(); } }, [currentTasks.length, taskLength]); return ( &lt;div className=&quot;todoapp stack-large&quot;&gt; &lt;h1&gt;TodoMatic&lt;/h1&gt; &lt;Form addTask={addTask} /&gt; &lt;div className=&quot;filters btn-group stack-exception&quot;&gt; {filterList} &lt;/div&gt; &lt;h2 id=&quot;list-heading&quot; tabIndex=&quot;-1&quot; ref={headingRef}&gt; {headingText} &lt;/h2&gt; {/* eslint-disable-next-line jsx-a11y/no-redundant-roles */} &lt;ul role=&quot;list&quot; className=&quot;todo-list stack-large stack-exception&quot; aria-labelledby=&quot;list-heading&quot; &gt; {taskList} &lt;/ul&gt; &lt;/div&gt; ); } App.propTypes = { tasks: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, completed: PropTypes.bool }) ).isRequired }; export default App; </code></pre> <p>components/FilterButton.js</p> <pre><code>import PropTypes from &quot;prop-types&quot;; import React from &quot;react&quot;; export default function FilterButton({ text, setFilter, isPressed = false }) { return ( &lt;button type=&quot;button&quot; className=&quot;btn toggle-btn&quot; aria-pressed={isPressed} onClick={() =&gt; setFilter(text)} &gt; &lt;span className=&quot;visually-hidden&quot;&gt;Show &lt;/span&gt; &lt;span&gt;{text}&lt;/span&gt; &lt;span className=&quot;visually-hidden&quot;&gt; tasks&lt;/span&gt; &lt;/button&gt; ); } FilterButton.propTypes = { text: PropTypes.string.isRequired, setFilter: PropTypes.func.isRequired, isPressed: PropTypes.bool }; </code></pre> <p>components/Form.js:</p> <pre><code>/* eslint-disable jsx-a11y/label-has-associated-control */ import PropTypes from &quot;prop-types&quot;; import React, { useState } from &quot;react&quot;; export default function Form({ addTask }) { const [name, setName] = useState(&quot;&quot;); const handleSubmit = (e) =&gt; { e.preventDefault(); if (name === &quot;&quot;) return; addTask(name); setName(&quot;&quot;); }; const handleChange = (e) =&gt; { setName(e.target.value); }; return ( &lt;form onSubmit={handleSubmit}&gt; &lt;h2 className=&quot;label-wrapper&quot;&gt; &lt;label htmlFor=&quot;new-todo-input&quot; className=&quot;label__lg&quot;&gt; What needs to be done? &lt;/label&gt; &lt;/h2&gt; &lt;input type=&quot;text&quot; id=&quot;new-todo-input&quot; className=&quot;input input__lg&quot; name=&quot;text&quot; autoComplete=&quot;off&quot; value={name} onChange={handleChange} /&gt; &lt;button type=&quot;submit&quot; className=&quot;btn btn__primary btn__lg&quot;&gt; Add &lt;/button&gt; &lt;/form&gt; ); } Form.propTypes = { addTask: PropTypes.func }; </code></pre> <p>components/Todo.js:</p> <pre><code>import React, { useEffect, useRef, useState } from &quot;react&quot;; import PropTypes from &quot;prop-types&quot;; import usePrevious from &quot;../usePrevious&quot;; export default function Todo({ name, id, toggleCompleted, deleteTodo, editTodo, completed = false }) { const [isEditing, setEditing] = useState(false); const [newName, setNewName] = useState(&quot;&quot;); const editFieldRef = useRef(null); const editButtonRef = useRef(null); const wasEditing = usePrevious(isEditing); const handleChange = (e) =&gt; { setNewName(e.target.value); }; const handleSubmit = (e) =&gt; { e.preventDefault(); if (!newName.trim()) { return; } editTodo(id, newName); setNewName(&quot;&quot;); setEditing(false); }; const editTemplate = ( &lt;form className=&quot;stack-small&quot; onSubmit={handleSubmit}&gt; &lt;div className=&quot;form-group&quot;&gt; &lt;label className=&quot;todo-label&quot; htmlFor={id}&gt; New name for {name} &lt;/label&gt; &lt;input id={id} className=&quot;todo-text&quot; type=&quot;text&quot; name={newName} onChange={handleChange} ref={editFieldRef} /&gt; &lt;/div&gt; &lt;div className=&quot;btn-group&quot;&gt; &lt;button type=&quot;button&quot; className=&quot;btn todo-cancel&quot; onClick={() =&gt; setEditing(false)} &gt; Cancel &lt;span className=&quot;visually-hidden&quot;&gt;renaming {name}&lt;/span&gt; &lt;/button&gt; &lt;button type=&quot;submit&quot; className=&quot;btn btn__primary todo-edit&quot;&gt; Save &lt;span className=&quot;visually-hidden&quot;&gt;new name for {name}&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;/form&gt; ); const viewTemplate = ( &lt;li className=&quot;todo stack-small&quot;&gt; &lt;div className=&quot;c-cb&quot;&gt; &lt;input id={id} type=&quot;checkbox&quot; defaultChecked={completed} onChange={() =&gt; toggleCompleted(id)} /&gt; &lt;label className=&quot;todo-label&quot; htmlFor={id}&gt; {name} &lt;/label&gt; &lt;/div&gt; &lt;div className=&quot;btn-group&quot;&gt; &lt;button type=&quot;button&quot; className=&quot;btn&quot; onClick={() =&gt; setEditing(true)} ref={editButtonRef} &gt; Edit &lt;span className=&quot;visually-hidden&quot;&gt;{name}&lt;/span&gt; &lt;/button&gt; &lt;button type=&quot;button&quot; className=&quot;btn btn__danger&quot; onClick={() =&gt; deleteTodo(id)} &gt; Delete &lt;span className=&quot;visually-hidden&quot;&gt;{name}&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;/li&gt; ); useEffect(() =&gt; { if (!wasEditing &amp;&amp; isEditing) { editFieldRef.current.focus(); } else if (wasEditing &amp;&amp; !isEditing) { editButtonRef.current.focus(); } }, [wasEditing, isEditing]); return ( &lt;div className=&quot;todo&quot;&gt;{isEditing ? editTemplate : viewTemplate}&lt;/div&gt; ); } Todo.propTypes = { name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, toggleCompleted: PropTypes.func, deleteTodo: PropTypes.func, editTodo: PropTypes.func, completed: PropTypes.bool }; </code></pre> <p>And this is the code refactored by me (only updated/added files): App.js</p> <pre><code>import PropTypes from &quot;prop-types&quot;; import React, { useState } from &quot;react&quot;; import { nanoid } from &quot;nanoid&quot;; import Form from &quot;./components/Form&quot;; import TaskTable from &quot;./components/TaskTable&quot;; function App({ tasks }) { const [currentTasks, setTasks] = useState(tasks); const toggleTaskCompleted = (id) =&gt; { setTasks((prevTasks) =&gt; { const toggledTask = prevTasks.find((task) =&gt; task.id === id); toggledTask.completed = !toggledTask.completed; return [...prevTasks]; }); }; const deleteTodo = (id) =&gt; { setTasks(currentTasks.filter((task) =&gt; task.id !== id)); }; const editTodo = (id, newName) =&gt; { setTasks((prevTasks) =&gt; { const toggledTask = prevTasks.find((task) =&gt; task.id === id); toggledTask.name = newName; return [...prevTasks]; }); }; const addTask = (name) =&gt; { const newTask = { id: `todo-${nanoid()}`, name, completed: false }; setTasks((storedTasks) =&gt; [...storedTasks, newTask]); }; return ( &lt;div className=&quot;todoapp stack-large&quot;&gt; &lt;h1&gt;TodoMatic&lt;/h1&gt; &lt;Form addTask={addTask} /&gt; &lt;TaskTable tasks={currentTasks} toggleCompleted={toggleTaskCompleted} editTodo={editTodo} deleteTodo={deleteTodo} /&gt; &lt;/div&gt; ); } App.propTypes = { tasks: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, completed: PropTypes.bool }) ).isRequired }; export default App; </code></pre> <p>components/Form.js:</p> <pre><code>/* eslint-disable jsx-a11y/label-has-associated-control */ import PropTypes from &quot;prop-types&quot;; import React from &quot;react&quot;; class Form extends React.Component { constructor(props) { super(props); this.state = { name: &quot;&quot; }; } handleSubmit = (e) =&gt; { e.preventDefault(); const { name } = this.state; const { addTask } = this.props; if (name === &quot;&quot;) return; addTask(name); this.setState({ name: &quot;&quot; }); }; handleChange = (e) =&gt; { this.setState({ name: e.target.value }); }; render() { const { name } = this.state; return ( &lt;form onSubmit={this.handleSubmit}&gt; &lt;h2 className=&quot;label-wrapper&quot;&gt; &lt;label htmlFor=&quot;new-todo-input&quot; className=&quot;label__lg&quot;&gt; What needs to be done? &lt;/label&gt; &lt;/h2&gt; &lt;input type=&quot;text&quot; id=&quot;new-todo-input&quot; className=&quot;input input__lg&quot; name=&quot;text&quot; autoComplete=&quot;off&quot; value={name} onChange={this.handleChange} /&gt; &lt;button type=&quot;submit&quot; className=&quot;btn btn__primary btn__lg&quot;&gt; Add &lt;/button&gt; &lt;/form&gt; ); } } Form.propTypes = { addTask: PropTypes.func }; export default Form; </code></pre> <p>components/FilterBar.js:</p> <pre><code>import React from &quot;react&quot;; import PropTypes from &quot;prop-types&quot;; import FilterButton from &quot;./FilterButton&quot;; export const FILTER_MAP = { All: () =&gt; true, Active: (task) =&gt; !task.completed, Completed: (task) =&gt; task.completed }; const FILTER_NAMES = Object.keys(FILTER_MAP); class FilterBar extends React.Component { constructor(props) { super(props); this.state = { activeFilter: &quot;All&quot; }; } updateFilter = (filterName) =&gt; { this.setState({ activeFilter: filterName }); }; render() { const { activeFilter } = this.state; const { updateFilter } = this.props; const filterList = FILTER_NAMES.map((name) =&gt; ( &lt;FilterButton key={name} text={name} setFilter={() =&gt; { this.updateFilter(name); updateFilter(name); }} isPressed={name === activeFilter} /&gt; )); return ( &lt;div className=&quot;filters btn-group stack-exception&quot;&gt; {filterList} &lt;/div&gt; ); } } FilterBar.propTypes = { updateFilter: PropTypes.func.isRequired }; export default FilterBar; </code></pre> <p>components/TaskList.js:</p> <pre><code>import PropTypes from &quot;prop-types&quot;; import React, { useRef } from &quot;react&quot;; import Todo from &quot;./Todo&quot;; export default function TaskList({ tasks, toggleCompleted, editTodo, deleteTodo }) { const headingRef = useRef(null); const taskList = tasks.map((task) =&gt; ( &lt;Todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggleCompleted={toggleCompleted} editTodo={editTodo} deleteTodo={(...args) =&gt; { deleteTodo(...args); headingRef.current.focus(); }} /&gt; )); const tasksNoun = taskList.length === 1 ? &quot;task&quot; : &quot;tasks&quot;; const headingText = `${taskList.length} ${tasksNoun} remaining`; return ( &lt;div&gt; &lt;h2 id=&quot;list-heading&quot; tabIndex=&quot;-1&quot; ref={headingRef}&gt; {headingText} &lt;/h2&gt; {/* eslint-disable-next-line jsx-a11y/no-redundant-roles */} &lt;ul role=&quot;list&quot; className=&quot;todo-list stack-large stack-exception&quot; aria-labelledby=&quot;list-heading&quot; &gt; {taskList} &lt;/ul&gt; &lt;/div&gt; ); } TaskList.propTypes = { tasks: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, completed: PropTypes.bool }) ).isRequired, toggleCompleted: PropTypes.func.isRequired, editTodo: PropTypes.func.isRequired, deleteTodo: PropTypes.func.isRequired }; </code></pre> <p>components/TaskTable.js:</p> <pre><code>import PropTypes from &quot;prop-types&quot;; import React from &quot;react&quot;; import TaskList from &quot;./TaskList&quot;; import FilterBar, { FILTER_MAP } from &quot;./FilterBar&quot;; class TaskTable extends React.Component { constructor(props) { super(props); this.state = { filter: &quot;All&quot; }; } updateFilter = (newFilter) =&gt; { this.setState({ filter: newFilter }); }; render() { const { filter } = this.state; const { tasks, toggleCompleted, editTodo, deleteTodo } = this.props; const filteredTasks = tasks.filter(FILTER_MAP[filter]); return ( &lt;div&gt; &lt;FilterBar filter={filter} updateFilter={this.updateFilter} /&gt; &lt;TaskList tasks={filteredTasks} filter={filter} toggleCompleted={toggleCompleted} editTodo={editTodo} deleteTodo={deleteTodo} /&gt; &lt;/div&gt; ); } } TaskTable.propTypes = { tasks: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, completed: PropTypes.bool }) ).isRequired, toggleCompleted: PropTypes.func.isRequired, editTodo: PropTypes.func.isRequired, deleteTodo: PropTypes.func.isRequired }; export default TaskTable; </code></pre> <p>I would like to get feedback on how I improved the code, and whether I can improve it further (i.e. to make it more React-way, etc.).</p> <p>Also, I have a question, how should I correctly manage the <code>tasks</code> passed to <code>App</code> as <code>props</code>, which then becomes <code>state</code> in <code>App</code>?</p> <p>Thanks in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:32:21.407", "Id": "498854", "Score": "1", "body": "Quick comment: you switch between class-based components, functional components, and components defined as arrow functions all over the place. Some take props, some take arguments. I would pick a style and stick with it. Maybe two if you want to show `function F(props)` is an exported component and `F = (props) => {}` is used inside a file or something. And they should always accept `props` unlike `FilterButton`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:53:03.857", "Id": "498875", "Score": "0", "body": "should i switch back to functional components?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:54:23.883", "Id": "498877", "Score": "1", "body": "I think the trend is toward functional components with React but you don't have to. Consistency is more important than which particular you choose which is true for a lot of stylistic choices" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:55:20.963", "Id": "498878", "Score": "0", "body": "okay got it, also what do you mean by components defined with arrow functions? which one? and why not destructure right in the argument? of course when i switch back to functional components" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:02:17.650", "Id": "498881", "Score": "0", "body": "Arrow functions are any defined `f = () => {...}` vs the standard `f() {...}`. On second look none of your components specifically use arrow functions but the overall use between which style you use in your code is inconsistent. Again, it's not like any one way is wrong (except for components not accepting `props` which is required to be a valid component per https://reactjs.org/docs/components-and-props.html), just it's harder to follow when they change all the time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:05:35.520", "Id": "498883", "Score": "0", "body": "okay i see, thanks for your comments, I'll consider them." } ]
[ { "body": "<p>The code you've got looks pretty good :), it's very readable and easy to understand what's going on. I'll points out a handful of suggestions, some of which you might you might decide you don't like as much and prefer to ignore.</p>\n<p><strong>App.js</strong></p>\n<p>To address your concern of passing in props then turning it into state, what you are doing is perfectly fine. However, I might renamed the &quot;tasks&quot; being passed in too &quot;initialTasks&quot;, to make it more clear that that's just the starting value.</p>\n<p>Try to make your function naming a little more consistent. you have both &quot;addTask()&quot; and &quot;deleteTodo()&quot; - pick either &quot;task&quot; or &quot;todo&quot; and stick with it.</p>\n<p>All of those functions revolve around updating the same bit of state. This makes a good candidate for using useReducer() instead of useState(). Here's an example of what that might look like:</p>\n<pre><code>function reducer(tasks, action) {\n const updateTask = (id, update) =&gt; (\n tasks.map((task) =&gt; task.id === id ? update(task) : task)\n );\n\n switch (action.type) {\n case &quot;TOGGLE_TASK_COMPLETED&quot;:\n return updateTask(action.id, (task) =&gt; ({...task, completed: !task.completed}));\n \n case &quot;DELETE_TASK&quot;:\n return tasks.filter((task) =&gt; task.id !== action.id);\n \n case &quot;EDIT_TASK&quot;:\n return updateTask(action.id, (task) =&gt; ({...task, name: action.newName}));\n \n case &quot;ADD_TASK&quot;:\n const newTask = { id: `todo-${nanoid()}`, name: action.name, completed: false };\n return [...tasks, newTask];\n \n default:\n throw new Error();\n }\n}\n\nfunction App({ initialTasks }) {\n const [tasks, dispatch] = useReducer(reducer, initialTasks);\n const modifyTodos = {\n add: (name) =&gt; dispatch({ type: &quot;ADD_TASK&quot;, name }),\n toggleCompleted: (id) =&gt; dispatch({ type: &quot;TOGGLE_TASK_COMPLETED&quot;, id }),\n edit: (id, newName) =&gt; dispatch({ type: &quot;EDIT_TASK&quot;, id, newName }),\n delete: (id) =&gt; dispatch({ type: &quot;DELETE_TASK&quot;, id }),\n };\n\n return (\n &lt;div className=&quot;todoapp stack-large&quot;&gt;\n &lt;h1&gt;TodoMatic&lt;/h1&gt;\n &lt;Form addTask={modifyTodos.add} /&gt;\n &lt;TaskTable tasks={tasks} modifyTodos={modifyTodos} /&gt;\n &lt;/div&gt;\n );\n}\n</code></pre>\n<p>In the above code example, I also bundled together the task modifier functions into one object to make it easier to pass around. It would be equally valid to just pass the dispatch function down and not make these lightweight wrapper functions, or to keep them all separate as you had it before, if you find it easier to understand when props are more explicit.</p>\n<p><strong>Form.js</strong></p>\n<p>It's been a common practice among the popular Javascript frameworks (angular, react, or vue) to have one component per file. This has been a useful practice that really helps with code organization. It's akin to having one class per file in java. But with the recent addition of react hooks, which empower functional components, there's some additional power to harness that's unique to React. There's some great potential that we miss out on if we keep trying to structure projects with a single medium-sized component per file. If we instead changed this rule to &quot;one well-defined exported component per file&quot;, we are then free to make all sorts of smaller helper components that can aid us in defining the component we wish to export - akin to having multiple helper functions in a single file.</p>\n<p>Here's a version of Form.js that I've broken up into lots of little components</p>\n<pre><code>/* eslint-disable jsx-a11y/label-has-associated-control */\nimport PropTypes from &quot;prop-types&quot;;\nimport React, { useState } from &quot;react&quot;;\n\nfunction Form({ addTask }) {\n const [name, setName] = useState(&quot;&quot;);\n\n const handleSubmit = e =&gt; {\n e.preventDefault();\n if (name === &quot;&quot;) return;\n addTask(name);\n setName(&quot;&quot;);\n };\n\n return (\n &lt;Container onFormSubmit={handleSubmit}&gt;\n &lt;Heading&gt;What needs to be done?&lt;/Heading&gt;\n &lt;TaskBox name={name} setName={setName} /&gt;\n &lt;SubmitButton /&gt;\n &lt;/Container&gt;\n );\n}\n\nconst Container = ({ children, onFormSubmit }) =&gt; (\n &lt;form onSubmit={onFormSubmit}&gt;{children}&lt;/form&gt;\n);\n\nconst Heading = ({ children }) =&gt; (\n &lt;h2 className=&quot;label-wrapper&quot;&gt;\n &lt;label htmlFor=&quot;new-todo-input&quot; className=&quot;label__lg&quot;&gt;\n {children}\n &lt;/label&gt;\n &lt;/h2&gt;\n);\n\nfunction TaskBox({ name, setName }) {\n const handleChange = (e) =&gt; setName(e.target.value);\n return (\n &lt;input\n type=&quot;text&quot;\n id=&quot;new-todo-input&quot;\n className=&quot;input input__lg&quot;\n name=&quot;text&quot;\n autoComplete=&quot;off&quot;\n value={name}\n onChange={handleChange}\n /&gt;\n );\n}\n\nconst SubmitButton = () =&gt; (\n &lt;button type=&quot;submit&quot; className=&quot;btn btn__primary btn__lg&quot;&gt;\n Add\n &lt;/button&gt;\n)\n\nForm.propTypes = {\n addTask: PropTypes.func\n};\n\nexport default Form;\n</code></pre>\n<p>Extracting out these helper components makes the main exported component a much higher-level component - it turns this component into an overview of what this module does, then invites the code reader to look into one of the helper components if they want more specific details of how a particular piece functions.</p>\n<p>Also notice that I'm only attaching propTypes to the exported Form component - this is the component that needs to be well-defined - this is the external API. Attaching prop-types to each helper component would just get tedious and get in the way.</p>\n<p><strong>Todo.js</strong></p>\n<p>Here's another example of a file that would do well to be split up a little. Especially with your editTemplate and viewTemplate variables - those are already almost stand-alone component, the only thing they're missing is to be wrapped in a function and receive their props explicitly.</p>\n<p><strong>index.css</strong></p>\n<p>It looks like you've got a good naming scheme going on in there to prevent class-name clashes, so good job there. Having all of your styles in one file won't scale very well though, so I would recommend creating a stylesheet for each component, and have each component import their own style sheet.</p>\n<p><strong>Final Thoughts</strong></p>\n<p>While I didn't go into detail about all of your modules, I hope the ones I did talk about can give you some ideas of where you might take your code next. Overall, this is some great code, it's easy to follow and understand. it seems you're really understanding how to code the react way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T16:54:46.990", "Id": "500931", "Score": "0", "body": "thanks for the comments, i find all of them helpful. i changed most of them. i didn't use reducer because it was kind sophisticated for me, i'll consider it when i dig deeper into react, and will get back to this code then.\nw.r.t. splitting into smaller components - is this a emerging trend?\nw.r.t. editTemplate and viewTemplate, i tried to split them into components, but how do i deal with state that's common for both? (e.g. setEditing)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T17:07:39.843", "Id": "500933", "Score": "1", "body": "The well-defined exported component that uses the editTemplate and viewTemplate components can create the state and pass down the state value and setState function the its children that needs it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T17:14:49.177", "Id": "500935", "Score": "1", "body": "Smaller functions have always been preferred over larger functions. With the power to define all React components as functions, it's almost a natural thing to sub-divide the logic into smaller functions. Even when using class-based components, I would sometimes make helper-render functions. The particular idea I mentioned above of having one well-defined exported component per file is just something I sometimes use. In larger projects I do things a little different. I haven't seen any emerging trend regarding project structure, so figure out what works for you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T17:10:14.333", "Id": "501009", "Score": "0", "body": "okay, got it. so i separated two components for each edit and view templates. in my Todo component i have `editFieldRef` and `editButtonRef`refs which are passed to each of view and edit components, and initialized there. since i use the refs in `useEffect()` in Todo component, i get `Cannot read property 'focus' of null` for the refs. what's wrong here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:06:34.917", "Id": "501011", "Score": "0", "body": "Did you pass them down under the name \"ref\" - you can't name a prop \"ref\" as it has special meaning. You can either name it anything else, or do \"ref forwarding\" as described here: https://reactjs.org/docs/forwarding-refs.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T17:38:43.640", "Id": "501197", "Score": "1", "body": "oops, sorry, i hadn't passed the refs as prop. it works now." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T06:30:41.073", "Id": "253693", "ParentId": "253046", "Score": "0" } } ]
{ "AcceptedAnswerId": "253693", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T16:01:50.007", "Id": "253046", "Score": "2", "Tags": [ "javascript", "react.js", "to-do-list" ], "Title": "Simple to-do list application in React" }
253046
<p>I was wondering if someone could review my object oriented design for my Noughts &amp; Crosses program. Yesterday I <a href="https://codereview.stackexchange.com/q/252992/120114">posted a procedural version</a> and now I've done an OOP version.</p> <p>Can someone tell me what I've done well, what I haven't done well, and provide any suggestions on how I can improve this program? I included inheritance to practice with dynamic polymorphism. I haven't done error checking so treat my program how it's supposed to be entered.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;utility&gt; #include &lt;algorithm&gt; bool ClaimSquare(std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;&amp; grid, int move, const unsigned char player) { for (auto&amp; vec : grid) { auto validSquare = std::find_if(vec.begin(), vec.end(), [&amp;](auto pair) { return pair.first == move; }); if (validSquare != vec.end()) { if (validSquare-&gt;second == '-') { validSquare-&gt;second = player; return true; } else { std::cout &lt;&lt; &quot;This square has already been claimed. Choose a different square!&quot; &lt;&lt; std::endl; return false; } } } } void Displaygrid(const std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;&amp; grid) { for (auto const&amp; row : grid) { for (auto const&amp; cell : row) { if (cell.second != '-') { std::cout &lt;&lt; cell.second &lt;&lt; &quot; &quot;; } else { std::cout &lt;&lt; cell.first &lt;&lt; &quot; &quot;; } } std::cout &lt;&lt; &quot;\n\n&quot;; } } class Player { private: protected: std::string m_type; unsigned char m_name; public: std::string GetType() { return m_type; } Player(unsigned char name, std::string&amp;&amp; type = &quot;Player&quot;) :m_name(name),m_type(type) {} virtual ~Player() = default; virtual unsigned char GetName() { return m_name; } }; class Human : public Player { public: Human(unsigned char name) :Player(name, &quot;Human&quot;) {} std::string GetType() { return m_type; } }; class Robot : public Player { public: Robot(unsigned char name) :Player(name, &quot;Robot&quot;){} std::string GetType() { return m_type; } }; class Game { private: std::vector&lt;Player*&gt; m_p; public: Game(Player *p1, Player*p2) { m_p.push_back(p1); m_p.push_back(p2); } //Does anyone know if there's a better way of checking for winner? bool CheckForAWinner(std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;&amp; m_board, const unsigned char key) { if (m_board.at(0).at(1) == key &amp;&amp; m_board.at(0).at(2) == key &amp;&amp; m_board.at(0).at(3) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(1).at(4) == key &amp;&amp; m_board.at(1).at(5) == key &amp;&amp; m_board.at(1).at(6) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(2).at(7) == key &amp;&amp; m_board.at(2).at(8) == key &amp;&amp; m_board.at(2).at(9) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(0).at(1) == key &amp;&amp; m_board.at(1).at(4) == key &amp;&amp; m_board.at(2).at(7) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(0).at(2) == key &amp;&amp; m_board.at(1).at(5) == key &amp;&amp; m_board.at(2).at(8) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(0).at(3) == key &amp;&amp; m_board.at(1).at(6) == key &amp;&amp; m_board.at(2).at(9) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(0).at(1) == key &amp;&amp; m_board.at(1).at(5) == key &amp;&amp; m_board.at(2).at(9) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else if (m_board.at(2).at(7) == key &amp;&amp; m_board.at(1).at(5) == key &amp;&amp; m_board.at(0).at(3) == key) { std::cout &lt;&lt; key &lt;&lt; &quot; is the winner&quot; &lt;&lt; std::endl; return true; } else { return false; } } void play(std::vector&lt;std::map&lt;int, unsigned char&gt;&gt; &amp;board) { int currentPlayer = 1; Player *ref = nullptr; do { int move = 0; currentPlayer = (currentPlayer + 1) % 2; do { Displaygrid(board); std::cout &lt;&lt; m_p.at(currentPlayer)-&gt;GetType() &lt;&lt; &quot;: &quot; &lt;&lt; m_p.at(currentPlayer)-&gt;GetName() &lt;&lt; &quot; turn: &quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Enter a number on the grid (e.g. 1): &quot;; std::cin &gt;&gt; move; } while (ClaimSquare(board, move, m_p.at(currentPlayer)-&gt;GetName()) == false); } while (CheckForAWinner(board,m_p.at(currentPlayer)-&gt;GetName()) == false); } }; int main() { std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;grid = { {std::make_pair(1, '-'), std::make_pair(2, '-'), std::make_pair(3, '-') }, { std::make_pair(4,'-'), std::make_pair(5,'-'), std::make_pair(6,'-') }, { std::make_pair(7,'-'), std::make_pair(8,'-'), std::make_pair(9,'-') } }; Player *player = new Human('O'); Player *player2 = new Robot('X'); Player* robot = new Robot('O'); Player* robot2 = new Robot('X'); //Game 1: Human vs Human Game HumanVsHuman(player, player2); HumanVsHuman.play(grid); //The robot doesn't work yet. Just treat it as a human. Point is to demonstrate polymorphisim. Game RobotvsHumanGame(robot, robot2); RobotvsHumanGame.play(grid); //deleting memory used delete player; delete player2; //deleting memory used delete robot; delete robot2; } </code></pre>
[]
[ { "body": "<p>I would enable all your warnings (and treat them like errors). Warnings in C++ show logic flaw in your reasoning usally and fixing them will save you some time.</p>\n<p>The warnings show one fatal flaw (missing return) and one oversight (unused variable).</p>\n<hr />\n<p>You don't need a copy of <code>GetType()</code> in Human and Robot it already exists in <code>Player</code>. Then you will not need the <code>protected</code> region in <code>Player</code> it can all be <code>private</code> (protected is a code smell).</p>\n<pre><code>class Human : public Player\n{\n public:\n Human(unsigned char name) :Player(name, &quot;Human&quot;) {}\n std::string GetType() { return m_type; }\n};\n\nclass Robot : public Player\n{\n public:\n Robot(unsigned char name) :Player(name, &quot;Robot&quot;){}\n std::string GetType() { return m_type; }\n};\n</code></pre>\n<hr />\n<p>You have not defined how a player makes a move. The <code>Player</code> object should define a virtual (abstract) method for <code>getMove()</code> that for player asks for user input. Then you can call this method in the Game <code>play()</code> method.</p>\n<pre><code>class Player\n{\n public:\n virtual int getMove() = 0;\n};\nclass Human\n{\n public:\n virtual int getMove() override\n {\n int move;\n std::cout &lt;&lt; &quot;Enter a number on the grid (e.g. 1): &quot;;\n std::cin &gt;&gt; move;\n return move;\n }\n};\n\nvoid Game::play(std::vector&lt;std::map&lt;int, unsigned char&gt;&gt; &amp;board)\n{\n int currentPlayer = 1;\n //Player *ref = nullptr;\n do\n {\n int move = 0;\n currentPlayer = (currentPlayer + 1) % 2;\n do\n {\n Displaygrid(board);\n std::cout &lt;&lt; m_p.at(currentPlayer)-&gt;GetType() &lt;&lt; &quot;: &quot; &lt;&lt; m_p.at(currentPlayer)-&gt;GetName() &lt;&lt; &quot; turn: &quot; &lt;&lt; std::endl;\n\n // Then call getMove in the loop.\n move = m_p.at(currentPlayer)-&gt;getMove();\n \n }\n while (ClaimSquare(board, move, m_p.at(currentPlayer)-&gt;GetName()) == false);\n }\n while (CheckForAWinner(board,m_p.at(currentPlayer)-&gt;GetName()) == false); \n}\n</code></pre>\n<hr />\n<p>Not sure this is a good idea.</p>\n<pre><code>std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;grid =\n{\n {std::make_pair(1, '-'), std::make_pair(2, '-'), std::make_pair(3, '-') },\n { std::make_pair(4,'-'), std::make_pair(5,'-'), std::make_pair(6,'-') },\n { std::make_pair(7,'-'), std::make_pair(8,'-'), std::make_pair(9,'-') }\n};\n</code></pre>\n<p>Go back to your original design or one of the choices (this seems to be a hybrid of the two styles).</p>\n<hr />\n<p>Don't use RAW pointers.</p>\n<pre><code>Player *player = new Human('O');\nPlayer *player2 = new Robot('X');\n</code></pre>\n<p>This is how it was done in the old days. When we manually managed memory. Nowadays you practically never create things with new (unless you are deep in the bowls of something). Normally you can stick with normal objects.</p>\n<pre><code>Player player{'O'};\nPlayer player2{'X'};\n\nGame HumanVsHuman(&amp;player, &amp;player2); // as you are using pointers internally\n // in Game you can simply pass the address\n // of the players here.\n //\n // Though in the long run I would pass references.\n</code></pre>\n<p>======</p>\n<p>Alternatively, if you do want to keep pointers, you should be using smart pointers to make sure the objects are managed.</p>\n<pre><code>std::shared_ptr&lt;Player&gt; player = std::make_shared&lt;Player&gt;('O');\n</code></pre>\n<p>This will make sure the memory is deallocated correctly (even when exceptions are thrown).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:37:44.457", "Id": "498858", "Score": "0", "body": "Thanks so much! I’m truly indebted to you! You have helped me think abstractly! I shall take on board everything you have suggested! This has been a huge learning curve!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T18:24:18.907", "Id": "253053", "ParentId": "253050", "Score": "3" } }, { "body": "<p>You have already received an excellent review. I would suggest using aliases with <a href=\"https://en.cppreference.com/w/cpp/keyword/using\" rel=\"nofollow noreferrer\"><strong><code>using</code></strong></a> here.</p>\n<p>Make an alias for <code>std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;</code></p>\n<pre><code>using Board = std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;;\n\nstd::cout&lt;&lt;std::is_same&lt;Board, std::vector&lt;std::map&lt;int, unsigned char&gt;&gt;&gt;::value;\n// 1\n</code></pre>\n<p>Now you can re-write functions like</p>\n<pre><code>bool ClaimSquare(Board&amp; grid, int move, const unsigned char player){\n // ... \n}\n\nvoid Displaygrid(const Board&amp; grid){\n// ...\n}\n</code></pre>\n<p>If you want <code>Board</code> to be parameterized, then use <code>template</code> with <code>using</code>(<a href=\"https://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow noreferrer\"><code>type alias, alias template</code></a>)</p>\n<pre><code>template&lt;typename T, typename U&gt;\nusing Board = std::vector&lt;std::map&lt;T, U&gt;&gt;;\n\n// Define Board with any types\nBoard&lt;std::int64_t, std::string&gt; grid; //valid \n// equivalent to std::vector&lt;std::map&lt;std::int64_t, std::string&gt;&gt;\n\n\nBoard&lt;std::string, std::uint8_t&gt; grid; //valid\n// equivalent to std::vector&lt;std::map&lt;std::string, std::uint8_t&gt;&gt;\n</code></pre>\n<p>Now, re-written functions would be</p>\n<pre><code>bool ClaimSquare(Board&lt;int, unsigned char&gt;&amp; grid, int move, const unsigned char player){\n // ... \n}\n\nvoid Displaygrid(const Board&lt;int, unsigned char&gt;&amp; grid){\n// ...\n}\n</code></pre>\n<hr />\n<p><code>std::endl</code> does much more than just adding a newline character. It flushes the stream too. Since you are just using it for adding a newline use <code>'\\n'</code> or <code>&quot;\\n&quot;</code>. <a href=\"https://stackoverflow.com/questions/35580919/should-stdendl-always-be-used\">Related answer from SO</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T20:07:06.647", "Id": "498977", "Score": "0", "body": "Thanks for your review. I'm a little confused, why would I want to use an alias with \"using\"? What does this do for me? Do I really need to template it if I know the values in the map won't change?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T21:02:16.277", "Id": "498982", "Score": "0", "body": "@GeorgeAustinBradley it makes it more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T22:00:52.330", "Id": "498991", "Score": "3", "body": "@GeorgeAustinBradley `using Board ` not only allows you to give a short name to complex type, but it puts the type definition in a single place. Then if you change the underlying type you only need to change it in that one place. All locations where you pass `Board` are automatically using the new type." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T19:43:04.783", "Id": "253092", "ParentId": "253050", "Score": "4" } } ]
{ "AcceptedAnswerId": "253053", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:55:16.323", "Id": "253050", "Score": "1", "Tags": [ "c++", "c++11", "tic-tac-toe" ], "Title": "Noughts & Crosses (Tic Tac Toe) OOP Design" }
253050
<p>I'm super excited to share my hangman game with you. (haven't added the graphics yet...)</p> <p>I will be using this program as my final project (for school), but I would like to have this polished before handing it in. I have given my program the limit of 7 attempts, but if the user continues to guess the wrong letters and then suddenly guesses the right letter, the attempt count stays where it's at.</p> <p>Here's what I mean:</p> <p>Let's say the word the computer has chosen is 'cougar' (I'm going to pretend I don't actually know this).</p> <p>BTW this is on my console:</p> <pre><code>Guess the word: ______ 7 chances left a # &lt;-- my input (1st actual input) Yes! a is in the word! Guess the word: ____a_ 7 chances left b # &lt;-- my input (2nd actual input) Sorry, b is not in the word. Try again. Guess the word: ____a_ 6 chances left b # &lt;-- my input (this was just to test out if my program would let me know that I have repeated a letter) You already guessed b. Please try another one! Guess the word: ____a_ 6 chances left t # &lt;-- my input (3rd actual input) Sorry, t is not in the word. Try again. Guess the word: ____a_ 5 chances left q # &lt;-- my input (4th actual input) Sorry, q is not in the word. Try again. Guess the word: ____a_ 4 chances left r # &lt;-- my input (5th actual input) Yes! r is in the word! Guess the word: ____ar 4 chances left h # &lt;-- my input (6th actual input) Sorry, h is not in the word. Try again. Guess the word: ____ar 3 chances left c # &lt;-- my input (7th actual input) </code></pre> <p>this is where the program should've initially said 'Sorry, you ran out of attempts. The word was cougar. Maybe next time ☹.</p> <p>instead, I get this:</p> <pre><code>Yes! c is in the word! Guess the word: c___ar 3 chances left # &lt;-- this is WRONG!! g # &lt;-- my input (my 1st extra attempt) Yes! g is in the word! Guess the word: c__gar 3 chances left i # &lt;-- my input (my 2nd extra attempt) Sorry, i is not in the word. Try again. Guess the word: c__gar 2 chances left o # &lt;-- my input (my 3rd extra attempt) Yes! o is in the word! Guess the word: co_gar 2 chances left u # &lt;-- my input (my 4th extra attempt) Yes! u is in the word! Awesome! You guessed cougar! </code></pre> <p>So my program is supposed to allow only 7 attempts (with the exception of a repeated letter). As you can clearly see I got <strong>12</strong> attempts! Out of which only 8 were acceptable (7 actual attempts and 1 for repeating 'b'), meaning I got 4 EXTRA attempts. (this is what I need to fix).</p> <p>Here's my code:</p> <pre><code>from random import choice words = choice(['ant', 'alpaca', 'baboon', 'badger', 'bat', 'bear', 'beaver', 'camel', 'cat', 'clam', 'cobra', 'cougar', 'coyote', 'crow', 'deer', 'dog', 'donkey', 'duck', 'eagle', 'ferret', 'fox', 'frog', 'goat', 'goose', 'hawk', 'lion', 'lizard', 'llama', 'mole', 'monkey', 'moose', 'mouse', 'mule', 'newt', 'otter', 'owl', 'panda', 'parrot', 'pigeon', 'python', 'rabbit', 'ram', 'rat', 'raven', 'rhino', 'salmon', 'seal', 'shark', 'sheep', 'skunk', 'sloth', 'snake', 'spider', 'stork', 'swan', 'tiger', 'toad', 'trout', 'turkey', 'turtle', 'weasel', 'whale', 'wolf', 'wombat', 'zebra']) guessed = [] wrong = [] attempts = 7 while attempts &gt; 0: out = '' for letter in words: if letter in guessed: out = out + letter else: out = out + '_' if out == words: break print('Guess the word:',out) print(attempts,'chances left\n') guess = input() if guess in guessed or guess in wrong: print('You already guessed',guess+ '.','Please try another one!') elif guess in words: print('Yes!',guess,'is in the word!') guessed.append(guess) else: print('Sorry,',guess,'is not in the word. Try again.') attempts = attempts - 1 wrong.append(guess) print() if attempts: print('Awesome! You guessed',words + '!') else: print('Sorry you ran out of attempts. The word was',words + '.', 'Maybe next time ☹') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:14:30.497", "Id": "498867", "Score": "0", "body": "All you need to do to fix your code is add `attempts = attempts - 1` when the person guesses right. But normally when playing hangman correct guesses do not count. Are you sure you want your game to work like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:13:55.907", "Id": "498888", "Score": "0", "body": "@ThisIsAQuestion I think that would be better as it just leads me to get confused..." } ]
[ { "body": "<p>Great job on your project! You're amazing!</p>\n<p>I reviewed your code and, rather than fixing the attempts variable, I removed it entirely and used <code>7-len(wrong)</code> to get the remaining attempts. This seems to fix your issue. Also, I change the if statement at the end to <code>if len(wrong) != 7</code> because the other if statement didn't make sense while using <code>len</code>. The way I put it, it will only congratulate you if you have less than 7 attempts used before it calls the <code>break</code>.</p>\n<p>The hardest part of fixing the code was testing it as I suck at hangman ;). If you need more help with this project, please let me know!</p>\n<p>Here is your code:</p>\n<pre><code>from random import choice\n\nwords = choice(['ant', 'alpaca', 'baboon', 'badger', 'bat', 'bear', 'beaver', 'camel', 'cat', 'clam', 'cobra', 'cougar',\n 'coyote', 'crow', 'deer', 'dog', 'donkey', 'duck', 'eagle', 'ferret', 'fox', 'frog', 'goat', 'goose',\n 'hawk', 'lion', 'lizard', 'llama', 'mole', 'monkey', 'moose', 'mouse', 'mule', 'newt', 'otter', 'owl',\n 'panda', 'parrot', 'pigeon', 'python', 'rabbit', 'ram', 'rat', 'raven', 'rhino', 'salmon', 'seal',\n 'shark', 'sheep', 'skunk', 'sloth', 'snake', 'spider', 'stork', 'swan', 'tiger', 'toad', 'trout',\n 'turkey', 'turtle', 'weasel', 'whale', 'wolf', 'wombat', 'zebra'])\n\nguessed = []\nwrong = []\n\nwhile len(wrong) &lt; 7:\n\n out = ''\n\n for letter in words:\n if letter in guessed:\n out = out + letter\n else:\n out = out + '_'\n\n if out == words:\n break\n\n print('Guess the word:',out)\n print(7-len(wrong),'chances left\\n')\n\n guess = input()\n\n if guess in guessed or guess in wrong:\n print('You already guessed',guess+ '.','Please try another one!')\n elif guess in words:\n print('Yes!',guess,'is in the word!')\n guessed.append(guess)\n else:\n print('Sorry,',guess,'is not in the word. Try again.')\n wrong.append(guess)\n\n print()\n\nif len(wrong) != 7:\n print('Awesome! You guessed',words + '!')\nelse:\n print('Sorry you ran out of attempts. The word was',words + '.', 'Maybe next time ☹')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:37:25.583", "Id": "498870", "Score": "0", "body": "Thank you so much!! And @Salocor YOU'RE awesome for taking the time to help me!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:45:49.913", "Id": "498873", "Score": "0", "body": "No problem! If this solved your problem, it'd be great if you marked my solution as the answer :)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:10:03.160", "Id": "253054", "ParentId": "253051", "Score": "2" } }, { "body": "<p>You are improving, that's nice.</p>\n<p>Since the project is quite minimal, I would just highlight few points for consideration.</p>\n<h2>Misleading variable names</h2>\n<p><code>words</code> and <code>out</code> are misleading, what does <code>out</code> mean, your variables should explain themselves clearly and be as unambiguous as possible, <code>words</code> gives the intent of holding multiple words but actually, it holds just a word.</p>\n<h2>You might not need it</h2>\n<p><code>wrong</code> list is totally unnecessary here, you might have implemented it for future purposes but right now, it isn't really used, define only what you are currently using. So it means <code>guess in wrong</code> is an irrelevant check</p>\n<p><code>guessed</code> happens to append only correct guesses, that's misleading, you might want to make it append both correct and wrong guess and it makes the variable <code>wrong</code> even more irrelevant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:10:27.187", "Id": "498887", "Score": "0", "body": "Thank you for your insight @theProgrammer. I appreciate your feedback and I will make sure to use your suggestions :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:02:03.560", "Id": "253059", "ParentId": "253051", "Score": "4" } } ]
{ "AcceptedAnswerId": "253054", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T17:59:35.370", "Id": "253051", "Score": "3", "Tags": [ "python", "beginner", "game" ], "Title": "Hangman Game with Python" }
253051
<p>I am working on a project which uses JNI. More than once I fell over the absence of type safety working with the variardic function calls. So I came up with this module. It wraps the variardic JNI functions using C++ variardc templates to offer a type-safe alternative. It also features integrated error checking for more compact code. This could be of use to others. I want to flesh it out and then publish it so others may base their work on it. This is the first time I really used templates in C++. I know it works well for me, but I also want to know whether the design is good. I am grateful for your opinions.</p> <p>In the code below, I omitted the repetitive implementations which only differ in the type used. You can find the complete code <a href="https://github.com/hoehermann/TypedJNI" rel="nofollow noreferrer">here</a>.</p> <h3>Use-Case</h3> <p>Instead of the lengthy and error-prone</p> <pre><code>jclass jcls = (*env)-&gt;FindClass(env, &quot;SomeClass&quot;); if (jcls == NULL) { return; // handle error } jmethodID constructor = (*env)-&gt;GetMethodID(env, jcls, &quot;&lt;init&gt;&quot;, &quot;(JLjava/lang/String;)V&quot;); if (constructor == NULL) { return; // handle error } jstring jsomestring = (*env)-&gt;NewStringUTF(env, somestring); if (jsomestring == NULL) { return; // handle error } jlong jsomelong = somelong; // explicitly convert jobject jobj = (*env)-&gt;NewObject(env, jcls, constructor, jsomelong, jsomestring); if (jobj == NULL) { return; // handle error } jmethodID method = (*env)-&gt;GetMethodID(env, jcls, &quot;someMethod&quot;, &quot;()V&quot;); if (method == NULL) { return; // handle error } (*env)-&gt;CallVoidMethod(env, jobj, method); (*env)-&gt;DeleteLocalRef(jsomestring); // late cleanup (*env)-&gt;DeleteLocalRef(jobj); </code></pre> <p>you can now write</p> <pre><code>try { tenv.find_class(&quot;SomeClass&quot;). GetConstructor&lt;jlong,jstring&gt;()( some_number, // implicit conversion where possible tenv.make_jstring(some_string) // explicit conversion with automated clean-up ). GetMethod&lt;void()&gt;(&quot;someMethod&quot;)(); } catch (std::exception &amp; e) { // handle error } </code></pre> <p>.</p> <h3>Header</h3> <pre><code>#pragma once #include &lt;jni.h&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; #include &lt;functional&gt; #include &lt;memory&gt; /** * Exception class for all runtime errors regarding TypedJNI. */ class TypedJNIError : public std::runtime_error { public: TypedJNIError(const std::string&amp; what_arg); }; namespace TypedJNI { // namespace for internal helper functions /** * GetTypeString maps the type arguments to the corresponding JNI type signature. * * * GetTypeString&lt;jboolean&gt;() → &quot;Z&quot; * * GetTypeString&lt;jbyte&gt;() → &quot;B&quot; * * and so on * * The full list is at https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/types.html#type_signatures. * * Can handle an arbitrary number of arguments: `GetTypeString&lt;jboolean,jbyte&gt;()` → &quot;ZB&quot; */ template &lt;typename T&gt; std::string GetTypeString(){ // this declares the templated function, but the default template may never actually be used static_assert(std::is_same&lt;T,void&gt;::value, &quot;Cannot handle this type.&quot;); return &quot;This actually never gets compiled.&quot;; }; template &lt;&gt; std::string GetTypeString&lt;void&gt;(); template &lt;&gt; std::string GetTypeString&lt;jboolean&gt;(); template &lt;&gt; std::string GetTypeString&lt;jint&gt;(); template &lt;&gt; std::string GetTypeString&lt;jlong&gt;(); template &lt;&gt; std::string GetTypeString&lt;jstring&gt;(); template&lt;typename T, typename... Args&gt; typename std::enable_if&lt;sizeof...(Args) != 0, std::string&gt;::type GetTypeString() { // recursively expand type string return GetTypeString&lt;T&gt;() + GetTypeString&lt;Args...&gt;(); }; template&lt;typename... Args&gt; typename std::enable_if&lt;sizeof...(Args) == 0, std::string&gt;::type GetTypeString() { // end of recursion return &quot;&quot;; }; /** * Wrapper around GetStaticMethodID(…) * * Performs error-checking. Throws an exception on error. */ jmethodID GetStaticMethodID(JNIEnv *env, const jclass cls, const std::string name, const std::string &amp; signature); /** * Wrapper around GetMethodID(…) * * Performs error-checking. Throws an exception on error. */ jmethodID GetMethodID(JNIEnv *env, const jclass cls, const std::string name, const std::string &amp; signature); } // namespace TypedJNI /** * TypedJNIStaticMethod selects the corresponding JNI function for static methods based on the requested return type. * * * TypedJNIStaticMethod&lt;void&gt;::get(…) → CallStaticVoidMethod * * TypedJNIStaticMethod&lt;jint&gt;::get(…) → CallStaticIntMethod * * and so on * * The full list is at https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html#calling_static_methods. * * For convenience, jstring is handled explicitly. All other objects are jobject. * * Based on https://stackoverflow.com/questions/9065081/. */ template&lt;typename T&gt; class TypedJNIStaticMethod; template&lt;typename ...Args&gt; class TypedJNIStaticMethod&lt;void(Args...)&gt; { public: static std::function&lt;void(Args...)&gt; get(JNIEnv *env, const jclass cls, const std::string &amp; name) { jmethodID mid = TypedJNI::GetStaticMethodID(env, cls, name, &quot;(&quot;+TypedJNI::GetTypeString&lt;Args...&gt;()+&quot;)&quot;+TypedJNI::GetTypeString&lt;void&gt;()); return [env, cls, mid](Args... args) { env-&gt;CallStaticVoidMethod(cls, mid, args...); }; } }; // other types omitted for less code to review /** * Like TypedJNIStaticMethod, but for object methods. */ template&lt;typename T&gt; class TypedJNIMethod; template&lt;typename ...Args&gt; class TypedJNIMethod&lt;void(Args...)&gt; { public: static std::function&lt;void(Args...)&gt; get(JNIEnv *env, const jclass cls, const jobject obj, const std::string &amp; name) { jmethodID mid = TypedJNI::GetMethodID(env, cls, name, &quot;(&quot;+TypedJNI::GetTypeString&lt;Args...&gt;()+&quot;)&quot;+TypedJNI::GetTypeString&lt;void&gt;()); return [env, obj, mid](Args... args) { env-&gt;CallVoidMethod(obj, mid, args...); }; } }; // other types omitted for less code to review /** * Class for a proxy object referencing a Java object. * * The local reference to the Java object is deleted when the last copy of the proxy object is destroyed. */ class TypedJNIObject { private: JNIEnv *env = nullptr; jclass cls = nullptr; std::shared_ptr&lt;_jobject&gt; obj = nullptr; public: TypedJNIObject(JNIEnv *env, jclass cls, jobject obj); template&lt;typename... Args&gt; std::function&lt;Args...&gt; GetMethod(const std::string name) { return TypedJNIMethod&lt;Args...&gt;::get(env, cls, obj.get(), name); } }; /** * Special case of TypedJNIMethod for accessing a Java constructor. */ template&lt;typename ...Args&gt; class TypedJNIConstructor { public: static std::function&lt;TypedJNIObject(Args...)&gt; get(JNIEnv *env, const jclass cls) { // yes indeed GetMethodID as illustrated at https://stackoverflow.com/questions/7260376/ (not get GetStaticMethodID) const jmethodID mid = TypedJNI::GetMethodID(env, cls, &quot;&lt;init&gt;&quot;, &quot;(&quot;+TypedJNI::GetTypeString&lt;Args...&gt;()+&quot;)&quot;+TypedJNI::GetTypeString&lt;void&gt;()); return [env, cls, mid](Args... args) -&gt; TypedJNIObject { return TypedJNIObject(env, cls, env-&gt;NewObject(cls, mid, args...)); }; } }; /** * Special case of TypedJNIObject for convenient string conversion. * * Uses NewStringUTF (expects Java modified Unicode, see https://stackoverflow.com/questions/7921016). */ class TypedJNIString { private: std::shared_ptr&lt;_jstring&gt; jstrptr = nullptr; public: TypedJNIString(JNIEnv *env, const std::string &amp; str); operator jstring() const; }; /** * Class for a proxy object referencing a Java class. * * Static methods can be accessed as well as the constructors. */ class TypedJNIClass { private: JNIEnv *env = nullptr; public: const jclass cls = nullptr; TypedJNIClass(JNIEnv *env, jclass cls); template&lt;typename... Args&gt; std::function&lt;Args...&gt; GetStaticMethod(const std::string name) { return TypedJNIStaticMethod&lt;Args...&gt;::get(env, cls, name); } template&lt;typename... Args&gt; std::function&lt;TypedJNIObject(Args...)&gt; GetConstructor() { return TypedJNIConstructor&lt;Args...&gt;::get(env, cls); } }; /** * Class for creating a Java VM and Environment. * * Wrapper around JNI_CreateJavaVM. * * Performs error-checking. Throws an exception on error. * * Provides access to Java classes and utility methods. * * The VM is destroyed with the TypedJNIEnv object. */ class TypedJNIEnv { private: JavaVM *vm = nullptr; public: /** * The environment is provided by a naked pointer. * * This is public so functionality not wrapped by TypedJNI can use direct access. */ JNIEnv *env = nullptr; TypedJNIEnv(const TypedJNIEnv&amp;) = delete; TypedJNIEnv&amp; operator=(const TypedJNIEnv&amp;) = delete; TypedJNIEnv(JavaVMInitArgs vm_args); virtual ~TypedJNIEnv(); /** * Find a Java class from the Java runtime. */ TypedJNIClass find_class(std::string name); /** * Create a Java String from a std::string. */ TypedJNIString make_jstring(const std::string &amp; str); }; </code></pre> <h3>Implementation</h3> <pre><code>#include &quot;typedjni.hpp&quot; TypedJNIError::TypedJNIError(const std::string&amp; what_arg) : std::runtime_error(what_arg) {}; template &lt;&gt; std::string TypedJNI::GetTypeString&lt;void&gt;(){return &quot;V&quot;;}; template &lt;&gt; std::string TypedJNI::GetTypeString&lt;jboolean&gt;(){return &quot;Z&quot;;}; template &lt;&gt; std::string TypedJNI::GetTypeString&lt;jint&gt;(){return &quot;I&quot;;}; template &lt;&gt; std::string TypedJNI::GetTypeString&lt;jlong&gt;(){return &quot;J&quot;;}; template &lt;&gt; std::string TypedJNI::GetTypeString&lt;jstring&gt;(){return &quot;Ljava/lang/String;&quot;;}; jmethodID TypedJNI::GetStaticMethodID(JNIEnv *env, const jclass cls, const std::string name, const std::string &amp; signature) { jmethodID mid = env-&gt;GetStaticMethodID(cls, name.c_str(), signature.c_str()); if (mid == NULL) { throw TypedJNIError(&quot;Failed to find static method '&quot;+name+&quot;' &quot;+signature+&quot;.&quot;); } return mid; } jmethodID TypedJNI::GetMethodID(JNIEnv *env, const jclass cls, const std::string name, const std::string &amp; signature) { jmethodID mid = env-&gt;GetMethodID(cls, name.c_str(), signature.c_str()); if (mid == NULL) { throw TypedJNIError(&quot;Failed to find method '&quot;+name+&quot;' &quot;+signature+&quot;.&quot;); } return mid; } TypedJNIObject::TypedJNIObject(JNIEnv *env, jclass cls, jobject obj) : env(env), cls(cls), obj(std::shared_ptr&lt;_jobject&gt;(obj, [env](jobject o){env-&gt;DeleteLocalRef(o);})) {}; TypedJNIString::TypedJNIString(JNIEnv *env, const std::string &amp; str) { jstring jstr = env-&gt;NewStringUTF(str.c_str()); if (jstr == NULL) { throw TypedJNIError(&quot;NewStringUTF failed for string '&quot;+str+&quot;'.&quot;); } jstrptr = std::shared_ptr&lt;_jstring&gt;(jstr, [env](jstring s){env-&gt;DeleteLocalRef(s);}); } TypedJNIString::operator jstring() const { return jstrptr.get(); } TypedJNIClass::TypedJNIClass(JNIEnv *env, jclass cls) : env(env), cls(cls) { if (!cls) { throw TypedJNIError(&quot;Tried to create TypedJNIClass from nullptr.&quot;); } }; TypedJNIEnv::TypedJNIEnv(JavaVMInitArgs vm_args) { jint res = JNI_CreateJavaVM(&amp;vm, (void **)&amp;env, &amp;vm_args); if (res != JNI_OK) { throw TypedJNIError(std::string(&quot;Failed to create Java VM (error &quot;)+std::to_string(res)+&quot;).&quot;); } } TypedJNIEnv::~TypedJNIEnv() { vm-&gt;DestroyJavaVM(); } TypedJNIClass TypedJNIEnv::find_class(std::string name) { jclass cls = env-&gt;FindClass(name.c_str()); if (cls == NULL) { throw TypedJNIError(&quot;Failed to find class '&quot;+name+&quot;'.&quot;); } return TypedJNIClass(env, cls); } TypedJNIString TypedJNIEnv::make_jstring(const std::string &amp; str) { return TypedJNIString(env, str); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-26T21:03:00.337", "Id": "503622", "Score": "0", "body": "For further reference: I found a flaw in the design regarding the deleter in `TypedJNIObject`. If the last C++ instance goes out of scope, the deleter is called and the Java object is garbage collected. To compensate, `TypedJNIMethod::get` now captures the `TypedJNIObject` instance rather than the raw and potentially dangling pointers." } ]
[ { "body": "<h1>Consider changing the interface</h1>\n<p>I'm not very familiar with Java, but I assume you want the interface to the Java classes to feel as native C++ as possible. Your example code does not really look like native C++:</p>\n<pre><code> tenv.find_class(&quot;SomeClass&quot;).\n GetConstructor&lt;jlong,jstring&gt;()(\n some_number, // implicit conversion where possible\n tenv.make_jstring(some_string) // explicit conversion with automated clean-up\n ).\n GetMethod&lt;void()&gt;(&quot;someMethod&quot;)();\n</code></pre>\n<p>Part of it is the function names: I would expect <code>GetConstructor()</code> to return a constructor, but not actually construct the object. Perhaps it should just be renamed <code>Construct()</code>, but that still doesn't feel right; you never have to write <code>std::string foo = std::string::GetConstructor()(&quot;Hello&quot;)</code> in C++.</p>\n<p>Let's start with how I would want the interface to work:</p>\n<pre><code>auto psclass = tenv.find_class(&quot;SomeClass&quot;);\nauto object = psclass(some_number, tenv.make_jstring(some_string));\nobject.call&lt;void()&gt;(&quot;someMethod&quot;)();\n</code></pre>\n<p>In the above example, creating a class object would work the same as you already have. But then to construct it, I want to feel it as much C++ as possible. Overloading <code>operator()</code> of <code>TypedJNIClass</code> would allow you to do that to a certain extent (you can write <code>std::string = std::string(&quot;Hello&quot;)</code> after all). Also, I wouldn't want to have to specify the template parameters, so let the compiler deduce them automatically. Here's a possible implementation:</p>\n<pre><code>class TypedJNIClass {\n ...\n template&lt;typename... Args&gt;\n TypedJNIObject operator()(Args... &amp;&amp;args) {\n const jmethodID mid = TypedJNI::GetMethodID(env, cls, &quot;&lt;init&gt;&quot;, &quot;(&quot; + TypedJNI::GetTypeString&lt;Args...&gt;() + &quot;)&quot; + TypedJNI::GetTypeString&lt;void&gt;());\n return TypedJNIObject(env, cls, env-&gt;NewObject(cls, mid, args...));\n }\n};\n</code></pre>\n<p>And then for calling methods, I would want to avoid the two-step process, and not first get a lambda and then pass the parameters to the lambda:</p>\n<pre><code>class TypedJNIObject {\n ...\n template&lt;typename... Args&gt;\n auto call(const std::string &amp;name, Args... &amp;&amp;args) {\n return TypedJNIMethod&lt;Args...&gt;::get(env, cls, obj.get(), name)(args);\n }\n};\n</code></pre>\n<p>Of course, the latter might be inefficient if you repeatedly want to call the same method.</p>\n<h1>What about functions that return something?</h1>\n<p>You only handle functions that return <code>void</code>. I'm sure someone would want to use this to get some data back from the Java methods they are calling.</p>\n<h1>Enforce copy semantics for objects</h1>\n<p>C++ programmers are used to copy semantics. However, it looks like you wrote <code>TypedJNIObject</code> in such a way that if you write:</p>\n<pre><code>auto object1 = tenv.find_class(&quot;SomeClass&quot;)(...);\nauto object2 = object1;\n</code></pre>\n<p>Then both <code>object1</code> and <code>object2</code> refer to the same Java object. This could be very confusing. I recommend that you change the type of <code>TypedJNIObject::obj</code> from <code>std::shared_ptr</code> to <code>std::unique_ptr</code>, and write a copy constructor for it that actually creates a deep copy of the object, so it behaves like a regular C++ object. If a C++ programmer wants to avoid a deep copy, they'd just use references explicitly:</p>\n<pre><code>auto object1 = tenv.find_class(&quot;SomeClass&quot;)(...);\nauto &amp;object2 = object1;\n</code></pre>\n<h1>Avoid repeating the name of a <code>namespace</code> in its members</h1>\n<p>Many things inside <code>namespace TypedJNI</code> are prefixed with <code>TypedJNI</code>, but that is unnecessary duplication. You can remove that prefix from all its member functions and classes. Code using your classes can just write:</p>\n<pre><code>TypedJNI::Class psclass = tenv.find_class(&quot;SomeClass&quot;);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T21:05:30.090", "Id": "498896", "Score": "0", "body": "Thank you for your review. I was sure about many of the points you mentioned. I just updated the interface according to your suggestion. I definitely want to look if I can make the automatic template parameter deduction work. Many (but not all) other return types are actually implemented – I just left them out of the review because it is all the same (except for the type, of course). I was unsure whether a prefix or a namespace would be better (you can tell from the code I was undecided). Your answer made me lean more towards namespaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T21:16:51.277", "Id": "498897", "Score": "0", "body": "The C++ copy semantics are another good point. I am doubtful I can implement that as Java objects – as far as I know – are not guaranteed to provide a mechanism for creating a deep copy. Users will need to keep it in mind. But I want to add it to the comment for clarification." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:38:34.860", "Id": "253061", "ParentId": "253057", "Score": "2" } } ]
{ "AcceptedAnswerId": "253061", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:46:24.637", "Id": "253057", "Score": "6", "Tags": [ "c++", "template-meta-programming", "variadic", "jni" ], "Title": "Using templates to wrap variardic JNI method calls into type-safe C++ functors" }
253057
<p>I've done some coding in the past but nothing with OOP and honestly, I cannot wrap my head around using classes and constructors to tidy up my code. I'm used to &quot;calling functions&quot; instead of pasting code over and over again but in Java, the methods and classes, etc. take care of that but man, I'm just not getting it.</p> <p>My code is for a basic math game based on multiplication. I'd like to have two modes, one with elapsed time and one with a count-down timer. I've build most of the code (and it actually works) but it's to the point where it's getting super repetitive to add what I want to add because I'm coding the whole thing in the main method.</p> <p>I'd love some help cleaning it up by putting all of the basic functions in separate classes such as askQuestion, checkAnswer, displayScoreMessage, displayQuestionLog, playAgain, etc.</p> <p>My code is below and I tried to comment as I went.</p> <p>Any help would be very much appreciated!</p> <p>MY CODE:</p> <pre><code>package mathfactsGame; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; public class mathfactsGameMain { public static void main(String[] args) { // Set numbers to 0 int n1 = 0; int n2 = 0; long totalStart = 0; int mathfact = 0; // Create arraylist QuestionLog List&lt;Object&gt; questionLog = new ArrayList&lt;Object&gt;(); // Start game loop while (true) { // Set score to 0 int score = 0; // initialize scanner Scanner input = new Scanner(System.in); // Begin game System.out.println(&quot;MULTIPLICATION MATH FACTS GAME&quot;); System.out.println(&quot;==============================&quot;); // set name System.out.println(&quot;What is your name?&quot;); String playerName = input.next(); // Set the mathfact family you want System.out.println(&quot;What MathFact family do you want do you want? (1-12)&quot;); // Need to add an option for ALL int mathFact = input.nextInt();// in ALL option, mathFact would just be r.nextInt(13) // Greeting and choose count down mode or elapsed time mode System.out.println(&quot;Would you like to play challenge mode or timed mode?&quot;); System.out.println(&quot;1 = challenge&quot;); System.out.println(&quot;2 = timed&quot;); // need to build timed mode -&gt; when time ends, go to game score message and // print out questionLog int mode = input.nextInt(); // User sets number of questions System.out.println(&quot;How many questions do you want?&quot;); int questions = input.nextInt(); // Begin For loop, play game the number of times the user set with (questions) // count score (# right) // start timer totalStart = System.nanoTime(); for (int count = 1; count &lt;= questions; count++) { // Generate random numbers Random r = new Random(); n1 = mathFact; n2 = r.nextInt(13); // Start timer for each question Long start = System.nanoTime(); // check if answer is correct boolean resultOK = false; String displayResultOK = null; // TIMED (mode 1) (Haven't written mode 2) if (mode == 1) { System.out.println(&quot;\nQuestion #&quot; + count); System.out.println(&quot;What is &quot; + n1 + &quot; x &quot; + n2 + &quot;?&quot;); int answer = input.nextInt(); // Check if answer is correct else it's incorrect if (answer == (n1 * n2)) { System.out.println(&quot;CORRECT&quot;); score++; resultOK = (n1 * n2 == answer); displayResultOK = resultOK ? &quot;CORRECT&quot; : &quot;INCORRECT&quot;; long end = System.nanoTime(); double duration = end - start; double totalDurationSec = duration / 1000000000d; DecimalFormat formattingObject = new DecimalFormat(&quot;0.00&quot;); String roundedtotalDurationSec = formattingObject.format(totalDurationSec); System.out.println(&quot;Time elapsed: &quot; + roundedtotalDurationSec); questionLog.add(&quot;Question #&quot; + (count) + &quot;:&quot;); questionLog.add(n1 + &quot; x &quot; + n2); questionLog.add(&quot;\tYour answer = &quot; + answer); questionLog.add(&quot;\tCorrect answer = &quot; + (n1 * n2)); questionLog.add(&quot;\tYou got the answer &quot; + displayResultOK); questionLog.add(&quot;in &quot; + roundedtotalDurationSec + &quot; seconds\n&quot;); } // else for incorrect else { System.out.println(&quot;INCORRECT&quot;); resultOK = (n1 * n2 == answer); displayResultOK = resultOK ? &quot;CORRECT&quot; : &quot;INCORRECT&quot;; long end = System.nanoTime(); double duration = end - start; double totalDurationSec = duration / 1000000000d; DecimalFormat formattingObject = new DecimalFormat(&quot;0.00&quot;); String roundedtotalDurationSec = formattingObject.format(totalDurationSec); questionLog.add(&quot;Question #&quot; + (count) + &quot;:&quot;); questionLog.add(n1 + &quot; x &quot; + n2); questionLog.add(&quot;\tYour answer = &quot; + answer); questionLog.add(&quot;\tCorrect answer = &quot; + (n1 * n2)); questionLog.add(&quot;\tYou got the answer &quot; + displayResultOK); questionLog.add(&quot;in &quot; + roundedtotalDurationSec + &quot; seconds\n&quot;); System.out.println(&quot;Time elapsed: &quot; + roundedtotalDurationSec); } } } // clean up questionLog formatting questionLog.add(0, &quot;&quot;); String formattedString = questionLog.toString().replace(&quot;,&quot;, &quot;&quot;) // remove the commas .replace(&quot;[&quot;, &quot;&quot;) // remove the right bracket .replace(&quot;]&quot;, &quot;&quot;); // remove the left bracket // Calculate score messages if (score == questions) { // All correct System.out.println(&quot;\n===Question Log=== \n&quot;); System.out.println(formattedString); long totalEnd = System.nanoTime(); long totalDuration = totalEnd - totalStart; double totalDurationALL = totalDuration / 1000000000d; DecimalFormat formattingObject = new DecimalFormat(&quot;0.00&quot;); String roundedTotaltime = formattingObject.format(totalDurationALL); System.out.println(&quot;\nGreat Job! &quot; + playerName + &quot;, your score is &quot; + score + &quot; out of &quot; + questions + &quot;, or 100%! You got them all correct in &quot; + roundedTotaltime + &quot; total seconds.\n&quot;); } else { // Any wrong System.out.println(&quot;\n===Question Log=== \n&quot;); System.out.println(formattedString); long totalEnd = System.nanoTime(); long totalDuration = totalEnd - totalStart; double totalDurationALL = totalDuration / 1000000000d; DecimalFormat formattingObject = new DecimalFormat(&quot;0.00&quot;); String roundedTotaltime = formattingObject.format(totalDurationALL); double percent = (((double) score / (double) questions)) * 100; String roundedPercent = formattingObject.format(percent); System.out.println(&quot;\n&quot; + playerName + &quot;, your score is &quot; + score + &quot; out of &quot; + questions + &quot;, or &quot; + roundedPercent + &quot;%. You missed &quot; + (questions - score) + &quot; questions in &quot; + roundedTotaltime + &quot; total seconds. \n&quot;); } // Play again? System.out.println(&quot;Would you like to play again? Y/N&quot;); String again = input.next(); questionLog.clear(); // End loop if &quot;N&quot; if (again.equalsIgnoreCase(&quot;N&quot;)) { System.out.println(&quot;Thank you for playing!&quot;); input.close(); break; } } } } </code></pre> <p>===EDITED TO ADD===</p> <p>I understand I'm asking a lot so I've tried to do some more work to show some effort on my part but am getting stuck again.</p> <p>I finally made some headway splitting off into a different class.</p> <p>I have no idea how to build the question log and I cannot get the mathFact variable to work doing what I'm doing. It's always a random number.</p> <p>Thanks again for looking and any help would be super useful!</p> <p>Here's my Main method:</p> <pre><code>package game2; import java.util.Scanner; public class game2main { public static void main(String[] args) { while (true) { Scanner input = new Scanner(System.in); System.out.println(&quot;MULTIPLICATION MATH FACTS GAME&quot;); System.out.println(&quot;==============================&quot;); System.out.println(&quot;What is your name?&quot;); String playerName = input.next(); Question.mathFact(); System.out.println(&quot;How many questions do you want?&quot;); int questions = input.nextInt(); long totalStart = 0; totalStart = System.currentTimeMillis(); for (int i = 0; i &lt; questions; i++) { Question q = new Question(); q.askQuestion(); q.Check(); Question.qTime(); } Question.showScore(); long totalEnd = System.currentTimeMillis(); double totalDuration = totalEnd - totalStart; double totalDurationSec = (totalDuration / 1000); System.out.println(&quot;Total time elapsed: &quot; + totalDurationSec); // play again System.out.println(&quot;Would you like to play again? Y/N&quot;); String again = input.next(); if (again.equalsIgnoreCase(&quot;N&quot;)) { System.out.println(&quot;Thank you for playing!&quot;); input.close(); break; } } } } </code></pre> <p>Here is my Question class:</p> <pre><code>package game2; import java.util.Random; import java.util.Scanner; public class Question { public static int mathFact = 0; public static int mode = 0; private int n1; private int n2; public String Question; private static long start = 0; private int correct; Random rand = new Random(); static Scanner input = new Scanner(System.in); public static int score = 0; Question() { n1 = rand.nextInt(mathFact); n2 = rand.nextInt(13); } public void askQuestion() { System.out.println(&quot;What is &quot; + n1 + &quot; x &quot; + n2 + &quot; ?\n&quot;); correct = n1 * n2; start = System.currentTimeMillis(); } public static void qTime() { long end = System.currentTimeMillis(); double duration = end - start; double durationSec = (duration / 1000); System.out.println(&quot;Time elapsed: &quot; + durationSec); } public void Check() { int response = input.nextInt(); if (response == correct) { System.out.printf(&quot;yes.\n&quot;); score++; } else { System.out.printf(&quot;No. It is &quot; + correct + &quot;.\n&quot;); } } public static void showScore() { System.out.println(&quot;Number correct: &quot; + score); } public static void mathFact() { System.out.println(&quot;What MathFact family do you want do you want? (1-12)&quot;); mathFact = input.nextInt();// in ALL option, mathFact would just be r.nextInt(13) } public void Mode() { System.out.println(&quot;Would you like to play challenge mode or timed mode?&quot;); System.out.println(&quot;1 = challenge&quot;); System.out.println(&quot;2 = timed&quot;); // need to build timed mode -&gt; when time ends, go to game score message and print out questionLog mode = input.nextInt(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T20:14:52.327", "Id": "498889", "Score": "0", "body": "Please make sure that the title of your post is a description of what your code does, not what you need help with. For more assistance see [the help page](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-05T00:14:17.623", "Id": "498908", "Score": "1", "body": "I edited the title. Hopefully, that will suffice. Thank you." } ]
[ { "body": "<p>I reworked your code. Here's the result of a test run.</p>\n<pre><code>MULTIPLICATION MATH FACTS GAME\n==============================\nWhat is your name?\nGilbert\nWould you like to play challenge mode or timed mode?\n1 = challenge\n2 = timed\n2\nWhat MathFact family do you want do you want? (1-12)\n6\nHow many questions do you want?\n3\nWhat is 4 x 6 ?\n24\nYes, you're correct.\nTime elapsed: 3.641\nWhat is 2 x 6 ?\n12\nYes, you're correct.\nTime elapsed: 4.103\nWhat is 5 x 3 ?\n15\nYes, you're correct.\nTime elapsed: 3.32\nNumber correct: 3\nTotal time elapsed: 11.065\nWould you like to play again? Y/N\nn\nThank you Gilbert for playing!\n</code></pre>\n<p>Here are the major changes I made.</p>\n<ol>\n<li><p>I eliminated all static fields and methods, except for the <code>main</code> method to start the application. Generally, you don't use static methods or fields when creating a multi-class application.</p>\n</li>\n<li><p>I divided the code into a Main class and a Question class. The Main class is responsible for all of the non-game interaction with the user. The Question class generates the questions and checks the answers to the questions. Generally, you try and put the responsibility for input/output in one class and an application model in a separate class.</p>\n</li>\n<li><p>The code I wrote goes from general at the top to more specific as I go down through the methods. An understandable program is like an understandable essay. Start with the main points, then add the details.</p>\n</li>\n<li><p>I created one instance of <code>Scanner</code>. I passed that instance to the Question class. Generally, your code should have one and only one <code>System.in</code> <code>Scanner</code>.</p>\n</li>\n<li><p>I created one instance of the Question class.</p>\n</li>\n<li><p>I named all the methods with a verb-noun combination. Generally, that's what readers of your code expect. This tells them what the method does.</p>\n</li>\n<li><p>Class names start with an upper-case letter. Method names start with a lower-case letter. Field names start with a lower-case letter. This allows me to write <code>Question question = new Question(input);</code> and have the reading of that line make sense.</p>\n</li>\n</ol>\n<p>I didn't do anything with the mode value either.</p>\n<p>Here's the complete runnable code I modified. I made the Question class an inner class so I could copy and paste this code as one module.</p>\n<pre><code>import java.util.Random;\nimport java.util.Scanner;\n\npublic class MultiplicationGame {\n\n public static void main(String[] args) {\n new MultiplicationGame().runGame();\n }\n\n private void runGame() {\n Scanner input = new Scanner(System.in);\n Question question = new Question(input);\n String playerName = getPlayerName(input);\n \n do {\n int mode = getMode(input);\n int mathfact = getMathFact(input);\n int questionCount = getTotalQuestionCount(input);\n askQuestions(question, mode, mathfact, questionCount);\n } while (playAgain(input, playerName));\n \n input.close();\n }\n\n private void askQuestions(Question question, int mode, \n int mathfact, int questionCount) {\n question.setMode(mode);\n question.setMathFact(mathfact);\n question.setScore(0);\n \n long totalStart = System.currentTimeMillis();\n \n for (int i = 0; i &lt; questionCount; i++) {\n question.askQuestion();\n question.checkAnswer();\n question.printQuitTime();\n }\n question.printScore();\n \n long totalEnd = System.currentTimeMillis();\n double totalDuration = totalEnd - totalStart;\n double totalDurationSec = (totalDuration / 1000);\n System.out.println(&quot;Total time elapsed: &quot; + totalDurationSec);\n }\n\n private String getPlayerName(Scanner input) {\n System.out.println(&quot;MULTIPLICATION MATH FACTS GAME&quot;);\n System.out.println(&quot;==============================&quot;);\n System.out.println(&quot;What is your name?&quot;);\n return input.nextLine();\n }\n \n private int getMode(Scanner input) {\n System.out.println(&quot;Would you like to play challenge mode or timed mode?&quot;);\n System.out.println(&quot;1 = challenge&quot;);\n System.out.println(&quot;2 = timed&quot;);\n int mode = input.nextInt();\n input.nextLine();\n return mode;\n }\n \n private int getMathFact(Scanner input) {\n System.out.println(&quot;What MathFact family do you want? (1-12)&quot;);\n int mathFact = input.nextInt();\n input.nextLine();\n return mathFact;\n }\n \n private int getTotalQuestionCount(Scanner input) {\n System.out.println(&quot;How many questions do you want?&quot;);\n int questionCount = input.nextInt();\n input.nextLine();\n return questionCount;\n }\n \n private boolean playAgain(Scanner input, String playerName) {\n // play again\n System.out.println(&quot;Would you like to play again? Y/N&quot;);\n String again = input.nextLine();\n if (again.charAt(0) == 'n') {\n System.out.println(&quot;Thank you &quot; + playerName + &quot; for playing!&quot;);\n return false;\n } else {\n return true;\n }\n }\n\n public class Question {\n private int correctAnswer;\n private int mathfact;\n private int mode;\n private int score;\n \n private long start;\n \n private final Random random;\n private final Scanner input;\n\n public Question(Scanner input) {\n this.input = input;\n this.random = new Random();\n }\n\n public void setScore(int score) {\n this.score = score;\n }\n\n public void setMathFact(int mathfact) {\n this.mathfact = mathfact;\n }\n\n public void setMode(int mode) {\n this.mode = mode;\n }\n\n public void askQuestion() {\n int n1 = random.nextInt(mathfact) + 1;\n int n2 = random.nextInt(mathfact) + 1;\n System.out.println(&quot;What is &quot; + n1 + &quot; x &quot; + n2 + &quot; ?&quot;);\n correctAnswer = n1 * n2;\n start = System.currentTimeMillis();\n }\n\n public void printQuitTime() {\n long end = System.currentTimeMillis();\n double duration = end - start;\n double durationSec = (duration / 1000);\n System.out.println(&quot;Time elapsed: &quot; + durationSec);\n }\n\n public void checkAnswer() {\n int response = input.nextInt();\n input.nextLine();\n if (response == correctAnswer) {\n System.out.println(&quot;Yes, you're correct.&quot;);\n score++;\n } else {\n System.out.println(&quot;No. It is &quot; + correctAnswer + &quot;.&quot;);\n }\n }\n\n public void printScore() {\n System.out.println(&quot;Number correct: &quot; + score);\n }\n \n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-08T00:28:50.160", "Id": "499243", "Score": "0", "body": "Thanks so much! This helps a lot getting my head wrapped around everything. I appreciate it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T23:46:47.047", "Id": "253152", "ParentId": "253058", "Score": "1" } } ]
{ "AcceptedAnswerId": "253152", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-04T19:46:57.593", "Id": "253058", "Score": "1", "Tags": [ "java" ], "Title": "Multiplication math game using classes/constructors" }
253058