body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm trying to implement some domain driven design architecture, such as a repository to talk to the database, and a service that talks to the repository.</p>
<p>I have an action where I want to see if a User exists, and if he does, update his data, if he doesn't, create it and then perform a task (this could be done using event listeners but I'm not there yet).</p>
<ul>
<li>Now I'm wondering if my service method can do all these things? Is there another actor that should be responsible for this?</li>
<li>This method is not very testable, since it's performing multiple actions? How would I test a method like this?</li>
</ul>
<pre><code>public function updateOrCreate($data)
{
$userData = static::getUserDataFromAccessToken($data);
// Find the user
$user = $this->userRepository->find($userData['id']);
// If we found the user, update and return
if ($user) {
$this->userRepository->update($userData);
// Return the updated user
return $this->userRepository->find($userData['id']);
}
// Else create
$created = $this->userRepository->create($userData);
if ($created) {
// Get the newly created user
$user = $this->userRepository->find($userData['id']);
// Get the activities
$this->activityTask->perform($user);
return $user;
}
}
public static function getUserDataFromAccessToken($token): array
{
return [
'id' => $token->getValues()['athlete']['id'],
'username' => $token->getValues()['athlete']['username'],
'photo' => $token->getValues()['athlete']['profile'],
'access_token' => $token->getToken(),
'refresh_token' => $token->getRefreshToken(),
];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T22:13:05.283",
"Id": "487336",
"Score": "1",
"body": "Please cache `$token->getValues()` as a variable and use it multiple times instead of calling the method three times to populate the return array. We must never ask the system to fetch the same unchanged data more than once. Or (I don't know what else is in the `athlete` column), you might merge the return value of `array_column($token->getValues(), 'athlete')`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T06:38:31.440",
"Id": "487367",
"Score": "0",
"body": "Thanks @mickmackusa good advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:22:37.863",
"Id": "487698",
"Score": "1",
"body": "@MiguelStevens since you are following DDD it might be of benefit to create a DTO or a Value Object for the user data hence remove a need for `getUserDataFromAccessToken`. It's easier to deal with models than it is with repositories, since that removes a need for re fetch of data after you perform and update. Also, why would user creation fail?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:24:17.797",
"Id": "487699",
"Score": "1",
"body": "@MiguelStevens you would want one action class for user creation and another action class for user update. this updateOrCreate is a different service file and to test it you just need to check that correct class is called depending on data you send into the method."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T19:58:42.403",
"Id": "248725",
"Score": "2",
"Tags": [
"php",
"repository"
],
"Title": "A UserService method that calls the UserRepository a few times"
}
|
248725
|
<p>This is exercise 2.4.20. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<p>Implement a class that simulates Conway’s Game of Life.</p>
<p>One thing to note: I did not want my grid to have passive edges and so in my program I considered the grid to be an opened torus (for example in a 10-by-10 grid represented by an array: a[9+1][9+1] == a[0][0]). I also tried to make the name of the methods and variables as self-explanatory as possible.</p>
<p>Here is my program:</p>
<pre><code>public class GameOfLife
{
public static boolean[][] randomGridMaker(int n, double p)
{
// n is the number of grid cells in each row or column
// p is the probability of a cell being alive
boolean[][] grid = new boolean[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.random() < p)
{
grid[i][j] = true;
}
}
}
return grid;
}
public static boolean[][] gridEqualizer(boolean[][] a)
{
int n = a.length;
boolean[][] b = new boolean[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = a[i][j];
}
}
return b;
}
public static int liveNeighborCounter(boolean[][] a, int i, int j)
{
int counter = 0;
int n = a.length;
if (a[(i-1)%n][(j-1)%n]) counter++;
if (a[(i-1)%n][j%n]) counter++;
if (a[(i-1)%n][(j+1)%n]) counter++;
if (a[i%n][(j+1)%n]) counter++;
if (a[(i+1)%n][(j+1)%n]) counter++;
if (a[(i+1)%n][j%n]) counter++;
if (a[(i+1)%n][(j-1)%n]) counter++;
if (a[i%n][(j-1)%n]) counter++;
return counter;
}
public static boolean[][] gridUpdater(boolean[][] a)
{
int n = a.length;
boolean[][] b = new boolean[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = a[i][j];
}
}
for (int i = 1; i < n; i++)
{
for (int j = 1; j < n; j++)
{
int liveNeighbors = liveNeighborCounter(a, i, j);
if (!a[i][j] && liveNeighbors == 3) b[i][j] = true;
if (a[i][j])
{
if (liveNeighbors == 1) b[i][j] = false;
if (liveNeighbors > 3) b[i][j] = false;
}
}
}
return b;
}
public static void gridDrawer(boolean[][] a)
{
int n = a.length;
StdDraw.setXscale(0,n);
StdDraw.setYscale(0,n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j]) StdDraw.filledSquare(i+0.5,j+0.5,0.47);
}
}
}
public static void main(String[] args)
{
int n = Integer.parseInt(args[0]);
double p = Double.parseDouble(args[1]);
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
StdDraw.enableDoubleBuffering();
boolean[][] a = new boolean[n][n];
boolean[][] b = new boolean[n][n];
a = randomGridMaker(n, p);
while (true)
{
StdDraw.clear();
gridDrawer(a);
StdDraw.show();
StdDraw.pause(50);
StdDraw.clear();
b = gridUpdater(a);
gridDrawer(b);
StdDraw.show();
StdDraw.pause(50);
a = gridEqualizer(b);
}
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="noreferrer">StdDraw</a> is a simple API written by the authors of the book. I checked my program and it works. Here are two different instances of it:</p>
<p>Instance 1: n = 20 and p = 0.1:</p>
<p><a href="https://i.stack.imgur.com/NeS1i.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/NeS1i.gif" alt="enter image description here" /></a></p>
<p>Instance 2: n = 100 and p = 0.5:</p>
<p><a href="https://i.stack.imgur.com/hp5ZT.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/hp5ZT.gif" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program (especially its performance)?</p>
<p>Thanks for your attention.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:15:21.413",
"Id": "487353",
"Score": "1",
"body": "This had been my favorite programming exercise for a long time. I have 2 suggestions: 1) make a Glider Gun. The Gosper gun is ok but there are more interesting ones out there. 2) read about the construction of a Turing Machine in the Game of Life (it's theoretical, I'd not try actually doing it, but the concept is really interesting)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T08:35:25.140",
"Id": "487378",
"Score": "0",
"body": "@Z4-tier Thank you very much. I certainly try to make other constructions with it. :)"
}
] |
[
{
"body": "<p>Nice implementation, few suggestions:</p>\n<h2>Naming conventions</h2>\n<p>In Java methods should be verbs and classes should be nouns.</p>\n<ul>\n<li>method <code>randomGridMaker</code> can be renamed to <code>makeRandomGrid</code> (or similar)</li>\n<li>method <code>liveNeighborCounter</code> can be renamed to <code>countAliveNeighbors</code></li>\n<li>method <code>gridDrawer</code> could be <code>drawGrid</code>, etc..</li>\n</ul>\n<p><a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">Java Naming Convetions</a></p>\n<h2>Input validation</h2>\n<p>The program needs two arguments to start, better to provide a message to the user:</p>\n<pre><code>if(args.length != 2) {\n System.out.println("Size and probability not provided");\n System.exit(1);\n}\n</code></pre>\n<h2>Encapsulation</h2>\n<p>The grid is passed around in almost every method. Would be better to have the grid as state of <code>GameOfLife</code>:</p>\n<pre><code>public class GameOfLife {\n \n private boolean[][] grid;\n private int n;\n private double p;\n \n public GameOfLife(int n, double p) {\n grid = new boolean[n][n];\n this.n=n;\n this.p=p;\n }\n//...\n}\n</code></pre>\n<p>This will also make <code>GameOfLife</code> easier to reuse.</p>\n<h2>Main loop</h2>\n<pre><code>while (true)\n {\n StdDraw.clear(); \n gridDrawer(a);\n StdDraw.show();\n StdDraw.pause(50);\n StdDraw.clear();\n b = gridUpdater(a);\n gridDrawer(b);\n StdDraw.show();\n StdDraw.pause(50);\n a = gridEqualizer(b);\n }\n</code></pre>\n<ul>\n<li><p>The method <code>gridDrawer</code> already knows how to use the library <code>StdDraw</code>, so the the methods <code>clear</code> and <code>show</code> can be moved there</p>\n</li>\n<li><p>There is no need of <code>gridEqualizer</code> if a new grid is already created in <code>gridUpdater</code></p>\n</li>\n<li><p>The two calls to <code>pause(50)</code> can now become <code>pause(100)</code></p>\n</li>\n</ul>\n<p>The result would be:</p>\n<pre class=\"lang-java prettyprint-override\"><code>GameOfLife gol = new GameOfLife(n,p);\ngol.initRandom();\nwhile (true){\n drawGrid(gol.getGrid());\n StdDraw.pause(100);\n gol.update(); // this is gridUpdater\n}\n</code></pre>\n<p>Notice that:</p>\n<ul>\n<li><code>GameOfLife</code> doesn't know how to draw itself, therefore is independent of the library <code>StdDraw</code></li>\n<li>Only <code>GameOfLife</code> can modify the grid</li>\n</ul>\n<h2>Performance</h2>\n<p>There are no big issues about performances, just few suggestions.</p>\n<p>There are many operations in <code>liveNeighborCounter</code>:</p>\n<pre><code>public static int liveNeighborCounter(boolean[][] a, int i, int j)\n {\n int counter = 0;\n int n = a.length;\n if (a[(i-1)%n][(j-1)%n]) counter++;\n if (a[(i-1)%n][j%n]) counter++;\n if (a[(i-1)%n][(j+1)%n]) counter++;\n if (a[i%n][(j+1)%n]) counter++;\n if (a[(i+1)%n][(j+1)%n]) counter++;\n if (a[(i+1)%n][j%n]) counter++;\n if (a[(i+1)%n][(j-1)%n]) counter++;\n if (a[i%n][(j-1)%n]) counter++;\n return counter;\n }\n</code></pre>\n<p>I noticed that there is no need to use <code>%</code> so often, but only when the index oveflows.\nIt can be simplified like this:</p>\n<pre><code>private int countAliveNeighbors(int i, int j) {\n int counter = 0;\n for(int x=i-1 ; x<=i+1; x++) {\n for(int y=j-1; y<=j+1; y++) {\n // Skip given position\n if(x==i && y==j)\n continue;\n if(isAlive(castIndex(x),castIndex(y))) {\n counter++;\n }\n }\n }\n return counter;\n}\n\nprivate boolean isAlive(int i, int j) {\n return grid[i][j];\n}\n\nprivate int castIndex(int i) {\n if(i>=n) return 0;\n return i<0 ? n-1 : i;\n}\n</code></pre>\n<p>Regarding memory, I noticed that there are some initializations that can be avoided like:</p>\n<pre><code>boolean[][] a = new boolean[n][n];\na = randomGridMaker(n, p);\n</code></pre>\n<p>The initialization is already done in the method <code>randomGridMaker</code>, so you can directly have:</p>\n<pre><code>boolean[][] a = randomGridMaker(n, p);\n</code></pre>\n<p>Same for other parts in the code. I will just paste here the code refactored.</p>\n<h2>Refactored code</h2>\n<pre><code>public class GameOfLife {\n \n private boolean[][] grid;\n private int n;\n private double p;\n \n public GameOfLife(int n, double p) {\n grid = new boolean[n][n];\n this.n=n;\n this.p=p;\n }\n \n public void initRandom() {\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n if (Math.random() < p)\n {\n grid[i][j] = true;\n }\n }\n }\n }\n \n private boolean isAlive(int i, int j) {\n return grid[i][j];\n }\n \n private int castIndex(int i) {\n if(i>=n) return 0;\n return i<0 ? n-1 : i;\n }\n \n private int countAliveNeighbors(int i, int j) {\n int counter = 0;\n for(int x=i-1 ; x<=i+1; x++) {\n for(int y=j-1; y<=j+1; y++) {\n // Skip given position\n if(x==i && y==j)\n continue;\n if(isAlive(castIndex(x),castIndex(y))) {\n counter++;\n }\n }\n }\n return counter;\n }\n \n private boolean[][] cloneGrid(){\n boolean[][] b = new boolean[n][n];\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n b[i][j] = grid[i][j];\n }\n }\n return b;\n }\n \n public void update() {\n boolean[][] b = cloneGrid();\n for (int i = 1; i < n; i++)\n {\n for (int j = 1; j < n; j++)\n {\n int liveNeighbors = countAliveNeighbors(i,j);\n if(isAlive(i,j)) {\n if (liveNeighbors == 1 || liveNeighbors > 3) { \n b[i][j] = false;\n }\n } else if (liveNeighbors == 3){\n b[i][j] = true;\n }\n }\n }\n grid=b;\n }\n \n public boolean[][] getGrid(){\n return grid;\n }\n \n public static void drawGrid(boolean[][] a)\n {\n int n = a.length;\n StdDraw.clear();\n StdDraw.setXscale(0,n);\n StdDraw.setYscale(0,n);\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n if (a[i][j]) StdDraw.filledSquare(i+0.5,j+0.5,0.47);\n }\n }\n StdDraw.show();\n }\n public static void main(String[] args)\n {\n if(args.length != 2) {\n System.out.println("Size and probability not provided");\n System.exit(1);\n }\n int n = Integer.parseInt(args[0]);\n double p = Double.parseDouble(args[1]);\n StdDraw.setPenColor(StdDraw.BOOK_BLUE);\n StdDraw.enableDoubleBuffering();\n GameOfLife gol = new GameOfLife(n,p);\n gol.initRandom();\n while (true)\n {\n drawGrid(gol.getGrid());\n StdDraw.pause(100);\n gol.update();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T08:35:53.793",
"Id": "487379",
"Score": "0",
"body": "Thank you very much for your time. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T08:43:25.213",
"Id": "487381",
"Score": "0",
"body": "I try to assimilate all the above information gradually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T15:23:46.573",
"Id": "487435",
"Score": "0",
"body": "@KhashayarBaghizadeh I'm glad I could help ;) Please consider to accept the answer when you are satisfied."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T15:31:04.903",
"Id": "487436",
"Score": "0",
"body": "Of course :) I'm just waiting for a few more hours to see if there could be other suggestions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T00:42:15.850",
"Id": "248741",
"ParentId": "248728",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248741",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T20:36:22.087",
"Id": "248728",
"Score": "6",
"Tags": [
"java",
"beginner",
"game-of-life"
],
"Title": "Simulation of Conway's Game of Life with periodic boundary conditions"
}
|
248728
|
<p>I'm pretty new to algorithms, and it's my first attempt to implement sentinel linear search in JS. I'm wondering if it can be improved.</p>
<pre><code>const array1 = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'cras', 'eu', 'metus', 'volutpat', 'sagittis', 'nunc', 'in', 'porta', 'quam'];
let i = 0;
let x = 'elit';
let n = array1.length;
let last = array1[n - 1];
array1[n - 1] = x;
(function () {
while (array1[i] !== x) {
i++;
if (array1[i] === x) {
array1[n - 1] = last;
if (array1[i] === x) {
return console.log('FOUND ON INDEX', i);
} else {
return console.log('NOT FOUND');
}
}
}
})();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T20:56:17.813",
"Id": "487324",
"Score": "1",
"body": "For those of us that don't know, can you tell us what makes a 'sentinel linear search' special with regards to an ordinary 'linear search'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T20:56:59.503",
"Id": "487325",
"Score": "0",
"body": "Is it related to [this programming challenge](https://www.geeksforgeeks.org/sentinel-linear-search/)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T20:58:34.077",
"Id": "487326",
"Score": "1",
"body": "@Mast Linear search with a sentinel, https://en.wikipedia.org/wiki/Linear_search#With_a_sentinel"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T21:04:29.213",
"Id": "487328",
"Score": "0",
"body": "@Mast no, it's from the book Algorithms Unlocked by Thomas Cormen"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T21:20:39.163",
"Id": "487329",
"Score": "0",
"body": "@Mast basically, we put the value we're searching for into the last position of the array to avoid 2 checks on every iteration of the loop (in `for` loop it's evaluation of the condition expression and execution of the statement, both of which are called on each iteration). After the value is found, we restore the original value of the last position in the array and perform one additional check on the array"
}
] |
[
{
"body": "<p>If the point of the sentinel is to, as the wiki article says:</p>\n<blockquote>\n<p>The basic algorithm above makes two comparisons per iteration: one to check if Li equals T, and the other to check if i still points to a valid index of the list. By adding an extra record Ln to the list (a sentinel value) that equals the target, the second comparison can be eliminated until the end of the search, making the algorithm faster.</p>\n</blockquote>\n<p>Then the approach should be to <em>tack on</em> the value to find onto the end of the array, instead of <em>replacing</em> the last value of the array with the value to find. I guess you <em>can</em> replace the last value, then once a match is found, replace it back, then check it, but that's unnecessarily convoluted.</p>\n<p>Your code has a bug: if the first element of the array is the item to search for, <code>while (array1[i] !== x) {</code> will evaluate to <code>false</code>, and the IIFE will terminate immediately without logging anything.</p>\n<p>That test is superfluous anyway, since inside the loop, the array item will either be found before the end, or at the end - either way, <code>console.log</code> will be called.</p>\n<p>To add an element to the end of an array in JS, it's easier to use <code>push</code>:</p>\n<pre><code>array1.push(x);\n</code></pre>\n<p>You might consider using more precise variable names, to make the code more readable. (I'd avoid using single-letter variable names except maybe for <code>i</code>, which is pretty universally understood to be an index.)</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 linearSearchSentinel = (array, itemToFind) => {\n const { length } = array;\n array.push(itemToFind);\n for (let i = 0;; i++) {\n if (array[i] === itemToFind) {\n array.pop(); // remove the added item from array\n if (i === length) {\n return console.log('NOT FOUND');\n }\n return console.log('FOUND ON INDEX', i);\n }\n }\n};\n\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'foo');\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'baz');\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'nope');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Or, if you wanted to use the <code>while</code> approach, then don't put any testing inside the loop - simply increment the index:</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 linearSearchSentinel = (array, itemToFind) => {\n const { length } = array;\n array.push(itemToFind);\n let i = 0;\n while (array[i] !== itemToFind) i++;\n array.pop(); // remove the added item from array\n if (i === length) {\n return console.log('NOT FOUND');\n }\n console.log('FOUND ON INDEX', i);\n};\n\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'foo');\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'baz');\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'nope');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It's also a good idea to <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">prefer <code>const</code></a> over <code>let</code> when you don't need to reassign the variable name.</p>\n<p>I'd prefer one of the easy-to-understand versions above, but if you really want to avoid changing the length of the array for optimization purposes, I suppose you could replace the last item similar to you're originally doing 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>const linearSearchSentinel = (array, itemToFind) => {\n const { length } = array;\n const lastItem = array[length - 1];\n array[length - 1] = itemToFind;\n let i = 0;\n while (array[i] !== itemToFind) i++;\n array[length - 1] = lastItem;\n console.log(\n (i !== length - 1 || lastItem === itemToFind)\n ? 'FOUND ON INDEX ' + i\n : 'NOT FOUND'\n );\n};\n\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'foo');\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'baz');\nlinearSearchSentinel(['foo', 'bar', 'baz'], 'nope');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This is all for informational purposes only, of course - if you were actually facing a practical problem where you needed to find the index of an element in an array in JavaScript, it would make more sense to use the built-in <code>indexOf</code> method, which would be far faster and easier. Better not to reinvent the wheel unless an assignment like this one requires it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:49:00.890",
"Id": "487357",
"Score": "0",
"body": "By adding en extra record to the array using Array.push you get a nonneglegable increase in runtime for some inputs. Because a push may trigger internal data reallocation and copy which takes O(n) time. Push is only amortized O(1). Typicaly `log2(n) / n` of cases will exhibit the behaviour. Also Array.shift is always O(n) and you should avoid it entirely. Although the algorithm is O(n) either way, it is still a difference if you loop though n elements once and if you do it two or more times. Also pushing and shifting modifies the array which may not be desired to do with a caller provided data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:51:05.753",
"Id": "487358",
"Score": "1",
"body": "Dont take me wrong, but if the point of sentinel linear search is to reduce number of operations, the efforts are all wasted if you loop more then once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:54:44.553",
"Id": "487360",
"Score": "0",
"body": "Oops, yeah, I meant to `.pop()`, not `shift()`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T21:25:15.457",
"Id": "248732",
"ParentId": "248731",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T20:41:04.593",
"Id": "248731",
"Score": "3",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Sentinel linear search"
}
|
248731
|
<p>Trying to come up with a pattern where the code to open db, writing queries is elegant and clean while handling all possible error conditions.</p>
<p>Following code</p>
<pre><code>let file = try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("mydb.db")
var result = sqlite3_open(file.path, &database)
if result == SQLITE_OK {
defer { sqlite3_close(database) }
} else {
print("couldn't open database")
return
}
result = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)", nil, nil, nil)
if result != SQLITE_OK {
print("couldn't insert into department")
return
}
result = sqlite3_exec(database, "INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')", nil, nil, nil)
if result != SQLITE_OK {
print("error inserting")
return
}
</code></pre>
|
[] |
[
{
"body": "<p>A few observations:</p>\n<ol>\n<li><p>The <code>.cachesDirectory</code> is deleted when your device runs low in storage. Are you sure you want to delete your app database in this scenario? Usually we would use <code>.applicationSupportDirectory</code>, which is not deleted when storage runs low and is backed up when you back up your device. But we avoid the use of the <code>.documents</code> folder, because that is reserved for user-facing files.</p>\n<p>Also, we would also generally use use the <code>create</code> option of <code>true</code>.</p>\n</li>\n<li><p>If opening a database failed for any reason, you still need to call <code>sqlite3_close</code>. As <a href=\"https://sqlite.org/c3ref/open.html\" rel=\"nofollow noreferrer\">the documentation</a> says:</p>\n<blockquote>\n<p>Whether or not an error occurs when it is opened, resources associated with the <a href=\"https://sqlite.org/c3ref/sqlite3.html\" rel=\"nofollow noreferrer\">database connection</a> handle should be released by passing it to <a href=\"https://sqlite.org/c3ref/close.html\" rel=\"nofollow noreferrer\"><code>sqlite3_close()</code></a> when it is no longer required.</p>\n</blockquote>\n<p>So I would move the <code>defer</code> out of that <code>if</code> statement. You want to move it out of there, anyway, because <code>defer</code> will run at the end of the current scope (at the end of your <code>if</code> statement in your current implementation), not at the end of the function. But if you move the <code>defer</code> to the right place, that observation is moot.</p>\n</li>\n<li><p>If a SQL statement fails for any reason, if you are going to print an error, you really should include the <code>sqlite3_errmsg</code>. Without that, it will be exceedingly difficult to debug problems.</p>\n</li>\n<li><p>I would generally advise using <code>guard</code> in situations where you want to exit upon failure. The compiler will make sure that you properly <code>return</code> when an error condition occurs.</p>\n<p>So, pulling that together with the above points, you get something like:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let folder = try! FileManager.default\n .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)\n .appendingPathComponent("AppData")\n\ntry? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)\n\nlet fileURL = folder.appendingPathComponent("mydb.db")\n\nvar database: OpaquePointer?\nvar result = sqlite3_open(fileURL.path, &database)\n\ndefer { sqlite3_close(database) }\n\nguard result == SQLITE_OK else {\n printError(in: database, message: "couldn't open database")\n return\n}\n\nresult = sqlite3_exec(database, "CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)", nil, nil, nil)\nguard result == SQLITE_OK else {\n printError(in: database, message: "couldn't insert into department")\n return\n}\n\nresult = sqlite3_exec(database, "INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')", nil, nil, nil)\nguard result == SQLITE_OK else {\n printError(in: database, message: "error inserting")\n return\n}\n</code></pre>\n<p>Where</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func printError(in database: OpaquePointer?, message: String) {\n let error = sqlite3_errmsg(database).flatMap { String(cString: $0) } ?? "Unknown error"\n print(message, error)\n}\n</code></pre>\n</li>\n<li><p>Usually we do not open and close the database with every method call. We generally open the database once, and leave it open. SQLite is very good about committing changes to the file as you go along, so opening and closing the database for every call is a tad inefficient.</p>\n</li>\n<li><p>As a broader observation, I would suggest abstracting the SQLite API from this <code>department</code> related SQL. E.g., perhaps</p>\n<pre class=\"lang-swift prettyprint-override\"><code>do {\n let database = try openDatabase()\n try database.exec("CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)")\n try database.exec("INSERT OR REPLACE INTO department(id, name) VALUES(0, 'HR'), (1, 'Sales'), (2, 'Accounts'), (3, 'Shipping')")\n} catch {\n print(error)\n}\n</code></pre>\n<p>Where:</p>\n<pre><code>func openDatabase() throws -> Database {\n let folder = try! FileManager.default\n .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)\n .appendingPathComponent("AppData")\n\n try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)\n\n let fileURL = folder.appendingPathComponent("mydb.db")\n\n let database = Database(fileURL: fileURL)\n\n try database.open()\n\n return database\n}\n</code></pre>\n<p>Now, the above is using my own personal SQLite database wrapper:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>// Database.swift\n//\n// Created by Robert Ryan on 3/8/19.\n\nimport Foundation\nimport SQLite3\n\nprivate let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)\nprivate let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)\n\n// MARK: - Database\n\n/// Thin wrapper for SQLite C interface\n\npublic class Database {\n // MARK: - Properties\n\n /// The URL for the database\n let fileURL: URL\n\n /// The `sqlite3_open` options\n public var options: OpenOptions\n\n /// A `DateFormatter` for writing dates to the database\n public static var dateFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"\n formatter.timeZone = TimeZone(secondsFromGMT: 0)\n formatter.locale = Locale(identifier: "en_US_POSIX")\n return formatter\n }()\n\n /// The SQLite database pointer\n private var database: OpaquePointer?\n\n /// Array of prepared statements that have not yet been finalized\n private var openStatements: [Statement] = []\n\n // MARK: - Initialization\n\n /// Database initializer\n ///\n /// Note: You must still `open` this database before using it.\n public init(fileURL: URL, options: OpenOptions = .default) {\n self.fileURL = fileURL\n self.options = options\n }\n\n /// Deinitializer that will finalize any open statements and then close the database if not already closed.\n deinit {\n finalizeStatements()\n try? close()\n }\n}\n\n// MARK: - Types\n\npublic extension Database {\n enum DatabaseError: Error {\n case failed(ReturnCode, String)\n case unknownType(Any)\n case notOpened\n case noStatementPrepared\n case closeFailed\n }\n\n struct OpenOptions: OptionSet {\n public let rawValue: Int32\n\n public static let readOnly = OpenOptions(rawValue: SQLITE_OPEN_READONLY)\n public static let readWrite = OpenOptions(rawValue: SQLITE_OPEN_READWRITE)\n public static let create = OpenOptions(rawValue: SQLITE_OPEN_CREATE)\n public static let noMutex = OpenOptions(rawValue: SQLITE_OPEN_NOMUTEX)\n public static let fullMutex = OpenOptions(rawValue: SQLITE_OPEN_FULLMUTEX)\n public static let sharedCache = OpenOptions(rawValue: SQLITE_OPEN_SHAREDCACHE)\n public static let privateCache = OpenOptions(rawValue: SQLITE_OPEN_PRIVATECACHE)\n\n public static let `default`: OpenOptions = [.readWrite, .create]\n\n public init(rawValue: Int32) {\n self.rawValue = rawValue\n }\n }\n\n enum ReturnCode: Equatable {\n // non error codes\n\n case ok\n case done\n case row\n\n // error codes\n\n case auth\n case busy\n case cantOpen\n case constraint\n case corrupt\n case empty\n case error\n case fail\n case format\n case full\n case `internal`\n case interrupt\n case ioerr\n case locked\n case mismatch\n case misuse\n case nolfs\n case nomem\n case notadb\n case notfound\n case notice\n case perm\n case `protocol`\n case range\n case readonly\n case schema\n case toobig\n case warning\n\n case unknown(Int32)\n\n static func code(for code: Int32) -> ReturnCode {\n switch code {\n case SQLITE_OK: return .ok\n case SQLITE_DONE: return .done\n case SQLITE_ROW: return .row\n\n case SQLITE_AUTH: return .auth\n case SQLITE_BUSY: return .busy\n case SQLITE_CANTOPEN: return .cantOpen\n case SQLITE_CONSTRAINT: return .constraint\n case SQLITE_CORRUPT: return .corrupt\n case SQLITE_EMPTY: return .empty\n case SQLITE_ERROR: return .error\n case SQLITE_FAIL: return .fail\n case SQLITE_FORMAT: return .format\n case SQLITE_FULL: return .full\n case SQLITE_INTERNAL: return .internal\n case SQLITE_INTERRUPT: return .interrupt\n case SQLITE_IOERR: return .ioerr\n case SQLITE_LOCKED: return .locked\n case SQLITE_MISMATCH: return .mismatch\n case SQLITE_MISUSE: return .misuse\n case SQLITE_NOLFS: return .nolfs\n case SQLITE_NOMEM: return .nomem\n case SQLITE_NOTADB: return .notadb\n case SQLITE_NOTFOUND: return .notfound\n case SQLITE_NOTICE: return .notice\n case SQLITE_PERM: return .perm\n case SQLITE_PROTOCOL: return .protocol\n case SQLITE_RANGE: return .range\n case SQLITE_READONLY: return .readonly\n case SQLITE_SCHEMA: return .schema\n case SQLITE_TOOBIG: return .toobig\n case SQLITE_WARNING: return .warning\n\n default: return .unknown(code)\n }\n }\n }\n}\n\n// MARK: - Public methods\n\npublic extension Database {\n /// Open database\n func open() throws {\n do {\n try call { sqlite3_open_v2(fileURL.path, &database, options.rawValue, nil) }\n } catch {\n try? close()\n throw error\n }\n }\n\n /// Close database\n func close() throws {\n if database == nil { return }\n finalizeStatements()\n try call {\n defer { database = nil }\n return sqlite3_close(database)\n }\n }\n\n /// Execute statement\n ///\n /// - Parameter sql: SQL to be performed.\n /// - Throws: SQLite errors.\n func exec(_ sql: String) throws {\n guard database != nil else { throw DatabaseError.notOpened }\n\n try call { sqlite3_exec(database, sql, nil, nil, nil) }\n }\n\n\n /// Prepare SQL\n ///\n /// - Parameters:\n /// - sql: SQL to be prepared\n /// - parameters: Any parameters to be bound to any `?` in the SQL.\n /// - Returns: The prepared statement.\n /// - Throws: SQLite errors.\n func prepare(_ sql: String, parameters: [DatabaseBindable?]? = nil) throws -> Statement {\n guard database != nil else { throw DatabaseError.notOpened }\n\n var stmt: OpaquePointer?\n\n try call { sqlite3_prepare_v2(database, sql, -1, &stmt, nil) }\n\n let statement = Statement(database: self, statement: stmt!)\n\n openStatements.append(statement)\n\n try statement.bind(parameters)\n\n return statement\n }\n\n /// The `rowid` of the last row inserted\n ///\n /// - Returns: The `rowid`.\n func lastRowId() -> Int64 {\n sqlite3_last_insert_rowid(database)\n }\n\n /// Returns number of rows changed by last `INSERT`, `UPDATE`, or `DELETE` statement.\n ///\n /// - Returns: Number of rows changed.\n func changes() -> Int32 {\n sqlite3_changes(database)\n }\n\n /// Returns number of rows changed `INSERT`, `UPDATE`, or `DELETE` statements since the database was opened.\n ///\n /// - Returns: Number of rows changed.\n func totalChanges() -> Int32 {\n sqlite3_total_changes(database)\n }\n\n /// Finalize a previously prepared statement\n ///\n /// - Parameter statement: The previously prepared statement.\n /// - Throws: SQLite error.\n func finalize(_ statement: Statement) throws {\n guard let index = openStatements.firstIndex(where: { $0.sqlite3_stmt == statement.sqlite3_stmt }) else {\n return\n }\n\n openStatements.remove(at: index)\n\n try call {\n defer { statement.sqlite3_stmt = nil }\n return sqlite3_finalize(statement.sqlite3_stmt)\n }\n }\n\n /// The version of SQLite being used.\n ///\n /// - Returns: Version string.\n func version() -> String? {\n sqlite3_libversion()\n .flatMap { String(cString: $0) }\n }\n}\n\n// MARK: Private methods\n\nfileprivate extension Database {\n /// Call block containing SQLite C function\n ///\n /// - Parameter block: Block that returns value from SQLite C function.\n /// - Returns: Returns return value from that C function if it returned `.ok`, `.done`, or `.row`.\n /// - Throws: SQLite error.\n @discardableResult\n func call(block: () -> (Int32)) throws -> Database.ReturnCode {\n let result = Database.ReturnCode.code(for: block())\n switch result {\n case .ok, .done, .row:\n return result\n\n default:\n let message = String(cString: sqlite3_errmsg(database))\n throw DatabaseError.failed(result, message)\n }\n }\n\n /// Finalize all open statements (those prepared but not yet finalized).\n func finalizeStatements() {\n for statement in openStatements {\n try? finalize(statement)\n }\n }\n}\n\n// MARK: - Statement\n\n/// SQLite statement.\npublic class Statement {\n public fileprivate(set) var sqlite3_stmt: OpaquePointer?\n private weak var database: Database?\n\n init(database: Database, statement: OpaquePointer) {\n self.database = database\n self.sqlite3_stmt = statement\n }\n\n deinit {\n try? database?.finalize(self)\n }\n}\n\n// MARK: Public methods\n\npublic extension Statement {\n /// Bind array of parameters to `?` placeholders in SQL\n ///\n /// - Parameter parameters: The array of parameters.\n /// - Throws: SQLite error.\n func bind(_ parameters: [DatabaseBindable?]?) throws {\n try parameters?.enumerated().forEach { index, value in\n let offset = Int32(index + 1)\n if let value = value {\n try database?.call { value.bind(to: self, offset: offset) }\n } else {\n try database?.call { sqlite3_bind_null(sqlite3_stmt, offset) }\n }\n }\n }\n\n @discardableResult\n /// Perform the prepared statement.\n ///\n /// - Returns: The return code if `.done`, `.row` (or `.ok`, which it never can be).\n /// - Throws: The SQLite error if return code is not one of the aforementioned values.\n func step() throws -> Database.ReturnCode {\n guard\n let database = database,\n let statement = sqlite3_stmt\n else {\n throw Database.DatabaseError.notOpened\n }\n\n return try database.call { sqlite3_step(statement) }\n }\n\n /// Reset the values bound to this prepared statement.\n ///\n /// Used if you want to bind new values and perform the statement again without re-preparing it.\n ///\n /// - Throws: SQLite error.\n func reset() throws {\n guard let database = database,\n let statement = sqlite3_stmt else { throw Database.DatabaseError.notOpened }\n\n try database.call { sqlite3_reset(statement) }\n }\n\n /// Determines if the particular column value is `NULL` or not.\n ///\n /// - Parameter index: The column index number.\n func isNull(index: Int32) -> Bool {\n sqlite3_column_type(sqlite3_stmt, index) == SQLITE_NULL\n }\n\n /// Retrieve the value returned for a column of the particular `index`.\n ///\n /// - Parameters:\n /// - type: The type to be returned for the column (e.g. `Int.self`).\n /// - index: The zero-based column index number.\n /// - Returns: Returns the value found at the specified column index. If the value cannot be converted to that type, it will return `nil`.\n /// - Throws: The SQLite error if return code is not one of the aforementioned values.\n func column<T: DatabaseBindable>(_ type: T.Type, index: Int32) -> T? {\n T(from: self, index: index)\n }\n\n /// Retrieve the name of the column of the particular `index`.\n ///\n /// - Parameter index: The zero-based column index number.\n /// - Returns: The name of the column or `nil` if it couldn't determine the name.\n func columnName(index: Int32) -> String? {\n sqlite3_column_name(sqlite3_stmt, index)\n .flatMap { String(cString: $0) }\n }\n\n /// Retrieve the origin name of the column of the particular `index`.\n ///\n /// - Parameter index: The zero-based column index number.\n /// - Returns: The name of the column or `nil` if it couldn't determine the name.\n func columnOriginName(index: Int32) -> String? {\n sqlite3_column_origin_name(sqlite3_stmt, index)\n .flatMap { String(cString: $0) }\n }\n\n /// Retrieve the name of the table associated with the column of the particular `index`.\n ///\n /// - Parameter index: The zero-based column index number.\n /// - Returns: The name of the column or `nil` if it couldn't determine the name.\n func columnTableName(index: Int32) -> String? {\n sqlite3_column_table_name(sqlite3_stmt, index)\n .flatMap { String(cString: $0) }\n }\n\n /// Retrieve the name of the table associated with the column of the particular `index`.\n ///\n /// - Parameter index: The zero-based column index number.\n /// - Returns: The name of the column or `nil` if it couldn't determine the name.\n func columnDatabaseName(index: Int32) -> String? {\n sqlite3_column_database_name(sqlite3_stmt, index)\n .flatMap { String(cString: $0) }\n }\n}\n\n// MARK: - Data binding protocol\n\npublic protocol DatabaseBindable {\n /// Initializer used when returning value from result set of performed SQL `SELECT` statement.\n ///\n /// - Parameters:\n /// - statement: The prepared and performed SQLite statement.\n /// - index: The 0-based index for the column being returned.\n init?(from statement: Statement, index: Int32)\n\n /// When binding a value to a prepared (but not yet performed) SQL statement.\n ///\n /// - Parameters:\n /// - statement: The prepared SQLite statement to be performed.\n /// - offset: the 1-based index for the column being bound.\n /// - Returns: The SQLite return code.\n func bind(to statement: Statement, offset: Int32) -> Int32\n}\n\n// MARK: Specific type conformances\n\nextension String: DatabaseBindable {\n public init?(from statement: Statement, index: Int32) {\n guard !statement.isNull(index: index), let pointer = sqlite3_column_text(statement.sqlite3_stmt, index) else { return nil }\n self = String(cString: pointer)\n }\n\n public func bind(to statement: Statement, offset: Int32) -> Int32 {\n sqlite3_bind_text(statement.sqlite3_stmt, offset, cString(using: .utf8), -1, SQLITE_TRANSIENT)\n }\n}\n\nextension Decimal: DatabaseBindable {\n public init?(from statement: Statement, index: Int32) {\n guard\n !statement.isNull(index: index),\n let string = String(from: statement, index: index),\n let value = Decimal(string: string, locale: Locale(identifier: "en_US_POSIX")) else { return nil }\n self = value\n }\n\n public func bind(to statement: Statement, offset: Int32) -> Int32 {\n var value = self\n let string = NSDecimalString(&value, Locale(identifier: "en_US_POSIX"))\n return sqlite3_bind_text(statement.sqlite3_stmt, offset, string.cString(using: .utf8), -1, SQLITE_TRANSIENT)\n }\n}\n\nextension IntegerLiteralType: DatabaseBindable {\n public init?(from statement: Statement, index: Int32) {\n guard !statement.isNull(index: index) else { return nil }\n let value = sqlite3_column_int64(statement.sqlite3_stmt, index)\n self = .init(value)\n }\n\n public func bind(to statement: Statement, offset: Int32) -> Int32 {\n sqlite3_bind_int64(statement.sqlite3_stmt, offset, Int64(self))\n }\n}\n\nextension BinaryFloatingPoint {\n public init?(from statement: Statement, index: Int32) {\n guard !statement.isNull(index: index) else { return nil }\n self = Self(sqlite3_column_double(statement.sqlite3_stmt, index))\n }\n\n public func bind(to statement: Statement, offset: Int32) -> Int32 {\n sqlite3_bind_double(statement.sqlite3_stmt, offset, Double(self))\n }\n}\n\nextension Data: DatabaseBindable {\n public init?(from statement: Statement, index: Int32) {\n guard !statement.isNull(index: index) else { return nil }\n\n let count = sqlite3_column_bytes(statement.sqlite3_stmt, index)\n if count == 0 { return nil }\n\n guard let bytes = sqlite3_column_blob(statement.sqlite3_stmt, index) else { return nil }\n self = Data(bytes: bytes, count: Int(count))\n }\n\n public func bind(to statement: Statement, offset: Int32) -> Int32 {\n withUnsafeBytes { pointer in\n let bytes = pointer.baseAddress\n return sqlite3_bind_blob(statement.sqlite3_stmt, offset, bytes, Int32(count), SQLITE_TRANSIENT)\n }\n }\n}\n\nextension Date: DatabaseBindable {\n public init?(from statement: Statement, index: Int32) {\n guard\n !statement.isNull(index: index),\n let pointer = sqlite3_column_text(statement.sqlite3_stmt, index) else { return nil }\n\n let string = String(cString: pointer)\n guard let date = Database.dateFormatter.date(from: string) else { return nil }\n\n self = date\n }\n\n public func bind(to statement: Statement, offset: Int32) -> Int32 {\n let string = Database.dateFormatter.string(from: self)\n return sqlite3_bind_text(statement.sqlite3_stmt, offset, string.cString(using: .utf8), -1, SQLITE_TRANSIENT)\n }\n}\n</code></pre>\n<p>Now, that is my personal thin wrapper around the SQLite API, but there are lots of them out there and you probably want to find one that is publicly supported. Or roll your own. But I would advise abstracting the SQLite code away from your app-specific SQL.</p>\n<p>Even if you do this (using my wrapper, your own, or some established third-party wrapper), I'd also abstract the “department” repository code out in its own controller. You do not want to entangle your model object and general controller code with any particular storage mechanism. You should be able to change your database API at a future date without impacting your app-specific logic.</p>\n</li>\n<li><p>When inserting into a database, we often would avoid using string interpolation, but rather bind values to <code>?</code> placeholders in our SQL using <a href=\"https://sqlite.org/c3ref/bind_blob.html\" rel=\"nofollow noreferrer\"><code>sqlite3_bind_xxx()</code></a>. Or, using the above SQLite wrapper:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>do {\n let database = try openDatabase()\n try database.exec("CREATE TABLE IF NOT EXISTS department(id INTEGER PRIMARY KEY, name TEXT NOT NULL)")\n let statement = try database.prepare("INSERT OR REPLACE INTO department(id, name) VALUES (?, ?)")\n for (id, string) in [(5, "Bob's Department"), (6, "Susan's Department")] {\n try statement.bind([id, string])\n try statement.step()\n try statement.reset()\n }\n} catch {\n print(error)\n}\n</code></pre>\n<p>This gets us out of worrying about the presence of apostrophes or other SQLite reserved string literals in our SQL. In the case of this fixed list of departments, it is not much of an issue, but if you start inserting values supplied by the end user, making sure that values are inserted correctly with <a href=\"https://sqlite.org/c3ref/bind_blob.html\" rel=\"nofollow noreferrer\"><code>sqlite3_bind_xxx()</code></a> functions and <code>?</code> placeholders in your SQL.</p>\n</li>\n<li><p>Personally, I would not just open a database with <code>sqlite3_open</code>.</p>\n<ul>\n<li>I would use <code>sqlite3_open_v2</code> with the <code>SQLITE_OPEN_READWRITE</code> option (or the <code>.readWrite</code> option in my wrapper), but <em>not</em> the <code>SQLITE_OPEN_CREATE</code> option (or my <code>.create</code> option).</li>\n<li>If open failed, then I would go through the creation process (creating tables, populating them, etc.; or frequently I would put an initialized database in my bundle, and if opening in app support directory failed, then I'd copy from the bundle to app support directory and then open again).</li>\n</ul>\n<p>In your simple example, it is not terribly relevant, but as the app/db grows in complexity, you may want to avoid having to write a ton of “create and populate the database” code. It is convenient to have a saved “initial state” database ready and waiting in the bundle. It is your call, though, but just a recommendation.</p>\n<p>Either way, it is often preferable to avoiding <code>sqlite3_open</code>, which silently creates a database if it is not there, but use <code>sqlite3_open_v2</code> without the “create” option, and use the success or failure of that to determine whether you need to initialize the database or not.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T09:21:18.600",
"Id": "501072",
"Score": "1",
"body": "Excellent answer (as always)!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-28T07:13:38.117",
"Id": "253989",
"ParentId": "248736",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T22:58:07.283",
"Id": "248736",
"Score": "1",
"Tags": [
"c",
"swift",
"ios",
"sqlite"
],
"Title": "Improving sqlite3 code in swift using c api"
}
|
248736
|
<p>I've recently reviewed code twice, from two different authors, where the author has cleverly used <code>Thingy z = Optional.ofNullable(x).orElse(y)</code> rather than using, say, <code>Thingy z = x == null ? y : x</code>.</p>
<p>My first reaction was that this is not the intended use or semantic of Optional and that a ternary conditional operator, or even just an if-else, would be better.</p>
<p>But the more I look at it, there is a beauty and a fluidity to <code>Thingy z = Optional.ofNullable(x).orElse(y)</code> which makes sense. To be honest, I've actually never loved the conditional operator.</p>
<p>Thoughts?</p>
|
[] |
[
{
"body": "<p>I consider it more as a preference or inclination for Java features.</p>\n<p>I mean, calling <code>ofNullable</code> has a time and space cost (passing params by copy + internal execution) same as <code>orElse</code>, it is a bit more than the ternary, secondly, the ternary is qute compact and if in some sense harder to read than <code>Optional...</code> it is clear which is your intent.</p>\n<p>Trying to be objective (if possible)</p>\n<ul>\n<li>Optional is in general more readable (not all of us are familiar with the ternary)</li>\n<li>It depends on your likes</li>\n<li>If efficiency is needed, well I consider there are better options than Java, and also some integrations with other technologies are also to be taken into account.</li>\n</ul>\n<p>I hope it helped you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:37:38.137",
"Id": "487355",
"Score": "3",
"body": "This answer is quite subjective. And no wonder, the OP's question tends to generate opinion based answers. You should avoid making opinion based answers. What more, the OP's question is hypothetical, thus off topic and you should not answer off topic questions at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T05:44:31.570",
"Id": "487365",
"Score": "1",
"body": "Going along with what @slepic stated, [Please refrain from answering questions that are likely to get closed.](https://codereview.meta.stackexchange.com/a/6389/35991). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T06:41:24.653",
"Id": "487368",
"Score": "2",
"body": "Well it's something that's come up twice in professional code reviews. I have debated it with a colleague and searched the internets. This seems like the best forum to sort out the possibilities. I'm happy to take the question elsewhere."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T01:55:09.653",
"Id": "248743",
"ParentId": "248738",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T23:56:34.653",
"Id": "248738",
"Score": "-1",
"Tags": [
"java",
"optional"
],
"Title": "Using Java Optional.ofNullable() instead of if/else or ternary conditional"
}
|
248738
|
<p>I'm currently writing on a Router for a MVC framework that will be the core part of my application. The Router is implemented as a Servlet to be registered on any embedded servlet container. In the Router I'm matching the route using the URI given by <code>HttpServletRequest#getPathInfo</code> but later I'm registering the route into a central path registry so that every part of the application can find a route by matching a uri, but the problem here is that the Router is aware of the Context Path and <code>getPathInfo</code> already hides the Context Path. But the Path Registry is not aware of the context paths and any other part of the application might get into problems when trying to match a uri with Context Path. So, I'm thinking if it might be a better idea to use <code>HttpServletRequest#getRequestURI</code>.</p>
<p>The Routers important source code:</p>
<pre class="lang-java prettyprint-override"><code>/**
* Main method for the Router to be called when a route is accessed
* @throws IOException
* @throws ServletException
*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
String url = req.getPathInfo();
List<String> acceptHeaders = StringUtil.parseAcceptHeader(req.getHeader("Accept") == null ? "" : req.getHeader("Accept"));
Route route = null;
RouteQuery query = RouteQuery.of(url).method(req.getMethod()).accepts(req.getContentType());
if(!acceptHeaders.isEmpty()) {
for(String acceptHeader : acceptHeaders) {
query.produces(acceptHeader);
route = this.getRouteByURL(query);
if(route != null) {
break;
}
}
} else {
route = this.getRouteByURL(query);
}
if(route == null) {
String failureReason = this.getFailureReason(query);
switch(failureReason) {
case "URL_NOT_MATCHING":
res.sendError(HttpStatus.NOT_FOUND_404, "The request url <b>" + req.getRequestURI() + "</b> was not found.");
return;
case "METHOD_NOT_MATCHING":
res.sendError(HttpStatus.METHOD_NOT_ALLOWED_405, "The method " + query.method() + " is not allowed for the path <b>" + req.getRequestURI() + "</b>.");
return;
case "PRODUCES_NOT_MATCHING":
res.sendError(HttpStatus.BAD_REQUEST_400, "The Accept-Headers are not allowed for <b>" + req.getRequestURI() + "</b>.");
return;
case "ACCEPTS_NOT_MATCHING":
res.sendError(HttpStatus.BAD_REQUEST_400, "Request Content-Type is not allowed");
return;
default:
res.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Unknown error occured while searching routes");
return;
}
}
Map<RequestParameter, String> params = this.pathResolver.resolvePathParameters(
route.getCompiledPathSpec(),
route.getParameters().keySet().toArray(new RequestParameter[route.getParameters().size()]),
url);
try {
Result result = route.execute(req, res, params);
if(result.redirect().isPresent()) {
res.sendRedirect(result.redirect().get());
return;
}
if(result.status() > 399) {
if(result.statusMessage().isPresent()) {
res.sendError(result.status(), result.statusMessage().get());
} else {
res.sendError(result.status());
}
return;
}
if(result.contentType().equalsIgnoreCase("application/json")) {
result.content(NightWeb.getGson().toJson(result.data()));
}
res.setStatus(result.status());
res.setContentType(result.contentType());
res.setCharacterEncoding(result.characterEncoding());
res.getWriter().write(result.content());
result.cookies().forEach(cookie -> res.addCookie(cookie));
result.headers().forEach((name, value) -> res.addHeader(name, value));
} catch (ServletException e) {
if(e.getCause() instanceof IllegalAccessException) {
InvokedRoute invokedRoute = (InvokedRoute) route;
LOGGER.error("Unable to access method " + route.getController().getClass().getCanonicalName() + "." + invokedRoute.getUnderlyingMethodName() + " - maybe it is private or not exported?");
} else {
throw e;
}
}
}
@Override
public void addRoute(Method method, Controller controller) {
MethodHolder holder = new MethodHolder(this.ctx, method, controller);
Path pathAnnotation = method.getAnnotation(Path.class);
if(pathAnnotation == null) {
LOGGER.debug("path annotation not present on "
+ method.getName()
+ "(" + String.join(",", Arrays.stream(method.getParameters()).map(param -> param.getType().getName() + " " + param.getName()).toArray(String[]::new)));
return;
}
Path controllerPath = controller.getClass().getAnnotation(Path.class);
holder.setPathSpec(StringUtil.filterURL((controllerPath == null ? "" : controllerPath.value()) + pathAnnotation.value()));
holder.setCompiledPathSpec(this.pathResolver.compilePathSpec(pathAnnotation.value()));
dev.teamnight.nightweb.core.mvc.annotations.Method methodAnnotation = method.getAnnotation(dev.teamnight.nightweb.core.mvc.annotations.Method.class);
if(methodAnnotation != null) {
holder.setHttpMethod(methodAnnotation.value());
}
if(holder.getHttpMethod() == null) {
GET getAnnotation = method.getAnnotation(GET.class);
if(getAnnotation != null) {
holder.setHttpMethod("GET");
} else {
POST postAnnoation = method.getAnnotation(POST.class);
if(postAnnoation != null) {
holder.setHttpMethod("POST");
} else {
throw new IllegalArgumentException("no GET, POST or Method annotation present on " + method.toGenericString());
}
}
}
Accepts acceptsAnnotation = method.getAnnotation(Accepts.class);
if(acceptsAnnotation != null) {
holder.setAccepts(acceptsAnnotation.value());
}
Produces producesAnnotation = method.getAnnotation(Produces.class);
if(producesAnnotation != null) {
holder.setProduces(producesAnnotation.value());
}
Map<RequestParameter, Integer> parametersMap = new HashMap<RequestParameter, Integer>();
int i = 0;
for(Parameter param : method.getParameters()) {
if(param.getType() == HttpServletRequest.class) {
holder.setPosReq(i++);
continue;
} else if(param.getType() == HttpServletResponse.class) {
holder.setPosRes(i++);
continue;
} else if(Context.class.isAssignableFrom(param.getType())) {
holder.setPosCtx(i++);
continue;
} else if(param.getType() == Map.class) {
holder.setPosParamMap(i++);
continue;
}
PathParam pathParam = param.getAnnotation(PathParam.class);
if(pathParam != null) {
parametersMap.put(new RequestParameter(true, pathParam.value()), i++);
continue;
}
QueryParam queryParam = param.getAnnotation(QueryParam.class);
if(queryParam != null) {
parametersMap.put(new RequestParameter(false, queryParam.value()), i++);
}
throw new IllegalArgumentException("Method has unallowed parameter " + param.getName());
}
holder.setParameters(parametersMap);
this.addRoute(holder);
}
@Override
public Route getRouteByURL(RouteQuery query) {
return this.routes.stream()
.filter(h -> h.getCompiledPathSpec().matcher(query.url()).matches())
.filter(h -> h.getHttpMethod().equalsIgnoreCase(query.method()))
.filter(h -> {
if(query.produces().isPresent()) {
return h.getProduces().equalsIgnoreCase(query.produces().get());
} else {
return h.getProduces().equalsIgnoreCase("text/html");
}
})
.filter(h -> {
if(h.getAccepts().isPresent()) {
if(query.accepts().isPresent()) {
return query.accepts().get().equalsIgnoreCase(h.getAccepts().get());
} else {
return false;
}
} else {
return true;
}
})
.findFirst()
.orElse(null);
}
</code></pre>
<p>The interface of the Path Registry, as I did not implement it yet, thinking of the problem above:</p>
<pre class="lang-java prettyprint-override"><code> /**
* Matches a route using a given request uri.
*
* @param uri the URI
* @return {@link dev.teamnight.nightweb.core.mvc.Route} the route or {@code null}
*/
public Route matchRoute(String uri);
</code></pre>
<p>The code is also accessible at GitHub, if you need this to answer my question <a href="https://github.com/TeamNight/NightWeb/blob/master/NightWeb-Core/src/main/java/dev/teamnight/nightweb/core/impl/ServletRouterImpl.java" rel="nofollow noreferrer">https://github.com/TeamNight/NightWeb/blob/master/NightWeb-Core/src/main/java/dev/teamnight/nightweb/core/impl/ServletRouterImpl.java</a></p>
<p>Thanks for helping</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T00:33:59.270",
"Id": "248739",
"Score": "1",
"Tags": [
"java",
"mvc",
"url-routing"
],
"Title": "Using HttpServletRequest#getPathInfo or getRequestURI for matching routes in a Router"
}
|
248739
|
<p>Here's a <code>constexpr</code> hash function, that will pack a string into the largest unsigned integral type available. So, what do you think?</p>
<pre><code>#include <climits>
#include <cstdint>
#include <utility>
#include <iostream>
namespace detail
{
template <typename T, std::size_t ...I>
constexpr T hash(char const* const s, std::size_t const N,
std::index_sequence<I...>) noexcept
{
return ((T(s[I < N ? I : 0]) << ((I < N ? I : 0) * CHAR_BIT)) | ...);
}
}
template <typename T = std::uintmax_t>
constexpr T hash(char const* const s, std::size_t const N) noexcept
{
return detail::hash<T>(s, N, std::make_index_sequence<sizeof(T)>());
}
template <typename T = std::uintmax_t, std::size_t N>
constexpr T hash(char const(&s)[N]) noexcept
{
return hash<T>(s, N - 1);
}
int main()
{
std::cout << (hash("a") == 'a') << std::endl;
return 0;
}
</code></pre>
<p><a href="https://wandbox.org/permlink/KbPiWJc434xYLL3q" rel="nofollow noreferrer">https://wandbox.org/permlink/KbPiWJc434xYLL3q</a></p>
|
[] |
[
{
"body": "<p>Your code is too complex. With C++17, you can write more complex constexpr functions, so you don't need the variadic template tricks:</p>\n<pre><code>template <typename T = std::uintmax_t, std::size_t N>\nconstexpr T hash(char const(&s)[N]) noexcept\n{\n T val{};\n\n for (size_t i = 0; i < N; ++i)\n val |= s[i] << (i * CHAR_BIT);\n\n return val;\n}\n</code></pre>\n<p>Apart from that, this is a terrible hash function! The output is highly correlated to the input. It will also only hash up to <code>sizeof(T)</code> characters, so long strings with a common prefix might all get the same hash value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:01:57.223",
"Id": "487449",
"Score": "0",
"body": "take one more look at the code, what does `std::make_index_sequence<sizeof(T)>()` do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:19:29.900",
"Id": "487451",
"Score": "0",
"body": "Ah, missed that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:26:28.007",
"Id": "487453",
"Score": "0",
"body": "The whole idea was to implement a perfect hash for small strings. We are going 128-bit, so it might not be such a bad idea. Even now, it's possible to enable a 128-bit uint by using `-std=gnu++17` That's 16 chars."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:33:02.937",
"Id": "487454",
"Score": "0",
"body": "+ even though they are not supposed to, looping `constexpr` functions tend to produce worse code than non-looping ones, when evaluated at run-time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T20:26:20.750",
"Id": "487457",
"Score": "1",
"body": "Can you clarify in your question what the use case is of this hash function? Because I don't see the point in what basically is a `memcpy()` from a string into a suitably large `int`. I wouldn't call it hashing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T20:56:37.553",
"Id": "487460",
"Score": "0",
"body": "@Sliepen just avoiding a large chain of `if` comparisons or having to use a recognizer. Now, a `memcpy` in a `constexpr` is not possible yet and technically it is hashing, how else would I call it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T21:26:35.810",
"Id": "487461",
"Score": "2",
"body": "How oes this help you avoid a chain of if-comparisons? Please give a *concrete* example of how you intend to use this hash function."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T17:44:50.917",
"Id": "248775",
"ParentId": "248744",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T02:14:14.980",
"Id": "248744",
"Score": "2",
"Tags": [
"c++",
"c++17",
"hashcode",
"constant-expression"
],
"Title": "constexpr hash function"
}
|
248744
|
<p>I'm a chemistry student working on a simple bash script to automate HPC density functional theory calculations using Quantum Espresso (pw.x). I am very much a novice at shell scripting and would appreciate some criticism/feedback before I try to implement it on the cluster. The script calls in-gen.py which is a Python script I wrote for generating new input files if certain parameter thresholds in the log file are not met.</p>
<pre><code>#!/bin/bash
#SBATCH --job-name=2x2x6_PbCO3 # job name
#SBATCH --output=slurm.out # Output file name
#SBATCH --error=slurm.err # Error file name
#SBATCH --partition=batch # Partition
#SBATCH --qos=medium+ # Queue
#SBATCH --time=24:00:00 # Time limit
#SBATCH --nodes=3 # Number of nodes
#SBATCH --ntasks-per-node=16 # MPI processes per node
errors='MPI_ABORT|error|aborted|SIGTERM|TIME|CANCELLED|SIGCONT|terminated|fork'
job='2x2x6_PbCO3'
max_runs=5
prefix=PbCO3
#-------------------------------------------------------------------------------
Clear ()
{
# Checks for input/log from a completed batch script
if [[ -f "$prefix.in" && -f "$prefix.log" ]]; then
# If both are found a new input file is generated
python ~/path-to-in-gen.py $prefix.log $prefix.in $job override
if [ -z "$(ls -A ../logs_and_inputs)" ]; then
index=1
else
indices=()
# Old input/log are tagged and stored
for entry in "../logs_and_inputs"/$prefix.in-*; do
indices+=("${entry: -1}")
done
max=${indices[0]}
for n in "${indices[@]}" ; do
((n > max)) && max=$n
done
index=$((max+1))
rm -r *x*x*
mv $prefix.in ../logs_and_inputs/$prefix.in-$index
mv $prefix.log ../logs_and_inputs/$prefix.log-$index
mv $prefix.in-new $prefix.in
fi
fi
}
#-------------------------------------------------------------------------------
# Creates a directory for old logs and inputs to be stored with a numerical tag from 1 to k
Sort ()
{
if [ ! -d "../logs_and_inputs" ]; then
mkdir ../logs_and_inputs
iter=1
else
if [ -z "$(ls -A ../logs_and_inputs)" ]; then
iter=1
else
indices=()
for entry in "../logs_and_inputs"/$prefix.in-*; do
indices+=("${entry: -1}")
done
max=${indices[0]}
for n in "${indices[@]}" ; do
((n > max)) && max=$n
done
iter=$((max+1))
fi
fi
max_iter=$((iter+max_runs))
}
#-------------------------------------------------------------------------------
Automode ()
{
mpirun ~/path-to-pw.x < $prefix.in > $prefix.log
# Runs pw.x job, checks for completion and errors
if grep -E -q -- $errors "slurm.err"; then
exit 1
fi
if grep -q "job DONE." "$prefix.log"; then
# Clear wavefunction files and temp directories
rm -r *x*x*
# Generates new input file
python ~/path-to-in-gen.py $prefix.log $prefix.in $job
# Tags and stores the previous input and log
mv $prefix.in ../logs_and_inputs/$prefix.in-$iter
mv $prefix.log ../logs_and_inputs/$prefix.log-$iter
else
exit 1
fi
# Checks for generation of new input file
if test -f "$prefix.in-new"; then
mv $prefix.in-new $prefix.in
else
exit 1
fi
let "iter=iter+1"
}
#-------------------------------------------------------------------------------
Clear
Sort
while ((iter < max_iter)); do
Automode
done
</code></pre>
|
[] |
[
{
"body": "<p>Specific suggestions:</p>\n<ol>\n<li>Function names are by convention <code>snake_case</code>.</li>\n<li><a href=\"https://mywiki.wooledge.org/Quotes\" rel=\"nofollow noreferrer\">Use More Quotes™</a>.</li>\n<li><a href=\"https://mywiki.wooledge.org/BashGuide/TestsAndConditionals\" rel=\"nofollow noreferrer\"><code>[[</code> should be used instead of <code>[</code></a>, because it's safer.</li>\n<li><code>[[ EXPRESSION ]] && [[ EXPRESSION ]]</code> would be clearer than <code>[[ EXPRESSION && EXPRESSION ]]</code>, in my opinion.</li>\n<li><code>set -o errexit -o noclobber -o nounset -o pipefail</code> and <code>shopt -s globfail</code> would make the error handling much stricter.</li>\n<li>This is no longer trivial code, so I'd recommend implementing it in a non-shell language like Python.</li>\n</ol>\n<p>Tool suggestions:</p>\n<ol>\n<li>Running <code>shellcheck</code> on your script regularly is a good way to capture possible issues. In this case the only thing it finds is for <code>rm -r *x*x*</code>:\n<blockquote>\n<p>SC2035: Use ./<em>glob</em> or -- <em>glob</em> so names with dashes won't become options.</p>\n</blockquote>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T03:25:04.687",
"Id": "487344",
"Score": "0",
"body": "Thank you for pointing these issues out. Where would I use `[[ -e PATH ]]` in this script? In place of `[ ! -d \"../logs_and_inputs\" ]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T03:28:16.133",
"Id": "487345",
"Score": "1",
"body": "Clarified, cheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T03:38:19.397",
"Id": "487348",
"Score": "1",
"body": "I may be misunderstanding, but I used `[ -z \"$(ls -A ../logs_and_inputs)\" ]` for the scenario where `../logs_and_inputs` already existed, but was an empty directory, in which case we start with `iter=1` for the input/log tags"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T03:44:39.370",
"Id": "487350",
"Score": "1",
"body": "Ah, [this one](https://superuser.com/a/352290/2259)? Ok, that actually looks like a legit use of `ls` in a script, the first one I've seen so far. Removed that line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:01:50.310",
"Id": "487352",
"Score": "1",
"body": "Will implement all suggestions aside from 6, which I will read up on how to do before attempting. Much appreciated."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T03:02:08.510",
"Id": "248746",
"ParentId": "248745",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248746",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T02:34:42.923",
"Id": "248745",
"Score": "3",
"Tags": [
"bash",
"linux",
"mpi"
],
"Title": "Bash script for automating HPC calculations"
}
|
248745
|
<p>I'm a total noob to OpenGL just following the tutorial at learnopengl.com. Anyway, I'm trying to build a GUI that involves rectangles that have border radiuses. I figured I could do this using the fragment shader. Essentially, I'm masking each corner with a circle that is <code>r</code> units away from each wall for that corner. I then check if the point is between the circle's center and the corner. If the point is between those two, then I check if it's outside of the circle's radius. If so, I discard the point.</p>
<pre><code>#version 330 core
// the xy position of the fragment (in world coordinates?)
in vec2 xy;
// the bottom left corner of the rectangle
uniform vec2 u_position;
// the width and height of the rectangle
uniform vec2 u_dimensions;
// the border radius (how far the mask circle's center we be from either wall of the corner)
uniform float u_radius;
out vec4 FragColor;
void main(void) {
// xy = test point coordinates
// rc = rectangle corner
// ec = ellipse center
// uv = test point coordinates relative to ellipse center
if (xy.x - u_position.x < u_dimensions.x / 2) {
if (xy.y - u_position.y < u_dimensions.y / 2) {
// bottom left
vec2 rc = u_position;
vec2 ec = rc + vec2(u_radius, u_radius);
vec2 uv = xy - ec;
if (uv.x < 0 && uv.y < 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
discard;
}
} else {
// top left
vec2 rc = u_position + vec2(0, u_dimensions.y);
vec2 ec = rc + vec2(u_radius, -u_radius);
vec2 uv = xy - ec;
if (uv.x < 0 && uv.y > 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
discard;
}
}
} else {
if (xy.y - u_position.y < u_dimensions.y / 2) {
// bottom right
vec2 rc = u_position + vec2(u_dimensions.x, 0);
vec2 ec = rc + vec2(-u_radius, u_radius);
vec2 uv = xy - ec;
if (uv.x > 0 && uv.y < 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
discard;
}
} else {
// top right
vec2 rc = u_position + vec2(u_dimensions.x, u_dimensions.y);
vec2 ec = rc + vec2(-u_radius, -u_radius);
vec2 uv = xy - ec;
if (uv.x > 0 && uv.y > 0 && pow(uv.x/u_radius, 2) + pow(uv.y/u_radius, 2) > 1) {
discard;
}
}
}
FragColor = vec4(0.0f, 0.0f, 0.0f, 1.0f);
}
</code></pre>
<p>The result looks like this (the corners are really jagged):
<a href="https://i.stack.imgur.com/Zb6QA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zb6QA.png" alt="enter image description here" /></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T05:00:24.950",
"Id": "248748",
"Score": "1",
"Tags": [
"opengl"
],
"Title": "Border Radius in OpenGL"
}
|
248748
|
<p>I'm really bothered with my approach in this, as I'd like to use the client in multiple projects.</p>
<p>The client extends Guzzle and I'm using a factory method to initialize the client with the necessary settings:</p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\Services\ApiClient;
use App\Tenant;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Str;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
class ApiClient extends GuzzleClient {
protected Tenant $tenant;
public static function factory(Tenant $tenant)
{
$handler = HandlerStack::create();
$handler->push(Middleware::mapRequest(function (RequestInterface $request) use ($tenant) {
$extraParams = ['tenant' => $tenant->api_tenant];
$uri = $request->getUri();
$uri .= (isset(parse_url($uri)['query']) ? '&' : '?');
$uri .= http_build_query($extraParams);
return new Request(
$request->getMethod(),
$uri,
$request->getHeaders(),
$request->getBody(),
$request->getProtocolVersion()
);
}));
$client = [
'base_uri' => rtrim($tenant->api_base_url, '/') . "/api/{$tenant->api_rest_version}/companies({$tenant->api_company_id})/",
'timeout' => 5.0,
'handler' => $handler,
'auth' => [$tenant->api_user, $tenant->api_password],
'curl' => [CURLOPT_SSL_VERIFYPEER => false],
'debug' => false,
'headers' => [
'Accept' => 'application/json',
'If-Match' => '*',
'Accept-Language' => 'en-US',
'OData-Version' => '4.0',
'Prefer' => 'odata.continue-on-error',
],
];
return new static($client, $tenant);
}
public function __construct(array $config = [], Tenant $tenant)
{
parent::__construct($config);
$this->tenant = $tenant;
}
public function getBatchUri() {
return rtrim($this->tenant->api_base_url, '/') . "/api/{$this->tenant->api_rest_version}/\$batch";
}
/**
* Converts request data for batch preparation.
*
* @param array $body
* @param string $method
* @param string $url
* @return array
*/
public function batch(array $body = [], $method = 'POST', string $url)
{
$extraParams = ['tenant' => $this->tenant->api_tenant];
$uri = $url;
$uri .= (isset(parse_url($uri)['query']) ? '&' : '?');
$uri .= http_build_query($extraParams);
return array_filter([
'method' => $method,
'atomicityGroup' => uniqid(null, true),
'id' => 'id_' . uniqid(null, true),
'url' => $uri,
'body' => (empty($body)) ? null : $body,
'headers' => [
'Content-Type' => 'application/json; odata.metadata=minimal; odata.streaming=true',
'OData-Version' => '4.0',
'If-Match' => '*',
'Prefer' => 'odata.continue-on-error',
],
]);
}
}
</code></pre>
<p>The available endpoints that the client is using differs based on the <code>Tenant</code> and the application the client is being used in.</p>
<p>As an example, I'm using the client to get some contacts from the external service and I then try and use that information for authentication.</p>
<p>Example:</p>
<pre class="lang-php prettyprint-override"><code><?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthenticationController extends Controller
{
public function login(Request $request)
{
$request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
if (!$user = Auth::guard('nav')->attempt($request->all())) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return response()->json(['token' => $this->createToken($user)]);
}
}
</code></pre>
<p>The <code>attempt</code> method contains some nested methods that ends up with the following use of the API Client:</p>
<pre class="lang-php prettyprint-override"><code> public function retrieveByCredentials(array $credentials)
{
$request = $this->apiClient->get('contacts', ['query' => [
'$filter' => "E_Mail eq '{$credentials['email']}'",
'$top' => 1
]]);
$data = json_decode($request->getBody()->getContents());
if(!empty($data->value)) {
return new NavContact((array)$data->value[0]);
}
return null;
}
</code></pre>
<p><code>NavContact</code> is a Data Transfer Object (that resembles an Eloquent Model).</p>
<p>Now, the whole ordeal feels and looks awful (to me at least). And I'm not particularly interested in having a client library blowing up to the size of PayPal or Google's PHP libraries in the same way I'm not particularly interested in having something that requires me to use my memory alone to fetch the right endpoints with the required query parameters.</p>
<p>I'm sure there must be a place in the middle?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:33:50.777",
"Id": "487700",
"Score": "0",
"body": "It's hard to suggest because I don't know the full usage of this library, but what you are talking about is a library. I don't see an issue with having \"model type\" classes i.e. `(new Contact)->get('myemail@google.com')` and so onwards.. it will only make things clearer. Additionally, you can have a strategy that will perform correct action based on tennant type."
}
] |
[
{
"body": "<p>While there isn't a lot of code here, there is some duplicated code - e.g.</p>\n<blockquote>\n<pre><code>$extraParams = ['tenant' => $tenant->api_tenant];\n\n$uri = $request->getUri();\n$uri .= (isset(parse_url($uri)['query']) ? '&' : '?');\n$uri .= http_build_query($extraParams);\n</code></pre>\n</blockquote>\n<p>in the callback to <code>Middleware::mapRequest</code> passed to <code>$handler->push()</code> in the <code>factory()</code> method, as well as similar lines in the <code>batch()</code> method:</p>\n<blockquote>\n<pre><code>$extraParams = ['tenant' => $this->tenant->api_tenant];\n\n$uri = $url;\n$uri .= (isset(parse_url($uri)['query']) ? '&' : '?');\n$uri .= http_build_query($extraParams);\n</code></pre>\n</blockquote>\n<p>This could be seen as a violation of the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself principle</a>. The similar lines could be abstracted into a static method that accepts a URL and a <code>Tenant</code> object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-19T22:30:43.297",
"Id": "270237",
"ParentId": "248750",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T06:15:08.003",
"Id": "248750",
"Score": "4",
"Tags": [
"php",
"api",
"laravel",
"client"
],
"Title": "API Client and usage implementation"
}
|
248750
|
<p>I have created the following Bash script to somewhat automate the upgrade of any <a href="https://www.mediawiki.org/wiki/Download" rel="nofollow noreferrer">MediaWiki</a> website which contains one extension (<a href="https://www.mediawiki.org/wiki/Extension:ContactPage" rel="nofollow noreferrer">ContactPage</a>).</p>
<p>I have tested the essential parts of the script several times and also tested the version here line by line from the edit mode and I didn't find any problem with it; my website was updated as long as new versions for MediaWiki core and for ContactPage were available or if not, it stayed with the same versions.</p>
<h2>preface.sh:</h2>
<blockquote>
<pre><code>#!/bin/bash
</code></pre>
<p><strong>Set debug mode:</strong></p>
<pre><code>set -x && complete -r
</code></pre>
<p><strong>Declare MediaWiki download variables:</strong></p>
<pre><code>latest_mediawiki_core="https://releases.wikimedia.org/mediawiki/1.34/mediawiki-1.34.2.tar.gz"
latest_mediawiki_contactpage_extension="https://extdist.wmflabs.org/dist/extensions/ContactPage-REL1_34-48b0c07.tar.gz"
</code></pre>
<p><strong>Declare web application backup variables:</strong></p>
<pre><code>current_date="$(date +%d-%m-%Y-%H-%M-%S)"
general_backups_dir="${HOME}/mediawiki_general_backups"
specific_backups_dir="${HOME}/mediawiki_specific_backups"
</code></pre>
<p><strong>Declare web application root variables:</strong></p>
<pre><code>web_application_root="${HOME}/public_html"
read domain
domain_dir="${web_application_root}/${domain}"
</code></pre>
<p><strong>Declare web application dbname:</strong></p>
<pre><code>read -s dbname
</code></pre>
<p><strong>Declare web application dbusername:</strong></p>
<pre><code>read -s dbusername
</code></pre>
</blockquote>
<h2>backups.sh:</h2>
<blockquote>
<pre><code>#!/bin/bash
</code></pre>
<p><strong>Create backup directories:</strong></p>
<pre><code>rm -rf "${general_backups_dir}"
rm -rf "${specific_backups_dir}"
mkdir -p "${general_backups_dir}"
mkdir -p "${specific_backups_dir}"
</code></pre>
<p><strong>Test backup directories:</strong></p>
<pre><code>ll "${general_backups_dir}"
ll "${specific_backups_dir}"
</code></pre>
<p><strong>Create specific backups:</strong></p>
<pre><code>cp "${domain_dir}/LocalSettings.php" "${specific_backups_dir}"
cp "${domain_dir}/robots.txt" "${specific_backups_dir}"
cp "${domain_dir}/${domain}.png" "${specific_backups_dir}"
cp "${domain_dir}"/.htaccess* "${specific_backups_dir}" # This includes a shell glob;
cp "${domain_dir}"/google*.html "${specific_backups_dir}" # This includes a shell glob;
</code></pre>
<p><strong>Test specific backups:</strong></p>
<pre><code>ll "${specific_backups_dir}"
</code></pre>
<p><strong>Create web application root backup:</strong></p>
<pre><code>zip -r "${general_backups_dir}/${domain}-directory-backup-${current_date}.zip" "${domain_dir}"
</code></pre>
<p><strong>Test web application root backup:</strong></p>
<pre><code>ll "${general_backups_dir}"
</code></pre>
<p><strong>Create web application database backup:</strong></p>
<pre><code>mysqldump -u"$dbusername" -p "$dbname" > "${general_backups_dir}/${dbusername}-${current_date}.sql"
# -u && -p and dbname variable expansions shouldn't have "${}", rather, just "$";
# If one wants to prompt dbusername password, -p should include a following whitespace character;
# In general, dbusername and dbname variables must be different variables even if their values are the same;
# Database Management Programs (i.e PHPMyAdmin) and mysqldump can produce databases in different sizes due to different data organization methods;
</code></pre>
<p><strong>Test web application database backup:</strong></p>
<pre><code>ll "${general_backups_dir}"
</code></pre>
</blockquote>
<h2>delete-download-install-and-configure-MediaWiki.sh:</h2>
<blockquote>
<pre><code>#!/bin/bash
</code></pre>
<p><strong>Prepare to download, install and configure CMS and specific backups:</strong></p>
<pre><code>cd "${web_application_root}"
rm -rf "${domain_dir}"
</code></pre>
<p><strong>Download and configure MediaWiki core:</strong></p>
<pre><code>wget "${latest_mediawiki_core}" &&
find . -maxdepth 1 -iname 'mediawiki*.tar.gz' -type f -exec tar -xzf {} \; &&
find . -maxdepth 1 -type d -iname '*mediawiki*' -execdir mv {} "${domain}" \; &&
find . -maxdepth 1 -iname 'mediawiki*.tar.gz' -type f -exec rm {} \;
</code></pre>
<p><strong>Download and configure MediaWiki ContactPage extension:</strong></p>
<pre><code>wget "${latest_mediawiki_contactpage_extension}" &&
find . -maxdepth 1 -iname 'ContactPage*.tar.gz' -type f -exec tar -xzf {} \; &&
find . -maxdepth 1 -type d -iname 'ContactPage*' -execdir mv {} "${domain}/extensions" \; &&
find . -maxdepth 1 -iname 'ContactPage*.tar.gz' -type f -exec rm {} \;
</code></pre>
<p><strong>Test previous operations:</strong></p>
<pre><code>ll
ll "${domain_dir}/extensions"
</code></pre>
<p><strong>Retreive specific backups to the new installation:</strong></p>
<pre><code>cp -a "${specific_backups_dir}"/.htaccess "${domain_dir}" # Only .htaccess file;
cp -a "${specific_backups_dir}"/* "${domain_dir}" # All files besides .htaccess;
</code></pre>
<p><strong>Test specific backups retreiving:</strong></p>
<pre><code>ll ${domain_dir}
</code></pre>
</blockquote>
<h2>final-configurations.sh:</h2>
<blockquote>
<pre><code>#!/bin/bash
</code></pre>
<p><strong>Prepare to create and configure a new sitemap and to update database:</strong></p>
<pre><code>cd "${domain_dir}"
</code></pre>
<p><strong>Create a new sitemap:</strong></p>
<pre><code>rm -rf "${domain_dir}/sitemap"
mkdir -p "${domain_dir}/sitemap"
php "${domain_dir}/maintenance/generateSitemap.php" \
--memory-limit=50M \
--fspath=/"${domain_dir}/sitemap" \
--identifier="${domain}" \
--urlpath=/sitemap/ \
--server=https://"${domain}" \
--compress=yes
</code></pre>
<p><strong>Update database (One might need to change LocalSettings.php before doing so):</strong></p>
<pre><code>php "${domain_dir}/maintenance/update.php" --quick &&
php maintenance/rebuildrecentchanges.php
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T10:19:46.977",
"Id": "487386",
"Score": "0",
"body": "Instead of segmenting the file for the purpose of post here, just dump the contents as is, and use comments inside bash for marking different sections."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T10:23:33.403",
"Id": "487387",
"Score": "0",
"body": "The segments reflect how I document it the script in a `.sh` file, although here I only presented the `** COMMENT **` instead `## COMMENT ##` or similar ; let along, I have four different files stored on my cloud and PC..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T10:24:50.837",
"Id": "487388",
"Score": "0",
"body": "Bash comments would make each line very long **here** ; I can put the comments under each line but I think it's even less comfortable than the current mode, but perhaps it's just me."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T08:06:32.547",
"Id": "248755",
"Score": "2",
"Tags": [
"bash"
],
"Title": "Upgrade script for MediaWiki website with one external addon (wave 2)"
}
|
248755
|
<p>Update! I got a lot of pointers, suggestions and tips on improving the readability, structure and efficiency of my program <a href="https://codereview.stackexchange.com/questions/248665/project-euler-4-finding-the-largest-palindrome-that-is-a-product-of-two-3-digi?noredirect=1#comment487292_248665">yesterday</a>, so I made the suggested improvements to the program and am happy to announce I managed to reduce the execution time of the program to nearly 1/25th! Still, I would love feedback on the improved state of my program. Thanks to everyone who commented on my previous post!</p>
<pre class="lang-cpp prettyprint-override"><code>// Largest palindrome product (4)
#include <iostream>
#include <chrono>
bool is_palindrome(int num);
void compute_palindromes(void);
void save_palindrome(int i, int j, int val);
void log_palindrome(void);
void time_function(void (*func)(void), const char *desc);
void version_one(void);
void version_two(void);
struct Palindrome_storage {
static int primary;
static int secondary;
static int palindrome;
};
int Palindrome_storage::primary = 0;
int Palindrome_storage::secondary = 0;
int Palindrome_storage::palindrome = 0;
int main(void) {
time_function(version_one, "Program -- Version 1.0");
time_function(version_two, "Program -- Version 1.1 (yesterday's code)");
time_function(compute_palindromes, "Program -- All optimizations");
log_palindrome();
return 0;
}
bool is_palindrome(int num) { // Determine if a given number is a palindrome or not
int original = num;
int reversed = 0;
while (num > 0) {
reversed *= 10;
reversed += num % 10;
num /= 10;
}
return reversed == original;
}
void compute_palindromes(void) {
int max_palindrome = 0;
for (int i=999; i>99; --i) {
if (i < max_palindrome/1000) break; // Optimalization
for (int j=999; j>=i; --j) {
int product = i*j;
if ((product > max_palindrome) && is_palindrome(product)) {
max_palindrome = product;
save_palindrome(i, j, product);
break;
}
}
}
}
void save_palindrome(int i, int j, int val) { // Stores the largest palindrome found in a struct with static variables
Palindrome_storage::primary = i;
Palindrome_storage::secondary = j;
Palindrome_storage::palindrome = val;
}
void log_palindrome(void) { // Outputs the largest palindrome found
std::cout << "Largest palindrome: " << Palindrome_storage::primary << " * " << Palindrome_storage::secondary << " == " << Palindrome_storage::palindrome << std::endl;
}
void time_function(void (*func)(void), const char *desc) { // Time how long a function takes to execute
double best_time;
for (int i=0; i<100; i++) { // Multiple checks to find the lowest (should maybe be average) computing time
auto begin_time = std::chrono::high_resolution_clock::now();
func();
auto end_time = std::chrono::high_resolution_clock::now();
double elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>(end_time - begin_time).count();
if (i == 0) best_time = elapsed_time;
else if (elapsed_time < best_time) best_time = elapsed_time;
}
std::cout << desc << ":\n";
std::cout << "Elapsed time is " << best_time/1000000.0 << " seconds." << '\n' << std::endl;
}
// Previous versions
void version_one(void) {
int largest_palindrome = 0;
for (int i=999; i>99; i--) {
for (int j=999; j>99; j--) {
int product = i*j;
if (is_palindrome(product) && product>largest_palindrome) {
largest_palindrome = product;
}
}
}
}
void version_two(void) {
int largest_palindrome = 0;
for (int i=999; i>99; i--) {
for (int j=999; j>99; j--) {
if (i < largest_palindrome/1000) { // Optimalization
i = 0;
j = 0;
} else {
int product = i*j;
if (is_palindrome(product) && product>largest_palindrome) {
largest_palindrome = product;
j = 0;
}
}
}
}
}
</code></pre>
<p>Output:</p>
<pre><code>Program -- Version 1.0:
Elapsed time is 0.037895 seconds.
Program -- Version 1.1 (yesterday's code):
Elapsed time is 0.003956 seconds.
Program -- All optimizations:
Elapsed time is 0.000153 seconds.
Largest palindrome: 913 * 993 == 906609
</code></pre>
|
[] |
[
{
"body": "<h1>static</h1>\n<p>Why a <code>struct</code> of <code>static</code> members? Seems awkward. You could instead have a <code>static</code> <code>struct</code>, and having 1 <code>static</code> is better than three:</p>\n<pre><code>struct Palindrome_storage {\n int primary;\n int secondary;\n int palindrome;\n};\nstatic Palindrome_storage palindrome_storage = { 0, 0, 0 };\n</code></pre>\n<h1><s>static</s></h1>\n<p>Having no statics would be even better than 1 static. You could run variations of the algorithm on separate threads without fear of static variables colliding. You are simply returning data; why not just return the structure?</p>\n<pre><code>Palindrome_storage compute_palindromes(void) {\n ...\n return Palindrome_storage{ ..., ... , ...};\n}\n</code></pre>\n<p>On the plus side, this reduces redundant work. <code>product</code> is being stored in two places: <code>max_palindrome</code> and <code>Palindrome_storage::palindrome</code>.</p>\n<pre><code> max_palindrome = product;\n save_palindrome(i, j, product);\n</code></pre>\n<p>If you simply stored <code>max_palindrome</code>, <code>primary</code> & <code>secondary</code> as local variables, you store them all only once. And you can easily construct & return the structure from these locals.</p>\n<h1><s>struct</s></h1>\n<p>You don't really need a structure to hold these 3 integers. A <code>std::tuple</code> could work.</p>\n<pre><code>std::tuple<int, int, int> compute_palindromes(void) {\n ...\n return std::tuple<int, int, int>{ primary, secondary, max_product };\n}\n</code></pre>\n<p>Although you've lost some nice naming the structure gave you.</p>\n<h1>Loop over the correct range limits</h1>\n<pre><code> for (int i=999; i>99; --i) {\n</code></pre>\n<p>What does this loop mean? From <code>999</code> down to just before <code>99</code>. Seems like 9's are significant, but why?</p>\n<pre><code> for (int i=999; i>=100; --i) {\n</code></pre>\n<p>This is the same loop, but now we see we're going from <code>999</code> down to <code>100</code> inclusive. All of the 3-digit numbers. I think this is slightly clearer.</p>\n<h1>Optimizations</h1>\n<h2>Why divide by 1000?</h2>\n<pre><code> if (i < max_palindrome/1000) break; // Optimalization\n for (int j=999; j>=i; --j) {\n</code></pre>\n<p>What is this optimization really doing for you? If <code>i</code> is less than <code>max_palindrome</code> divide by 1000? Where did that 1000 come from? What does it mean? And can we do better?</p>\n<p>What you are really doing is testing against a limit. The maximum <code>product</code> you can form from <code>i</code> and a 3-digit number is <code>i * 999</code>. So why divide by 1000? Is that even correct? Is it too much? Is it not enough? Is this an off-by-one error? The following would be better, clearer, more correct, and if multiplication is faster than division, slightly faster:</p>\n<pre><code> if (i*999 < max_palindrome) break; // Optimization\n</code></pre>\n<p>And yet, we can still do better. For a given value of <code>i</code>, what is the smallest value <code>j</code> can have, and still have <code>i * j > max_palindrome</code>?</p>\n<pre><code> int lower_j_limit = max(i, max_palindrome / i);\n if (lower_j_limit > 999) break;\n for (int j=999; j>=lower_j_limit; --j) {\n</code></pre>\n<h2>max_palindrome = 0</h2>\n<p>Is <code>max_palindrome = 0</code> the correct initialization? You were testing <code>i < max_palindrome/1000</code>, which is means it was effectively <code>i < 0</code>. Now we're computing the lower limit with <code>max_palindrome / i</code>, which again starts off as <code>0</code>. Perhaps, since we're looking for 6 digit palindromes, we should initialize <code>max_palindrome = 99999</code>.</p>\n<p>It won't make a difference here. But it is something to remember to examine in future problems.</p>\n<h2>11 fold speed increase.</h2>\n<p>As <a href=\"https://codereview.stackexchange.com/a/248682/100620\">L.F. pointed out</a>, since for a 6-digit palindrome, <span class=\"math-container\">\\$abccba\\$</span>,</p>\n<p><span class=\"math-container\">$$a - b + c - c + b - a = 0 = 11 * k, k \\in \\mathbb{Z}$$</span></p>\n<p>then <span class=\"math-container\">\\$abccba = i * j\\$</span> must be divisible by 11.</p>\n<p>Since 11 is prime, when <code>i</code> is not divisible by 11, then <code>j</code> must be, so you can start <code>j</code> at <code>990</code>, and decrement it by 11. Testing 1/11th of the values gives you an 11-fold speed increase. Of course, when <code>i</code> is divisible by 11, you must start <code>j</code> at <code>999</code> and go down by 1's, as usual.</p>\n<h2>is_palindrome</h2>\n<p>Your test for a palindrome is fine. Your algorithm reverses the digits of the number, and compares the reversed number to the original. But you are doing twice as much work as necessary.</p>\n<p>Consider: When you are reversing <code>580085</code>, you repeatedly remove the last digit from <code>num</code>, and add it to the last digit of <code>reversed</code>:</p>\n<pre><code>num reversed\n580085 0\n 58008 5\n 5800 58\n 580 580 <-- These are equal!\n 58 5800\n 5 58008\n 0 580085\n</code></pre>\n<p>Note the halfway point. After half of the digits have been removed, and reversed, the partial values should be equal if the number is a palindrome. To be general, we'd also have to handle the case of an odd number of digits, by testing for equality both before and after adding the extracted digit to the reversed value.</p>\n<pre><code>bool is_palindrome(int num) {\n if (num == 0) return true;\n if (num % 10 == 0) return false;\n int reversed = 0;\n while (num > reversed) {\n int digit = num % 10;\n num /= 10;\n if (num == reversed) return true; // For odd number of digits\n reversed = reversed * 10 + digit;\n if (num == reversed) return true; // For even number of digits\n }\n return false;\n}\n</code></pre>\n<p>But in this problem, you know exactly how many digits you are expecting. Only six. So you only need to reverse the bottom 3 and compared these to the top 3. Reversing the bottom 3 digits can be done without any loops at all.</p>\n<pre><code>bool is_6_digit_palindrome(int num) {\n int top3 = num / 1000;\n int btm3 = num % 1000;\n int btm3_reversed = btm3 % 10 * 99 + btm3 % 100 + btm3 / 100;\n return top3 == btm3_reversed;\n}\n</code></pre>\n<p>Derivation of the <code>btm3_reversed</code> left as exercise to student.</p>\n<h1>Tests</h1>\n<p>There is no guarantee that <code>version_one</code> and <code>version_two</code> are producing the correct results. They produce no output, return no value, and call functions with no side-effect. A truly aggressive optimizer might optimize these functions away completely, and your tests could show them executing in zero time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:51:50.557",
"Id": "487665",
"Score": "0",
"body": "You! Thank you! What you said about tuples (removing structs/statics) made a lot of sense and I think I understand it a lot better. The range limits also make sense, although not as important. However I don't quite understand why initializing max_palindrome as 0, why would that matter? Checking if i<0 still wouldn't return incorrect results? Half the amount of work for checking palindromes was clever, I never would have thought of that myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:56:54.657",
"Id": "487668",
"Score": "0",
"body": "The 11-fold speed increase would have been nice, although while I'm trying to optimise my program as much as possible, I'm also trying to keep it flexible and universal, able to work with other ranges of numbers as well. Thus, not restricting the palindromes to six digits (abccba) but potentially a lot more. With some of your revisions to my code I was able to shave another ~0.6ms off of execution time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:15:35.980",
"Id": "487671",
"Score": "0",
"body": "Re: `max_palindrome = 0`. You originally check `if (i < max_palindrome/1000) break;`. This initially tests `i < 0`. If `max_palindrome` was initialized to `99999`, then the test would initially check `i < 99`. My changes added a `lower_j_limit = max_palindrome / i`, and the lower limit again is initially 0, but with the 99999 initialization raises the limit to 100. Without other optimizations elsewhere, these limit improvements would speed the algorithm up. But as I said, \"_It won't make a difference here_\" because there are other things which impose these anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:26:16.270",
"Id": "487674",
"Score": "0",
"body": "Keeping the algorithm general is a good worthy goal. But note that every even digit palindrome (aa, abba, abccba, abcddcba, ...) is divisible by 11, because the alternating digit sum will always sum to zero, which is a multiple of 11. So in your general purpose algorithm, you should detect the special case of an even number of digits, and apply the optimization for any even digit cases. It is still flexible & universal, but faster when certain conditions are detected."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T16:25:42.173",
"Id": "248772",
"ParentId": "248756",
"Score": "5"
}
},
{
"body": "<p>What you need to do is, actually, to go the other way around, for each palindromic number verify if it has the required two 3-digit divisors. Here is how I would do:</p>\n<pre><code>int rev_search()\n{\n for (int i = 999; i >= 100; i--)\n {\n int palnum = i;\n for (int x = i; x > 0; x /= 10)\n {\n palnum *= 10;\n palnum += x % 10;\n }\n int start = 990;\n int step = 11;\n\n for (int j = start; j >= 100; j -= step)\n {\n int k = palnum / j;\n if (k >= 1000)\n break;\n if (k < 100)\n continue; \n if ((k * j) == palnum)\n {\n return palnum;\n } \n }\n }\n return -1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:38:35.303",
"Id": "487759",
"Score": "0",
"body": "You have provided an alternative solution, but you have not reviewed the OP's code. Alternate solution only answers are not valid answers on Code Review, and subject to deletion. You need to at least explain how this solution would be better than the OP's. Simply stating one solution is better than another is not a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:38:47.473",
"Id": "487760",
"Score": "0",
"body": "Your `palnum` generation could be improved, using a triple loop: `for (int a = 900009; a > 0; a -= 100001) { for (int ab = a + 90090; ab >= a; ab -= 10010) { for (int palnum = ab + 9900; palnum >= ab; palnum -= 1100) { ... } } }` No digit-reversal loop, with division-by-10, multiplication-by-10, and modulo-division-by-10 required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:39:12.133",
"Id": "487761",
"Score": "0",
"body": "Your `if (k < 100) continue;` is unnecessary. The smallest value `k = palnum / j` can obtain is when `palnum` in at its minumum (`100001`) and `j` is at its maximum (`990`), which leads to `k = 101`. Therefore the condition will never be true, and the statement can be removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:39:40.380",
"Id": "487762",
"Score": "0",
"body": "You loop while `j >= 100`, but break out of the loop if `palnum / j` exceed 3 digits. This second condition also establishes a lower limit on `j`, which means you could directly compute a combined lower limit before the loop `int end = max((int)ceil(palnum/999.0), 100);`, and change the loop condition to `j >= end`. The expression `(int)ceil(palnum/999.0)` may be reworked to `(palnum+998)/999` to remain in integer math."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T16:23:06.457",
"Id": "487771",
"Score": "0",
"body": "@AJNeufeld Sure, I'll add the explanation. I am not sure though, that the improvements you are suggesting will have some significant impact, but I'll try to benchamrk and see what works best."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T23:35:11.677",
"Id": "248894",
"ParentId": "248756",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T08:22:17.193",
"Id": "248756",
"Score": "3",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "Project Euler #4: Finding the largest palindrome that is a product of two 3-digit numbers UPDATE"
}
|
248756
|
<p>I've started learning to program, and as the first program I wrote on my own I wanted to come up with a number guessing game - the below is what I got.</p>
<p>I'm mainly looking for a review of my <code>Guess</code> function, but I do have a few specific questions:</p>
<ol>
<li>Does it make sense to have my loop variable as a function parameter?</li>
<li>I'm currently defining some variables (e.g. <code>tries</code>) outside of my function - is this an idiomatic way to do it?</li>
</ol>
<pre><code>import random
tries = [1]
def Guess(playing):
number = random.randint(1,100)
print(number)
print("We are going to play high and low, the avabile numbers are from 1 to 100 included.")
while playing == True:
user_input = input("What is your number? ")
if int(user_input) == number:
print("You have won!")
playing = False
elif int(user_input) < number:
print("You need to give a higher number")
tries.append(1)
elif int(user_input) > number:
print("You need to give an lower number")
tries.append(1)
else:
print("You have put an wrong number")
playing = False
print("It took you " + str(sum(tries)) + " turns to guess")
still = input("Do you want to play again?")
if still == "yes" or still == "YES" or still == "y" or still == "si":
Guess(playing=True)
else:
playing=False
Guess(playing=True)
</code></pre>
|
[] |
[
{
"body": "<p>Overall you've done a good job with your code, there are a couple things I'd look out for :</p>\n<ul>\n<li>You aren't paying for whitespace! What I mean is that it's important to let your\ncode breathe. Use some empty lines, it'll do wonder for your eyes when dealing with big chunks of code.</li>\n<li>Why is <code>tries</code> an array? In my opinion, <code>tries</code> should represent the number of tries, so it should be a number!</li>\n<li>Notice that you have for conditions, <code>==, <, > and... ?</code> Say I ask you to give me a number that is neither equal, smaller or greater than 3, is there a possible option? What you should do instead is make sure the player input a number! Right now, if I was to answer "I don't know my numbers I'm just a baby" to "We are going to play high and low, the avabile numbers are from 1 to 100 included.", your program will crash! You should look into <code>try/catch</code> blocks to solve this problem, that could be a next thing to learn for you!</li>\n<li>Say I need three tries on my first playthrough, then I start a new game (using "yes" when prompted) and I'm able to succeed on the first try, your code will tell me I've needed four tries to succeed. Can you find out why and how you can fix that?</li>\n<li>You could simplify your loop using the <code>break</code> keyword, that's also something you should search for (while we're at it, try to understand the usage of <code>break</code>, <code>return</code> and <code>continue</code>. Those three keywords are pretty useful, although you probably already know about <code>return</code>).</li>\n<li>What if I'm an english major and I can't stand making grammar mistakes (It's obviously not my case) and I write "Yes", instead of "yes" or "YES", when asked if I want to play again? What you could do is compare the <em>lowered</em> (or <em>uppered</em>) version of the input with what you want to check (ex. <code>still.lower() == "yes"</code>).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:10:11.533",
"Id": "487411",
"Score": "0",
"body": "Thanks for this guidance. I will try now to check all the things that you have listed here, and later I will try to post the changed program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:17:32.023",
"Id": "487414",
"Score": "4",
"body": "@KacperKrawczyk please do not edit your question to include updated code - editing a question that has answers may invalidate those answers. If you'd like, please feel free to wait a few days and post a new question to get review on your updated question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:28:43.333",
"Id": "487419",
"Score": "2",
"body": "@KacperKrawczyk As much as I appreciate accepting my answer so fast, I'd wait a little bit more :) Posts with no \"accepted answers\" tend to attract more attention!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:02:47.083",
"Id": "248762",
"ParentId": "248759",
"Score": "8"
}
},
{
"body": "<p>Here are a couple of improvements I think you could make (IEatBabels touched on a lot of these, but I'd like to expand on some areas and add my own phrasing):</p>\n<ul>\n<li>Why is <code>tries</code> a list? It would easier and make more sense to just let <code>tries = 0</code> starting out, and then increment tries (<code>tries += 1</code>) each time the user input an incorrect number.</li>\n<li>Since you don't have any other functions in your program, I wouldn't even bother with making a <code>Guess</code> function. Just write the code directly in the program.</li>\n<li>You may have just been debugging your program, but you're showing the user the number they're supposed to guess by writing <code>print(number)</code> in <code>Guess</code>!</li>\n<li>What happens if the user decides to be cheeky and entire some gibberish (i.e. something that's not a number)? Your program is going to raise an exception when it tries to convert the input to a number. What you should do is wrap the code under your loop in a <a href=\"https://docs.python.org/3/tutorial/errors.html#handling-exceptions\" rel=\"nofollow noreferrer\"><code>try/except</code></a> block. That way, whenever the user inputs gibberish, you can prompt them to entire a valid number.</li>\n<li>I'm not sure why you have the <code>else</code> block after your <code>if/elif</code> statements? If the user input isn't equal to the number, and it isn't less than the number, and it isn't greater than the number, what else could it be? Nothing! So there's really no need for the <code>else</code> statement there. You might've been trying to use the <code>else</code> statement in cases where the user input wasn't valid. This won't quite work though. If that's what you were trying to do, see my last point.</li>\n<li>Convert the user input to an integer once, and store it in a variable. This saves time and looks cleaner than converting the user input each time you want to test it.</li>\n<li>I'm not sure why you're using recursion here? Recursion is an excellent tool, but oftentimes <code>while</code> or <code>for</code> loops work much better. I think your program is one of those cases. Just use two loops - one loop for asking the user if they'd like to play again, and one loop for the actual game.</li>\n<li>I noticed you used flags to break out of our loops. This is a fine method. But I'd prefer here to just use <code>break</code>. <code>break</code> is a statement which tells Python to immediately jump out of the loop it's currently in. It has the same effect as setting flags to <code>True</code> and/or <code>False</code>.</li>\n<li>You were pretty good about this in your program, but always make sure to use descriptive variable names, and write clear, explicit code. This makes your code clean and self-documenting, and it lets you come back to it months from now and quickly understand what it does and how works.</li>\n</ul>\n<p>Here's how I'd re-write your program, with the above suggestions incorporated, and some formatting, logic, and naming improvements (also IEatBagels made an excellent point about whitespace. Make sure you take this to heart!):</p>\n<pre><code>import random\n\n\nprint("We are going to play high and low, the avabile numbers are from 1 to 100 included.")\n\ntries = 0\nwhile True:\n number_to_guess = random.randint(1, 100)\n while True:\n try:\n user_input = input("What is your number? ")\n guess = int(user_input)\n except ValueError:\n print("That's not a valid number! Try again.")\n else:\n if guess == number_to_guess:\n print("You have won!")\n break\n elif int(user_input) < number_to_guess:\n print("You need to give a higher number")\n tries += 1\n elif int(user_input) > number_to_guess:\n print("You need to give a lower number")\n tries += 1\n\n print("It took you " + str(tries) + " turns to guess")\n still = input("Do you want to play again?")\n\n if not (still == "yes" or still == "YES" or still == "y" or still == "si"):\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T09:29:25.003",
"Id": "487502",
"Score": "1",
"body": "If you wanna play again, you will have to geus the same number. The `number_to_guess` should be below the first `while True:`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T09:58:36.950",
"Id": "487505",
"Score": "0",
"body": "@SirDuckduck thanks, good catch!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T18:31:32.393",
"Id": "487572",
"Score": "0",
"body": "Thank you very much for explaining me those things. I have revised all the things that @IEatBagels had mentioned. Now I will take my time to process your stuff. Just by you two guys I have improved and learnt so many new things that i have to admit and appreciate. I am trying to implement all the things and build a hangman game, more clean with those new tricks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T23:20:33.117",
"Id": "487605",
"Score": "0",
"body": "That's awesome @KacperKrawczyk. I love hearing that I'm helping others to learn, grow, and better themselves. Best of luck with your hangman project!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T01:55:51.673",
"Id": "248791",
"ParentId": "248759",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T13:35:31.513",
"Id": "248759",
"Score": "7",
"Tags": [
"python",
"beginner",
"number-guessing-game"
],
"Title": "Beginner's Number Guessing Game"
}
|
248759
|
<p>I currently have a utility that will display details about a list of specified users. In its current state I don't use any functions, which I've noticed make it a little more repetitive than I would like.</p>
<p>I'm specifically interested in how to make this more functional, but I'd be interested in any suggestions for how to make this better.</p>
<p>Details.py</p>
<pre><code>class userdetails:
def __init__(self, Userdetails, Education, Work_history, Bank_history,
Credit_history):
self.Userdetails = Userdetails
self.Education = Education
self.Work_history = Work_history
self.Bank_history = Bank_history
</code></pre>
<p>My other file</p>
<pre><code>from Details import userdetails
pin_no = ('1111', '2222', '3333')
while True:
pin_no = input("Input the no : ")
if pin_no == '1111' or pin_no == '2222' or pin_no == '3333':
print ("\n Hello and welcome to my program. Please choose from one of the following
options:")
break
else:
print ("please try again ")
Tom_Watts = userdetails ('Tom Watts \n' , '\nSidney Stringer School \n\n' 'GCSE English: Grade A \n'
'GCSE Maths: Grade B \n' 'GCSE Physics: Grade A \n', 'GSA LTD', 'Barclays Bank', 'Good')
Bill_Gates = userdetails ('Bill Gates \n ', '\nBinley Woods School \n\n' 'GCSE Maths: Grade A \n',
'MI6', 'Bank of England', 'Good' )
Steve_McQueen = userdetails ('Steve McQueen \n', '\nArizona High School \n\n' 'GCSE English: Grade A
\n' 'GCSE Maths: Grade A \n', 'GSA LTD', 'Lloyds Bank ', 'Average')
dict = {
'1111': Tom_Watts,
'2222': Bill_Gates,
'3333': Steve_McQueen,
}
user = input("\n\n 1. Userdetails \n 2. Education \n 3. Work History \n 4. Bank History \n" ' 5.
Credit History \n\n ' )
a = '1'
b = '2'
c = '3'
d = '4'
e = '5'
if user == a:
print (dict[pin_no].Userdetails)
elif user == b:
print (dict[pin_no].Education)
elif user == c:
print (dict[pin_no].Work_history)
elif user == d:
print (dict[pin_no].Bank_history)
elif user == e:
print (dict[pin_no].Credit_history)
</code></pre>
|
[] |
[
{
"body": "<p>The code could be simpler and more Pythonic. For example:</p>\n<pre><code>pin_no = ('1111', '2222', '3333')\n\n\nwhile True:\n\n pin_no = input("Input the no : ")\n\n if pin_no == '1111' or pin_no == '2222' or pin_no == '3333':\n</code></pre>\n<p>could simply be:</p>\n<pre><code>valid_pins = ('1111', '2222', '3333')\npin_no = input("Input the no : ")\nif pin_no in valid_pins:\n</code></pre>\n<p>Thus avoiding repetition.</p>\n<p>This code:</p>\n<pre><code>user = input("\\n\\n 1. Userdetails \\n 2. Education \\n 3. Work History \\n 4. Bank History \\n" ' 5. \nCredit History \\n\\n ' )\n</code></pre>\n<p>could become:</p>\n<pre><code>str = ("Userdetails", "Education", "Work History", "Credit History")\nfor num, value in enumerate(str, start=1):\n print(f"{num}) {value}")\n\nuser = input("Choose an option: ")\n</code></pre>\n<p>which gets you output like this: (note that I use enumerate for automatic line numbering)</p>\n<pre>\n1) Userdetails\n2) Education\n3) Work History\n4) Credit History\nChoose an option: \n</pre>\n<p>The problem with this code is that your data is <strong>polluted</strong> with linebreaks. Just don't. The formatting can be done in your code. For example the join function can easily break down a tuple:</p>\n<pre><code>print("\\n".join(str))\n</code></pre>\n<pre>\nUserdetails\nEducation\nWork History\nCredit History\n</pre>\n<p>As it stands your class is underutilized. Instead of this:</p>\n<pre><code>Steve_McQueen = userdetails ('Steve McQueen \\n', '\\nArizona High School \\n\\n' 'GCSE English: Grade A \n\\n' 'GCSE Maths: Grade A \\n', 'GSA LTD', 'Lloyds Bank ', 'Average')\n</code></pre>\n<p>I would strongly advise to use <strong>keywords arguments</strong> like this:</p>\n<pre><code>Steve_McQueen = userdetails (education='Arizona High School', work_history='GSA LTD', bank_history='Lloyds Bank')\n</code></pre>\n<p>First of all, it is more clear what the values relate to. And then you can provide arguments in the order you want (so your code won't break if you insert new arguments in the future, or change their order).</p>\n<p>Reference: <a href=\"https://problemsolvingwithpython.com/07-Functions-and-Modules/07.07-Positional-and-Keyword-Arguments/\" rel=\"nofollow noreferrer\">Positional and Keyword Arguments</a></p>\n<p>Note that by convention Python variables should be <strong>lowercase</strong>.</p>\n<p>I am not sure the class is beneficial here. You could simply make up a dict of all users. That depends on the ultimate purpose. As an example:</p>\n<pre><code>people = {\n '1111': {\n 'name': 'Tom Watts',\n 'education': 'Sidney Stringer School',\n 'grade': 'GCSE English: Grade A'\n },\n '2222': {\n 'name': 'Bill Gates',\n 'education': 'Binley Woods School',\n 'grade': 'GCSE English: Grade A'\n },\n '3333': {\n 'name': 'Steve McQueen',\n 'education': 'Arizona High School',\n 'grade': 'GCSE Maths: Grade A'\n }\n}\n</code></pre>\n<p>Then:</p>\n<pre><code>>>> people['2222']['name']\n'Bill Gates'\n>>> people['2222']['education']\n'Binley Woods School'\n</code></pre>\n<p>And then, provided that your dict is defined beforehand, the list of valid 'pins' can be built automatically:</p>\n<pre><code># list comprehension\nvalid_pins = [k for k in people.keys()]\n\n# what the list comprehension returns:\n[k for k in people.keys()]\n['1111', '2222', '3333']\n</code></pre>\n<p>No need for hardcoding numbers.</p>\n<p>Thus, you could do something like this:</p>\n<pre><code># list comprehension: get the list of valid pins from dict 'people' defined above\nvalid_pins = [k for k in people.keys()]\n\nwhile True:\n pin_no = input("Input the no : ")\n if pin_no not in valid_pins:\n print ("please try again ")\n else:\n # show details of matching user\n print(people[pin_no])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T10:09:32.947",
"Id": "487507",
"Score": "0",
"body": "Thanks for the above, I will go through your examples and come back to you with some questions -"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T10:32:52.417",
"Id": "489534",
"Score": "0",
"body": "thanks I understand everything, can you explain how the last steps work and how I call the function. # list comprehension valid_pins = [k for k in people.keys()]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-22T20:50:53.043",
"Id": "489607",
"Score": "0",
"body": "Sorry I don't understand what you want exactly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T14:55:02.583",
"Id": "489937",
"Score": "0",
"body": "The last bit, valid_pins = [k for k in people.keys()] - I know what it means, but how am I bringing this into the program, and what is it doing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-25T20:49:22.973",
"Id": "489968",
"Score": "0",
"body": "I edited the bottom of my post to add some explanation. The idea is to centralize all the data in one single dict, and extract the portions you need. In your original code you have a separate dict to store the user-PIN mapping - this is redundant and unnecessary. If you have duplicate information, then it has to be updated in several places and there is a risk that you forget some parts, and you end up with several chunks of related data that are out of sync with each other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T11:51:27.820",
"Id": "490235",
"Score": "0",
"body": "That's great thanks. My orginal code earlier - I just wanted to see how tuples, lists, different classes, dictionaries, can all work together, and how they all link-up which is also very good to know. Thanks for your help,"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:11:22.280",
"Id": "248782",
"ParentId": "248760",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248782",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T13:35:32.147",
"Id": "248760",
"Score": "3",
"Tags": [
"python",
"beginner"
],
"Title": "Display user detail utility"
}
|
248760
|
<p>I offer same day shipping if the user places an order before 9AM ET. If they place the order after 9AM, same day shipping is unavailable.</p>
<p>My server is using UTC time so I need to check if the time is greater than or less than 9AM ET regardless of the time where the user is located.</p>
<p>Not being an expert with JS, I cobbled together this code.</p>
<pre><code>var d = new Date();
var e = d.getHours().toLocaleString('en-US', { timeZone: 'America/New_York' });
var f = '';
if(e >= 9) {
f = 'shipping unavailable';
}
else {
f = 'shipping available';
}
</code></pre>
<p>I am getting the correct result after 9AM ET on my computer but I am concerned that same day shipping will be offered after 9AM ET.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T22:09:43.113",
"Id": "487463",
"Score": "0",
"body": "Please say you're checking this on the server, too."
}
] |
[
{
"body": "<p>Your code has a bug: <code>d.getHours()</code> will return a plain number. Calling <code>toLocaleString</code> on that number calls <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString\" rel=\"nofollow noreferrer\"><code>Number.prototype.toLocaleString</code></a>, which:</p>\n<blockquote>\n<p>returns a string with a language-sensitive representation of this number.</p>\n</blockquote>\n<p>It does not do anything with timezones; the second parameter does not recognize a <code>timeZone</code> property. For example, where I am now, <code>.getHours()</code> returns <code>9</code>, and <code>(9).toLocaleString('en-US', { timeZone: 'America/New_York' })</code> returns <code>"9"</code>.</p>\n<p>On your server, to retrieve the hours in a particular timezone, one method would be to call <code>toLocaleString</code> on the date object itself with the appropriate timezone, then extract the number of hours from that string:</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 timeString = new Date().toLocaleString('en-US', { timeZone: 'America/New_York' });\nconst [, hours, ampm] = timeString.match(/ (\\d+).* ([AP]M)/);\nconsole.log('In NY, it is:', hours, ampm);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Other issues:</p>\n<ul>\n<li>Since it's 2020, best to prefer at least 2015+ syntax, which should not be an issue since the code is running on the server. (Among other things, being able to use <code>const</code> is <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">wonderful</a>)</li>\n<li>You initialize <code>f</code> to the empty string, but then you reassign it immediately; the empty string is not used, so there's no point to assigning it.</li>\n<li>Or, even better: since you want to conditionally assign a value to <code>f</code> depending on the number of hours, it would be more appropriate (and shorter) to use the conditional operator:</li>\n</ul>\n<pre><code>const f = Number(hours) < 9 && ampm === 'AM'\n ? 'shipping available'\n : 'shipping unavailable';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:37:57.493",
"Id": "487426",
"Score": "0",
"body": "Thanks a lot for the detailed reply. After applying the code changes it appears to work as desired. There's still a lot to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T16:56:01.510",
"Id": "487441",
"Score": "0",
"body": "I have a question related to javascript dates, for operations like calculus of current date minus one day or some other similar operations there is some specific library usually used (maybe `moment.js`) ? Thanks for your attention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T17:25:39.800",
"Id": "487442",
"Score": "1",
"body": "@dariosicily Yes, I believe moment.js is the most popular JS date library used by far. You can also subtract days very easily [with the built-in Date](https://stackoverflow.com/a/1296374) too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T19:57:20.967",
"Id": "487456",
"Score": "0",
"body": "I got it, thank you for your answer and time."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:21:45.810",
"Id": "248765",
"ParentId": "248761",
"Score": "4"
}
},
{
"body": "<p>From a short review;</p>\n<ul>\n<li><p>Naming could be better for when you look back at the code;</p>\n<ul>\n<li><code>var d</code> could be <code>const now</code></li>\n<li><code>var e</code> could be <code>const hour</code></li>\n<li><code>var f</code> could be <code>let shippingLabel</code></li>\n</ul>\n</li>\n<li><p><code>toLocaleString</code> does not do what you want with time zones</p>\n</li>\n<li><p>As a beginner, I would not go for ternary to keep things ultra simple</p>\n</li>\n</ul>\n<p>So my counter proposal would be</p>\n<pre><code>const now = new Date();\nconst hour = now.getHours();\nlet shippingLabel;\n\nif(hour >= 9) {\n shippingLabel = 'Shipping unavailable';\n} else {\n shippingLabel = 'Shipping available';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:35:58.993",
"Id": "487423",
"Score": "0",
"body": "Thanks for your replay but getHours returns the hour, according to local time. I need the hour to always be compared to ET."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:37:06.373",
"Id": "487425",
"Score": "1",
"body": "For that, I would strongly suggest to use moment.js, https://momentjs.com/timezone/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:32:11.457",
"Id": "248766",
"ParentId": "248761",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248765",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T13:46:06.667",
"Id": "248761",
"Score": "3",
"Tags": [
"javascript",
"datetime",
"node.js",
"server"
],
"Title": "Javascript check if server time is greater than or less than 9am EST"
}
|
248761
|
<p>I have this problem to solve:</p>
<blockquote>
<p>Given an integer <span class="math-container">\$z\$</span> and an array <span class="math-container">\$a\$</span> of distinct integers sorted in ascending order, find two numbers, <span class="math-container">\$x\$</span> and <span class="math-container">\$y\$</span>, belonging to the array such that <span class="math-container">\$x + y = z\$</span>. All this has to be done with <span class="math-container">\$O(n)\$</span> time performance in the worst case and <span class="math-container">\$O(1)\$</span> space.</p>
</blockquote>
<p>I tried to jot down a trivial solution:</p>
<pre><code>public static boolean find(int[] a, int z) {
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] + a[j] == z)
return true;
}
}
return false;
}
</code></pre>
<p>However, it is clearly O(n^2) and I cannot find a better algorithm.
Can you help me?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T20:34:09.483",
"Id": "487459",
"Score": "1",
"body": "looks like a problem from LeetCode"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T10:49:54.403",
"Id": "487508",
"Score": "2",
"body": "When the problem statement clearly states \\$O(n)\\$ time and your solution is \\$O(n^2)\\$ I can only close-vote as \"not implemented / not working as intended\". You are not looking for a review, you are looking for a solution you have not found."
}
] |
[
{
"body": "<p>You can do this by "squeezing" the array. Suppose you had these inputs::</p>\n<p><span class=\"math-container\">$$a = \\{1, 4, 6, 9, 13, 16\\}$$</span>\n<span class=\"math-container\">$$z = 14$$</span></p>\n<p>Obviously, the correct solution is <span class=\"math-container\">\\$(1, 13)\\$</span>. We can achieve this by taking the first value (it works fine in reverse as well), and stepping backwards through the array until we hit one of the following conditions:</p>\n<ol>\n<li>You find the value we're looking for (<span class=\"math-container\">\\$a_{0} + a_{i} = z\\$</span>)</li>\n<li>We reach a range that can never equal <span class=\"math-container\">\\$z\\$</span> with <span class=\"math-container\">\\$a_{0}\\$</span> (e.g. <span class=\"math-container\">\\$i = 3, 1 + 9 = 10 < 14\\$</span>)</li>\n<li>We run into our current index (<span class=\"math-container\">\\$0\\$</span>).</li>\n</ol>\n<p>In scenario #1, return true. In scenario #2, start squeezing from the left-side using the same rules. In scenario #3, return false.</p>\n<p>A quickly jotted down implementation in Python - I am quite confident that you can simplify/condense this if you take a few more minutes to do this.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def squeeze_search(array, target):\n left_index = 0\n right_index = len(array) - 1\n\n while True:\n right_result = squeeze_right(array, target, left_index, right_index)\n if right_result is not None:\n success, left_index, right_index = right_result\n if success:\n return True\n else:\n return False\n left_result = squeeze_left(array, target, left_index, right_index)\n if left_result is not None:\n success, right_index, left_index = left_result\n if success:\n return True\n else:\n return False\n\n\ndef squeeze_left(array, target, current_index, left_index):\n current_value = array[current_index]\n while left_index < current_index:\n left_value = array[left_index]\n if left_value + current_value == target:\n return (True, current_index, left_index)\n elif left_value + current_value > target:\n return (False, current_index, left_index)\n\n left_index = left_index + 1\n\n return None\n\ndef squeeze_right(array, target, current_index, right_index):\n current_value = array[current_index]\n while right_index > current_index:\n right_value = array[right_index]\n if right_value + current_value == target:\n return (True, current_index, right_index)\n elif right_value + current_value < target:\n return (False, current_index, right_index)\n\n right_index = right_index - 1\n return None\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:41:48.467",
"Id": "248768",
"ParentId": "248764",
"Score": "2"
}
},
{
"body": "<p>Since there's no real review to do and we're apparently just posting solutions... here's a simple O(n) time O(1) space one:</p>\n<pre><code>public static boolean find(int[] a, int z) {\n int i = 0, j = a.length - 1;\n while (i < j) {\n int sum = a[i] + a[j];\n if (sum == z)\n return true;\n if (sum < z) i++; else j--;\n }\n return false;\n}\n</code></pre>\n<p>Explanation: Try the ends, i.e., add the smallest and largest value. If the sum is right, bingo. If the sum is too small, then the smallest value is useless (it would need to be added with a number larger than the largest). If the sum is too large, then the largest value is useless. So remove the useless one. But since <em>actually</em> removing it, i.e., creating an array without it, would be expensive, just work with indexes marking the ends of the still potentially useful part of the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T07:12:24.487",
"Id": "487488",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (why it is better than the original) so that the author and other readers can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T09:09:53.010",
"Id": "487501",
"Score": "0",
"body": "@Mast Done that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T11:03:24.763",
"Id": "487509",
"Score": "0",
"body": "You're fairly new on CR, the point @Mast might have really been trying to make is that the question is off topic, therefore it shouldn't be answered. For stack overflow this would probably be a great answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T11:09:54.607",
"Id": "487511",
"Score": "2",
"body": "@pacmaninbw I thought/think it's off-topic, too, see my first sentence. But then Dannnno (who has been here longer than even you, and has fairly high reputation) posted their answer, and someone upvoted it. So I figured I'd do it as well. Partially because their solution is so horrifically complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T11:13:37.863",
"Id": "487513",
"Score": "1",
"body": "Agreed, Dannnno should have known better and you did post a better solution."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T15:03:45.220",
"Id": "248769",
"ParentId": "248764",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "248769",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T14:19:54.353",
"Id": "248764",
"Score": "0",
"Tags": [
"java",
"algorithm",
"array",
"search"
],
"Title": "Sum of 2 numbers in an array"
}
|
248764
|
<p>I was wondering whether I could use more data.table functions rather than using for loops in the following piece of code:</p>
<pre><code>library(data.table)
n1 <- data.table(A = c(1:5),
B = c(1:5),
C = c(1:5))
n2 <- data.table(D = c(1:5),
E = c(1:5),
F = c(1:5))
n3 <- data.table(G = c(10:15),
H = c(10:15),
I = c(10:15),
K = c(10:15))
m <- data.table(name1 = c("A", "B", "C"),
name2 = c("E", "F", "D"),
name3 = c("I", "H", "G"))
naming_convention <- function(l, m, index = 1){
if (index > length(l)){
stop("Indices cannot exceed the number of dataframes in the list.")
}
if (ncol(m) != length(l)){
stop("Columns in mapping matrix, need to match the number of dataframes in the list.")
}
new_names <- m[, eval(index), with = FALSE][[1]]
if (length(new_names) != ncol(l[[index]])){
stop("Not all columns are defined of the reference matrix.")
}
for(i in c(1:ncol(m))){
if(i == index){
next
}
temp <- l[[i]]
setnames(temp, old = m[[i]], new = new_names)
l[[i]] <- temp[,..new_names]
}
return(l)
}
l <- list(n1, n2, n3)
naming_convention(l, m, 1)
</code></pre>
<p>Examples:
naming_convention(l, m, 1)</p>
<p>should rename all columns to A, B, C of all the data tables in the list, based on the mapping presented in m matrix. For example, in the second matrix, the E would be mapped to an A, F to be mapped to B and D to be mapped to C. For the third table, I mapped to A, H mapped to B, G mapped to C.</p>
<p>Note that if we change the index to 2, <code>naming_convention(l, m, 2)</code>, all column names should be renamed to E, F, D. So for the first table it would rename A to E, B to F and C to D.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T15:13:04.737",
"Id": "248770",
"Score": "1",
"Tags": [
"r"
],
"Title": "Improvements on column renaming using a mapping table"
}
|
248770
|
<p>I have an .htaccess template I have been working on that I want to submit for code review. I want to accomplish these things:</p>
<ol>
<li>Custom error handling</li>
<li>Remove index.php if in url</li>
<li>Force HTTPS</li>
<li>Remove www.</li>
<li>SEO friendly URLs for a blog</li>
<li>Disable directory browsing</li>
<li>Protect .htaccess</li>
<li>Protect phpinfo.php</li>
</ol>
<p>Here is my code:</p>
<pre><code>RewriteEngine on
ErrorDocument 504 /error.php
ErrorDocument 502 /error.php
ErrorDocument 501 /error.php
ErrorDocument 500 /error.php
ErrorDocument 408 /error.php
ErrorDocument 405 /error.php
ErrorDocument 404 /error.php
ErrorDocument 403 /error.php
ErrorDocument 401 /error.php
ErrorDocument 400 /error.php
RewriteBase /
RewriteRule ^index.php$ / [R,L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,NC,L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,L]
RewriteRule blog/([0-9]+)/ blog.php?id=$1
Options -Indexes
<FilesMatch "^\.htaccess">
Order allow,deny
Deny from all
</FilesMatch>
<Files phpinfo.php>
AuthName "restricted"
AuthUserFile /home/ts/public_html/.htpasswd
AuthType Basic
require valid-user
</Files>
</code></pre>
<p>Is there anything I am missing? Is there anything I should clean up? Is there a better way to do something that I've missed?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-16T01:48:53.150",
"Id": "493214",
"Score": "0",
"body": "Which version of Apache?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T17:50:49.707",
"Id": "248776",
"Score": "2",
"Tags": [
".htaccess"
],
"Title": ".htaccess template"
}
|
248776
|
<p>In my ongoing quest to automate everything I have to do at my job, I've decided to learn how to do webscraping with VBA. I wanted to start with something easy, so the following simply fills out a time-off request and submits it. My main goals while writing this were to:</p>
<ol>
<li><p>Make the code readable and very obvious what everything does.</p>
</li>
<li><p>Try to keep everything as close to having one responsibility as possible.</p>
</li>
</ol>
<p>You won't be able to really run this since I've had to redact some company information, but if you want to compile this, you'll need to enable references to Microsoft Internet Controls and Microsoft HTML Object Library.</p>
<p>With that out of the way, here's the main procedure:</p>
<pre><code>Option Explicit
Public Sub Main()
Dim model As FormModel
Set model = New FormModel
If model.IsValid = False Then
MsgBox "fill in the blanks"
Exit Sub
End If
Dim explorer As InternetExplorer
Set explorer = New InternetExplorer
explorer.Visible = True
GetToLogin explorer
Dim page As HTMLDocument
Set page = explorer.document
InputPassword page
ClickLogin page
HoldUp explorer
GetToTimeOff explorer
Set page = explorer.document
FillOutForm page, model
SubmitRequest page
HoldUp explorer
'TODO: check to make sure submission was successful
explorer.Quit
End Sub
</code></pre>
<p>My plan for checking to make sure the submission is successful is to check the <code>explorer.address</code> to make sure the page goes to the confirmation page, but I won't be able to know what that web address is until I actually submit for time off.</p>
<p><code>FormModel</code> is an object that encapsulates all of the relevant information from <a href="https://i.stack.imgur.com/2mnXQ.png" rel="nofollow noreferrer">the sheet</a>. Here's what the code looks like:</p>
<pre><code>Public Property Get FirstName() As String
FirstName = Sheet1.Range("FirstName").Value
End Property
Public Property Get LastName() As String
LastName = Sheet1.Range("LastName").Value
End Property
Public Property Get Department() As String
Department = Sheet1.Range("Department").Value
End Property
Public Property Get Location() As String
Location = Sheet1.Range("Location").Value
End Property
Public Property Get Email() As String
Email = Sheet1.Range("Email").Value
End Property
Public Property Get ManagersEmail() As String
ManagersEmail = Sheet1.Range("ManagersEmail").Value
End Property
Public Property Get VacationHours() As String
VacationHours = Sheet1.Range("PTO").Value
End Property
Public Property Get UnpaidHours() As String
UnpaidHours = Sheet1.Range("UnpaidHours").Value
End Property
Public Property Get Dates() As String
Dates = Sheet1.Range("Dates").Value
End Property
Public Property Get Comments() As String
Comments = Sheet1.Range("Comments").Value
End Property
Public Property Get IsValid() As Boolean
'if any fields are empty besides comments (comments are not required by the timeoff webpage), returns false
IsValid = Not ((FirstName = vbNullString) Or (LastName = vbNullString) Or _
(Department = vbNullString) Or (Location = vbNullString) Or _
(Email = vbNullString) Or (ManagersEmail = vbNullString) Or _
(VacationHours = vbNullString) Or (UnpaidHours = vbNullString) Or _
(Dates = vbNullString))
End Property
</code></pre>
<p>And here are all the various helper procedures found in main:</p>
<pre><code>Private Sub GetToLogin(ByVal explorer As InternetExplorer)
explorer.navigate "https://example.com/loginpage"
HoldUp explorer
End Sub
Private Sub InputPassword(ByVal page As HTMLDocument)
Dim passwordBox As IHTMLElement
Set passwordBox = page.getElementById("pass")
passwordBox.Value = "supersecrettotallyrealpassword"
End Sub
Private Sub ClickLogin(ByVal page As HTMLDocument)
Dim submitButton As IHTMLElement
'this submit button doesn't have an id for some reason
Set submitButton = page.getElementsByName("submit").Item(0)
submitButton.Click
End Sub
Private Sub GetToTimeOff(ByVal explorer As InternetExplorer)
explorer.navigate "https://example.com/relevantform"
HoldUp explorer
End Sub
Private Sub HoldUp(ByVal explorer As InternetExplorer)
Do While explorer.Busy Or explorer.readyState <> READYSTATE_COMPLETE
Loop
End Sub
Private Sub FillOutForm(ByVal page As HTMLDocument, ByVal model As FormModel)
InputName page, model
InputDepartment page, model
InputLocation page, model
InputEmail page, model
InputManagerEmail page, model
InputPTO page, model
InputUnpaidHours page, model
InputDates page, model
InputComments page, model
End Sub
Private Sub SubmitRequest(ByVal page As HTMLDocument)
Dim submitButton As IHTMLElement
Set submitButton = page.getElementById("vac_request_submit")
submitButton.Click
End Sub
Private Sub InputName(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim firstNameBox As IHTMLElement
Set firstNameBox = page.getElementById("fname")
Dim lastNameBox As IHTMLElement
Set lastNameBox = page.getElementById("lname")
firstNameBox.Value = model.FirstName
lastNameBox.Value = model.LastName
End Sub
Private Sub InputDepartment(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim departmentBox As IHTMLElement
Set departmentBox = page.getElementById("department")
departmentBox.Value = model.Department
End Sub
Private Sub InputLocation(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim locationBox As IHTMLElement
Set locationBox = page.getElementById("location")
locationBox.Value = model.Location
End Sub
Private Sub InputEmail(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim emailBox As IHTMLElement
Set emailBox = page.getElementById("email")
emailBox.Value = model.Email
End Sub
Private Sub InputManagerEmail(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim managerBox As IHTMLElement
Set managerBox = page.getElementById("man_email")
managerBox.Value = model.ManagersEmail
End Sub
Private Sub InputPTO(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim PTOBox As IHTMLElement
Set PTOBox = page.getElementById("request_vac")
PTOBox.Value = model.VacationHours
End Sub
Private Sub InputUnpaidHours(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim unpaidBox As IHTMLElement
Set unpaidBox = page.getElementById("request_unpaid")
unpaidBox.Value = model.UnpaidHours
End Sub
Private Sub InputDates(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim datesBox As IHTMLElement
Set datesBox = page.getElementById("off_time")
datesBox.Value = model.Dates
End Sub
Private Sub InputComments(ByVal page As HTMLDocument, ByVal model As FormModel)
Dim commentsBox As IHTMLElement
Set commentsBox = page.getElementById("comments")
commentsBox.Value = model.Comments
End Sub
</code></pre>
<p>I think the various InputX procedures are the things I'm least happy with, but I'm not exactly sure what I could do to make it better.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T22:53:28.787",
"Id": "488475",
"Score": "0",
"body": "You are aware, that scraping is the worst method to do web-automation? Best is an API (e.g. Rest) to make request as Websites are designed for human readers, APIs for machines. E.g a website gets a redesign (usually no notification), humans are happy as it is more beautiful, machine is sad as can't get the data till programmer tells how-to. If API changes,you get notified, old version is availble some time together with new one (time to adapt code)- If no APi availble you can at least skip those simulated user action (click nutton) and rebuild resulting the form submit request instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T23:08:11.513",
"Id": "488476",
"Score": "0",
"body": "Explorer HoldUp function relies on `explorer.Busy Or explorer.readyState <> READYSTATE_COMPLETE` what is not reliable as e-g iframes create `READYSTATE_COMPLETE` if loaded and you may need to wait for js code executed. To make that more reliable you may check if a specific HTMLElement is availible in DOM and if not return to readystate loop. More improvement can be done by using explorers events (WithEvents) and catch the Document_Completed event (needs check for frames) and then check DOM for `readystate: complete` then code can start scraping. I'll add that as an answer, maybe next week."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T10:55:27.260",
"Id": "488509",
"Score": "0",
"body": "I actually didn't know about any of that stuff, I'm still pretty new to coding in general. I look forward to your answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T07:33:18.527",
"Id": "491310",
"Score": "1",
"body": "If you are on company private network and internally built webpage, API may not be available. In this case, try to talk to your IT to see if they can come up with API endpoints for your needs. That is truly the most efficient and correct way to do it for now. In short, API allows you to `GET` data from and `POST` data to a website. It does not use username-password login method, but uses API-key authentication which shall be provided uniquely for each user."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T17:52:42.740",
"Id": "248777",
"Score": "4",
"Tags": [
"vba",
"excel",
"web-scraping"
],
"Title": "Scraping and filling out a time-off request"
}
|
248777
|
<p>On linux there is the utility called unix2dos which converts UNIX EOLs(\n) to DOS EOLs(\r\n). However on windows there is no such tool so as a result I decided to make one.</p>
<p><code>unix2dos.c</code>:</p>
<pre><code>#include <windows.h>
#include <stdint.h>
#include <stddef.h>
#define chunksize (1 << 13)
#define nullptr ((void *)0)
uint8_t buffer[chunksize + 1] = { 0 };
int64_t newline_count(HANDLE filehandle)
{
DWORD bytes_read = 0;
int64_t result = 0;
do
{
if (ReadFile(filehandle, buffer + 1, chunksize, &bytes_read, nullptr) == 0)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not read file", 26, nullptr, nullptr);
ExitProcess(GetLastError());
}
if (SetFilePointerEx(filehandle, (LARGE_INTEGER) { .QuadPart = -1 }, nullptr, SEEK_CUR) == 0)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not read file", 26, nullptr, nullptr);
ExitProcess(GetLastError());
}
if (ReadFile(filehandle, buffer, 1, nullptr, nullptr) == 0)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not read file", 26, nullptr, nullptr);
ExitProcess(GetLastError());
}
if (SetFilePointerEx(filehandle, (LARGE_INTEGER) { .QuadPart = -1 }, nullptr, SEEK_CUR) == 0)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not read file", 26, nullptr, nullptr);
ExitProcess(GetLastError());
}
for (uint8_t *start = buffer + 1; start != buffer + 1 + (int64_t)bytes_read; ++start)
{
if (start[0] == '\n' && start[-1] != '\r') ++result;
}
} while (bytes_read == chunksize);
return result;
}
void unix2dos1(wchar_t const *const src, wchar_t const *const dst)
{
HANDLE const dst_file = CreateFileW(dst, GENERIC_ALL, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (dst_file == INVALID_HANDLE_VALUE)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not open ", 22, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), dst, lstrlenW(dst), nullptr, nullptr);
ExitProcess(GetLastError());
}
HANDLE const src_file = CreateFileW(src, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (src_file == INVALID_HANDLE_VALUE)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not open ", 22, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), src, lstrlenW(src), nullptr, nullptr);
ExitProcess(GetLastError());
}
int64_t invalid_newline_count = newline_count(src_file);
LARGE_INTEGER end_locaition = { 0 };
if (GetFileSizeEx(src_file, &end_locaition) == 0)
{
CloseHandle(src_file);
CloseHandle(dst_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not get the size of ", 33, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), src, lstrlenW(src), nullptr, nullptr);
ExitProcess(GetLastError());
}
if (SetFilePointerEx(dst_file, (LARGE_INTEGER) { .QuadPart = invalid_newline_count + end_locaition.QuadPart }, &end_locaition, FILE_BEGIN) == 0)
{
CloseHandle(src_file);
CloseHandle(dst_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not resize ", 24, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), dst, lstrlenW(dst), nullptr, nullptr);
ExitProcess(GetLastError());
}
if (SetEndOfFile(dst_file) == 0)
{
CloseHandle(dst_file);
CloseHandle(src_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not resize ", 24, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), dst, lstrlenW(dst), nullptr, nullptr);
ExitProcess(GetLastError());
}
HANDLE const dst_memory_mapped_file = CreateFileMappingW(
dst_file,
nullptr,
PAGE_READWRITE,
0, 0,
nullptr
);
if (dst_memory_mapped_file == nullptr)
{
CloseHandle(src_file);
CloseHandle(dst_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not create file mapping object for ", 48, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), dst, lstrlenW(dst), nullptr, nullptr);
ExitProcess(GetLastError());
}
HANDLE const src_memory_mapped_file = CreateFileMappingW(
src_file,
nullptr,
PAGE_READONLY,
0, 0,
nullptr
);
if (src_memory_mapped_file == nullptr)
{
CloseHandle(dst_memory_mapped_file);
CloseHandle(src_file);
CloseHandle(dst_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not create file mapping object for ", 48, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), src, lstrlenW(src), nullptr, nullptr);
ExitProcess(GetLastError());
}
uint8_t *const src_file_buffer = MapViewOfFile(src_memory_mapped_file, FILE_MAP_READ, 0, 0, end_locaition.QuadPart - invalid_newline_count);
if (src_file_buffer == nullptr)
{
CloseHandle(dst_memory_mapped_file);
CloseHandle(src_memory_mapped_file);
CloseHandle(src_file);
CloseHandle(dst_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not map view of ", 29, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), src, lstrlenW(src), nullptr, nullptr);
ExitProcess(GetLastError());
}
uint8_t *const dst_file_buffer = MapViewOfFile(dst_memory_mapped_file, FILE_MAP_ALL_ACCESS, 0, 0, end_locaition.QuadPart);
if (dst_file_buffer == nullptr)
{
UnmapViewOfFile(src_file_buffer);
CloseHandle(dst_memory_mapped_file);
CloseHandle(src_memory_mapped_file);
CloseHandle(src_file);
CloseHandle(dst_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not map view of ", 29, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), dst, lstrlenW(dst), nullptr, nullptr);
ExitProcess(GetLastError());
}
uint8_t *start1 = src_file_buffer;
uint8_t *start2 = dst_file_buffer;
end_locaition.QuadPart -= invalid_newline_count;
for (; end_locaition.QuadPart; ++start1, ++start2, --end_locaition.QuadPart)
{
if (start1[0] == '\n')
{
if (start1 - 1 <= src_file_buffer || start1[-1] != '\r')
{
*start2++ = '\r';
}
}
start2[0] = start1[0];
}
UnmapViewOfFile(src_file_buffer);
UnmapViewOfFile(dst_file_buffer);
CloseHandle(dst_memory_mapped_file);
CloseHandle(src_memory_mapped_file);
CloseHandle(src_file);
CloseHandle(dst_file);
}
void unix2dos2(const wchar_t *const filepath)
{
HANDLE const file = CreateFileW(filepath, GENERIC_ALL, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE)
{
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not open ", 22, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), filepath, lstrlenW(filepath), nullptr, nullptr);
ExitProcess(GetLastError());
}
int64_t invalid_newline_count = newline_count(file);
if (invalid_newline_count == 0)
{
CloseHandle(file);
return;
}
LARGE_INTEGER end_locaition = { 0 };
if (SetFilePointerEx(file, (LARGE_INTEGER) { .QuadPart = invalid_newline_count }, &end_locaition, FILE_END) == 0)
{
CloseHandle(file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not resize ", 24, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), filepath, lstrlenW(filepath), nullptr, nullptr);
ExitProcess(GetLastError());
}
if (SetEndOfFile(file) == 0)
{
CloseHandle(file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not resize ", 24, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), filepath, lstrlenW(filepath), nullptr, nullptr);
ExitProcess(GetLastError());
}
HANDLE const memory_mapped_file = CreateFileMappingW(
file,
nullptr,
PAGE_READWRITE,
0, 0,
nullptr
);
if (memory_mapped_file == nullptr)
{
CloseHandle(file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not create file mapping object for ", 48, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), filepath, lstrlenW(filepath), nullptr, nullptr);
ExitProcess(GetLastError());
}
uint8_t *const file_buffer = MapViewOfFile(memory_mapped_file, FILE_MAP_ALL_ACCESS, 0, 0, end_locaition.QuadPart);
if (file_buffer == nullptr)
{
CloseHandle(file);
CloseHandle(memory_mapped_file);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), L"Error: could not map view of ", 29, nullptr, nullptr);
WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), filepath, lstrlenW(filepath), nullptr, nullptr);
ExitProcess(GetLastError());
}
uint8_t *start1 = file_buffer + end_locaition.QuadPart - invalid_newline_count - 1;
uint8_t *start2 = file_buffer + end_locaition.QuadPart - 1;
for (; start1 - file_buffer >= 0; --start1, --start2)
{
start2[0] = start1[0];
if (start1[0] == '\n')
{
if (start1 - 1 <= file_buffer || start1[-1] != '\r')
{
*--start2 = '\r';
}
}
}
/* cleanup */
UnmapViewOfFile(file_buffer);
CloseHandle(memory_mapped_file);
CloseHandle(file);
}
void __cdecl mainCRTStartup()
{
int argc;
wchar_t **const argv = CommandLineToArgvW(GetCommandLineW(), &argc) + 1;
--argc;
enum mode
{
mode_overwrite = 0x0,
mode_create_file = 0x1,
} current_mode = { mode_overwrite };
for (int i = 0; i < argc; ++i)
{
if (lstrcmpW(argv[i], L"-o") == 0)
{
current_mode = mode_overwrite;
}
else if (lstrcmpW(argv[i], L"-n") == 0)
{
current_mode = mode_create_file;
}
else
{
switch (current_mode)
{
case mode_overwrite:
unix2dos2(argv[i]);
break;
case mode_create_file:
if (lstrcmpW(argv[i], argv[i + 1]) != 0)
{
unix2dos1(argv[i], argv[i + 1]);
}
else
{
unix2dos2(argv[i]);
}
++i;
break;
}
}
}
/* free memory and exit */
LocalFree(argv - 1);
ExitProcess(0);
}
</code></pre>
<p>to build the code use</p>
<pre><code>cl.exe -nologo -Oi -GS -Gs9999999 unix2dos.c -link -subsystem:console -nodefaultlib kernel32.lib shell32.lib -stack:0x100000,0x100000
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:36:21.793",
"Id": "487446",
"Score": "3",
"body": "Is this still part of your challenge not to use anything from the standard library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:40:03.817",
"Id": "487447",
"Score": "3",
"body": "Also, the documentation of the dos2unix tool mentions it can be built with MSVC, see: https://sourceforge.net/p/dos2unix/dos2unix/ci/master/tree/dos2unix/INSTALL.txt"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:42:09.790",
"Id": "487448",
"Score": "0",
"body": "Yes it is still part of my challenge."
}
] |
[
{
"body": "<p><strong>Overall design</strong></p>\n<p>Code makes heavy use of data as a file with a known size. I'd favor a stream approach where the conversion is done as data arrives and then written, negating the need for any large buffers.</p>\n<p><strong>mode_overwrite design</strong></p>\n<p>In my opinion, re-writing a file should not destroy the original until after the new file is <em>completely</em> written.</p>\n<p>I'd favor writing to a temporary new file first, rename files and then destroy the original.</p>\n<p>Should an error occur in the process, far easier to still have the original file around for recovery.</p>\n<p><strong>Memory mapping</strong></p>\n<p>The use of <code>CreateFileMappingW()</code> after walking the entire file with <code>newline_count()</code> reduces the benefit of mapping. It would make more sense to map the file and then read it for <code>CR/LF</code>.</p>\n<p><strong>Logic error</strong></p>\n<p>In <code>newline_count()</code>, there is no need for the 2nd. <code>SetFilePointerEx()</code>.</p>\n<p><code>newline_count()</code> is also amiss in re-reading the the last character of the buffer into <code>buffer[0]</code>. What should be in <code>buffer[0]</code> is the last value from the previous block read.</p>\n<p><strong>Pointer computation error</strong></p>\n<p><code>start1 - 1</code> is invalid (UB) to compute when <code>start1 == src_file_buffer</code>. Instead</p>\n<pre><code>// start1 - 1 <= src_file_buffer\nstart1 <= src_file_buffer + 1\n</code></pre>\n<p><strong>Access is UB</strong></p>\n<p><code>start1[-1]</code> is UB when <code>start1 == src_file_buffer</code>.</p>\n<p><strong>Confusing error message</strong></p>\n<p><code>SetFilePointerEx()</code> may report "Error: could not read file", yet the error is not in reading, but seeking.</p>\n<p><strong>Avoid error prone magic numbers</strong></p>\n<p>Rather than <code>..., L"Error: could not resize ", 24, ...</code></p>\n<pre><code>wchar_t err[] = L"Error: could not resize ";\n... err, sizeof err / sizeof err[0],...\n</code></pre>\n<p>Or other self-calculating code.</p>\n<p><strong>Potential out of range access</strong></p>\n<p><code>argv[i + 1]</code> is attempted without knowing <code>i + 1 < argc</code>.</p>\n<p><strong>Minor</strong></p>\n<p><code>locaition</code> --> <code>location</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T15:03:47.493",
"Id": "487852",
"Score": "0",
"body": "the extra `SetFilePointerEx()` is needed because by reading chunks you could end up only reading part of an EOL which would cause a false positive when reading the next chunk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T15:44:27.933",
"Id": "487853",
"Score": "0",
"body": "also even if `start1 == src_file_buffer` is true `start1[-1]` would not be evaluated in that case because of short circuiting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T08:07:17.417",
"Id": "248953",
"ParentId": "248778",
"Score": "5"
}
},
{
"body": "<p>It takes some time to navigate through all the error logging to reach the code that actually does the line ending conversion.</p>\n<p>Avoiding standard library functions doesn't mean you can't write some utility functions yourself, like a wrapper around <code>WriteConsoleW</code> to prevent passing all those arguments throughout the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T09:28:07.247",
"Id": "248955",
"ParentId": "248778",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248953",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:14:45.947",
"Id": "248778",
"Score": "1",
"Tags": [
"c",
"reinventing-the-wheel",
"windows"
],
"Title": "a simple implementation of unix2dos for windows"
}
|
248778
|
<p>This is a Windows forms application.</p>
<p><code>this.Server.GetLogMessages()</code> will block if there are no messages to get, so I want this in a separate thread. I'm putting the messages into a <code>ConcurrentStack</code> and then pulling them out on the main thread to output them.</p>
<p>Here is the respective code:</p>
<pre><code>private async Task UpdateLogs()
{
var logMessages = new ConcurrentStack<string>();
// assign to `_` to avoid warning
var _ = Task.Run(async () =>
{
await foreach (var message in this.Server.GetLogMessages())
{
logMessages.Push(message);
}
}, this.CancellationTokenSource.Token);
await foreach (var message in GetMessages())
{
// don't update the UI if task is canceled
if (this.CancellationTokenSource.Token.IsCancellationRequested)
{
break;
}
this.textLogs.AppendText($"{message}{Environment.NewLine}");
}
async IAsyncEnumerable<string> GetMessages()
{
var message = String.Empty;
while (!this.CancellationTokenSource.IsCancellationRequested)
{
while (!logMessages.TryPop(out message))
{
await Task.Delay(100);
}
yield return message;
}
}
}
</code></pre>
<p>It works fine, but seems as if it could be better/cleaner somehow.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T23:52:19.177",
"Id": "487469",
"Score": "1",
"body": "_this.Server.GetLogMessages() will block if there are no messages to get_ means that the method is not properly implemented. Can it be fixed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:24:00.260",
"Id": "487636",
"Score": "0",
"body": "Have you considered to use DataFlow for this problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:26:49.970",
"Id": "487646",
"Score": "1",
"body": "@aepot It may be able to be fixed. That is a different issue though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:27:03.770",
"Id": "487647",
"Score": "0",
"body": "@PeterCsala I have not heard of that. What is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:35:06.060",
"Id": "487676",
"Score": "0",
"body": "@rhughes [Here](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library) you can find an introduction article and [here](https://www.microsoft.com/en-us/download/details.aspx?id=14782) you can find a couple of good examples for the basic building blocks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:39:47.903",
"Id": "487678",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T22:10:35.977",
"Id": "487806",
"Score": "0",
"body": "Was my answer helpful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T23:25:46.897",
"Id": "487807",
"Score": "1",
"body": "@aepot It seems so. I haven't tested it yet sorry. I will let you know."
}
] |
[
{
"body": "<p>My try to simplify and prettify the method.</p>\n<p>Avoid using globals in async code, pass Token as argument.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>// optimized out async State Machine\nprivate Task UpdateLogsAsync(IProgress<string> status, CancellationToken token) => Task.Run(async () =>\n{\n await foreach (var message in this.Server.GetLogMessages().WithCancellation(token))\n {\n status.Report(message);\n }\n}, token);\n</code></pre>\n<p>Usage</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>// synchronized callback. Create new in UI Thread and its body will be always executed there.\nIProgress<string> status = new Progess<string>(message =>\n{\n this.textLogs.AppendText($"{message}{Environment.NewLine}");\n});\ntry\n{\n await UpdateLogsAsync(status, this.CancellationTokenSource.Token);\n}\ncatch (OperationCanceledException ex)\n{\n status.Report(ex.Message);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T07:36:14.480",
"Id": "487624",
"Score": "0",
"body": "You can take advantage of the `WithCancellation` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T07:55:40.993",
"Id": "487625",
"Score": "0",
"body": "@PeterCsala `this.Server.GetLogMessages().WithCancellation(token)`? Sorry, I'm not familiar with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:46:43.097",
"Id": "487627",
"Score": "1",
"body": "Yes, as long as the `GetLogMessages` returns with an `IAsyncEnumerable<T>` then you can use the `WithCancellation` [extension method](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskasyncenumerableextensions.withcancellation?view=dotnet-plat-ext-3.1) to pass the ct to the async enumerator. For further details please check the following [SO answer](https://stackoverflow.com/a/59300816/13268855)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:48:20.463",
"Id": "487628",
"Score": "0",
"body": "@PeterCsala got it, thank you! Updated the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:55:24.043",
"Id": "487629",
"Score": "1",
"body": "In this case there is no need to explicitly call this:`token.ThrowIfCancellationRequested();`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T00:15:57.270",
"Id": "248788",
"ParentId": "248780",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248788",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:27:29.790",
"Id": "248780",
"Score": "4",
"Tags": [
"c#",
"task-parallel-library",
".net-core"
],
"Title": "Updating items in a list from a blocking source asynchronously"
}
|
248780
|
<h1>What?, Why?</h1>
<p>I have been inspired by several other posts on the topic of OOP implementations in VBA to try and create a Pacman clone. I think this task is not all that hard in most languages; but, I first learned how to code via VBA and I, perhaps, have a masochistic fondness for the framework. VBA comes with a host of challenges (lack of inheritance, single thread environment, etc) that I seek to overcome.</p>
<p>One of my main goals with an OOP implementation is to have the game logic decoupled from the UI so that one could implement a UI as an Excel Worksheet, or a Userform, or whatever else you might imagine available to you in VBA. The other goal is to get as close to the real game rules as I can.</p>
<p>There is going to be a lot to go over, so I hope you don't mind me breaking this into multiple code review posts, each with some smaller scope of focus. For this post, I'd like to get feedback on my overall architecture plan, and give you a very general look at the game logic class and how I intend to make it interface-able to a UI. (The first UI implementation will be an Excel Worksheet).</p>
<h1>Architecture</h1>
<p>The design will resemble an MVP pattern with the idea that the View part of the architecture can be implemented in any number of ways. Again, in this case, I will implement an Excel Worksheet-based view for the game. I've included a (likely incomplete) diagram to help illustrate as well as my Rubberduck folder structure (also incomplete)</p>
<p><a href="https://i.stack.imgur.com/OvzG2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OvzG2.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/WeZy3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WeZy3.png" alt="enter image description here" /></a></p>
<p><strong>Models</strong><br/>
Models will consist of the various game elements. In a truly decoupled design, these would be simple <em>POVOs(?)</em>, but I plan to encapsulate some game logic into the models because these models won't ever have much use outside of the context of the Pacman game and it will make the game controller a little simpler. For example, characters like pacman and the ghosts will know how to move around in the maze. That way, the controller can simply call a <code>Move()</code> member in each of them. I will save the models' code for another code review post.</p>
<p><strong>View</strong><br/>
I don't really care too much about having a super flexible, independent view; so in my design, any view implemented for the Pacman game will know about the models. This will make passing data to the view much simpler because we can just pass the entire model(s). The game controller will talk to the view through an interface layer. The idea is that the View will implement the <code>IGameEventsHandler</code> interface so that the Controller can call methods in the View as game events happen. The View will also have a reference to an <code>IViewEventsHandler</code> class so that it can call event methods to notify the Controller of user generated events.</p>
<p><strong>Controller</strong><br/>
The controller will hold much of the game logic and will facilitate the continuous ticking of the game progression. Because of how events are done in VBA, I have an extra <code>ViewAdapter</code> class that will help facilitate listening to events from the View. When user generated things happen, the View can call <code>IViewEventsHandler</code> methods in the concrete <code>ViewAdapter</code> class, which will, in turn, raise an event to the controller. This way, events from the View can "interrupt" the game ticking in the controller thanks to <code>DoEvents</code> calls that will happen with every tick. (This is step 1 in overcoming our single-thread limitation).</p>
<h1>Code Samples</h1>
<h2>Interfaces</h2>
<p><strong>IGameEventsHandler:</strong></p>
<pre><code>'@Folder "PacmanGame.View"
'@Interface
'@ModuleDescription("Methods that the Controller will need to be able to call in the UI. These are things the Controller will need to tell the UI to do.")
Option Explicit
Private Const mModuleName As String = "IGameEventsHandler"
'@Description("Provides a way for the ViewAdapter to hook itself into an IGameEventsHandler implementer")
Public Property Get Events() As IViewEventsHandler
End Property
Public Property Set Events(ByVal value As IViewEventsHandler)
End Property
Public Sub CreateMap(map() As Tile)
End Sub
Public Sub CreatePacman(character As PacmanModel)
End Sub
Public Sub CreateGhost(character As GhostModel)
End Sub
Public Sub UpdateComponents(gamePieces As Collection)
End Sub
Private Sub Class_Initialize()
Err.Raise 5, mModuleName, "Interface class must not be instantiated."
End Sub
</code></pre>
<p><strong>IViewEventsHandler:</strong></p>
<pre><code>'@Folder "PacmanGame.View"
'@Interface
'@ModuleDescription("Methods that the UI can call to notify the controller of user interaction. These are events from the UI that the Controller wants to hear about")
Option Explicit
Private Const mModuleName As String = "IViewEventsHandler"
Public Enum KeyCode
LeftArrow = 37
RightArrow = 39
UpArrow = 38
DownArrow = 40
End Enum
Public Sub OnDirectionalKeyPress(vbKey As KeyCode)
End Sub
Public Sub OnGameStarted()
End Sub
Public Sub OnGamePaused()
End Sub
Public Sub OnQuit()
End Sub
Private Sub Class_Initialize()
Err.Raise 5, mModuleName, "Interface class must not be instantiated."
End Sub
</code></pre>
<h2>WorksheetViewWrapper</h2>
<p>This is a facade class that will wrap an <code>Excel.Worksheet</code> to use as our UI. This code <em>could</em> go directly into a worksheet class, but alas, you cannot make a worksheet <code>Implement</code> anything in the code-behind.</p>
<pre><code>'@Folder "ViewImplementations.ExcelWorksheet"
'//UI implemented as an Excel Worksheet
Option Explicit
Implements IGameEventsHandler
Private Const MAP_START_ADDRESS As String = "$D$3"
Private Type TWorksheetViewWrapper
MapRange As Range
dPad As Range
Adapter As IViewEventsHandler
ShapeWrappers As Dictionary
YIndexOffset As Long
XIndexOffset As Long
End Type
Private WithEvents innerWs As Worksheet
Private this As TWorksheetViewWrapper
Public Sub Init(xlWs As Worksheet)
Dim s As Shape
For Each s In xlWs.Shapes
s.Delete
Next
xlWs.Activate
xlWs.Range("AE65").Select
Set innerWs = xlWs
Set this.dPad = xlWs.Range("AE65")
End Sub
Private Sub Class_Initialize()
Set this.ShapeWrappers = New Dictionary
End Sub
Private Sub Class_Terminate()
Set this.Adapter = Nothing
Set innerWs = Nothing
Set this.dPad = Nothing
Debug.Print TypeName(Me) & " terminating..."
End Sub
'// Support for IGameEventsHandler
Private Sub IGameEventsHandler_CreateGhost(character As GhostModel)
'// Create a corrosponding ViewModel Ghost
Dim newGhostShape As New GhostStyler
newGhostShape.Init innerWs, character.Color
'// Add him to the drawing collection
this.ShapeWrappers.Add character.Name, newGhostShape
End Sub
Private Sub IGameEventsHandler_CreatePacman(character As PacmanModel)
'// Create a corrosponding ViewModel Pacman
Dim newPacmanShape As New PacmanStyler
newPacmanShape.Init innerWs
'// Add him to the drawing collection
this.ShapeWrappers.Add character.Name, newPacmanShape
End Sub
Private Sub IGameEventsHandler_CreateMap(map() As Tile)
this.YIndexOffset = 1 - LBound(map, 1)
this.XIndexOffset = 1 - LBound(map, 2)
Set this.MapRange = innerWs.Range(MAP_START_ADDRESS).Resize(UBound(map, 1) + this.YIndexOffset, UBound(map, 2) + this.XIndexOffset)
End Sub
Private Sub IGameEventsHandler_UpdateComponents(characters As Collection)
Dim character As IGamePiece
Dim characterShape As IDrawable
Dim i As Integer
For Each character In characters
'// use the id from each character to get the corresponding ShapeWrapper
Set characterShape = this.ShapeWrappers.Item(character.Id)
characterShape.Redraw character.CurrentHeading, TileToRange(character.CurrentTile)
Next
End Sub
Private Property Set IGameEventsHandler_Events(ByVal RHS As IViewEventsHandler)
Set this.Adapter = RHS
End Property
Private Property Get IGameEventsHandler_Events() As IViewEventsHandler
Set IGameEventsHandler_Events = this.Adapter
End Property
'// Events from the worksheet that we will translate into view events
Private Sub innerWs_Activate()
'// maybe pause the game?
End Sub
Private Sub innerWs_Deactivate()
'// maybe we need a resume game event?
End Sub
Private Sub innerWs_SelectionChange(ByVal Target As Range)
If this.dPad.Offset(-1, 0).Address = Target.Address Then
this.Adapter.OnDirectionalKeyPress UpArrow
ElseIf this.dPad.Offset(1, 0).Address = Target.Address Then
this.Adapter.OnDirectionalKeyPress (DownArrow)
ElseIf this.dPad.Offset(0, -1).Address = Target.Address Then
this.Adapter.OnDirectionalKeyPress (LeftArrow)
ElseIf this.dPad.Offset(0, 1).Address = Target.Address Then
this.Adapter.OnDirectionalKeyPress (RightArrow)
End If
Application.EnableEvents = False
this.dPad.Select
Application.EnableEvents = True
End Sub
'// Private helpers
Private Function TileToRange(mapTile As Tile) As Range
Set TileToRange = this.MapRange.Cells(mapTile.y + this.YIndexOffset, mapTile.x + this.XIndexOffset)
End Function
</code></pre>
<h2>Adapter</h2>
<pre><code>'@Folder "PacmanGame.View"
Option Explicit
Implements IViewEventsHandler
Implements IGameEventsHandler
Private Const mModuleName As String = "ViewAdapter"
Private viewUI As IGameEventsHandler
Public Event DirectionalKeyPressed(vbKeyCode As KeyCode)
Public Event GameStarted()
Public Event GamePaused()
Public Event Quit()
Public Sub Init(inViewUI As IGameEventsHandler)
Set viewUI = inViewUI
Set viewUI.Events = Me
End Sub
Public Sub Deconstruct()
'// unhooks itself from the GameEventsHandler to prevent memory leakage
Set viewUI.Events = Nothing
End Sub
Public Function AsCommandSender() As IGameEventsHandler
'// allows access to the IGameEventsHandler methods
Set AsCommandSender = Me
End Function
Private Sub Class_Terminate()
Set viewUI = Nothing
Debug.Print TypeName(Me) & " terminating..."
End Sub
'//IGameEventsHandler Support
Private Property Set IGameEventsHandler_Events(ByVal RHS As IViewEventsHandler)
'//this isn't meant to be set from the outside for this class
End Property
Private Property Get IGameEventsHandler_Events() As IViewEventsHandler
Set IGameEventsHandler_Events = Me
End Property
Private Sub IGameEventsHandler_CreateGhost(character As GhostModel)
viewUI.CreateGhost character
End Sub
Private Sub IGameEventsHandler_CreatePacman(character As PacmanModel)
viewUI.CreatePacman character
End Sub
Private Sub IGameEventsHandler_CreateMap(map() As Tile)
viewUI.CreateMap map
End Sub
Private Sub IGameEventsHandler_UpdateComponents(characters As Collection)
viewUI.UpdateComponents characters
End Sub
'//IViewEventsHandler Support
Private Sub IViewEventsHandler_OnDirectionalKeyPress(vbKey As KeyCode)
RaiseEvent DirectionalKeyPressed(vbKey)
End Sub
Private Sub IViewEventsHandler_OnGamePaused()
RaiseEvent GamePaused
End Sub
Private Sub IViewEventsHandler_OnGameStarted()
RaiseEvent GameStarted
End Sub
Private Sub IViewEventsHandler_OnQuit()
RaiseEvent Quit
End Sub
</code></pre>
<h2>Controller</h2>
<p><em>This class is obviously a WIP, but I've included it here to show how the Controller uses a ViewAdapter to send/receive messages to/from the View</em></p>
<pre><code>'@Folder "PacmanGame.Controller"
'@Exposed
Option Explicit
Private Const mModuleName As String = "GameController"
Private Const SECONDS_PER_TICK As Double = 0.06 '// sets a minimum amount of time (in seconds) that will pass between game ticks
Private Const TICK_CYCLE_RESOLUTION As Double = 10 '// helps faciliate game pieces moving at different speeds
Public WithEvents UIAdapter As ViewAdapter
Public Enum Direction
dNone = 0
dUp = -1
dDown = 1
dLeft = -2
dRight = 2
End Enum
'//Encasulated Fields
Private Type TGameController
IsGameOver As Boolean
Maze() As Tile
TickCounter As Long
Ghosts As Collection
GamePieces As Collection
Player As PacmanModel
End Type
Private this As TGameController
Public Sub StartGame()
'// this is here to temporarily provide a way for me to kick off the game from code
UIAdapter_GameStarted
End Sub
Private Sub Class_Initialize()
Set this.GamePieces = New Collection
End Sub
Private Sub Class_Terminate()
Debug.Print TypeName(Me) & " terminating..."
Set this.GamePieces = Nothing
UIAdapter.Deconstruct
Erase this.Maze
Erase MapManager.Maze
Set UIAdapter = Nothing
End Sub
'// This is the main engine of the game that is called repeatedly until the game is over
Private Sub Tick()
Dim t As Double
t = Timer
Dim character As IGamePiece
For Each character In this.GamePieces
If character.CycleRemainder >= TICK_CYCLE_RESOLUTION Then
character.CycleRemainder = character.CycleRemainder Mod TICK_CYCLE_RESOLUTION
character.Move
Else
If this.TickCounter Mod Round(TICK_CYCLE_RESOLUTION / (TICK_CYCLE_RESOLUTION * (1 - character.Speed)), 0) <> 0 Then
character.CycleRemainder = character.CycleRemainder + TICK_CYCLE_RESOLUTION Mod (TICK_CYCLE_RESOLUTION * (1 - character.Speed))
character.Move
End If
If Round(TICK_CYCLE_RESOLUTION / (TICK_CYCLE_RESOLUTION * (1 - character.Speed)), 0) = 1 Then
character.CycleRemainder = character.CycleRemainder + TICK_CYCLE_RESOLUTION Mod (TICK_CYCLE_RESOLUTION * (1 - character.Speed))
End If
End If
Next
'// TODO: check if player died and/or there is a game over... account for player Lives > 1
'If this.Player.IsDead Then IsGameOver = True
'// update the view
UIAdapter.AsCommandSender.UpdateComponents this.GamePieces
'// ensure a minimum amount of time has passed
Do
DoEvents
Loop Until Timer > t + SECONDS_PER_TICK
End Sub
'//ViewEvents Handling
Private Sub UIAdapter_DirectionalKeyPressed(vbKeyCode As KeyCode)
Select Case vbKeyCode
Case KeyCode.UpArrow
this.Player.Heading = dUp
Case KeyCode.DownArrow
this.Player.Heading = dDown
Case KeyCode.LeftArrow
this.Player.Heading = dLeft
Case KeyCode.RightArrow
this.Player.Heading = dRight
End Select
End Sub
Private Sub UIAdapter_GameStarted()
'// TODO: unbloat this a bit!
'// initialize vars
'//scoreboard
'//
'// initialize game peices
Dim blinky As GhostModel
Dim inky As GhostModel
Dim pinky As GhostModel
Dim clyde As GhostModel
'// set up maze
this.Maze = MapManager.LoadMapFromFile
MapManager.Maze = this.Maze
UIAdapter.AsCommandSender.CreateMap this.Maze
'// set up pacman
Set this.Player = New PacmanModel
Set this.Player.CurrentTile = MapManager.GetMazeTile(46, 30)
this.GamePieces.Add this.Player
UIAdapter.AsCommandSender.CreatePacman this.Player
'// set up ghosts
Set blinky = BuildGhost("Blinky", vbRed, MapManager.GetMazeTile(22, 30), ShadowBehavior.Create(this.Player))
this.GamePieces.Add blinky
UIAdapter.AsCommandSender.CreateGhost blinky
Set pinky = BuildGhost("Pinky", rgbLightPink, MapManager.GetMazeTile(22, 20), SpeedyBehavior.Create(this.Player))
this.GamePieces.Add pinky
UIAdapter.AsCommandSender.CreateGhost pinky
Set inky = BuildGhost("Inky", vbCyan, MapManager.GetMazeTile(22, 34), BashfulBehavior.Create(this.Player, blinky))
this.GamePieces.Add inky
UIAdapter.AsCommandSender.CreateGhost inky
Set clyde = BuildGhost("Clyde", rgbOrange, MapManager.GetMazeTile(22, 37), RandomBehavior.Create())
this.GamePieces.Add clyde
UIAdapter.AsCommandSender.CreateGhost clyde
'//play intro
this.TickCounter = 0
Do While Not this.IsGameOver
'DoEvents
'If TickCounter = MaxCycles Then TickCounter = 0
this.TickCounter = this.TickCounter + 1
Tick
'DoEvents
Loop
End Sub
'//Private Helpers
Private Function BuildGhost(Name As String, _
Color As Long, _
startTile As Tile, behavior As IGhostBehavior) As GhostModel
Dim newGhost As GhostModel
Set newGhost = New GhostModel
With newGhost
.Name = Name
.Color = Color
Set .CurrentTile = startTile
Set .ActiveBehavior = behavior
End With
Set BuildGhost = newGhost
End Function
Private Sub BuildGameBoard()
UIAdapter.AsCommandSender.CreateMap Me.Maze
End Sub
</code></pre>
<h3>Client - putting it all together:</h3>
<p>Here is some sample code that illustrates how some client code might snap all the pieces together to have a functioning game.</p>
<pre><code>Public Sub Main()
'//get our concrete sheet
Dim xlWs As Worksheet
Set xlWs = Sheet1
'//wrap it up
Dim sheetWrapper As WorksheetViewWrapper
Set sheetWrapper = New WorksheetViewWrapper
sheetWrapper.Init xlWs
'//give it to a game adapter
Dim viewUIAdapter As ViewAdapter
Set viewUIAdapter = New ViewAdapter
viewUIAdapter.Init sheetWrapper
'//hand that to a new controller
Set mController = New GameController
Set mController.UIAdapter = viewUIAdapter
'//start the game!
mController.StartGame
End Sub
</code></pre>
<p>I welcome any critiques on my architecture plan, naming conventions, and even nit picks! One of my specific questions is this: at some point I need to configure the game controller by setting its player, viewAdapter, ghosts, map, etc properties. It seems to me that the ViewAdapter should be injected from the outside. Should the other components also be injected? or should I just let the controller configure all of these internally?</p>
<p>I have published my entire project to a <a href="https://github.com/iamkylescode/Pacman" rel="noreferrer">github repo</a> so that you can build and run what I have working so far. There are so many parts in this project, so please forgive me as I attempt to balance <em>completeness</em> with <em>overbroadness</em> in my posts. In forthcoming posts, I plan to ask for code review on these topics: Moving game piece models and moving them at different speeds, map/maze building and interaction, animating game action in the view, and probably some others as I further development. Thank you for reading this whole thing!!!</p>
<h3>Acknowledgements</h3>
<ol>
<li>Everyone's favorite VBE addin, <a href="https://rubberduckvba.com/" rel="noreferrer">Rubberduck</a>!</li>
<li><a href="https://stackoverflow.com/a/45825831/6071871">This SO answer</a> which got me thinking about all this VBA OOP viability in the first place.</li>
<li><a href="https://github.com/rubberduck-vba/Battleship" rel="noreferrer">This excel version of Battleship</a> from which I have mimicked the Adapter-events-passing pattern.</li>
<li><a href="https://www.gamasutra.com/view/feature/132330/the_pacman_dossier.php?page=2" rel="noreferrer">Pacman Dossier</a> has very detailed analysis of the inner workings of pacman.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T23:13:58.203",
"Id": "487465",
"Score": "7",
"body": "*\"[...] and I, perhaps, have a masochistic fondness for the framework. VBA comes with a host of challenges [...] that I seek to overcome.\"* - this, right there. So much this! #NotAlone ;-) ...would love to see this on GitHub!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T00:01:05.127",
"Id": "487471",
"Score": "5",
"body": "This is awesome. Not only is it Pac-Man, you included an architecture diagram. *Chef’s Kiss*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T00:31:48.870",
"Id": "487472",
"Score": "2",
"body": "@RubberDuck thank you for the love! I'm glad to not be the only one enthusiastic about something as silly as this! <3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T04:04:20.173",
"Id": "487483",
"Score": "2",
"body": "You're off to a great start. Have you read [Understanding Pac-Man Ghost Behavior](https://gameinternals.com/understanding-pac-man-ghost-behavior)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T12:58:15.323",
"Id": "487525",
"Score": "1",
"body": "@MathieuGuindon repo added! I'm curious to see how well it will work on a machine other than my own!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:00:22.757",
"Id": "487527",
"Score": "1",
"body": "@TinMan Yes! I've created a family of classes for ghost behaviors that can be injected into the ghosts. It will change the way they find a target tile. The part I find tricky is speeding up blinky as the game progresses. I have some ideas though which I'll explore in another CR post :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T18:21:26.853",
"Id": "487571",
"Score": "1",
"body": "+1 for effort, and I wish I could +1 again for you possibly coining the term POVO :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T19:46:56.410",
"Id": "487579",
"Score": "2",
"body": "+1 Simply awesome. Rubberduck to the help again!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T21:14:46.297",
"Id": "248785",
"Score": "25",
"Tags": [
"vba",
"excel",
"mvp"
],
"Title": "Pacman implemented in OOP VBA"
}
|
248785
|
<p>As per tutorial <a href="https://www.freecodecamp.org/news/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28/" rel="noreferrer">here</a>, I have the following classes:</p>
<p>(In reference to this tutorial's section)</p>
<pre><code>namespace Supermarket.API.Domain.Services
{
public interface ICategoryService
{
Task<IEnumerable<Category>> ListAsync();
}
}
</code></pre>
<p><strong>IProductService.cs</strong></p>
<pre><code>namespace Supermarket.API.Domain.Services
{
public interface IProductService
{
Task<IEnumerable<Product>> ListAsync();
}
}
</code></pre>
<p><strong>ICustomerService.cs</strong></p>
<pre><code>namespace Supermarket.API.Domain.Services
{
public interface ICustomerService
{
Task<IEnumerable<Customer>> ListAsync();
}
}
</code></pre>
<p>I have about 10 Domains that I want to have the same interface as above (i.e. the service ability to <code>GET</code> items for e.g. Customer / Product / OrderItem / Order)</p>
<p>In view of the DRY principle, I am thinking of changing to the below:</p>
<pre><code>public interface IService<T>
{
/// <summary>
/// Gets a collection of entities
/// </summary>
/// <returns></returns>
Task<IEnumerable<T>> ListAsync();
}
</code></pre>
<p>Whereby at implementation time, it looks like the below:</p>
<pre><code>public class CustomerService : IService<Customer>
{
public async Task<IEnumerable<Customer>> ListAsync()
{
var entities = await // Imeplementation of DAL to follow
return entities;
}
}
</code></pre>
<p>None of the tutorials that I have read so far does anything similar to keep the interface DRY. Is this a good idea? Thanks.</p>
|
[] |
[
{
"body": "<p>To get part of the code review out of the way, and possibly a copy paste error on your part, but the <code>I</code> prefix is reserved for interfaces, not classes. Therefore the last code snippet should be rewritten as:</p>\n<pre><code>public class CustomerService : IService<Customer>\n{\n public async Task<IEnumerable<Customer>> ListAsync()\n {\n var entities = await // Imeplementation of DAL to follow\n\n return entities;\n }\n}\n</code></pre>\n<p>To your question of whether it's a good idea to replace the interfaces with a generic interface in the name of DRY, it depends.</p>\n<p>As a general guide into the DRY principle, you will need to identify whether the duplication in the code is truly a duplication, or whether the "duplication" is semantically different.</p>\n<p>As an example, say that we have the following code:</p>\n<pre><code>public class Payslip\n{\n public decimal Pay { get; set; }\n public decimal CalculateTaxAmount()\n {\n return Pay * 0.1M;\n }\n}\n\npublic class Item\n{\n public decimal Price { get; set; }\n public decimal CalculateTaxAmount()\n {\n return Price * 0.1M;\n }\n}\n</code></pre>\n<p>This is obviously hyper simplified, but we can see that both classes have a <code>CalculateTaxAmount</code> method, which does essentially the same calculation to get the tax amount. If we were naive, and decided to refactor this to share the same logic, for example:</p>\n<pre><code>public abstract class BaseTaxable\n{\n protected decimal _amount;\n\n public decimal CalculateTaxAmount()\n {\n return _amount * 0.1M;\n }\n}\n\npublic class Payslip : BaseTaxable\n{\n public decimal Pay { get => _amount; set => _amount = value; }\n}\n\npublic class Item : BaseTaxable\n{\n public decimal Price { get => _amount; set => _amount = value; }\n}\n</code></pre>\n<p>We've removed the duplication from both <code>Item</code> and <code>Payroll</code>, but these two objects fundamentally calculate tax differently.</p>\n<p>Say that the government decides to implement tax brackets for salaries, we would have to undo our refactoring on the <code>Payslip</code> object just to implement tax brackets.</p>\n<p>Back to your use case, this does look fine to do, but you need to ask yourself:</p>\n<ol>\n<li>Is the current contract for <code>IService<T></code> represent what all services will be in your project? What if you decided to add a <code>PasswordService</code>? I don't think that having a <code>ListAsync</code> for passwords is a good idea.</li>\n<li>What if, for example, <code>ICustomerService</code> requires additional functionality as part of it's contract? How do you expect to handle this use case? You can add additional interfaces onto your implementation but depending on your current code base, replacing references to accommodate this could be time consuming</li>\n<li>As we discussed above, do the classes that implement this interface semantically perform the same functionality. In the case for retrieving domain entities, probably yes, but is something to keep in mind.</li>\n</ol>\n<p>If you decide to refactor to use <code>IService<T></code>, it's best to rename the interface to something more meaningful (i.e. <code>IReadOnlyRepository<T></code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T02:02:18.450",
"Id": "487473",
"Score": "0",
"body": "(1) is a very very strong reason that I can comprehend.\n\nIn my mind, it seems \"overkill\" to create an interface that is quite specific (e.g. `ICustomerService`), hence thinking of expanding to a general `Service` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T02:14:24.023",
"Id": "487475",
"Score": "0",
"body": "* hence thinking of expanding to a general `IService<T>` class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T01:34:42.060",
"Id": "248790",
"ParentId": "248786",
"Score": "3"
}
},
{
"body": "<p>It makes perfect sense to define such generic interface as long as there is a generic consumer that can do some useful work with any of the implementations.</p>\n<p>And I suppose there is in this case.</p>\n<p>If I were to guess, I'd say the tutorial did not include generics just because that is a feature that might not be familiar to the audience that the tutorial was pointing at.</p>\n<p>As @Hayden already mentioned, <code>IService<T></code> is not a very useful name. Let me call it <code>IEntityListProvider<T></code> instead.</p>\n<p>I can imagine the common consumer could be a single route controller.</p>\n<p>Let me first a define a simple routing framework to provide some context:</p>\n<pre><code>// IRequest and IResponse are models of HTTP request resp. response\ninterface IRequestHandler\n{\n public Task<IResponse> HandleAsync(IRequest request);\n}\n\ninterface IRouterBuilder\n{\n // register a GET route handler\n public void Get(string path, IRequestHandler handler);\n\n // build the router instance\n public IRequestHandler Build();\n}\n</code></pre>\n<p>now we can implement the generic consumer like this:</p>\n<pre><code>class EntityListRouteHandler<T> : IRequestHandler\n{\n private IEntityListProvider<T> Provider;\n\n // add constructor to take the dependency\n\n Task<IResponse> HandleAsync(IRequest request)\n {\n // get the list from provider\n // and convert the list to a response in a way\n // that's going to be the same for all entities\n }\n}\n</code></pre>\n<p>and somewhere in router factory you would do somethig like this:</p>\n<pre><code>RouterBuilder.Get('/categories', new EntityListRouteHandler<Category>(categoriesProvider));\nRouterBuilder.Get('/products', new EntityListRouteHandler<Product>(productProvider));\nRouterBuilder.Get('/customers', new EntityListRouteHandler<Customer>(customersProvider));\n</code></pre>\n<p>Now I would like to expand on @Hayden's answer.</p>\n<p>Ad 1) he mentions that if a <code>PasswordService</code> were to exist, it would probably not need a <code>ListAsync</code> method. Well, that's true, but it's misleading because it is irrelevant. Such a service would simply not implement the <code>IEntityListProvider<T></code> interface.</p>\n<p>Ad 2) if some service needs some more methods, then I would ask mayself is there someone who needs those methods at the same time? If yes just create a new interface extending the base one. If not, just define a new separate interface. Whether the concrete class implements two interfaces or you simply provide two different classes to implement each of the two interfaces is up to you. But a separate class for each interface feels like it better follows SRP.</p>\n<p>I would add one more note regarding pagination. It is not very wise to provide the lists of entities without any limit. The momory consumption of such program is then out of control unless there is some logic that prevents too many entities to exist in the first place. Your <code>ListAsync</code> method should have arguments for pagination and possibly filtering and sorting as those are very common things to do with list resources. The type of these arguments may as well be generic arguments of the interface. I.e. <code>Task<IEnumerable<T>> IEntityListProvider<T, F, S, P>::ListAsync(F filter, S sort, P page)</code> or so...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T05:02:09.737",
"Id": "248795",
"ParentId": "248786",
"Score": "10"
}
},
{
"body": "<h2>Yes, but...</h2>\n<p>In the current picture you painted, where all the services are structurally <em>exactly</em> the same, you can indeed use the generic base interface. Your code will work exactly as you expect it to.</p>\n<p>However, in reality what starts off as an similar structure often ends up diverging, e.g. <code>CustomerService.GetUnderageCustomers()</code> making no sense to be implemented on the other services.</p>\n<h2>...it's better to have the best of both worlds.</h2>\n<p>Keep your generic interface:</p>\n<pre><code>public interface IService<T>\n{\n Task<IEnumerable<T>> ListAsync();\n}\n</code></pre>\n<p>But also define your specific interface types, relying on that generic interface where relevant:</p>\n<pre><code>public interface IProductService : IService<Product> { }\n\npublic interface ICategoryService : IService<Category> { }\n\npublic interface ICustomerService : IService<Customer> \n{ \n Task<IEnumerable<T>> GetUnderageCustomersAsync();\n}\n</code></pre>\n<p>Notice how I was able to extend the contract of the customer service, without needing to suddenly create an <code>ICustomerService</code> where none would've existed before (i.e. when you only would have had the generic service interface).</p>\n<p>If you had done it your way, if you then had to extend your customer service with <code>GetUnderageCustomersAsync</code>, you would've had to change your <code>CustomerService : IService<Customer></code> to <code>CustomerService : ICustomerService</code>, which in turn would require you to re-evaluatle all references in your codebase to see if they need to move from using a <code>IService<Customer></code> dependency to using a <code>ICustomerService</code> dependency.<br />\nThat is a lot of work, there's a big change you're going to forget it here or there, and you're liable to introduce bugs or inconsistencies.</p>\n<p>Creating the specific <code>I[xxx]Service</code> interfaces from the beginning allows your codebase to adapt to new features without introducing breaking changes, since you don't have to change the interface implementation hierarchy anymore.</p>\n<ul>\n<li>New method that applies to all those services? Add it to the generic base interface</li>\n<li>New method that applies to a specific service? Add it to the specific interface</li>\n</ul>\n<h2>Is the generic interface necessary?</h2>\n<p>That's arguable. If there is some reusable logic that applies to all services, then having that generic base interface type makes a lot of sense, as it helps you to streamline your reusable service logic handling code, or even your test suite.</p>\n<p>However, if you end up never really using the <code>IService<></code> type directly in your code, then the interface doesn't really add any value, other than keeping your services structurally similarly, so they e.g. don't have varying <code>ListAsync</code>/<code>GetAllAsync</code>/<code>Get</code>/... methods that do the same thing but just end up being named differently.</p>\n<p>In short, there are two reasons to use this generic base interface</p>\n<ul>\n<li>When there is actually reusable code that can handle <em>any</em> <code>IService<T></code>.</li>\n<li>When you want to enforce a clean and consistent interface across multiple types for reasons of human readability.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T03:18:11.443",
"Id": "487614",
"Score": "0",
"body": "Why would adding a method to customer service require to change every class that was already using it as the generic service? Only those who need the new method have to change and that's presumably zero places in the existing code and one in code that you are yet to write."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T09:33:43.967",
"Id": "487631",
"Score": "0",
"body": "@slepic: If you use a DI framework and the repository is not transient (which repositories usually aren't), you're going to want to stick with one interface type to request your non-transient dependency. You are, however, correct that not all references should be changes, and that's part of the issue: needing to evaluate each reference individually instead of a blanket find and replace. I didn't explain that part well, I'll improve it in the answer. But I disagree that it's \"presumably zero places\" as an additional feature is liable to change or further extend existing behavior as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T09:52:11.440",
"Id": "487632",
"Score": "0",
"body": "@Flater In standard ASP.Net Core with EF Core there's rarely a reason to register the repository as anything but transient - the state is kept in the DbContext which is scoped."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T09:53:41.610",
"Id": "487633",
"Score": "0",
"body": "@Voo: Those are a whole lot of ifs that the question does not specify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:01:41.000",
"Id": "487634",
"Score": "0",
"body": "@Flater It's the default and what's used in tutorials and samples by Microsoft. You're making the assumptions that someone puts state into the repository and then registers the class with the DI container twice (something so dubious that I've written explicit tests in the past to make sure nobody makes such a mistake)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:23:25.790",
"Id": "487635",
"Score": "0",
"body": "@Voo: The comment I responded to explicitly suggests using _both_ `IService<Customer>` and `ICustomerService` dependency types in the codebase, which would always have to be registered separately, thus registering the concrete `ConsumerRepository` twice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:56:44.690",
"Id": "487637",
"Score": "0",
"body": "@Flater The usual solution that I'm aware of is to register the actual type (or one of the interfaces) and use a lambda to register the other interfaces by resolving them registered scoped type. Not pretty, but you can nicely hide that behind a helper method and certainly much better than having duplicate state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T04:45:23.697",
"Id": "487720",
"Score": "0",
"body": "@Flater If additional feature of interface X forces a change to class Y that depends on X, you're going to have to change the class Y anyway (to use the new method of X) even if you dont have to change the type of the dependency. The need to evaluate each reference individually exists regardless of the interface X being a generic interface or a specific service interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T04:47:26.693",
"Id": "487721",
"Score": "0",
"body": "It's actually quite the opposite. If I added a method to existing interface X and there is a class Z that does not need this new method then I have to change this class Z to take the generic interface rather then the specifi service interface otherwise if I don't change the class Z, I am suddenly injecting a method to Z, but Z will never use this method which break ISP and I got myself to this state by changing a completly different piece of codebase and maybe even not knowing that Z exists."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T12:00:25.120",
"Id": "248809",
"ParentId": "248786",
"Score": "5"
}
},
{
"body": "<p>@Flater, @slepic, and @Hayden answers have almost cover common case scenarios on when and where to use a generic (or generalized) interface to reuse it. As there are many real world cases applying the same concept. For instance, in .NET, <code>IEnumerable</code> interface is implemented in most .NET collections and arrays. All of which adds the ability to have one generic interface that implements many different collection types. The benefit here is to have a shared minimum requirement on all collection along with implementing a specific interface for each type (e.g. IList). when you see it up-close, you'll see how is it easy to extend, maintain, and also reuse and it how easy would be to convert between collection types (say from List to Array).</p>\n<p>Another thing that you must consider in tutorials, almost all of them will have the long approach. This is because they're targeting a wide range of audience with different skills. So, every author tries to be as descriptive as possible to cover all audience. In which readers can understand and take the idea then improve it in their way. This is why you thought about <code>ISerivce</code> and <code>DRY</code> principle (improve it in your way). because you've got the idea and you can complete the work on your own.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:27:52.327",
"Id": "248819",
"ParentId": "248786",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T22:10:41.130",
"Id": "248786",
"Score": "7",
"Tags": [
"c#",
"interface"
],
"Title": "IService<T> or defining IProductService, ICustomerService"
}
|
248786
|
<p>My C++ knowledge is outdated and I'm trying to learn about C++11 threading. I'm working on a <a href="https://github.com/watkipet/osmo-fl2k" rel="nofollow noreferrer">SoapySDR driver</a> where the client acquires a buffer it wants to write to and the hardware transmits from that same buffer once it's filled. Rather than post the actual code here, I've distilled it down to an example using <code>std::cout</code> as my "transmitter".</p>
<pre><code>//
// main.cpp
// ThreadingExample
//
// Demonstrates sharing a common buffer between two threads. One
// is the consumer (see tx_loop()), the other is the producer.
//
#include <iostream> // std::cout
#include <thread> // std::thread
#include <chrono> // std::chrono::seconds
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable, std::cv_status
#include <iomanip>
std::mutex _buf_mutex;
std::condition_variable _buf_cond;
char _buff[10];
std::atomic<ssize_t> _buf_count;
bool running;
std::chrono::system_clock::time_point start;
// The transmit loop. Every 500 ms, it tries to get a lock on the buffer,
// then "transmits" (cout) that buffer
void tx_loop()
{
while (running)
{
std::unique_lock <std::mutex> lock(_buf_mutex);
if (_buf_cond.wait_for(lock, std::chrono::seconds(1), []{return _buf_count > 0;}) == false)
{
// We hit this if we've had an underflow or if the producer thread has stopped.
std::cout
<< std::setfill('0') << std::setw(5)
<< std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::system_clock::now() - start).count()
<< ": tx_loop timed out\n";
return;
}
// Decrement the number of filled buffers.
_buf_count--;
// "Transmit" the packet
std::cout
<< std::setfill('0') << std::setw(5)
<< std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::system_clock::now() - start).count()
<< ": "
<< std::string(_buff, sizeof(_buff) / sizeof(_buff[0]))
<< "\n";
std::this_thread::sleep_for (std::chrono::milliseconds(500));
// Notify the other threads that transmission has finished
_buf_cond.notify_one();
}
}
// Aqcuires a buffer that the client can write to. Blocks until the buffer becomes
// available for writing.
size_t acquireWriteBuffer(void **buf)
{
std::cout
<< std::setfill('0') << std::setw(5)
<< std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::system_clock::now() - start).count()
<< ": acquireWriteBuffer _buf_count="
<< (int) _buf_count
<< "\n";
// Increment the number of buffers about to be filled
_buf_count++;
// Notify the transmission thread that there's a buffer to transmit
if (_buf_count > 0)
{
_buf_cond.notify_one();
}
// Wait for the buffer to become available
std::unique_lock <std::mutex> lock(_buf_mutex);
if (_buf_cond.wait_for(lock, std::chrono::seconds(1), []{return _buf_count < 1;}) == false)
{
// We hit this if we can't TX fast enough
std::cout
<< std::setfill('0') << std::setw(5)
<< std::chrono::duration_cast<std::chrono::milliseconds> (std::chrono::system_clock::now() - start).count()
<< ": acquireWriteBuffer timed out\n";
return 0;
}
*buf = _buff;
return sizeof(_buff) / sizeof(_buff[0]);
}
// The main program. Sends 10 "packets" of 10 characters each. Each
// character is one ASCII value greater than the last.
int main (int argc, const char * argv[])
{
start = std::chrono::system_clock::now();
running = true;
// Note that _buf_count starts at -1. This is because we not only need
// to acquire a buffer, we need to write to it prior to the TX thread
// sending it. When _buf_count is 0, we've acquired a buffer. When it's
// 1, we've filled it.
_buf_count = -1;
std::thread th (tx_loop);
// Send 10 chunks
char presentChar = ' ';
for (int i = 0; i < 10; i++)
{
char *buf;
size_t numElements = acquireWriteBuffer((void **) &buf);
for (int j = 0; j < numElements; j++)
{
buf[j] = presentChar;
presentChar < 127 ? presentChar++ : presentChar = ' ';
}
}
running = false;
th.join();
return 0;
}
</code></pre>
<p>The output from running my program is as follows:</p>
<pre><code>00000: acquireWriteBuffer _buf_count=-1
00000: acquireWriteBuffer _buf_count=0
00000: !"#$%&'()
00503: acquireWriteBuffer _buf_count=0
00503: *+,-./0123
01006: acquireWriteBuffer _buf_count=0
01006: 456789:;<=
01511: acquireWriteBuffer _buf_count=0
01511: >?@ABCDEFG
02014: acquireWriteBuffer _buf_count=0
02014: HIJKLMNOPQ
02518: acquireWriteBuffer _buf_count=0
02518: RSTUVWXYZ[
03019: acquireWriteBuffer _buf_count=0
03019: \]^_`abcde
03519: acquireWriteBuffer _buf_count=0
03519: fghijklmno
04024: acquireWriteBuffer _buf_count=0
04024: pqrstuvwxy
05532: tx_loop timed out
</code></pre>
<p>The odd thing about my situation is that I know when the client wants to acquire a buffer, but I don't know when it has actually written to it. So, all I can do is assume that it's written to the last buffer it acquired once it requests another one. You'll see this in the comments about <code>_buf_count</code> starting at -1.</p>
<p>There are a few things I'm unsure about in my code:</p>
<ol>
<li>Is my use of <code>_buf_count</code> thread-safe?</li>
<li>Is my code prone to deadlocks?</li>
<li>Is my use of a single condition variable appropriate?</li>
<li>Am I managing my mutexes well? Since I'm using <code>wait_for</code>, they automatically get unlocked, right?</li>
</ol>
<p>Please indicate in a comment if you'd like me to change anything (i.e. add more comments, etc.) before you answer.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T23:24:34.827",
"Id": "248787",
"Score": "2",
"Tags": [
"c++11",
"multithreading"
],
"Title": "Producer consumer with shared buffer in C++11"
}
|
248787
|
<p>I have some nominal variables encoded as integers (not ordinal), which I would like to encode as binary (not dummies nor one hot!). The following code is what I came up with (adapted from other code I found). Is this a valid/scalable approach? Thanks!</p>
<pre><code>library(binaryLogic)
df <- data.frame(x1 = c(1, 1, 2, 3), x2 = c(1, 2, 3, 4))
encode_binary <- function(x, name = "binary_") {
x2 <- as.binary(x)
maxlen <- max(sapply(x2, length))
x2 <- lapply(x2, function(y) {
l <- length(y)
if (l < maxlen) {
y <- c(rep(0, (maxlen - l)), y)
}
y
})
d <- as.data.frame(t(as.data.frame(x2)))
rownames(d) <- NULL
colnames(d) <- paste0(name, 1:maxlen)
d
}
df <- cbind(df, encode_binary(df[["x1"]], name = "binary_x1_"))
df <- cbind(df, encode_binary(df[["x2"]], name = "binary_x2_"))
df
</code></pre>
|
[] |
[
{
"body": "<p>If we test on larger vector your approach is quite slow:</p>\n<pre><code>test_vec <- 1:1e5\nsystem.time(v1 <- encode_binary(test_vec, name = "binary_x1_"))\n# user system elapsed \n# 22.23 0.08 22.37 \n</code></pre>\n<p>Based on this SO <a href=\"https://stackoverflow.com/questions/12088080/how-to-convert-integer-number-into-binary-vector\">question</a>\nI managed to write code that performs a lot faster:</p>\n<pre><code>encode_binary2 <- function(x, name = "binary_") {\n m <- sapply(x, function(x) rev(as.integer(intToBits(x))))\n tm <- t(m)\n # remove empty bit cols\n i <- which(colSums(tm) != 0L)[1]\n tm <- tm[, i:ncol(tm)]\n # save to data.frame\n d <- as.data.frame(tm)\n rownames(d) <- NULL\n colnames(d) <- paste0(name, 1:ncol(d))\n d\n}\n\nsystem.time(v2 <- encode_binary2(test_vec, name = "binary_x1_"))\n# user system elapsed \n# 0.61 0.02 0.63 \n\n# test that results are equal:\nall.equal(v1, v2)\n# [1] TRUE\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T08:23:06.837",
"Id": "248801",
"ParentId": "248796",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248801",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T05:19:35.163",
"Id": "248796",
"Score": "1",
"Tags": [
"r"
],
"Title": "transform columns to binary encoded columns in R"
}
|
248796
|
<p>I am following <a href="https://www.codingame.com/playgrounds/5518/multi-tenant-asp-net-core-5---implementing-database-per-tenant-strategy" rel="nofollow noreferrer">this sample</a> by Gunnar Peipman to create a multi-tenant architecture in my ASP.NET Core 3.1 application. It is working as expected up to the point shown in the sample.</p>
<pre><code>public class Tenant
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Host { get; set; }
public string DatabaseConnectionString { get; set; }
}
public interface ITenantProvider
{
Tenant GetTenant();
}
public class DummyTenantProvider : ITenantProvider
{
private static IList<Tenant> _tenants = new List<Tenant>
{
new Tenant { Id = MultitenantDbContext.Tenant1Id, Name = "Imaginary corp", DatabaseConnectionString = "ConnStr1" },
new Tenant { Id = MultitenantDbContext.Tenant2Id, Name = "The Very Big corp", DatabaseConnectionString = "ConnStr2" },
};
public Tenant GetTenant()
{
return _tenants.First();
}
}
public class Person
{
public Guid Id { get; set; }
public Guid TenantId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
</code></pre>
<p>Registering the services in startup.cs:</p>
<pre><code>public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MultitenantDbContext>(o => { });
services.AddMvc();
services.AddTransient<ITenantProvider, DummyTenantProvider>();
}
</code></pre>
<p>MultitenantDbContext.cs</p>
<pre><code>public class MultitenantDbContext : DbContext
{
public static Guid Tenant1Id = Guid.Parse("51aab199-1482-4f0d-8ff1-5ca0e7bc525a");
public static Guid Tenant2Id = Guid.Parse("ae4e21fa-57cb-4733-b971-fdd14c4c667e");
public DbSet<Person> People { get; set; }
private Tenant _tenant;
private ILogger<MultitenantDbContext> _logger;
public MultitenantDbContext(ITenantProvider tenantProvider, ILogger<MultitenantDbContext> logger)
{
_tenant = tenantProvider.GetTenant();
_logger = logger;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Comment out for real application
//optionsBuilder.UseSqlServer(_tenant.DatabaseConnectionString);
// Comment in for real applications
optionsBuilder.UseInMemoryDatabase(Guid.NewGuid().ToString());
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>().HasQueryFilter(p => p.TenantId == _tenant.Id);
}
public void AddSampleData()
{
People.Add(new Person
{
Id = Guid.Parse("79865406-e01b-422f-bd09-92e116a0664a"),
TenantId = Tenant1Id,
FirstName = "Gunnar",
LastName = "Peipman"
});
People.Add(new Person
{
Id = Guid.Parse("d5674750-7f6b-43b9-b91b-d27b7ac13572"),
TenantId = Tenant2Id,
FirstName = "John",
LastName = "Doe"
});
People.Add(new Person
{
Id = Guid.Parse("e41446f9-c779-4ff6-b3e5-752a3dad97bb"),
TenantId = Tenant1Id,
FirstName = "Mary",
LastName = "Jones"
});
SaveChanges();
}
}
</code></pre>
<p>I now want to dynamically select a tenant depending upon the domain host of the application. For this, I modified the <code>DummyTenantProvider</code> and injected <code>IHttpContextAccessor</code> to access the request's <code>HttpContext</code> and extract the domain host. Is the approach given below correct?</p>
<pre><code>public class DummyTenantProvider : ITenantProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public DummyTenantProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private readonly static IList<Tenant> _tenants = new List<Tenant>
{
new Tenant { Id = MultitenantDbContext.Tenant1Id, Name = "Imaginary corp", DatabaseConnectionString = "ConnStr1", Host = "mywebhost.com" },
new Tenant { Id = MultitenantDbContext.Tenant2Id, Name = "The Very Big corp", DatabaseConnectionString = "ConnStr2", Host = "anotherhost.com" },
};
public Tenant GetTenant()
{
var httpContext = _httpContextAccessor.HttpContext;
return _tenants.Single(t => t.Host == httpContext.Request.Host.Host);
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T06:53:20.057",
"Id": "248797",
"Score": "2",
"Tags": [
"c#",
"asp.net-core"
],
"Title": "ASP.NET Core 3.1 Multi-tenant with separate database"
}
|
248797
|
<p>I have to go through files with metadata and I am unhappy with the iteration and how I have build it due to the fact, that I have a modeltree with lists. So basically I iterate through <code>filesOfFolder</code> and pick each file and then I am adding the metadata. In the <code>else</code> I am checking, if the fileName has the same beginning then the fileNameBefore, because then it is a child of the last file, and it needs a different <code>documentOrderNumber</code>.</p>
<p>The modeltree is like and it cannot get changed:</p>
<pre><code>Mainmodel
Documents (public MainDocumentModel[] and AttDocumentModel[])
MainDocumentModel
FileContent
AttDocumentModel
FileContent
</code></pre>
<p>So as of this tree I did it so and I am totally unhappy with that:</p>
<pre class="lang-csharp prettyprint-override"><code>string fileNameBefore = "";
model.Documentlist = new Documents
{
Attdocument = new AttDocumentModel[filesOfFolder.Count() + 1]
};
int i = 0;
int j = 0;
int k = 0;
string mainPath = System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data/" + model.DocId + "/");
string directoryAttPath = mainPath + "Att/";
Directory.CreateDirectory(directoryAttPath);
foreach (var file in filesOfFolder)
{
if (file.f_name.Contains("Maindocument") || file.f_name.Contains("Wrapdocument"))
{
FileContent fContent = new FileContent();
fContent.FileType = "PDF";
fContent.FileName = "Maindocument.pdf";
MainDocumentModel mainDoc = new MainDocumentModel();
mainDoc.MainDoc = new List<FileContent>();
mainDoc.Message = "";
mainDoc.Status = true;
mainDoc.MainDoc.Add(fContent);
model.Documentlist.Maindocument = new MainDocumentModel[1];
model.Documentlist.Maindocument[0] = mainDoc;
string mainDocumentPath = mainPath + fContent.FileName;
System.IO.File.WriteAllBytes(mainDocumentPath, file.f_file);
}
else
{
if (!(fileNameBefore.Split(' ')[0] == file.f_name.Split(' ')[0]))
{
j = 0;
i++;
}
else
{
j++;
}
FileContent attachment = new FileContent();
string documentOrderNumber = GenerateOrderNumberForRis(i, j, fileNameBefore);
attachment.FileName = documentOrderNumber + ".pdf";
attachment.FileType = "PDF";
AttDocumentModel attDoc = new AttDocumentModel();
attDoc.AttDoc = new List<FileContent>();
attDoc.Message = "";
attDoc.Status = true;
attDoc.ShowName = file.f_subject;
attDoc.AttDoc.Add(attachment);
model.Documentlist.Attdocument[k] = attDoc;
System.IO.File.WriteAllBytes(directoryAttPath + documentOrderNumber + ".pdf", file.f_file);
k++;
fileNameBefore = file.f_name;
}
}
</code></pre>
<p>Here are the models:</p>
<pre class="lang-csharp prettyprint-override"><code>public class MainModel
{
....
[XmlIgnore]
public MainDocumentModel Maindocument { get; set; }
[XmlIgnore]
public AttDocumentModel Attdocument { get; set; }
[XmlElement(ElementName = "documentlist")]
public Documents Documentlist { get; set; }
}
[XmlRoot(elementName: "maindocument")]
public class MainDocumentModel
{
[XmlIgnore]
public String Message { get; set; }
[XmlIgnore]
public Boolean Status { get; set; }
[XmlElement("content")]
public List<FileContent> MainDoc { get; set; }
}
[XmlRoot(elementName: "attacheddocument")]
public class AttDocumentModel
{
[XmlIgnore]
public String Message { get; set; }
[XmlIgnore]
public Boolean Status { get; set; }
[XmlElement("showname")]
public string ShowName { get; set; }
[XmlElement("content")]
public List<FileContent> AttDoc { get; set; }
}
public class FileContent
{
[XmlElement("dataformat")]
public string FileType { get; set; }
[XmlElement("uri")]
public string FileName { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:11:11.367",
"Id": "487547",
"Score": "0",
"body": "fileNameBefore is never modified and will always be \"\"... Please add the code and class of variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T15:08:34.657",
"Id": "487554",
"Score": "0",
"body": "Added it @MartinVerjans, forgot the last line `fileNameBefore = file.f_name;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T07:27:46.667",
"Id": "487623",
"Score": "0",
"body": "Can you please elaborate on the following statement: \"I am totally unhappy with that\"?"
}
] |
[
{
"body": "<p>Some quick remarks.</p>\n<ul>\n<li><p>Don't pointlessly abbreviate: <code>fContent</code> isn't a clear name, for instance.</p>\n</li>\n<li><p><code>i</code>, <code>j</code> and <code>k</code> are okay names for variables in a <code>for</code>-loop, but here they really should have meaningful names.</p>\n</li>\n<li><p>Avoid adding words like "list" to names of collections. Especially when <code>Documentlist</code> isn't a collection, but the oddly named <code>Documents</code>. A class with a plural name? Which is then initialized by setting the badly named property <code>Attdocument</code>?</p>\n</li>\n<li><p>I'm assuming that you cannot change the property name <code>f_name</code>?</p>\n</li>\n<li><p>Are you certain that <code>.Contains("Maindocument")</code> will always work? Or should it be case insensitive?</p>\n</li>\n<li><p>In several places you seem to use string concatenation to create directory paths. Avoid this and instead use <code>Path.Combine()</code>.</p>\n</li>\n<li><p>When you construct the MainDocumentModel, try to keep it succinct. (I have omitted <code>Message = ""</code> since IMHO it seems superfluous: why not simply leave it <code>null</code>?) Same for <code>AttDocumentModel</code> in the <code>else</code>, BTW.</p>\n<pre><code> var mainDocumentModel = new MainDocumentModel\n {\n Status = true,\n MainDoc = new List<FileContent>{ fContent }\n };\n</code></pre>\n</li>\n<li><p>I have trouble figuring out what <code>if (!(fileNameBefore.Split(' ')[0] == file.f_name.Split(' ')[0]))</code> is supposed to mean. As a matter of fact, that whole <code>if</code>...<code>else</code> seems to reference some kind of logic that really should be documented there with comments. It doesn't help that we don't have access to the code for <code>GenerateOrderNumberForRis</code>.</p>\n</li>\n<li><p>There are two places where you do <code>documentOrderNumber + ".pdf"</code>.</p>\n</li>\n<li><p><code>Maindocument</code>, <code>Attdocument</code>, ... are compound words and thus should be PascalCase.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T15:08:33.423",
"Id": "248873",
"ParentId": "248806",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T11:03:32.603",
"Id": "248806",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Iterate through a list of data and add it to nested models"
}
|
248806
|
<p>I have implemented a substring search, which works as expected and provides the right output. On some edge cases tho, I get either Memory or Time limit exceeded because:</p>
<ol>
<li>the string length is too big</li>
<li>there are too many queries</li>
</ol>
<p>The code asks for a few inputs:</p>
<ol>
<li>a string</li>
<li>the number of queries</li>
<li>query</li>
</ol>
<p>Info about the string and the queries:</p>
<ol>
<li>string length is not bigger than 300.000 and consists of English lowercase characters.</li>
<li>max number of queries is 300.000</li>
<li>sum of the queries length is not bigger than 300.000</li>
</ol>
<p>I get MLE if I use HashMap caching, and I get TLE without it.</p>
<p>Where can my code be improved, so it also handles those edge cases?</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
use std::io::{stdin, stdout, BufWriter, Write};
fn main() {
let out = &mut BufWriter::new(stdout());
let mut s = String::new();
stdin().read_line(&mut s).expect("Failed to read input");
let s = s.trim();
let mut q = String::new();
stdin()
.read_line(&mut q)
.expect("Failed to read number of queries");
let q: u32 = q.trim().parse().unwrap();
if q == 0 {
writeln!(out, "No").ok();
}
let sorted_suffixes = suffix_array(&s);
let mut saved_idx = HashMap::with_capacity(q as usize);
let mut saved_results = HashMap::with_capacity(q as usize);
for idx in 0..q {
let mut i = String::new();
stdin()
.read_line(&mut i)
.unwrap_or_else(|_| panic!("Failed to read input {}", idx));
let i = i.trim();
let result = saved_results.entry(i.to_string()).or_insert_with(|| {
let sorted_suffixes = saved_idx
.entry(i.len())
.or_insert_with(|| transform(&sorted_suffixes, s, i.len()));
match sorted_suffixes.binary_search(&i) {
Ok(_) => "Yes",
_ => "No",
}
});
writeln!(out, "{}", result).ok();
}
}
fn transform<'a>(prep: &[usize], s: &'a str, max_len: usize) -> Vec<&'a str> {
let str_len = s.len();
let mut result = Vec::with_capacity(prep.len());
for &p in prep {
if p + max_len > str_len {
result.push(&s[p..])
} else {
result.push(&s[p..p + max_len])
}
}
result
}
fn suffix_array(s: &str) -> Vec<usize> {
let s = format!("{}{}", s, "$");
let str_len = s.len();
let (mut prep, mut class) = (vec![0; str_len], vec![0; str_len]);
let mut arr: Vec<(char, usize)> = Vec::with_capacity(str_len);
for (idx, ch) in s.chars().enumerate() {
arr.push((ch, idx));
}
arr.sort_by(|a, b| a.0.cmp(&b.0));
for (idx, a) in arr.iter().enumerate() {
prep[idx] = a.1;
}
for (idx, _) in s.chars().enumerate().skip(1) {
if arr[idx].0 == arr[idx - 1].0 {
class[prep[idx]] = class[prep[idx - 1]];
} else {
class[prep[idx]] = class[prep[idx - 1]] + 1;
}
}
let mut k = 0;
while (1 << k) < str_len {
prep = prep
.iter()
.map(|p| (p + str_len - (1 << k)) % str_len)
.collect();
count_sort(&mut prep, &class);
let mut c_new = vec![0; str_len];
for idx in 1..str_len {
let prev = (
class[prep[idx - 1]],
class[(prep[idx - 1] + (1 << k)) % str_len],
);
let cur = (class[prep[idx]], class[(prep[idx] + (1 << k)) % str_len]);
if cur == prev {
c_new[prep[idx]] = c_new[prep[idx - 1]];
} else {
c_new[prep[idx]] = c_new[prep[idx - 1]] + 1;
}
}
class = c_new;
k += 1;
}
prep
}
fn count_sort(p: &mut Vec<usize>, c: &[i32]) {
let n = &p.len();
let mut cnt = vec![0; *n];
for idx in 0..c.len() {
cnt[c[idx] as usize] += 1;
}
let mut p_new = vec![0; *n];
let mut pos = vec![0; *n];
for idx in 1..*n {
pos[idx] = pos[idx - 1] + cnt[idx - 1];
}
p.iter().for_each(|&item| {
let i = c[item] as usize;
p_new[pos[i]] = item;
pos[i] += 1;
});
*p = p_new;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T12:26:19.677",
"Id": "487522",
"Score": "1",
"body": "Memory / time usage aside, is your code producing correct results, to the best of your knowledge? If that is the case, your question might be on-topic; please edit your question to include the clarification. Also, please include a more detailed description of what your code does and/or some test cases, if possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:19:22.097",
"Id": "487535",
"Score": "0",
"body": "Thanks. The code is correct and produces the right result. I'll make it clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T15:23:26.153",
"Id": "487555",
"Score": "0",
"body": "Can you re-open it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T00:47:48.297",
"Id": "487607",
"Score": "0",
"body": "It has been reopened."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T02:31:08.237",
"Id": "487612",
"Score": "1",
"body": "Some questions: 1. are the strings guaranteed to consist of a fixed set of bytes? 2. what is the rough scale of the lengths of the string and queries, as well as the number of queries?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T04:51:53.493",
"Id": "487617",
"Score": "0",
"body": "I'll update the question with that info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T15:58:59.980",
"Id": "488138",
"Score": "0",
"body": "Some sample input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:26:06.277",
"Id": "488145",
"Score": "0",
"body": "Can be anything between a..z (lowercase) up to 300k chars"
}
] |
[
{
"body": "<h2>suffix_array</h2>\n<p>First major issue I found while checking code was this cycle</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut k = 0;\nwhile (1 << k) < str_len {\n prep = prep\n .iter()\n .map(|p| (p + str_len - (1 << k)) % str_len)\n .collect(); // what exactly should've happened here\n\n count_sort(&mut prep, &class); // nvm just sort it back\n\n let mut c_new = vec![0; str_len];\n for idx in 1..str_len {\n let prev = (\n class[prep[idx - 1]],\n class[(prep[idx - 1] + (1 << k)) % str_len],\n );\n let cur = (class[prep[idx]], class[(prep[idx] + (1 << k)) % str_len]);\n if cur == prev {\n c_new[prep[idx]] = c_new[prep[idx - 1]];\n } else {\n c_new[prep[idx]] = c_new[prep[idx - 1]] + 1;\n }\n }\n class = c_new;\n k += 1;\n}\n</code></pre>\n<p>it does something to <code>prep</code>, than calls <code>count_sort</code> on it, and then messes up with class. After second iteration looks like <code>prep</code> doesn't change at all as well as class, so it basically waste time on calling <code>count_sort</code>and allocating/deallocating memory buffers up to 300k times. It is easily replaceable with single call of <code>count_sort</code>.</p>\n<p>second minor issue - <code>for (idx, _) in s.chars().enumerate().skip(1) </code>\nit's really complicated way of saying <code>for idx in 1..str_len</code>. Compiler probably will optimize unused things, but it is still potential slowdown.</p>\n<p>Also</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let (mut prep, mut class) = (vec![0; str_len], vec![0; str_len]);\n</code></pre>\n<p>is harder to read and make really no sense to unbind tuple you've just created. So better is separate them and make them <code>Vec<usize></code> because there's no negative values in the algorithm.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let mut prep = vec![0usize; str_len];\nlet mut class = vec![0usize; str_len];\n</code></pre>\n<p>Also requires to fix <code>count_sort</code> second parameter type and remove unnecessary cast <code>as usize</code>.</p>\n<h2>count_sort</h2>\n<p>not sure why you've decided to make <code>n</code> as a pointer, it isn't really helps anywhere and doesn't affect performance as well.\nmight be a good idea to change function from</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn count_sort(p: &mut Vec<usize>, class: &[usize]) \n</code></pre>\n<p>to</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn count_sort(p: Vec<usize>, class: &[usize]) -> Vec<usize> \n</code></pre>\n<p>because function will discard previous values anyway. Probably it will help compiler to optimize some calls away and make it easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T06:12:51.590",
"Id": "488181",
"Score": "0",
"body": "About the mapping inside the while loop:\n\nit sorts `prep`, first it will sort by the first char, then the first 2 chars, first 4... doubling each time and comparing the values of both sides. The code doesn't work without it.\nSo let's say before the iteration prep is (using the equivalent chars): `[$, a, a, a, b, b, b]`\nThis doesn't mean that prep is sorted because the 2nd chars of the first iteration could be something like: `[$a, ab, ab, a$, ba, bb, ba]`. We need the 2nd iteration to sort it to: `[$a, a$, ab, ab, ba, ba, bb]`. \nAnd without this sorting, the binary search won't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T08:02:16.970",
"Id": "488199",
"Score": "0",
"body": "if you check content of prep on every cycle of the loop you will notice nothing really changes. It doesn't change content of `prep` after first cycle. Same stands for `class` - it changes only once and then it produces the same output. So it cycle just waste time or lacks some extra logic. You can check output on [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ed4fced0254f3ef69ed3083dd5c62977). Comment cycle and uncomment sort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T12:22:28.437",
"Id": "488219",
"Score": "0",
"body": "Looks like you are correct. but for some reason, this is returning \"No\" when I uncomment count and comment cycle (even tho `fla` is there):\n`fla in [\"\", \"ajf\", \"ajs\", \"a\", \"fhl\", \"fla\", \"fka\", \"hkf\", \"hla\", \"jhk\", \"jfl\", \"jsf\", \"klj\", \"kfh\", \"ka\", \"ljh\", \"laj\", \"laj\", \"sfk\"]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T12:37:57.363",
"Id": "488222",
"Score": "0",
"body": "Ah, without the cycle prep is not properly sorted, in the case above `fla` comes before `fka` and binary search fails to find it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T12:38:36.247",
"Id": "488223",
"Score": "0",
"body": "Hmmm, looks like i was a bit wrong - cycle repeats itself after second loop, so if make it `while (1 << k) < 2` it pops proper array and succeeds on finding right answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T13:51:03.617",
"Id": "488229",
"Score": "0",
"body": "It seems that there are still some edge cases. I can't see the string and queries for the edge case tho. If you wanna try by yourself: https://codeforces.com/edu/course/2/lesson/2/3/practice/contest/269118/problem/A"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T17:31:20.537",
"Id": "488256",
"Score": "0",
"body": "Welp, looks like you've broke an agreement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T18:09:38.053",
"Id": "488259",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112843/discussion-between-kadobot-and-sugar)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T18:11:26.807",
"Id": "488260",
"Score": "0",
"body": "After looking a lecture i think I understand what exactly wrong with that cycle - it doesn't check if `class` consist of unique prefixes. So this is your corner case and thats why one sorted count not enough. It is better to create subroutine function that make level of iteration and checks uniqueness of classes"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T19:26:29.873",
"Id": "249095",
"ParentId": "248807",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249095",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T11:18:32.990",
"Id": "248807",
"Score": "3",
"Tags": [
"beginner",
"algorithm",
"rust"
],
"Title": "Memory/Time usage on substring search code"
}
|
248807
|
<p>I have implemented Astar algorithm for a problem on an online judge relating to maze given start and end positions along with a grid representing the maze. I output the length of the path along with the path itself. The following is the implementation in Python using the Euclidean distance:</p>
<pre><code>import heapq, math, sys
infinity = float('inf')
class AStar():
def __init__(self, start, grid, height, width):
self.start, self.grid, self.height, self.width = start, grid, height, width
class Node():
def __init__(self, position, fscore=infinity, gscore=infinity, parent = None):
self.fscore, self.gscore, self.position, self.parent = fscore, gscore, position, parent
def __lt__(self, comparator):
return self.fscore < comparator.fscore
def heuristic(self, end, distance = "Euclidean"):
(x1, y1), (x2, y2) = self.start, end
if (distance == "Manhattan"):
return abs(x1 - x2) + abs(y1 - y2)
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def nodeNeighbours(self, pos):
(x, y) = pos
return [(dx, dy) for (dx, dy) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] if 0 <= dx < self.width and 0 <= dy < self.height and self.grid[dy][dx] == 0]
def getPath(self, endPoint):
current, path = endPoint, []
while current.position != self.start:
path.append(current.position)
current = current.parent
path.append(self.start)
return list(reversed(path))
def computePath(self, end):
openList, closedList, nodeDict = [], [], {}
currentNode = AStar.Node(self.start, fscore=self.heuristic(end), gscore = 0)
heapq.heappush(openList, currentNode)
while openList:
currentNode = heapq.heappop(openList)
if currentNode.position == end:
return self.getPath(currentNode)
else:
closedList.append(currentNode)
neighbours = []
for toCheck in self.nodeNeighbours(currentNode.position):
if toCheck not in nodeDict.keys():
nodeDict[toCheck] = AStar.Node(toCheck)
neighbours.append(nodeDict[toCheck])
for neighbour in neighbours:
newGscore = currentNode.gscore + 1
if neighbour in openList and newGscore < neighbour.gscore:
openList.remove(neighbour)
if newGscore < neighbour.gscore and neighbour in closedList:
closedList.remove(neighbour)
if neighbour not in openList and neighbour not in closedList:
neighbour.gscore = newGscore
neighbour.fscore = neighbour.gscore + self.heuristic(neighbour.position)
neighbour.parent = currentNode
heapq.heappush(openList, neighbour)
heapq.heapify(openList)
return None
if __name__ == '__main__':
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
matrix = [[int(num) for num in line.split()] for line in sys.stdin]
size = matrix.pop(0)
coordinates = matrix.pop(0)
n, m = size[0], size[1]
x1, y1, y2, x2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
path = AStar((x1-1, y1-1), matrix, n, m).computePath((y2-1, x2-1))
print(len(path))
for pos in path:
print(pos[0] + 1, pos[1] + 1)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:40:52.360",
"Id": "487544",
"Score": "0",
"body": "I do not have anything else to say yet, but your Manhattan distance code seems to be wrong (it currently is `abs((x1 - x2) + abs(y1 - y2))` but should probably be `abs(x1 - x2) + abs(y1 - y2)`)"
}
] |
[
{
"body": "<pre><code>self.start, self.grid, self.height, self.width = start, grid, height, width\n</code></pre>\n<p>I would not put these all on the same line like that. I think it would be much easier to read spread over multiple lines:</p>\n<pre><code>self.start = start\nself.grid = grid\nself.height = height\nself.width = width\n</code></pre>\n<hr />\n<p>I would probably have the <code>Node</code> class as toplevel instead of nested. I don't think you're gaining much by having it inside <code>AStar</code>. You could name it <code>_Node</code> to make it "module-private" so that attempting to import it to another file will potentially raise warnings.</p>\n<p>In <code>Node</code>'s <code>__lt__</code> implementation, I wouldn't call the second parameter <code>comparator</code>. A comparator is something that compares, whereas in this case, that's just another node. <code>other_node</code> or something would be more appropriate.</p>\n<hr />\n<p>In <code>heuristic</code>, I'd personally make use of an <code>else</code> there:</p>\n<pre><code>if (distance == "Manhattan"):\n return abs((x1 - x2) + abs(y1 - y2))\nelse:\n return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\n</code></pre>\n<p>It makes it clearer that only one of the lines will be executed. Personally, I only neglect the <code>else</code> in a case like that if the <code>if</code> was an "early exit" precondition check, and I want to avoid nesting the entire rest of the function inside a block. That's not a problem here though.</p>\n<hr />\n<p><code>nodeNeighbors</code> (<a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">which should be <code>node_neighbors</code></a>) would be cleaner broken over several lines:</p>\n<pre><code>def nodeNeighbours(self, pos):\n (x, y) = pos\n return [(dx, dy)\n for (dx, dy) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]\n if 0 <= dx < self.width and 0 <= dy < self.height and self.grid[dy][dx] == 0]\n</code></pre>\n<p>I think that makes it a lot easier to see what's going on in it.</p>\n<hr />\n<p>Again, in many places you're assigning two or more variables on one line:</p>\n<pre><code>(x1, y1), (x2, y2) = self.start, end\ncurrent, path = endPoint, []\nopenList, closedList, nodeDict = [], [], {}\nx1, y1, y2, x2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]\n</code></pre>\n<p>I would break those up. Especially once you get to 3+ on a line, for the reader to see what variable matches up with what value, they'll need to count from the left instead of just checking what's on each side of a <code>=</code>.</p>\n<hr />\n<p>In <code>computePath</code>, it seems like <code>closedList</code> should be a set. It doesn't appear as though order matters with it, and <code>neighbour in closedList</code> will be faster with a set than it will with a list. It looks though like <code>openList</code> is required to be a list though due to it being passed to <code>heapify</code>.</p>\n<hr />\n<p>I don't think I'd reassign <code>stdin</code> and <code>stdout</code>. The reassignment of <code>stdin</code> seems completely unnecessary, and changing <code>stdout</code> will make it harder to debug later using <code>print</code> statements. You don't necessarily want <em>all</em> printed text to be sent to the file.</p>\n<p>If need-be, you can specify what file you want printed to when printing:</p>\n<pre><code>with open('output.txt', 'w') as out_f:\n print("To file!", file=out_f)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T16:39:23.883",
"Id": "487559",
"Score": "0",
"body": "Thanks! Do you think using openList a `priority_queue` instead will make the code more efficient than using heapq?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T16:43:48.923",
"Id": "487560",
"Score": "1",
"body": "@JalanjiMoh Honestly, it's been a long time since I've written a A* implementation, so it's difficult for me to make algorithmic suggestions here. Even if you did switch though, you likely still wouldn't be able to have `open_list` as a set for the same reason. Standard Python sets are unordered, so any place you need to maintain order, plain sets won't be appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T16:57:06.643",
"Id": "487561",
"Score": "0",
"body": "Right. Thanks!!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:24:57.577",
"Id": "248818",
"ParentId": "248810",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "248818",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T12:15:29.040",
"Id": "248810",
"Score": "6",
"Tags": [
"python",
"algorithm",
"game",
"pathfinding",
"a-star"
],
"Title": "Python: Astar algorithm implementation"
}
|
248810
|
<p>I'm am trying to classify MLB (Baseball) games whose score go over the total based on the total and the number of people who have bet the over. The total is a number set by Vegas and a bettor can either bet the over - meaning both team's combined scores will be greater than the number Vegas set or you can bet the under mean both team's combined scores will be less than the number set by Vegas. The training data coming in is stored in a CSV file a looks like this <code>Team</code> <code>Total</code> <code>Over_Perc</code> <code>Cover</code> i.e. <code>NYY</code> <code>8.5</code> <code>0.61</code> <code>0</code>. I've tested several different models and the highest accuracy achieved was using the <code>RandomForestClassifier</code>. I would like to know if I am implementing this model correctly and if there is anything I can do to tune the parameters to achieve better accuracy?</p>
<pre><code>import pandas as pd
import numpy as np
import json
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn import metrics
training_data = pd.read_csv('/Users/aus10/Desktop/MLB_Data/ML/Data/Training_Data/Training_Data_Total.csv')
df_model = training_data.copy()
scaler = StandardScaler()
features = [['Total', 'Over_Perc' ]]
for feature in features:
df_model[feature] = scaler.fit_transform(df_model[feature])
test_data = pd.read_csv('/Users/aus10/Desktop/MLB_Data/ML/Data/Test_Data/Test_Data_Total.csv')
X = training_data.iloc[:,1:3] #independent columns
y = training_data.iloc[:,-1] #target column
results = []
# fit final model
model = RandomForestClassifier(n_estimators=500, random_state=42) # 0.54
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
model.fit(X_train, y_train)
y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)
y_pred = model.predict(X_test)
print("Accuracy:", round(metrics.accuracy_score(y_test, y_pred),2))
# define one new data instance
index = 0
count = 0
while count < len(test_data):
team = test_data.loc[index].at['Team']
total = test_data.loc[index].at['Total']
over_perc = test_data.loc[index].at['Over_Perc']
Xnew = [[ total, over_perc ]]
# make a prediction
ynew = model.predict_proba(Xnew)
# show the inputs and predicted outputs
results.append(
{
'Team': team,
'Cover': round(ynew[0][1],2)
})
index += 1
count += 1
sorted_results = sorted(results, key=lambda k: k['Cover'], reverse=True)
df = pd.DataFrame(sorted_results, columns=[
'Team', 'Cover'])
writer = pd.ExcelWriter('/Users/aus10/Desktop/MLB_Data/ML/Results/Over_Probability.xlsx', engine='xlsxwriter') # pylint: disable=abstract-class-instantiated
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.style.set_properties(**{'text-align': 'center'})
pd.set_option('display.max_colwidth', 100)
pd.set_option('display.width', 1000)
writer.save()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T18:40:37.410",
"Id": "487573",
"Score": "0",
"body": "It would be optimal to link the training files (or some \"fake\" ones with the same format if you do not want to share the originals) to let reviewers test your code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T01:27:06.563",
"Id": "487608",
"Score": "1",
"body": "@Caridorc sure here's a link https://docs.google.com/spreadsheets/d/1qxuOkUPeR5qIscmiVg9KRXm9i6mdIPbcNWjQtCCAx4c/edit?usp=sharing"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:39:12.237",
"Id": "248814",
"Score": "1",
"Tags": [
"python",
"machine-learning"
],
"Title": "Machine Learning Implementation when dealing with high variance data"
}
|
248814
|
<p>This is the first exercise from <a href="https://gophercises.com/" rel="nofollow noreferrer">https://gophercises.com/</a>.</p>
<p>Basically the idea is to parse a CSV file in a form of 'question:answer' and count the number of correct answers. Also you have a time out range in which you must finish it.</p>
<p>I would appreciate any comments, good or bad :) Thanks a lot !</p>
<pre><code>package main
import (
"encoding/csv"
"os"
"fmt"
"flag"
"time"
)
const Ready = "yes"
var correctAnswers int
func getFileContent(filename string) (records[][] string, err error) {
fd, err := os.Open(filename)
if err != nil {
exit("Problem with opening the file")
}
reader := csv.NewReader(fd)
return reader.ReadAll()
}
func outputResult(totalQuestions, correctAnswers int) {
fmt.Println("Number of total questions:", totalQuestions)
fmt.Println("Number of corrected answers:", correctAnswers)
}
func exit(message string) {
fmt.Println(message)
os.Exit(3)
}
func provideQuestions(questions[][] string, done chan bool) {
for index, value := range questions {
question, answer := value[0], value[1]
fmt.Println("Question N:=", index+1, "=>", question)
var userAnswer string
fmt.Scanf("%s", &userAnswer)
if userAnswer == answer {
correctAnswers ++
}
}
done <- true
}
func main() {
fileName := flag.String("name of csv file", "problems.csv", "The name of the csv file - default to 'problems.csv'")
allowedTime := flag.Int("allowed time", 10, "The duration in seconds for which the quizz must be finished.")
flag.Parse()
var readyToStart string
fmt.Println("Type 'yes' if you are ready to start")
fmt.Scanf("%s", &readyToStart)
if readyToStart != Ready {
fmt.Println("Come back later if you are ready")
os.Exit(0)
}
records, err := getFileContent(*fileName)
if err != nil {
exit("Reader problem.")
}
done := make(chan bool)
timer := time.NewTimer(time.Duration(*allowedTime) * time.Second)
go provideQuestions(records, done)
select {
case <- done:
fmt.Println("Great job")
fmt.Println("You finished with all questions.")
case <- timer.C:
fmt.Println("Time expired")
}
outputResult(len(records), correctAnswers)
}
</code></pre>
|
[] |
[
{
"body": "<p>Your function returns <code>error</code>, but actually you don't return it and exit in the function body when opening the file:</p>\n<pre><code>func getFileContent(filename string) (records[][] string, err error) {\n fd, err := os.Open(filename)\n\n if err != nil {\n exit("Problem with opening the file")\n }\n\n reader := csv.NewReader(fd)\n return reader.ReadAll()\n}\n</code></pre>\n<p>From the point of error handling it will be more consistent to return error:</p>\n<pre><code>fd, err := os.Open(filename)\nif err != nil {\n return nil, err\n}\n</code></pre>\n<p>The file was open, but not closed: <code>defer fd.Close()</code>.</p>\n<p>I don't remember <code>flag</code> package, but if it is not ensure the presence of parameter you need to check <code>filename != nil</code>:</p>\n<pre><code>records, err := getFileContent(*fileName)\n</code></pre>\n<p>Here you have created new goroutine, but returns the result via global variable <code>correctAnswers</code>:</p>\n<pre><code>done := make(chan bool)\ngo provideQuestions(records, done)\n</code></pre>\n<p>It stops working if you decide to improve your game and allow more than one person to play on the same time. You will have <strong>race condition</strong> on this variable. Much better return the value from goroutine using channel.</p>\n<p>You already have such channel - <code>done</code>, just change its type to channel of <code>int</code> and return the number of correct answers using it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T06:29:53.617",
"Id": "248986",
"ParentId": "248815",
"Score": "3"
}
},
{
"body": "<h2>Improving the quiz</h2>\n<p><strong>Parsing user input</strong></p>\n<p>You should parse all user input, including the csv file, by stripping them from white-spaces and making it lower-case. This ensures that user supplied data is correctly handled and the user doesn't fail a Question while it should be correct.</p>\n<p>Let's take for example the following quiz in the csv:</p>\n<p><em>What is the capital of the UK, london</em></p>\n<p>The user might have it correct but it could be stated as incorrect in the following ways:</p>\n<ol>\n<li>You don't Trim the csv, and it's easy to forget a white-space in there</li>\n<li>A user could answer with London (Capital L)</li>\n</ol>\n<p>Secondly there could be a <em>malformed</em> csv file, with only 1 item in the line, this would break the code without giving any indication why to the user.</p>\n<p><strong>Randomise</strong></p>\n<p>It would be nice if the problems were shuffled to avoid repetition.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T12:45:13.470",
"Id": "249035",
"ParentId": "248815",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248986",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:46:24.400",
"Id": "248815",
"Score": "2",
"Tags": [
"csv",
"go"
],
"Title": "Go Quiz exercise, part of Gophercises"
}
|
248815
|
<p>This script calculates points in reciprocal space for hexagonal 2D lattices, then uses the <a href="https://docs.python.org/3.7/library/itertools.html#itertools.product" rel="nofollow noreferrer">cartesian product from itertools</a> to add each vector from one lattice to all of the vectors of the other in the line</p>
<pre><code>np.array([a+b for a, b in list(itertools.product(p1.T, p2.T))])
</code></pre>
<p>It's slow right now because as written its instantiating millions of tiny numpy arrays.</p>
<p>I'm aware of:</p>
<ul>
<li><a href="https://stackoverflow.com/a/11144716">Cartesian product of x and y array points into single array of 2D points</a></li>
<li><a href="https://stackoverflow.com/q/1208118">Using numpy to build an array of all combinations of two arrays</a></li>
<li><a href="https://scicomp.stackexchange.com/q/10748">cartesian products in numPy</a></li>
</ul>
<p>and I suspect there's some way to do this, possibly using <code>np.meshgrid</code> or <code>np.mgrid</code> that's faster, uses less memory and looks cleaner, but I can not figure out how.</p>
<p>I will use the output in an optimization loop matching these positions to measured positions, so it needs to be callable several hundred times in a row, so reusing large array spaces rather than instantiating and garbage collecting them might have some advantages.</p>
<p><a href="https://i.stack.imgur.com/RRNbS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RRNbSm.png" alt="simulated diffraction spots" /></a> click for larger</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import itertools
def rotatem(xy, rot):
r3o2, twopi, to_degs, to_rads = np.sqrt(3)/2., 2*np.pi, 180/np.pi, np.pi/180
c, s = [f(to_rads*rot) for f in (np.cos, np.sin)]
x, y = xy
xr = c*x - s*y
yr = c*y + s*x
return np.vstack((xr, yr))
def get_points(a=1.0, nmax=5, rot=0):
r3o2, twopi, to_degs, to_rads = np.sqrt(3)/2., 2*np.pi, 180/np.pi, np.pi/180
g = twopi / (r3o2 * a)
i = np.arange(-nmax, nmax+1)
I, J = [thing.flatten() for thing in np.meshgrid(i, i)]
keep = np.abs(I + J) <= nmax
I, J = [thing[keep] for thing in (I, J)]
xy = np.vstack((I+0.5*J, r3o2*J))
return g * rotatem(xy, rot=rot)
r3o2, twopi, to_degs, to_rads = np.sqrt(3)/2., 2*np.pi, 180/np.pi, np.pi/180
a1, a2, rot = 1.0, 2**0.2, 22
p1 = get_points(a=a1, nmax=20)
p2 = get_points(a=a2, nmax=20, rot=rot)
p3 = get_points(a=a2, nmax=20, rot=-rot)
d12 = np.array([a+b for a, b in list(itertools.product(p1.T, p2.T))])
d13 = np.array([a+b for a, b in list(itertools.product(p1.T, p3.T))])
d12, d13 = [d[((d**2).sum(axis=1)<4.)] for d in (d12, d13)]
if True:
plt.figure()
for d in (d12, d13):
plt.plot(*d.T, 'o', ms=2)
plt.gca().set_aspect('equal')
plt.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T16:16:06.050",
"Id": "487558",
"Score": "0",
"body": "This comment won't be a solution to the main question at hand, but it's important to understand that you don't need the two intermediate lists created in your first line of code. Instead, just write this: `np.array(a+b for a, b in itertools.product(p1.T, p2.T))`. The same point could be made about the creation of `d12` and `d13` in your larger code example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T16:57:30.440",
"Id": "487562",
"Score": "0",
"body": "@FMc While `d12 = np.array(a+b for a, b in list(itertools.product(p1.T, p2.T)))` is accepted, the next step `d12 = np.array(d12[((d12**2).sum(axis=1)<4.)])` throws an exception \"unsupported operand type(s) for ** or pow(): 'generator' and 'int\""
}
] |
[
{
"body": "<p>You can replace:</p>\n<pre><code>d12 = np.array([a+b for a, b in list(itertools.product(p1.T, p2.T))])\n</code></pre>\n<p>with something like:</p>\n<pre><code>p1 = p1.T\np2 = p2.T\np3 = p3.T\nd12 = p1[:,np.newaxis,:] + p2[np.newaxis,:,:]\nd12 = my_d12.reshape((len(p1)*len(p2),2))\n</code></pre>\n<p>I find it most of the times easier to use the first index of an array for <em>point_index</em> and the second index for the dimensions, hence the <code>.T</code>'s</p>\n<p>With the use of the <em>magic</em> index <a href=\"https://numpy.org/doc/stable/reference/constants.html#numpy.newaxis\" rel=\"nofollow noreferrer\"><code>np.newaxis</code></a> at the right places you can create numpy array's of shape (M,N) with normal operators acting on arrays of shape (M) and (N).</p>\n<p>With the <code>reshape</code> method <code>d12</code> changed again to the shape in your original solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T17:08:47.807",
"Id": "487563",
"Score": "0",
"body": "Oh this is great! So simple; exactly what's needed. I've always used `None` in the place of `np.newaxis` thinking they did the same thing but never checked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T16:40:36.277",
"Id": "487685",
"Score": "1",
"body": "@uhoh, you can also use `None` because `np.newaxis` is only an alias of `None`. I prefer to use `np.newaxis` because it is a heads-up that there is something funny going on with indexes and [broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T17:18:50.740",
"Id": "487690",
"Score": "0",
"body": "Okay got it! I think I will switch to that as well since I've been soundly reprimanded for poor readability ;-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T16:53:42.963",
"Id": "248827",
"ParentId": "248816",
"Score": "2"
}
},
{
"body": "<p>Your code is pretty cluttered and you seem fixated on a 'less lines of code equals better code' mindset.</p>\n<p>Firstly lets move <code>r3o2</code> and friends out into the global scope as constants - <code>UPPER_SNAKE_CASE</code> variables in Python.\nThis gets rid of 2 lines of code. Additionally it and makes:</p>\n<ul>\n<li><code>rotatem</code> less confusing as now you're not defining 3 things you never use.</li>\n<li><code>get_points</code> less confusing as now you're not defining 2 things you never use.</li>\n</ul>\n<p>To get <code>rotatem</code> to look cleaner I'd then go on to:</p>\n<ol>\n<li>Move the expression for defining <code>xr</code> and <code>yr</code> into the return.</li>\n<li>Get rid of the clunky tuple unpacked comprehension; just write it out.</li>\n<li>Use better names than <code>c</code> and <code>s</code>; <code>cos</code> and <code>sin</code> could be far more readable.<br />\nI moved them to the latter side of multiplication so the equation doesn't look like <span class=\"math-container\">\\$\\sin x - \\cos y\\$</span></li>\n</ol>\n<p>This makes <code>rotatem</code> pretty readable now.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def rotatem(xy, rot):\n x, y = xy\n cos = np.cos(TO_RADS * rot)\n sin = np.sin(TO_RADS * rot)\n return np.vstack((\n x*cos - y*sin,\n y*cos + x*sin,\n ))\n</code></pre>\n<p>To get <code>get_points</code> to look cleaner I'd then go on to:</p>\n<ol>\n<li>Move the definition of <code>g</code> down to the bottom of the function. By defining it at the top of the function I'm having to read each and every line of code in the function to see if <code>g</code> is used. This is just a waste of time when you only use it in the <code>return</code>.</li>\n<li>Rename:\n<ul>\n<li><code>i</code> to <code>domain</code>,</li>\n<li><code>I</code> to <code>i</code>, and</li>\n<li><code>J</code> to <code>j</code>.</li>\n</ul>\n</li>\n<li>Split the tuple in the expression for <code>xy</code> over multiple lines.</li>\n<li>Change <code>i</code> to <code>i[keep]</code> and <code>j</code> to <code>j[keep]</code>; remove the tuple comprehension before this.</li>\n<li>Add some whitespace around operators.</li>\n</ol>\n<p>This makes <code>get_points</code> a bit more readable. But <code>np.meshgrid</code> is hampering this a bit.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_points(a=1.0, nmax=5, rot=0):\n domain = np.arange(-nmax, nmax + 1)\n i, j = [thing.flatten() for thing in np.meshgrid(domain, domain)]\n keep = np.abs(i + j) <= nmax\n xy = np.vstack((\n i[keep] + 0.5 * j[keep],\n R3O2 * j[keep],\n ))\n return (TWO_PI / (R3O2 * a)) * rotatem(xy, rot=rot)\n</code></pre>\n<p>I still don't really understand what your code is doing, what are <code>rotatem</code> and <code>get_points</code> doing? You can explain this at the top of each function by using a docstring.</p>\n<p>It's taken me a while to understand your code this much, and I still don't see myself understanding it all any time soon. You should really try to improve the readability of your code to the best it can be in the future so others don't just get bored.</p>\n<p>In case you think my changes will decrease performance by anything important, my changes have a negligible impact on performance.</p>\n<pre><code>$ python orig.py\n0.0005879989994355128 4.213629218999813\n$ python peil.py\n0.0005172819992367295 4.236298889999489\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\nimport timeit\n\nR3O2 = np.sqrt(3) / 2.\nTWO_PI = 2 * np.pi # You could just call this tau.\nTO_DEGS = 180 / np.pi\nTO_RADS = np.pi / 180\n\n\ndef rotatem(xy, rot):\n """Explain what rotatem does."""\n x, y = xy\n cos = np.cos(rot)\n sin = np.sin(rot)\n return np.vstack((\n x*cos - y*sin,\n y*cos + x*sin,\n ))\n\n\ndef get_points(a=1.0, nmax=5, rot=0):\n """Explain what get_points does."""\n domain = np.arange(-nmax, nmax + 1)\n i, j = [thing.flatten() for thing in np.meshgrid(domain, domain)]\n keep = np.abs(i + j) <= nmax\n xy = np.vstack((\n i[keep] + 0.5 * j[keep],\n R3O2 * j[keep],\n ))\n return (TWO_PI / (R3O2 * a)) * rotatem(xy, rot=rot)\n\n\ndef main(a1, a2, rot):\n timer = timeit.perfcounter()\n start = timer()\n\n p1 = get_points(a=a1, nmax=20)\n p2 = get_points(a=a2, nmax=20, rot=TO_RADS * rot)\n p3 = get_points(a=a2, nmax=20, rot=TO_RADS * -rot)\n\n mid = timer()\n\n d12 = np.array([a+b for a, b in list(itertools.product(p1.T, p2.T))])\n d13 = np.array([a+b for a, b in list(itertools.product(p1.T, p3.T))])\n d12, d13 = [d[((d**2).sum(axis=1)<4.)] for d in (d12, d13)]\n\n stop = timer()\n print(mid - start, stop - start)\n\n\nif __name__ == '__main__':\n main(1.0, 2**0.2, 22)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:36:10.957",
"Id": "487649",
"Score": "0",
"body": "\"I still don't really understand what your code is doing...\" & \"...my changes have a negligible impact on performance.\" Got it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:52:43.717",
"Id": "487652",
"Score": "0",
"body": "@uhoh If you'd have followed my answer before I'd posted it then you'd get a better answer. Instead due to you not caring about readability or explaining what your code does it's just a waste of our time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:12:41.907",
"Id": "487661",
"Score": "0",
"body": "@uhoh You can also fix this by writing docstrings and improving the readability of your code so your code is accessible to anyone that reads it. Even more so when you put it up for critique."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:28:47.350",
"Id": "248864",
"ParentId": "248816",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T13:58:00.180",
"Id": "248816",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy",
"memory-management",
"physics"
],
"Title": "Better way to calculate double-scattering diffraction using cartesian product of arrays?"
}
|
248816
|
<p>This question is a follow up question to the <a href="https://codereview.stackexchange.com/questions/248561/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-c">Common Unit Testing Code portion</a> of my lexical analyzer questions.</p>
<p>My primary concern is the code in the header file and the C source file that implements strdup(). Since the program this code is a part of is designed to be cross platform it needs to compile and run on either Windows or Linux, and should be compliant with both. The <code>strdup()</code> function is part of the C2X C standard so if it becomes available the code should continue to compile and work. The #defines in the header file are based on the <code>gcc</code> version of <code>string.</code>h.</p>
<p>A secondary concern is performance, many of the parameters have changed to const. The members of the Test_Log_Data struct have been reordered to improve memory usage.</p>
<p>A third concern was archaic usage, the extern preceding the function prototypes has been removed in all header files, not just common_unit_test_logic.h.</p>
<p>The original code is provided for comparison.</p>
<h2><a href="https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor/UnitTests/Common_UnitTest_Code" rel="nofollow noreferrer">New Code</a></h2>
<p><strong>common_unit_test_logic.h</strong></p>
<pre><code>#ifndef COMMON_UNIT_TEST_LOGIC_H
#define COMMON_UNIT_TEST_LOGIC_H
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
#include "human_readable_program_format.h"
#endif
typedef struct test_log_data
{
const char* function_name;
char* path;
bool status;
bool stand_alone;
} Test_Log_Data;
extern FILE* error_out_file;
extern FILE* unit_test_log_file;
bool init_vm_error_reporting(const char* error_log_file_name);
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
Human_Readable_Program_Format* default_program(size_t* program_size);
#endif
#ifndef strdup
#ifdef _MSC_VER
#if _MSC_VER > 1920
#define strdup _strdup
#endif
#else
#define strdup mystrdup
#endif
#endif
char* mystrdup(const char* string_to_copy);
unsigned char* ucstrdup(const unsigned char* string_to_copy);
void disengage_error_reporting(void);
bool init_unit_tests(const char* log_file_name);
void report_error_generic(const char* error_message);
void report_create_and_init_test_log_data_memory_failure(const char* function_name);
void log_test_status_each_step(const char* function_name, const bool status, const char* path, const bool stand_alone);
void init_test_log_data(Test_Log_Data* log_data, const char* function_name, const bool status, char* path, const bool stand_alone);
Test_Log_Data* create_and_init_test_log_data(const char* function_name, const bool status, char* path, const bool stand_alone);
void log_test_status_each_step2(const Test_Log_Data* test_data_to_log);
void log_start_positive_path(const char* function_name);
void log_start_positive_path2(const Test_Log_Data* log_data);
void log_start_test_path(const Test_Log_Data* log_data);
void log_end_test_path(const Test_Log_Data* log_data);
void log_end_positive_path(const char* function_name);
void log_end_positive_path2(const Test_Log_Data* log_data);
void log_start_negative_path(const char* function_name);
void log_end_negative_path(const char* function_name);
void log_generic_message(const char *log_message);
void close_unit_tests(void);
#endif // !COMMON_UNIT_TEST_LOGIC_H
</code></pre>
<p><strong>common_unit_test_logic.c</strong></p>
<pre><code>#include "common_unit_test_logic.h"
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
#include "virtual_machine.h"
#endif
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE* error_out_file = NULL;
FILE* unit_test_log_file = NULL;
char* mystrdup(const char* string_to_copy)
{
char* return_string = NULL;
size_t length = strlen(string_to_copy);
++length;
return_string = calloc(length, sizeof(*return_string));
if (return_string)
{
memcpy(return_string, string_to_copy, length - 1);
}
return return_string;
}
unsigned char* ucstrdup(const unsigned char* string_to_copy)
{
unsigned char* return_string = NULL;
size_t length = strlen((const char *)string_to_copy);
++length;
return_string = calloc(length, sizeof(*return_string));
if (return_string)
{
memcpy(return_string, string_to_copy, length - 1);
}
return return_string;
}
bool init_vm_error_reporting(const char* error_log_file_name)
{
bool status_is_good = true;
if (error_log_file_name)
{
error_out_file = fopen(error_log_file_name, "w");
if (!error_out_file)
{
error_out_file = stderr;
fprintf(error_out_file, "Can't open error output file, %s", "error_log_file_name");
status_is_good = false;
}
}
else
{
error_out_file = stderr;
}
return status_is_good;
}
void disengage_error_reporting(void)
{
if (error_out_file != stderr)
{
fclose(error_out_file);
}
}
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
/*
* Allow unit tests that don't require virtual_machine.c and human_readable_program_format.c.
*/
Human_Readable_Program_Format* default_program(size_t* program_size)
{
Human_Readable_Program_Format program[] =
{
{PUSH, 0x0A},
{PUSH, 0x43},
{PUSH, 0x42},
{PUSH, 0x41},
{OUTPUTCHAR, 0x00},
{POP, 0x00},
{OUTPUTCHAR, 0x00},
{POP, 0x00},
{OUTPUTCHAR, 0x00},
{POP, 0x00},
{HALT, 0x00}
};
size_t progsize = sizeof(program) / sizeof(*program);
Human_Readable_Program_Format* copy_of_program = duplicate_program(program, progsize);
if (copy_of_program)
{
*program_size = progsize;
}
return copy_of_program;
}
#endif
bool init_unit_tests(const char* log_file_name)
{
if (log_file_name)
{
unit_test_log_file = fopen(log_file_name, "w");
if (!unit_test_log_file)
{
fprintf(error_out_file, "Can't open %s for output\n", log_file_name);
return false;
}
error_out_file = unit_test_log_file;
}
else
{
unit_test_log_file = stdout;
error_out_file = stderr;
}
return true;
}
void report_error_generic(const char *error_message)
{
fprintf(error_out_file, "%s\n", error_message);
}
void close_unit_tests(void)
{
if (unit_test_log_file != stdout)
{
fclose(unit_test_log_file);
}
}
static bool log_test_is_positive_path(const Test_Log_Data* log_data)
{
bool is_positive = true;
if (!log_data->path)
{
fprintf(error_out_file, "Programmer error: log_data->path is NULL in log_test_is_positive_path()\n");
return false;
}
char* string_to_test = strdup(log_data->path);
if (!string_to_test)
{
fprintf(error_out_file, "Memory Allocation error: strdup() failed in log_test_is_positive_path()\n");
fprintf(error_out_file, "Exiting program.\n");
exit(EXIT_FAILURE);
}
char* stt_ptr = string_to_test;
while (*stt_ptr)
{
*stt_ptr = (char) toupper(*stt_ptr);
stt_ptr++;
}
is_positive = (strcmp(string_to_test, "POSITIVE") == 0);
free(string_to_test);
return is_positive;
}
void log_test_status_each_step(const char* function_name, const bool status, const char* path, const bool stand_alone)
{
if (stand_alone)
{
fprintf(unit_test_log_file, "%s(): %s Path %s\n", function_name, path,
(status) ? "Passed" : "Failed");
}
}
void log_test_status_each_step2(const Test_Log_Data *test_data_to_log)
{
if (test_data_to_log->stand_alone)
{
fprintf(unit_test_log_file, "%s(): %s Path %s\n", test_data_to_log->function_name,
test_data_to_log->path, (test_data_to_log->status) ? "Passed" : "Failed");
}
}
void log_start_positive_path(const char* function_name)
{
fprintf(unit_test_log_file, "\nStarting POSITIVE PATH testing for %s\n\n",
function_name);
}
void log_start_positive_path2(const Test_Log_Data *log_data)
{
fprintf(unit_test_log_file, "\nStarting POSITIVE PATH testing for %s\n\n",
log_data->function_name);
}
void log_end_positive_path(const char* function_name)
{
fprintf(unit_test_log_file, "\nEnding POSITIVE PATH testing for %s\n", function_name);
}
void log_end_positive_path2(const Test_Log_Data* log_data)
{
fprintf(unit_test_log_file, "\nEnding POSITIVE PATH testing for %s, POSITIVE PATH %s \n",
log_data->function_name, log_data->status? "PASSED" : "FAILED");
}
void log_start_negative_path(const char* function_name)
{
fprintf(unit_test_log_file, "\nStarting NEGATIVE PATH testing for %s\n\n", function_name);
}
void log_end_negative_path(const char* function_name)
{
fprintf(unit_test_log_file, "\nEnding NEGATIVE PATH testing for %s\n", function_name);
fflush(unit_test_log_file); // Current unit test is done flush the output.
}
void log_start_test_path(const Test_Log_Data* log_data)
{
bool is_positive = log_test_is_positive_path(log_data);
fprintf(unit_test_log_file, "\nStarting %s PATH testing for %s\n\n",
is_positive ? "POSITIVE" : "NEGATIVE", log_data->function_name);
}
void log_end_test_path(const Test_Log_Data *log_data)
{
bool is_positive = log_test_is_positive_path(log_data);
fprintf(unit_test_log_file, "\nEnding %s PATH testing for %s, Path %s\n",
is_positive ? "POSITIVE" : "NEGATIVE", log_data->function_name,
log_data->status ? "PASSED" : "FAILED");
if (!is_positive)
{
fflush(unit_test_log_file); // Current unit test is done flush the output.
}
}
void log_generic_message(const char* log_message)
{
fprintf(unit_test_log_file, log_message);
}
void init_test_log_data(Test_Log_Data* log_data, const char *function_name, const bool status, char *path, bool stand_alone)
{
log_data->function_name = function_name;
log_data->status = status;
log_data->path = path;
log_data->stand_alone = stand_alone;
}
Test_Log_Data *create_and_init_test_log_data(const char* function_name, const bool status, char* path, const bool stand_alone)
{
Test_Log_Data* log_data = calloc(1, sizeof(*log_data));
if (log_data)
{
init_test_log_data(log_data, function_name, status, path, stand_alone);
}
else
{
fprintf(error_out_file, "In %s calloc() failed\n", "create_and_init_test_log_data");
}
return log_data;
}
// provides common error report for memory allocation error.
void report_create_and_init_test_log_data_memory_failure(const char *function_name)
{
fprintf(error_out_file, "In function %s, Memory allocation failed in create_and_init_test_log_data\n", function_name);
}
</code></pre>
<h2><a href="https://github.com/pacmaninbw/VMWithEditor/tree/Before_First_Code_Review/VMWithEditor/UnitTests/Common_UnitTest_Code" rel="nofollow noreferrer">Original Code</a>:</h2>
<p><strong>common_unit_test_logic.h</strong></p>
<pre><code>#ifndef COMMON_UNIT_TEST_LOGIC_H
#define COMMON_UNIT_TEST_LOGIC_H
#include <stdio.h>
#include <stdbool.h>
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
#include "human_readable_program_format.h"
#endif
typedef struct test_log_data
{
char* function_name;
bool status;
char* path;
bool stand_alone;
} Test_Log_Data;
extern FILE* error_out_file;
extern FILE* unit_test_log_file;
extern bool init_vm_error_reporting(char* error_log_file_name);
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
extern Human_Readable_Program_Format* default_program(size_t* program_size);
#endif
extern void disengage_error_reporting(void);
extern bool init_unit_tests(char* log_file_name);
extern void report_error_generic(char* error_message);
extern void report_create_and_init_test_log_data_memory_failure(char* function_name);
extern void log_test_status_each_step(char* function_name, bool status, char* path, bool stand_alone);
extern void init_test_log_data(Test_Log_Data* log_data, char* function_name, bool status, char* path, bool stand_alone);
extern Test_Log_Data* create_and_init_test_log_data(char* function_name, bool status, char* path, bool stand_alone);
extern void log_test_status_each_step2(Test_Log_Data* test_data_to_log);
extern void log_start_positive_path(char* function_name);
extern void log_start_positive_path2(Test_Log_Data* log_data);
extern void log_start_test_path(Test_Log_Data* log_data);
extern void log_end_test_path(Test_Log_Data* log_data);
extern void log_end_positive_path(char* function_name);
extern void log_end_positive_path2(Test_Log_Data* log_data);
extern void log_start_negative_path(char* function_name);
extern void log_end_negative_path(char* function_name);
extern void log_generic_message(char *log_message);
extern void close_unit_tests(void);
#endif // !COMMON_UNIT_TEST_LOGIC_H
</code></pre>
<p><strong>common_unit_test_logic.c</strong></p>
<pre><code>#include "common_unit_test_logic.h"
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
#include "virtual_machine.h"
#endif
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE* error_out_file = NULL;
FILE* unit_test_log_file = NULL;
bool init_vm_error_reporting(char* error_log_file_name)
{
bool status_is_good = true;
if (error_log_file_name)
{
error_out_file = fopen(error_log_file_name, "w");
if (!error_out_file)
{
error_out_file = stderr;
fprintf(error_out_file, "Can't open error output file, %s", "error_log_file_name");
status_is_good = false;
}
}
else
{
error_out_file = stderr;
}
return status_is_good;
}
void disengage_error_reporting(void)
{
if (error_out_file != stderr)
{
fclose(error_out_file);
}
}
#ifndef REDUCED_VM_AND_HRF_DEPENDENCIES
/*
* Allow unit tests that don't require virtual_machine.c and human_readable_program_format.c.
*/
Human_Readable_Program_Format* default_program(size_t* program_size)
{
Human_Readable_Program_Format program[] =
{
{PUSH, 0x0A},
{PUSH, 0x43},
{PUSH, 0x42},
{PUSH, 0x41},
{OUTPUTCHAR, 0x00},
{POP, 0x00},
{OUTPUTCHAR, 0x00},
{POP, 0x00},
{OUTPUTCHAR, 0x00},
{POP, 0x00},
{HALT, 0x00}
};
size_t progsize = sizeof(program) / sizeof(*program);
Human_Readable_Program_Format* copy_of_program = duplicate_program(program, progsize);
if (copy_of_program)
{
*program_size = progsize;
}
return copy_of_program;
}
#endif
bool init_unit_tests(char* log_file_name)
{
if (log_file_name)
{
unit_test_log_file = fopen(log_file_name, "w");
if (!unit_test_log_file)
{
fprintf(error_out_file, "Can't open %s for output\n", log_file_name);
return false;
}
error_out_file = unit_test_log_file;
}
else
{
unit_test_log_file = stdout;
error_out_file = stderr;
}
return true;
}
void report_error_generic(char *error_message)
{
fprintf(error_out_file, "%s\n", error_message);
}
void close_unit_tests(void)
{
if (unit_test_log_file != stdout)
{
fclose(unit_test_log_file);
}
}
static bool log_test_is_positive_path(Test_Log_Data* log_data)
{
bool is_positive = true;
if (!log_data->path)
{
fprintf(error_out_file, "Programmer error: log_data->path is NULL in log_test_is_positive_path()\n");
return false;
}
char* string_to_test = _strdup(log_data->path);
if (!string_to_test)
{
fprintf(error_out_file, "Memory Allocation error: _strdup() failed in log_test_is_positive_path()\n");
fprintf(error_out_file, "Exiting program.\n");
exit(EXIT_FAILURE);
}
char* stt_ptr = string_to_test;
while (*stt_ptr)
{
*stt_ptr = (char) toupper(*stt_ptr);
stt_ptr++;
}
is_positive = (strcmp(string_to_test, "POSITIVE") == 0);
return is_positive;
}
void log_test_status_each_step(char* function_name, bool status, char* path, bool stand_alone)
{
if (stand_alone)
{
fprintf(unit_test_log_file, "%s(): %s Path %s\n", function_name, path,
(status) ? "Passed" : "Failed");
}
}
void log_test_status_each_step2(Test_Log_Data *test_data_to_log)
{
if (test_data_to_log->stand_alone)
{
fprintf(unit_test_log_file, "%s(): %s Path %s\n", test_data_to_log->function_name,
test_data_to_log->path, (test_data_to_log->status) ? "Passed" : "Failed");
}
}
void log_start_positive_path(char* function_name)
{
fprintf(unit_test_log_file, "\nStarting POSITIVE PATH testing for %s\n\n",
function_name);
}
void log_start_positive_path2(Test_Log_Data *log_data)
{
fprintf(unit_test_log_file, "\nStarting POSITIVE PATH testing for %s\n\n",
log_data->function_name);
}
void log_end_positive_path(char* function_name)
{
fprintf(unit_test_log_file, "\nEnding POSITIVE PATH testing for %s\n", function_name);
}
void log_end_positive_path2(Test_Log_Data* log_data)
{
fprintf(unit_test_log_file, "\nEnding POSITIVE PATH testing for %s, POSITIVE PATH %s \n",
log_data->function_name, log_data->status? "PASSED" : "FAILED");
}
void log_start_negative_path(char* function_name)
{
fprintf(unit_test_log_file, "\nStarting NEGATIVE PATH testing for %s\n\n", function_name);
}
void log_end_negative_path(char* function_name)
{
fprintf(unit_test_log_file, "\nEnding NEGATIVE PATH testing for %s\n", function_name);
fflush(unit_test_log_file); // Current unit test is done flush the output.
}
void log_start_test_path(Test_Log_Data* log_data)
{
bool is_positive = log_test_is_positive_path(log_data);
fprintf(unit_test_log_file, "\nStarting %s PATH testing for %s\n\n",
is_positive ? "POSITIVE" : "NEGATIVE", log_data->function_name);
}
void log_end_test_path(Test_Log_Data *log_data)
{
bool is_positive = log_test_is_positive_path(log_data);
fprintf(unit_test_log_file, "\nEnding %s PATH testing for %s, Path %s\n",
is_positive ? "POSITIVE" : "NEGATIVE", log_data->function_name,
log_data->status ? "PASSED" : "FAILED");
if (!is_positive)
{
fflush(unit_test_log_file); // Current unit test is done flush the output.
}
}
void log_generic_message(char* log_message)
{
fprintf(unit_test_log_file, log_message);
}
void init_test_log_data(Test_Log_Data* log_data, char *function_name, bool status, char *path, bool stand_alone)
{
log_data->function_name = function_name;
log_data->status = status;
log_data->path = path;
log_data->stand_alone = stand_alone;
}
Test_Log_Data *create_and_init_test_log_data(char* function_name, bool status, char* path, bool stand_alone)
{
Test_Log_Data* log_data = calloc(1, sizeof(*log_data));
if (log_data)
{
init_test_log_data(log_data, function_name, status, path, stand_alone);
}
else
{
fprintf(error_out_file, "In %s calloc() failed\n", "create_and_init_test_log_data");
}
return log_data;
}
// provides common error report for memory allocation error.
void report_create_and_init_test_log_data_memory_failure(char *function_name)
{
fprintf(error_out_file, "In function %s, Memory allocation failed in create_and_init_test_log_data\n", function_name);
}
</code></pre>
|
[] |
[
{
"body": "<h2>The files <code>common_unit_test_logic.*</code> are too complex.</h2>\n<p>The common_unit_test_logic .c file and header file do not follow the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that states</p>\n<blockquote>\n<p>… that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>This forced unnecessary #ifdef and #ifndef statements into the code. This has been rectified by breaking <code> common_unit_test_logic.c</code> and <code> common_unit_test_logic.h</code> into 3 separate modules, <code>error_reporting</code>, <code>my_strdup</code>, and <code> unit_test_logging</code>.</p>\n<p>Only the <code> unit_test_logging</code> module is still in the <code> Common_UnitTest_Code</code> directory under the <code> UnitTests</code> directory. The <code>error_reporting</code> module and the <code> my_strdup</code> module have both been moved up to the <code> VMWithEditor</code> source code directory so that they can be shared with the primary project as well as the multiple unit test projects. A forth module <code>default_program</code> was also created for the main program and some of the other unit tests, the code was ifdef’de out of the lexical analyzer unit test.</p>\n<p>Breaking the code up allows greater reuse of each of the modules, but requires additional <code>#include</code> statements in many of the files.</p>\n<h2>The separated modules:</h2>\n<p><strong>my_strdup.h</strong></p>\n<pre><code>#ifndef MY_STRDUP_H\n#define MY_STRDUP_H\n\n#include <string.h>\n\n#ifndef strdup\n#ifdef _MSC_VER\n#if _MSC_VER > 1920\n#define strdup _strdup\n#endif\n#else\n#define strdup mystrdup \n#endif\n#endif\n\nchar* mystrdup(const char* string_to_copy);\nunsigned char* ucstrdup(const unsigned char* string_to_copy);\n\n#endif // MY_STRDUP_H\n</code></pre>\n<p><strong>my_strdup.c</strong></p>\n<pre><code>#include "my_strdup.h"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar* mystrdup(const char* string_to_copy)\n{\n char* return_string = NULL;\n size_t length = strlen(string_to_copy);\n ++length;\n\n return_string = calloc(length, sizeof(*return_string));\n if (return_string)\n {\n memcpy(return_string, string_to_copy, length - 1);\n }\n\n return return_string;\n}\n\nunsigned char* ucstrdup(const unsigned char* string_to_copy)\n{\n unsigned char* return_string = NULL;\n size_t length = strlen((const char*)string_to_copy);\n ++length;\n\n return_string = calloc(length, sizeof(*return_string));\n if (return_string)\n {\n memcpy(return_string, string_to_copy, length - 1);\n }\n\n return return_string;\n}\n</code></pre>\n<p><strong>error_reporting.h</strong></p>\n<pre><code>#ifndef ERROR_REPORTING_H\n#define ERROR_REPORTING_H\n\n#include <stdbool.h>\n#include <stdio.h>\n\nextern FILE* error_out_file;\n\nbool init_vm_error_reporting(const char* error_log_file_name);\nvoid disengage_error_reporting(void);\nvoid report_error_generic(const char* error_message);\n\n#endif // !ERROR_REPORTING_H\n</code></pre>\n<p><strong>error_reporting.c</strong></p>\n<pre><code>#ifndef ERROR_REPORTING_C\n#define ERROR_REPORTING_C\n\n#include "error_reporting.h"\n#ifdef UNIT_TESTING\n#include "unit_test_logging.h"\n#endif // UNIT_TESTING\n#include <stdio.h>\n\nFILE* error_out_file = NULL;\n\nbool init_vm_error_reporting(const char* error_log_file_name)\n{\n bool status_is_good = true;\n\n if (error_log_file_name)\n {\n error_out_file = fopen(error_log_file_name, "w");\n if (!error_out_file)\n {\n#ifdef UNIT_TESTING\n error_out_file = stderr;\n#endif // UNIT_TESTING\n fprintf(error_out_file, "Can't open error output file, %s", "error_log_file_name");\n status_is_good = false;\n }\n }\n else\n {\n error_out_file = stderr;\n }\n\n return status_is_good;\n}\n\nvoid disengage_error_reporting(void)\n{\n if (error_out_file != stderr)\n {\n fclose(error_out_file);\n }\n}\n\nvoid report_error_generic(const char *error_message)\n{\n fprintf(error_out_file, "%s\\n", error_message);\n}\n\n#endif // !ERROR_REPORTING_C\n</code></pre>\n<p><strong>default_program.h</strong></p>\n<pre><code>#ifndef DEFAULT_PROGRAM_H\n#define DEFAULT_PROGRAM_H\n\n#include "human_readable_program_format.h"\n#include <stdint.h>\n\nHuman_Readable_Program_Format* default_program(size_t* program_size);\n\n\n#endif // DEFAULT_PROGRAM_H\n</code></pre>\n<p><strong>default_program.c</strong></p>\n<pre><code>#ifndef DEFAULT_PROGRAM_C\n#define DEFAULT_PROGRAM_C\n\n#include "human_readable_program_format.h"\n#include "default_program.h"\n#include <stdint.h>\n\nHuman_Readable_Program_Format* default_program(size_t* program_size)\n{\n Human_Readable_Program_Format program[] =\n {\n {PUSH, 0x0A},\n {PUSH, 0x43},\n {PUSH, 0x42},\n {PUSH, 0x41},\n {OUTPUTCHAR, 0x00},\n {POP, 0x00},\n {OUTPUTCHAR, 0x00},\n {POP, 0x00},\n {OUTPUTCHAR, 0x00},\n {POP, 0x00},\n {HALT, 0x00}\n };\n\n size_t progsize = sizeof(program) / sizeof(*program);\n\n Human_Readable_Program_Format* copy_of_program = duplicate_program(program, progsize);\n if (copy_of_program)\n {\n *program_size = progsize;\n }\n\n return copy_of_program;\n}\n\n#endif // DEFAULT_PROGRAM_C\n</code></pre>\n<p><strong>unit_test_logging.h</strong></p>\n<pre><code>#ifndef UNIT_TEST_LOGGING_H\n#define UNIT_TEST_LOGGING_H\n#include <stdio.h>\n#include <stdbool.h>\n\ntypedef struct test_log_data\n{\n const char* function_name;\n char* path;\n bool status;\n bool stand_alone;\n} Test_Log_Data;\n\nextern FILE* unit_test_log_file;\n\nbool init_unit_tests(const char* log_file_name);\nvoid report_create_and_init_test_log_data_memory_failure(const char* function_name);\nvoid log_test_status_each_step(const char* function_name, const bool status, const char* path, const bool stand_alone);\nvoid init_test_log_data(Test_Log_Data* log_data, const char* function_name, const bool status, char* path, const bool stand_alone);\nTest_Log_Data* create_and_init_test_log_data(const char* function_name, const bool status, char* path, const bool stand_alone);\nvoid log_test_status_each_step2(const Test_Log_Data* test_data_to_log);\nvoid log_start_positive_path(const char* function_name);\nvoid log_start_positive_path2(const Test_Log_Data* log_data);\nvoid log_start_test_path(const Test_Log_Data* log_data);\nvoid log_end_test_path(const Test_Log_Data* log_data);\nvoid log_end_positive_path(const char* function_name);\nvoid log_end_positive_path2(const Test_Log_Data* log_data);\nvoid log_start_negative_path(const char* function_name);\nvoid log_end_negative_path(const char* function_name);\nvoid log_generic_message(const char *log_message);\nvoid close_unit_tests(void);\n\n#endif // !UNIT_TEST_LOGGING_H\n</code></pre>\n<p><strong>unit_test_logging.c</strong></p>\n<pre><code>#include "error_reporting.h"\n#include <ctype.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nFILE* unit_test_log_file = NULL;\n\n\nbool init_unit_tests(const char* log_file_name)\n{\n if (log_file_name)\n {\n unit_test_log_file = fopen(log_file_name, "w");\n if (!unit_test_log_file)\n {\n fprintf(error_out_file, "Can't open %s for output\\n", log_file_name);\n return false;\n }\n error_out_file = unit_test_log_file;\n }\n else\n {\n unit_test_log_file = stdout;\n error_out_file = stderr;\n }\n\n return true;\n}\n\nvoid close_unit_tests(void)\n{\n if (unit_test_log_file != stdout)\n {\n fclose(unit_test_log_file);\n }\n}\n\nstatic bool log_test_is_positive_path(const Test_Log_Data* log_data)\n{\n bool is_positive = true;\n\n if (!log_data->path)\n {\n fprintf(error_out_file, "Programmer error: log_data->path is NULL in log_test_is_positive_path()\\n");\n return false;\n }\n\n char* string_to_test = strdup(log_data->path);\n if (!string_to_test)\n {\n fprintf(error_out_file, "Memory Allocation error: strdup() failed in log_test_is_positive_path()\\n");\n fprintf(error_out_file, "Exiting program.\\n");\n exit(EXIT_FAILURE);\n }\n\n char* stt_ptr = string_to_test;\n while (*stt_ptr)\n {\n *stt_ptr = (char) toupper(*stt_ptr);\n stt_ptr++;\n }\n\n is_positive = (strcmp(string_to_test, "POSITIVE") == 0);\n free(string_to_test);\n\n return is_positive;\n}\n\nvoid log_test_status_each_step(const char* function_name, const bool status, const char* path, const bool stand_alone)\n{\n if (stand_alone)\n {\n fprintf(unit_test_log_file, "%s(): %s Path %s\\n", function_name, path,\n (status) ? "Passed" : "Failed");\n }\n}\n\nvoid log_test_status_each_step2(const Test_Log_Data *test_data_to_log)\n{\n if (test_data_to_log->stand_alone)\n {\n fprintf(unit_test_log_file, "%s(): %s Path %s\\n", test_data_to_log->function_name,\n test_data_to_log->path, (test_data_to_log->status) ? "Passed" : "Failed");\n }\n}\n\nvoid log_start_positive_path(const char* function_name)\n{\n fprintf(unit_test_log_file, "\\nStarting POSITIVE PATH testing for %s\\n\\n",\n function_name);\n}\n\nvoid log_start_positive_path2(const Test_Log_Data *log_data)\n{\n fprintf(unit_test_log_file, "\\nStarting POSITIVE PATH testing for %s\\n\\n",\n log_data->function_name);\n}\n\nvoid log_end_positive_path(const char* function_name)\n{\n fprintf(unit_test_log_file, "\\nEnding POSITIVE PATH testing for %s\\n", function_name);\n}\n\nvoid log_end_positive_path2(const Test_Log_Data* log_data)\n{\n fprintf(unit_test_log_file, "\\nEnding POSITIVE PATH testing for %s, POSITIVE PATH %s \\n",\n log_data->function_name, log_data->status? "PASSED" : "FAILED");\n}\n\nvoid log_start_negative_path(const char* function_name)\n{\n fprintf(unit_test_log_file, "\\nStarting NEGATIVE PATH testing for %s\\n\\n", function_name);\n}\n\nvoid log_end_negative_path(const char* function_name)\n{\n fprintf(unit_test_log_file, "\\nEnding NEGATIVE PATH testing for %s\\n", function_name);\n fflush(unit_test_log_file); // Current unit test is done flush the output.\n}\n\nvoid log_start_test_path(const Test_Log_Data* log_data)\n{\n bool is_positive = log_test_is_positive_path(log_data);\n\n fprintf(unit_test_log_file, "\\nStarting %s PATH testing for %s\\n\\n",\n is_positive ? "POSITIVE" : "NEGATIVE", log_data->function_name);\n}\n\nvoid log_end_test_path(const Test_Log_Data *log_data)\n{\n bool is_positive = log_test_is_positive_path(log_data);\n\n fprintf(unit_test_log_file, "\\nEnding %s PATH testing for %s, Path %s\\n",\n is_positive ? "POSITIVE" : "NEGATIVE", log_data->function_name,\n log_data->status ? "PASSED" : "FAILED");\n\n if (!is_positive)\n {\n fflush(unit_test_log_file); // Current unit test is done flush the output.\n }\n}\n\nvoid log_generic_message(const char* log_message)\n{\n fprintf(unit_test_log_file, log_message);\n}\n\nvoid init_test_log_data(Test_Log_Data* log_data, const char *function_name, const bool status, char *path, bool stand_alone)\n{\n log_data->function_name = function_name;\n log_data->status = status;\n log_data->path = path;\n log_data->stand_alone = stand_alone;\n}\n\nTest_Log_Data *create_and_init_test_log_data(const char* function_name, const bool status, char* path, const bool stand_alone)\n{\n Test_Log_Data* log_data = calloc(1, sizeof(*log_data));\n if (log_data)\n {\n init_test_log_data(log_data, function_name, status, path, stand_alone);\n }\n else\n {\n fprintf(error_out_file, "In %s calloc() failed\\n", "create_and_init_test_log_data");\n }\n\n return log_data;\n}\n\n// provides common error report for memory allocation error.\nvoid report_create_and_init_test_log_data_memory_failure(const char *function_name)\n{\n fprintf(error_out_file, "In function %s, Memory allocation failed in create_and_init_test_log_data\\n", function_name);\n}\n</code></pre>\n<h2>Update 9/9/2020.</h2>\n<p>In response to the <a href=\"https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a/248599#248599\">original answer</a> by @chux-ReinstateMonica as well as their comment below, <code>error_reporting.h</code> is now <code>ERH_error_reporting.h</code>, all global symbols provided by that module start with <code>ERH_</code>.</p>\n<p><code>lexical_analyzer.h</code> has been renamed <code>LAH_lexical_analyzer.h</code> and all global symbols provided by the lexical analyzer now start with <code>LAH_</code>.</p>\n<p><code>my_strdup.h</code> has been renamed <code>SSF_safe_string_functions.h</code> and all symbols now start with <code>SSF_</code>, additional functions such as <code>char* SSF_strcat(char* destination, char* source, size_t destination_size);</code> have been added.</p>\n<p><code>unit_test_logging.h</code> has been renamed <code>UTL_unit_test_logging.h</code> with the corresponding name changes to the structs, functions and new enum that replaces the <code>char* path</code> variable in the struct.</p>\n<p>Similar name changes have been made to at least 3 other files as well.</p>\n<p>In response to the <a href=\"https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a/248581#248581\">answer by @G.Sliepen</a> 2 variadic function have been added, <code>void UTL_va_log_fprintf(const char* format, ...);</code> in <code>UTL_unit_test_logging.h</code> and <code>void ERH_va_report_error_fprintf(const char* format, ...);</code> in <code>ERH_error_reporting.h</code> to reduce the usage of <code>sprintf()</code> and any remaining <code>sprintf()</code> statements were converted to <code>snprintf()</code>.</p>\n<p>The programs no longer depend on a <code>BUFSIZ</code> from <code>stdio.h</code> <code>ERH_error_reporting.h</code> provides the constant <code>ERH_ERROR_BUFFER_SIZE</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T23:01:38.410",
"Id": "488166",
"Score": "0",
"body": "I'd like to see a common among the functions per *.h file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T23:26:08.313",
"Id": "488168",
"Score": "0",
"body": "@chux-ReinstateMonica Look in the [repository](https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor) All the enums and macros have been renamed with 3 or 4 letters at the beginning. Many of the header files have also been renamed so that they start with the same 3 or 4 letters, for example my_strdup.h is now SSF_sage_string_functions.h, and I need to re-implement SSF_strdup() to at least make sure that the input is not nil like in your answer. Removed most sprintf statements and any that weren't removed now use snprintf rather than sprintf."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T17:20:21.560",
"Id": "488250",
"Score": "1",
"body": "Adding a prefix like `ERH_` might be a way to avoid global namespace clashes, but you don't need to use it in the filenames, and furthermore you now have a lot of repetition, like `ERH_error_reporting` having both the full name and abbreviation. Also, `ERH_va_report_error_fprintf()` contains way too much details. That it is variadic and calls `fprintf()` internally is not important.The most important parts are `ERH` for the module, and the fact that you want to report something, so `ERH_report()` would be a much better name."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:10:14.947",
"Id": "248883",
"ParentId": "248817",
"Score": "2"
}
},
{
"body": "<p><code>mystrdup()</code> has a short-coming: to be *nix-like, I'd expect detecting cases that may set <code>errno</code>.</p>\n<p>IMO, use <code>malloc()</code> and copy the <em>null character</em> too.</p>\n<p>From <a href=\"https://stackoverflow.com/a/39694254/2410359\">When is it a good idea to use strdup (vs malloc / strcpy)</a></p>\n<pre><code>#include <errno.h>\n#include <stdlib.h>\n\nchar *mystrdup(const char *s) {\n // Optional test, s should point to a string\n if (s == NULL) { \n #ifdef EINVAL\n // For systems that support this "invalid argument" errno\n errno = EINVAL;\n #ednif\n return NULL; \n }\n size_t siz = strlen(s) + 1;\n char *y = malloc(siz);\n if (y != NULL) {\n memcpy(y, s, siz);\n } else {\n #ifdef ENOMEM\n // For systems that support this "out-of-memory" errno\n errno = ENOMEM;\n #else\n ;\n #endif\n }\n return y;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T00:32:27.170",
"Id": "488172",
"Score": "1",
"body": "Thanks, you helped me fix a section of code where I wasn't checking the return value of mystrdup() before using it. I went looking for calls to mystrdup() to add perror()."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T22:55:39.073",
"Id": "249103",
"ParentId": "248817",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249103",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:18:01.387",
"Id": "248817",
"Score": "2",
"Tags": [
"performance",
"c",
"unit-testing",
"comparative-review"
],
"Title": "Common Unit Testing Code – Follow Up"
}
|
248817
|
<p>Haven't worked too much with jQuery and I had to get the values from different elements (they have the ids 0, 1 and 2) in order to compute the sum of them and update a field with that value.</p>
<p>The code works well but I was wondering if it is possible to write less code and use something like a for loop in this case.</p>
<p>Here is the code:</p>
<pre><code>function total() {
var subtotal0 = parseFloat(
$('#0').find('.cart-subtotal').text().replace('€', '')
);
var subtotal1 = parseFloat(
$('#1').find('.cart-subtotal').text().replace('€', '')
);
var subtotal2 = parseFloat(
$('#2').find('.cart-subtotal').text().replace('€', '')
);
var total = subtotal0 + subtotal1 + subtotal2;
$('.cart-total-price').text(total + '€');
}
</code></pre>
<p>Is it possible to make it better?</p>
|
[] |
[
{
"body": "<p>Instead of IDs (like <code>#0</code>), use classes instead. (Numeric-indexed IDs are quite a code smell anyway.) Or, if you can't remove the IDs entirely, just add classes to those elements. For example, adding the class of <code>subtotal-container</code> to each of those elements with IDs.</p>\n<p>To make things clearer, I'd also recommend calling the function something like <code>calculateTotal</code> instead of <code>total</code> - it's more precise and also avoids <a href=\"https://eslint.org/docs/rules/no-shadow\" rel=\"nofollow noreferrer\">possibly-confusing shadowing</a>:</p>\n<pre><code>function calculateTotal() {\n const total = [...$('.subtotal-container .cart-subtotal')]\n .map(subtotalElm => \n Number(subtotalElm.textContent.replace('€', '')))\n .reduce((a, b) => a + b, 0);\n $('.cart-total-price').text(total + '€');\n}\n</code></pre>\n<p>Though, at this point, you may as well remove the dependency on jQuery entirely if you wished, it's not really accomplishing anything useful:</p>\n<pre><code>const total = [...document.querySelectorAll('.subtotal-container .cart-subtotal')]\n .map(subtotalElm => Number(subtotalElm.textContent.replace('€', '')))\n .reduce((a, b) => a + b, 0);\ndocument.querySelector('.cart-total-price').textContent = total + '€';\n</code></pre>\n<p>With jQuery, keep in mind that</p>\n<pre><code>$('someSelector').find('someOtherSelector')\n</code></pre>\n<p>is equivalent to</p>\n<pre><code>$('someSelector someOtherSelector')\n</code></pre>\n<p>via the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator\" rel=\"nofollow noreferrer\">descendant selector</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:36:17.387",
"Id": "487548",
"Score": "0",
"body": "I was writing it as a function in order to be able to call it and I see that you've done it as an array. In this case it doesn't work anymore. Is it possible to make it \"callable\" or should it be changed also where is called from `total()` to something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:41:09.900",
"Id": "487549",
"Score": "0",
"body": "I was trying to only write the necessary code, thought it was obvious that it was the new content of the `total` function"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:30:43.473",
"Id": "248821",
"ParentId": "248820",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248821",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:28:40.443",
"Id": "248820",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Iterate through multiple elements based on their id in jQuery"
}
|
248820
|
<p>I did a simple to-do application for native Javascript. This is my first time, previously I used only jQuery. What recommendations would be useful?</p>
<p><a href="https://codepen.io/denibudeyko/pen/MWyEmox" rel="nofollow noreferrer">https://codepen.io/denibudeyko/pen/MWyEmox</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>(function(window) {
'use strict';
// Initial Const
const input = document.getElementsByClassName('new-todo')[0]
const todoList = document.getElementsByClassName('todo-list')[0]
const items = document.querySelectorAll('.todo-list li')
const clear = document.querySelector('.clear-completed')
const todoCount = document.querySelector('.todo-count strong')
// Add new task
input.addEventListener('keyup', function(e) {
var string = input.value;
if (e.key == 'Enter') {
const li = document.createElement('li')
li.innerHTML = `
<div class="view">
<input class="toggle" type="checkbox" />
<label>${string}</label>
<button class="destroy"></button>
</div>
<input class="edit" value="${string}">
`;
todoList.appendChild(li);
const childrenItem = li.querySelector('input.toggle')
childrenItem.addEventListener('click', event => {
toggleTaskStatusEvent(event.target)
})
input.value = '';
updateCount();
}
})
function updateCount() {
todoCount.textContent = document.querySelectorAll('.todo-list li:not(.completed)').length;
}
updateCount()
// Toggle Status
document.querySelectorAll('.todo-list li').forEach(item => {
const toggleCheckbox = item.querySelector('input.toggle')
toggleCheckbox.addEventListener('click', event => {
toggleTaskStatusEvent(event.target)
})
})
// ToggleTaskStatus
function toggleTaskStatusEvent(e) {
const liParent = e.closest('li')
liParent.classList.toggle('completed')
updateCount()
}
clear.addEventListener('click', function() {
document.querySelectorAll('.todo-list li.completed').forEach(item => {
item.remove()
})
})
// FiltersButtons
document.querySelectorAll('ul.filters li').forEach(item => {
const filterButton = item.children[0];
filterButton.addEventListener('click', event => {
runFilter(event.target)
})
})
// Function Filter
function runFilter(item) {
const notCompletedItemsFilter = document.querySelectorAll('.todo-list li:not(.completed)')
const completedItemsFilter = document.querySelectorAll('.todo-list li.completed')
const allItemsFilter = document.querySelectorAll('.todo-list li');
var href = item.getAttribute('href')
href = href.split('#/')[1]
const activeButton = document.querySelector('ul.filters a.selected')
activeButton.classList.remove('selected')
item.classList.add("selected")
if (href == 'active') {
notCompletedItemsFilter.forEach(item => {
item.style.display = 'block';
})
completedItemsFilter.forEach(item => {
item.style.display = 'none';
})
} else if (href == 'completed') {
notCompletedItemsFilter.forEach(item => {
item.style.display = 'none';
})
completedItemsFilter.forEach(item => {
item.style.display = 'block';
})
} else if (href == 'all') {
allItemsFilter.forEach(item => {
item.style.display = 'block'
})
}
}
// Edit Task Double click
items.forEach(item => {
item.addEventListener('dblclick', event => {
editTask(item)
})
})
// Edit Task
function editTask(item) {
var label = item.querySelector('label');
var editButton = item.querySelector('.edit')
editButton.style.display = 'block'
editButton.addEventListener('keyup', function(event) {
label.textContent = this.value
if (event.key == 'Enter') {
this.style.display = 'none';
}
})
}
// Function Remove Task
items.forEach(item => {
item.querySelector('.destroy').addEventListener('click', function(event) {
item.remove()
updateCount();
})
})
})(window);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.todo-list li .toggle {
cursor: pointer;
}
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #4d4d4d;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 300;
}
:focus {
outline: 0;
}
.hidden {
display: none;
}
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp h1 {
position: absolute;
top: -155px;
width: 100%;
font-size: 100px;
font-weight: 100;
text-align: center;
color: rgba(175, 47, 47, 0.15);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
border: 0;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0, 0, 0, 0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
.toggle-all {
width: 1px;
height: 1px;
border: none;
/* Mobile Safari */
opacity: 0;
position: absolute;
right: 100%;
bottom: 100%;
}
.toggle-all+label {
width: 60px;
height: 34px;
font-size: 0;
position: absolute;
top: -52px;
left: -13px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
}
.toggle-all+label:before {
content: '❯';
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
.toggle-all:checked+label:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: 506px;
padding: 12px 16px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none;
/* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle {
opacity: 0;
}
.todo-list li .toggle+label {
/*
Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
*/
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
background-repeat: no-repeat;
background-position: center left;
}
.todo-list li .toggle:checked+label {
background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E');
}
.todo-list li label {
word-break: break-all;
padding: 15px 15px 15px 60px;
display: block;
line-height: 1.2;
transition: color 0.4s;
}
.todo-list li.completed label {
color: #d9d9d9;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover {
color: #af5b5e;
}
.todo-list li .destroy:after {
content: '×';
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
color: #777;
padding: 10px 15px;
height: 20px;
text-align: center;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6, 0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6, 0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
.filters li a.selected {
border-color: rgba(175, 47, 47, 0.2);
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
cursor: pointer;
}
.clear-completed:hover {
text-decoration: underline;
}
.info {
margin: 65px auto 0;
color: #bfbfbf;
font-size: 10px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #c5c5c5;
border-bottom: 1px dashed #f7f7f7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
#issue-count {
display: none;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar>.learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
padding-left: 300px;
}
.learn-bar>.learn {
left: 8px;
}
}
.destroy {
cursor: pointer;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- <link rel="stylesheet" href="node_modules/todomvc-common/base.css"> -->
<!-- <link rel="stylesheet" href="node_modules/todomvc-app-css/index.css"> -->
<section class="todoapp">
<header class="header">
<h1>todos</h1>
<input class="new-todo" placeholder="What needs to be done?" autofocus>
</header>
<!-- This section should be hidden by default and shown when there are todos -->
<section class="main">
<input id="toggle-all" class="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<ul class="todo-list">
<!-- These are here just to show the structure of the list items -->
<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
<li class='completed'>
<div class="view">
<input class="toggle" checked type="checkbox">
<label>Taste JavaScript</label>
<button class="destroy"></button>
</div>
<input class="edit" value="Taste JavaScript">
</li>
<li>
<div class="view">
<input class="toggle" type="checkbox">
<label>Refactoring Code</label>
<button class="destroy"></button>
</div>
<input class="edit" value="Refactoring Code">
</li>
<li>
<div class="view">
<input class="toggle" type="checkbox">
<label>Rewrite app to react</label>
<button class="destroy"></button>
</div>
<input class="edit" value="Rewrite app to react">
</li>
</ul>
</section>
<!-- This footer should hidden by default and shown when there are todos -->
<footer class="footer">
<!-- This should be `0 items left` by default -->
<span class="todo-count"><strong>0</strong> item left</span>
<!-- Remove this if you don't implement routing -->
<ul class="filters">
<li>
<a class="selected" href="#/all">All</a>
</li>
<li>
<a href="#/active">Active</a>
</li>
<li>
<a href="#/completed">Completed</a>
</li>
</ul>
<!-- Hidden if no completed items are left ↓ -->
<button class="clear-completed">Clear completed</button>
</footer>
</section>
<footer class="info">
<p>Double-click to edit a todo</p>
<p>Enter to add/edit task</p>
</footer>
<!-- Scripts here. Don't remove ↓ -->
<!-- <script src="node_modules/todomvc-common/base.js"></script> --></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:46:54.563",
"Id": "487551",
"Score": "2",
"body": "Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:47:08.857",
"Id": "487552",
"Score": "2",
"body": "To close voters, the code is now in the question"
}
] |
[
{
"body": "<p>You have</p>\n<pre><code>const input = document.getElementsByClassName('new-todo')[0]\n</code></pre>\n<p>When selecting only a single element, it's a bit more appropriate and terser to use <code>querySelector</code> instead:</p>\n<pre><code>const input = document.querySelector('.new-todo');\n</code></pre>\n<p>I notice that sometimes you're using semicolons, and sometimes you're not. Unless you're an expert, I'd recommend using them, else <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">ASI</a> may trip you up, resulting in hard-to-understand bugs. Consider using <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">a linter</a> to enforce your preferred style.</p>\n<p>You have</p>\n<pre><code>var string = input.value;\n// ...\nli.innerHTML = `\n <div class="view">\n <input class="toggle" type="checkbox" />\n <label>${string}</label>\n <button class="destroy"></button>\n </div>\n <input class="edit" value="${string}">\n`;\n</code></pre>\n<p>Don't concatenate HTML strings from user input; if the user accidentally uses characters with HTML syntax, like <code><</code>, this can result in a unexpected appearance and unexpected elements in the DOM. It can also run arbitrary code, which could be a security risk (imagine if another user said: "Try putting this in as a todo input, you won't believe what happens next!" and then the victim gets their login info stolen).</p>\n<p>Instead, once you have a reference to the container of the text, assign to the container's <code>textContent</code>:</p>\n<pre><code>var string = input.value;\n\nif (e.key == 'Enter') {\n const li = document.createElement('li')\n li.innerHTML = `\n <div class="view">\n <input class="toggle" type="checkbox" />\n <label></label>\n <button class="destroy"></button>\n </div>\n <input class="edit" value="${string}">\n `;\n li.querySelector('label').textContent = string;\n</code></pre>\n<p>You have a <code>var</code> there, but you're also using <code>const</code>. If you're going to write in ES2015 with <code>const</code> and <code>let</code>, that's great - but, best to use it everywhere. (If you're writing in ES2015, never use <code>var</code>. <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\">Linting rule</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-30T18:17:36.423",
"Id": "501132",
"Score": "0",
"body": "FYI I cited this answer (and [one of your others](https://codereview.stackexchange.com/a/250206/120114)) [in a comment about not using `var`](https://codereview.stackexchange.com/questions/254048/create-a-simple-hangman-game-using-oop-and-javascript/254050#comment501131_254070)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T15:45:05.030",
"Id": "248824",
"ParentId": "248822",
"Score": "2"
}
},
{
"body": "<h2>User interaction issue</h2>\n<p>There is a flaw with the double-click to edit mechanism - it only works for existing items, but for newly added items, the double click handler is not registered. The same is true for the destroy links.</p>\n<p><a href=\"https://i.stack.imgur.com/cL7Si.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cL7Si.gif\" alt=\"edit not working few new items\" /></a></p>\n<p>Instead of adding a click handler to each list item, event delegation could be used to add a click handler to the list and delegate the editing event to the list item.</p>\n<h2>JS</h2>\n<h3>selecting elements</h3>\n<p>I know CertainPerformance has already touched on the code to select elements. For the selection of list items, event delegation could be achieved by converting these lines:</p>\n<blockquote>\n<pre><code>const todoList = document.getElementsByClassName('todo-list')[0]\nconst items = document.querySelectorAll('.todo-list li')\n</code></pre>\n</blockquote>\n<p>to this:</p>\n<pre><code>const todoList = document.getElementsByClassName('todo-list')[0];\nconst items = todoList.getElementsByTagName('li'); // <- active collection\n</code></pre>\n<p>Note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName\" rel=\"nofollow noreferrer\"><code>getElementsByTagName()</code></a> returns a live <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection\" rel=\"nofollow noreferrer\"><code>HTMLCollection</code></a><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName\" rel=\"nofollow noreferrer\">1</a></sup> so there is no need to re-query the list after items are added or removed... and to iterate over the items, they can be put into an array using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread operator</a>:</p>\n<pre><code>[...items].forEach(...)\n</code></pre>\n<h3>comparison operators</h3>\n<p>It is recommended by many to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\">strict equality</a> when comparing values - that way there is no need to have types converted. For example, in this line in <code>runFilter</code>:</p>\n<blockquote>\n<pre><code>if (href == 'active') {\n</code></pre>\n</blockquote>\n<p><code>href</code> comes from <code>var href = item.getAttribute('href')</code> and that method returns a string or <code>null</code>. Thus there is no need for type coercion.</p>\n<h3>Repeated methods to update element display properties</h3>\n<p>That <code>runFilter</code> function has multiple <code>forEach()</code> loops with arrow functions like this:</p>\n<blockquote>\n<pre><code>item => {\n item.style.display = 'block';\n}\n</code></pre>\n</blockquote>\n<p>The repeated functions could be abstracted to named functions to avoid redundancies.</p>\n<p>Additionally, instead of setting the style, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList\" rel=\"nofollow noreferrer\"><code>classList</code></a> methods like <code>add()</code> and <code>remove()</code> could be used instead - with the CSS class <code>hidden</code>.</p>\n<h2>CSS</h2>\n<h3></h3>\n<p>There is a ruleset for <code>html</code> and <code>body</code>:</p>\n<blockquote>\n<pre><code>html,\nbody {\n margin: 0;\n padding: 0;\n} \n</code></pre>\n</blockquote>\n<p>then later on there is one for <code>body</code>:</p>\n<blockquote>\n<pre><code>body { \n</code></pre>\n</blockquote>\n<p>and it has this:</p>\n<blockquote>\n<pre><code> margin: 0 auto;\n</code></pre>\n</blockquote>\n<p>That seems excessive... one or both of those could be removed.</p>\n<h3>margin syntax</h3>\n<p>The current CSS contains this:</p>\n<blockquote>\n<pre><code>.todoapp {\n background: #fff;\n margin: 130px 0 40px 0;\n</code></pre>\n</blockquote>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/margin#Syntax\" rel=\"nofollow noreferrer\">margin syntax</a> could be converted from <code>/* top | right | bottom | left */</code> to <code>/* top | horizontal | bottom */</code>.</p>\n<pre><code> margin: 130px 0 40px;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T15:54:46.557",
"Id": "248825",
"ParentId": "248822",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248825",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T14:41:44.360",
"Id": "248822",
"Score": "1",
"Tags": [
"javascript",
"css",
"ecmascript-6",
"event-handling",
"to-do-list"
],
"Title": "Javascript to-do application for native Javascript"
}
|
248822
|
<p>I wrote the following script to fill a Triangle.</p>
<pre><code>import pygame
import random
pygame.init()
WIN = pygame.display
D = WIN.set_mode((1200, 600))
p1 = (200, 50)
p2 = (1000, 600)
class Vec2:
def __init__(self, x, y):
self.x = x
self.y = y
def getLine(start, end):
# RETURNS ALL THE PIXELS THAT NEEDS TO BE FILLED TO FORM A LINE
x1, y1 = int(start.x), int(start.y)
x2, y2 = int(end.x), int(end.y)
dx = x2 - x1
dy = y2 - y1
is_steep = abs(dy) > abs(dx)
if is_steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
swapped = False
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
swapped = True
dx = x2 - x1
dy = y2 - y1
error = int(dx / 2.0)
ystep = 1 if y1 < y2 else -1
y = y1
points = []
for x in range(x1, x2 + 1):
coord = Vec2(y, x) if is_steep else Vec2(x, y)
points.append(coord)
error -= abs(dy)
if error < 0:
y += ystep
error += dx
if swapped:
points.reverse()
return points
RED = (255, 0, 0)
BLUE = (0, 105, 255)
GREEN = (0, 255, 0)
def drawLine(p1, p2):
# DRAWS A LINE BY FILLING IN THE PIXELS RETURNED BY getLine
points = getLine(p1, p2)
color = (0, 0, 0)
pixels = len(points)
for i in range(pixels):
# COLOR BLEDNING
r0 = i/pixels* RED[0]
b1 = (abs(pixels-i)/ pixels) * BLUE[1]
b2 = (abs(pixels-i)/ pixels) * BLUE[2]
color = (r0, b1, b2)
D.set_at((points[i].x, points[i].y), color)
# TRIANGLE
v1 = Vec2(500, 500)
v2 = Vec2(100, 100)
v3 = Vec2(1000, 200)
def fillFlatBottom(v1, v2, v3):
# FILL IN TRIANGLE WITH A FLAT BOTTOM
invm1 = (v1.x - v2.x)/(v1.y - v2.y)
invm2 = (v1.x - v3.x)/(v1.y - v3.y)
curx1 = v1.x
curx2 = v1.x
for y in range(int(v1.y), int(v2.y+1)):
drawLine(Vec2(curx1, y), Vec2(curx2, y))
curx1 += invm1
curx2 += invm2
def fillFlatTop(v1, v2, v3):
# FILL IN TRIANGLE WITH A FLAT TOP
invm1 = (v3.x - v2.x)/ (v3.y - v2.y)
invm2 = (v3.x - v1.x)/ (v3.y - v1.y)
curx1 = v3.x
curx2 = v3.x
for y in range(int(v3.y), int(v1.y), -1):
drawLine(Vec2(curx1, y), Vec2(curx2, y))
curx1 -= invm1
curx2 -= invm2
def drawTriangle(v1, v2, v3):
# DRAWS ANY TRIANGLE BY SPLITTING THEM INTO FLAT TOP AND
# FLAT BOTTOM
v = [v1, v2, v3]
for i in range(0, len(v)):
for j in range(i+1, len(v)):
if(v[i].y > v[j].y):
tempy = v[i].y
v[i].y = v[j].y
v[j].y = tempy
tempx = v[i].x
v[i].x = v[j].x
v[j].x = tempx
v1, v2, v3 = v[0], v[1], v[2]
if v1.y == v2.y == v3.y:
drawLine(v1, v2)
elif v2.y == v3.y:
fillFlatBottom(v1, v2, v3)
elif v1.y == v2.y:
fillFlatTop(v1, v2, v3)
else:
v4 = Vec2(v1.x + ((v2.y - v1.y)/ (v3.y - v1.y))* (v3.x - v1.x), v2.y)
fillFlatBottom(v1, v2, v4)
fillFlatTop(v2, v4, v3)
while True:
pygame.event.get()
D.fill((255, 255, 255))
drawTriangle(v1, v2, v3)
WIN.flip()
</code></pre>
<p>It uses bresenham's line algorithm and scan line algorithm to draw lines and fill triangle respectively. My goal is to fill in triangles that make up a 3d mesh. I tried implementing the code shown above to fill in a mesh (made of only 2 triangles). When i tried to rotate the mesh, it causes heavy lag, so it is clearly of no use in rendering bigger models(by bigger models, i mean a cube. That's my goal for now).</p>
<p>I can see a couple of things which might be causing problems. Firstly, in getLine function, it converts the points it receives as arguments from float to int.</p>
<pre><code>x1, y1 = int(start.x), int(start.y)
x2, y2 = int(end.x), int(end.y)
</code></pre>
<p>I read that the whole point of bresenham's algorithm is to avoid this rounding off, but in my case i couldn't avoid it. It is called like this(<code>drawLine</code> calls <code>getLine</code>)</p>
<pre><code>drawLine(Vec2(curx1, y), Vec2(curx2, y))
curx1 += invm1
curx2 += invm2
</code></pre>
<p>invm1 and invm2 are inverse of slopes of 2 sides making up a triangle, which are always floating point numbers. This is passed to <code>getLine</code>, which forced me to convert them to int, otherwise it causes error as <code>for</code> loop in <code>getLine</code> function expects int.</p>
<p>Secondly, in <code>fillFlatBottom</code> and <code>fillFlatTop</code> functions, in <code>for</code> loops for both the functions, the upper and lower bound of <code>range</code> is converted to int because vertices of triangle making a mesh use floating point numbers, which might be avoidable through techniques i might not be aware of.</p>
|
[] |
[
{
"body": "<h1>Avoid storing points unnecessarily</h1>\n<p>The function <code>getLine()</code> creates a list of pixel coordinates, and then <code>drawLine()</code> iterates over it once, drawing each individual pixel, and then discards the list. Consider changing the function <code>getLine()</code> to be a generator instead, so it returns a point at a time. It is quite easy to modify the function to be a generator; instead of adding a coordinate pair to <code>points</code>, <code>yield</code> it instead:</p>\n<pre><code>def getLine(start, end):\n # Setup\n ...\n\n y = y1\n for x in range(x1, x2 + 1):\n yield Vec2(y, x) if is_steep else Vec2(x, y)\n error -= abs(dy)\n if error < 0:\n y += ystep\n error += dx\n</code></pre>\n<p>The are two issues to deal with though. First, you can no longer do <code>points.reverse()</code> inside <code>getLine()</code>, so you have to modify your function a bit to always yield coordinates in the right order. Second, <code>drawLine()</code> wants to get the length of the line in order to interpolate the pixel colors. Either you have to have some function to calculate and return the line length separately, or you can modify <code>getLine()</code> to yield a tuple of both the pixel coordinates and a floating point value between 0 and 1 that <code>drawLine()</code> can use directly for the interpolation. For example:</p>\n<pre><code>yield (Vec2(y, x) if is_steep else Vec2(x, y), x / abs(x2 + x1 + 1))\n</code></pre>\n<p>With this in place, you can change <code>drawLine()</code> as follows:</p>\n<pre><code>def drawLine(p1, p2):\n for point, t in getLine(p1, p2):\n r0 = t * RED[0]\n b1 = (1 - t) * BLUE[1]\n b2 = (1 - t) * BLUE[2]\n color = (r0, b1, b2)\n D.set_at(point, color)\n</code></pre>\n<h1>Drawing filled triangles</h1>\n<p>The idea to split the triangle into two parts is a good one. However, there are some issues. First, you have two functions that basically do exactly the same thing, except with some variables swapped and a sign flipped. I would try to write a single function that handles both a flat bottom and a flat top. If you ever need to modify the algorithm, it's easier to change it in one place than to have to do the same thing in two places.</p>\n<p>But there is another issue: you assume that you can iterate over the y-coordinate, or to put otherwise, that the lines involved are steep. But I can easily create a set of coordinates where none of the lines are steep, for example:</p>\n<pre><code>v1 = Vec2(100, 100)\nv2 = Vec2(500, 200)\nv3 = Vec2(900, 300)\n</code></pre>\n<p>This will result in a dotted line instead of a solid line. Just like Bresenham's algorithm itself, you need to distinguish between steep and non-steep.</p>\n<h1>Use <code>sort()</code></h1>\n<p>You implemented your own bubble-sort algorithm to sort <code>v</code> in <code>drawTriangle()</code>. But Python comes with a sorting function that can take an optional function to tell it what to sort on, so you can replace your own algorithm with:</p>\n<pre><code>v = [v1, v2, v2]\nv.sort(key=lambda p: p.y)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T12:54:34.583",
"Id": "248959",
"ParentId": "248835",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248959",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T20:48:11.127",
"Id": "248835",
"Score": "5",
"Tags": [
"python",
"performance",
"algorithm",
"mathematics",
"pygame"
],
"Title": "Scan-line algorithm to fill in a triangle"
}
|
248835
|
<p>This is exercise 3.1.4. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<p>Write a program that takes the name of a grayscale image file as a command-line argument and uses StdDraw to plot a histogram of the frequency of occurrence of each of the 256 grayscale intensities.</p>
<p>Here is my program:</p>
<pre><code>import java.awt.Color;
public class ImageToHistogram
{
public static double getIntensity(Color color) // this method produces monochrome luminance
{
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
return 0.299*r + 0.587*g + 0.114*b;
}
public static double[][] convertPictureToArray(Picture picture)
{
int width = picture.width();
int height = picture.height();
double[][] pixels = new double[width][height];
for (int col = 0; col < width; col++)
{
for (int row = 0; row < height; row++)
{
Color color = picture.get(col,row);
pixels[col][row] = getIntensity(color);
}
}
return pixels;
}
public static void drawHistogram(double[][] a)
{
int m = a.length;
int n = a[0].length;
int pixels = m*n;
int[] histogram = new int[256];
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
int intensity = (int) a[i][j];
histogram[intensity]++;
}
}
StdDraw.setXscale(0,256);
StdDraw.setYscale(0,pixels/20); // obtained "20" by experimentation
StdDraw.enableDoubleBuffering();
for (int i = 0; i < 256; i++)
{
StdDraw.filledRectangle(i+0.5,histogram[i]/2,0.5,histogram[i]/2);
}
StdDraw.show();
}
public static void main(String[] args)
{
Picture picture = new Picture(args[0]);
double[][] a = convertPictureToArray(picture);
drawHistogram(a);
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> and <a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/Picture.html" rel="nofollow noreferrer">Picture</a> are simple APIs written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input (Grayscale picture of Coleen Gray taken from <a href="https://en.wikipedia.org/wiki/Coleen_Gray#/media/File:Coleen_Gray_in_Kansas_City_Confidential.jpg" rel="nofollow noreferrer">Wikipedia</a>):</p>
<p><a href="https://i.stack.imgur.com/xSvSM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xSvSM.jpg" alt="enter image description here" /></a></p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/Lz2SS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lz2SS.png" alt="enter image description here" /></a></p>
<p>I also tested the extreme cases of pure black and pure white images.</p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
<p><strong>Clarification:</strong></p>
<p>I used the preview of the image provided by Wikipedia with resolution of 800 by 933 and not the original image with resolution of 2000 by 2333.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:34:02.053",
"Id": "487648",
"Score": "2",
"body": "The histogram doesn't look correct. Did you crop it and only show the left (=dark) part? There's no bright highlight in the picture, so the histogram should be completely flat on the right part. Also, the left part of the histogram should be smoother, without those discrete peaks with large spaces in between. You can use dcode.fr/image-histogram for comparison. Here's the histogram in Photoshop : https://i.imgur.com/VI3PrcO.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:50:47.057",
"Id": "487651",
"Score": "0",
"body": "@EricDuminil I figured it out. You used the original picture with resolution 2000 by 2333 but I used the preview with resolution 800 by 933."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:53:16.063",
"Id": "487653",
"Score": "0",
"body": "This is the histogram when I use the 2000 by 2333 image: https://imgur.com/986pdcK"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:57:48.753",
"Id": "487654",
"Score": "1",
"body": "Thanks for the answer. This histogram looks much better indeed. I also used the 800x933 in Photoshop, though. Resizing an image shouldn't change the overall shape of the histogram, so there must be another explanation. Are you sure the above histogram is for the shown picture?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:04:54.663",
"Id": "487657",
"Score": "0",
"body": "@EricDuminil Yes. I think the discrete look (discrete peaks and none valleys) of my histogram is because of the fact that I have used integers in my program and it could be that PS uses real (double) values. So the overall outlook of the histogram generated by PS seems finer (PS used finer intervals). What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:10:26.053",
"Id": "487660",
"Score": "1",
"body": "I don't think so. With integers, you should still have 256 distinct values, so the large valleys cannot be explained by double -> int . And the overall shape should still be similar to https://imgur.com/986pdcK . There's a problem, I just don't know where."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:18:32.227",
"Id": "487662",
"Score": "0",
"body": "Consider this. Suppose one bar of the histogram represents 100 values for all the intensities between 22 and 23. Now if we refine the interval to two intervals (22-22.5 and 22.5-23) our one bar of 100 could turn into two bars one with 42 values and another with 58 values for example and this produces less peaks and zero valleys. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:52:48.130",
"Id": "487667",
"Score": "1",
"body": "Yes, some small variations would appear. But not huge peaks with 8 empty values in between, and the global shape wouldn't change much. I don't know how else to tell you : the above histogram is not correct for the above portrait. Here are the histogram values I get with Python and the 800x933 portrait : https://pastebin.com/raw/FErFeY2G. For reference : `np.histogram(plt.imread('ColeenGray.jpg').ravel(), bins=256, range=(0, 256))[0]` Every shade of grey between 0 and 238 is present at least once, so there shouldn't be any valley in the histogram, only empty values on the right part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:13:29.920",
"Id": "487670",
"Score": "0",
"body": "@EricDuminil I refined each interval by a factor of 10 and here is the result: https://imgur.com/pl9FrGc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:32:03.040",
"Id": "487675",
"Score": "0",
"body": "This looks better. I tried to replicate your code on my system, I still got weird gaps. As far as I can tell, `ImageIO.read(file);` doesn't work fine with the above JPG. If you convert it to png, you get the expected histogram. Could you please try with https://i.imgur.com/TX1Nssa.png ? It's the exact same image, just encoded in PNG."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:41:14.490",
"Id": "487679",
"Score": "0",
"body": "@EricDuminil I did. Still the same result unfortunately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T15:08:26.717",
"Id": "487680",
"Score": "0",
"body": "Okay. I also found a small bug in your code, and wrote the corresponding answer. I'll delete my comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T15:17:50.237",
"Id": "487681",
"Score": "0",
"body": "One last try. Could you please test it with https://download.ericduminil.com/ColeenGray.jpg ? I think the imgur version is too compressed, or uses a compression algorithm which isn't supported by ImageIO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T18:16:57.947",
"Id": "487695",
"Score": "2",
"body": "https://bugs.openjdk.java.net/browse/JDK-5051418 ; https://stackoverflow.com/questions/31312645/java-imageio-grayscale-png-issue ; https://stackoverflow.com/questions/32583772/reading-grayscale-png-image-files-without-distortion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T22:18:30.240",
"Id": "487716",
"Score": "0",
"body": "@Nayuki thanks. Is that a bug or a feature?"
}
] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>In your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>StdDraw.filledRectangle(i + 0.5, histogram[i] / 2, 0.5, histogram[i] / 2);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int half = histogram[i] / 2;\nStdDraw.filledRectangle(i + 0.5, half, 0.5, half);\n</code></pre>\n<h2>Replace the <code>for</code> loop with an enhanced 'for' loop</h2>\n<p>In your code, you don’t actually need the index provided by the loop, you can the enhanced version.</p>\n<h3>ImageToHistogram#drawHistogram</h3>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int intensity = (int) a[i][j];\n histogram[intensity]++;\n }\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (double[] currentRow : a) {\n for (int j = 0; j < n; j++) {\n int intensity = (int) currentRow[j];\n histogram[intensity]++;\n }\n}\n</code></pre>\n<p>For the rest it looks good!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T01:58:17.163",
"Id": "248838",
"ParentId": "248836",
"Score": "4"
}
},
{
"body": "<p>I myself found another way to improve my code.</p>\n<h2>Obtain the maximum for the y-coordinate of the histogram</h2>\n<p>I need to obtain the maximum for the y-coordinate of the histogram to avoid experimentation for each instance of the program.</p>\n<p><strong>Before:</strong></p>\n<pre><code> StdDraw.setXscale(0,256);\n StdDraw.setYscale(0,pixels/20); // obtained "20" by experimentation\n</code></pre>\n<p><strong>After:</strong></p>\n<pre><code> int max = 0;\n for (int i = 0; i < 256; i++)\n {\n max = Math.max(max,histogram[i]);\n }\n StdDraw.setXscale(0,256);\n StdDraw.setYscale(0,max);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:50:30.550",
"Id": "248849",
"ParentId": "248836",
"Score": "2"
}
},
{
"body": "<p>Your review scope is extremely broad. I'm concentrating on the the code being completely procedural in a language that is object oriented.</p>\n<p>The operation you perform on each pixel is independent of each other, so you should implement this as a series of operations performed on a stream of pixels.</p>\n<ol>\n<li>Write a <a href=\"https://www.baeldung.com/java-spliterator\" rel=\"nofollow noreferrer\">Spliterator</a> that allows you to process the RGB pixels of the <code>Picture</code> as a Java 8 <code>IntStream</code> (BTW, it's more common and convenient to process image data as simpe one dimensional array/stream of pixels where image rows follow each other instead of using an array of rows).</li>\n<li>Write a <code>IntUnaryOperator</code> that maps an RGB pixel into a intensity value and pass this to <code>IntStream.map(IntUnaryOperator)</code>.</li>\n<li>Write a <code>Collector</code> that generates a <a href=\"https://gist.github.com/hoffrocket/7558352\" rel=\"nofollow noreferrer\">histogram</a> from a stream of integers.</li>\n<li>Write a method that shows a histogram, when given a <code>Map<Integer, Integer></code>. This needs to go through the map to find the smallest and largest key as well as the largest value so you can scale the X and Y axis. You may be tempted to optimize this step to the ones above, but we're talking about a map with 255 entries. The code mess is not worth the performance gain.</li>\n</ol>\n<p>When you put each step into an independent class that is not unnecessarily dependent on the domain of image processing, you make maintenance and unit testing much easier. Now you could take the histogram collector to any program and use it, for example, to generate a histogram on student grades for a programming test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T11:46:13.227",
"Id": "487643",
"Score": "0",
"body": "I truly appreciate your answer but I still don't know OOP. When I learn it, I will certainly come back to this answer to enhance my understanding. Thank you very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T11:01:24.123",
"Id": "248858",
"ParentId": "248836",
"Score": "3"
}
},
{
"body": "<h1>JPG vs PNG</h1>\n<p>Somehow, your code seems to produce wrong results with the above JPG. When used with the same image converted to PNG, the histogram looks much better, and much closer to what Photoshop displays.</p>\n<p><code>ImageIO.read(file)</code> seems to not return the correct RGB values with the above JPG. It is outside of your code though, and seems to be called by <code>Picture</code> class.</p>\n<p>As mentioned by @Nayuki, it seems to be a known bug/feature:</p>\n<ul>\n<li><a href=\"https://bugs.openjdk.java.net/browse/JDK-5051418\" rel=\"nofollow noreferrer\">https://bugs.openjdk.java.net/browse/JDK-5051418</a></li>\n<li><a href=\"https://stackoverflow.com/questions/31312645/java-imageio-grayscale-png-issue\">https://stackoverflow.com/questions/31312645/java-imageio-grayscale-png-issue</a></li>\n<li><a href=\"https://stackoverflow.com/questions/32583772/reading-grayscale-png-image-files-without-distortion\">https://stackoverflow.com/questions/32583772/reading-grayscale-png-image-files-without-distortion</a></li>\n</ul>\n<h1>Double -> int</h1>\n<p><code>getIntensity</code> returns a double.</p>\n<p>For example, <code>getIntensity(new Color(1, 1, 1))</code> returns <code>0.9999999999999999</code>, which is very close to <code>1.0</code> but strictly smaller than <code>1.0</code>.</p>\n<p>When you cast this double to an integer in <code>int intensity = (int) a[i][j]</code>, it gets converted to <code>0</code>, which isn't desired.</p>\n<p>With your current code, the first histogram bins look like this:</p>\n<pre><code>[37509, 2429, 0, 3981, 0, 1763, 1757, 4131, 0, 2016, 4718, 0, 6498, 0, 3526, 7824, ...\n</code></pre>\n<p>If you replace the line with <code>int intensity = (int) Math.round(a[i][j]);</code>, the first bins look like this:</p>\n<pre><code>[32317, 5192, 2429, 2327, 1654, 1763, 1757, 2034, 2097, 2016, 2230, 2488, 2947, 3551, 3526, 3683, 4141, ...\n</code></pre>\n<p>Which should produce a smoother and more correct diagram.</p>\n<p>As mentioned by @MarkRansom:</p>\n<blockquote>\n<p>the goal should be to redistribute the values in a way that preserves\ntheir overall distribution.</p>\n</blockquote>\n<p>Rounding the doubles should work fine in the above case, because the values are very close to integers. In the general case, truncating might be preferred.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T15:38:48.477",
"Id": "487684",
"Score": "2",
"body": "I can't thank you enough. I appreciate all the time that you put into solving this problem. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T17:38:31.863",
"Id": "487691",
"Score": "2",
"body": "@KhashayarBaghizadeh: My pleasure. It's always funny to play detective. Thanks for staying with me and trying to understand what the problem was."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T22:11:57.810",
"Id": "487714",
"Score": "0",
"body": "`round` is rarely how you want to convert from floating to integer, because it results in an uneven distribution unless all the values are extremely close to integers already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T22:17:31.993",
"Id": "487715",
"Score": "0",
"body": "@MarkRansom interesting. Why should the distribution be uneven? What is the alternative you propose? In the above case, with a grayscale image, the values are basically integers +- epsilon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T23:20:08.043",
"Id": "487717",
"Score": "1",
"body": "Suppose your values were evenly distributed between 0.0 and 0.999999 and you wanted to convert them into integers 0-100: `v2 = round(v1*100)`. 0 will result from an input of 0.0-0.005, while 1 will result from 0.005 to 0.015 - you're twice as likely to get 1 than 0. Use `v2 = trunc(v1*101)` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T08:47:10.277",
"Id": "487736",
"Score": "0",
"body": "@MarkRansom: Thanks for the explanation, it makes sense. It does shift all the data half a bin to the left, but I guess there's no perfect solution. What should be done if 1.0 is reachable (e.g. for a completely white pixel)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T14:32:27.107",
"Id": "487752",
"Score": "0",
"body": "The difference between endpoints included and endpoints excluded in the floating point scale is nearly unmeasurable. Just do as I said above with `trunc`, and add some logic to make sure the one-in-a-billion out of bounds value is brought back into range. `v2 = min(trunc(v1*101),100)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:04:37.030",
"Id": "487755",
"Score": "0",
"body": "@MarkRansom \"just do as I said\". Well, no. It depends on the distribution. If the values are really random floats, 1.0 might indeed never happen. But I'm not satisfied with a method which treats \"pure white\" as an annoying edge case, even though it will be the most frequent value in the histogram of many png images. As you said, rounding should be fine in the above case, when the doubles are always very close to an integer value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:27:04.983",
"Id": "487758",
"Score": "0",
"body": "As I said, the goal should be to redistribute the values in a way that preserves their overall distribution. Using my previous example, the values from 0.99 to 1.0 should all map to 100 so that 100 isn't underrepresented compared to 99."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T16:15:20.173",
"Id": "487770",
"Score": "0",
"body": "@MarkRansom: I've updated the answer. Does it fit your point of view?"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T15:01:49.053",
"Id": "248872",
"ParentId": "248836",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248872",
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T22:21:20.393",
"Id": "248836",
"Score": "6",
"Tags": [
"java",
"beginner"
],
"Title": "Turning a grayscale image into a histogram of the intensity of the pixels of that image"
}
|
248836
|
<p>I'm learning modern C++ and also algorithms, and am doing some practice by coding up some simple algorithms. Also trying to use templates whenever possible as I'm quite unfamiliar with generic programming.</p>
<p>Would like some help in reviewing the code in terms of design, efficiency, conciseness, and style.
Please do not hold back and rip my code apart. It's the best way for me to learn :) thank you!
I'm using MSVC, C++17.</p>
<pre><code>// version for contaners with random access
// move minima to correct position (sweep from right to left)
template<typename T>
void bubbleRandCppStl(T& container) {
for (auto i{ container.rend() - 1 }; i != container.rbegin(); --i) {
bool swapped {}; // flag to store if swap occured in sweep
for (auto j{ container.rbegin() }; j != i; ++j) {
if (*j < *(j + 1)) {
std::iter_swap(j, j + 1);
swapped = true;
}
}
if (!swapped) { // end early if no swap occurred in sweep
break;
}
}
}
// version for lists (std::list and std::forward_list)
// move maxima to correct position (sweep from left to right, because forward iterator is unidirectional)
template<typename T>
void bubbleListCppStl(T& container) {
// container.size() takes O(n) time, so we just do a full sweep
// and get the size at the same time
typename T::size_type sz{};
bool swapped{}; // flag to store if swap occured in sweep
for (auto i{ container.begin() }, after_i{ ++container.begin() };
after_i != container.end(); ++i, ++after_i) {
++sz;
if (*i > * after_i) {
std::iter_swap(i, after_i);
swapped = true;
}
}
if (!swapped) { // end early if no swap occurred in sweep
return;
}
// decrement size as we now need to sort only sz - 1 elements
--sz;
// sort the remaining elements
for (; sz > 1; --sz) {
auto i{ container.begin() };
for (auto elem_left{ sz }; elem_left > 1; --elem_left, ++i) {
if (*i > * (std::next(i))) {
std::iter_swap(i, std::next(i));
swapped = true;
}
}
if (!swapped) { // end early if no swap occurred in sweep
break;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T17:55:27.510",
"Id": "487782",
"Score": "1",
"body": "Not sure why you need different algorithms for this. Don't quite understand why the random access iterator version is more efficient."
}
] |
[
{
"body": "<p>Welcome to Code Review. Here's some suggestions:</p>\n<ul>\n<li><p>Instead of taking a container as argument, take a pair of iterators\nfor flexibility.</p>\n</li>\n<li><p>Provide one function that uses <code>iterator_category</code> to find the\ncorrect version.</p>\n</li>\n<li><p>Allow the user to specify a custom comparator.</p>\n</li>\n<li><p>Personally, I'd say that <code>bool swapped{false};</code> is clearer than\n<code>bool swapped{}</code>.</p>\n</li>\n<li><p>Constantly swapping seems less efficient than moving.</p>\n</li>\n<li><p>Are you sure you need reverse iterators here? Just traversing from\nleft to right seems fine.</p>\n</li>\n<li><p>Calculating <code>std::next(i)</code> twice doesn't feel efficient.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T03:54:08.673",
"Id": "248841",
"ParentId": "248840",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248841",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T03:16:29.707",
"Id": "248840",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"sorting",
"generics",
"c++17"
],
"Title": "Bubble Sort In C++"
}
|
248840
|
<p>I have this short function, it converts a human selected name like "Accelerometer" to "Acc" which a sensor can use:</p>
<pre><code>private final String[] sensorNames = {"Acc", "Gyro", "Magn", "IMU9", "Temp"};
/**
* Converts human representation of sensor names to movesense names. TODO: better code
* @param sensorType Human representation of sensor name.
* @return Short name of the sensor.
*/
private String findShortSensorName(String sensorType) {
for (int i = 0; i < sensorNames.length; i++) {
if (sensorType.substring(0,1).equals(sensorNames[i].substring(0,1))) {
return sensorNames[i];
}
}
return "";
}
</code></pre>
<p>Is there a way to make this more efficient or use less code? The <code>return "";</code> is also bugging me. Thanks for your input!</p>
|
[] |
[
{
"body": "<p>It's hard to comment really well on this as your problem specification is more than a little vague.\nDo you really want to do this based only on the first letter - is "AbominableSnowman" to be mapped to "Acc"?\nOr do you know that the input sensor types are drawn from a specific set of values?</p>\n<p>You could make your <em>method</em> (Java doesn't have functions) more succint, for example like this</p>\n<pre><code>private String findShortSensorName(String sensorType) {\n for (String sensorName : sensorNames) {\n if (sensorName.startsWith(sensorType.substring(0,1))) {\n return sensorName;\n }\n }\n return "";\n}\n</code></pre>\n<p>However, the idiomatic approach for lookup in Java is usually to use a Map, and I'd have thought that if the value isn't found, throwing an Exception may be more appropriate than returning an empty string, though that will depend on your application. As your method doesn't look tied to a particular Java object, it can probably be "static", as well.</p>\n<p>My version isn't shorter (it's considerably longer), but it's idiomatic (in my view) and easier to safely extend.</p>\n<pre><code>class BadSensorTypeException extends Exception {\n// Thrown when a sensor type isn't found in the lookup table\n\n public BadSensorTypeException(String detailMessage) {\n super(detailMessage);\n }\n }\n\n/**\n * lookup table mapping sensor types to short movesense names\n */\nprivate static final Map<String, String> sensorNames = new HashMap<>();\nstatic {\n// static block to initialise the lookup table\n sensorNames.put("Accelerometr", "Acc");\n sensorNames.put("Gyroscope", "Gyro");\n // etc\n}\n\n/**\n * Converts human representation of sensor names to movesense names.\n * @param sensorType Human representation of sensor name.\n * @return Short name of the sensor.\n * @throws BadSensorTypeException if the sensor type isn't found\n */\nprivate static String findShortSensorName(String sensorType) throws BadSensorTypeException {\n String shortName = sensorNames.get(sensorType);\n if (shortName != null) {\n return shortName;\n }\n throw new BadSensorTypeException(String.format("%s is not a valid sensor type", sensorType));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:17:09.783",
"Id": "248854",
"ParentId": "248844",
"Score": "3"
}
},
{
"body": "<p>If memory is not a constraint here you can create a lookup data structure for example HashMap(key-value data structure) or HashSet.</p>\n<p>Once the HashMap/HashSet is populated with the sensor names then after that all your queries will be done in O(1).</p>\n<p>considering private final String[] sensorNames = {"Acc", "Gyro", "Magn", "IMU9", "Temp"}; is given or can be read from properties file we can populate a HashMap like below</p>\n<pre><code>class Sensor {\n\n private Map<String, String> map;\n\n public Sensor() {\n map = new HashMap();\n }\n\n public void populateSensorNames(String[] sensorNames) {\n for(String str : sensorNames)\n map.put(str.substring(0, 1), str);\n }\n\n public String findShortSensorName(String sensorType) {\n return map.getOrDefault(sensorType.substring(0, 1), "");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:59:32.723",
"Id": "487734",
"Score": "0",
"body": "I'd be interested to see your suggested solution using a Set.\nI'm also worried about what happens if the input list of sensorNames is changed to add an entry with the same initial letter as an existing one, which is why my solution does a full string lookup."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T11:49:15.710",
"Id": "487741",
"Score": "0",
"body": "I have used HashMap because I wanted to map start char with the sensor string, with set I can not do that.\nAnd I took this approach of checking against the start character because I saw this same comparison in the question, I thought the author wants to reduce the time complexity here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:33:10.423",
"Id": "248867",
"ParentId": "248844",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T07:59:27.107",
"Id": "248844",
"Score": "1",
"Tags": [
"java",
"array"
],
"Title": "Shortening code for string substitution"
}
|
248844
|
<p>I recently interviewed for a backend developer role at a startup involved in financial products, as a 2020 grad. The take-home assignment they had me submit had a few basic goals and they recommended the Nodejs/MongoDB stack. I received the following feedback on my submission:</p>
<p><em>1. Visibility of REST architecture is less.</em></p>
<p><em>2. Code structuring could have been better (I agree with this).</em></p>
<p><em><strong>3. If the language chosen is Nodejs, at least the basic syntax usage should be correct. The opposite was observed.</strong></em></p>
<p>My questions about this feedback are:</p>
<p><em>1. Isn't the structure of a REST API highly subjective? How can I make my application more compliant with REST goals?</em></p>
<p><em>2. What is "incorrect syntax usage?" If my syntax were incorrect, the project would misbehave or not work, wouldn't it?</em> I posted this question on the <em>r/codereview</em> subreddit, and got little useful feedback apart from one comment saying "spaghetti." I'd love it if you could give me pointers on how to improve my code.</p>
<p>I'd love to learn from this exercise and am open to all feedback/criticism. My code resides at <a href="https://github.com/utkarshpant/portfolio-api" rel="nofollow noreferrer">github.com/utkarshpant/portfolio-api</a> along with the documentation. I tested the application using Postman and as an exercise, I am writing unit/integration tests for it.</p>
<p>I'm reproducing below a portion of the <code>routes/portfolio_v2.js</code> file, where I have implemented the majority of the endpoints:</p>
<pre><code>const dbDebugger = require('debug')('app:db');
const apiDebugger = require('debug')('app:api');
const express = require('express');
const router = express.Router();
const Joi = require('joi');
const customError = require('http-errors');
const errorHandlerMiddleware = require('../middleware/errorHandlerMiddleware');
// importing models;
const Portfolio = require('../models/portfolioModel');
// import validations;
const validations = require('../validations/validateRequest');
// get returns on portfolio
router.get('/getReturns/:portfolioName', errorHandlerMiddleware((req, res) => {
const portfolioName = req.params.portfolioName;
(async () => {
const portfolio = await Portfolio.findOne({ "name": portfolioName }).catch(err => res.send(error));
if (!portfolio) {
return res.status(404).send("No portfolio found");
}
const currentPrice = 100;
let returns = 0;
portfolio.securities.forEach(security => {
apiDebugger(`The returns on ${security.ticker} are ${((currentPrice - security.avgBuyPrice) * security.shares)}`);
returns += ((currentPrice - security.avgBuyPrice) * security.shares)
})
console.log("Returns:\t", returns);
res.send({
portfolio: portfolio.name,
cumulativeReturns: returns
});
})();
}));
// place a buy trade
router.post('/buy/:portfolioName', errorHandlerMiddleware((req, res) => {
/*
Request body includes:
Trade object, including ticker, type, quantity, price
TODO:
- validations for
- ticker match
- trade type == sell,
- shares - quantity > 0 always
- resultant shares > 0 always
*/
// validating request body;
const { error } = validations.validateTradeRequest(req);
if (error) {
throw customError(400, "Bad Request; re-check the request body.");
} else {
// mismatch of type;
if (req.body.type != "buy") {
throw customError(400, "Bad request; type must be 'buy'.")
}
const portfolioName = req.params.portfolioName;
const trade = req.body;
(async () => {
// retrieve portfolio and find relevant security;
const portfolio = await Portfolio.findOne({ "name": portfolioName }).catch(err => res.send(err));
if (!portfolio) {
return res.status(404).send("No portfolio found");
}
const security = portfolio.securities.find(security => security.ticker == trade.ticker);
// if the ticker does not exist, return a 404;
if (!security) {
return res.status(404).send("Invalid ticker.");
}
// register sell trade and update shares;
security.trades.push(trade);
let oldShares = security.shares;
security.shares += trade.quantity;
security.avgBuyPrice = (((security.avgBuyPrice) * (oldShares)) + ((trade.price) * (trade.quantity))) / (security.shares);
apiDebugger(`(security.avgBuyPrice): ${security.avgBuyPrice},\nsecurity.shares: ${security.shares},\ntrade.price: ${trade.price},\ntrade.quantity: ${trade.quantity}\n`);
// save portfolio
try {
await portfolio.save().then(res.status(200).send(trade));
} catch (err) {
let errorMessages = [];
ex.errors.forEach(property => errorMessages.push(property));
res.status(500).send("An error occured in saving the transaction.")
}
})();
}
}));
// place a sell trade
router.post('/sell/:portfolioName', errorHandlerMiddleware((req, res) => {
/*
Request body includes:
Trade object, including ticker, type, quantity
TODO:
- validations for
- ticker match
- trade type == sell,
- shares - quantity > 0 always
- resultant shares > 0 always
*/
// validating request body;
const { error } = validations.validateTradeRequest(req);
if (error) {
throw customError(400, "Bad Request; re-check the request body.");
} else {
if (req.body.type != "sell") {
throw customError(400, "Bad Request; type must be 'sell'.");
}
const portfolioName = req.params.portfolioName;
const trade = req.body;
(async () => {
// retrieve portfolio and find relevant security;
const portfolio = await Portfolio.findOne({ "name": portfolioName }).catch(err => res.send(err));
if (!portfolio) {
return res.status(404).send("No portfolio found");
}
const security = await portfolio.securities.find(security => security.ticker == trade.ticker);
// check that resultant share count > 0;
if ((security.shares - trade.quantity) < 0) {
// throw customError(422, `The given Trade will result in ${security.shares - trade.quantity} shares and cannot be processed.`);
return res.status(422).send(`Request cannot be serviced. Results in (${security.shares - trade.quantity}) shares.`);
}
// register sell trade and update shares;
security.trades.push({ "ticker": trade.ticker, "type": "sell", quantity: trade.quantity });
security.shares -= trade.quantity;
// save portfolio
try {
await portfolio.save().then(res.status(200).send(trade)).catch();
} catch (err) {
let errorMessages = [];
ex.errors.forEach(property => errorMessages.push(property));
res.status(500).send("An error occured in saving the transaction.")
}
})();
}
}));
function validateRequest(request) {
const tradeRequestSchema = Joi.object({
ticker: Joi.string().required().trim(),
type: Joi.string().required().valid("buy", "sell").trim(),
quantity: Joi.number().required().min(1).positive(),
price: Joi.number().min(1).positive()
})
return tradeRequestSchema.validate(request.body);
}
module.exports = router;
</code></pre>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>From a medium review;</p>\n<ul>\n<li><p>The exception handling definitely raises eyebrows</p>\n<ul>\n<li><p><code>ex</code> is not defined, so <code>ex.errors.forEach(property => errorMessages.push(property));</code>\nwill fail</p>\n</li>\n<li><p><code>errorMessages</code> is a mystery, you don't seem to do anything with it?</p>\n</li>\n<li><p>This</p>\n<pre><code> let errorMessages = [];\n ex.errors.forEach(property => errorMessages.push(property));\n</code></pre>\n<p>should be</p>\n<pre><code> const errorMessages = err.errors;\n</code></pre>\n</li>\n<li><p>Similarly, <code>.catch(err => res.send(error));</code> is not going to work</p>\n</li>\n</ul>\n</li>\n<li><p>Use a hint tool like <a href=\"https://jshint.com/\" rel=\"nofollow noreferrer\">https://jshint.com/</a></p>\n</li>\n<li><p><code>async () => </code> creates an anymous function, you should use named functions for stack trace reasons</p>\n</li>\n<li><p>Wrap <code>console.log</code> in some kind of verbosity level filtering function, never write to <code>console.log</code> directly</p>\n</li>\n<li><p>The calculation of <code>returns</code> would be perfect to show off <code>reduce()</code></p>\n</li>\n<li><p>The big comment of <code>router.post('/buy/:portfolioName'</code> should be above the function</p>\n</li>\n<li><p>To me <code>:portfolioName/buy</code> is much more REST like than <code>'/buy/:portfolioName'</code>, I look at the big players and they tend to go much more for noun/verb then verb/noun</p>\n</li>\n<li><p>If I were to log errors for a trading app, I would</p>\n<ol>\n<li>Create for each error a GUID, and dump that GUID in to server logs</li>\n<li>Als provide that GUID in the 500 message, <code>"An error occured in saving the transaction."</code> is so devoid of information, it could get you fired</li>\n</ol>\n</li>\n<li><p>When I see this;</p>\n<pre><code> if (error) {\n throw customError(400, "Bad Request; re-check the request body.");\n } else {\n</code></pre>\n<ul>\n<li>I cringe, why do you <code>else</code> after a <code>throw</code> ?</li>\n<li>why do you not do <code>else</code> after the next <code>throw</code> ?</li>\n</ul>\n</li>\n<li><p>Was it their design to check for <code>type</code> even if the type is part of the URL? That's just bad design</p>\n</li>\n<li><p>You should have wrapped <code>validateTradeRequest</code> in a function that</p>\n<ol>\n<li>Calls <code>validateTradeRequest</code></li>\n<li>Checks the type</li>\n<li>Checks the portfolio type</li>\n<li>Throws an error if anything else goes wrong</li>\n<li>Re-used this function in both <code>sell</code> and <code>buy</code></li>\n</ol>\n</li>\n<li><p><code>return res.status(404).send("Invalid ticker.");</code> is an unfortunate choice of http error code and message. REST wise, 404 means that the portfolio does not exist, but it does exist. Message wise, imagine if the message said <code>No security found for ticker ${trade.ticket} in portfolio ${portfolioName}</code></p>\n</li>\n<li><p>One time you use <code>portfolio.securities.find</code> and the other time <code>await portfolio.securities.find</code>?? I stopped reviewing in depth here..</p>\n</li>\n<li><p>As for visibility, I agree with the reviewer, imagine that your code started with</p>\n<pre><code> router.get( '/:portfolio/getReturns', getPortfolioReturns);\n router.post('/:portfolio/buy', postPortfolioBuy);\n router.post('/:portfolio/sell', postPortfolioSell);\n</code></pre>\n<p>the reader would know in 1 split second what this code does (possibly be annoyed by that one space to align the <code>get</code> with the <code>post</code> ;)) Now the reader has to slog through lines and lines of code to figure this out.</p>\n</li>\n<li><p>For the syntax part, your use of <code>async</code> triggers my spidey sense, but every time I think I found something I am wrong. Either the reviewer is really smart, or wants to appear really smart</p>\n</li>\n</ul>\n<p>All in all, and I rarely say this, this should have had tests. More specifically this should have had tests for failures, and you would have found and fixed a lot of these problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:07:54.377",
"Id": "487659",
"Score": "0",
"body": "Thank you for the review, @konijn. This exercise, I will admit, an effort to write Javascript after a very long time (it isn't my daily driver), and did make me feel like it wasn't the most elegantly put together. However, I do the issues you have raised and plan to better them by practicing on this project! Accepting your answer because even the medium review was of terrific help.\n\nOne last bit of help. Could you briefly explain why the `.catch(err => res.send(error));` snippet won't work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:25:11.397",
"Id": "487673",
"Score": "0",
"body": "Edit - nevermind, the last bit is glaringly obvious."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:53:05.930",
"Id": "248865",
"ParentId": "248845",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:04:19.730",
"Id": "248845",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"rest",
"mongodb",
"mongoose"
],
"Title": "Is this nodejs web-application spaghetti code?"
}
|
248845
|
<p><strong>Goal:</strong></p>
<p>Currently creating an application using <code>Node JS</code> and <code>Handlebars</code>.</p>
<p>I have a to do list set up in <code>Handlebars</code>, when clicked on <code>Start today's report</code>, it shows up the to do list:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<section id="daily-reports">
<div class="container">
<div class="jumbotron">
<h1 class="display-4">Daily Reports</h1>
<p class="lead">View completed reports or start daily reports.</p>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#dailyModal">
Start today's report
</button>
<button type="button" class="btn btn-primary">
View Data
</button>
</div>
</div>
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="dailyModal" tabindex="-1" role="dialog" aria-labelledby="dailyModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="dailyModalLabel">To do</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<a id="tempBtn" href="/temp-check">Temperature</a>
</div>
<div class="col">
<input id="temp" type="checkbox" name="" value="" disabled {{temp}}>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script></code></pre>
</div>
</div>
</p>
<p>Here is the Node JS server side to determine whether to <code>check</code> or <code>un-check</code> the checkbox</p>
<pre><code>const express = require('express');
const router = express.Router();
const db = require('../controllers/db').db;
router.get('/', (req, res) => {
db.query("SELECT DATEDIFF(time, curdate()) as lastChecked FROM tempcheck ORDER BY id DESC LIMIT 1;",(error, result) => {
console.log(result[0].lastChecked);
if(result[0].lastChecked == 0){
res.render('home/index', {temp: 'checked'});
}
else{
res.render('home/index', {temp: ''});
}
});
});
module.exports = router;
</code></pre>
<p>This will affect this handlebars line:</p>
<pre><code><input id="temp" type="checkbox" name="" value="" disabled {{temp}}>
</code></pre>
<p>Next, I have added Javascript script bottom of handlebars, to do the following:</p>
<ul>
<li>If <code>checkbox</code> is <code>checked</code> then prompt with a message <code>"You have already completed this check, do you want to do it again?"</code>. Like so...</li>
</ul>
<p><a href="https://i.stack.imgur.com/ZLyYY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZLyYY.png" alt="enter image description here" /></a></p>
<p>If clicked <code>Ok</code> then continue to form, If clicked <code>Cancel</code> then stop rendering the form.</p>
<p>Here is the Javascript code bottom of handlebars:</p>
<pre><code>...
<script type="text/javascript">
if(document.getElementById('temp').checked == true){
document.getElementById('tempBtn').addEventListener('click', function(e){
if(confirm("You have already completed this check, do you want to do it again?")){
}
else{
e.preventDefault();
}
});
}
</script>
</code></pre>
<p><strong>Summary</strong></p>
<p>I'd like to hear some reviews to my current logic, structure and my coding.</p>
<p>Would like to see where I can improve :)</p>
|
[] |
[
{
"body": "<p>There is:</p>\n<pre><code>const db = require('../controllers/db').db;\n</code></pre>\n<p>When the variable name to assign a property to is the same as the property, you can destructure if you wish:</p>\n<pre><code>const { db } = require('../controllers/db');\n</code></pre>\n<p>You have:</p>\n<pre><code>db.query("SELECT DATEDIFF(time, curdate()) as lastChecked FROM tempcheck ORDER BY id DESC LIMIT 1;",(error, result) => {\n</code></pre>\n<p>There are a number of issues here. First, it's hard to read. Consider defining the query on its own line:</p>\n<pre><code>const lastCheckedQuery = `\n SELECT DATEDIFF(time, curdate()) as lastChecked\n FROM tempcheck\n ORDER BY id DESC\n LIMIT 1;\n`;\n</code></pre>\n<p>Then, you can pass that in to <code>.query</code> instead.</p>\n<p>It depends on what your database is, but since you're only expecting one row to be returned, consider using a method which returns only one row instead - perhaps using <code>.one</code> instead of <code>.query</code>. That way, rather than <code>result[0].lastChecked</code>, you can do something like <code>row.lastChecked</code>.</p>\n<p>It's generally easier to work with Promises than with callbacks. This will become especially clear if you ever need to make more than one query before finishing - nested callbacks are ugly, and their logic can be hard to deal with. Again, it depends on your database driver, but consider looking for how to get it to return Promises instead of using callbacks. (<code>.query</code> may already return a Promise)</p>\n<p>If you stick with the callback route, at least check whether there's an error before examining the result. The main point of having the callback form having the error first:</p>\n<pre><code>(error, result) => {\n</code></pre>\n<p>is to try to force the programmer to think about the error, rather than just ignore it. (Consider using a linter and a rule like <a href=\"https://eslint.org/docs/rules/no-unused-vars\" rel=\"nofollow noreferrer\"><code>no-unused-vars</code></a>) You'd at least want something like</p>\n<pre><code>(error, result) => {\n if (error) {\n // put error into logs / examine it to send more detail to the user\n return res.status(500).send('Unexpected database error');\n }\n // proceed to work with result\n</code></pre>\n<p>Your <code>res.render</code> calls are nearly the same, all that's different is the <code>temp</code> property. This would be done much more concisely with the conditional operator.</p>\n<p>The <code>temp</code> property is not very informative. Consider naming it something more meaningful, like <code>possiblyChecked</code>, or a boolean <code>temperatureHasBeenChecked</code>.</p>\n<p>You're using <code>==</code> in a couple places. Best to <a href=\"https://stackoverflow.com/q/359494\">always use <code>===</code></a> - <code>==</code> has lots of weird rules and gotchas that script-writers should not have to memorize (nor that script-writers should force <em>others</em> who may need to look over their code to have to understand first).</p>\n<p>In full, your backend code might be able to look something like:</p>\n<pre><code>const express = require('express');\nconst router = express.Router();\nconst { db } = require('../controllers/db');\n\nconst lastCheckedQuery = `\n SELECT DATEDIFF(time, curdate()) as lastChecked\n FROM tempcheck\n ORDER BY id DESC\n LIMIT 1;\n`;\n\nrouter.get('/', (req, res) => {\n db.one(lastCheckedQuery)\n .then((row) => {\n res.render('home/index', { possiblyChecked: row.lastChecked === 0 ? 'checked' : '' });\n })\n .catch((error) => {\n // put error into logs / examine it to send more detail to the user\n return res.status(500).send('Unexpected database error');\n });\n});\n\nmodule.exports = router;\n</code></pre>\n<blockquote>\n<p>If checkbox is checked then prompt with a message "You have already completed this check, do you want to do it again?". Like so...</p>\n</blockquote>\n<p>It would be better to avoid <code>prompt</code> if possible. It's <a href=\"https://ux.stackexchange.com/a/12888\">pretty user-unfriendly</a> and prevents anything else on the page (such as JavaScript) from running, which is a problem on anything but the most trivial pages. Better to use a proper non-blocking modal instead.</p>\n<p>Rather than</p>\n<pre><code>if(document.getElementById('temp').checked == true){\n</code></pre>\n<p>Since <code>checked</code> returns a boolean, simply check that boolean:</p>\n<pre><code>if (document.getElementById('temp').checked) {\n</code></pre>\n<p>You have:</p>\n<pre><code><a id="tempBtn" href="/temp-check">Temperature</a>\n</code></pre>\n<pre><code><input id="temp" type="checkbox" name="" value="" disabled {{temp}}>\n</code></pre>\n<p>Personally, I prefer to avoid IDs since they implicitly create global variables. Regardless, <code>tempBtn</code> and <code>temp</code> aren't great names, especially if the page ever gets more complicated - one looking at the code might initially think "Does <code>temp</code> mean "temporary" or "temperature", or something else? And if <code>tempBtn</code> is a button, why is <code>temp</code> called just <code>temp</code> rather than <code>tempCheckbox</code> or something?"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T15:13:16.307",
"Id": "248874",
"ParentId": "248847",
"Score": "3"
}
},
{
"body": "<p>This code has a bit of redundancy:</p>\n<blockquote>\n<pre><code> if(result[0].lastChecked == 0){\n res.render('home/index', {temp: 'checked'});\n }\n else{\n res.render('home/index', {temp: ''});\n }\n</code></pre>\n</blockquote>\n<p>The only thing that changes in the two cases is the value of <code>temp</code> in the object.</p>\n<p>While only shorter by one line, the following re-written code only has a single line with a call to <code>res.render()</code>:</p>\n<pre><code>const returnObj = {temp: ''};\nif(result[0].lastChecked === 0){\n returnObj.temp = 'checked';\n}\nres.render('home/index', returnObj);\n</code></pre>\n<p>A benefit of this would be that if the route <code>home/index</code> needed to be updated it could be done in one spot instead of two (or multiple if the code ever got expanded).</p>\n<p>It could also be simplified using a ternary operator :</p>\n<pre><code> const returnObj = {temp: result[0].lastChecked === 0 ? 'checked' : '' };\n</code></pre>\n<hr />\n<p>In the answer by CertainPerformance the following advice is contained:</p>\n<blockquote>\n<p>Consider using a linter...</p>\n</blockquote>\n<p>That is great advice.</p>\n<p>Let's try using <a href=\"https://eslint.org/demo#eyJ0ZXh0IjoiaWYoZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ3RlbXAnKS5jaGVja2VkID09IHRydWUpe1xuICAgICAgZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ3RlbXBCdG4nKS5hZGRFdmVudExpc3RlbmVyKCdjbGljaycsIGZ1bmN0aW9uKGUpe1xuICAgICAgICBpZihjb25maXJtKFwiWW91IGhhdmUgYWxyZWFkeSBjb21wbGV0ZWQgdGhpcyBjaGVjaywgZG8geW91IHdhbnQgdG8gZG8gaXQgYWdhaW4/XCIpKXtcblxuICAgICAgICB9XG4gICAgICAgIGVsc2V7XG4gICAgICAgICAgZS5wcmV2ZW50RGVmYXVsdCgpO1xuICAgICAgICB9XG4gICAgICB9KTtcbiAgICB9Iiwib3B0aW9ucyI6eyJwYXJzZXJPcHRpb25zIjp7ImVjbWFWZXJzaW9uIjo2LCJzb3VyY2VUeXBlIjoic2NyaXB0IiwiZWNtYUZlYXR1cmVzIjp7fX0sInJ1bGVzIjp7ImNvbnN0cnVjdG9yLXN1cGVyIjoyLCJmb3ItZGlyZWN0aW9uIjoyLCJnZXR0ZXItcmV0dXJuIjoyLCJuby1hc3luYy1wcm9taXNlLWV4ZWN1dG9yIjoyLCJuby1jYXNlLWRlY2xhcmF0aW9ucyI6Miwibm8tY2xhc3MtYXNzaWduIjoyLCJuby1jb21wYXJlLW5lZy16ZXJvIjoyLCJuby1jb25kLWFzc2lnbiI6Miwibm8tY29uc3QtYXNzaWduIjoyLCJuby1jb25zdGFudC1jb25kaXRpb24iOjIsIm5vLWNvbnRyb2wtcmVnZXgiOjIsIm5vLWRlYnVnZ2VyIjoyLCJuby1kZWxldGUtdmFyIjoyLCJuby1kdXBlLWFyZ3MiOjIsIm5vLWR1cGUtY2xhc3MtbWVtYmVycyI6Miwibm8tZHVwZS1lbHNlLWlmIjoyLCJuby1kdXBlLWtleXMiOjIsIm5vLWR1cGxpY2F0ZS1jYXNlIjoyLCJuby1lbXB0eSI6Miwibm8tZW1wdHktY2hhcmFjdGVyLWNsYXNzIjoyLCJuby1lbXB0eS1wYXR0ZXJuIjoyLCJuby1leC1hc3NpZ24iOjIsIm5vLWV4dHJhLWJvb2xlYW4tY2FzdCI6Miwibm8tZXh0cmEtc2VtaSI6Miwibm8tZmFsbHRocm91Z2giOjIsIm5vLWZ1bmMtYXNzaWduIjoyLCJuby1nbG9iYWwtYXNzaWduIjoyLCJuby1pbXBvcnQtYXNzaWduIjoyLCJuby1pbm5lci1kZWNsYXJhdGlvbnMiOjIsIm5vLWludmFsaWQtcmVnZXhwIjoyLCJuby1pcnJlZ3VsYXItd2hpdGVzcGFjZSI6Miwibm8tbWlzbGVhZGluZy1jaGFyYWN0ZXItY2xhc3MiOjIsIm5vLW1peGVkLXNwYWNlcy1hbmQtdGFicyI6Miwibm8tbmV3LXN5bWJvbCI6Miwibm8tb2JqLWNhbGxzIjoyLCJuby1vY3RhbCI6Miwibm8tcHJvdG90eXBlLWJ1aWx0aW5zIjoyLCJuby1yZWRlY2xhcmUiOjIsIm5vLXJlZ2V4LXNwYWNlcyI6Miwibm8tc2VsZi1hc3NpZ24iOjIsIm5vLXNldHRlci1yZXR1cm4iOjIsIm5vLXNoYWRvdy1yZXN0cmljdGVkLW5hbWVzIjoyLCJuby1zcGFyc2UtYXJyYXlzIjoyLCJuby10aGlzLWJlZm9yZS1zdXBlciI6Miwibm8tdW5kZWYiOjIsIm5vLXVuZXhwZWN0ZWQtbXVsdGlsaW5lIjoyLCJuby11bnJlYWNoYWJsZSI6Miwibm8tdW5zYWZlLWZpbmFsbHkiOjIsIm5vLXVuc2FmZS1uZWdhdGlvbiI6Miwibm8tdW51c2VkLWxhYmVscyI6Miwibm8tdW51c2VkLXZhcnMiOjIsIm5vLXVzZWxlc3MtY2F0Y2giOjIsIm5vLXVzZWxlc3MtZXNjYXBlIjoyLCJuby13aXRoIjoyLCJyZXF1aXJlLXlpZWxkIjoyLCJ1c2UtaXNuYW4iOjIsInZhbGlkLXR5cGVvZiI6Mn0sImVudiI6eyJicm93c2VyIjp0cnVlfX19\" rel=\"nofollow noreferrer\">eslint with that last block of JavaScript "<em>bottom of handlebars</em>"</a></p>\n<pre><code><script type="text/javascript">\n if(document.getElementById('temp').checked == true){\n document.getElementById('tempBtn').addEventListener('click', function(e){\n if(confirm("You have already completed this check, do you want to do it again?")){\n\n }\n else{\n e.preventDefault();\n }\n });\n }\n</script>\n</code></pre>\n<p>Under the <strong>Messages</strong> tab on the right side we see:</p>\n<blockquote>\n<p>3:90 - Empty block statement.<a href=\"https://eslint.org/docs/rules/no-empty\" rel=\"nofollow noreferrer\">no-empty</a></p>\n</blockquote>\n<p>That link <a href=\"https://eslint.org/docs/rules/no-empty\" rel=\"nofollow noreferrer\">no-empty</a> leads to a page that explains why this rule exists:</p>\n<blockquote>\n<p>Empty block statements, while not technically errors, usually occur due to refactoring that wasn't completed. They can cause confusion when reading code.</p>\n</blockquote>\n<p>That code can be cleaned up (A.K.A. "linted") by reversing the logic on the conditional:</p>\n<pre><code>if(!confirm("You have already completed this check, do you want to do it again?")){\n e.preventDefault();\n}\n</code></pre>\n<p>That is more concise and would hopefully avoid anybody reading the code (including your future self) from wondering if something should happen in that empty block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:35:27.870",
"Id": "487746",
"Score": "0",
"body": "For your first method of using `res.render('home/index', returnObj);` I am not sure if that is correct. This is because it does not give me any output. Whereas if I did `res.render('home/index', {returnObj : returnObj.temp});` it would work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T16:53:14.920",
"Id": "487773",
"Score": "0",
"body": "Hmm... did you use the suggestion of using `===`? If so, perhaps the expected value is not actually `0` but maybe a string like `\"false\"`..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T17:20:24.507",
"Id": "248877",
"ParentId": "248847",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248874",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:29:58.557",
"Id": "248847",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"handlebars"
],
"Title": "Node JS and Handlebars checking if records have been completed today"
}
|
248847
|
<p>Currently the class takes a json file and retrieves data from it, and i'd like to improve this class.</p>
<h1>ConfigLoader.h</h1>
<pre><code>#ifndef LEVELEDITOR_CONFIGLOADER_H
#define LEVELEDITOR_CONFIGLOADER_H
#include <string>
#include <json/json.h>
#include <stdexcept>
#include <fstream>
namespace Editor
{
class JsonInit
{
public:
JsonInit()
{
std::ifstream inputFile("config.json");
if (inputFile.bad())
{
throw std::runtime_error("could not load config file");
}
inputFile >> _root;
}
inline Json::Value& getRoot() { return _root; }
private:
Json::Value _root;
};
class ConfigLoader
{
public:
inline static int loadInt(const std::string key) {return json.getRoot().get(key, -1).asInt(); }
inline static std::string& loadString(const std::string key) {return json.getRoot().get(key, -1).asString();}
private:
static JsonInit json;
};
}
#endif // LEVELEDITOR_CONFIGLOADER_H
</code></pre>
<h1>ConfigLoader.cpp</h1>
<pre><code>#include "configloader.h"
Editor::JsonInit Editor::ConfigLoader::json;
</code></pre>
<p>Edit: forgot to say the "config.json" path is temporary, as i wish to make it possible to let the user choose</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:54:34.190",
"Id": "488274",
"Score": "0",
"body": "Is the configuration set or does it allow random values. If fixed then I would look at [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer) as it requires zero code to load the config file into a C++ object,"
}
] |
[
{
"body": "<p>It appears that the file <code>ConfigLoader.cpp</code> is unnecessary unless you are just providing an example of usage.</p>\n<p>The keyword <code>inline</code> is obsolete, it is really only a suggestion these days. Modern C++ compilers will make the decision on whether the code should be inlined or not when using the -O3 switch.</p>\n<p>If you are going to let the user define the config file name, then pass the name into the constructor and default it at a higher level.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T11:49:08.210",
"Id": "248859",
"ParentId": "248848",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T08:42:47.147",
"Id": "248848",
"Score": "1",
"Tags": [
"c++",
"json",
"classes",
"static"
],
"Title": "Json config loader class"
}
|
248848
|
<p>for learning purposes (and I found it kinda useful), I built a very basic command-line based metronome in rust. It's the first actual smaller project I built in rust.</p>
<p>It consists of 4 source files.
What I'm most concerned about:</p>
<ul>
<li>Audio Handling: At the moment i'm loading the audio files on the fly, every time I want to play a sound, which is redundant, obviously. Is there a way to embed the audio files into the executable? Or alternatively at least preload the files at the start of the app. I already tried this, but I had problems with the reusage of the buffer.</li>
<li>The metronome is supposed to be controllable from the main thread. Is that a sensible to implement that functionality? (Currently, only Stopping is implemented, as I first wanted to get the basic Threading functionality down)</li>
<li>I'm mainly coming from Python and C++, so I'm afraid I'm applying patterns I'm used to from those languages.</li>
</ul>
<p>The source code:</p>
<p>main.rs</p>
<pre><code>mod audio_handling;
mod io;
mod metronome;
fn main() {
audio_handling::check_audio_files();
let metronome: metronome::Metronome = io::ask_metronome_settings();
let worker = metronome.start();
loop {}
}
</code></pre>
<p>io.rs</p>
<pre><code>use crate::metronome::Metronome;
use std::io;
pub fn ask_metronome_settings() -> Metronome {
let mut bpm = String::new();
let mut time_signature = String::new();
println!("Please enter the BPM for ♩ = (0-65536):");
io::stdin().read_line(&mut bpm).expect("You failed!");
println!("Please enter the time signature, (Format: \"x/y\"):");
io::stdin()
.read_line(&mut time_signature)
.expect("You failed!");
let bpm: u16 = match bpm.trim().parse() {
Ok(num) => num,
Err(_) => 0,
};
let numbers: Vec<u8> = time_signature
.trim()
.split("/")
.map(|x| x.parse().expect("Error parsing time signature"))
.collect();
Metronome::new(bpm, numbers[0], numbers[1])
}
</code></pre>
<p>metronome.rs</p>
<pre><code>use std::sync::mpsc::{channel, Sender};
use std::thread;
use std::time::Duration;
use std::time::Instant;
use crate::audio_handling::AudioSettings;
use crate::audio_handling::TicToc;
pub fn calc_beat_delta(bpm: u16, lower: u8) -> Duration {
let quarter_note_sec: f64 = 60f64 / bpm as f64;
let factor: f64 = 4f64 / lower as f64;
Duration::from_secs_f64(quarter_note_sec * factor)
}
#[derive(Debug, Copy, Clone)]
pub struct TimeSignature {
upper: u8,
lower: u8,
}
#[derive(Debug, Copy, Clone)]
pub struct MetronomeSettings {
bpm: u16,
time_signature: TimeSignature,
}
#[derive(Debug)]
pub enum MetronomeControls {
Stop,
}
#[derive(Debug, Copy, Clone)]
pub struct Metronome {
metronome_settings: MetronomeSettings,
current_beat: u8,
last_time_run: Instant,
beat_delta: Duration,
}
impl Metronome {
pub fn new(bpm: u16, upper: u8, lower: u8) -> Metronome {
Metronome {
metronome_settings: MetronomeSettings {
bpm,
time_signature: TimeSignature { upper, lower },
},
current_beat: 0,
last_time_run: Instant::now(),
beat_delta: calc_beat_delta(bpm, lower),
}
}
fn next(&mut self) {
self.current_beat = (self.current_beat + 1) % self.metronome_settings.time_signature.upper;
self.last_time_run = std::time::Instant::now();
}
fn play_beat(self) {
let audio_settings: AudioSettings = AudioSettings::load();
match self.current_beat {
0 => audio_settings.play(TicToc::Tic),
_ => audio_settings.play(TicToc::Toc),
}
}
pub fn start(mut self) -> Sender<MetronomeControls> {
println!("Metronome started!");
let (tx, rx) = channel();
thread::spawn(move || loop {
self.play_beat();
let sleep_time = self.beat_delta - (Instant::now() - self.last_time_run);
let msg = rx.recv_timeout(sleep_time);
match msg {
Ok(MetronomeControls::Stop) => break,
Err(_) => (),
}
self.next();
});
tx
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calc_beat_delta() {
assert_eq!(calc_beat_delta(120, 4), Duration::from_millis(500));
assert_eq!(calc_beat_delta(119, 4), Duration::from_secs_f64(0.50420168));
assert_eq!(calc_beat_delta(119, 8), Duration::from_secs_f64(0.25210084));
}
#[test]
fn test_metronome_next() {
let mut metronome: Metronome = Metronome::new(120, 4, 4);
assert_eq!(metronome.current_beat, 0);
metronome.next();
assert_eq!(metronome.current_beat, 1);
metronome.next();
metronome.next();
assert_eq!(metronome.current_beat, 3);
metronome.next();
assert_eq!(metronome.current_beat, 0);
}
}
</code></pre>
<p>audio_handling.rs</p>
<pre><code>use std::io::BufReader;
use std::path::Path;
const TIC_PATH: &str = "./tic.wav";
const TOC_PATH: &str = "./toc.wav";
const AUDIO_FILE_PATHS: [&str; 2] = [TIC_PATH, TOC_PATH];
pub fn check_audio_files() {
for file_path in AUDIO_FILE_PATHS.iter() {
if !Path::new(&file_path).exists() {
panic!("Audio files missing!");
}
}
}
#[derive(Debug)]
pub enum TicToc {
Tic,
Toc,
}
pub struct AudioSettings {
device: rodio::Device,
}
impl AudioSettings {
pub fn load() -> AudioSettings {
AudioSettings {
device: rodio::default_output_device().unwrap(),
}
}
pub fn play(self, what: TicToc) {
let file_path = match what {
TicToc::Tic => TIC_PATH,
TicToc::Toc => TOC_PATH,
};
let audio_file = std::fs::File::open(file_path).unwrap();
rodio::play_once(&self.device, BufReader::new(audio_file))
.unwrap()
.detach();
}
}
</code></pre>
<p>If you want to compile it, the code can be found here:
<a href="https://github.com/zapfdk/rust-metronome" rel="nofollow noreferrer">https://github.com/zapfdk/rust-metronome</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T09:07:55.780",
"Id": "248851",
"Score": "3",
"Tags": [
"multithreading",
"rust",
"audio"
],
"Title": "Metronome in Rust, Audio Handling and Threading"
}
|
248851
|
<p>Raku script to open files from terminal with xdg-open and, with del option, asks for deletion. Happy to receive Raku syntax improvements. Thanks!</p>
<pre><code>use v6;
#| Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion
sub MAIN( $pattern is copy, Str $ext, Str $del? where ( $del ∈ < del nodel > ) = "nodel" ) {
$pattern = "" if $pattern eq "all";
my @files = '.'.IO.dir(test => /.*$pattern.*\.$ext/);
for @files -> $file {
my @args = 'xdg-open', $file.basename;
my $command = run @args;
$command.exitcode == 0 or die "system @args failed: $!";
if $del eq 'del' {
my $delete = prompt("\n \n Delete file $file (s/n) ");
next if $delete ne "s";
say "mv $file /tmp/$file";
$file.IO.move("/tmp/$file");
}
my $exit = prompt("\n Press 'q' to end, return to continue ");
last if $exit eq q{q};
}
@files = '.'.IO.dir(test => /.*$pattern.*$ext$/);
say "-" x 60;
for @files -> $file { $file.Str.say }
say "-" x 60;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T16:45:18.980",
"Id": "487686",
"Score": "1",
"body": "Well, it might be a bit cleaner if you use a multi with different values for `$pattern`, a `multi sub MAIN( $pattern )` and `multi sub MAIN(\"all\"), with this one defined first. `$pattern` is apparently only used to define a glob, so you might want to use that instead. . Also a multi for values of `del` but if that works for you, it's OK. What kind of improvement were you looking for, exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-06T18:25:52.280",
"Id": "491062",
"Score": "1",
"body": "Thank you very much! Even though it worked, he wanted to incorporate Raku's logic. Not used to the multi sub: a great improvement! Great!"
}
] |
[
{
"body": "<p>If I just run your program without any arguments, this is what I get:</p>\n<pre><code>Usage:\n foo.raku <pattern> <ext> [<del>] -- Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion\n</code></pre>\n<p>That's not super helfpul, so let's tackle that first.</p>\n<pre><code>#| Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion \nsub MAIN(\n $pattern is copy, #= The pattern to match against (use 'all' to match everything)\n Str $ext, #= The extension for the file\n Str $del? where ( $del ∈ < del nodel > ) #= Options for opening ('del' or 'nodel', defaults to 'nodel')\n = "nodel" \n) {\n ...\n}\n</code></pre>\n<p>This produces much nicer output:</p>\n<pre><code>Usage:\n foo.raku <pattern> <ext> [<del>] -- Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion\n \n <pattern> The pattern to match against (use 'all' to match everything)\n <ext> The extension for the file\n [<del>] Options for opening ('del' or 'nodel', defaults to 'nodel')\n</code></pre>\n<p>One thing you'll note is that the <code>#=</code> syntax doesn't play nicely with default values, so while I normally prefer using <code>#=</code> for parameters, the <code>#|</code> might be better when you have defaults. I personally like to let it breathe a bit more when doing this, but YMMV.</p>\n<pre><code>#| Linux: Opens file 'pattern.ext' with xdg-open and, with del option, asks for deletion \nsub MAIN(\n\n #| The pattern to match against (use 'all' to match everything)\n $pattern,\n\n #| The extension for the file\n Str $ext,\n\n #| Options for opening ('del' or 'nodel', defaults to 'nodel')\n Str $del? where {$del <del nodel>} = "nodel"\n) {\n ...\n}\n</code></pre>\n<p>You'll notice I adjust the <code>$del</code> <code>where</code> clause a bit. Where clauses expect a block, and using parentheses like you did along with the default value can cause problems IME where the equals sign gets gobbled into the block implied block, so explicit blocks are safest. Because you've set a default value, you don't need to mark it as explicitly optional.</p>\n<p>Now let's look at your main code. First we have the line</p>\n<pre><code>my @files = '.'.IO.dir(test => /.*$pattern.*\\.$ext/);\n</code></pre>\n<p>First, instead of <code>'.'.IO</code>, you can use <code>$*CWD</code>, which identifies the purpose a bit better. Your regex pattern is a bit off also. Let's comment it and you'll see what's going on:</p>\n<pre><code> my @files = $*CWD.dir:\n test => /\n .* # match any characters\n $pattern # then the pattern\n .* # then any characters\n \\. # then literal period \n $ext # then the extension\n /);\n</code></pre>\n<p>Regexen declared with <code>/ /</code> aren't anchored to the start or end, so the initial <code>.*</code> isn't necessary. OTOH, you <em>will</em> want an explicit end so you can do</p>\n<pre><code> my @files = '.'.IO.dir:\n test => /\n $pattern # the pattern\n .* # then any characters\n \\. # then literal period \n $ext # then the extension\n $ # and end the filename\n /);\n</code></pre>\n<p>It might add a few lines to your code, but commenting regex is a very good idea and can help you catch bugs sometimes.</p>\n<p>Now in your main logic block</p>\n<pre><code> for @files -> $file {\n my @args = 'xdg-open', $file.basename;\n my $command = run @args;\n $command.exitcode == 0 or die "system @args failed: $!";\n if $del eq 'del' {\n my $delete = prompt("\\n \\n Delete file $file (s/n) ");\n next if $delete ne "s";\n say "mv $file /tmp/$file";\n $file.IO.move("/tmp/$file");\n }\n my $exit = prompt("\\n Press 'q' to end, return to continue ");\n last if $exit eq q{q};\n }\n</code></pre>\n<p>Separating out your arguments for run into a separate variable is nice, although obviously not strictly necessary. Because the result of <code>run</code> is truthy based on its success, and we don't use the exit code anywhere else, we can just put the run inside the <code>unless</code> clause. If that's compacting too much into too small of a space for you, or if you'll need to use the exit code for later expansions of the script, you could use <code>my $command = run @args; fail '...' unless $command</code>. (ht Brad in comments).</p>\n<p>One thing to consider is if you really want to die. I don't know the <code>xdg-open</code> command personally, so not sure its mechanics. If you do need to die (terminates the entire script), then by all means do so. But since each file is being handled separately, perhaps you'd prefer to warn the user and continue with the others. In that case, you could use a <code>fail</code>, optionally with a CATCH handler to provide more detailed support:</p>\n<pre><code> for @files -> $file {\n my @args = 'xdg-open', $file.basename;\n\n fail "system @args failed: $!" \n unless run @args;\n\n if $del eq 'del' {\n my $delete = prompt("\\n \\n Delete file $file (s/n) ");\n next if $delete ne "s";\n say "mv $file /tmp/$file";\n $file.IO.move("/tmp/$file");\n }\n\n my $exit = prompt("\\n Press 'q' to end, return to continue ");\n last if $exit eq 'q';\n\n CATCH {\n .message.say;\n next if prompt "Would you like to continue processing other files?" eq "y";\n exit 0;\n }\n }\n\n</code></pre>\n<p>You'll notice I also gave it a little bit of extra space. Think of it like separating paragraphs in your code. I would recommend against using <code>q{q}</code> to match <code>q</code>, just use <code>'q'</code>. The special quote structures have their place, but this doesn't feel like one of them.</p>\n<p>For the final bit of code, the same thing I mentioned about the regex will apply. For the output:</p>\n<pre><code> say "-" x 60;\n for @files -> $file { $file.Str.say }\n say "-" x 60;\n</code></pre>\n<p>Works well, but the middle line can be greatly simplified to <code>.Str.say for @files</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T19:27:03.393",
"Id": "491378",
"Score": "1",
"body": "There is also no need to directly check the exit code. The result of calling `run` automatically does the right thing in Bool context. `fail \"…\" unless $command;` That is `Proc.Bool()` is exactly the same as `Proc.exitcode == 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-09T20:34:11.453",
"Id": "491382",
"Score": "0",
"body": "@BradGilbert Ah yes, I forgot about that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-08T01:43:05.597",
"Id": "250350",
"ParentId": "248853",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250350",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:02:21.933",
"Id": "248853",
"Score": "3",
"Tags": [
"linux",
"raku"
],
"Title": "Linux: Raku script to open files from terminal and ask for deletion"
}
|
248853
|
<p>I am currently experimenting a bit with C# and as a way of learning I am making a very simple 2D game (asteroids-ish).</p>
<p>I am using the monogame framework and the general plan of attack was to have all data "flow one way", if that makes sense? In the sense that I have multiple layers of objects such as this:</p>
<pre><code>CoreGame.Update(gametime) ->
Scene.Update(gametime) ->
GameManager.Update(gametime) (if scene is game scene) ->
EntityManager.Update(gametime) ->
Entity.Update(gametime) ->
Component.Update(gametime)
</code></pre>
<p>Where every subsequent layer has a many-to-one relationship with the previous layer (an Entity can have many components, an entity manager can have many entities, but an entity can only have one entity manager).</p>
<p>I also use a simple ECS scheme as can probably be inferred. However the "data only runs one way" thinking hits a snag when events occur such as a spaceship firing a laser for example, which requires the <code>EntityManager</code> to be informed to add this entity to its list of entities etc, sounds must be generated etc. But the actual event occurs at the component level so data would have to travel "upwards".</p>
<p>So I figured I would make a messaging system that dispatches a message to the layer above it, which the layer then handles that message or forwards it to the next layer. The message itself would be added to a concurrent queue of Actions which are emptied and invoked in each update call for each layer.</p>
<p>Some code to show what I mean:</p>
<pre><code>namespace SpaceGame.Engine.ECS {
public class EntityManager : IRecv<EntityManagerMsg> {
#region properties
private ConcurrentQueue<Action> _recvActions;
public MessageSendingService MsgService { get; set; }
public Dictionary<Guid, GameEntity> Entities;
public ConcurrentQueue<Action> RecvActions { get => this._recvActions; set => this._recvActions = value; }
private Camera camera;
#endregion
public EntityManager(ref Camera camera) {
this.MsgService = new MessageSendingService();
this.Entities = new Dictionary<Guid, GameEntity>();
this.RecvActions = new ConcurrentQueue<Action>();
this.Camera = camera;
var player = AssetManager.CreatePlayer ( new Vector2 (400,300) );
this.AddEntity ( player );
}
public void AddEntity (GameEntity entity) {
entity.MsgService.Subscribe(OnRecv);
this.Entities.Add(entity.Id, entity);
return;
}
public void RemoveEntity(Guid id) {
if (this.Entities.ContainsKey(id)) {
this.Entities[id].MsgService.UnSubscribe(OnRecv);
this.Entities.Remove(id);
}
}
public void Update (GameTime gameTime) {
while (_recvActions.TryDequeue (out var msg)) {
msg.Invoke();
}
Parallel.ForEach(this.Entities, KeyValuePair => {
KeyValuePair.Value.Update(gameTime);
});
//will handle collisions here
}
public void Draw (SpriteBatch sb) {
foreach(GameEntity entity in this.Entities.Values) {
entity.Draw(sb);
}
}
public void HandleIncomingMessages (EntityManagerMsg msg) {
switch (msg) {
case SpawnBallMsg spawnBallMsg:
var ball = AssetManager.CreateBall(
new Vector2(
spawnBallMsg.XPos,
spawnBallMsg.YPos),
new Vector2(
spawnBallMsg.XSpeed * 6,
spawnBallMsg.YSpeed * 6),
spawnBallMsg.Owner
);
this.RecvActions.Enqueue( () => this.AddEntity (ball));
return;
case IsKilledMsg killedMsg:
this.RecvActions.Enqueue( () => this.RemoveEntity(killedMsg.EntityId));
return;
case SpawnFighter fighterMsg:
var fighter = AssetManager.CreateFighter(fighterMsg.Id, new Vector2(fighterMsg.XPos, fighterMsg.YPos));
this.RecvActions.Enqueue( () => this.AddEntity(fighter));
return;
default:
return;
}
}
public void OnRecv (object source, Msg msg) {
if (msg is EntityManagerMsg emsg) {
HandleIncomingMessages(emsg);
}
else {
MsgService.ForwardMsg(msg);
}
}
}
}
</code></pre>
<p>This is an example of a layer which implements the IRecv message interface and has a has a msg service composition.</p>
<p>Finally the code for the message passing:</p>
<pre><code>namespace SpaceGame.Engine.MessageSystem {
public interface IRecv<T> where T : Msg {
ConcurrentQueue<Action> RecvActions { get; set; }
void HandleIncomingMessages(T msg);
void OnRecv(object source, Msg msg);
}
}
namespace SpaceGame.Engine.MessageSystem {
public class MessageSendingService {
#region properties
private EventHandler<Msg> Msgs { get; set; }
#endregion
protected void OnDispatch(Msg msg) {
this.Msgs?.Invoke(this, msg);
}
protected void OnDispatchAsync(Msg msg) {
Task.Factory.StartNew(() => this.OnDispatch(msg));
}
public void Dispatch(Msg msg) {
OnDispatchAsync(msg);
}
public void ForwardMsg(Msg msg) {
OnDispatch(msg);
}
public void Subscribe(Action<object, Msg> func) {
EventHandler<Msg> a = func.Invoke;
this.Msgs += a;
}
public void UnSubscribe(Action<object, Msg> func) {
EventHandler<Msg> a = func.Invoke;
this.Msgs -= a;
}
}
}
</code></pre>
<p>And the messages are structured like this (removed some messages for brevity but you get the point).</p>
<pre><code>namespace SpaceGame.Engine.MessageSystem {
abstract public class Msg : EventArgs {}
abstract public class EntityManagerMsg : Msg {}
public class IsKilledMsg : EntityManagerMsg {
public Guid EntityId { get; set; }
public IsKilledMsg(Guid eId) {
this.EntityId = eId;
}
}
abstract public class EntityMsg : Msg {}
abstract public class GameManagerMsg : Msg {}
public class ExitGame : Msg {
public ExitGame() {}
}
}
</code></pre>
<p>So in this case a <code>StatComponent</code> would then call <code>dispatch new IsKilledMsg(this.Entity.Id)</code> which would send it from the <code>StatComponent -> Entity</code> where the entity would see that it is not an <code>EntityMsg</code> and forward it to the <code>EntityManager</code> who would then insert the command to its queue to remove it from its entity list.</p>
<p>Every message is also sent asynchronously, I have tested this a bit and it seems to work fine but is there a problem with this design? Or is it a rational way of making this game? Any improvements, potential issues or other ways of doing it that are better?. I know it is a long post and I apologize, but if you read through it I am most appreciative.</p>
|
[] |
[
{
"body": "<p><strong>Some general advice:</strong></p>\n<p>You need to think about the pros/cons of each step in your design.</p>\n<p>For example, you've said you would like all the data to "flow one way"</p>\n<ul>\n<li>Are there benefits to doing this?</li>\n<li>Do the benefits outweigh the problems you have listed?</li>\n</ul>\n<p>If I were in your shoes, I'd opt for the simplest solution I could think of.\nIf simple solutions don't work, then you can start looking for complicated ones.</p>\n<p>In the words of Bill Gates, <code>“I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.”</code></p>\n<p><strong>Problem specific answer</strong></p>\n<p>You've mentioned that your message system works asynchronously/concurrently. I'd absolutely avoid having asynchronous operations unless they are needed. <a href=\"https://softwareengineering.stackexchange.com/questions/153632/what-are-the-usual-difficulties-in-concurrent-programming-and-tuning-of-concurre\">There's plenty of resources out there listing difficulties in concurrent programming</a>.</p>\n<p>A message system itself is not a bad idea. I wouldn't recommend using one in a simple game though; it seems like an overkill. <a href=\"https://gamedevelopment.tutsplus.com/tutorials/how-to-implement-and-use-a-message-queue-in-your-game--cms-25407\" rel=\"nofollow noreferrer\">See here for an overview of a game message system</a>.</p>\n<p>With the laser spawning issue, you could have a <code>Queue</code> in your entity manager that holds any new entities spawned in that frame.</p>\n<p>At the end of the frame, the entity manager can move the entities from the <code>Queue</code> to whatever data structure the active entities are stored in.</p>\n<p>You've mentioned that you have multiple entity managers, which adds a complication; since entities would then need a reference to their entity manager. The solution to this depends on how you've divided the entity managers up:</p>\n<ul>\n<li>If it's one entity manager per type of entity, you can have a global reference that any entity can access. Creating a new entity is as simple as pushing it onto the relevant entity manager.</li>\n<li>If it's one entity manager per level, you can set up a global getter that points to the entity manager that relates to the current level.</li>\n</ul>\n<p>This way, no entity has to store a reference to its entity manager.</p>\n<p>Finally, your <a href=\"https://en.wikipedia.org/wiki/Entity_component_system\" rel=\"nofollow noreferrer\">component-based design is a popular architecture</a>. Unreal Engine is a commerical engine that uses it. <a href=\"https://stackoverflow.com/questions/58596897/what-are-the-disadvantages-of-the-ecs-entity-component-system-architectural-pa#:%7E:text=Changing%20the%20content%20of%20components,entity%20across%20all%20it%27s%20components.\">However, it isn't without issues</a>. For a simple game as you describe, I would go for an inheritance-based design. I would imagine that all your entities have many overlapping properties, which is what inheritance-based design is effective at. Your entity base class can have properties such as location, sprite, and collision box.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:35:01.617",
"Id": "487701",
"Score": "0",
"body": "Hello thank you for your response. I realize that this is laughably over-designed for what it is. I more wanted to sort of make it extendible for the future if I wanted to make it more complex/re-usable for an entirely different game. I am wondering however, how would the asynchronous behaviour be a problem in this instance as the messages themselves are virtually immutable and I am adding them to a threadsafe queue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:43:02.713",
"Id": "487702",
"Score": "1",
"body": "No problem @kiooikml! It's understandable to want to design perfect low-level systems from the start. Unfortunately it's difficult to do, as it involves having solving problems that haven't arisen yet! The nature of programming is to find a solution to a problem, and then revisit it later when a new problem arises. I suggest you extensively modularise your systems. For example, you can create an API that can add entities, and under-the-hood it might simply add the entity directly to the entity manager for the time being, but in the future you can change it to use a message system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:46:43.033",
"Id": "487705",
"Score": "1",
"body": "I'll use Unreal Engine as an example again; they haven't simply created a great engine from scratch. They continually develop their game `Fortnite`, and push new features back to the engine if they think it will be usable in other games."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:54:48.110",
"Id": "487706",
"Score": "1",
"body": "Regarding your question about asynchronous behaviour being an issue. It isn't an issue, you can use that approach, given that you are aware of issues surrounding concurrent programming (see my answer). However, it's simply unnecessary. You need to ask yourself \"What would happen if I *didn't* use an asynchronous approach?\" The benefit is a much simpler message system. I can't see any drawbacks from avoiding the async approach judging by your original post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:20:58.940",
"Id": "487708",
"Score": "1",
"body": "Ok I get you, the reasoning for the asynchronous nature of it was the intention of maybe adding a simple multiplayer mode. But as it is now, you are correct it really does not add anything, it may even slow the entire thing down from the overhead by running threads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:22:54.350",
"Id": "487743",
"Score": "0",
"body": "@kiooikml Even when adding multiplayer, you can avoid an asynchronous message system. You can have two threads, the game thread and the network thread. In your game loop, you can take data from the network thread buffer and push it to the game thread; this can happen synchronously. The asynchronous part is *not* the message system, it is instead the network thread filling up the buffer as data comes in."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:30:24.687",
"Id": "248881",
"ParentId": "248855",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:18:45.330",
"Id": "248855",
"Score": "3",
"Tags": [
"c#",
"game",
"event-handling",
"monogame"
],
"Title": "Creating a simple event message passing system in C# for a rudimentary 2d sprite game"
}
|
248855
|
<p>I needed to execute a sequence of async tasks in JavaScript. They are async because I need them to be non-blocking, but I still want the current task to end before starting the next one.
The order of tasks doesn't matter, the only important thing is that they are in mutual exclusion with each other.</p>
<p>For this reason, maybe because of C/C++ background, I was about to implement a queue and a system of locks. Then I stop to think if the problem could be solved just using async/await, and I ended up with this solution:</p>
<pre><code>previousPromise = null;
async function enqueue(task) {
while (previousPromise) {
await previousPromise;
}
previousPromise = executeTask(task);
await previousPromise;
previousPromise = null;
}
</code></pre>
<p>In practice, I use the promise subscribers internal queue as the lock queue, in order to achieve a non-blocking wait. When the promise resolves, it awakes all the async tasks† and the first finding <code>previousPromise</code> equals to null will continue.</p>
<p>Here is a <a href="https://codepen.io/crisz/pen/poyWXKg?editors=1011" rel="nofollow noreferrer">codepen example</a>.</p>
<p>Is there any problem in this solution?
Thank you</p>
<ul>
<li><p><em>Side note 1</em>: a <strong>real</strong> lock system is obviously not needed. JavaScript is single-threaded, so there isn't any risk to be preempted after the while and before <code>executeTask</code> assignment.</p>
</li>
<li><p><em>Side note 2</em>: the tasks arrive from the server in an asynchronous fashion, so I can't collect them all before executing.</p>
</li>
</ul>
<p>† It actually calls the first callback in the subscriber's list</p>
|
[] |
[
{
"body": "<p>This loop:</p>\n<pre><code>async function enqueue(task) {\n while (previousPromise) {\n await previousPromise;\n }\n</code></pre>\n<p>will (asynchronously) block forever, after the first time <code>previousPromise</code> has been assigned to. An expression which is a Promise (for example, the <code>previousPromise</code>) will always remain a Promise, and will be truthy. You can use <code>await previousPromise</code> to extract its <em>resolve value</em> into a different expression, but the <code>previousPromise</code> remains a Promise. No more than two tasks can be completed using that <code>enqueue</code>.</p>\n<p>A better method would be to reassign the Promise every time <code>enqueue</code> is called, while chaining onto the previous Promise with a <code>.then</code>:</p>\n<pre><code>previousPromise = previousPromise.then(() => executeTask(task));\n</code></pre>\n<p>It'll also be easier to manage if the <code>previousPromise</code> stays the same shape (that is, of a Promise), rather than having to manage it possibly being <code>null</code>. Initialize it to <code>Promise.resolve()</code>.</p>\n<p>Demo below, where a task takes 1 second: it starts 2 tasks immediately, then 2 more tasks after 1.5 seconds (so these 4 together finish after 4 seconds), then another after 7 seconds (which finishes on second 8).</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 executeTask = () => new Promise(resolve => setTimeout(() => {\n console.log('task resolving');\n resolve();\n}, 1000));\nlet previousPromise = Promise.resolve();\n\nfunction enqueue(task) {\n previousPromise = previousPromise.then(() => executeTask(task));\n}\n\nconsole.log('start');\nenqueue();\nenqueue();\nsetTimeout(() => {\n enqueue();\n enqueue();\n}, 1500);\nsetTimeout(() => {\n enqueue();\n}, 7000);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Another thing to consider is: what do you want to occur when one of the tasks rejects (if that's ever a possibility)? You might want to add on a <code>.catch</code> onto the end of <code>executeTask</code> to make sure the next task can be started, without the whole Promise chain breaking:</p>\n<pre><code>previousPromise = previousPromise\n .then(() => executeTask(task))\n .catch((err) => { /* log error? Make sure previousPromise always resolves */ });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:33:14.453",
"Id": "248869",
"ParentId": "248856",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T10:52:02.663",
"Id": "248856",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Use async/await to implement mutual exclusion in JavaScript"
}
|
248856
|
<p>I'm trying to write simple parser using regexes. This is what I currently have, it looks really messy. Any tips what can I change?</p>
<pre><code>from re import compile
from typing import Dict, Iterator, List, NamedTuple, TextIO
# PATTERNS
registers_pattern = list(map(compile, [
r'(rax=[0-9a-f]{16}) (rbx=[0-9a-f]{16}) (rcx=[0-9a-f]{16})\n',
r'(rdx=[0-9a-f]{16}) (rsi=[0-9a-f]{16}) (rdi=[0-9a-f]{16})\n',
r'(rip=[0-9a-f]{16}) (rsp=[0-9a-f]{16}) (rbp=[0-9a-f]{16})\n',
r' (r8=[0-9a-f]{16}) (r9=[0-9a-f]{16}) (r10=[0-9a-f]{16})\n',
r'(r11=[0-9a-f]{16}) (r12=[0-9a-f]{16}) (r13=[0-9a-f]{16})\n',
r'(r14=[0-9a-f]{16}) (r15=[0-9a-f]{16})\n',
]))
flags_pattern = compile(r'iopl=[0-9a-f]+(?:\s+[a-z]{2}){8}\n')
segments_pattern = compile(r'(?:[a-z]{2}=[0-9a-f]{4}\s+){6}efl=[0-9a-f]{8}\n')
label_pattern = compile(r'[\w\+]+:\n')
instruction_pattern = compile(
r'[0-9a-f]{8}`[0-9a-f]{8}\s+(?P<ENCODING>[0-9a-f]+)\s+(?P<INSTRUCTION>.+?)\n?'
)
class Instruction(NamedTuple):
instruction: str
encoding: str
registers: Dict[str, str]
def parse_trace(stream: TextIO) -> Iterator[Instruction]:
""" TODO: some description
"""
iterator = iter(enumerate(stream, start=1))
for index, line in iterator:
# Parse general-purpose registers
registers: Dict[str, str] = {}
for pattern in registers_pattern:
if match := pattern.fullmatch(line):
# Extract register values from regex match and go to the next line
registers.update(group.split('=') for group in match.groups())
index, line = next(iterator)
else:
raise RuntimeError(f'Failed to parse line: {index}')
if flags_pattern.fullmatch(line) is None:
raise RuntimeError(f'Failed to parse line: {index}')
if segments_pattern.fullmatch(next(iterator)[1]) is None:
# TODO: here will be something
raise RuntimeError(f'Failed to parse line: {index}')
if label_pattern.fullmatch(next(iterator)[1]) is None:
raise RuntimeError(f'Failed to parse line: {index}')
if (match := instruction_pattern.fullmatch(next(iterator)[1])) is None:
raise RuntimeError(f'Failed to parse line: {index}')
yield Instruction(match.group('INSTRUCTION'), match.group('ENCODING'), registers)
# Example of usage:
from io import StringIO
trace = StringIO("""rax=0000000000000000 rbx=0000000000000000 rcx=0000000000000000
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
rip=000000000040100a rsp=0000000000000000 rbp=0000000000000000
r8=0000000000000000 r9=0000000000000000 r10=0000000000000000
r11=0000000000000000 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0 nv up ei pl zr na po nc
cs=0033 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246
lol+0x1000:
00000000`00401000 48bba47868302035e80c mov rbx,0CE83520306878A4h
rax=0000000000000000 rbx=0000000000000000 rcx=0000000000000000
rdx=0000000000000000 rsi=0000000000000000 rdi=0000000000000000
rip=000000000040100a rsp=0000000000000000 rbp=0000000000000000
r8=0000000000000000 r9=0000000000000000 r10=0000000000000000
r11=0000000000000000 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0 nv up ei pl zr na po nc
cs=0033 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246
lol+0x1000:
00000000`00401000 48bba47868302035e80c mov rbx,0CE83520306878A4h""")
for each in parse_trace(trace):
print(each.instruction)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T22:11:04.113",
"Id": "487713",
"Score": "1",
"body": "Is your goal to create the parser using regex's, or do you just want to parse the input into `Instruction` objects as cleanly as possible? Will the input coming from a file, or must it accept any `TextIO` object? Because if it is being read from a file, and this instruction parser can open the file, it could use [`fileinput.filelineno`](https://docs.python.org/3.8/library/fileinput.html?highlight=fileinput#fileinput.filelineno) to keep track of line numbers."
}
] |
[
{
"body": "<p>This line is repeated many times</p>\n<pre><code>raise RuntimeError(f'Failed to parse line: {index}')\n</code></pre>\n<p>I would create a function for it like so:</p>\n<pre><code>def parseError(index):\n raise RuntimeError(f'Failed to parse line: {index}') \n</code></pre>\n<p>and by calling this function you avoid repeating the format string over and over.</p>\n<p>Also this pattern <code>=[0-9a-f]{16}</code> is repeated 17 times in your definition. You could define it once as a variable, and then build those regex strings with some combination of format strings, list, dict, and/or functions to reduce the repetition.</p>\n<p>for example</p>\n<pre><code>p = r'=[0-9a-f]{16}'\n\ndef pattern(prefixes):\n result = r''\n for prefix in prefixes:\n # build the format string from the prefixes\n\n\nregisters_pattern = list(map(compile, [ pattern( ['rax', 'rbx', 'rcx'] ) , pattern ( [] ) \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:53:41.513",
"Id": "248866",
"ParentId": "248861",
"Score": "1"
}
},
{
"body": "<p>Instead of trying to match whole lines, it would be simpler to match smaller chunks of the input and the combine the smaller regexes. For example, one regex could match any of the registers, a different one could match the segment registers, etc. Order of the patterns may be important if one regex is be a prefix of another, but that doesn't seem to apply in this case.</p>\n<p>Use capture groups to get the important information, and <code>MatchObject.lastgroup</code> to see which part of the regex matched.</p>\n<p>The flags pattern probably needs to have other codes added.</p>\n<p>The <code>(?x)</code> in the pattern is for verbose mode, which lets you add whitespace and comments to the regex pattern.</p>\n<pre><code>pattern = r"""(?x)\n (?P<REG>r\\w{1,2})=(?P<RVAL>[0-9a-f]{16}) # registers\n |iopl=(?P<IOPL>[0-9a-f]+) # iopl\n |(?P<FLAGS>(\\s+(?:nv|up|ei|pl|zr|na|po|nc))+) # flags\n |(?P<SREG>[csdefg]s|efl)=(?P<SVAL>[0-9a-f]+) # segments\n |(?P<LABEL>^[\\w\\+]+:) # label\n |[0-9a-f]{8}`[0-9a-f]{8}\\s+(?P<ENCODING>[0-9a-f]+)\\s+(?P<INSTRUCTION>.+)\n |(?P<NL>\\n)\n """\nregex = re.compile(pattern)\n\nregisters = {}\n\nlineno = 1\n\nfor line in trace:\n print(f"line = {lineno}")\n \n for mo in regex.finditer(line):\n group_name = mo.lastgroup\n \n if group_name == 'NL':\n lineno += 1\n \n else:\n if group_name == "RVAL":\n registers[mo['REG']] = mo['RVAL']\n print(f" {mo['REG']} = {mo['RVAL']}")\n \n elif group_name == "IOPL":\n print(f" iopl = {mo['IOPL']}") \n \n elif group_name == "FLAGS":\n print(f" FLAGS = {mo['FLAGS'].strip().split()}") \n \n elif group_name == "SVAL":\n print(f" {mo['SREG']} = {mo['SVAL']}")\n \n elif group_name == "LABEL":\n print(f" LABEL = {mo['LABEL']}") \n \n elif group_name == "INSTRUCTION":\n print(f" {mo['INSTRUCTION']} = {mo['ENCODING']}")\n</code></pre>\n<p>For the sample input, the code outputs:</p>\n<pre><code>line = 1\n rax = 0000000000000000\n rbx = 0000000000000000\n rcx = 0000000000000000\nline = 2\n rdx = 0000000000000000\n rsi = 0000000000000000\n rdi = 0000000000000000\nline = 3\n rip = 000000000040100a\n rsp = 0000000000000000\n rbp = 0000000000000000\nline = 4\n r8 = 0000000000000000\n r9 = 0000000000000000\n r10 = 0000000000000000\nline = 5\n r11 = 0000000000000000\n r12 = 0000000000000000\n r13 = 0000000000000000\nline = 6\n r14 = 0000000000000000\n r15 = 0000000000000000\nline = 7\n iopl = 0\n FLAGS = ['nv', 'up', 'ei', 'pl', 'zr', 'na', 'po', 'nc']\nline = 8\n cs = 0033\n ss = 002b\n ds = 002b\n es = 002b\n fs = 0053\n gs = 002b\n efl = 00000246\nline = 9\n LABEL = lol+0x1000:\nline = 10\n mov rbx,0CE83520306878A4h = 48bba47868302035e80c\nline = 11\n rax = 0000000000000000\n rbx = 0000000000000000\n rcx = 0000000000000000\nline = 12\n rdx = 0000000000000000\n rsi = 0000000000000000\n rdi = 0000000000000000\nline = 13\n rip = 000000000040100a\n rsp = 0000000000000000\n rbp = 0000000000000000\nline = 14\n r8 = 0000000000000000\n r9 = 0000000000000000\n r10 = 0000000000000000\nline = 15\n r11 = 0000000000000000\n r12 = 0000000000000000\n r13 = 0000000000000000\nline = 16\n r14 = 0000000000000000\n r15 = 0000000000000000\nline = 17\n iopl = 0\n FLAGS = ['nv', 'up', 'ei', 'pl', 'zr', 'na', 'po', 'nc']\nline = 18\n cs = 0033\n ss = 002b\n ds = 002b\n es = 002b\n fs = 0053\n gs = 002b\n efl = 00000246\nline = 19\n LABEL = lol+0x1000:\nline = 20\n mov rbx,0CE83520306878A4h = 48bba47868302035e80c\n</code></pre>\n<p>Obviously, do something useful instead of just printing the information.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T22:19:34.990",
"Id": "248890",
"ParentId": "248861",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248890",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:09:54.247",
"Id": "248861",
"Score": "2",
"Tags": [
"python",
"regex"
],
"Title": "Simple text parser using regexes"
}
|
248861
|
<p>I'm currently going over <a href="https://algs4.cs.princeton.edu/24pq/" rel="nofollow noreferrer">Robert Sedgewick's Algorithms</a> book. For the implementation of A priority queue using a binary heap I implemented the code using ES6. I believe to have more experience with Ruby but I have come to enjoy working with ES-6 using classes.</p>
<p>I would like feedback on how can the code be improved, if there is anything that can be optimized, if am following best practices or if I'm breaking any principles.</p>
<pre><code> class Heap {
constructor() {
this.n = 0;
this.pq = [];
}
size() {
return this.n;
}
isEmpty() {
this.n === 0;
}
swim(k) {
while(k > 1 && this.less(Math.floor(k / 2), k)){
this.exch(Math.floor(k / 2), k);
k = Math.floor(k / 2)
}
}
sink(k) {
while(2 * k <= this.n) {
let j = 2 * k;
if(this.pq[j + 1] != null) {
if(k > 1 && this.less(j, j + 1)){
j++;
}
}
if(this.pq[k] > this.pq[j]) {
break;
}
this.exch(k, j)
k = j
}
}
insert(v) {
this.pq[++this.n] = v;
this.swim(this.n);
}
delMax() {
let max = this.pq[1];
this.exch(1, this.n--);
this.pq[this.n + 1] = null;
this.sink(1);
return max;
}
less(i, j) {
return this.pq[i] < this.pq[j];
}
exch(i, j) {
let temp = this.pq[i];
this.pq[i] = this.pq[j];
this.pq[j] = temp;
}
}
</code></pre>
<p>Here is some tests:</p>
<pre><code>let heap = new Heap();
heap.insert("t")
heap.insert("p")
heap.insert("r")
heap.insert("n")
heap.insert("h")
heap.insert("o")
heap.insert("a")
heap.insert("e")
heap.insert("i")
heap.insert("g")
heap.insert("s")
console.log(heap.isEmpty())
console.log(heap.size())
heap.delMax()
console.log(heap.pq)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:19:48.130",
"Id": "487663",
"Score": "1",
"body": "Class named `Heap` containing `pq` property seems like heap implemented using priority queue. It should be vice versa. And did you intentionally not implement \"build-heap\" and \"sort-heap\" algorithms? And im not sure if `a[a.length] = x` Is correct, you might want to push instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:52:42.453",
"Id": "487666",
"Score": "0",
"body": "Good point, yes it should be `class PQ` and the array `this.pq` that is the binary heap. The `a[a.length] = x` works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:49:42.090",
"Id": "487747",
"Score": "0",
"body": "It appears that the first element in the array `pq` is `undefined `. Is that intentional and/or desired?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T13:59:40.177",
"Id": "487751",
"Score": "1",
"body": "Yes, is intentional so that the element first element in the heap starts at index 1. Thus making easier to look for parent (k/2) and child (2*k & 2*k + 1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:25:24.173",
"Id": "487800",
"Score": "0",
"body": "Your API is somewhat inflexible. A priority queue associates entries with priorities, so the `insert` operation should be something like `insert(value, priority)`, where `priority` is some type that has a total order (e.g. `number`). An alternative that is sometimes used is to instantiate the PQ with a total ordering function, e.g. `const pq = new PQ((a, b) => a.length <= b.length)`, then you could do `pq.insert(\"Hello\")`, and would get a PQ for strings with priority based on their length. In your implementation, you are using the value also at the same time as the priority and the comparison"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:26:16.143",
"Id": "487801",
"Score": "0",
"body": "… is hard-coded, which means you can only use values that have a total order, and not only that, but they have to support the `<` operator. So, what happens if you want to, e.g. use an object as the value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:29:18.393",
"Id": "487802",
"Score": "0",
"body": "@JörgWMittag Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment). Protip: you can earn more reputation that way!"
}
] |
[
{
"body": "<h2>Formatting</h2>\n<p>The code formatting is fairly consistent in terms of line terminators, though there are a couple lines missing semi-colons - e.g. in <code>swim()</code> and <code>sink()</code>. While they are not always required it is best to be consistent.</p>\n<h2>Method without return value</h2>\n<p>The <code>isEmpty</code> method has no <code>return</code> keyword, nor any side effects:</p>\n<blockquote>\n<pre><code>isEmpty() {\n this.n === 0;\n}\n</code></pre>\n</blockquote>\n<p>Presumably it should <code>return</code> that boolean value.</p>\n<h2>Declaring variables</h2>\n<p><code>const</code> can be used for <code>max</code> since it never gets re-assigned. A recommended practice is to default to using <code>const</code> and then when re-assignment is deemed necessary then switch to <code>let</code>. This helps avoid accidental re-assignment.</p>\n<h2>Swapping values without a temporary variable</h2>\n<p>One could use <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">Destructuring assignment</a> to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Swapping_variables\" rel=\"nofollow noreferrer\">swap variables</a></p>\n<pre><code>exch(i, j) {\n [this.pq[i], this.pq[j]] = [this.pq[j], this.pq[i]];\n}\n</code></pre>\n<p>However it seems that can be slower than other techniques even though the V8 blog claims "<em>Once we unblocked escape analysis to eliminate all temporary allocation, array destructuring with a temporary array is as fast as a sequence of assignments.</em>"<sup><a href=\"https://v8.dev/blog/v8-release-68#performance\" rel=\"nofollow noreferrer\">1</a></sup>. There is a "hack" suggested in <a href=\"https://stackoverflow.com/a/16201730/1575353\">this SO answer by showdev</a> that <a href=\"https://jsperf.com/swap-array-vs-variable/9\" rel=\"nofollow noreferrer\">appears to be the fastest method to swap variables</a>:</p>\n<pre><code>this.pq[i] = [this.pq[j], (this.pq[j] = this.pq[i])][0];\n</code></pre>\n<h2>Using array length instead of variable <code>n</code></h2>\n<p>I could be wrong but it may be possible to eliminate the <code>n</code> variable and just utilize <code>this.pq.length</code> - it may require adjusting things (e.g. manually inserting <code>undefined</code> to the start of the array, etc.).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T20:52:59.710",
"Id": "248929",
"ParentId": "248862",
"Score": "2"
}
},
{
"body": "<h1>Naming</h1>\n<p>The name <code>Heap</code> is confusing, since this is a priority queue, not a heap. The heap is merely an internal private implementation detail that should not be exposed to the outside world. Just call it what it is: a <code>PriorityQueue</code>.</p>\n<p>The same applies to <code>heap</code>. This one is a local variable with limited scope and obvious semantics, so I would be fine with <code>pq</code> as a name in this case.</p>\n<p>Conversely, the <code>pq</code> field actually looks like it is a heap, not a priority queue, so it should probably be named <code>heap</code>.</p>\n<p><code>delMax</code> <em>sounds</em> like the method is deleting the highest priority element, but it is actually <em>popping</em> the highest priority element, i.e. it is returning it. <code>pull</code>, <code>poll</code>, <code>pop</code>, <code>getMax</code>, <code>dequeue</code> are all popular names for this operation.</p>\n<p>In fact, in the beginning, I thought you don't even provide this operation at all, since I was led amiss by the name. Even in your <em>own tests</em>, you actually ignore the return value!</p>\n<h1>Bug</h1>\n<p>Your <code>isEmpty()</code> method does not return anything. It is evaluating an expression and then throwing away the result. It should be something like this instead:</p>\n<pre><code>isEmpty() {\n return this.n === 0;\n}\n</code></pre>\n<h1>Testing</h1>\n<p>The above bug is actually caught be the very tests you posted in your question. That seems to indicate that you wrote those tests but are not running them, otherwise you would have noticed.</p>\n<p>You should regularly run your tests, ideally in an automated fashion and with automated verification of the results. I run my tests automatically every time I save, every time before I commit to my local Git repository, every time locally before I push to my remote Git repository and then again on the remote repository every time someone pushes to it, every time before and after a merge, every time before a release … you get the idea. Run them as often as possible.</p>\n<h1>Potential bug?</h1>\n<p>I have the feeling, although I have not tested it, that your priority queue will not deal well if I want to store <code>null</code> in it.</p>\n<h1>Triple equals</h1>\n<p>There is one place where you use the <em>Abstract Equality Comparison Operator</em> <code>==</code> or its negation <code>!=</code>. It is generally best if you forget about its existence and never use it.</p>\n<p>Always use the <em>Strict Equality Comparison Operator</em> <code>===</code> or its negation <code>!==</code> instead.</p>\n<h1>Consistency</h1>\n<p>Sometimes you use the Abstract Equality Comparison Operator and sometimes the Strict Equality Comparison Operator. Sometimes you use 4 spaces for indentation, sometimes 2. Sometimes you use the term <em>heap</em> and sometimes <em>priority queue</em> (or <code>pq</code>) to refer to the priority queue.</p>\n<h1>Getters</h1>\n<p><code>isEmpty</code> and <code>size</code> should probably be getters instead of normal methods:</p>\n<pre><code>get size() {\n return this.n;\n}\n\nget isEmpty() {\n return this.n === 0;\n}\n</code></pre>\n<p>And the tests need to change accordingly as well:</p>\n<pre><code>console.log(pq.isEmpty);\nconsole.log(pq.size);\n</code></pre>\n<h1>Use abstractions internally</h1>\n<p>I am a big fan of using public abstractions also internally. Not everybody agrees with this, though.</p>\n<p>So, personally, I would use the <code>size</code> getter in <code>isEmpty</code> instead of accessing the internal <code>n</code> field:</p>\n<pre><code>get isEmpty() {\n return this.size === 0;\n}\n</code></pre>\n<p>That way, if someone extends your class and overrides some parts of it with a different implementation that doesn't use an <code>n</code> field, <code>isEmpty</code> will still work unchanged.</p>\n<h1><code>const</code> over <code>let</code></h1>\n<p>When ECMAScript 2015 introduced <code>let</code> and <code>const</code>, the general sentiment was <code>let</code> is the new <code>var</code>, you should always use <code>let</code>. Personally, I disagree, and I think <code>const</code> should be the new <code>var</code>, and you should always <code>const</code> <em>unless</em> you really, really, really need to re-assign it and can't find a way around. Then, and only then, use <code>let</code>.</p>\n<p>In your code, <code>heap</code>, <code>max</code>, and <code>temp</code> are never reassigned, so you can use <code>const</code> for them instead.</p>\n<h1>Class fields</h1>\n<p><code>n</code> and <code>pq</code> should probably be <a href=\"https://github.com/tc39/proposal-class-fields\" rel=\"nofollow noreferrer\"><em>class fields</em></a>. Note that class fields are currently a Stage 3 proposal, which means that while it is highly likely that they will end up unchanged in the ECMAScript Language Specification, they have not been accepted <em>yet</em> and have definitely missed the window for the 2020 release.</p>\n<pre><code>class PriorityQueue {\n n = 0;\n pq = [];\n\n // no constructor needed, all fields already initialized\n}\n</code></pre>\n<h1>Private methods and fields</h1>\n<p><code>swim</code>, <code>sink</code>, <code>less</code>, and <code>exch</code> should be <a href=\"https://github.com/tc39/proposal-private-methods\" rel=\"nofollow noreferrer\"><em>private methods</em></a>, they shouldn't be part of the public API, same for the class field <code>n</code>.</p>\n<p><code>pq</code> (or <code>heap</code>) should probably also be private. You are using it externally in the tests, but I don't think this is something that should be exposed to the outside world.</p>\n<pre><code>class PriorityQueue {\n #n = 0;\n #heap = [];\n\n get size() {\n return this.#n;\n }\n\n get isEmpty() {\n return this.size === 0;\n }\n\n #swim(k) {\n while (k > 1 && this.#less(Math.floor(k / 2), k)) {\n this.#exch(Math.floor(k / 2), k);\n k = Math.floor(k / 2);\n }\n }\n\n #sink(k) {\n while (2 * k <= this.#n) {\n let j = 2 * k;\n\n if (this.#heap[j + 1] !== null) {\n if (k > 1 && this.#less(j, j + 1)) {\n j++;\n }\n }\n\n if (this.#heap[k] > this.#heap[j]) {\n break;\n }\n this.#exch(k, j);\n k = j;\n }\n }\n\n insert(v) {\n this.#heap[++this.#n] = v;\n this.#swim(this.#n);\n }\n\n getMax() {\n const max = this.#heap[1];\n this.#exch(1, this.#n--);\n this.#heap[this.#n + 1] = null;\n this.#sink(1);\n return max;\n }\n\n #less(i, j) {\n return this.#heap[i] < this.#heap[j];\n }\n\n #exch(i, j) {\n const temp = this.#heap[i];\n this.#heap[i] = this.#heap[j];\n this.#heap[j] = temp;\n }\n}\n</code></pre>\n<p>Note that private methods are also in Stage 3.</p>\n<h1>API limitations</h1>\n<p>As currently implemented, the values stored in your priority queue and the priorities assigned to the values are actually the same thing. This is very limiting:</p>\n<ul>\n<li>You cannot have an ordering of priorities that is different from the natural ordering of the values. For example, you cannot have a priority queue where the priority is based on the length of a string instead of its lexicographic ordering.</li>\n<li>You can only store values in your priority queue that <em>have</em> a total ordering. Note that in ECMAScript this is trivially true, because all objects are totally ordered with respect to each other, but the ordering is not always intuitive, or do you know offhand what the result of <code>{ b: "a", a: "b" } < ["a", 2]</code> is?</li>\n</ul>\n<p>Typically, priority queue implementations resolve this in one of two ways:</p>\n<ol>\n<li>Each value is associated with a numeric priority.</li>\n<li>The priority queue is instantiated with a comparison function that expresses the total ordering relation between the values.</li>\n</ol>\n<p>Solution #1 would mean that you change the signature or your <code>insert</code> method to something like this:</p>\n<pre><code>insert(v, p)\n</code></pre>\n<p>and then use <code>p</code> as the key for the heap.</p>\n<p>Solution #2 would mean that you change the signature of the constructor to something like this:</p>\n<pre><code>constructor(f)\n</code></pre>\n<p>and then use <code>f</code> inside <code>less</code> as the comparison function instead of <code><</code>.</p>\n<p>Here is a rough sketch of what that would look like for option #1, the only changes are in <code>insert</code> and <code>less</code>:</p>\n<pre><code>insert(v, p) {\n this.#heap[++this.#n] = { element: v, priority: p };\n this.#swim(this.#n);\n}\n\n#less(i, j) {\n return this.#heap[i].priority < this.#heap[j].priority;\n}\n</code></pre>\n<p>The usage would then look like this:</p>\n<pre><code>pq.insert("tally", 2);\npq.insert("plus", 1);\npq.insert("rust", 8);\npq.insert("no", 127);\n</code></pre>\n<p>The version for option #2 would look something like this:</p>\n<pre><code>#comparator;\n\nconstructor(f) {\n this.#comparator = f;\n}\n\n#less(i, j) {\n return this.#comparator(this.#heap[i], this.#heap[j]);\n}\n</code></pre>\n<p>And the usage like this:</p>\n<pre><code>const pq = new PriorityQueue((a, b) => a.length < b.length);\n</code></pre>\n<h1>Further API additions</h1>\n<p>Being a collection, your priority queue should implement the <em>Iterable</em> interface.</p>\n<p>All major data structures in the ECMAScript standard library have methods <code>entries</code>, <code>keys</code>, and <code>values</code>. It makes sense to conform to that interface as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T09:27:25.063",
"Id": "248954",
"ParentId": "248862",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:15:12.843",
"Id": "248862",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"ecmascript-6",
"priority-queue"
],
"Title": "JavaScript Priority Queue implementation using a binary heap"
}
|
248862
|
<p>In an app which it is possible to transfer money between accounts I have the following logic:</p>
<p>View:</p>
<pre><code>class GiftCardRegisterBuyConfirmationView(LoginRequiredMixin, generic.CreateView):
template_name = "giftcard/buy-card-modal-content.html"
model = BuyGiftCardOrder
form_class = BuyGiftCardOrderForm
success_url = reverse_lazy("giftcard:register-buy-list")
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
</code></pre>
<p>Form:</p>
<pre><code>class BuyGiftCardOrderForm(forms.ModelForm):
class Meta:
model = BuyGiftCardOrder
exclude = ('created_by', 'order_total_btc_value')
def clean(self):
cleaned_data = super().clean()
amount = self.cleaned_data.get("amount")
if amount:
with transaction.atomic():
try:
admin_wallet = Wallet.objects.filter(user__is_superuser=True).first()
user_wallet = Wallet.objects.select_for_update().get(user=self.user)
if user_wallet.balance - amount < 0:
raise Exception("Not enough balance")
if admin_wallet.pk == user_wallet.pk:
raise Exception("Admins can't buy cards. Create a normal account in order to buy one.")
user_wallet.transfer(
self.total_btc_price,
admin_wallet
)
except Exception as e:
self.add_error(None, ValidationError(f"Error: {e}"))
return cleaned_data
</code></pre>
<p>Model:</p>
<pre><code>class Wallet(models.Model):
currency = models.ForeignKey('Currency', on_delete=models.CASCADE)
balance = models.DecimalField(_('Balance'), max_digits=18, decimal_places=8, default=0)
holded = models.DecimalField(_('Holded'), max_digits=18, decimal_places=8, default=0)
unconfirmed = models.DecimalField(_('Unconfirmed'), max_digits=18, decimal_places=8, default=0)
label = models.CharField(_('Label'), max_length=100, blank=True, null=True, unique=True)
def __str__(self):
return u'{0} {1} "{2}"'.format(self.balance, self.currency.ticker, self.label or '')
def transfer(self, amount, deposite_wallet, reason=None, description=""):
if amount < 0:
raise ValueError('Invalid amount')
if self.balance - amount < 0:
raise ValueError('No money')
self.balance -= amount
self.save()
deposite_wallet.balance += amount
deposite_wallet.save()
</code></pre>
<p>This works correctly but the problem is that the transaction is happening at the form.</p>
<p>The correct way would be to handle the transfer operation in the view, but in the view, it should happen at the form_valid method. But in in the transfer operation, it would be possible that a user does not have enough money and from what I have researched, errors should not be handled after form is valid..</p>
<p>I could check for balance in form and perform the transfer operation in view. The problem I see is that they should happen within a transaction as it uses select_for_update and I see no way to keep object locked in form and view.</p>
<p>What is the best approach ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T13:34:20.897",
"Id": "487664",
"Score": "3",
"body": "Hey could you add the model to the question too? For example, the best solution may move some of your code to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:02:16.540",
"Id": "487669",
"Score": "0",
"body": "@Peilonrayz Just edited and added the model. It is already being validated in the model as well.. But how should this model side error be returned to the form in this case?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T12:17:58.253",
"Id": "248863",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Model and form validation in class based view"
}
|
248863
|
<p>I am working on an API wrapper for calls to a website. Each of several types of calls can take a large number of optional arguments, some of which contradict. In the interest of preventing the user from supplying incompatible parameters, I would like to verify that the arguments are correct before submitting the request.</p>
<p>However, the simplest technique to do so has resulted in the below nightmare, with several if-statements. I know this is not a best practice, but I am unsure what the best method to correct it would be. I know that using *kwargs would probably be involved, but I don't see how that would save me from verifying the arguments in much the same way as below. I have heard that I should probably wrap the arguments in a class, but I'm unsure how much of a better idea that is.</p>
<pre><code>def list_tag_alias(
self,
name_matches: str = None,
status: str = None,
order: str = None,
antecedent_tag: int = None,
consequent_tag: int = None,
limit: int = None,
before_page: int = None,
after_page: int = None,
page: int = None,
):
query_url = "tag_aliases.json?"
arguments = []
if name_matches != None:
arguments.append("search[name_matches]={}".format(name_matches))
if status != None:
assert status.lower() in (
"approved",
"active",
"pending",
"deleted",
"retired",
"processing",
"queued",
"blank",
), "status must be one of: approved, active, pending, deleted, retired, processing, queued, or blank."
arguments.append("search[status]={}".format(status.lower()))
if order != None:
assert order.lower() in (
"status",
"created_at",
"updated_at",
"name",
"tag_count",
), "order must be one of status, created_at, updated_at, name, tag_count"
arguments.append("search[order]={}".format(order.lower()))
if antecedent_tag != None:
assert 0 <= antecedent_tag <= 8
arguments.append(
"search[antecedent_tag][category]={}".format(str(antecedent_tag))
)
if consequent_tag != None:
assert 0 <= consequent_tag <= 8
arguments.append(
"search[consequent_tag][category]={}".format(str(consequent_tag))
)
if limit != None:
assert 0 <= limit <= 1000, "limit must be between 0 and 1000, inclusive"
arguments.append("limit={}".format(str(limit)))
if before_page != None:
assert (
after_page == None and page == None
), "only one of before_page, after_page, or page must be supplied."
assert before_page >= 0, "before_page must be greater than 0"
arguments.append("page=b{}".format(str(before_page)))
if after_page != None:
assert (
before_page == None and page == None
), "only one of before_page, after_page, or page must be supplied."
assert after_page >= 0, "after_page must be greater than 0"
arguments.append("page=a{}".format(str(after_page)))
if page != None:
assert (
before_page == None and after_page == None
), "only one of before_page, after_page, or page must be supplied."
arguments.append("page={}".format(str(page)))
query_url += "&".join(arguments)
request = WebRequest(state_info=self.state_info)
response = request.submit_request(query_url=query_url)
return response.json()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Don't assert; raise exceptions</h1>\n<p><code>assert</code> statements may be disabled by <a href=\"https://docs.python.org/using/cmdline.html#cmdoption-O\" rel=\"nofollow noreferrer\">flag</a> (<code>python -O ...</code>) or <a href=\"https://docs.python.org/using/cmdline.html#envvar-PYTHONOPTIMIZE\" rel=\"nofollow noreferrer\">environment variable</a>.</p>\n<p>Use <code>raise ValueError("status must be one of: approved...")</code> instead.</p>\n<h1>Don't test for equality with None</h1>\n<p><code>None</code> is a singleton value. You should use <code>status is not None</code> instead of <code>status != None</code>.</p>\n<p>You can just test the value directly, <code>None</code> is a false value. So <code>if status:</code> can be used instead of <code>if status != None:</code> or <code>if status is not None:</code>. Note: that other things test as false, such as <code>0</code>, <code>""</code>, and <code>[]</code>, so this test is not exactly the same.</p>\n<h1>Use enums</h1>\n<p>Strings are hard to use. Should you pass <code>"delete"</code>, <code>"deleted"</code>, or <code>"deleting"</code>, ... or maybe <code>"removed"</code>?</p>\n<p>Enumerations give you named constants to use. Your IDE may even help you autocomplete the constant name.</p>\n<pre><code>from enum import Enum\n\nclass Status(Enum):\n APPROVED = "approved"\n ACTIVE = "active"\n ...\n\n...\n if status:\n arguments.append("search[status]={}".format(status.value))\n</code></pre>\n<p>You can turn strings into enums like:</p>\n<pre><code> if status is not None and not isinstance(status, Status):\n status = Status(status.lower())\n</code></pre>\n<p>So the caller could pass in <code>"deleted"</code> or <code>"DELETED"</code> or <code>Status.DELETED</code> and they would all work, but if they passed in <code>"removed"</code>, you'd get a <code>ValueError: 'removed' is not a valid Status</code> exception. So you no longer have to manually test if the given <code>status</code> is a legal status word. (However, if not every status word is legal in a function, these would still need to be tested.)</p>\n<h1>Common functions</h1>\n<p>If you have several functions which take <code>before_page</code>, <code>after_page</code> and <code>page</code> arguments, you probably have the same validation requirements in each. You should call another method to validate these, something like:</p>\n<pre><code> self._validate_pages(before_page, after_page, page, arguments)\n</code></pre>\n<h1>Positional & keyword-only arguments</h1>\n<p>As it stands, a caller may try call <code>obj.list_tag_alias(None, None, "approved")</code> to list the approved tag aliases. But actually, that used <code>"approved"</code> as the <code>order</code> parameter; while <code>status</code> is the 3th argument, that includes <code>self</code> in the count.</p>\n<p>The correct call would be either <code>obj.list_tag_alias(None, "approved")</code>, or better, <code>obj.list_tag_alias(status="approved")</code>.</p>\n<p>You can deny the positional argument variant by forcing the parameters to be keyword-only parameters, by adding a <code>*</code> to the argument list:</p>\n<pre><code>def list_tag_alias(\n self,\n name_matches: str = None,\n *, # remaining parameters are keyword-only\n status: str = None,\n order: str = None,\n ...\n</code></pre>\n<p>Now you can call <code>obj.list_tag_alias("fred")</code> or <code>obj.list_tag_alias(status="approved")</code>, but <code>obj.list_tag_alias(None, "approved")</code> is an error:</p>\n<pre><code>TypeError: list_tag_alias() takes 1 positional argument but 2 were given\n</code></pre>\n<h1>Argument dictionary</h1>\n<pre><code> arguments = []\n ...\n arguments.append("search[name_matches]={}".format(name_matches))\n ...\n query_url += "&".join(arguments)\n</code></pre>\n<p>You are using <code>"...={}".format(...)</code> and <code>.append()</code> multiple times to create your argument list to produce the query string. Consider using a dictionary instead:</p>\n<pre><code> arguments = {}\n ...\n arguments["search[name_matches]"] = name_matches\n ...\n query_url += "&".join(f"{key}={value}" for key, value in arguments.items())\n</code></pre>\n<p>Bonus: using <code>f"...{value}"</code> is interpolating the value into a string, so <code>str()</code> calls for limit, tag, and page parameters are unnecessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T16:24:22.647",
"Id": "248876",
"ParentId": "248871",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "248876",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T14:47:21.660",
"Id": "248871",
"Score": "8",
"Tags": [
"python",
"design-patterns",
"parsing"
],
"Title": "Making argument parsing more streamlined and readable than if-statements"
}
|
248871
|
<p>As i am learning bash, i have written a small code which is nothing but a simple <code>ldapsearch</code> query which lists all the<code>memberNisNetgroup</code> under <code>Infra_Global</code> netgroup.</p>
<p>I am pulling the list out of the netgroup and iterating over the list with a <code>for loop</code> which works fine. I am just curious if the below code which works fine can have an improvement from the <code>bash</code> standard.</p>
<p>Would appreciate any help on this.</p>
<pre><code>#!/bin/bash
#
NTGRP=$(ldapsearch -h ldapServer -xLL -b "cn=Infra_Global,ou=Netgroup,ou=tdi,o=tdp" | awk '/^memberNisNetgroup/{print $2}'| cut -d"_" -f2-)
for netg in $NTGRP ;
do
echo "-- $netg --";
ldapsearch -h ldapServer -xLL -b "ou=Netgroup,ou=$netg,ou=location,ou=tdi,o=tdp" | awk '/,,/{print $2}' | tr -d '(),'
done
</code></pre>
<h2>Result:</h2>
<pre><code>---- SAT-GEN11 ----
inv0602.tdi.tdp.com
inv0557.tdi.tdp.com
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T18:06:53.243",
"Id": "248879",
"Score": "2",
"Tags": [
"bash",
"ldap"
],
"Title": "Pulling host list from ldapserach command from netgroup"
}
|
248879
|
<p>I'm trying to build up a toolset of best practices, so as this is my first complete program (if you can call it that) writen in c++, I know there's definitely better ways of doing things</p>
<pre><code>#include <iostream>
#include <string>
#include <limits>
using namespace std;
void buildGrid(char arr[]) {
string line = "---|---|---\n";
cout << " " << arr[0] << " | " << arr[1] << " | " << arr[2] << "\n" << line;
cout << " " << arr[3] << " | " << arr[4] << " | " << arr[5] << "\n" << line;
cout << " " << arr[6] << " | " << arr[7] << " | " << arr[8] << "\n";
}
bool checkLines(char a, char arr[9]) {
if (arr[0] == a && arr[1] == a && arr[2] == a) {
return true;
/*
x | x | x
---|---|---
3 | 4 | 5
---|---|---
6 | 7 | 8
*/
} else if (arr[3] == a && arr[4] == a && arr[5] == a) {
return true;
/*
0 | 1 | 2
---|---|---
x | x | x
---|---|---
6 | 7 | 8
*/
} else if (arr[6] == a && arr[7] == a && arr[8] == a) {
return true;
/*
0 | 1 | 2
---|---|---
3 | 4 | 5
---|---|---
x | x | x
*/
} else if (arr[0] == a && arr[3] == a && arr[6] == a) {
return true;
/*
x | 1 | 2
---|---|---
x | 4 | 5
---|---|---
x | 7 | 8
*/
} else if (arr[1] == a && arr[4] == a && arr[7] == a) {
return true;
/*
0 | x | 2
---|---|---
3 | x | 5
---|---|---
6 | x | 8
*/
} else if (arr[2] == a && arr[5] == a && arr[8] == a) {
return true;
/*
0 | 1 | x
---|---|---
3 | 4 | x
---|---|---
6 | 7 | x
*/
} else if (arr[0] == a && arr[4] == a && arr[8] == a) {
return true;
/*
x | 1 | 2
---|---|---
3 | x | 5
---|---|---
6 | 7 | x
*/
} else if (arr[2] == a && arr[4] == a && arr[6] == a) {
return true;
/*
0 | 1 | x
---|---|---
3 | x | 5
---|---|---
x | 7 | 8
*/
}
return false;
}
char whoUp(char a, char b, char c) {
if (c == a) {
c = b;
} else if (c == b) {
c = a;
}
return c;
}
int main() {
int input;
int spacesLeft = 9;
char gridPos[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
char first;
char second;
char c;
cout << "who goes first?(a-z): ";
cin >> first;
do {
c = cin.get();
} while (c != '\n');
cout << "who goes second?(a-z): ";
cin >> second;
do {
c = cin.get();
} while (c != '\n');
char up = first;
cout << "\nspaces left: " << spacesLeft << endl;
buildGrid(gridPos);
cout << up << ", choose a space(1-9): ";
while (!(cin >> input).fail()) {
input -= 1;
if (input < 0 || input > 8) {
cout << "invalid space\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} else if (gridPos[input] == first || gridPos[input] == second) {
cout << "space already taken\n";
cout << "\nspaces left: " << spacesLeft << endl;
cin.clear();cin.ignore (numeric_limits<streamsize>::max(), '\n');
} else {
spacesLeft--;
gridPos[input] = up;
bool check = checkLines(up, gridPos);
if (check == true) {
cout << "the winner is: " << up << endl;
break;
} else if (check == false) {
cout << "\nspaces left: " << spacesLeft << endl;
up = whoUp(first, second, up);
}
}
buildGrid(gridPos);
if (spacesLeft == 0) {
cout << "no more spaces left\n";
break;
}
cout << up << ", choose a space(1-9): ";
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T05:26:28.427",
"Id": "493779",
"Score": "0",
"body": "Please accept any answer, this questino is 1 month old"
}
] |
[
{
"body": "<p>Due to the simplicity, there isn't much you need to change, it's good but just a few suggestions</p>\n<h2>Don't use <code>using namespace std;</code></h2>\n<p>It is considered bad practice to have this in your program\nRefer to <a href=\"https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/#:%7E:text=The%20statement%20using%20namespace%20std%20is%20generally%20considered%20bad%20practice.&text=In%20the%20worst%20case%2C%20the,to%20resolve%20identifier%20name%20conflicts.\" rel=\"nofollow noreferrer\">this</a> link to understand why it is a bad practice and why you should avoid it</p>\n<h2>Display the board after the game is over</h2>\n<p>After a player as won, you shall display the board again with using <code>buildGrid(gridPos);</code> and then break, so you can see the end position of the game</p>\n<h2>Prefer using "\\n" over <code>std::endl</code></h2>\n<p>Both <code>endl</code> and <code>"\\n"</code> serve the same purpose in C++ – they insert a new line. However, the key difference between them is that <code>endl</code> causes flushing of the output buffer every time it is called, whereas <code>"\\n"</code> does not.</p>\n<p>While the difference is not obvious in smaller programs, endl performs significantly worse than \\n because of the constant flushing of the output buffer.</p>\n<p>source: <a href=\"https://www.educative.io/edpresso/what-is-the-difference-between-endl-and-n-in-cpp\" rel=\"nofollow noreferrer\">What is the difference between \\n and endl?</a></p>\n<h2>Clear the terminal after every turn</h2>\n<p>After the player makes a move, you can clear the whole terminal and then display the usual stuff rather than threading the whole thing.</p>\n<p>If you are on windows</p>\n<pre><code>system("CLS");\n</code></pre>\n<h2>Formate your code to make it look more legible</h2>\n<p>White spaces don't mean anything to the compiler, it is for the programmers' legibility.\nYou can use something like <a href=\"https://www.tutorialspoint.com/online_c_formatter.htm\" rel=\"nofollow noreferrer\">this online c++ code formatter</a> to make your code look better in 2-3 clicks</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T11:47:11.373",
"Id": "248912",
"ParentId": "248880",
"Score": "1"
}
},
{
"body": "<h2>General Observations</h2>\n<p>For someone who is new to coding you did pretty well, there are no global variables and that is excellent. There are functions, there could be more but still excellent. I for one believe you are following a best practice by embedding the code in an if statement within braces (<code>{</code> and <code>}</code>), it makes the code much easier to maintain.</p>\n<p>While I understand why you put the comments in that you did, the code would be more readable without them. Comments need to be maintained as well as code does.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>DRY Code</h2>\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n<p>By removing the comments we can see that there is repetition in the following function:</p>\n<pre><code>bool checkLines(char a, char arr[9]) {\n if (arr[0] == a && arr[1] == a && arr[2] == a) {\n return true;\n }\n else if (arr[3] == a && arr[4] == a && arr[5] == a) {\n return true;\n }\n else if (arr[6] == a && arr[7] == a && arr[8] == a) {\n return true;\n }\n else if (arr[0] == a && arr[3] == a && arr[6] == a) {\n return true;\n }\n else if (arr[1] == a && arr[4] == a && arr[7] == a) {\n return true;\n }\n else if (arr[2] == a && arr[5] == a && arr[8] == a) {\n return true;\n }\n else if (arr[0] == a && arr[4] == a && arr[8] == a) {\n return true;\n\n }\n else if (arr[2] == a && arr[4] == a && arr[6] == a) {\n }\n return false;\n}\n</code></pre>\n<p>The repetion can be reduced by having 2 additional functions, <code>checkRow(size_t firstColumnInRow)</code> and <code>checkColumn(size_t firstRowInColumn)</code>. There isn't enough diagonal repetiton to create a third function.</p>\n<pre><code>bool checkRow(char user, char arr[], size_t firstColumnInRow)\n{\n if (arr[firstColumnInRow] == user && arr[firstColumnInRow + 1] == user && arr[firstColumnInRow + 2] == user) {\n return true;\n }\n}\n\nbool checkColumn(char user, char arr[], size_t firstRowInColumn)\n{\n if (arr[firstRowInColumn] == user && arr[firstRowInColumn + 2] == user && arr[firstRowInColumn + 6] == user) {\n return true;\n }\n}\n\nbool checkLines(char a, char arr[9]) {\n size_t rowStarts[] = {0, 3, 6};\n for (size_t row = 0; row < sizeof(rowStarts) / sizeof(*rowStarts); row++)\n {\n if (checkRow(a, arr, rowStarts[row])) {\n return true;\n }\n }\n\n size_t columnStarts[] = {0, 1, 2};\n for (size_t column = 0; column < 3; column++)\n {\n if (checkColumn(a, arr, columnStarts[column])) {\n return true;\n }\n }\n\n if (arr[0] == a && arr[4] == a && arr[8] == a) {\n return true;\n\n }\n else if (arr[2] == a && arr[4] == a && arr[6] == a) {\n }\n return false;\n}\n</code></pre>\n<p>Using the DRY principle generally results in less code, it didn't happen this time because the sample size is so small. There are variations on this code that would result in less code, such as having <code>checkRow(size_t firstColumnInRow)</code> be <code>checkRows(char user, char arr[], size_t rowStarts[])</code> and move the loop into the function.</p>\n<h2>Always Check User Input</h2>\n<p>What a user enters may not be the correct type for the receiving variable, always check user input to see that it is correct, an example in this program is that when entering a box id number the user could use a character rather than a number (I did, the program just sat there).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:36:31.853",
"Id": "248914",
"ParentId": "248880",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248914",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:14:46.883",
"Id": "248880",
"Score": "7",
"Tags": [
"c++",
"tic-tac-toe"
],
"Title": "Managed to make Tic-Tac-Toe as someone who is new to coding"
}
|
248880
|
<p>I am learning some assembly for a compiler project I am working on and I have come across the Exponentiation by Squaring algorithm when it came to calculating x ^ n. To get a grasp on how the algorithm works before I add the operation to my code generation, I have written it out to see if it works.</p>
<p>Is my code optimum? and can it be improved on (such as reducing the number of line needed and efficiency?)</p>
<p>I am assembling with nasm and I am running on x86_64 linux</p>
<pre><code>; Function exp_by_squaring_iterative(x, n)
_ipow:
; set the x and y values
mov r8, 50 ; x
mov r9, 10 ; n
; check if n is 1
cmp r9, 1 ; compare n with 1
je _equalsOne ; goto equalsone if n is 1
jne _notEqualsOne ; goto noequalsone if n is not 1
; return 1
_equalsOne:
mov rax, r8
ret ; if n equals 1 return x
; if n < 0 then
_notEqualsOne:
cmp r9, 0 ; compare n with 0
jl _lessthan ; goto lessthan zero if x is less than zero
jnl _equalszero ; goto equalszero if n is equal to zero
_lessthan:
; x := 1 / x;
; n := -n;
xor rdx, rdx ; zero rdx
mov rax, 1 ; move 1 to rax
div r8 ; divide 1 / x
mov r8, rax ; move x back to r8
not r9 ; revers ns bits
; if n = 0 then return 1
_equalszero:
cmp r9, 0 ; compare n with zero
je _ezero ; go to ezero if n equals zero
jne _nzero ; go to nzero if n is not zero
_ezero: ; return 1
mov rax, 1 ; set rax as 1
ret ; return 1 if n is 0
; y := 1;
_nzero:
mov r10, 1 ; set r10 as 1, y
_loop1:
mov rax, r9 ; move n to rax
test al, 1 ; check if n is an odd number by testing the low bit
jz _even ; jump if even = lowest bit clear = zero
jnz _odd ; jump if odd = lowest bit set
; if n is even then
_even:
; x := x * x;
mov rax, r8 ; move x to rax
mul rax ; multiply x by itself
mov r8, rax ; move x back to r8
; n := n / 2;
mov rbx, 2 ; 2 to rbx
mov rax, r9 ; move n to rax
div rbx ; divide n by 2
mov r9, rax ; move n back
jmp _condition ; jump over odd since if even, was processed
; n is an odd number
_odd:
; y := x * y;
mov rax, r10 ; move y to rax
mul r8 ; multiply y by x
mov r10, rax ; move y back to r10
; x := x * x;
mov rax, r8 ; mov x to rax
mul rax ; multiply x by itself
mov r8, rax ; mov x back to r10
; n := (n – 1) / 2;
mov rax, r9 ; mov n to rax
sub rax, 1 ; minus 1 from n
mov rbx, 2 ; set rbx as 2
div rbx ; divide n by 2
mov r9, rax ; move n back to rax
; while n > 1 do
_condition:
cmp r9, 1 ; compare r9 with 1
jg _loop1 ; if 1 is greater than 1 then loop
; return x * y
mov rax, r8 ; move x to rax
mul r10 ; multiple x and y
ret ; return
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Testing for <code>n == 1</code> before handling a negative <code>n</code> seems like a bug. Consider what would have happen with <code>n == -1</code>:</p>\n<ol>\n<li><code>n</code> is not <code>1</code>. Branch to <code>_notEqualsOne</code>.</li>\n<li><code>n</code> is less than <code>0</code>. Branch to <code>_lessthan</code>. Now <code>n</code> becomes <code>1</code>.</li>\n<li>The code falls through all the way to <code>_loop1</code>.</li>\n<li><code>n</code> is odd. Branch to <code>_odd</code>.</li>\n<li><code>y</code> := x * y<code>; </code>x := x * x<code>; </code>n := 0`</li>\n<li><code>_condition</code> fails; fall through the <code>return x * y</code>.</li>\n</ol>\n<p>Now, this is bad: we are returning an inversed <em>cube</em> of the original <code>x</code>.</p>\n<p>Postpone equality for <code>1</code> testing until the negative case is handled.</p>\n</li>\n<li><p>Eliminate <code>_equalsOne</code> label:</p>\n<pre><code> cmp r9, 1\n jne _notEqualsOne\n\n mov rax, r8\n ret\n\n_notEqualsOne:\n</code></pre>\n</li>\n<li><p><code>cmp r9, 0</code> is executed twice. This is redundant (keep in mind that <code>jne</code> does not affect the flags):</p>\n<pre><code> cmp r9, 0\n jne _notZero\n ; next two lines is what your code does at _ezero\n mov rax, 1\n ret\n\n_notZero:\n jnl _positive\n ; handle a negative case here:\n ; x := 1/x\n ; n := -n\n ; and proceed with the _positive case\n ....\n\n_positive:\n ; A regular case. n > 1 is guaranteed.\n</code></pre>\n</li>\n<li><p>Again, <code>_even</code> and <code>_odd</code> lead to some code duplication. <code> x := x * x</code> and <code>n := n/2</code> are spelled out in both branches. Consider</p>\n<pre><code> test al, 1\n jz _even\n\n ; n is odd here\n ; y := x * y\n ; n := n - 1\n\n_even:\n ; x := x * x\n ; n := n / 2\n</code></pre>\n</li>\n<li><p>Division by 2 is better be a right shift. One instruction versus four; a definite win.</p>\n</li>\n<li><p><code>while n > 1</code> style loop looks more natural than <code>do ... while n > 1</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T06:43:12.717",
"Id": "487729",
"Score": "0",
"body": "I have to disagree with that last point. Rather, all loops should have the branch on the bottom, to avoid having an extra jump in the loop. A literal `while` loop in assembly just makes the code look like it naively transcribed from higher level code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:47:17.057",
"Id": "487733",
"Score": "0",
"body": "@harold readability is more important than a tiny performance increase when this code is clearly not optimized to squeeze out performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T17:27:46.790",
"Id": "487779",
"Score": "0",
"body": "@qwr it's not even more readable. Do-loops are *the most standard* pattern."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:55:52.680",
"Id": "248886",
"ParentId": "248882",
"Score": "2"
}
},
{
"body": "<h1>Handling <code>n < 0</code></h1>\n<p>The computation is entirely integer-based. When <code>x := 1 / x</code> is computed, that means the new <code>x</code> is <em>usually zero</em>, though if <code>x</code> was 1 to begin with then the new <code>x</code> is still 1.</p>\n<p>As it currently is, with an integer computation, handling negative <code>n</code> makes very little sense. It almost never gives a useful result. It makes more sense to just not handle that case at all - of course this saves code.</p>\n<h1>There are more ways to multiply than <code>mul</code></h1>\n<blockquote>\n<pre><code>; x := x * x;\n mov rax, r8 ; move x to rax\n mul rax ; multiply x by itself\n mov r8, rax ; move x back to r8\n</code></pre>\n</blockquote>\n<p>Unless you need the upper 64 bits of the 128 bit product, it is easier and more appropriate to use the 2-operand or 3-operand form (whichever applies) of <code>imul</code>. <code>imul</code> is described in the manual as a signed multiplication, but that only matters for "upper half" which is ignored in most cases. See for example <a href=\"https://stackoverflow.com/q/42587607/555045\">Why is imul used for multiplying unsigned numbers?</a>.</p>\n<p>So this code can be:</p>\n<pre><code>imul r8, r8\n</code></pre>\n<h1>Loading small constants into 64bit registers</h1>\n<p><code>mov rax, 1</code> is actually not the best way to set <code>rax</code> to 1, the best way is <code>mov eax, 1</code>.</p>\n<p>If the assembler honours the program text, <code>mov rax, 1</code> would be encoded as <code>48 c7 c0 01 00 00 00</code>, using a REX.W prefix and the C7-group <code>mov</code>. <code>mov eax, 1</code> does exactly the same thing (writes to 32bit registers are zero-extended) but can be encoded as <code>b8 01 00 00 00</code>, saving two bytes (a byte from REX prefix, and an extra byte because the B8-group <code>mov</code> can be used).</p>\n<p>Saving 2 bytes is not critial, but all else being equal, smaller code is better (faster to fetch, less pressure on code cache).</p>\n<h1>Comparing a register to zero</h1>\n<p><code>cmp r9, 0</code> is an obvious way to do it, but <code>test r9, r9</code> saves a byte.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T06:40:39.933",
"Id": "248905",
"ParentId": "248882",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T19:31:53.403",
"Id": "248882",
"Score": "2",
"Tags": [
"algorithm",
"mathematics",
"linux",
"assembly",
"nasm"
],
"Title": "Exponentiation by squaring in x64 Linux Assembly"
}
|
248882
|
<p>I have a data frame, which contains three columns:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(0)
dataframe = pd.DataFrame({'operation': ['data_a', 'data_b', 'avg', 'concat', 'sum', 'take_a', 'concat'],
'data_a': list(np.random.uniform(-1,1,[7,2])), 'data_b': list(np.random.uniform(-1,1,[7,2]))})
</code></pre>
<p><a href="https://i.stack.imgur.com/JydOP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JydOP.png" alt="dataframe in table format" /></a></p>
<p>Column 'operation' represent merge column, so if there is 'data_a' value in Column 'operation', it means take that particular row's data_a value, if there is 'avg' operation, then take the average of 'data_a' and 'data_b' of that particular row so on.</p>
<p>What I am expecting in the output, a new column contains the values as per the operation column's merge functions:</p>
<p><a href="https://i.stack.imgur.com/jS6gq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jS6gq.png" alt="merged data in table format" /></a></p>
<p>What I have tried:</p>
<pre><code>dataframe['new_column'] = 'dummy_values'
for i in range(len(dataframe)):
if dataframe['operation'].iloc[i] == 'data_a':
dataframe['new_column'].iloc[i] = dataframe['data_a'].iloc[i]
elif dataframe['operation'].iloc[i] == 'data_b':
dataframe['new_column'].iloc[i] = dataframe['data_b'].iloc[i]
elif dataframe['operation'].iloc[i] == 'avg':
dataframe['new_column'].iloc[i] = dataframe[['data_a','data_b']].iloc[i].mean()
elif dataframe['operation'].iloc[i] == 'sum':
dataframe['new_column'].iloc[i] = dataframe[['data_a','data_b']].iloc[i].sum()
elif dataframe['operation'].iloc[i] == 'concat':
dataframe['new_column'].iloc[i] = np.concatenate([dataframe['data_a'].iloc[i], dataframe['data_b'].iloc[i]], axis=0)
</code></pre>
<p>That is obviously not a good way to do this, It's very slow too. I am looking for more pandas version to do this task.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:32:40.530",
"Id": "487709",
"Score": "0",
"body": "Code Review requires [concrete code from a project, with enough code and / or context](https://codereview.meta.stackexchange.com/a/3652) for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please provide your real, actual function for a proper review. It's ok if the data is anonymized, just don't change the format. Every string can be replaced by a string, every int by an int, etc. Please don't change the function names though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:47:01.170",
"Id": "487710",
"Score": "0",
"body": "Hi, @Mast the problem statement is same, I can't post real values because it's nth dim so I just used np.random for values."
}
] |
[
{
"body": "<ol>\n<li><p>Wrap the logic in a function, then <code>.apply</code> that function.</p>\n</li>\n<li><p>Consider then doing another function lookup using a simple dictionary. This keeps your functions very short and simple.</p>\n</li>\n</ol>\n<p>Something like:</p>\n<pre><code>def _op_get_a(row):\n return row.data_a\n\ndef _op_get_b(row):\n return row.data_b\n\ndef _op_avg(row):\n return (row.data_a + row.data_b) / 2.0\n\ndef _op_sum(row):\n return row.data_a + row.data_b\n\ndef _op_concat(row):\n return np.concatenate([row.data_a, row.data_b], axis=0)\n\ndef process_row(row):\n return {\n 'data_a': _op_get_a,\n 'data_b': _op_get_b,\n 'avg': _op_avg,\n 'sum': _op_sum,\n 'concat': _op_concat,\n }[row.operation](row)\n\n# The "axis=1" is critical to apply this row-wise rather than column-wise\ndataframe['new_column'] = dataframe.apply(process_row, axis=1)\n</code></pre>\n<p>I haven't tested this code, but you get the idea. Supporting new row operations is as simple as writing it as a row-wise function and hooking it into the lookup dictionary. The code is written at the smallest possible unit and able to be individually documented without creating a big cluttered mess.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T17:34:35.690",
"Id": "249091",
"ParentId": "248884",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:18:15.673",
"Id": "248884",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"pandas"
],
"Title": "Pandas : Apply Merge operations from a column"
}
|
248884
|
<p>This is exercise 3.1.31. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a filter KamasutraCipher that takes two strings as command-line
argument (the key strings), then reads strings (separated by
whitespace) from standard input, substitutes for each letter as
specified by the key strings, and prints the result to standard
output. This operation is the basis for one of the earliest known
cryptographic systems. The condition on the key strings is that they
must be of equal length and that any letter in standard input must
appear in exactly one of them. For example, if the two keys are
THEQUICKBROWN and FXJMPSVLAZYDG, then we make the table</p>
<p>T H E Q U I C K B R O W N</p>
<p>F X J M P S V L A Z Y D G</p>
<p>which tells us that we should substitute F for T, T for F, H for X, X
for H, and so forth when filtering standard input to standard output.
The message is encoded by replacing each letter with its pair. For
example, the message MEET AT ELEVEN is encoded as QJJF BF JKJCJG. The
person receiving the message can use the same keys to get the message
back.</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>public class KamasutraCipher
{
public static void encrypt(String s, String t)
{
int m = s.length();
int n = t.length();
if (m != n)
{
throw new RuntimeException("The key lengths must be equal");
}
while (!StdIn.isEmpty())
{
String word = StdIn.readString();
int wordLength = word.length();
for (int i = 0; i < wordLength; i++)
{
for (int j = 0; j < m; j++)
{
if (String.valueOf(word.charAt(i)).equals(String.valueOf(s.charAt(j))))
{
String temp = word;
word = temp.substring(0,i) + String.valueOf(t.charAt(j)) + temp.substring(i+1);
}
else if (String.valueOf(word.charAt(i)).equals(String.valueOf(t.charAt(j))))
{
String temp = word;
word = temp.substring(0,i) + String.valueOf(s.charAt(j)) + temp.substring(i+1);
}
}
}
System.out.print(word + " ");
}
}
public static void main(String[] args)
{
encrypt(args[0], args[1]);
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdIn.html" rel="noreferrer">StdIn</a> is a simple API written by the authors of the book. I checked my program and it works.</p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>The implementation looks good, I just have a few suggestions.</p>\n<h2>Single-responsibility principle</h2>\n<p>The method <code>encrypt</code> seems to have a lot of responsibility:</p>\n<ol>\n<li>Reads the input from the user</li>\n<li>Encrypts the input</li>\n<li>Outputs the result to the console</li>\n</ol>\n<p>One definition of <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a> is "A class should have only one reason to change". But there are many reasons for <code>KamasutraCipher</code> to change:</p>\n<ol>\n<li>The input may come from <code>System.in</code>, file, database, etc.</li>\n<li>The library <code>StdIn</code> changes.</li>\n<li>The output needs to go to a file, etc.</li>\n<li>The output needs to be formatted nicely for the user</li>\n<li>etc..</li>\n</ol>\n<p>The only responsibility of <code>KamasutraCipher</code> should be to encrypt (or decrypt) a string and return the result.</p>\n<p>The interface can be refactored from this:</p>\n<pre><code>public class KamasutraCipher {\n public static void encrypt(String s, String t)\n}\n</code></pre>\n<p>To:</p>\n<pre><code>public class KamasutraCipher {\n public KamasutraCipher(String key1, String key2)\n public String encrypt(String s)\n}\n</code></pre>\n<p>Now the only reason for <code>KamasutraCipher</code> to change is for optimizations or if the Kamasutra algorithm changes, but the latter is not going to happen soon.</p>\n<p>All the logic for requesting the input and producing the output is pushed to the <code>main</code>.</p>\n<h2>Strings are immutable</h2>\n<p>In Java strings are immutable objects, and any modification to a string creates a new string. Therefore this part:</p>\n<pre><code>String temp = word;\nword = temp.substring(0,i) + String.valueOf(t.charAt(j)) + temp.substring(i+1);\n</code></pre>\n<p>Can be changed to:</p>\n<pre><code>word = word.substring(0,i) + t.charAt(j) + word.substring(i+1);\n</code></pre>\n<h2>Optimization</h2>\n<p>The complexity of the method <code>encrypt</code> is <code>O(m*n)</code> where <code>m</code> is the length of the input string and <code>n</code> is the length of the key. (ignoring the methods of <code>String</code> and the while loop).</p>\n<p>A more efficient way would be to use a map to store the string keys. For example, given the string keys <strong>ABC</strong> and <strong>FGH</strong>, the map would contain:</p>\n<ul>\n<li>A -> F</li>\n<li>B -> G</li>\n<li>C -> H</li>\n<li>F -> A</li>\n<li>G -> B</li>\n<li>H -> C</li>\n</ul>\n<p>The method <code>encrypt</code> then becomes a simple lookup on the map, reducing the complexity to <code>O(m)</code>:</p>\n<pre><code>public String encrypt(String s) {\n StringBuilder sb = new StringBuilder(s.length());\n for (int i = 0; i < s.length(); i++) {\n Character c = s.charAt(i);\n sb.append(keyMap.get(c));\n }\n return sb.toString();\n}\n</code></pre>\n<p><code>SpringBuilder</code> lets us save some memory by creating the result string more efficiently. <code>keyMap</code> is created in the constructor because the keys don't change after initialization.</p>\n<h2>Input validation</h2>\n<blockquote>\n<p>any letter in standard input must appear in exactly one of them (keys)</p>\n</blockquote>\n<p>As mentioned by others this is a requirement that needs to be handled, possibly in the method <code>encrypt</code>.</p>\n<p>For the exceptions you can use <code>IllegalArgumentException</code> instead of <code>RuntimeException</code>.</p>\n<h2>Refactored code</h2>\n<pre><code>public class KamasutraCipher {\n \n private final Map<Character,Character> keyMap;\n \n public KamasutraCipher(String key1, String key2) {\n if (key1.length() != key2.length()) {\n throw new IllegalArgumentException("The key lengths must be equal");\n }\n keyMap = new HashMap<>();\n for (int i = 0; i < key1.length(); i++) {\n keyMap.put(key1.charAt(i), key2.charAt(i));\n keyMap.put(key2.charAt(i), key1.charAt(i));\n }\n }\n \n public String encrypt(String s) {\n StringBuilder sb = new StringBuilder(s.length());\n for (int i = 0; i < s.length(); i++) {\n Character c = s.charAt(i);\n if(!keyMap.containsKey(c)) {\n throw new IllegalArgumentException(String.format("'%c' is not in the keys", c));\n }\n sb.append(keyMap.get(c));\n }\n return sb.toString();\n }\n\n public static void main(String[] args) {\n KamasutraCipher cipher = new KamasutraCipher(args[0], args[1]);\n while (!StdIn.isEmpty()) {\n String input = StdIn.readString();\n System.out.println(cipher.encrypt(input));\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:16:06.250",
"Id": "487730",
"Score": "2",
"body": "Since you know the length of the encoded string, you should consider setting the capacity of the `StringBuilder`: `new StringBuilder(s.length())`. Or just directly use a `char` array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:33:04.640",
"Id": "487731",
"Score": "1",
"body": "You just missed the point that any letter in standard input must appear in exactly one of the keys. Aside of that I have the same result as your sample but with `Stream` instead of loops."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T10:40:01.383",
"Id": "487739",
"Score": "0",
"body": "@RoToRa good point, I updated the answer with your suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T10:44:44.923",
"Id": "487740",
"Score": "0",
"body": "@gervais.b yep I missed that, answer updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:23:58.147",
"Id": "487744",
"Score": "1",
"body": "@Marc Thank you very much. I'm still not familiar to OOP (although I'm not sure whether you used it or not). I try to assimilate the above information gradually."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T02:51:19.990",
"Id": "248899",
"ParentId": "248885",
"Score": "14"
}
},
{
"body": "<p>Marc has covered much of the ground, but I'd like to point out a couple of things he didn't explicitly mention and add some further comments.</p>\n<ul>\n<li>"public static void encrypt(String s, String t)". Notice how Marc replaced the opaque names "s" and "t" with more meaningful ones. In general short names are not our friends. Marc's use of "s" as an argument name in his encrypt() method is, IMHO, OK in this context as the method's so short, but in general prefer longer more expressive names.</li>\n<li>"String.valueOf(word.charAt(i)).equals(String.valueOf(s.charAt(j)))"\nString.charAt(int) returns a <em>char</em> value, which is actually a (fairly) small integer. You don't need to wrap two <em>chars</em> in Strings and use String.equals() to compare them. You can just say "word.charAt(i) == s.charAt(j)".</li>\n<li>Neither your solution nor Marc's actually checks that the two keystrings share no characters, nor contain duplicates.</li>\n<li>The problem specification suggests that if the word to be encrypted contains a character not in the keystrings, it's an error. Neither your solution nor Marc's treats it as such.</li>\n</ul>\n<p>As an alternative to Marc's solution, I'll outline an alternative lookup strategy in place of Marc's Map. (I'm not going to code it - it would be a more useful exercise for you to do so.)</p>\n<p>If you create an array of chars of size Character.MAX_VALUE, you can populate it with substitute characters and simply access that using input characters as your index.\nUnassigned entries in the array (for characters not supplied in the key strings) will be initialised to the null character (<a href=\"https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5\" rel=\"noreferrer\">as per the language specification</a>).</p>\n<p>[Note: I have ignored surrogate code units on the assumption that the OPs input won't involve them...]</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:37:17.703",
"Id": "248908",
"ParentId": "248885",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "248899",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:34:00.280",
"Id": "248885",
"Score": "9",
"Tags": [
"java",
"beginner"
],
"Title": "Implementation of Kamasutra cipher"
}
|
248885
|
<p>Asking here instead of SO as suggested.</p>
<p>I'm trying to use Julia to solve the common tile game 15 Puzzle using Julia using A* algorithm. I am quite new to the language and my style may seem very C like. When I try the following code, I run out of memory. I'm not sure if its related to the use of a pointer style in my structs or just bad design.</p>
<pre><code>struct Node
parent
f::Int64
board::Array{Int64,1}
end
function findblank(A::Array{Int64,1})
x = size(A,1)
for i = 1:x
if A[i] == x
return i
end
end
return -1
end
function up(A::Array{Int64,1})
N = size(A,1)
Nsq = isqrt(N)
blank = findblank(A)
B = copy(A)
if blank / Nsq <= 1
return nothing
end
B[blank-Nsq],B[blank] = B[blank],B[blank-Nsq]
return B
end
function down(A::Array{Int64,1})
N = size(A,1)
Nsq = isqrt(N)
blank = findblank(A)
B = copy(A)
if (blank / Nsq) > (Nsq -1)
return nothing
end
B[blank+Nsq],B[blank] = B[blank],B[blank+Nsq]
return B
end
function left(A::Array{Int64,1})
N = size(A,1)
Nsq = isqrt(N)
blank = findblank(A)
B = copy(A)
if (blank % Nsq) == 1
return nothing
end
B[blank-1],B[blank] = B[blank],B[blank-1]
return B
end
function right(A::Array{Int64,1})
N = size(A,1)
Nsq = isqrt(N)
blank = findblank(A)
B = copy(A)
if (blank % Nsq) == 0
return nothing
end
B[blank+1],B[blank] = B[blank],B[blank+1]
return B
end
function manhattan(A::Array{Int64,1})
N = size(A,1)
Nsq = isqrt(N)
r = 0
for i in 1:N
if (A[i]==i || A[i]==N)
continue
end
row1 = floor((A[i]-1) / Nsq)
col1 = (A[i]-1) % Nsq
row2 = floor((i-1) / Nsq)
col2 = (i-1) % Nsq
r+= abs(row1 - row2) + abs(col1 - col2)
end
return r
end
# start = [1,2,3,4,5,6,7,9,8]
# start = [6,5,4,1,7,3,9,8,2] #26 moves
start = [7,8,4,11,12,14,10,15,16,5,3,13,2,1,9,6] # 50 moves
goal = [x for x in 1:length(start)]
# println("The manhattan distance of $start is $(manhattan(start))")
g = 0
f = g + manhattan(start)
pq = PriorityQueue()
actions = [up,down,left,right]
dd = Dict{Array{Int64,1},Int64}()
snode = Node(C_NULL,f,start)
enqueue!(pq,snode,f)
pos_seen = 0
moves = 0
while (!isempty(pq))
current = dequeue!(pq)
if haskey(dd,current.board)
continue
else
push!(dd, current.board =>current.f)
end
if (current.board == goal)
while(current.board != start)
println(current.board)
global moves +=1
current = current.parent[]
end
println(start)
println("$start solved in $moves moves after looking at $pos_seen positions")
break
end
global pos_seen+=1
global g+=1
for i in 1:4
nextmove = actions[i](current.board)
if (nextmove === nothing || nextmove == current.board || haskey(dd,nextmove))
continue
else
global f = g+manhattan(nextmove)
n = Node(Ref(current),f,nextmove)
enqueue!(pq,n,f)
end
end
end
println("END")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T21:13:59.930",
"Id": "487711",
"Score": "0",
"body": "Did you test the code with other testcases? Did it provide the correct output on those?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T21:29:05.487",
"Id": "487712",
"Score": "0",
"body": "Yes. [1,2,3,4,5,6,7,9,8] works fine.....as does [6,5,4,1,7,3,9,8,2]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T10:00:45.600",
"Id": "489100",
"Score": "0",
"body": "Please do not append code to your question, doing so goes against the Question + Answer style of Code Review. If you'd like a review of your latest version of the code please post a new question. Additionally please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)* for alternate options."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T15:24:18.380",
"Id": "491542",
"Score": "0",
"body": "@Gr3g-prog sorry to leave you waiting, you didn't ping me on SO, so I forgot."
}
] |
[
{
"body": "<p>It looks like you store the board after each movement for each possibility, that's a lot of arrays in memory, no wonder it fills your memory</p>\n<p>for your second example, your code looks for 157523 positions, which is half of the total possibilities.</p>\n<p>the number of permutations for <code>1:16</code> is enormous, the a-star algorithm is probably not sufficient</p>\n<p>even if you look at only 1% of the total possibilities, you would need hundreds of gigabytes if not terabytes to store them</p>\n<pre><code>[6, 5, 4, 1, 7, 3, 9, 8, 2] solved in 26 moves after looking at 157523 positions\n\njulia> using Combinatorics\n\njulia> length(permutations(1:9))\n362880\n\njulia> length(permutations(1:16))\n20922789888000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T04:51:45.103",
"Id": "489074",
"Score": "0",
"body": "Thanks @Marc. By comparison, the version I wrote in pure C only looks at 4434 positions and also solves in 26 moves. I'm sure that something is missing in my code but being new to Julia cant seem to put my finger on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T07:14:28.703",
"Id": "489086",
"Score": "0",
"body": "Works Now! Thanks again for insight."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T09:47:53.223",
"Id": "249149",
"ParentId": "248888",
"Score": "3"
}
},
{
"body": "<p>That was a fun exercise to work on! I completely refactored the code; the basic complexity issue Marc mentions still holds.</p>\n<p>I recommend <a href=\"https://julialang.org/blog/2016/02/iteration/\" rel=\"nofollow noreferrer\">this blog post</a> for the cartesian indexing tricks.</p>\n<pre><code># we need this include\nusing DataStructures\n\n\n# let's define some constants -- barcode is explained below\nconst Barcode = Int64 # can be switche out for a larger type if necessary\nconst Board = Matrix{Int64}\n\n# assuming `board` is a square matrix\nboardsize(board) = size(board, 1)\n\n# shorter version, altough we get rid of this below\n# by storing the blank position instead of recalculating\nfindblank(board) = findfirst(==(length(board)), board)\n\n# save some array allocation: instead of hashing, we can directly \n# encode each board permutation in a sufficiently large integer\n# by using the length of the board as basis of a number system\nfunction barcode(board)\n s = one(Barcode) # be type stable!\n bc = zero(Barcode)\n base = length(board)\n \n for n in board\n bc += n * s\n s *= base\n end\n\n return bc\nend\n\n# those four function can be generalized. we conveniently use \n# `CartesianIndex`s here, as in `manhattan`.\nfunction try_move(board, blank, action)\n delta = CartesianIndex(action...)\n moved = blank + delta\n \n if !checkbounds(Bool, board, moved)\n return nothing\n else\n new_board = copy(board)\n new_board[blank], new_board[moved] = new_board[moved], new_board[blank]\n return new_board, moved\n end\nend\n\n# I think I got this right... since we store the board as a matrix \n# anyway, we can directly access the indices.\nfunction manhattan(board)\n N = boardsize(board)\n \n return sum(CartesianIndices(board)) do ix\n row1, col1 = Tuple(ix)\n col2, row2 = divrem(board[ix] - 1, N) .+ 1 # column major!\n abs(row1 - row2) + abs(col1 - col2)\n end\nend\n\n\n# redo some things. storing the `f` here is not necessary; on the \n# other hand, we can get rid of recalculating the blank position and \n# and simply store it here, after every move.\n# the parent can become a small `Union`, no need for pointers\n# (never use `C_NULL` unless for interop!)\n# the barcodes also only need to be calculated once\nstruct Node\n board::Board\n blank::CartesianIndex\n parent::Union{Node, Nothing}\n barcode::Barcode\n\n function Node(\n board::Board,\n blank::CartesianIndex,\n parent::Union{Node, Nothing}\n )\n @assert size(board, 1) == size(board, 2)\n return new(board, blank, parent, barcode(board))\n end\nend\n\nNode(board, blank) = Node(board, blank, nothing)\n\n# factor out this loop into its own function -- it is not part of the \n# solution, but needed only once the solution is found\nfunction backtrace(node)\n current_node = node\n trace = Board[current_node.board]\n \n while !isnothing(current_node.parent)\n current_node = current_node.parent\n push!(trace, current_node.board)\n end\n\n return reverse(trace)\nend\n\n\n# since this remains global, make it a constant. also, it is of known\n# size and immutable, so a tuple is better\nconst ACTIONS = ((+1, 0), (-1, 0), (0, -1), (0, +1))\n\nfunction try_solve(start_board, goal_board)\n g = 0\n \n pq = PriorityQueue()\n start_node = Node(start_board, findblank(start_board))\n \n enqueue!(pq, start_node, manhattan(start_board))\n seen_barcodes = Set{Barcode}([start_node.barcode])\n goal_barcode = barcode(goal_board)\n\n # early return, since otherwise we only check immediately\n # after a move\n (start_node.barcode == goal_barcode) && return start_node, 1\n \n while !isempty(pq)\n g += 1\n current_node = dequeue!(pq)\n \n for action in ACTIONS\n move_result = try_move(current_node.board, current_node.blank, action)\n \n if !isnothing(move_result)\n moved_board, new_blank = move_result\n new_node = Node(moved_board, new_blank, current_node)\n \n if new_node.barcode == goal_barcode\n return new_node, length(seen_barcodes)\n elseif new_node.barcode ∉ seen_barcodes\n f = g + manhattan(moved_board)\n enqueue!(pq, new_node, f)\n push!(seen_barcodes, new_node.barcode)\n end\n end\n end\n end\n\n # I tried to keep `print`s out of the calculation function; this\n # one's useful for debugging, though:\n # println("Tried $(length(seen_barcodes)) boards")\n return nothing\nend\n\n# put main code into a function -- always put as many things into\n# functions as possible\nfunction main()\n # Again, Julia matrices are column major, so I needed to \n # transpose the boards to meaningfully work with the indexing\n\n # 0 moves\n # start_board = [\n # 1 4 7\n # 2 5 8\n # 3 6 9\n # ]\n\n # 4 moves\n # start_board = [\n # 1 9 4\n # 2 5 7\n # 3 6 8\n # ]\n \n # 26 moves\n # start_board = [\n # 6 1 9\n # 5 7 8\n # 4 3 2\n # ]\n \n # 50 moves\n start_board = [\n 7 12 16 2\n 8 14 5 1\n 4 10 3 9\n 11 15 13 6\n ]\n \n # quick way to initialize the reference matrix\n goal_board = reshape(1:length(start_board), size(start_board))\n\n println("The manhattan distance of the start board is $(manhattan(start_board))")\n \n # let's also print some time and memory statistics\n @time solution = try_solve(start_board, goal_board)\n \n if !isnothing(solution)\n solution_node, pos_seen = solution\n trace = backtrace(solution_node)\n\n println("Solved puzzle in $(length(trace)) moves after looking at $pos_seen positions. Steps: ")\n foreach(println, trace)\n else\n println("Failed to solve puzzle")\n println(start_board)\n end\nend\n\n# corresponds to `if __name__ == __main__` in Python; only run\n# `main()` when called as a script\nif abspath(PROGRAM_FILE) == @__FILE__\n main()\nend\n</code></pre>\n<p>A cool improvement would be to use <a href=\"https://julialang.org/blog/2019/07/multithreading/\" rel=\"nofollow noreferrer\">multithreading</a> for processing the queue. And one probably could also completely avoid storing the board as matrix by switching to the barcode representation everywhere (basically, a bitvector in a generalized basis) -- both left as an exercise. There are even <a href=\"https://en.wikipedia.org/wiki/Lehmer_code\" rel=\"nofollow noreferrer\">succinter codings for permuations</a>, though.</p>\n<p>I tried running the 50-moves problem, but killed the program at 1 GiB.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T08:35:03.763",
"Id": "499584",
"Score": "0",
"body": "Sorry for delay...got sidetracked on some other things. Great code style. Thanks for this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-11T15:23:42.950",
"Id": "250512",
"ParentId": "248888",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "250512",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T21:08:30.240",
"Id": "248888",
"Score": "3",
"Tags": [
"a-star",
"sliding-tile-puzzle",
"julia"
],
"Title": "Solving 15Puzzle with Julia"
}
|
248888
|
Handlebars is a simple templating language for JavaScript.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T22:30:03.917",
"Id": "248892",
"Score": "0",
"Tags": null,
"Title": null
}
|
248892
|
<p>I need to get familiar with web programming, so I decided to write up a fairly simple PHP page that accepts GET requests and serves back an image of the Mandelbrot set... as a table of colored cells.</p>
<p>Examples:</p>
<p><a href="https://i.stack.imgur.com/jl24a.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jl24a.png" alt="Mandelbrot Set Form Example" /></a></p>
<p>and</p>
<p><a href="https://i.stack.imgur.com/PBhDW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PBhDW.png" alt="Nicer Example" /></a></p>
<p>I'm sending the response as a table because I didn't want to get into using image libraries yet, so I wanted to try doing it entirely using HTML, and I couldn't think of a simpler way.</p>
<p>Basically how it works is, you indicate where in the Set you want to view by specifying the "Bounds" fields, the size of the view and table, the aspect ratio (as a decimal), then nine colored fields that decide how the image will be colored.</p>
<p>The main logic is essentially a port of my <a href="https://codereview.stackexchange.com/questions/217574/ascii-mandelbrot-set-image-producer">C code from last year</a>, and the coloring idea is pulled from a <a href="https://github.com/carcigenicate/mandelbrot" rel="noreferrer">project I did several years</a> ago in Clojure.</p>
<p>I'm looking for suggestions about anything. I haven't used HTML, PHP, or CSS is years, and I was never great with them to begin with. There's a lot here, so I don't expect super thorough reviews, but anything would be appreciated.</p>
<p>Specifically though:</p>
<ul>
<li><p>The function <code>new_color_f()</code> is a disaster. Basically, I want to be able to produce a function that has some parameters already set, and I'm doing that by closing over the parameters of the enclosing function. It's long and ugly though, and is made worse by PHP's <code>use</code> syntax. Any suggestions there would be appreciated.</p>
</li>
<li><p>The function <code>defaulting_get()</code> seems like a smell as well. I need to account for the GET data being missing, and potentially empty. That lead to using a bizarre mix of <code>??</code> and <code>?:</code> operators though.</p>
</li>
</ul>
<p>Anything except:</p>
<ul>
<li>Yes, this is stupid to do in PHP the way I am, and it's also stupid to do this using an HTML <code>table</code>. It causes issues with the input form being wiped every entry, and also causes incredible browser lag when receiving larger tables. I wanted to get some experience with PHP thought before I try something more complicated, and I've always loved this project. Really, I should be doing this in JavaScript, or using AJAX to request images instead of using a form.</li>
</ul>
<p>The server is running PHP 7.4 for reference.</p>
<hr />
<p><code>index.php</code></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mandelbrot Generator</title>
<style>
.display_table {
font-size: 1px;
border-spacing: 0;
}
.input_form {
display: table;
}
.input_row {
display: table-row;
}
.input_row label, .input_row input {
display: table-cell;
}
.red_input input, .green_input input, .blue_input input {
border-width: 5px;
}
.red_input input {
border-color: red;
}
.green_input input {
border-color: lightgreen;
}
.blue_input input {
border-color: blue;
}
</style>
</head>
<body>
<form method="get" class="input_form">
<div class="input">
<div class="location_input">
<div class="input_row">
<label>Lower Real Bound</label>
<input name="lreal" type="number" min="-2" max="2" step="any">
</div>
<div class="input_row">
<label>Lower Imaginary Bound</label>
<input name="limag" type="number" min="-2" max="2" step="any">
</div>
<div class="input_row">
<label>View Width</label>
<input name="vwidth" type="number" min="0" max="4" step="any">
</div>
<div class="input_row">
<label>Pixels Wide</label>
<input name="pwidth" type="number" min="0" max="1000" step="any">
</div>
<div class="input_row">
<label>Aspect Ratio</label>
<input name="aratio" type="number" min="0" max="2" step="any">
</div>
</div>
<div class="color_input">
<div class="red_input">
<div class="input_row">
<label>Real</label>
<input name="rr" type="number" min="-1000" max="1000" step="any">
</div>
<div class="input_row">
<label>Imaginary</label>
<input name="rim" type="number" min="-1000" max="1000" step="any">
</div>
<div class="input_row">
<label>Iters</label>
<input name="rit" type="number" min="-1000" max="1000" step="any">
</div>
</div>
<div class="green_input">
<div class="input_row">
<label>Real</label>
<input name="gr" type="number" min="-1000" max="1000" step="any">
</div>
<div class="input_row">
<label>Imaginary</label>
<input name="gim" type="number" min="-1000" max="1000" step="any">
</div>
<div class="input_row">
<label>Iters</label>
<input name="git" type="number" min="-1000" max="1000" step="any">
</div>
</div>
<div class="blue_input">
<div class="input_row">
<label>Real</label>
<input name="br" type="number" min="-1000" max="1000" step="any">
</div>
<div class="input_row">
<label>Imaginary</label>
<input name="bim" type="number" min="-1000" max="1000" step="any">
</div>
<div class="input_row">
<label>Iters</label>
<input name="bit" type="number" min="-1000" max="1000" step="any">
</div>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
<?php
include "display.php";
const DEF_LOW_REAL = -2;
const DEF_LOW_IMAG = -2;
const DEF_VIEW_WIDTH = 4;
const DEF_PIX_WIDTH = 100;
const DEF_ASP_RATIO = 1;
const DEF_COLOR_MULT = 2;
function defaulting_get($key, $default) {
return ($_GET[$key] ?? $default) ?: $default;
}
$low_real = defaulting_get("lreal", DEF_LOW_REAL);
$low_imag = defaulting_get("limag", DEF_LOW_IMAG);
$view_width = defaulting_get("vwidth", DEF_VIEW_WIDTH);
$pixels_wide = defaulting_get("pwidth", DEF_PIX_WIDTH);
$aspect_ratio = defaulting_get("aratio", DEF_ASP_RATIO);
$view_height = $view_width / $aspect_ratio;
$high_real = $low_real + $view_height;
$high_imag = $low_imag + $view_width;
$pixels_high = $pixels_wide / $aspect_ratio;
$color_f = new_color_f(
defaulting_get("rr", DEF_COLOR_MULT),
defaulting_get("rim", DEF_COLOR_MULT),
defaulting_get("rit", DEF_COLOR_MULT),
defaulting_get("gr", DEF_COLOR_MULT),
defaulting_get("gim", DEF_COLOR_MULT),
defaulting_get("git", DEF_COLOR_MULT),
defaulting_get("br", DEF_COLOR_MULT),
defaulting_get("bim", DEF_COLOR_MULT),
defaulting_get("bit", DEF_COLOR_MULT),
);
emit_mandelbrot_view(
$color_f,
$low_real,
$high_real,
$low_imag,
$high_imag,
$pixels_wide,
$pixels_high);
</code></pre>
<p><code>display.php</code></p>
<pre><code><?php
include "iteration.php";
const COLOR_MAX = (2 << 7) - 1;
function clamp_color($n) {
return max(0, min(COLOR_MAX, $n));
}
function checked_produce_rgb($red, $green, $blue) {
$c_red = clamp_color($red);
$c_green = clamp_color($green);
$c_blue = clamp_color(($blue));
return "rgb($c_red, $c_green, $c_blue)";
}
function new_color_f($red_real, $red_imag, $red_iter,
$gre_real, $gre_imag, $gre_iter,
$blu_real, $blu_imag, $blu_iter) {
$color_func = function($real, $imag, $iters) use
($red_real, $red_imag, $red_iter,
$gre_real, $gre_imag, $gre_iter,
$blu_real, $blu_imag, $blu_iter) {
return checked_produce_rgb(
$real * $red_real + $imag * $red_imag + $iters * $red_iter,
$real * $gre_real + $imag * $gre_imag + $iters * $gre_iter,
$real * $blu_real + $imag * $blu_imag + $iters * $blu_iter
);
};
return $color_func;
}
function produce_pixel($color) {
return "<td style='background: $color; color: $color'>_</td>";
}
function emit_mandelbrot_view($color_f,
$lower_real,
$upper_real,
$lower_imag,
$upper_imag,
$pixels_wide,
$pixels_high) {
$real_step = ($upper_real - $lower_real) / $pixels_wide;
$imag_step = ($upper_imag - $lower_imag) / $pixels_high;
echo "<table class='display_table'>";
for ($imag = $lower_imag; $imag <= $upper_imag; $imag += $imag_step) {
echo "<tr>";
for ($real = $lower_real; $real <= $upper_real; $real += $real_step) {
$iters = test_point([$real, $imag]);
$color = $color_f($real, $imag, $iters);
echo produce_pixel($color);
}
echo "</tr>";
}
echo "</table>";
}
</code></pre>
<p><code>iteration.php</code></p>
<pre><code><?php
// Make mutative?
const STD_MAX_ITERS = 200;
const STD_INF_LIMIT = 2;
function square_complex($complex) {
[$real, $imag] = $complex;
return [($real * $real) - ($imag * $imag),
2 * $real * $imag];
}
function mandelbrot_iteration($init_complex, $curr_complex) {
[$i_real, $i_imag] = $init_complex;
$sqrd = square_complex($curr_complex);
$sqrd[0] += $i_real;
$sqrd[1] += $i_imag;
return $sqrd;
}
function is_under_limit($complex, $inf_limit) {
[$real, $imag] = $complex;
return ($real * $real) + ($imag * $imag) <= ($inf_limit * $inf_limit);
}
function test_point($initial_complex,
$max_iters = STD_MAX_ITERS,
$inf_limit = STD_INF_LIMIT) {
$current = $initial_complex;
$i = 0;
for (; $i < $max_iters && is_under_limit($current, $inf_limit); $i++) {
$current = mandelbrot_iteration($initial_complex, $current);
}
return $i;
}
</code></pre>
|
[] |
[
{
"body": "<h2>User Interface</h2>\n<p>I noticed that if I entered values into the form and then submitted it, the values were not persisted after the next page load. It would be nice to have the values persisted in the form inputs. This is easy to achieve since the form is rendered by a PHP page.</p>\n<p>Because the PHP code towards the latter half of index.php comes after the HTML is closed, the HTML generated for the table is technically outside the HTML document:</p>\n<blockquote>\n<pre><code> </form>\n\n </body>\n</html>\n\n<table class='display_table'>\n</code></pre>\n</blockquote>\n<p>Most modern browsers would display the table as if it were inside the <code><body></code> tag but it isn't technically a valid structure. Using <a href=\"https://validator.w3.org/\" rel=\"nofollow noreferrer\">https://validator.w3.org/</a> with the generated source shows this output:</p>\n<p><a href=\"https://i.stack.imgur.com/If7EN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/If7EN.png\" alt=\"validation errors\" /></a></p>\n<p>A common convention is to have most of the PHP code at the top of the file - especially useful if there is functionality that modifies HTTP headers e.g. calls to <a href=\"https://php.net/header\" rel=\"nofollow noreferrer\"><code>header()</code></a> since headers cannot be sent after HTML has been emitted.</p>\n<blockquote>\n<p>Remember that <code>header()</code> must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.<sup><a href=\"https://www.php.net/manual/en/function.header.php\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>The HTML generated from the PHP calls (e.g. calls to <code>emit_mandelbrot_view()</code> which would need to <code>return</code> the generated HTML instead of calling <code>echo</code> directly) can be stored in a variable or emitted inline, optionally using the shortcut syntax for <a href=\"https://php.net/echo\" rel=\"nofollow noreferrer\"><code>echo</code></a> - i.e. <code><?=</code>:</p>\n<pre><code><?php\n//setup PHP code here\n?>\n<!DOCTYPE html>\n<html lang="en">\n <head>\n <!-- ... HTML headers here -->\n </head>\n <body>\n <form>\n <!-- ... HTML here -->\n </form>\n <?= emit_mandelbrot_view($color_f...)?>\n </body>\n</html>\n</code></pre>\n<h2>Code suggestions</h2>\n<blockquote>\n<ul>\n<li><code>new_color_f</code> is a disaster. Basically, I want to be able to produce a function that has some parameters already set, and I'm doing that by closing over the parameters of the enclosing function. It's long and ugly though, and is made worse by PHP's use syntax. Any suggestions there would be appreciated.</li>\n</ul>\n</blockquote>\n<p>Since you confirmed the server that the code runs on is using PHP 7.4 then the code can be updated to take advantage of newer features like <a href=\"https://www.php.net/manual/en/functions.arrow.php\" rel=\"nofollow noreferrer\">arrow functions</a></p>\n<blockquote>\n<p>Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic.</p>\n</blockquote>\n<p>This would allow the <code>use</code> statement to be eliminated in <code>new_color_f()</code>.</p>\n<hr />\n<p>The function <a href=\"https://www.php.net/range\" rel=\"nofollow noreferrer\"><code>range()</code></a> can be used with <code>foreach</code> to simplify the nested loops within <code>emit_mandelbrot_view()</code>:</p>\n<blockquote>\n<pre><code>for ($imag = $lower_imag; $imag <= $upper_imag; $imag += $imag_step) {\n echo "<tr>";\n for ($real = $lower_real; $real <= $upper_real; $real += $real_step) {\n</code></pre>\n</blockquote>\n<p>Can be simplified to:</p>\n<pre><code>foreach (range($lower_imag, $upper_imag, $imag_step) as $imag) {\n echo "<tr>";\n foreach (range($lower_real, $upper_real, $real_step) as $real) {\n</code></pre>\n<p>though given the amount of times that function is called it might not be advisable to add more function calls just to simplify the syntax.</p>\n<hr />\n<p>For this block in index.php:</p>\n<blockquote>\n<pre><code> $color_f = new_color_f(\n defaulting_get("rr", DEF_COLOR_MULT),\n defaulting_get("rim", DEF_COLOR_MULT),\n defaulting_get("rit", DEF_COLOR_MULT),\n defaulting_get("gr", DEF_COLOR_MULT),\n defaulting_get("gim", DEF_COLOR_MULT),\n defaulting_get("git", DEF_COLOR_MULT),\n defaulting_get("br", DEF_COLOR_MULT),\n defaulting_get("bim", DEF_COLOR_MULT),\n defaulting_get("bit", DEF_COLOR_MULT),\n );\n</code></pre>\n</blockquote>\n<p>Obviously there is a lot of duplication here. One simplification would be to put the query string keys into an array and loop over them, passing them to the function and storing the results in an array that can be <a href=\"https://www.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat\" rel=\"nofollow noreferrer\">spread</a> out into a call to <code>new_color_f()</code>.</p>\n<hr />\n<p>In <code>test_point()</code> the iterator is set up outside the loop:</p>\n<blockquote>\n<pre><code>$i = 0;\nfor (; $i < $max_iters && is_under_limit($current, $inf_limit); $i++) {\n $current = mandelbrot_iteration($initial_complex, $current);\n}\n</code></pre>\n</blockquote>\n<p>Unlike c code <code>$i</code> can be declared in the first statement of the <code>for</code> loop and still be visible outside the loop since variables aren't limited to a block but rather a function (if applicable). This isn't really explained well in the PHP documentation <a href=\"https://www.php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\"><em>variable scope</em></a> though <a href=\"https://www.php.net/manual/en/language.variables.scope.php#105925\" rel=\"nofollow noreferrer\">there is a comment about it</a>.</p>\n<blockquote>\n<p><a href=\"https://www.php.net/manual/en/language.variables.scope.php#1059250\" rel=\"nofollow noreferrer\">dodothedreamer at gmail dot com ¶</a> 8 years ago</p>\n<hr />\n<p>Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:</p>\n<pre><code><?php\nfor($j=0; $j<3; $j++)\n{\n if($j == 1)\n $a = 4;\n}\necho $a;\n?>\n</code></pre>\n<p>Would print 4.</p>\n</blockquote>\n<hr />\n<p>This constant definition looks like a C style optimization</p>\n<blockquote>\n<pre><code>const COLOR_MAX = (2 << 7) - 1; \n</code></pre>\n</blockquote>\n<p>Correct me if I am wrong but I doubt there is any optimization over declaring this as <code>255</code>:</p>\n<pre><code>const COLOR_MAX = 255;\n</code></pre>\n<p>P.S. I <a href=\"https://stackoverflow.com/q/63802712/1575353\">asked about that constant declaration on Stack Overflow</a>. From the responses so far it just seems to be personal preference as far as how the value is declared. If you prefer using the bit-shifted syntax then feel free to do so though be forewarned that if you were to work on a team with others that could come up as a question in a code review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T14:15:17.517",
"Id": "487849",
"Score": "0",
"body": "Thank you. I'm not sure how I didn't realize that I was creating the table outside of the document. What would be the typical way of setting this up? Putting everything from `include \"display.php\";` to the end of `$color_f = . . .` at the very top, then put the call to `emit_mandelbrot_view` inside its own set of `<?php` tags at the bottom of `body` (or wherever I want it in the document)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T23:36:06.727",
"Id": "248944",
"ParentId": "248895",
"Score": "3"
}
},
{
"body": "<h2>Types</h2>\n<p>It makes the code easier to understand if you specify types for all function signatures. PHP will check types if specified at runtime whenever entering and exiting a function, and when writing to a class property, helping you to detect and find errors much more quickly, especially if using an IDE or static analysis tool. They also help communicate the intent of your code to make it easier to add more to it.</p>\n<p>Some example changes to add types:</p>\n<p>In index.php, change <code>function defaulting_get($key, $default) {</code> to <code>function defaulting_get(string $key, int $default): int {</code></p>\n<p>In display.php, change <code>function clamp_color($n) {</code> to <code>function clamp_color(int $n): int {</code></p>\n<p>and</p>\n<pre><code> function new_color_f($red_real, $red_imag, $red_iter,\n $gre_real, $gre_imag, $gre_iter,\n $blu_real, $blu_imag, $blu_iter) {\n</code></pre>\n<p>to</p>\n<pre><code> /** @return \\Closure(int, int, int): string */\n function new_color_f(int $red_real, int $red_imag, int $red_iter,\n int $gre_real, int $gre_imag, int $gre_iter,\n int $blu_real, int $blu_imag, int $blu_iter): \\Closure {\n</code></pre>\n<p>I'm not sure if I've got the type of that closure quite right in the docblock.</p>\n<p>I would do this for every single function.</p>\n<h1>Avoiding <code>use</code></h1>\n<p>You can avoid the need for <code>use</code> by taking advantage of the short closure syntax introduced in PHP 7.4:</p>\n<pre><code> /** @return \\Closure(int, int, int): string */\n function new_color_f(int $red_real, int $red_imag, int $red_iter,\n int $gre_real, int $gre_imag, int $gre_iter,\n int $blu_real, int $blu_imag, int $blu_iter): \\Closure {\n return fn(int $real, int $imag, int $iters): string => \n checked_produce_rgb(\n $real * $red_real + $imag * $red_imag + $iters * $red_iter,\n $real * $gre_real + $imag * $gre_imag + $iters * $gre_iter,\n $real * $blu_real + $imag * $blu_imag + $iters * $blu_iter\n );\n };\n }\n</code></pre>\n<p>PHP automatically encloses any variables mentioned after the <code>=></code> in the short closure.</p>\n<h1>Classes and autoloading</h1>\n<p>Modern idiomatic PHP, particularly for larger applications, tends to have almost all code in the form of classes, even if the application isn't intended to be object-oriented. One advantage of using classes is that PHP's autoloading system can load them on demand. This is not available for free functions. Static functions on classes can be conveniently used in place of free functions.</p>\n<p>Replacing all the free functions with static class functions will also make it possible to mark any functions used only within the class that declares them as <code>private</code>, which should make it much easier to understand code flow.</p>\n<p>The typical way to use autoloading is to set up the project with Composer, organize the classes one per file, following PSR-4 rules for the location and name of each file, and make Composer generate an <em>autoload.php</em> file. This can be called with <code>require_once</code> from <code>index.php</code> or any other entry point. Any classes needed after that will be automatically loaded if they can be found.</p>\n<p>I would also make new_color_f return an object instead of a closure, and rename it accordingly. This object can have private fields instead enclosed variables, and a <code>getRGB</code> public function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T15:55:56.407",
"Id": "249315",
"ParentId": "248895",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248944",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T00:18:14.773",
"Id": "248895",
"Score": "7",
"Tags": [
"php",
"html",
"css",
"fractals"
],
"Title": "PHP Mandelbrot Set Generator"
}
|
248895
|
<p>I have this snippet, which computes on two columns, and if I get some increasing pattern then I will consider it a valid Key. How can I optimize this in pandas?</p>
<h3>Sample Code</h3>
<p>Here there is only one group of <code>track_id</code>. However, I will have many <code>track_id</code> groups, I need to apply the same for all groups.</p>
<pre><code>import pandas as pd
import numpy as np
tid = [5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.]
j = [ 0., 0., 0., 0., 0., 1., 52., 53., -1., -1., -1., -1., -1.,
-1., -1., -1., -1., 1., -1., -1., -1., -1., -1., -1., -1., -1.,
-1., -1.]
k = [ 0., 0., 0., 0., 0., -1., -1., -1., -1., -1., 56., 57., 58.,
59., 60., 61., 62., 63., -1., -1., -1., -1., -1., -1., -1., -1.,
-1., -1.]
rules = ['rule_1_start', 'rule_1_end']
data = {'rule_1_start': j, 'rule_1_end': k, 'track_id': tid }
df = pd.DataFrame.from_dict(data)
for r in range(0, len(rules), 2):
track_groups = df.groupby('track_id')
for key, item in track_groups:
_min = np.argmin(item[rules[r]].values)
_max = np.argmax(item[rules[r+1]].values)
if _min < _max:
print(f"{key}")
</code></pre>
<h3>The pattern</h3>
<p>I am trying to find is something like this. If you see these two columns, there is increasing value pattern. Col 1 has <code>77, 78,79</code> and col 2 has <code>82-91</code>. The pattern should be increasing from col1 to col2 but not vice versa.</p>
<p><a href="https://i.stack.imgur.com/8TKxE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8TKxE.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T05:36:28.670",
"Id": "487722",
"Score": "2",
"body": "The title of your question is too generic to be useful. The standard on this site is to simply state the task accomplished by the code, rather then your concerns about it. Also the question \"how to run as lambda in python\" seems to imply that something is not implemented and that may attract close votes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T06:04:28.380",
"Id": "487724",
"Score": "2",
"body": "Please show us more of your code. What does `df` actually look like? Not just an image of some of the columns, but ideally as code (or how to generate a toy example)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T13:32:02.110",
"Id": "487750",
"Score": "0",
"body": "updated with sample valid set, for simplicity I am just keeping one group."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T00:22:31.310",
"Id": "248896",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Computing on two colums"
}
|
248896
|
<p>I'm working through Stanford's algorithms course on edX.</p>
<p>One of the programming assignments is to find strongly connected components using Kosaraju's algorithm, on a graph with ~875,000 vertices. My implementation is the most basic translation from the textbook's pseudo code into Python, and it works fine on smaller graphs, so I think it's correct.</p>
<p>With Python's default recursion limit of 1000 it reaches the limit.</p>
<p>I've tried <code>sys.setrecursionlimit(1000000)</code>, but that doesn't help, and instead I get "Process finished with exit code -1073741571" which is a stack overflow.</p>
<pre><code>G = {}
for i in range(1, 875715):
G[i] = [0] #Each dictionary entry is a list. The first element of the list is 0 if the vertex is unexplored, otherwise 1.
for l in open('SCC.txt'):
items = list(map(int, l.split()))
G[items[0]].append(items[1])
Grev = {} #The same graph, with the edges reversed.
for i in range(1, 875715):
Grev[i] = [0]
for l in open('SCC.txt'):
items = list(map(int, l.split()))
Grev[items[1]].append(items[0])
def TopoSort(G): #Topological sort on the reversed graph.
for v in G:
if G[v][0] == 0:
DFStopo(G, v)
def DFStopo(G, s):
G[s][0] = 1
global orderedVertexList #The order in which to run DFS and assign SCCs.
for v in G[s][1:]:
if G[v][0] == 0:
DFStopo(G, v)
orderedVertexList.insert(0, s)
def Kosaraju(G, Grev):
TopoSort(Grev)
global numSCC
for v in orderedVertexList:
if G[v][0] == 0:
numSCC = numSCC + 1
DFSSCC(G, v)
def DFSSCC(G, s):
G[s][0] = 1
global SCC
SCC.append(numSCC) #The submission only requires the size of the five largest SCCs, so order doesn't matter.
for v in G[s][1:]:
if G[v][0] == 0:
DFSSCC(G, v)
numSCC = 0
orderedVertexList = []
SCC = []
Kosaraju(copy.deepcopy(G), copy.deepcopy(Grev))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T06:13:21.547",
"Id": "487725",
"Score": "1",
"body": "[Initially asked on SO](https://stackoverflow.com/q/63732271#comment112699640_63732271)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T05:42:16.813",
"Id": "248900",
"Score": "1",
"Tags": [
"algorithm",
"recursion",
"graph"
],
"Title": "Finding strongly connected components in a directed graph using Kosaraju's algorithm"
}
|
248900
|
<p>I have a potentially long running operation and I want to trigger some action if takes too long time. Also I want to reuse this logic. Operation to check:</p>
<pre><code>public static async Task Do(CancellationToken ct, TimeSpan actionDuration)
{
await Task.Delay(actionDuration, ct);
Debug.WriteLine("action finished");
}
</code></pre>
<p>Example of usage:</p>
<pre><code>[Fact]
public async Task AsyncTaskMethodWithoutException_LongerThanCheck_CheckTriggeredActionSucceed()
{
Func<Task> action = () => Do(CancellationToken.None, TimeSpan.FromMilliseconds(300));
var checkResult = await action.Check(TimeSpan.FromMilliseconds(100),
() => { Debug.WriteLine("too long"); return Task.CompletedTask; },
CancellationToken.None);
checkResult.IsOnTooLongFired.Should().BeTrue();
checkResult.ActionTask.Status.Should().Be(TaskStatus.RanToCompletion);
checkResult.CheckTask.Status.Should().Be(TaskStatus.Canceled);
}
</code></pre>
<p>Here is my code:</p>
<pre><code>public class TooLongCheckResult
{
public static TooLongCheckResult ActionFailedInstantly = new TooLongCheckResult(Task.CompletedTask, Task.CompletedTask);
public TooLongCheckResult(Task actionTask, Task checkTask)
{
ActionTask = actionTask;
CheckTask = checkTask;
}
public Task ActionTask { get; }
public Task CheckTask { get; }
public bool IsOnTooLongFired { get; private set; }
public void OnTooLongFired() => IsOnTooLongFired = true;
}
public sealed class TooLongCheckResult<T>
{
public static TooLongCheckResult<T> ActionFailedInstantly = new TooLongCheckResult<T>(Task.CompletedTask, Task.CompletedTask);
public TooLongCheckResult(Task actionTask, Task checkTask)
{
ActionTask = actionTask;
CheckTask = checkTask;
}
public Task ActionTask { get; }
public Task CheckTask { get; }
public bool IsOnTooLongFired { get; private set; }
public T Result { get; private set; }
public void SetResult(T result) => Result = result;
public void OnTooLongFired() => IsOnTooLongFired = true;
}
public static class TooLongTaskExt
{
public static async Task<TooLongCheckResult> Check(this Func<Task> action, TimeSpan tooLongThreshold, Func<Task> onTooLong, CancellationToken ct)
{
var childCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
childCts.CancelAfter(tooLongThreshold);
Task actionTask;
try
{
actionTask = action.Invoke();
}
catch (Exception ex)
{
//most likely it's because method in action isn't declared with async keyword
Debug.WriteLine("instant error: " + ex.GetType().Name);
return TooLongCheckResult.ActionFailedInstantly;
}
var timerTask = Task.Delay(Timeout.InfiniteTimeSpan, childCts.Token);
var result = new TooLongCheckResult(actionTask, timerTask);
var firstFinished = await Task.WhenAny(timerTask, actionTask);
if (firstFinished == timerTask)
{
await onTooLong.Invoke();
result.OnTooLongFired();
}
else
{
childCts.Cancel();
}
try
{
await Task.WhenAll(timerTask, actionTask);
}
catch (TaskCanceledException)
{
Debug.WriteLine("cancellation is triggered");
}
catch (Exception ex)
{
Debug.WriteLine("awaited error: " + ex.GetType().Name);
throw;
}
Debug.WriteLine("actionTask: " + actionTask.Status);
Debug.WriteLine("timerTask: " + timerTask.Status);
return result;
}
public static async Task<TooLongCheckResult<T>> CheckWithResult<T>(this Func<Task<T>> action, TimeSpan tooLongThreshold, Func<Task> onTooLong, CancellationToken ct)
{
var childCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
childCts.CancelAfter(tooLongThreshold);
Task<T> actionTask;
try
{
actionTask = action.Invoke();
}
catch (Exception ex)
{
//most likely it's because method in action isn't declared with async keyword
Debug.WriteLine("instant error: " + ex.GetType().Name);
return TooLongCheckResult<T>.ActionFailedInstantly;
}
var timerTask = Task.Delay(Timeout.InfiniteTimeSpan, childCts.Token);
var result = new TooLongCheckResult<T>(actionTask, timerTask);
var firstFinished = await Task.WhenAny(timerTask, actionTask);
if (firstFinished == timerTask)
{
await onTooLong.Invoke();
result.OnTooLongFired();
}
else
{
childCts.Cancel();
}
try
{
await Task.WhenAll(timerTask, actionTask);
}
catch (TaskCanceledException)
{
Debug.WriteLine("cancellation is triggered");
}
catch (Exception ex)
{
Debug.WriteLine("awaited error: " + ex.GetType().Name);
throw;
}
Debug.WriteLine("actionTask: " + actionTask.Status);
Debug.WriteLine("timerTask: " + timerTask.Status);
if (actionTask.Status == TaskStatus.RanToCompletion)
{
result.SetResult(actionTask.Result);
}
return result;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a suggestion to consider as improvement.</p>\n<p>Abstract example:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public static class TaskExtensions\n{\n public static Task InvokeAfterAsync(this Task task, double thresholdMilliseconds, Func<Task> callbackAsync, CancellationToken token = CancellationToken.None)\n => task.InvokeAfterAsync(TimeSpan.FromMilliseconds(thresholdMilliseconds), callbackAsync, token);\n\n public static async Task InvokeAfterAsync(this Task task, TimeSpan threshold, Func<Task> callbackAsync, CancellationToken token = CancellationToken.None)\n {\n using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(token))\n {\n Task fastTask = await Task.WhenAny(task, Task.Delay(threshold, cts.Token));\n if (fastTask != task)\n {\n await Task.WhenAll(callbackAsync(), task);\n }\n else\n {\n cts.Cancel();\n }\n }\n }\n}\n</code></pre>\n<p>Possible usage</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>await DoMyJobAsync().InvokeAfterAsync(100, myCallbackAsync);\n</code></pre>\n<ul>\n<li>CTS implements <code>IDisposable</code>, consider to <code>Dispose()</code> it or decorate with <code>using</code> statement.</li>\n<li>Don't use shorten names if possible. Make code more readable.</li>\n<li>Use less <code>var</code> statements. Use it only with <code>= new</code> if you want to store exactly the same type (not interface or parent type), otherwise avoid it. (but it's up to you)</li>\n<li>Let exceptions to be handled outside. E.g. if caller want to <code>Cancel()</code> its own CTS, it must care about to <code>catch</code> the exception.</li>\n<li>Use method overloads and default values to simplify the method usage.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:42:40.357",
"Id": "248938",
"ParentId": "248902",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248938",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T06:10:17.017",
"Id": "248902",
"Score": "1",
"Tags": [
"c#",
"task-parallel-library"
],
"Title": "C# extension method to do some action if a target operation takes too long time to finish"
}
|
248902
|
<p>I'm building an android application and I have some second thoughts on some error handling case.</p>
<p>I have a method that gets data from the internet by calling this method:</p>
<pre><code>public static string StoredDatesList
{
get => Preferences.Get(nameof(StoredDatesList), string.Empty);
set => Preferences.Set(nameof(StoredDatesList), value);
}
public static async Task<string> GetDraws(Uri url, string date)
{
Dictionary<string, string> StoredDates = new Dictionary<string, string>();
StoredDates = JsonConvert.DeserializeObject<Dictionary<string, string>>(StoredDatesList);
var contents = string.Empty;
HttpClient client = new HttpClient();
if (StoredDates != null)
if (StoredDates.ContainsKey(date))
{
contents = StoredDates[date];
}
else
{
var current = Connectivity.NetworkAccess;
if (current != NetworkAccess.Internet)
return null;
client = new HttpClient();
contents = await client.GetStringAsync(url);
var res2 = JsonConvert.DeserializeObject<RootObject>(contents.ToString());
if (180 == res2.content.Count)
{
StoredDates.Add(date, contents);
StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented);
}
}
else
{
StoredDates = new Dictionary<string, string>();
contents = await client.GetStringAsync(url);
var res2 = JsonConvert.DeserializeObject<RootObject>(contents.ToString());
if (180 == res2.content.Count)
{
StoredDates.Add(date, contents);
StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented);
}
}
return contents;
}
</code></pre>
<p>the <code>if</code> statement <code>current != NetworkAccess.Internet</code>
checks if internet is available. When internet is not available I return null and I check if the data is null and display a message(error, internet is not available etc).<br />
I find this approach very bad and I'm trying to think how is the proper way to handle this. I cannot show a message to the user from the <code>GetDraws()</code> function.</p>
<p>Maybe the correct way for this approach is to have a public variable like <code>bool internetError = false;</code> and to make if false every time I call <code>GetDraws()</code>, make it true if internet is not available and check its state after <code>GetDraws()</code>?<br />
Or should I return as result of <code>GetDraws()</code> the error and check first if the result match of any errors?</p>
<p>Internet connection is not necessary every time <code>GetDraws()</code> is used and that is why I'm not checking before I called this function for internet connection</p>
<p><strong>EDIT:</strong> My implementation i decided to be this:</p>
<pre><code> #region Setting Error Constants
public const string Common_Error_NoInternetConnection = "Error_NoInternetConnection";
#endregion
static MainApplication ApplicationState = (MainApplication)Application.Context;
public static string StoredDatesList
{
get => Preferences.Get(nameof(StoredDatesList), string.Empty);
set => Preferences.Set(nameof(StoredDatesList), value);
}
public static async Task<string> GetDraws(Uri url, string date)
{
var StoredDates = JsonConvert.DeserializeObject<Dictionary<string, string>>(StoredDatesList);
var contents = string.Empty;
if (StoredDates == null)
StoredDates = new Dictionary<string, string>();
if (StoredDates.ContainsKey(date))
{
contents = StoredDates[date];
}
else
{
if (IsInternetEnabled())
contents = await DownloadResults(url, date, StoredDates, contents).ConfigureAwait(false);
else
return Settings.Common_Error_NoInternetConnection;
}
return contents;
}
private static bool IsInternetEnabled()
{
return Connectivity.NetworkAccess == NetworkAccess.Internet;
}
private static async Task<string> DownloadResults(Uri url, string date, Dictionary<string, string> StoredDates, string contents)
{
using (var client = ApplicationState.GlobalHTTPClient)
{
contents = await client.GetStringAsync(url).ConfigureAwait(false);
var res2 = JsonConvert.DeserializeObject<RootObject>(contents);
if ((int)DailyDrawsEnum.AllDraws == res2.content.Count)
{
StoredDates.Add(date, contents);
StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented);
}
return contents;
}
}
public class MainApplication : Application
{
// Global objects to share data between activities
public MainApplication(IntPtr handle, JniHandleOwnership transer)
: base(handle, transer)
{
}
public HttpClient GlobalHTTPClient { get; } = new HttpClient(new HttpRetryMessageHandler(new HttpClientHandler()));
}
public class HttpRetryMessageHandler : DelegatingHandler
{
public HttpRetryMessageHandler(HttpClientHandler handler) : base(handler) { }
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) =>
Policy
.Handle<HttpRequestException>()
.Or<TaskCanceledException>()
.OrResult<HttpResponseMessage>(x => !x.IsSuccessStatusCode)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)))
.ExecuteAsync(() => base.SendAsync(request, cancellationToken));
}
</code></pre>
<p>And when internet is not available i return a string error code which i check if exist and if yes, i display a message to the user:</p>
<pre><code>contents = await GetDrawsFunctions.GetDraws(url, dates[datesPos]);
if (contents == Settings.Common_Error_NoInternetConnection)
{
((MainActivity)Activity).ShowNoInternetConnectionSnackbarMessage();
return -1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T10:53:11.947",
"Id": "487834",
"Score": "0",
"body": "Please add a description of what `GetDraws()` is to accomplish (the source code would have been a favourable place)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:00:31.940",
"Id": "487835",
"Score": "0",
"body": "I have post the source code of GetDates() get dates return a list of strings if the data exists on the DB or download them if they are not available. If they are not available and internet connection is not available im trying to figure out the best way to handle it and display an error to the user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:01:51.937",
"Id": "487836",
"Score": "0",
"body": "My question is: if another function is calling GetDates() how i should handle the errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T06:08:03.590",
"Id": "487988",
"Score": "0",
"body": "_[`HttpClient`](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#examples) is intended to be instantiated once per application, rather than per-use._ And you don't need to call `.ToString()` for `string` members because `string.ToString()` has no sense if you pass no arguments there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T06:11:11.900",
"Id": "487989",
"Score": "1",
"body": "Oh i haven't thought about it. I can have only one in the application state and use only that one everywhere"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:23:24.817",
"Id": "488023",
"Score": "0",
"body": "@aepot i have update the question with the code i use now and your idea, how do you find it?\nthe app is MUCH faster now with only one HTTP client, sometimes i'm not sure if the download happen or the data was loaded from the app DB"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:46:03.037",
"Id": "488027",
"Score": "0",
"body": "Looks better. It will be useful to throw an exception if data was not received after all retry attempts. And retry sholdn't be executed in all cases. For example, it has no sense if 404 was received. After hundred of retries it will be still 404. You may make the retry logic a bit smarter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:49:52.827",
"Id": "488028",
"Score": "0",
"body": "@aepot how can you know that a 404 error will not be fixed in some seconds later? i use 3 retries with 3 seconds delay, there is a slight chance the site to be up again maybe? About the exception when no data exist, should i create my own exception? what kind of exception to throw?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T17:06:53.983",
"Id": "488034",
"Score": "0",
"body": "There's a method `HttpResponseMessage.EnsureSuccessStatusCode()`, It throws if not success. You can conditionally call it. That's up to you, anyway."
}
] |
[
{
"body": "<p>Thanks for clarifying the requirements, let's say they are:</p>\n<ul>\n<li><p>First call to GetDraws, no cached dates, has internet, download dates into cache, return date.</p>\n</li>\n<li><p>First call to GetDraws, no cached dates, no internet, indicate error.</p>\n</li>\n<li><p>First call to GetDraws, cached dates, download and store new cache of dates,\nreturn dates.</p>\n</li>\n</ul>\n<p>Let's go with that. You mention "old dates does not require to be downloaded again or refreshed, only new ones are being downloaded.' so a calls the cache is refreshed.</p>\n<p>Okay, so you can see there are a few actions going on and they have all been placed into the one method. thinking SRP. They are related but the code meshes them together. So, I'd recommend separating out the actions into methods.</p>\n<p>Here is a rework of the code that demonstrates how that would look like.</p>\n<p>Now the question of how to deal with error. It's difficult because null says nothing about the failure. Raising an exception is overkill although, you see it depends on what is call this code. This isn't really the code that we need to see to help with error handling. We'd need to see what uses the null content. Let's see that code and maybe something will come to mind.</p>\n<p>Here's the code reimagined.</p>\n<pre><code>class Draw\n{\n public string Get(Uri uri, string date)\n {\n // load cached data, that may or may not have the key\n // if no cached data, then use empty dictionary with no keys\n Dictionary<string, string> StoredDates = this.GetStoredDates();\n\n if (!StoredDates.ContainsKey(date))\n {\n if (IsInternetEnabled)\n {\n // of course huge assumption here\n // the internet is enabled, but does it work!\n // is the website there?\n StoredDates.Add(this.DownloadContent(uri, date));\n this.CacheStoredDates(StoredDates);\n }\n else\n {\n // what to do here, no stored data, no way to get data\n // null content for the draws on that date? \n // raising an exception doesn't seem correct this is not exception circumstances\n }\n\n }\n return StoredDates[date];\n }\n\n private Dictionary<string, string> GetStoredDates()\n {\n // if null then return an empty dictionary\n return JsonConvert.DeserializeObject<Dictionary<string, string>>(StoredDatesList) ? new Dictionary<string, string>();\n }\n\n private void CacheStoredDates(Dictionary<string, string> StoredDates)\n {\n StoredDatesList = JsonConvert.SerializeObject(StoredDates, Formatting.Indented);\n }\n\n private bool IsInternetEnabled()\n {\n return Connectivity.NetworkAccess != NetworkAccess.Internet;\n }\n\n private KeyValuePair<string, string> DownloadContent(Uri uri, string date)\n {\n // have a look at the Polly framework\n\n HttpClient client = new HttpClient();\n var contents = await client.GetStringAsync(url);\n var result = JsonConvert.DeserializeObject<RootObject>(contents.ToString());\n\n // why 180? what does it mean, make it a constant with a variable name.\n if (180 == result.content.Count)\n {\n // maybe return a key value pair here instead. Why? \n // to reduce the side effects in your code, \n // side effect smell, updating state from lots of places\n // makes it difficult to parallelize later \n return new KeyValuePair<string, string>(date, contents);\n }\n else\n {\n // what if it is not 180?\n return new KeyValuePair<string, string>(date, "let's assume that this is fine.");\n }\n }\n}\n</code></pre>\n<p>Update:</p>\n<p>To clarify the use of KeyValuePair is purely option. Previously, the UpdateContent() method updated data in the class. This creates a direct dependency between the class and the UpdateContent() method. Returning a value, whatever it's type, will allow the UpdateContent() method be movable.</p>\n<p>Okay errors. You have control over the code that checks the error; that's good. If this was an API then maybe you wouldn't be able to change the error code as it would have breaking changes.</p>\n<p>Checking null, not good as it implicitly says something that should be made explicit. There is a design pattern called a NullObject that might work here. The idea of using an empty collection rather than null is an example of NullObject at work; the code doesn't need to check for null it just loops over a list with no items.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Null_object_pattern\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Null_object_pattern</a></p>\n<p>I don't think NullObject would work as the code deals with strings. NullObject for string is string.Empty with is almost the same as null in this context.</p>\n<p>Using a predefined string would work, no doubt. Let's think about some other options.</p>\n<p>There is a pattern in .NET called the try method. You may have seen it.</p>\n<pre><code>bool success = int.TryParse(input, out int value)\nif(!success) \n</code></pre>\n<p>You could have a TryGetDraw() method.</p>\n<pre><code> public bool TryGetDraw(Uri uri, string date, out string content)\n {\n // load cached data, that may or may not have the key\n // if no cached data, then empty dictionary with no keys\n Dictionary<string, string> StoredDates = this.GetStoredDates();\n\n if (!StoredDates.ContainsKey(date))\n {\n if (IsInternetEnabled)\n {\n StoredDates.Add(this.DownloadContent(uri, date));\n this.CacheStoredDates(StoredDates);\n }\n else\n {\n // what to do here, no stored data, no way to get data\n // null content for the draws on that date? \n // raising an exception doesn't seem correct this is not exception circumstances\n content = string.Empty;\n return false;\n }\n\n }\n\n content = StoredDates[date];\n return true;\n }\n</code></pre>\n<p>Called like this...</p>\n<pre><code>bool success = draws.TryGetDraw(uri, date, out string content)\nif(!success) // show message box\n</code></pre>\n<p>That's removes the need to check content completely, no special strings; however, it does cause information about the reasons why TryGetDraw failed.</p>\n<p>Maybe, the content string could contain a human readable reason for the failure. Maybe we can improve the pattern with an enumeration.</p>\n<pre><code> enum Outcome\n {\n Success,\n InternetDisabled,\n RequestTimeout,\n InternalServerError,\n Unknown\n }\n\n public Outcome TryGetDraw(Uri uri, string date, out string content)\n {\n if (!StoredDates.ContainsKey(date))\n {\n if (IsInternetEnabled)\n {\n try\n {\n\n }\n // just be sure this makes sense\n catch (HttpRequestException ex)\n {\n return Outcome.InternalServerError;\n }\n }\n else\n {\n content = string.Empty;\n return Outcome.InternetDisabled;\n }\n }\n\n content = StoredDates[date];\n return Outcome.Success;\n }\n</code></pre>\n<p>Called like this...</p>\n<pre><code>Outcome outcome = draws.TryGetDraw(uri, date, out string content)\nif(outcome == Outcome.InternetDisabled) // check wifi is on msg\nif(outcome == Outcome.InternalServerError) // try again later msg\n</code></pre>\n<p>That could lead to a mass of Outcomes and if statements everywhere that would need to maintained so treat this approach with care. There's no silver bullet.</p>\n<p>The two try methods are the same, just depends on whether you want the code being called to know the error messages (error messages in TryGetDraw method) or the code doing the calling to know the error messages (in the Form).</p>\n<p>One last thing, since you are calling out over the internet the different errors you will get will be more than Internet is disabled. The internet maybe enables but the network might be down, the web server may be down, the web server might be too busy, it might have an internal error, the data might not be at that url, hopefully it's accessed over TLS... so anyway the nuget package Polly will allow your code to be more resilient to this uncertainty.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing</a></p>\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/</a></p>\n<p><a href=\"https://docs.microsoft.com/en-us/azure/architecture/patterns/retry\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/azure/architecture/patterns/retry</a></p>\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:26:31.240",
"Id": "487843",
"Score": "0",
"body": "@CDrosos you might want to clarify with the business or user of the system what they expect to happen in the case of an network outage, what would they want to happen if the data wasn't there. User experience people as well; if there are any."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T13:08:39.033",
"Id": "487846",
"Score": "0",
"body": "great changes thanks, so with keyvaluepair it will be impossible for a date to exist twice in the list? while in my implementation it might be possible? 180 are all the results that can be in one day, so if they are 180 i will store them into the DB, if not then lets try to download them again.sometimes it is ok to have less than 180 but in the end of a day they should be 180 so i only store them if the results are 180 (we can call the 180 as of DailyDraws). \nWhat if i have a table with constrant strings of errors and when internet is not available i return the string error code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T13:14:25.747",
"Id": "487847",
"Score": "0",
"body": "Also i have update the question with an idea on how to handle the network connection issue"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T14:34:04.750",
"Id": "487850",
"Score": "1",
"body": "@CDrosos, the keyvaluepair was used because the code to download from the internet really belongs elsewhere, and passing something back rather than updating directly allows that method to be moved, it's impossible to test this code so injecting a 'downloader' would be better in the long run. Have a look at the Polly framework, it allows automatic retries of a request. If the internet isn't on then it's good to think why and for how long. I'll be online later and have will have a look at the updates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T09:31:07.433",
"Id": "487904",
"Score": "1",
"body": "@CDrosos updated, couple of options for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:25:05.990",
"Id": "488024",
"Score": "1",
"body": "I have update the question with the code i use now from your ideas and aepot notes, i believe is an acceptable workaround the way i check if internet connection is available."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:42:53.957",
"Id": "248939",
"ParentId": "248906",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248939",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:12:01.733",
"Id": "248906",
"Score": "4",
"Tags": [
"c#",
"android",
"error-handling",
"xamarin"
],
"Title": "Proper Error handling when we expect results from secondary functions"
}
|
248906
|
<p>I have an array of data in the below format</p>
<pre><code>let input = [
{
time: "2020-7",
tasks: [
{
key: "p1",
value: 15
},
{
key: "p2",
value: 13
},
]
},
{
time: "2020-8",
tasks: [
{
key: "p1",
value: 16
},
{
key: "p2",
value: 19
},
]
},
{
time: "2020-9",
tasks: [
{
key: "p1",
value: 12
},
{
key: "p2",
value: 93
},
]
}
]
</code></pre>
<p>After config input array, then 'dataConvert' is formatted as follows:</p>
<pre><code>dataConvert = [
["x","2020-7", "2020-8", "2020-9"],
["p1", 15, 16, 12],
["p2", 13, 19, 93]
]
</code></pre>
<p>I tried use <code>reduce</code> , I want to find another way of optimizing.</p>
<pre><code>let dateConvert = [], valueConvert = [];
data2.forEach(x=>{
let date = new Date(x.time);
if (date) {
let getYear = date.getFullYear();
let getMonth = date.getMonth() + 1;
let newDate = `${getYear}-${getMonth}-1`;
return dateConvert = [...dateConvert, newDate];
}
})
dateConvert.unshift("x");
// get p1 p2 value
let allTasks = data2.flatMap(x => x.tasks);
valueConvert = Object.values(allTasks.reduce((arr, item) => {
arr[item.key] = arr[item.key] || [item.key];
arr[item.key].push(item.value);
return arr;
}, {}));
dataConvert = [...[dateConvert], ...valueConvert];
</code></pre>
<p>thank u.</p>
|
[] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li>The code does not produce exactly your output, the <code>x</code> part is different;\n["x", "2020-7-1", "2020-8-1", "2020-9-1"], I assume the code is right</li>\n<li>That <code>reduce</code> is fine, it's the best part of the code really</li>\n<li>The date part seems complicated the check for the valid date could have been done in a filter, the rest in a map</li>\n<li>Consistency is important, you use both the fancy technique <code>dataConvert = [...[dateConvert], ...valueConvert];</code> and <code>dateConvert.unshift("x");</code> which could have been <code>dateConvert = ["x", ...dateConvert];</code>, the only good reason for <code>unshift</code> could have been that <code>dateConvert</code> is a <code>const</code> but it isnt</li>\n<li>I dont like <code>x</code> as a variable name, it says nothing to me, I would go for <code>o</code> (object)</li>\n<li>Similarly when you reduce <code>allTasks</code> you pass <code>arr</code> as the cumulator, but it's not an array, it's an object so you could/should use <code>o</code> there</li>\n<li>This <code>[...[dateConvert], ...valueConvert];</code> is equivalent to <code>[dateConvert, ...valueConvert];</code>, you may want to play around more with the spread operator</li>\n<li><code>get p1 p2 value</code> is a very contemporary comment, it is true today because tasks indeed only contain p1 and p2, but the day that tasks get new or changed, that comment will be worthless, consider something like <code>group all tasks properties</code></li>\n<li>I guess a task is an item, but I would rather see <code>allTasks.reduce((o, task)</code> than <code>allTasks.reduce((arr, item) </code></li>\n</ul>\n<p>If you take all that, I would counter propose this;</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 convertData(data){\n\n let dateConvert = data.filter(o => new Date(o.time)).map(o => {\n const date = new Date(o.time);\n return `${date.getFullYear()}-${ date.getMonth() + 1}-1`;\n });\n dateConvert = [\"x\", ...dateConvert];\n\n let allTasks = data.flatMap(x => x.tasks);\n\n //Group all task properties\n const valueConvert = Object.values(allTasks.reduce((o, task) => {\n o[task.key] = o[task.key] || [task.key];\n o[task.key].push(task.value);\n return o;\n }, {}));\n\n return [dateConvert, ...valueConvert];\n}\n\nconst data2 = [\n{\n time: \"2020-7\",\n tasks: [\n {\n key: \"p1\",\n value: 15\n },\n {\n key: \"p2\",\n value: 13\n },\n ]\n },\n{\n time: \"2020-8\",\n tasks: [\n {\n key: \"p1\",\n value: 16\n },\n {\n key: \"p2\",\n value: 19\n },\n ]\n },\n{\n time: \"2020-9\",\n tasks: [\n {\n key: \"p1\",\n value: 12\n },\n {\n key: \"p2\",\n value: 93\n },\n ]\n }\n];\n\nconsole.log(convertData(data2));</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-09-04T08:29:40.803",
"Id": "248910",
"ParentId": "248907",
"Score": "3"
}
},
{
"body": "<p>You have</p>\n<pre><code>valueConvert = Object.values(allTasks.reduce((arr, item) => {\n arr[item.key] = arr[item.key] || [item.key];\n arr[item.key].push(item.value);\n return arr;\n}, {}));\n</code></pre>\n<p>This is somewhat opinion-based, but I'd recommend <a href=\"https://www.youtube.com/watch?v=qaGjS7-qWzg\" rel=\"nofollow noreferrer\">avoiding reduce</a> in these sorts of situations, where the accumulator is the same object throughout all iterations. See that link above for a video by some of Chrome's developers going into more detail on why it's not the best idea. In short, while <code>reduce</code> is a possible method to solve the problem, it's unnecessarily verbose and can be a bit confusing (especially for readers of your code who may not be sufficiently familiar with <code>reduce</code>) compared to a plain loop; it's needlessly complex. Don't feel like you <em>have</em> to use array methods everywhere you can (even if using it shows that you know how to use <code>.reduce</code>).</p>\n<p>You could change it to:</p>\n<pre><code>const tasksByKey = {};\nfor (const { key, value } of arr) {\n tasksByKey[key] = tasksByKey[key] || [key];\n tasksByKey[key].push(value);\n}\nconst valueConvert = Object.values(tasksByKey);\n</code></pre>\n<p>You use <code>let</code> a lot. Best to <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">always use <code>const</code></a> when possible - this makes code easier to read and reason about, when you know at a glance that a particular variable name will never be reassigned. Consider <a href=\"https://eslint.org/docs/rules/prefer-const\" rel=\"nofollow noreferrer\">using a linter</a>, if you aren't already doing so - it can make code style more consistent and readable, and can reduce bugs.</p>\n<p>Similarly, if a variable name doesn't <em>have</em> to be reassigned, consider avoiding doing so. Rather than</p>\n<pre><code>dataConvert = [...[dateConvert], ...valueConvert];\n</code></pre>\n<p>you might use</p>\n<pre><code>const datesAndValues = [dateConvert, ...valueConvert];\n</code></pre>\n<p>Remember that <code>.flatMap</code> is a pretty new method - if this code is running on a public-facing website, make sure to include <a href=\"https://github.com/es-shims/Array.prototype.flatMap\" rel=\"nofollow noreferrer\">a polyfill</a>. (<code>Object.values</code> was only officialized in ES2017, so you'll probably want a polyfill for it too)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T14:16:10.293",
"Id": "248917",
"ParentId": "248907",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248910",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T07:16:33.957",
"Id": "248907",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Convert task data into a flat structure"
}
|
248907
|
<h2>Reasons</h2>
<p>I'm recently learning Go with various exercises (might be more questions coming in the future)</p>
<p>However, I'm quite annoyed with the default argument parsing module in Go <a href="https://golang.org/pkg/flag/" rel="nofollow noreferrer">flag</a> as it doesn't satisfy my needs most of the time.</p>
<p>So as a learning exercise I went ahead and created a simplified clone of python's argparse module. It isn't a 1 on 1 clone and I don't want it to be.</p>
<h2>Module</h2>
<pre><code>package argparse
import (
"fmt"
"os"
"reflect"
"strconv"
"strings"
)
type Argument struct {
ShortFlag, LongFlag, Help string
Type, Default interface{}
Required bool
}
type Argparse struct {
Programme, Description string
Arguments []Argument
}
func (p *Argparse) findArgument(arg string) *Argument {
if !strings.Contains(arg, "-") {
return nil
}
for _, a := range p.Arguments {
if a.ShortFlag == arg[1:] || a.LongFlag == arg[2:] {
return &a
}
}
return nil
}
func (p *Argparse) Parse() map[string]interface{} {
args := make(map[string]interface{})
osArgs := os.Args
for _, a := range osArgs[1:] {
if "-h" == a || "--help" == a {
p.Help()
}
}
for i := 1; i < len(osArgs); i++ {
a := p.findArgument(osArgs[i])
if a != nil {
_type := reflect.TypeOf(a.Type)
switch _type.Kind() {
case reflect.String:
if len(osArgs) == i + 1 {
fmt.Println("[ERROR] Didn't supply the argument for", a.LongFlag)
os.Exit(3)
}
args[a.LongFlag] = osArgs[i + 1]
i += 1
case reflect.Int:
if len(osArgs) == i + 1 {
fmt.Println("[ERROR] Didn't supply the argument for", a.LongFlag)
os.Exit(3)
}
retValue, err := strconv.Atoi(osArgs[i + 1])
if err != nil {
fmt.Println(osArgs[i + 1], "is not an integer")
os.Exit(3)
}
args[a.LongFlag] = retValue
i += 1
case reflect.Bool:
args[a.LongFlag] = true
default:
fmt.Println("[ERROR]: Flag", a.LongFlag, "is of type", _type.Kind(), "which is not supported")
os.Exit(3)
}
}
}
for _, arg := range p.Arguments {
if _, f := args[arg.LongFlag]; !f {
if arg.Required && arg.Default == nil {
fmt.Println("[ERROR]: Flag", arg.LongFlag, "is required and not set")
os.Exit(3)
}
args[arg.LongFlag] = arg.Default
}
}
return args
}
func (p *Argparse) AddArgument(arg Argument) {
if arg.LongFlag == "" {
fmt.Println("[ERROR]: LongFlag must be set")
os.Exit(1)
}
if arg.Type == nil {
fmt.Println("[ERROR]: Type must be set")
os.Exit(1)
}
p.Arguments = append(p.Arguments, arg)
}
func (p *Argparse) Help() {
if p.Programme == "" {
p.Programme = os.Args[0]
}
fmt.Print("Usage ", p.Programme, "\n\n")
fmt.Print(p.Description, "\n\n")
for _, a := range p.Arguments {
fmt.Print("\t", "-" + a.ShortFlag, ", ", "--" + a.LongFlag, "\t", a.Help, "\n")
}
os.Exit(0)
}
</code></pre>
<h2>Implementation</h2>
<pre><code>package main
import (
"fmt"
"argparse"
)
func parseArguments() map[string]interface{} {
parser := argparse.Argparse {
Description: "Testing argparse logic",
}
parser.AddArgument(
argparse.Argument {
ShortFlag: "t", LongFlag: "text", Type: "string",
Required: true, Help: "A line of text",
},
)
parser.AddArgument(
argparse.Argument {
ShortFlag: "e", LongFlag: "enc", Type: false,
Help: "Something else", Default: false,
},
)
return parser.Parse()
}
func main() {
args := parseArguments()
for k, v := range args {
fmt.Println("Argument:", k, "=", v)
}
}
</code></pre>
<h2>Example</h2>
<pre><code>$ ./test -t "-e"
Argument: text = -e
Argument: enc = false
</code></pre>
<p>As mentioned I'm fairly new to the language so any recommendation would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T23:03:09.080",
"Id": "506838",
"Score": "0",
"body": "Could this help: https://pkg.go.dev/github.com/akamensky/argparse?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T11:07:46.563",
"Id": "248911",
"Score": "3",
"Tags": [
"go"
],
"Title": "Argparse for Golang"
}
|
248911
|
<p>This is a small part of a larger program for implementing a limited syntax regular expression constructor using Ken Thompson's construction algorithm. Converting to postfix before the regular expression is processed makes the processing vastly simpler because everything can be smoothly read and processed left to right. The following algorithm for performing the conversion works in a shunting-yard like manner where an operator stack is used to determine when operators should be sent to the output string.</p>
<h3>Conversion Function:</h3>
<pre class="lang-c prettyprint-override"><code>typedef struct _conv_ret {
char *re;
int err;
} conv_ret;
conv_ret conv(char *re) {
/* converts limited regex infix notation with explicit
* catenation denoted by '.' to postfix in a shunting-yard manner */
conv_ret ret = {NULL, REGEX_TOOLARGE};
if(strlen(re) > MAX_LINE)
return ret;
static char buf[MAX_LINE];
char *bufp = buf;
ret.re = buf;
ret.err = 0;
/* operator stack */
int bp[strlen(re)];
int *sp = bp;
#define OP_NUM 6
/* placeholder for id 0 */
char id_map[OP_NUM+1] = {' ', '(', '|', '.', '?', '+', '*'};
int prec_map[OP_NUM+1] = {0, 1, 2, 3, 4, 4, 4};
#define push(id) *++sp = id
#define pop() *bufp = id_map[*sp--]; bufp++
for(; *re; re++) {
/* loop skips open paren (id 1) because it is only there
* as a placeholder until the closing paren is pushed */
for(int id = 2; id < OP_NUM+1; id++) {
/* pop until incoming op is
* highest precedence on stack */
if(id_map[id] == *re) {
if(sp > bp) {
while(prec_map[id] <= prec_map[*sp]) {
pop();
}
}
push(id);
goto RELOOP;
}
}
switch(*re) {
case '(':
push(1);
goto RELOOP;
case ')':
while(*sp != 1) {
/* couldn't find matching paren. send error */
if(sp == bp) {
ret.re = NULL;
ret.err = PAREN_MISMATCH;
return ret;
}
pop();
}
/* pop without sending paren to buf */
--sp;
goto RELOOP;
default:
/* send non op to buf */
*bufp = *re;
bufp++;
}
RELOOP: ;
}
/* pop all leftover values in stack to buf */
while(sp > bp) {
/* error if unmatched open paren */
if(*sp == 1) {
ret.re = NULL;
ret.err = PAREN_MISMATCH;
return ret;
}
pop();
}
/* null terminate */
*bufp = 0;
return ret;
}
</code></pre>
<h3>Header:</h3>
<pre class="lang-c prettyprint-override"><code>#include <string.h>
#define MAX_LINE 10000
/* error codes */
#define REGEX_TOOLARGE 1
#define PAREN_MISMATCH 2
</code></pre>
<p><strong>Note:</strong> Further errors are caught in later stages of parsing within the program, but this post is just about the postfix conversion and the conversion itself is not meant to do a whole lot of syntactic and semantic parsing.</p>
<h3>Examples:</h3>
<p><code>a+a</code> -> <code>aa+</code></p>
<p><code>a+a*</code> -> <code>aa+*</code></p>
<p><code>a.(a+b)*.b</code> -> <code>aab+*.b.</code></p>
<p><code>a.(a+b)*.b()</code> -> <code>aab+*.b.</code></p>
<p><code>a.(a+b)*.b)</code> -> <code>PAREN_MISMATCH</code></p>
<p><code>a.(a+b)*.b(</code> -> <code>PAREN_MISMATCH</code></p>
<p>Any criticisms aimed towards improving the efficiency and readability of this code would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:55:02.880",
"Id": "487748",
"Score": "2",
"body": "It would be helpful for reviewers to have the missing #define information as well as any header files used for the code. It would also be helpful if you added any test cases (programs and data) you wrote for this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T13:28:28.510",
"Id": "487749",
"Score": "0",
"body": "@pacmaninbw I added some more information. Hopefully it helps!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:45:16.707",
"Id": "487763",
"Score": "1",
"body": "Please do not modify the question after an answer has been posted, especially please do not modify the code, everyone has to see the code as reviewed [help center](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T16:09:02.270",
"Id": "487769",
"Score": "0",
"body": "Please see the rules I pointed at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T03:14:30.287",
"Id": "487815",
"Score": "0",
"body": "You can post a follow up question with your changes and link back to this one."
}
] |
[
{
"body": "<h2>General Observations</h2>\n<p>It is difficult to accurately define any bottle necks when only one function is presented. The brief moment when <code>main()</code> and <code>match()</code> were visible was very helpful, although it would have been nice if the body of <code>match()</code> was included as well.</p>\n<p>It might be better to use a power of 2 (1024, 2048, ...) for MAX_LINE rather than a round number like 10000.</p>\n<p>The code is overly complex and should be broken into multiple functions, this is actually proved by the multiple <code>goto RELOOP;</code> statements. These goto statements can be replaced by <code>break;</code> and <code>continue</code> and in one case by the return of a function. Try to avoid writing <a href=\"https://en.wikipedia.org/wiki/Spaghetti_code\" rel=\"nofollow noreferrer\">Spaghetti code</a>.</p>\n<h2>Implement Stacks using Structs</h2>\n<p>It is much easier to maintain code when the stack pointer and the stack container (array) can be found in one place. Rather than write <code>push</code> and <code>pop</code> as macros, implement them as functions that take a stack struct, and in the case of <code>push</code> the parameter of what is being pushed on the stack.</p>\n<h2>Magic Numbers</h2>\n<p>While there are symbolic constants used rather than number constants in some parts of the code, this could be improved, it is also possible to use enums rather than #define to define symbolic constants in C and I would recommend using enums to represent the error ids because it is expandable.</p>\n<pre><code>typedef enum Error_Code\n{\n REGEX_TOOLARGE = 1,\n PAREN_MISMATCH = 2\n} Error_Code;\n</code></pre>\n<p>Just a quick though here, if the error codes start at 0 rather than 1 than any error messages could be stored as an array of strings.</p>\n<p>The place where there are still magic numbers is in this code:</p>\n<pre><code> int prec_map[OP_NUM] = { 1, 2, 3, 4, 4, 4 };\n</code></pre>\n<p>It isn't clear what any of those numbers mean.</p>\n<p>It isn't clear that <code>OP_NUM</code> is necessary because the count can be determined by either one of the following:</p>\n<pre><code> char id_map[] = { '(', '|', '.', '?', '+', '*' };\n const size_t OP_NUM = sizeof(id_map)/sizeof(*id_map);\n</code></pre>\n<p>or</p>\n<pre><code> int prec_map[] = { 1, 2, 3, 4, 4, 4 };\n const size_t OP_NUM = sizeof(prec_map)/sizeof(*prec_map);\n</code></pre>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them.</p>\n<h2>Posible Optimization</h2>\n<p>Use <code>strlen()</code> only once and store the value in a variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T14:12:44.177",
"Id": "248916",
"ParentId": "248913",
"Score": "2"
}
},
{
"body": "<p>Avoid function-like macros. They are <em>sooo</em> seventyish, and they may seriously reduce the readability of the code. In this particular case it took me a while to realize that</p>\n<pre><code> while(sp > bp) {\n /* error if unmatched open paren */ \n if(*sp == 1) {\n ret.re = NULL;\n ret.err = PAREN_MISMATCH;\n return ret;\n }\n pop();\n }\n</code></pre>\n<p><em>is not</em> an infinite loop. Looking at just this snippet, it is not possible to see that <code>sp</code> does change. The fact that it is decremented is hidden in <code>pop()</code>, and very hidden it is.</p>\n<p>Use an inline function, and trust the compiler to produce an identical code. The compilers are very good in optimization these days.</p>\n<hr />\n<p>The inner loop over <code>id</code>s does not look pretty. The nesting is too deep. Factor out important functions. First, the real job is done only when <code>id_map[id] == *re</code>. It means</p>\n<pre><code> int id = find_id(*re);\n if (id != INVALID_ID) {\n do_the_job;\n } \n</code></pre>\n<hr />\n<p><code>goto</code>s are not called for. Those inside <code>switch</code> are absolutely unnecessary; a normal <code>break</code> would do the same thing. The <code>goto</code> inside the inner loop is more tricky to eliminate. Notice that it naturally belongs to the <code>default</code> case of the <code>switch</code>: it does nothing for <code>(</code> and <code>)</code>. Also notice that the</p>\n<pre><code> *bufp = *re;\n bufp++;\n</code></pre>\n<p>sequence is only executed if <code>push(id)</code> never happened.</p>\n<p>With the previous comment in mind, consider</p>\n<pre><code> default:\n id = find_id(*re);\n if (id == INVALID_ID) {\n *bufp++ = *re;\n } else {\n do_the_job;\n }\n</code></pre>\n<p>See how the <code>goto</code>s disappear. And yet again, don't be shy of functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T00:12:30.550",
"Id": "487809",
"Score": "0",
"body": "Yeah. I completely refactored the code such that everything is within a switch statement, the id system is totally different, and b/c unary operators are unnecessarily processed in the stack, the only operator ever to go in the stack is the binary union '|'. I wish I could change my code as in the original post because when someone looks up 'regex infix to postfix', this comes up, and I don't want people to see such sloppy and bad/ not even fully functional for some cases code, but it is what it is."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:18:57.907",
"Id": "248934",
"ParentId": "248913",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248916",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:25:35.030",
"Id": "248913",
"Score": "3",
"Tags": [
"c",
"regex",
"stack"
],
"Title": "Convert infix regular expression notation to postfix"
}
|
248913
|
<p>I am learning Graphs on my own and want to use a graph for a personal small project, so I decided to take a look here in Code Review for some cool implementations and <a href="https://codereview.stackexchange.com/questions/151883/implementation-of-a-graph-in-java">came across this one</a> by <a href="https://codereview.stackexchange.com/users/23821/maksim-dmitriev">Maksim Dmitriev</a></p>
<p>I found it really great, so, heavily inspired and based on his implementation, I present you my own implementation.</p>
<p>I'd appreciate some honest review, and where I can get this better and more robust.</p>
<p>Thank you in advance!!</p>
<p><strong>DirectedGraph.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package experiments.implement.graph;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class DirectedGraph<T> {
private final Map<T, Map<T, Double>> graphData = new HashMap<>();
private final Map<T, T> nodeSet = new HashMap<>();
private int edgeCount = 0;
public int getNodeCount() {
return nodeSet.size();
}
public int getEdgeCount() {
return edgeCount;
}
public boolean addNode(T node) {
graphData.putIfAbsent(node, new HashMap<>());
return nodeSet.putIfAbsent(node, node) == null;
}
public T getNode(T node) {
return nodeSet.getOrDefault(node, null);
}
public T removeNode(T node) {
node = getNode(node);
if (node != null) {
edgeCount -= graphData.get(node).size();
graphData.remove(node);
nodeSet.remove(node);
for (T t : graphData.keySet()) {
if (graphData.get(t).remove(node) != null) {
--edgeCount;
}
}
}
return node;
}
public Iterator<T> nodeIterator() {
return graphData.keySet().iterator();
}
public Set<T> getNodes() {
return nodeSet.keySet();
}
public boolean addEdge(T from, T to) {
return addEdge(from, to, 1.0);
}
public boolean addEdge(T from, T to, double weight) {
return addEdge(from, to, weight, true);
}
public boolean addEdge(T from, T to, double weight, boolean addsNodes) {
if (weight == Double.NEGATIVE_INFINITY ||
Double.isNaN(weight)) {
throw new IllegalArgumentException(
"Weight must be a number or the positive infinity");
}
if (addsNodes) {
addNode(from);
addNode(to);
}
if ((from = getNode(from)) == null
|| (to = getNode(to)) == null) {
return false;
}
Double oldWeight = graphData.get(from).put(to, weight);
if (oldWeight == null) {
++edgeCount;
}
return !Objects.equals(weight, oldWeight);
}
public double getEdgeWeight(T from, T to) {
if (hasEdge(from, to)) {
return graphData.get(from).get(to);
}
return Double.NaN;
}
private boolean hasEdge(T from, T to) {
return graphData.getOrDefault(from, new HashMap<>(0)).containsKey(to);
}
public boolean removeEdge(T from, T to) {
if (hasEdge(from, to)) {
graphData.get(from).remove(to);
--edgeCount;
return true;
}
return false;
}
public Set<T> outDegreeOf(T node) {
if (getNode(node) == null) {
return null;
}
return graphData.get(node).keySet();
}
public Set<T> inDegreeOf(T node) {
Set<T> inDegree = new HashSet<>();
for (T graphNode : nodeSet.keySet()) {
if (graphData.get(graphNode).getOrDefault(node, null) != null) {
inDegree.add(graphNode);
}
}
return inDegree.isEmpty() ? null : inDegree;
}
public void clear() {
graphData.clear();
nodeSet.clear();
edgeCount = 0;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DirectedGraph)) {
return false;
}
DirectedGraph<?> that = (DirectedGraph<?>) o;
return Objects.equals(graphData, that.graphData);
}
@Override
public int hashCode() {
return Objects.hash(graphData);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
Iterator<T> nodesIter = graphData.keySet().iterator();
while (nodesIter.hasNext()) {
T node = nodesIter.next();
sb.append(node);
Iterator<T> edgesIter = graphData.get(node).keySet().iterator();
sb.append(":[");
while (edgesIter.hasNext()) {
T edge = edgesIter.next();
sb.append("<")
.append(edge)
.append(", ").append(graphData.get(node).get(edge))
.append(">");
if (edgesIter.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
if (nodesIter.hasNext()) {
sb.append(", ");
}
}
return sb.append("}").toString();
}
}
</code></pre>
<p><strong>UndirectedGraph.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package experiments.implement.graph;
import java.util.Set;
public class UndirectedGraph<T> extends DirectedGraph<T> {
@Override
public int getEdgeCount() {
return super.getEdgeCount() / 2;
}
@Override
public boolean addEdge(T node1, T node2, double weight, boolean addsNodes) {
if (super.addEdge(node1, node2, weight, addsNodes)) {
return super.addEdge(node2, node1, weight, addsNodes);
}
return false;
}
@Override
public boolean removeEdge(T node1, T node2) {
if (super.removeEdge(node1, node2)) {
return super.removeEdge(node2, node1);
}
return false;
}
@Override
public Set<T> inDegreeOf(T node) {
return super.outDegreeOf(node);
}
}
</code></pre>
<p>EXTRA: Some utility algorithm implementations like, Breadth First Search and Dijkstra Search
<strong>GraphUtil.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package experiments.implement.graph;
import java.util.*;
public class GraphUtil<T> {
private Map<T, Double> distances;
private Map<T, T> previousNodes;
private DirectedGraph<T> graph;
public GraphUtil(DirectedGraph<T> graph) {
this.graph = graph;
}
public void loadGraph(DirectedGraph<T> graph) {
this.graph = graph;
}
public void breadthFirstSearch(T from) {
breadthFirstSearch(from, null);
}
public void breadthFirstSearch(T from, T to) {
Set<T> nodes = new HashSet<>(graph.getNodes());
previousNodes = new HashMap<>(nodes.size(), 1);
Set<T> visited = new HashSet<>();
LinkedList<T> queue = new LinkedList<>();
queue.add(from);
while (!queue.isEmpty()) {
T parent = queue.pop();
visited.add(parent);
for (T node : graph.outDegreeOf(parent)) {
if (visited.contains(node)) {
continue;
}
queue.add(node);
previousNodes.putIfAbsent(node, parent);
if (node.equals(to)) {
return;
}
}
}
}
public void dijkstraSearch(T from) {
Set<T> nodes = new HashSet<>(graph.getNodes());
Set<T> settledNodes = new HashSet<>();
distances = new HashMap<>(nodes.size(), 1);
previousNodes = new HashMap<>(nodes.size(), 1);
for (T node : nodes) {
distances.put(node, Double.POSITIVE_INFINITY);
}
distances.put(from, 0.0);
T previous = from;
while (!nodes.isEmpty()) {
Set<T> outDegree = graph.outDegreeOf(previous);
for (T node : outDegree) {
if (settledNodes.contains(node)) {
continue;
}
double weight = graph.getEdgeWeight(previous, node);
if (weight < distances.get(node)) {
distances.put(node, distances.get(previous) + weight);
previousNodes.put(node, previous);
}
}
settledNodes.add(previous);
nodes.remove(previous);
double smallest = Double.POSITIVE_INFINITY;
for (T node : nodes) {
smallest = Math.min(smallest, distances.get(node));
}
for (T node : nodes) {
if (distances.get(node) == smallest) {
previous = node;
}
}
}
}
public List<T> getPathTo(T to) {
if (previousNodes == null || previousNodes.isEmpty()) {
return null;
}
T next = to;
LinkedList<T> list = new LinkedList<>();
while (next != null) {
list.addFirst(next);
next = previousNodes.getOrDefault(next, null);
}
return list;
}
public double getDistanceTo(T to) {
if (distances == null || distances.isEmpty()) {
return Double.NaN;
}
return distances.getOrDefault(to, Double.NaN);
}
}
</code></pre>
<p>And now, just some basic program to experiment with some features of the graph:</p>
<p><strong>Main.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package experiments.implement.graph;
public class Main {
public static void main(String[] args) {
DirectedGraph<String> dGraph = new DirectedGraph<>();
dGraph.addEdge("Zero", "One", 1.5);
dGraph.addEdge("One", "Zero", 1.5);
dGraph.addEdge("One", "Two", 0.7);
dGraph.addEdge("Two", "Three", 1.9);
dGraph.addEdge("Three", "Four", 1.1);
dGraph.addEdge("Four", "One", 1.7);
dGraph.addEdge("Four", "Five", 0.9);
dGraph.addEdge("Five", "Four", 1.1);
dGraph.addEdge("Five", "Zero", 2.0);
System.out.println(dGraph);
System.out.println("Nodes: " + dGraph.getNodeCount() + ", Edges: " + dGraph.getEdgeCount());
System.out.println("In degree: " + dGraph.inDegreeOf("Zero"));
System.out.println("Out degree: " + dGraph.outDegreeOf("Zero"));
UndirectedGraph<String> uGraph = new UndirectedGraph<>();
uGraph.addEdge("Zero", "One");
uGraph.addEdge("One", "Zero");
uGraph.addEdge("One", "Two");
uGraph.addEdge("Two", "Three");
uGraph.addEdge("Three", "Four");
uGraph.addEdge("Four", "One");
uGraph.addEdge("Four", "Five");
uGraph.addEdge("Five", "Four");
uGraph.addEdge("Five", "Zero");
System.out.println(uGraph);
System.out.println("Nodes: " + uGraph.getNodeCount() + ", Edges: " + uGraph.getEdgeCount());
System.out.println("In degree: " + uGraph.inDegreeOf("Zero"));
System.out.println("Out degree: " + uGraph.outDegreeOf("Zero"));
uGraph.removeEdge("Five", "Zero");
System.out.println(uGraph);
System.out.println("Nodes: " + uGraph.getNodeCount() + ", Edges: " + uGraph.getEdgeCount());
System.out.println("In degree: " + uGraph.inDegreeOf("Zero"));
}
}
</code></pre>
<p>And the output of this little main method:</p>
<pre><code>{Zero:[<One, 1.5>], Five:[<Zero, 2.0>, <Four, 1.1>], One:[<Zero, 1.5>, <Two, 0.7>], Four:[<Five, 0.9>, <One, 1.7>], Two:[<Three, 1.9>], Three:[<Four, 1.1>]}
Nodes: 6, Edges: 9
In degree: [Five, One]
Out degree: [One]
{Zero:[<Five, 1.0>, <One, 1.0>], Five:[<Zero, 1.0>, <Four, 1.0>], One:[<Zero, 1.0>, <Four, 1.0>, <Two, 1.0>], Four:[<Five, 1.0>, <One, 1.0>, <Three, 1.0>], Two:[<One, 1.0>, <Three, 1.0>], Three:[<Four, 1.0>, <Two, 1.0>]}
Nodes: 6, Edges: 7
In degree: [Five, One]
Out degree: [Five, One]
{Zero:[<One, 1.0>], Five:[<Four, 1.0>], One:[<Zero, 1.0>, <Four, 1.0>, <Two, 1.0>], Four:[<Five, 1.0>, <One, 1.0>, <Three, 1.0>], Two:[<One, 1.0>, <Three, 1.0>], Three:[<Four, 1.0>, <Two, 1.0>]}
Nodes: 6, Edges: 6
In degree: [One]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:09:42.400",
"Id": "487757",
"Score": "1",
"body": "`Map<T, Map<T, Double>>` could be `Map<T, Map<T, K>>` since `K` implements or has a provided lambda of type `Comparable`. Why? Because K may add more information, properties, etc. In such case, it would be interesting to create a `Measurable<Edge> extends Comparable<Edge>` (`Edge` instead of `K`) interface so that `K` be a type which implements `Measurable` and be a measurable edge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T17:31:18.643",
"Id": "487780",
"Score": "1",
"body": "@MiguelAvila this is an interesting idea!!"
}
] |
[
{
"body": "<p>Just some remarks, I didn't review every method...</p>\n<h2>Concise API</h2>\n<p>As an API for creating and querying graphs, <code>DirectedGraph</code> could be more focussed. E.g. there are too many different methods for adding nodes or edges to the graph. More is not always better. Example questions:</p>\n<ul>\n<li>Do you need graphs with isolated nodes (no connecting edges)? If not, having the <code>addEdge()</code> method add missing nodes is enough.</li>\n<li>What about weight? Is this part of the graph model that you implement, or not? If yes, remove all the methods without a <code>weight</code> parameter. If you want to support unweighted edges as well, see below for a more generic approach. The current version allows for any strange mixture between weighted and unweighted edges.</li>\n</ul>\n<h2>Javadocs</h2>\n<p>You should add Javadoc comments explaining what the methods do and what the parameters mean.</p>\n<h2>addsNodes</h2>\n<p>Especially the <code>addsNodes</code> parameter has a non-intuitive meaning. If false, adding the edge will only succeed if the nodes are already present in the graph. If not present, the edge is ignored, and you inform the caller about the failure by returning <code>false</code>. But a <code>false</code> return value can also mean that the edge was already present, which presents an ambiguity to your caller. I'd eliminate the methods with the <code>addsNodes</code> parameter and always add nodes if not yet present.</p>\n<p>If you want to keep the <code>addNodes</code> parameter (for probably misguided performance reasons), I'd document that like "If false, the caller guarantees that the <code>from</code> and <code>to</code> nodes are already present in the graph." If the nodes are indeed missing, you should throw an IllegalArgumentException or similar.</p>\n<h2>Edge model</h2>\n<p>You chose to represent edges by three elements:</p>\n<ul>\n<li>the <code>from</code> node,</li>\n<li>the <code>to</code> node,</li>\n<li>a weight.</li>\n</ul>\n<p>And you place some specific restrictions on weight, disallowing <code>NaN</code> and negative infinity.</p>\n<p>A more generic approach would be to model the edges as first-class objects, with an interface <code>Edge</code>. For graph management, you only need the <code>from</code> and <code>to</code> nodes, any additional information (e.g. weight) is just for the user's convenience, so can be added by the specific classes implementing that interface.</p>\n<pre><code>public interface Edge<T> {\n T getFromNode();\n T getToNode();\n}\n\npublic class DirectedGraph<T, E extends Edge<T> {\n ...\n}\n</code></pre>\n<p>Then you just need one method for adding something to the graph, being</p>\n<pre><code>boolean addEdge(E edge) {\n ...\n}\n</code></pre>\n<p>And it's up to your caller to use the appropriate Edge implementation, as you already did it with the node model. This way, the edges can be unweighted, weighted, or labelled with whatever information necessary for the user's graphing needs.</p>\n<h2>UndirectedGraph</h2>\n<p>You implemented <code>UndirectedGraph</code> as a subclass of <code>DirectedGraph</code>, implying that every <code>UndirectedGraph</code> can as well be seen as a <code>DirectedGraph</code>. But I think the semantics of both graph types are different, so I'd recommend to have <code>UndirectedGraph</code> not inherit from <code>DirectedGraph</code>.</p>\n<p>If you really want to re-use the <code>DirectedGraph</code> implementation (I'd not do that), you can do that by giving <code>UndirectedGraph</code> a field of type <code>DirectedGraph</code>, meaning that you implement the undirected graph by maintaining an internal directed graph where every edge is duplicated. Then you can implement the public methods for an undirected graph by using the appropriate actions on the embedded directed graph. This is called delegation.</p>\n<p>Your <code>UndirectedGraph</code> still has methods like <code>inDegreeOf()</code> and <code>outDegreeOf()</code> (inherited/overridden from the directed graph), and this does not match the concept of an undirected graph.</p>\n<p>With your modelling, an <code>UndirectedGraph</code> can be stored into a variable of type <code>DirectedGraph</code>. A user unaware of the subclass will then experience strange behavior of that <code>DirectedGraph</code>, being e.g. that every edge gets doubled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:16:05.920",
"Id": "488045",
"Score": "0",
"body": "Really concise and straight to the point. I tried to apply the improvements pointed out into the original inspiration graph implementation, but this does make a lot of sense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T10:10:31.170",
"Id": "249026",
"ParentId": "248915",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249026",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T12:58:35.293",
"Id": "248915",
"Score": "3",
"Tags": [
"java",
"graph"
],
"Title": "Implementing a Directed and Undirected Graph in Java"
}
|
248915
|
<p>I have a <a href="https://www.kaggle.com/gpreda/covid19-tweets/version/24" rel="nofollow noreferrer">dataframe</a> <code>df</code> such that:</p>
<pre><code>print(df['user_location'].value_counts())
</code></pre>
<pre><code>India 3741
United States 2455
New Delhi, India 1721
Mumbai, India 1401
Washington, DC 1354
...
SpaceCoast,Florida 1
stuck in a book. 1
Beirut , Lebanon 1
Royston Vasey - Tralfamadore 1
Langham, Colchester 1
Name: user_location, Length: 26920, dtype: int64
</code></pre>
<p>I wanted to know the frequency of specific countries like <code>USA</code>, <code>India</code> from the <code>user_location</code> column. Then I wanted to plot the frequencies as <code>USA</code>, <code>India</code>, and <code>Others</code>.
So, I thought about applying some operation on that column such that the <code>value_counts()</code> would give the output as:</p>
<pre><code>India (sum of all frequencies of all the locations in India including cities, states, etc.)
USA (sum of all frequencies of all the locations in the USA including cities, states, etc.)
Others (sum of all frequencies of the other locations)
</code></pre>
<p>It seemed to me that I should merge the frequencies of rows containing the same countries and merge the rest of them together! But the complexity appeared while handling the rows that contain the names of cities, states, etc. instead of their country names.</p>
<hr />
<p>The solution what I have come up with so far is given below (and also in <a href="https://stackoverflow.com/a/63711039/7673979">stackoverflow</a>):</p>
<p>Firstly, I have tried to get all the locations including cities, unions, states, districts, territories. Then I have made a function <code>checkl()</code> such that it can check if the location is India or USA and then convert it into its country name. Finally the function has been applied on the <a href="https://www.kaggle.com/gpreda/covid19-tweets/version/24" rel="nofollow noreferrer">dataframe</a> column <code>df['user_location']</code> :</p>
<pre><code># Trying to get all the locations of USA and India
import pandas as pd
us_url = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'
us_states = pd.read_html(us_url)[0].iloc[:, 0].tolist()
us_cities = pd.read_html(us_url)[0].iloc[:, 1].tolist() + pd.read_html(us_url)[0].iloc[:, 2].tolist() + pd.read_html(us_url)[0].iloc[:, 3].tolist()
us_Federal_district = pd.read_html(us_url)[1].iloc[:, 0].tolist()
us_Inhabited_territories = pd.read_html(us_url)[2].iloc[:, 0].tolist()
us_Uninhabited_territories = pd.read_html(us_url)[3].iloc[:, 0].tolist()
us_Disputed_territories = pd.read_html(us_url)[4].iloc[:, 0].tolist()
us = us_states + us_cities + us_Federal_district + us_Inhabited_territories + us_Uninhabited_territories + us_Disputed_territories
in_url = 'https://en.wikipedia.org/wiki/States_and_union_territories_of_India#States_and_Union_territories'
in_states = pd.read_html(in_url)[3].iloc[:, 0].tolist() + pd.read_html(in_url)[3].iloc[:, 4].tolist() + pd.read_html(in_url)[3].iloc[:, 5].tolist()
in_unions = pd.read_html(in_url)[4].iloc[:, 0].tolist()
ind = in_states + in_unions
usToStr = ' '.join([str(elem) for elem in us])
indToStr = ' '.join([str(elem) for elem in ind])
# Country name checker function
def checkl(T):
TSplit_space = [x.lower().strip() for x in T.split()]
TSplit_comma = [x.lower().strip() for x in T.split(',')]
TSplit = list(set().union(TSplit_space, TSplit_comma))
res_ind = [ele for ele in ind if(ele in T)]
res_us = [ele for ele in us if(ele in T)]
if 'india' in TSplit or 'hindustan' in TSplit or 'bharat' in TSplit or T.lower() in indToStr.lower() or bool(res_ind) == True :
T = 'India'
elif 'US' in T or 'USA' in T or 'United States' in T or 'usa' in TSplit or 'united state' in TSplit or T.lower() in usToStr.lower() or bool(res_us) == True:
T = 'USA'
elif len(T.split(','))>1 :
if T.split(',')[0] in indToStr or T.split(',')[1] in indToStr :
T = 'India'
elif T.split(',')[0] in usToStr or T.split(',')[1] in usToStr :
T = 'USA'
else:
T = "Others"
else:
T = "Others"
return T
# Appling the function on the dataframe column
print(df['user_location'].dropna().apply(checkl).value_counts())
</code></pre>
<pre><code>Others 74206
USA 47840
India 20291
Name: user_location, dtype: int64
</code></pre>
<p>I am quite new in python coding. I think this code can be written in a better and more compact form. Also, I think there are still a lot of edge cases left to deal with.</p>
<p>Any criticisms and suggestions to improve the efficiency & readability of my code would be greatly appreciated. Also, I want to know if there exist any dedicated python modules so that it can convert all the locations automatically into their country names!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T22:56:07.423",
"Id": "487976",
"Score": "2",
"body": "I'm Pretty sure this would report Indiana and Indianapolis as India belongings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T04:03:55.347",
"Id": "487983",
"Score": "0",
"body": "Yes, it's one of the issues my code couldn't solve. \nIf I interchange the conditions of `if` and `elif` statements, it would report `India` as USA belongings. \nCan you please suggest me how to improve it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T05:01:23.930",
"Id": "487986",
"Score": "0",
"body": "I found a way for it though I am not sure about the efficiency. I have updated my code by removing the `'India' in T` from the `if` statement. Kindly check it now."
}
] |
[
{
"body": "<p><strong>Test cases</strong></p>\n<p>I would create test cases. Something like the code below, but using the <code>unittest</code> or <code>pytest</code> module would be better. That way you can change the code with more confidence.</p>\n<pre><code>known_values = [\n ('astroworld', 'Others'),\n ('New York, NY', 'USA'),\n ('Indianapolis, IN', 'USA'),\n ('Pewee Valley, KY', 'USA'),\n ('Stuck in the Middle ', 'Others'),\n ('Jammu and Kashmir', 'India'),\n ('Новоро́ссия', 'Others'),\n ('Gainesville, FL', 'USA'),\n ('Dhaka,Bangladesh', 'Others'),\n ('Hotel living - various cities! Who needs a home when hotel living is so fabulous!', 'Others'),\n ('Africa', 'Others'),\n ('New Delhi', 'India'),\n ('Nagaland, India', 'India'),\n ('Brussels', 'Others'),\n ('Florida, USA', 'USA'),\n ('Northwest Indiana', 'USA'),\n ('Graz', 'Others'),\n ('Mumbai, India', 'India'),\n ]\n\nfor user_loc, loc in known_values:\n print(user_loc) # The last printed before the assertion error that fails, feel free to comment out\n assert checkl(user_loc) == loc\n</code></pre>\n<p><strong>read_html</strong></p>\n<p>I would use pd.read_html just twice, for the two files, and I would use those dataframes later many times. For example:</p>\n<pre><code>india_table = pd.read_html(in_url)\nin_states = india_table[3].iloc[:, 0].tolist() + india_table[3].iloc[:, 4].tolist() + \\\n india_table[3].iloc[:, 5].tolist()\nin_unions = india_table[4].iloc[:, 0].tolist()\n</code></pre>\n<p>I guess it is faster, because there is no need to fetch and read the web page several times.</p>\n<p><strong>Other</strong></p>\n<p>You might define TSplit like that:</p>\n<p>TSplit = T.strip().lower().replace(",", " ").split()</p>\n<p>This replaces the commas with spaces first, so you don't need to parse twice. Its result will be different however. I'm not sure which is the best.</p>\n<p>For example here are the results for <code>Talangana Hyderabad, India</code> and <code>Minneapolis,MN</code>:</p>\n<pre><code> new TSplit: ['talangana', 'hyderabad', 'india']\nold TSplit: ['india', 'hyderabad,', 'talangana hyderabad', 'talangana']\n new TSplit: ['minneapolis', 'mn']\nold TSplit: ['minneapolis,mn', 'mn', 'minneapolis']\n</code></pre>\n<p>I would change <code>bool(res_ind) == True</code> to <code>len(res_ind) > 0</code>. It's clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T05:28:33.663",
"Id": "488072",
"Score": "0",
"body": "Thank you for your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T06:07:08.280",
"Id": "488076",
"Score": "0",
"body": "Where should I put your fist code block of test cases in my code? If I put it below my `checkl()` function, it gives me `AssertionError` in Jupyter Notebook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T06:11:17.570",
"Id": "488078",
"Score": "0",
"body": "And also, your suggested modification has reduced the `USA` frequency from `47840` to `47837`! Why is it happening?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T07:48:42.653",
"Id": "488091",
"Score": "1",
"body": "Instead of the assert column, you can use print(checkl(user_loc), loc, user_loc) and you can see which assertion fails. Assertion error means, that at least in one of the cases my assumption is not true. I've run the code in your question and the tests and it haven't failed, so you might have changed the checkl function. Running the test cases shouldn't alter the results. It is just calls the checkl functions some times, doesn't change the df data frame, so the result of the print in the end should be the same, as the one without testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T09:40:00.717",
"Id": "488099",
"Score": "0",
"body": "Yes, `print(checkl(user_loc), loc, user_loc) ` is working okay."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T09:41:15.423",
"Id": "488100",
"Score": "0",
"body": "In previous comment, I meant, your suggested modification (on `TSplit`) is reducing the `USA` frequency from `47840` to `47837`. I don't understand why does it change! \nAs I can't properly show a code block in the comment, I am giving a Pastebin link of the modified `checkl` function: https://paste.ubuntu.com/p/Yvhsr8jrkq/\nPlease check it.\nAnother thing, if you have seen my updated question (the output of my test list `P`), my function `checkl` is printing `Others` for some USA locations with lower case. Can you please tell me how to fix that drawback?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:36:24.327",
"Id": "488121",
"Score": "0",
"body": "@raf It is easy to find the differences. You can print the cases where the result is different. You create the new version with a different name like checkl2, then\nfor uloc in df.user_location:\n if chekl(uloc) != checkl2(uloc):\n print(chekl(uloc), checkl2(uloc), uloc)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T07:01:32.503",
"Id": "488189",
"Score": "0",
"body": "While trying to compare between `checkl` and `checkl2` by your suggestion, it gave me: `AttributeError: 'float' object has no attribute 'split'`!. Kindly check my [code (Pastebin link)](https://paste.ubuntu.com/p/tTx8vtg4N5/) and [error (Pastebin link)](https://paste.ubuntu.com/p/Y4MW69nMNN/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T07:14:19.467",
"Id": "488192",
"Score": "0",
"body": "Ok. This works like this `if not pd.isna(uloc) and checkl(uloc) != checkl1(uloc):` But I can't find any differences. I use the dataset from here: https://www.kaggle.com/gpreda/covid19-tweets/version/24"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T07:21:52.613",
"Id": "488195",
"Score": "0",
"body": "You may wonder what does df.user_location mean. If the column name don't have spaces or spectial characters, we can use it like that instead of df['user_location']. With Jupyter's and Pycharm's autocomplete feature it is easy to type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T07:26:55.687",
"Id": "488197",
"Score": "1",
"body": "In your original code there was a dropna. We could use ` for uloc in df.user_location.dropna():` so we don't need to change the condition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T07:54:59.237",
"Id": "488198",
"Score": "1",
"body": "Your TSplit is different than mine. Here is the comparison for the user locations https://gist.github.com/horvatha/0c20faa86bfb6dd77a48dc44892b2651#file-tsplit-txt-L64. See for example \"Carlsbad, California US\" at line 74. The old version has \"california us\" in the list, and it has \"carlsbad,\" with comma at the end too (you know why, don't you?). You can see Atlanta | St. Louis | Miami at line 64. You would consider to handle vertical lines as well. I would recommend to create a separate function to split the user location. It is easier to test that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T08:04:35.833",
"Id": "488201",
"Score": "1",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/112817/discussion-between-arpad-horvath-and-raf)."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T11:36:36.660",
"Id": "249033",
"ParentId": "248918",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T14:26:56.200",
"Id": "248918",
"Score": "4",
"Tags": [
"python",
"pandas",
"data-visualization"
],
"Title": "Converting location names into country names in pandas dataframe"
}
|
248918
|
<p>I have a link aimed to <code>'/FridgeTemperatureRoute'</code> and a checkbox. Purpose of the checkbox is to show the user whether the check has been done or not.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="row">
<div class="col">
<a id="FridgeTemperatureBtn" href="/FridgeTemperatureRoute">Fridge and Freezer Temperature</a>
</div>
<div class="col">
<input id="FridgeTemperatureCheckBox" type="checkbox" name="" value="" disabled {{fridgeFreezerTemperatureReturnObj}}>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong>Summary of code</strong></p>
<p>You'll see this line <code>{{fridgeFreezerTemperatureReturnObj}}</code> - this is from Node JS server, which determines whether the <code>checkbox</code> <code>is ticked or not</code>.</p>
<p><strong>Jquery, Javascript and Bootstrap Model</strong></p>
<p>Next, I am aiming to open a bootstrap <code>model</code> on user click, but only if the <code>checkbox</code> is <code>ticked</code>. If the user clicks and the checkbox is checked, then open a bootstrap model asking whether to continue to the <code>href</code> or simply cancel rendering the next page.</p>
<pre><code> <!-- Modal confirm -->
<div class="modal" id="confirmModal" style="display: none; z-index: 1050;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="confirmMessage">
<p>You have already completed this check, do you want to do it again?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="confirmOk">Ok</button>
<button type="button" class="btn btn-default" id="confirmCancel" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
if(document.getElementById('FridgeTemperatureCheckBox').checked){
$('#FridgeTemperatureBtn').attr('data-toggle', 'modal');
$('#FridgeTemperatureBtn').attr('data-target', '#confirmModal');
document.getElementById('FridgeTemperatureBtn').addEventListener('click', function(e){
$('#confirmOk').click(function(){
window.location.href = '/FridgeTemperatureRoute';
});
});
}
</script>
</code></pre>
<p><strong>Summary</strong></p>
<p>I have it working - but I believe it can be simplified. Just looking for some reviews and where I can improve on :)</p>
|
[] |
[
{
"body": "<h2>Be consistent</h2>\n<p>If you're going to use jQuery, it would be stylistically appropriate (and terser) to use it instead of the native DOM methods. For example:</p>\n<pre><code>if(document.getElementById('FridgeTemperatureCheckBox').checked){\n</code></pre>\n<p>can turn into</p>\n<pre><code>if ($('#FridgeTemperatureCheckBox').is(':checked')) {\n</code></pre>\n<p>To translate <code>getElementById</code> to jQuery or <code>querySelector</code>, put a <code>#</code> in front of the ID you want to select.</p>\n<p>Or you can use vanilla DOM methods everywhere if you prefer (like I do) - but whatever you choose to do, it would be good to do it <em>consistently</em>, otherwise you'll probably confuse future readers of the code.</p>\n<p><strong>HTML too</strong>: On a similar note about consistency - with your element IDs, better to choose either <code>camelCase</code>, <code>PascalCase</code>, or <code>kebab-case</code> everywhere, but don't mix and match different styles, else you're more likely to run into typo problems when you don't have a set style and mis-remember which style you used. (You can also consider using classes instead of IDs, since IDs with their <a href=\"https://stackoverflow.com/q/3434278\">automatically global variables</a> are unintuitive and can cause bugs.)</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> code</h2>\n<p>Rather than selecting the same element multiple times, eg:</p>\n<pre><code>$('#FridgeTemperatureBtn').attr('data-toggle', 'modal');\n$('#FridgeTemperatureBtn').attr('data-target', '#confirmModal');\n</code></pre>\n<p>It would be more elegant to select the element <em>once</em> and save it in a variable. Or, even better, since <code>.attr</code> returns the existing jQuery collection, just chain the <code>.attr</code> calls:</p>\n<pre><code>$('#FridgeTemperatureBtn')\n .attr('data-toggle', 'modal')\n .attr('data-target', '#confirmModal');\n</code></pre>\n<p><strong>Attach listener once, immediately</strong>: It looks like the <code>confirmModal</code> only becomes visible when the user clicks the button <em>and</em> has already completed the check, is that correct? If so, consider attaching the <code>#confirmOk</code> click listener immediately, rather than only after the <code>#FridgeTemperatureBtn</code> is clicked. (Attaching identical listeners multiple times won't cause problems in this case, but it's peculiar logic.)</p>\n<p><strong>Semantics:</strong> Your <code>FridgeTemperatureBtn</code> is an <code><a></code>, not a button, so its ID's name should probably be tweaked. If you have it styled to look like a button with your CSS, it would probably be a bit <a href=\"https://www.reddit.com/r/webdev/comments/hwourm/friendly_reminder_that_visually_styling_a_button/\" rel=\"nofollow noreferrer\">more semantically appropriate</a> to surround a <code><button></code> inside an <code><a></code> instead.</p>\n<p><strong>Unchangeable checkbox UX</strong>: The <code>#FridgeTemperatureCheckBox</code> is <code>disabled</code>. Having it be a checkbox is a bit unintuitive, because users generally expect checkboxes to be clickable. Consider informing the user that the check has already been done some other way, such as by adding a <a href=\"https://www.shutterstock.com/image-vector/green-check-mark-icon-tick-symbol-522874111\" rel=\"nofollow noreferrer\">checkmark</a> (not a checkbox), or by changing the background color, or something like that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T18:11:12.043",
"Id": "487785",
"Score": "1",
"body": "Yeah, I think you're right. Sectioning is a lot more suited for CR which is often about nitpicking a bunch of things."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T16:45:27.350",
"Id": "248921",
"ParentId": "248919",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248921",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:01:36.373",
"Id": "248919",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"handlebars"
],
"Title": "Confirmation Model with jQuery"
}
|
248919
|
<p>I'm not actually that new to writing Python. But I've no formal training and have only learnt to build applications to solve problems for my job out of necessity. Starting to bring my existing skills up to a professional standard is a long overdue project. I'd like to humbly post some snippets here for criticism to guide me in filling the gaping holes in my education.</p>
<p>This is also my first post, so I hope I'm not one of the 10-20 people a day who haven't read the rules correctly.</p>
<p><strong>Context</strong></p>
<p>The below is a working part of a Django project which will automate some workflows for me. The class in this snippet is used to interact with Xero, an accounting platform I use for my finances, via their API.</p>
<p>Docs for the Xero API are <a href="https://developer.xero.com/documentation/" rel="noreferrer">here</a>. The interaction with Xero is working, so my main concern is with the quality and layout of my work. However my error-handling feels shoddy so any pointers there would be amazing too.</p>
<p>I have a Django app called <code>apis</code> in the project which includes Python files for interaction with specific external APIs. The classes within are instantiated from elsewhere in the project to complete various different workflows involving those external platforms. There are also very basic models in the app for storing access tokens between uses.</p>
<p><strong>xero.py</strong></p>
<pre><code>import json
from datetime import datetime
import requests
from django.core import signing
from environ import Env
from apis.models import XeroAccessToken
env = Env()
class XeroApi:
def __init__(self):
pass
# auth functions
def get_auth_url(self):
scope = 'offline_access ' \
'openid ' \
'accounting.transactions ' \
'accounting.contacts ' \
'accounting.settings'
return ('https://login.xero.com/identity/connect/authorize'
'?response_type=code'
'&client_id={}'
'&redirect_uri={}'
'&scope={}'
'&state={}').format(
env('XERO__CLIENT_ID'),
env('XERO__REDIRECT_URI'),
scope,
env('XERO__STATE')
)
def request_token(self, auth_code):
auth_credentials = base64.urlsafe_b64encode(
bytes(
'{}:{}'.format(
env('XERO__CLIENT_ID'),
env('XERO__CLIENT_SECRET')
),
'utf-8'
)
).decode('utf-8')
headers = {
'Authorization': 'Basic {}'.format(auth_credentials)
}
payload = {
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': env('XERO__REDIRECT_URI')
}
return requests.post(
'https://identity.xero.com/connect/token',
headers=headers,
data=payload
)
def refresh_token(self, access_credentials):
auth_credentials = base64.urlsafe_b64encode(
bytes(
'{}:{}'.format(
env('XERO__CLIENT_ID'),
env('XERO__CLIENT_SECRET')
),
'utf-8'
)
).decode('utf-8')
headers = {
'Authorization': 'Basic {}'.format(auth_credentials),
'Content-Type': 'application/x-www-form-urlencoded'
}
payload = {
'grant_type': 'refresh_token',
'refresh_token': access_credentials['refresh_token']
}
return requests.post(
'https://identity.xero.com/connect/token',
headers=headers,
data=payload
)
def get_tenant_id(self, access_token):
url = 'https://api.xero.com/connections'
headers = {
'Authorization': 'Bearer {}'.format(access_token),
'Content-Type': 'application.json'
}
response = requests.get(url, headers=headers).json()
return response[0]['tenantId']
def retrieve_stored_token(self):
access_token_objects = XeroAccessToken.objects.all()
if len(access_token_objects):
access_credentials = json.loads(
signing.loads(
access_token_objects[0].signed_access_credentials
)
)
tenant_id = signing.loads(access_token_objects[0].signed_tenant_id)
return access_credentials, tenant_id
else:
return False, False
def update_access_credentials(self):
credentials, tenant_id = self.retrieve_stored_token()
if not credentials:
return {'error': 'Access credentials not found.'}
now = datetime.now()
expires_at = datetime.fromtimestamp(credentials['expires_at'])
if expires_at < now:
credentials = self.refresh_token(credentials).json()
credentials['expires_at'] = datetime.timestamp(
now
) + credentials['expires_in'] - 30
credentials_object = XeroAccessToken.objects.all()[0]
credentials_object.signed_access_credentials = signing.dumps(
json.dumps(credentials)
)
credentials_object.save()
return {
'Authorization': 'Bearer {}'.format(credentials['access_token']),
'Xero-tenant-id': tenant_id,
'Accept': 'application/json'
}
# operational functions
def get(self, endpoint, params={}):
headers = self.update_access_credentials()
if 'error' in headers:
return {'failure': True, 'error': headers['error']}
page = 1
more = True
content = []
while more:
url = 'https://api.xero.com/api.xro/2.0/{}?page={}'.format(
endpoint, page
)
response = self._clean_get(
requests.get(url, headers=headers, params=params)
)
if 'failure' in response:
return response
content += response[endpoint]
page += 1
if len(response[endpoint]) < 100:
more = False
return {'failure': False, 'content': content}
def post(self, endpoint, payload):
headers = self.update_access_credentials()
if 'error' in headers:
return {'failure': True, 'error': headers['error']}
url = 'https://api.xero.com/api.xro/2.0/{}'.format(endpoint)
response = self._clean_post(
requests.post(url, headers=headers, data=json.dumps(payload))
)
if 'failure' in response:
return response
return {'failure': False, 'content': response}
def email_document(self, endpoint, id):
headers = self.update_access_credentials()
if 'error' in headers:
return {'failure': True, 'error': headers['error']}
url = 'https://api.xero.com/api.xro/2.0/{}/{}/Email'.format(
endpoint, id
)
response = self._clean_post(requests.post(url, headers=headers))
if 'failure' in response:
return response
return {'failure': False, 'content': response}
# utils
def _clean_get(self, response):
if response.status_code > 299:
return {'failure': True,
'status_code': response.status_code,
'error': response.reason}
return response.json()
def _clean_post(self, response):
try:
response = response.json()
if 'ErrorNumber' in response:
message = response['Message']
if 'Elements' in response:
for element in response['Elements']:
if 'ValidationErrors' in element:
for error in element['ValidationErrors']:
message += ' | {}'.format(error['Message'])
return {'failure': True,
'status_code': response['ErrorNumber'],
'error': message}
return response
except ValueError:
if response.status_code > 299:
return {'failure': True,
'status_code': response.status_code,
'error': response.reason}
return response
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T17:27:31.293",
"Id": "487778",
"Score": "0",
"body": "Welcome to CR! I don't really have the time for an answer right now but the first thing that came to mind are the missing error exceptions. What happens if a request throws an exception? Wouldn't that make your whole app crash? Also, there's no `logging` and so how do you know what happens to your app except for what you present in the client?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T10:39:17.010",
"Id": "488003",
"Score": "0",
"body": "Thanks @GrajdeanuAlex.! I have been trying to handle unexpected exceptions (asking for forgiveness) as part of the workflow in which this class is used, while this class focusses on expected issues returned from the external server (asking for permission).\n\nAppreciate the point about logging. The same applies as above with regard to the workflow using the class, but I think I could do with some more development in that area. I will do some learning today."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T15:10:51.600",
"Id": "248920",
"Score": "6",
"Tags": [
"python",
"beginner",
"api",
"django"
],
"Title": "Xero API Client in Django"
}
|
248920
|
<p>I have a list of <code>Component</code>s. When an actor is connected, I want to run <code>onActorConnected</code> on each component. However, if a component's <code>onActorConnected</code> method throws an exception for whatever reason, this cannot affect other components' execution of that method.</p>
<p>Here's a minimized extract of my code:</p>
<pre><code>import static java.lang.String.format;
public class Match {
private final Set<Actor> actors = ...;
private final List<MatchComponent> components = ...;
public void connectActor(@NotNull Actor actor) {
if (actors.contains(actor))
throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));
actors.add(actor);
// This is hard to read!
// But I will be doing this in a lot of places, so I want to keep in short.
components.forEach(c-> runOrLogException(() -> c.onActorConnect(actor), c.getName(), "onActorConnect"));
}
// The same pattern will be used in `disconnectActor` and other similar methods.
private void runOrLogException(@NotNull Runnable runnable, @NotNull String instanceName, @NotNull String methodName) {
try {
runnable.run();
} catch (Exception e) {
logger.log(Level.SEVERE, format("'%s' on '%s' in '%s' threw an exception.", methodName, instanceName, this.getName()), e);
}
}
}
</code></pre>
<p>My question primarily is about whether this is a good way to do it? I fear I might be missing some way of using Java's lambdas to make this cleaner.</p>
<p>Bonus question is whether it's considered good practice to throw an exception if an "actor" is already connected. I considered just returning <code>false</code> if this is the case, but I do not ever expect myself to call this method if an actor is already connected. If that happens, something has gone wrong somewhere. I instead provide an <code>isActorConnected</code> method that the caller can use to explicitly handle such a case.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T22:00:42.030",
"Id": "487874",
"Score": "0",
"body": "\"But I will be doing this in a lot of places, so I want to keep in short.\" as in \"it must run fast\" or as in \"copy and paste\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T22:04:37.513",
"Id": "487875",
"Score": "0",
"body": "Maybe I'm failing to see something here, but couldn't you do it with `runOrLogException(Actor actor, Function<Actor> function)` and then call it with `runOrLogException(actor, actor::onActorConnected)`? That would clear the calling code up."
}
] |
[
{
"body": "<p>Are there certain exceptions you can anticipate for <code>onActorConnected</code>? Let's make an encompassing checked exception <code>ActorUnconnectableException</code>, though this would need to be be made more finegrained for particular connectivity issues:</p>\n<pre><code>class ActorUnconnectableException extends Exception {\n ActorUnconnectableException(Actor actor, MatchComponent component) {\n super(\n String.format("actor: %s cannot connect to component: %s", actor.getName(), component.getName())\n );\n }\n}\n</code></pre>\n<p>And declare <code>onActorConnect</code> within <code>MatchComponent</code> like this:</p>\n<pre><code>void onActorConnect(Actor actor) throws ActorUnconnectableException {\n ...\n}\n</code></pre>\n<p>The reason I advocate for a checked exception here is because it sounds like the it is hard to guarantee that an <code>Actor</code> is connectable without attempting to connect it. If we were able to verify that an <code>Actor</code> is connectable beforehand, an unchecked exception would be better suited here.</p>\n<p>For something like a string that we're trying to parse as a number, let's say this parsable string is typed in our frontend. We can enforce through whatever frontend framework that this string contains only digits. That's why <code>Integer::parseInt</code> throws an unchecked exception, it expects that the validation is done before hand.</p>\n<p>Another thing that can be improved is this:</p>\n<pre><code>if (actors.contains(actor))\n throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));\n\nactors.add(actor);\n</code></pre>\n<p>Apart from adding braces for the <code>if</code>, we can utilize the fact that <code>actors::add</code> returns <code>true</code> if <code>actor</code> is not contained, otherwise <code>false</code>, like this:</p>\n<pre><code>boolean actorAdded = actors.add(actor);\n\nif (!actorAdded) {\n throw new IllegalArgumentException(format("Actor '%s' is already connected.", actor.getName()));\n}\n</code></pre>\n<p>This should remain an unchecked exception cause the calling code should be able to determine whether it already added an <code>Actor</code> equal to <code>actor</code> beforehand.</p>\n<p>The rest of <code>connectActor</code> ends up looking like this:</p>\n<pre><code>var unconnectableComponents = new ArrayList<MatchComponent>();\n\nfor (MatchComponent component : components) {\n try {\n component.onActorConnect(actor);\n }\n catch (ActorUnconnectableException e) {\n unconnectableComponents.add(component);\n }\n}\n\n// Log `unconnectableComponents` or create new exception to report their collective failure.\n</code></pre>\n<p>This definitely ends up looking verbose, but the idea is that we want things outside of the calling code's control (like whether can actor is in fact connectable, which sounds like it can't be decided beforehand) to be checked at compile time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T21:11:20.953",
"Id": "248971",
"ParentId": "248922",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T17:30:16.343",
"Id": "248922",
"Score": "1",
"Tags": [
"java",
"stream",
"lambda"
],
"Title": "Concise and exception-prone method for running method on component"
}
|
248922
|
<p>I have a ViewModel where objects are all <code>string</code> and the model from the database <code>Address</code> is a list. I wanted to know if there is any other way to set the viewModel string values other then the way I have it done below? Any advice on how to make this code; cleaner, more effective, just overall better!</p>
<pre><code> static void Main(string[] args)
{
//EF Data
List<Address> ListOfProducts = new List<Address>();
ListOfProducts.Add(new Address() { StreetLine1="address 1",StreetLine2="address line2 1" });
ViewModelAddress vm = new ViewModelAddress();
vm.StreetLine1 = ListOfProducts.Select(a => a.StreetLine1).FirstOrDefault();
vm.StreetLine2 = ListOfProducts.Select(a => a.StreetLine2).FirstOrDefault();
}
class Address
{
public string StreetLine1 { get; set; }
public string StreetLine2{ get; set; }
}
class ViewModelAddress
{
public string StreetLine1 { get; set; }
public string StreetLine2 { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T18:43:56.060",
"Id": "487789",
"Score": "2",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site."
}
] |
[
{
"body": "<p>This line is confusing.</p>\n<pre><code>List<Address> ListOfProducts = new List<Address>();\n</code></pre>\n<p>Should it be</p>\n<pre><code>List<Address> addresses = new List<Address>();\n</code></pre>\n<p>The example you have provided is rather simple. Since the view model is exactly the same as the source object you might as well use an anonymous type and just not include the properties you do not want to see in the view model.</p>\n<pre><code>static string Main(string[] args)\n{\n List<Address> addresses = new List<Address>();\n addresses.Add(new Address() { StreetLine1 = "address 1", StreetLine2 = "address line2 1", Postcode = "pstc0d3" });\n\n // no postcode\n var vm = addresses.Select(_ => new { _.StreetLine1, _.StreetLine2 }).FirstOrDefault();\n}\n\nclass Address\n{\n public string StreetLine1 { get; set; }\n public string StreetLine2 { get; set; }\n\n public string Postcode { get; set; }\n}\n</code></pre>\n<p>The variable vm will have the properties StreetLine1 and StreetLine2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:22:59.857",
"Id": "248935",
"ParentId": "248924",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248935",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T18:32:34.157",
"Id": "248924",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "Model return List object"
}
|
248924
|
<p>Here is my bubble sort algorithm that I would like to improve in any way possible</p>
<pre><code>#include<iostream>
int main(){
int arr[6] = {5,2,3,7,2,6};
int f = 0;
int b = 0;
for(int i = 1;i < 6;i++){
if(arr[i] < arr[i-1]){
f = arr[i];
b = arr[i-1];
arr[i] = b;
arr[i-1] = f;
i=1;
}
}
for(int i = 0;i < 6;i++) std::cout << arr[i] << " ";
}
</code></pre>
<p>Anything is appreciated</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T20:29:33.127",
"Id": "487795",
"Score": "4",
"body": "Please do not modify the question after it has been answered, it is against the [code review rules](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:07:55.010",
"Id": "487798",
"Score": "4",
"body": "I rolled back your last edit. As pacmaninbw stated earlier: after getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
}
] |
[
{
"body": "<p>Some notes:</p>\n<ul>\n<li>I would avoid running a loop while changing <code>i</code> inside, it is very unclear to the reader. I prefer using two nested loops.</li>\n<li>The swap can be done in one step less</li>\n<li>I would initialize a size variable and use it throughout the code instead of hard-coding 6.</li>\n<li>Printing the array to the console should be in a separate function (as well as the sorting function really).</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include<iostream>\n\nint main(){\n const int sz = 6;\n int arr[sz] = {5,2,3,7,2,6};\n do{\n swapped = false;\n for(int i = 1;i < sz; i++){\n if(arr[i] < arr[i-1]){\n int tmp = arr[i];\n arr[i] = arr[i-1];\n arr[i-1] = tmp;\n swapped = true;\n }\n }\n } while(swapped);\n print_array(arr, sz);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:11:07.310",
"Id": "487838",
"Score": "4",
"body": "How about using `std::swap(arr[i], arr[i - 1])`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T10:31:33.493",
"Id": "487907",
"Score": "0",
"body": "@L.F. It is preferred to use `std::swap`, I would also prefer to use `std::array` or `std::vector`. I just followed the C-style code in original question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T19:45:51.830",
"Id": "248927",
"ParentId": "248925",
"Score": "4"
}
},
{
"body": "<p>You don't implement the obvious optimization to Bubble sort. If you run through the inner loop and no swapping is done then the array is now sorted.</p>\n<p>This reduces the "Best Case" complexity to <code>O(n)</code> rather than the <code>O(n^2)</code> that you have implemented.</p>\n<hr />\n<p>Your sort is based on integers. That is not very useful in C++ as arrays can be of nearly anything. So you should think of this as being able to sort a list of anything.</p>\n<p>Sure you say I just change the type <code><int></code> to something I want and recompile.</p>\n<p>Sure I say. But if you choose a type <code>T</code> that is large your code becomes very ineffecient becuase you make copies of the object in the middle of the loop.</p>\n<pre><code> std::array<MyBigType> arr;\n\n int tmp = arr[i]; // You made a copy of the object here.\n f = arr[i]; // You made a copy of the object here. \n b = arr[i-1]; // You made a copy of another object here.\n</code></pre>\n<p>So each time you are doing a swap you are making three copies of the object.</p>\n<p>You can do better by using <code>std::move()</code> to move the object. Or you can use <code>std::swap()</code> or <code>std::swap_iter()</code> to do a more efficient job of moving large objects.</p>\n<hr />\n<p>Your code assumes that you are sorting a C-array. In C++ we handle things differently we abstract away the container by referring to things with iterators. That way we can sort any type of container by simply providing the iterator.</p>\n<p>Now different iterators have different properties and you can potentially optimze the algorithm by the type of the iterator you are using.</p>\n<hr />\n<p>Most importantly the code does not work.<br />\n<strike>You only have a single loop. You need a nested loop (I assume some</p>\n<p>You perform a sort of copy paste issue!</strike>\nI assumed it did not work because I did not understand the hack you did to simulate a second loop. It is still broken.</p>\n<hr />\n<p>It is written in a way that makes it hard to read.<br />\nCode is designed to be read by humans. Write the code in a away that is easy to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T20:24:33.740",
"Id": "487794",
"Score": "0",
"body": "I didn't understand, why doesn't this code work? I am looking to sort an array of integers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:30:05.407",
"Id": "487803",
"Score": "0",
"body": "@Martin look at the sneaky `i=1` at the end of the `if`, if a swap is detected then he reiterates the array which acts like a pseudo-nested- loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T01:12:25.453",
"Id": "487814",
"Score": "0",
"body": "@AryanParekh See superb rain answer above. I assumed it was it was missing a loop, Turns out to be designed to be hard to read instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T20:06:05.940",
"Id": "248928",
"ParentId": "248925",
"Score": "4"
}
},
{
"body": "<ol>\n<li>It's wrong. For example for input <code>{5,9,3,7,2,6}</code> you print <code>5 2 3 6 7 9</code>.</li>\n<li>It's not bubble sort. More like an inefficient insertion sort.</li>\n<li>It's not O(n<sup>2</sup>) but only O(n<sup>3</sup>). For example for input <code>int arr[100] = {99,98,97,...,2,1,0}</code> you have <a href=\"https://repl.it/repls/MistyIgnorantNormalform#main.cpp\" rel=\"nofollow noreferrer\">161,799 iterations</a> of your loop (that's 100C3 + 99).</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:02:00.873",
"Id": "487796",
"Score": "0",
"body": "Yes I had a small mistake, instead of i=1 It should be i=0"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T20:58:36.583",
"Id": "248930",
"ParentId": "248925",
"Score": "2"
}
},
{
"body": "<p>I would suggest to use the newer C++ stuff at least where it very obviously simplifies the code.</p>\n<ol>\n<li><p>The</p>\n<pre><code> int tmp = arr[i];\n arr[i] = arr[i-1];\n arr[i-1] = tmp;\n</code></pre>\n</li>\n</ol>\n<p>can be written in one line instead of three:</p>\n<pre><code> std::swap(arr[i], arr[i-1]);\n</code></pre>\n<ol start=\"2\">\n<li><p><code>std::array</code> is just the same as the plain old array but knows the own size:</p>\n<pre><code> std::array<int,6> arr = {5,2,3,7,2,6};\n</code></pre>\n</li>\n</ol>\n<p>and then you can use <code>arr.size()</code> instead of hard coded 6 over the rest of the code. Unlike <code>std::vector</code>, <code>std::array</code> is a light structure without internal fields or heap allocations.</p>\n<ol start=\"3\">\n<li><p>For printing the array the C++11 loop is very handy:</p>\n<pre><code>for (auto a: arr) std::cout << a << " ";\n</code></pre>\n</li>\n</ol>\n<p>I am not sure, maybe asking to use iterators would be too much but it would be possible to rewrite with iterators:</p>\n<pre><code> std::array<int,6> arr = {5, 2, 3, 7, 2, 6};\n\n static_assert(arr.size() >= 2);\n auto current = arr.begin();\n auto prev = current++;\n\n while (current != arr.end()) {\n if (*current < *prev) {\n std::swap(*current, *prev);\n current = arr.begin();\n }\n prev = current++;\n }\n\n for (int a: arr) std::cout << a << " ";\n</code></pre>\n<p>This code would be beneficial when sorting something like <code>std::deque</code> where random access like <code>arr[i]</code> is not so efficient. This algorithm only needs immediate access to the current and previous positions. Let's make this its strong side.</p>\n<p><code>static_assert</code> that I added would fail at compilation time, not at runtime, if the array is too small. The size of this array is known for compiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T16:25:10.467",
"Id": "487855",
"Score": "0",
"body": "`std::swap()` is C++98, not exactly new anymore :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T16:47:28.757",
"Id": "487955",
"Score": "0",
"body": "Not only does `std::swap()` do it in one line but more importantly it will use move semantics rather than copy semantics. Thus for larger types (that have the appropriate move defined) it becomes much more efficient."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T16:17:46.220",
"Id": "248963",
"ParentId": "248925",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248927",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T18:40:47.370",
"Id": "248925",
"Score": "2",
"Tags": [
"c++",
"sorting"
],
"Title": "Sorting an array in C++ using Bubble sort"
}
|
248925
|
<p>I'm disturbed about the line <code>value.word = removeSpecialCharacters(value.word);</code>. Is there a elegant way to develop this line?</p>
<pre><code>function checkWords() {
var listOfWords = { word: "abc!!??deftest" };
value.word = removeSpecialCharacters(listOfWords.word);
}
function removeSpecialCharacters(param) {
return param.replace(/\s+/g, " ").replace(/[!?@#$%^&*()+-,.;:'"`\\|]/g, "").trim();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T19:34:40.280",
"Id": "487790",
"Score": "1",
"body": "Looks fine to me, but consider if a whitelist of characters (eg `\\w` and whatever others you permit) might work instead of a big list of special characters"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T04:49:45.250",
"Id": "487817",
"Score": "0",
"body": "Can you add more context about where this function is used and what it's meant to accomplish?"
}
] |
[
{
"body": "<p>This question probably violates the site guideline that reviews should contain <em>real</em> code. Your real code doesn't use names like <code>value</code> and <code>myFunction</code>, does it? Anyway, there's nothing wrong with the line you wrote, but, from just what you've written, I would suggest either of the following patterns:</p>\n<pre><code>var value = {\n word: removeSpecialCharacters("abc!!??deftest"),\n};\n\nfunction modifyWord(input) {\n let value = { word: removeSpecialCharacters(input.word) };\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:39:12.053",
"Id": "488042",
"Score": "0",
"body": "This is part of a website I'm developing, I've isolated this part to show you guys the exact point I'm trying to improve. So, I changed it to look more realistic and thanks for your answer, definitely is a better way to implement it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T19:42:26.067",
"Id": "248968",
"ParentId": "248926",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248968",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T19:32:49.867",
"Id": "248926",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "An elegant way to get the value from function"
}
|
248926
|
<h2>Overview & Motivation</h2>
<p>This project manages and displays sensor data (temperature, humidity, Air Quality Index). The sensor data is <a href="https://www.purpleair.com/map?opt=1/mAQI/a10/cC0&select=22085#5.14/39.646/-3.6" rel="noreferrer">displayed</a> by the sensor manufacturer, <a href="https://www2.purpleair.com/" rel="noreferrer">PurpleAir</a>, but their tool is hard to navigate (e.g. can't look at data more than a few days old) and slow to load.</p>
<p>I've aimed to make a tool that addresses these issues and can be hosted on an individual's own website. Additional features include displaying forecast and current weather for a set location via the <a href="https://openweathermap.org/api" rel="noreferrer">OpenWeather API</a>, and displaying <a href="https://cfpub.epa.gov/airnow/index.cfm?action=aqibasics.aqi#:%7E:text=An%20AQI%20value%20of%20100,generally%20thought%20of%20as%20satisfactory." rel="noreferrer">air quality warnings according to EPA thresholds</a>.</p>
<p>This is how the web app looks right now:</p>
<p><a href="https://i.stack.imgur.com/yJl2S.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yJl2S.png" alt="enter image description here" /></a></p>
<p>This is my first large-ish, self-directed programming project. Any and all improvements welcome!</p>
<h2>Usage</h2>
<p>The app and database for data storage are deployed on <a href="http://dokku.viewdocs.io/dokku/" rel="noreferrer">Dokku</a>. The user needs to push the code to Dokku; set up the app, environment variables, Postgres database, and host; and link a PurpleAir sensor. For full functionality, an OpenWeather API key should also be linked.</p>
<p>User preferences are set via environment variables in Dokku (e.g. latitude/longitude, display defaults). Display settings can be toggled in the app's GUI, which updates via callback.</p>
<p>The app uses Plotly, Dash, and Flask for the app management and dashboard. The Postgres database is managed through Python using psycopg2.</p>
<h2>Contents</h2>
<p>I've included here code for the main app (puts sensor data into database and makes the web app) and the app helper code (plots, data-fetching functions, etc).</p>
<p>The <a href="https://github.com/nmdefries/airdash/tree/91511a43716248d03f8f317e92833b64372eb5c8" rel="noreferrer">code not shown here</a> includes:</p>
<ul>
<li>Functions to calculate Air Quality Index based on pollutant concentrations</li>
<li>Class and methods to manage the database (e.g. inserting data, deleting tables/rows, checking existence of specific observation, etc)</li>
<li>Script to get user-defined environment variables or use defaults if not defined</li>
</ul>
<h2>Code</h2>
<h3>App</h3>
<p>The app file establishes the Dash app object, which manages both the web app and data insertion, and database connections. There are two database connections:</p>
<ul>
<li>One for writing data. This is saved as an attribute of an instance of the DB-managing class. Since all write queries use a single connection, they are done in serial. This could be slow, but since it happens in the background, it doesn't matter.</li>
<li>One for reading data. This is a connection pool so that data-fetching happens in parallel to decrease plot render time.</li>
</ul>
<p>A write procedure is started when the URL receives a POST request from the PurpleAir sensor. This happens every 2 minutes if the sensor and WiFi are working correctly; the sensor data is processed and inserted into the relevant table.</p>
<p>Every time sensor data is received, the code makes a GET request to the OpenWeather API. The API only provides new data about every 15 minutes, so attempts to insert already-seen data are caught by UNIQUE constraints in the relevant tables and rolled back.</p>
<p>The app layout is defined here. The app shows three main plots, which can be manipulated by a series of selector tools (date range, temperature unit, etc). Manipulating a selector triggers one or more callbacks; callbacks are also automatically run every 2 minutes to display the most recent data, since sensor data is updated every 2 minutes. Callbacks for plots fetch data from the database and return formatted plot objects.</p>
<pre><code># -*- coding: utf-8 -*-
# Running app and building webpage.
import dash
import dash_core_components as dcc
import dash_html_components as html
from flask import Flask
from flask import request
# Making plots and handling data.
import plotly.graph_objects as go # More complex plotly graphs
import pandas as pd
from requests import get # Make get requests
import json # Decode jsons
import page_helper as ph # Functions to fetch data and build plots
# Managing database.
import psycopg2
from psycopg2 import extras
from psycopg2 import pool
import database_management as dm
import user_settings as us # JSON header verification, API key, etc.
# Initializing the app and webpage.
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = 'PurpleAir Monitoring'
server = app.server
# Get DB connection pool for fetching data.
connPool = pool.ThreadedConnectionPool(
1, 10, us.databaseUrl, cursor_factory=extras.DictCursor)
# Get read and write DB connection for managing database. Initialize DB object.
writeConn = psycopg2.connect(us.databaseUrl)
db = dm.AirDatabase(writeConn)
# Add incoming data to DB.
@server.route('/sensordata', methods=['POST'])
def insert_data():
if not db:
raise Exception('db object not defined')
if us.header_key and request.headers.get('X-Purpleair') == us.header_key:
db.insert_sensor_row(request.json)
elif not us.header_key:
db.insert_sensor_row(request.json)
if us.loadHistoricalData:
# Add all historical data to DB.
db.load_historal_data()
if us.openWeatherApiKey:
print('querying weather API')
# Make get request to OpenWeather API.
weatherResponse = get("https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&appid={}&units=imperial&lang={}".format(
us.latitude, us.longitude, us.openWeatherApiKey, us.lang))
print('got weather API response')
weatherData = json.loads(weatherResponse.content.decode('utf-8'))
db.insert_weather_row_and_forecasts(weatherData)
return 'done'
# Laying out the webpage.
forecastDisplaySettings = []
if us.showDailyForecast:
forecastDisplaySettings.append('daily')
if us.showHourlyForecast:
forecastDisplaySettings.append('hourly')
app.layout = html.Div(children=[
html.Div([
html.Div([
html.Label('Select a date range to display:'
)], className="three columns"),
html.Div([
dcc.Dropdown(
id='standard-date-picker',
options=[
{'label': '1 day', 'value': '1 day'},
{'label': '3 days', 'value': '3 days'},
{'label': '1 week', 'value': '1 week'},
{'label': '2 weeks', 'value': '2 weeks'},
{'label': '1 month', 'value': '1 month'},
{'label': '6 months', 'value': '6 months'},
{'label': '1 year', 'value': '1 year'},
{'label': 'All time', 'value': 'all'},
{'label': 'Custom date range', 'value': 'custom'}
], value=us.defaultTimeRange
)], className="three columns"),
html.Div([
dcc.DatePickerRange(
id='custom-date-range-picker',
start_date_placeholder_text='Select a date',
end_date_placeholder_text='Select a date',
disabled=True
),
dcc.Interval(
id='fetch-interval',
interval=(2 * 60) * 1000, # 2 minutes in milliseconds
n_intervals=0
)
], className="six columns")
], className="row"),
html.Div([
html.Div('Select forecast to display:', className="three columns"),
html.Div([
dcc.Checklist(
options=[
{'label': 'Hourly forecast', 'value': 'hourly'},
{'label': 'Daily forecast', 'value': 'daily'}
],
value=forecastDisplaySettings,
id='forecast-picker'
)], className="three columns"),
], className="row"),
html.Div(
html.H3('Forecast', id='forecast-heading'),
className="row"),
html.Div([
html.Div(
id='daily-forecast-boxes')
], className="row"),
html.Div([
html.Div(
id='hourly-forecast-display')
], className="row"),
html.Div([
html.H3('Temperature')
], className="row"),
# Plot of temperature. Dropdown to toggle between °F and °C.
html.Div([
html.Div([
dcc.Graph(
id='temp-vs-time',
)], className="eight columns"),
html.Div([
html.Div(
dcc.Dropdown(
id='temp-unit-picker',
options=[
{'label': '°F', 'value': 'temp_f'},
{'label': '°C', 'value': 'temp_c'}
], value='temp_f'
), className="row"),
html.Blockquote(
id='curr-sensor-temp',
className="row"),
html.Blockquote(
id='curr-outside-temp',
className="row")
], className="three columns", style={'position': 'relative'}),
], className="row"),
html.Div([
html.H3('Humidity')
], className="row"),
# Plot of humidity.
html.Div([
html.Div([
dcc.Graph(
id='humid-vs-time',
)], className="eight columns"),
html.Div([], className="four columns")
], className="row"),
html.Div([
html.H3('Air Quality Index')
], className="row"),
# Plot of AQI (both PM 2.5 and 10.0). Multi-select dropdown to toggle between displaying one or both. Text display + color of associated warning message.
html.Div([
html.Div([
dcc.Graph(
id='aqi-vs-time',
)], className="eight columns"),
html.Div([
html.Div([
dcc.Dropdown(
id='aqi-picker',
options=[
{'label': 'PM 2.5', 'value': 'pm_2_5_aqi'},
{'label': 'PM 10.0', 'value': 'pm_10_0_aqi'}
], value=['pm_2_5_aqi', 'pm_10_0_aqi'], multi=True
)], className="row"),
html.Blockquote(id='aqi-warning', className="row")
], className="three columns")
], className="row"),
])
# Webpage callbacks
# Toggle custom date range picker display setting only when date dropdown menu is set to custom.
@ app.callback(
dash.dependencies.Output('custom-date-range-picker', 'disabled'),
[dash.dependencies.Input('standard-date-picker', 'value')])
def displayCustomDateRangePicker(standardDate):
if standardDate == 'custom':
return False
return True
# Regenerate temp vs time graph when inputs are changed.
@ app.callback(
[dash.dependencies.Output('temp-vs-time', 'figure'),
dash.dependencies.Output('curr-sensor-temp', 'children'),
dash.dependencies.Output('curr-outside-temp', 'children')],
[dash.dependencies.Input('standard-date-picker', 'value'),
dash.dependencies.Input('custom-date-range-picker', 'start_date'),
dash.dependencies.Input('custom-date-range-picker', 'end_date'),
dash.dependencies.Input('temp-unit-picker', 'value'),
dash.dependencies.Input('fetch-interval', 'n_intervals')])
def updateTempPlot(standardDate, customStart, customEnd, tempUnit, n):
records = ph.fetchSensorData(connPool, tempUnit, standardDate, [
customStart, customEnd])
weather = ph.fetchWeatherDataNewTimeRange(connPool, tempUnit, standardDate, [
customStart, customEnd])
records = ph.correctTemp(records, tempUnit)
fig = ph.temp_vs_time(records, tempUnit)
fig.add_trace(go.Scattergl(x=weather.ts, y=weather[tempUnit],
mode='markers+lines', line={"color": "rgb(175,175,175)"},
hovertemplate='%{y:.1f}',
name='Official outside'))
currentRecords = ph.fetchSensorData(connPool, tempUnit, '1 day')
currentWeather = ph.fetchWeatherDataNewTimeRange(
connPool, tempUnit, '1 day')
currentRecords = ph.correctTemp(currentRecords, tempUnit)
try:
currSensorStatement = 'Current sensor temperature: {:.0f}°'.format(
currentRecords.iloc[0][tempUnit])
currWeatherStatement = 'Current outside temperature: {:.1f}°'.format(
currentWeather.iloc[0][tempUnit])
except IndexError as e:
print(e)
currSensorStatement = 'Current sensor temperature: Unknown'
currWeatherStatement = 'Current outside temperature: Unknown'
return fig, currSensorStatement, currWeatherStatement
# Regenerate humidity vs time graph when inputs are changed.
@ app.callback(
dash.dependencies.Output('humid-vs-time', 'figure'),
[dash.dependencies.Input('standard-date-picker', 'value'),
dash.dependencies.Input('custom-date-range-picker', 'start_date'),
dash.dependencies.Input('custom-date-range-picker', 'end_date'),
dash.dependencies.Input('fetch-interval', 'n_intervals')])
def updateHumidPlot(standardDate, customStart, customEnd, n):
records = ph.fetchSensorData(connPool, "humidity", standardDate, [
customStart, customEnd])
weather = ph.fetchWeatherDataNewTimeRange(connPool, "humidity", standardDate, [
customStart, customEnd])
records = ph.correctHumid(records)
fig = ph.humid_vs_time(records)
fig.add_trace(go.Scattergl(x=weather.ts, y=weather.humidity,
mode='markers+lines', line={"color": "rgb(175,175,175)"},
hovertemplate='%{y}',
name='Official outside'))
return fig
# Regenerate AQI vs time graph when inputs are changed.
@ app.callback(
[dash.dependencies.Output('aqi-vs-time', 'figure'), dash.dependencies.Output(
'aqi-warning', 'children'), dash.dependencies.Output('aqi-warning', 'style')],
[dash.dependencies.Input('standard-date-picker', 'value'),
dash.dependencies.Input('custom-date-range-picker', 'start_date'),
dash.dependencies.Input('custom-date-range-picker', 'end_date'),
dash.dependencies.Input('aqi-picker', 'value'),
dash.dependencies.Input('fetch-interval', 'n_intervals')])
def updateAqiPlot(standardDate, customStart, customEnd, aqiSpecies, n):
if len(aqiSpecies) == 0:
# Default to showing PM 2.5.
aqiSpecies = ["pm_2_5_aqi"]
records = ph.fetchSensorData(connPool, aqiSpecies, standardDate, [
customStart, customEnd])
warningMessage, style = ph.fetchAqiWarningInfo(
connPool,
aqiSpecies,
standardDate,
[customStart, customEnd])
return ph.aqi_vs_time(records, aqiSpecies), warningMessage, style
# Generate daily forecast display with most recent data.
@ app.callback(
[dash.dependencies.Output('forecast-heading', 'children'),
dash.dependencies.Output('daily-forecast-boxes', 'children')],
[dash.dependencies.Input('forecast-picker', 'value'),
dash.dependencies.Input('temp-unit-picker', 'value'),
dash.dependencies.Input('fetch-interval', 'n_intervals')])
def updateDailyForecast(forecastsToDisplay, tempUnit, n):
if 'daily' not in forecastsToDisplay:
if 'hourly' not in forecastsToDisplay:
return [], []
return 'Forecast', None
tempSelector = {'temp_f': ['min_f', 'max_f'], 'temp_c': ['min_c', 'max_c']}
degreeUnit = {'temp_f': '°F', 'temp_c': '°C'}
columns = ['weather_type_id', 'short_weather_descrip', 'detail_weather_descrip',
'weather_icon', 'precip_chance', 'uvi'] + tempSelector[tempUnit]
records = ph.fetchDailyForecastData(connPool, columns)
blockStyle = {
'backgroundColor': 'rgba(223,231,244,1.0)',
"width": "15%",
"margin-left": '0.83333333333%',
"margin-right": '0.83333333333%',
"border-radius": 10}
lineStyle = {
"margin-left": 15,
"margin-top": 0,
"margin-bottom": 0}
forecastBoxes = []
# TODO: Not recommended to use iterrows(), though this dataframe is quite small.
for index, row in records.iterrows():
if index < 6:
# Customize weather description by weather type. Weather type codes here: https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2
if round(row["weather_type_id"], -2) in (300, 700) or row["weather_type_id"] == 800:
weatherDescription = row["short_weather_descrip"]
elif round(row["weather_type_id"], -2) == 200 or (round(row["weather_type_id"], -2) == 800 and row["weather_type_id"] != 800):
weatherDescription = row["detail_weather_descrip"]
if round(row["weather_type_id"], -2) in (500, 600):
weatherDescription = row["detail_weather_descrip"]
# Swap "shower" and following word.
weatherDescription = weatherDescription.split(' ')
if 'shower' in weatherDescription:
swapIndex = weatherDescription.index('shower')
weatherDescription[swapIndex], weatherDescription[swapIndex +
1] = weatherDescription[swapIndex + 1], weatherDescription[swapIndex]
if round(row["weather_type_id"], -2) == 500:
# Drop any instances of "intensity"
weatherDescription = [
item for item in weatherDescription if item != "intensity"]
weatherDescription = ' '.join(weatherDescription)
weatherDescription = weatherDescription.capitalize()
forecastBoxes.append(
html.Div([
html.B([row['ts'].strftime('%B '), row['ts'].day,
html.Img(
src='http://openweathermap.org/img/wn/{}@2x.png'.format(
row['weather_icon']),
style={'height': '25%',
'width': '25%',
'verticalAlign': 'middle'})],
style={"margin-left": 5}),
html.P([weatherDescription],
style=lineStyle),
html.P(["Min: ",
round(row[tempSelector[tempUnit][0]]),
degreeUnit[tempUnit]],
style=lineStyle),
html.P(["Max: ",
round(row[tempSelector[tempUnit][1]]),
degreeUnit[tempUnit]],
style=lineStyle),
html.P(["Chance of rain: ",
round(row['precip_chance'] * 100), '%'],
style=lineStyle),
html.P(["UV Index: ",
round(row['uvi'], 0)],
style=lineStyle)
], style=blockStyle,
className="two columns"))
return 'Forecast', forecastBoxes
# TODO: Generate hourly forecast display.
@ app.callback(
dash.dependencies.Output('hourly-forecast-display', 'children'),
[dash.dependencies.Input('forecast-picker', 'value'),
dash.dependencies.Input('temp-unit-picker', 'value'),
dash.dependencies.Input('fetch-interval', 'n_intervals')])
def updateHourlyForecast(forecastsToDisplay, tempUnit, n):
if 'hourly' not in forecastsToDisplay:
return []
return 'Hourly forecast display not yet implemented'
tempSelector = {'temp_f': ['min_f', 'max_f'], 'temp_c': ['min_c', 'max_c']}
degreeUnit = {'temp_f': '°F', 'temp_c': '°C'}
if __name__ == '__main__':
app.run_server(debug=True)
</code></pre>
<h3>App helper code</h3>
<p>Each data-fetching function gets a connection and cursor from the connection pool object (provided as an argument). Each data-fetching function is table-specific. Columns to fetch are specified by name as a list of strings (varName; queryFields is intended to be used for processing and renaming table fields, e.g. 'old_field + 2 AS new_field').</p>
<p>The data is formatted as a pandas dataframe and returned. The cursor is closed and the connection is returned to connection pool.</p>
<p>correctTemp() and correctHumid() apply fixed corrections as reported by PurpleAir based on the company's calibration data.</p>
<p>Graphing functions take sensor data and display settings as arguments. Weather API data is added on as a separate trace in the respective callback. The AQI plot function includes stripes of color to reflect EPA AQI safety thresholds. These are added in a loop since I only want to display stripes up to the last one that the largest shown sensor value falls within.</p>
<pre><code># -*- coding: utf-8 -*-
import plotly.graph_objects as go # More complex plotly graphs
import pandas as pd
import psycopg2
import user_settings as us
def fetchSensorData(pool, varName, standardDate=us.defaultTimeRange, customDate=None, queryFields=None, timezone=us.timezone):
"""
Fetch updated data for a single variable or a list of variables when date range is changed.
Args:
varName: str or list of str corresponding to fields in the sensor_data table
standardDate: str
Returns:
pandas dataframe of data fetched
"""
conn = pool.getconn()
conn.set_session(readonly=True)
cur = conn.cursor()
if isinstance(varName, str):
varName = [varName]
names = ['measurement_ts'] + varName
if not queryFields:
queryFields = ', '.join(names)
else:
if isinstance(queryFields, str):
queryFields = [queryFields]
queryFields = ', '.join(['measurement_ts'] + queryFields)
records = None
print("getting sensor data from database...")
# Get data from database within desired time frame.
if standardDate != 'custom':
if standardDate == 'all':
cur.execute(
"SELECT {} FROM sensor_data ORDER BY measurement_ts DESC ".format(queryFields))
else:
cur.execute(
"SELECT {} FROM sensor_data WHERE measurement_ts >= NOW() - INTERVAL '{}' ORDER BY measurement_ts DESC ".format(queryFields, standardDate))
else:
if customDate[0] and customDate[1]:
cur.execute("SELECT {} FROM sensor_data WHERE measurement_ts >= '{}' and measurement_ts <= '{}' ORDER BY measurement_ts DESC ".format(
queryFields, customDate[0], customDate[1]))
else:
records = pd.DataFrame(columns=names)
# Format data.
if not records:
try:
records = pd.DataFrame([{name: row[name] for name in names}
for row in cur.fetchall()], columns=names)
records.measurement_ts = records.measurement_ts.apply(
lambda ts: ts.tz_convert(timezone))
except psycopg2.ProgrammingError:
print('no data in selected timeframe, creating empty dataframe')
records = pd.DataFrame(columns=names)
print("got data")
cur.close()
pool.putconn(conn)
return records
def fetchAqiWarningInfo(pool, aqiSpecies=['pm_2_5_aqi', 'pm_10_0_aqi'], standardDate=us.defaultTimeRange, customDate=None):
varNames = ['rgb', 'description', 'message']
# AQI warning text and color.
if "pm_2_5_aqi" in aqiSpecies and "pm_10_0_aqi" not in aqiSpecies:
warningVars = ['pm_2_5_aqi_rgb as rgb',
'pm_2_5_aqi_description as description',
'pm_2_5_aqi_message as message']
elif "pm_2_5_aqi" not in aqiSpecies and "pm_10_0_aqi" in aqiSpecies:
warningVars = ['pm_10_0_aqi_rgb as rgb',
'pm_10_0_aqi_description as description',
'pm_10_0_aqi_message as message']
elif "pm_2_5_aqi" in aqiSpecies and "pm_10_0_aqi" in aqiSpecies:
warningVars = [
'CASE WHEN pm_2_5_aqi >= pm_10_0_aqi THEN pm_2_5_aqi_rgb ELSE pm_10_0_aqi_rgb END AS rgb',
'CASE WHEN pm_2_5_aqi >= pm_10_0_aqi THEN pm_2_5_aqi_description ELSE pm_10_0_aqi_description END AS description',
'CASE WHEN pm_2_5_aqi >= pm_10_0_aqi THEN pm_2_5_aqi_message ELSE pm_10_0_aqi_message END AS message']
else:
warningVars = []
varNames = []
try:
# First (most recent) row of warning info.
warnings = fetchSensorData(pool,
varNames, standardDate, customDate, warningVars).iloc[0]
warningMessage = [warnings['description'], '.\r', warnings['message']]
style = {
'backgroundColor': warnings['rgb']
}
except IndexError:
warningMessage = ''
style = {}
return warningMessage, style
def fetchWeatherDataNewTimeRange(pool, varName, standardDate=us.defaultTimeRange, customDate=None, timezone=us.timezone):
"""
Fetch updated data for a single variable or a list of variables when date range is changed.
Args:
varName: str or list of str corresponding to fields in the weather_data table
Returns:
pandas dataframe of data fetched
"""
conn = pool.getconn()
conn.set_session(readonly=True)
cur = conn.cursor()
if isinstance(varName, str):
varName = [varName]
names = ['ts'] + varName
queryFields = ', '.join(names)
records = None
print("getting weather data from database...")
# Get data from database.
if standardDate != 'custom':
if standardDate == 'all':
cur.execute(
"SELECT {} FROM weather_data ORDER BY ts DESC ".format(queryFields))
else:
cur.execute(
"SELECT {} FROM weather_data WHERE ts >= NOW() - INTERVAL '{}' ORDER BY ts DESC ".format(queryFields, standardDate))
else:
if customDate[0] and customDate[1]:
cur.execute("SELECT {} FROM weather_data WHERE ts >= '{}' and ts <= '{}' ORDER BY ts DESC ".format(
queryFields, customDate[0], customDate[1]))
else:
records = pd.DataFrame(columns=names)
# Format data
if not records:
try:
records = pd.DataFrame([{name: row[name] for name in names}
for row in cur.fetchall()], columns=names)
records.ts = records.ts.apply(
lambda ts: ts.tz_convert(timezone))
except psycopg2.ProgrammingError:
print('no data in selected timeframe, creating empty dataframe')
records = pd.DataFrame(columns=names)
print("got data")
cur.close()
pool.putconn(conn)
return records
def fetchForecastData(pool, varName, tableName, timezone=us.timezone):
"""
Fetch all daily forecast data.
Args:
timezone:
Returns:
pandas dataframe of data fetched
"""
conn = pool.getconn()
conn.set_session(readonly=True)
cur = conn.cursor()
if isinstance(varName, str):
varName = [varName]
names = ['ts'] + varName
queryFields = ', '.join(names)
print("getting weather forecast from database...")
# Get data from database.
cur.execute(
"SELECT {} FROM {} ORDER BY ts ASC ".format(queryFields, tableName))
# Format data.
try:
records = pd.DataFrame([{name: row[name] for name in names}
for row in cur.fetchall()], columns=names)
records.ts = records.ts.apply(
lambda ts: ts.tz_convert(timezone))
except psycopg2.ProgrammingError:
print('no data in selected timeframe, creating empty dataframe')
records = pd.DataFrame(columns=names)
print('got data')
cur.close()
pool.putconn(conn)
return records
def fetchDailyForecastData(pool, varName, timezone=us.timezone):
return fetchForecastData(pool, varName, "daily_weather_forecast", timezone)
def fetchHourlyForecastData(pool, varName, timezone=us.timezone):
return fetchForecastData(pool, varName, "hourly_weather_forecast", timezone)
def correctTemp(records, tempUnit):
# Temp correction: https://de-de.facebook.com/groups/purpleair/permalink/722201454903597/?comment_id=722403448216731
if tempUnit == "temp_c":
records[tempUnit] = (
(((records[tempUnit] * 9 / 5) + 32) - 8) - 32) * 5 / 9
elif tempUnit == "temp_f":
records[tempUnit] = records[tempUnit] - 8
return records
def correctHumid(records):
# Humidity correction: https://de-de.facebook.com/groups/purpleair/permalink/722201454903597/?comment_id=722403448216731
records["humidity"] = records["humidity"] + 4
return records
# Figures to insert.
defaultMargin = dict(b=100, t=0, r=0)
def temp_vs_time(records, species="temp_f", margin=defaultMargin):
newTempLabel = {
"temp_c": "Temperature [°C]", "temp_f": "Temperature [°F]"}[species]
if records.empty:
# Make empty/blank plot.
records = pd.DataFrame(columns=["measurement_ts", "value"])
species = "value"
fig = go.Figure()
fig.add_trace(go.Scattergl(x=records["measurement_ts"],
y=records[species],
mode='markers+lines',
hovertemplate='%{y:.0f}',
name='Sensor'))
fig.update_layout(margin=margin,
hovermode="x",
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
))
fig.update_yaxes(title_text=newTempLabel)
if not records.empty:
xBounds = [min(records.measurement_ts),
max(records.measurement_ts)]
fig.update_layout(xaxis_range=xBounds)
return fig
def humid_vs_time(records, margin=defaultMargin):
if records.empty:
# Make empty/blank plot.
records = pd.DataFrame(columns=["measurement_ts", "humidity"])
fig = go.Figure()
fig.add_trace(go.Scattergl(x=records["measurement_ts"],
y=records["humidity"],
mode='markers+lines',
hovertemplate='%{y}',
name='Sensor'))
fig.update_layout(margin=margin,
hovermode="x",
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
))
fig.update_yaxes(title_text="Relative humidity [%]")
if not records.empty:
xBounds = [min(records.measurement_ts),
max(records.measurement_ts)]
fig.update_layout(xaxis_range=xBounds)
return fig
def aqi_vs_time(records, species=["pm_2_5_aqi", "pm_10_0_aqi"], margin=defaultMargin):
if isinstance(species, str):
species = [species]
# Initialize figure
fig = go.Figure()
if not species or records.empty:
# Make empty records df with correct column names.
records = pd.DataFrame(columns=["measurement_ts"] + species)
else:
xBounds = [min(records.measurement_ts),
max(records.measurement_ts)]
yBound = max(max(item for item in records[aqiType] if item is not None)
for aqiType in species)
# EPA color bands by AQI risk.
# TODO: pull from csv instead of hard-coding.
colorCutoffs = [
[50, 'rgba(0,228,0,0.3)'], [100, 'rgba(255,255,0,0.3)'],
[150, 'rgba(255,126,0,0.3)'], [200, 'rgba(255,0,0,0.3)'],
[300, 'rgba(143,63,151,0.3)'], [10000, 'rgba(126,0,35,0.3)']]
colorList = list((item[1] for item in colorCutoffs))
# Put AQI color band info into dataframe. Data should span min ts to max ts to get full coloring of plot area.
colorCutoffs = [
[bound] + cutoff for bound in xBounds for cutoff in colorCutoffs]
colorCutoffs = pd.DataFrame(colorCutoffs, columns=[
"measurement_ts", "aqi", "color"])
# Add color stripe one at a time. Stop at the last AQI color band that includes the max AQI value seen in measured data.
for index, color in enumerate(colorList):
x = colorCutoffs.loc[colorCutoffs["color"]
== color]["measurement_ts"]
y = colorCutoffs.loc[colorCutoffs["color"] == color]["aqi"]
fig.add_trace(go.Scatter(
x=x, y=y,
mode='lines',
line=dict(width=0),
fillcolor=color,
fill='tozeroy' if index == 0 else 'tonexty',
showlegend=False,
hovertemplate=None,
hoverinfo='skip'
))
# Max AQI value within most recently added color band.
if int(yBound) < y.iloc[0]:
break
# Set plot axes ranges.
if index == len(colorCutoffs) - 1:
# Cap y range at nearest hundred greater than max measured AQI value.
fig.update_layout(
yaxis_range=(0, round(yBound + 100, -2)),
xaxis_range=xBounds
)
else:
fig.update_layout(
yaxis_range=(0, y.iloc[0]),
xaxis_range=xBounds
)
# Add measured AQI values.
aqiLabel = {"pm_2_5_aqi": "PM 2.5", "pm_10_0_aqi": "PM 10.0"}
aqiColor = {"pm_2_5_aqi": "#636EFA", "pm_10_0_aqi": "#EF553B"}
# Add measured series one by one.
for aqiType in species:
fig.add_trace(go.Scattergl(
x=records["measurement_ts"], y=records[aqiType],
mode="markers+lines",
hovertemplate='%{y}',
name=aqiLabel[aqiType],
marker=dict(color=aqiColor[aqiType])
))
fig.update_layout(
legend=dict(
yanchor="top",
y=0.99,
xanchor="left",
x=0.01
),
margin=margin,
hovermode="x"
)
fig.update_yaxes(title_text="AQI")
return fig
</code></pre>
<p>Any criticism or comments would be greatly appreciated!</p>
|
[] |
[
{
"body": "<p>I have no experience with any of these libraries, so I can only comment on aspects of the language itself.</p>\n<hr />\n<pre><code>def insert_data():\n if not db:\n raise Exception('db object not defined')\n</code></pre>\n<p>Just to be clear, if <code>db</code> truly hasn't been assigned at this point, you cannot use <code>if not db</code> to check for that. Attempting to use a name before it's been associated with an object with raise a <code>NameError</code>, which you'd need to catch. At that point though, I'd probably just allow the original <code>NameError</code> to propagate and not worry about catching it unless there was other specific information that I wanted to add to the error.</p>\n<p>If you meant that "db is in a bad, falsey state", I'd probably change the error message to be clearer what the problem is, and change <code>raise Exception(. . .</code> to <code>raise ValueError(. . .</code>. Throwing generic <code>Exception</code>s isn't a great idea, since it makes it harder for the caller of the function to handle only specific errors.</p>\n<hr />\n<pre><code>if us.header_key and request.headers.get('X-Purpleair') == us.header_key:\n db.insert_sensor_row(request.json)\nelif not us.header_key:\n db.insert_sensor_row(request.json)\n</code></pre>\n<p>It seems like this could be reduced down to:</p>\n<pre><code>if not us.header_key or request.headers.get('X-Purpleair') == us.header_key:\n db.insert_sensor_row(request.json)\n</code></pre>\n<p>If <code>not us.header_key</code> is false, the right operand of <code>or</code> will run, and you know at that point that <code>us.header_key</code> must be truthy.</p>\n<hr />\n<pre><code>def displayCustomDateRangePicker(standardDate):\n if standardDate == 'custom':\n return False\n\n return True\n</code></pre>\n<p>This can be just:</p>\n<pre><code>def displayCustomDateRangePicker(standardDate):\n return standardDate != 'custom'\n</code></pre>\n<hr />\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">Please using "snake_case" naming</a> when naming function and variables.</p>\n<hr />\n<hr />\n<p>Sorry, I'm more tired than I originally thought. Hopefully someone else can give you a more complete review.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T14:45:58.953",
"Id": "248962",
"ParentId": "248931",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:02:23.857",
"Id": "248931",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"graph",
"postgresql",
"flask"
],
"Title": "Air Quality/Environment Monitoring Web App using Plotly Dash"
}
|
248931
|
<p>This is a follow up to my previous post as it contained a lot of errors and wasn't accurate.</p>
<p>I am using the Bubble sort algorithm to sort an array of integers and I would like to know whether I could optimize it in any way.</p>
<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
void printarr(int *arr,const int siz){
for(int i = 0;i < siz;i++) std::cout << arr[i] << " ";
std::cout << "\n";
}
int main(){
const int siz = 6;
int arr[siz] = {4,6,3,1,3,8};
std::cout << "Before sort\n";
printarr(arr,siz);
for(int i = 0;i < siz;i++){
for(int j = i+1;j < siz;j++){
if(arr[i] > arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
std::cout << "After sort\n";
printarr(arr,siz);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:19:23.453",
"Id": "487799",
"Score": "0",
"body": "linked: [Sorting an array in C++ using bubble sort](https://codereview.stackexchange.com/questions/248925/sorting-an-array-in-c-using-bubble-sort)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T18:03:14.153",
"Id": "487864",
"Score": "1",
"body": "Really, the only way to optimize a bubble sort is to use a different algorithm. Which is a principle applicable in many cases :-) Unless you're doing this as a class assignment or similar, your best option is probably to call the library qsort function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T23:51:10.647",
"Id": "487880",
"Score": "2",
"body": "@jamesqf `std::sort` would be much better since the compiler knows the input type and can optimize accordingly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:18:49.657",
"Id": "487964",
"Score": "0",
"body": "@phuclv: Same principle. qsort is much simpler to use, IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:46:07.527",
"Id": "488272",
"Score": "0",
"body": "@jamesqf Not true. Bubble sort has an optimization that when it holds makes the algorithm `O(n)` (beating all other forms). Bubble sort also has a very very very low overhead. Making it exceptionally good for sorting small list of numbers where it regularly outperforms your more complex sorts."
}
] |
[
{
"body": "<p>That's not bubble sort. More like an overly eager selection sort. Bubble sort swaps neighbors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:26:39.017",
"Id": "248936",
"ParentId": "248933",
"Score": "4"
}
},
{
"body": "<p>First thing first, make it into a function, such that your <code>main</code> will be</p>\n<pre><code>int main(){\n const int siz = 6;\n int arr[siz] = {4,6,3,1,3,8};\n\n std::cout << "Before sort\\n";\n printarr(arr,siz);\n\n sort(arr, siz);\n\n std::cout << "After sort\\n";\n printarr(arr,siz);\n}\n</code></pre>\n<hr />\n<p>Since you've tagged it <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a>, do not use <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged 'c'\" rel=\"tag\">c</a>-style array. Use <code>std::vector</code>. Use <code>std::swap</code>. Currently, it is plain old <a href=\"/questions/tagged/c\" class=\"post-tag\" title=\"show questions tagged 'c'\" rel=\"tag\">c</a>. Nothing wrong with it, except the tag.</p>\n<hr />\n<p>Optimization wise, well, bubble sort does not deserve it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:32:10.733",
"Id": "487804",
"Score": "0",
"body": "Just to clarify, another review says that this isn't bubble sort?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:18:32.170",
"Id": "487841",
"Score": "1",
"body": "Indeed. From that answer: *Bubble sort swaps neighbors.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T21:40:37.727",
"Id": "487873",
"Score": "1",
"body": "Why not use arrays in C++? They're a perfectly valid language feature. Just because you have something else, such as vectors, doesn't mean you have to use it, especially when it makes your code more complicated, harder to understand, and possibly less efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T22:08:05.433",
"Id": "487876",
"Score": "0",
"body": "@jamesqf \"Why not use arrays in C++?\" See C++ Super FAQ https://isocpp.org/wiki/faq/containers#arrays-are-evil"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T08:02:36.413",
"Id": "487898",
"Score": "0",
"body": "@jamesqf If performance is an issue, std::array will have the exact same performance as a c style array without the numerous pitfalls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:15:28.593",
"Id": "487963",
"Score": "0",
"body": "@stefan: That is just plain wrong. Arrays are good BECAUSE a C array is a very low level data structure which is easy to write, understand, &c."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:28:34.610",
"Id": "248937",
"ParentId": "248933",
"Score": "8"
}
},
{
"body": "<p>After all the suggestions I turned my old code into the following:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include<iostream>\n#include<vector>\n\nvoid printvec(std::vector<int> vec){\n for(int i:vec){\n std::cout << i << ' ';\n }\n std::cout << '\\n';\n}\n\nstd::vector<int> sortvec(std::vector<int> &vec){\n int temp = 0;\n for(long unsigned int i = 0;i < vec.size();i++){\n for(long unsigned int j = i+1;j < vec.size();j++){\n if(vec[j] < vec[i]){\n temp = vec[i];\n vec[i] = vec[j];\n vec[j] = temp;\n }\n }\n }\n return vec;\n}\n\n\nint main(){\n std::vector<int> my_vec{7,2,4,6,7,2,3,6,3,2,1,4,6,9,2,3,5,8,6,4,3,2,2,4,5,7,2,8,4,6,3,3};\n my_vec = sortvec(my_vec);\n printvec(my_vec);\n return 0x1;\n\n}\n</code></pre>\n<ul>\n<li>I changed the container type from C-style array to <code>std::vector<int></code>.</li>\n<li>I moved the sort algorithm into a separate function and then.</li>\n</ul>\n<p>Both of them were suggested by @vnp</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T08:03:53.147",
"Id": "487900",
"Score": "1",
"body": "3 comments here: 1. You still dont use std::swap. Why? 2. (This is probably up for discussion) why use vec in the name of the functions? This is already part of the signature. 3. If you pass vec by reference and sort in place, there is no reason to return vec by value, this just creates an extra copy unnecessarily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T08:11:59.497",
"Id": "487901",
"Score": "1",
"body": "Also: 4. This is still selection sort and not bubble sort. 5. If you insist on using std::swap, declare temp as close as possible to the usage, ie in the inner for loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T09:37:58.907",
"Id": "487905",
"Score": "1",
"body": "6. Use iterators instead of direct indices (and the type of the indices is `std::size_t` anyway)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:52:31.170",
"Id": "488273",
"Score": "0",
"body": "New code that needs reviewing means a new question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T17:49:16.453",
"Id": "248966",
"ParentId": "248933",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248937",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T21:18:00.580",
"Id": "248933",
"Score": "3",
"Tags": [
"c++",
"array",
"sorting"
],
"Title": "Sorting an array of integers in C++"
}
|
248933
|
<p>I've written a program that does three things:</p>
<p>Take an equirectangular image and ...</p>
<ul>
<li>... cut horizontally-overlapping image areas.</li>
<li>... fill the image from the bottom with black so it has a ratio of 2:1.</li>
<li>... create each face-texture of a cubemap from the image.</li>
<li>... do interpolation optionally.</li>
</ul>
<p>The algorithm is the following: I use the image as a projection on a unit-sphere. I put a cube around that sphere and project each pixel of the faces onto the sphere. I'm doing that using the pixel-coordinates and the corresponding vector in cartesian-coordinates. I only evaluate the vectors that belong to the -Z-direction-face and rotate them to get the corresponding vectors for other directions.</p>
<pre class="lang-cpp prettyprint-override"><code>#define _USE_MATH_DEFINES
#include <iostream>
#include <OpenImageIO/imageio.h>
#include <vector>
#include <boost/filesystem.hpp>
namespace bfs = boost::filesystem;
struct Pixel {
unsigned char R;
unsigned char G;
unsigned char B;
};
struct Vector {
double x;
double y;
double z;
};
double dot(const Vector& v1, const Vector& v2) {
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
double len(const Vector& v) {
return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}
double angle(const Vector& v1, const Vector& v2) {
double temp = dot(v1, v2) / (len(v1) * len(v2));
// acos for values outside [-1.0, 1.0] is a complex number
if (temp > 1.0) {
temp = 1.0;
}
if (temp < -1.0) {
temp = -1.0;
}
return std::acos(temp);
}
const double radToDegFactor = 180.0 / M_PI;
double radToDeg(double rad) {
return rad * radToDegFactor;
}
enum class Orientation {
X_POS,
X_NEG,
Y_POS,
Y_NEG,
Z_POS,
Z_NEG
};
// using simple 3d rotation matrices:
// X_POS and X_NEG rotate by -90 and 90 around y.
// Y_POS and Y_NEG rotate by 90 and -90 around x.
// Z_POS rotates by 180 around y and Z_NEG doesn't rotate.
Vector rotate(const Vector& v, const Orientation o) {
switch (o) {
case Orientation::X_POS:
return Vector{ -v.z, v.y, v.x };
case Orientation::X_NEG:
return Vector{ v.z, v.y, -v.x };
case Orientation::Y_POS:
return Vector{ v.x, v.z, -v.y };
case Orientation::Y_NEG:
return Vector{ v.x, -v.z, v.y };
case Orientation::Z_POS:
return Vector{ -v.x, v.y, -v.z };
case Orientation::Z_NEG:
return Vector{ v.x, v.y, v.z };
default:
assert(false);
return Vector{ 0.0, 0.0, 0.0 };
}
}
class SphericalImage {
public:
std::vector<unsigned char> data;
int width, height, nchannels;
SphericalImage(std::vector<unsigned char>& data, int width, int height, int nchannels)
: data{ data.begin(), data.end() }, width{ width }, height{ height }, nchannels{ nchannels } {
assert(data.size() == width * height * nchannels);
}
int index(int x, int y) {
assert(0 <= x && x < width);
assert(0 <= y && y < height);
return y * width * nchannels + x * nchannels;
}
// replaces the old image by a new image that discards nCols from the right
void popCols(int nCols) {
assert(nCols <= width);
int newWidth = width - nCols;
std::vector<unsigned char> newData(newWidth * height * nchannels);
int destIdx = 0;
for (int h = 0; h < height; ++h) {
for (int w = 0; w < newWidth; ++w) {
int srcIdx = index(w, h);
for (int c = 0; c < nchannels; ++c) {
newData[destIdx++] = data[srcIdx++];
}
}
}
data = std::move(newData);
width = newWidth;
}
void pushRows(int nRows) {
height += nRows;
data.resize(width * height * nchannels);
}
// checks the different between pixel at (x1, y1) and pixel at (x2, y2)
// where each absolute distance of each channel is summed up
int pixelDiff(int x1, int y1, int x2, int y2) {
int i1 = index(x1, y1);
int i2 = index(x2, y2);
int diff = 0;
for (int c = 0; c < nchannels; ++c) {
diff += std::abs(data[i1++] - data[i2++]);
}
return diff;
}
// searches the index of the column that is the most similar to the first one
// by going backwards starting from the final column and remembering the closest one
int findOverlap(int range, double threshold, bool centerWeighted) {
int closestCol = -1;
double smallestDiff = -1.;
for (int w = width - 1; w >= width - range; --w) {
double diff = 0;
for (int h = 0; h < height; ++h) {
double currDiff = pixelDiff(0, h, w, h);
if (centerWeighted) {
// we weight the pixels that are vertically in the middle higher
currDiff *= (double) std::min(std::abs(h - height), h) / ((double) height / 2);
}
diff += currDiff;
}
diff /= height;
if (diff < smallestDiff || smallestDiff == -1) {
smallestDiff = diff;
closestCol = w;
}
}
if (smallestDiff > threshold) {
assert(false);
}
return closestCol;
}
// interpolate the pixel at the given coordinates with 3 neighbors by considering the fractional part
// this is a simple bilinear interpolation; we do nothing crazy here
Pixel interpolate(const double x, const double y) {
// idx1 is upper left, idx2 is upper right, idx3 is bottom left, idx4 is bottom right
int idx1 = index((int)x, (int)y);
int idx2 = index(x == width - 1 ? 0 : (int)x, (int)y);
int idx3 = index((int)x, y == height - 1 ? (int)y : (int)(y + 1));
int idx4 = index(x == width - 1 ? 0 : (int)x, y == height - 1 ? (int)y : (int)(y + 1));
Pixel upperLeft { data[idx1], data[idx1 + 1], data[idx1 + 2] };
Pixel upperRight { data[idx2], data[idx2 + 1], data[idx2 + 2] };
Pixel bottomLeft { data[idx3], data[idx3 + 1], data[idx3 + 2] };
Pixel bottomRight{ data[idx4], data[idx4 + 1], data[idx4 + 2] };
double dummy = 42.0;
double xFrac = std::modf(x, &dummy);
double yFrac = std::modf(y, &dummy);
double oneMinusX = 1.0 - xFrac;
double nulMinusX = std::abs(0.0 - xFrac);
double oneMinusY = 1.0 - yFrac;
double nulMinusY = std::abs(0.0 - yFrac);
// the actual interpolation by combining both rows and combining the results
Pixel upper{
oneMinusX * upperLeft.R + nulMinusX * upperRight.R,
oneMinusX * upperLeft.G + nulMinusX * upperRight.G,
oneMinusX * upperLeft.B + nulMinusX * upperRight.B,
};
Pixel bottom{
oneMinusX * bottomLeft.R + nulMinusX * bottomRight.R,
oneMinusX * bottomLeft.G + nulMinusX * bottomRight.G,
oneMinusX * bottomLeft.B + nulMinusX * bottomRight.B,
};
Pixel whole{
oneMinusY * upper.R + nulMinusY * bottom.R,
oneMinusY * upper.G + nulMinusY * bottom.G,
oneMinusY * upper.B + nulMinusY * bottom.B,
};
return whole;
}
// project the point v on the sphere and return the corresponding color from the array data
// v is initially in the typical -z world coordinates and is reorientated with o before projection
Pixel project(const Vector& v, const Orientation o, bool interpolated) {
Vector vec = rotate(v, o);
Vector longvec{ vec.x, 0.0, vec.z };
Vector latvec { vec.x, vec.y, vec.z };
Vector forward{ 0.0, 0.0, -1.0 };
double longitude = radToDeg(angle(forward, longvec));
double latitude = radToDeg(angle(longvec, latvec));
// when v is (0, 0, -1) and o is Y_POS or Y_NEG then |longvec| becomes 0
// and makes the angle between longvec and latvec undefined
if (len(longvec) == 0.0) {
longitude = 0.0;
latitude = 90.0;
}
// the angle between two vectors is positive, therefore we need this hack
if (vec.x < 0.0) {
longitude = -longitude;
}
if (vec.y < 0.0) {
latitude = -latitude;
}
// the image ranges from 90 to -90 degrees vertically and from -180 to 180 degrees horizontally
// we map (logitude, latitude) -> (x, y) of the image space and consider the array bounds
double x = (longitude / 180) * ((double)(width - 1) / 2) + ((double)(width - 1) / 2);
double y = (latitude / 90) * ((double)(height - 1) / 2) + ((double)(height - 1) / 2);
int idx = index((int)x, (int)y);
return Pixel{ data[idx], data[idx + 1], data[idx + 2] };
if (interpolated) {
return interpolate(x, y);
}
else {
int idx = index((int)x, (int)y);
return Pixel{ data[idx], data[idx + 1], data[idx + 2] };
}
}
// project the spherical image on the face of the cube that is specified by o
void projectOnFace(const Orientation o, const int size, const std::string filename) {
const int width = size;
const int height = size;
std::vector<unsigned char> buf(size * size * 3);
int i = 0;
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
// we map (x, y) -> ([-1, 1], [-1, 1]) to stay in range of the face
Vector v{(double)(x * 2) / size - 1, (double)(y * 2) / size - 1, -1.0};
Pixel p = project(v, o, false);
buf[i++] = p.R;
buf[i++] = p.G;
buf[i++] = p.B;
}
}
std::cout << filename << '\n';
std::unique_ptr<OIIO::ImageOutput> testOut = OIIO::ImageOutput::create(filename.c_str());
if (!testOut) { return assert(false); }
OIIO::ImageSpec testSpec(width, height, nchannels, OIIO::TypeDesc::UINT8);
testOut->open(filename.c_str(), testSpec);
testOut->write_image(OIIO::TypeDesc::UINT8, &buf[0]);
testOut->close();
}
void projectOnCube(const int size, const std::string dir) {
bfs::path path{ dir };
if (!bfs::exists(path)) {
bfs::create_directory(path);
}
projectOnFace(Orientation::X_POS, size, bfs::path{ path }.append("east.jpg").string());
projectOnFace(Orientation::X_NEG, size, bfs::path{ path }.append("west.jpg").string());
projectOnFace(Orientation::Y_POS, size, bfs::path{ path }.append("top.jpg").string());
projectOnFace(Orientation::Y_NEG, size, bfs::path{ path }.append("bot.jpg").string());
projectOnFace(Orientation::Z_POS, size, bfs::path{ path }.append("south.jpg").string());
projectOnFace(Orientation::Z_NEG, size, bfs::path{ path }.append("north.jpg").string());
}
};
int main(int argc, char* argv[]) {
std::string inFile(argv[1]);
std::cout << "input : " << inFile << '\n';
// Read file.
std::unique_ptr<OIIO::ImageInput> in = OIIO::ImageInput::open(inFile.c_str());
if (!in) { return EXIT_FAILURE; }
const OIIO::ImageSpec& inSpec = in->spec();
const int inWidth = inSpec.width;
const int inHeight = inSpec.height;
const int nchannels = inSpec.nchannels;
std::cout << "resolution " << inWidth << "x" << inHeight << '\n';
std::vector<unsigned char> inBuf(inWidth * inHeight * nchannels);
in->read_image(OIIO::TypeDesc::UINT8, &inBuf[0]);
in->close();
// Do the stuff.
SphericalImage simage(inBuf, inWidth, inHeight, nchannels);
int chopAt = simage.findOverlap(simage.width / 2, 9., true);
if (chopAt == -1) { return EXIT_FAILURE; }
int chopN = simage.width - chopAt;
if ((simage.width - chopN) % 2 == 1) { ++chopN; }
simage.popCols(chopN);
simage.pushRows(simage.width / 2 - simage.height);
const int outWidth = simage.width;
const int outHeight = simage.height;
std::cout << "new resolution " << outWidth << "x" << outHeight << '\n';
// Write projection.
simage.projectOnCube(simage.height / 2,
bfs::path(inFile).parent_path().append("Cubify_out").string());
return EXIT_SUCCESS;
}
</code></pre>
<p>Example input:</p>
<p><a href="https://i.stack.imgur.com/Ik9dk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ik9dk.jpg" alt="enter image description here" /></a></p>
<p>Example output (stitched together to a single image):</p>
<p><a href="https://i.stack.imgur.com/BxCXf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BxCXf.jpg" alt="enter image description here" /></a></p>
<p>I wonder if there is anything strange in the code I've written. I'm especially interested in readability of my code. I feel like I'm writing hard-to-understand-code but I'm not sure how to simplify it or improve documentation. I'm using BOOST for IO, OpenImageIO for image-IO and nothing else.</p>
<p>Previous version: <a href="https://codereview.stackexchange.com/q/245081/219028">Program for chopping overlapping image areas and filling up to a specific ratio</a></p>
|
[] |
[
{
"body": "<h1>Make sure you add <code>#include</code> for everything you use directly</h1>\n<p>Your code happens to compile without errors because some other header file <code>#include</code>s the necessary header files for you to be able to use functions like <code>std::acos()</code> (from <code><cmath></code>), <code>std::abs()</code> (from <code><cstdlib></code>), <code>std::min()</code> (from <code><algorithm></code>), <code>std::unique_ptr</code> (from <code><memory></code>), and so on, you should not rely on this. Go through all the functions from the standard library you use, and ensure the corresponding <code>#include</code> is present.</p>\n<h1>Consider making <code>dot()</code>, <code>len()</code>, etc. member functions of <code>Vector</code></h1>\n<p>These functions clearly only work on instances of <code>Vector</code>, so it makes sense to make them member functions of <code>Vector</code>. This avoids polluting the global namespace. Do this for all the functions that operate purely on vectors: <code>dot()</code>, <code>len()</code>, <code>angle()</code>, <code>rotate()</code>.</p>\n<h1>Use radians everywhere</h1>\n<p>I have found that a major source of bugs is using degrees, when all the standard library functions work in radians. It is easy to make a mistake in converting between them, and it can also result in less efficient code. The only place I would use degrees in code is when displaying angles or reading angles as input. So for example:</p>\n<pre><code>double longitude = forward.angle(longvec);\n...\ndouble x = (longitude / M_PI) * (width - 1) / 2.0 + (width - 1) / 2.0;\n</code></pre>\n<h1>Make helper functions <code>private</code></h1>\n<p>Everything in <code>class SphericalImage</code> is public, however only a few functions should actually part of the public API. Right away, you can make <code>index()</code>, <code>pixelDiff()</code>, <code>interpolate()</code> and <code>project()</code> <code>private</code>, since they are only used internally by other member functions.</p>\n<p>Then there is "the stuff" that you do in <code>main()</code>. Can you make a single member function that performs the task of finding the overlap, popping columns and pushing rows, with a clear and descriptive name? Then, <code>findOverlap()</code>, <code>popCols()</code> and <code>pushRows()</code> can also be hidden.</p>\n<h1>Use <code>size_t</code> for sizes and counts</h1>\n<p>Use <code>size_t</code> for variables such as <code>width</code>, <code>height</code>, <code>nchannels</code>, <code>srcIdx</code> and so on. This type is guaranteed to be able to hold integers large enough for everything that can be held in memory. Furthermore, it is <code>unsigned</code>, so you don't have to worry about negative numbers. Lastly, it will avoid compiler warnings about comparing integers of different signedness in expressings such as <code>data.size() == width * height * nchannels</code>.</p>\n<h1>Optimize <code>popCols()</code></h1>\n<p>When you are removing columns, you first allocate space for the new image, build the new image, and then copy it back into <code>data</code>. But this is unnecessary, you can update <code>data</code> in-place:</p>\n<pre><code>void popCols(size_t nCols) {\n assert(nCols <= width);\n size_t newWidth = width - nCols;\n size_t destIdx = 0;\n\n for (int h = 0; h < height; ++h) {\n for (int w = 0; w < newWidth; ++w) {\n size_t srcIdx = index(w, h);\n for (int c = 0; c < nchannels; ++c) {\n data[destIdx++] = data[srcIdx++];\n }\n }\n }\n\n width = newWidth;\n data.resize(width * height * nchannels);\n}\n</code></pre>\n<h1>Don't <code>assert(false)</code></h1>\n<p>The whole point of the function <code>assert()</code> is that you provide it with a condition to check, and if the condition is false, it will print an error message that contains the condition. So just write:</p>\n<pre><code>assert(smallestDiff > threshold);\n</code></pre>\n<p>This way, when the assertion triggers, a more helpful error message is displayed.</p>\n<h1>Avoid unnecessary casts</h1>\n<p>C and C++ will implicitly cast variables for you in some cases. While that is sometimes a problem, it usually avoids you having to write explicit casts. For example, when calling <code>index()</code>, you don't need to explictly cast <code>double</code> values to an integer type. For example, you can just write:</p>\n<pre><code>Pixel interpolate(const double x, const double y) {\n size_t idx1 = index(x, y);\n size_t idx2 = index(x == width - 1 ? 0 : x, y);\n size_t idx3 = index(x, y == height - 1 ? y : y + 1);\n size_t idx4 = index(x == width - 1 ? 0 : x, y == height - 1 ? y : y + 1);\n ...\n</code></pre>\n<p>Also, when performing arithmetic operations involving constants, you can make the constants <code>double</code>s, and then they can automatically cause integers to be promoted to <code>double</code>, like so:</p>\n<pre><code>Vector v{x * 2.0 / size - 1, y * 2.0 / size - 1, -1.0};\n</code></pre>\n<h1>Split responsibilities</h1>\n<p>The function <code>projectOnFace()</code> not only performs an image projection, it also writes out the image. In general, it is best to split up such a function in two parts, one that does the projection, and another that writes it to a file. Consider that you might want to do something else with the projects face before writing it out, or perhaps you don't want to write it to a file, but rather display it on the screen.\nIdeally, <code>projectOnFace()</code> returns an image object of some kind. Since you are using OpenImageIO, consider using <code>OIIO::ImageBuf</code> for this.</p>\n<p>The function <code>projectOnCube()</code> has similar issues, although it doesn't do any projection of its own. Since this is the one called from <code>main()</code> to write out the images, maybe it should just call <code>projectOnFace()</code> six times to get image buffers, and then it write those to disk itself. The function should be renamed to something more descriptive, like <code>writeCubeFaces()</code>.</p>\n<h1>Only use <code>assert()</code> to catch programming errors</h1>\n<p>You should only use <code>assert()</code> to check for possible programming errors, not use them as a generic error handling function for things that can go wrong even if the program itself is written correctly. Take for example:</p>\n<pre><code>std::unique_ptr<OIIO::ImageOutput> testOut = ...;\nif (!testOut) { return assert(false); }`\n</code></pre>\n<p>Apart from the fact that the last like should just have been <code>assert(testOut)</code>, the issue here is that not being able to create a file is not a programming error, but rather something like the program being called inside a directory that is not writable, or having run out of disk space, and so on. The user of your program is not helped by a core dump and the message "assertion 'false' is false". Even worse, <code>assert()</code> is a macro that is typically disabled in release builds, so then there would be no error message at all.</p>\n<p>The manual of OpenImageIO shows the correct way to handle errors:</p>\n<pre><code>#include <stdexcept>\n...\nstd::unique_ptr<OIIO::ImageOutput> testOut = ...;\nif (!testOut) {\n std::cerr << "Could not create an ImageOutput for "\n << filename << ", error = "\n << OpenImageIO::geterror() << "\\n";\n return;\n}\n</code></pre>\n<p>Now the user gets a detailed error message, which should explain why it couldn't write the file. The user then hopefully has enough information to correct the situation.\nHowever, just returning from the function makes an error condition indistinguishable from success for the caller of this function. Therefore, I would replace the <code>return</code> statement with:</p>\n<pre><code>throw std::runtime_error("Error creating output image");\n</code></pre>\n<h1>Check for all possible errors</h1>\n<p>Just checking whether a file could be opened or created is not enough. You also have to check whether the whole file was successfully read, or if all image data has been fully written to disk. So check the return value of <code>read_image()</code>, <code>write_image()</code> and <code>close()</code>, ensure you print a helpful error message in each case, and <code>throw</code> an exception if necessary to signal any callers of an error.</p>\n<h1>Consider whether it is necessary to create a <code>class SphericalImage</code> at all</h1>\n<p>The only thing you can do with a <code>class SphericalImage</code> is to project an image onto cube faces. The few functions it has to manipulate the stored image are just there to help with the projection. Instead of using a <code>class</code>, perhaps it is better to just have a single function that takes an image, and splits it into six cube faces. It could look like this:</p>\n<pre><code>std::array<OIIO::ImageBuf, 6> projectOnCube(const OIIO:ImageBuf &image);\n</code></pre>\n<p>Basically, you give it an <code>ImageBuf</code>, and you get six <code>ImageBuf</code>s back. You can add additional parameters for your algorithm, like <code>threshold</code>, <code>centerWeighted</code>, possibly with default values. Your <code>main()</code> should then be able to look like:</p>\n<pre><code>int main(int argc, char* argv[]) {\n if (argc <= 1) {\n // report usage error and exit\n }\n\n OIIO::ImageBuf image(argv[1]);\n\n if (!image.read(0, 0, true, OIIO::TypeDesc::UINT8)) {\n // report read error and exit\n }\n\n auto faces = projectOnCube(image);\n\n const char *filenames[6] = {"east.jpg", "west.jpg", ...};\n\n for (size_t i = 0; i < 6; ++i) {\n if (!faces[i].write(filenames[i])) {\n // report write error and exit\n }\n }\n}\n</code></pre>\n<p>Note that this doesn't mean you have to put all the functionality inside that function, you can still have helper functions. These should then be made <code>static</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T17:02:00.787",
"Id": "487956",
"Score": "0",
"body": "Thank you much for all the tipps!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T10:18:23.433",
"Id": "248956",
"ParentId": "248940",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248956",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T22:21:56.657",
"Id": "248940",
"Score": "2",
"Tags": [
"c++",
"image",
"mathematics",
"graphics"
],
"Title": "Converting an equirectangular image to a cubemap"
}
|
248940
|
<p>I took it as a challenge to write a C++ program to find the first 10 <a href="https://math.eku.edu/amicable-pairs" rel="nofollow noreferrer">amicable-number</a> pairs.</p>
<h2>Amicable numbers</h2>
<p>Let's take 4. What are the <a href="https://mathworld.wolfram.com/ProperDivisor.html" rel="nofollow noreferrer">proper divisors</a> of 4?. They are 1 and 2. Their sum is 3.</p>
<p>Now let's do the same thing for the number 220. The sum of the proper divisors of 220 is 284.
The sum of proper divisors of the number 284 is 220.</p>
<p>If the sum of proper divisors of two numbers are equal to each other then they are amicable.
For example 284 and 220, whose proper factors sum to 220 and 284 respectively, are amicable.</p>
<p>This is my C++ program to find the first 10 amicable numbers.</p>
<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
int GetSumOfFactors(int num){
int sum = 0;
for(int i = 1;i < num/2+1;i++){
if(num % i==0){
sum+=i;
}
}
return sum;
}
int main(){
int sum_of_factors = 0;
int counter = 0;
int num = 0;
for(;;){
num++;
sum_of_factors = GetSumOfFactors(num);
if(num == sum_of_factors) continue;
if (GetSumOfFactors(sum_of_factors) == num && num > sum_of_factors){
std::cout << "Pair: " << num << " " << sum_of_factors << "\n";
counter+=1;
}
if(counter == 10) break;
}
return 1;
}
</code></pre>
<p>To make sure I don't find the same pair twice, that means 220 to 284, just like 284 to 220, I keep an extra condition where the number should be greater than its sum of factors.</p>
<p>Output:</p>
<pre><code>Pair: 284 220
Pair: 1210 1184
Pair: 2924 2620
Pair: 5564 5020
Pair: 6368 6232
Pair: 10856 10744
Pair: 14595 12285
Pair: 18416 17296
Pair: 66992 66928
Pair: 71145 67095
Process returned 1 (0x1) execution time : 4.955 s
Press any key to continue.
</code></pre>
|
[] |
[
{
"body": "<p>There are few aspects which I will touch.</p>\n<ul>\n<li>The function <code>GetSumOfFactors</code> could be renamed as <code>FactorsSum</code>, it is done to simplify the reading.</li>\n<li>You are declaring a for loop <code>for(;;)</code> (equivalent to <code>while (true)</code>) but that is quite bad, one generally includes the ending statement in the for, as the variables updates and, if used only there, for loop scoped variables.</li>\n<li>You are sending <code>" "</code> and <code>"\\n"</code> to the <code>cout</code> variable, it depends on the interpretation the compiler will do but primarily it is interpreted as a <code>const char*</code> variable, it would be better to use <code>'\\n'</code> and <code>' '</code> which are <code>char</code> variables.</li>\n<li>Try to not use <code>break</code> if it depends on a verifiable condition each iteration, put the equivalent condition in the for statement.</li>\n</ul>\n<p>Finally, a tip which I consider not as optimization in the coding aspect but is useful is to use <code>-O3</code> when compiling your code (works for g++), this is a flag which tells the compiler to optimize output.</p>\n<p>Specifically your code could be written as:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n\nint FactorsSum(int num)\n{\n int sum = 0;\n for (int i = 1; i < num / 2 + 1; i++)\n if (num % i == 0) sum += i;\n return sum;\n}\n\nint main()\n{\n int sum_of_factors = 0;\n int num = 0;\n for (int counter = 0; counter < 10; num++)\n {\n sum_of_factors = FactorsSum(num);\n if (num != sum_of_factors && FactorsSum(sum_of_factors) == num && num > sum_of_factors)\n {\n std::cout << "Pair: " << num << ' ' << sum_of_factors << '\\n';\n counter++;\n }\n }\n return 0x0;\n}\n</code></pre>\n<p>Note that <code>num != sum_of_factors</code> is equivalent to end the if in the case <code>num == sum_of_factors</code> be true, so that you can omit the <code>continue</code> instruction.</p>\n<p>I hope it was of help.</p>\n<p>(Thanks to <a href=\"https://codereview.stackexchange.com/users/35991/martin-r\">Martin R</a> for his comment. Now I have tested this program and it works as intended)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T15:53:01.003",
"Id": "487854",
"Score": "1",
"body": "Note that your program does *not* print the first 10 amicable pairs. In fact it prints nothing. The reason is that `counter` is increased in every loop iteration, no matter if an amicable number is found or not. – Also returning a non-zero exit code does normally indicate an error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T17:28:39.967",
"Id": "487863",
"Score": "1",
"body": "Yes I fixed that error, ig I corrected it in the main code and forgot to correct it here, I apologize for that ✌"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T02:01:42.560",
"Id": "248945",
"ParentId": "248941",
"Score": "3"
}
},
{
"body": "<p>I'll add some remarks (adding to what Miguel Avila already said) and then focus on the performance aspect.</p>\n<ul>\n<li>Use consistent naming: you mix camel case (<code>FactorsSum</code>) and snake case (<code>sum_of_factors</code>).</li>\n<li>Use consistent spacing (after keywords like <code>if</code> and around operators).</li>\n<li>Declare variables and the narrowest possible scope. As an example, <code>sum_of_factors</code> is only needed inside the for-loop.</li>\n<li>Use proper exit codes. A non-zero exit code indicates the <em>failure</em> of a program. You'll want to <code>return 0;</code> or <code>return EXIT_SUCCESS;</code>. In fact you can simply <em>omit</em> the return statement: Reaching the end of <code>main()</code> does an implicit <code>return 0;</code> in C++.</li>\n</ul>\n<p>If you care about <em>portability:</em> C++ does not specify the size of <code>int</code>, only its minimum range (which is -32767 to 32767). You should use <code>long</code> (with a minimum range -2147483647 to 2147483647) or one of the fixed-size types (<code>int32_t</code> or <code>int64_t</code>) depending on the needed range.</p>\n<h3>Performance improvement #1</h3>\n<p>Computing the sum of all (proper) divisors of a number can be significantly improved by observing that if <span class=\"math-container\">\\$ i \\$</span> divides <span class=\"math-container\">\\$ n \\$</span> then both <span class=\"math-container\">\\$ i \\$</span> and <span class=\"math-container\">\\$ n/i \\$</span> are divisors of <span class=\"math-container\">\\$ n\\$</span>. Therefore it suffices to test all <span class=\"math-container\">\\$ i \\le \\sqrt n\\$</span>. See for example <a href=\"https://www.geeksforgeeks.org/sum-of-all-proper-divisors-of-a-natural-number/\" rel=\"nofollow noreferrer\">Sum of all proper divisors of a natural number</a>. A possible implementation is</p>\n<pre><code>// Returns the sum of all proper divisors of `n`.\nint divisor_sum(int n) {\n if (n <= 1) {\n return 0;\n }\n \n int count = 1; // 1 is always a divisor.\n int sqrt_n = (int)sqrt(n); // Upper bound for the loop.\n for (int i = 2; i <= sqrt_n; i++) {\n if (n % i == 0) {\n // `i` and `n / i` are divisors of `n`.\n count += i;\n if (i != n / i) {\n count += n / i;\n }\n }\n }\n return count;\n}\n</code></pre>\n<h3>Performance improvement #2</h3>\n<p>In your main loop, you compute the divisor sum of <code>sum_of_factors</code> even if that is larger than <code>num</code>:</p>\n<pre><code>if (GetSumOfFactors(sum_of_factors) == num && num > sum_of_factors)\n</code></pre>\n<p>A simple improvement would be to change the order of the expressions:</p>\n<pre><code>if (num > sum_of_factors && GetSumOfFactors(sum_of_factors) == num)\n</code></pre>\n<p>Another option is to <em>remember</em> the divisor sums of numbers which are possible candidates of an amicable pair, so that they need not be computed again. This can for example be done with a</p>\n<pre><code>std::unordered_map<int, int> abundant_divsums;\n</code></pre>\n<p>which holds all abundant numbers with their divisor sums encountered so far. A number is abundant if its proper divisor sum is larger than the number. These are candidates for an amicable pair with higher numbers.</p>\n<p>A possible implementation is</p>\n<pre><code>#include <unordered_map>\n\nint main()\n{\n std::unordered_map<int, int> abundant_divsums;\n \n int num = 1;\n for (int counter = 0; counter < 10; num++) {\n int divsum = divisor_sum(num);\n if (divsum > num) {\n abundant_divsums[num] = divsum;\n } else if (divsum < num) {\n if (abundant_divsums.find(divsum) != abundant_divsums.end() && abundant_divsums[divsum] == num) {\n std::cout << "Pair: " << num << ' ' << divsum << '\\n';\n counter++;\n }\n }\n }\n}\n</code></pre>\n<h3>Benchmarks</h3>\n<p>The tests were done on a MacBook Air (1.1 GHz Quad-Core Intel Core i5), with the code compiled with optimizations (“Release” configuration).</p>\n<p>I measured the time for computing the first 10/20/50 amicable pairs. All times are in seconds.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th># of amicable pairs</th>\n<th>10</th>\n<th>20</th>\n<th>50</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Original code:</td>\n<td>3.8</td>\n<td>24</td>\n<td></td>\n</tr>\n<tr>\n<td>After improvement #1:</td>\n<td>0.08</td>\n<td>0.2</td>\n<td>3.8</td>\n</tr>\n<tr>\n<td>After improvement #2:</td>\n<td>0.05</td>\n<td>0.15</td>\n<td>2.5</td>\n</tr>\n</tbody>\n</table>\n</div>",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T00:16:02.903",
"Id": "487881",
"Score": "0",
"body": "@superbrain: I simply used the `time` command line utility on macOS. – `abundant_divsums.count(divsum)` made no significant difference in my tests. Just `abundant_divsums[divsum] == num` without checking for the existence of the key will *insert* `{ divsum, 0 }` if it does not exist. That made it slightly slower in my tests, probably because of the increase in size of the hash map."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T00:34:07.237",
"Id": "487883",
"Score": "0",
"body": "@superbrain: Computing the divisor function from the prime factorization is indeed faster (~1 second for 50 pairs)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T03:40:59.397",
"Id": "487889",
"Score": "0",
"body": "That is a huge improvement!, I knew about the square root rule for the natural number but wasn't 100 % sure, do I need to include any library for that function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T04:11:52.830",
"Id": "487892",
"Score": "0",
"body": "You can also add this: The pair is always even and even or odd and odd. That means the `sum_of_factors` and `num` is always the same. either both are even or both are odd, will this speed up the program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T11:31:45.317",
"Id": "487911",
"Score": "0",
"body": "@superbrain: Good catch. It does not affect the search for amicable pairs, but should be fixed of course (done). Thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T11:57:06.007",
"Id": "487915",
"Score": "0",
"body": "Two more off-by-1 errors: the number ranges start at -32768 and -2147483648 (not that it matters here, but still :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T12:04:24.420",
"Id": "487918",
"Score": "0",
"body": "@superbrain: I have only stated what the C(++) standard mandates, see for example https://stackoverflow.com/a/589684/1187415. The standard does not even mandate that integers use twos-complement for negative numbers. – However that might have changed in newer versions of the C++ standard (C++ 20?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T12:09:42.790",
"Id": "487921",
"Score": "0",
"body": "Hmm. Interesting. In my experience it's always been the lower bounds I mentioned. Didn't realize the C++ standard didn't guarantee that. Before writing my comment, I had even checked [this table](https://en.cppreference.com/w/cpp/language/types#Range_of_values) but I didn't read the surrounding text. It does say that that's starting at C++ 20."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T21:02:36.533",
"Id": "248970",
"ParentId": "248941",
"Score": "4"
}
},
{
"body": "<p>Martin R already made <code>get_sum_of_factors</code> a lot faster by going only up to sqrt(n). You can do even better by using prime factorization as shown below. This also at most goes up to sqrt(n), but reduces n and thus sqrt(n) in the process. Here are times for computing the sums of factors for <code>num</code> from 0 to 1,000,000 with the sqrt-method and with my prime-method (<a href=\"https://repl.it/@sp0/amicable-numbers\" rel=\"nofollow noreferrer\">benchmark here</a> and at the bottom of this answer):</p>\n<pre><code>round 1\nget_sum_of_factors1 11.436 seconds\nget_sum_of_factors2 1.767 seconds\n\nround 2\nget_sum_of_factors1 11.397 seconds\nget_sum_of_factors2 1.675 seconds\n\nround 3\nget_sum_of_factors1 10.539 seconds\nget_sum_of_factors2 1.699 seconds\n</code></pre>\n<p>Here's the code:</p>\n<pre><code>int get_sum_of_factors(int n) {\n if (n < 2) {\n return 0;\n }\n int sum = 1, n0 = n;\n for (int p = 2; p * p <= n; p += 1 + (p > 2)) {\n int m = 1;\n while (n % p == 0) {\n n /= p;\n m = m * p + 1;\n }\n sum *= m;\n }\n if (n > 1)\n sum *= n + 1;\n return sum - n0;\n}\n</code></pre>\n<p>It finds prime factors. Imagine you're at some prime <span class=\"math-container\">\\$p\\$</span> and you already have the (sum of) divisors made up from primes smaller than <span class=\"math-container\">\\$p\\$</span>. How do we incorporate <span class=\"math-container\">\\$p\\$</span>? Let's say the remaining value <span class=\"math-container\">\\$n\\$</span> is divisible by <span class=\"math-container\">\\$p\\$</span> thrice (i.e., by <span class=\"math-container\">\\$p^3\\$</span> but not by <span class=\"math-container\">\\$p^4\\$</span>). Then you can build additional new divisors by multiplying previous divisors by <span class=\"math-container\">\\$p\\$</span>, <span class=\"math-container\">\\$p^2\\$</span> or <span class=\"math-container\">\\$p^3\\$</span>. Any divisor multiplied by <span class=\"math-container\">\\$p\\$</span>, <span class=\"math-container\">\\$p^2\\$</span> or <span class=\"math-container\">\\$p^3\\$</span> becomes <span class=\"math-container\">\\$p\\$</span>, <span class=\"math-container\">\\$p^2\\$</span> or <span class=\"math-container\">\\$p^3\\$</span> times as large (duh :-). Thus the sum of all divisors gets multiplied by <span class=\"math-container\">\\$m = 1+p+p^2+p^3\\$</span> (the <span class=\"math-container\">\\$1\\$</span> is for the previously found divisors).</p>\n<p>How to compute <span class=\"math-container\">\\$m = 1+p+p^2+p^3\\$</span>? Easy. For example to go from <span class=\"math-container\">\\$1+p+p^2\\$</span> to <span class=\"math-container\">\\$1+p+p^2+p^3\\$</span> you multiply by <span class=\"math-container\">\\$p\\$</span> to get <span class=\"math-container\">\\$p+p^2+p^3\\$</span> and then add the <span class=\"math-container\">\\$1\\$</span>.</p>\n<p>As the method finds the sum of <em>all</em> divisors, including the original n, we store it in a variable and subtract that in the end.</p>\n<p>Two more reviewy things:</p>\n<ul>\n<li><p>You say you find the "first 10 amicable numbers". They do happen to be among your output, but it's not really what you're doing. What you're really doing is find the first 10 amicable <em>pairs</em>, where pairs are ranked by the larger number in the pair. You're btw also not showing the first 20 amicable numbers that way, as you're missing 63020, which is smaller than <em>both</em> numbers in your last pair (it's partner is 76084, which is larger than both).</p>\n</li>\n<li><p>Your loop condition is <code>i < num/2+1</code>. It would be simpler and meaningful to do <code>i <= num/2</code>.</p>\n</li>\n</ul>\n<p>Benchmark code:</p>\n<pre><code>#include <math.h>\n#include <iostream>\n#include <string>\n#include <chrono>\n\nint get_sum_of_factors1(int num) {\n int sum = 1;\n int squareroot = (int)sqrt(num);\n for(int i = 2; i <= squareroot; i++) {\n if(num%i==0) {\n sum+=i;\n if(num/i != i)\n sum+=num/i;\n }\n }\n return sum;\n}\n\nint get_sum_of_factors2(int n) {\n if (n < 2) {\n return 0;\n }\n int sum = 1, n0 = n;\n for (int p = 2; p * p <= n; p += 1 + (p > 2)) {\n int m = 1;\n while (n % p == 0) {\n n /= p;\n m = m * p + 1;\n }\n sum *= m;\n }\n if (n > 1)\n sum *= n + 1;\n return sum - n0;\n}\n\nstd::chrono::steady_clock::time_point begin;\nvoid start() {\n begin = std::chrono::steady_clock::now(); \n}\nvoid stop(std::string label) {\n std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n double seconds = std::chrono::duration_cast<std::chrono::milliseconds> (end - begin).count() / 1000.;\n std::cout << label << ' ' << seconds << " seconds" << std::endl;\n}\n\nint main() {\n int max = 1000000;\n for (int round = 1; round <= 3; round++) {\n std::cout << "round " << round << std::endl;\n start();\n for (int i=0; i<=max; i++)\n get_sum_of_factors1(i);\n stop("get_sum_of_factors1");\n start();\n for (int i=0; i<=max; i++)\n get_sum_of_factors2(i);\n stop("get_sum_of_factors2");\n std::cout << std::endl;\n }\n for (int i=0; i<=max; i++) {\n int sum1 = get_sum_of_factors1(i);\n int sum2 = get_sum_of_factors2(i);\n if (sum1 != sum2) {\n std::cout << i << ' ' << sum1 << ' ' << sum2 << std::endl;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T11:08:14.123",
"Id": "248997",
"ParentId": "248941",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248970",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T22:27:59.187",
"Id": "248941",
"Score": "6",
"Tags": [
"c++",
"performance"
],
"Title": "Find first 10 pairs of amicable numbers"
}
|
248941
|
<p>Hide email characters:</p>
<ol>
<li><p>When email only has one letter then just cover that letter with the <code>*</code> symbol e.g. <code>*@gmail.com</code></p>
</li>
<li><p>When email has two letters then cover second letter with the symbol * e.g. <code>t*@gmail.com</code></p>
</li>
<li><p>When email has three letters then cover second and third with the symbol <code>*</code> e.g. <code>t**gmail.com</code></p>
</li>
<li><p>When email has four or more letters then show first three letters and add 4 stars at the ends - e.g.</p>
<pre><code>tim****@gmail.com
tom****@gmail.com
</code></pre>
</li>
</ol>
<p>My code works but I feel like its way too much hard-coding and can be done much cleaner</p>
<pre><code>public static String hideSomeOfEmailValue(String privateEmail) {
StringBuilder stringBuilder = new StringBuilder(privateEmail);
int atSignIndex = privateEmail.indexOf("@");
String emailName = privateEmail.substring(0, atSignIndex);
if (emailName.length() == 1) {
return stringBuilder.replace(0, emailName.length(), "*").toString();
}
if (emailName.length() > 1 && emailName.length() < 4) {
return stringBuilder.replace(1, atSignIndex, StringUtils.repeat("*", emailName.length() - 1)).toString();
} else {
stringBuilder = new StringBuilder(privateEmail.substring(0, 2));
String emailProvider = privateEmail.substring(atSignIndex);
stringBuilder.append("****").append(emailProvider);
return stringBuilder.toString();
}
</code></pre>
<ol>
<li>locate at what index at sign located</li>
<li>trim everything until at sign which gives us name of the email only so we can easily.</li>
</ol>
|
[] |
[
{
"body": "<p>Bugs:</p>\n<ol>\n<li><p><code>privateEmail.substring(0, 2)</code> needs to change to <code>privateEmail.substring(0, 3)</code> in the <code>else</code>, since end index is exclusive and we want to include 3 characters, not 2.</p>\n</li>\n<li><p>Method assumes that <code>privateEmail</code> contains a "@", and does not check if <code>atSignIndex</code> results in -1, resulting in a <code>StringIndexOutOfBoundsException</code> if there is no "@". Return <code>privateEmail</code> (with no hiding applied) early if you expect this method be handed any generic string which could potentially be an email, or <code>throw</code> an <code>IllegalArgumentException</code> if <code>privateEmail</code> is always expected to be an email. I consider the latter to be better design. Note that both these situations handle empty strings as well.</p>\n</li>\n</ol>\n<p>Improvements:</p>\n<ol>\n<li><p>Use <code>var</code> for type inference where the type is obvious from the right side, like <code>new StringBuilder(...)</code>, or <code>String#substring</code>. This is as of Java 10.</p>\n</li>\n<li><p><code>1 < emailName.length()</code> is redundant because length of 0 and 1 are handled by earlier cases.</p>\n</li>\n<li><p><code>StringUtils.repeat</code> can be replaced with <code>String#repeat</code> as of Java 11. Rids of need for external dependency here.</p>\n</li>\n<li><p>Instantiating a new <code>StringBuilder</code> in the else can be replaced with mutating the current one, namely with the <code>delete</code> and <code>insert</code> instance methods.</p>\n</li>\n<li><p>Move <code>stringBuilder</code> declaration lower, to only when it is needed.</p>\n</li>\n<li><p>Replace "*" with a <code>static</code> <code>final</code> variable, such that we could change it to "-" or "_" down the road and remain consistent across all the <code>if</code>s and the <code>else</code>. This, despite being a character, will have to be a <code>String</code> to remain type-compatible with <code>String#repeat</code> and <code>StringBuilder#replace</code>.\nFinal code:</p>\n</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static final String HIDE_CHAR = "*";\n\npublic static String asHiddenEmail(String privateEmail) {\n int atSignIndex = privateEmail.indexOf("@");\n\n if (atSignIndex == -1) {\n throw new IllegalArgumentException("`privateEmail` must be an email.");\n }\n\n var stringBuilder = new StringBuilder(privateEmail);\n var emailName = privateEmail.substring(0, atSignIndex);\n\n if (emailName.length() == 1) {\n return stringBuilder.replace(0, emailName.length(), HIDE_CHAR).toString();\n }\n if (emailName.length() < 4) {\n var hiddenNameEnd = HIDE_CHAR.repeat(emailName.length() - 1);\n return stringBuilder.replace(1, atSignIndex, hiddenNameEnd).toString();\n }\n else {\n stringBuilder.delete(3, atSignIndex);\n stringBuilder.insert(3, HIDE_CHAR.repeat(4));\n return stringBuilder.toString();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T19:41:30.117",
"Id": "487868",
"Score": "0",
"body": "Thanks man, regarding the check if it is even an email not necessary UI will not lend send it to back its not properly formatted. Sadly i cannot use Java 11 hence i cannot use repeat function that String have in Java 11"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T20:33:48.447",
"Id": "487870",
"Score": "0",
"body": "@Artjom you're welcome. I still recommend keeping the `throw new IllegalArgumentException(...)` and the check because even if the UI will not let the email be improperly typed, it is good to keep this sanity check. What if down the road you have the email entered some other way, but forgot to check it there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T11:20:39.450",
"Id": "488005",
"Score": "0",
"body": "@MarioIshac I find it a bit confusing that ``HIDE_CHAR` is not of type `char`, as the name suggests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T11:31:17.380",
"Id": "488008",
"Score": "0",
"body": "@DorianGray Yeah that is confusing, I'll clarify it in answer. But it comes down to `char` / `Character` not being compatible with `StringBuilder#replace` and `String#repeat`, there are no character equivalents for those. We would have to insert `String.valueOf` everywhere."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T04:19:25.223",
"Id": "248948",
"ParentId": "248942",
"Score": "5"
}
},
{
"body": "<p>I have refactored the code a bit, using a switch statement, commenting the code (important!) and simplifying the single cases. Maybe a name like <code>obfuscateEMail</code> would be more understandable.</p>\n<p>The "Shouldn't happen" case could be replaced by throwing an Exception.</p>\n<pre><code>public class EMail {\n public static void main(String[] args) {\n System.out.println(hideSomeOfEmailValue("a@gmail.com")); //$NON-NLS-1$\n System.out.println(hideSomeOfEmailValue("ab@gmail.com")); //$NON-NLS-1$\n System.out.println(hideSomeOfEmailValue("abc@gmail.com")); //$NON-NLS-1$\n System.out.println(hideSomeOfEmailValue("abcd@gmail.com")); //$NON-NLS-1$\n System.out.println(hideSomeOfEmailValue("abcde@gmail.com")); //$NON-NLS-1$\n System.out.println(hideSomeOfEmailValue("abcdefghijklmnopqrst@gmail.com")); //$NON-NLS-1$\n }\n \n /**\n * \n * @param privateEmail\n * @return\n */\n public static String hideSomeOfEmailValue(String privateEmail) {\n final int atSignIndex = privateEmail.indexOf('@');\n if (atSignIndex <= 0) {\n // Not an E-Mail address.\n // Shouldn't happen. Return the input.\n return privateEmail;\n }\n \n final StringBuilder obfuscatedEmail = new StringBuilder(privateEmail);\n switch (atSignIndex) {\n case 1:\n // When email only has one letter then just cover that letter with the * symbol e.g. *@gmail.com\n obfuscatedEmail.setCharAt(0, '*');\n return obfuscatedEmail.toString();\n\n case 2:\n // When email has two letters then cover second letter with the * symbol e.g. t*@gmail.com\n obfuscatedEmail.setCharAt(1, '*');\n return obfuscatedEmail.toString();\n \n case 3:\n // When email has three letters then cover second and third with the symbol * e.g. t**gmail.com\n return obfuscatedEmail.replace(1, 3, "**").toString(); //$NON-NLS-1$\n \n default:\n // When email has four or more letters then show first three letters and add 4 stars at the ends - e.g. tim****@gmail.com\n return obfuscatedEmail.replace(3, atSignIndex, "****").toString(); //$NON-NLS-1$\n }\n }\n}\n</code></pre>\n<p>Output of the main methid is as follows (this shall be a JUnit test):</p>\n<pre><code>*@gmail.com\na*@gmail.com\na**@gmail.com\nabc****@gmail.com\nabc****@gmail.com\nabc****@gmail.com\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T12:16:10.620",
"Id": "488011",
"Score": "0",
"body": "Good job also buddy"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T11:35:15.613",
"Id": "249032",
"ParentId": "248942",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T22:41:44.757",
"Id": "248942",
"Score": "6",
"Tags": [
"java",
"strings"
],
"Title": "Hide certain email characters"
}
|
248942
|
<p>I'm trying to determine best case round-trip times to a redis server. Particularly, I am trying to determine exactly how low I can get the latency on a local instance.</p>
<p>On a technical level, this is pretty easy. However, profiling is always a bit of a dark art, doubly so when network/IPC is involved.</p>
<p>Is this method reasonable?</p>
<p>Here's the numbers I am getting:</p>
<pre><code> localhost:6379: 92.42 µs # local, bare metal on host tcp loopback
/tmp/go/redis.sock: 49.08 µs # local, bare metal on host unix socket
localhost:6380: 276.26 µs # local, docker networking
</code></pre>
<p>Which seems in line with my intuition.</p>
<pre><code> package main
import (
"context"
"fmt"
"github.com/go-redis/redis"
"math"
"strconv"
"time"
)
var ctx = context.Background()
func reduceMin(xs []float64) float64 {
if len(xs) == 0 {
return math.NaN()
}
if len(xs) == 1 {
return xs[0]
}
best := math.Min(xs[0], xs[1])
for _, v := range xs {
best = math.Min(best, v)
}
return best
}
func runProfileN(rdb *redis.Client, N int, tries int) (timePer float64, countErrors int){
var val string
totalElapsed := time.Duration(0)
for t := 0; t < tries; t++ {
start := time.Now()
for i := 0; i < N; i++ {
//err := rdb.Set(ctx, "key", fmt.Sprintf("|%3d|val|%3d|", N, i), 0).Err()
err := rdb.Set(ctx, "key", fmt.Sprintf("%d", i), 0).Err()
if err != nil {
panic(err)
}
val, err = rdb.Get(ctx, "key").Result()
if err != nil {
panic(err)
}
i2, err := strconv.Atoi(val)
if err != nil {
panic(err)
}
if i != i2 {
countErrors++
}
}
elapsed := time.Since(start)
totalElapsed += elapsed
}
timePer = float64(totalElapsed.Microseconds()) / float64(N*tries)
return
}
func runProfile(redisAddr string) float64 {
rdb := redis.NewClient(&redis.Options{
Addr: redisAddr,
Password: "", // no password set
DB: 0, // use default DB
})
iters := []int{3, 10, 33, 100, 333, 1000, 3333, 10000}
times := make([]float64, 0)
tries := 5
for _, N := range iters {
timePer, countErrors := runProfileN(rdb, N, tries)
fmt.Printf("%8d: elapsed: %7.2f µs errors: %d\n", N, timePer, countErrors/tries)
times = append(times, timePer)
}
best := reduceMin(times)
fmt.Printf("\n %11s best: %7.2f µs \n", " ", best)
return best
}
func main() {
hosts := []string{"localhost:6379", "/tmp/go/redis.sock", "localhost:6380"}
results := map[string]float64{}
for _, redisAddr := range hosts {
fmt.Println("client on ", redisAddr)
results[redisAddr] = runProfile(redisAddr)
}
for _, redisAddr := range hosts {
fmt.Printf("%30s: %5.2f µs\n", redisAddr, results[redisAddr])
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:19:19.500",
"Id": "487842",
"Score": "1",
"body": "would not be simpler to use pprof and benchmarking ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T14:09:03.813",
"Id": "488128",
"Score": "0",
"body": "Ah, pprof would be a great idea! I'll give that a spin in a bit."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-04T23:28:00.263",
"Id": "248943",
"Score": "2",
"Tags": [
"performance",
"go",
"redis"
],
"Title": "Profiling redis RTT in go"
}
|
248943
|
<p>This is a Java program I implemented to encrypt a string using the ADVGVX cipher. It takes in the message, the passphrase used to generate the Polybius square, and keyword for the transposition part of the encryption. It prints the encrypted string. What would you suggest fixing and improving?</p>
<pre><code>import java.util.*;
public class Cipher {
public static void main(String args[]){
// get input!
// make scanner object for input
Scanner scan = new Scanner(System.in);
// the message to encrypt
System.out.print("Enter message to encrypt: ");
String mes = scan.nextLine();
// keyphrase, used to make polybius square
System.out.print("Enter keyphrase for Polybius square: ");
String keyphrase = scan.nextLine();
while (!validKeyphrase(keyphrase) ){
System.out.print("Enter valid keyphrase: ");
keyphrase = scan.nextLine();
}
// keyword for transposition
System.out.print("Enter keyword for transposition: ");
String keyword = scan.nextLine();
while (keyword.length() <= 1 && keyword.length() > mes.length()){
System.out.println("Keyword length must match message length.");
System.out.print("Enter keyword: ");
keyword = scan.nextLine();
}
// take keyphrase and chuck into polybius square
char [][] square = new char[6][6];
// putting keyphrase into a character array
char[] letters = keyphrase.toCharArray();
// filling the polybius square
int counter = -1;
for (int i = 0; i< 6; i++){
for (int j=0; j< 6; j++){
counter++;
square[i][j] = letters[counter];
}
}
// after the substitution
String substitution = substitute(square, mes);
// dimensions of transposition array
int transY = keyword.length();
int transX = substitution.length()/keyword.length()+1;
char [][] newSquare = new char[transX][transY];
// fills in the transposition square
counter = -1;
for (int i=0; i< transX; i++){
for (int j=0; j< transY; j++){
counter++;
if (counter < substitution.length())
newSquare[i][j] = substitution.charAt(counter);
}
}
// the keyword as a character array
char [] keyArr = keyword.toCharArray();
// switching columns based on a bubble sort
boolean repeat = true;
while (repeat){
repeat = false;
for (int i=0; i<keyArr.length-1; i++){
if (keyArr[i+1] < keyArr[i]){
repeat = true;
//dealing with the keyArr
char temp = keyArr[i+1];
keyArr[i+1] = keyArr[i];
keyArr[i] = temp;
// dealing with the newSquare array
for (int n = 0; n < transY -1 ; n++){
temp = newSquare[n][i+1];
newSquare[n][i+1] = newSquare[n][i];
newSquare[n][i] = newSquare[n][i];
newSquare[n][i] = temp;
}
}
}
}
String result = "";
StringBuilder sb = new StringBuilder(result);
for (int i=0; i< transX; i++){
for (int j=0; j< transY; j++){
if (newSquare[i][j] != '\0')
sb.append(newSquare[i][j]);
}
}
for (int i=0; i< sb.toString().length(); i++){
System.out.print(sb.toString().charAt(i));
if (i %2 == 1){
System.out.print(" ");
}
}
System.out.println();
}
// must contain exactly 36 characters
// must contain all unique characters
// must contain a-z/A-Z and 0-9
public static boolean validKeyphrase(String s){
if (s.length() != 36){
return false;
}
String S = s.toLowerCase();
Set<Character> foo = new HashSet<>();
for (int i=0; i< S.length(); i++){
foo.add(S.charAt(i));
}
if (foo.size() != S.length()){
return false;
}
for (int i='a'; i<='z'; i++){
if (foo.remove((char) i)){}
else
return false;
}
for (int i='0'; i<='9'; i++){
if (foo.remove((char) i)){}
else
return false;
}
if (!foo.isEmpty())
return false;
return true;
}
public static String substitute(char[][] arr, String s){
String result = "";
final char[] cipher = {'A', 'D', 'F', 'G', 'V', 'X'};
for (int k = 0; k < s.length(); k++){
arrLoop: {
for (int i=0; i< 6; i++){
for (int j=0; j< 6; j++){
if (s.charAt(k) == arr[i][j] ){
result += cipher[i];
result += cipher[j];
break arrLoop;
}
}
}
}
}
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T06:14:07.003",
"Id": "487818",
"Score": "3",
"body": "Welcome to Code Review, please add link, documentation to the explanation of algorithm you had implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T07:01:19.750",
"Id": "487820",
"Score": "1",
"body": "`What [needs fixing]?` For starters, the acronym in the post body. (Then, as of 2020/9/5, CR is one of the sites needing a newline following a `~~~` or `\\`\\`\\`` closing a code block.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:10:15.210",
"Id": "487837",
"Score": "0",
"body": "@greybeard I usually remove the code-fencing when it goes wrong like that and simply indent-all. The tag takes care of the code-highlighting. See edit, Ctrl+K is magic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:16:28.767",
"Id": "487839",
"Score": "0",
"body": "(@Mast one advantage of fences is copy&paste between IDE & SE.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T11:17:23.537",
"Id": "487840",
"Score": "0",
"body": "@greybeard My IDE can un-indent with shift-tab. The whole thing at once. A lot of modern editors can (Notepad++ has had it standard for years now)."
}
] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Always add curly braces to <code>loop</code> & <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h3>Avoid using <code>C-style</code> array declaration</h3>\n<p>In the main method, you declared a <code>C-style</code> array declaration with the <code>args</code> variable.</p>\n<p><strong>before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>String args[]\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>String[] args\n</code></pre>\n<p>In my opinion, this style is less used and can cause confusion.</p>\n<h2>Extract some of the logic to methods.</h2>\n<p>When you have logic that does the same thing, you can generally move it into a method and reuse it.</p>\n<p>In your main method, you can extract most of the logic that asks the user a question to new methods; this will shorten the method and make the code more readable.</p>\n<p>I suggest the following refactor:</p>\n<ol>\n<li>Create a new method <code>askUserAndReceiveAnswer</code> that ask a question as a string and return a string with the answer.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static String askUserAndReceiveAnswer(Scanner scan, String s) {\n System.out.print(s);\n return scan.nextLine();\n}\n</code></pre>\n<p>This method can be reused 3x time in your code.</p>\n<ol start=\"2\">\n<li>Create a new method that asks the user, for a valid keyphrase.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static String askUserForValidKeyPhrase(Scanner scan) {\n String keyphrase = askUserAndReceiveAnswer(scan, "Enter keyphrase for Polybius square: ");\n\n while (!validKeyphrase(keyphrase)) {\n System.out.print("Enter valid keyphrase: ");\n keyphrase = scan.nextLine();\n }\n return keyphrase;\n}\n</code></pre>\n<ol start=\"3\">\n<li>Create a new method that asks the user, for a valid keyword.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static String askUserForValidKeyword(Scanner scan, String mes) {\n String keyword = askUserAndReceiveAnswer(scan, "Enter keyword for transposition: ");\n\n while (keyword.length() <= 1 && keyword.length() > mes.length()) {\n System.out.println("Keyword length must match message length.");\n System.out.print("Enter keyword: ");\n keyword = scan.nextLine();\n }\n return keyword;\n}\n</code></pre>\n<h2>Use <code>java.lang.StringBuilder</code> to concatenate String in a loop.</h2>\n<p>It's generally more efficient to use the builder in a loop, since the compiler is unable to make it efficient in a loop; since it creates a new String each iteration. There are lots of good explanations with more details on the subject.</p>\n<p>Cipher#substitute\n<strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public static String substitute(char[][] arr, String s) {\n String result = "";\n final char[] cipher = {'A', 'D', 'F', 'G', 'V', 'X'};\n\n for (int k = 0; k < s.length(); k++) {\n arrLoop: {\n for (int i = 0; i < 6; i++) {\n for (int j = 0; j < 6; j++) {\n if (s.charAt(k) == arr[i][j]) {\n result += cipher[i];\n result += cipher[j];\n break arrLoop;\n }\n }\n }\n }\n }\n\n return result;\n}\n</code></pre>\n<p><strong>after</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public static String substitute(char[][] arr, String s) {\n StringBuilder result = new StringBuilder();\n final char[] cipher = {'A', 'D', 'F', 'G', 'V', 'X'};\n\n for (int k = 0; k < s.length(); k++) {\n arrLoop: {\n for (int i = 0; i < 6; i++) {\n for (int j = 0; j < 6; j++) {\n if (s.charAt(k) == arr[i][j]) {\n result.append(cipher[i]);\n result.append(cipher[j]);\n break arrLoop;\n }\n }\n }\n }\n }\n\n return result.toString();\n}\n</code></pre>\n<h2>Instead of having empty body in a condition, invert the logic.</h2>\n<p>In your code, you have multiple conditions that have an empty body; I highly suggest that you invert the logic to remove the confusion those can create.</p>\n<h3>Cipher#validKeyphrase</h3>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 'a'; i <= 'z'; i++) {\n if (foo.remove((char) i)) {\n\n } else {\n return false;\n }\n}\n\nfor (int i = '0'; i <= '9'; i++) {\n if (foo.remove((char) i)) {\n\n } else {\n return false;\n }\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 'a'; i <= 'z'; i++) {\n if (!foo.remove((char) i)) {\n return false;\n }\n}\n\nfor (int i = '0'; i <= '9'; i++) {\n if (!foo.remove((char) i)) {\n return false;\n }\n}\n</code></pre>\n<h2>Simplify the boolean conditions.</h2>\n<p>This can be simplified</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!foo.isEmpty()) {\n return false;\n}\n\nreturn true;\n</code></pre>\n<p>to</p>\n<pre class=\"lang-java prettyprint-override\"><code>return foo.isEmpty();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T12:34:45.053",
"Id": "248958",
"ParentId": "248946",
"Score": "5"
}
},
{
"body": "<p>Here's my nitpick on code practices. You should really be more consistent and more neat with regard to code style. Furthermore, you should definitely use more methods, better error reporting and better keywords.</p>\n<p>As for the design, I would expect to be able to instantiate a <code>Cipher</code> (e.g. a constructor with the square as input) and then have non-static <code>encrypt</code> and <code>decrypt</code> methods on them that take a <code>message</code> and identically sized <code>passphrase</code>. Those methods in turn should be subdivided using <code>private</code> methods.</p>\n<hr />\n<pre><code>public class Cipher {\n</code></pre>\n<p>That's not specific enough for a class name.</p>\n<hr />\n<pre><code>System.out.print("Enter message to encrypt: ");\n...\nSystem.out.print("Enter valid keyphrase: ");\n</code></pre>\n<p>I'd make it a bit more clear what is expected from the user, e.g. that you have to enter a line, or what kind of keyphrase is acceptable.</p>\n<hr />\n<pre><code>char [][] square = new char[6][6];\n</code></pre>\n<p>That you perform the user interface within the <code>main</code> is somewhat acceptable, but the business logic should not be in the main method.</p>\n<p>The variables <code>6</code> should be in a constant or two.</p>\n<hr />\n<pre><code>char[] letters = keyphrase.toCharArray();\n</code></pre>\n<p>Later on we'll find that the <code>letters</code> should also contain digits. We call those alphanumericals (<code>alphaNumericals</code>).</p>\n<hr />\n<pre><code>int counter = -1;\n...\nsquare[i][j] = letters[counter];\n</code></pre>\n<p>Try and avoid invalid values. For instance, in this case <code>letters[counter++]</code> would have let you start with a zero.</p>\n<hr />\n<pre><code>int transX = substitution.length()/keyword.length()+1;\n</code></pre>\n<p>Always use spaces around operators, e.g. <code>substitution.length() / keyword.length() +1;</code>.</p>\n<hr />\n<pre><code>// dimensions of transposition array\nint transY = keyword.length();\n</code></pre>\n<p>I'm a bit worried about the variable naming here, transY doesn't sound like a dimention to me. And the fact that you need to prefix <code>trans</code> indicates that you should have created a method (see next comment).</p>\n<hr />\n<pre><code>// fills in the transposition square\n</code></pre>\n<p>If you have to make such a comment then you might as well create a method, e.g. <code>fillTranspositionSquare()</code> right?</p>\n<hr />\n<pre><code>for (int i=0; i< transX; i++){\n</code></pre>\n<p>For sure, if <code>transX</code> is the maximum for <code>x</code>, you're not naming your variable <code>i</code>, right?</p>\n<hr />\n<pre><code>String result = "";\n</code></pre>\n<p>This is definitely a code smell. Assigning <code>null</code> or an empty string is almost never needed.</p>\n<p>Also, this is where you got bored explaining your code in comments. It would not be necessary if you'd had used well named methods.</p>\n<hr />\n<pre><code>StringBuilder sb = new StringBuilder(result);\n</code></pre>\n<p>Now your <code>StringBuilder</code> has a capacity of zero character, in all likelihood. Instead, you already know how large it will be in the end, right? So calculate the size beforehand and use the <code>StringBuilder(int capacity)</code> constructor.</p>\n<hr />\n<pre><code>if (s.length() != 36){\n</code></pre>\n<p>Never use literals like that. First of all, 36 is 6 x 6. Just use the dimensions to calculate that number, and if it is indeed static, put it in a constant.</p>\n<hr />\n<pre><code>String S = s.toLowerCase();\n</code></pre>\n<p>You already had an <code>s</code> and decided to use <code>S</code> for a <em>lowercase</em> string? Seriously? And why is <code>s</code> not called <code>keyphrase</code>? Hint: you can use simple names while typing, but modern IDE's will let you rename variables afterwards. That way you can type concisely and make it more verbose afterwards.</p>\n<hr />\n<pre><code>return false;\n</code></pre>\n<p>No, here you should have a more complex result, e.g. an enum to indicate the kind of failure. Just returning false for any kind of failure won't allow you to indicate to the user what is wrong.</p>\n<hr />\n<pre><code>public static String substitute(char[][] arr, String s){\n</code></pre>\n<p>Wait, the <code>polybiusSquare</code> has become <code>arr</code>? Why is that?</p>\n<hr />\n<pre><code>String result = "";\n</code></pre>\n<p>Mentioned already, here <code>String resultBuilder = new StringBuilder(s.length())</code> would certainly be better.</p>\n<hr />\n<pre><code>arrLoop: {\n</code></pre>\n<p>If you need labels then you're doing it wrong, most of the time. Note that the label is for the <code>for</code> loop, so the brace is not necessary. If you ever need to use a label, make it fully upper case. However, in this case the double for loop can easily be put inside a separate method, so it is not required.</p>\n<p>Note that the spacing for <code><</code> is completely inconsistent. Not using enough spacing is bad enough, having an inconsistent style is considered worse.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T00:11:05.863",
"Id": "249014",
"ParentId": "248946",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T03:04:15.347",
"Id": "248946",
"Score": "3",
"Tags": [
"java",
"cryptography",
"encryption"
],
"Title": "Encrypts a message using the ADFGVX cipher"
}
|
248946
|
<p>Here is a custom class I use to handle different types of orders in Laravel. This question includes the code regarding Order Type A. I want to know whether I can simplify the code. I have different Order Types with the same functions but different in behaviour. That's why I'm using an abstract class to extend all order types.</p>
<pre><code>abstract class BaseOrder
{
abstract public function getOrder(Order $order);
abstract public function storeOrder(Request $request);
...
}
class OrderTypeA extends BaseOrder
{
private $type = 'A';
public function getOrder(Order $order)
{
return $order->load('items.product')
->makeHidden(['order_no', 'created_at', 'updated_at', 'created_by']);
}
public function storeOrder($request)
{
$returnedValues = DB::transaction(function () use ($request) {
$order = new Order;
$order->type = $this->type;
$order->from = $request->json('from');
$order->amount = $request->json('amount');
$order->status = 2;
$order->save();
foreach ($request->json('items') as $item) {
$order->items()->create([
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'total' => $item['total'],
]);
}
return compact('order');
});
return $returnedValues['order']->load('items');
}
public function updateOrder($request)
{
$returnedValues = DB::transaction(function () use ($request) {
if ($request->id) {
$order = Order::findOrFail($request->id);
$order->amount = $request->json('amount');
$order->status = 1;
$order->save();
$order->items()->delete();
foreach ($request->json('items') as $item) {
$order->items()->create([
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'total' => $item['total'],
]);
}
} else {
$order = new Order;
$order->type = $this->type;
$order->from = $request->json('from');
$order->to = null;
$order->amount = $request->json('amount');
$order->status = 1;
$order->save();
foreach ($request->json('items') as $item) {
$order->items()->create([
'product_id' => $item['product_id'],
'quantity' => $item['quantity'],
'total' => $item['total'],
]);
}
}
return compact('order');
});
return $returnedValues['order']->load('items');
}
public function generateOrder($customer)
{
$order = new stdClass();
$order->id = null;
$order->type = $this->type;
$order->from = $customer->id;
$order->to = null;
$order->status = 1;
$totalAmount = 0;
$items = [];
$stocks = Stock::where('type', 1)
->where('customer_id', $customer->id)
->whereRaw('stock <= reorder_level')
->get();
if (count($stocks) > 0) {
foreach ($stocks as $key => $stock) {
if ($stock->minimum_order_quantity != 0) {
$priceListItem = PriceList::where('product_id', $stock->product_id)->latest()->first();
$item = new stdClass;
$item->id = $key;
$item->product_id = $stock->product_id;
$item->product = Product::findOrFail($stock->product_id);
$item->order_id = null;
$item->quantity = (int) $stock->minimum_order_quantity;
$item->total = ((int) $stock->minimum_order_quantity * ((float) $priceListItem->price));
$item->is_checked = true;
$item->created_at = null;
$item->updated_at = null;
$totalAmount += $item->total;
$items[] = $item;
}
}
}
$order->amount = $totalAmount;
$order->items = $items;
return $order;
}
public function deleteOrder(Order $order)
{
if ($order->status == 'Draft') {
$order->forceDelete();
} else {
$order->delete();
}
return $order;
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>main “question”</h1>\n<blockquote>\n<p><em>I want to know whether I can simplify the code more.</em></p>\n</blockquote>\n<h2>Redundant code</h2>\n<p>There are three places in the code where an order is either created or loaded before being saved and having its items saved. This code could be abstracted to a separate method - perhaps on <code>BaseOrder</code>, though it is difficult to know without seeing the other subclassses - that accepts a request object and status. If that request object has an <code>id</code> then it will:</p>\n<ul>\n<li>call <code>Order::findOrFail()</code></li>\n<li>call <code>$order->items()->delete();</code></li>\n</ul>\n<p>otherwise it will:</p>\n<ul>\n<li>call <code>Order::create()</code> (or instantiate with the <code>new</code> operator if preferred)</li>\n<li>Set the <code>type</code> property</li>\n<li>Set the <code>from</code> property</li>\n<li>Sets the <code>to</code> property to <code>null</code>?</li>\n</ul>\n<p>And then in both cases:</p>\n<ul>\n<li>sets the amount property</li>\n<li>Saves the order</li>\n<li>loops over <code>$request->json('items')</code> to create items.</li>\n</ul>\n<p>If that method is moved up to the base class, then I would consider whether <code>type</code> really needs to be a member/instance variable. If not, it could just be a constant that is set it each class and referenced with the <code>static</code> class (thanks to <a href=\"https://www.php.net/manual/en/language.oop5.late-static-bindings.php\" rel=\"nofollow noreferrer\">Late static binding</a>). Additionally, could the class name be used? E.g, <code>$this->type = str_replace('OrderType', '', static::class);</code></p>\n<h1>Other suggestions</h1>\n<h2>returning early to minimize indentation</h2>\n<p>In the <code>foreach</code> loop within the <code>generateOrder()</code> method</p>\n<blockquote>\n<pre><code> if ($stock->minimum_order_quantity != 0) { \n $priceListItem = PriceList::where('product_id', $stock->product_id)->latest()->first();\n</code></pre>\n</blockquote>\n<p>Look at how long that line is. Also consider that it is indented 5 times! One tactic to reduce indentation levels is to return early - in this case use <code>continue</code>:</p>\n<pre><code>if ($stock->minimum_order_quantity === 0) {\n continue;\n}\n$priceListItem = PriceList::where('product_id', $stock->product_id)->latest()->first();\n</code></pre>\n<p>Also consider following <a href=\"https://www.php-fig.org/psr/psr-12/#23-lines\" rel=\"nofollow noreferrer\">PSR-12 section 2.3</a> and limit the line length to 80 characters:</p>\n<blockquote>\n<p>Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD be split into multiple subsequent lines of no more than 80 characters each.</p>\n</blockquote>\n<p>That long line could be split to multiple for readability:</p>\n<pre><code>$priceListItem = PriceList::where('product_id', $stock->product_id)\n ->latest()\n ->first();\n</code></pre>\n<h2>arbitrary values</h2>\n<p>There are a couple places where the <code>status</code> field is set to an integer value e.g.</p>\n<blockquote>\n<pre><code> $order->status = 2;\n</code></pre>\n</blockquote>\n<p>And</p>\n<blockquote>\n<pre><code>$order->status = 1;\n</code></pre>\n</blockquote>\n<p>I can’t tell from the code what those values mean, and neither will anybody else (possibly including your future self!).</p>\n<p>It would be wise to declare <a href=\"https://www.php.net/manual/en/language.oop5.constants.php\" rel=\"nofollow noreferrer\">constants</a> for those-\nI can only guess as to what to call them but use appropriate names-</p>\n<pre><code>class OrderTypeA extends BaseOrder\n{\n const STATUS_CREATED = 1;\n const STATUS_UPDATED = 2;\n</code></pre>\n<p>Maybe it makes sense to declare those on <code>BaseOrder</code>?</p>\n<p>Then if somebody sees a line like this:</p>\n<pre><code>$order->status = self::STATUS_UPDATED;\n</code></pre>\n<p>That person can tell what the value is. Also if the value ever changes it can be updated in a single spot instead of everywhere it is used throughout the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-15T06:23:09.907",
"Id": "253489",
"ParentId": "248947",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253489",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T03:19:59.500",
"Id": "248947",
"Score": "2",
"Tags": [
"php",
"inheritance",
"laravel",
"crud",
"eloquent"
],
"Title": "PHP Laravel Order generation Custom Class"
}
|
248947
|
<p>I have created a DFS backtracking maze generator (non-recursive) using C++ and SFML. It works great but the final results of creating a 9000 x 9000 with cell size 2 is around 1 min and 46 seconds <-> 1 min and 30 seconds, to directly store the generated maze as an image without any kind of GUI.</p>
<p>I'll try to explain my code. The second last function <code>drawMaze()</code> is the main logic. I have used to stacks one for x and other for y coordinate to store the backtrack.</p>
<pre class="lang-cpp prettyprint-override"><code>//maze.cpp
#define SFML_STATIC
#include "Maze.h"
#include "SFML/Graphics.hpp"
#include<iostream>
#include<stack>
#include <chrono>
#include <thread>
#include<time.h>
using namespace std;
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; //
void Maze::setWidth(int width)
{
this->width=width;
}
void Maze::setHeight(int height)
{
this->height=height;
}
void Maze::setCellSize(int size)
{
cellSize=size;
rows=height/cellSize;
cols=width/cellSize;
}
void Maze::setNotVisitedCellColor(sf::Color color)
{
notVisitedColor=color;
}
void Maze::setCurrentCellColor(sf::Color color)
{
currentColor=color;
}
void Maze::setVisitedCellColor(sf::Color start, sf::Color end)
{
this->start=start;
this->end=end;
}
void Maze::setBorderColor(sf::Color color)
{
borderColor=color;
}
void Maze::setBackgroundColor(sf::Color color)
{
backgroundColor=color;
}
void Maze::handleBorder(sf::VertexArray &Border,int borderCounter,sf::Color borderColor,int x,int y)
{
if(checkBit(maze[(cols*x)+y],topMask))
{
Border[borderCounter].color = this->borderColor;
Border[borderCounter+1].color = this->borderColor;
}
else
{
Border[borderCounter].color =borderColor;
Border[borderCounter+1].color =borderColor;
}
if(checkBit(maze[(cols*x)+y],rightMask))
{
Border[borderCounter+2].color = this->borderColor;
Border[borderCounter+3].color = this->borderColor;
}
else
{
Border[borderCounter+2].color =borderColor;
Border[borderCounter+3].color = borderColor;
}
if(checkBit(maze[(cols*x)+y],bottomMask))
{
Border[borderCounter+4].color = this->borderColor;
Border[borderCounter+5].color = this->borderColor;
}
else
{
Border[borderCounter+4].color =borderColor;
Border[borderCounter+5].color = borderColor;
}
if(checkBit(maze[(cols*x)+y],leftMask))
{
Border[borderCounter+6].color = this->borderColor;
Border[borderCounter+7].color = this->borderColor;
}
else
{
Border[borderCounter+6].color = borderColor;
Border[borderCounter+7].color =borderColor;
}
}
int Maze::invalidNeighbour(int x,int y,char dir)
{
if(dir=='t' || dir=='b')
{
if(x<0 || x>((rows*cols)-1))
{
return 0;
}
else
{
return 1;
}
}
else
{
if(x<0 || x>((rows*cols)-1) || abs((y/cols)-(x/cols))!=0)
{
return 0;
}
else
{
return 1;
}
}
}
void Maze::checkNeighbours(int x,int y)
{
vector<char> direction;
int top=invalidNeighbour(cols*(x-1)+y,cols*x+y,'t');
int right=invalidNeighbour(cols*x+(y+1),cols*x+y,'r');
int bottom=invalidNeighbour(cols*(x+1)+y,cols*x+y,'b');
int left=invalidNeighbour(cols*x+(y-1),cols*x+y,'l');
if(top)
{
int visited=checkBit(maze[((cols*(x-1))+y)],visitedMask);
if(!visited)
{
direction.push_back('t');
}
}
if(right)
{
int visited=checkBit(maze[(cols*x)+(y+1)],visitedMask);
if(!visited)
{
direction.push_back('r');
}
}
if(bottom)
{
int visited=checkBit(maze[(cols*(x+1)+y)],visitedMask);
if(!visited)
{
direction.push_back('b');
}
}
if(left)
{
int visited=checkBit(maze[(cols*x+(y-1))],visitedMask);
if(!visited)
{
direction.push_back('l');
}
}
if(direction.size()>0)
{
int randomNumber=rand()%direction.size();
btx.push(x);
bty.push(y);
if(direction[randomNumber]=='t')
{
turnOnBit(maze[((cols*(x-1))+y)],visitedMask);
btx.push(x-1);
bty.push(y);
turnOffBit(maze[cols*x+y],topMask);
turnOffBit(maze[((cols*(x-1))+y)],bottomMask);
}
else if(direction[randomNumber]=='r')
{
turnOnBit(maze[(cols*x)+(y+1)],visitedMask);
turnOffBit(maze[cols*x+y],rightMask);
turnOffBit(maze[(cols*x)+(y+1)],leftMask);
btx.push(x);
bty.push(y+1);
}
else if(direction[randomNumber]=='b')
{
turnOnBit(maze[(cols*(x+1)+y)],visitedMask);
turnOffBit(maze[cols*x+y],bottomMask);
turnOffBit(maze[(cols*(x+1)+y)],topMask);
btx.push(x+1);
bty.push(y);
}
else if(direction[randomNumber]=='l')
{
turnOnBit(maze[(cols*x+(y-1))],visitedMask);
turnOffBit(maze[cols*x+y],leftMask);
btx.push(x);
bty.push(y-1);
turnOffBit(maze[(cols*(x)+(y-1))],rightMask);
}
}
}
void Maze::saveImage()
{
float initial=0.9;
sf::Image image;
image.create((cols*cellSize)+(2*10),(rows*cellSize)+(2*10), backgroundColor);
for(int x=0;x<rows;x++)
{
for(int y=0;y<cols;y++)
{
sf::Color testing;
testing.r=(start.r*initial)+(end.r*(1-initial));
testing.g=(start.g*initial)+(end.g*(1-initial));
testing.b=(start.b*initial)+(end.b*(1-initial));
for(int i=(y*cellSize)+10;i<=(y*cellSize)+10+cellSize;i++)
{
for(int j=(x*cellSize)+10;j<=(x*cellSize)+10+cellSize;j++)
{
image.setPixel(i,j, testing);
}
}
if(checkBit(maze[cols*x+y],topMask))
{
for(int i=(y*cellSize)+10;i<=(y*cellSize)+10+cellSize;i++)
{
image.setPixel(i, (x*cellSize)+10, borderColor);
}
}
if(checkBit(maze[cols*x+y],rightMask))
{
for(int i=(x*cellSize)+10;i<=(x*cellSize)+10+cellSize;i++)
{
image.setPixel((y*cellSize)+10+cellSize,i, borderColor);
}
}
if(checkBit(maze[cols*x+y],bottomMask))
{
for(int i=(y*cellSize)+10;i<=(y*cellSize)+10+cellSize;i++)
{
image.setPixel(i,(x*cellSize)+10+cellSize, borderColor);
}
}
if(checkBit(maze[cols*x+y],leftMask))
{
for(int i=(x*cellSize)+10;i<=(x*cellSize)+10+cellSize;i++)
{
image.setPixel((y*cellSize)+10,i, borderColor);
}
}
}
initial=initial-(initial/rows);
}
if (!image.saveToFile("finally.png"))
cout<<"unsuccessfull image saving";
else
cout<<"successful image save";
maze.clear();
// vector<unsigned char> emptyMaze(0);
// vector<unsigned char> emptyMaze().swap(maze);
}
void Maze::drawMaze(string mazeName,int animate,int fps=200)
{
float initial=0.9;
sf::Color borderColor;
int padding=10;
turnOnBit(maze[0],visitedMask);
btx.push(0);
bty.push(0);
sf::VertexArray Quad(sf::Quads,4*rows*cols);
sf::VertexArray Border(sf::Lines,rows*cols*8);
if(animate!=-1)
{
window.create(sf::VideoMode(width+padding+padding,height+padding+padding),mazeName);
if(animate)
{
window.setFramerateLimit(fps);
}
}
while(window.isOpen() || animate==-1)
{
if(animate!=-1)
{
sf::Event event;
while(window.pollEvent(event))
{
if(event.type==sf::Event::Closed)
{
window.close();
}
}
window.clear(backgroundColor);
}
int counter=0;
int borderCounter=0;
if(animate)
{
if(!btx.empty() && !bty.empty())
{
int x=btx.top();
int y=bty.top();
btx.pop();
bty.pop();
checkNeighbours(x,y);
}
}
float p=initial;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(animate==0 || animate==-1)
{
if(!btx.empty() && !bty.empty())
{
int x=btx.top();
int y=bty.top();
btx.pop();
bty.pop();
checkNeighbours(x,y);
}
}
Quad[counter].position = sf::Vector2f((j*cellSize)+padding, (i*cellSize)+cellSize+padding);
Quad[counter+1].position = sf::Vector2f(j*cellSize+padding, i*cellSize+padding);
Quad[counter+2].position = sf::Vector2f((j*cellSize)+cellSize+padding, i*cellSize+padding);
Quad[counter+3].position = sf::Vector2f((j*cellSize)+cellSize+padding,(i*cellSize)+cellSize+padding);
Border[borderCounter].position = sf::Vector2f((j*cellSize)+padding,(i*cellSize)+padding);
Border[borderCounter+1].position = sf::Vector2f((j*cellSize)+cellSize+padding,i*cellSize+padding);
Border[borderCounter+2].position = sf::Vector2f((j*cellSize)+cellSize+padding,i*cellSize+padding);
Border[borderCounter+3].position = sf::Vector2f((j*cellSize)+cellSize+padding,(i*cellSize)+cellSize+padding);
Border[borderCounter+4].position = sf::Vector2f((j*cellSize)+cellSize+padding,(i*cellSize)+cellSize+padding);
Border[borderCounter+5].position = sf::Vector2f((j*cellSize)+padding,(i*cellSize)+cellSize+padding);
Border[borderCounter+6].position = sf::Vector2f((j*cellSize)+padding,(i*cellSize)+cellSize+padding);
Border[borderCounter+7].position = sf::Vector2f((j*cellSize)+padding,(i*cellSize)+padding);
if(animate!=-1)
{
int visited=checkBit(maze[(cols*i)+j],visitedMask);
if(!visited)
{
Quad[counter].color = notVisitedColor;
Quad[counter+1].color = notVisitedColor;
Quad[counter+2].color = notVisitedColor;
Quad[counter+3].color =notVisitedColor;
}
else
{
sf::Color testing;
testing.r=(start.r*p)+(end.r*(1-p));
testing.g=(start.g*p)+(end.g*(1-p));
testing.b=(start.b*p)+(end.b*(1-p));
Quad[counter].color = testing;
Quad[counter+1].color = testing;
Quad[counter+2].color = testing;
Quad[counter+3].color =testing;
borderColor=testing;
}
}
handleBorder(Border,borderCounter,borderColor,i,j);
if(animate==1 && !btx.empty() && !bty.empty())
{
int topx=btx.top();
int topy=bty.top();
if(topx==i && topy==j)
{
Quad[counter].color = currentColor;
Quad[counter+1].color =currentColor;
Quad[counter+2].color = currentColor;
Quad[counter+3].color =currentColor;
}
}
counter=counter+4;
borderCounter=borderCounter+8;
}
p=p-((initial/rows));
}
if(animate==0 || animate==1)
{
window.draw(Quad);
window.draw(Border);
window.display();
}
else if(animate==-1)
{
if(btx.empty() || bty.empty())
{
break;
}
}
}
}
void Maze::createMaze(string mazeName,int animate,int fps)
{
srand(time(NULL));
unsigned char initial=0b0000'1111;
maze.resize(rows*cols);
for(int i=0;i<rows*cols;i++)
{
maze[i]=initial;
}
drawMaze(mazeName,animate,fps);
}
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>
//maze.h
#ifndef _MAZE_H_
#define _MAZE_H_
#define SFML_STATIC
#include "SFML/Graphics.hpp"
#include "Cell.h"
#include<stack>
#include<vector>
using namespace std;
class Maze
{
private:
vector<unsigned char> maze;
int width;
int height;
int cellSize;
int rows;
int cols;
sf::Color start;
sf::Color end;
sf::Color notVisitedColor;
sf::Color currentColor;
stack<int> btx;
stack<int> bty;
sf::RenderWindow window;
sf::Color borderColor;
sf::Color backgroundColor;
public:
void setWidth(int width);
void setHeight(int height);
void setCellSize(int size);
void setVisitedCellColor(sf::Color start,sf::Color end);
void setNotVisitedCellColor(sf::Color color);
void setCurrentCellColor(sf::Color color);
void setBorderColor(sf::Color color);
void setBackgroundColor(sf::Color color);
void drawMaze(string mazeName,int animate,int fps);
void checkNeighbours(int x,int y);
int invalidNeighbour(int x,int y,char dir);
void createMaze(string mazeName,int animate,int fps=200);
void handleBorder(sf::VertexArray &Border,int borderCounter,sf::Color borderColor,int x,int y);
void saveImage();
};
#endif
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>
//cell.h
#ifndef _CELL_H_
#define _CELL_H_
void turnOnBit(unsigned char &cell, unsigned char mask);
void turnOffBit(unsigned char &cell, unsigned char mask);
int checkBit(unsigned char &cell,unsigned char mask);
const unsigned char topMask = 0b0000'0001;
const unsigned char rightMask = 0b0000'0010;
const unsigned char bottomMask = 0b0000'0100;
const unsigned char leftMask = 0b0000'1000;
const unsigned char visitedMask = 0b0001'0000;
#endif
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>//cell.cpp
#include "Cell.h"
void turnOnBit(unsigned char &cell, unsigned char mask)
{
cell |= mask;
}
void turnOffBit(unsigned char &cell, unsigned char mask)
{
cell &= ~mask;
}
int checkBit(unsigned char &cell,unsigned char mask)
{
if(cell & mask)
{
return 1;
}
else
{
return 0;
}
}
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>
//main.cpp
// g++ -c main.cpp -o main.o -I"I:/SFML/include"
// g++ -c cell.cpp -o cell.o -I"I:/SFML/include"
// g++ -c maze.cpp -o maze.o -I"I:/SFML/include"
// g++ main.o maze.o cell.o -o main -L"I:/SFML/lib" -lsfml-graphics-s -lsfml-window-s -lsfml-audio-s -lsfml-system-s -lsfml-network-s -lwinmm -lopengl32 -lopenal32 -lflac -lvorbisenc -lvorbisfile -lvorbis -logg -lws2_32 -lgdi32 -lkernel32 -luser32 -lwinspool -lshell32 -lole32 -luuid -lcomdlg32 -lfreetype -ladvapi32
#define SFML_STATIC
#include "Maze.h"
#include "SFML/Graphics.hpp"
using namespace std;
int main()
{
sf::Color grey(200,200,200);
sf::Color start(255,100,45);
sf::Color end(30,150,200);
Maze maze;
maze.setWidth(1000);
maze.setHeight(600);
maze.setCellSize(25);
maze.setBackgroundColor(grey);
maze.setBorderColor(sf::Color::White);
maze.setCurrentCellColor(sf::Color::Red);
maze.setNotVisitedCellColor(grey);
maze.setVisitedCellColor(start,end);
maze.createMaze("First Maze",1,25);
maze.saveImage();
return 0;
}
</code></pre>
<p>The <code>saveImage()</code> saves the image of the maze and it takes around 30 seconds for this (I know this is a huge bottle neck, but for now I am gonna stick to it).</p>
<p>The main logic takes around 56 seconds to create the entire mathematical model of the maze. This is where I want to improve, if possible.</p>
<p>Instead of using a 2d array for the grid I am using 1D array to store all of the data and to store the state of walls and whether the cell is visited or not i use bit masking and single bit byte date type.</p>
<p>Any suggestions for improvement?</p>
<p>I am going to try and separate the mathematical generation and the graphics. I hope that is going to be the solution will update.</p>
<p>I tried it and just implemented a clean DFS algorithm without any graphics and used the same array size. This takes long too, so my guess is that the bottleneck is caused by bit masking / bit toggling etc.</p>
<p>Just in case anyone stumbles here in the future, my second edit is kind of wrong because bit fields do not make the program slow.</p>
<p>edit : I optimized it even more by eliminating the for loop during animation and only changing the affected cell.</p>
<p>This code is the same as posted the first time, i have not shared any of the edits</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T08:53:34.900",
"Id": "487826",
"Score": "0",
"body": "@G.Sliepen here you go : https://github.com/irrevocablesake/maze"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T09:24:50.913",
"Id": "487828",
"Score": "0",
"body": "@G.Sliepen here ya go"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T20:14:56.617",
"Id": "487869",
"Score": "0",
"body": "Please don't edit your code after receiving answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T02:02:39.750",
"Id": "487886",
"Score": "0",
"body": "@Mast oh no, don't worry, i never edited the code it's just that after posting the code here i was trying different things and the edits were one of the first"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T20:34:23.683",
"Id": "488270",
"Score": "0",
"body": "I have used: [Prim's algorithm](https://en.wikipedia.org/wiki/Prim%27s_algorithm) before. It is practically instantaneous. https://github.com/Loki-Astari/Valkyrie/blob/master/src/Maze/MazeDetail.cpp See: `MazeGenerator::operator()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T02:49:48.173",
"Id": "488297",
"Score": "0",
"body": "@MartinYork omg you programmed a neural net to solve it, that's cool!!\n\nBtw i feel like dfs iterative backtracker is a bit slow for bigger mazes and also memory intensive, what do you think? and i actually made the code a lot faster the same code took around 0.6 seconds for producing a 4.5k maze from start to image saving"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:33:47.783",
"Id": "488332",
"Score": "0",
"body": "@theirrevocableSake To be honest I do not know much about Maze generation. I did a search and found Prim's algorithm and simply implemented from the Wikipedia description. The NN was fun. It took about 3 hours of train (using natural selection) the net to get it working. But once trained it could solve mazes very quickly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-10T16:35:18.680",
"Id": "488333",
"Score": "0",
"body": "A time of 0.6 seconds to generate a large maze sounds like a perfectly good result. Good job."
}
] |
[
{
"body": "<p>Below is a non-comprehensive review of your code.</p>\n<h1>Choosing a maze generation algorithm</h1>\n<p>There are many algorithms for generating mazes, each with their own pros and cons. If you really need to create huge mazes as fast as possible, your backtracking algorithm might not be the best. However, each algorithm typically has its own bias for generating particular mazes, so you can't just swap it out for a random other algorithm and expect the same results. Have a look at this website for an extensive list of maze generation algorithms:</p>\n<p><a href=\"http://www.astrolog.org/labyrnth/algrithm.htm\" rel=\"nofollow noreferrer\">http://www.astrolog.org/labyrnth/algrithm.htm</a></p>\n<p>That said, the backtracking algorithm is certainly not the worst, and generates pleasing looking mazes without obvious biases.</p>\n<h1>Separate maze creation from maze rendering</h1>\n<p>The function <code>Maze::createMaze()</code> not only creates a maze, it also renders an animation of how it creates the maze. The code is intertwined, which makes it hard to read. I suggest you restructure it so you have <code>class Maze</code> responsible only for generating the maze itself, and create a function that can render the current state of a <code>Maze</code>. Then, find some way so you can animate what is going on. This could be done in two ways:</p>\n<ol>\n<li>Add a <code>step()</code> function to <code>Maze</code> that performs one step of the algorithm. Have it return a <code>bool</code> indicating whether the maze is still unfinished. Then, you can basically write:\n<pre><code>while (maze.step()) {\n render(maze);\n window.display();\n // handle window events here\n}\n</code></pre>\n</li>\n<li>Give a callback function to <code>maze()</code> which it can call in its maze generation algorithm after each step. Use <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a> to store a reference to the callback function. The callback function should then look like:\n<pre><code>void render_cb(const Maze &maze) {\n // render maze\n // update window\n // handle events\n}\n</code></pre>\n</li>\n</ol>\n<p>The first solution is the cleanest in my opinion, but the drawback is that you need to have something like a <code>step()</code> function. In this case it is fine though, since you are not using recursive function calls to generate the maze, and you keep the state of the algorithm in <code>btx</code> and <code>bty</code>.</p>\n<h1>Store x and y coordinates in a single <code>std::stack</code></h1>\n<p>You have two <code>std::stack</code> variables, one for the x and one for the y coordinates. However, you always push and pop simultaneously. Each operation on a stack requires some bookkeeping, including possibly memory allocations. So, a simple optimization is to combine the x and y coordinates into a <code>struct Position</code>, and have one <code>std::stack<Position> bt</code>.</p>\n<h1>Optimize <code>Cell</code> state</h1>\n<p>First, I would make it so that the state of each cell at the start of the algorithm has all zero-bits. This saves some time initializing the maze, since after <code>maze.resize()</code>, the contents will be all zeroes already. This means you have to turn on a top/bottom/left/right bit to indicate it is not a wall, or perhaps you can think of a one meaning a passage instead of a wall. Second, consider that you always turned on the <code>visitedMask</code> bit whenever you removed one of the other bits. Now that the meaning of the other bits is flipped, you always set <code>visitedMask</code> if you also set another bit. This means that whenever one of the passage bits is set, you have necessarily also visited this cell. And that means you no longer need to store <code>visitedMask</code> at all, it can be derived from the other bits. In fact:</p>\n<pre><code>int visited = checkBit(maze[...], visitedMask);\nif (!visited)\n{\n ...\n}\n</code></pre>\n<p>Can now be replaced by:</p>\n<pre><code>if (maze[...])\n{\n ...\n}\n</code></pre>\n<p>This is slightly more efficient than checking for a particular bit, and it's also less typing. The only issue is the first cell of the maze. I would make it so the top or right is always set at the start, to indicate the direction of the entrance to the maze.</p>\n<h1>Checking for the walls</h1>\n<p>The code to deal with walls is written in a very confusing way. <code>invalidNeighbour()</code> takes parameters <code>x</code> and <code>y</code>, which sounds like x and y coordinates, but they are actually array indices of the neighbour and the current position. Furthermore, it returns <code>0</code> (<code>false</code>) if the position of the neighbour is invalid, and <code>1</code> (<code>true</code>) if it is valid, the opposite of that the name suggests. Last but not least, it is terribly inefficient to first convert <code>x</code> and <code>y</code> coordinates to array indices just to check if you are at a wall, when you can easily see that from the coordinates themselves. So, I would get rid of <code>invalidNeighbour()</code> entirely, and in <code>checkNeighbour()</code> write:</p>\n<pre><code>void Maze::checkNeighbours(int x,int y)\n{\n ...\n if (x >= 0) // we are not at the top\n {\n if (!maze[cols * (x - 1) + y])\n {\n direction...\n }\n }\n ...\n</code></pre>\n<h1>Avoid unnecessary memory allocations</h1>\n<p>A <code>std::vector</code> allocates memory from the heap. In <code>checkNeighbours()</code>, you only need to track of four bits: which of the four directions have not been visited yet. A <code>std::vector</code> is overkill and will do expensive memory allocations. What you can do instead is just have a fixed-size array, and a counter:</p>\n<pre><code>char direction[4];\nsize_t count = 0;\n...\nif (...)\n{\n direction[count++] = 't';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T14:40:01.127",
"Id": "487851",
"Score": "0",
"body": "WHAT!!!!, thanks for the extensive reply, i appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T14:32:29.790",
"Id": "248961",
"ParentId": "248949",
"Score": "3"
}
},
{
"body": "<p>The <code>checkBit</code> function is very verbose. It can be much shorter and maybe even faster without losing clarity:</p>\n<pre><code> bool checkBit(unsigned char cell, unsigned char mask) {\n return cell & mask;\n }\n</code></pre>\n<p>In general you use <code>int</code> for boolean values but there is a new <code>bool</code> type in C++ now that I would recommend.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T20:57:01.500",
"Id": "487871",
"Score": "1",
"body": "`bool` was introduced in the previous millenium, it's not exactly new anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T20:59:47.210",
"Id": "487872",
"Score": "0",
"body": "But this likely means even more that it should be used were relevant."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T20:12:05.340",
"Id": "248969",
"ParentId": "248949",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T04:47:59.543",
"Id": "248949",
"Score": "5",
"Tags": [
"c++",
"sfml"
],
"Title": "Maze Generator using C++ and SFML"
}
|
248949
|
<p>I'm trying to solve <a href="https://www.hackerrank.com/challenges/filter-elements/problem" rel="nofollow noreferrer">this problem on HackerRank</a>, which basically requires the solution to read an input like this (comments are mine)</p>
<pre class="lang-none prettyprint-override"><code>3 # the number of cases, each of which consists of a pair of lines below
9 2 # case 1, the two numbers are N and K
4 5 2 5 4 3 1 3 4 # case 1, the N numbers; filter out those that occur less than K times
9 4 # case 2
4 5 2 5 4 3 1 3 4 # case 2
10 2 # case 3
5 4 3 2 1 1 2 3 4 5 # case 3
</code></pre>
<p>and the desired output is</p>
<pre class="lang-none prettyprint-override"><code>4 5 3
-1
5 4 3 2 1
</code></pre>
<p>where the second line signifies that there's no number in case 2 which occurs 4 times or more, first and third lines list those elemnts of cases 1 and 3 which all occur the prescribed number of times or more (in this case the threshold is 2 for both case 1 and case 2).</p>
<p>I came up with an algorithmically correct solution, but apparently it has poor performance, as it fails for timeout on <a href="https://hr-testcases-us-east-1.s3.amazonaws.com/2509/input04.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1599333689&Signature=eCWU%2B9EbnHuAjUOujBuSxKqipug%3D&response-content-type=text%2Fplain" rel="nofollow noreferrer">this input</a> (<a href="https://hr-testcases-us-east-1.s3.amazonaws.com/2509/output04.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1599333876&Signature=7umJdsH0BR3egosMBWSXyZztTw8%3D&response-content-type=text%2Fplain" rel="nofollow noreferrer">expected output</a>)</p>
<pre class="lang-hs prettyprint-override"><code>import Control.Monad (liftM2)
import Data.List (sort,groupBy)
import Data.List (foldl')
main :: IO()
main = do
nCasesStr <- getLine
let nCase = read nCasesStr :: Int
sequence_ $ replicate nCase $ do
firstLine <- getLine
secondLine <- getLine
let [_,k] = asInts $ firstLine
let list = asInts $ secondLine -- LINE A
let outList = processList k list
if null outList
then putStr $ show (-1)
else mapM_ (putStr . (++" ") . show) outList -- LINE B
putStrLn ""
where
asInt :: String -> Int
asInt s = read s :: Int
asInts :: String -> [Int]
asInts = map asInt . words
processList :: Int -> [Int] -> [Int]
processList k = map fst . filter ((>= k) . snd) . foldl' step []
where
step acc@((n,c):ac) val
| n == val = (n,c + 1):ac
| otherwise = (n,c):step ac val
step _ val = [(val,1)]
</code></pre>
<p>I'm especially worried about the lines marked as <code>-- LINE A</code> ad <code>-- LINE B</code>: they both traverse the full long input and output lines respectively; then the <code>processList</code> function traverses the input too. Traversing the input only once while spitting out output, however, would not change the BigO complexity, but just reduce it by a factor of 3, am I right?</p>
<p>As regards the <code>processList</code> function, I'm quite happy I had the idea of using a fold (the three of them don't seem to have a consistent difference in performances, as regards the bulk test cases), but maybe I've chosen the wrong <code>step</code>ping function?</p>
<p>Or maybe folding is not the right tool in this case?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T18:28:49.167",
"Id": "487865",
"Score": "0",
"body": "I have moved this question of mine from StackOverflow to here. Someone had left this comment: _Counting happens in O(n), and this per elements, so it makes it an O(n^2) algorithm. You might want to use a Map, and thus first calculate the number of occurences per element._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T07:07:48.693",
"Id": "487992",
"Score": "0",
"body": "Algorithmic complexity is important to think about, in particular in a competitive programming context (which HackerRank is) :)"
}
] |
[
{
"body": "<p>It seems that the suggestion I got in the comment is enough to pass the HR test:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.Maybe (fromJust)\nimport Data.List (foldl', nub)\nimport qualified Data.Map as M\n\nmain :: IO()\nmain = do\n nCasesStr <- getLine\n let nCase = read nCasesStr :: Int\n sequence_ $ replicate nCase $ do\n k <- (str2int. last . words) <$> getLine\n list <- map str2int . words <$> getLine\n let outList = processList k list\n if null outList\n then putStr $ show (-1)\n else mapM_ (putStr . (++" ") . show) outList\n putStrLn ""\n where\n str2int = read :: String -> Int\n\nprocessList :: Int -> [Int] -> [Int]\nprocessList k = nub . (filter <$> (flip (\\x -> (k <=) . fromJust . M.lookup x . list2map)) <*> id)\n where\n list2map = foldl' step M.empty\n step map num = M.insertWith (+) num 1 map\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T21:38:40.000",
"Id": "248972",
"ParentId": "248967",
"Score": "1"
}
},
{
"body": "<p>Looks like you already solved it, so good job! :)</p>\n<p>I took the liberty to solve the challenge too, so I'll post my code below. I tried to make the code a bit more "functional", or less imperative, if you will: there is less logic in IO. It's also slightly shorter than yours, though that's not really a goal. I also used a number of techniques and library functions that you could have used, but didn't; using them all is not necessarily what you want, but I wanted to showcase them nevertheless.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>{-# LANGUAGE LambdaCase #-}\nimport Control.Monad\nimport Data.List\nimport qualified Data.Map.Strict as Map\n\nmain :: IO ()\nmain = do\n let readInts = map read . words <$> getLine\n [numCases] <- readInts\n cases <- sequence $ replicate numCases\n (processCase <$> fmap (!!1) readInts\n <*> readInts)\n forM_ cases $ \\case [] -> putStrLn "-1"\n l -> putStrLn (intercalate " " (map show l))\n where\n processCase :: Int -> [Int] -> [Int]\n processCase k l =\n let groups = [head g | g <- group (sort l), length g >= k]\n order = foldr (uncurry (Map.insertWith const))\n mempty (zip l [0::Int ..])\n in sortOn (order Map.!) groups\n</code></pre>\n<p>In my subjective opinion, this is somewhat "cleaner", whatever that may mean. But make your own judgement, and most important is that you solved it. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T07:36:06.160",
"Id": "249023",
"ParentId": "248967",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249023",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T18:25:50.927",
"Id": "248967",
"Score": "2",
"Tags": [
"programming-challenge",
"haskell",
"functional-programming"
],
"Title": "HackerRank - Filter huge list for elements that occur more than a given number of times"
}
|
248967
|
<p>In Shopify a product can belong to a collection.</p>
<p>I have written a method which accepts an organisation. It would then get a list of collections that this organisation has from Shopify. Finally, it has to loop through each collection to get the products that belong to this collection.</p>
<p>I don't want to overload Shopify server by sending too many requests, so I have added 75 ms wait between each request. But since this method is <code>async</code>, I am not quite sure if the responses are handled correctly? Do I need any sort of mutext or locking mechanism to ensure each response is being handled correctly?</p>
<pre><code>public async Task<List<ShopifyCollection>> GetShopifyCollections(Organisation organisation)
{
int waitInMilliSeconds = 50;
var shopifyCollections = new List<ShopifyCollection>();
var customCollections = await GetAllCustomCollections(organisation);
foreach (var cc in customCollections)
{
shopifyCollections.AddCollection(cc.Id, cc.Title);
}
foreach (var curCollection in shopifyCollections)
{
var products = await GetCollectionProducts(organisation, curCollection.CollectionId);
curCollection.ProductIds = products.Where(p => p.Id != null && p.Id > 0).Select(p => p.Id.Value).ToList();
await Task.Delay(waitInMilliSeconds); // <-- do not overload Shopify
}
return shopifyCollections;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T01:27:50.910",
"Id": "487885",
"Score": "2",
"body": "In async code you should use Task.Delay https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.delay?view=netcore-3.1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T03:56:47.953",
"Id": "487890",
"Score": "0",
"body": "@CharlesNRice: thanks for your comment, I have modified my code to use `Task.Delay` instead of `Thread.Sleep`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T20:58:27.327",
"Id": "487972",
"Score": "1",
"body": "_Do I need any sort of mutext or locking mechanism...?_ No. _I am not quite sure if the responses are handled correctly_ Why do you think that the responses aren't correctly handled? As for me, this method looks fine now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T03:11:47.020",
"Id": "487982",
"Score": "0",
"body": "@aepot: thanks for your response, I have never used `Delay` in an `async` method and just wanted to double check if this is correct."
}
] |
[
{
"body": "<p>Create throttling for API calls is just one aspect of making your API integration resilient. There are many other types of failures to handle. Instead of weaving the error handling into your code, you should consider using something like Polly <a href=\"https://github.com/App-vNext/Polly\" rel=\"nofollow noreferrer\">https://github.com/App-vNext/Polly</a></p>\n<p>There a more details on it here <a href=\"http://www.thepollyproject.org/2018/03/06/policy-recommendations-for-azure-cognitive-services/\" rel=\"nofollow noreferrer\">http://www.thepollyproject.org/2018/03/06/policy-recommendations-for-azure-cognitive-services/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T09:42:49.470",
"Id": "249025",
"ParentId": "248976",
"Score": "4"
}
},
{
"body": "<blockquote>\n<p>But since this method is async, I am not quite sure if the responses are handled correctly?</p>\n</blockquote>\n<p>Your observation on asyncs not inherently waiting is correct, <strong>but</strong> you've glossed over the <code>await</code> which enforces the waiting logic.</p>\n<p>Were you to have written this code:</p>\n<pre><code>Task.Delay(waitInMilliSeconds);\n</code></pre>\n<p>The could would indeed not wait. The task would be returned immediately, and your code here would continue immediately.</p>\n<p>But that all changes when you use <code>await</code>:</p>\n<pre><code>await Task.Delay(waitInMilliSeconds);\n</code></pre>\n<p>Now, the task will be returned immediately, the <code>await</code> will block your current code until the task is completed, and your code here would continue after the <code>await</code> has stopped blocking it.</p>\n<p>Note that during the wait, control is released outside of your code, so it is possible that <em>other</em> parts of your application keep working in the meantime if they are not themselves awaiting the completion of another task.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T11:26:11.870",
"Id": "488006",
"Score": "0",
"body": "Great explanation, thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T19:03:25.913",
"Id": "488266",
"Score": "0",
"body": "_will block your current code until_ = will schedule the continuation of the code after. Actually it doesn't block anything. Technically it leaves (ends) the method and returns to execution after awaiting is done. Sorry, I cringe when someone locks or blocks something in async code. )"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T10:11:08.110",
"Id": "249027",
"ParentId": "248976",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249025",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T00:40:07.810",
"Id": "248976",
"Score": "2",
"Tags": [
"c#",
"api",
"asynchronous"
],
"Title": "Adding some wait time between API requests to avoid overloading the server"
}
|
248976
|
<p>I would like to find the best way to access function variables that are being used as parameters in other functions in another module. The <code>parsefile.js</code> is a Node.js script that is exported as package module and two functions. <code>getfirst</code> and <code>getsecond</code> need to access the variables that are passed from index.js like <code>'a', 'b'</code> from <code>parsefile('a', 'b', 'c')</code>. Other than using <code>global</code>, do we have another way to do it?</p>
<pre><code>// index.js from some application
const parsefile = require('./parsefile')
parsefile('a', 'b', 'c')
//parsefile.js exports about package module
function getfirst() {
if (global.f && global.s) {
return `i have totally 2 arguments: ${global.f}///${global.s}`
}
return `first arguments is ${global.f}`
}
function getsecond() {
return `second arguments is ${global.s}`
}
module.exports = (...args) => {
global.f = args[0];
global.s = args[1];
Promise.all([getfirst(), getsecond()]).then(([first, second]) => {
console.log(`return from getfirst: ${first}`);
console.log(`return from getsecond: ${second}`);
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T14:36:27.513",
"Id": "487947",
"Score": "0",
"body": "Why is this tagged with TypeScript?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T14:42:15.793",
"Id": "487949",
"Score": "0",
"body": "Additionally, is this code your own? Or is this just an example? We only review code that is actually intended to be used, not dummy code written for expressing an idea. Finally, I suggest you read up variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T15:52:37.437",
"Id": "487954",
"Score": "0",
"body": "Yes it's my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T12:32:35.997",
"Id": "492755",
"Score": "0",
"body": "On a broad level, what does the code achieve? How are the functions returned by parsefile used in the end?"
}
] |
[
{
"body": "<p>Since <code>getfirst()</code> and <code>getsecond()</code> are called only within <code>parsefile.js</code>, you can just define an object inside this file (something like this <code>const local = {}</code> at the top of your file) and use it instead of <code>global</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-12T07:33:22.200",
"Id": "249259",
"ParentId": "248977",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T01:38:43.917",
"Id": "248977",
"Score": "4",
"Tags": [
"javascript",
"node.js"
],
"Title": "function access variable in module.exports file in nodeJs"
}
|
248977
|
<p><a href="https://github.com/BingXiong1995/react-flv-player/blob/master/lib/wrapper/ReactFlvPlayer.js" rel="nofollow noreferrer">https://github.com/BingXiong1995/react-flv-player/blob/master/lib/wrapper/ReactFlvPlayer.js</a></p>
<pre><code>import React, { Component } from 'react';
import flvjs from './flv.min';
import PropTypes from 'prop-types';
class ReactFlvPlayer extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
this.flvPlayerRef = element => {
this.flvPlayerRef = element;
};
}
componentDidMount() {
const {type , url, isLive, enableStashBuffer, stashInitialSize, hasAudio, hasVideo, handleError, enableWarning, enableError} = this.props;
// 组件挂载后,拿到Ref进行操作
if (flvjs.isSupported()) {
const flvPlayer = flvjs.createPlayer({
type,
isLive,
url,
hasAudio,
hasVideo
},{
enableStashBuffer,
stashInitialSize
});
flvjs.LoggingControl.enableError = false;
flvjs.LoggingControl.enableWarn = enableWarning;
flvPlayer.attachMediaElement(this.myRef.current); // 将这个DOM付给第三方库
flvPlayer.load();
flvPlayer.play();
flvPlayer.on('error', (err)=>{
// console.log(err);
handleError(err);
});
}
}
render() {
const { height, width, isMuted,showControls } = this.props;
return (
<div>
<video
controls={showControls}
muted={{isMuted}}
ref={this.myRef}
style={{height, width}}
/>
</div>
);
}
}
ReactFlvPlayer.propTypes = {
type: PropTypes.string,
url: PropTypes.string.isRequired,
isLive: PropTypes.bool,
showControls: PropTypes.bool,
hasAudio: PropTypes.bool,
hasVideo: PropTypes.bool,
enableStashBuffer: PropTypes.bool,
stashInitialSize: PropTypes.number,
height: PropTypes.string,
width: PropTypes.string,
isMuted: PropTypes.bool,
enableWarning: PropTypes.bool,
enableError: PropTypes.bool,
handleError: PropTypes.func
};
ReactFlvPlayer.defaultProps = {
type: 'flv',
isLive: true,
hasAudio: true,
hasVideo: true,
showControls: true,
enableStashBuffer: true,
stashInitialSize: 128,
height: '100%',
width: '100%',
isMuted: false,
handleError: (err)=>{console.log(err)},
enableWarning: false,
enableError: false
};
export default ReactFlvPlayer;
</code></pre>
<p>Wrote some wrapper a long time ago. I am wondering if I could have done it in a better way. What are some of the improvements I could make or issues with the code. Thanks.</p>
|
[] |
[
{
"body": "<p><strong>flvPlayerRef?</strong></p>\n<p>In the constructor, you have</p>\n<pre><code>this.myRef = React.createRef();\nthis.flvPlayerRef = element => {\n this.flvPlayerRef = element;\n};\n</code></pre>\n<p>This is pretty confusing. The property is either a function or an element, depending on whether it was called as a function before, and either way, it's not a ref, so it's also misnamed. It also isn't used anywhere else in the code, and consumers of the instance <em>already</em> can get a reference to the <code><video></code> element through the <code>myRef</code> property.</p>\n<p>I'd remove <code>flvPlayerRef</code> completely, and also rename the less-than-informative <code>myRef</code> property name to <code>videoRef</code> or to <code>flvPlayerRef</code>.</p>\n<p>At that point, you can make things concise by using class fields instead of a constructor:</p>\n<pre><code>class ReactFlvPlayer extends Component {\n videoRef = React.createRef();\n\n componentDidMount() {\n // ...\n</code></pre>\n<p>You can also consider using a functional component instead of a class-based component, as React tentatively recommends for new code - but that's not required.</p>\n<p><strong>Destructured props</strong></p>\n<p>This line is hard to read:</p>\n<pre><code>const {type , url, isLive, enableStashBuffer, stashInitialSize, hasAudio, hasVideo, handleError, enableWarning, enableError} = this.props;\n</code></pre>\n<p>When there are more than 2 or 3 properties to be destructured, I'd recommend putting each on a separate line</p>\n<pre><code>const {\n type,\n url,\n isLive,\n // ...\n} = this.props;\n</code></pre>\n<p>But, in this case, a significant fraction of the properties are used <em>only</em> to be passed into <code>flvjs.createPlayer</code> later. Consider using rest syntax to collect those options into a single object, without having to specify each one individually:</p>\n<pre><code>const {\n enableStashBuffer,\n stashInitialSize,\n handleError,\n enableWarning,\n enableError,\n ...createPlayerOptions\n} = this.props;\n</code></pre>\n<p>The <code>enableError</code> variable is not used. If that's deliberate, best to not extract it from the props in the first place. Or maybe you meant to assign it to <code>LoggingControl</code>? Change</p>\n<pre><code>flvjs.LoggingControl.enableError = false;\n</code></pre>\n<p>to</p>\n<pre><code>flvjs.LoggingControl.enableError = enableError;\n</code></pre>\n<p><strong>Nicer indentation</strong> Rather than creating another indentation block after checking if flvjs is supported, you can consider returning early if it's <em>not</em> supported:</p>\n<pre><code>componentDidMount() {\n if (!flvjs.isSupported()) {\n return;\n }\n const {\n enableStashBuffer,\n stashInitialSize,\n handleError,\n enableWarning,\n enableError,\n ...createPlayerOptions\n } = this.props;\n\n const flvPlayer = flvjs.createPlayer(\n createPlayerOptions,\n {\n enableStashBuffer,\n stashInitialSize\n }\n );\n // etc\n</code></pre>\n<p>Returning early is pretty nice, especially with more complex logic which would otherwise require multiple levels of indentation, which can get pretty hard to read.</p>\n<p><strong>Spacing</strong> There are a few places where I'd expect to see a space but don't see any given the code style in the rest of the script, or where I see spaces where there probably shouldn't be any, like <code>const {type , url,</code>, <code>},{</code>, <code>(err)=>{</code>, <code>const { height, width,</code> (do you want leading/trailing space when destructuring and with objects, or no?).</p>\n<p>Whatever you want your code style to be, it would be good to be consistent - consider using <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">ESLint</a> to keep your style consistent, to fix things automatically, and warn you of potential bugs before they turn into runtime errors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T05:42:20.403",
"Id": "248984",
"ParentId": "248979",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248984",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T03:35:37.607",
"Id": "248979",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "React wrapper for existing library"
}
|
248979
|
<p>The problem is to design an structure which generates "uniformly" the next one in an initially zero matrix. Taking an arbitrary index <code>i</code> in the range [0,m-1] for any <code>j</code> where <code>a[i,j] == 0</code>.</p>
<p>It is, for example:</p>
<p><span class="math-container">\begin{gather}
\begin{bmatrix}
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 0 & 1\\
0 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix}\\
\to\begin{bmatrix}
1 & 0 & 1\\
1 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 0 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 0\\
0 & 0 & 0\\
0 & 0 & 0\\
\end{bmatrix}\\
\to\begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 0\\
0 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 0\\
1 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 1\\
1 & 1 & 0\\
0 & 0 & 0\\
\end{bmatrix} \to \cdots \to \begin{bmatrix}
1 & 1 & 1\\
1 & 1 & 1\\
1 & 1 & 1\\
1 & 1 & 1\\
\end{bmatrix}
\end{gather}</span></p>
<p><strong>Where is the utility?</strong> This algorithm can be used for procedural generation in any tile game. Now, I'm not a game programmer but I found really annoying the tile generation of Audiosurf 2 so, I want to perhaps provide a better solution.</p>
<p>(Note that the ones can be replaced by a number located by its input order.)</p>
<p>(I know the implications of the player when he doesn't "tap" some tile but there are other alternatives.)</p>
<p>My solution is:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import numpy.random as rd
class RandomMatrixGenerator():
def __init__(self, m: int, n: int):
self.m = m
self.n = n
self.matrix = np.zeros(shape=(m,n), dtype='int8')
self.ones = np.ones(shape=(m,n), dtype='int8')
def __put_next(self):
j: int = rd.randint(0, self.n, dtype='int8')
if self.ones[:,j].all() == self.matrix[:,j].all():
self.__put_next()
for i in range(self.m):
if self.matrix[i, j] == 0:
self.matrix[i, j] = 1
return
def put_next(self):
if self.ones.all() == self.matrix.all():
return
self.__put_next()
# Mini test
gen = RandomMatrixGenerator(4, 5)
for i in range(4 * 5):
gen.put_next()
if gen.matrix.all() == gen.ones.all():
print(i + 1)
</code></pre>
<p>I'm learning Python for a class and I want to know if there is a way to optimize this code or reduce syntax, I greatly appreciate it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T00:25:09.583",
"Id": "489410",
"Score": "0",
"body": "The generation is done previous the exposure of the map, else I think it would be very time consuming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T11:49:47.197",
"Id": "489438",
"Score": "0",
"body": "Your example looks like a very special case, the ones don't appear randomly anywhere in the matrix, but only from the top downwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T14:31:59.023",
"Id": "489454",
"Score": "0",
"body": "As I said, in example, it was to show how the first rows would get filled first (probably)\nalso, the intention is to get the first rows filled first."
}
] |
[
{
"body": "<p>You don't need to create a second <code>m x n</code> matrix to track where you've set. Since you're only interested in the index of the last one placed in each column you can use an one dimensional <code>n</code>-length array to track the row of the last one added and then use that directly when indexing the matrix.</p>\n<p>Similarly, it also lets you randomly choose columns that still have space to add ones directly (that is, the nber of ones added is less than the length of the column) using <code>np.less</code>, <code>np.where</code>, and <code>np.random.choice</code> instead of picking a column, checking if it contains all ones, and resampling if it does. That's almost always a bad approach, especially when you start to have more columns full than not. If there are 5 full columns and 1 non-full one you have to keep sampling until you randomly select the one non-full column with only 1/6th odds which is going to be slow.</p>\n<p>Combining all that you can write everything you need in about 8 lines with a 6-7x speed up</p>\n<pre><code>def matrix_generator(m, n): \n matrix = np.zeros((m,n), dtype="int")\n ones = np.zeros(n, dtype="int")\n\n while np.any(np.less(ones, m)):\n i = np.random.choice(np.where(np.less(ones, m))[0])\n\n matrix[ones[i],i] = 1\n ones[i] += 1\n\n yield matrix\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T04:56:57.287",
"Id": "249604",
"ParentId": "248980",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249604",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T03:50:58.460",
"Id": "248980",
"Score": "2",
"Tags": [
"python",
"performance",
"random",
"matrix"
],
"Title": "Procedural generation of a general matrix representing a tile map"
}
|
248980
|
<p>So I have a text file filled with old onion links and its incredibly messy:</p>
<pre><code>1 Dark web Link– Deep Web Links – Hidden Wiki http://dwlonion3o3pjqsl.onion/ online
2 Darkode Reborn http://darkodevasbv5yof.onion online
3 Arm’s Factory http://gunsfact2f6oz7cw.onion/ online
4 Dark Web Hackers Zone http://darkzonebry27nxa.onion/ online
5 Raptor (Tor Chat Service) http://raptortiabg7uyez.onion online
</code></pre>
<p>*Each line looks like: <code>(int)\t(name) (url) (status)</code><br />
Since my C code tends to be pretty bad I wanted to improve it. I wrote a simple file parser which attempts to only take into account the url and status and would like to know if there are any ways of optimizing my code/improving the sort function since that's where I feel weakest:</p>
<p><strong>main.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include "sorter.h"
#define onionLinksFile "onionlinks.txt"
#define output "sorted\\output.txt" //folder for output
int main() {
FILE *file = fopen(onionLinksFile, "r");
FILE *nFile = fopen(output, "w+");
char line[256]; //allocate up to 256 chars for each line
if (file == NULL){
printf("> An error occured while attempting to open our file...");
return 1;
}
while (fgets(line, sizeof(line), file)) { //get each newline
fprintf(nFile, sort(line)); //write our sorted data to our text file
//printf(line);
}
fclose(file);
fclose(nFile);
return 0;
}
</code></pre>
<p><strong>sorter.h</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
#define delimter "\t" //our delimters
#define mDelimter "//"
char *sort(char line[256]) {
int objCount = 0;
int mObjCount = 0;
char *token = strtok(line, delimter);
while (token != NULL){ //attempt to split our string by tabs
objCount++;
if (objCount > 1){ //ignore the first number, don't care about that
char *nToken = strtok(token, mDelimter);
while (nToken != NULL){ //split the string again this time take everything past the //
mObjCount++;
if (mObjCount > 1){
return nToken;
}
nToken = strtok(NULL, "");
}
}
token = strtok(NULL, "");
}
}
</code></pre>
<p>And here is how the output looks:</p>
<pre><code>/dwlonion3o3pjqsl.onion/ online
/darkodevasbv5yof.onion online
/gunsfact2f6oz7cw.onion/ online
/darkzonebry27nxa.onion/ online
/raptortiabg7uyez.onion online
/gurochanocizhuhg.onion/ offline
/6a3nny6zpg23dj7g.onion/ offline
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T06:52:19.693",
"Id": "487894",
"Score": "0",
"body": "`fprintf(nFile, sort(line)); ` i call it in the file output"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T07:33:27.670",
"Id": "487896",
"Score": "0",
"body": "Ah, I missed that. Thanks for clearing it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T08:02:43.160",
"Id": "487899",
"Score": "0",
"body": "I don't see `sort()` handling the order of items/tokens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T08:23:31.427",
"Id": "487902",
"Score": "0",
"body": "@greybeard yeah guess sorting wasn't really the right title, I'll remove sort, more meant cleaning up the text."
}
] |
[
{
"body": "<h2>General Observations</h2>\n<p>This program is great if you are the only user, but if it is for use by others here are some suggestions:</p>\n<ol>\n<li>Allow users different ways to supply input and output files, rather than hard coding the name of the input and output files into the code.</li>\n<li>Provide guidance for users if the enter the wrong thing.</li>\n<li>Improve the error handling.</li>\n</ol>\n<p>There are at least 3 ways that input and output can be handled by a program like this if the program is being executed from the command line:</p>\n<ol>\n<li>File redirection</li>\n<li>Command line arguments</li>\n<li>The program prompts the user for the input and output file names.</li>\n</ol>\n<p>It should be noted that one program can use all 3 methods to be the most flexible.</p>\n<p>If the user is using file redirection than the input is coming in on <code>stdin</code> and the output is going out on <code>stdout</code>, errors should go to <code>stderr</code>. In this case the code</p>\n<pre><code> FILE* file = stdin;\n FILE* nFile = stdout;\n</code></pre>\n<p>would be appropriate and the rest of the code would still work as it does now.</p>\n<p>With command line arguments the program would have to use <code>int main(int argc, char **argv)</code> to get the file names.</p>\n<p>While the code is checking that the input file can be opened for input, it is not checking that the output file can be opened for output and that can result in errors.</p>\n<h2>Declare Variables When You Need Them</h2>\n<p>The variable <code>line</code> is defined at the top of <code>main()</code>, it would make the code more understandable and maintainable if <code>line</code> was declared immediately before the <code>while()</code> loop that drives the program. That would also make it easier to see that the <code>while loop</code> itself could be a function.</p>\n<h2>Best Practice with Header Files</h2>\n<p>In C the <code>#include</code> preprocessor directive actually copies the included file into the file with the include directive, to prevent the code in the included file from being included there needs to be some mechanism for preventing the code from being included twice. There are 2 mechanisms for this, using include guards or using <code>#pragma once</code>. I prefer using include guards for 2 reasons, one it is more traditional (I am very old school) and the second is that while <code>#pragma once</code> is widely supported by many compilers it is not currently part of either the C standard or the C++ standard.</p>\n<p>Include guards:</p>\n<pre><code>#ifndef FILE_NAME_H_\n#define FILE_NAME_H_\n\n... code ...\n\n#endif // !FILE_NAME_H_\n</code></pre>\n<p>Header files are generally used to provide the APIs or function prototypes from another C source file, it C it is very rare for a header file to contain executable code, because if the header file is included by multiple source files the functions within it exist in multiple places in the program and the program won't link.</p>\n<h2>Enable All Compiler Warnings</h2>\n<p>When you compile your code use the -wall switch to enable all warnings, the <code>sort()</code> function currently has some logic issues in it that yields the following warning message:<br />\n<code>'sort': not all control paths return a value</code>. This warning message indicates that the function can return without providing a value and can indicate that there are serious problems in the code.</p>\n<h2>Standard Symbolic Constants</h2>\n<p>Since the program includes <code>stdlib.h</code> there are 2 symbolic constants available that would make <code>main()</code> more readable, <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code>. These symbolic constants can be used in place of <code>return 0;</code> and <code>return 1;</code> in <code>main()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T17:52:44.620",
"Id": "487958",
"Score": "1",
"body": "Thank you very much, exact feedback I was looking for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T12:20:57.697",
"Id": "249002",
"ParentId": "248985",
"Score": "5"
}
},
{
"body": "<p>It would be more efficient to tokenise on '//' first, then tokenise the second array element on '\\t'. This would avoid some string copying.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T18:39:59.217",
"Id": "249007",
"ParentId": "248985",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "249002",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T06:12:46.680",
"Id": "248985",
"Score": "4",
"Tags": [
"c",
"file",
"io"
],
"Title": "FileParsing in C"
}
|
248985
|
<p>My chess game is over, everything has been finished, except for some special (like en passant)moves.
The main part of the game is its engine which I have coded using the Minimax algorithm with alpha-beta pruning
currently, It is searching at a depth of 4 moves ahead. this takes less than 4 seconds at most times to search for a move. This is the procedure are which I find a good move</p>
<ul>
<li><p>Initialise two containers <code>std::vector<std::string></code> <code>legal_moves</code> and <code>pseudomoves</code></p>
</li>
<li><p>These two will hold all the possible moves in the current position from either player. The reason there are two containers is that one of them is generated by following all the individual rules for the pieces. For example, a bishop moves diagonally. These are the <strong>pseudomoves</strong>. This is because it does not look into the aspect of <a href="https://en.wikipedia.org/wiki/Check_(chess)" rel="noreferrer">check</a> in chess. That means if your king is under attack, you are ought to get rid of that attack either by blocking it or moving the king. Also in a situation where your king will come under attack <strong>AFTER</strong> you move a piece as it was blocking the attack. This is why I iterate through pseudomoves first.</p>
</li>
<li><p>Iterate through pseudomoves and perform each move in the container. After performing the move, if there is no <a href="https://en.wikipedia.org/wiki/Check_(chess)" rel="noreferrer">check</a>. Then the move is valid. Hence <code>insert(themove,legal_moves.begin())</code>.</p>
</li>
<li><p>After you have a valid set of moves. Start the search depth. Perform each move in the container and give it points based on your evaluation function, then pick the best accordingly. This is the minimax algorithm</p>
</li>
</ul>
<p>Here are the values for each piece on the board, which is represented by an 8x8 integer array.</p>
<ul>
<li>King = 10</li>
<li>Pawn = 1</li>
<li>Bishop = 3</li>
<li>Knight = 2</li>
<li>Queen = 6</li>
<li>Rook = 5</li>
</ul>
<p>negative values of the same represent black pieces. Here is my chess class to that holds everything. My main goal is to <em><strong>speed up the time taken to get the best move</strong></em>.</p>
<h2>chess2.h</h2>
<pre class="lang-cpp prettyprint-override"><code>#ifndef CHESS2_H_INCLUDED
#define CHESS2_H_INCLUDED
#include<vector>
#include<string>
typedef std::vector<std::string> buff;
typedef std::string str;
class Chess2
{
public:
buff pseudomoves;
buff legal_moves;
short int board[8][8] = // This array represents the chess board
{
{-5,0,0,-6,-10,-2,-3,-5},
{-1,-1,-1,0,0,-1,-1,-1},
{0,0,-3,-1,0,0,0,0},
{0,0,0,0,-1,0,0,0},
{0,0,2,0,1,0,-2,0},
{0,0,3,0,0,3,0,0},
{1,1,1,1,0,1,1,1},
{5,3,2,6,10,0,0,5},
};
int perform(str Move);
str push(int row, int col, int desrow, int descol);
buff getallmoves(bool turn);
str computer_move(unsigned short int depth);
bool checkmate(bool turn);
bool check(bool turn);
bool checkmatewhite = false;
bool checkmateblack = false;
private:
void getdiagonalmoves(bool turn, int row, int col);
void getstraigtmoves(bool turn, int row, int col);
void getknightmoves(bool turn, int row, int col);
void getpawnmoves(bool turn, int row, int col);
void getkingmoves(bool turn, int row, int col);
int evaluation();
int miniMax(int depth, bool ismax, int alpha, int beta);
str miniMaxroot(int depth, bool turn);
void undomove(int original, str Move);
};
#endif // CHESS2_H_INCLUDED
</code></pre>
<p>Note that the board is not set to the starting position(for testing purposes)</p>
<h2>chess2.cpp</h2>
<pre class="lang-cpp prettyprint-override"><code>#include "chess2.h"
#include<iostream>
int Chess2::perform(str Move) {
int original;
original = board[Move[2] - 48][Move[3] - 48];
board[Move[2] - 48][Move[3] - 48] = board[Move[0] - 48][Move[1] - 48];
board[Move[0] - 48][Move[1] - 48] = 0;
return original;
}
str Chess2::push(int row, int col, int desrow, int descol) {
using std::to_string;
str mystr = to_string(row) + to_string(col) + to_string(desrow) + to_string(descol);
return mystr;
}
str Chess2::computer_move(unsigned short int depth) {
str bestmove;
bestmove = miniMaxroot(depth, false);
perform(bestmove);
return bestmove;
}
buff Chess2::getallmoves(bool turn) {
int original = 0;
pseudomoves.clear();
legal_moves.clear();
if (turn == true) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (!board[i][j]) continue;
if (board[i][j] == 1) getpawnmoves(true, i, j);
else if (board[i][j] == 2) getdiagonalmoves(true, i, j);
else if (board[i][j] == 3) getknightmoves(true, i, j);
else if (board[i][j] == 5) getstraigtmoves(true, i, j);
else if (board[i][j] == 6) {
getdiagonalmoves(true, i, j);
getstraigtmoves(true, i, j);
}
else if (board[i][j] == 10) getkingmoves(true, i, j);
}
}
for(std::string i:pseudomoves){
original = perform(i);
if (check(true) == false) {
legal_moves.push_back(i);
}
undomove(original, i);
}
}
else if (!turn) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (!board[i][j]) continue;
else if (board[i][j] == -1){
getpawnmoves(false, i, j);
}
else if (board[i][j] == -2) getdiagonalmoves(false, i, j);
else if (board[i][j] == -3) getknightmoves(false, i, j);
else if (board[i][j] == -5) getstraigtmoves(false, i, j);
else if (board[i][j] == -6) {
getdiagonalmoves(false, i, j);
getstraigtmoves(false, i, j);
}
else if (board[i][j] == -10) getkingmoves(false, i, j);
}
}
for(std::string i:pseudomoves){
original = perform(i);
if (check(false) == false) {
legal_moves.push_back(i);
}
undomove(original, i);
}
}
return legal_moves;
}
bool Chess2::check(bool turn) {
if (turn == true) {
bool found = false;
int row, col;
//Finding the king on the board
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == 10) {
row = i;
col = j;
found = true;
break;
}
}
}
if (found == false){
return false;
}
//Finding the king on the board
if (row != 0 && col != 0 && board[row - 1][col - 1] == -1) return true;
else if (row != 0 && col != 7 && board[row - 1][col + 1] == -1) return true;
int a, b;
a = row;
b = col;
if (a != 0 && b != 0) {
for (;;) {
a -= 1;
b -= 1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 0 || b == 0) break;
}
}
a = row;
b = col;
if (a != 0 && b != 7) {
for (;;) {
a -= 1;
b += 1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 0 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7 && b != 0) {
for (;;) {
a += 1;
b -= 1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 7 || b == 0) break;
}
}
a = row;
b = col;
if (a != 7 && b != 7) {
for (;;) {
a += 1;
b += 1;
if (board[a][b] == -6 || board[a][b] == -2) return true;
if (board[a][b] != 0 || a == 7 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7) {
for (;;) {
a += 1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || a == 7) break;
}
}
a = row;
b = col;
if (a != 0) {
for (;;) {
a -= 1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || a == 0) break;
}
}
a = row;
b = col;
if (b != 7) {
for (;;) {
b += 1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || b == 7) break;
}
}
a = row;
b = col;
if (b != 0) {
for (;;) {
b -= 1;
if (board[a][b] == -6 || board[a][b] == -5) return true;
if (board[a][b] != 0 || b == 0) break;
}
}
if (row > 0 && col < 6 && board[row - 1][col + 2] == -3)return true;
if (row > 1 && col < 7 && board[row - 2][col + 1] == -3)return true;
if (row < 7 && col < 6 && board[row + 1][col + 2] == -3)return true;
if (row < 6 && col < 7 && board[row + 2][col + 1] == -3)return true;
if (row < 6 && col > 0 && board[row + 2][col - 1] == -3)return true;
if (row < 7 && col > 1 && board[row + 1][col - 2] == -3)return true;
if (row > 1 && col > 0 && board[row - 2][col - 1] == -3)return true;
if (row > 0 && col > 1 && board[row - 1][col - 2] == -3)return true;
if (row != 7 && board[row + 1][col] == -10)return true;
if (row != 0 && board[row - 1][col] == -10)return true;
if (col != 7 && board[row][col + 1] == -10) return true;
if (col != 0 && board[row][col - 1] == -10) return true;
if (row != 7 && col != 7 && board[row + 1][col + 1] == -10)return true;
if (row != 7 && col != 0 && board[row + 1][col - 1] == -10) return true;
if (row != 0 && col != 7 && board[row - 1][col + 1] == -10) return true;
if (row != 0 && col != 0 && board[row - 1][col - 1] == -10) return true;
}
else if (turn == false) {
bool found = false;
int row, col;
//Finding the king on the board
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == -10) {
row = i;
col = j;
found = true;
break;
}
}
}
if (found == false){
return false;
}
//Finding the king on the board
if (row != 7 && col != 0 && board[row + 1][col - 1] == 1) return true;
else if (row != 7 && col != 7 && board[row + 1][col + 1] == 1) return true;
int a, b;
a = row;
b = col;
if (a != 0 && b != 0) {
for (;;) {
a -= 1;
b -= 1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 0 || b == 0) break;
}
}
a = row;
b = col;
if (a != 0 && b != 7) {
for (;;) {
a -= 1;
b += 1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 0 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7 && b != 0) {
for (;;) {
a += 1;
b -= 1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 7 || b == 0) break;
}
}
a = row;
b = col;
if (a != 7 && b != 7) {
for (;;) {
a += 1;
b += 1;
if (board[a][b] == 6 || board[a][b] == 2) return true;
if (board[a][b] != 0 || a == 7 || b == 7) break;
}
}
a = row;
b = col;
if (a != 7) {
for (;;) {
a += 1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || a == 7) break;
}
}
a = row;
b = col;
if (a != 0) {
for (;;) {
a -= 1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || a == 0) break;
}
}
a = row;
b = col;
if (b != 7) {
for (;;) {
b += 1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || b == 7) break;
}
}
a = row;
b = col;
if (b != 0) {
for (;;) {
b -= 1;
if (board[a][b] == 6 || board[a][b] == 5) return true;
if (board[a][b] != 0 || b == 0) break;
}
}
if (row > 0 && col < 6 && board[row - 1][col + 2] == 3)return true;
if (row > 1 && col < 7 && board[row - 2][col + 1] == 3)return true;
if (row < 7 && col < 6 && board[row + 1][col + 2] == 3)return true;
if (row < 6 && col < 7 && board[row + 2][col + 1] == 3)return true;
if (row < 6 && col > 0 && board[row + 2][col - 1] == 3)return true;
if (row < 7 && col > 1 && board[row + 1][col - 2] == 3)return true;
if (row > 1 && col > 0 && board[row - 2][col - 1] == 3)return true;
if (row > 0 && col > 1 && board[row - 1][col - 2] == 3)return true;
if (row != 7 && board[row + 1][col] == 10)return true;
if (row != 0 && board[row - 1][col] == 10)return true;
if (col != 7 && board[row][col + 1] == 10) return true;
if (col != 0 && board[row][col - 1] == 10) return true;
if (row != 7 && col != 7 && board[row + 1][col + 1] == 10)return true;
if (row != 7 && col != 0 && board[row + 1][col - 1] == 10) return true;
if (row != 0 && col != 7 && board[row - 1][col + 1] == 10) return true;
if (row != 0 && col != 0 && board[row - 1][col - 1] == 10) return true;
}
return false;
}
void Chess2::getdiagonalmoves(bool turn, int row, int col) {
int a, b;
if (turn) {
a = row;
b = col;
if (a != 0 && b != 0) {
for (;;) {
a -= 1;
b -= 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 0 || b == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 0 && b != 7) {
for (;;) {
a -= 1;
b += 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 0 || b == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 7 && b != 7) {
for (;;) {
a += 1;
b += 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 7 || b == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 7 && b != 0) {
for (;;) {
a += 1;
b -= 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 7 || b == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
}
else if (!turn) {
a = row;
b = col;
if (a != 0 && b != 0) {
for (;;) {
a -= 1;
b -= 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 0 || b == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 0 && b != 7) {
for (;;) {
a -= 1;
b += 1;
if (board[a][b] < 0)
break;
if (board[a][b] > 0 || a == 0 || b == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (board[a][b] == 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 7 && b != 7) {
for (;;) {
a += 1;
b += 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 7 || b == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 7 && b != 0) {
for (;;) {
a += 1;
b -= 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 7 || b == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b])pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
}
}
void Chess2::getstraigtmoves(bool turn, int row, int col)
{
int a, b;
if (turn) {// white player
a = row;
b = col;
if (a != 0) {
for (;;) {
a -= 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 7) {
for (;;) {
a += 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || a == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (b != 0) {
for (;;) {
b -= 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || b == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (b != 7) {
for (;;) {
b += 1;
if (board[a][b] > 0) break;
if (board[a][b] < 0 || b == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
}
else if (!turn) // black player
{
a = row;
b = col;
if (a != 0) {
for (;;) {
a -= 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (a != 7) {
for (;;) {
a += 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || a == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (b != 0) {
for (;;) {
b -= 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || b == 0) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
a = row;
b = col;
if (b != 7) {
for (;;) {
b += 1;
if (board[a][b] < 0) break;
if (board[a][b] > 0 || b == 7) {
pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
break;
}
if (!board[a][b]) pseudomoves.insert(pseudomoves.begin(),push(row, col, a, b));
}
}
}
//returnpseudomoves;
}
void Chess2::getknightmoves(bool turn, int row, int col) {
if (turn) {
if (row > 0 && col < 6 && board[row - 1][col + 2] <= 0) // one up two right
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col + 2));
if (row > 1 && col < 7 && board[row - 2][col + 1] <= 0) // two up one right
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 2, col + 1));
if (row < 7 && col < 6 && board[row + 1][col + 2] <= 0) // one down two right
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col + 2));
if (row < 6 && col < 7 && board[row + 2][col + 1] <= 0) // two down one right
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 2, col + 1));
if (row < 6 && col > 0 && board[row + 2][col - 1] <= 0) //two down one left
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 2, col - 1));
if (row < 7 && col > 1 && board[row + 1][col - 2] <= 0) // one down two left
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col - 2));
if (row > 1 && col > 0 && board[row - 2][col - 1] <= 0) // two up one left
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 2, col - 1));
if (row > 0 && col > 1 && board[row - 1][col - 2] <= 0) // one up two left
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col - 2));
}
else if (!turn) {
if (row > 0 && col < 6 && board[row - 1][col + 2] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col + 2));
if (row > 1 && col < 7 && board[row - 2][col + 1] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 2, col + 1));
if (row < 7 && col < 6 && board[row + 1][col + 2] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col + 2));
if (row < 6 && col < 7 && board[row + 2][col + 1] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 2, col + 1));
if (row < 6 && col > 0 && board[row + 2][col - 1] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 2, col - 1));
if (row < 7 && col > 1 && board[row + 1][col - 2] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col - 2));
if (row > 1 && col > 0 && board[row - 2][col - 1] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 2, col - 1));
if (row > 0 && col > 1 && board[row - 1][col - 2] >= 0)pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col - 2));
}
//returnpseudomoves;
}
void Chess2::getpawnmoves(bool turn, int row, int col) {
if (turn) {
if (row == 0){
return ;
}
if (row == 6 && board[row - 1][col] == 0 && board[row - 2][col] == 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 2, col));
if (board[row - 1][col] == 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col));
if (col != 0 && board[row - 1][col - 1] < 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col - 1));
if (col != 7 && board[row - 1][col + 1] < 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col + 1));
}
else if (!turn) {
if (row == 7){
return ;
}
if (row == 1 && board[row + 1][col] == 0 && board[row + 2][col] == 0){
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 2, col));
}
if (board[row + 1][col] == 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col));
if (col != 0 && board[row + 1][col - 1] > 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col - 1));
if (col != 7 && board[row + 1][col + 1] > 0)
pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col + 1));
}
//returnpseudomoves;
}
void Chess2::getkingmoves(bool turn, int row, int col) {
if (!turn) {
if (row != 7 && board[row + 1][col] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col));
if (row != 0 && board[row - 1][col] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col));
if (col != 7 && board[row][col + 1] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row, col + 1));
if (col != 0 && board[row][col - 1] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row, col - 1));
if (row != 7 && col != 7 && board[row + 1][col + 1] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col + 1));
if (row != 7 && col != 0 && board[row + 1][col - 1] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col - 1));
if (row != 0 && col != 7 && board[row - 1][col + 1] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col + 1));
if (row != 0 && col != 0 && board[row - 1][col - 1] >= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col - 1));
}
else if (turn) {
if (row != 7 && board[row + 1][col] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col));
if (row != 0 && board[row - 1][col] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col));
if (col != 7 && board[row][col + 1] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row, col + 1));
if (col != 0 && board[row][col - 1] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row, col - 1));
if (row != 7 && col != 7 && board[row + 1][col + 1] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col + 1));
if (row != 7 && col != 0 && board[row + 1][col - 1] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row + 1, col - 1));
if (row != 0 && col != 7 && board[row - 1][col + 1] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col + 1));
if (row != 0 && col != 0 && board[row - 1][col - 1] <= 0) pseudomoves.insert(pseudomoves.begin(),push(row, col, row - 1, col - 1));
}
//returnpseudomoves;
}
int Chess2::evaluation() {
const short int pawn = 95,bishop = 330,knight = 320,rook = 500,queen = 900,king = 2000;
const int pawnt[8][8] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{50, 50, 50, 50, 50, 50, 50, 50},
{10, 10, 20, 30, 30, 20, 10, 10},
{5, 5, 10, 45, 45, 10, 5, 5},
{0, 0, 0, 20, 20, 0, 0, 0},
{5, -5,-10, 0, 0,-10, -5, 5},
{5, 10, 10,-20,-20, 10, 10, 5},
{0, 0, 0, 0, 0, 0, 0, 0}
};
const int bishopt[8][8] = {
{-20,-10,-10,-10,-10,-10,-10,-20},
{-10, 0, 0, 0, 0, 0, 0,-10},
{-10, 0, 5, 10, 10, 5, 0,-10},
{-10, 5, 5, 10, 10, 5, 5,-10},
{-10, 0, 10, 10, 10, 10, 0,-10},
{-10, 10, 10, 10, 10, 10, 10,-10},
{-10, 5, 0, 0, 0, 0, 5,-10},
{-20,-10,-10,-10,-10,-10,-10,-20},
};
const int knightt[8][8] = {
{-50,-40,-30,-30,-30,-30,-40,-50},
{-40,-20, 0, 0, 0, 0,-20,-40},
{-30, 0, 10, 15, 15, 10, 0,-30},
{-30, 5, 15, 20, 20, 15, 5,-30},
{-30, 0, 15, 20, 20, 15, 0,-30},
{-30, 5, 10, 15, 15, 10, 5,-30},
{-40,-20, 0, 5, 5, 0,-20,-40},
{-50,-40,-30,-30,-30,-30,-40,-50},
};
const int queent[8][8] = {
{-20,-10,-10, -5, -5,-10,-10,-20},
{-10, 0, 0, 0, 0, 0, 0,-10},
{-10, 0, 5, 5, 5, 5, 0,-10},
{-5, 0, 5, 5, 5, 5, 0, -5},
{0, 0, 5, 5, 5, 5, 0, -5},
{-10, 5, 5, 5, 5, 5, 0,-10},
{-10, 0, 5, 0, 0, 0, 0,-10},
{-20,-10,-10, -5, -5,-10,-10,-20}
};
const int kingt[8][8] = {
{-30,-40,-40,-50,-50,-40,-40,-30},
{-30,-40,-40,-50,-50,-40,-40,-30},
{-30,-40,-40,-50,-50,-40,-40,-30},
{-30,-40,-40,-50,-50,-40,-40,-30},
{-20,-30,-30,-40,-40,-30,-30,-20},
{-10,-20,-20,-20,-20,-20,-20,-10},
{20, 20, 0, 0, 0, 0, 20, 20},
{20, 30, 10, 0, 0, 10, 30, 20 },
};
const int rookt[8][8] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{5, 10, 10, 10, 10, 10, 10, 5},
{-5, 0, 0, 0, 0, 0, 0, -5},
{-5, 0, 0, 0, 0, 0, 0, -5},
{-5, 0, 0, 0, 0, 0, 0, -5},
{-5, 0, 0, 0, 0, 0, 0, -5},
{-5, 0, 0, 0, 0, 0, 0, -5},
{0, 0, 0, 5, 5, 0, 0, 0}
};
int score = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (!board[i][j]) continue;
if (board[i][j] == 1) {
score-=pawnt[i][j];
score -= pawn;
if (board[i-1][j] == 1) // double stacked pawn
score-=20;
}
else if (board[i][j] == 2){
score-=bishopt[i][j];
score -= bishop;
}
else if (board[i][j] == 3){
score-=knightt[i][i];
score -= knight;
}
else if (board[i][j] == 5){
score-=rookt[i][j];
score -= rook;
}
else if (board[i][j] == 6){
score-=queent[i][j];
score -= queen;
}
else if (board[i][j] == 10){
score-=kingt[i][j];
score -= king;
}
if (board[i][j] == -1) {
score+=pawnt[7-i][7-j];
score+= pawn;
}
else if (board[i][j] == -2){
score+=bishopt[7-i][7-j];
score+= bishop;
}
else if (board[i][j] == -3){
score+=knightt[7-i][7-j];
score+= knight;
}
else if (board[i][j] == -5){
score+=rookt[7-i][7-j];
score+= rook;
}
else if (board[i][j] == -6){
score+=queent[7-i][7-j];
score+= queen;
}
else if (board[i][j] == -10){
score+=kingt[7-i][7-j];
score+= king;
}
}
}
return score;
}
int Chess2::miniMax(int depth, bool ismax, int alpha, int beta) {
if (depth == 0) {
return evaluation();
}
int maxeval = -999999;
int mineval = 999999;
buff possiblemoves;
int original;
int eval;
if (ismax == true) {
possiblemoves = getallmoves(false);
if (possiblemoves.size() == 0 && check(false) == false) {
return 999999;
}
if (possiblemoves.size() == 0 && check(false) == true) {
return -999999;
}
for (std::string i:possiblemoves) {
original = perform(i);
eval = miniMax(depth - 1, false, alpha, beta);
undomove(original, i);
if (eval > maxeval)
maxeval = eval;
if (alpha >= eval)
alpha = eval;
if (beta <= alpha)
break;
}
return maxeval;
}
else {
possiblemoves = getallmoves(true);
if (possiblemoves.size() == 0 && check(true) == false){
return -99999999;
}
if (possiblemoves.size() == 0 && check(true) == true){
return 99999999;
}
else if (possiblemoves.size() == 0 && check(true) == false){
return -99999999;
}
for (std::string i:possiblemoves) {
original = perform(i);
eval = miniMax(depth - 1, true, alpha, beta);
undomove(original, i);
if (eval < mineval)
mineval = eval;
if (beta <= eval)
beta = eval;
if (beta <= alpha)
break;
}
return mineval;
}
return 1;
}
str Chess2::miniMaxroot(int depth, bool turn) {
str bestmove;
int maxeval = -9999999;
buff allmoves = getallmoves(turn);
int original;
int eval;
for (std::string i:allmoves) {
original = perform(i);
eval = miniMax(depth - 1, false, -99999999, 99999999);
std::cout << "Move: " << i << ' ' << "Points: " << eval << '\n';
undomove(original, i);
if (eval > maxeval) {
maxeval = eval;
bestmove = i;
}
}
return bestmove;
}
void Chess2::undomove(int original, str Move) {
board[Move[0] - 48][Move[1] - 48] = board[Move[2] - 48][Move[3] - 48]; // -48 is to convert char to int
board[Move[2] - 48][Move[3] - 48] = original; // -48 to convert char to int
}
</code></pre>
<p>Here is what a move would look like <code>"1030"</code>. the first two characters are the co-ordinates of a piece. The last two characters are the co-ordinates to where that piece should move.</p>
<p>Is this the best container choice for my purpose?
How can I optimize this program? mainly the generator functions and the minimax algorithm</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T07:22:33.367",
"Id": "487895",
"Score": "0",
"body": "linked: [chess](https://codereview.stackexchange.com/questions/248387/chess-game-class)"
}
] |
[
{
"body": "<p>In my opinion, the best way to improve this program is by using <a href=\"https://en.wikipedia.org/wiki/Board_representation_(computer_chess)#Bitboards\" rel=\"noreferrer\">bitboards</a>. Instead of using a table in two dimensions to represent the chess board, you use 12 numbers of 64 bits, each number representing a type of piece and each bit saying whether there's a piece or not on a square. You can then use <a href=\"https://en.wikipedia.org/wiki/Bitwise_operation\" rel=\"noreferrer\">bitwise operators</a> to modify the chessboard.\nThis method is much more complex, but generating legal moves becomes 8'000 times faster (I can say that because I already tried using a 2D table and bitboards in a <a href=\"https://www.academia.edu/42305762/Jouer_aux_%C3%A9checs_avec_un_algorithme_dapprentissage_automatique_S%C3%A9bastien_Delsad\" rel=\"noreferrer\">chess project</a>). With this improvement, you can easily reach a depth of 5 in your minimax.</p>\n<p>If you're looking for something easier that could also have a great impact on the performance of the minimax, use lookup tables. It is a table that knows lots of different board positions that have already been faced by professionals. You can modify your evaluation function to use this table to give more importance to moves made by professionals. To use less memory space, you can hash the chessboards (see <a href=\"https://www.chessprogramming.org/Hash_Table\" rel=\"noreferrer\">hash tables</a>).</p>\n<p>Finally, all the articles I read give <a href=\"https://en.wikipedia.org/wiki/Chess_piece_relative_value\" rel=\"noreferrer\">9 points</a> to the queen instead of 6. You can also set the value of the king to infinite (or a very high value). Apart from that, I advise you to use <a href=\"https://en.wikipedia.org/wiki/OpenMP\" rel=\"noreferrer\">OpenMP library</a> to multi-thread the minimax. This library is very easy to use (one line of code on top of a loop) and works well. Also, be sure to use -O2 or -O3 option if you compile your code with gcc.</p>\n<p>I hope this answers your questions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T09:08:55.433",
"Id": "248990",
"ParentId": "248987",
"Score": "9"
}
},
{
"body": "<h1>About using typedefs</h1>\n<p>First, don't create aliases for standard types. Just write <code>std::string</code> instead of <code>str</code>. For someone reading your code, or perhaps you yourself reading your own code half a year later, whenever one reads <code>str</code> one wonders "is this a <code>std::string</code> or some other kind of string?"</p>\n<p>Furthermore, it is not good practice to introduce very generic names such as <code>buff</code> in the global namespace. Move that <code>typedef</code> into <code>class Chess2</code>. Also consider giving it a name that makes it more clear that it is a type, not a variable, for example use <code>buffer_type</code>.</p>\n<p>Also, when you do declare a <code>typedef</code>, make sure you use it consistently.</p>\n<h1>Use a consistent way to write names</h1>\n<p>I see <code>pseudomoves</code>, <code>legal_moves</code> and <code>miniMax</code>. Be consistent and use one way to write variable and function names that might contain multiple words. I suggest you write function and variable names with all lower case characters, and separate individual words with an underscore. So:</p>\n<ul>\n<li><code>pseudomoves</code> -> <code>pseudo_moves</code></li>\n<li><code>getallmoves()</code> -> <code>get_all_moves()</code></li>\n<li><code>checkmatewhite</code> -> <code>checkmate_white</code></li>\n<li>...and so on.</li>\n</ul>\n<h1>Avoid magic numbers</h1>\n<p>I see lots of code like <code>if (board[i][j] == -6) {...}</code>. What does <code>-6</code> mean? Why is it negative? This makes the code really hard to understand. Of course you need to store the type of chess piece somehow, and a computer likes simple integers best, but in a programming language we can give those integers human readable names. So in C++, the best thing to do is create an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"noreferrer\"><code>enum class</code></a>, like so:</p>\n<pre><code>class Chess2\n{\n enum class Piece: signed char {\n EMPTY = 0,\n BLACK_PAWN = 1,\n BLACK_BISHOP = 2,\n ...\n WHITE_PAWN = -1,\n WHITE_BISHOP = -2,\n ...\n };\n\n Piece board[8][8] = {\n {WHITE_ROOT, EMPTY, EMPTY, ...},\n ...\n };\n};\n</code></pre>\n<p>And in your code you can now write:</p>\n<pre><code>if (board[i][j] == Piece::WHITE_QUEEN) {...}\n</code></pre>\n<p>Note that I made the underlying type a <code>signed char</code>, since it is big enough to handle all possible chess pieces. Also, if the actual value doesn't really matter, you can omit them from the <code>enum</code> declaration. You will need to type a bit more, but in the end your code will be much more legible.</p>\n<p>Similar to pieces, you made <code>turn</code> a boolean. But what does it mean that a <code>turn</code> is <code>true</code>? Again just use an <code>enum class</code> to make it explicit:</p>\n<pre><code>enum class Color {\n WHITE;\n BLACK;\n};\n</code></pre>\n<p>And then use <code>Color turn</code> instead of <code>bool turn</code> everywhere.</p>\n<h1>Don't encode moves as strings</h1>\n<p>Strings are not the best way to store moves. A <code>std::string</code> is a large object and it might perform memory allocations. With the short string optimization technique commonly used in the standard libraries nowadays, you will not have an issue with memory allocations, but a string of only a few characters will still take about 32 bytes on a 64-bit machine. Also, lets look at your code:</p>\n<pre><code>board[Move[2] - 48][Move[3] - 48] = board[Move[0] - 48][Move[1] - 48];\n</code></pre>\n<p>That just looks terrible. Again there is no way to tell what the array indices mean just by looking at this line. And why do you need to subtract 48? Ideally, you want to create a <code>class Position</code> to encode a position on the chess board, and a <code>class Move</code> to encode a move. Both should be declared inside <code>class Chess2</code>. For example:</p>\n<pre><code>class Chess2 {\n class Position {\n unsigned char row;\n unsigned char col;\n };\n\n class Move {\n Position from;\n Position to;\n };\n\n std::vector<Move> pseudo_moves;\n std::vector<Move> legal_moves;\n ...\n};\n</code></pre>\n<p>There are other ways to encode a position, for example you could store it in a single 8-bit integer if you enumerate all the positions from 0 to 63. But now that you have created a class for this, it will be much easier to change. Now you can use it like:</p>\n<pre><code>Piece Chess2::perform(Move move) {\n Piece original = board[move.to.row][move.to.col];\n board[move.to.row][move.to.col] = board[move.from.row][move.from.col];\n board[move.from.row][move.from.col] = Piece::EMPTY;\n return original;\n}\n</code></pre>\n<p>Still very verbose, but at least now I can actually understand much better what is going on. But that brings me to:</p>\n<h1>Create a class to represent a chess board</h1>\n<p>Instead of declaring a two-dimensional array for the board and manipulating it directly, consider creating a <code>class Board</code> that contains helper functions to make manipulating the board easier. For example:</p>\n<pre><code>class Board {\n std::array<std::array<Piece, 8>, 8> squares;\n\npublic:\n Board(const std::array<std::array<Piece, 8>, 8> &initial_state): squares(initial_state) {}\n Piece &operator[](Position pos) {\n return squares[pos.row][pos.col];\n }\n};\n</code></pre>\n<p>With this, you can now access the chess board as an array but using a <code>Position</code> as the array index. And <code>perform()</code> now simplifies to:</p>\n<pre><code>Piece Chess2::perform(Move move) {\n Piece original = board[move.to];\n board[move.to] = board[move.from];\n board[move.from] = Piece::EMPTY;\n return original;\n}\n</code></pre>\n<h1>More code improvements</h1>\n<p>There are many more improvements you could make to make your code more readable. For example, you could create an iterator class for <code>Board</code> so that instead of:</p>\n<pre><code>for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == 1) getpawnmoves(true, i, j)\n ...\n</code></pre>\n<p>You could write:</p>\n<pre><code>for (auto &[piece, pos]: board) {\n if (piece == Piece::BLACK_PAWN) get_pawn_moves(Color::BLACK, pos);\n ...\n</code></pre>\n<p>But this will take a bit of time, especially if you are not used to writing such code. However, while it has an up-front cost, it will pay off in the long run.</p>\n<h1>Avoid inserting at the start of a <code>std::vector</code></h1>\n<p>Inserting something at the start of a <code>std::vector</code> is an expensive operation, since it has to move all elements one place. Either ensure you always <code>push_back()</code> elements, and reverse the order in which you iterator over <code>pseudo_move()</code>, or use a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"noreferrer\"><code>std::deque</code></a> to store pseudo_moves, as it has an efficient <code>push_front()</code> operation.</p>\n<h1>Avoid code duplication</h1>\n<p>There is a lot of repetition in your code. Try to avoid this as much as possible. For example, you duplicate a lot of code for black and white turns. Find some way to generalize away the difference between black and white to avoid <code>if (turn) ... else ...</code> blocks.\nFor example, take <code>getdiagonalmoves()</code>, where the only difference between the black and white turns is whether you write <code>board[a][b] > 0</code> or <code>board[a][b] < 0</code>. Create a function to check if a given piece has a given color:</p>\n<pre><code>bool has_color(Piece piece, Color color) {\n // Make use of the fact that black pieces have a positive enum value\n if (color == COLOR_BLACK)\n return static_cast<unsigned char>(piece) > 0;\n else\n return static_cast<unsigned char>(piece) < 0;\n}\n</code></pre>\n<p>Then in <code>getdiagonalmoves()</code>, you can write:</p>\n<pre><code>void Chess2::get_diagonal_moves(Color turn, Position from) {\n Color opponent = turn == Color::BLACK ? Color::WHITE : Color::BLACK;\n Position to = from;\n\n while (to.row != 0 && to.col != 0) {\n to.row--;\n to.pos--;\n if (has_color(board[to], turn)) break;\n if (has_color(board[to], opponent) || to.row == 0 || to.col == 0) {\n ...\n</code></pre>\n<p>Alternatively, make it even clearer what you are actually trying to check, and create a function to check if a destination square is a valid position for a piece of a given color, so you can write something like:</p>\n<pre><code> if (is_valid_destination(to, turn))\n pseudo_moves.push_front({from, to});\n</code></pre>\n<p>Not only does this remove code duplication, removing <code>if</code>-statements might also remove branches from the code, which reduces the chance of branch mispredictions.</p>\n<p>Another possibility to remove code duplication is to separate the constant part from the variables that do change. For example, in <code>getknightmoves()</code>, separate the 8 possible directions of a knight from the check whether a night can move in a possible direction, like so:</p>\n<pre><code>void Chess2::getknightmoves(Color turn, Position from) {\n static const struct Direction {\n signed char row;\n signed char col;\n } knight_moves[8] = {\n {-1, +2},\n {-2, +1},\n ...\n };\n\n for (auto dir: knight_moves) {\n Position to = {from.col + dir.col, from.row + dir.row};\n if (to.col < 8 && to.row < 8 && is_valid_destination(to, turn))\n pseudo_moves.push_front({from, to});\n }\n}\n</code></pre>\n<p>You can do something similar for <code>getkingmoves()</code>, and even for the four directions of <code>getstraightmoves()</code> and <code>getdiagonalmoves()</code>. Also note that in <code>check()</code> you have very similar code that could also be shortened in the same way.</p>\n<h1>Consider keep track of the positions of the kings</h1>\n<p>You call <code>check()</code> a lot of times, and the first thing it does is to scan all the tiles of a chess board to find the position of a king. Consider storing the positions of the kings in separate variables in <code>class Board</code>. Of course, you now have to be a bit careful about keeping those variables up to date.</p>\n<h1>Optimize storage of state</h1>\n<p>As mentioned in S. Delsad's answer, a better way to store the board might be to use bitboards. This is particularly efficient on today's computers, since 64 squares on a chess board is a perfect fit for the 64-bit registers most processors have.</p>\n<p>Another potential optimization is how to store positions. Instead of a separate row and column, consider storing a single integer, and enumerate the squares going from left to right first and then continue on from top to bottom. This also makes it easier to calculate desination positions. For example, a knight might move 2 squares right and 1 square down, but with the above enumeration, it just means adding 10 to the index (2 for going two squares right, plus 8 to go one row down).</p>\n<p>Lastly, instead of storing the state of all 64 squares of a board, consider storing the position of the 32 chess pieces instead. When checking if a king is checked, you then for example only have to visit all the pieces of the opposite color, and then for example for a bishop, check if they are on the same diagonal (absolute difference in row and column position is identical), and if so you just need to check if there is no piece inbetween. This can potentially speed up this test a lot, especially in the end game when many pieces have already been removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T11:33:58.423",
"Id": "487912",
"Score": "0",
"body": "A lot of things to improve!, I would like to note one thing, the duplication part that you talked about, during the development process I did think about it for a whole day but I couldn't find any way where it would be easy for me to perform the same thing without duplicating to an extent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T17:43:30.530",
"Id": "487957",
"Score": "1",
"body": "Small note: use `using` instead of typedefs if you decide to use typedef anyways. It reads so much better!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T13:29:23.877",
"Id": "488226",
"Score": "0",
"body": "Isn't it just the arcane naming of `turn` that invites use of an `enum`? If it was called `white_to_move` seems like a `bool` would be perfectly fine..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T13:51:12.700",
"Id": "488230",
"Score": "0",
"body": "@Will Yes, ensuring the name of the variable fits a boolean `true`/`false` value would be a solution as well. But maybe even better is `Color player_to_move`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T10:58:27.180",
"Id": "248995",
"ParentId": "248987",
"Score": "28"
}
}
] |
{
"AcceptedAnswerId": "248995",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T07:20:57.607",
"Id": "248987",
"Score": "17",
"Tags": [
"c++",
"performance",
"algorithm",
"chess"
],
"Title": "C++ chess game engine using Minimax and alpha-beta pruning;"
}
|
248987
|
<p>I have the following code (in php) that calls the open weather api with my credentials, and returns data for me.</p>
<p>Know I'm returning some data I pick from that response, I'm wondering if it's good practice to create a dedicated class for that? Is this something that's commonly used and does it have a name?</p>
<pre><code>try {
$request = $this->http->get( 'api.openweathermap.org/data/2.5/weather', $options);
$response = json_decode($request->getBody());
return [
'main' => $response->weather[0]->main,
'temperature' => $response->main->temp,
];
} catch (GuzzleException $e) {
die(var_dump($e->getMessage()));
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T04:31:29.220",
"Id": "487985",
"Score": "2",
"body": "You might want to include the entire class. And in pure OOP, everything is a class, So generally, the answer is yes. In this particular case, I'd call it adapter."
}
] |
[
{
"body": "<p>Your might actually take it a step further and create a value object for the data, making it much more type safe. Notice I added PHP 7.4 proeprty typehints. I chosen float for the temperature (maybe it's not appropriate, idk), but i definitely don't know what to choose for the <code>main</code>, but it sure deserves a typehint, if it's nested object, create another class for it or maybe pick the wanted information directly into the <code>WeatherStatus</code> class.</p>\n<pre><code>final class WeatherStatus\n{\n private ??? $main;\n private float $temperature;\n\n public function __construct(??? $main, float $temperature)\n {\n $this->main = $main;\n $this->temperature = $temperature;\n }\n\n public function getMain(): ???\n {\n return $this->main;\n }\n\n public function getTemperature(): float\n {\n return $this->temperature;\n }\n}\n</code></pre>\n<p>You can also define an interface for such a method, including a domain specific exception (because just halting the program with <code>die</code> or <code>exit</code> is not very nice thing to do, in that case it would be better to not catch the exception at all).</p>\n<pre><code>class WeatherProviderException extends \\Exception\n{\n}\n\ninterface IWeatherProvider\n{\n /**\n * @throws WeatherProviderException\n */\n public function getWeather(): WeatherStatus;\n}\n</code></pre>\n<p>In the implementation I would accept the api url rather then hardcoding it. You may add a static named constructor for the version 2.5 api.\nThe credentials for <code>openweathermap.org</code> (whatever they are, let me assume a user name and password) might be also promoted to a class or may be passed to the provider constructor as multiple arguments as well.</p>\n<pre><code>final class OpenWeatherCredentials\n{\n private string $user;\n private string $password;\n\n // constructor + getters ...\n}\n</code></pre>\n<pre><code>class OpenWeatherProvider implements IWeatherProvider\n{\n private ClientInterface $client;\n private string $apiUrl;\n private OpenWeatherCredentials $credentials;\n\n public function __construct(ClientInterface $client, string $apiUrl, OpenWeatherCredentials $credentials)\n {\n $this->client = $client;\n $this->apiUrl = $apiUrl;\n $this->credentials = $credentials;\n }\n\n public static function createV2_5(ClientInterface $client, OpenWeatherCredentials $credentials): self\n {\n return new self($client, 'https://api.openweathermap.org/data/2.5/weather', $credentials);\n }\n\n public function getWeather(): WeatherStatus\n {\n $options = [\n // whatever is needed, $this->credentials->get*\n ];\n\n try {\n // here you called the object $request, but it really is a $response\n $response = $this->client->get($this->apiUrl, $options);\n } catch (GuzzleException $e) {\n throw new WeatherProviderException($e->getMessage(), $e->getCode(), $e);\n }\n\n try {\n $json = json_decode($response->getBody(), \\JSON_THROW_ON_ERROR);\n } catch (\\JsonException $e) {\n throw new WeatherProviderException($e->getMessage(), $e->getCode(), $e);\n }\n\n return new WeatherStatus(\n $json->weather[0]->main,\n (float) $json->main->temp,\n );\n }\n}\n</code></pre>\n<p>Also notice how I wrap each statement in separate try-catch to only catch what can be caught. As long as they are handled the same way you try-catch both together but maybe you should catch their common ancestor exception instead to make it even simpler. And I pulled the instantiation of the <code>WeatherStatus</code> out of the try-catch just because I don't expect it to throw <code>GuzzleException</code> nor <code>\\JsonException</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T08:43:25.967",
"Id": "488592",
"Score": "0",
"body": "This is great! Very interesting approach, I suppose this follows ddd principles? Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T05:01:09.267",
"Id": "488677",
"Score": "1",
"body": "@MiguelStevens Well, I guess you could say so. But to me, ddd is just a buzz word. I'd rather say it follows common sense and top to bottom approach. First define what you need to be done (get current weather status), then implement it using whatever you found appropriate (openweathermap.org accessed through http). The separation of domains is just a side effect of application of common sense. Did you ever heard a weather forecaster to tell you \"tommorow will be.. HTTP 500\", those things just don't belong together, in TV they would just say \"we have technical difficulties\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T07:29:16.693",
"Id": "249022",
"ParentId": "248992",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "249022",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T09:33:36.290",
"Id": "248992",
"Score": "1",
"Tags": [
"php"
],
"Title": "Class dedicated to transforming API response to the data I need?"
}
|
248992
|
<p>This is exercise 3.1.34. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>The <a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)" rel="nofollow noreferrer">Shannon entropy</a> measures the information content of an input
string and plays a cornerstone role in information theory and data
compression. Given a string of n characters, let f(c) be the frequency
of occurrence of character c. The quantity p(c) = f(c)/n is an estimate
of the probability that c would be in the string if it were a random
string, and the entropy is defined to be the sum of the quantity -p(c)*log2(p(c)),
over all characters that appear in the string. The entropy is
said to measure the information content of a string: if each character
appears the same number times, the entropy is at its minimum value
among strings of a given length. Write a program that takes the name
of a file as a command-line argument and prints the entropy of the
text in that file. Run your program on a web page that you read
regularly, a recent paper that you wrote, and the <a href="https://introcs.cs.princeton.edu/java/data/ecoli.txt" rel="nofollow noreferrer">E. coli genome</a>
found on the website.</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>public class ShannonEntropy
{
public static String removeUnnecessaryChars()
{
String text = "";
while (!StdIn.isEmpty())
{
String word = StdIn.readString();
int wordLength = word.length();
String newWord = "";
for (int i = 0; i < wordLength; i++)
{
if (word.charAt(i) != '.' &&
word.charAt(i) != '!' &&
word.charAt(i) != '?' &&
word.charAt(i) != ',' &&
word.charAt(i) != '"' &&
word.charAt(i) != ':' &&
word.charAt(i) != ';' &&
word.charAt(i) != '(' &&
word.charAt(i) != ')')
{
newWord += word.charAt(i);
}
}
text += newWord;
}
return text.toLowerCase();
}
// this method (below) is written specifically for texts without
// unnecessary characters (e.g. E. coli genome)
public static String convertTextToString()
{
String text = "";
while (!StdIn.isEmpty())
{
String word = StdIn.readString();
text = word;
}
return text;
}
public static int[] findFrequencies(String text)
{
int textLength = text.length();
/*
char[] ALPHABET = {'a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x',
'y','z'};
*/
char[] ALPHABET = {'a','c','g','t'}; // specifically used for genes and genomes
int[] frequencies = new int[ALPHABET.length];
for (int i = 0; i < textLength; i++)
{
for (int j = 0; j < ALPHABET.length; j++)
{
if (text.charAt(i) == ALPHABET[j])
{
frequencies[j]++;
break; // to speed up the computation
}
}
}
return frequencies;
}
public static double[] findProbabilities(String text, int[] frequencies)
{
int textLength = text.length();
int n = frequencies.length;
double[] probabilities = new double[n];
for (int i = 0; i < n; i++)
{
probabilities[i] = (double) frequencies[i]/textLength;
}
return probabilities;
}
public static double log2(double x)
{
return (Math.log(x)/Math.log(2));
}
public static double calculateEntropy(double[] probabilities)
{
double shannonEntropy = 0;
int n = probabilities.length;
for (int i = 0; i < n; i++)
{
if (probabilities[i] != 0)
{
shannonEntropy += probabilities[i]*log2(probabilities[i]);
}
}
return -1*shannonEntropy;
}
public static void main(String[] args)
{
//final long time1 = System.currentTimeMillis();
//String text = removeUnnecessaryChars();
String text = convertTextToString();
//final long time2 = System.currentTimeMillis();
//System.out.println("Time to remove unnecessary characters: " + (time2-time1) + " ms");
int[] frequencies = findFrequencies(text);
//final long time3 = System.currentTimeMillis();
//System.out.println("Time to calculate character frequencies: " + (time3-time2) + " ms");
double[] probabilities = findProbabilities(text, frequencies);
System.out.println("Shannon entropy of the E. coli genome: " + calculateEntropy(probabilities));
String randomGene = "";
for (int i = 0; i < 1000000; i++)
{
double r = Math.random();
if (r < 0.25) randomGene += "a";
else if (r < 0.50) randomGene += "c";
else if (r < 0.75) randomGene += "g";
else if (r < 1.00) randomGene += "t";
}
int[] rFrequencies = findFrequencies(randomGene);
double[] rProbabilities = findProbabilities(randomGene, rFrequencies);
System.out.println("Shannon entropy of the random genome: " + calculateEntropy(rProbabilities));
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdIn.html" rel="nofollow noreferrer">StdIn</a> is a simple API written by the authors of the book. Here is one instance of my program:</p>
<p>Input: <a href="https://introcs.cs.princeton.edu/java/data/ecoli.txt" rel="nofollow noreferrer">E. coli genome</a></p>
<p>Output:</p>
<hr />
<p>Shannon entropy of the E. coli genome: 1.9998212455541713 (which is exactly compatible with the answer from <a href="https://planetcalc.com/2476/" rel="nofollow noreferrer">Online Shannon entropy calculator</a>)</p>
<p>Shannon entropy of the random genome: 1.9999979438235416</p>
<hr />
<p>Is there any way that I can improve my program (especially its performance (especially the method <code>removeUnnecessaryChars</code>))?</p>
<p>Thanks for your attention.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T21:13:19.947",
"Id": "487973",
"Score": "0",
"body": "Not your fault, and not really relevant to the question I suppose, but this is not \"the Shannon entropy\". It's the entropy of the string according to an order-0 model trained on the string itself. It's fine as an exercise, but you shouldn't use it in production code unless someone who understands information theory clears you to use it. Anyone who calls it \"the Shannon entropy\" probably doesn't understand information theory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T21:53:12.863",
"Id": "487975",
"Score": "0",
"body": "@benrg Thank you very much for the clarification. I haven't studied information theory yet."
}
] |
[
{
"body": "<p>The thinking behind the code is very good. You have split the tasks into the required methods very well. You could make some improvements still.</p>\n<p>For example, this line is a little off, looks like negation. It's just an interesting way to do it.</p>\n<pre><code>return -1*shannonEntropy;\n</code></pre>\n<p>This line, you could derive the alphabet from the text, the distinct characters.</p>\n<pre><code>char[] ALPHABET = {'a','c','g','t'};\n</code></pre>\n<p>You are doing a large amount of looping over the text, and the alphabet, then the frequencies, then the probabilities, etc. Is there any way to do it all with minimal looping?</p>\n<p>Your first loops, there is no need for the inner loop on alphabet. Just increment the count of a characters in the text and accumulate a count of the characters present - no need to even specify an alphabet - ... something like this.</p>\n<pre><code>Dictionary<char, int> frequencies = new Dictionary<char, int>();\nfor (int i = 0; i < text.Length; i++)\n{\n if (!frequencies.ContainsKey(text[i]))\n {\n frequencies.Add(text[i], 0);\n }\n frequencies[text[i]]++;\n}\n</code></pre>\n<p>Next, there is no need for separate loops to calculate probability and character entropy. Both those calculations can be done on the same loop and a running total kept.</p>\n<pre><code>double totalEntropy;\nforeach (KeyValuePair<char, int> frequency in frequencies)\n{\n double probability = ...;\n double entropy = ...;\n\n totalEntropy += entropy;\n}\n</code></pre>\n<p>That would keep looping to a minimal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:46:48.293",
"Id": "487969",
"Score": "0",
"body": "Thank you very much. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T20:33:25.947",
"Id": "487971",
"Score": "3",
"body": "This looks like C# rather than Java."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T07:29:15.423",
"Id": "487995",
"Score": "0",
"body": "it is c#; pretty sure it can be translated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T12:43:01.537",
"Id": "249004",
"ParentId": "248998",
"Score": "3"
}
},
{
"body": "<p>In Java, we typically place open braces on the same line, not a newline.</p>\n<p>Since you're specifically interested in <code>removeUnnecessaryChars</code>...</p>\n<ul>\n<li><p>using a <code>Set<Character></code> to hold the collection would be cleaner than enumerating them in the method.</p>\n</li>\n<li><p>You've got a nested loop, but then you're just smooshing everything together into one string anyway.</p>\n</li>\n<li><p>This method is only called inside its containing class, so it should be <code>private</code>. Minimize scope where possible.</p>\n</li>\n<li><p>It would be preferable if it took an argument rather than relying on the static class <code>StdIn</code>, but I'll assume this is an artifact of the assignment.</p>\n</li>\n<li><p>Note that <code>convertTextToString</code> and <code>removeUnnecessaryChars</code> operate differently on an identical input with no unnecessary characters. I expect there's a bug in <code>convertTextToString</code>.</p>\n</li>\n<li><p>The streaming version could be prettier if StdIn gives useful streaming methods, but I don't know the API of that class. Using only what you've revealed, I took a stab at it. I'm pretty sure you could also make the <code>Set</code> a <code>Set<Integer></code>, keep the rest of that declaration, and skip the <code>mapToObj</code> step, but it's past my bedtime.</p>\n</li>\n</ul>\n<p>If I were to rewrite it, it might look something like (untested!)</p>\n<pre><code>private static final Set<Character> CHARACTERS_TO_IGNORE = Set.of('.', '!', '?', ',', '"', ':', ';', '(', ')');\n\npublic static String removeUnnecessaryChars() {\n String text = "";\n while (!StdIn.isEmpty()) {\n for (char c : StdIn.readString().toCharArray()) {\n if (!CHARACTERS_TO_IGNORE.contains(c)) {\n text += c;\n }\n }\n }\n return text;\n}\n\npublic static String removeUnnecessaryChars() {\n String text = "";\n while (!StdIn.isEmpty()) {\n text += StdIn.readString()\n .chars()\n .mapToObj(i -> (char)i)\n .filter(c -> !CHARACTERS_TO_IGNORE.contains(c))\n .collect(Collectors.joining);\n }\n return text;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T03:26:15.380",
"Id": "249018",
"ParentId": "248998",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "249018",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T11:30:39.940",
"Id": "248998",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Calculating the Shannon entropy of a string (e.g. E. coli genome)"
}
|
248998
|
<p>I have written a Python script whose purpose is to read logs from CloudWatch and then post them to ElasticSearch. It is not quite finished but I've progressed far enough that I could benefit from feedback from Python experts, specifically:</p>
<ul>
<li>Is the use of Python Generators correct and idiomatic</li>
<li>Is the use of Class Composition correct and idiomatic</li>
<li>Anything else style-wise inappropriate for Python 3.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
import json
import time
import uuid
import os
import sys
import boto3
from elasticsearch import Elasticsearch, helpers
client = boto3.client("logs")
def usage() -> None:
print("Usage: GROUP_NAME=cloudwatch_group ES_HOST=es_host {}".format(
os.path.basename(__file__)))
sys.exit(1)
if "GROUP_NAME" not in os.environ:
usage()
if "ES_HOST" not in os.environ:
usage()
class CWLogs:
group_name = os.environ["GROUP_NAME"]
def events(self) -> None:
for event in self.__generate_events():
yield event
def __generate_streams(self) -> None:
kwargs = {
"logGroupName": self.group_name,
}
while True:
stream_batch = client.describe_log_streams(**kwargs)
yield from stream_batch["logStreams"]
try:
kwargs["nextToken"] = stream_batch["nextToken"]
except KeyError:
break
def __generate_events(self) -> None:
stream_names = \
[stream["logStreamName"] for stream in self.__generate_streams()]
for stream_name in stream_names:
kwargs = {
"logGroupName": self.group_name,
"logStreamName": stream_name,
}
while True:
logs_batch = client.get_log_events(**kwargs)
yield from logs_batch["events"]
try:
kwargs["nextToken"] = logs_batch["nextToken"]
except KeyError:
break
class ESWriter:
es_host = os.environ["ES_HOST"]
elastic = Elasticsearch()
def post(self, events: object) -> None:
try:
response = helpers.bulk(
self.elastic, self.__transformer(events))
print("\nRESPONSE:", response)
except Exception as e:
print("\nERROR:", e)
@staticmethod
def __index_name(timestamp: str) -> str:
return "eventbridge-auth0-{}".format(
time.strftime("%Y.%m", time.localtime(timestamp)))
@staticmethod
def __normalize(message: str) -> str:
return message # TODO.
def __transformer(self, events: object) -> None:
for event in events:
yield self.__transform(event)
def __transform(self, event: dict) -> None:
timestamp = event["timestamp"]
index_name = self.__index_name(timestamp)
message = self.__normalize(event["message"])
return "\n".join([
json.dumps({
"index": {
"_id": str(uuid.uuid4()), # TODO. Check
"_index": index_name,
"_type": "_doc"}}),
json.dumps({
"source": {
"@source": "auto-populate script",
"@timestamp": timestamp,
"@message": message}})])
if __name__ == '__main__':
ESWriter().post(CWLogs().events())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T13:58:35.903",
"Id": "487944",
"Score": "3",
"body": "Please note: code should not be changed (updated/added to) once posted, and the code should work as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T18:53:07.910",
"Id": "487961",
"Score": "0",
"body": "Small review: Change your two `if` statements to `for n in ['GROUP_NAME, 'ES_HOST'']: if n not in os.environ: usage()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:35:43.347",
"Id": "487967",
"Score": "1",
"body": "@user229550 Please post answers in answer boxes. If you have even one suggestion and you explain why you think your solution is better; it's a fine answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T21:14:31.657",
"Id": "487974",
"Score": "0",
"body": "Okay. ---------"
}
] |
[
{
"body": "<p>Don't hardcode environment variables inside the classes. Instead of this:</p>\n<pre><code>class CWLogs:\n group_name = os.environ["GROUP_NAME"]\n</code></pre>\n<p>do it like this:</p>\n<pre><code>class CWLogs:\n group_name = None\n\n def __init__(self, group_name):\n self.group_name = group_name\n\nif not GROUP_NAME := getenv('GROUP_NAME'):\n usage()\n# pass the variable when initializing the class :\nCWLogs(GROUP_NAME)\n</code></pre>\n<p>This will make the code more maintainable as it does not tightly bound it to the env. variable, but rather to whatever you'll pass there and it will be easier to write tests for such code. Moreover you dont have to repeat the variable in two places, which will increase chance you'll make a typo in one place or forget to modify it in both places when the functionality will change. Same with the <code>ESWriter</code> class.</p>\n<p>then there's this function:</p>\n<pre><code>def __generate_events(self) -> None:\n stream_names = [stream["logStreamName"] for stream in self.__generate_streams()]\n\n for stream_name in stream_names:\n ...\n</code></pre>\n<p>Here you have an unnecessary extra loop and extra list allocated in the memory. First you iterate through data returned from <code>__generate_streams()</code>, and then you iterate through the same data once again. You can do this instead:</p>\n<pre><code>def __generate_events(self) -> None:\n for stream_obj in self.__generate_streams():\n stream_name = stream_obj['logStreamName']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T07:07:58.813",
"Id": "487993",
"Score": "0",
"body": "Oh yes thank you! Good pickup."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T04:27:25.960",
"Id": "249020",
"ParentId": "248999",
"Score": "1"
}
},
{
"body": "<h1>Code Organization</h1>\n<p>Your code organization seems non-existent. You have:</p>\n<ul>\n<li>imports</li>\n<li>code</li>\n<li>function definition</li>\n<li>code</li>\n<li>class definitions</li>\n<li>main-guarded code</li>\n</ul>\n<p>Code should be organized in a more consistent structure, like:</p>\n<ul>\n<li>imports</li>\n<li>class definitions</li>\n<li>function definitions</li>\n<li>main-guarded code</li>\n</ul>\n<p>The point of using a main-guard is to prevent code from running if the file is imported into another file. Here, you have two separate code blocks which are unconditionally executed. This limits code reuse. For example, imagine someone could use <code>CWLogs</code> for their own task, but doesn't need <code>ESWriter</code>. They try <code>from your_file import CWLogs</code>, and find their program exits after displaying a cryptic error message about a how to execute a program they are not actually running, due to a missing environment variable they don't actually use.</p>\n<h1>sys.exit()</h1>\n<p>Don't call this. It terminates the Python interpreter.</p>\n<p>Any debugging you may have hoped to do when the program finishes will be impossible, because the entire Python environment imploded. It is impossible to safely import your file using <code>try:</code> <code>import your_file</code> <code>except ImportError:</code> because Python execution terminates during the import, meaning the program trying to import it unconditionally terminated. If you try to use <code>unittest</code> to test your program, or Sphinx to generate documentation for your program, or any number of other common things, you can't, because your file has unconditionally terminated the Python interpreter.</p>\n<p>Don't call it.</p>\n<p>Instead:</p>\n<pre><code>if __name__ == '__main__':\n if {'GROUP_NAME', 'ES_HOST'} <= os.environ.keys():\n main()\n else:\n usage()\n</code></pre>\n<p>No need for <code>usage()</code> to call <code>sys.exit()</code>. After <code>usage()</code> is called, and returns normally, execution reaches the end of the file, which if this is the main program file, will naturally end the program. Of course, if this is not the main program file, the main guard would have not run either method, the execution would reach the end of the file completing the importation of the file as a module in another program.</p>\n<h1>Stop Writing Classes</h1>\n<p>See "<a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop Writing Classes</a>" for a PyCon talk by Jack Diederich.</p>\n<p>A class with no instance data members probably shouldn't be a class. Neither <code>ESWriter</code> nor <code>CWLogs</code> have any instance data members.</p>\n<p>A class with no constructor and only one public method to call shouldn't be a class. Neither <code>ESWriter</code> nor <code>CWLogs</code> have a constructor. Both have a single public method, called immediately after constructing a class instance, so the instance is not even saved.</p>\n<p>These should not be classes.</p>\n<h1>Private name mangling</h1>\n<p><a href=\"https://docs.python.org/3/reference/expressions.html#atom-identifiers\" rel=\"nofollow noreferrer\">Private name mangling</a> is used to prevent private member name collisions when a class is derived from another class, typically when the base class and the derive class are under control of different entities. For instance, if you derive your own class from a <code>tkinter.Frame</code>, and you create a <code>_validate</code> method in your class, you could cause the base class to stop functioning properly if it had its own <code>_validate</code> method that was just abruptly changed on it. So, the base class would use <code>__validate</code>, the leading double underscore would trigger name "mangling", and replace the name with <code>_Frame__validate</code>, so collisions are less likely.</p>\n<p>There appears to be no reason for your usage of a double underscore prefix in your method names; a single underscore would be more idiomatic.</p>\n<h1>Type Hints</h1>\n<p>Your type hints are wrong.</p>\n<p>For instance, the following is clearly returning a <code>str</code>, not <code>None</code>:</p>\n<pre><code> def __transform(self, event: dict) -> None:\n ...\n return "\\n".join( ... )\n</code></pre>\n<p>Since <code>__transformer</code> is yielding the results of <code>__transform</code>, it is not returning <code>None</code> either, but should be declared as:</p>\n<pre><code>from typing import Generator\n\n...\n\n def __transformer(self, events: object) -> Generator[str, None, None]:\n ...\n</code></pre>\n<p>Or simply:</p>\n<pre><code>from typing import Iterator\n\n...\n\n def __transformer(self, events: object) -> Iterator[str]:\n ...\n</code></pre>\n<p>And <code>events: object</code> is virtually meaningless, since everything in Python is an object. Either use a proper type for it, or don't bother with a type hint at all.</p>\n<h1>Generator Expressions</h1>\n<p>As <a href=\"https://codereview.stackexchange.com/a/249020/100620\">yedpodtrziko</a> noted,</p>\n<pre><code>def __generate_events(self) -> None:\n stream_names = [stream["logStreamName"] for stream in self.__generate_streams()]\n\n for stream_name in stream_names:\n ...\n</code></pre>\n<p>builds up a temporary list, only to immediately iterate through it. They made a fairly large change in the code to avoid the temporary list. There is a much smaller change that can be made:</p>\n<pre><code>def __generate_events(self) -> None:\n stream_names = (stream["logStreamName"] for stream in self.__generate_streams())\n\n for stream_name in stream_names:\n ...\n</code></pre>\n<p>Because it may be hard to see the change, I'll amplify it: the <code>[...]</code> got changed to <code>(...)</code>. This means instead of <code>stream_names</code> being realized as an in-memory list, it becomes a generator expression, which will produce the values one at a time when asked.</p>\n<p>It doesn't make much of a difference here, but if <code>stream_names</code> was being passed to a function, instead of being used locally, the change proposed by yedpodtrziko would require reworking code much further away to accept the <code>stream_obj</code> and extracting the stream names inside that function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:17:29.103",
"Id": "488038",
"Score": "0",
"body": "Wow thank you, a lot to digest, appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:12:11.870",
"Id": "249047",
"ParentId": "248999",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249047",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T12:04:24.497",
"Id": "248999",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"generator",
"elasticsearch"
],
"Title": "Feedback on generator functions and class composition in Python 3"
}
|
248999
|
<p>I have a MongoRepository:</p>
<pre><code>@Repository
public interface GooglePlayGameRepository extends MongoRepository<GooglePlayGame, String> {
Optional<GooglePlayGame> findByTitle(String title);
List<GooglePlayGame> findByTitleContainsIgnoreCase(String title);
@Aggregation("{$sample: {size: ?0} }")
List<GooglePlayGame> findRandomGames(Long number);
}
</code></pre>
<p>And service:</p>
<pre><code>@Service
public class GooglePlayGameService {
private final GooglePlayGameRepository googlePlayGameRepository;
public GooglePlayGameService(GooglePlayGameRepository googlePlayGameRepository) {
this.googlePlayGameRepository = googlePlayGameRepository;
}
public void saveToLibrary(GooglePlayGame googlePlayGame) {
googlePlayGameRepository.save(googlePlayGame);
}
public GooglePlayGame getGameByTitle(String title) throws NoSuchGooglePlayGameFoundException {
Optional<GooglePlayGame> googlePlayGame = googlePlayGameRepository.findByTitle(title);
return googlePlayGame.orElseThrow(
() -> new NoSuchGooglePlayGameFoundException("Game was not found: " + title)
);
}
public List<GooglePlayGame> findByTitle(String title) {
List<GooglePlayGame> googlePlayGames = googlePlayGameRepository.findByTitleContainsIgnoreCase(title);
return googlePlayGames.isEmpty()
? Collections.emptyList()
: googlePlayGames;
}
public Long getLibrarySize() {
return googlePlayGameRepository.count();
}
public List<GooglePlayGame> getRandomGames(Long number) {
return googlePlayGameRepository.findRandomGames(number);
}
}
</code></pre>
<p>What do you think about methods <code>getGameByTitle</code> (returns exact match) and <code>findByTitle</code> (looking for similar matches by title)? Is it good practice to handle <code>Optional</code> in Service layer and just throws Exception? Or should I use <code>Optional</code> as a return type in Service layer too and handle it in other places which will use this service?</p>
<p>About <code>findByTitle</code>: is it necessary to use this construction?</p>
<pre><code>googlePlayGames.isEmpty()
? Collections.emptyList()
: googlePlayGames;
</code></pre>
<p>Maybe I should just check it in code like this (not in the service):</p>
<pre><code>if (googlePlayGames.isEmpty()){
log.error("Game {} doesn't exist in library", title);
}
</code></pre>
<p>I have another variant for these methods:</p>
<pre><code>public GooglePlayGame getGameByTitle(String title) throws NoSuchGooglePlayGameFoundException {
return findByTitle(title).stream()
.findFirst()
.orElseThrow(NoSuchGooglePlayGameFoundException::new);
}
public List<GooglePlayGame> findByTitle(String title) {
List<GooglePlayGame> games = googlePlayGameRepository.findByTitleContainsIgnoreCase(title);
if (!games.isEmpty()) {
return games;
}
return Collections.emptyList();
}
</code></pre>
<p>Which one is better?</p>
|
[] |
[
{
"body": "<ol>\n<li>You don't need to make additional save method since save method already exist.</li>\n</ol>\n<pre><code>public void saveToLibrary(GooglePlayGame googlePlayGame) {\n googlePlayGameRepository.save(googlePlayGame);\n }\n</code></pre>\n<ol start=\"2\">\n<li>You have two methods one called <code>findByTitle(String title)</code> and <code>findByTitleContainsIgnoreCase</code></li>\n</ol>\n<p>To make other programmer understand whats going on maybe renaming <code>findByTitleContainsIgnoreCase</code> to <code>findListOfGamesByTitle</code>since you are returning List and also it can be optional since games might not be there at all.</p>\n<p>In your service call <code>findListOfGamesByTitle</code> just pass String <code>(title.equalsIgnoreCase())</code></p>\n<ol start=\"3\">\n<li><p>Why are you throwing exception at method level and also inside the body in <code>getGameByTitle</code> , do you want to pass that exception further ? there is no point doing it.</p>\n</li>\n<li><p>Yes, you should handle optional in the service layer because next layer is the constructor.</p>\n</li>\n</ol>\n<p>The sentence and the place you mentioned is not understood so please fix it a bit\ni am referring to the following -> Maybe I should just check it in code like this (not in the service):</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T18:49:33.117",
"Id": "249008",
"ParentId": "249001",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T12:12:27.617",
"Id": "249001",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"spring"
],
"Title": "Repository and service improvements"
}
|
249001
|
<p>I'm trying to implement a palindrome check for each element in a vector and return a vector with only the palindromes. This should work for different type .e.g strings int vector of ints.I have done a templated solution but I feel like this doesn't take full advantage of templates.</p>
<pre><code>//main.cpp
// Checking palindrome with integers
Palindrome <int>pal = {125125, 4947, 74347, 11};
pal.FindPalindromeDataset();
pal.Print();
// Checking palindrome with strings
Palindrome <std::string>pal1 = {"yay", "world", "level", "hello"};
pal1.FindPalindromeDataset();
pal1.Print();
// Checking palindrome with vector of ints
Palindrome<std::vector<int> > pal3 = {{6, 2, 2, 6},
{1, 2, 2},
{1, 4, 6, 3, 5, 3, 6, 4, 1},
{5, 2, 2, 6, 9, 1, 2}};
</code></pre>
<pre><code>//palindrome.hpp
#ifndef PALINDROME_HHP
#define PALINDROME_HHP
#include <vector>
#include <iostream>
template <class T>
class Palindrome {
public:
//! Construct from a std::initializer list
Palindrome(std::initializer_list<T> _dataset) : dataset(_dataset)
{}
//! Print the palindromeDataset
void Print() const;
/* Traverse to check if each element of the vector is a palindrome
* and push them in the new array
*/
void FindPalindromeDataset()
{
for (auto i : dataset)
{
if (IsPalindrome(i))
{
palindromeDataset.push_back(i);
}
}
}
private:
//! Is the element of the vector palindrome
bool IsPalindrome(const T& s) const;
//! Initial dataset
std::vector<T> dataset;
//! Dataset after palindrome check
std::vector<T> palindromeDataset;
};
#endif
</code></pre>
<pre><code>#include "palindrome.hpp"
#include "iostream"
#include "string"
template <>
void Palindrome<int>::Print() const
{
std::cout << "{";
for (auto iter = palindromeDataset.begin(); iter != palindromeDataset.end();)
{
std::cout << *iter;
if (++iter != palindromeDataset.end())
{
std::cout << ", ";
}
}
std::cout << "}"<<std::endl;
}
template <>
void Palindrome<std::string>::Print() const
{
std::cout << "{";
for (auto iter = palindromeDataset.begin(); iter != palindromeDataset.end();)
{
std::cout << *iter;
if (++iter != palindromeDataset.end())
{
std::cout << ", ";
}
}
std::cout << "}"<<std::endl;
}
template <>
void Palindrome<std::vector<int>>::Print() const
{
std::cout << "{";
for (auto iter1 = palindromeDataset.begin(); iter1 != palindromeDataset.end();)
{
std::cout << "{";
for (auto iter2 = iter1->begin(); iter2 != iter1->end();)
{
std::cout << *iter2;
if (++iter2 != iter1->end())
{
std::cout << ", ";
}
}
std::cout << "}";
if (++iter1 != palindromeDataset.end())
{
std::cout << ", ";
}
}
std::cout << "}"<<std::endl;
}
template <>
bool Palindrome<int>::IsPalindrome(const int& s) const
{
int x = s;
long int rev = 0;
if (x<0)
{
return false;
}
while (x!=0)
{
rev= rev*10+(x%10);
x=x/10;
}
return s == rev;
}
template <>
bool Palindrome<std::string>::IsPalindrome(const std::string& s) const
{
const size_t len = s.size();
if (!len)
{
return true;
}
size_t l = 0;
size_t r = len - 1;
while (l < r)
{
if (s[l] != s[r])
{
return false;
}
++l;
--r;
}
return true;
}
template <>
bool Palindrome<std::vector<int>>::IsPalindrome(const std::vector<int>& s) const
{
const size_t len = s.size();
if (!len)
{
return true;
}
size_t l = 0;
size_t r = len - 1;
while (l < r)
{
if(s[l] != s[r])
{
return false;
}
++l;
--r;
}
return true;
}
</code></pre>
|
[] |
[
{
"body": "<p>I. Construction is split in several phases. Or, in other words, a freshly constructed object is not in a finalized, ready-to-use state and needs one more explicit initialization call. This is a very strong antipattern, which could obviously lead to errors.<br/>\nA more decent solution would be to filter the dataset right inside the constructor, and not keep two vectors at once, thus doubling the space needed (especially when one of the vectors is only needed as an argument to create the other, and is unsable and inaccessible otherwise). (One drawback to this design is obviously that the construction would be very strict, but this is okay as long as we neglect the possibility that the constructed palindrome filter could never be actually used.)</p>\n<p>II. The code for <code>Print</code> is <em>absolutely</em> identical between ints and strings, and for vectors, only differs in printing-an-element part.</p>\n<p>III. The palindrome filter itself could be more useful perhaps, if it was implemented simply as a function operating on ranges, similar to those defined in <code><algorithm></code>; or at least if it implemented idiomatic <code>iterator</code>/<code>begin</code>/<code>end</code> interface. <code>std::remove_if</code> with <code>IsPalindrome</code> as predicate would be a good start.</p>\n<p><sup>IV. And the constructor itself (as it's written) could be templated, accepting an arbitrary argument pack and forwarding it to <code>dataset</code> ctor.</sup></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:00:22.797",
"Id": "249009",
"ParentId": "249005",
"Score": "2"
}
},
{
"body": "<p>First: This seems like an application of <a href=\"https://quuxplusone.github.io/blog/2020/05/28/oo-antipattern/\" rel=\"noreferrer\">"The OO Antipattern"</a>. I don't see why you need <code>class Palindrome</code> at all; and if you must keep it, you certainly shouldn't store the entire dataset — just process it once in the constructor and keep the palindromes!</p>\n<p>Similarly, <code>Palindrome<T>::Print()</code> seems like it ought to be generalized to "print this <em>thing</em>, whatever it is"; that operation has nothing to do with palindromes and can be split out into its own utility function.</p>\n<p>So we're left with this:</p>\n<pre><code>template<class T>\nstd::vector<T> keep_only_palindromes(std::vector<T> dataset) {\n std::erase_if(dataset, [](auto&& elt) {\n return !is_palindromic(elt);\n });\n return dataset;\n}\n\ntemplate<class T>\nclass PrintableVector {\n const std::vector<T> *v_;\npublic:\n explicit PrintableVector(const std::vector<T>& v) : v_(&v) {}\n friend std::ostream& operator<<(std::ostream& os, const PrintableVector& me) {\n os << "{ ";\n for (auto&& elt : *me.v_) os << elt << ", ";\n os << "}";\n return os;\n }\n};\n</code></pre>\n<p>Then we could rewrite your test cases as:</p>\n<pre><code>int main() {\n auto pal = keep_only_palindromes(\n std::vector<int>{125125, 4947, 74347, 11}\n );\n std::cout << PrintableVector(pal) << "\\n";\n\n auto pal1 = keep_only_palindromes(\n std::vector<std::string>{"yay", "world", "level", "hello"}\n );\n std::cout << PrintableVector(pal1) << "\\n";\n\n std::vector<std::vector<int>> pal2_data = {\n {6, 2, 2, 6},\n {1, 2, 2},\n {1, 4, 6, 3, 5, 3, 6, 4, 1},\n {5, 2, 2, 6, 9, 1, 2}\n };\n auto pal2 = keep_only_palindromes(pal2_data);\n std::cout << PrintableVector(pal2) << "\\n";\n}\n</code></pre>\n<p>By the way, it's very nice that you wrote test cases! Very few people do. Your test cases are useful because they show how you intend the class to be used — and allow <em>me</em> to show how I intend my rewrite to be used!</p>\n<p>I do notice that you don't test any corner cases, such as <code>1</code>, <code>0</code>, <code>-1</code>, <code>""</code>, <code>{42}</code>, or <code>{}</code>. This is not so great.</p>\n<hr />\n<p>Your <code>IsPalindrome</code> for anything iterable is going to be exactly the same. So prefer to write something like</p>\n<pre><code>template<class T>\nauto is_palindromic(const T& seq)\n -> decltype(std::begin(seq), std::rbegin(seq), true)\n{\n return std::equal(\n std::begin(seq), std::end(seq),\n std::rbegin(seq), std::rend(seq)\n );\n}\n</code></pre>\n<p>There I'm using <em>return type SFINAE</em> to say that this template should be considered for instantiation only when the expression <code>std::begin(seq), std::rbegin(seq), true</code> is well-formed. In C++20 you could convey the intent better with something like this:</p>\n<pre><code>template<class T>\nconcept sequence = requires (const T& seq) {\n seq.begin(); seq.rbegin();\n};\n\ntemplate<class T> requires sequence<T> // !!\nbool is_palindromic(const T& seq) {\n return std::equal(\n std::begin(seq), std::end(seq),\n std::rbegin(seq), std::rend(seq)\n );\n}\n</code></pre>\n<p>In either case, you'd still have to write your other overload</p>\n<pre><code>bool is_palindromic(int x)\n</code></pre>\n<p>by hand.</p>\n<p>A version of this code with slightly less handwaving and more arcane syntax is at <a href=\"https://godbolt.org/z/aqPfGx\" rel=\"noreferrer\">https://godbolt.org/z/aqPfGx</a> — might be interesting to take a look, even if some of the arcane syntax is intimidating (and, honestly, unnecessary — if I were going to print out a vector of vectors in C++, "I wouldn't start from here").</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T22:10:01.983",
"Id": "249013",
"ParentId": "249005",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T15:58:31.350",
"Id": "249005",
"Score": "6",
"Tags": [
"c++",
"c++11",
"template"
],
"Title": "Templated palindrome"
}
|
249005
|
<p>I'm trying to solve <a href="https://www.hackerrank.com/challenges/functional-programming-the-sums-of-powers/problem" rel="nofollow noreferrer">this challenge on HackerRank</a>.</p>
<p>In short, given <code>x</code> and <code>n</code>, I have to determine how many ways I can pick numbers from the <code>n</code>th powers of the natural numbers such that their sum is <code>x</code>.</p>
<p>So my first reasoning was to compute the list of the <code>n</code>th powers that I need as a first step. This list is</p>
<pre class="lang-hs prettyprint-override"><code>list = takeWhile (<= x) [i^n | i <- [1..]]`
</code></pre>
<p>Now <code>list</code> is the bucket from which I have to pick numbers to add up to <code>n</code>.</p>
<p>I first thought about list comprehensions, because that's how I would pick a <strong>given</strong> number of numbers from the list; for instance this is how I would generate the <code>sumList</code> of the sums of any different triplets from <code>list</code>:</p>
<pre class="lang-hs prettyprint-override"><code>sumList = [x + y + z | x <- list, y <- dropWhile (<= x) list, z <- dropWhile (<= y) list]
</code></pre>
<p>Then I would just need to <code>length $ filter (== x) sumList</code>.</p>
<p>However, after some thinking, I concluded that list comprehensions are not the way to go, since I don't know in advance how many numbers I have to pick from <code>list</code> when attempting to sum them up to <code>x</code>.</p>
<p>So I thought that any possible sum corresponds to a combination of <em>pick or not-pick</em> while traversing the <code>list</code>. This made me think of binary trees, and I eventually came up with this solution, which fails the <em>Test Case 3</em> for timeout:</p>
<pre class="lang-hs prettyprint-override"><code>main :: IO()
main = do
[x,n] <- sequence $ replicate 2 ((read :: String -> Int) <$> getLine)
print $ length $ filter (== x) $ getLeaves $ listToSumTree $ takeWhile (<= x) [i^n | i <- [1..]]
data Tree a = Leaf a | Node a (Tree a) (Tree a) deriving (Show)
listToTreeImpl :: (Num a, Eq a) => [a] -> Tree a -> Tree a
listToTreeImpl [] tree = tree
listToTreeImpl (l:ls) (Leaf x) = Node x
(listToTreeImpl ls $ Leaf x)
(listToTreeImpl ls $ Leaf (x + l))
getLeaves :: Tree a -> [a]
getLeaves (Leaf a) = [a]
getLeaves (Node _ (Leaf _) (Node _ _ _)) = error "this should not happen"
getLeaves (Node _ (Node _ _ _) (Leaf _)) = error "this should not happen"
getLeaves (Node _ left right) = getLeaves left ++ getLeaves right
listToSumTree :: (Num a, Eq a) => [a] -> Tree a
listToSumTree ls = listToTreeImpl ls (Leaf 0)
</code></pre>
<p>I can only think of <code>getLeaves $ listToSumTree</code> as the only critical part of the program, since <code>listToSumTree</code> constructs a full tree, which is not needed (only the leaves are), and <code>getLeaves</code> traverses all the tree, only to get to the bottom layer of it.</p>
|
[] |
[
{
"body": "<p>What you're essentially doing with your binary tree is checking all possible combinations of numbers from the list <code>[i^n | i <- [1..x]]</code>. That's quite a lot of combinations! (Exercise: how many?)</p>\n<p>Not all of those combinations are sensible, however. For example, if x = 100 and n = 2, and you've already chosen, say, 4 and 5 (giving 6<sup>2</sup>+7<sup>2</sup>=85), then adding 8<sup>2</sup>=64 is not going to help, nor is adding 9<sup>2</sup>=81. In your current solution, however, you're still checking those.</p>\n<p>So how does one encode this knowledge in the search for solutions? The key thing is that we can build the solution recursively: we can use an already computed answer for a smaller case to help answer a larger case. If we're given x = 10 and n = 2, then we can only add 1<sup>2</sup>, 2<sup>2</sup> or 3<sup>2</sup>. If we try adding 3<sup>2</sup>, we have only 1 left to fill, which we can only do by adding 1<sup>2</sup>. If, instead, we start by trying 2<sup>2</sup>, we have to make 6, which is impossible. Starting with 1<sup>2</sup> lets us choose 3<sup>2</sup> to fill up the remaining 9. Since only the set of numbers counts, not their order, this means there is only one solution for x=10,n=2: namely, {1<sup>2</sup>,3<sup>2</sup>} (as stated in the problem).</p>\n<p>Checking whether two solutions are the same modulo ordering is annoying, however. Can we do better? Yes we can, by adding another parameter to the problem.</p>\n<p>Think about how we could do this before reading on.</p>\n<hr />\n<p>A way to change the problem to prevent us from generating multiple solutions that are really the same set of numbers, is to add as a parameter the maximum value we're allowed to choose. So a problem is now not only specified by (x=10,n=2), but also by an integer M; for example, if M=9, then we may add 1<sup>2</sup>≤9, 2<sup>2</sup>≤9 and 3<sup>2</sup>≤9, so (x=10,n=2,M=9) has one solution: {1<sup>2</sup>,3<sup>2</sup>}. However, (x=10,n=2,M=2) has no solutions, because by only using 1<sup>2</sup> and 2<sup>2</sup> you can never make 10.</p>\n<p>How is this useful? Well, consider how we could, as a lazy office worker, go about computing how many solutions there are to (x=10,n=2,M=10). (For the original problem, we just set M=x, since choosing numbers higher than x is certainly useless.) This lazy office worker realises that either x=0, in which case we have precisely 1 solution (choosing no numbers at all), or x≠0, in which case we need to choose at least one number. If we choose, say, i<sup>2</sup>, then the remainder still to fill is 10 - i<sup>2</sup>. Since our lazy office worker is also clever, they realise that if we force any solutions for 10 - i<sup>2</sup> to only choose numbers smaller than i<sup>2</sup> (i.e. set M = i<sup>2</sup> - 1), then we won't ever get any duplicates: there may certainly be solutions for our (x,n,M) that choose i<sup>2</sup> and also some larger j<sup>2</sup>, but then we'll find that one by starting with j<sup>2</sup> and then going downward.</p>\n<p>So our lazy office worker writes down a series of smaller problems: <code>[(x-i<sup>n</sup>,n,i<sup>n</sup>-1) | i <- [1..M]]</code>, to solve for the next office worker in line. (These are recursive calls.) The total number of solutions is just the sum of the number of solutions for each of these subproblems.</p>\n<p>An alternative, more direct way to explain the same way of solving, is to note that while all solutions are sets of distinct integers, we can represent those sets by sorted lists. If the empty solution is not possible (i.e. x≠0), then each of the possible solutions for our current problem has one largest value, so we can find all solutions for the problem going over each largest value i<sup>n</sup> from 1 to M, computing the solutions for (x - i<sup>2</sup>, n, i<sup>n</sup> - 1), and prepending that largest value i<sup>2</sup> to its corresponding sub-solutions. If, instead of building the actual solution lists we just compute the number of them, we arrive at the same solution as above.</p>\n<hr />\n<p>Now the above is not very formalised yet, and that is on purpose. Because for me, the next step to formalisation would be writing out the recursive function, which is 95% of the work in implementing the program. And that's your task. :)</p>\n<p>If any of the above is unclear (probably), or you get stuck, feel free to ask further questions.</p>\n<p>EDIT: When I coded out my first solution for the problem, I also cached recursive calls in a table, making it a dynamic programming solution. However, for the given input range that apparently doesn't help, so a standard recursive program works fine.</p>\n<p>EDIT 2: If you want to handle <code>1000 1</code>, then you do need dynamic programming :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:35:22.947",
"Id": "487966",
"Score": "0",
"body": "Thanks, I'll take my time to read your answer with the pace you suggested. Btw, you've forgotten a `<` after a `3`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:39:34.240",
"Id": "487968",
"Score": "0",
"body": "Good luck! Typo fixed :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T20:12:18.763",
"Id": "487970",
"Score": "0",
"body": "Thanks :) Btw, I have [this](https://codereview.stackexchange.com/questions/248967/hackerrank-filter-huge-list-for-elements-that-occur-more-than-a-given-number-o) other review on Haskell, if you like to give a look at it too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T19:24:27.793",
"Id": "249010",
"ParentId": "249006",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T17:37:23.777",
"Id": "249006",
"Score": "2",
"Tags": [
"programming-challenge",
"haskell",
"time-limit-exceeded",
"tree",
"binary-tree"
],
"Title": "HackerRank - Binary tree to compute the Nth power of natural numbers that sum up to X"
}
|
249006
|
<p>I have implemented <code>Dijkstra's algorithm</code> for my research on an Economic model, using Python.
In my research I am investigating two functions and the differences between them. Every functions takes as input two parameters:
<code>F(a,b)</code> and <code>Z(a,b)</code>.</p>
<p>Every cell of the matrix is defined as: <span class="math-container">$$M[a][b]=|F(a,b)-Z(a,b)|$$</span></p>
<p>The purpose of this is to find the path of minimal difference between the equations that will be correct for every input <code>a</code></p>
<p>Online implementations of Dijkstra's algorithm were all using weighted edges whereas I have weighted vertices.</p>
<h3>Pseudo-code:</h3>
<pre><code>function Dijkstra(Graph, source):
create vertex set Q
for each vertex v in Graph:
dist[v] ← INFINITY
prev[v] ← UNDEFINED
add v to Q
dist[source] ← 0
while Q is not empty:
u ← vertex in Q with min dist[u]
remove u from Q
for each neighbor v of u: // only v that are still in Q
alt ← dist[u] + length(u, v)
if alt < dist[v]:
dist[v] ← alt
prev[v] ← u
return dist[], prev[]
</code></pre>
<h3>Input:</h3>
<ol>
<li>2d array where each cells value is its weight</li>
<li>source tuple (x, y)</li>
</ol>
<h3>Output:</h3>
<ol>
<li><p>distance matrix where each cell contains distance from source to vertex (i, j)</p>
</li>
<li><p>prev matrix where each cell contains its parent. By tracebacking from (98,98) I can find the shortest path.</p>
</li>
</ol>
<h3>Implementation:</h3>
<pre><code>MAX_DISTANCE = 99999
RANGE_ARR = [x for x in range(1, 1001)]
def dijkstra_get_min(Q, dist):
min = MAX_DISTANCE + 1
u = None
for vertex in Q:
if dist[vertex[0], vertex[1]] <= min:
min = dist[vertex[0], vertex[1]]
u = vertex
return u
def dijkstra(graph, src=(0, 0)):
dist = np.array([np.array([0 for x in RANGE_ARR], dtype=float) for y in RANGE_ARR])
prev = np.array([np.array([(0, 0) for x in RANGE_ARR], dtype='i,i') for y in RANGE_ARR])
Q = []
for i in RANGE_ARR_0:
for j in RANGE_ARR_0:
dist[i, j] = MAX_DISTANCE
prev[i, j] = (0, 0)
Q.append((i, j))
dist[0][0] = 0
while Q:
u = dijkstra_get_min(Q, dist)
Q.remove(u)
moves = [x for x in ( (u[0], u[1] + 1), (u[0] + 1, u[1]), (u[0] + 1, u[1] + 1) ) if x in Q]
for v in moves:
alt = dist[u[0]][u[1]] + graph[v[0]][v[1]]
if alt < dist[v[0]][v[1]]:
dist[v[0], v[1]] = alt
prev[v[0], v[1]] = u
return dist, prev
</code></pre>
<p>Any opinions about its correctness?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T09:33:24.560",
"Id": "488001",
"Score": "0",
"body": "What is ``RANGE_ARR_0``?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T11:59:37.897",
"Id": "488010",
"Score": "0",
"body": "I am confused by your mentioning of online implementations. It doesn't look like your algorithm is online at all, nor do I see any attempt at making it online. Also, from the description of your problem, I don't even see why the algorithm needs to be online, especially since online algorithms typically only give approximately correct results, not absolutely correct ones. (Online insertion sort is a rare exception to the rule.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:59:09.850",
"Id": "488031",
"Score": "0",
"body": "@MisterMiyagi I guess it slipped when I copy pasted, it's same as RANGE_ARR but from 0 to 1000"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T17:00:02.120",
"Id": "488032",
"Score": "0",
"body": "@JörgWMittag Online I meant on the internet, not live data input. My mistake for using this terminology."
}
] |
[
{
"body": "<p><code>[x for x in range(1, 1001)]</code> can be written as just <code>list(range(1, 1001))</code>.</p>\n<p>It would be good to give that <code>1001</code> a name too.</p>\n<hr />\n<p>Similarly, <code>[0 for x in RANGE_ARR]</code> can be written as <code>[0] * len(RANGE_ARR)</code>. Multiplying any sequence type by an integer repeats the elements within the sequence. As a bonus, from some quick benchmarking that I just did, it's also more than 10x faster:</p>\n<pre><code>from timeit import timeit\n\nN = int(1e6)\nTRIALS = int(1e3)\n\nprint(timeit(lambda: [0] * N, number=TRIALS), "seconds")\n\nprint(timeit(lambda: [0 for x in range(N)], number=TRIALS), "seconds")\n\n2.9889957 seconds\n38.1463017 seconds\n</code></pre>\n<p><strong>Be aware though</strong> that you should not use this when the element type is mutable (like <code>[[0]] * 5</code>). Multiplying a sequence creates multiple references to the same object; it doesn't make copies.</p>\n<hr />\n<p>It looks like <code>Q</code> should be a set. You don't care about order, and the only thing you use it for is to track membership of a set. Sets will be significantly faster here. The only two changes needed are:</p>\n<pre><code>Q = set()\n\n. . .\n\nQ.add((i, j))\n</code></pre>\n<p>The only change I can see this making is <code>dijkstra_get_min</code> technically does rely on the order of <code>Q</code>. If two elements with the same minimum values are in Q, your algorithm picks the last instance. Since sets may use a different order, this may change what vertex gets returned.</p>\n<hr />\n<p>It looks like <code>MAX_DISTANCE</code> is meant to be some arbitrarily large number that everything else will be less than. You may want to try using <code>np.inf</code> for that. By hardcoding the upper limit, you risk the problem "growing" later and potentially exceeding that max; causing erroneous behavior.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T23:41:29.673",
"Id": "487977",
"Score": "0",
"body": "Thanks for your input! I guess I should have made Q a set and not a list, but I have already started execution of my run and expect it to take about 3 days (I only save data to file when the execution is complete, and not every iteration), so I am not sure if it's worth restarting for this change. \n\nHopefully the algorithm is also correct for that matter.\n\nRegarding [0] * size, I didn't know that is such a big difference in run time. However it looks dangerous for lists in lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T23:46:59.053",
"Id": "487978",
"Score": "1",
"body": "@O.B. Honestly, if I were you, I'd make the changes then see if you can run another instance of the program (I have no idea what environment you're running this is in, so idk if that's feasible). The changes I suggested have the potential for *massive* speed increases. The `*` suggestion likely won't matter unless the `dijkstra` function is being called repeatedly with large inputs. The set change will likely be where the majority of speedups happens. `remove` on a list is an expensive operation. It's `O(n)` on lists, but effectively `O(1)` with sets. How big of `Q`s are you working with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T23:48:16.460",
"Id": "487979",
"Score": "1",
"body": "If restarting is the only option though, I wouldn't say to restart since I obviously have little background about the size of data you're working with and external constraints you're under."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T23:57:12.503",
"Id": "487980",
"Score": "2",
"body": "Actually, `remove` on lists might be worse than I originally thought. It needs to search through the list to find the element, then after removing it, it needs to shift all the elements after the removed element to the left to fill in the space (lists don't support efficient random removals). That means even if the first element in the list is the one to be removed, every element after it will need to be shifted. So every element in the list will need to be \"visited\" regardless of which element is removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T00:03:31.820",
"Id": "487981",
"Score": "0",
"body": "I see your point. I have restarted it as it is running only for few hours... Hopefully it will be faster. My matrix is 1,000x1,000 cells at this stage."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T20:55:01.610",
"Id": "249012",
"ParentId": "249011",
"Score": "7"
}
},
{
"body": "<p>Your code looks generally correct, but ignores <code>src</code> and only searches in positive direction. In addition, it can be cleaned up and optimised significantly.</p>\n<hr />\n<p>Some general comments first:</p>\n<ul>\n<li>Use full variable names in code that express meaning/purpose. There is no significant cost to using meaningful names, but they can make code much easier to digest.</li>\n<li>Be aware of the host language's features and standards. Avoid re-using the names of builtins (e.g. <code>min</code>) and try to adhere to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">coding style standards</a>.</li>\n<li>Avoid <code>numpy</code> unless actually using its inbuilt features. Using <code>numpy.array</code> for direct access is usually <em>slower</em> than <code>list</code>/<code>set</code>/... because values are converted to full Python objects on each access.</li>\n</ul>\n<hr />\n<p>Do not make assumptions about the features of your data. In specific, avoid these:</p>\n<pre><code>MAX_DISTANCE = 99999\nRANGE_ARR = [x for x in range(1, 1001)]\n</code></pre>\n<p>These fail for graphs with distance > 99999 or more than 1000 elements. Either compute them for your input, or use true upper bounds.</p>\n<p>Since numbers have a well-defined "maximum", we can use this safely:</p>\n<pre><code>INFINITY = float('int')\n</code></pre>\n<p>Since the input <code>graph</code> is an nxn matrix, we can just query its size.</p>\n<pre><code># inside `def dijkstra(graph, source):`\nindices = range(len(graph))\n</code></pre>\n<hr />\n<p>Let us start with <code>vertex in Q with min dist[u]</code>/<code>dijkstra_get_min</code>. Your algorithm is proper, but we can exploit that Python's builtin <code>min</code> already allows custom weights. The <code>for vertex in Q:</code> becomes the primary argument to <code>min</code>, the <code>if dist[vertex[0], vertex[1]] <= min:</code> becomes the weight <code>key</code>.</p>\n<pre><code>def dijkstra_get_min(vertices, distances):\n return min(vertices, key=lambda vertex: distance[vertex[0]][vertex[1]])\n</code></pre>\n<hr />\n<p>The <code>Dijkstra</code> algorithm consists of two parts – initialisation and search. Your code becomes clearer if we split these two parts – your line <code>dist[0][0] = 0</code> is the transition from one to the other.</p>\n<pre><code>def dijkstra(graph, src=(0, 0)):\n # dist, prev, Q\n distances, prev_nodes, unvisited = dijkstra_initial(len(graph))\n # set starting point\n distances[src[0]][src[1]] = 0\n dijkstra_search(graph, distances, prev_nodes, unvisited)\n return distances, prev_nodes\n</code></pre>\n<hr />\n<p>The purpose of initialisation is that <em>every</em> point has the same value. This means we can directly create the matrices with their final value. Also, since the algorithm does not <em>use</em> the "previous node", we can initialise it to a cheap placeholder.</p>\n<pre><code>def dijkstra_initial(size):\n distances = [[INFINITY] * size for _ in range(size)]\n prev_nodes = [[None] * size for _ in range(size)]\n unvisited = {(x, y) for x in range(size) for y in range(size)}\n # dist, prev, Q\n return distances, prev_nodes, unvisited\n</code></pre>\n<p>Instead of tracking visited nodes as a <em>list</em> (<code>[..., ...]</code>) we use a <em>set</em> (<code>{..., ...}</code>). A set is unordered and supports O(1) membership tests, compared to list O(n) membership tests. This makes it better suited for bookkeeping of visited/unvisited nodes.</p>\n<hr />\n<p>To search through the graph, we will be visiting the neighbours repeatedly. This is a key part that can be easily done wrong – unless the Graph implementation provides it, it can be worthwhile to implement explicitly.</p>\n<pre><code>def neighbours(node):\n x, y = node\n return [\n (x + x_offset, y + y_offset)\n for x_offset in (-1, 0, 1)\n for y_offset in (-1, 0, 1)\n if not (x_offset == y_offset == 0) # reject node itself\n ]\n</code></pre>\n<p>The core of the algorithm stays logically the same: We adjust some names to be more speaking (e.g. <code>u</code> -> <code>node</code>, <code>v</code> -> <code>neighbour</code>). We use the prepared <code>neighbours</code> instead of the lengthy expression.</p>\n<pre><code>def dijkstra_search(graph, distances, prev_nodes, unvisited):\n while unvisited:\n node = dijkstra_get_min(unvisited, dist)\n unvisited.remove(node)\n for neighbour in neighbours(node):\n if neighbour not in unvisited:\n continue\n alt = distances[node[0]][node[1]] + graph[neighbour[0]][neighbour[1]]\n if alt < distances[neighbour[0]][neighbour[1]]:\n distances[neighbour[0]][neighbour[1]] = alt\n prev_nodes[neighbour[0]][neighbour[1]] = node\n</code></pre>\n<hr />\n<p>At this point, the code should be both faster and easier to maintain. The most glaring flaw we still have is the explicit handling of dimensions. Instead of manually accessing each dimension, it would be better if we could directly access points.</p>\n<pre><code># currently\ndistances[neighbour[0]][neighbour[1]]\n# desirable\ndistances[neighbour]\n</code></pre>\n<p>This can be "fixed" by using dictionaries (<code>{point: value, ...}</code>) instead of nested lists (<code>[[value, ...], ...]</code>). An immediate downside is that this trades memory for simplicity.</p>\n<p>However, it can be used to actually reduce memory usage – dictionaries can be naturally sparse, allowing us to simply not store undetermined fields. Since any visited node becomes irrelevant for distances, we can even clear <code>distances</code> of nodes that are already processed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T17:00:43.877",
"Id": "488033",
"Score": "0",
"body": "Thank you so much for your detailed comment! Regarding usage of numpy, its only purpose is because it provides easy debugging in Pycharm. But I guess that after debug I should have reverted them to normal lists.\n I have also changed my global input variables as you suggested and it allows easier flexibility for different inputs of data. the usuage of min function is good to know, as I implemented another version of this in another section of my analysis and this does save some hassle (took notes for future)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T17:08:53.800",
"Id": "488035",
"Score": "0",
"body": "I will implement the rest of the changes you suggest as I am getting very long run time that could use some optimizations. Thank you so much!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T10:47:27.480",
"Id": "249029",
"ParentId": "249011",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249029",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-06T20:23:33.873",
"Id": "249011",
"Score": "10",
"Tags": [
"python",
"pathfinding",
"dijkstra"
],
"Title": "Implementation of Dijkstra's algorithm in Python"
}
|
249011
|
<p>I have a problem that I solved in 2 different ways and I would like to know which one is better, cleaner and easier to read.</p>
<p>Problem:
Write a while loop that starts at the last character in the
string and works its way backwards to the first character in the string,
printing each letter on a separate line.</p>
<p>Example 1:</p>
<pre><code>char = 'Wednesday'
cont = -1
cont2 = len(char)
cont3 = len(char) + 1
while cont < cont2:
print(char[cont2:cont3])
cont2 = cont2 - 1
cont3 = cont3 - 1
</code></pre>
<p>Example 2:</p>
<pre><code>char = 'Wednesday'
cont = len(char) - 1
while cont >= 0:
cont2 = char[cont]
print(cont2)
cont -= 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:14:58.287",
"Id": "488037",
"Score": "2",
"body": "You should use better variable names. They should be more descriptive. In example 2, I'd suggest `string` instead of `char`, `i` instead of `cont`, and `char` instead of `cont2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T13:40:46.783",
"Id": "488122",
"Score": "2",
"body": "If you just want to print a word backwards with each character being on a new line you could use a for loop and a slice that steps backwards:\n`for character in word[::-1]: print(character)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T16:25:54.557",
"Id": "488144",
"Score": "2",
"body": "Similar to @whme, you could even go for `print(*reversed(word), sep = '\\n')`. That is: reverse the word, unpack it, i.e, split into letters and print every letter separated by a linebreak."
}
] |
[
{
"body": "<p>Looking at the two implementations side by side, ignoring the goal of the exercise and alternative implementations, I'd say the second example is better:</p>\n<ul>\n<li>It uses one fewer variables.</li>\n<li>It does a simple index lookup rather than a slice.</li>\n<li>The implementation is easier to follow.</li>\n</ul>\n<p>For simple problems like this it's often useful to think of the complexity of the solution as the number of "tokens", or distinct language elements, necessary to write it down. For example, <code>print(cont2)</code> is four tokens: <code>print</code>, <code>(</code>, <code>cont2</code> and <code>)</code>. By a quick read the first example has about twice as many tokens as the second.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T03:16:15.090",
"Id": "249017",
"ParentId": "249015",
"Score": "15"
}
},
{
"body": "<p>The shorter code, the better (as long as it does not goes into extreme which makes the code obfuscated). So the second solution is better - it's using fewer lines and variables to achieve the same goal.</p>\n<p>Here's a small nitpick, which might sound like an overreaction advice for this simple task, but every massive codebase once started as a simple thing: use better variable names.</p>\n<ul>\n<li><p><code>char</code> is usually a reference to a single character, however in your case it's the whole string, which might be a bit confusing.</p>\n</li>\n<li><p><code>cont</code> is abbreviation for what?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T15:39:54.127",
"Id": "488019",
"Score": "1",
"body": "I second the variable naming. It's exactly what I would have written if you didn't it before."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T04:13:47.577",
"Id": "249019",
"ParentId": "249015",
"Score": "12"
}
},
{
"body": "<p>Another reason the first one is worse is that it prints an extra empty line at the beginning due to your off-by-one error. The only reason you don't get an error is that Python plays nice when you ask for out-of-bounds slices and gives you an empty string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T10:59:16.877",
"Id": "249030",
"ParentId": "249015",
"Score": "-1"
}
},
{
"body": "<p>Sure, the second answer is better, but neither answer looks like code\nthat a fluent Python programmer would write.</p>\n<p>The telltale sign: both answers fail to take full advantage of the fact that strings are\n<a href=\"https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range\" rel=\"noreferrer\">sequences</a>,\nlike lists and tuples. Among other things, this means that strings are directly\niterable.</p>\n<pre><code>word = 'Wednesday'\n\n# No: too much red tape.\n\nfor i in range(len(word)):\n print(word[i])\n\n# Yes: nice and simple.\n\nfor char in word:\n print(char)\n</code></pre>\n<p>In addition to being directly iterable, sequences are sortable and\n<a href=\"https://docs.python.org/3/library/functions.html?highlight=reverse#reversed\" rel=\"noreferrer\">reversible</a>.</p>\n<pre><code>for char in reversed(word):\n print(char)\n</code></pre>\n<p>Or even:</p>\n<pre><code>print('\\n'.join(reversed(word)))\n</code></pre>\n<p>And it you absolutely must use a <code>while</code> loop, perhaps this will do the trick.\nYes, it's dumb, but it's still simpler and easier to understand than the bureaucracy of accessing characters in a string by index.</p>\n<pre><code>while True:\n print('\\n'.join(reversed(word)))\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:18:32.853",
"Id": "488039",
"Score": "0",
"body": "Good answer. That's definitely more Pythonic. It is not a while loop though (OP's context)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:23:31.160",
"Id": "488040",
"Score": "0",
"body": "@theonlygusti Point taken ... but who gives that assignment? Ugh! Added an edit to satisfy the critics. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:31:46.153",
"Id": "488041",
"Score": "0",
"body": "Haha I know right, probably the purpose is to get students to think about looping backwards, but they should have assigned a language other than Python... do we ever have to loop backwards in Python..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:24:43.063",
"Id": "488048",
"Score": "0",
"body": "Even shorter and dumber: `while print('\\n'.join(reversed(word))): pass`. Anyway, I think the assignment is legitimate. Everybody should *know* iteration with a while-loop like that. If people iterate iterables only ever with `for` loop \"magic\", they'll become the kind of people who ask why removing elements from the list they're iterating doesn't work as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T20:47:41.987",
"Id": "488061",
"Score": "0",
"body": "it was an assignment from \"Python for everybody\" with Dr. Charles R."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T01:34:40.047",
"Id": "488173",
"Score": "0",
"body": "\"bureaucracy of accessing characters in a string by index\" is this really how python-coders think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T02:51:53.680",
"Id": "488174",
"Score": "0",
"body": "@infinitezero I haven't convinced them all, but the movement is growing!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T18:04:14.553",
"Id": "249046",
"ParentId": "249015",
"Score": "5"
}
},
{
"body": "<p>As other have pointed out descriptive variable naming will improve readability a great deal. Things like <code>char</code> allude to a character, but that's vague and needlessly shortened.</p>\n<p>In a programmatic mindset of looking for optimizations it can be easy to try to reduce the size of code, but the length of variable names are of no consequence. It's more important their name be unambiguous and understandable from a glance than it be short.</p>\n<p>A <code>for</code> loop can represent, among other things, operating on a set of items interacting with each on in turn. A <code>while</code> loop can represent, among other things, <em>consuming</em> a resource one item at a time. Perhaps it is the latter that this exercise was mean to demonstrate, thus the requirement of using a <code>while</code> loop instead of <em>any</em> loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>word = "Wednesday"\nwhile word:\n print(word[-1])\n word = word[:-1]\n</code></pre>\n<p><code>while word:</code></p>\n<p>An empty sequence (list with no items, string with no characters) is evaluated to False for things like While loop conditions. This is equivalent to "while the string 'word' is not an empty string."</p>\n<p><code> print(word[-1])</code></p>\n<p>This project seems to be a fine way to explore string slicing. On the python website's "<a href=\"https://docs.python.org/3/tutorial/introduction.html\" rel=\"nofollow noreferrer\">An informal introduction to Python</a>" string slicing is introduced\nand it is shown that getting index -1 of a string or other sequence returns the last item.</p>\n<p><code> word = word[:-1]</code></p>\n<p>Slicing with <code>[:-1]</code> will get everything <em>except</em> the last item.</p>\n<p>You can combine these to continue printing <code>word</code>, trimming off what was printed, until there is nothing left to print. If the word was actually a list (and you could make it one if you really wanted with <code>list(word)</code>) you could use the <code>list.pop</code> function which you can find more on <a href=\"https://docs.python.org/3.7/tutorial/datastructures.html\" rel=\"nofollow noreferrer\">here</a>. In that case this code may look more like this:</p>\n<pre><code>char = ["w","e","d","n","e","s","d","a","y"]\n# or\nchar = list("Wednesday")\n\nwhile char:\n print(char.pop())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T17:33:58.037",
"Id": "249090",
"ParentId": "249015",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249017",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T02:36:12.417",
"Id": "249015",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x",
"comparative-review"
],
"Title": "Print a word, one character per line, backwards"
}
|
249015
|
<p>I've written something (i.e. frankensteined from stack exchange) that appears to work but I haven't done much testing on the edge cases. Signed up here for some feedback on what optimizations or other functions/methods I could have used, and whether or not I've missed something critical -- this is my first time dealing with arrays extensively. To be honest the data sizes used will be less than 10000 cells so I doubt the speed will improve much, but I feel like I'm accessing the same data multiple times and would like to learn to reduce redundancy.</p>
<p>Basically I select multiple cells on a worksheet, usually a filtered one, and I want to see how much the sum of each column, rounded as displayed/printed, would vary from the true, precise sum (as excel would show if using the SUM() function). I'll hit the keyboard shortcut and have a Msgbox pop up.</p>
<pre><code>Private DecPlace As Integer 'decimal places for rounding checker vertical
Private boo1 As Boolean 'check if decimal place has been assigned
Sub RoundingMsgbox()
' Ctrl + E
Dim DataRange as Variant 'values from selection
Dim ResultArr() As String 'output
Dim RoundedSum As Double 'rounded sum
Dim PrecSum As Double 'precise sum
Dim x%, y%, z%, ans%, rng As Range '% = integers
Dim rowslist As New Collection
Dim colslist As New Collection
Dim Lrow As Integer, Lcol As Integer, Xrow As Integer, Xcol As Integer, Tcol() As Integer, Trow() As Integer
On Error GoTo ender
RoundedSum = 0
PrecSum = 0
Selection.SpecialCells(xlCellTypeVisible).Select 'this will split areas??
If boo1 = 0 Then
DecPlace = InputBox("Input rounding decimal places:", , 2)
boo1 = 1
End If
If Selection.Cells.Count < 2 Then Exit Sub
If Selection.Areas.Count = 1 Then 'if contiguous, no need to manually populate an array but did it anyway
DataRange = Selection.Value
Xrow = Selection.Rows.Count
Xcol = Selection.Columns.Count 'Max
ReDim ResultArr(0 To Xcol)
For y = 1 To Selection.Columns.Count
For x = 1 To Selection.Rows.Count
DataRange(x, y) = Selection.Cells(x, y).Value
Next
Next
Else 'non contiguous, find unique rows and cols to prep arrays
For z = 1 To Selection.Areas.Count
For Each rng In Selection.Areas(z).Rows 'L-R, U-D order.
On Error Resume Next
rowslist.Add rng.Row, CStr(rng.Row)
On Error GoTo 0
Next rng
For Each rng In Selection.Areas(z).Columns
On Error Resume Next
colslist.Add rng.Column, CStr(rng.Column)
On Error GoTo 0
Next rng
Next
Xrow = rowslist.Count
Xcol = colslist.Count
On Error GoTo ender
ReDim Trow(1 To rowslist(rowslist.Count)) 'primitive way of storing the corresponding index of each cell's addresses instead of row/col number
ReDim Tcol(1 To colslist(colslist.Count))
For z = 1 To rowslist.Count
Trow(rowslist(z)) = z
'Debug.Print "row" & rowslist(z)
Next
For z = 1 To colslist.Count
Tcol(colslist(z)) = z
'Debug.Print "col" & colslist(z)
Next
ReDim DataRange(Xrow, Xcol) 'redim after finding max cols
ReDim ResultArr(0 To Xcol)
For z = 1 To Selection.Areas.Count 'populating DataRange array with values ordered by their columns
For Each rng In Selection.Areas(z)
DataRange(Trow(rng.Row), Tcol(rng.Column)) = rng.Value
Next
Next
End If
ResultArr(0) = "Round to " & DecPlace & " decimal places:" & vbCrLf & "Rounded diff ; Rounded total"
For Lcol = 1 To Xcol
For Lrow = 1 To Xrow
RoundedSum = RoundedSum + WorksheetFunction.Round(CDec(DataRange(Lrow, Lcol)), DecPlace) 'vba round uses banker's rounding so call excel round instead
PrecSum = PrecSum + DataRange(Lrow, Lcol) 'index(arr,0,col) does not work for manually populated array variant
Next Lrow
ResultArr(Lcol) = "Col " & Lcol & vbTab & FormatNumber(RoundedSum - PrecSum, DecPlace, , vbFalse, vbTrue) & vbTab & FormatNumber(RoundedSum, DecPlace, , vbFalse, vbTrue)
RoundedSum = 0
PrecSum = 0
Next Lcol
ans = MsgBox(Join(ResultArr, vbCrLf) & vbCrLf & vbCrLf & "Set new decimal place?", vbYesNo + vbDefaultButton2)
If ans = 6 Then '6 = yes
DecPlace = InputBox("Input rounding decimal places:", , 2)
End If
Exit Sub
ender:
boo1 = 0
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>For now I'm the only one using it, so I can manually constrain my selections and inputs to either not crash the code or just click "End" if it throws an error. It seems to work fine for "normal" columns but I suspect something hidden in the flawed logic will collapse if this encounters a more intricate spreadsheet.
After I figure everything out here eventually I want to expand to horizontal sums, and also reading the selection for "sum", "sumif", "+" etc., and checking the corresponding cells... but that's for later.</p>
<p>I would appreciate any feedback, for both code and comments! Thanks :]</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T08:10:03.240",
"Id": "487996",
"Score": "1",
"body": "Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:39:04.960",
"Id": "488960",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:44:56.353",
"Id": "488962",
"Score": "0",
"body": "@Mast sorry about that, I just wanted to edit the comments so it's easier to follow. have you reversed that for me already? If so, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:47:37.283",
"Id": "488963",
"Score": "0",
"body": "Yes, I have reversed this. I understand the sentiment, but do you realize what happens if you keep changing the code and 3 answers on 3 different revisions come in? Whoever comes in later and notices your post, will have trouble understanding what's going on. Good chance 1-2 of those 3 answers no longer make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T09:50:55.247",
"Id": "488964",
"Score": "0",
"body": "Yes I see, I have done no changes to the code itself, just comments, spacing/line breaks, and commented out the error handling which was not intended. But thanks again, understand now that it was improper. And sorry again!"
}
] |
[
{
"body": "\n<h2>General Notes</h2>\n<p>When I tried to run your code as written, it errored out, and did not properly store the precision variable that you had assigned. In general, I recommend avoiding the <code>On Error Goto Ender</code> approach to error handling, as it makes it more difficult to know at a glance if a given behavior is intended. That is, unless you are going to make an error handling section that actually notifies the user, writes to the debug console, or to some log, it is probably best to not have an error handling block, so that when you encounter an error, you know it.</p>\n<p>Your code is a bit cluttered, and therefore a bit hard to read. Consider adding spacing between logical steps in your code, along with comments ahead of those steps to explain what they do. An example may look something like</p>\n<pre class=\"lang-vb prettyprint-override\"><code>'' Iterate over rows, then columns in selection\nFor row = 1 to Selection.Rows.Count\n For col = 1 to Selection.Columns.Count\n '' Do some thing with individual cell in selection\n Call DoTheThing(Selection.Item(row,col))\nNext col, row\n</code></pre>\n<h2>Modification to Approach</h2>\n<p>Rather than making collection objects with cell addresses, we can instead find the footprint of all of the areas that the visible cells in the selection take up, and iter over the columns (or rows) that make up that footprint. We can then check if the intsection of that range and the visible portion of the selection is nothing to know whether we should consider that cell for analysis</p>\n<h2>Step 0: Initialize Module-Level Variables</h2>\n<p>There are generally two approaches for handling module level variables of the form</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private mPrecision As Byte\n</code></pre>\n<p>for this kind of project. If the module level variable is an <code>Object</code>, instead of some primative, is used in many different methods, or there are many objects that need to be initialized, then it is generally best to have some <code>Initialize</code> method, which is called at the beginning of each sub in the module. This might look something like</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private mDict as Scripting.Dictionary, _ \n mData as Long()\n\n\nPrivate Sub Initialize()\n '' if objects are initialized, then exit the routine\n If Not mDict Is Nothing Then Exit Sub\n \n Set mDict = New Scripting.Dictionary\n Redim Long(0 to 100, 0 to 100)\nEnd Sub\n</code></pre>\n<p>however, in this case, we only have one variable that really needs to be tracked, one method using it, and it is a primitive type, so we can handle its initialization using a bool inside of the main method. This will look something like</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private mInitialized as Boolean\nPrivate mPrecision as Byte\n\nPublic Sub MacroExample()\n\n '' check if the precision is assigned\n If Not mInitialized Then \n\n '' add entry point for assigning precision at the end of the method\nAssignPrec:\n\n '' assign the precision\n Let mPrec = SomeFunction()\n\n '' check if assiging the precision for first time, if not exit\n If mInitialized Then Exit Sub Else Let mInitialized = True\n End If \n\n '' other logic\n Call SomeOtherFunctions()\n\n '' query if user wants to assign new precision\n If vbYes = MsgBox("Would you like to assign new precision", vbYesNo) Then Goto AssignPrec\n\nEnd Sub\n</code></pre>\n<h2>Step 1: Find the footprint</h2>\n<p>This section of code is from one of my previous code review responses, and is a rather quick way to find the total footprint of all of the areas in a given <code>Excel.Range</code> object. Of note, as any single range object can only exist on a single <code>Excel.Worksheet</code> object, we do not need any logic to ensure that this is the case, however, if you have an array of ranges, you would need to check that they all exist on the same worksheet.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>'' Function that takes in a Range object, and returns the rectangular footprint of that range, as a range\nPublic Function footprint(ByRef rng As Excel.Range) As Excel.Range\n\n Dim numAreas As Long, _\n rMin As Long, rMax As Long, _\n cMin As Long, cMax As Long, _\n iter As Long\n \n '' handle trivial case (numAreas = 1)\n Let numAreas = rng.Areas.Count\n If numAreas = 1 Then Set footprint = rng: Exit Function\n \n '' Initialize row and column min and maxs\n Let rMin = rng.Areas(1).Item(1).Row\n Let cMin = rng.Areas(1).Item(1).Column\n Let rMax = rng.Areas(1).Item(rng.Areas(1).Count).Row\n Let cMax = rng.Areas(1).Item(rng.Areas(1).Count).Column\n \n '' iter over areas, adjusting mins and maxs as needed\n For iter = 2 To numAreas\n With rng.Areas(iter)\n If .Item(1).Row < rMin Then Let rMin = .Item(1).Row\n If .Item(1).Column < cMin Then Let cMin = .Item(1).Column\n If .Item(.Count).Row > rMax Then Let rMax = .Item(.Count).Row\n If .Item(.Count).Column > cMax Then Let cMax = .Item(.Count).Column\n End With\n Next iter\n \n '' output the footprint\n With rng.Worksheet\n Set footprint = .Range(.Cells(rMin, cMin), .Cells(rMax, cMax))\n End With\nEnd Function\n</code></pre>\n<h2>Step 2: Iter over Columns (or Rows) of the Footprint</h2>\n<p>Using the <code>Footprint()</code> function defined above, and the <code>Intersect(rngA, rngB)</code> function we can iterate over all of the visible cells in the selection. You expressed interest in modifying your function to iterate over rows instead of columns in your prompt, so I have included an implementation of this in addition to a method for iterating over column by column below.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Sub MacroIterOverSelection()\n\n Dim rng as Excel.Range\n Set rng = IIf(Selection.Cells.Count = 1, Selection, Selection.SpecialCells(xlCellTypeVisible))\n \n '' example to iter over all the visible cells in selection, top left to bottom right\n Dim cell as Excel.Range\n For Each cell in Intersect(Footprint(rng), rng)\n \n '' do analysis\n \n Next cell\n \n '' example to iter over all the cols in the selection, col by col\n Dim col as Excel.Range\n For Each col in rng.Columns\n set col = Intersect(col, rng)\n\n '' Intersect can return nothing so check if that is the case\n If Not col Is Nothing Then\n\n '' do analysis\n\n End If\n Next col\n \n '' example to iter over all the rows in the selection, row by row\n Dim row as Excel.Range\n For Each row in rng.Rows\n set row = Intersect(row, rng)\n\n '' Intersect can return nothing so check if that is the case\n If Not row Is Nothing Then\n\n '' do analysis\n\n End If\n next row\n\nEnd Sub\n</code></pre>\n<h2>Step 3: Gather the relevant Sums</h2>\n<p>To get the precise sum of a range, in the form that we are iterating over, we can use the <code>WorksheetFunction.Sum</code> function. In the example iterating over column by column, this looks like</p>\n<pre class=\"lang-vb prettyprint-override\"><code>let pSum = Excel.WorksheetFunction.Sum(col)\n</code></pre>\n<p>and we can use the <code>Evaluate</code> function to get the rounded sum. This rounded sum calculation looks like</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Let rsum = Evaluate("=Sum(Round(" & col.Address & "," & mPrecision & "))")\n</code></pre>\n<p>where mPrecision is the number of decimal places to show. In this rounded case, Excel is calculating an array of rounded values, then summing them, all in one step, and is equivalant to an Excel function of the form</p>\n<pre class=\"lang-vb prettyprint-override\"><code>=Sum(Round(A1:A30,3))\n</code></pre>\n<p>where <code>A1:A30</code> is analagous to the selected range, and <code>3</code> to the desired precision.</p>\n<p>Adding in logic to trace precedents is more complicated. If you want to only follow the <code>SUM</code>-type precedents, that would look something like</p>\n<pre class=\"lang-vb prettyprint-override\"><code>... \n\n'' get visible cells from the selection, and its footprint\nSet rng = IIf(Selection.Cells.Count = 1, Selection, Selection.SpecialCells(xlCellTypeVisible))\nSet frng = footprint(rng)\n\n\nDim RegExp As New VBScript_RegExp_55.RegExp, _\n matches As VBScript_RegExp_55.match, _\n cell As Excel.Range, _\n out As Excel.Range, _\n match As Variant, _\n submatch As Variant, _\n found As Boolean\n \n \nLet RegExp.IgnoreCase = True\nLet RegExp.Global = True\nLet RegExp.MultiLine = True\nLet RegExp.Pattern = "(?:SUM\\((.+)\\))?(?:SUMIFS?\\((?:(.+),.+)\\))?"\n\n\nFor Each col In frng.Columns '' iter over columns in footprint\n Set col = Intersect(col, rng) '' get overlapping section of column & visible selection\n \n '' if the column has anything in it\n If Not col Is Nothing Then\n '' iter over each cell with a formula in the column\n For Each cell In col\n '' iter over the regex output\n For Each match In RegExp.Execute(cell.Formula)\n '' if no output, skip\n If Not match Is Nothing Then\n '' iter over ranges encapsulated by sum or sumif(s)\n For Each submatch In match.SubMatches\n '' if empty, skip\n If Not IsEmpty(submatch) Then\n '' set flag that says the cell was found to contain a formula\n Let found = True\n \n '' union out with the precedents in the cell\n Set cell = cell.Worksheet.Range(submatch)\n End If\n Next submatch\n End If\n Next match\n '' if the cell does not contain a formula, union it with out\n Debug.Print cell.Address\n If out Is Nothing Then Set out = cell Else Set out = Union(out, cell)\n Next cell\n \n \n \n '' out is now a range covering the initial selection, plus the precedants of areas w/ a sum statement, minus those cells\n \n '' do logic onto out\n Debug.Print out.Address\n \n \n \n End If\nNext col\n...\n</code></pre>\n<h2>All together</h2>\n<p>If we throw together all of the relevant bits, we end up with a module which looks something like the below.</p>\n<p>There is certainly more to be said for this, in particular about the string building technique, but that may not be relevant to what you are looking for. If it is relevant, and you want more info on it, just let me know, and I explain it</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n \nPrivate mInitialized As Boolean\nPrivate mPrecision As Byte\n\nPublic Sub MacroSumVisibleSelectedByCol()\n\n Dim inVal As String, _\n length As Byte, _\n i As Long, _\n rng As Excel.Range, _\n frng As Excel.Range, _\n col As Excel.Range, _\n psum As Double, _\n rsum As Double\n \n '' On First Run, take input\n If Not mInitialized Then\nTakeInput:\n '' Take user input for number of decimal places\n Let inVal = Application.InputBox( _\n Title:="Macro In - Sum Selected Visible Cells by Column", _\n Prompt:="Input rounding decimal places (0 to 22):", _\n Default:=mPrecision, _\n Type:=1) '' 1 specifies input is to be a number\n If inVal = "False" Then Exit Sub '' user cancelled\n \n '' Handle bad input\n If Not Int(inVal) = inVal Or inVal < 0 Or inVal > 23 Then\n If Not vbYes = VBA.MsgBox( _\n Title:="Error - Invalid mprecision", _\n Prompt:="Number of decimal places must be an integer, n, such that 0 <= n <= 22" & _\n vbCrLf & vbCrLf & "Would you like to retry?", _\n Buttons:=vbRetryCancel + vbQuestion) _\n Then Exit Sub Else GoTo TakeInput '' exit if user cancelled else go back to input\n Else\n Let mPrecision = inVal '' user gave good input, convert to byte\n 'Let length = 8 + 2 * mPrecision '' define line length\n End If\n \n '' if redirected into this block from below, ask if\n '' useer wants to run again or exit at this point\n If Not mInitialized Then\n Let mInitialized = True\n ElseIf Not vbYes = VBA.MsgBox( _\n Title:="Macro Out - Sum Selected Visible Cells by Column", _\n Prompt:="Would you like to run macro again?", _\n Buttons:=vbYesNo + vbDefaultButton1) Then GoTo CleanExit\n End If\n End If\n \n '' get visible cells from the selection, and its footprint\n Set rng = IIf(Selection.Cells.Count = 1, Selection, Selection.SpecialCells(xlCellTypeVisible))\n Set frng = footprint(rng)\n \n '' define string array to hold output lines\n '' ( using line format `XFD | 0.###` )\n ReDim lines(1 To frng.Columns.Count) As String\n\n '' calculate the average, and build strings for ouput\n Let i = 0\n For Each col In frng.Columns '' iter over columns in footprint\n Set col = Intersect(col, rng) '' get overlapping section of column & visible selection\n If Not col Is Nothing Then '' if exists, then\n Let i = i + 1 '' count\n \n '' calc both values\n Let psum = Excel.WorksheetFunction.Sum(col)\n Let rsum = Evaluate("=Sum(Round(" & col.Address & "," & mPrecision & "))")\n \n '' construct the line\n Let lines(i) = join(Array( _\n Split(col.Address(ColumnAbsolute:=False), "$")(0), _\n Round(psum, mPrecision), _\n Round(rsum, mPrecision), _\n FormatNumber(rsum - psum, mPrecision, groupdigits:=vbFalse) _\n ), vbTab)\n End If\n Next col\n\n '' trim off unused indices from lines array\n ReDim Preserve lines(1 To i)\n\n '' output to the user\n If vbYes = VBA.MsgBox( _\n Title:="Macro Out - Sum Selected Visible Cells by Column", _\n Prompt:="The following sums were calculated:" & vbCrLf & vbCrLf & _\n "Column" & vbTab & "Actual" & Space$(mPrecision) & vbTab & "Round" & Space$(mPrecision) & vbTab & "Diff" & vbCrLf & _\n VBA.join(lines, vbCrLf) & vbCrLf & vbCrLf & _\n "Would you like to set a default number of decimal places?", _\n Buttons:=vbYesNo + vbDefaultButton2) Then GoTo TakeInput\n \nCleanExit:\n Exit Sub\nEnd Sub\n\n'' Function that takes in a Range object, and returns the rectangular footprint of that range, as a range\nPublic Function footprint(ByRef rng As Excel.Range) As Excel.Range\n\n Dim numAreas As Long, _\n rMin As Long, rMax As Long, _\n cMin As Long, cMax As Long, _\n iter As Long\n \n '' handle trivial case (numAreas = 1)\n Let numAreas = rng.Areas.Count\n If numAreas = 1 Then Set footprint = rng: Exit Function\n \n '' Initialize row and column min and maxs\n Let rMin = rng.Areas(1).Item(1).Row\n Let cMin = rng.Areas(1).Item(1).Column\n Let rMax = rng.Areas(1).Item(rng.Areas(1).Count).Row\n Let cMax = rng.Areas(1).Item(rng.Areas(1).Count).Column\n \n '' iter over areas, adjusting mins and maxs as needed\n For iter = 2 To numAreas\n With rng.Areas(iter)\n If .Item(1).Row < rMin Then Let rMin = .Item(1).Row\n If .Item(1).Column < cMin Then Let cMin = .Item(1).Column\n If .Item(.Count).Row > rMax Then Let rMax = .Item(.Count).Row\n If .Item(.Count).Column > cMax Then Let cMax = .Item(.Count).Column\n End With\n Next iter\n \n '' output the footprint\n With rng.Worksheet\n Set footprint = .Range(.Cells(rMin, cMin), .Cells(rMax, cMax))\n End With\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:37:55.787",
"Id": "488943",
"Score": "0",
"body": "Hi Taylor, thanks a lot for such a structured and detailed answer! I learned about a lot of new properties and methods that I didn't know existed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:46:47.197",
"Id": "488945",
"Score": "0",
"body": "oops, i accidentally submitted the comment -- \nOne problem I encountered using your code is where some rows are hidden/filtered/ I want to sum non-contiguous parts of the same column. It throws an error on evaluating the rsum, since col.Address doesn't seem to store the desired range.\nI'm sorry that my code was so messy and poorly commented, I'll do better next time. \nI actually commented out my On Error Goto but pasted a wrong version here, sorry about that as well. I noticed that my ctrl+select must go top left to bottom right or else it will error on my original code's min/max settings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T08:48:32.687",
"Id": "488946",
"Score": "0",
"body": "I originally planned to loop through but had no idea how to deal with non-contiguous ranges and therefore ended up using the convoluted array method above. This was very helpful! And I'm certainly interested in RegEx matching techniques but I don't have the time to develop that yet, so I did what I could. I'm also curious what sort of selections you did that ended up in errors with my code, if you don't mind going through that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T03:57:21.557",
"Id": "489195",
"Score": "0",
"body": "I'll go ahead and mark this as answered. I only changed the rounded sum to a loop to add up all the values in col in case the col was not contiguous and so far it works perfect! Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-14T17:46:08.860",
"Id": "249359",
"ParentId": "249016",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249359",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T03:07:01.773",
"Id": "249016",
"Score": "2",
"Tags": [
"array",
"vba",
"excel"
],
"Title": "Output the rounded sum of each column in selection"
}
|
249016
|
<p>Here is my solution for the <a href="https://github.com/gophercises/quiz" rel="nofollow noreferrer">Quiz game</a> exercise from <a href="https://gophercises.com/" rel="nofollow noreferrer">https://gophercises.com/</a>. The goal is to write a program that will read questions and their correct answers from a CSV file, ask them from a user one by one, and print the number of correct answers. The interesting part is that a user has a limited amount of time for answering questions and the quiz should stop as soon as the time limit has exceeded.</p>
<p>I use <code>MissingH</code> and <code>parsec</code> to parse CSV files, <code>optparse-applicative</code> to parse CLI options.</p>
<p>From a code review, I expect some general advice and answers to the following specific questions:</p>
<ul>
<li>Is there a way to rewrite <code>play</code> function without <code>MVar</code>'s?</li>
<li>How to separate quiz logic from the concurrent implementation (forking, <code>MVar</code> manipulation) in the <code>play</code> function?</li>
<li>The first version of the solution was without a timer and to count the number of correct answers I used the following function:</li>
</ul>
<p>Code for kinda beautiful <code>count</code> function:</p>
<pre><code>count :: [IO Bool] -> IO Integer
count [] = return 0
count (act:xs) = do
correct <- act
fmap ((if correct then 1 else 0) +) (count xs)
</code></pre>
<p>With the presence of a timer, I have to use another <code>MVar</code> (which is an ugly solution IMHO) to hold the number of correct answers because the thread could be killed at any time. Is it possible to stop recursion somehow when the thread got killed to return the partial result?</p>
<p>Code for the final solution:</p>
<pre><code>module Main where
import Lib
import System.IO
import Text.ParserCombinators.Parsec (parseFromFile)
import Data.CSV (csvFile)
import Control.Applicative (liftA2)
import Options.Applicative
import Data.Semigroup ((<>))
import Control.Concurrent.MVar
import Control.Exception
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad (when)
data Options = Options {inputFile :: String, time :: Int}
options :: Parser Options
options = Options
<$> strOption
(long "csv-file" <> value "problems.csv")
<*> option auto
(long "time" <> value 30)
main :: IO ()
main = do
Options {inputFile = file, time = t} <- execParser $ info options briefDesc
result <- parseFromFile csvFile file
case result of
Left e -> putStrLn ("CSV parse error: " ++ show e)
Right lines -> play lines t
play :: [[String]] -> Int -> IO ()
play lines time = do
putStrLn $ "Total number of questions is " ++ (show . length) lines
waitAnyKey
done <- newEmptyMVar
correct <- newMVar 0
questionsT <- forkIO $ do
askQuestions (map (\[q, a] -> ask q a) lines) done correct
putMVar done True
timerT <- forkIO $ do
threadDelay $ time * 10^6
putStrLn "\nTimes is out"
putMVar done True
takeMVar done
throwTo questionsT ThreadKilled
throwTo timerT ThreadKilled
c <- takeMVar correct
putStrLn $ "\nNumber of correct answers is " ++ show c
waitAnyKey :: IO ()
waitAnyKey = do
hSetBuffering stdin NoBuffering
putStrLn "Hit any key when you get ready"
getChar
putChar '\b'
hSetBuffering stdin LineBuffering
askQuestions :: [IO Bool] -> MVar Bool -> MVar Integer -> IO ()
askQuestions [] done correct = putMVar done True
askQuestions (act:xs) done correct = do
c <- act
when c $ modifyMVar_ correct $ \ v -> return (v + 1)
askQuestions xs done correct
type Question = String
type Answer = String
ask :: Question -> Answer -> IO Bool
ask q a = do
putStr (q ++ "? ")
hFlush stdout
userAnswer <- getLine
return (userAnswer == a)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-11T06:28:43.397",
"Id": "488390",
"Score": "0",
"body": "A basic recommendation is to use the async library to synchronize threads instead of explicit `MVar`s."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T08:59:24.147",
"Id": "249024",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Solution for Gophercises Quiz game in Haskell"
}
|
249024
|
<p>This is exercise 3.1.39. from the book <em>Computer Science An Interdisciplinary Approach</em> by Sedgewick & Wayne:</p>
<blockquote>
<p>Write a program that takes the name of an image file as a command-line
argument and applies a glass filter: set each pixel p to the color of
a random neighboring pixel (whose pixel coordinates both differ from
p’s coordinates by at most 5).</p>
</blockquote>
<p>Here is my program:</p>
<pre><code>import java.awt.Color;
public class test
{
public static int[] chooseRandomNeighbor(int i, int j)
{
int[] chosenNeighbor = new int[2];
double r = Math.random();
if (r < 1.0/8.0)
{
chosenNeighbor[0] = i-1;
chosenNeighbor[1] = j-1;
}
else if (r < 2.0/8.0)
{
chosenNeighbor[0] = i-1;
chosenNeighbor[1] = j;
}
else if (r < 3.0/8.0)
{
chosenNeighbor[0] = i-1;
chosenNeighbor[1] = j+1;
}
else if (r < 4.0/8.0)
{
chosenNeighbor[0] = i;
chosenNeighbor[1] = j+1;
}
else if (r < 5.0/8.0)
{
chosenNeighbor[0] = i+1;
chosenNeighbor[1] = j+1;
}
else if (r < 6.0/8.0)
{
chosenNeighbor[0] = i+1;
chosenNeighbor[1] = j;
}
else if (r < 7.0/8.0)
{
chosenNeighbor[0] = i+1;
chosenNeighbor[1] = j-1;
}
else if (r < 8.0/8.0)
{
chosenNeighbor[0] = i;
chosenNeighbor[1] = j-1;
}
return chosenNeighbor;
}
public static Picture filter(Picture picture)
{
int width = picture.width();
int height = picture.height();
Picture filteredPicture = new Picture(width,height);
// the following four for-loops make the dead frame
for (int row = 0; row < height; row++)
{
Color color = picture.get(0,row);
filteredPicture.set(0,row,color);
}
for (int row = 0; row < height; row++)
{
Color color = picture.get(width-1,row);
filteredPicture.set(width-1,row,color);
}
for (int col = 0; col < width; col++)
{
Color color = picture.get(col,0);
filteredPicture.set(col,0,color);
}
for (int col = 0; col < width; col++)
{
Color color = picture.get(col,height-1);
filteredPicture.set(col,height-1,color);
}
// the real filtering takes place here
for (int col = 1; col < width-1; col++)
{
for (int row = 1; row < height-1; row++)
{
int[] chosenNeighbor = chooseRandomNeighbor(row,col);
Color color = picture.get(chosenNeighbor[1],chosenNeighbor[0]);
filteredPicture.set(col,row,color);
}
}
return filteredPicture;
}
public static void main(String[] args)
{
Picture picture = new Picture(args[0]);
Picture filteredPicture = filter(filter(filter(filter(picture))));
filteredPicture.show();
}
}
</code></pre>
<p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/Picture.html" rel="nofollow noreferrer">Picture</a> is a simple API written by the authors of the book. I checked my program and it works. Here is one instance of it:</p>
<p>Input (picture of James McAvoy taken from <a href="https://en.wikipedia.org/wiki/James_McAvoy#/media/File:James_McAvoy_by_Gage_Skidmore_2.jpg" rel="nofollow noreferrer">Wikipedia</a> who played in the movie <a href="https://en.wikipedia.org/wiki/Glass_(2019_film)" rel="nofollow noreferrer">Glass</a>):</p>
<p><a href="https://i.stack.imgur.com/PD8Io.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PD8Io.jpg" alt="enter image description here" /></a></p>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/aSbVq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aSbVq.jpg" alt="enter image description here" /></a></p>
<p>Is there any way that I can improve my program?</p>
<p>Thanks for your attention.</p>
|
[] |
[
{
"body": "<p>Interesting exercise and nice implementation, few suggestions on my side:</p>\n<ul>\n<li>The method <code>chooseRandomNeighbor</code> is only used by <code>filter</code>, so it can be set to <code>private</code></li>\n<li>The name <code>filter</code> is too general for a method, a better name might be <code>applyGlassFilter</code></li>\n<li>In Java the name of a class starts with a capital letter</li>\n</ul>\n<h2>Optimization</h2>\n<blockquote>\n<p>random neighboring pixel (whose pixel coordinates both differ from p’s\ncoordinates by at most 5).</p>\n</blockquote>\n<p>The method <code>chooseRandomNeighbor</code> picks an adjacent random neighbor (which differ by at most 1) and then gets called 4 times. That implies creating 4 full images in memory. Wouldn't be better to directly pick a neighbor with maximum distance 5?</p>\n<p>To do that the method <code>chooseRandomNeighbor</code> needs to accept the width or height:</p>\n<pre><code>int neighborColIndex = chooseRandomNeighbor(col,width);\nint neighborRowIndex = chooseRandomNeighbor(row,height);\n</code></pre>\n<p>And this is <code>chooseRandomNeighbor</code> refactored:</p>\n<pre><code>private static int chooseRandomNeighbor(int index, int max) {\n // Random delta between -5 and +5\n int randomDelta = (int) ((Math.random() * (10)) - 5);\n // Add delta to index without overflowing the limit\n int neighborIndex = (index + randomDelta) % max;\n // If index is negative return 0\n return neighborIndex < 0 ? 0 : neighborIndex;\n}\n</code></pre>\n<p>Now the method <code>filter</code> can be called only once and only the new image will be created in memory.</p>\n<p><strong>Side note</strong>: you are getting better and better, keep up the good work!</p>\n<h2>Code Refactored</h2>\n<pre><code>public class Test {\n \n public static Picture applyGlassFilter(Picture inputPicture) {\n int width = inputPicture.width();\n int height = inputPicture.height();\n Picture outputPicture = new Picture(width, height);\n for (int col = 0; col < width; col++) {\n for (int row = 0; row < height; row++) {\n int neighborColIndex = chooseRandomNeighbor(col,width);\n int neighborRowIndex = chooseRandomNeighbor(row,height);\n Color c = inputPicture.get(neighborColIndex,neighborRowIndex);\n outputPicture.set(col, row, c);\n }\n }\n return outputPicture;\n }\n \n private static int chooseRandomNeighbor(int index, int max) {\n // Random delta between -5 and +5\n int randomDelta = (int) ((Math.random() * (10)) - 5);\n // Add delta to index without overflowing the limit\n int neighborIndex = (index + randomDelta) % max;\n // If index is negative return 0\n return neighborIndex < 0 ? 0 : neighborIndex;\n }\n \n public static void main(String[] args) {\n Picture inputPicture = new Picture(args[0]);\n Picture outputPicture = applyGlassFilter(inputPicture);\n outputPicture.show();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T19:15:02.220",
"Id": "488044",
"Score": "1",
"body": "Thank you very much for the answer. Also appreciate the \"side note\". It's nice to have feedback sometimes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T15:32:46.157",
"Id": "249040",
"ParentId": "249028",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "249040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T10:31:18.507",
"Id": "249028",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Implementation of glass filter for images"
}
|
249028
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.