body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>My script works but I just want to know how I can protect myself from SQL injection with Procedural Oriented MySQLi. Most of the tutorials are about Object-Oriented MySQLi and I'm not familiar with it and don't want to have both Procedural and OO MySQLi in the same script. I have a lot more PHP files. I also do know how to protect against SQL injections but not with procedural style. I know that OO is more useful and A LOT better but as I said I'm not familiar with it. Any help would be appreciated but preferably Procedural Oriented MySQLi.</p> <p>PHP</p> <pre><code>&lt;?php session_start(); $link = mysqli_connect(&quot;****&quot;, &quot;****&quot;, &quot;****&quot;, &quot;****&quot;); if(mysqli_connect_error()) { die(&quot;Couldn't connect to the database. try again later.&quot;); } $query = &quot;SELECT * FROM `users`&quot;; if($result = mysqli_query($link, $query)) { $row = mysqli_fetch_array($result); } $signupButton = &quot;&quot;; $username = &quot;&quot;; $password = &quot;&quot;; $termsandconditions = &quot;&quot;; $payment = &quot;&quot;; $creatorAccount = &quot;&quot;; if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) { if(isset($_POST['username'])) { $username = signupform_input($_POST[&quot;username&quot;]); } if(isset($_POST['password'])) { $password = signupform_input($_POST[&quot;password&quot;]); } if(isset($_POST['signupButton'])) { $signupButton = signupform_input($_POST[&quot;signupButton&quot;]); } if(isset($_POST['termsandconditions'])) { $termsandconditions = signupform_input($_POST[&quot;termsandconditions&quot;]); } if(isset($_POST['payment'])) { $payment = signupform_input($_POST[&quot;payment&quot;]); } if(isset($_POST['creatorAccount'])) { $createrAccount = signupform_input($_POST[&quot;creatorAccount&quot;]); } } function signupform_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $usernameError = &quot;&quot;; $passwordError = &quot;&quot;; $termsandconditionsError = &quot;&quot;; $error = &quot;&quot;; $insertPlan = &quot;&quot;; $updatePassword = &quot;&quot;; $hash = &quot;&quot;; $one = &quot;&quot;; $paymentError = &quot;&quot;; if ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) { if (empty($_POST[&quot;username&quot;])) { $usernameError = &quot;Username is required.&quot;; echo $usernameError; } else { $username = signupform_input($_POST[&quot;username&quot;]); } if (empty($_POST[&quot;password&quot;])) { $passwordError = &quot; Password is required.&quot;; echo $passwordError; } else { $password = signupform_input($_POST[&quot;password&quot;]); $updatePassword = signupform_input($_POST[&quot;password&quot;]); } if(isset($_POST['loginActive'])) { if($_POST['loginActive'] == &quot;0&quot; &amp;&amp; $usernameError == &quot;&quot; &amp;&amp; $passwordError == &quot;&quot; &amp;&amp; $termsandconditionsError == &quot;&quot;) { $query = &quot;SELECT * FROM users WHERE BINARY username = '&quot;. mysqli_real_escape_string($link, $_POST['username']).&quot;' LIMIT 1&quot;; $result = mysqli_query($link, $query); if(mysqli_num_rows($result) &gt; 0) { $error = &quot;That username is already taken.&quot;; echo $error; } else { $one = &quot;1&quot;; $hash = password_hash($updatePassword, PASSWORD_DEFAULT); $insertPlan = $_SESSION['playerPlan']; echo &quot;&lt;p style='color: green'&gt;Hi&lt;/p&gt;&quot;; $query = &quot;INSERT INTO `users` (`username`, `password`, `plan`, `creatorPlan`) VALUES ('&quot;. mysqli_real_escape_string($link, $_POST['username']).&quot;', '&quot;. mysqli_real_escape_string($link, $hash).&quot;', '&quot;. mysqli_real_escape_string($link, $insertPlan).&quot;', '&quot;. mysqli_real_escape_string($link, $one).&quot;')&quot;; mysqli_query($link, $query); $_SESSION['id'] = mysqli_insert_id($link); } } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T02:10:56.903", "Id": "504092", "Score": "1", "body": "You must never sanitize a user's password. Why are you checking `if ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {` twice? What if the submitted username is 10 spaces (no visible characters)? Why `BINARY`? I recommend prepared statements; forget those old escaping techniques. `$row = mysqli_fetch_array($result);` is going to keep overwriting itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T02:17:11.100", "Id": "504094", "Score": "0", "body": "Why are you declaring SELECTing the whole table to begin with? Switching from `mysqli`'s procedural syntax to its OO syntax is not a hard task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T03:31:09.977", "Id": "504096", "Score": "0", "body": "The thing is that I'm not familiar with OO syntax and I learned MySQL the procedural way" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T03:32:18.867", "Id": "504097", "Score": "0", "body": "I originally learned the procedural way, then I taught myself the OO way. I can tell you from experience that the differences are not many and the benefits are several." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T03:36:29.667", "Id": "504098", "Score": "0", "body": "What are some benefits?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T03:37:50.370", "Id": "504099", "Score": "1", "body": "Less verbose code, more professional/modern looking code, and it puts you on the path to using more object oriented syntax elsewhere in your code (where it is appropriate)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T03:38:48.087", "Id": "504100", "Score": "0", "body": "So if I switch my queries right now would I just have to replace underscores with -> or what?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T05:01:32.223", "Id": "504101", "Score": "3", "body": "pretty much yes. it's literally changing underscores to arrows and getting rid of useless repetitions when the word mysqli or stmt is typed twice. nothing really to talk about" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T00:21:59.127", "Id": "504193", "Score": "0", "body": "Well then is there a way to protect me with SQL injections with the code I have right now(procedural)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T01:12:30.010", "Id": "504199", "Score": "0", "body": "I don't think I'll want to convert this procedural mysqli into object-oriented mysqli because I really want to move on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T01:57:09.937", "Id": "504200", "Score": "0", "body": "How about I just have procedural for variables and links and other stuff that's not revolving queries and use OO for queries. It would work but look disorganize but it doesn't matter because nobody else can see my PHP and sql." } ]
[ { "body": "<h2>Procedural Prepared Query Structure</h2>\n<p>This is the typical layout of a prepared query, in a procedural setting:</p>\n<pre><code>$sql = &quot;...&quot;;\n$query = mysqli_prepare($mysqli, $sql);\nmysqli_stmt_bind_param($query, &quot;si&quot;, $stringValue, $integerValue);\nmysqli_stmt_execute($query);\n</code></pre>\n<p>The key points are that you:</p>\n<ol>\n<li>Don't need to carry out your own custom sanitization or use functions like <code>mysqli_real_escape_string</code></li>\n<li>Use <code>mysqli_prepare</code> instead of <code>mysqli_query</code></li>\n<li>Bind the parameters based on whether they are <code>string</code> or <code>integer</code></li>\n<li>Exceute the query after building it with <code>prepare</code> and <code>bind</code></li>\n</ol>\n<h2>Updating your code</h2>\n<p><strong><code>SELECT</code> Query</strong></p>\n<pre><code>$sql = &quot;\n SELECT *\n FROM users\n WHERE username = ?\n&quot;; \n\n$query = mysqli_prepare($link, $sql);\nmysqli_stmt_bind_param($query, &quot;s&quot;, $_POST[&quot;username&quot;]);\nmysqli_stmt_execute($query);\n$result = mysqli_stmt_get_result($query);\nif (mysqli_num_rows($result)) {\n $error = &quot;That username is already taken.&quot;;\n echo $error;\n}\n</code></pre>\n<p><strong><code>INSERT</code> Query</strong></p>\n<p>Note: this assumes that <code>$insertPlan</code> and <code>$one</code> are always integers.</p>\n<pre><code>$sql = &quot;\n INSERT INTO users\n (username, password, plan, creatorPlan)\n VALUES\n (?, ?, ?, ?)\n&quot;;\n\n$query = mysqli_prepare($link, $sql);\nmysqli_stmt_bind_param($query, &quot;ssii&quot;, $_POST[&quot;username&quot;], $hash, $insertPlan, $one);\nmysqli_stmt_execute($query);\n$_SESSION[&quot;id&quot;] = mysqli_insert_id($link);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T14:12:34.317", "Id": "505075", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/119630/discussion-on-answer-by-steven-my-script-inserts-users-into-a-database-and-hashe)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T02:38:55.903", "Id": "255534", "ParentId": "255485", "Score": "1" } }, { "body": "<h1>Overview</h1>\n<h2>OOP vs Procedural <code>mysqli</code></h2>\n<p>Firstly, it's important to note that the difference between the two methods is the way in which you, as a developer, interact with them. They both <em>use</em> use OOP one just hides it behind a veil of <em>procedural functions</em>. In fact, you can mix and match:</p>\n<pre><code>// OOP\n$query = $mysqli-&gt;query(&quot;SELECT * FROM table&quot;);\nwhile( $row = $query-&gt;fetch_assoc()){\n print_r($row);\n}\n\n// Procedural\n$query = mysqli_query($mysqli, &quot;SELECT * FROM table&quot;);\nwhile( $row = mysqli_fetch_assoc($query)){\n print_r($row);\n}\n\n// Combined\n$query = mysqli_query($mysqli, &quot;SELECT * FROM table&quot;);\nwhile( $row = $query-&gt;fetch_assoc()){\n print_r($row);\n}\n</code></pre>\n<p>Secondly, reference your concern about having procedural and OOP in the same code: there's nothing wrong with this. In fact I would argue it's a good thing. Code should be maintained, optimised, and refactored; the process of which takes time and can be done in small chunks. Today you improve your registration system, tomorrow maybe the login(?), and by next year you'll have upgraded everything and be ready to start all over again with PHP 8.x!</p>\n<p>The reality is that <em>best practice</em>, available functionality, etc. is constantly changing and your code should change to reflect this.</p>\n<p>Having said all that Procedural vs OOP is a style choice. Use what you prefer - but know that if you use procedural you're making life <em>slightly</em> more difficult for yourself and anyone who inherits your code base.</p>\n<h2>Error handling</h2>\n<p><strong>General</strong></p>\n<p>You initialise a whole bunch of individual error variables in the form <code>$errorName = &quot;&quot;;</code>. The problem here is that now you have to remember them all to use them! Additionally although you've initialised the variables you only &quot;set&quot; them later on, so what's the point?</p>\n<p>If you must do it this way then I suggest you at least use an array so that all <code>errors</code> are grouped together and can be passed as a whole:</p>\n<pre><code>// Initialise the error array\n$errors = [];\n\n// Check username is present and add error message if necessary\nif(!$username){\n $errors[] = &quot;Username required&quot;;\n}\n\n// Check for any errors\nif(count($errors)){\n // Some errors were found...\n} else {\n // Error free so far...\n}\n</code></pre>\n<p>Alternatively, if you're interested in learning more about OOP implement a basic error reporting class which you can re-use across your webpages.</p>\n<p><strong>MySQLi</strong></p>\n<p>You don't appear to have turned on error reporting for <code>mysqli</code>; which you should aim to do so that you can catch any errors/bugs down the road.</p>\n<h2>Prepared Statements</h2>\n<p>There's really no excuse not to be using prepared statements for SQL queries. There are a number of benefits for both security, simplicity, and readability: with very few downsides.</p>\n<pre><code>$sql = &quot;SELECT * FROM user WHERE username = &quot; . sanitizeString($username) . &quot; AND status = &quot; . sanitizeInteger($status);\n\n// Becomes...\n\n$sql = &quot;SELECT * FROM user WHERE username = ? AND status = ?&quot;;\n</code></pre>\n<p>It's a regular occurrence that people are advised to move toward <code>PDO</code> and ditch <code>mysqli</code> entirely as well; for comparison:</p>\n<pre><code>// Prepared statement with Procedural mysqli\n$query = mysqli_prepare($mysqli, $sql);\nmysqli_stmt_bind_param($query, &quot;si&quot;, $username, $status);\nmysqli_stmt_execute($query);\n$result = mysqli_stmt_get_result($query);\n$row = mysqli_fetch_assoc($result);\n\n// Preapred statement with OOP mysqli\n$query = $mysqli-&gt;prepare($sql);\n$query-&gt;bind_param(&quot;si&quot;, $username, $status);\n$query-&gt;execute();\n$result = $query-&gt;get_result();\n$row = $result-&gt;fetch_assoc();\n\n// Prepared statement with PDO\n$query = $pdo-&gt;prepare($sql);\n$query-&gt;execute([$username, $status]);\n$row = $query-&gt;fetch(PDO::FETCH_ASSOC);\n</code></pre>\n<p>Again, there's no harm in having <code>PDO</code> and <code>mysqli</code> in the same code... Eventually you'll refactor all of the code and it will be uniform.</p>\n<p>Changing from one to the other doesn't take as long as you might think either. A number of the methods are similarly named: after all, for a query/result to work, with any method, you have to input and output the same information.</p>\n<h2>Misc. Points</h2>\n<p><strong>Typos</strong></p>\n<p>You have an error in one of your variable names:</p>\n<pre><code> $createrAccount = signupform_input($_POST[&quot;creatorAccount&quot;]);\n ^\n</code></pre>\n<p><strong>Code formatting</strong></p>\n<p>At first glance your <em>generous</em> use of <code>if</code> statements look as though they are all nested inside one another... They aren't, but having the braces <code>{}</code> positioned as you do just makes it a bit awkward to read, stick to the standard:</p>\n<pre><code>if (condition) {\n // Do something...\n} elseif (condition) {\n // Do something else...\n} else {\n // Do something else...\n}\n</code></pre>\n<p>You have a few <strong>really</strong> long lines in your code... This makes it confusing to read, especially if the lines break at non-optimal places. You might consider intentionaly breaking lines to make it clearer:</p>\n<pre><code>INSERT INTO `users` (`username`, `password`, `plan`, `creatorPlan`) VALUES ('&quot;. mysqli_real_escape_string($link, $_POST['username']).&quot;', '&quot;. mysqli_real_escape_string($link, $hash).&quot;', '&quot;. mysqli_real_escape_string($link, $insertPlan).&quot;', '&quot;. mysqli_real_escape_string($link, $one).&quot;')\n\n// Becomes...\n\nINSERT INTO `users`\n (`username`, `password`, `plan`, `creatorPlan`)\nVALUES (\n '&quot;. mysqli_real_escape_string($link, $_POST['username']).&quot;',\n '&quot;. mysqli_real_escape_string($link, $hash).&quot;',\n '&quot;. mysqli_real_escape_string($link, $insertPlan).&quot;',\n '&quot;. mysqli_real_escape_string($link, $one).&quot;'\n)\n</code></pre>\n<p><strong>Code Placement</strong></p>\n<p>It is almost always preferred to have your functions defined at the top of the document. If you define them <em>somewhere</em> in the middle of the document they get lost. I, for instance, had no idea what <code>signupform_input</code> did until stumbling across it.</p>\n<p><strong>Variable names</strong></p>\n<p><em><code>$one</code> what is that? Aside from the fact that you set it to <code>1</code> I have absolutely no idea!</em></p>\n<p>It's good practice to make your variable and function names meaningful: ideally so that other people (and yourself when you come back to the code in a couple of months) understand what they do/contain/mean wihtout having to try and figure out the code or looking around the document. In your case names like <code>$username</code> and <code>$password</code> are obvious but names like <code>$link</code> can be ambiguous. Much better to use names which makes it clear what they are to anyone reading the code. For example:</p>\n<pre><code>$link &gt;&gt;&gt; $mysqli // Because it's a mysqli object\nsignupform_input(...) &gt;&gt;&gt; sanitizeInput(...) // Because the function sanitizes the input\n</code></pre>\n<p>Bringing this briefly back to <em>errors</em>: you have named a whole bunch of errors reasonably well (<code>$usernameError</code>, <code>$termsandcontitionsError</code>) and then you have a random <code>$error</code>. To me that looks like a <em>general error condition</em> but in reality it is actually there to note when the username already exists in the database. Changing it's name would make that much clearer.</p>\n<p>Other than that you should be aware that you re-use a few variable names. Especially when it come to queries and result sets. There's potential for confusion here and, if the code were more entangled/complex, there's the possibility you could overwrite something prematurely. If the <em>bland names</em> (e.g. <code>$query</code> and <code>$result</code>) were inside of a function then it doesn't matter so much (assuming they're used once only) because readers are already aware of scope; but having multiple occurrences and overwrites in any one body of code is not a good idea.</p>\n<hr />\n<h1>Updates and Changes</h1>\n<h2>Redundant Code</h2>\n<p>There is a significant percentage of your code that, well, doesn't seem to do anything <strong>or</strong> is repeated later in the code...</p>\n<p>This query just executes and does nothing with the result set:</p>\n<pre><code>$query = &quot;SELECT * FROM `users`&quot;;\n\nif($result = mysqli_query($link, $query)) {\n\n $row = mysqli_fetch_array($result);\n\n}\n</code></pre>\n<p>Anything to do with <code>$creatorAccount</code>, <code>$payment</code> &amp; <code>$signupButton</code> is halted after the input is <em>sanitized</em>. Which means the related errors are also, kind of, pointless?</p>\n<p><em>Terms and Conditions</em> has a few variables (including error variables) and <code>if</code> statements but it never actually does anything: the code never actually checks whether T&amp;C are set.</p>\n<p>Every sigle input is <em>sanitized</em> with <code>signupform_input</code> at least twice, for example:</p>\n<pre><code>if(isset($_POST['username'])) {\n $username = signupform_input($_POST[&quot;username&quot;]); \n}\n\n\n// And...\n\nif (empty($_POST[&quot;username&quot;])) {\n $usernameError = &quot;Username is required.&quot;;\n echo $usernameError;\n} else {\n $username = signupform_input($_POST[&quot;username&quot;]);\n}\n</code></pre>\n<p>Additionally, you don't actually use the <em>sanitized</em> <code>$username</code> in either of your queries! You put it through mysqli's escape function instead.</p>\n<pre><code>mysqli_real_escape_string($link, $_POST['username'])\n</code></pre>\n<p>You don't need to use a <code>LIMIT</code> in your query when you simply are checking if there are any records. Not least becasue there should only ever be a maximum of one match.</p>\n<p>There's no need to check the <code>REQUEST_METHOD</code> because you explicitly get the <code>POST</code> variables. There's definitely no need to check it twice!</p>\n<p>I'm not sure (but concerned) with regards to what <code>$_POST[&quot;loginActive&quot;]</code> is actually referencing? If it's checking that the user is logged on, shouldn't that be some <code>SESSION</code> variable anyway?</p>\n<p>Your banks of <code>if</code> statements can largely be reduced or removed entirely:</p>\n<pre><code>if(isset($_POST['username'])) {\n $username = signupform_input($_POST[&quot;username&quot;]); \n}\n\n// Becomes...\n\n$username = signupform_input($_POST[&quot;username&quot;] ?? null);\n</code></pre>\n<p>Some of your <em>larger</em> <code>if</code> statements just aren't needed. For example:</p>\n<pre><code>if(isset($_POST['loginActive'])) // Is basically (or could be) redone in the next line of code\n\nif ($_SERVER[&quot;REQUEST_METHOD&quot;] == &quot;POST&quot;) // As already covered\n</code></pre>\n<p>I'm not sure what the point in having <code>$password</code>, <code>$updatePassword</code>, and <code>$hash</code> is?</p>\n<p>Your comparisons are <em>odd</em>. You frequently use the <code>==</code> comparison operator in your <code>if</code> statements. Nothing wrong with that; however, you then do things like:</p>\n<pre><code>$_POST['loginActive'] == &quot;0&quot; &amp;&amp; $usernameError == &quot;&quot;\n\n// However, that is effectively the same thing...\n\n&quot;&quot; == &quot;0&quot; == 0 == false == null\n\n// You may as well just do...\n\n!$_POST['loginActive'] &amp;&amp; !$usernameError\n</code></pre>\n<h2>Missing Code</h2>\n<p><strong>Data Validation</strong></p>\n<p>I would suggest that you should be scrapping your function <code>signupform_input</code> for a few reasons:</p>\n<ol>\n<li>We don't want to inadvertently <em>edit</em> people's passwords\n<ul>\n<li><em>John</em> always starts and finishes his password with a <code>space</code>; now his password is 2 characters shorter!</li>\n<li><em>Sophie</em> uses a random password generator which includes <code>\\</code>; now her password is shorter as well!</li>\n<li>Bear in mind that if you edit the password on registration you then have to be certain to do the same edits on loin as well. If you don't Sophie and John won't be able to log on!</li>\n</ul>\n</li>\n<li>It is typical for sanitizing functions like <code>htmlspecialchars</code> to be carried out on output and the <em>raw data</em> be stored in the database</li>\n<li>The function is solely about sanitizing data and not validating it</li>\n</ol>\n<p>However, you should implement a couple of new functions</p>\n<ol>\n<li>To validate the username\n<ul>\n<li>For example: to make sure it only contains letters and numbers (or whatever characters you so allow)</li>\n</ul>\n</li>\n<li>To validate the password\n<ul>\n<li>For example: to make sure that it is 8 characters long and contains at least one number and one letter etc.</li>\n</ul>\n</li>\n</ol>\n<p><strong>mysqli Error Reporting</strong></p>\n<p>You should add error reporting for <code>mysqli</code> so that you catch and report errors that occur in an appropriate manner:</p>\n<pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n</code></pre>\n<hr />\n<h1>Updated Code</h1>\n<h2>Notes</h2>\n<p>I'm not 100% sure on a few aspects of your so bear in mind:</p>\n<ol>\n<li><code>$_POST[&quot;loginActive&quot;]</code>\n<ul>\n<li>I'm not sure what this is and am a little worried it's some kind of &quot;I'm logged on&quot; marker?</li>\n<li>Have removed from the below code for the time being...</li>\n</ul>\n</li>\n<li><code>$_POST[&quot;termsandconditions&quot;]</code>\n<ul>\n<li>I assume this returns a <code>1</code> if it has been <em>checked</em>?</li>\n</ul>\n</li>\n<li>Any other code highlighted earlier to be <em>redundant</em> has been removed</li>\n<li>Some basic rules for username and password validation have been incorporated</li>\n<li>The below code uses OOP methodology</li>\n<li>Error messages are printed after the execution of the code, not during.</li>\n<li>The validation functions are deliberately simple - I don't know what your <em>rules</em> are</li>\n<li>I've added an anonymous class to handle error reporting; it's something you can expand on should you so wish.</li>\n<li>The logic below consists of approximately half the lines of code of the original\n<ul>\n<li>Not including the functions and class: because they are new functionality</li>\n</ul>\n</li>\n</ol>\n<h2>Code</h2>\n<p><em><strong>Disclaimer:</strong> Please note that this code is untested</em></p>\n<pre><code>&lt;?\n\nsession_start();\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli(&quot;****&quot;, &quot;****&quot;, &quot;****&quot;, &quot;****&quot;);\n\n\n$error = new class {\n public array $active = [];\n\n private array $message = [\n &quot;usernameRequired&quot; =&gt; &quot;Username is required.&quot;,\n &quot;usernameTaken&quot; =&gt; &quot;That username is already taken.&quot;,\n &quot;passwordRequired&quot; =&gt; &quot;Password is required.&quot;,\n &quot;termsRequired&quot; =&gt; &quot;You must accept the T&amp;Cs to create an account&quot;,\n ];\n\n public function count() : int\n {\n return count($this-&gt;active);\n }\n \n public function throw($messageid) : void\n {\n $this-&gt;active[] = $this-&gt;message[$messageid];\n }\n\n public function __toString() : string\n {\n $errorMessages = '';\n foreach($this-&gt;active as $error){\n $errorMessages .= $error . &quot;&lt;br&gt;&quot;;\n }\n return $errorMessages;\n }\n};\n\nfunction validateUsername(?string $username) : ?string\n{\n return preg_match(&quot;/^\\w+$/&quot;, $username) ? $username : null;\n}\n\nfunction validatePassword(?string $password) : ?string\n{\n return preg_match(\n &quot;\n /\n (?=.*[a-z])\n (?=.*[A-Z])\n (?=.*[0-9])\n (?=.*[!£$%&amp;@#])\n ^(.{8,})$\n /x\n &quot;, $password\n ) ? password_hash($password, PASSWORD_DEFAULT) : null;\n}\n\n$username = validateUsername($_POST[&quot;username&quot;] ?? null);\n$password = validatePassword($_POST[&quot;password&quot;] ?? null); \n$terms = (int) ($_POST[&quot;termsandconditions&quot;] ?? null);\n\n$insertPlan = $_SESSION['playerPlan'] ?? null;\n$creatorPlan = 1;\n\nif (!$username) {\n $error-&gt;throw(&quot;usernameRequired&quot;);\n}\nif (!$password) {\n $error-&gt;throw(&quot;passwordRequired&quot;);\n}\nif ($terms !== 1) {\n $error-&gt;throw(&quot;termsRequired&quot;);\n}\n\nif ($error-&gt;count() === 0) {\n $usernameSql = &quot;\n SELECT *\n FROM users \n WHERE username = ?\n &quot;;\n $usernameQuery = $mysqli-&gt;prepare($usernameSql);\n $usernameQuery-&gt;bind_param(&quot;s&quot;, $username);\n $usernameQuery-&gt;execute();\n $usernameQuery-&gt;store_result();\n\n if ($query-&gt;num_rows) {\n $error-&gt;throw(&quot;usernameTaken&quot;);\n } else {\n $insertSql = &quot;\n INSERT INTO users\n (username, password, plan, creatorPlan)\n VALUES \n (?, ?, ?, ?)\n &quot;;\n $insertQuery = $mysqli-&gt;prepare($insertSql);\n $insertQuery-&gt;bind_param(&quot;ssss&quot;, $username, $password, $insertPlan, $creatorPlan);\n $insertQuery-&gt;execute();\n $_SESSION['id'] = $mysqli-&gt;insert_id ?? null;\n echo &quot;Success!&quot;;\n }\n}\n\n// Output any errors\necho $error;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T02:51:29.203", "Id": "255536", "ParentId": "255485", "Score": "3" } } ]
{ "AcceptedAnswerId": "255536", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T01:37:19.247", "Id": "255485", "Score": "-1", "Tags": [ "php", "sql", "mysql", "mysqli", "sql-injection" ], "Title": "My Script Inserts users into a database and hashes the password, I need to know how to prevent SQL injection with Procedural-Oriented MySQLi" }
255485
<p>I am developing a multistep wizard for complicated forms in our app, in a react-redux context, with formik. There is one such wizard already in the app, but it is not reusable. I am in the process of making another one, and with several others on the horizon in the workload, I want to create a pattern that is reusable. None of the forms in the app manage their state in redux - they all manage their state internally. I have a <code>MultistepWizard</code> component:</p> <pre class="lang-js prettyprint-override"><code>const MultistepWizard = props =&gt; { const { context, open, onClose, steps, menuClasses } = props; const { currentStep } = context; return ( &lt;Dialog id={id} open={open} onClose={onClose} &gt; &lt;DialogContent className={clsx(classes.content, classes.root)}&gt; &lt;nav className={clsx(classes.leftPanel, menuClasses?.container)}&gt; &lt;WizardMenu context={context} steps={steps} menuClasses={menuClasses} /&gt; &lt;/nav&gt; &lt;section className={classes.mainContent}&gt; &lt;CloseButton className={classes.closeIcon} onClick={handleClose} /&gt; {steps[currentStep].screen} &lt;/section&gt; &lt;/DialogContent&gt; &lt;/Dialog&gt; ); }; </code></pre> <p>You can see this is a very generic component (simplified from the original code). It can be heavily customized through the props, namely through the <code>context</code>, <code>steps</code>, and <code>menuClasses</code> props, and it will then manage displaying the menu and the correct screen (which is the main content of a certain step).</p> <p>Rather than have the <code>MultistepWizard</code>'s parent manage the state, I opted to wrap the customized parent in a react context object. In this sense, common state variables and methods can be easily shared between various levels of components without the need for prop drilling. For example, in the wizard I'm working on now:</p> <pre class="lang-js prettyprint-override"><code>const ConfigureUsersWizard = ({ open, handleClose, selectedUsers }) =&gt; { const classes = useStyles(); const menuClasses = useMenuStyles(); const context = useContext(ConfigureUsersWizardContext); // Formik props for all pages of form const formikProps = useFormik({ initialValues, validationSchema }) const onClose = (): void =&gt; { handleClose(); formikProps.resetForm(); }; const configureUsersSteps = [ { label: &quot;Activate&quot;, completeIcon: &lt;Check className={menuClasses.successIcon} /&gt;, screen: &lt;Activate formikProps={formikProps} /&gt; }, { label: &quot;License&quot;, completeIcon: &lt;Check className={menuClasses.successIcon} /&gt;, screen: &lt;License formikProps={formikProps} /&gt; }, { label: &quot;Configure&quot;, completeIcon: &lt;Check className={menuClasses.successIcon} /&gt;, screen: &lt;Configure formikProps={formikProps} /&gt; } ]; return ( &lt;MultistepWizard context={context} open={open} onClose={onClose} steps={provisionDevicesSteps} menuClasses={menuClasses} title={CustomizedTitleComponentHere} /&gt; ); }; const ContextualizedUsersWizard = props =&gt; ( &lt;ConfigureUsersWizardProvider&gt; &lt;ConfigureUsersWizard {...props} /&gt; &lt;/ConfigureUsersWizardProvider&gt; ); export default ContextualizedUsersWizard; </code></pre> <p>So with this pattern, I can customize my menu styles for each multistep wizard (it seems like we don't have a lot of consistency in the designs or functionality of the menus), and I can create each screen as its own component, which can directly pull in the context (or its children and grandchildren can directly pull in the context). In this way, I can create non-generic properties and methods specific to a certain wizard, that still work with the reusable wizard components. The context for my users wizard looks like this:</p> <pre class="lang-js prettyprint-override"><code>export const ConfigureUsersWizardContext = React.createContext(); export const ConfigureUsersWizardProvider: React.FC = ({ children }) =&gt; { // generic methods that will need to be present on every contex // that uses the generic components - enforced with typescript const [currentStep, setStep] = useState(0); const [completedSteps, setCompletedSteps] = useState([false, false, false]); const [disabledSteps, setDisabledSteps] = useState([false, false, false]); const [handleClose, setHandleClose] = useState(() =&gt; (): void =&gt; undefined); // lots of custom logic here specific to this particular wizard return ( &lt;ConfigureUsersWizardContext.Provider value={{ currentStep, setStep, completedSteps, setCompletedSteps, disabledSteps, handleClose, setHandleClose }} &gt; {children} &lt;/ConfigureUsersWizardContext.Provider&gt; ); } </code></pre> <p>In essence, this pattern allows me to keep the state of the multistep wizard centralized in the context, without having to go as far as creating actions/reducers/sagas to connect to the redux store. However, certain aspects of the context's state for this wizard do indeed depend on certain pieces of the store. For example, if all <code>selectedUsers</code> in the store are already activated, the UX team wants that step of the form to be considered 'complete', and the wizard should open to the next step. To accomplish this, in my context provider, I include the following custom logic:</p> <pre class="lang-js prettyprint-override"><code> const selectedUsers = useSelector( state =&gt; state.users.selectedUsers ); useEffect(() =&gt; { // logic here to process selectedUsers // if all selected user already activated: setCompletedSteps([true, false, false]) setStep(1) }, [selectedUsers]); </code></pre> <p>Or if that's not the case, I have another useEffect that listens for the form to be filled out in the activate step, when the api call to responds and populates the store:</p> <pre class="lang-js prettyprint-override"><code> const licensingResults = useSelector( (state: ApplicationState) =&gt; state.devicesPage.deviceProvisioningWizardWindow.licensing.results ); useEffect(() =&gt; { if (activationResults) { const newSteps = [...completedSteps]; newSteps[0] = true; setCompletedSteps(newSteps); } }, [activationResults]); </code></pre> <p>My colleague pointed out to me that this is &quot;wrong.&quot; I agree that having one component derive its state from properties that exist in the store seems redundant, and likely to cause unnecessary rerenders. But the reason I went this route is so that my <code>MultistepWizard</code> only sees <code>currentStep</code> or <code>completedSteps</code> as a prop. I want to extract the logic specific to a wizard to its context provider, and let <code>MultistepWizard</code> and <code>WizardMenu</code> be totally reusable, simply rendering the proper screens and styles based on what the context dictates.</p> <p>However, this pattern does seem to leave me open for many unneecssary rerenders, as some of the components that call <code>useContext(ConfigureUsersWizardContext)</code> will render unecessarily when any value from the context provider changes. For example, I have a <code>Footer</code> component, which is a descendant of the <code>License</code> screen component. In the body of <code>Footer</code>, I call:</p> <pre class="lang-js prettyprint-override"><code> const { currentStep, setStep } = useContext(ProvisioningWizardContext); </code></pre> <p>And now within <code>Footer</code>, I can have buttons that set the current step of the wizard. However, even if <code>completedSteps</code> changes, the whole <code>Footer</code> rerenders, because the context value has changed.</p> <p>Is using a local context object that is only relevant to a given wizard a silly workaround? It is definitely helping me organize all the components and their state for a given wizard. How can I optimize this? Wrap everything in <code>useMemo</code> calls and carefully craft the dependency arrays with values like <code>context.relevantValue</code> and any relevant props? Multistep wizard are tricky, and I'd appreciate any feedback on how I can improve my approach.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T05:22:02.387", "Id": "255489", "Score": "0", "Tags": [ "javascript", "performance", "react.js", "redux" ], "Title": "Creating a reusable multistep wizard with react, redux, and formik" }
255489
<h1>The application</h1> <p>I'm making a small app (currently ~500 lines) to manage and download books and other media items. Each item is uniquely identify by its <code>(downloader, code)</code> tuple and the index (save in a pickled file) contains the title, authors, and tags (e.g. &quot;scfi-fi&quot;, &quot;comedy&quot;) of each item. The &quot;downloader&quot; is a module in a collection of user-made modules to scrape certain pages for metadata (title, authors and tags). For example, the module <code>example_dl</code>, given either the url <code>example.com/book/123</code> or code <code>123</code>, handles scraping <code>example.com</code> for the book with the code/ID of <code>123</code>, namely its metadata and possibly download the book to a directory.</p> <p>The code below contains the dictionary <code>config</code> for global configuration variables (stored in a config file <code>shelf.yaml</code>), a short description of the classes <code>Item</code> and <code>Shelf</code> and the function I'd like to be reviewed, <code>search_item()</code>.</p> <h1>Code</h1> <pre><code>import sys import os import re import argparse import importlib.util import yaml import pickle # Default configurations PATH = os.path.expanduser(&quot;~/.config/shelf&quot;) config = { &quot;config_file&quot;: PATH + &quot;/shelf.yaml&quot;, &quot;index_file&quot;: PATH + &quot;/data/index&quot;, &quot;favorites_file&quot;: PATH + &quot;/data/favorites&quot;, &quot;downloaders_dir&quot;: PATH + &quot;/downloaders&quot;, &quot;data_dir&quot;: PATH + &quot;/data&quot;, &quot;threads&quot;: 10, } class Item: &quot;&quot;&quot;Items stored in the Shelf Attributes: title: title of the media item authors: set of authors tags: set of tags media: media type the item is stored as (e.g. png, md, pdf) &quot;&quot;&quot; title = None authors = None tags = None media = None class Shelf: &quot;&quot;&quot;Shelf containing indexed data of items Attributes: downloaders: a dict of available downloaders index: Shelf indexing containing data about all items saved. Data is read from index file and is as follows: ( (downloader1, code1) : item_1, (downloader2, code2) : item_2 ) &quot;&quot;&quot; global config downloaders = dict() index = dict() favorites = set() verbosity = 0 def search_item( self, title_regex: str, authors: set[str], tags: set[str], blacklist: set[str], broad_search=False, favorites=False, ) -&gt; list[tuple[str, str]]: &quot;&quot;&quot;Search item in index Args: title_regex: regex to search title by authors: set of authors OR comma-separated string tags: set of tags OR comma-separated string broad_search: If False (Default), returns only when *all* tags match. If True, returns when at least 1 tag matches. favorites: only search items in favorties Returns: A 2-tuple containing the downloader and code. For example: (&quot;test_dl&quot;, &quot;test_code&quot;) &quot;&quot;&quot; if self.verbosity &gt;= 2: print( &quot;Searching with:\n&quot; f&quot;\tTitle regex: {title_regex}\n&quot; f&quot;\tAuthors: {authors}\n&quot; f&quot;\tTags: {tags}\n&quot; f&quot;\tBroad search: {broad_search}\n&quot; f&quot;\tFavorites: {favorites}&quot; ) result = None if favorites: # Search in favorites result = self.favorites if self.verbosity &gt;= 2: print(f&quot;Filtered by favorites: {result}&quot;) if title_regex: # Search with title regex result = { (k, v) for (k, v) in self.index if re.match(title_regex, self.index[(k, v)].title) } if self.verbosity &gt;= 2: print(f&quot;Filtered by title regex: {result}&quot;) if authors: # Search by authors (always broad search) if type(authors) == str: authors = set(authors.split(&quot;,&quot;)) if result: result = { (k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors } else: result = { (k, v) for (k, v) in self.index if authors &amp; self.index[(k, v)].authors } if self.verbosity &gt;= 2: print(f&quot;Filtered by authors: {result}&quot;) if tags: # Search by tags if type(tags) == str: tags = set(tags.split(&quot;,&quot;)) if broad_search: # Broad search if result: result = { (k, v) for (k, v) in result if tags &amp; self.index[(k, v)].tags } else: result = { (k, v) for (k, v) in self.index if tags &amp; self.index[(k, v)].tags } if self.verbosity &gt;= 2: print(f&quot;Filtered by broad_search: {result}&quot;) else: # Normal search if result: result = { (k, v) for (k, v) in result if not (tags - self.index[(k, v)].tags) } else: result = { (k, v) for (k, v) in self.index if not (tags - self.index[(k, v)].tags) } if self.verbosity &gt;= 2: print(f&quot;Filtered by broad_search: {result}&quot;) if blacklist: if type(blacklist) == str: blacklist = set(blacklist.split(&quot;,&quot;)) if result: result = { (k, v) for (k, v) in result if not blacklist &amp; self.index[(k, v)].tags } else: result = { (k, v) for (k, v) in self.index if not blacklist &amp; self.index[(k, v)].tags } return result </code></pre> <h1>Description of <code>search_item</code></h1> <p>The function <code>search_item</code> goes runs the <code>index</code> dictionary through 5 filters (kinda): <code>favorites</code>, <code>title_regex</code>, <code>author</code>, <code>tags</code>, and <code>blacklist</code>. The switches available to affect the search are <code>-t TITLE_REGEX</code>, <code>-a AUTHOR</code>, -T <code>TAGS</code>, <code>--broad-search</code>, <code>--favorites</code>, <code>--blacklist</code>.</p> <h2><code>if result</code></h2> <p>I have <code>if result</code> and <code>else</code> in almost every filter to hopefully improve speed and memory usage, since not every filter is required to be used in a single search.</p> <h2><code>favorites</code></h2> <p>The <code>Shelf</code> object has a <code>set</code> of 2-tuples, each tuple being <code>(downloader, code)</code>. Since <code>favorites</code> is a subset of <code>Shelf.index.keys()</code>, I simply copy the entire <code>set</code> of <code>favorites</code> to be further filtered.</p> <h2><code>title_regex</code> and <code>author</code></h2> <p>These 2 are similar in implementation. The only major difference is that <code>title_regex</code> is matched using <code>re.match(user_defined_regex, titles_in_index)</code>, while author is filtered with `author in set_of_authors.</p> <h2><code>tags</code></h2> <p>The <code>--broad-search</code> switch is only used with the <code>search_book</code> function when <code>tags</code> is used, and is ignored otherwise.</p> <h3>Normal Search</h3> <p>In normal search, <em>all</em> of the provided tags (comma-separated) must match the book's tags to show up in the result.</p> <h3>Broad search</h3> <p>In broad search, books show up in the result if <em>at least 1</em> of the provided tags is found in the book's <code>set</code> of tags.</p> <h2><code>blacklist</code></h2> <p>Basically the inverse of broad search.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T07:21:29.567", "Id": "504106", "Score": "4", "body": "Can you include the imports you use please? I see `os` and `re` but I don't want to assume." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T11:03:21.683", "Id": "504127", "Score": "0", "body": "are you sure that in blacklist, `author` is to be matched against `self.index[(k, v)].tags`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T11:16:20.813", "Id": "504130", "Score": "0", "body": "@hjpotter92 Right, it should be `not blacklist & tags`" } ]
[ { "body": "<p>I'm not going too deeply into flow of that solution, but I have some comments. Hopefully it will be useful to you.</p>\n<ol>\n<li>The first thing is that you should definitely refactor <code>search_item</code> by splitting that to smaller functions which will allow for better reading flow, but also it should help with finding code duplicates. Another benefit is that when in smaller functions, it's easier to comment such code (sometimes just by good name, sometimes with proper docstring).</li>\n<li>You have quite a lot of redundant code, like for example</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>result = {\n (k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors\n}\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>result = {\n (k, v) for (k, v) in result if tags &amp; self.index[(k, v)].tags\n}\n</code></pre>\n<p>or even in broader scopes, with whole <code>if result: .. if self.verbosity &gt;= 2: ...</code> sections. Right, there are different attributes like <code>authors</code>, <code>tags</code>, etc., but it should be quite easy handle them especially if you'd split that into smaller functions.</p>\n<ol start=\"3\">\n<li><p>these operations like <code>if tags &amp; self.index[(k, v)].tags</code> are not very obvious. Please document them somewhere to avoid confusions when someone will work with your code in future.</p>\n</li>\n<li><p>you don't need to specify whole tuple in these set comprehensions. That</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code> {(k, v) for (k, v) in result if authors &amp; self.index[(k, v)].authors}\n</code></pre>\n<p>could be rewritten to</p>\n<pre class=\"lang-py prettyprint-override\"><code>{key for key in result if authors &amp; self.index[key].authors}\n</code></pre>\n<p>most likely.</p>\n<ol start=\"5\">\n<li>I bet this is because of that you pasted here only a part of your code, but there you have not used imports (almost all of them).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:04:31.920", "Id": "255623", "ParentId": "255491", "Score": "2" } }, { "body": "<h1>Use libraries to join path components</h1>\n<p>Instead of using raw string concatenation, use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\"><code>os.path.join</code></a> or <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>. Both of these provide more robust ways of joining together path components.</p>\n<h1>Static variables in <code>Item</code> should be instance variables</h1>\n<pre class=\"lang-python prettyprint-override\"><code>class Item:\n title = None\n authors = None\n tags = None\n media = None\n</code></pre>\n<p>This definition of <code>Item</code> only supports one item, because the variables are all static when you probably want them to be instance variables. You can correct this by declaring a <code>__init__</code> and initializing <code>self.title</code>, <code>self.authors</code>, etc.</p>\n<pre class=\"lang-python prettyprint-override\"><code>class Item:\n def __init__(\n self, title: str, authors: set[str], tags: set[str], media: Media\n ) -&gt; None:\n self.title = title\n self.authors = authors\n self.tags = tags\n self.media = media\n</code></pre>\n<p>Or even better, make <code>Item</code> a <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a> or a <a href=\"https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass\" rel=\"nofollow noreferrer\"><code>dataclass</code></a> to save yourself from writing a lot of boilerplate code.</p>\n<h1><code>(downloader, code)</code> deserves its own name</h1>\n<p>Since every <code>Item</code> is uniquely identifiable by this 2-tuple, and since this particular 2-tuple shows up so often, you should really give it a proper name. Maybe something like <code>ItemId</code>. This will make the code easier to read.</p>\n<pre class=\"lang-python prettyprint-override\"><code>from typing NamedTuple\n\nclass ItemId(NamedTuple):\n downloader: str\n code: str\n</code></pre>\n<h1>Unnecessary <code>global</code></h1>\n<pre class=\"lang-python prettyprint-override\"><code>global config\n</code></pre>\n<p><code>global</code> is unnecessary here for several reasons:</p>\n<ul>\n<li>You're not changing what <code>config</code> points to anywhere in the program (at least, not anywhere in the code provided)</li>\n<li>You can read, and thus mutate the dictionary pointed to by <code>config</code> without the <code>global</code> keyword</li>\n<li>Using <code>global</code> to begin with is a code smell. There are much cleaner ways of sharing/communicating state. More on this below.</li>\n</ul>\n<h1><code>Shelf</code></h1>\n<p>Missing from this class definition is the code where you load file contents from the paths in <code>config</code> into <code>Shelf</code>. Based on the above-mentioned <code>global</code> keyword, I'm assuming you're doing the loading inside of <code>Shelf</code>. This works, but there's a cleaner way of doing this.</p>\n<ol>\n<li>Load the files into data structures before instantiating <code>Shelf</code>, e.g. read <code>index_file</code> into <code>index: dict</code>, read <code>favorites_file</code> into <code>favorites: set</code>.</li>\n<li>Initialize <code>Shelf</code> with these data structures on instantiation.</li>\n</ol>\n<p>By doing this, <code>Shelf</code> becomes a lot easier to test because it's no longer responsible for doing file I/O and parsing of the files in <code>config</code>. When you instantiate <code>Shelf</code> for testing, you can just declare and pass in test data directly.</p>\n<h1><code>search_item</code></h1>\n<ul>\n<li>If you declare a parameter's type to be <code>set[str]</code>, it should always be treated as such in the function body. For <code>authors</code>, <code>tags</code>, and <code>blacklist</code>, you are actually treating them as a <code>Union[set[str], str]</code> which is something completely different.</li>\n<li>I will go one step further and say that making <code>search_item</code> responsible for handling a parameter of type <code>Union[set[str], str]</code> is not a good design. <code>search_item</code> is not the right place to parse a user's command-line <code>str</code> input into a <code>set[str]</code>. Any pre-processing/parsing of input like this should be done before calling <code>search_item</code>.</li>\n<li>The return type should be a <code>set</code>, not a list. Technically, the return type as it is written now is actually an <code>Optional[set]</code> because <code>result</code> is initialized to <code>None</code>, and if <code>search_item</code> is called with <code>title_regex=&quot;&quot;, authors=set(), tags=set(), blacklist=set(), favorites=False</code>, we do not step into any of the filter-related if conditions and simply return <code>result</code>. This is probably not what you want.</li>\n<li>An alternative to repeated <code>if self.verbosity &gt;= 2</code> guards followed by <code>print</code> statements might be using the <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> module. You can map <code>self.verbosity</code> to a logging level (<code>DEBUG</code>, <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>, <code>CRITICAL</code>), configure your logger to have that logging level, and then print logs with <code>logging.debug</code>, <code>logging.info</code>, etc. according to how chatty you want the messages to be.</li>\n<li>All of the inner branching on <code>if result</code> for each filtering stage is what I would call a premature optimization, and the code is much harder to read as a result. It's better to write the code to be as clean and maintainable as possible first. If after that you still have concerns about performance, profile your code to see where you can make optimizations.</li>\n<li><code>tags &lt;= self.index[(k, v)].tags</code> (testing if the set of desired tags is a subset of the item's tags) is more straightforward than <code>not (tags - self.index[(k, v)].tags)</code></li>\n<li><code>blacklist.isdisjoint(self.index[(k, v)].tags)</code> is more straightforward than <code>not blacklist &amp; self.index[(k, v)].tags</code></li>\n</ul>\n<p>There is a lot of repetition at each stage where we filter the collection of candidate items in the same way (using set comprehensions), with the only difference being the predicate.</p>\n<p>If we define the predicates (or checks) as functions that judge an <code>Item</code>, with the help of <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a> we can generate custom predicates, all of the form <code>(Item) -&gt; bool</code>, based on the user's search query.</p>\n<pre class=\"lang-python prettyprint-override\"><code>import re\n\nfrom enum import Enum\nfrom functools import partial\nfrom typing import Callable, NamedTuple\n\nclass Media(Enum):\n EPUB = 1\n MARKDOWN = 2\n PDF = 3\n PNG = 4\n\nclass Item(NamedTuple):\n title: str\n authors: set[str]\n tags: set[str]\n media: Media\n\ndef title_check(title_regex: str, item: Item) -&gt; bool:\n return bool(re.match(title_regex, item.title))\n\ndef authors_check(authors: set[str], item: Item) -&gt; bool:\n return bool(authors &amp; item.authors)\n\ndef tags_broad_check(tags: set[str], item: Item) -&gt; bool:\n return bool(tags &amp; item.tags)\n\ndef tags_normal_check(tags: set[str], item: Item) -&gt; bool:\n return tags &lt;= item.tags\n\ndef blacklisted_tags_check(blacklisted_tags: set[str], item: Item) -&gt; bool:\n return blacklisted_tags.isdisjoint(item.tags)\n\ndef generate_checks(\n title_regex: str,\n authors: set[str],\n tags: set[str],\n blacklisted_tags: set[str],\n broad_search: bool = False,\n) -&gt; list[Callable[[Item], bool]]:\n checks: list[Callable[[Item], bool]] = []\n\n if title_regex:\n checks.append(partial(title_check, title_regex))\n if authors:\n checks.append(partial(authors_check, authors))\n if tags:\n if broad_search:\n checks.append(partial(tags_broad_check, tags))\n else:\n checks.append(partial(tags_normal_check, tags))\n if blacklisted_tags:\n checks.append(partial(blacklisted_tags_check, blacklisted_tags))\n\n return checks\n</code></pre>\n<p>Then, assuming</p>\n<ul>\n<li><code>self.index</code> is a <code>dict[ItemId, Item]</code> and</li>\n<li><code>self.favorites</code> is a <code>set[ItemId]</code></li>\n</ul>\n<p><code>search_item</code> can be refactored like so:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def search_item(\n self,\n title_regex: str,\n authors: set[str],\n tags: set[str],\n blacklisted_tags: set[str],\n broad_search: bool = False,\n favorites: bool = False,\n) -&gt; set[ItemId]:\n if favorites:\n items_to_search = {\n item_id: item\n for item_id, item in self.index.items()\n if item_id in self.favorites\n }\n else:\n items_to_search = self.index\n\n checks = generate_checks(\n title_regex, authors, tags, blacklisted_tags, broad_search\n )\n\n return {\n item_id\n for item_id, item in items_to_search.items()\n if all(check(item) for check in checks)\n }\n</code></pre>\n<p>One advantage of writing it this way is that adding/removing/updating checks is easy, and won't require too many changes to <code>search_item</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T12:33:27.943", "Id": "255716", "ParentId": "255491", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T07:12:15.603", "Id": "255491", "Score": "2", "Tags": [ "python", "python-3.x", "search" ], "Title": "Searching database of books" }
255491
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/255269/231235">ConvertAll Methods Implementation for Multidimensional Array in C#</a> and <a href="https://codereview.stackexchange.com/q/255395/231235">ConvertAll Methods Implementation for Multidimensional Array in C# - follow-up</a>. Besides the multidimensional array (<code>[,]</code>, <code>[,,]</code>, <code>[,,,]</code>...) case, I am trying to implement another series overloading methods to deal with jagged arrays in C#.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation is as below.</p> <pre><code>class Converters { public static TOutput[][] ConvertAll&lt;TInput, TOutput&gt;(TInput[][] inputs, Converter&lt;TInput, TOutput&gt; converter) { if (inputs is null) { throw new ArgumentNullException(nameof(inputs)); } if (converter is null) { throw new ArgumentNullException(nameof(converter)); } TOutput[][] output = Array.ConvertAll(inputs, dim1 =&gt; Array.ConvertAll(dim1, dim2 =&gt; converter(dim2))); return output; } public static TOutput[][][] ConvertAll&lt;TInput, TOutput&gt;(TInput[][][] inputs, Converter&lt;TInput, TOutput&gt; converter) { if (inputs is null) { throw new ArgumentNullException(nameof(inputs)); } if (converter is null) { throw new ArgumentNullException(nameof(converter)); } TOutput[][][] output = Array.ConvertAll(inputs, dim1 =&gt; Array.ConvertAll(dim1, dim2 =&gt; Array.ConvertAll(dim2, dim3 =&gt; converter(dim3) ))); return output; } public static TOutput[][][][] ConvertAll&lt;TInput, TOutput&gt;(TInput[][][][] inputs, Converter&lt;TInput, TOutput&gt; converter) { if (inputs is null) { throw new ArgumentNullException(nameof(inputs)); } if (converter is null) { throw new ArgumentNullException(nameof(converter)); } TOutput[][][][] output = Array.ConvertAll(inputs, dim1 =&gt; Array.ConvertAll(dim1, dim2 =&gt; Array.ConvertAll(dim2, dim3 =&gt; Array.ConvertAll(dim3, dim4 =&gt; converter(dim4) )))); return output; } public static TOutput[][][][][] ConvertAll&lt;TInput, TOutput&gt;(TInput[][][][][] inputs, Converter&lt;TInput, TOutput&gt; converter) { if (inputs is null) { throw new ArgumentNullException(nameof(inputs)); } if (converter is null) { throw new ArgumentNullException(nameof(converter)); } TOutput[][][][][] output = Array.ConvertAll(inputs, dim1 =&gt; Array.ConvertAll(dim1, dim2 =&gt; Array.ConvertAll(dim2, dim3 =&gt; Array.ConvertAll(dim3, dim4 =&gt; Array.ConvertAll(dim4, dim5 =&gt; converter(dim5) ))))); return output; } public static TOutput[][][][][][] ConvertAll&lt;TInput, TOutput&gt;(TInput[][][][][][] inputs, Converter&lt;TInput, TOutput&gt; converter) { if (inputs is null) { throw new ArgumentNullException(nameof(inputs)); } if (converter is null) { throw new ArgumentNullException(nameof(converter)); } TOutput[][][][][][] output = Array.ConvertAll(inputs, dim1 =&gt; Array.ConvertAll(dim1, dim2 =&gt; Array.ConvertAll(dim2, dim3 =&gt; Array.ConvertAll(dim3, dim4 =&gt; Array.ConvertAll(dim4, dim5 =&gt; Array.ConvertAll(dim5, dim6 =&gt; converter(dim6) )))))); return output; } } </code></pre> <p><strong>Test cases</strong></p> <p>The test cases listed here include array of arrays, array of arrays of arrays and array of arrays of arrays of arrays.</p> <pre><code>// Reference: https://www.geeksforgeeks.org/c-sharp-jagged-arrays/ Console.WriteLine(&quot;Jagged Array [][]&quot;); Console.WriteLine(); int[][] jagged_arr = new int[][] { new int[] {1, 2, 3, 4}, new int[] {11, 34, 67}, new int[] {89, 23}, new int[] {0, 45, 78, 53, 99} }; double[][] output1 = Converters.ConvertAll(jagged_arr, x =&gt; x + 0.1); for (int dim1 = 0; dim1 &lt; output1.Length; dim1++) { for (int dim2 = 0; dim2 &lt; output1[dim1].GetLength(0); dim2++) { Console.Write($&quot;[{dim1}][{dim2}]: {output1[dim1][dim2]}\t&quot;); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(&quot;Jagged Array [][][]&quot;); Console.WriteLine(); int[][][] jagged_arr2 = new int[][][] { jagged_arr, jagged_arr, jagged_arr, jagged_arr }; double[][][] output2 = Converters.ConvertAll(jagged_arr2, x =&gt; x + 0.1); for (int dim1 = 0; dim1 &lt; output2.Length; dim1++) { Console.WriteLine($&quot;dim1 = {dim1}&quot;); for (int dim2 = 0; dim2 &lt; output2[dim1].GetLength(0); dim2++) { for (int dim3 = 0; dim3 &lt; output2[dim1][dim2].GetLength(0); dim3++) { Console.Write($&quot;[{dim2}][{dim3}]: {output2[dim1][dim2][dim3]}\t&quot;); } Console.WriteLine(); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(&quot;Jagged Array [][][][]&quot;); Console.WriteLine(); int[][][][] jagged_arr3 = new int[][][][] { jagged_arr2, jagged_arr2, jagged_arr2, jagged_arr2 }; double[][][][] output3 = Converters.ConvertAll(jagged_arr3, x =&gt; x + 0.1); for (int dim1 = 0; dim1 &lt; output3.Length; dim1++) { for (int dim2 = 0; dim2 &lt; output3[dim1].GetLength(0); dim2++) { Console.WriteLine($&quot;dim1 = {dim1}, dim2 = {dim2}&quot;); for (int dim3 = 0; dim3 &lt; output3[dim1][dim2].GetLength(0); dim3++) { for (int dim4 = 0; dim4 &lt; output3[dim1][dim2][dim3].GetLength(0); dim4++) { Console.Write($&quot;[{dim3}][{dim4}]: {output3[dim1][dim2][dim3][dim4]}\t&quot;); } Console.WriteLine(); } Console.WriteLine(); } } </code></pre> <p>The output of the test code above:</p> <pre><code>Jagged Array [][] [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 Jagged Array [][][] dim1 = 0 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 1 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 2 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 3 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 Jagged Array [][][][] dim1 = 0, dim2 = 0 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 0, dim2 = 1 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 0, dim2 = 2 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 0, dim2 = 3 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 1, dim2 = 0 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 1, dim2 = 1 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 1, dim2 = 2 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 1, dim2 = 3 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 2, dim2 = 0 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 2, dim2 = 1 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 2, dim2 = 2 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 2, dim2 = 3 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 3, dim2 = 0 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 3, dim2 = 1 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 3, dim2 = 2 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 dim1 = 3, dim2 = 3 [0][0]: 1.1 [0][1]: 2.1 [0][2]: 3.1 [0][3]: 4.1 [1][0]: 11.1 [1][1]: 34.1 [1][2]: 67.1 [2][0]: 89.1 [2][1]: 23.1 [3][0]: 0.1 [3][1]: 45.1 [3][2]: 78.1 [3][3]: 53.1 [3][4]: 99.1 </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/255269/231235">ConvertAll Methods Implementation for Multidimensional Array in C#</a> and</p> <p><a href="https://codereview.stackexchange.com/q/255395/231235">ConvertAll Methods Implementation for Multidimensional Array in C# - follow-up</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>Trying to implement another series <code>ConvertAll</code> overloading methods to deal with jagged arrays in C#.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any issue about potential drawback or unnecessary overhead of the implemented methods, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T08:16:50.863", "Id": "504109", "Score": "0", "body": "Have you considered to use meta programming to generate the different overloads? Just like I suggested in your previous follow-up thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T08:26:15.670", "Id": "504111", "Score": "1", "body": "@PeterCsala Thank you for the comments. I know that there is a way to use meta programming to generate these overloads. Besides, I am wondering the feedback of the proposed non-metaprogramming version first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T08:48:39.577", "Id": "504114", "Score": "1", "body": "The parameters' null checks can be shortened. Unfortunately [Simplified parameter null validation code](https://github.com/dotnet/csharplang/issues/2145) is not yet part of the C# language. But with code weaving you can use [NullGuards](https://github.com/Fody/NullGuard)." } ]
[ { "body": "<p>It seems like your end goal is to apply <code>ConvertAll</code> to all of the different types of C# arrays, nested or not, and with with lower bounds not equal to zero.</p>\n<p>All arrays can be manipulated through the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array\" rel=\"nofollow noreferrer\"><code>Array</code></a> base class and any level of nesting can be handled by using recursion.</p>\n<p>First some plumbing is needed to <a href=\"https://referencesource.microsoft.com/mscorlib/R/c4961fbba63d3a44.html\" rel=\"nofollow noreferrer\">enumerate all possible indices</a> of an array of arbitrary dimensions:</p>\n<pre><code>private static bool IncrementIndices(Array array, int[] indices)\n{\n int rank = array.Rank;\n indices[rank - 1]++;\n for (int dim = rank - 1; dim &gt;= 0; dim--)\n {\n if (indices[dim] &gt; array.GetUpperBound(dim))\n {\n if (dim == 0)\n {\n return false;\n }\n for (int j = dim; j &lt; rank; j++)\n indices[j] = array.GetLowerBound(j);\n indices[dim - 1]++;\n }\n }\n return true;\n}\n</code></pre>\n<p>With this method we can then convert each value in a non-nested array:</p>\n<pre><code>public static Array ConvertAll&lt;TInput, TOutput&gt;(this Array source, Converter&lt;TInput, TOutput&gt; converter)\n{\n if (ReferenceEquals(source, null))\n {\n throw new ArgumentNullException(nameof(source));\n }\n if (ReferenceEquals(converter, null))\n {\n throw new ArgumentNullException(nameof(converter));\n }\n if (!typeof(TInput).IsAssignableFrom(source.GetType().GetElementType()))\n {\n throw new ArgumentException(&quot;Type of &quot; + nameof(TInput) + &quot; (&quot; + typeof(TInput).Name + &quot;) is not assignable from the element type of &quot; + nameof(source) + &quot; (&quot; + source.GetType().GetElementType().Name + &quot;)&quot;);\n }\n\n var dimensions = new int[source.Rank];\n var indices = new int[source.Rank];\n var anyDimensionZero = false;\n for (int dimension = 0; dimension &lt; dimensions.Length; dimension++)\n {\n dimensions[dimension] = source.GetLength(dimension);\n indices[dimension] = source.GetLowerBound(dimension);\n if (dimensions[dimension] == 0)\n {\n anyDimensionZero = true;\n }\n }\n\n var destination = Array.CreateInstance(typeof(TOutput), dimensions, indices);\n if (anyDimensionZero)\n {\n return destination;\n }\n\n do\n {\n var currentValue = source.GetValue(indices);\n var convertedValue = converter((TInput)currentValue);\n destination.SetValue(convertedValue, indices);\n }\n while (IncrementIndices(source, indices));\n\n return destination;\n}\n</code></pre>\n<p>We can then add recursion to handle nesting:</p>\n<pre><code>public static Array ConvertAll&lt;TInput, TOutput&gt;(this Array source, Converter&lt;TInput, TOutput&gt; converter)\n{\n if (ReferenceEquals(source, null))\n {\n throw new ArgumentNullException(nameof(source));\n }\n if (ReferenceEquals(converter, null))\n {\n throw new ArgumentNullException(nameof(converter));\n }\n var elementType = source.GetType().GetElementType();\n if (!typeof(TInput).IsAssignableFrom(source.GetType().GetElementType()) &amp;&amp; !elementType.IsArray)\n {\n throw new ArgumentException(&quot;Type of &quot; + nameof(TInput) + &quot; (&quot; + typeof(TInput).Name + &quot;) is not assignable from the element type of &quot; + nameof(source) + &quot; (&quot; + source.GetType().GetElementType().Name + &quot;)&quot;);\n }\n\n var recursivelyApplyConverter = elementType != typeof(TInput);\n\n var dimensions = new int[source.Rank];\n var indices = new int[source.Rank];\n var anyDimensionZero = false;\n for (int dimension = 0; dimension &lt; dimensions.Length; dimension++)\n {\n dimensions[dimension] = source.GetLength(dimension);\n indices[dimension] = source.GetLowerBound(dimension);\n if (dimensions[dimension] == 0)\n {\n anyDimensionZero = true;\n }\n }\n\n var destinationElementType = recursivelyApplyConverter ? GetTargetArrayType(elementType, typeof(TOutput)) : typeof(TOutput);\n var destination = Array.CreateInstance(destinationElementType, dimensions, indices);\n if (anyDimensionZero)\n {\n return destination;\n }\n\n do\n {\n var currentValue = source.GetValue(indices);\n if (ReferenceEquals(currentValue, null) &amp;&amp; recursivelyApplyConverter)\n continue;\n var convertedValue = recursivelyApplyConverter\n ? (object)ConvertAll&lt;TInput, TOutput&gt;((Array)currentValue, converter)\n : converter((TInput)currentValue);\n destination.SetValue(convertedValue, indices);\n }\n while (IncrementIndices(source, indices));\n\n return destination;\n}\n</code></pre>\n<p>Here the tricky bit is to construct the correct target type:</p>\n<pre><code>private static Type GetTargetArrayType(Type sourceType, Type targetType)\n{\n var types = new Stack&lt;Type&gt;();\n var type = sourceType;\n while (type.IsArray &amp;&amp; type != targetType)\n {\n types.Push(type);\n type = type.GetElementType();\n }\n var resultType = targetType;\n while (types.Count &gt; 0)\n {\n var arrayType = types.Pop();\n var rank = arrayType.GetArrayRank();\n //MakeArrayType() != MakeArrayType(1)\n //See: https://docs.microsoft.com/en-us/dotnet/api/system.type.makearraytype\n resultType = rank == 1 ? resultType.MakeArrayType() : resultType.MakeArrayType(rank);\n }\n return resultType;\n}\n</code></pre>\n<p>The same basic construct can be used to implement other primitives such as foreach:</p>\n<pre><code>public static void ForEach&lt;TSource&gt;(this Array source, Func&lt;TSource, int[], TSource&gt; updater)\n{\n if (ReferenceEquals(source, null))\n {\n throw new ArgumentNullException(nameof(source));\n }\n if (ReferenceEquals(updater, null))\n {\n throw new ArgumentNullException(nameof(updater));\n }\n if (!typeof(TSource).IsAssignableFrom(source.GetType().GetElementType()))\n {\n throw new ArgumentException(&quot;Type of &quot; + nameof(TSource) + &quot; (&quot; + typeof(TSource).Name + &quot;) is not assignable from the element type of &quot; + nameof(source) + &quot; (&quot; + source.GetType().GetElementType().Name + &quot;)&quot;);\n }\n\n var indices = new int[source.Rank];\n for (int dimension = 0; dimension &lt; indices.Length; dimension++)\n {\n if (source.GetLength(dimension) == 0)\n {\n return;\n }\n indices[dimension] = source.GetLowerBound(dimension);\n }\n\n var tempIndices = new int[indices.Length];\n do\n {\n Array.Copy(indices, tempIndices, indices.Length);\n var currentValue = source.GetValue(indices);\n var updatedValue = updater((TSource)currentValue, tempIndices);\n source.SetValue(updatedValue, indices);\n }\n while (IncrementIndices(source, indices));\n}\n\npublic static void ForEach&lt;TSource&gt;(this Array source, Action&lt;TSource, int[]&gt; action)\n{\n if (ReferenceEquals(source, null))\n {\n throw new ArgumentNullException(nameof(source));\n }\n if (ReferenceEquals(action, null))\n {\n throw new ArgumentNullException(nameof(action));\n }\n if (!typeof(TSource).IsAssignableFrom(source.GetType().GetElementType()))\n {\n throw new ArgumentException(&quot;Type of &quot; + nameof(TSource) + &quot; (&quot; + typeof(TSource).Name + &quot;) is not assignable from the element type of &quot; + nameof(source) + &quot; (&quot; + source.GetType().GetElementType().Name + &quot;)&quot;);\n }\n\n var indices = new int[source.Rank];\n for (int dimension = 0; dimension &lt; indices.Length; dimension++)\n {\n if (source.GetLength(dimension) == 0)\n {\n return;\n }\n indices[dimension] = source.GetLowerBound(dimension);\n }\n\n var tempIndices = new int[indices.Length];\n do\n {\n Array.Copy(indices, tempIndices, indices.Length);\n var currentValue = source.GetValue(indices);\n action((TSource)currentValue, tempIndices);\n }\n while (IncrementIndices(source, indices));\n}\n</code></pre>\n<p>Now all that's left is to wrap the core ConvertAll in strongly typed wrappers, preferably in an automated way.</p>\n<pre><code>int[,][] test = (int[,][])Array.CreateInstance(typeof(int[]), lengths: new int[] { 2, 2 }, lowerBounds: new int[] { -11, 10 });\nint arrayLength = 1;\nint valueCounter = 1;\ntest.ForEach(_ =&gt;\n{\n var array = new int[arrayLength++];\n array.ForEach(__ =&gt; valueCounter++);\n return array;\n});\n\ntest.ConvertAll(x =&gt; x + 0.1f)\n .ForEach((l2, l1Indices) =&gt; \n l2.ForEach((x, l2Indices) =&gt; \n Console.WriteLine(&quot;array[{1}][{2}] = {0}&quot;, x, string.Join(&quot;, &quot;, l1Indices), string.Join(&quot;, &quot;, l2Indices))));\n\npublic static class ArrayExtensions\n{\n //All of the above\n \n public static void ForEach&lt;TSource&gt;(this TSource[] source, Func&lt;TSource, TSource&gt; updater)\n {\n ForEach&lt;TSource&gt;((Array)source, (x, _) =&gt; updater(x));\n }\n \n public static void ForEach&lt;TSource&gt;(this TSource[,] source, Func&lt;TSource, TSource&gt; updater)\n {\n ForEach&lt;TSource&gt;((Array)source, (x, _) =&gt; updater(x));\n }\n \n public static void ForEach&lt;TSource&gt;(this TSource[] source, Action&lt;TSource, int[]&gt; action)\n {\n ForEach&lt;TSource&gt;((Array)source, action);\n }\n \n public static void ForEach&lt;TSource&gt;(this TSource[,] source, Action&lt;TSource, int[]&gt; action)\n {\n ForEach&lt;TSource&gt;((Array)source, action);\n }\n \n public static TOutput[,][] ConvertAll&lt;TInput, TOutput&gt;(this TInput[,][] source, Converter&lt;TInput, TOutput&gt; converter)\n {\n return (TOutput[,][])ConvertAll&lt;TInput, TOutput&gt;((Array)source, converter);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T13:18:26.517", "Id": "255563", "ParentId": "255493", "Score": "3" } } ]
{ "AcceptedAnswerId": "255563", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T07:41:45.147", "Id": "255493", "Score": "1", "Tags": [ "c#", "array", "generics", "converting", "lambda" ], "Title": "ConvertAll Methods Implementation for Jagged Arrays in C#" }
255493
<p>I come from java background and I am trying to implement lambda chaining in <strong>Python</strong>. Below is my code</p> <pre><code>li = [&quot;amol&quot;, &quot;vikas&quot;, &quot;rahul&quot;] li2 = list(filter(lambda n: (n == &quot;Amol&quot;), list(map(lambda name: (name.capitalize()), li)))) print(li2) </code></pre> <p>This Function will</p> <ul> <li>Capitalize the names</li> <li>Filter the names with &quot;Amol&quot;</li> </ul> <p>Currently the code is <strong>running well</strong> but it seems to be cluttered and complicated when compared to java</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T08:38:34.343", "Id": "504112", "Score": "0", "body": "\"_when compared to java_\", can you show the java equivalent?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T08:49:09.567", "Id": "504115", "Score": "0", "body": "`myList.stream().map(name -> name.functionToCapitalize()).filter(name -> name.equals(\"Amol\")).collect(toList())`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T09:59:02.817", "Id": "504120", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T06:43:08.610", "Id": "504210", "Score": "0", "body": "This looks \"dumbed down\" code: If you can, please show running code from a project where this came up." } ]
[ { "body": "<p>You're better off doing an inline list comprehension.</p>\n<pre><code>li2 = [name.capitalize() for name in li if name == &quot;amol&quot;]\n</code></pre>\n<p>For the lambda implementation itself, you can leave the map and filter generators until only when you want to convert back to list:</p>\n<pre><code>li2 = filter(lambda n: n == &quot;Amol&quot;, map(str.capitalize, li))\nprint(list(li2))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T09:30:18.210", "Id": "504116", "Score": "0", "body": "sorry for my english but i did not get the meaning of \"you can leave the map and filter generators until only when you want to convert back to list\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T09:36:46.827", "Id": "504117", "Score": "0", "body": "got it. li2 should be just a stream object as we have in java" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T09:56:18.007", "Id": "504119", "Score": "0", "body": "@amol updated the `map` function call." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T09:05:35.700", "Id": "255497", "ParentId": "255496", "Score": "1" } } ]
{ "AcceptedAnswerId": "255497", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T08:26:08.313", "Id": "255496", "Score": "0", "Tags": [ "python", "lambda" ], "Title": "Is this the right way to do lambda method chaining in python?" }
255496
<p>Recently I've needed a Binary Space Partitioning (BSP) tree and I was surprised that there was not a &quot;C++ container-ish&quot; implementation available. I've decided to make my own with custom allocator support and to work in any number of dimensions alongside. This is my first ever code dealing with custom allocators. Is there anything I missed in terms of C++ best practices? Or even potential UB? Is there anything I've missed to be a proper STL container? (I've mostly looked at <code>std::map</code>, as that's usually a tree)</p> <pre><code>#define FWD(...) ::std::forward&lt;decltype(__VA_ARGS__)&gt;(__VA_ARGS__) /** * A view for BSP tree to simplify iterations. * Basically an iterator begin and end pair. */ template &lt;typename It&gt; class bsptree_view { private: It from; It to; public: constexpr bsptree_view(It from, It to) noexcept : from(from), to(to) {} [[nodiscard]] constexpr auto begin() noexcept { return from; } [[nodiscard]] constexpr auto end() noexcept { return to; } }; /** * An N dimensional point in space. */ template &lt;std::size_t Dim, typename T&gt; struct point { std::array&lt;T, Dim&gt; coordinates; }; /** * An N dimensional axis-aligned bounds type, consisting of the offset and size in each dimension. */ template &lt;std::size_t Dim, typename T&gt; struct bounds { std::array&lt;T, Dim&gt; offset; std::array&lt;T, Dim&gt; size; /** * Checks if a point is contained within this bounds. */ [[nodiscard]] constexpr bool contains(point&lt;Dim, T&gt; const&amp; p) const noexcept { for (std::size_t i = 0; i &lt; Dim; ++i) { if (p.coordinates[i] &lt; offset[i] || p.coordinates[i] &gt;= offset[i] + size[i]) return false; } return true; } /** * Checks if two bounds intersect. */ [[nodiscard]] constexpr bool intersects(bounds const&amp; o) const noexcept { for (std::size_t i = 0; i &lt; Dim; ++i) { if (offset[i] &gt;= o.offset[i] + o.size[i] || o.offset[i] &gt;= offset[i] + size[i]) return false; } return true; } }; /** * A generic, N-dimensional Binary Space Partitioning tree. */ template &lt; std::size_t Dim, typename Key, typename T, typename Allocator = std::allocator&lt;std::pair&lt;const point&lt;Dim, Key&gt;, T&gt;&gt; &gt; class bsptree { public: // Common type definitions for std::map using key_type = point&lt;Dim, Key&gt;; using bounds_type = bounds&lt;Dim, Key&gt;; using mapped_type = T; using value_type = std::pair&lt;const key_type, T&gt;; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using allocator_type = Allocator; using reference = value_type&amp;; using const_reference = value_type const&amp;; using pointer = typename std::allocator_traits&lt;Allocator&gt;::pointer; using const_pointer = typename std::allocator_traits&lt;Allocator&gt;::const_pointer; inline static constexpr size_type subdivision_count = 1 &lt;&lt; Dim; private: using storage_type = std::aligned_storage_t&lt;sizeof(value_type), alignof(value_type)&gt;; public: // The node structure type struct node_type { // Parent for iteration node_type* parent; // The bounds of the node bounds_type bounds; // Stored data storage_type* data; size_type length = 0; // Subnodes std::array&lt;node_type*, subdivision_count&gt; subnodes; node_type(node_type* parent, bounds_type const&amp; bounds, storage_type* data) : parent(parent), bounds(bounds), data(data) { for (size_type i = 0; i &lt; subdivision_count; ++i) subnodes[i] = nullptr; } [[nodiscard]] value_type* values() noexcept { return std::launder(reinterpret_cast&lt;value_type*&gt;(data)); } [[nodiscard]] value_type const* values() const noexcept { return std::launder(reinterpret_cast&lt;value_type const*&gt;(data)); } [[nodiscard]] value_type&amp; value(size_type i) noexcept { return values()[i]; } [[nodiscard]] value_type const&amp; value(size_type i) const noexcept { return values()[i]; } }; private: // A simple helper for iterating through the node structure template &lt;typename Derived&gt; class node_stepper { protected: node_type* current; explicit constexpr node_stepper(node_type* current) noexcept : current(current) {} [[nodiscard]] Derived&amp; underlying() { return static_cast&lt;Derived&amp;&gt;(*this); } [[nodiscard]] Derived const&amp; underlying() const { return static_cast&lt;Derived const&amp;&gt;(*this); } [[nodiscard]] constexpr bool accepts_node(node_type* n) { return n != nullptr &amp;&amp; underlying().intersects_bounds(n-&gt;bounds); } void descend_first_node() { if (current == nullptr) return; while (true) { start: for (size_type i = 0; i &lt; subdivision_count; ++i) { if (accepts_node(current-&gt;subnodes[i])) { current = current-&gt;subnodes[i]; goto start; } } break; } } bool move_next_node() { if (current == nullptr) return false; begin: auto parent = current-&gt;parent; if (parent == nullptr) return false; for (size_type i = 0; i + 1 &lt; subdivision_count; ++i) { if (current == parent-&gt;subnodes[i]) { for (size_type j = i + 1; j &lt; subdivision_count; ++j) { if (accepts_node(parent-&gt;subnodes[j])) { current = parent-&gt;subnodes[j]; descend_first_node(); return true; } } break; } } // This was the last node we visited, now stay at the parent current = parent; if (!accepts_node(current)) goto begin; return true; } bool move_prev_node() { // Step down in reverse order for (size_type i = subdivision_count; i &gt; 0; --i) { if (accepts_node(current-&gt;subnodes[i - 1])) { current = current-&gt;subnodes[i - 1]; return true; } } // No more children, step up // NOTE: We want to keep the child if there are no more nodes, so we don't copy back until found auto next = current; while (true) { auto parent = next-&gt;parent; if (parent == nullptr) return false; // We hit the start // Now we need to step back in reverse order for (size_type i = subdivision_count; i &gt; 1; --i) { if (next == parent-&gt;subnodes[i - 1]) { for (size_type j = i - 1; j &gt; 0; --j) { if (accepts_node(parent-&gt;subnodes[j - 1])) { current = parent-&gt;subnodes[j - 1]; return true; } } break; } } // We gotta step up more next = parent; } return false; } }; // Base for iterators to factor out stepping template &lt;typename Derived&gt; class value_iterator_base : public node_stepper&lt;Derived&gt; { private: using base_type = node_stepper&lt;Derived&gt;; friend class bsptree; template &lt;typename&gt; friend class value_iterator_base; public: using difference_type = typename bsptree::difference_type; using iterator_category = std::bidirectional_iterator_tag; protected: size_type index; constexpr value_iterator_base(node_type* current, size_type index) noexcept : base_type(current), index(index) { } [[nodiscard]] constexpr bool is_end() const noexcept { return this-&gt;current == nullptr || (this-&gt;current-&gt;parent == nullptr &amp;&amp; index &gt;= this-&gt;current-&gt;length); } [[nodiscard]] bool accepts_value() const noexcept { return this-&gt;current != nullptr &amp;&amp; index &lt; this-&gt;current-&gt;length &amp;&amp; this-&gt;underlying().contains_point(value().first); } public: void descend_first() { this-&gt;descend_first_node(); if (!accepts_value()) move_next(); } void move_next() { begin: if (this-&gt;current == nullptr) return; if (index &lt; this-&gt;current-&gt;length) { index += 1; if (!accepts_value()) goto begin; return; } if (this-&gt;move_next_node()) { index = 0; if (!accepts_value()) goto begin; } } void move_prev() { begin: if (this-&gt;current == nullptr) return; if (index &gt; 0) { --index; if (!accepts_value()) goto begin; return; } if (this-&gt;move_prev_node()) { index = this-&gt;current-&gt;length - 1; if (!accepts_value()) goto begin; } } [[nodiscard]] typename bsptree::value_type&amp; value() noexcept { return this-&gt;current-&gt;value(index); } [[nodiscard]] typename bsptree::value_type const&amp; value() const noexcept { return this-&gt;current-&gt;value(index); } Derived&amp; operator++() { this-&gt;move_next(); return this-&gt;underlying(); } Derived operator++(int) { auto cpy = this-&gt;underlying(); this-&gt;operator++(); return cpy; } Derived&amp; operator--() { this-&gt;move_prev(); return this-&gt;underlying(); } Derived operator--(int) { auto cpy = this-&gt;underlying(); this-&gt;operator--(); return cpy; } public: template &lt;typename OtherDerived&gt; [[nodiscard]] constexpr bool operator==(value_iterator_base&lt;OtherDerived&gt; const&amp; r) noexcept { return (is_end() &amp;&amp; r.is_end()) || (this-&gt;current == r.current &amp;&amp; index == r.index); } template &lt;typename OtherDerived&gt; [[nodiscard]] constexpr bool operator!=(value_iterator_base&lt;OtherDerived&gt; const&amp; r) noexcept { return !(*this == r); } }; using node_allocator = typename std::allocator_traits&lt;Allocator&gt;::template rebind_alloc&lt;node_type&gt;; bounds_type root_bounds; Allocator alloc; size_type bucket_size; node_type* root; size_type count; // Initializes all members bsptree( bounds_type const&amp; bounds, Allocator const&amp; alloc, size_type bucket, node_type* root, size_type count) : root_bounds(bounds), alloc(alloc), bucket_size(bucket), root(root), count(count) {} // Allocation node_type* allocate_node(node_type* parent, bounds_type const&amp; bounds) { // Allocate the node node_allocator node_alloc = node_allocator(std::move(alloc)); node_type* result = node_alloc.allocate(1); // Allocate bucket alloc = Allocator(std::move(node_alloc)); value_type* data = alloc.allocate(bucket_size); // Initialize the node new (result) node_type(parent, bounds, std::launder(reinterpret_cast&lt;storage_type*&gt;(data))); return result; } void deallocate_node(node_type* n) { // First destruct every element for (size_type i = 0; i &lt; n-&gt;length; ++i) { n-&gt;value(i).~value_type(); } // Free the space for the data alloc.deallocate(std::launder(reinterpret_cast&lt;value_type*&gt;(n-&gt;data)), bucket_size); auto parent = n-&gt;parent; if (parent != nullptr) { // Null out the proper subnode of parent for (size_type i = 0; i &lt; subdivision_count; ++i) { if (parent-&gt;subnodes[i] == n) { parent-&gt;subnodes[i] = nullptr; break; } } } // Now we can free the node itself node_allocator node_alloc = node_allocator(std::move(alloc)); n-&gt;~node_type(); node_alloc.deallocate(n, 1); alloc = Allocator(std::move(node_alloc)); } void destruct() { auto current = root; while (current) { for (size_type i = 0; i &lt; subdivision_count; ++i) { if (current-&gt;subnodes[i] != nullptr) { current = current-&gt;subnodes[i]; continue; } } // This is a leaf, we can free it auto parent = current-&gt;parent; deallocate_node(current); current = parent; } root = nullptr; count = 0; } node_type* clone_node(node_type* other, node_type* parent) { auto n = allocate_node(parent, other-&gt;bounds); for (; n-&gt;length &lt; other-&gt;length; ++n-&gt;length) { new (&amp;n-&gt;data[n-&gt;length]) value_type(other-&gt;value(n-&gt;length)); } return n; } void clone(bsptree const&amp; other) { if (other.root == nullptr) return; // We at least have a root root = clone_node(other.root, nullptr); auto current = root; auto other_current = other.root; while (true) { // Clone the first non-null child for (size_type i = 0; i &lt; subdivision_count; ++i) { if (current-&gt;subnodes[i] == nullptr &amp;&amp; other_current-&gt;subnodes[i] != nullptr) { current-&gt;subnodes[i] = clone_node(other_current-&gt;subnodes[i], current); current = current-&gt;subnodes[i]; other_current = other_current-&gt;subnodes[i]; continue; } } // Either a leaf or cloned everything, step up if (current-&gt;parent == nullptr) break; current = current-&gt;parent; other_current = other_current-&gt;parent; } } public: class iterator : public value_iterator_base&lt;iterator&gt; { private: using base_type = value_iterator_base&lt;iterator&gt;; public: using base_type::difference_type; using base_type::iterator_category; using reference = typename bsptree::reference; using pointer = typename bsptree::pointer; using value_type = typename bsptree::value_type; using base_type::base_type; using base_type::operator++; using base_type::operator--; [[nodiscard]] reference operator*() noexcept { return this-&gt;value(); } [[nodiscard]] pointer operator-&gt;() noexcept { return &amp;this-&gt;value(); } [[nodiscard]] constexpr bool intersects_bounds(bounds_type const&amp; bounds) const noexcept { return true; } [[nodiscard]] constexpr bool contains_point(key_type const&amp; point) const noexcept { return true; } }; class const_iterator : public value_iterator_base&lt;const_iterator&gt; { private: using base_type = value_iterator_base&lt;const_iterator&gt;; public: using base_type::difference_type; using base_type::iterator_category; using reference = typename bsptree::const_reference; using pointer = typename bsptree::const_pointer; using value_type = typename bsptree::value_type; using base_type::base_type; constexpr const_iterator(iterator it) noexcept : const_iterator(it.current, it.index) {} using base_type::operator++; using base_type::operator--; [[nodiscard]] reference operator*() noexcept { return *this-&gt;value(); } [[nodiscard]] pointer operator-&gt;() noexcept { return this-&gt;value(); } [[nodiscard]] constexpr bool intersects_bounds(bounds_type const&amp; bounds) const noexcept { return true; } [[nodiscard]] constexpr bool contains_point(key_type const&amp; point) const noexcept { return true; } }; template &lt;typename Shape&gt; class query_iterator : public value_iterator_base&lt;query_iterator&lt;Shape&gt;&gt; { private: using base_type = value_iterator_base&lt;query_iterator&lt;Shape&gt;&gt;; Shape shape; public: using base_type::difference_type; using base_type::iterator_category; using reference = typename bsptree::reference; using pointer = typename bsptree::pointer; using value_type = typename bsptree::value_type; constexpr query_iterator(node_type* current, size_type index, Shape const&amp; shape) noexcept : base_type(current, index), shape(shape) {} using base_type::operator++; using base_type::operator--; [[nodiscard]] reference operator*() noexcept { return this-&gt;value(); } [[nodiscard]] pointer operator-&gt;() noexcept { return &amp;this-&gt;value(); } [[nodiscard]] constexpr bool intersects_bounds(bounds_type const&amp; bounds) const noexcept { return shape.intersects(bounds); } [[nodiscard]] constexpr bool contains_point(key_type const&amp; point) const noexcept { return shape.contains(point); } }; template &lt;typename Shape&gt; class const_query_iterator : public value_iterator_base&lt;const_query_iterator&lt;Shape&gt;&gt; { private: using base_type = value_iterator_base&lt;const_query_iterator&lt;Shape&gt;&gt;; Shape shape; public: using base_type::difference_type; using base_type::iterator_category; using reference = typename bsptree::const_reference; using pointer = typename bsptree::const_pointer; using value_type = typename bsptree::value_type; constexpr const_query_iterator(node_type* current, size_type index, Shape const&amp; shape) noexcept : base_type(current, index), shape(shape) {} constexpr const_query_iterator(query_iterator&lt;Shape&gt; it) noexcept : const_query_iterator(it.current, it.index, it.shape) {} using base_type::operator++; using base_type::operator--; [[nodiscard]] reference operator*() noexcept { return this-&gt;value(); } [[nodiscard]] pointer operator-&gt;() noexcept { return &amp;this-&gt;value(); } [[nodiscard]] constexpr bool intersects_bounds(bounds_type const&amp; bounds) const noexcept { return shape.intersects(bounds); } [[nodiscard]] constexpr bool contains_point(key_type const&amp; point) const noexcept { return shape.contains(point); } }; class node_iterator : public node_stepper&lt;node_iterator&gt; { private: friend class bsptree; using base_type = node_stepper&lt;node_iterator&gt;; public: using difference_type = typename bsptree::difference_type; using iterator_category = std::bidirectional_iterator_tag; using value_type = node_type; using reference = value_type const&amp;; using pointer = value_type const*; explicit constexpr node_iterator(node_type* current) noexcept : base_type(current) {} [[nodiscard]] constexpr bool intersects_bounds(bounds_type const&amp; bounds) const noexcept { return true; } [[nodiscard]] reference operator*() noexcept { return *this-&gt;current; } [[nodiscard]] pointer operator-&gt;() noexcept { return this-&gt;current; } node_iterator&amp; operator++() { this-&gt;move_next_node(); return *this; } node_iterator operator++(int) { auto cpy = *this; this-&gt;operator++(); return cpy; } node_iterator&amp; operator--() { this-&gt;move_prev_node(); return *this; } node_iterator operator--(int) { auto cpy = *this; this-&gt;operator--(); return cpy; } public: [[nodiscard]] constexpr bool operator==(node_iterator const&amp; r) noexcept { return this-&gt;current == r.current; } [[nodiscard]] constexpr bool operator!=(node_iterator const&amp; r) noexcept { return !(*this == r); } }; explicit bsptree(bounds_type const&amp; bounds, size_type bucket = 1) : bsptree(bounds, bucket, Allocator()) {} bsptree(bounds_type const&amp; bounds, Allocator const&amp; alloc) : bsptree(bounds, 1, alloc) {} bsptree(bounds_type const&amp; bounds, size_type bucket, Allocator const&amp; alloc) : bsptree(bounds, alloc, bucket, nullptr, 0) {} bsptree(bsptree&amp;&amp; other, Allocator const&amp; alloc) : bsptree(other.root_bounds, alloc, other.bucket_size, other.root, other.count) { other.root = nullptr; other.count = 0; } bsptree(bsptree&amp;&amp; other) : bsptree(std::move(other), other.data_alloc) {} ~bsptree() { destruct(); } bsptree&amp; operator=(bsptree&amp;&amp; other) noexcept { destruct(); root_bounds = other.root_bounds; alloc = other.alloc; bucket_size = other.bucket_size; root = other.root; count = other.count; other.root = nullptr; other.count = 0; return *this; } bsptree(bsptree const&amp; other) : bsptree(other, other.alloc) {} bsptree(bsptree const&amp; other, Allocator const&amp; alloc) : bsptree(other.root_bounds, alloc, other.bucket_size, nullptr, other.count) { clone(other); } bsptree&amp; operator=(bsptree const&amp; other) { destruct(); root_bounds = other.root_bounds; alloc = other.alloc; bucket_size = other.bucket_size; count = other.count; clone(other); return *this; } [[nodiscard]] allocator_type get_allocator() const noexcept { return alloc; } [[nodiscard]] node_type* root_node() const noexcept { return root; } // TODO: Element access? // Iterators [[nodiscard]] iterator begin() noexcept { auto it = iterator(root, 0); if (root != nullptr) it.descend_first(); return it; } [[nodiscard]] iterator end() noexcept { if (root == nullptr) return iterator(root, 0); return iterator(root, root-&gt;length); } [[nodiscard]] const_iterator begin() const noexcept { return cbegin(); } [[nodiscard]] const_iterator end() const noexcept { return cend(); } [[nodiscard]] const_iterator cbegin() const noexcept { auto it = const_iterator(root, 0); if (root != nullptr) it.descend_first(); return it; } [[nodiscard]] const_iterator cend() const noexcept { if (root == nullptr) return const_iterator(root, 0); return const_iterator(root, root-&gt;length); } template &lt;typename Shape&gt; [[nodiscard]] query_iterator&lt;Shape&gt; query_begin(Shape const&amp; shape) noexcept { auto it = query_iterator&lt;Shape&gt;(root, 0, shape); if (root != nullptr) it.descend_first(); return it; } template &lt;typename Shape&gt; [[nodiscard]] query_iterator&lt;Shape&gt; query_end(Shape const&amp; shape) noexcept { if (root == nullptr) return query_iterator&lt;Shape&gt;(root, 0, shape); return query_iterator&lt;Shape&gt;(root, root-&gt;length, shape); } template &lt;typename Shape&gt; [[nodiscard]] const_query_iterator&lt;Shape&gt; query_begin(Shape const&amp; shape) const noexcept { return cquery_begin(shape); } template &lt;typename Shape&gt; [[nodiscard]] const_query_iterator&lt;Shape&gt; query_end(Shape const&amp; shape) const noexcept { return cquery_end(shape); } template &lt;typename Shape&gt; [[nodiscard]] const_query_iterator&lt;Shape&gt; cquery_begin(Shape const&amp; shape) const noexcept { auto it = const_query_iterator&lt;Shape&gt;(root, 0, shape); if (root != nullptr) it.descend_first(); return it; } template &lt;typename Shape&gt; [[nodiscard]] const_query_iterator&lt;Shape&gt; cquery_end(Shape const&amp; shape) const noexcept { if (root == nullptr) return const_query_iterator&lt;Shape&gt;(root, 0, shape); return const_query_iterator&lt;Shape&gt;(root, root-&gt;length, shape); } [[nodiscard]] node_iterator nodes_begin() const noexcept { auto it = node_iterator(root); if (root != nullptr) it.descend_first_node(); return it; } [[nodiscard]] node_iterator nodes_end() const noexcept { return node_iterator(root); } // Views template &lt;typename Shape&gt; [[nodiscard]] bsptree_view&lt;query_iterator&lt;Shape&gt;&gt; query(Shape const&amp; shape) &amp; noexcept { return { query_begin(shape), query_end(shape) }; } template &lt;typename Shape&gt; [[nodiscard]] bsptree_view&lt;const_query_iterator&lt;Shape&gt;&gt; query(Shape const&amp; shape) const&amp; noexcept { return cquery(shape); } template &lt;typename Shape&gt; [[nodiscard]] bsptree_view&lt;const_query_iterator&lt;Shape&gt;&gt; cquery(Shape const&amp; shape) const&amp; noexcept { return { cquery_begin(shape), cquery_end(shape) }; } [[nodiscard]] bsptree_view&lt;node_iterator&gt; nodes() const&amp; noexcept { return { nodes_begin(), nodes_end() }; } // Capacity [[nodiscard]] bool empty() const noexcept { return count == 0; } [[nodiscard]] size_type size() const noexcept { return count; } [[nodiscard]] size_type max_size() const noexcept { return std::numeric_limits&lt;difference_type&gt;::max(); } [[nodiscard]] bounds_type const&amp; bounds() const noexcept { return root_bounds; } // Modifiers // TODO: Remaining? void clear() noexcept { destruct(); } iterator insert(value_type const&amp; value) { return emplace(value); } template &lt;typename... Args&gt; iterator emplace(Args&amp;&amp;... args) { // NOTE: Cheeky emplace, as I don't really know how to extract the key from here return insert(value_type(FWD(args)...)); } iterator insert(value_type&amp;&amp; value) { if (root == nullptr) root = allocate_node(nullptr, root_bounds); // Search the first free subnode auto subnode = root; while (true) { if (subnode-&gt;length &lt; bucket_size) { // Free space in subnode new (&amp;subnode-&gt;data[subnode-&gt;length++]) value_type(std::move(value)); ++count; return iterator(subnode, subnode-&gt;length - 1); } // No free space in current node, find where to traverse auto const&amp; bounds = subnode-&gt;bounds; // Calculate center auto center = std::array&lt;Key, Dim&gt;(); for (size_type i = 0; i &lt; Dim; ++i) center[i] = bounds.offset[i] + bounds.size[i] / Key{2}; // Search for the next subnode // We search by constructing an index bit-wise node_type** next_subnode = nullptr; bounds_type next_subbounds; size_type next_subbounds_index = 0; for (size_type i = 0; i &lt; Dim; ++i) { if (value.first.coordinates[i] &lt; center[i]) { next_subbounds.offset[i] = bounds.offset[i]; next_subbounds.size[i] = center[i] - bounds.offset[i]; } else { next_subbounds_index |= (1 &lt;&lt; i); next_subbounds.offset[i] = center[i]; next_subbounds.size[i] = bounds.offset[i] + bounds.size[i] - center[i]; } } next_subnode = &amp;subnode-&gt;subnodes[next_subbounds_index]; if (*next_subnode == nullptr) { // The next subnode is unallocated *next_subnode = allocate_node(subnode, next_subbounds); } subnode = *next_subnode; } } iterator erase(iterator pos) { return erase_impl(pos); } iterator erase(const_iterator pos) { auto it = erase_impl(pos); return iterator(it.current, it.index); } template &lt;typename Shape&gt; query_iterator&lt;Shape&gt; erase(query_iterator&lt;Shape&gt; pos) { return erase_impl(pos); } template &lt;typename Shape&gt; query_iterator&lt;Shape&gt; erase(const_query_iterator&lt;Shape&gt; pos) { auto it = erase_impl(pos); return query_iterator&lt;Shape&gt;(it.current, it.index, it.shape); } size_type erase(iterator first, iterator last) { return erase_impl(first, last); } size_type erase(const_iterator first, const_iterator last) { return erase_impl(first, last); } template &lt;typename Shape&gt; size_type erase(query_iterator&lt;Shape&gt; first, query_iterator&lt;Shape&gt; last) { return erase_impl(first, last); } template &lt;typename Shape&gt; size_type erase(const_query_iterator&lt;Shape&gt; first, const_query_iterator&lt;Shape&gt; last) { return erase_impl(first, last); } template &lt;typename It&gt; size_type erase(bsptree_view&lt;It&gt; view) { return erase_impl(view.begin(), view.end()); } // TODO: Lookup private: template &lt;typename It&gt; size_type erase_impl(It start, It end) { size_type removed = 0; for (; start != end; ++removed) start = erase_impl(start); return removed; } template &lt;typename It&gt; It erase_impl(It pos) { // Remove element auto node = pos.current; auto idx = pos.index; pos.value()-&gt;~value_type(); for (size_type i = idx + 1; i &lt; node-&gt;length; ++i) { new (&amp;node-&gt;data[i - 1]) value_type(std::move(node-&gt;value(i))); } --count; --node-&gt;length; if (idx &lt; node-&gt;length) { // The position is still valid, contains the next element return pos; } // The position is no longer valid, gotta step pos.move_next(); return pos; } }; // Some aliases template &lt; typename Key, typename T, typename Allocator = std::allocator&lt;std::pair&lt;const point&lt;2, Key&gt;, T&gt;&gt; &gt; using quadtree = bsptree&lt;2, Key, T, Allocator&gt;; template &lt; typename Key, typename T, typename Allocator = std::allocator&lt;std::pair&lt;const point&lt;3, Key&gt;, T&gt;&gt; &gt; using octree = bsptree&lt;3, Key, T, Allocator&gt;; </code></pre> <p>Some sample usage code is provided here:</p> <pre><code>// Create a quadtree with float coordinates, with an area from (0,0) to (100, 100), bucket size of 4 // Associated values are Particle pointers auto qtree = quadtree&lt;float, Particle*&gt;{ {0.0f, 0.0f, 100.0f, 100.0f}, 4 }; // Add a few particles at specific positions qtree.insert({ { 10.0f, 10.0f }, &amp;p1 }); qtree.insert({ { 10.0f, 30.0f }, &amp;p2 }); qtree.insert({ { 30.0f, 30.0f }, &amp;p3 }); // Let's list all the particles intersecting the bounds starting (5, 5) and dimensions (40, 35) // Note that any shape can be used that implements contains(point) and intersects(bounds) for (auto&amp; [pos, particle] : qtree.query(bounds&lt;2, float&gt;{ {5, 5}, {40, 35} })) { // TODO: Do something with the particles } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T12:59:10.840", "Id": "504136", "Score": "0", "body": "Why the macro FWD()? Shouldn't that work with C++17 \"board utilities\"? Besides that, why then only to substitute a single occurrence? PS: I'm curious about a possible upcoming philosophical debate about the goto/label usage :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T13:14:57.150", "Id": "504139", "Score": "0", "body": "@Secundi The macro actually leaked from another header file, but you're right that as a standalone utility I might as well type it out. About the goto, I've tried the loop way and honestly this was the less ugly alternative. I'm open to suggestions tho!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T13:18:17.707", "Id": "504140", "Score": "1", "body": "I think, your gotos are ok so far, no spaghetti code is persistent because of their usage. But I experienced them as a predictable trigger for extensive discussions in the past on code review and SO :)" } ]
[ { "body": "<p>This is absolutely not a &quot;full&quot; review, just a couple of things I noticed.</p>\n<p>First, if you're going to have that macro <code>FWD</code>, you should just do</p>\n<pre><code>#define FWD(x) static_cast&lt;decltype(x)&gt;(x)\n</code></pre>\n<p>You don't need the <code>__VA_ARGS__</code> because nobody should ever be using it with arbitrary expressions (that would mess up the <code>decltype</code>); they should be using it only with names of function parameters, which are always simple identifiers.</p>\n<p>Plus, once you're macro-izing it anyway, there's no reason to pay for function template codegen. Skip <code>std::forward</code> and just inline the <code>static_cast</code>. (I often do this in template code, even without hiding it behind a macro.)</p>\n<hr />\n<pre><code>template &lt;typename... Args&gt;\niterator emplace(Args&amp;&amp;... args) {\n // NOTE: Cheeky emplace, as I don't really know how to extract the key from here\n return insert(value_type(FWD(args)...));\n}\n\niterator insert(value_type&amp;&amp; value) {\n ~~~\n new (&amp;subnode-&gt;data[subnode-&gt;length++]) value_type(std::move(value));\n</code></pre>\n<p>One possible trick here is to treat <code>insert</code> as a special case of <code>emplace</code>, not vice versa. Rewrite as</p>\n<pre><code>iterator insert(value_type&amp;&amp; value) {\n return emplace(std::move(value));\n}\n\ntemplate&lt;class... Args&gt;\niterator emplace(Args&amp;&amp;... args) {\n ~~~\n ::new ((void*)&amp;subnode-&gt;data[subnode-&gt;length]) value_type(static_cast&lt;Args&amp;&amp;&gt;(args)...);\n subnode-&gt;length += 1;\n</code></pre>\n<p>Notice that I'm fully qualifying <code>::new</code> to turn off ADL and make sure we're getting the ordinary core-language &quot;placement new&quot; instead of <code>T::operator new</code> for some user-defined <code>node_type</code>. (This qualification is vastly more important than the one full qualification you actually wrote, in <code>::std::forward</code>!)</p>\n<p>I also split the increment of <code>subnode-&gt;length</code> out of the new-expression so that it's more obvious <em>when</em> it's supposed to happen. If the constructor throws, we don't increment <code>subnode-&gt;length</code>. (Or if I got it wrong and we <em>do</em> want to increment it no matter what, then put the increment on the line <em>before</em> the placement-new.) One side-effect per line, that's my rule.</p>\n<p>Down below, where you use <code>value.first.coordinates[i]</code>, you'll have to have already constructed the pair — and in fact, constructed it in its final location, because <code>mapped_type</code> might not be movable. Therefore, the STL's <code>map</code> actually does have two completely different codepaths for <code>insert</code> and <code>emplace</code>. The <code>insert</code> codepath gets to do the lookup <em>before</em> deciding whether to heap-allocate a new node. The <code>emplace</code> codepath must heap-allocate the node first, and then deallocate it again if a duplicate is found in the tree.</p>\n<hr />\n<p>Speaking of duplicates, do you foresee a need for a <code>quad_multitree</code> that can contain duplicates? Think about the naming bikeshed now, before it's too late! ;)</p>\n<hr />\n<p>Your <code>query_begin() const</code> delegates to <code>cquery_begin() const</code>. I would have done it the other way around, so that you have just <code>query_begin()</code> and <code>query_begin() const</code> whose code differs by a single <code>const</code> qualifier (but otherwise is cut-and-paste identical); and then you can add <code>cquery_begin() const { return query_begin(); }</code> if you really feel like it. Personally I wouldn't bother adding <code>cquery_begin()</code> or <code>cquery()</code>, because, who's the target audience for these methods? Who would voluntarily make a call to the cumbersomely named <code>cquery</code>, when the <code>query</code> method already exists and does the exact same thing?</p>\n<p>I say the same thing about the STL's <code>cbegin</code> and <code>cend</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:10:47.633", "Id": "504238", "Score": "0", "body": "My only problem with emplace is that I don't really know how to properly extract the key from the arguments. Originally I also wanted to base everything on emplace." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T21:47:18.540", "Id": "255523", "ParentId": "255498", "Score": "3" } }, { "body": "<p>[also not a full review]</p>\n<p><strong>spot the algorithm:</strong></p>\n<pre><code> void descend_first_node() {\n if (current == nullptr) return;\n while (true) {\n start:\n for (size_type i = 0; i &lt; subdivision_count; ++i) {\n if (accepts_node(current-&gt;subnodes[i])) {\n current = current-&gt;subnodes[i];\n goto start;\n }\n }\n break;\n }\n }\n</code></pre>\n<p>That's a <code>std::find_if(begin, end, accepts_node)</code>!</p>\n<pre><code> bool move_next_node() {\n if (current == nullptr) return false;\n begin:\n auto parent = current-&gt;parent;\n if (parent == nullptr) return false;\n\n for (size_type i = 0; i + 1 &lt; subdivision_count; ++i) {\n if (current == parent-&gt;subnodes[i]) {\n for (size_type j = i + 1; j &lt; subdivision_count; ++j) {\n if (accepts_node(parent-&gt;subnodes[j])) {\n current = parent-&gt;subnodes[j];\n descend_first_node();\n return true;\n }\n }\n break;\n }\n }\n\n // This was the last node we visited, now stay at the parent\n current = parent;\n if (!accepts_node(current)) goto begin;\n return true;\n }\n</code></pre>\n<p>And that's an <code>auto curr_it = std::find(begin, end, current)</code>, followed by a <code>std::find_if(std::next(curr_it), end, accepts_node)</code>!</p>\n<pre><code> bool move_prev_node() {\n // Step down in reverse order\n for (size_type i = subdivision_count; i &gt; 0; --i) {\n if (accepts_node(current-&gt;subnodes[i - 1])) {\n current = current-&gt;subnodes[i - 1];\n return true;\n }\n }\n // No more children, step up\n // NOTE: We want to keep the child if there are no more nodes, so we don't copy back until found\n auto next = current;\n while (true) {\n auto parent = next-&gt;parent;\n if (parent == nullptr) return false; // We hit the start\n // Now we need to step back in reverse order\n for (size_type i = subdivision_count; i &gt; 1; --i) {\n if (next == parent-&gt;subnodes[i - 1]) {\n for (size_type j = i - 1; j &gt; 0; --j) {\n if (accepts_node(parent-&gt;subnodes[j - 1])) {\n current = parent-&gt;subnodes[j - 1];\n return true;\n }\n }\n break;\n }\n }\n // We gotta step up more\n next = parent;\n }\n return false;\n }\n</code></pre>\n<p>Ooh! That's a <code>std::find_if(rbegin, rend, accepts_node)</code> to start with. Then in the loop we have <code>auto curr_it = std::find(rbegin, rend, next)</code> followed by <code>std::find_if(std::next(curr_it), rend, accepts_node))</code>.</p>\n<hr />\n<p>I wonder if we could change the initial <code>nullptr</code> checks to assertions (should we ever call <code>descend_first_node()</code> when <code>current == nullptr</code>?).</p>\n<p>I'm not really a fan of changing <code>current</code> as we go. It's less complicated to use static or non-member functions to do the iteration.</p>\n<p>If I've not misunderstood too badly what's going on, I'd imagine something a bit more like the following:</p>\n<pre><code> template&lt;class Shape&gt;\n static node_type* find_intersecting_subnode(node_type* root, Shape const&amp; shape) {\n assert(root);\n\n auto begin = root-&gt;subnodes.begin();\n auto end = root-&gt;subnodes.end();\n auto next = std::find_if(begin, end, [&amp;] (node_type* n) { return shape.intersects_bounds(n-&gt;bounds); });\n\n return (next != end ? *next : nullptr);\n }\n\n template&lt;class Shape&gt;\n static node_type* find_intersecting_leaf(node_type* root, Shape const&amp; shape) {\n assert(root);\n\n auto current = root;\n\n while (auto next = find_intersecting_subnode(root, shape))\n current = next;\n\n return current;\n }\n\n template&lt;class Shape&gt;\n static node_type* find_next_intersecting_leaf(node_type* start, Shape const&amp; shape) {\n assert(start);\n\n auto current = start;\n\n while (true) {\n\n auto parent = current-&gt;parent;\n if (!parent) return nullptr;\n\n auto begin = parent-&gt;subnodes.begin();\n auto end = parent-&gt;subnodes.end();\n auto curr = std::find(begin, end, current);\n auto next = std::find_if(std::next(curr), end, [&amp;] (node_type* n) { return shape.intersects_bounds(n-&gt;bounds); });\n \n if (next != end)\n return find_intersecting_leaf(*next, shape);\n \n current = current-&gt;parent;\n\n if (shape.intersects_bounds(current-&gt;bounds))\n break;\n }\n\n return current;\n }\n</code></pre>\n<p>(not actually compiled or tested - reverse iteration left as an exercise <code>;)</code> ).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:09:39.700", "Id": "504237", "Score": "0", "body": "Good catch on the algorithms!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:16:40.923", "Id": "255526", "ParentId": "255498", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T09:09:49.997", "Id": "255498", "Score": "6", "Tags": [ "c++" ], "Title": "Generic C++ BSP tree implementation" }
255498
<p>This is code for a measurement setup that receives a steady stream of UDP data, finds the trigger in one channel and operates on the data in the other channel to enhance the signal and remove noise, and display the enhanced signal.</p> <p>I can see this project growing, and therefor I would like a more robust design and clean control flow and code. There are a lot of global variables there, mostly because they need to be persistent. Also, initialisation needs to happen early on, like in case of the updateable matplotlib plot. Object-orientation could help with the percistency, but I don't feel confident about OO. What would the objects and methods be?</p> <p>Are the variable names helpful? Which ones need improvement?</p> <p>I consider to go multi-process, with parts like reading from the socket, graphics and data evaluation all in seperate processes, and passing data between them in queues. However that makes things complicated quickly. What other options do I have?</p> <pre><code>#!/usr/bin/env python3 import collections import socket from struct import calcsize, unpack_from import numpy as np import argparse import matplotlib.pyplot as plt # Todo: no global variables (?) # Todo: show several old signals, in a faint, transparent way, in the signal graph # Todo: show trigger graph and signal graph over the whole time window in subplots (to make sure the COUNT = '&lt;H' HEADER = '&lt;IQ' DATA = '&lt;ddd' # contains the data of x, y, and z axis commandline_parser = argparse.ArgumentParser(description='Receive the data, which the Sensys MX3DUW sends.') commandline_parser.add_argument('port_num', metavar='P', type=int, help='the port number to listen on for the data') args = commandline_parser.parse_args() previousTimestamp: int = 0 rawData = collections.defaultdict(list) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.bind(('', args.port_num)) # one udp frame holds 8 samples # each sample holds one time stamp and five sensor readings # each sensor has three axis cycle_length = int(2000 / 8) * 8 data = np.zeros((4, cycle_length * 2, 3)) signal_len = 60 # in samples signal = np.zeros(signal_len) noise = np.zeros(signal_len) # prepare plot x = np.arange(signal_len) plt.ion() fig = plt.figure() ax = fig.add_subplot(111) plt.ylim(-15, 15) plt.title(&quot;signal minus noise over many cycles&quot;) line1, = ax.plot(x, signal, 'b-') # Returns a tuple of line objects, thus the comma sensor_num = 4 axis_num = 3 data_line = 0 correction = 0 measurement_cnt = 0 #old_flank = 0 def elvaluate_data(data): # these variables could just as well be local, if they were persistent! global measurement_cnt, signal, noise rising_flanks = find_rising_flanks(data) for flank in rising_flanks: # make sure the rising flank is not too close to the edge if (flank &gt; 200) and (flank &lt; (cycle_length - 200)): useful_flank = flank measurement_cnt += 1 signal = signal + data[2, (useful_flank + 60):(useful_flank + 60 + signal_len), 2] noise = data[2, useful_flank - signal_len - 20:useful_flank - 20, 2] signal = (signal - noise) / measurement_cnt update_plot(signal) stabilize_measurement_window(useful_flank) break def update_plot(signal): line1.set_ydata(signal) # line2.set_ydata(data[2, :, 2]) plt.ylim(np.min(signal), np.max(signal)) fig.canvas.draw() fig.canvas.flush_events() def stabilize_measurement_window(useful_flank): global correction, cycle_length correction = int((1000 - useful_flank) / 2) cycle_length = 2000 - correction # print(&quot;current cycle_length:&quot;, cycle_length, &quot;useful_flank&quot;, useful_flank, &quot;correction:&quot;, correction, # &quot;accelleration: &quot;, old_flank - useful_flank) # old_flank = useful_flank def find_rising_flanks(data): mask = (np.abs(data[1, :, 2]) &gt; 11.0) window = 10 # count the number of times the value is below thresh in the window below_thresh = np.sum([mask[i:len(mask) - window + i] for i in range(window)], axis=0) idx_mask = below_thresh == window rising_flanks = np.where(idx_mask[1:] &amp; (~idx_mask[:-1]))[0] + window + 1 return rising_flanks def read_data(offset, message): for sensor_cnt in range(0, sensor_num): data[sensor_cnt][data_line] = unpack_from(DATA, message, offset) offset += calcsize(DATA) offset += calcsize(DATA) # skip the last last sensor, it is not connected return offset signal = np.zeros(signal_len) try: while True: message, (sender_ip, sender_port) = server_socket.recvfrom(65507) # this is 65535-28 == 65507 # first wait till data is coming, then stop recording once it stops coming in server_socket.settimeout(1.5) # 28 is size of IP + UDP header offset = 0 [sample_num] = unpack_from(COUNT, message, offset) offset += calcsize(COUNT) for sample_cnt in range(0, sample_num): sensor_config, timestamp = unpack_from(HEADER, message, offset) offset += calcsize(HEADER) stepSize = timestamp - previousTimestamp if stepSize &gt; 500: # detect if we dropped packages. if we did, we might want to flush the current cycle print(&quot;Stepsize: &quot; + str(stepSize) + &quot; at time &quot; + str(timestamp)) previousTimestamp = timestamp offset = read_data(offset, message) data_line += 1 if data_line == cycle_length: data_line = 0 elvaluate_data(data) except socket.timeout: print('\n no more data from measurement system') server_socket.close() </code></pre>
[]
[ { "body": "<h2>Spelling</h2>\n<p><code>elvaluate</code> -&gt; <code>evaluate</code></p>\n<h2>Globals</h2>\n<p>They're the enemy of testing and re-entrant modules. Everything from <code>commandline_parser</code> through <code>line1, =</code>, and everything for <code>signal =</code> onward, should be moved into functions. The variables starting at <code>sensor_num</code> onward should be capitalized and kept as global constants.</p>\n<p>The two &quot;easy&quot; ways to transfer global state into a re-entrant place are either conversion to an object where the state exists as members, or convert everything into function parameters and return values, passing around as necessary.</p>\n<p>Define more global constants for the magic numbers within these statements:</p>\n<pre><code>cycle_length = int(2000 / 8) * 8\n\n if (flank &gt; 200) and (flank &lt; (cycle_length - 200)):\n\ncorrection = int((1000 - useful_flank) / 2)\n\ncycle_length = 2000 - correction\n\nmask = (np.abs(data[1, :, 2]) &gt; 11.0)\n\n server_socket.settimeout(1.5)\n\n if stepSize &gt; 500:\n</code></pre>\n<h2>Resource context management</h2>\n<p>rather than</p>\n<pre><code>except socket.timeout:\n print('\\n no more data from measurement system')\n server_socket.close()\n</code></pre>\n<p>Your socket should be closed unconditionally, and in a <code>finally</code>. Better yet, put the</p>\n<pre><code>server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n</code></pre>\n<p>in a <code>with</code>, for example</p>\n<pre><code>def some_upper_server_loop():\n with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server_socket:\n server_socket.bind(('', args.port_num))\n # ...\n</code></pre>\n<h2>Unit tests</h2>\n<p>Add them. Add them while it's still easy and your project is small. You claim that</p>\n<blockquote>\n<p>Unit tests work best with object oriented code</p>\n</blockquote>\n<p>but - happily - this is not whatsoever the case. Often, well-decoupled, re-entrant procedural code is actually easier to unit test than OO code because the incoming state can be more narrow and well-defined as parameters than as class member variables.</p>\n<p>Picking on <code>stabilize_measurement_window</code> for a moment, if it's repaired so that <code>correction</code> is a parameter and <code>cycle_length</code> is a return value:</p>\n<pre><code>def stabilize_measurement_window(useful_flank: float, correction: float) -&gt; int:\n correction = int((1000 - useful_flank) / 2)\n cycle_length = 2000 - correction\n return cycle_length\n\n# ...\n\nassert stabilize_measurement_window(500, 1) == 1749\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T14:58:17.007", "Id": "504151", "Score": "0", "body": "After reading your answer, i looked for the *with* and found https://stackoverflow.com/questions/55661915/how-to-close-a-socket-connection-in-python but it does not show how to close the socket like that, or how the recvfrom-loop would look. Could you add a resource that showcases that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T14:59:50.447", "Id": "504153", "Score": "0", "body": "Unit tests work best with object oriented code. But you didnt suggest to go OO. Do you have a link for doing tests for my kind of code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T15:05:46.750", "Id": "504154", "Score": "0", "body": "You dont touch on the persistence aspect of the variables. Can you please explain how to achive that without global variables? i googled and found either OO with instance variables or global variables, perhaps with a wrapper function to hide the variable itself. @reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T15:47:23.230", "Id": "504157", "Score": "0", "body": "I've made an edit that attempts to answer these three things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T15:48:33.547", "Id": "504158", "Score": "0", "body": "For extended discussion let's switch to https://chat.stackexchange.com/rooms/119252/hardware-driven-data-processing-and-ploting-in-need-of-better-control-flow" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T14:42:03.670", "Id": "255506", "ParentId": "255502", "Score": "1" } } ]
{ "AcceptedAnswerId": "255506", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T11:56:56.850", "Id": "255502", "Score": "2", "Tags": [ "python-3.x", "object-oriented", "numpy", "matplotlib", "multiprocessing" ], "Title": "Hardware driven data processing and ploting in need of better control flow" }
255502
<pre><code>import java.util.*; public class BFS { static LinkedList&lt;Node&gt; tracker = new LinkedList&lt;&gt;(); static Node[] nodes = new Node[]{ new Node(1), new Node(2), new Node(3), new Node(4), new Node(5), new Node(6), }; public static void main(String[] args) { Map&lt;Node, ArrayList&lt;Edge&gt;&gt; graph = new TreeMap&lt;&gt;(); graph.put(nodes[3], addEdges(2,3,5,6)); graph.put(new Node(5), addEdges(3,4,6)); graph.put(new Node(6), addEdges(4,5)); graph.put(new Node(1), addEdges(2,3)); graph.put(new Node(2), addEdges(1,4)); graph.put(new Node(3), addEdges(1,4,5)); traverse(graph, nodes[0]); } private static ArrayList&lt;Edge&gt; addEdges(int... edges) { ArrayList&lt;Edge&gt; edgeList = new ArrayList&lt;&gt;(edges.length); for(int edge : edges) edgeList.add(new Edge(nodes[edge-1])); return edgeList; } static class Node implements Comparable&lt;Node&gt;{ final int vertex; boolean isExplored; Node(int vertex) { this.vertex = vertex; } @Override public int compareTo(Node node) { return this.vertex - node.vertex; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Node)) return false; Node node = (Node) o; return vertex == node.vertex; } @Override public int hashCode() { return Objects.hash(vertex, isExplored); } } static class Edge { Node endNode; boolean isExplored; Edge(Node endPoint) { this.endNode = endPoint; } } private static void traverse(Map&lt;Node, ArrayList&lt;Edge&gt;&gt; graph, Node startNode) { startNode.isExplored = true; tracker.add(startNode); System.out.println(&quot;Start Node -&gt; &quot; + startNode.vertex + &quot; (&quot; + startNode.hashCode() + &quot;)&quot;); while(!tracker.isEmpty()) { Node top = tracker.pop(); System.out.println(&quot;Top Node -&gt;&quot; + top.vertex + &quot; (&quot; + top.hashCode() + &quot;)&quot;); for(Edge edge : graph.get(top)) { System.out.println(&quot;About to check Node -&gt;&quot; + edge.endNode.vertex); if(!edge.isExplored &amp;&amp; !edge.endNode.isExplored) { edge.endNode.isExplored = true; edge.isExplored = true; tracker.add(edge.endNode); System.out.println(&quot;Marked Node -&gt;&quot; + edge.endNode.vertex); } } } } } </code></pre> <p>I have implemented BFS can someone please review it and give recommendations. My main concern(but not limitted to) is the way I defined Graph i.e. Node and Edge class isn't a standard way of dealing with graphs.</p>
[]
[ { "body": "<p><strong>Data structure</strong></p>\n<p>There is no such thing as a &quot;standard graph data structure.&quot; There are a few different data structures for representing a graph and you have implemented the <a href=\"https://en.wikipedia.org/wiki/Adjacency_list\" rel=\"nofollow noreferrer\">adjacency list</a>. The main problem with your implementation is that you have actually implemented the traversal algorithm and the data structure is just an &quot;accessory&quot; to it. It is not possible to extract the graph from the code and use it somewhere else so there is not much point in spending a lot of time reviewing the graph implementation as a data structure.</p>\n<p>I would expect a graph data structrue to be encapsulated in a class named <code>Graph</code> (or an interface named <code>Graph</code> with implementations in classes like <code>AdjacencyListGraph</code> and <code>AdjacencyMatrixGraph</code>). The purpose of the encapsulation is to protect the data structure from manipulation which would break the data structure. For example, as you represent the adjacency as a <code>Map&lt;Node, ArrayList&lt;Edge&gt;&gt;</code> you allow a situation where a single edge could be assigned to two nodes, which would destroy your traversal algorithm.</p>\n<p>Your <code>Edge</code> implementation is tightly bound to the traversal algorithm because you have placed the <code>isExplored</code> attribute to it. A pure graph implementation should not be concerned about how it is traversed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T12:29:20.887", "Id": "255597", "ParentId": "255508", "Score": "0" } } ]
{ "AcceptedAnswerId": "255597", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T15:02:26.183", "Id": "255508", "Score": "0", "Tags": [ "java", "object-oriented", "graph" ], "Title": "BFS implementation in JAVA" }
255508
<p>I believe the provided code can be rewritten shorter. Now one block is basically copy-pasted. In reality I have 6 such blocks.</p> <p>This would be the data:</p> <pre><code>WITH x(id, yr, more_info) AS (SELECT 1, 2020, 'info1' FROM DUAL UNION SELECT 2, 2021, 'info2' FROM DUAL UNION SELECT 3, 2021, 'info3' FROM DUAL UNION SELECT 4, 2020, 'info4' FROM DUAL ) , n(n_id, n_id2, n_year) AS (SELECT 1, 3, 2021 FROM DUAL UNION SELECT 2, 4, 2021 FROM DUAL ) </code></pre> <p>Desired result - complemented table <code>x</code> with up-to-date column <code>yr</code> values and info taken from previous year:<br /> <a href="https://i.stack.imgur.com/NbRQY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NbRQY.png" alt="enter image description here" /></a></p> <p>Current code:</p> <pre><code>WITH x(id, yr, more_info) AS (SELECT 1, 2020, 'info1' FROM DUAL UNION SELECT 2, 2021, 'info2' FROM DUAL UNION SELECT 3, 2021, 'info3' FROM DUAL UNION SELECT 4, 2020, 'info4' FROM DUAL ) , n(n_id, n_id2, n_year) AS (SELECT 1, 3, 2021 FROM DUAL UNION SELECT 2, 4, 2021 FROM DUAL ) SELECT * FROM x -- ========&gt; BLOCK_1 for column n_id &lt;========= UNION SELECT n_id, n_year, more_info FROM (SELECT * FROM x WHERE (id, yr) IN (SELECT id, MAX(yr) FROM x GROUP BY id) ) t1, (SELECT n_id, n_year FROM n WHERE (n_id, n_year) NOT IN (SELECT id, yr FROM x) ) t2 WHERE t1.id = t2.n_id -- ========&gt; BLOCK_2 for column n_id2 &lt;======== UNION SELECT n_id2, n_year, more_info FROM (SELECT * FROM x WHERE (id, yr) IN (SELECT id, MAX(yr) FROM x GROUP BY id) ) t1, (SELECT n_id2, n_year FROM n WHERE (n_id2, n_year) NOT IN (SELECT id, yr FROM x) ) t2 WHERE t1.id = t2.n_id2 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T17:02:22.870", "Id": "504166", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Found a possibility employing <code>UNPIVOT</code></p>\n<pre><code>WITH\nx(id, yr, more_info) AS\n (SELECT 1, 2020, 'info1' FROM DUAL UNION \n SELECT 2, 2021, 'info2' FROM DUAL UNION \n SELECT 3, 2021, 'info3' FROM DUAL UNION \n SELECT 4, 2020, 'info4' FROM DUAL )\n,\nn(n_id, n_id2, n_year) AS\n (SELECT 1, 3, 2021 FROM DUAL UNION \n SELECT 2, 4, 2021 FROM DUAL )\n \nSELECT * FROM x\nUNION\nSELECT id2, n_year, more_info \nFROM (SELECT * \n FROM x\n WHERE (id, yr) IN (SELECT id, MAX(yr)\n FROM x\n GROUP BY id) ) t1,\n (SELECT * FROM n\n UNPIVOT(\n id2\n FOR id_type\n IN (n_id, n_id2) ) ) t2\nWHERE t1.id = t2.id2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T20:51:54.760", "Id": "255521", "ParentId": "255509", "Score": "0" } } ]
{ "AcceptedAnswerId": "255521", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T15:05:01.603", "Id": "255509", "Score": "0", "Tags": [ "sql", "oracle" ], "Title": "Shortening Oracle SQL containing several unions" }
255509
<p>I wrote a little game of snake that where you can see the field in which the snake moves fixed and you can also see the &quot;viewpoint&quot; of the snake, which is basically calculating the positions of all the things in the board taking the snake's head as the center.</p> <p>Right now I'm doing it through two <code>for</code> loops in the following way:</p> <pre><code>for x in range(ROWS): n_x = (x - snake_head[0] - center) % ROWS for y in range(ROWS): n_y = (y - snake_head[1] - center) % ROWS snake_view.grid[n_x, n_y] = field.grid[x,y] </code></pre> <p><code>ROWS</code> is the number of rows the field's grid has (currently <code>15</code>) and it has to be an odd number so there's a center. <code>snake_head</code> is a numpy array of shape <code>(2,)</code> which has the coordinates of head in the field grid. <code>field.grid</code> is a numpy array of shape <code>(ROWS, ROWS)</code> that holds the value of what is in each square of the grid, <code>-1</code> for snake body, <code>-2</code> for snake head, <code>0</code> for nothing or empty, <code>1</code> for a fruit or snack.</p> <p><code>snake_view.grid</code> is a numpy array of the same dimensions as <code>field.grid</code> but has the viewpoint as the snake sees it.</p> <p>This works fine, as you can see in the code that I have pasted below (it is in two different .py files but I have pasted it all into one so it can be copy/pasted easily). But since I want to use this game to train an AI, I need help optimizing it.</p> <p>Is there a way to vectorize this?</p> <pre><code>import pygame import time import random import numpy as np WIN_WIDTH, WIN_HEIGHT = 800, 720 GRID_WIDTH = 400 ROWS = 15 GRID_SPACE = GRID_WIDTH // ROWS class Snake: &quot;&quot;&quot; Snake Object &quot;&quot;&quot; def __init__(self, x, y, body_color = (255,0,0), head_color = (255,0,255)): &quot;&quot;&quot; Initializes the Snake Object on a given coordinate &quot;&quot;&quot; # Position is a list of tuples where each tuple # is a coordinate of the position of a certain # block in the field self.positions = np.array([np.array([x, y])]) self.direction = np.array([0, 1]) # dir is an array of [x,y] values for the direction # of the snake's movement self.vel = 1 self.body_color = body_color self.head_color = head_color self.eaten = False def head(self): # Returns the position of the head return self.positions[-1] def move(self): # Funcion that moves the snake in a particular direction new_head = np.array([self.positions[-1] + self.direction*self.vel]) if not self.eaten: self.positions[:-1] = self.positions[1:] self.positions[-1] = new_head else: self.eaten = False self.positions = np.concatenate((self.positions, new_head)) self.positions = np.mod(self.positions, ROWS) def bite(self): return np.unique(self.positions, axis=0).shape != self.positions.shape def eat(self): self.eaten = True class Fruit: &quot;&quot;&quot; Fruits the snake can eat &quot;&quot;&quot; def __init__(self, grid): x, y = random.sample(grid, 1)[0] grid.remove((x,y)) self.position = np.array([x, y]) class Field(): COLORS = { -1: (255, 0, 0), -2: (255, 0, 255), 0: (50,50,50), 1: (0,255,0) } available_grid = set( (i,j) for i in range(ROWS) for j in range(ROWS) ) available_grid.remove((5,5)) def __init__(self): self.grid = np.zeros((ROWS, ROWS), dtype=np.int8) def empty_grid(self): self.grid = np.zeros((ROWS, ROWS), dtype=np.int8) def update_grid(self, snake=None, fruits=None): self.empty_grid() self.available_grid = set( (i,j) for i in range(ROWS) for j in range(ROWS) ) for pos in snake.positions[:-1]: self.grid[pos[0], pos[1]] = -1 if (pos[0], pos[1]) in self.available_grid: self.available_grid.remove((pos[0], pos[1])) pos = snake.head() self.grid[pos[0], pos[1]] = -2 if (pos[0], pos[1]) in self.available_grid: self.available_grid.remove((pos[0], pos[1])) for fruit in fruits: self.grid[fruit.position[0], fruit.position[1]] = 1 if (fruit.position[0], fruit.position[1]) in self.available_grid: self.available_grid.remove((fruit.position[0], fruit.position[1])) def draw(self, win, offset_x = 0, offset_y = 0): x, y = 0, 0 for row in range(ROWS): pos_x = x * GRID_SPACE + offset_x for col in range(ROWS): pos_y = y * GRID_SPACE + offset_y pygame.draw.rect(win, self.COLORS[self.grid[x,y]], ( pos_x + 2, pos_y + 2, GRID_SPACE - 2, GRID_SPACE -2 )) y+=1 x+=1 y=0 pygame.font.init() STAT_FONT = pygame.font.SysFont(&quot;arial&quot;, 50) SCORE = 0 try: with open(&quot;HIGH_SCORE.txt&quot;, &quot;r&quot;) as f: HIGH_SCORE = f.read() if len(HIGH_SCORE) &gt; 0: HIGH_SCORE = int(HIGH_SCORE) else: HIGH_SCORE = 0 except FileNotFoundError: HIGH_SCORE = 0 def record_hs(): if SCORE &gt; HIGH_SCORE: with open(&quot;HIGH_SCORE.txt&quot;, &quot;w&quot;) as f: f.write(str(SCORE)) def draw_window(win, field, snake_view=None): win.fill((0,0,0)) pygame.draw.line(win, (150, 150, 150), (GRID_WIDTH, 0), (GRID_WIDTH, GRID_WIDTH)) field.draw(win) snake_view.draw(win, offset_x=GRID_WIDTH) text = STAT_FONT.render(f&quot;HIGH SCORE: {HIGH_SCORE}&quot;, 1,(255,255,255)) win.blit(text, (10,10+GRID_WIDTH)) text = STAT_FONT.render(f&quot;Score: {SCORE}&quot;, 1,(255,255,255)) win.blit(text, (10,10+GRID_WIDTH+text.get_height())) pygame.display.update() def main(): # Initializes the screen center = ROWS // 2 + 1 if ROWS % 2 == 1 else ROWS // 2 n_fruits = 5 global HIGH_SCORE, SCORE win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) field = Field() snake = Snake(5,5) snake_view = Field() fruits = [Fruit(field.available_grid) for i in range(n_fruits)] clock = pygame.time.Clock() run = True while run: clock.tick(8) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() # Get the direction the snake should turn from keyboard keys = pygame.key.get_pressed() if keys[pygame.K_DOWN]: if snake.direction[1] != -1: snake.direction[1] = 1 snake.direction[0] = 0 elif keys[pygame.K_LEFT]: if snake.direction[0] != 1: snake.direction[0] = -1 snake.direction[1] = 0 elif keys[pygame.K_UP]: if snake.direction[1] != 1: snake.direction[1] = -1 snake.direction[0] = 0 elif keys[pygame.K_RIGHT]: if snake.direction[0] != -1: snake.direction[0] = 1 snake.direction[1] = 0 snake.move() if snake.bite(): record_hs() run = False snake_head = snake.head() rem = None a = np.abs(snake_head- fruits[0].position) d = np.sqrt(np.square(a[0]) + np.square(a[1])) for fruit in fruits: if abs(snake_head[0] - fruit.position[0]) &lt; 1 and abs(snake_head[1] - fruit.position[1]) &lt; 1: rem = fruit if rem: fruits.remove(rem) fruits.append(Fruit(field.available_grid)) snake.eat() SCORE += 1 field.update_grid(snake, fruits) for x in range(ROWS): n_x = (x - snake_head[0] - center) %ROWS for y in range(ROWS): n_y = (y - snake_head[1] - center) % ROWS snake_view.grid[n_x, n_y] = field.grid[x,y] draw_window(win, field, snake_view) if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<p>Found a better solution using numpy's roll function:</p>\n<pre><code>shift = center - snake_head\nsnake_view.grid = np.roll(field.grid, shift=(shift[0], shift[1]), axis=(0,1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T17:52:12.910", "Id": "255613", "ParentId": "255519", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T20:24:54.087", "Id": "255519", "Score": "0", "Tags": [ "performance", "numpy", "snake-game", "vectorization" ], "Title": "Snake from the viewpoint of the snake" }
255519
<p>I would like to <a href="https://stackoverflow.com/q/1857928">perform a right shift on a negative number</a>. According to the linked answers, performing a right shift on a negative number is implementation-defined, because the sign bit may or may not be maintained. Here's my solution to this.</p> <pre class="lang-c prettyprint-override"><code>int n = -18; printf(&quot;%d %d\n&quot;, n&amp;0xF, ~((~n)&gt;&gt;4)); // Filler </code></pre> <p>I reasoning is that if I <code>not</code> the value to perform the shift then <code>not</code> it back, it won't matter whether the sign bit is shifted or not. However I'm still unsure if this fully solves the problem. Suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-13T10:51:45.833", "Id": "505226", "Score": "1", "body": "How do you form an opinion whether a *procedure* is a *solution*? Suggestion: Try defining and automating a *test*. Finding that impossible, the *problem definition* may be insufficient." } ]
[ { "body": "<p>Sadly, no, your approach does not work if the implementation's right-shift is zero-filling and <code>n</code> is positive.</p>\n<p>Here's my test program: <a href=\"https://godbolt.org/z/WxsjnW\" rel=\"nofollow noreferrer\">https://godbolt.org/z/WxsjnW</a></p>\n<pre><code>int SAR(int n, int sh) {\n return n &gt;&gt; sh; // sign-filling (arithmetic) &quot;shift right&quot;\n}\n\nint SHR(int n, int sh) {\n return (unsigned)n &gt;&gt; sh; // zero-filling (logical) &quot;shift right&quot;\n}\n\nint main() {\n int n = -18;\n printf(&quot;%d %d %d\\n&quot;, SAR(n, 4), ~SAR(~n, 4), ~SHR(~n, 4));\n n = 18;\n printf(&quot;%d %d %d\\n&quot;, SAR(n, 4), ~SAR(~n, 4), ~SHR(~n, 4));\n}\n</code></pre>\n<p>In practice you can rely on right-shift to do the sign-filling thing, because we already have a way to get the zero-filling thing (just cast to unsigned first). But if you really really want a sign-propagating right-shift, perhaps consider reusing integer division, or adding the sign bits back manually after the shift? <a href=\"https://godbolt.org/z/xsonbK\" rel=\"nofollow noreferrer\">https://godbolt.org/z/xsonbK</a></p>\n<pre><code>int SAR(int n, int sh)\n{\n int mask = -(n &lt; 0) * (1 &lt;&lt; sh);\n return ((unsigned)n &gt;&gt; sh) | mask;\n}\n</code></pre>\n<p>I bet Google knows even cleverer tricks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T21:57:27.437", "Id": "504182", "Score": "1", "body": "`return n < 0 ? ~((~(unsigned)n) >> sh) : n >> sh;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:04:48.820", "Id": "504183", "Score": "1", "body": "Your solution doesn't work though, I noticed that `mask` adds a lot more than the missing bits. It should be `(n < 0)*(~((~0u)>>sh))`. What's happening is your mask is all 1 except for the first `sh` least significant bits. It should be only the first `sh` _most_ significant bits are 1 and the rest are 0. `(~0u)` is `UINT_MAX`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:10:51.610", "Id": "504184", "Score": "0", "body": "Or, since my mask would be compile time constant (except for the < 0 check), I could just define it as `(n < 0)*0xF0000000`. Also, instead of `(n < 0)*`, it could be `(-(n < 0))&`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:20:12.027", "Id": "504186", "Score": "0", "body": "Also, how about `return ((unsigned)n >> 4)|((-(n < 0)) << 28);`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T00:29:25.320", "Id": "504196", "Score": "0", "body": "After some testing, using `(n>>31)` seems to be faster than `(n < 0)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T00:37:40.713", "Id": "504197", "Score": "0", "body": "Yes, but if you know that `(n>>31)` is equivalent to `(n < 0)` for signed `n`, then your original issue is already solved — you know that the built-in signed shift operator is sign-extending. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T04:39:56.430", "Id": "504205", "Score": "0", "body": "`(n>>31)` was wrong, I meant `((unsigned)n>>31)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T13:37:55.840", "Id": "504493", "Score": "1", "body": "Note:, with 32-bit `int`, `1 << sh` is UB when `sh==31`. Consider `1u << sh`. `int mask` as `unsigned mask` makes more sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-14T15:20:43.580", "Id": "505322", "Score": "0", "body": "`return n >> sh; // sign-filling (arithmetic) \"shift right\"` relies on implementation-defined behavior: \"An example of implementation-defined behavior is the propagation of the high-order bit when a signed integer is shifted right.\" C17dr § 3.4.1" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T21:09:39.847", "Id": "255522", "ParentId": "255520", "Score": "1" } }, { "body": "<p>First, you should check at preprocess time if shifts are 0 filling or sign filling, because if they are in fact sign filling, then the simple <code>&gt;&gt;4</code> works and using a more complex workaround is only wasting processor power, so only use it where it's needed, and let the preprocessor take care of that for you</p>\n<pre><code>#if ((-1)&gt;&gt;1) &lt; 0 // Check if rightshift on negative number is sign filling or 0 filling\n# define RSHIFT4(N) ((N)&gt;&gt;4)\n#else\n# define RSHIFT4(N) (((N)&gt;&gt;4)|((-((unsigned int)(N)&gt;&gt;0x1F))&lt;&lt;0x1C))\n#endif\n</code></pre>\n<p>However, to be portable, you should replace <code>0x1F</code> and <code>0x1C</code> with <code>(sizeof(int)*CHAR_BIT)-1</code> and <code>(sizeof(int)*CHAR_BIT)-4</code> respectively, for platforms where <code>sizeof(int) != 4</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-14T16:55:34.223", "Id": "505329", "Score": "0", "body": "`((-1)>>1) < 0` is not limited to \"negative number is sign filling or 0 filling\". At PP time, this is `intmax_t` math, although reasonable to assume `int` math works likewise. If one is trying to form highly portable code, `0x1F` and `0x1C` fail for non-32-bit `int` widths." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:36:14.467", "Id": "505817", "Score": "0", "body": "@chux-ReinstateMonica `_Static_assert (sizeof(int) == 4, \"FATAL ERROR!!!! sizeof(int) IS NOT 4!!!!\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:37:43.827", "Id": "505818", "Score": "0", "body": "@chux-ReinstateMonica Or alternatively those could be replaced with `(sizeof(int)<<3)-1` and `(sizeof(int)<<3)-4` respectively" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:47:14.030", "Id": "505820", "Score": "0", "body": "`sizeof (int) << 3`? That's significantly less portable than `sizeof (int) * CHAR_BIT`, which is what I think you meant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:48:55.930", "Id": "505822", "Score": "0", "body": "Why embed a requirement like that (and so rudely) when there's absolutely no need to? (and a `char` and a byte aren't necessarily the same thing!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:50:22.447", "Id": "505824", "Score": "1", "body": "@TobySpeight In C a char is the same as a 1 byte integer, hence `unsigned char` and `signed char`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:55:57.697", "Id": "505826", "Score": "0", "body": "Oops, I see newer C standards define \"byte\" to mean the same as \"char\" (section 3.6). Thanks for the correction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:57:15.103", "Id": "505827", "Score": "0", "body": "@TobySpeight You're welcome" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-13T06:51:31.643", "Id": "255977", "ParentId": "255520", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T20:49:37.773", "Id": "255520", "Score": "-2", "Tags": [ "c" ], "Title": "Portable signed right shift" }
255520
<p>how what am i supposed to make cout so the changes i make show up as the out put because putting a just shows the original string</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { string a = &quot;w is the time for all good people to come to the aide of their country.&quot;; for (int i = 0; a[i] != '\0'; i++) { switch (a[i]) { case 'a':a[i] = '#'; break; case 'e':a[i] = '#'; break; case 'i':a[i] = '#'; break; case 'o':a[i] = '#'; break; case 'u':a[i] = '#'; break; { for (unsigned int l = 0; l &lt; a.length(); l++) { a[l] = toupper(a[l]); } } } cout &lt;&lt; &lt;&lt; endl; return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:11:53.457", "Id": "504185", "Score": "1", "body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T00:25:09.220", "Id": "504194", "Score": "0", "body": "You can spot your error easily if you use good indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T00:27:48.337", "Id": "504195", "Score": "0", "body": "PS. It still does not compile. Please just make sure the code works before you post. Make sure the code is formatted nicely. This will solve 90% of your issues." } ]
[ { "body": "<p>I just want to show you your code when it has been correctly formatted:</p>\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\nint main()\n{\n string a = &quot;w is the time for all good people to come to the aide of their country.&quot;;\n\n for (int i = 0; a[i] != '\\0'; i++)\n {\n switch (a[i])\n {\n case 'a':a[i] = '#';\n break;\n case 'e':a[i] = '#';\n break;\n case 'i':a[i] = '#';\n break;\n case 'o':a[i] = '#';\n break;\n case 'u':a[i] = '#';\n break;\n {\n for (unsigned int l = 0; l &lt; a.length(); l++)\n {\n a[l] = toupper(a[l]);\n }\n }\n\n }\n cout &lt;&lt; &lt;&lt; endl;\n return 0;\n }\n}\n</code></pre>\n<p>I think the errors jump out at you because you can see that the printing is at the wrong level of indentation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T01:00:06.290", "Id": "255530", "ParentId": "255525", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:07:21.017", "Id": "255525", "Score": "-1", "Tags": [ "c++", "c", "strings" ], "Title": "c++ convert all letters in the following text to uppercase and replace all vowels with the '#' character different format from last" }
255525
<p>In my react application I have Tabs done with Material UI. Some of those tabs are shown or hide depending on an option is true or false. The code is not a clean solution but I have no experience working with this and was wondering to see a better solution to what I have done.</p> <p>We have 3 options:</p> <ul> <li>isEngagementPortal</li> <li>isRecruitmentPortal</li> <li>isConsenteesPortal</li> </ul> <p>when one of the above options is true/false the corresponding tab is shown or hide.</p> <p>I was thinking to make it in smaller components or dynamic but have difficulties doing it.</p> <pre><code>&lt;div className={classes.root}&gt; &lt;AppBar className={classes.appBar} position=&quot;static&quot; elevation={0}&gt; &lt;Toolbar disableGutters&gt; &lt;Tabs value={tab} onChange={(e, newValue) =&gt; setTab(newValue)}&gt; &lt;Tab label=&quot;Study Info&quot; /&gt; &lt;Tab label=&quot;Study Tracks&quot; /&gt; &lt;Tab label=&quot;User Admin&quot; /&gt; &lt;Tab label=&quot;Study Locales&quot; /&gt; {isEngagementPortal &amp;&amp; &lt;Tab label=&quot;Resources&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab label=&quot;Pre-screener&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab label=&quot;Consent&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab label=&quot;Manuscript&quot; /&gt;} &lt;Tab label=&quot;Survey&quot; /&gt; {isRecruitmentPortal &amp;&amp; &lt;Tab label=&quot;Translations&quot; /&gt;} &lt;Tab label=&quot;Sites&quot; /&gt; {isConsenteesPortal &amp;&amp; &lt;Tab label=&quot;eConsent&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab label=&quot;Reports&quot; /&gt;} &lt;/Tabs&gt; &lt;/Toolbar&gt; &lt;/AppBar&gt; {console.log(tab)} &lt;Grid&gt; {tab === 0 &amp;&amp; ( &lt;StudyInfo studyId={studyId} refetchQueries={refetchQueries} setAlert={setAlert} /&gt; )} {tab === 1 &amp;&amp; &lt;StudyTracks studyId={studyId} /&gt;} {tab === 2 &amp;&amp; &lt;div&gt;USER ADMIN&lt;/div&gt;} {tab === 3 &amp;&amp; ( &lt;StudyLocales setAlert={setAlert} studyId={studyId} locales={locales} currentLocales={currentLocales} refetchQueries={refetchQueries} /&gt; )} {isEngagementPortal &amp;&amp; tab === 4 &amp;&amp; ( &lt;StudyResources studyId={studyId} locales={locales} /&gt; )} {tab === 5 &amp;&amp; isRecruitmentPortal &amp;&amp; ( &lt;Questionnaire type=&quot;PRESCREENER&quot; preview locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {isRecruitmentPortal &amp;&amp; tab === 6 &amp;&amp; ( &lt;Questionnaire type=&quot;CONSENT&quot; locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {isRecruitmentPortal &amp;&amp; tab === 7 &amp;&amp; ( &lt;Questionnaire type=&quot;MANUSCRIPT&quot; locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {tab === 8 &amp;&amp; ( &lt;Questionnaire type=&quot;SURVEY&quot; preview locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {isRecruitmentPortal &amp;&amp; tab === 9 &amp;&amp; ( &lt;StudyTranslation studyId={studyId} locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} /&gt; )} {tab === 10 &amp;&amp; ( &lt;Sites studyId={studyId} refetchQueries={refetchQueries} setAlert={setAlert} locales={locales} /&gt; )} {isConsenteesPortal &amp;&amp; tab === 11 &amp;&amp; &lt;div&gt;E-CONSENT&lt;/div&gt;} {isRecruitmentPortal &amp;&amp; tab === 12 &amp;&amp; &lt;Reports studyId={studyId} /&gt;} &lt;/Grid&gt; &lt;Alert content={alert} closeDialog={setAlert} /&gt; &lt;/div&gt; ); </code></pre> <p>As requested the full component</p> <pre><code>/* eslint-disable react/prop-types */ import { useState } from 'react'; import { AppBar, Grid, Tab, Tabs, Toolbar, makeStyles, } from '@material-ui/core'; import { get, map } from 'lodash'; import { useQuery } from '@apollo/react-hooks'; import Alert from '../../Dialogs/Alert'; import Loading from '../../Loading'; import StudyInfo from './StudyTabs/StudyInfo'; import StudyTranslation from './StudyTabs/StudyTranslations'; import Questionnaire from './StudyTabs/Questionnaire'; import Sites from './StudyTabs/Sites'; import studyRefetchQueries from './StudyTabs/utils/refetchQueries'; import StudyLocales from './StudyTabs/StudyLocales'; import StudyTracks from './StudyTabs/StudyTracks'; import { getLocales, getFeatureOptions } from './StudyTabs/utils/queries'; import Reports from './StudyTabs/Reports'; import StudyResources from './StudyTabs/StudyResources'; const useStyles = makeStyles(theme =&gt; ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper, color: 'white', }, appBar: { backgroundColor: theme.palette.background.paper, }, })); function Study({ studyId }) { console.log(studyId); const classes = useStyles(); const { loading, data } = useQuery(getLocales, { variables: { studyId } }); const { data: featureOptionsData } = useQuery(getFeatureOptions, { variables: { studyId }, }); const [alert, setAlert] = useState(); const [tab, setTab] = useState(0); const [showTab, setShowTab] = useState(false); if (loading) { return &lt;Loading /&gt;; } const { refetchQueries } = studyRefetchQueries({ studyId }); const locales = get(data, 'locales.nodes') || []; const currentLocales = map(locales, l =&gt; l.locale); const options = get(featureOptionsData, 'featureOptions') || []; console.log(options); const isRecruitmentPortal = options.recruitmentPortal; const isEngagementPortal = options.engagementPortal; const isConsenteesPortal = options.consenteesPortal; console.log(isRecruitmentPortal, isEngagementPortal, isConsenteesPortal); return ( &lt;div className={classes.root}&gt; &lt;AppBar className={classes.appBar} position=&quot;static&quot; elevation={0}&gt; &lt;Toolbar disableGutters&gt; &lt;Tabs value={tab} onChange={(e, newValue) =&gt; setTab(newValue)}&gt; &lt;Tab value={0} label=&quot;Study Info&quot; /&gt; &lt;Tab value={1} label=&quot;Study Tracks&quot; /&gt; &lt;Tab value={2} label=&quot;User Admin&quot; /&gt; &lt;Tab value={3} label=&quot;Study Locales&quot; /&gt; {isEngagementPortal &amp;&amp; &lt;Tab value={4} label=&quot;Resources&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab value={5} label=&quot;Pre-screener&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab value={6} label=&quot;Consent&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab value={7} label=&quot;Manuscript&quot; /&gt;} &lt;Tab value={8} label=&quot;Survey&quot; /&gt; {isRecruitmentPortal &amp;&amp; &lt;Tab value={9} label=&quot;Translations&quot; /&gt;} &lt;Tab value={10} label=&quot;Sites&quot; /&gt; {isConsenteesPortal &amp;&amp; &lt;Tab value={11} label=&quot;eConsent&quot; /&gt;} {isRecruitmentPortal &amp;&amp; &lt;Tab value={12} label=&quot;Reports&quot; /&gt;} &lt;/Tabs&gt; &lt;/Toolbar&gt; &lt;/AppBar&gt; {console.log(tab)} &lt;Grid&gt; {tab === 0 &amp;&amp; ( &lt;StudyInfo studyId={studyId} refetchQueries={refetchQueries} setAlert={setAlert} /&gt; )} {tab === 1 &amp;&amp; &lt;StudyTracks studyId={studyId} /&gt;} {tab === 2 &amp;&amp; &lt;div&gt;USER ADMIN&lt;/div&gt;} {tab === 3 &amp;&amp; ( &lt;StudyLocales setAlert={setAlert} studyId={studyId} locales={locales} currentLocales={currentLocales} refetchQueries={refetchQueries} /&gt; )} {isEngagementPortal &amp;&amp; tab === 4 &amp;&amp; ( &lt;StudyResources studyId={studyId} locales={locales} /&gt; )} {tab === 5 &amp;&amp; isRecruitmentPortal &amp;&amp; ( &lt;Questionnaire type=&quot;PRESCREENER&quot; preview locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {isRecruitmentPortal &amp;&amp; tab === 6 &amp;&amp; ( &lt;Questionnaire type=&quot;CONSENT&quot; locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {isRecruitmentPortal &amp;&amp; tab === 7 &amp;&amp; ( &lt;Questionnaire type=&quot;MANUSCRIPT&quot; locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {tab === 8 &amp;&amp; ( &lt;Questionnaire type=&quot;SURVEY&quot; preview locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} studyId={studyId} /&gt; )} {isRecruitmentPortal &amp;&amp; tab === 9 &amp;&amp; ( &lt;StudyTranslation studyId={studyId} locales={currentLocales} refetchQueries={refetchQueries} setAlert={setAlert} /&gt; )} {tab === 10 &amp;&amp; ( &lt;Sites studyId={studyId} refetchQueries={refetchQueries} setAlert={setAlert} locales={locales} /&gt; )} {isConsenteesPortal &amp;&amp; tab === 11 &amp;&amp; &lt;div&gt;E-CONSENT&lt;/div&gt;} {isRecruitmentPortal &amp;&amp; tab === 12 &amp;&amp; &lt;Reports studyId={studyId} /&gt;} &lt;/Grid&gt; &lt;Alert content={alert} closeDialog={setAlert} /&gt; &lt;/div&gt; ); } export default Study; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T23:32:12.090", "Id": "504188", "Score": "1", "body": "Could you post the entire component? It looks like you're missing part of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T08:03:35.337", "Id": "504217", "Score": "1", "body": "@ScottyJamison Added the full component please have a look :)" } ]
[ { "body": "<p>Each tab seems to have three pieces of data/logic associated with it:</p>\n<ul>\n<li>The tab label</li>\n<li>The tab content</li>\n<li>When to render it</li>\n</ul>\n<p>A good way to simplify your component would be to actually group these bits of related logic together. This can be done by using an array of objects, as an example.</p>\n<p>Some other suggestions to help improve your overall component:</p>\n<ul>\n<li>Prefer using standard javascript features over lodash ones when convenient. i.e. just use <code>array.map(fn)</code> instead of lodash's <code>map(array, fn)</code>. More people know how to use the standard language features than lodash-specific functions, so it makes the code easier to read and maintain by other people.</li>\n<li>Likewise, if your target browsers support it, or if you're transpiling these features, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\">optional chaining operator (?.)</a> instead of lodash's get(). The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">nullish coalescing operator (??)</a> can be used instead of <code>||</code> in some cases too.</li>\n<li>At one point you're getting the featureOptions property from an object, and defaulting to an empty array. You then access different values from the result. Did you mean to default to an empty object?</li>\n<li>Things like network resources can be taken out into it's own custom hook to try and move out some of the slightly lower-level logic from the main component.</li>\n</ul>\n<p>The following is an example that puts these suggestions together.</p>\n<pre><code>const Study = ({ studyId }) =&gt; {\n const classes = useStyles();\n const { loading, options, locales } = useNetworkResources(studyId)\n const [alert, setAlert] = useState();\n const [selectedTabId, setSelectedTabId] = useState(0);\n\n const visibleTabs = tabs.filter(tab =&gt; tab.isVisible(options));\n const selectedTab = visibleTabs[selectedTabId]\n\n if (loading) {\n return &lt;Loading /&gt;;\n }\n \n return (\n &lt;div className={classes.root}&gt;\n &lt;TabBar\n selectedTabId={selectedTabId}\n setSelectedTabId={setSelectedTabId}\n visibleTabs={visibleTabs}\n /&gt;\n &lt;Grid&gt;\n {selectedTab.isVisible(options) &amp;&amp; (\n &lt;selectedTab.Content\n setAlert={setAlert}\n studyId={studyId}\n locales={locales}\n currentLocales={locales.map(l =&gt; l.locale)}\n refetchQueries={studyRefetchQueries({ studyId }).refetchQueries}\n /&gt;\n )}\n &lt;/Grid&gt;\n &lt;Alert content={alert} closeDialog={setAlert} /&gt;\n &lt;/div&gt;\n );\n};\n\nconst TabBar = ({ selectedTabId, setSelectedTabId, visibleTabs }) =&gt; (\n &lt;AppBar className={classes.appBar} position=&quot;static&quot; elevation={0}&gt;\n &lt;Toolbar disableGutters&gt;\n &lt;Tabs value={selectedTabId} onChange={(e, newValue) =&gt; setSelectedTabId(newValue)}&gt;\n {visibleTabs.map(({ label }) =&gt; &lt;Tab key={label} label={label} /&gt;)}\n &lt;/Tabs&gt;\n &lt;/Toolbar&gt;\n &lt;/AppBar&gt;\n);\n\nconst useNetworkResources = studyId =&gt; {\n const { loading, data: rawLocalesData } = useQuery(getLocales, { variables: { studyId } });\n const { data: rawOptionsData } = useQuery(getFeatureOptions, { variables: { studyId }, });\n return {\n loading,\n options: rawOptionsData?.featureOptions ?? {},\n locales: rawLocalesData?.locales?.nodes ?? [],\n };\n};\n\nconst tabs = [\n {\n label: 'Study Info',\n isVisible: () =&gt; true,\n Content: ({ studyId, refetchQueries, setAlert }) =&gt;(\n &lt;StudyInfo\n studyId={studyId}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n /&gt;\n ),\n },\n {\n label: 'Study Tracks',\n isVisible: () =&gt; true,\n Content: ({ studyId }) =&gt; &lt;StudyTracks studyId={studyId} /&gt;,\n },\n {\n label: 'User Admin',\n isVisible: () =&gt; true,\n Content: () =&gt; &lt;div&gt;USER ADMIN&lt;/div&gt;,\n },\n {\n label: 'Study Locales',\n isVisible: () =&gt; true,\n Content: ({ setAlert, studyId, locales, currentLocales, refetchQueries }) =&gt; (\n &lt;StudyLocales\n setAlert={setAlert}\n studyId={studyId}\n locales={locales}\n currentLocales={currentLocales}\n refetchQueries={refetchQueries}\n /&gt;\n ),\n },\n {\n label: 'Resources',\n isVisible: options =&gt; options.isEngagementPortal,\n Content: ({ studyId, locales }) =&gt; &lt;StudyResources studyId={studyId} locales={locales} /&gt;,\n },\n {\n label: 'Pre-screener',\n isVisible: options =&gt; options.isRecruitmentPortal,\n Content: ({ currentLocales, refetchQueries, setAlert, studyId }) =&gt; (\n &lt;Questionnaire\n type=&quot;PRESCREENER&quot;\n preview\n locales={currentLocales}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n studyId={studyId}\n /&gt;\n ),\n },\n {\n label: 'Consent',\n isVisible: options =&gt; options.isRecruitmentPortal,\n Content: ({ currentLocales, refetchQueries, setAlert, studyId }) =&gt; (\n &lt;Questionnaire\n type=&quot;CONSENT&quot;\n locales={currentLocales}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n studyId={studyId}\n /&gt;\n ),\n },\n {\n label: 'Manuscript',\n isVisible: options =&gt; options.isRecruitmentPortal,\n Content: ({ currentLocales, refetchQueries, setAlert, studyId }) =&gt; (\n &lt;Questionnaire\n type=&quot;MANUSCRIPT&quot;\n locales={currentLocales}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n studyId={studyId}\n /&gt;\n ),\n },\n {\n label: 'Survey',\n isVisible: () =&gt; true,\n Content: ({ currentLocales, refetchQueries, setAlert, studyId }) =&gt; (\n &lt;Questionnaire\n type=&quot;SURVEY&quot;\n preview\n locales={currentLocales}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n studyId={studyId}\n /&gt;\n ),\n },\n {\n label: 'Translations',\n isVisible: options =&gt; options.isRecruitmentPortal,\n Content: ({ studyId, currentLocales, refetchQueries, setAlert }) =&gt; (\n &lt;StudyTranslation\n studyId={studyId}\n locales={currentLocales}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n /&gt;\n ),\n },\n {\n label: 'Sites',\n isVisible: () =&gt; true,\n Content: () =&gt; (\n &lt;Sites\n studyId={studyId}\n refetchQueries={refetchQueries}\n setAlert={setAlert}\n locales={locales}\n /&gt;\n ),\n },\n {\n label: 'eConsent',\n isVisible: options =&gt; options.isConsenteesPortal,\n Content: () =&gt; &lt;div&gt;E-CONSENT&lt;/div&gt;,\n },\n {\n label: 'Reports',\n isVisible: options =&gt; options.isRecruitmentPortal,\n Content: ({ studyId }) =&gt; &lt;Reports studyId={studyId} /&gt;,\n },\n];\n</code></pre>\n<p><strong>Update</strong> Took out logic and explanation having to do with a faulty assumption of how the O.P.'s three booleans were used. (The O.P. corrected me in the comments). Also added more feedback because the O.P. provided the entire component to review, and fixed some bugs (also mentioned in the comments).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T08:08:16.353", "Id": "504219", "Score": "0", "body": "Seems nice what you add I need to test. The assumption is that we can have all of them true as false. Or like one true and the rest false or so on. All depends on the setup configuration as a user can decide to have all, one or some of the portals activated, \nI added my full component to have a look :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T09:41:04.620", "Id": "504233", "Score": "0", "body": "I tested but I'm stuck on this `const selectedTab = tabs[selectedTab];` it is saying is undefined and that was used before is defined and don't know what to do. \nHere you can see my changes\nhttps://pastebin.com/E5P5tGR8" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:05:58.040", "Id": "504236", "Score": "0", "body": "Sorry, that was a mess-up, I didn't test the code above. Do `const selectedTab = tabs[selectedTabId]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:15:33.330", "Id": "504239", "Score": "0", "body": "Thanks but now I have another issue. When I hide the tabs the corresponding content is not aligned with the tab. For example I hide the Pre-screener tab and what is about that. \nWhen I click on the Survey tab I see that pre-screenr as selectedTab and not Survey." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:31:24.917", "Id": "504242", "Score": "0", "body": "I presume that's because setSelectedTabId() is receiving the tab index after hidden items have been filtered out while the content is indexing into the tabs with the unfiltered list. You can filter out hidden items from the list before indexing into it to fix this. I've updated my answer to include these bug fixes, along with more feedback related to the rest of the component you recently shared." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:36:55.863", "Id": "504243", "Score": "1", "body": "Yes thanks I saw the comments and regarding lodash parts I'm doing to be consistent on how the project is done before me. The featureOptions are coming from a GraphQL query and as default are all false so in reality I think will never be an empty array. \nThe network hook thing is a good idea but I need to discuss internally if can move like that :) but was great explanations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T12:27:54.013", "Id": "504257", "Score": "0", "body": "I have a last question about this but to re render the tab bar to reflect the changes of the options how can I do that with useEffect()? \nNow when the options changes the tabs are not and they should change based on the options.\nI think I need to useEffect but not sure how. Can you help me with this last thing? thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T16:25:40.863", "Id": "504277", "Score": "0", "body": "Nah, that shouldn't need useEffect(). If the option's object changes, it *should* auto-update the TabBar component (unless you changed it by mutation, which is a no-no in react). You should the options object is actually changing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T16:26:04.333", "Id": "504278", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/119283/discussion-between-scotty-jamison-and-jakub)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T02:50:52.347", "Id": "255535", "ParentId": "255527", "Score": "3" } } ]
{ "AcceptedAnswerId": "255535", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:24:02.170", "Id": "255527", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "React material UI tabs in a different way" }
255527
<p>For the last couple of months, I have started to learn Haskell and since I am following a course on functional programming soon, I thought I would test my current skills. So what I did was create an HTML parser that transforms this input:</p> <pre><code> body div#container.classA span;attr=attr text1 span.classB text2 div#other span test div div.class </code></pre> <p>Into this formatted HTML file:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;HTML&gt; &lt;body&gt; &lt;div id='container' class='classA'&gt; &lt;span attr='attr'&gt;text1&lt;/span&gt; &lt;span class='classB'&gt;text2&lt;/span&gt; &lt;/div&gt; &lt;div id='other'&gt; &lt;span&gt;test&lt;/span&gt; &lt;div&gt; &lt;div class='class'&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And I was wondering if the implementation could be more straightforward, if I am using the correct syntax or if I am generally doing an okay job using the concepts Haskell offers. Here is my code:</p> <pre><code>module HtmlParser ( parse, toHtmlFile, HtmlObject ) where data HtmlObject = HtmlContent String | HtmlElement { tag :: String, attributes :: [(String, String)], children :: [HtmlObject] } deriving (Show) ----- Exported Functions ----- parse :: String -&gt; [HtmlObject] parse xs = recReverse $ foldl parse' [] (lines xs) where parse' ls s = let element = stringToElement s in insertElement element ls toHtmlFile :: String -&gt; String toHtmlFile xs = &quot;&lt;!DOCTYPE html&gt;\n&lt;html&gt;&quot; ++ toString (parse xs) [] ++ &quot;\n&lt;/html&gt;&quot; ----- Step 1: Parsing the input ----- stringToElement :: String -&gt; (HtmlObject, Int) stringToElement xs = (parseString s, i) where (s,i) = getIndentation xs getIndentation :: String -&gt; (String, Int) getIndentation [] = ([], 0) getIndentation xs'@(x:xs) | x == ' ' = (a, b+1) | otherwise = (xs', 0) where (a,b) = getIndentation xs parseString :: String -&gt; HtmlObject parseString = handleInput . splitInput ----- Step 2: Splitting the input line into separate parts ----- splitInput :: String -&gt; (String, String, String) splitInput s = splitInput (split ' ' s) where splitInput (temp,msg) = (tag, attrs, msg) where (tag, attrs) = split ';' temp handleInput :: (String, String, String) -&gt; HtmlObject handleInput (tag, attrs, msg) = addMessage msg $ addAttributes attrs $ createElement tag ----- Step 3: Handling separate parts of the HtmlElement ----- createElement :: String -&gt; HtmlObject createElement s = HtmlElement tag (getAttr id &quot;id&quot; ++ getAttr classes &quot;class&quot;) [] where (tag, id, classes) = splitElement s splitElement :: String -&gt; (String, String, String) splitElement xs = splitElement' $ split '.' xs where splitElement' (temp, classes) = (tag, id, classes) where (tag, id) = split '#' temp getAttr :: String -&gt; String -&gt; [(String, String)] getAttr [] _ = [] getAttr xs name = [(name, replace '.' ' ' xs)] getAttributes :: String -&gt; [(String, String)] getAttributes [] = [] getAttributes xs = split '=' attribute : getAttributes rest where (attribute, rest) = split ',' xs addMessage :: String -&gt; HtmlObject -&gt; HtmlObject addMessage [] e = e addMessage msg (HtmlElement tag attrs children) = HtmlElement tag attrs (HtmlContent msg : children) ----- Step 4: Inserting the HtmlElement in the tree structure ----- insertElement :: (HtmlObject, Int) -&gt; [HtmlObject] -&gt; [HtmlObject] insertElement (obj, 0) ls = obj : ls insertElement (obj, n) ((HtmlElement tag attr children) : ls) = HtmlElement tag attr (insertElement (obj, n-1) children) : ls insertElement _ _ = error &quot;Wrong File Format&quot; ----- Step 5: Turn objects in a valid HTML file ----- toString :: [HtmlObject] -&gt; String -&gt; String toString [] _ = [] toString ((HtmlContent msg):xs) ys = msg toString ((HtmlElement tag attrs children):xs) ys = &quot;\n&quot; ++ ys ++ &quot;&lt;&quot; ++ tag ++ attributesToString attrs ++ &quot;&gt;&quot; ++ toString children ('\t':ys) ++ newline ++ &quot;&lt;/&quot; ++ tag ++ &quot;&gt;&quot; ++ toString xs ys where newline = if (isContent children) then &quot;&quot; else &quot;\n&quot; ++ ys attributesToString :: [(String, String)] -&gt; String attributesToString [] = [] attributesToString ((a,b):rest) = ' ' : a ++ &quot;='&quot; ++ b ++ &quot;'&quot; ++ attributesToString rest ----- Utility Functions ----- split :: Eq a =&gt; a -&gt; [a] -&gt; ([a], [a]) split _ [] = ([], []) split e (x:xs) | e == x = ([], xs) | otherwise = (x : a, b) where (a,b) = split e xs replace :: Eq a =&gt; a -&gt; a -&gt; [a] -&gt; [a] replace _ _ [] = [] replace x y (z:zs) | x == z = y : replace x y zs | otherwise = z : replace x y zs recReverse :: [HtmlObject] -&gt; [HtmlObject] recReverse [] = [] recReverse xs = reverse $ map recReverse' xs where recReverse' (HtmlElement a b c) = HtmlElement a b (recReverse c) recReverse' a = a isContent :: [HtmlObject] -&gt; Bool isContent [] = True isContent [(HtmlContent _)] = True isContent _ = False </code></pre> <p>I think the main concept that I am trying to improve upon is creating functions from other functions. Whereas a lot of functions get re-used in libraries, I can't seem to get a set of functions working which can work together to create new functions. How could I restructure this parser, such that I can reuse functions in multiple spots and not have lots of different functions?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:26:49.457", "Id": "255528", "Score": "2", "Tags": [ "html", "parsing", "haskell" ], "Title": "Custom HTML parser in Haskell" }
255528
<p>I 've made a tic-tac-toe game in C, I want some tips on how to improve it since the program is a little bit too long. <br><strong>(500 lines with comments)</strong><br> How I done the game: <br> Mapped a 3x3 Matrix like the board bellow: <br></p> <pre><code>/* ------------------------- | 1 || 2 || 3 | ------------------------- | 4 || 5 || 6 | ------------------------- | 7 || 8 || 9 | ------------------------- */ </code></pre> <p>With the 3x3 i did a switch with the position, as show in the code snippets bellow I think that this solution is a little bit too long, so as the algorithms to calculate the win on a given column, row or diagonal. <br><br> Here I will show some snipets of the code:</p> <pre><code>/* is_pos_free takes as arg1 a square matrix (board), state (from the enum on Main), and a position (from 1 trought 9) return: return 1 if position is free return 0 if position isn't free return -1 if position isn't within range of 1 until 9 (position &lt; 1 or position &gt; 9) */ int is_pos_free(int board[SIZE][SIZE],int state,int pos){ int cond; switch(pos){ case 1: if(state == 0 &amp;&amp; board[0][0] == 0 ){ board[0][0] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[0][0] == 0){ board[0][0] = 2; break; } else{ cond = 0; break; } case 2: if(state == 0 &amp;&amp; board[0][1] == 0){ board[0][1] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[0][1] == 0){ board[0][1] = 2; break; } else{ cond = 0; break; } case 3: if(state == 0 &amp;&amp; board[0][2] == 0){ board[0][2] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[0][2] == 0){ board[0][2] = 2; break; } else{ cond = 0; break; } case 4: if(state == 0 &amp;&amp; board[1][0] == 0){ board[1][0] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[1][0] == 0){ board[1][0] = 2; break; } else{ cond = 0; break; } case 5: if(state == 0 &amp;&amp; board[1][1] == 0){ board[1][1] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[1][1] == 0){ board[1][1] = 2; break; } else{ cond = 0; break; } case 6: if(state == 0 &amp;&amp; board[1][2] == 0){ board[1][2] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[1][2] == 0){ board[1][2] = 2; break; } else{ cond = 0; break; } case 7: if(state == 0 &amp;&amp; board[2][0] == 0){ board[2][0] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[2][0] == 0){ board[2][0] = 2; break; } else{ cond = 0; break; } case 8: if(state == 0 &amp;&amp; board[2][1] == 0){ board[2][1] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[2][1] == 0){ board[2][1] = 2; break; } else{ cond = 0; break; } case 9: if(state == 0 &amp;&amp; board[2][2] == 0){ board[2][2] = 1; cond = 1; break; } else if(state == 1 &amp;&amp; board[2][2] == 0){ board[2][2] = 2; break; } else{ cond = 0; break; } default: printf(&quot;%s&quot;,RED); printf(&quot;Error 2\n&quot;); printf(&quot;%s&quot;,YELLOW); printf(&quot;Position &lt;1 or Position &gt; 9\nType a valid position\n&quot;); cond = -1; break; } return cond; } /* calculate_win_line takes as arg1 a square matrix (board), and the size of the board the function calculate if the player or the machine has won on a line return: returns 1 for 'O' won returns 2 for 'X' won default 0 -&gt; No one won */ int calculate_win_line(int board[][SIZE],int size){ int j; int k; int win_count_O ; int win_count_X ; int who_won = 0; for(j = 0;j&lt;size;j++){ win_count_O = 0; win_count_X = 0; for(k = 0;k&lt;size;k++){ if(board[j][k] == 1){ win_count_O++; } else if(board[j][k] == 2){ win_count_X++; } if(win_count_O == 3){ who_won = 1; break; } else if(win_count_X == 3 ){ who_won = 2; break; } } } return who_won; } /* calculate_win_col takes as arg1 a square matrix (board), and the size of the board the function calculate if the player or the machine has won on a column return: returns 1 for 'O' won returns 2 for 'X' won default 0 -&gt; No one won */ int calculate_win_col(int board[][SIZE],int size){ int j; int k; int win_count_O = 0; int win_count_X = 0; int who_won = 0; for(j = 0;j&lt;size;j++){ win_count_O = 0; win_count_X = 0; for(k = 0;k&lt;size;k++){ if(board[k][j] == 1){ win_count_O++; } else if(board[k][j] == 2){ win_count_X++; } if(win_count_O == 3){ who_won = 1; break; } if(win_count_X == 3){ who_won = 2; break; } } } return who_won; } /* calculate_win_diagonal takes as arg1 a square matrix (board), and the size of the board the function calculate if the player or the machine has won on a main diagonal or on a antidiagonal of the given matrix return: returns 1 for 'O' won on a main diagonal or antidiagonal returns 2 for 'X' won on a main diagonal or antidiagonal default 0 -&gt; No one won */ int calculate_win_diagonal(int board[][SIZE],int size){ int j; int k; int win_count_X = 0; int win_count_O = 0; int who_won = 0; for(j = 0;j&lt;size;j++){ if(board[j][j] == 1){ win_count_O++; } if(board[j][j] == 2){ win_count_X++; } } if(win_count_O == 3){ return who_won = 1; } else if(win_count_X == 3){ return who_won = 2; } else{ win_count_O = 0; win_count_X = 0; k = size - 1; } for(j = 0;j&lt;size;j++){ if(board[j][k] == 1){ win_count_O++; } else if(board[j][k] == 2){ win_count_X++; } k--; } if(win_count_O == 3){ who_won = 1; } else if(win_count_X == 3){ who_won = 2; } return who_won; } </code></pre> <p>Link to complete code:<br> <a href="https://pastebin.com/BFULPtJB" rel="nofollow noreferrer">https://pastebin.com/BFULPtJB</a> <br> <br> I'd like sugestions on how to improve it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T23:36:22.107", "Id": "504189", "Score": "1", "body": "The magic numbers are confusing; instead of an `int` array, a more human-readable `enum { FREE, X, O }` would be good for readability. You will have to explain what `state` and `pos` are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T08:47:42.320", "Id": "504222", "Score": "0", "body": "Please be aware that we can review *only the code in the question*. If you want a review of the whole program, it needs to be shown directly in the question, not hidden behind a link." } ]
[ { "body": "<p>I actually created a tic-tac-toe program in C several years ago for the fun of it as I was learning the ins and outs of the C language. Since this post I've updated it and added some additional comments for understanding. Take a look yourself <a href=\"https://pastebin.com/Dg6vKu5s\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>I believe it's redundant to have two functions with nearly identical functionality (determine a win on the current state of the board) separated and essentially return identical information. For example, you have <code>calculate_win_diagonal(..)</code>, <code>calculate_win_col(..)</code>, and <code>calculate_win_line(..)</code>. In my code, I write one win condition function that takes the current state of the board and determines if there is a win condition (3-in-a-row) on the board, regardless if its a row, column or diagonal.</p>\n<p>Your algorithm in particular for evaluating a current win on the state of the board is suitable. In the instance you wish to increase the size of the board, your algorithm is dynamic and flexible to the dimensions of the board.</p>\n<p>Having a <code>position</code>, <code>pos</code> variable is perfectly acceptable. However, problems rise when using a two-dimensional array. Your game-board is two-dimensional, and using a single variable to describe the position in a two-dimensional array can lead to some problems. You could cut down on a lot of the desired space (especially in your <code>is_pos_free(..)</code> function) by instead using a one-dimensional array for the game-board. This way you don't have to do the necessary calculations to get a pair of positions from a single variable. If you intend on keeping the two-dimensional array for your <code>int board[SIZE][SIZE]</code>, you could have a function that looks something like this:</p>\n<p><code>void get_position_pair(int pos /*in-parameter*/ , int* row /*in-out*/, int* col /*in-out*/) { .. }</code></p>\n<p>and calling it by</p>\n<p><code>get_position_pair(pos, &amp;row, &amp;col);</code></p>\n<p>If you're not sure how in-out parameters work, I've attached a link <a href=\"https://www.cs.usfca.edu/%7Ewolber/SoftwareDev/C/paramPassing.htm\" rel=\"nofollow noreferrer\">here</a>. Welcome to CR.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T05:03:17.067", "Id": "255541", "ParentId": "255529", "Score": "0" } }, { "body": "<p>I dislike <code>else if</code> where the preceding controlled statement diverted program flow unconditionally (<code>continue/break/return</code>).\nWith a statement like</p>\n<pre class=\"lang-none prettyprint-override\"><code>if (c1)\n modify O // not touching X\nelse if (c2)\n modify X // not touching O\n</code></pre>\n<p>, don't continue</p>\n<pre class=\"lang-none prettyprint-override\"><code>if (c3(O))\n sO\nif (c4(X))\n sX\n</code></pre>\n<p>(<code>calculate_win_col/line()</code>):</p>\n<pre><code> switch (board[j][k]) {\n case O_PLAY:\n if INaROW &lt;= ++win_count_O)\n return O_PLAY;\n break;\n case X_PLAY:\n if INaROW &lt;= ++win_count_X)\n return X_PLAY;\n break;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T21:11:12.450", "Id": "270394", "ParentId": "255529", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-02T22:32:40.013", "Id": "255529", "Score": "2", "Tags": [ "algorithm", "c", "tic-tac-toe" ], "Title": "tic-tac-toe algorithm improvement in C" }
255529
<p>I'm working on a program to program the bisection method: <a href="https://www.calculushowto.com/bisection-method/" rel="nofollow noreferrer">https://www.calculushowto.com/bisection-method/</a></p> <p>I know there's questions similar to this one but I want to see if my own one works.</p> <pre><code>double func(double x) { return x * x - 3 * x - 1; } double bisect(double (*f)(double), double a, double b, double e) { double mid = (a + b) / 2; while (abs(mid) &gt; e) { if (f(mid) &lt; 0) { mid = a; } else { mid = b; } } return mid; } </code></pre> <p><code>func()</code> is the function I'm using to test the bisection method. In the other function, <code>a</code> is the left point, <code>b</code> is the right point and <code>e</code> is the error bound.</p> <p>Any mistakes that I didn't catch?</p>
[]
[ { "body": "<ul>\n<li><p>You seem to assume that there is a root between <code>a</code> and <code>b</code>. If it is not the case, <code>bisect</code> will never terminate. Assuming that <code>f</code> is well-behaving, it would be prudent to test that <code>f(a)</code> and <code>f(b)</code> have different signs before proceeding.</p>\n<p>Also, consider the case <code>f(a) &gt; 0 &amp;&amp; f(b) &lt; 0</code></p>\n</li>\n<li><p><code>bisect</code> doesn't find the approximation of the root. It finds an argument at which <code>f</code> is reasonably small. It could be quite far from the root. A prudent termination condition is <code>b - a &lt; e</code>.</p>\n</li>\n<li><p><code>a + b</code> may overflow, and then all bets are off. Consider <code>mid = a + (b - a)/2</code>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T08:50:58.107", "Id": "504223", "Score": "0", "body": "`a` and `b` are floating-point numbers, which makes the overflow less likely. But does mean we ought to be checking for non-finite values (infinities and NANs) before we do *any* arithmetic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:33:13.563", "Id": "504526", "Score": "0", "body": "\"bisect will never terminate.\" --> Likely the integer truncation of `abs(mid)` will readily cause the loop to quit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:35:44.817", "Id": "504527", "Score": "0", "body": "Given `a,b` are unordered, `b - a` can overflow like `a + b`. Alternate `a/2 + b/2;`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T06:41:14.777", "Id": "255546", "ParentId": "255532", "Score": "1" } }, { "body": "<blockquote>\n<p>Any mistakes that I didn't catch?</p>\n</blockquote>\n<p><strong>Bug: wrong function</strong></p>\n<p><code>abs()</code> is for <code>int</code>. Use <code>fabs()</code>. <code>abs(mid)</code> is a problem when <code>mid</code> out of <code>int</code> range and not mathematical the desired algorithm as it truncates. Slower to converting to and from <code>int</code> too.</p>\n<pre><code>double mid = (a + b) / 2;\n// while (abs(mid) &gt; e) {\nwhile (fabs(mid) &gt; e) {\n</code></pre>\n<hr />\n<p><strong>Subtle</strong></p>\n<p><code>(x - 3)*x - 1;</code> is more computational stable than <code>x * x - 3 * x - 1</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:27:13.100", "Id": "255674", "ParentId": "255532", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T02:12:57.193", "Id": "255532", "Score": "2", "Tags": [ "c" ], "Title": "Bisection Method Implementation" }
255532
<p>I often get into the dilemma of how to use string constants, this is the way I use now:</p> <pre><code>UIImage *image = [UIImage imageNamed:@&quot;apple.png&quot;]; NSArray *imageNames = @[@&quot;apple01.png&quot;,@&quot;apple02.png&quot;]; NSDictionary *imageKeyValues = @{@&quot;Avatar&quot; : @&quot;apple.png&quot;}; </code></pre> <p>Once I encounter this type of code, I often use string pointers to refactor, because I don't know what the string code means:</p> <pre><code>static NSString *appleImage = @&quot;apple.png&quot;; UIImage *image = [UIImage imageNamed:appleImage]; NSArray *imageNames = @[@&quot;apple01.png&quot;,@&quot;apple02.png&quot;]; static NSString *avatarKey = @&quot;Avatar&quot;; NSDictionary *imageKeyValues = @{avatarKey : appleImage}; </code></pre> <p>My question now is: Should I assign each string to a variable? Many strings are not shared and will only be used once. Is it worth modifying like this? Is there a better way?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T18:32:22.997", "Id": "504299", "Score": "0", "body": "What is the purpose of the `imageNames` example? It is the same in the two snippets. Was that an oversight, or are you trying to make some argument for why you refactored `appleImage` and `avatarKey` but not the elements of that array? (Frankly, I'm not getting the “I don't know what the string code means”, as it seems that you obviously do.)" } ]
[ { "body": "<p>Refactoring your code to what you provided would really only be necessary if you plan on expanding the use of these strings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T03:24:43.900", "Id": "255539", "ParentId": "255537", "Score": "0" } }, { "body": "<p>You ask:</p>\n<blockquote>\n<p>Should I assign each string to a variable? Many strings are not shared and will only be used once.</p>\n</blockquote>\n<p>Obviously, in the other case, where the string <em>is</em> reused/shared, then of course one would (and should) define the constant/pointer once rather than ever repeating the same string literal in multiple places. This makes code easier to maintain.</p>\n<p>You might also use constants/pointer to centralize the definition of all the possible keys in one place. E.g. if the string literals define possible key names used in some web interface, we might want to put all these key names in one place, making it easier to keep track of the API.</p>\n<p>But if the strings are not shared and there is no organizational benefit to centralizing these definitions, then no, one would not assign each string its own variable.</p>\n<blockquote>\n<p>Is it worth modifying like this?</p>\n</blockquote>\n<p>If you are asking whether you should convert this ...</p>\n<pre><code>- (UIImage *)appleImage {\n UIImage *image = [UIImage imageNamed:@&quot;apple.png&quot;];\n return image;\n}\n</code></pre>\n<p>... to the following ...</p>\n<pre><code>- (UIImage *)appleImage {\n static NSString *name = @&quot;apple.png&quot;;\n UIImage *image = [UIImage imageNamed:name];\n return image;\n}\n</code></pre>\n<p>... then the answer is, no, there is little benefit in doing do.</p>\n<p>I would advise against pulling the string literal into its own local <code>NSString</code> pointer just for the sake of it. It just adds syntactic noise in this case. Yes, there are cases where one might pull the literal into its own line for the sake of clarity, but that not is not the case here.</p>\n<p>The governing principles are code maintainability and readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T07:23:45.993", "Id": "504645", "Score": "0", "body": "Thank you very much for your answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T18:20:06.263", "Id": "255577", "ParentId": "255537", "Score": "1" } }, { "body": "<p>I'm going to be the heretic in the room... I think your first code sample is just fine and doesn't need any refactoring at all.</p>\n<p>Let's pretend for a moment that the code lines in question are in wildly different places in the code base instead of one right after the other.</p>\n<p>When I see <code>NSDictionary *imageKeyValues = @{@&quot;Avatar&quot; : @&quot;apple.png&quot;};</code> somewhere. Learn a lot. I don't have to hunt all over the code trying to figure this dictionary out.</p>\n<p>If I were to see <code>NSDictionary *imageKeyValues = @{avatarKey : appleImage};</code> I learn much less. I have no idea what the key or value are at all. I have to hunt in some other file to figure out what this line might mean or whether I can safely use it in my current context.</p>\n<p>Then there's the horrible practice of having a single file that contains all the string literals for the entire program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-22T00:54:47.517", "Id": "266281", "ParentId": "255537", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T03:04:39.130", "Id": "255537", "Score": "1", "Tags": [ "strings", "objective-c" ], "Title": "How to use string constants correctly" }
255537
<p>I have a script that checks if the specified set of <code>$_POST</code> variables are supplied and not empty and returns an error string that is human readable.</p> <p>Here's my code:</p> <pre class="lang-php prettyprint-override"><code>if ($_SERVER[&quot;REQUEST_METHOD&quot;] === &quot;POST&quot;) { // Local variables initialization $missing = []; $checkVariables = [ 'name', 'address', 'contact' ]; // Check for nulls or non existent payload foreach ($checkVariables as $item) { if (empty($_POST[$item]) || !array_key_exists($item, $_POST)) { $missing[] = $item; } } $missingCount = count($missing); if ($missingCount &gt; 0) { $missingString = ''; if ($missingCount === 1) { $missingString = $missing[0]; } else if ($missingCount === 2) { $missingString = implode(' and ', $missing); } else { $lastItem = array_pop($missing); $partialMissingString = implode(', ', $missing); $missingString = $partialMissingString . &quot;, and {$lastItem}&quot;; } $verb = $missingCount &gt; 1 ? 'are' : 'is'; $field = $missingCount &gt; 1 ? 'fields' : 'field'; $errorString = &quot;Incomplete information received. &quot; . &quot;The {$missingString} {$field} {$verb} missing. &quot; . &quot;Please check your inputs and try again.&quot;; // Exits the script OutputResponse::sendResponse(400, $errorString); } // if there's no missing continue running the script // more code here but it's not the focus of this code review } </code></pre> <p>My <code>OutputResponse</code> code:</p> <pre class="lang-php prettyprint-override"><code>class OutputResponse { public static function sendResponse(string $statusCode, $messageBody): void { if ($statusCode == 500) { header(&quot;HTTP/1.1 500 Internal Server Error&quot;); } else if ($statusCode == 405) { header('HTTP/1.1 405 Method Not Allowed'); } else if ($statusCode == 404) { header(&quot;HTTP/1.1 404 Not Found&quot;); } else if ($statusCode == 403) { header(&quot;HTTP/1.1 403 Forbidden&quot;); } else if ($statusCode == 401) { header(&quot;HTTP/1.1 401 Unauthorized&quot;); } else if ($statusCode == 400) { header(&quot;HTTP/1.1 400 Bad Request&quot;); } else { header(&quot;HTTP/1.1 200 OK&quot;); } header('Content-Type: application/json'); echo json_encode([ 'code' =&gt; $statusCode, 'data' =&gt; $messageBody ]); exit; } } </code></pre> <hr /> <p>The script expects <code>$_POST['name']</code>, <code>$_POST['address']</code>, and <code>$_POST['contact']</code> to be not null or empty. The array keys to be checked are in the <code>$checkVariables</code> array.</p> <p>For simplification, I'm dropping the <code>$_POST</code> in the next examples.</p> <p>If <code>name</code> is the only one missing:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;code&quot;: &quot;400&quot;, &quot;data&quot;: &quot;Incomplete information received. The name field is missing. Please check your inputs and try again.&quot; } </code></pre> <p>If <code>name</code> and <code>contact</code> are missing:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;code&quot;: &quot;400&quot;, &quot;data&quot;: &quot;Incomplete information received. The name and contact fields are missing. Please check your inputs and try again.&quot; } </code></pre> <p>If all three are missing:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;code&quot;: &quot;400&quot;, &quot;data&quot;: &quot;Incomplete information received. The name, address, and contact fields are missing. Please check your inputs and try again.&quot; } </code></pre> <hr /> <p>Personally, the part on the <code>if ($missingCount &gt; 0)</code> block is the messiest or unoptimized.</p> <p>Any improvements or critiques are welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T21:18:47.517", "Id": "506090", "Score": "0", "body": "I would wrap the field name in quotes/double quotes in your error message to indicate that it's being referred to as a word. e.g. `The field \"foo\" is missing`" } ]
[ { "body": "<p>An interesting approach.</p>\n<p>Being a dev, I never bothered myself with proper English syntax, using just implode and calling it a day. but yours looks definitely better. Regarding optimization, you may notice that a condition <code>$missingCount === 2</code> is actually covered by else case, so it can be removed. Or so I think because I believe that the last comma is superfluous in <code> name, address, and contact</code>.</p>\n<p>Also, a trick I myself learned not long ago, is <code>http_status_code()</code> function which <em>alone</em> replaces the whole <code>if ($statusCode == 500) { ...</code> ladder, sending the proper header when called. So you can make it <em>just</em></p>\n<pre><code>http_response_code($statusCode);\n</code></pre>\n<p>and call it a day.</p>\n<p>It will also eliminate that awkward type juggling when you are sending a string status to the function and then have to compare it using == operator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:56:24.433", "Id": "504532", "Score": "0", "body": "I would have guessed that the type juggling `int >> string >> int` isn't intentional and the type hinting should be updated?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:29:27.770", "Id": "255553", "ParentId": "255538", "Score": "2" } }, { "body": "<ol>\n<li><p><code>if (empty($_POST[$item]) || !array_key_exists($item, $_POST)) {</code> is literally checking if <code>$_POST[$item]</code> is not declared or is falsey THEN checking if <code>$_POST[$item]</code> is not declared.</p>\n<blockquote>\n<pre><code>// Check for nulls or non existent payload\n</code></pre>\n</blockquote>\n<p>The comment associated with the step indicates that you want to check if <code>$_POST</code> elements are not declared or are <code>null</code>. In this case, you should only use:<br> <code>if (!isset($_POST[$item])) {</code>.</p>\n<p>If you want to check that elements are not declared or empty/falsey, then use:<br><code>if (empty($_POST[$item])) {</code>.</p>\n</li>\n<li><p><code>if ($missingCount &gt; 0) {</code> can be safely reduced to <code>if ($missingCount) {</code> which checks if the count is &quot;truthy&quot; (in other words, not zero).</p>\n</li>\n<li><p><code>else if</code> is one word in php, please always type <code>elseif</code> to comply with PSR guidelines.</p>\n</li>\n<li><p>Don't bother declaring <code>$missingString = '';</code> if you are unconditionally going to overwrite it anyhow.</p>\n</li>\n<li><p>You can combine the <code>if</code> and first <code>else if</code> because if the array only has one element, then no glue will be used while producing the output string.</p>\n<pre><code>if ($missingCount &lt; 3) {\n $missingString = implode(' and ', $missing);\n}\n</code></pre>\n</li>\n<li><p>The &quot;smart-implode&quot; as I've seen it referred to at least once on StackOverflow is fine enough. There are <a href=\"https://stackoverflow.com/q/52193927/2943403\">a few other ways to do it</a> -- I'll show another one below.</p>\n</li>\n<li><p>The whole chunk of code that crafts the OutputResponse might look like this: (<a href=\"https://3v4l.org/quMIB\" rel=\"nofollow noreferrer\">Demo</a>). The advantages are: fewest declared variables (specifically no single-use variables), not repeated function calls, and the elegance of <code>sprintf()</code> when injecting variables into a string.</p>\n<pre><code>$missingCount = count($missing);\nif ($missingCount) {\n if ($missingCount &lt; 3) {\n $glue = ' and ';\n } else {\n $glue = ', ';\n $missing[] = 'and ' . array_pop($missing);\n }\n OutputResponse::sendResponse(\n 400,\n sprintf(\n 'Incomplete information received. The %s %s missing. Please check your inputs and try again.',\n implode($glue, $missing),\n $missingCount === 1 ? 'field is' : 'fields are'\n )\n );\n}\n</code></pre>\n</li>\n<li><p>[EDITED] After reading the other reviews and learning that my recommended lookup array was incomplete, flawed, and frankly suboptimal, I now find myself agreeing with YourCommonSense's advice to use <code>http_response_code()</code> for setting the HTTP response code. See <a href=\"https://stackoverflow.com/q/3258634/2943403\">this Stack Overflow page for additional considerations and fringe cases</a> around the native function which was available since PHP5.4. Also, Now I suppose my new code for the <code>sendResponse()</code> method would look like this:</p>\n<pre><code> http_response_code($statusCode);\n header('Content-Type: application/json');\n exit(\n json_encode([\n 'code' =&gt; $statusCode,\n 'data' =&gt; $messageBody\n ])\n );\n</code></pre>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:00:05.593", "Id": "504534", "Score": "0", "body": "There's a minor bug with your lookup where you could output (for example) a `301 OK` response header" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:03:21.243", "Id": "504535", "Score": "0", "body": "I intentionally did not change the behavior of the OP's code. I did not know if they specifically wanted this behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:27:15.727", "Id": "504537", "Score": "0", "body": "Sorry, but you have (maybe unintentionally), changed the behaviour of the OPs code. In three ways: **First** the `$statusCode` returned is a formatted header and not the integer that the OP has, **secondly** the code above exits without sending any header so actually a `200 OK` header will be sent not the `400 Bad Request` which the OP intends, and **third** the formatted header (which isn't set and is instead returned to the wrong place) will always be `XXX OK` unless it's explicitly in the `$codes` array; the OP originally output a `200 OK` if `$statusCode` didn't match" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:28:45.370", "Id": "504539", "Score": "0", "body": "Also, I'm aware that that probably sounds far more confrontational than I intended! Apologies for that, it's tricky to get the point across with limited characters without being direct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:30:00.017", "Id": "504540", "Score": "1", "body": "Ah, I see what you mean. I'll edit when I get out of my garden. The function declaration and the header were omitted because I was only addressing the lookup (not providing a full function body." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:33:49.250", "Id": "255554", "ParentId": "255538", "Score": "3" } }, { "body": "<h2>OutputResponse</h2>\n<p><strong>Quotation marks</strong></p>\n<p>This is hugely pedantic: your <code>405</code> header response uses single quotes where as all of the others use double quotes. It makes no difference (in fact single quotes are slightly faster for plain text in <code>PHP</code>), however, it's good practice to stick to one method especially when setting near identical strings.</p>\n<p><strong>Type hints &amp; Parameters</strong></p>\n<p>You have a <code>string</code> type hint on your <code>integer</code> parameter and <strong>no</strong> type hint at all for your <code>$messageBody</code> parameter?</p>\n<p>Currently you pass an integer...</p>\n<pre><code>OutputResponse::sendResponse(400, $errorString);\n</code></pre>\n<p>... to a parameter of type string...</p>\n<pre><code>function sendResponse(string $statusCode, $messageBody)\n</code></pre>\n<p>... and then compare it as an integer...</p>\n<pre><code>if ($statusCode == 500)\nelse if ($statusCode == 405)\n...\n</code></pre>\n<p>... which is confusing on many levels and presumably not intended behaviour?</p>\n<p>So that needs to be fixed, while there I would also swap your parameter order around too; then you can set a default value of, for example, <code>200</code> for your <code>$statusCode</code>.</p>\n<pre><code>public static function sendResponse(string $statusCode, $messageBody): void\n\n// Becomes....\n\npublic static function sendResponse(string $messageBody, int $statusCode = 200) : void\n</code></pre>\n<p><strong>HTTP Status: logic</strong></p>\n<p>Currently you're using a series of <code>if/else</code> statements to work out what HTTP response code to send. This can be tricky to read and isn't always clear what the code block attempts to do; <code>switch</code> is pretty much designed for this exact use case although personally I would use an array for this type of task.</p>\n<p>Also, I wouldn't put the <code>header(...)</code> function call in every <code>if</code> statement. Much better to put one call at the end and return the string from the logic.</p>\n<p>One more note is that you have your code set up to default to <code>200 OK</code> if the response code doesn't exist in the block. This is wrong IMO: if your own code doesn't know what response to give then I doubt everything is <code>OK</code>? I'd opt for something like a generic <code>500</code>, because the server has obviously run into a problem!</p>\n<p><em>Note: <code>500</code> doesn't automatically mean fatal</em></p>\n<p>Using <code>switch</code>:</p>\n<pre><code>$header = &quot;HTTP/1.1 500 Internal Server Error&quot;;\nswitch $statusCode{\n case 500:\n $header = &quot;HTTP/1.1 500 Internal Server Error&quot;;\n break;\n case 405:\n $header = &quot;HTTP/1.1 405 Method Not Allowed&quot;;\n break;\n case 404:\n $header = &quot;HTTP/1.1 404 Not Found&quot;;\n break;\n case 403:\n $header = &quot;HTTP/1.1 403 Forbidden&quot;;\n break;\n case 401:\n $header = &quot;HTTP/1.1 401 Unauthorized&quot;;\n break;\n case 400:\n $header = &quot;HTTP/1.1 400 Bad Request&quot;;\n break;\n} \n\nheader($header);\n</code></pre>\n<p>Using an <code>array</code>:</p>\n<pre><code>$httpStatus = [\n 500 =&gt; &quot;HTTP/1.1 500 Internal Server Error&quot;,\n 405 =&gt; &quot;HTTP/1.1 405 Method Not Allowed&quot;,\n 404 =&gt; &quot;HTTP/1.1 404 Not Found&quot;,\n 403 =&gt; &quot;HTTP/1.1 403 Forbidden&quot;,\n 401 =&gt; &quot;HTTP/1.1 401 Unauthorized&quot;,\n 400 =&gt; &quot;HTTP/1.1 400 Bad Request&quot;,\n 200 =&gt; &quot;HTTP/1.1 200 OK&quot;,\n];\n\nheader($httpStatus[$StatusCode] ?? $httpStatus[500]);\n</code></pre>\n<p><strong>HTTP status: code</strong></p>\n<p>I'm not 100% onboard with sending a <code>400 Bad Request</code> response in this scenario.</p>\n<p>Perhaps you can call this personal preference or what not but as far as I can tell this is some form of <code>ajax</code> style set up? In which case the <em>client side</em> script is sending a request to the server which then acts upon it. Your <em>server side</em> script then gets hold of the header content and makes it's own checks... Which means that the HTTP request did succeed, the script (resource) was executed, and content was even generated.</p>\n<p>The fact is, it isn't a HTTP issue, the user just hasn't submitted the correct details. You obviously implement your own error reporting to come back with application errors - so just set a code or a message in there (which is what you have done anyway) and leave the <code>HTTP</code> response code alone.</p>\n<h2>Main Code</h2>\n<p><strong><code>REQUEST_METHOD</code></strong></p>\n<p>There's really no need for your opening (all encompassing) <code>if</code> statement. The whole purpose of the code block is to check that the <code>$_POST</code> variables are present and correct and if they aren't stop the execution of further code with <code>exit;</code>. By using the <code>===</code> comparison operator all you're doing is opening yourself up to issues in the event of a badly structured request where the method isn't formed as all caps (of course, this <em>shouldn't</em> be a problem in 2021 but you can't be sure).</p>\n<p>Again, if the <code>REQUEST_METHOD</code> isn't <code>POST</code> then the rest of the code fails and exits anyway. So why waste the time checking?</p>\n<p><strong><code>if</code>: logic</strong></p>\n<p>The second condition in your first <code>if</code> statement is redundant: if the index doesn't exist then the first condition is effectively <code>empty(null)</code> which, of course, is <code>true</code>. So checking afterwards to see if the array key exists isn't doing anything extra.</p>\n<pre><code>if (empty($_POST[$item]) || !array_key_exists($item, $_POST))\n\n// Becomes...\n\nif (empty($_POST[$item]))\n</code></pre>\n<p>Later on you use <code>$missingCount &gt; 0</code> which is okay, but... Not needed: <code>count</code> will return either <code>0</code> or some positive value greater than <code>0</code>. Logically <code>0 == false</code> so you can just skip the comparison; if the value is <code>0</code> then it's false, otherwise, its <code>true</code>.</p>\n<pre><code>if ($missingCount &gt; 0)\n\n// Becomes...\n\nif ($missingCount)\n</code></pre>\n<p><strong>String assembly</strong></p>\n<p>Custom error messages are tricky: they have to be informative but succinct, forceful but polite, etc. You don't want to annoy your user with a lengthy error message or, worse still, intimidate them with overly aggressive language.</p>\n<p>So, my suggestion, would be to simply change the error message:</p>\n<pre><code>$errorString = &quot;Incomplete information received. Please check the following fields:&quot;;\n</code></pre>\n<p>Now all you need to do is append your variables to the end of the string. Which means we can reduce your code to a simple loop:</p>\n<pre><code>foreach ($checkVariables as $item) {\n $errorFields .= empty($_POST[$item]) ? &quot;{$item}, &quot; : &quot;&quot;;\n}\n</code></pre>\n<p>This leaves you with a trailing comma and no <code>and</code> so we do need to do a little formatting; but now you have a piece of code that scales automatically if you need to add more variables for example maybe you start collecting <code>$_POST[&quot;phoneNumber&quot;]</code>.</p>\n<pre><code>$errorString .= rtrim(preg_replace(&quot;/, (\\w+), $/&quot;, &quot; and $1&quot;, $errorFields), &quot;, &quot;);\n</code></pre>\n<p><em>This, I believe, is technically also the fastest method despite implementing regular expressions</em></p>\n<p>If you're against changing your error message this is compatible with your current logic to work out plural etc. just use <code>$errorFields</code> and then concatenate as you see fit.</p>\n<h2>Updated Code</h2>\n<p><strong>Main Body</strong></p>\n<pre><code>$checkVariables = ['name', 'address', 'contact'];\n$errorString = &quot;Incomplete information received. Please check the following fields: &quot;;\n$errorFields = &quot;&quot;;\n\nforeach ($checkVariables as $item) {\n $errorFields .= empty($_POST[$item]) ? &quot;{$item}, &quot; : &quot;&quot;;\n}\n\n$errorString .= rtrim(preg_replace(&quot;/, (\\w+), $/&quot;, &quot; and $1&quot;, $errorFields), &quot;, &quot;);\n\nif ($errorFields) {\n OutputResponse::sendResponse(400, $errorString);\n}\n</code></pre>\n<p><strong>OutputResponse</strong></p>\n<pre><code>class OutputResponse\n{\n public static function sendResponse(string $messageBody, int $statusCode = 200) : void\n {\n $httpStatus = [\n 500 =&gt; &quot;HTTP/1.1 500 Internal Server Error&quot;,\n 405 =&gt; &quot;HTTP/1.1 405 Method Not Allowed&quot;,\n 404 =&gt; &quot;HTTP/1.1 404 Not Found&quot;,\n 403 =&gt; &quot;HTTP/1.1 403 Forbidden&quot;,\n 401 =&gt; &quot;HTTP/1.1 401 Unauthorized&quot;,\n 400 =&gt; &quot;HTTP/1.1 400 Bad Request&quot;,\n 200 =&gt; &quot;HTTP/1.1 200 OK&quot;,\n ];\n\n header($httpStatus[$StatusCode] ?? $httpStatus[500]);\n header('Content-Type: application/json');\n\n echo json_encode([\n 'code' =&gt; $statusCode,\n 'data' =&gt; $messageBody\n ]);\n\n exit;\n }\n}\n</code></pre>\n<p><em>or, my preference...</em></p>\n<pre><code>class OutputResponse\n{\n public static function sendResponse(string $messageBody, int $statusCode = 200) : void\n {\n header('Content-Type: application/json');\n\n echo json_encode([\n 'code' =&gt; $statusCode,\n 'data' =&gt; $messageBody\n ]);\n\n exit;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:06:12.987", "Id": "504536", "Score": "0", "body": "I see some redundant review points with this review that already exist in other answers. Please spare the OP re-reading the same insights by only mentioning new insights. If you agree with / support insights from other reviewers, you can express your agreement in your answer without repeating it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:34:42.127", "Id": "504541", "Score": "0", "body": "@mickmackusa I did check the `guidelines` before posting because I wasn't sure whether to remove them or not... But the only real _duplicate_ is probably `> 0` (and potentially `empty()`) everything else seems - to me at least - have a different slant? But who knows, I'm knew here and wasn't sure on etiquette (also I figured an answer has been accepted already so it didn't matter too much)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:38:14.077", "Id": "504542", "Score": "0", "body": "At the end of the day, my stance on your posting style is that it errs on the side of generosity and therefore raises the expected standard of other reviews. For that reason, I hope that you settle in and continue reviewing. And yes, perhaps the truthy check is the only redundancy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:03:47.887", "Id": "504558", "Score": "0", "body": "@mickmackusa a review is like a sculpture - written the way one sees it. I don't think there should be any restrictions in this regard. I would rather love to see http_response_code() used in your answers. Although I do understand that a lookup array is used as a generic example for fixing this kind of code but why stop here if you have even better optimization for this specific case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:13:29.397", "Id": "504559", "Score": "0", "body": "I will edit my answer. I am spending all day in my garden. My opinion is that there is no benefit to the OP or future researchers/reviewers to see the exact same insight twice. @You" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:16:03.670", "Id": "504560", "Score": "0", "body": "@mickmackusa in my experience (mostly personal), people seldom catch the new information at the first take. It takes several attempts, probably at different angles to get it right. I see no harm in the duplicated suggestion. It just means more emphasis" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:21:46.333", "Id": "504561", "Score": "0", "body": "Regarding this answer, I am in huge doubts about the personal preference part. In my world, HTTP status codes are precious, being a lingua franca for the inter-system interaction. I may be don't understand what is said in the text response but I surely understands the HTTP status code. It makes the logic simpler and allows me to use a premade library with standard responses to standard codes, instead of writing some logic by hand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:23:26.510", "Id": "504562", "Score": "0", "body": "It is just as easy to acknowledge an earlier reviews insights if you want to give more emphasis. Simply say, \"I agree with [user]'s review in using a truthy check on the error count.\" Or \"I agree with [user]'s review in using a falsey check instead of `empty()`.\"This shows that the new reviewer bothered to read the earlier reviews before posting a new one and the OP gets the emphasis without seeing it mansplained a second time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:46:12.253", "Id": "504563", "Score": "0", "body": "@mickmackusa but he is not required to \"read the other reviews\" :) Come on, that's not the topic to argue over. It smells like a gatekeeping. Let's just have as much good reviews as possible, and disregard such petty concerns. Or well let's just agree to disagree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T07:21:30.153", "Id": "504564", "Score": "0", "body": "I do not appreciate the accusation of being a \"gatekeeper\" after I already gave justifications for why I feel reading the other answers and not repeating insights is better for the community and the OP. I'll have a look around Meta (when I get out of the garden) to see if there is any discussion on this etiquette." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T10:56:19.150", "Id": "504568", "Score": "1", "body": "So this seems to have taken a turn I did not expect! I obviously did _\"read the other reviews\"_ before posting, I thought, that was clear as I have also commented on both answers? This review only **really* duplicates the two points I mentioned in an earlier comment(?) and even then the explanation is different. I would hope that explanation isn't considered _mansplaining_ it just clarifies what is actually going on and why the additional code is redundant; is it not better to explain reasoning so that the OP doesn't blindly go off and use similar practices without understanding?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:19:33.767", "Id": "504570", "Score": "0", "body": "@YourCommonSense yes, I suppose that's one way to look at it. My _question_ is what benefit does it provide? A HTTP response code tells the browser that something's wrong with the request, not an _ordinary_ user? Sending a `200 OK` means the browser (and the client scripts etc.) know that the request succeeded and the internal `error code/message` tells the script what happened with the server script logic... If using a HTTP code to return script logic then where's the line? Would you, for example, return a `400` for an incorrect username/password? Or debugging a typo in the ajax URL?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:25:22.317", "Id": "504572", "Score": "0", "body": "Surely it's about client scripts. A ready made library *already* understands 500 and 404, u don't have to write any code by hand to handle it. Whether I would or would not handle 400 is my choice. the problem is, when it's always 200, then there is **no choice**. After all, sending proper http codes is **defined by the standard**. But what I don't understand the most, why this question at all. Adding proper http code costs you absolutely nothing. I really don't see any reason to argue against them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:36:32.467", "Id": "504573", "Score": "0", "body": "@YourCommonSense I suppose my view is that in this scenario a HTTP response code isn't the proper response? A `4XX` error means something like: _\"...the server doesn't/can't understand/handle the request...\"_ but the server and the script - in this case - were able to handle the request, it's the content which is in question. So to me a `200 OK` with feed back is appropriate? I'm not saying I would never use them, for example, if I try to access a `users page` without logging in I might expect to see a `403` (I would probably opt for a re-direct). Maybe I'm wrong or maybe we're both right ‍" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:40:36.327", "Id": "504574", "Score": "0", "body": "as long as you are **using** a standard HTTP status code in the response body, there is not a single reason not to use it in the HTTP response header. If you don't see any use for the codes, why send them at all" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:43:01.293", "Id": "504575", "Score": "0", "body": "@mickmackusa also, I have commented on a previous review of yours with suggestions rather than providing a complete solution; because to do so would have given largely the same content (code) in an optimised order? There is guidance on [how to answer](https://codereview.stackexchange.com/help/how-to-answer) which suggests that reviews can cover the same points so long as there is at least one unique point - so I guess that's down to interpretation - and I would say that all but a very small section is unique points? Also, your answer was accepted when I posted... So it doesn't detract?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:50:30.087", "Id": "504579", "Score": "0", "body": "@YourCommonSense I wouldn't use the same HTTP code in this scenario I would implement an internal error system that provides standard error messages for application specific errors - you have to do this anyway to provide output/feedback (e.g. _wrong password_). Using a HTTP code potentially masks where the code has arisen. Again, I would call it personal preference I'm not saying that sending a HTTP response code is strictly wrong?" } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:52:28.340", "Id": "255675", "ParentId": "255538", "Score": "3" } } ]
{ "AcceptedAnswerId": "255554", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T03:11:44.193", "Id": "255538", "Score": "4", "Tags": [ "php" ], "Title": "PHP script that returns an error message based on what $_POST parameters are missing" }
255538
<p>I wanted to ask this question to my interview candidates, hence wanted to first give it a shot to see if this is doable in 45 mins. Here's the code that I was able to come up with in 45 minutes. Can folks please let me know if there are any logic flaws in this code?</p> <p>Constraints:</p> <ol> <li>The robot does not have any data of the room to start with.</li> <li>The robot has to traverse the entire area of the room.</li> <li>The room can have obstacles.</li> <li>The robot can go front or right or left.</li> </ol> <pre><code>public interface IRobot { public void TurnLeft(); public void TurnRight(); public bool Advance(); // This returns true if the robot is able to advance/no obstacle in that step public void Clean(); } public class Node { public bool Visited { get; set; } public bool Cleaned { get; set; } public Node Front { get; set; } public Node Left { get; set; } public Node Right { get; set; } } public class RobotManager { private IRobot _robot; private Node _rootNode; private Node _currentNode; public RobotManager(IRobot robot) { Validator.ThrowArgumentNullIfApplicable(robot); this._robot = robot; this._rootNode = new Node(); } public void Clean() { Clean(_rootNode); } private void Clean(Node currentNode) { if(currentNode.Cleaned) { return; } this._robot.Clean(); currentNode.Cleaned = true; this._currentNode = currentNode; if(this._robot.Advance()) { currentNode.Front = new Node(); Clean(currentNode.Front); } this._robot.TurnLeft(); if(this._robot.Advance()) { currentNode.Left = new Node(); Clean(currentNode.Left); this._robot.TurnRight(); } this._robot.TurnRight(); if(this._robot.Advance()) { currentNode.Right = new Node(); Clean(currentNode.Right); this._robot.TurnLeft(); } Console.WriteLine(&quot;Finished Cleaning!&quot;); Reset(); } // This will return the robot back to the starting point public void Reset() { Traverse(this._currentNode); this._rootNode = new Node(); } private bool Traverse(Node currentNode) { if(currentNode == null || currentNode.Visited) { return false; } currentNode.Visited = true; if(currentNode == _rootNode) { return true; } if(currentNode.Front != null) { this._robot.Advance(); if(Traverse(currentNode.Front)) { return true; } } if(currentNode.Left != null) { this._robot.TurnLeft(); this._robot.Advance(); if(Traverse(currentNode.Left)) { return true; } this._robot.TurnRight(); } if(currentNode.Right != null) { this._robot.TurnRight(); this._robot.Advance(); if(Traverse(currentNode.Right)) { return true; } this._robot.TurnLeft(); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T07:25:32.780", "Id": "504213", "Score": "0", "body": "Welcome to Code Review! Are you primarily concerned with the [tag:c#]? If so, please add it or any other appropriate tags." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T19:15:22.963", "Id": "504306", "Score": "0", "body": "Sometimes, interviewers ask interviewees to discuss problems with code the interviewer presents to them, including refactoring opportunities, instead of a code-from-scratch question. Your code could be useful for that, with a small tweak. Replace some of your logic with \"black box\" functions they're told to assume **successfully** do such and such (e.g. Clean & Traverse), and let them comment on everything else, including names." } ]
[ { "body": "<h1>TL;DR - I would not hire you</h1>\n<p>I am going to be fair here and state that I am judging this code more harshly because you are a not just any junior developer or applicant, but you are actually responsible for testing and technically evaluating potential hires. This implies a certain skill level, and it means that you should be innately able to display what the bar for the quality of the company's code is.</p>\n<p>And to be quite frank, as an applicant, if I saw this as the proposed solution, I would genuinely back out of working for this company.</p>\n<p>I spent more time reviewing this than you did writing it (if you kept to your own 45 minute limit), so I hope you appreciate that I'm not trying to be mean, but I am trying to be very direct about the many issues I've uncovered. The more I looked at your code, the more started realizing that it is deeply flawed, suffers from multiple <a href=\"https://dwotd.wordpress.com/2010/05/31/reality-101-failure/\" rel=\"noreferrer\">reality 101 failures</a>, and most of all it is painfully apparent that <strong>you never even tested it, not even once</strong>.</p>\n<p>I wouldn't hire you (for any position above junior) for several reasons:</p>\n<ul>\n<li>You are <strong>asking applicants to solve <a href=\"https://en.wikipedia.org/wiki/Pathfinding\" rel=\"noreferrer\">pathfinding</a></strong>, a notoriously difficult problem that has existed for decades and that <em>to this day</em> still has not been optimized (with reasonable performance), and you're giving them <strong>45 minutes</strong> to do so. This is sheer insanity. Unless you are hiring for a game developer (or roomba developer) with significant prior experience, the posed challenge just doesn't fit the kind of applicant you're looking for.</li>\n<li>Some of the issues I found are related to not grasping the elemental basics of the field you're trying to work with. That's general grounds for rejecting any applicant, let alone the interviewer who created the challenge to begin with. <strong>Interviewers who don't understand the subject matter they're interviewing about are not good interviewers</strong>.</li>\n<li><strong>You never even bothered to test your code.</strong> Some of these issues are blindingly obvious from the most barebones example, without even factoring in features like obstacles.</li>\n<li><strong>There is not a single situation in which your code works.</strong> It's not that you've forgotten to account for fringe cases, or specific features such as obstacle avoidance. Your code fails for a 2x2 empty room.</li>\n<li>Furthermore, you also therefore didn't consider that applicants would like to be able to test and debug their code, which in my opinion raises red flags for both your roles as an interviewer and as a developer.</li>\n</ul>\n<p>That being said, the code was formatted nicely.</p>\n<p>I don't want to make you feel bad. We've all struggled with certain problems at one time or another. There are plenty of projects I've started that have been deeply flawed.</p>\n<p>But I would strongly suggest you re-evaluate if you are the right person to evaluate these applicants for technical interviews. In the interest of the company, I do not think that you are the right person for the job without some significant improvements being made.</p>\n<h2><strong>Test data and visualization tool</strong></h2>\n<p>This is more a comment on the question rather than the solution, but behavioral logic of this kind is notorious for needing <a href=\"https://en.wikipedia.org/wiki/Shotgun_debugging\" rel=\"noreferrer\">shotgun debugging</a>. It's exceedingly hard if not impossible to see if this algorithm works as intended based on reading the code and not seeing it in action.</p>\n<p>This applies to me needing to review your code now, you needing to check your applicants' code, as well as any applicant who'd like to debug their code while developing to find any obvious flaws.</p>\n<p>I would strongly advise you to create a default test fixture where you have some predefined room setups to test the robot with, and a <strong>visual</strong> tool that shows you the room and the robot's progress step by step.</p>\n<p>I will try to review your algorithm to some degree, but keep in mind that I did not write an entire test scenario for this. This is just based on what I can interpret by reading the code, and some experience I have with pathfinding logic.</p>\n<h2><strong>Code structure</strong></h2>\n<p>Based on the question as presented, I find it counterintuitive that you only add a robot interface without implementation, and then develop the &quot;algorithm for a robot&quot; in another class altogether. I'm not against separating the movement logic from the cleaning logic, but the names leave something to be desired. <code>IRobot</code> (and the presumed <code>Robot</code> class) don't indicate movement, and <code>RobotManager</code> doesn't indicate cleaning.</p>\n<p>Especially for an interview question, I find this a really important sticking point. It shows you how well this developer is independently going to be able to keep your code clean.</p>\n<h2><strong>Stack overflow</strong></h2>\n<p>Your code relies on recursion, and the recursive stack size is finite. Therefore, you've implemented a natural cap on how big a room can be, and the way it behaves when it reaches that cap (StackOverflowException) is ugly.</p>\n<p>I would strongly advice using some kind of iteration instead of recursion here. A <code>for(each)</code> is not going to be appropriate since you don't know the size of the room in advance, but a <code>while</code> would be appropriate here.</p>\n<h2><strong>DRY and method naming</strong></h2>\n<p>I don't like the <code>Clean</code> method name, because it is also the method which handles traversal, even though you also have a separate <code>Traverse</code> method. Something has gone awry here. You've duplicated the movement logic in both methods, and implemented them slightly differently.</p>\n<p>That's not promoting reusability the way it should.</p>\n<h2><strong>Your algorithm in general</strong></h2>\n<p>There are frankly a lot of glaring issues with the logic itself. I can't delve into all of them in full depth. If you had had a visualization tool and test data, some of these would've been easy to spot. I'll elaborate on a few core issues, but quite frankly there's little logic to salvage here when you've noticed all the bugs.</p>\n<p>It's important to observe that your <code>Clean</code> method is the only method being called to handle both the cleaning and the room traversal. <code>Traverse</code> is only used after the cleaning has been completed.</p>\n<pre><code>private void Clean(Node currentNode)\n{ \n if(currentNode.Cleaned)\n {\n return;\n }\n</code></pre>\n<p>If you back out of every cleaning operation when the current node has already been cleaned, that means that <strong>you are not allowing the robot to cross a cleaned node</strong>. That is a significant flaw in your logic. The easiest test case is having a room whose obstacles are laid out like a Bomberman level:</p>\n<p><a href=\"https://i.stack.imgur.com/uuLOMm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uuLOMm.png\" alt=\"enter image description here\" /></a></p>\n<p>Try traversing all the green tiles in a continuous line without crossing your path.</p>\n<p>You might be able to snake around the level and then get into the first dead-end street, and your robot will never turn itself around (it only attempts straight, left and right).</p>\n<p>But even if it did turn around, when it tries to exit that dead-end street, it has to drive over a path it already drove over. And what does you code do then? Refuse to continue. It tries to backtrack back into the dead-end street.</p>\n<p>Since it is no longer adjacent to any uncleaned and accessible tile, and therefore it will report that the cleaning has been completed.</p>\n<p>You might think that my example is a fringe case for a room that's designed to trip up your system. But <strong>your logic fails for a completely empty room as well</strong>. Your logic is as follows:</p>\n<ul>\n<li>Go straight</li>\n<li>If you can't, go left</li>\n<li>If you can't, go right</li>\n<li>In any of the above cases, repeat the logic</li>\n<li>In none of the above cases, back out and continue that recursion level's logic.</li>\n</ul>\n<p>Placing the robot in a room, it's going to go straight until it can't, turn left once, go straight until it can't again, etc,... Think about what that means in visual terms:</p>\n<p><a href=\"https://i.stack.imgur.com/4s42K.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4s42K.png\" alt=\"enter image description here\" /></a></p>\n<p><em>Edit: I just noticed I forgot to number the first straight. Oops! Let's just say I totally intended to zero-index them...</em></p>\n<p>After the straight that is (incorrectly) labeled 6 in the image, since it will never cross a tile that has already been cleaned, your robot has boxed itself in and will never clean the left half of the room (except the outer edge which it cleaned in the beginning).</p>\n<h2><strong>Node-based traversal</strong></h2>\n<p>This system just doesn't make any sense. The robot's interface is fine. You are clearly understanding that the robot only knows its own orientation, and therefore must be issued commands relative to its own position (without knowing its location in the room).</p>\n<p>But then your node-based system throws all of that out the window and tries to dynamically build a room-scale grid, and issues commands based on the grid (which has the room as a reference point) to the robot (which has itself as a reference point).</p>\n<p><strong>You never check the robot's orientation</strong>. That's a massive red flag. It makes no sense to actively need to rotate a robot, and then never bother with using that rotation in your logic. Your logic decides to &quot;go left&quot;, but since it doesn't know the orientation of the robot, how can it even figure out what &quot;left&quot; means to the robot?</p>\n<p>I can't elaborate on the full ramification of this, but it essentially means that you cannot just assume that &quot;node left&quot; == &quot;robot left&quot;, since the robot's orientation alters how the robot is oriented in the room. You've mixed two completely different coordinate systems and have not made sure they are compatible with one another.</p>\n<h2><strong>Node-based traversal 2 - the big one</strong></h2>\n<p>In my opinion, this is the biggest issue in your algorithm. This is something you should have spotted without even running the code.</p>\n<p><strong>Every movement moves onto a <code>new Node()</code>. You are not tracking any meaningful node state</strong>.</p>\n<p>Let's imagine a 4 tile room, and the robot starts in the bottom right corner.</p>\n<p><a href=\"https://i.stack.imgur.com/XAPV1m.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XAPV1m.png\" alt=\"enter image description here\" /></a></p>\n<p>For brevity, I'm only focusing on the successful movement actions. The first 4 steps are what you intended them to be:</p>\n<ol>\n<li>Go straight (new location: top-right)</li>\n<li>Go left (new location: top-left)</li>\n<li>Go left (new location: bottom-left)</li>\n<li>Go left (new location: bottom-right)</li>\n</ol>\n<p>I want to focus on what happens in step 3 when you realize that moving to the left was possible:</p>\n<pre><code>this._robot.TurnLeft();\nif(this._robot.Advance())\n{\n currentNode.Left = new Node();\n Clean(currentNode.Left);\n</code></pre>\n<p>The next node is a <code>new Node()</code>. But you actually already knew this location (because you have been there before). But <strong>your code makes no effort to check if this is a known location</strong>. It always blindly makes a new node.</p>\n<p>Therefore, your entire clean-node-tracking logic is defeated:</p>\n<pre><code> if(currentNode.Cleaned)\n {\n return;\n }\n</code></pre>\n<p>Since <code>currentNode</code> is <strong>always</strong> a newly created node, which by definition could not have been cleaned yet.</p>\n<p>You've fallen into the age-old trap of thinking that compilers read intent, speak English, and figure out your system for you. Putting it another way:</p>\n<pre><code>var topLeft = new Node();\nvar topRight = new Node();\n\ntopLeft.Right = topRight;\n\nvar whatIsThisValue = topRight.Left;\n</code></pre>\n<p>Tell me what will be in <code>whatIsThisValue</code>. Is it your <code>topRight</code> object?</p>\n<p>Nope. It's <code>null</code>. Just because left is the opposite of right doesn't mean that your code will automatically understand that &quot;if B is right of A, then A must be left of B&quot;. That's just not how it works.</p>\n<p><strong>This issue renders your entire floor node state tracking logic, which the entire cleaning logic hinges on to know both how to avoid double work and to figure out when it's done, completely defeated.</strong></p>\n<h2><strong>Recursive backtracking</strong></h2>\n<p>Next, we get to the recursive logic. It just doesn't make much sense. You lay out your pathfinding in recursive steps. Each recursive level will <em>at some point</em> attempt going forward, left and right. It doesn't just attempt one of these, it attempts <em>all of them</em> sequentially. When a movement attempt succeeds, it first drills down further, but the remaining movement attempts are still &quot;queued&quot; to happen when the recursive stack starts bubbling up again.</p>\n<p>Following the above example, the robot will go straight for a few steps. Each step, that's a new recursive level. But you mustn't forget about the &quot;queued&quot; left/right commands from the first few steps. For now, you've drilled down into a new level, but what drills down will eventually bubble back up. Numbering the levels of recursion, you're looking at something like:</p>\n<ul>\n<li>Straight 1 - success\n<ul>\n<li>Straight 2 - success\n<ul>\n<li>Straight 3 - success\n<ul>\n<li>Straight 4 &lt;---- we are currently here</li>\n</ul>\n</li>\n<li>Left 3</li>\n<li>Right 3</li>\n</ul>\n</li>\n<li>Left 2</li>\n<li>Right 2</li>\n</ul>\n</li>\n<li>Left 1</li>\n<li>Right 1</li>\n</ul>\n<p>No matter how deep we dig into the recursive tree, Left/Right 1/2/3 will <em>eventually</em> be executed when we're done digging.</p>\n<p>The problem with this is that <strong>backtracking on the recursive stack does not backtrack the robot's actual location</strong>. Therefore, the location in which Left 1 will be executed will be completely different depending on whether or not Straight 1 succeeded or not. This makes it impossible to know <em>which</em> location Left 1 is actually going to visit.</p>\n<p>When you realize the chaos that this entails, you start understanding that you don't have an algorithm here, you have <strong>a brute force attack with just loads and loads of uncoordinated random movement</strong>.</p>\n<p>If your robot had backtracked (i.e. moved backwards) whenever your <code>Clean</code> method returned (and bubbled up one recursive level), your logic would have been more correct. Still bugged, but the recursive approach would've at least made more sense.</p>\n<p>The kind of recursive logic you're using here only works when each recursive level works in its own fixed location. But because you are dealing with a real robot in a room, whose location is altered by <em>all</em> of those recursive levels, it becomes impossible for each recursive level to ensure that its sequential operations (straight/left/right) are executed on the same fixed location regardless of what happened on lower recursive levels.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T20:09:21.647", "Id": "504309", "Score": "0", "body": "I posted this as soon as I finished writing the code (before testing I agree - since 45 mins is the time I gave myself to code and test and I could barely finish coding within 45 mins), and it hit me right after that I am new-ing a Node object everytime. So I changed my code but forgot to update the post here. \n\nGreat feedback about the rest of the aspects. Please note that this is an interview question, so I am not looking for a 'perfect' solution, but rather how a candidate will approach the problem and what kind of thinking goes into their minds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T20:17:13.340", "Id": "504310", "Score": "0", "body": "A good software engineering interviewer does not look for a 'perfect' solution in an interview, rather they are looking for the approach, fundamentals etc. So, even if I'd asked this question to a candidate and even if they had been able to come up with just the `Clean()` logic (that too flawed), if they show signs of good testing, adapting to feedback, writing clean code etc., I'd give them benefit of doubt. Ofcourse, the level/position for which we are hiring also matters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T20:22:47.130", "Id": "504311", "Score": "0", "body": "Given this, I respect your assessment of my code and probably agree as to how this is not a suitable interview question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T03:53:33.970", "Id": "504342", "Score": "0", "body": "@CalmCurtain: I propose turning your approach around. Set a problem, solve it yourself, time yourself doing it, then assume that applicants will need _more_ time than you. Depending on presumed skill level difference, I'd add another 50% to 100% of the time you spent solving it. And by solving, I mean solving it without _anything_ that would draw negative feedback if an applicant delivered this code. Anything less is unfair to applicants taking the test, it makes it an exercise with an impossible standard. If this means the exercise takes too long, then you need to simplify the exercise itself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T18:58:59.353", "Id": "504395", "Score": "0", "body": "\"And by solving, I mean solving it without anything that would draw negative feedback if an applicant delivered this code.\" - I wouldn't necessarily agree to that. The candidate does not have to finish a question in an interview for the interviewer to be able to assess the candidate. I'd argue that a good interviewer should still be able to assess the candidate despite not knowing the answer to the question himself/herself. i.e, even if the first time the interviewer themselves is solving the question is during the interview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:08:24.713", "Id": "504453", "Score": "0", "body": "@CalmCurtain: _\"The candidate does not have to finish a question in an interview for the interviewer to be able to assess the candidate.\"_ That is not the same as saying that an interview answer must be completable. There's a difference between still evaluating a partial answer and making it so that you can _at best_ write a partial answer. If you go this route, at the _very_ very least **announce it** to the applicant that this challenge is not meant to be completed. But I still think it's a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:17:54.190", "Id": "504456", "Score": "0", "body": "@CalmCurtain: Why does most bad practice happen? Some of it is inexperience, but the vast majority stems from **being given a much too short deadline**. If you give your applicants an unreasonably short time to complete it, then any developer worth their salt who is able to plan their time is going to (**correctly**) realize that they don't have time to deliver the code with full good practice implementations yet. If you then turn around and _not_ judge what you asked them to deliver, and instead judge them on the good practice you effectively forced them to avoid, **that is massively unfair**" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T11:45:35.430", "Id": "255557", "ParentId": "255545", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T06:35:39.560", "Id": "255545", "Score": "0", "Tags": [ "interview-questions" ], "Title": "Implement an algorithm for a room cleaning robot" }
255545
<p>I have a modal for adding new contacts, in order to disable the save button if no data has entered I check if the contact object is empty, is there a shorter way to check for an empty complex object?</p> <pre><code> let isContactEmpty = true Object.keys(contact).forEach(field =&gt; { if (typeof contact[field] === 'string' &amp;&amp; contact[field]) { isContactEmpty = false return } if (typeof contact[field] === 'object') { contact[field].forEach(fieldVal =&gt; { if (fieldVal.value.length) { isContactEmpty = false } }) } }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T09:28:48.180", "Id": "504232", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T12:16:27.230", "Id": "504358", "Score": "1", "body": "Can you please add some possible values for `contact` variable and what is considered as an empty object?" } ]
[ { "body": "<ul>\n<li>Is there a particular reason you're using a <code>.forEach()</code> instead of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for-of</code></a>?. Because <code>.forEach()</code> uses a function for iteration, you don't have a way to stop early once you've you know the contact is not empty. If you used <code>for-of</code> instead, you can just <code>return false</code> once you know the result will be false.</li>\n<li>It looks like you're doing a <code>typeof value === 'object'</code> to check if something is an array. Instead, you can do <a href=\"https://developer.mozilla.org/en-us/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\" rel=\"nofollow noreferrer\"><code>Array.isArray(value)</code></a>.</li>\n<li>You're looping over the keys of the object, but you only use the key to get the field's value. Why not just loop over the values instead with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values\" rel=\"nofollow noreferrer\"><code>Object.values()</code></a>?</li>\n</ul>\n<p>With these suggestions applied, your code would look something like this:</p>\n<pre><code>function isContactEmpty(contact) {\n for (const field of Object.values(contact)) {\n if (typeof field === 'string' &amp;&amp; field) {\n return false\n } else if (Array.isArray(field)) {\n for (const { value } of field) {\n if (value.length) return false\n }\n }\n }\n return true\n}\n</code></pre>\n<p>But, we can take it a step further. Javascript has a higher-level function to do exactly what we're doing with these loops, but without the boilerplate - <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\"><code>array.every()</code></a>. It takes a callback that returns a boolean and gets called with each element of an array. The return value of every() is true if all the callbacks returned true, or false if one of them returned false. (It'll also stop iterating as soon as one callback returns false).</p>\n<pre><code>const isContactEmpty = contact =&gt; (\n Object.values(contact).every(field =&gt; {\n if (typeof field === 'string') return !field\n if (Array.isArray(field)) return areArrayEntriesEmpty(field)\n return true\n })\n)\n\nconst areArrayEntriesEmpty = field =&gt; (\n field.every(({ value }) =&gt; value.length === 0)\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T03:56:52.857", "Id": "504638", "Score": "0", "body": "Since your implementation iterate over `Object.values()`. Maybe `field` is not a good name for loop variable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T03:38:44.137", "Id": "255588", "ParentId": "255547", "Score": "2" } } ]
{ "AcceptedAnswerId": "255588", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T07:06:50.073", "Id": "255547", "Score": "1", "Tags": [ "javascript" ], "Title": "Check for empty object" }
255547
<p>I've been solving K&amp;R 1-14.</p> <blockquote> <p><strong>Exercise 1-14.</strong> Write a program to print a histogram of the frequencies of different characters in its input.</p> </blockquote> <p>After several edits, it looks good to me now. But it's my first time to write a long code(it's long to me). I wonder if there is more simple and shorter code with the same logic or I wrote a bad style code or not. I also wonder whether my vertical graph looks good and well written. Any suggestion will be so appreciated!</p> <pre><code>#include &lt;stdio.h&gt; /* print a graph of the frequencies of different characters */ #define GRAPH_HEIGHT 20 main() { int af[26] = {0}; int max = 1; int c; int i, j; /* get characters */ while ((c = getchar()) != EOF) { if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') if (++af[c - 'a'] &gt; max) { ++max; continue; } if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') if (++af[c - 'A'] &gt; max) ++max; } /* calculate a relative frequencies */ for (i = 0; i &lt; 26; ++i) { af[i] = GRAPH_HEIGHT * af[i] / max; } /* print characters on a graph */ for (i = GRAPH_HEIGHT; i &gt; 0; --i) { printf(&quot;%2d |&quot;, i); for (j = 'a'; j &lt;= 'z'; ++j) { if (af[j - 'a'] == i) { printf(&quot; | &quot;); --af[j - 'a']; } else printf(&quot; &quot;); } printf(&quot;\n&quot;); } printf(&quot; &quot; &quot;*&quot; &quot;---------------&quot; &quot;---------------&quot; &quot;---------------&quot; &quot;---------------&quot; &quot;---------------&quot; &quot;---&quot; &quot;\n&quot;); printf(&quot; &quot;); for (i = 'a'; i &lt;= 'z'; ++i) { printf(&quot;%3c&quot;, i); } printf(&quot;\n&quot;); } </code></pre>
[]
[ { "body": "<p>This is a pretty good start. You should be warned that K&amp;R describes a very early version of C, and the language has evolved considerably since the 1980s.</p>\n<p>For example, we normally always write function declarations as <em>prototypes</em>, i.e. specifying the argument types, and we don't depend on the implicit <code>int</code>. So:</p>\n<pre><code>int main(void)\n</code></pre>\n<p>Also, we don't need to declare all variables at the start of their scope any more; instead, we can declare them where they are initialised:</p>\n<pre><code>for (int i = 0; i &lt; 26; ++i)\n</code></pre>\n<p>Although the problem statement says that you should chart the frequency of different characters, we have implemented something different here, because we're only counting the characters between <code>a</code> and <code>z</code> and between <code>A</code> and <code>Z</code>.</p>\n<p>While looking at that, there's a non-portable assumption in this code that <code>'Z'-'A'</code> and <code>'z'-'a'</code> are both 25. That is true on ASCII systems, but definitely not true on EBCDIC systems, for example, where this code will index <code>af</code> outside its bounds.</p>\n<p>You could solve this by declaring <code>af</code> differently:</p>\n<pre><code>#define AZ_COUNT ('z' - 'a' + 1)\nunsigned int af[AZ_COUNT] = {0};\n</code></pre>\n<p>I think I would store counts of all different characters, and filter to just the alphabetic ones later (and use <code>isalpha()</code> for that, from <code>&lt;ctype.h&gt;</code>):</p>\n<pre><code>#include &lt;limits.h&gt;\nunsigned int af[UCHAR_MAX+1] = {0};\n</code></pre>\n<p>That can make it easier to adapt the printing part (e.g. to show digits and punctuation characters) later. (Note the use of <code>unsigned int</code>, too - a negative count makes no sense).</p>\n<p>I think the printing part would be better if it didn't modify the counts. We can ensure that if we split the counting and printing into separate functions:</p>\n<pre><code>void count_chars(FILE *in, unsigned int *frequencies);\nvoid print_graph(FILE *out, const unsigned int *frequencies);\n</code></pre>\n<p>That <code>const</code> helps us write code that's more reusable.</p>\n<hr />\n<p>With my changes, the code looks more like this (not perfect, but I hope it has some items to learn from):</p>\n<pre><code>#include &lt;ctype.h&gt;\n#include &lt;limits.h&gt;\n#include &lt;stdio.h&gt;\n\n/* print a graph of the frequencies of different characters */\n\n#define GRAPH_HEIGHT 20\n\nstatic void count_chars(FILE *in, unsigned int *frequencies)\n{\n int c;\n while ((c = fgetc(in)) != EOF) {\n ++frequencies[(unsigned char)c];\n }\n}\n\nstatic void print_graph(FILE *out, const unsigned int *frequencies)\n{\n /* start at 1 to avoid division by 0 later */\n unsigned int max = 1;\n for (unsigned int i = 0; i &lt;= UCHAR_MAX; ++i) {\n if (frequencies[i] &gt; max) {\n max = frequencies[i];\n }\n }\n\n /* print characters on a graph */\n for (unsigned int i = GRAPH_HEIGHT; i &gt; 0; --i) {\n fprintf(out, &quot;%2d |&quot;, i);\n for (int c = 0; c &lt;= UCHAR_MAX; ++c) {\n if (!isalnum(c)) { continue; }\n char bar = frequencies[c] &gt;= i * max / GRAPH_HEIGHT ? '|' : ' ';\n fprintf(out, &quot; %c &quot;, bar);\n }\n fputs(&quot;\\n&quot;, out);\n }\n\n /* print the base line */\n fputs(&quot; +&quot;, out);\n for (int c = 0; c &lt;= UCHAR_MAX; ++c) {\n if (!isalnum(c)) { continue; }\n fputs(&quot;---&quot;, out);\n }\n fputs(&quot;\\n&quot;, out);\n for (int c = 0; c &lt;= UCHAR_MAX; ++c) {\n if (!isalnum(c)) { continue; }\n fprintf(stdout, &quot;%3c&quot;, c);\n }\n fputs(&quot;\\n&quot;, out);\n}\n\nint main(void)\n{\n unsigned int af[UCHAR_MAX+1] = {0};\n count_chars(stdin, af);\n print_graph(stdout, af);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T11:29:50.227", "Id": "504248", "Score": "0", "body": "Wow, thanks for the detailed answer. I enjoyed your code by freely modifying it.\nAnyway, I have one question. I saw the CS50 course and a professor said \"It's just human convention to put the main program at the top\". You put the main() at the bottom. Is there a special reason to that? In order not to type the function prototype?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T11:33:53.213", "Id": "504249", "Score": "1", "body": "I have to admit I'm not even consistent whether I start with bare prototypes and `main()`, or write definitions and put `main()` last. Do it whichever way you're happy with!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T11:36:04.217", "Id": "504251", "Score": "1", "body": "I've made an edit, to declare the helpers with *static linkage*. That makes no perceptible difference for single-file programs like this, but helps keep concerns separate when you get to bigger programs comprising multiple object files." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T10:24:25.043", "Id": "255552", "ParentId": "255551", "Score": "5" } } ]
{ "AcceptedAnswerId": "255552", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T08:50:47.970", "Id": "255551", "Score": "5", "Tags": [ "beginner", "c" ], "Title": "Print a character frequencies as a vertical graph" }
255551
<p>I'm in the process of understanding shell scripting - this is my simple code for adding test files for python <a href="https://docs.python.org/3/library/unittest.html" rel="nofollow noreferrer">unittest</a></p> <p>I'm looking for best practice pointers, variable naming, and of course comments on structure and readability.</p> <p>EDIT: Script is called by, for example</p> <pre><code>./create_tests.sh math tensor_add </code></pre> <pre><code>dir_name=&quot;$1&quot; file_name=&quot;$2&quot; test_dir=&quot;test/${dir_name}&quot; file_in_dir=&quot;${test_dir}/${file_name}.py&quot; addFile() { if [[ -f &quot;${file_in_dir}&quot; ]] then echo &quot;File already exists in directory, exiting.&quot; exit 0 else touch &quot;${file_in_dir}&quot; fi } if [[ -d &quot;${test_dir}&quot; ]] then echo &quot;Directory already exists, adding the file to this directory.&quot; addFile else echo &quot;Directory and __init__.py created.&quot; mkdir &quot;${test_dir}&quot; touch &quot;${test_dir}/__init__.py&quot; addFile fi </code></pre>
[]
[ { "body": "<ol>\n<li>Add a shebang.</li>\n<li>Keep naming consistent, I personally prefer and follow <a href=\"https://google.github.io/styleguide/shellguide.html#s7-naming-conventions\" rel=\"nofollow noreferrer\">Google's style guide</a>; you may use a different guide if available.</li>\n<li>Try to make your script POSIX compliant, for a wider target reach (no need to rely on <code>[[</code> expression from bash)</li>\n<li>Define a function to create the test directory.</li>\n<li>Use <a href=\"https://github.com/koalaman/shellcheck\" rel=\"nofollow noreferrer\">shellcheck</a>.</li>\n<li>The <code>echo &quot;Directory and __init__.py created.&quot;</code> should happen <strong>after</strong> the creation has happened.</li>\n<li>Use <code>mkdir -p</code> to allow for nested directories to also be created (if needed).</li>\n<li>Let script throw error and stop as early as possible on errors. This is achieved with <a href=\"https://stackoverflow.com/q/19622198/1190388\"><code>set -e</code></a>.</li>\n</ol>\n<hr />\n<p>Together:</p>\n<pre><code>#!/bin/sh\n\nset -e\n\ndir_name=&quot;$1&quot;\nfile_name=&quot;$2&quot;\ntest_dir=&quot;test/${dir_name}&quot;\nfile_in_dir=&quot;${test_dir}/${file_name}.py&quot;\n\nadd_file() {\n if test -f &quot;${file_in_dir}&quot;\n then\n echo &quot;File already exists in directory, exiting.&quot;\n exit 0\n else\n touch &quot;${file_in_dir}&quot;\n fi\n}\n\ncreate_dir() {\n mkdir -p &quot;${test_dir}&quot;\n touch &quot;${test_dir}/__init__.py&quot;\n echo &quot;Directory and __init__.py created.&quot;\n}\n\n[ ! -d &quot;${test_dir}&quot; ] &amp;&amp; create_dir &quot;${test_dir}&quot;\n\nadd_file\n</code></pre>\n<p>The chunk of variable declarations (<code>dir_name</code>, <code>file_name</code> etc.) could also be localised to functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T13:03:56.647", "Id": "504260", "Score": "1", "body": "You missed \"extract common lines from `if`/`else`\" from the list - though you've demonstrated in your reworked code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T13:35:10.093", "Id": "504264", "Score": "0", "body": "Thank you for your brilliant advice. One question: what is the difference between the double brackets and single brackets in my contra your implementation? Does it have to do with POSIX compliance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T14:11:50.110", "Id": "504267", "Score": "0", "body": "https://stackoverflow.com/q/669452/2002471 explains why double brackets are a good thing. Striving for POSIX-compliance after bash and Linux has taken over the world is an interesting prioritization. I'd hope that code readability and maintainability are more important these days. Going from `if [[` to `if test` makes sense to people who understand how shell if's work, but I'd say it makes it less readable and intuitive for most folks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T12:47:48.933", "Id": "255561", "ParentId": "255558", "Score": "2" } } ]
{ "AcceptedAnswerId": "255561", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T11:46:44.447", "Id": "255558", "Score": "2", "Tags": [ "bash", "shell" ], "Title": "Bash - Automating creation of test files" }
255558
<h1>Code</h1> <pre><code>@Service @Slf4j public class SpendingServiceImpl implements SpendingService { private final SpendingGroupRepository spendingGroupRepository; private final SpendingRepository spendingRepository; private final IdempotencyRepository idempotencyRepository; private final TransactionTemplate transactionTemplate; public SpendingServiceImpl(SpendingGroupRepository spendingGroupRepository, SpendingRepository spendingRepository, IdempotencyRepository idempotencyRepository, PlatformTransactionManager platformTransactionManager) { this.spendingGroupRepository = spendingGroupRepository; this.spendingRepository = spendingRepository; this.idempotencyRepository = idempotencyRepository; this.transactionTemplate = new TransactionTemplate(platformTransactionManager); this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } @Override public void addSpending(SpendingMessageDto spendingMessageDto) { SpendingGroup spendingGroup; try { spendingGroup = spendingGroupRepository .findByExternalId(spendingMessageDto.getSpendingGroupId()) .orElseGet(() -&gt; spendingGroupRepository.save(SpendingGroup.builder() .externalId(spendingMessageDto.getSpendingGroupId()) .description(&quot;Banana&quot;).build())); } catch (DataIntegrityViolationException e) { // Parallel Insert Violates Unique Key, get the entry spendingGroup = spendingGroupRepository.findByExternalId(spendingMessageDto.getSpendingGroupId()).orElseThrow(); } if (spendingGroup == null) { throw new RuntimeException(&quot;&quot;); // TODO: Real exception } Idempotency idempotency; try { // Needs transaction for LOB (TEXT) idempotency = transactionTemplate.execute(transactionStatus -&gt; idempotencyRepository.findByIdempotencyKey(spendingMessageDto.getIdempotencyKey()) .orElseGet(() -&gt; idempotencyRepository.save(Idempotency.builder() .idempotencyKey(spendingMessageDto.getIdempotencyKey()) .status(IdempotencyStatus.CREATED) .build()))); } catch (DataIntegrityViolationException e) { // Parallel Insert Violates Unique Key, get the entry idempotency = idempotencyRepository.findByIdempotencyKey(spendingMessageDto.getIdempotencyKey()).orElseThrow(); } if (idempotency == null) { throw new RuntimeException(&quot;&quot;); // TODO: Real exception } switch (idempotency.getStatus()) { case ERROR_NOT_RETRYABLE, FINISHED -&gt; { log.info(&quot;Returning response: &quot; + idempotency.getStatus() + &quot; - &quot; + idempotency.getResponse()); return; } } // Now try to lock the row final SpendingGroup spendingGroup1 = spendingGroup; transactionTemplate.executeWithoutResult(transactionStatus -&gt; { // PESSIMISTIC_WRITE, SHOULD block all others with SELECT FOR UPDATE Idempotency idm = idempotencyRepository.findByIdempotencyKeyPW(spendingMessageDto.getIdempotencyKey()).orElseThrow(); switch (idm.getStatus()) { case ERROR_NOT_RETRYABLE, FINISHED -&gt; { log.info(&quot;Returning response: &quot; + idm.getStatus() + &quot; - &quot; + idm.getResponse()); return; } } log.warn(&quot;-----------PROCESSING----------&quot;); Spending spending = Spending.builder() .spendingGroupId(spendingGroup1.getId()) .amount(new BigDecimal(spendingMessageDto.getAmount())) .build(); spendingRepository.save(spending); idm.setStatus(IdempotencyStatus.FINISHED); idm.setCode(200); idm.setResponse(&quot;Ok&quot;); }); } } </code></pre> <h1>What is the goal?</h1> <p>There are many parallel messages delivered from a message queue. These messages contain a &quot;payment&quot; and follow the pattern <code>amount=11.11;spending_group=adeu47;idempotency_key={uuid}</code></p> <p>So basically Payment Group is a collector for payments. And each payment shall only be inserted exactly once. But the message broker has a retry mechanism when a message isn't acknowledged in time.</p> <h1>Current Design</h1> <ol> <li>For every message, check if the spending group exists. If not insert it. <ul> <li>This can fail if a parallel process also reads and tries to insert. Then the solution is to read what was written. <strong>Is catching the UniqueKeyViolation the right thing here?</strong></li> </ul> </li> <li>Same with the idempotency key, get or create, catch the UniqueKeyViolation</li> <li>If the idempotency request is in a final state (basically was sent already), return the saved response.</li> <li>If the idempotency request is in status new or retryable, select again, this time with a pessimistic write lock. <ul> <li><strong>Is there any better way do to this? The double select seems weird. But I only need a lock when the state isn't finished.</strong></li> </ul> </li> <li>While holding the row lock, do the processing. then persist the response and set the status to FINISHED.</li> </ol> <h2>Additional questions</h2> <ol> <li>I tried the design in a concurrent test case and it seemed to work. Is there any obvious oversight?</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T14:07:48.537", "Id": "255565", "Score": "2", "Tags": [ "spring", "hibernate" ], "Title": "Idempotent Processing of Messages" }
255565
<p>Given this ciphertext from a Caesar cipher:</p> <blockquote> <p>fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq</p> </blockquote> <p>The task is to decrypt it without being given the key.</p> <p>My solution:</p> <pre class="lang-py prettyprint-override"><code>napis = &quot;fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq&quot;.upper() ALPHABET = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ &quot; napis = [ALPHABET.index(i) for i in napis] for x in range(0,4): wynik = [ALPHABET[i+x] if i+x&lt;len(ALPHABET) else ALPHABET[i+x-len(ALPHABET)] for i in napis] print(&quot;&quot;.join(wynik)) </code></pre> <p>output:</p> <pre class="lang-none prettyprint-override"><code>FXEYAXKLQXHKLTKXQEBOBXTBOBXPLXJYKVXFAFLQPXFKXQEBXTLOIAXRKQFIXFXPQYOQBAXRPFKDXQEBXFKQBOKBQ GYFZBYLMRYILMULYRFCPCYUCPCYQMYKZLWYGBGMRQYGLYRFCYUMPJBYSLRGJYGYQRZPRCBYSQGLEYRFCYGLRCPLCR HZG CZMNSZJMNVMZSGDQDZVDQDZRNZL MXZHCHNSRZHMZSGDZVNQKCZTMSHKZHZRS QSDCZTRHMFZSGDZHMSDQMDS I HAD NOT KNOWN THERE WERE SO MANY IDIOTS IN THE WORLD UNTIL I STARTED USING THE INTERNET </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:40:04.870", "Id": "504292", "Score": "0", "body": "@Toby My answer's suggestion with frequencies and spaces was inspired/justified by that now-deleted sentence :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T18:25:15.467", "Id": "504298", "Score": "0", "body": "Oh, sorry - it looked like a request to change the code. Is there a way it could be fixed and reinstated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T23:24:04.743", "Id": "504316", "Score": "1", "body": "Welcome to Code Review! 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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." } ]
[ { "body": "<ul>\n<li>Don't use meaningless names like &quot;napis&quot; and &quot;wynik&quot;.</li>\n<li><code>x</code> and <code>i</code> are meaningful in some contexts, but not for what you're using them, so use better names for those as well.</li>\n<li>You could take advantage of negative indices, i.e., remove <code>ALPHABET[i+x] if i+x&lt;len(ALPHABET) else </code> and just use <code>ALPHABET[i+x-len(ALPHABET)]</code>. Or, more generally, <code>ALPHABET[(i+x) % len(ALPHABET)]</code>.</li>\n<li>You could assume that spaces are the most frequent characters and do <code>x = ALPHABET.index(' ') - max(napis, key=napis.count)</code> instead of the loop.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:02:08.240", "Id": "504281", "Score": "4", "body": "Polish words are \"meaningless\" to you, but probably convey a lot more to the author (presumably Polish?). I don't think it's fair to insist that everyone code in English, even when the keywords are English, unless they intend to share that code amongst English speakers. It's not even that hard for the rest of us: Wiktionary says they mean `string` and `result`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:03:18.307", "Id": "504282", "Score": "1", "body": "@TobySpeight They *did* share that code amongst English speakers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:04:33.113", "Id": "504283", "Score": "3", "body": "It might be better to say \"Use English names\" rather than calling Polish \"meaningless\". It just seems offensive to belittle an entire language like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:09:46.560", "Id": "504285", "Score": "1", "body": "@TobySpeight I'm not belittling a culture. I see no meaning in those words and I even checked them at dictionary.com (because I'm not a native English speaker), and there are *no results*. They're asking for a review, i.e., what we think of their code, and that's what I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:12:44.193", "Id": "504287", "Score": "1", "body": "Wiktionary evidently has better coverage: [napis](https://en.wiktionary.org/wiki/napis#Noun_3), [wynik](https://en.wiktionary.org/wiki/wynik#Noun)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:15:15.490", "Id": "504288", "Score": "1", "body": "@TobySpeight Not for English, though, and this is an English-speaking site and they shouldn't expect us to know Polish or find it out." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T14:52:52.263", "Id": "255567", "ParentId": "255566", "Score": "3" } }, { "body": "<p>It seems like your current solution would require the person to look through all the possible decryptions and decide which one is right. That could work ok, but it might not be necessary. It could be possible for the program to figure it out itself.</p>\n<p>Here’s an example of superb rain’s idea to assume the decryption with the most spaces is the correct one:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import string\n\nencrypted_text = &quot;fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq&quot;\n\nch_list = string.ascii_lowercase + ' '\n\ndef translation_maker(offset, ch_list):\n \n translation_dict = dict()\n \n for ind, ch in enumerate(ch_list):\n translation_dict[ch] = ch_list[(ind + offset) % len(ch_list)]\n \n return str.maketrans(translation_dict)\n\ndef translation_generator(text, ch_list):\n \n for ind in range(len(ch_list)):\n for offset in range(len(ch_list)):\n yield text.translate(translation_maker(offset, ch_list))\n \nlikely_decryption = max(translation_generator(encrypted_text, ch_list), key=lambda x: x.count(' '))\n\nprint(likely_decryption)\n# a lot of this could be one-lined, but it might maybe considered less readable\n# e.g.:\n&quot;&quot;&quot;\nlikely_decryption = max(\n (\n encrypted_text.translate(str.maketrans(\n {\n ch: ch_list[(ind + offset) % len(ch_list)]\n for ind, ch in enumerate(ch_list)\n }))\n for offset in range(len(ch_list))\n ),\n key=lambda x: x.count(' '))\n&quot;&quot;&quot;\n</code></pre>\n<p>It prints the correct string in this case.</p>\n<p>A different thing you could do is have a big set with every word in the English language, and assume the correct decryption is the one that has the most matches with the set after you split it by space. It would be mostly the same, but the lambda function would be changed to this:\n<code>key=lambda x: sum(word in word_set for word in x.split()))</code></p>\n<p>This might be slower even when disregarding the creation of the word set, and it would obviously use more memory, but it would be more unlikely to give a wrong result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T07:39:36.147", "Id": "255590", "ParentId": "255566", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T14:11:15.680", "Id": "255566", "Score": "2", "Tags": [ "python", "caesar-cipher" ], "Title": "Python decryption of Caesar Cipher" }
255566
<p>I made this simple Tetris game where I only have 2 blocks, the square and the line. Also the game ends after 20 blocks are created and the player wins. I was wondering how I can make it better overall.</p> <p>Here's the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;windows.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #define RIGA 21 #define COLONNA 10 #define DESTRA 77 #define SINISTRA 75 #define GIU 80 #define SU 72 void GotoXY(int x, int y) { COORD CursorPos = {x, y}; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hConsole, CursorPos); } // FUNCTION PER RALLENTARE I MOVIMENTI void ritardo() { long double i; for(i=0;i&lt;=(30000000);i++); } int i, j; // CONTATORI int sposta, random; // VARIABILI BOOLEANE int punti = 0; // VARIABILE PER ASSEGNAZIONE DEI PUNTI int contatore_pezzi = 1; // VARIABILE PER CONTARE IL NUMERO DI OGGETTI CREATI char griglia[21][10]; // DICHIARAZIONE ARRAY DI CHAR char pezzo[2][2] = {{'X', 'X'}, // DICHIARAZIONE CUBO {'X', 'X'}}; char linea[3][1] = {{'X'}, {'X'}, {'X'}}; // DICHIARAZIONE LINEA char linea_or[1][3] = { {'X'},{'X'},{'X'}}; void caricaArray() // INIZIALIZZA L'ARRAY VUOTO CON CICLI FOR INNESTATI { for (i = 0; i &lt; RIGA; i++) { for (j = 0; j &lt; COLONNA; j++) { griglia[i][j] = ' '; } } } // PROTOTIPI FUCTION void movimenti(); void assegnaPezzo(); void eliminaRiga(); void stampaBordi(); int main() { caricaArray(); movimenti(); printf(&quot;\n\n&quot;); return 0; } void visualizzaArray() // VISUALIZZA L'ARRAY ALLO STATO ATTUALE { printf(&quot;\n&quot;); for (i = 0; i &lt; RIGA; i++) { printf(&quot; &quot;); //Spazio per visualizzare tutti i punti all'interno del bordo for (j = 0; j &lt; COLONNA; j++) { printf(&quot;%c &quot;, griglia[i][j]); } printf(&quot;\n&quot;); } stampaBordi(); } void movimenti() // GESTISCE TUTTI I POSSIBILI MOVIMENTI DELLA FORMA { do { eliminaRiga(); // Ad ogni ciclo verifica la presenza di righe piene int r = 0; int c = 4; srand(time(NULL)); // Random random = rand() % 2; assegnaPezzo(); visualizzaArray(); do { GotoXY(r,c); // Inizia a scorrere verso il basso r++; system(&quot;cls&quot;); if (random == 0) { // Se l'oggetto creato e' il cubo griglia[r-1][c] = ' '; // Libera le posizioni precedenti griglia[r-1][c+1] = ' '; griglia[r][c] = pezzo[0][0]; // Riassegna l'oggetto nella nuova posizione griglia[r][c+1] = pezzo[0][1]; griglia[r+1][c] = pezzo[1][0]; griglia[r+1][c+1] = pezzo[1][1]; } if (random == 1) { // Se l'oggetto creato e' la linea if ( !kbhit() ) // Se non si premono tasti { griglia[r-1][c] = ' '; // Libera le posizioni precedenti griglia[r][c] = linea[0][0]; // Riassegna l'oggetto nella nuova posizione griglia[r+1][c] = linea [1][0]; griglia[r+2][c] = linea [2][0]; } } visualizzaArray(); ritardo(); if ( kbhit() ) // Se durante lo scroll verticale si preme un tasto { sposta = getch(); // Prende in input un tasto e lo assegna alla variabile sposta if (sposta==SU) // E se e' la freccia SU { griglia[r-1][c] = ' '; griglia[r][c-1] = linea_or[0][0]; griglia[r][c] = linea_or[1][0]; griglia[r][c+1] = linea_or[2][0]; } if (sposta == DESTRA ) // E se e' la freccia DESTRA { c++; // L'oggetto si sposta a destra system(&quot;cls&quot;); if (random == 0) { if (c+1&gt;COLONNA-1) { break; } // Se supera il bordo destro griglia[r][c-1] = ' '; // Libera le posizioni precedenti griglia[r+1][c-1] = ' '; } else if (random == 1) { griglia[r-2][c-1] = ' '; // Libera le posizioni precedenti griglia[r-1][c-1] = ' '; griglia[r][c-1] = ' '; griglia[r+1][c-1] = ' '; griglia[r+2][c-1] = ' '; } visualizzaArray(); //visualizza il tutto } if (sposta == SINISTRA ) // E se e' la freccia SINISTRA { c--; // L'oggetto si sposta a sinistra if (c&lt;0) { break; } // Se supera il bordo sinistro system(&quot;cls&quot;); if (random == 0) { griglia[r][c+2] = ' '; // Libera le posizioni precedenti griglia[r+1][c+2] = ' '; } else if (random == 1) { griglia[r-1][c+2] = ' '; // Libera le posizioni precedenti griglia[r-1][c+1] = ' '; griglia[r][c+1] = ' '; griglia[r+1][c+1] = ' '; griglia[r+2][c+1] = ' '; } visualizzaArray(); } } if (random == 0) { if (griglia[r+2][c] == 'X' || griglia[r+2][c+1] == 'X') // Se il pezzo tocca un altro pezzo inferiormente { if (griglia[0][c] == 'X' || griglia[1][c] == 'X') // Se lo spazio superiore e' troppo piccolo { system(&quot;cls&quot;); printf(&quot;HAI PERSO!\nPremi ESC per uscire.&quot;); break; } contatore_pezzi++; return movimenti(); //Allora attiva la ricorsivita' } } if (random == 1) { if (griglia[r+3][c] == 'X') { if (griglia[0][c] == 'X' || griglia[1][c] == 'X') { system(&quot;cls&quot;); printf(&quot;HAI PERSO!\nPremi ESC per uscire.&quot;); break; } contatore_pezzi++; return movimenti(); } } if (random == 0) { if (r+1==20) { // Se tocca il borso inferiore crea un altro oggetto contatore_pezzi++; return movimenti(); } } else if (random == 1) { if (r+2==20) { // Se tocca il borso inferiore crea un altro oggetto contatore_pezzi++; return movimenti(); } } } while ( sposta != 27 ); } while ( getch() != 27 ); } void stampaBordi() // STAMPA LA CORNICE DEL CAMPO DI GIOCO { for(i=1;i&lt;=19;i++) { GotoXY(i,22); putch('-'); GotoXY(i,0); putch('-'); } printf(&quot; PUNTI:%d - PEZZO No %d&quot;, punti, contatore_pezzi); for (j=1;j&lt;22; j++) { GotoXY(0,j); putch('|'); GotoXY(20,j); putch('|'); } } void assegnaPezzo() { int i1 = 0; int j1 = 4; if (random==0) { griglia[i1][j1] = pezzo[0][0]; // Assegna il pezzo nella posizione iniziale griglia[i1][j1+1] = pezzo[0][1]; griglia[i1+1][j1] = pezzo[1][0]; griglia[i1+1][j1+1] = pezzo[1][1]; } if (random==1) { griglia[i1][j1] = linea[0][0]; griglia[i1+1][j1] = linea [1][0]; griglia[i1+2][j1] = linea [2][0]; } } void eliminaRiga() // ELIMINA UNA O PIU' RIGHE, SE PIENE { int k; int cont_riga; int colonna; char aus[COLONNA]; for (cont_riga=0; cont_riga&lt;=20; cont_riga++) { if (griglia[cont_riga][0] == 'X' &amp;&amp; griglia[cont_riga][1] == 'X' &amp;&amp; griglia[cont_riga][2] == 'X' &amp;&amp; griglia[cont_riga][3] == 'X' &amp;&amp; griglia[cont_riga][4] == 'X' &amp;&amp; griglia[cont_riga][5] == 'X' &amp;&amp; griglia[cont_riga][6] == 'X' &amp;&amp; griglia[cont_riga][7] == 'X' &amp;&amp; griglia[20][8] == 'X' &amp;&amp; griglia[20][9] == 'X') { for (colonna=0; colonna&lt;10; colonna++) { aus[colonna] = griglia[cont_riga-1][colonna]; } for (colonna=0; colonna&lt;10; colonna++) { griglia[cont_riga][colonna] = aus[colonna]; } for (colonna=0; colonna&lt;10; colonna++) { griglia[cont_riga-1][colonna] = '.'; } punti++; for (k=2; k&lt;11; k++) { if (griglia[cont_riga-k][0] == 'X' || griglia[cont_riga-k][1] == 'X' || griglia[cont_riga-k][2] == 'X' || griglia[cont_riga-k][3] == 'X' || griglia[cont_riga-k][4] == 'X' || griglia[cont_riga-k][5] == 'X' || griglia[cont_riga-k][6] == 'X' || griglia[cont_riga-k][7] == 'X' || griglia[cont_riga-k][8] == 'X' || griglia[cont_riga-k][9] == 'X' ) { for (colonna=0; colonna&lt;10; colonna++) { aus[colonna] = griglia[cont_riga-k][colonna]; } for (colonna=0; colonna&lt;10; colonna++) { griglia[cont_riga-k+1][colonna] = aus[colonna]; } for (colonna=0; colonna&lt;10; colonna++) { griglia[cont_riga-k][colonna] = '.'; } } } system(&quot;cls&quot;); visualizzaArray(); } } } </code></pre>
[]
[ { "body": "<p>Some suggestions in no particular order:</p>\n<ol>\n<li><p>Organize your header files.</p>\n<p>I like to group related things together. In this case, &quot;standard&quot; versus &quot;OS specific&quot;. I also default to sorting things alphabetically/asciibetically if there is no reason to do otherwise.</p>\n</li>\n<li><p>Group related things: functions with functions, variables with variables. Don't mix functions and global variables randomly.</p>\n</li>\n<li><p>Don't make variables global unless you must. Your <code>i</code> and <code>j</code> should be local variables.</p>\n</li>\n<li><p>Tetris lines have 4 blocks, not 3.</p>\n</li>\n<li><p>Use library functions where possible. Your <code>ritardo()</code> seems like a bad replacement for POSIX <code>sleep()</code> or Windows <code>Sleep()</code>.</p>\n</li>\n<li><p>Use <code>memset</code> to initialize your <code>griglia</code> in <code>caricaArray</code>:</p>\n<pre><code>memset(griglia, SPACE, sizeof(griglia));\n</code></pre>\n</li>\n<li><p>Standard C requires the use of <code>void</code> to prototype a function taking no arguments. (C++ allows empty parens to mean no arguments.) So a line like:</p>\n<pre><code>void movimenti();\n</code></pre>\n<p>isn't really a prototype, but a declaration.</p>\n</li>\n<li><p>Turn on <strong>every possible warning.</strong> Your compiler has some settings, somewhere, that will enable &quot;All warnings&quot;. It then probably has settings that will enable &quot;Uncommon warnings&quot; or &quot;Extra warnings&quot; or something. It might even have a setting for &quot;Enable incredibly pedantic, ridiculous warnings&quot;. Turn them on. All of them.</p>\n</li>\n<li><p>The definition of <code>main()</code> should either be the very first, or the very last, function. If you favor &quot;read my programs&quot; then <code>main</code> is first, and functions will be appended to the end as they are used (main calls A, A calls B, etc.) If you favor &quot;avoid forward declarations&quot; then you try to define every function before it gets called. So lowest-level functions go at the top of the file, then higher, and finally <code>main()</code> at the end. If you favor &quot;everything should be in alphabetical order&quot; then you're a psychopath, but at least you know where things should be.</p>\n<p>This is a matter of style, so pick one and stay with it.</p>\n</li>\n<li><p>Don't mix terminal modes. If you're going to position the cursor and draw characters, then write your own print functions (to manage a scrolling window, if nothing else). Also, don't call <code>cls</code> to clear the screen. Just write your own function.</p>\n</li>\n<li><p>Write more functions</p>\n<p>You have some very large functions. There are lots of guidelines about what makes a good size for a function, but most of them concentrate on keeping functions visible on a single screen. (Some suggest very low numbers. You'd be surprised what you can do if you try to use a really small number!)</p>\n<p>As a suggestion, if you are doing the &quot;same thing&quot; in different places, that should be a function.</p>\n<p>If you are doing the same thing in different ways -- for example, drawing a square versus drawing a line -- then you probably need to sit and think about how you could treat them the same way. Perhaps you need a data structure to tell you what the sizes are? Or maybe you could use a pointer and a single integer to tell you what was being pointed to? An <code>enum</code> type?</p>\n</li>\n<li><p>Cache the results of <code>kbhit()</code>. That function checks whether a key has been hit. Which means that each time you call it, you're doing another check. In a loop, it's probably easier to call it once at the top of the loop, remember the result, and wait until the next pass through the loop to call it another time.</p>\n</li>\n<li><p>Pick a <a href=\"https://en.wikipedia.org/wiki/Programming_style\" rel=\"nofollow noreferrer\">programming style</a> and stay with it until the end of the program! I see three <a href=\"https://en.wikipedia.org/wiki/Indentation_style\" rel=\"nofollow noreferrer\">indentation styles</a> in your program (all right next to each other!):</p>\n<pre><code>if (sposta==SU) // E se e' la freccia SU\n {\n griglia[r-1][c] = ' ';\n griglia[r][c-1] = linea_or[0][0];\n griglia[r][c] = linea_or[1][0];\n griglia[r][c+1] = linea_or[2][0];\n }\n</code></pre>\n<p>This is the &quot;GNU Style.&quot; Don't use it unless you personally owe Richard Stallman money.</p>\n<pre><code>if (sposta == DESTRA ) // E se e' la freccia DESTRA\n{\n</code></pre>\n<p>This is the &quot;Allman Style&quot;.</p>\n<pre><code> c++; // L'oggetto si sposta a destra\n system(&quot;cls&quot;);\n if (random == 0) {\n</code></pre>\n<p>This is the &quot;One True Brace Style&quot; or the &quot;K &amp; R Style&quot; depending on how you treat functions.</p>\n<pre><code> if (c+1&gt;COLONNA-1) { break; } // Se supera il bordo destro\n</code></pre>\n<p>This is the &quot;Mandatory Braces variant,&quot; a.k.a. the <a href=\"https://en.wikipedia.org/wiki/Aerial_advertising#Standard_letters\" rel=\"nofollow noreferrer\">&quot;Banner Plane&quot;</a> style.</p>\n<p>So just pick one of GNU, Allman, K&amp;R, or BannerPlane. <a href=\"https://youtu.be/nhB7_1uix0o\" rel=\"nofollow noreferrer\">My mistake, four styles.</a></p>\n</li>\n</ol>\n<ol start=\"14\">\n<li>Use named <code>#define</code>s or <code>enum</code> constants everywhere. You're off to a good start, but then you get bogged down with values like <code>'X'</code> and <code>20</code>. What's a 20?</li>\n</ol>\n<p>There's probably more to say, but that seems like enough for now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T13:05:34.903", "Id": "504365", "Score": "0", "body": "11] More functions is not always better. It creates so much more indirection." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T22:43:15.767", "Id": "255585", "ParentId": "255574", "Score": "5" } }, { "body": "<ul>\n<li><p><em>Always</em> write source code and comments in English (I'm not a native English speaker either). You will sooner or later need to share code with other people around the world, like you just did here and now. Therefore it needs to be in English.</p>\n<p>More importantly still, learning two technical programming terms for everything when you only need to learn one is madness. The worst mistake I did when studying engineering back at university was to read books translated to my own language, rather than English. This meant that I had to learn twice the amount of technical terms: the real, correct term in English, and the hogwash term questionably translated to my own language. The latter is completely useless knowledge - in the real world outside school, English terms are used.</p>\n</li>\n<li><p>As pointed out in another review, the <code>ritardo</code> busy-delay should have been replaced by Windows API <code>Sleep</code> in this case. In more advanced Windows programming with threads and events, you wouldn't use <code>Sleep</code> either but <code>WaitForSingleObject</code> etc. Multi-threading is a somewhat advanced topic, but one you'll eventually need to pick up. Then this program would use one thread for the graphics, one for input and maybe a third for calculations. Rather than using old MS DOS style <code>kbhit</code> - DOS didn't have threads.</p>\n</li>\n<li><p>If you <em>were</em> to implement a busy-delay loop, the loop iterator <code>i</code> would need to be declared <code>volatile</code>. Otherwise the compiler is just going to optimize away the whole loop.</p>\n</li>\n<li><p>Never use floating point numbers for loop iterators. It makes the code slower and the comparison expression might unexpectedly fail because of floating point inaccuracy.</p>\n</li>\n<li><p>Always try to declare the loop iterator inside the for loop: <code>for(int i=0; ...</code>.</p>\n</li>\n<li><p>You need to get rid of all global variables. Plenty of info about why they are bad to be found on the net.</p>\n</li>\n<li><p>Never use obsolete style empty parenthesis functions in C: <code>void caricaArray()</code>. This means that the function takes <em>any</em> parameter and this style might get removed from C at any point, since it is formally obsolete. Correct form is <code>void caricaArray(void)</code>.</p>\n<p>(Not to be confused with C++ where empty parenthesis is fine and equivalent to <code>(void)</code>.)</p>\n</li>\n<li><p>As noted in another review, you need to decide a coding style and stick with it. Brace placement, indention etc. As it stands, the code is barely readable.</p>\n</li>\n<li><p><code>srand();</code> should only be called once at the beginning of the program, you call it inside a loop.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T13:13:03.667", "Id": "504367", "Score": "0", "body": "It is true that reducing scope where a variable lives makes it easier to understand code, but some variables are global by nature. Having goal to get rid of **all** globals is nonsense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T13:30:45.507", "Id": "504368", "Score": "0", "body": "@user712092 As usual, it depends on what you mean with \"global\". Internal linkage file scope variables are fine. External linkage spaghetti across multiple files is not fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T17:49:28.490", "Id": "504385", "Score": "0", "body": "@user712092 I believe that, especially as a program grows large, the likelihood of a *variable* (rather than just a constant) being truly global vanishes. Drawing clear lines around what data is needed where is good for code quality, and the same goes for loosening coupling by programming to abstractions (like parameters rather than closed-over globals). Of course, you can always go too far and it's a situational question to answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T08:32:10.907", "Id": "255592", "ParentId": "255574", "Score": "6" } }, { "body": "<p>It looks like pretty good procedural code overall.</p>\n<h1>Scope</h1>\n<pre><code>int i, j; // CONTATORI\n</code></pre>\n<p>These indices can be local to functions. Globals are fine, but not in this case.</p>\n<p>Also <code>sposta</code> is probably always local to <code>movimenti()</code> function.</p>\n<h1>Magic numbers</h1>\n<pre><code>void stampaBordi() // STAMPA LA CORNICE DEL CAMPO DI GIOCO\n{\n for(i=1;i&lt;=19;i++)\n {\n GotoXY(i,22); putch('-');\n GotoXY(i,0); putch('-');\n\n</code></pre>\n<ul>\n<li>I don't know what these numbers mean (19, 22), and You probably won't few days/months/years later</li>\n<li>what's <code>i</code> is columnIndex or numberOfIterations, or something like else?</li>\n</ul>\n<h1>Using structures</h1>\n<pre><code>char griglia[21][10]; // DICHIARAZIONE ARRAY DI CHAR\n\n...\nvoid stampaBordi() // STAMPA LA CORNICE DEL CAMPO DI GIOCO\n{\n for(i=1;i&lt;=19;i++)\n {\n GotoXY(i,22); putch('-');\n GotoXY(i,0); putch('-');\n\n</code></pre>\n<p>These are all related to board. It is usually good idea to pull these variables together because it is easier to think about when related values are toghether (understanding / readability reason).</p>\n<pre><code>struct Grid {\n char cells[21][10];\n int rows;\n int columns;\n};\n\nGrid grid = {\n rows = 21;\n columns = 10;\n}\n...\nvoid stampaBordi(Grid * grid) // STAMPA LA CORNICE DEL CAMPO DI GIOCO\n{\n for(int i=1;i&lt;= grid-&gt;rows - 2;i++)\n {\n GotoXY(i, grid-&gt;rows + 1 ); putch('-');\n GotoXY(i, 0 ); putch('-');\n\n</code></pre>\n<p>I am pretty sure that some of these constants should also be members of Grid structure :) ...</p>\n<pre><code>#define RIGA 21\n#define COLONNA 10\n#define DESTRA 77\n#define SINISTRA 75\n#define GIU 80\n#define SU 72\n\n</code></pre>\n<h1>Compressing code</h1>\n<p>Also in this case ...</p>\n<pre><code>if (sposta == DESTRA ) // E se e' la freccia DESTRA\n {\n c++; // L'oggetto si sposta a destra\n system(&quot;cls&quot;);\n if (random == 0) {\n if (c+1&gt;COLONNA-1) { break; } // Se supera il bordo destro\n griglia[r][c-1] = ' '; // Libera le posizioni precedenti\n griglia[r+1][c-1] = ' ';\n }\n else if (random == 1) {\n griglia[r-2][c-1] = ' '; // Libera le posizioni precedenti\n griglia[r-1][c-1] = ' ';\n griglia[r][c-1] = ' ';\n griglia[r+1][c-1] = ' ';\n griglia[r+2][c-1] = ' ';\n }\n visualizzaArray(); //visualizza il tutto\n }\n</code></pre>\n<p>Pull out related information into structures to make it easier make new stuff and read.</p>\n<pre><code>\n// code like this repeats on multiple places\n// and it seems like You are working with an array of offsets\n// and You are doing single operation to them\n\n griglia[r-2][c-1] = ' '; // Libera le posizioni precedenti\n griglia[r-1][c-1] = ' ';\n griglia[r][c-1] = ' ';\n griglia[r+1][c-1] = ' ';\n griglia[r+2][c-1] = ' ';\n\n// this can be compressed like this\n\nstruct Offset { int x; int y; }\n\nOffset offsets = [{-2,-1},{-1,-1},{0,-1},{1,-1},{2,-1}];\nint offsetCount = 5;\n\nfor(auto i = 0; i &lt; offsetCount; i++) {\n auto offset = offsets[i];\n griglia[r + offset.x][c + offset.y] = ' ';\n}\n\n// and it can be pulled into function\n\nclearOffsets( Offsets * offsets, int offsetCount )\n\n// Also these offsets seem to be always asociated with a tetromino\n// each tetromino has it's own offsets, so\n\nstruct Offset { int x; int y; }\n\nstruct Tetromino { Offset cellOffsets[]; int offsetCount; ... }\n\nTetromino l_shape = { cellOffsets = [{-2,-1},{-1,-1},{0,-1},{1,-1},{2,-1}], 5}\n\n\n// now You can make functions like this\n\nclearTetromino(l_shape);\nrotateTetrominoLeft(l_shape);\n\n// also You can reuse function to rotate another shape or shapes ...\n\nrotateTetrominoLeft(box_shape); \nrotateTetrominoRight(shapes[shapeIndex]);\n\n</code></pre>\n<p>For more on code compression see excellent <a href=\"https://caseymuratori.com/blog_0015\" rel=\"nofollow noreferrer\">https://caseymuratori.com/blog_0015</a> .</p>\n<h1>Formatting</h1>\n<pre><code> else if (random == 1) {\n if (r+2==20) { // Se tocca il borso inferiore crea un altro oggetto\n</code></pre>\n<p>This is hard for me to quickly scan, because I am used to K&amp;R brace style and Allman brace style (most people use them).</p>\n<h1>Comments</h1>\n<p>English would be nice in comments :)</p>\n<p>I have this heuristic: I avoid comments that explain what a variable or function means, I make better (longer, more descriptive) name for functions/variables instead. I comment stuff which is non-obvious ...</p>\n<p>This one is ok</p>\n<pre><code> if (r+2==20) { // Se tocca il borso inferiore crea un altro oggetto\n</code></pre>\n<p>but, again, maybe removing comment by introducing variable can clear things up (and You can re-use variable at multiple places)</p>\n<pre><code>auto touchesLongerEdge = r + 2 === 20;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T12:59:16.563", "Id": "255599", "ParentId": "255574", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:43:32.203", "Id": "255574", "Score": "5", "Tags": [ "c", "game", "windows", "tetris" ], "Title": "Simple Tetris game" }
255574
<p>I am new to python.</p> <p>Got a question in Hackerrank.</p> <p>Given an Array of bad numbers and a range of integers, how can I determine the longest segment of integers within that inclusive range that doesn't contain a bad number?</p> <p>For example, you are given the lower limit <code>l = 3</code> and the upper limit <code>r = 48</code>, The array <code>badNumbers = [37,7,22,15,49,60]</code>. Segments without bad numbers are <code>[3,6]</code>, <code>[8,14]</code>, <code>[16,21]</code>, <code>[23,36]</code> and <code>[38,48]</code>. The longest segment is <code>[23,36]</code> and it is 14 elements long.</p> <p>Problem : Function Description Complete the function <code>goodStatement</code> in the editor below. The function must return an integer denoting the length of the longest contiguous range of natural number in the range l to r, inclusive, which does not include any bad numbers.</p> <p><code>goodSegment</code> has the following parameter(s): <code>badNumbers[badNumbers[0],...badNumbers[n-1]]</code>: an array of integers l: an integer, the lower bound, inclusive r: an integer, the upper bound, inclusive</p> <p>Constraints <span class="math-container">\$1 \le n \le 10^5\$</span>, <span class="math-container">\$1 \le badNumbers[i] \le 10^9\$</span>, badNumbers contains distinct elements</p> <pre class="lang-py prettyprint-override"><code>def goodSegment(badNumbers, l, r): ranges = [] subrange = [] large=0 for i in range(l,r+1): if badNumbers.count(i)==0: if len(subrange)==0: subrange.append(i) else: if i==r: subrange.append(i) ranges.append(subrange) if len(range(subrange[0],subrange[1]+1))&gt;large: large=len(range(subrange[0],subrange[1]+1)) else: if len(subrange)==1: subrange.append(i-1) ranges.append(subrange) if len(range(subrange[0],subrange[1]+1))&gt;large: large=len(range(subrange[0],subrange[1]+1)) subrange=[] else: subrange=[] return large badNumbers=[5,4,2,15] l=1 r=10 result = goodSegment(badNumbers, l, r) print(result) </code></pre> <p><strong>The code is working fine. But this is not getting executed in 10 seconds as per the hackerrank test cases. How can I optimize this for a faster execution?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T18:38:31.050", "Id": "504300", "Score": "2", "body": "The code does `ranges.append(subrange)` , but never uses `ranges`. That's a lot of extra work if `n` is large." } ]
[ { "body": "<p>It’s <span class=\"math-container\">\\$ O(n * m) \\$</span> because of <code>badNumbers.count(i)</code>, n and m being the lengths of badNumbers and the range from left to right. You could reduce this to <span class=\"math-container\">\\$ O(n + m) \\$</span> if you cast badNumbers to a set and check if <code>i</code> is in the set.</p>\n<p>You’re doing a lot of unnecessary things in the function. You only need to keep track of the current amount and the largest amount of numbers you’ve seen in a row which weren’t in badNumbers. You don’t need to use any lists.</p>\n<p>Btw, in a couple places you could make your current code flatter by using <code>elif</code> instead of using else and nested if/else blocks. Specifically <code>if i==r:</code> and <code>if len(subrange)==1:</code>. Those could be changed to <code>elif</code>, and then the bottom <code>else</code> block could be unindented.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T03:35:12.773", "Id": "504340", "Score": "2", "body": "Note: To get \\$O(n + m)\\$ you must assume set creation is an \\$O(n)\\$ operation and that `in` is always an \\$O(1)\\$ operation. The former isn't documented and the latter is the 'average case' where [the worst case is \\$O(n)\\$](https://wiki.python.org/moin/TimeComplexity). I have had sets explode to what seems like \\$O(n^2)\\$ before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T11:49:54.030", "Id": "504355", "Score": "0", "body": "@Peilonrayz Can you show us such an explosion case you had?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T12:37:33.113", "Id": "504362", "Score": "0", "body": "@KellyBundy Unfortunately I don't remember which project I had that exploded like this. Since I changed from sets to a 'worse' algorithm (\\$O(n\\log n)\\$) I probably wouldn't be able to find it now. :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T13:05:34.637", "Id": "504364", "Score": "0", "body": "@Peilonrayz Do you know of any other? And sounds like it wasn't intentional, which is rather hard to believe then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T13:53:28.787", "Id": "504369", "Score": "0", "body": "@KellyBundy Sure you're entitled to think I'm a liar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T14:30:09.580", "Id": "504375", "Score": "0", "body": "@Peilonrayz Um, so everybody being mistaken is a liar now?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T19:33:47.303", "Id": "255580", "ParentId": "255575", "Score": "4" } }, { "body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> lists many recommendations:</p>\n<ul>\n<li>variables &amp; functions should be <code>snake_case</code></li>\n<li>commas should be followed by a space</li>\n<li>binary operators should be surrounded by a space (eg, <code>l == r</code> instead of <code>l==r</code>, and <code>r + 1</code> instead of <code>r+1</code>)</li>\n</ul>\n<p>Some of the function/variable names may be dictated to you by the coding challenge, but for all others you should follow the PEP 8 conventions.</p>\n<h1>Optimizations</h1>\n<h2>Loop range</h2>\n<p><code>for i in range(l, r + 1):</code></p>\n<p>Assuming your range is 1 to <span class=\"math-container\">\\$10^9\\$</span>, this loop will take more than 10 seconds if the code inside the loop takes more than 10 nanoseconds per iteration. That's asking a lot for an interpreted language. You would do better if that loop can be removed.</p>\n<p>More on this in a moment.</p>\n<h2>Counting -vs- existence</h2>\n<p><code>if badNumbers.count(i)==0:</code></p>\n<p>You are searching the list of bad numbers counting the number occurrences of the value <code>i</code> in the list.</p>\n<blockquote>\n<p>badNumbers contains distinct elements</p>\n</blockquote>\n<p>Because <code>badNumbers</code> contains unique elements, the count will be either 0 or 1. More over, as soon as we find the first match, we can stop counting even if uniqueness was guarenteed, since we are testing the count against zero. What you really want is simply to ask if the value <code>i</code> is in <code>badNumbers</code>. You write that exactly how we said it:</p>\n<p><code>if i in badNumbers:</code></p>\n<p>This is still an <span class=\"math-container\">\\$O(n)\\$</span> operation, but would be faster. As mentioned in another answer, turning <code>badNumbers</code> into a set would speed that up into an <span class=\"math-container\">\\$O(1)\\$</span> operation. But let's investigate another option.</p>\n<h2>Reducing data</h2>\n<p>Your example <code>badNumbers = [37, 7, 22, 15, 49, 60]</code> with limits <code>l=3</code> and <code>r=48</code> reveals more inefficiency. The <code>badNumbers</code> contains numbers outside of the limits. Looking at those numbers over and over again (such as in <code>badNumbers.count(i) == 0</code> or <code>i in badNumbers</code>) is wasted time.</p>\n<p>We can filter out the &quot;bad&quot; bad numbers which end up just wasting time.</p>\n<p><code>badNumbers = [number for number in badNumbers if l &lt;= number &lt;= r]</code></p>\n<h2>Organizing your data</h2>\n<p>You are looping over your candidate numbers, and then effectively searching to see if the candidate number is in the bad numbers list. If that list was sorted, you could just maintain an index to the next unmatched bad number, and increment it each time a match was found.</p>\n<p>Combining that with the previous step:</p>\n<p><code>badNumbers = sorted(x for x in badNumbers if l &lt;= x &lt;= r)</code></p>\n<p>Now in your example, the <code>badNumbers</code> would be <code>[7, 15, 22, 37]</code></p>\n<p>Now, <code>it = iter(badNumbers)</code> would create an iterator which could walk over the list, in order, <code>bad_number = next(it)</code> could extract the next bad number from the list, and we've gotten rid of that pesky index I mentioned above, too.</p>\n<p>But I'd really like to get rid of that first loop, so lets take a different approach.</p>\n<h2>Gap Length and End Posts</h2>\n<p><code>[7, 15, 22, 37]</code></p>\n<p>In this array, we can immediately see there are <code>15-7-1</code> good numbers between the first two bad numbers, <code>22-15-1</code> between the next pair, and <code>37-22-1</code> between the last pair. This is almost all we need to get the longest run of good numbers!</p>\n<p>What is missing is the good number runs at the beginning and end of the list. We can fix that by adding some &quot;end posts&quot;, extra bad numbers one beyond the good range end points:</p>\n<p><code>badNumbers = [l - 1] + sorted(x for x in badNumbers if l &lt;= x &lt;= r) + [r + 1]</code></p>\n<p>With limits of <code>l=3</code> and <code>r=48</code>, this creates <code>badNumbers = [2, 7, 15, 22, 37, 49]</code>.</p>\n<p>Now, every pair of numbers can be used to determine the length of a run of good numbers.</p>\n<h2>pairwise</h2>\n<p>Since we want to take the numbers in pairs, it makes sense to consult the Python <code>itertools</code> library for an appropriate function. It isn't built-in, but the <a href=\"https://docs.python.org/3/library/itertools.html?highlight=pairwise#itertools-recipes\" rel=\"noreferrer\"><code>pairwise</code></a> recipe can be installed from <code>more-itertools</code>.</p>\n<p>Take the numbers as pairs, computing the number of good values between the pair of bad values, and remember the maximum value. The &quot;minus 1&quot; from the internal calculation can be delayed till the end, for efficiency, since <span class=\"math-container\">\\$\\max{(x_i-1)} == \\max{(x_i)} - 1\\$</span></p>\n<pre class=\"lang-py prettyprint-override\"><code>from more_itertools import pairwise\n\ndef goodSegment(bad_numbers, l, r):\n bad_numbers = [l - 1] + sorted(x for x in bad_numbers if l &lt;= x &lt;= r) + [r + 1]\n gap_lengths = (b - a for a, b in pairwise(bad_numbers))\n return max(gap_lengths) - 1\n\nbadNumbers = [5, 4, 2, 15]\nl = 1\nr = 10\n \nresult = goodSegment(badNumbers, l, r)\nprint(result)\n</code></pre>\n<p>If <code>more-itertools</code> is not available, you can make something almost equivalent</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pairwise(numbers):\n return zip(numbers[:-1], numbers[1:])\n</code></pre>\n<p>It may even be faster, although it will use up to three times more memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T01:20:19.670", "Id": "504323", "Score": "1", "body": "Isn’t it possible for this to be slower depending on the size of bad_numbers and the range being checked? I started thinking of something like this but assumed it could be slower since the sorting is \\$ O(n * log(n)) \\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T03:40:00.977", "Id": "504341", "Score": "2", "body": "@my_first_c_program I'm certain there are m,n ranges where this may be slower, since sorting is \\$O(n \\log n)\\$, but with with n ranging up to 10^5, the log n factor is only 16, where as with m ranging to 10^9, or n*10^4, then m+n becomes 10001*n. There are other constant factors to consider, of course, but a back of the envelope comparison give a factor of 600 advantage to the sorting, with both m & n at there limits. Of course, profiling actual implementations is really required." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T00:44:35.907", "Id": "255587", "ParentId": "255575", "Score": "7" } } ]
{ "AcceptedAnswerId": "255587", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T17:47:19.690", "Id": "255575", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x", "time-limit-exceeded" ], "Title": "Determine the longest segment of integers within an inclusive range that doesn't contain a bad number using Python" }
255575
<p>I recently started out with C++ and I am working on an application that can watermark entire directories of images at once.</p> <p>Currently you can call the program with an argument of the target directory where the images are stored and an argument for the path of which watermark image to use.</p> <p>It works so far but I think my code is a bit messy. I don't really know how to make it more readable and more clean, so I am asking for your help.</p> <p>I would really appreciate it if people could look at my code and review it. All feedback is welcome.</p> <p>A link to my GitHub repository: <a href="https://github.com/JelleVos1/watermarker" rel="nofollow noreferrer">github repo</a></p> <p>Main.CPP:</p> <pre><code>#include &lt;iostream&gt; #include &quot;FileSystem.h&quot; #include &quot;Watermarker.h&quot; int main(int arc, const char** argv) { // Get the given argument for the target directory std::string targetDirectory = argv[1]; // Get the given argument for the watermark file std::string watermarkPath = argv[2]; FileSystem fileSystem; // Check if the target directory is valid if (!fileSystem.checkDirectory(targetDirectory)) { return 1; } // Create an output directory where the new watermarked images will be stored std::string path = targetDirectory + &quot;\\watermarked_images&quot;; fileSystem.createDirectory(path); Watermarker marker; // Mark all the images in the target directory with the watermarkPath image marker.mark(targetDirectory, watermarkPath); } </code></pre> <p>FileSystem.h</p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; #include &lt;boost/filesystem.hpp&gt; class FileSystem { private: std::vector&lt;std::string&gt; validExtensions = { &quot;.png&quot;, &quot;.jpg&quot;, &quot;.tiff&quot;, &quot;.jpeg&quot; }; public: void createDirectory(std::string&amp; directory); bool checkDirectory(std::string&amp; directory); bool checkFile(boost::filesystem::path&amp; filePath); }; </code></pre> <p>FileSystem.CPP</p> <pre><code>#include &quot;FileSystem.h&quot; #include &lt;iostream&gt; #include &lt;boost/algorithm/string.hpp&gt; void FileSystem::createDirectory(std::string&amp; directory) { boost::filesystem::create_directory(directory); } bool FileSystem::checkDirectory(std::string&amp; directory) { if (boost::filesystem::exists(directory)) { if (!boost::filesystem::is_directory(directory)) { std::cout &lt;&lt; &quot;The given path is not a directory.\n&quot;; return false; } } else { std::cout &lt;&lt; directory &lt;&lt; &quot; does not exist\n&quot;; return false; } return true; } bool FileSystem::checkFile(boost::filesystem::path&amp; filePath) { // Check if the file is a regular file if (!boost::filesystem::is_regular_file(filePath)) { return false; } // Get the file extension in lower case std::string fileExtension = filePath.extension().string(); boost::to_lower(fileExtension); // Check if the file extension matches one of the valid ones if (std::find(validExtensions.begin(), validExtensions.end(), fileExtension) != validExtensions.end()) { return true; } else { return false; } } </code></pre> <p>Watermarker.h</p> <pre><code>#pragma once #include &lt;iostream&gt; class Watermarker { public: void mark(std::string&amp; targetDirectory, std::string&amp; watermarkPath); }; </code></pre> <p>Watermarker.cpp</p> <pre><code>#include &quot;Watermarker.h&quot; #include &quot;FileSystem.h&quot; #include &lt;boost/filesystem.hpp&gt; #include &lt;opencv2/core.hpp&gt; #include &lt;opencv2/highgui.hpp&gt; #include &lt;opencv2/imgproc.hpp&gt; void Watermarker::mark(std::string&amp; targetDirectory, std::string&amp; watermarkPath) { boost::filesystem::path path; // Loop through all the files in the target directory for (auto&amp; entry : boost::filesystem::directory_iterator(targetDirectory)) { // Set the boost filesystem path to the path of the file path = entry.path(); FileSystem fileSystem; // If the file is not valid, skip it if (!fileSystem.checkFile(path)) { continue; } // Get the original and watermark image cv::Mat image = cv::imread(path.string()); cv::Mat watermarkImage = cv::imread(watermarkPath, cv::IMREAD_UNCHANGED); // Make the watermark image the same size as the original image cv::resize(watermarkImage, watermarkImage, image.size(), 0, 0, cv::InterpolationFlags::INTER_LINEAR); // Give the images 4 channels cv::cvtColor(image, image, cv::COLOR_RGB2RGBA); cv::cvtColor(watermarkImage, watermarkImage, cv::COLOR_RGB2RGBA); cv::Mat newImage; // Add the watermark to the original image cv::addWeighted(watermarkImage, 0.3, image, 1, 0.0, newImage); // Save the new image to the new watermarked_images folder cv::imwrite(std::string(targetDirectory + &quot;\\watermarked_images\\&quot; + path.filename().string()).c_str(), newImage); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T07:35:58.233", "Id": "504348", "Score": "0", "body": "Sorry for the extra edits - I misread who added the code to the question. It's ready for review!" } ]
[ { "body": "<p><code>#pragma once</code> is not standard C++ - use conventional <code>#ifndef</code>/<code>#define</code> include guards until/unless that gets standardised (by that time, Modules will be a better approach, anyway).</p>\n<p>This looks strange:</p>\n<blockquote>\n<pre><code>#include &lt;iostream&gt;\n\nclass Watermarker\n{\npublic:\n void mark(std::string&amp; targetDirectory, std::string&amp; watermarkPath);\n};\n</code></pre>\n</blockquote>\n<p>Why include <code>&lt;iostream&gt;</code>? We don't use anything from there. More importantly, we're missing an include of <code>&lt;string&gt;</code>.</p>\n<p>Why is <code>mark()</code> a non-static member function? It doesn't require any object state, nor even any class state. It can be a free function.</p>\n<p>Why do we pass mutable references to the paths? I don't think there's a good reason the caller would want either of those strings to be modified, so just take a copy (or use a const reference if the implementation won't modify the values).</p>\n<blockquote>\n<pre><code>class FileSystem\n</code></pre>\n</blockquote>\n<p>That's a confusing name, given that we use <code>boost::filesystem</code> in the same code.</p>\n<blockquote>\n<pre><code>int main(int arc, const char** argv)\n{\n // Get the given argument for the target directory\n std::string targetDirectory = argv[1];\n\n // Get the given argument for the watermark file\n std::string watermarkPath = argv[2];\n</code></pre>\n</blockquote>\n<p>Conventionally, we call the first argument <code>argc</code>, not <code>arc</code>. More important is that we cannot access <code>argv[1]</code> and <code>argv[2]</code> unless we know <code>argc</code> is at least 3. And if it's not exactly 3, we should be informing the user (via <code>std::cerr</code>) that the usage is incorrect, and exiting with a non-zero status (e.g. <code>EXIT_FAILURE</code>, from <code>&lt;cstdlib&gt;</code>).</p>\n<blockquote>\n<pre><code> if (!fileSystem.checkFile(path)) { continue; }\n\n // Get the original and watermark image\n cv::Mat image = cv::imread(path.string());\n</code></pre>\n</blockquote>\n<p>There's a gap between the check and the read where anything could happen in a multi-process environment. And given that we never checked whether we had permission to read the file, <code>cv::imread()</code> could fail even if nothing changed in that time. Read <a href=\"https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56\" rel=\"nofollow noreferrer\" title=\"cv::imread\">the fine manual</a>:</p>\n<blockquote>\n<p>If the image cannot be read (because of missing file, improper\npermissions, unsupported or invalid format), the function returns an\nempty matrix (<code>Mat::data==NULL</code>).</p>\n</blockquote>\n<p>It's probably better to just remove <code>FileSystem::checkFile()</code> and rely on OpenCV to report whether each file is readable.</p>\n<blockquote>\n<pre><code> cv::imwrite(std::string(targetDirectory + &quot;\\\\watermarked_images\\\\&quot; + path.filename().string()).c_str(), newImage);\n</code></pre>\n</blockquote>\n<p>Here's another place where we forgot to check whether the operation succeeded. (In fairness, the example in <a href=\"https://docs.opencv.org/3.4/d4/da8/group__imgcodecs.html#gabbc7ef1aa2edfaa87772f1202d67e0ce\" rel=\"nofollow noreferrer\" title=\"cv::imwrite\">the manual</a> also makes this mistake). It's poor practice to continue silently when we didn't achieve what the user asked for.</p>\n<p>Also here, we have a string fragment <code>&quot;\\\\watermarked_images\\\\&quot;</code> that has to agree with that in the calling code. Firstly, it looks like <code>\\</code> is being assumed to be a path separator, which is needlessly non-portable (especially given that we're using <code>boost::filesystem</code>). Secondly, the destination path ought to be passed in (and would be better if it could be specified as a program option).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T08:00:09.843", "Id": "255591", "ParentId": "255578", "Score": "2" } }, { "body": "<p><strong><code>#pragma once</code></strong>:</p>\n<p>If you're making a library that needs to work for any compiler on any platform, you need proper include guards. For something like this <code>#pragma once</code> is the way to go. (It's easier and less error prone, and supported by all the major modern compilers).</p>\n<p>[Other than this I mainly agree with Toby Speight's answer <code>;)</code>.]</p>\n<hr />\n<p><strong><code>#include</code> order</strong>:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &quot;FileSystem.h&quot;\n#include &quot;Watermarker.h&quot;\n</code></pre>\n<p>Conventional include ordering is to put local includes at the top, third party library includes next, and standard library includes last:</p>\n<pre><code>#include &quot;FileSystem.h&quot;\n#include &quot;Watermarker.h&quot;\n\n#include &lt;boost/filesystem.hpp&gt; // added for illustration\n\n#include &lt;iostream&gt;\n</code></pre>\n<p>Our local headers should <code>#include</code> everything they use themselves. With this ordering we'll get a compiler error if we've forgotten to <code>#include</code> something in the local header.</p>\n<p>e.g. if <code>FileSystem.h</code> depends on <code>&lt;iostream&gt;</code>, but forgets to include it, we want to <em>always</em> get a compiler error when we try to use <code>FileSystem.h</code> in a <code>.cpp</code> file (so we can fix the issue). If we include <code>&lt;iostream&gt;</code> first in the <code>.cpp</code> file, we won't get a compiler error here, but might do at some arbitrary time in the future when we don't happen to include <code>&lt;iostream&gt;</code> too.</p>\n<hr />\n<p><strong><code>class Filesystem</code></strong>:</p>\n<p><code>std::vector&lt;std::string&gt; validExtensions</code> should be <code>static</code>, since it isn't specific to a class instance. In fact, this class has no instance state (member variables), so it doesn't need to be a <code>class</code>. We could perhaps make it a <code>namespace</code> instead.</p>\n<p>I'd probably just put all the code for this application in one namespace though, rather than having a separate namespace for a few utilities.</p>\n<p>Arguably, we could inline the contents of these functions into the functions that call them without losing much readability.</p>\n<hr />\n<p><strong><code>class Watermarker</code></strong>:</p>\n<p>Again, this class has no members, so it doesn't need to be a <code>class</code>.</p>\n<p>While it's true that there's no point checking if a file exists, or is readable before we actually try to open the file, we should still check that our iterator points to a file, not a directory, and that it has one of the extensions we care about.</p>\n<p>[Another slight disagreement with Toby Speight's answer.]</p>\n<p>So <code>checkFile()</code> is necessary. But I do think that it but should be split into two parts, e.g.: <code>isFile(path)</code> and <code>hasExtension(path, validExtensions);</code>.</p>\n<p>I think we could split the <code>mark</code> function into two parts. One function (<code>processDir()</code>) to deal with iterating the directory (we could just inline the file and extension check here). A second function <code>addWatermark()</code> to do the actual watermarking with OpenCV.</p>\n<hr />\n<p><strong>possible performance improvement</strong>:</p>\n<p>We read the same watermark image file over and over again.</p>\n<p>We can read the image and convert to RGBA just once. Then we can copy and resize it each time, which is probably faster than reading from disk.</p>\n<hr />\n<p><strong>project structure</strong>:</p>\n<p>While separating parts of a project into different files is generally a very good thing, it can actually make things less readable for a very small application like this!</p>\n<p><code>validExtensions</code>, for example, is application specific, and quite important, but hard to find in a separate file. Meanwhile <code>Watermarker.cpp</code> also depends on <code>FileSystem.h</code> (and those valid extensions), which makes it less readable (because we have to jump around the codebase to understand it) and less reusable.</p>\n<p>Perhaps, in this case, it would be better to put everything in main.cpp, something like this:</p>\n<pre><code>#include &lt;boost/algorithm/string.hpp&gt;\n#include &lt;boost/filesystem.hpp&gt;\n\n#include &lt;opencv2/core.hpp&gt;\n#include &lt;opencv2/highgui.hpp&gt;\n#include &lt;opencv2/imgproc.hpp&gt;\n\n#include &lt;algorithm&gt;\n#include &lt;cstdlib&gt;\n#include &lt;initializer_list&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nnamespace fs = boost::filesystem;\n\nnamespace wtr\n{\n\n void addWatermark(std::string const&amp; targetFile, std::string const&amp; outputFile, std::string const&amp; watermarkFile)\n {\n cv::Mat original = cv::imread(targetFile); // todo: handle failure!\n cv::cvtColor(original, original, cv::COLOR_RGB2RGBA);\n\n cv::Mat watermark = cv::imread(watermarkFile, cv::IMREAD_UNCHANGED); // todo: handle failure!\n cv::resize(watermark, watermark, image.size(), 0, 0, cv::InterpolationFlags::INTER_LINEAR);\n cv::cvtColor(watermark, watermark, cv::COLOR_RGB2RGBA);\n\n cv::Mat composite;\n cv::addWeighted(watermark, 0.3, original, 1, 0.0, composite); // todo: make 0.3 a function argument!\n\n cv::imwrite(outputFile, composite); // todo: handle failure!\n }\n\n template&lt;class It, class T&gt;\n bool contains(It begin, It end, T const&amp; value)\n {\n return std::find(begin, end, value) != end;\n }\n\n void processDir(std::string const&amp; targetDir, std::string const&amp; outputDir, std::string const&amp; watermarkFile)\n {\n for (auto&amp; entry : boost::filesystem::directory_iterator(targetDir))\n {\n fs::path path = entry.path();\n\n if (!fs::is_regular_file(path))\n continue;\n\n auto validExtensions = { &quot;.png&quot;, &quot;.jpg&quot;, &quot;.jpeg&quot;, &quot;.tiff&quot; };\n if (!contains(validExtensions.begin(), validExtensions.end(), boost::to_lower_copy(path.extension().string())))\n continue;\n \n addWatermark(path.string(), outputDir + path.filename().string(), watermarkFile);\n }\n }\n\n} // wtr\n\nint main(int argc, const char** argv)\n{\n // todo: check argc is correct!!!\n std::string targetDir = argv[1];\n std::string watermarkFile = argv[2];\n\n if (!fs::is_directory(targetDir)) // note: only one check needed - if the file doesn't exist, it won't be a directory!\n {\n std::cout &lt;&lt; &quot;The given path is not a directory.\\n&quot;;\n return EXIT_FAILURE;\n }\n\n std::string outputDir = targetDir + &quot;\\\\watermarked_images&quot;;\n fs::create_directory(outputDir);\n // todo: handle failure!!!\n\n wtr::processDir(targetDir, outputDir, watermarkFile); // note: pass in output directory path instead of recalculating it inside the function.\n}\n</code></pre>\n<p>[note: not tested]</p>\n<p>If our code-base grows, or we want to reuse the functions or move them to a library, it's easy to separate parts out. For example, now <code>addWatermark</code> only depends on the standard library and OpenCV (so it could be grouped with other OpenCV utility functions), and <code>contains</code> could similarly be moved to a separate file.</p>\n<p>But... until then, <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>.</p>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T13:10:52.977", "Id": "504366", "Score": "1", "body": "I do disagree about using the filename as indicator of whether something is an image - OpenCV is a lot more reliable at detecting that! But I guess it's really for the asker to decide what's wanted - all files matching that pattern, or all files containing raster images? (I went with the description, and you with the code)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T12:40:06.833", "Id": "255598", "ParentId": "255578", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T18:56:20.697", "Id": "255578", "Score": "3", "Tags": [ "c++", "performance", "file-system" ], "Title": "Simplifying small watermark application" }
255578
<p>I am working on an open Chess data-set (~15500 rows after cleaning), and I create nodes and edges. But the way I create the edges takes a bit of time.</p> <p>A sample of my nodes tibble:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>player</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>bougris</td> </tr> <tr> <td>2</td> <td>a-00</td> </tr> <tr> <td>3</td> <td>ischia</td> </tr> <tr> <td>...</td> <td>...</td> </tr> </tbody> </table> </div> <p>A sample picture of the <code>per_game</code> tibble:</p> <p><a href="https://i.stack.imgur.com/XIGzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XIGzu.png" alt="Part of the tibble" /></a></p> <p>The way I do it:</p> <ol> <li>I iterate for each node/player in <code>nodes</code> tibble,</li> <li>searching the games where he played as black in <code>per_game</code>,</li> <li>and exchanging values of column <code>white_d</code> with <code>black_id</code>, while changing the winner in <code>winner</code> column (using the <code>swap()</code> method I created).</li> <li>Then, with <code>calc_victories()</code> method, I group all games for the specific player, with every opponent he has faced, and calculating how many times he won, or lost, from the opponent (I store it to <code>player_result</code>). An example picture: <a href="https://i.stack.imgur.com/FklyH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FklyH.png" alt="enter image description here" /></a></li> <li>Then I append the <code>player_result</code> to a tibble, with all previous players' results.</li> <li>Finally, I delete from the <code>per_game</code> tibble the node I just handled, both from black and white columns.</li> </ol> <p>Here is my code:</p> <pre><code>for(i in 1:dim(nodes)){ # Exchange values of white with black column, only where black_id is the specific player per_game[per_game$black_id == nodes[[1]][i], c('white_id', 'black_id', 'winner')] &lt;- per_game[per_game$black_id == nodes[[1]][i], c('black_id', 'white_id', swap('winner'))] # Calculate the victories, for each opponent of the specific player player_results &lt;- calc_victories(nodes[[1]][i]) # Append the player's matches with the rest. all_results &lt;- rbind(all_results, player_results) # Delete all matches with the specific player, either if he/she is black or white per_game &lt;- subset(per_game, white_id != nodes[[1]][i] &amp; black_id != nodes[[1]][i]) } all_results </code></pre> <p>Here are the functions <strong>calc_victories()</strong> and <strong>swap()</strong>:</p> <pre><code># A method to group the matches for a player, and sum his victories against each opponent calc_victories &lt;- function(i='-') { player_results &lt;- per_game %&gt;% filter(white_id==i | black_id==i) %&gt;% # Finds matches with the specific player group_by(white_id, black_id) %&gt;% rename(player1=white_id, player2=black_id) %&gt;% summarise_at(vars(total_matches), list(victories = sum)) %&gt;% # Summarize total matches arrange(desc(victories)) %&gt;% # Sorts descending ungroup() return (player_results) } # A method to change the winner, because of white-black column exchange swap &lt;- function(winner='draw') { if(winner=='black'){ gets = 'white' } else if(winner=='white'){ gets = 'black' } else { return (winner) } return(gets) } </code></pre> <p>The code executes for about 5 minutes, to handle all nodes. I think that this is happening, mainly because I iterate for each node. Maybe I should use something like map, but I am not so sure. Thank you.</p>
[]
[ { "body": "<h2>General tips</h2>\n<ol>\n<li>Avoid defining your own loops. This is especially true with R because the chances are that there is another more elegant way to solve the problem using highly optimized functions.</li>\n<li>Avoid <code>rbind</code> function inside loops especially if your are using it as an appending mechanism. This function creates a new empty data frame with a number of rows equal to number or rows of the <code>old</code> plus the number or rows of the <code>new</code>. Then it will copy the old and the new into this newly created data frame. This operation can be really expensive if you have large dataset. An optimizing solution can be achieved by creating an empty data frame with right size once outside the loop and populate it with the results using <code>i</code> index e.g <code>all_results[i] = new_results</code> inside the loop.</li>\n<li>Avoid <code>subset</code> inside loops. The function documentation states that this is only a convienet function and should only be used in interactive setting.It also recommends that you use <code>[</code> for subsetting.</li>\n</ol>\n<blockquote>\n<h2><a href=\"https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/subset\" rel=\"nofollow noreferrer\">Warning</a></h2>\n<p>This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.</p>\n</blockquote>\n<p>Moreover, it has the same issue as in the tip #2 since you are writing a new data frame minus the processed row in every go inside the loop.</p>\n<h2>Alternative solution</h2>\n<p>The problem can be solved using much less code than provided. Also it will only involves where the real data is the <code>per_game</code> table.</p>\n<p>First you need to breakdown winner column in 3 for each winner. Since you seem familiar with the <code>tidyverse</code> family packages I will use functions from these packages.</p>\n<pre><code>library(&quot;tidyr&quot;)\nlibrary(&quot;dplyr&quot;)\n\nper_game %&gt;% \n# Here we breakdown the winner columns into 3 using `spread()` function from tidyr\nspread(winner, total_matches) %&gt;% \n# Then we add the black and white columns into new column called `victories`\nrowwise() %&gt;% # to ensure summation excute on per row. \nmutate(victories = sum(black, white,na.rm = TRUE))\n\n# the results should look like this \n\n# Rowwise: \n white_id black_id black draw white victories\n &lt;chr&gt; &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;\n 1 --jim-- &quot;voodooo&quot; 1 NA NA 1\n 2 -1-jedi_knighl_-1- &quot;erik123678&quot; NA NA 1 1\n 3 -1-jedi_knighl_-1- &quot;kaY\\\\ran0098&quot; 2 NA 2 4\n 4 -1-jedi_knighl_-1- &quot;pav1ngt&quot; 1 NA NA 1\n 5 -mati- &quot;astronavtearl101&quot; NA NA 1 1\n 6 -pavel- &quot;hishamtheman&quot; NA NA 1 1\n 7 1063314 &quot;dccbc,ss&quot; NA NA 1 1\n 8 1111112222 &quot;crusova_ 33&quot; 1 NA NA 1\n 9 1111112222 &quot;steelviper&quot; 1 NA NA 1\n10 1240100948 &quot;aa22bb&quot; 1 NA NA 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-17T22:54:20.297", "Id": "259675", "ParentId": "255584", "Score": "3" } } ]
{ "AcceptedAnswerId": "259675", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T21:50:55.350", "Id": "255584", "Score": "2", "Tags": [ "performance", "time-limit-exceeded", "r" ], "Title": "Calculating edges of a social network" }
255584
<p>My first component</p> <pre><code>export class EditIntegrationComponentAttributeComponent implements OnInit { constructor( private _router: ActivatedRoute, private _intApi: IntegrationsApiService, private _spinner: SpinnerService, private _fb: FormBuilder, private _routerNavigation: Router, private _notification: NotificationsService, ) { this.componentAttributeID = this._router.snapshot.params.id; } ngOnInit(): void { this._spinner.showSpinner('loading'); if (this.isNew) { this.sources = { componentAttributes: this._intApi.getIntComponentAttributesOptions(), componentAttributeType: this._intApi.getIntComponentTypes(), allComponentAttribute: this._intApi.getIntComponentAttributes() }; } else { this.sources = { componentAttributes: this._intApi.getIntComponentAttributesOptions(), componentAttribute: this._intApi.getIntComponentAttributeById(this.componentAttributeID), componentAttributeType: this._intApi.getIntComponentTypes(), allComponentAttribute: this._intApi.getIntComponentAttributes() }; } forkJoin(this.sources).pipe( finalize(() =&gt; { this._spinner.hideSpinner(); this.isLoading = false; }) ).subscribe( obj =&gt; { Object.keys(obj).forEach(key =&gt; { this[key] = obj[key]; }); }, (er) =&gt; { // If one call fails then the entire forkjoin fails // Display a message telling the user there was a problem pulling data console.log(er); this.hasLoadingError = true; }, () =&gt; { this._buildForm(this.componentAttributes); this._createSectionNames(this.allComponentAttribute); this.filteredOptions = this.iFg.controls.section_name.valueChanges.pipe( startWith(''), map(val =&gt; val.length &gt;= 2 ? this._filter(val) : []) ); } ); } /** * generating form using the controls created by * fn _createControls */ private _buildForm(data) { this.iFg = this._fb.group(this._createControls(data)); console.log(this.iFg) } /** * * Creating form controls by using the option provided by API * @params data */ private _createControls(data) { const ctrls = {}; for (const attr in data) { let str = {}; if ( data[attr].type === 'boolean' ) { str = { [attr]: [{ value: this.isNew ? false : this.componentAttribute[attr], disabled: this.isNew ? false : data[attr].read_only }] }; } else if ( data[attr].type === 'list' || attr === 'validation_expression' || data[attr].type === 'choice') { str = { [attr]: [{ value: this.isNew ? null : this.componentAttribute[attr], disabled: this.isNew ? false : data[attr].read_only }] }; } else if ( data[attr].type === 'datetime') { str = { [attr]: [{ value: this.isNew ? null : this._formatDate( this.componentAttribute[attr]), disabled: this.isNew ? false : data[attr].read_only }] }; } else { str = { [attr]: [{ value: this.isNew ? '' : this.componentAttribute[attr], disabled: this.isNew ? false : data[attr].read_only }] }; } Object.assign(ctrls, str); } this.isLoading = false; this._spinner.hideSpinner(); return ctrls; } /** * * getter method for checking if component is new or old */ get isNew() { return !this.componentAttributeID; } /** * * Save the updated/New Component Attribute */ public saveAttribute() { // remove null and empty from data this._spinner.showSpinner('saving'); const obj = this.iFg.value; Object.keys(obj).forEach(k =&gt; (!obj[k] &amp;&amp; obj[k] !== false) &amp;&amp; delete obj[k]); if (!this.isNew) { if (this.isTypeChanged) { this.iFg.value.ordering = 1; } this._intApi.updateIntComponentAttribute(this.componentAttributeID, obj).subscribe( (data) =&gt; { console.log(data); this._spinner.hideSpinner(); this._notification.success('', 'Component Attribute Updated'); }, (err) =&gt; { console.log(err); this._spinner.hideSpinner(); this._notification.error('', 'Component Attribute can not be updated please check logs'); } ); } else { this._intApi.postIntComponentAttribute(this.iFg.value).subscribe( (data) =&gt; { console.log(data); this._notification.success('', 'Component Attribute Added'); this._spinner.hideSpinner(); this._routerNavigation.navigateByUrl('/admin/integration/component-attributes/edit/' + data.id); }, (err) =&gt; { console.log(err); this._spinner.hideSpinner(); this._notification.error('', 'Component Attribute can not be updated please check console'); } ); } } /** * * adding choice in the choices array */ public removeChoicesFromList(value): void { const index = this.componentAttribute.choices.indexOf(value); if (index &gt;= 0) { this.componentAttribute.choices.splice(index, 1); } } /** * * removing choice from the choices array */ public addChoicesToList(event: MatChipInputEvent): void { console.log(this.iFg.value); if (this.iFg.value.choices === null || this.iFg.value.choices === '') { this.iFg.value.choices = []; } const input = event.input; const value = event.value; if ((value || '').trim()) { this.iFg.value.choices.push(value.trim()); } // Reset the input value if (input) { input.value = ''; } } public deleteComponentAttribute() { if (confirm('Are you sure you want to delete Component Attribute')) { this._intApi.removeIntComponentAttribute(this.componentAttributeID).subscribe( (data) =&gt; { this._notification.success('', 'Component Attribute deleted successfully'); this._routerNavigation.navigateByUrl('/admin/integration/component-attributes'); }, () =&gt; { this._notification.warn('', 'Can not delete Component Attribute'); } ); } } public onCancel() { this._routerNavigation.navigateByUrl('/admin/integration/component-attributes'); } private _formatDate(params: any): string { return new Date(params).toLocaleDateString(); } private _filter(value: string): string[] { const filterValue = value.toLowerCase(); return this.options.filter(option =&gt; option.toLowerCase().indexOf(filterValue) === 0); } private _createSectionNames(obj) { const key = this.componentAttribute.component_type; this.options = [... new Set (obj.filter(attribute =&gt; attribute.component_type === key).map(attr =&gt; attr.section_name).filter( ob =&gt; ob != null))]; } } </code></pre> <p>My 2nd component</p> <pre><code>@Component({ selector: 'app-edit-note-type', templateUrl: './edit-note-type.component.html', styleUrls: ['./edit-note-type.component.scss'] }) export class EditNoteTypeComponent implements OnInit { private noteTypeID; public sources: object; public isLoading = false; public hasLoadingError = false; public noteTypeOptions: IntUrlType[] = []; public noteTypeDetails: IntUrlType; public noteTypeFg: FormGroup; public chk ; constructor( private _router: ActivatedRoute, private _intApi: IntegrationsApiService, private _spinner: SpinnerService, private _fb: FormBuilder, private _routerNavigation: Router, private _notification: NotificationsService, private _auth: AuthorizationService, private _adminApi: AdminApiService ) { this.noteTypeID = this._router.snapshot.params.id; // for navigation to new server page } ngOnInit(): void { this.isLoading = true; this._spinner.showSpinner('loading'); if (this.isNew) { this.sources = { noteTypeOptions: this._intApi.getIntNoteCategoriesOptions(), }; } else { this.sources = { noteTypeOptions: this._intApi.getIntNoteCategoriesOptions(), noteTypeDetails: this._intApi.getIntNoteCategoriesById(this.noteTypeID), }; } forkJoin(this.sources).pipe( finalize(() =&gt; { this._spinner.hideSpinner(); this.isLoading = false; }) ).subscribe( obj =&gt; { Object.keys(obj).forEach(key =&gt; { this[key] = obj[key]; }); this.chk = [this.noteTypeOptions]; }, (er) =&gt; { // If one call fails then the entire forkjoin fails // Display a message telling the user there was a problem pulling data console.log(er); this.hasLoadingError = true; }, () =&gt; {this._buildForm(this.noteTypeOptions); } ); } /** * * getter method for checking if component is new or old */ get isNew() { return !this.noteTypeID; } /** * generating form using the controls created by * fn _createControls */ private _buildForm(data) { this.noteTypeFg = this._fb.group(this._createControls(data)); } /** * * Creating form controls by using the option provided by API * @params data */ private _createControls(data) { const ctrls: object = {}; for (const attr in data) { let str = {}; if ( data[attr].type === 'boolean' ) { str = { [attr]: [{ value: this.isNew ? true : this.noteTypeDetails[attr], disabled: this.isNew ? false : data[attr].read_only }] }; } else if ( data[attr].type === 'list' || attr === 'validation_expression' || data[attr].type === 'choice') { str = { [attr]: [{ value: this.isNew ? null : this.noteTypeDetails[attr], disabled: this.isNew ? false : data[attr].read_only }] }; } else if ( data[attr].type === 'datetime') { str = { [attr]: [{ value: this.isNew ? null : this._formatDate( this.noteTypeDetails[attr]), disabled: this.isNew ? false : data[attr].read_only }] }; } else { str = { [attr]: [{ value: this.isNew ? '' : this.noteTypeDetails[attr], disabled: this.isNew ? false : data[attr].read_only }] }; } Object.assign(ctrls, str); } this.isLoading = false; this._spinner.hideSpinner(); return ctrls; } public onCancel() { this._routerNavigation.navigateByUrl('/admin/integration/note-type'); } private _formatDate(params: any): string { return new Date(params).toLocaleDateString(); } /** * * Save the updated/New Note Type */ public saveNoteType() { this._spinner.showSpinner('saving'); const obj = this.noteTypeFg.value; Object.keys(obj).forEach(k =&gt; (!obj[k] &amp;&amp; obj[k] !== false) &amp;&amp; delete obj[k]); if (!this.isNew) { this._intApi.updateIntNoteCategory(this.noteTypeID, obj).subscribe( (data) =&gt; { this._spinner.hideSpinner(); this._routerNavigation.navigateByUrl('/admin/integration/note-type/edit/' + data.id); this._notification.success('', 'Successfully Saved'); }, (err) =&gt; { console.log(err); this._spinner.hideSpinner(); this._notification.error('', 'Not Saved! Please check Error in logs'); } ); } else { this._intApi.postIntNoteCategory(this.noteTypeFg.value).subscribe( (data) =&gt; { this._notification.success('', 'Type Added'); this._spinner.hideSpinner(); this._routerNavigation.navigateByUrl('/admin/integration/note-type/edit/' + data.id); }, (err) =&gt; { console.log(err); this._spinner.hideSpinner(); this._notification.error('', 'Not Saved'); } ); } } public deleteNoteType() { if (confirm('Are you sure you want to delete category')) { this._intApi.removeIntNoteCategory(this.noteTypeID).subscribe( (data) =&gt; { this._notification.success('', 'Category deleted successfully'); this._routerNavigation.navigateByUrl('/admin/integration/note-type'); }, () =&gt; { this._notification.warn('', 'Can not delete'); } ); } } } </code></pre> <p>I have some more component which are doing same Crud operation using same API but different methods of it. I want to create a parent class which can reduce the code repeated in each component class. I tried but I am not sure how can I pass the different methods from child class to parent class</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T09:29:55.423", "Id": "504351", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T23:25:44.387", "Id": "514974", "Score": "0", "body": "You have basically written two update-methods in your IntegrationsApiService which all do an update taking in an id and an object. If you publish that service (add it into the question), we can try to rewrite it in a generic way and than we can also rewrite the save-nethods in a generic way. Take care and good luck." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T05:26:49.660", "Id": "255589", "Score": "2", "Tags": [ "javascript", "object-oriented", "typescript", "inheritance", "angular-2+" ], "Title": "what should be the best approach to follow DRY principle here" }
255589
<p><strong>Problem:</strong><br> I have a weighted graph. I want to get distance from definite point to all other points in the graph.(and then get path to them) <br> I used modified <a href="https://wiki2.org/en/Dijkstra%27s_algorithm" rel="nofollow noreferrer">dijkstra algorithm</a></p> <p>So, here is code:</p> <pre><code>var get_path = function(graph, a) { // declaration let cache, i, v, queue, node, links, root, j, link, c, n, d, max, w, L = graph.length; // initialization cache = Array(L); i = L; while (--i &gt;= 0) { v = graph[i]; cache[v.id] = { id: v.id, distance: Infinity, links: v.links, prev: null, }; } root = cache[a]; root.distance = 0; queue = [root]; // processing i = 0; while (i &lt; queue.length) { node = queue[i]; links = node.links; j = links.length; while (--j &gt;= 0) { link = links[j]; c = cache[link.id]; d = node.distance + link.weight; if (d &lt; c.distance) { c.prev = node; c.distance = d; queue.push(c); } } i++; } return cache; } </code></pre> <p><strong>Graph format</strong> is:<br></p> <pre><code>graph = [ { id: 1, links: [ { id: 2, weight: 1, }, { id: 3, weight: 1, }, ], }, { id: 2, links: [ { id: 1, weight: 1, }, { id: 4, weight: 2, } ] }, { id: 3, links: [ { id: 1, weight: 1, }, { id: 4, weight: 3, } ] }, { id: 4, links: [ { id: 2, weight: 2, }, { id: 1, weight: 1, }, { id: 3, weight: 3, }, { id: 5, weight: 1, } ] }, { id: 5, links: [ { id: 4, weight: 1, } ] } ] </code></pre> <p><strong>Performance:</strong><br> In my PC this algorithm works with graph of ~160 vertices and ~350 edges about 0.03-0.06ms. But I need faster!</p> <p>You can measure performance on your PC <a href="https://jsfiddle.net/magneto903/1t05qnwj/" rel="nofollow noreferrer">here</a></p> <p><strong>Question:</strong> How to make this code (function <code>get_path()</code>) faster? Is it possible on JavaScript? If I should change the format of graph to make algorithm faster it's not a problem.</p> <br> <p>Or I exhausted possibilities of JavaScript?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T15:09:17.960", "Id": "504503", "Score": "1", "body": "Your code is optimal as a general purpose solution so for further optimization you will need to target known structural regularities. EG if the set of nodes A must pass through C to get to nodes not in A. You can then cache all shortest paths from C to any node in A. Any path from B (B is not in set A) to B1 (B1 is in set A) need only find shortest path to C, the path from C to B1 will be cached by index of B1. Without knowing what the graph represents or how and how often it is constructed there is no way of knowing if such optimizations will pay off" } ]
[ { "body": "<p>Interesting question;</p>\n<p><strong>Naming</strong></p>\n<ul>\n<li>The names are on the whole terrible, it really blocks the reading flow, the only good 1 letter variable is <code>i</code></li>\n<li>Further evidence of the bad naming is that I only realized that <code>n</code>, <code>w</code>, and <code>max</code> are never used because of jshint.com</li>\n<li>JavaScript follows lowerCamelCase so <code>get_path</code> -&gt; <code>getPath</code></li>\n<li>In fact, even <code>getPath</code> would be a bad name, because you are not getting a path, <code>getPaths</code> could be better (you are getting more than 1 ), but <code>getDistances</code> or even <code>getDistancesFromNode</code> seems best</li>\n</ul>\n<p><strong>Declarations</strong></p>\n<ul>\n<li><p>You are mixing <code>var</code> and <code>let</code> in your code, I would stick to <code>let</code> and <code>const</code></p>\n</li>\n<li><p>You are not declaring <code>res</code> at all (now it's a global) because this</p>\n<pre><code>var s_t = performance.now()\nres = get_path(graph, 157)\n</code></pre>\n<p>should be</p>\n<pre><code>var s_t = performance.now(),\nres = get_path(graph, 157)\n</code></pre>\n</li>\n</ul>\n<p><strong>Performance</strong></p>\n<p>This is already quite impressive, the only thing I noticed is that you process child nodes even if their child count is one (meaning really zero, since that 1 node must be the parent).</p>\n<p>I assume the <code>while</code> loops are meant to be the fastest approach, however it seems that the fastest approach is now the most <a href=\"https://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript\">readable approach</a>.</p>\n<p>If you were allowed to just use/modify <code>graph</code> instead of <code>cache</code> it would be faster, of course the code reviewer would have told you that's not clean ;)</p>\n<p><strong>Comments</strong></p>\n<p>Comments should be meaningful, these comments are rather obvious.</p>\n<p>All in all, if I had to maintain this, then I would rewrite with proper variable names but otherwise this is perfectly maintainable.</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 getDistancesFromNode(graph, origin) {\n\n let cache, i, j, queue, node, links, root,\n link, nextNode, distance, nodeCount = graph.length;\n\n cache = Array(nodeCount);\n i = nodeCount;\n while (--i &gt;= 0) {\n node = graph[i];\n cache[node.id] = {\n id: node.id,\n distance: Infinity,\n links: node.links,\n prev: null,\n };\n }\n root = cache[origin];\n root.distance = 0;\n queue = [root];\n\n i = 0;\n while (i &lt; queue.length) {\n node = queue[i];\n links = node.links;\n j = links.length;\n while (--j &gt;= 0) {\n link = links[j];\n nextNode = cache[link.id];\n distance = node.distance + nextNode.weight;\n if (distance &lt; nextNode.distance &amp;&amp; nextNode.links.length &gt; 1) {\n nextNode.prev = node;\n nextNode.distance = d;\n queue.push(nextNode);\n }\n }\n i++;\n }\n return cache\n};\n\n\nvar graph = [{\"id\":0,\"links\":[{\"id\":6,\"weight\":70.71067811865476},{\"id\":1,\"weight\":810}]},\n{\"id\":1,\"links\":[{\"id\":0,\"weight\":810},{\"id\":2,\"weight\":70.71067811865476}]},\n{\"id\":2,\"links\":[{\"id\":1,\"weight\":70.71067811865476},{\"id\":3,\"weight\":1592}]},\n{\"id\":3,\"links\":[{\"id\":2,\"weight\":1592},{\"id\":5,\"weight\":70.71067811865476},{\"id\":153,\"weight\":205.87711451966396}]},\n{\"id\":4,\"links\":[{\"id\":7,\"weight\":70.71067811865476},{\"id\":112,\"weight\":512.6115351930363},{\"id\":153,\"weight\":737.0774717197235}]},\n{\"id\":5,\"links\":[{\"id\":3,\"weight\":70.71067811865476},{\"id\":153,\"weight\":135.6583919878893}]},\n{\"id\":6,\"links\":[{\"id\":0,\"weight\":70.71067811865476},{\"id\":94,\"weight\":310.40008748620136}]},\n{\"id\":7,\"links\":[{\"id\":4,\"weight\":70.71067811865476},{\"id\":94,\"weight\":1281.6150329914337}]},\n{\"id\":8,\"links\":[{\"id\":9,\"weight\":55.43314410935759},{\"id\":27,\"weight\":394.91497146070554},{\"id\":89,\"weight\":249.25217498817833},{\"id\":17,\"weight\":37.97639596422426}]},\n{\"id\":9,\"links\":[{\"id\":8,\"weight\":55.43314410935759},{\"id\":10,\"weight\":62.68381161480822},{\"id\":85,\"weight\":257.37611801643203},{\"id\":119,\"weight\":357.92609495024175}]},\n{\"id\":10,\"links\":[{\"id\":9,\"weight\":62.68381161480822},{\"id\":11,\"weight\":22.00603386355706},{\"id\":43,\"weight\":325.893754212365},{\"id\":95,\"weight\":145.6349677143284},{\"id\":114,\"weight\":495.27154468751036},{\"id\":157,\"weight\":475.0410693030716},{\"id\":159,\"weight\":424.5428223515612},{\"id\":160,\"weight\":386.9207320551183},{\"id\":161,\"weight\":293.9650424785912}]},\n{\"id\":11,\"links\":[{\"id\":10,\"weight\":22.00603386355706},{\"id\":12,\"weight\":40.754770931103174},{\"id\":66,\"weight\":338.44828019294425},{\"id\":154,\"weight\":277.7768610143829}]},\n{\"id\":12,\"links\":[{\"id\":11,\"weight\":40.754770931103174},{\"id\":13,\"weight\":63.96396957495827},{\"id\":71,\"weight\":279.46200199816974},{\"id\":130,\"weight\":423.73430144247175},{\"id\":142,\"weight\":605.3109163530141}]},\n{\"id\":13,\"links\":[{\"id\":12,\"weight\":63.96396957495827},{\"id\":14,\"weight\":42.685329113484585},{\"id\":22,\"weight\":267.044681207588},{\"id\":18,\"weight\":383.79570105328406},{\"id\":89,\"weight\":295.1151050396651},{\"id\":97,\"weight\":173.37684490280637},{\"id\":147,\"weight\":644.3394809974541}]},\n{\"id\":14,\"links\":[{\"id\":13,\"weight\":42.685329113484585},{\"id\":15,\"weight\":45.39123913699872}]},\n{\"id\":15,\"links\":[{\"id\":14,\"weight\":45.39123913699872},{\"id\":16,\"weight\":47.047036449194316},{\"id\":65,\"weight\":294.0887879580657},{\"id\":86,\"weight\":183.6721765115165},{\"id\":114,\"weight\":486.6941103104043},{\"id\":159,\"weight\":416.3689141062264},{\"id\":160,\"weight\":344.37793610826577}]},\n{\"id\":16,\"links\":[{\"id\":15,\"weight\":47.047036449194316},{\"id\":17,\"weight\":25.7772200449739},{\"id\":43,\"weight\":298.08763602419685},{\"id\":39,\"weight\":354.1679638306291},{\"id\":70,\"weight\":371.37278825824006},{\"id\":74,\"weight\":670.2294043204714},{\"id\":132,\"weight\":378.87860482952715},{\"id\":157,\"weight\":434.2784913076533},{\"id\":161,\"weight\":262.12088923847034}]},\n{\"id\":17,\"links\":[{\"id\":16,\"weight\":25.7772200449739},{\"id\":8,\"weight\":37.97639596422426},{\"id\":22,\"weight\":283.4489103653117},{\"id\":136,\"weight\":499.55002623505305},{\"id\":142,\"weight\":589.0762111107545}]},\n{\"id\":18,\"links\":[{\"id\":13,\"weight\":383.79570105328406},{\"id\":19,\"weight\":68.56451044560333},{\"id\":27,\"weight\":31.90572098820839}]},\n{\"id\":19,\"links\":[{\"id\":18,\"weight\":68.56451044560333},{\"id\":20,\"weight\":60.809531997686655},{\"id\":64,\"weight\":400.06011580087164},{\"id\":156,\"weight\":445.50275071828963}]},\n{\"id\":20,\"links\":[{\"id\":19,\"weight\":60.809531997686655},{\"id\":21,\"weight\":41.7268040869492}]},\n{\"id\":21,\"links\":[{\"id\":20,\"weight\":41.7268040869492},{\"id\":22,\"weight\":44.409786926805985},{\"id\":70,\"weight\":244.19177296204867},{\"id\":91,\"weight\":205.16309784978526},{\"id\":131,\"weight\":170.98157093493768}]},\n{\"id\":22,\"links\":[{\"id\":13,\"weight\":267.044681207588},{\"id\":17,\"weight\":283.4489103653117},{\"id\":21,\"weight\":44.409786926805985},{\"id\":23,\"weight\":73.41351083187409},{\"id\":44,\"weight\":578.7057992684693},{\"id\":39,\"weight\":603.7781336207288},{\"id\":49,\"weight\":794.3115697606781},{\"id\":57,\"weight\":486.1389713865941},{\"id\":86,\"weight\":298.95911490661615},{\"id\":128,\"weight\":342.80891355908545},{\"id\":135,\"weight\":282.6431518625895},{\"id\":142,\"weight\":308.1360659862511},{\"id\":147,\"weight\":378.58967001309463},{\"id\":161,\"weight\":491.24332514971724}]},\n{\"id\":23,\"links\":[{\"id\":22,\"weight\":73.41351083187409},{\"id\":24,\"weight\":47.156569853258866},{\"id\":63,\"weight\":299.1373917294431},{\"id\":156,\"weight\":424.0775352517563}]},\n{\"id\":24,\"links\":[{\"id\":23,\"weight\":47.156569853258866},{\"id\":25,\"weight\":86.13825660873893},{\"id\":131,\"weight\":210.320160984807}]},\n{\"id\":25,\"links\":[{\"id\":24,\"weight\":86.13825660873893},{\"id\":26,\"weight\":33.06353502569152}]},\n{\"id\":26,\"links\":[{\"id\":25,\"weight\":33.06353502569152},{\"id\":27,\"weight\":67.91460112401641},{\"id\":57,\"weight\":540.3387174980588},{\"id\":92,\"weight\":228.93825991593803},{\"id\":120,\"weight\":412.75883815805963},{\"id\":128,\"weight\":418.9168740031914},{\"id\":142,\"weight\":333.7521131385038}]},\n{\"id\":27,\"links\":[{\"id\":8,\"weight\":394.91497146070554},{\"id\":26,\"weight\":67.91460112401641},{\"id\":18,\"weight\":31.90572098820839},{\"id\":80,\"weight\":593.5258503155924},{\"id\":89,\"weight\":148.5928396302128},{\"id\":147,\"weight\":349.297544643658}]},\n{\"id\":28,\"links\":[{\"id\":29,\"weight\":59.67018420401978},{\"id\":81,\"weight\":209.96278270854182},{\"id\":106,\"weight\":69.99034725665763},{\"id\":149,\"weight\":340.8623984131601},{\"id\":37,\"weight\":28.746317165572204}]},\n{\"id\":29,\"links\":[{\"id\":28,\"weight\":59.67018420401978},{\"id\":30,\"weight\":23.113480906778186},{\"id\":60,\"weight\":155.8179847580466},{\"id\":77,\"weight\":297.5407757529884}]},\n{\"id\":30,\"links\":[{\"id\":29,\"weight\":23.113480906778186},{\"id\":31,\"weight\":24.194433832360634},{\"id\":48,\"weight\":312.87236629082633}]},\n{\"id\":31,\"links\":[{\"id\":30,\"weight\":24.194433832360634},{\"id\":32,\"weight\":95.03245812683691},{\"id\":52,\"weight\":306.82477443979093},{\"id\":107,\"weight\":78.85870804148841}]},\n{\"id\":32,\"links\":[{\"id\":31,\"weight\":95.03245812683691},{\"id\":33,\"weight\":28.769841069179858},{\"id\":60,\"weight\":147.93878749367386}]},\n{\"id\":33,\"links\":[{\"id\":32,\"weight\":28.769841069179858},{\"id\":34,\"weight\":26.884913041414087},{\"id\":149,\"weight\":324.73490720293273}]},\n{\"id\":34,\"links\":[{\"id\":33,\"weight\":26.884913041414087},{\"id\":35,\"weight\":34.539644671799884},{\"id\":48,\"weight\":312.60280041119495},{\"id\":82,\"weight\":298.7966839326061}]},\n{\"id\":35,\"links\":[{\"id\":34,\"weight\":34.539644671799884},{\"id\":36,\"weight\":47.88309910969351},{\"id\":52,\"weight\":298.6492567682363},{\"id\":78,\"weight\":270.88254329096384}]},\n{\"id\":36,\"links\":[{\"id\":35,\"weight\":47.88309910969351},{\"id\":37,\"weight\":55.92799176338086},{\"id\":146,\"weight\":250.2794421195491}]},\n{\"id\":37,\"links\":[{\"id\":36,\"weight\":55.92799176338086},{\"id\":28,\"weight\":28.746317165572204},{\"id\":101,\"weight\":174.53904785374436}]},\n{\"id\":38,\"links\":[{\"id\":45,\"weight\":41.60346490016386},{\"id\":160,\"weight\":259.95392603739697}]},\n{\"id\":39,\"links\":[{\"id\":16,\"weight\":354.1679638306291},{\"id\":22,\"weight\":603.7781336207288},{\"id\":40,\"weight\":28.56292626279466},{\"id\":136,\"weight\":827.1618749297187},{\"id\":142,\"weight\":911.9072364060776}]},\n{\"id\":40,\"links\":[{\"id\":39,\"weight\":28.56292626279466},{\"id\":41,\"weight\":71.83348433366919},{\"id\":87,\"weight\":385.18415791555594}]},\n{\"id\":41,\"links\":[{\"id\":40,\"weight\":71.83348433366919},{\"id\":42,\"weight\":25.66448755744104},{\"id\":84,\"weight\":301.86449922516306},{\"id\":119,\"weight\":304.09006218105435},{\"id\":160,\"weight\":191.66415098549578},{\"id\":161,\"weight\":42.17582986887332}]},\n{\"id\":42,\"links\":[{\"id\":41,\"weight\":25.66448755744104},{\"id\":43,\"weight\":25.041564347271354},{\"id\":114,\"weight\":201.32515950767336},{\"id\":159,\"weight\":136.50001088374017}]},\n{\"id\":43,\"links\":[{\"id\":10,\"weight\":325.893754212365},{\"id\":16,\"weight\":298.08763602419685},{\"id\":42,\"weight\":25.041564347271354},{\"id\":44,\"weight\":53.81505716045718},{\"id\":70,\"weight\":668.6142302142265},{\"id\":95,\"weight\":464.5912380083568},{\"id\":132,\"weight\":675.2576499747647},{\"id\":157,\"weight\":149.3858968154142},{\"id\":161,\"weight\":35.96703115932087}]},\n{\"id\":44,\"links\":[{\"id\":22,\"weight\":578.7057992684693},{\"id\":43,\"weight\":53.81505716045718},{\"id\":45,\"weight\":41.40801209082323},{\"id\":57,\"weight\":1063.3996891527247},{\"id\":136,\"weight\":809.6193736796965}]},\n{\"id\":45,\"links\":[{\"id\":44,\"weight\":41.40801209082323},{\"id\":38,\"weight\":41.60346490016386},{\"id\":86,\"weight\":326.14140573310647},{\"id\":83,\"weight\":413.3998108385815},{\"id\":118,\"weight\":301.0257064648056}]},\n{\"id\":46,\"links\":[{\"id\":47,\"weight\":32.324323407861954},{\"id\":54,\"weight\":25.030634943141447}]},\n{\"id\":47,\"links\":[{\"id\":46,\"weight\":32.324323407861954},{\"id\":48,\"weight\":74.97098636842881},{\"id\":150,\"weight\":482.148526864346}]},\n{\"id\":48,\"links\":[{\"id\":30,\"weight\":312.87236629082633},{\"id\":34,\"weight\":312.60280041119495},{\"id\":47,\"weight\":74.97098636842881},{\"id\":49,\"weight\":51.584467579702824},{\"id\":61,\"weight\":244.27972531448285},{\"id\":106,\"weight\":336.640487491796}]},\n{\"id\":49,\"links\":[{\"id\":22,\"weight\":794.3115697606781},{\"id\":48,\"weight\":51.584467579702824},{\"id\":57,\"weight\":308.50551001966323},{\"id\":128,\"weight\":451.6465055929891},{\"id\":135,\"weight\":511.844500792933}]},\n{\"id\":50,\"links\":[{\"id\":51,\"weight\":49.512416392803104}]},\n{\"id\":51,\"links\":[{\"id\":50,\"weight\":49.512416392803104},{\"id\":52,\"weight\":53.04787162699196}]},\n{\"id\":52,\"links\":[{\"id\":31,\"weight\":306.82477443979093},{\"id\":35,\"weight\":298.6492567682363},{\"id\":51,\"weight\":53.04787162699196},{\"id\":53,\"weight\":76.43056418497244},{\"id\":82,\"weight\":547.120073731121},{\"id\":110,\"weight\":325.05226324305437},{\"id\":150,\"weight\":458.3924820628751}]},\n{\"id\":53,\"links\":[{\"id\":52,\"weight\":76.43056418497244},{\"id\":54,\"weight\":20.039265191224455}]},\n{\"id\":54,\"links\":[{\"id\":53,\"weight\":20.039265191224455},{\"id\":46,\"weight\":25.030634943141447},{\"id\":58,\"weight\":244.9260216552532},{\"id\":67,\"weight\":756.3463895463947},{\"id\":76,\"weight\":482.3227102069046},{\"id\":124,\"weight\":422.2533744531271}]},\n{\"id\":55,\"links\":[{\"id\":56,\"weight\":58.460583239231624},{\"id\":102,\"weight\":115.82406310298205},{\"id\":125,\"weight\":152.5815324765102}]},\n{\"id\":56,\"links\":[{\"id\":55,\"weight\":58.460583239231624},{\"id\":57,\"weight\":55.57519143003837}]},\n{\"id\":57,\"links\":[{\"id\":22,\"weight\":486.1389713865941},{\"id\":26,\"weight\":540.3387174980588},{\"id\":44,\"weight\":1063.3996891527247},{\"id\":49,\"weight\":308.50551001966323},{\"id\":56,\"weight\":55.57519143003837},{\"id\":58,\"weight\":48.45767081071381},{\"id\":158,\"weight\":180.39992938539922},{\"id\":136,\"weight\":253.7803363149803},{\"id\":142,\"weight\":206.67779462996376}]},\n{\"id\":58,\"links\":[{\"id\":54,\"weight\":244.9260216552532},{\"id\":57,\"weight\":48.45767081071381},{\"id\":59,\"weight\":24.092997373752972}]},\n{\"id\":59,\"links\":[{\"id\":58,\"weight\":24.092997373752972},{\"id\":60,\"weight\":82.39211060953677},{\"id\":76,\"weight\":268.66979964854914},{\"id\":124,\"weight\":204.95995317424766}]},\n{\"id\":60,\"links\":[{\"id\":29,\"weight\":155.8179847580466},{\"id\":32,\"weight\":147.93878749367386},{\"id\":59,\"weight\":82.39211060953677},{\"id\":61,\"weight\":56.8386682833888}]},\n{\"id\":61,\"links\":[{\"id\":48,\"weight\":244.27972531448285},{\"id\":60,\"weight\":56.8386682833888},{\"id\":77,\"weight\":395.3342593777817},{\"id\":106,\"weight\":94.82870098367673}]},\n{\"id\":62,\"links\":[{\"id\":63,\"weight\":50.239660941572126},{\"id\":138,\"weight\":456.67384076187767},{\"id\":71,\"weight\":38.53358308507445}]},\n{\"id\":63,\"links\":[{\"id\":23,\"weight\":299.1373917294431},{\"id\":62,\"weight\":50.239660941572126},{\"id\":64,\"weight\":49.29188012559735}]},\n{\"id\":64,\"links\":[{\"id\":19,\"weight\":400.06011580087164},{\"id\":63,\"weight\":49.29188012559735},{\"id\":65,\"weight\":34.9390920450358},{\"id\":91,\"weight\":484.70495246456426}]},\n{\"id\":65,\"links\":[{\"id\":15,\"weight\":294.0887879580657},{\"id\":64,\"weight\":34.9390920450358},{\"id\":66,\"weight\":44.386933593419634},{\"id\":86,\"weight\":473.4945906187595},{\"id\":160,\"weight\":638.3194987663459}]},\n{\"id\":66,\"links\":[{\"id\":11,\"weight\":338.44828019294425},{\"id\":65,\"weight\":44.386933593419634},{\"id\":67,\"weight\":46.35007638082747},{\"id\":97,\"weight\":354.99096425656126},{\"id\":155,\"weight\":98.46201480548129}]},\n{\"id\":67,\"links\":[{\"id\":54,\"weight\":756.3463895463947},{\"id\":66,\"weight\":46.35007638082747},{\"id\":68,\"weight\":83.11118143775956},{\"id\":76,\"weight\":275.22916188389814},{\"id\":124,\"weight\":334.3275404295602}]},\n{\"id\":68,\"links\":[{\"id\":67,\"weight\":83.11118143775956},{\"id\":69,\"weight\":61.82288775247714}]},\n{\"id\":69,\"links\":[{\"id\":68,\"weight\":61.82288775247714},{\"id\":70,\"weight\":32.72720780632854}]},\n{\"id\":70,\"links\":[{\"id\":16,\"weight\":371.37278825824006},{\"id\":21,\"weight\":244.19177296204867},{\"id\":43,\"weight\":668.6142302142265},{\"id\":69,\"weight\":32.72720780632854},{\"id\":71,\"weight\":82.01328044192185},{\"id\":74,\"weight\":299.3033974268629},{\"id\":86,\"weight\":467.8800531253375},{\"id\":114,\"weight\":795.7351820979673},{\"id\":131,\"weight\":74.14997079035552},{\"id\":157,\"weight\":798.2577975693512},{\"id\":159,\"weight\":728.6111329180097},{\"id\":161,\"weight\":632.6993752105095}]},\n{\"id\":71,\"links\":[{\"id\":12,\"weight\":279.46200199816974},{\"id\":70,\"weight\":82.01328044192185},{\"id\":62,\"weight\":38.53358308507445},{\"id\":97,\"weight\":376.4367138297526},{\"id\":122,\"weight\":299.55665657848795},{\"id\":132,\"weight\":92.36209904758263},{\"id\":131,\"weight\":67.09223542194184},{\"id\":156,\"weight\":229.10251215735252}]},\n{\"id\":72,\"links\":[{\"id\":73,\"weight\":22.44295867376786},{\"id\":124,\"weight\":96.7927637387651},{\"id\":76,\"weight\":30.383770443458943}]},\n{\"id\":73,\"links\":[{\"id\":72,\"weight\":22.44295867376786}]},\n{\"id\":74,\"links\":[{\"id\":16,\"weight\":670.2294043204714},{\"id\":70,\"weight\":299.3033974268629},{\"id\":75,\"weight\":41.39428112635902},{\"id\":121,\"weight\":140.7096972711017},{\"id\":132,\"weight\":291.38771611392053}]},\n{\"id\":75,\"links\":[{\"id\":74,\"weight\":41.39428112635902},{\"id\":76,\"weight\":30.0627689482037}]},\n{\"id\":76,\"links\":[{\"id\":54,\"weight\":482.3227102069046},{\"id\":59,\"weight\":268.66979964854914},{\"id\":67,\"weight\":275.22916188389814},{\"id\":75,\"weight\":30.0627689482037},{\"id\":72,\"weight\":30.383770443458943}]},\n{\"id\":77,\"links\":[{\"id\":29,\"weight\":297.5407757529884},{\"id\":61,\"weight\":395.3342593777817},{\"id\":78,\"weight\":52.00968489404878},{\"id\":106,\"weight\":300.6735447670068},{\"id\":145,\"weight\":213.64883986492893}]},\n{\"id\":78,\"links\":[{\"id\":35,\"weight\":270.88254329096384},{\"id\":77,\"weight\":52.00968489404878},{\"id\":79,\"weight\":44.23783407847146}]},\n{\"id\":79,\"links\":[{\"id\":78,\"weight\":44.23783407847146},{\"id\":80,\"weight\":38.118361538425795}]},\n{\"id\":80,\"links\":[{\"id\":27,\"weight\":593.5258503155924},{\"id\":79,\"weight\":38.118361538425795},{\"id\":81,\"weight\":88.22727131494065},{\"id\":92,\"weight\":748.610228678086},{\"id\":117,\"weight\":922.5836952812741},{\"id\":160,\"weight\":981.0925983047125}]},\n{\"id\":81,\"links\":[{\"id\":28,\"weight\":209.96278270854182},{\"id\":80,\"weight\":88.22727131494065},{\"id\":82,\"weight\":65.51209274182104},{\"id\":101,\"weight\":323.12731048143235},{\"id\":147,\"weight\":350.10072558836436}]},\n{\"id\":82,\"links\":[{\"id\":34,\"weight\":298.7966839326061},{\"id\":52,\"weight\":547.120073731121},{\"id\":81,\"weight\":65.51209274182104},{\"id\":111,\"weight\":269.9434631344396}]},\n{\"id\":83,\"links\":[{\"id\":45,\"weight\":413.3998108385815},{\"id\":84,\"weight\":49.04899812555336},{\"id\":92,\"weight\":30.837464050468025}]},\n{\"id\":84,\"links\":[{\"id\":41,\"weight\":301.86449922516306},{\"id\":83,\"weight\":49.04899812555336},{\"id\":85,\"weight\":63.71188304619065},{\"id\":161,\"weight\":262.445211274406}]},\n{\"id\":85,\"links\":[{\"id\":9,\"weight\":257.37611801643203},{\"id\":84,\"weight\":63.71188304619065},{\"id\":86,\"weight\":49.09351203637654}]},\n{\"id\":86,\"links\":[{\"id\":15,\"weight\":183.6721765115165},{\"id\":22,\"weight\":298.95911490661615},{\"id\":45,\"weight\":326.14140573310647},{\"id\":65,\"weight\":473.4945906187595},{\"id\":70,\"weight\":467.8800531253375},{\"id\":85,\"weight\":49.09351203637654},{\"id\":87,\"weight\":83.46480593410709},{\"id\":119,\"weight\":151.90228469087668},{\"id\":114,\"weight\":329.0079671927419},{\"id\":128,\"weight\":641.7308695509025},{\"id\":132,\"weight\":471.07620316344014},{\"id\":135,\"weight\":581.5450583764579},{\"id\":157,\"weight\":337.27659265236},{\"id\":159,\"weight\":264.5824947674739},{\"id\":160,\"weight\":170.91599639926625}]},\n{\"id\":87,\"links\":[{\"id\":40,\"weight\":385.18415791555594},{\"id\":86,\"weight\":83.46480593410709},{\"id\":88,\"weight\":41.619088536378854},{\"id\":161,\"weight\":285.65519727136444}]},\n{\"id\":88,\"links\":[{\"id\":87,\"weight\":41.619088536378854},{\"id\":89,\"weight\":19.022840656019405}]},\n{\"id\":89,\"links\":[{\"id\":8,\"weight\":249.25217498817833},{\"id\":13,\"weight\":295.1151050396651},{\"id\":27,\"weight\":148.5928396302128},{\"id\":88,\"weight\":19.022840656019405},{\"id\":90,\"weight\":35.841603038774416}]},\n{\"id\":90,\"links\":[{\"id\":89,\"weight\":35.841603038774416},{\"id\":91,\"weight\":32.398612793756314}]},\n{\"id\":91,\"links\":[{\"id\":21,\"weight\":205.16309784978526},{\"id\":64,\"weight\":484.70495246456426},{\"id\":90,\"weight\":32.398612793756314},{\"id\":92,\"weight\":48.582975729764854}]},\n{\"id\":92,\"links\":[{\"id\":26,\"weight\":228.93825991593803},{\"id\":80,\"weight\":748.610228678086},{\"id\":91,\"weight\":48.582975729764854},{\"id\":83,\"weight\":30.837464050468025},{\"id\":120,\"weight\":188.7591372909066},{\"id\":117,\"weight\":174.02812344524793},{\"id\":146,\"weight\":572.3906052533645},{\"id\":159,\"weight\":344.37896644057383},{\"id\":160,\"weight\":232.48237745520552}]},\n{\"id\":93,\"links\":[{\"id\":97,\"weight\":102.0522575060609}]},\n{\"id\":94,\"links\":[{\"id\":6,\"weight\":310.40008748620136},{\"id\":7,\"weight\":1281.6150329914337}]},\n{\"id\":95,\"links\":[{\"id\":10,\"weight\":145.6349677143284},{\"id\":43,\"weight\":464.5912380083568},{\"id\":96,\"weight\":20.309465539051313},{\"id\":114,\"weight\":637.3889554757393},{\"id\":159,\"weight\":567.3380419121927},{\"id\":161,\"weight\":434.67294753052647}]},\n{\"id\":96,\"links\":[{\"id\":95,\"weight\":20.309465539051313},{\"id\":97,\"weight\":63.213233743350074}]},\n{\"id\":97,\"links\":[{\"id\":13,\"weight\":173.37684490280637},{\"id\":66,\"weight\":354.99096425656126},{\"id\":71,\"weight\":376.4367138297526},{\"id\":96,\"weight\":63.213233743350074},{\"id\":93,\"weight\":102.0522575060609},{\"id\":100,\"weight\":240.91712277511493},{\"id\":130,\"weight\":525.9007129529984},{\"id\":142,\"weight\":709.2888517760487},{\"id\":147,\"weight\":817.6275336689539},{\"id\":155,\"weight\":256.52958550596395}]},\n{\"id\":98,\"links\":[{\"id\":99,\"weight\":38.26238414408713}]},\n{\"id\":99,\"links\":[{\"id\":98,\"weight\":38.26238414408713},{\"id\":100,\"weight\":81.55030224358033}]},\n{\"id\":100,\"links\":[{\"id\":97,\"weight\":240.91712277511493},{\"id\":99,\"weight\":81.55030224358033},{\"id\":130,\"weight\":766.6709881560315},{\"id\":142,\"weight\":949.697709689759}]},\n{\"id\":101,\"links\":[{\"id\":37,\"weight\":174.53904785374436},{\"id\":81,\"weight\":323.12731048143235},{\"id\":102,\"weight\":47.30056869901373},{\"id\":143,\"weight\":92.85603330225935},{\"id\":109,\"weight\":48.22919045283958}]},\n{\"id\":102,\"links\":[{\"id\":55,\"weight\":115.82406310298205},{\"id\":101,\"weight\":47.30056869901373},{\"id\":103,\"weight\":35.380667355785846},{\"id\":125,\"weight\":257.26089278078433},{\"id\":145,\"weight\":86.69660180432261}]},\n{\"id\":103,\"links\":[{\"id\":102,\"weight\":35.380667355785846},{\"id\":104,\"weight\":43.58038875739012}]},\n{\"id\":104,\"links\":[{\"id\":103,\"weight\":43.58038875739012}]},\n{\"id\":105,\"links\":[{\"id\":106,\"weight\":49.00253118207074}]},\n{\"id\":106,\"links\":[{\"id\":28,\"weight\":69.99034725665763},{\"id\":48,\"weight\":336.640487491796},{\"id\":61,\"weight\":94.82870098367673},{\"id\":77,\"weight\":300.6735447670068},{\"id\":105,\"weight\":49.00253118207074},{\"id\":107,\"weight\":27.405833077229865}]},\n{\"id\":107,\"links\":[{\"id\":31,\"weight\":78.85870804148841},{\"id\":106,\"weight\":27.405833077229865},{\"id\":108,\"weight\":39.67467085048693},{\"id\":146,\"weight\":161.5285374896578}]},\n{\"id\":108,\"links\":[{\"id\":107,\"weight\":39.67467085048693},{\"id\":109,\"weight\":28.034817769574357}]},\n{\"id\":109,\"links\":[{\"id\":108,\"weight\":28.034817769574357},{\"id\":101,\"weight\":48.22919045283958}]},\n{\"id\":110,\"links\":[{\"id\":52,\"weight\":325.05226324305437},{\"id\":111,\"weight\":25.375224080516592},{\"id\":150,\"weight\":133.5176916667986}]},\n{\"id\":111,\"links\":[{\"id\":82,\"weight\":269.9434631344396},{\"id\":110,\"weight\":25.375224080516592}]},\n{\"id\":112,\"links\":[{\"id\":4,\"weight\":512.6115351930363},{\"id\":113,\"weight\":83.28092580028589},{\"id\":153,\"weight\":239.32930481887956}]},\n{\"id\":113,\"links\":[{\"id\":112,\"weight\":83.28092580028589}]},\n{\"id\":114,\"links\":[{\"id\":10,\"weight\":495.27154468751036},{\"id\":15,\"weight\":486.6941103104043},{\"id\":42,\"weight\":201.32515950767336},{\"id\":70,\"weight\":795.7351820979673},{\"id\":86,\"weight\":329.0079671927419},{\"id\":95,\"weight\":637.3889554757393},{\"id\":115,\"weight\":101.77827438406392},{\"id\":132,\"weight\":799.5716987622106},{\"id\":159,\"weight\":71.39727162164735},{\"id\":161,\"weight\":202.98164149753293}]},\n{\"id\":115,\"links\":[{\"id\":114,\"weight\":101.77827438406392},{\"id\":116,\"weight\":55.33658324913234},{\"id\":160,\"weight\":63.25551243883601}]},\n{\"id\":116,\"links\":[{\"id\":115,\"weight\":55.33658324913234},{\"id\":117,\"weight\":64.34602362067791}]},\n{\"id\":117,\"links\":[{\"id\":80,\"weight\":922.5836952812741},{\"id\":92,\"weight\":174.02812344524793},{\"id\":116,\"weight\":64.34602362067791},{\"id\":118,\"weight\":25.616725172113455},{\"id\":157,\"weight\":242.8128909397011},{\"id\":159,\"weight\":170.35193802012466},{\"id\":160,\"weight\":58.715883663506396}]},\n{\"id\":118,\"links\":[{\"id\":45,\"weight\":301.0257064648056},{\"id\":117,\"weight\":25.616725172113455},{\"id\":119,\"weight\":49.34327971363866}]},\n{\"id\":119,\"links\":[{\"id\":9,\"weight\":357.92609495024175},{\"id\":41,\"weight\":304.09006218105435},{\"id\":86,\"weight\":151.90228469087668},{\"id\":118,\"weight\":49.34327971363866},{\"id\":120,\"weight\":92.13543408276188},{\"id\":161,\"weight\":262.52409073917073}]},\n{\"id\":120,\"links\":[{\"id\":26,\"weight\":412.75883815805963},{\"id\":92,\"weight\":188.7591372909066},{\"id\":119,\"weight\":92.13543408276188}]},\n{\"id\":121,\"links\":[{\"id\":74,\"weight\":140.7096972711017},{\"id\":122,\"weight\":49.158380910815055}]},\n{\"id\":122,\"links\":[{\"id\":71,\"weight\":299.55665657848795},{\"id\":121,\"weight\":49.158380910815055},{\"id\":123,\"weight\":22.072670207307805},{\"id\":132,\"weight\":207.55080569931508}]},\n{\"id\":123,\"links\":[{\"id\":122,\"weight\":22.072670207307805},{\"id\":124,\"weight\":23.95147516157658}]},\n{\"id\":124,\"links\":[{\"id\":54,\"weight\":422.2533744531271},{\"id\":59,\"weight\":204.95995317424766},{\"id\":67,\"weight\":334.3275404295602},{\"id\":72,\"weight\":96.7927637387651},{\"id\":123,\"weight\":23.95147516157658},{\"id\":125,\"weight\":37.10612238764236}]},\n{\"id\":125,\"links\":[{\"id\":55,\"weight\":152.5815324765102},{\"id\":102,\"weight\":257.26089278078433},{\"id\":124,\"weight\":37.10612238764236},{\"id\":126,\"weight\":34.927378155183234},{\"id\":141,\"weight\":258.1518700205428}]},\n{\"id\":126,\"links\":[{\"id\":125,\"weight\":34.927378155183234},{\"id\":127,\"weight\":32.98615477724716}]},\n{\"id\":127,\"links\":[{\"id\":126,\"weight\":32.98615477724716},{\"id\":128,\"weight\":16.22742340952728}]},\n{\"id\":128,\"links\":[{\"id\":22,\"weight\":342.80891355908545},{\"id\":26,\"weight\":418.9168740031914},{\"id\":49,\"weight\":451.6465055929891},{\"id\":86,\"weight\":641.7308695509025},{\"id\":127,\"weight\":16.22742340952728},{\"id\":158,\"weight\":35.94532649063341},{\"id\":135,\"weight\":60.199671727187834}]},\n{\"id\":129,\"links\":[]},\n{\"id\":130,\"links\":[{\"id\":12,\"weight\":423.73430144247175},{\"id\":97,\"weight\":525.9007129529984},{\"id\":100,\"weight\":766.6709881560315},{\"id\":131,\"weight\":89.63249969243708},{\"id\":137,\"weight\":44.67921793243463}]},\n{\"id\":131,\"links\":[{\"id\":21,\"weight\":170.98157093493768},{\"id\":24,\"weight\":210.320160984807},{\"id\":70,\"weight\":74.14997079035552},{\"id\":71,\"weight\":67.09223542194184},{\"id\":130,\"weight\":89.63249969243708},{\"id\":132,\"weight\":70.44518620133896},{\"id\":142,\"weight\":273.78551731820147},{\"id\":138,\"weight\":351.5407196157602},{\"id\":156,\"weight\":296.14115910691856}]},\n{\"id\":132,\"links\":[{\"id\":16,\"weight\":378.87860482952715},{\"id\":43,\"weight\":675.2576499747647},{\"id\":71,\"weight\":92.36209904758263},{\"id\":74,\"weight\":291.38771611392053},{\"id\":86,\"weight\":471.07620316344014},{\"id\":114,\"weight\":799.5716987622106},{\"id\":122,\"weight\":207.55080569931508},{\"id\":131,\"weight\":70.44518620133896},{\"id\":133,\"weight\":53.20257740632008},{\"id\":157,\"weight\":803.2044974295419},{\"id\":159,\"weight\":733.0042344492691},{\"id\":161,\"weight\":639.4014374495188}]},\n{\"id\":133,\"links\":[{\"id\":132,\"weight\":53.20257740632008},{\"id\":134,\"weight\":50.32148162147291}]},\n{\"id\":134,\"links\":[{\"id\":133,\"weight\":50.32148162147291}]},\n{\"id\":135,\"links\":[{\"id\":22,\"weight\":282.6431518625895},{\"id\":49,\"weight\":511.844500792933},{\"id\":86,\"weight\":581.5450583764579},{\"id\":128,\"weight\":60.199671727187834},{\"id\":136,\"weight\":49.49620942581232}]},\n{\"id\":136,\"links\":[{\"id\":17,\"weight\":499.55002623505305},{\"id\":39,\"weight\":827.1618749297187},{\"id\":44,\"weight\":809.6193736796965},{\"id\":57,\"weight\":253.7803363149803},{\"id\":135,\"weight\":49.49620942581232},{\"id\":137,\"weight\":31.43818529653531},{\"id\":161,\"weight\":721.2341683340406}]},\n{\"id\":137,\"links\":[{\"id\":136,\"weight\":31.43818529653531},{\"id\":130,\"weight\":44.67921793243463}]},\n{\"id\":138,\"links\":[{\"id\":62,\"weight\":456.67384076187767},{\"id\":131,\"weight\":351.5407196157602},{\"id\":139,\"weight\":23.777001819899976},{\"id\":156,\"weight\":645.5864796077194},{\"id\":147,\"weight\":60.21879922428856}]},\n{\"id\":139,\"links\":[{\"id\":138,\"weight\":23.777001819899976},{\"id\":140,\"weight\":47.7270317027185}]},\n{\"id\":140,\"links\":[{\"id\":139,\"weight\":47.7270317027185},{\"id\":141,\"weight\":23.039143895070726}]},\n{\"id\":141,\"links\":[{\"id\":125,\"weight\":258.1518700205428},{\"id\":140,\"weight\":23.039143895070726},{\"id\":142,\"weight\":70.27931275561932}]},\n{\"id\":142,\"links\":[{\"id\":12,\"weight\":605.3109163530141},{\"id\":17,\"weight\":589.0762111107545},{\"id\":22,\"weight\":308.1360659862511},{\"id\":26,\"weight\":333.7521131385038},{\"id\":39,\"weight\":911.9072364060776},{\"id\":57,\"weight\":206.67779462996376},{\"id\":97,\"weight\":709.2888517760487},{\"id\":100,\"weight\":949.697709689759},{\"id\":131,\"weight\":273.78551731820147},{\"id\":141,\"weight\":70.27931275561932},{\"id\":143,\"weight\":64.98383750211529}]},\n{\"id\":143,\"links\":[{\"id\":101,\"weight\":92.85603330225935},{\"id\":142,\"weight\":64.98383750211529},{\"id\":144,\"weight\":30.097551026293797}]},\n{\"id\":144,\"links\":[{\"id\":143,\"weight\":30.097551026293797},{\"id\":145,\"weight\":100.10632073495346}]},\n{\"id\":145,\"links\":[{\"id\":77,\"weight\":213.64883986492893},{\"id\":102,\"weight\":86.69660180432261},{\"id\":144,\"weight\":100.10632073495346},{\"id\":146,\"weight\":43.76422694558446}]},\n{\"id\":146,\"links\":[{\"id\":36,\"weight\":250.2794421195491},{\"id\":92,\"weight\":572.3906052533645},{\"id\":107,\"weight\":161.5285374896578},{\"id\":145,\"weight\":43.76422694558446},{\"id\":147,\"weight\":62.554721469410964}]},\n{\"id\":147,\"links\":[{\"id\":13,\"weight\":644.3394809974541},{\"id\":22,\"weight\":378.58967001309463},{\"id\":27,\"weight\":349.297544643658},{\"id\":81,\"weight\":350.10072558836436},{\"id\":97,\"weight\":817.6275336689539},{\"id\":146,\"weight\":62.554721469410964},{\"id\":138,\"weight\":60.21879922428856}]},\n{\"id\":148,\"links\":[{\"id\":153,\"weight\":83.09197814327331}]},\n{\"id\":149,\"links\":[{\"id\":28,\"weight\":340.8623984131601},{\"id\":33,\"weight\":324.73490720293273},{\"id\":150,\"weight\":40.27917844217807}]},\n{\"id\":150,\"links\":[{\"id\":47,\"weight\":482.148526864346},{\"id\":52,\"weight\":458.3924820628751},{\"id\":110,\"weight\":133.5176916667986},{\"id\":149,\"weight\":40.27917844217807}]},\n{\"id\":151,\"links\":[{\"id\":152,\"weight\":16.05179269405632}]},\n{\"id\":152,\"links\":[{\"id\":151,\"weight\":16.05179269405632},{\"id\":153,\"weight\":95.08995160516936}]},\n{\"id\":153,\"links\":[{\"id\":3,\"weight\":205.87711451966396},{\"id\":4,\"weight\":737.0774717197235},{\"id\":5,\"weight\":135.6583919878893},{\"id\":112,\"weight\":239.32930481887956},{\"id\":152,\"weight\":95.08995160516936},{\"id\":148,\"weight\":83.09197814327331}]},\n{\"id\":154,\"links\":[{\"id\":11,\"weight\":277.7768610143829},{\"id\":155,\"weight\":33.19341980748434}]},\n{\"id\":155,\"links\":[{\"id\":66,\"weight\":98.46201480548129},{\"id\":97,\"weight\":256.52958550596395},{\"id\":154,\"weight\":33.19341980748434},{\"id\":156,\"weight\":58.397228717203404}]},\n{\"id\":156,\"links\":[{\"id\":19,\"weight\":445.50275071828963},{\"id\":23,\"weight\":424.0775352517563},{\"id\":71,\"weight\":229.10251215735252},{\"id\":131,\"weight\":296.14115910691856},{\"id\":138,\"weight\":645.5864796077194},{\"id\":155,\"weight\":58.397228717203404}]},\n{\"id\":157,\"links\":[{\"id\":10,\"weight\":475.0410693030716},{\"id\":16,\"weight\":434.2784913076533},{\"id\":43,\"weight\":149.3858968154142},{\"id\":70,\"weight\":798.2577975693512},{\"id\":86,\"weight\":337.27659265236},{\"id\":117,\"weight\":242.8128909397011},{\"id\":132,\"weight\":803.2044974295419}]},\n{\"id\":158,\"links\":[{\"id\":57,\"weight\":180.39992938539922},{\"id\":128,\"weight\":35.94532649063341},{\"id\":160,\"weight\":44.1282092957909}]},\n{\"id\":159,\"links\":[{\"id\":10,\"weight\":424.5428223515612},{\"id\":15,\"weight\":416.3689141062264},{\"id\":42,\"weight\":136.50001088374017},{\"id\":70,\"weight\":728.6111329180097},{\"id\":86,\"weight\":264.5824947674739},{\"id\":92,\"weight\":344.37896644057383},{\"id\":95,\"weight\":567.3380419121927},{\"id\":117,\"weight\":170.35193802012466},{\"id\":114,\"weight\":71.39727162164735},{\"id\":132,\"weight\":733.0042344492691},{\"id\":160,\"weight\":112.12052199347016},{\"id\":161,\"weight\":134.34656675925888}]},\n{\"id\":160,\"links\":[{\"id\":10,\"weight\":386.9207320551183},{\"id\":15,\"weight\":344.37793610826577},{\"id\":38,\"weight\":259.95392603739697},{\"id\":41,\"weight\":191.66415098549578},{\"id\":65,\"weight\":638.3194987663459},{\"id\":80,\"weight\":981.0925983047125},{\"id\":86,\"weight\":170.91599639926625},{\"id\":92,\"weight\":232.48237745520552},{\"id\":117,\"weight\":58.715883663506396},{\"id\":115,\"weight\":63.25551243883601},{\"id\":158,\"weight\":44.1282092957909},{\"id\":159,\"weight\":112.12052199347016}]},\n{\"id\":161,\"links\":[{\"id\":10,\"weight\":293.9650424785912},{\"id\":16,\"weight\":262.12088923847034},{\"id\":22,\"weight\":491.24332514971724},{\"id\":43,\"weight\":35.96703115932087},{\"id\":41,\"weight\":42.17582986887332},{\"id\":70,\"weight\":632.6993752105095},{\"id\":87,\"weight\":285.65519727136444},{\"id\":84,\"weight\":262.445211274406},{\"id\":95,\"weight\":434.67294753052647},{\"id\":119,\"weight\":262.52409073917073},{\"id\":114,\"weight\":202.98164149753293},{\"id\":132,\"weight\":639.4014374495188},{\"id\":136,\"weight\":721.2341683340406},{\"id\":159,\"weight\":134.34656675925888}]}]\n\n\nvar get_path = function(graph, a) {\n// declaration\n let cache, i, v, queue, node, links, root,\n j, link, c, n, d, max, w, L = graph.length;\n\n // initialization\n cache = Array(L);\n i = L;\n while (--i &gt;= 0) {\n v = graph[i];\n cache[v.id] = {\n id: v.id,\n distance: Infinity,\n links: v.links,\n prev: null,\n };\n }\n root = cache[a];\n root.distance = 0;\n queue = [root];\n\n // processing\n i = 0;\n while (i &lt; queue.length) {\n node = queue[i];\n links = node.links;\n j = links.length;\n while (--j &gt;= 0) {\n link = links[j];\n c = cache[link.id];\n d = node.distance + link.weight;\n if (d &lt; c.distance) {\n c.prev = node;\n c.distance = d;\n queue.push(c);\n }\n }\n i++;\n }\n\n return cache\n};\n\nvar times = [], newTimes = [];\n\nfor (let i=0; i &lt; 1000; i++) {\n var s_t = performance.now();\n res = get_path(graph, 157);\n times.push(performance.now() - s_t);\n}\n\nfor (let i=0; i &lt; 1000; i++) {\n var s_t = performance.now();\n res = getDistancesFromNode(graph, 157);\n newTimes.push(performance.now() - s_t);\n}\n\n\nfunction average(nums) {\n return nums.reduce((a, b) =&gt; (a + b)) / nums.length;\n}\n\nconsole.log(average(times), 'ms')\nconsole.log(average(newTimes), 'ms')</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T23:43:34.267", "Id": "504421", "Score": "0", "body": "what's wrong with variable name? And can you tell me more details about optimization to make it faster? I should use ```graph``` instead of ```cache```? I am afriad, that it will broke the algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T15:08:07.697", "Id": "504502", "Score": "0", "body": "I rewrote with better variable names, I hope you can appreciate the difference in readability." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T17:58:48.597", "Id": "255614", "ParentId": "255594", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T08:57:34.680", "Id": "255594", "Score": "3", "Tags": [ "javascript", "performance", "graph", "mathematics" ], "Title": "Collect distances from 1 point to all others in a graph" }
255594
<p>I tried implementing the nQueens problem in CUDA, but it is actually slower than the sequential algorithm! What can I do to optimize this? This was run sequentially on an AMD Ryzen 5 4600H (clock speed of 3GHz) and in parallel on an Geforce RTX 1650 (894 cores with a clock speed of 1.5 GHz).</p> <p><strong>Brief introduction to the problem</strong></p> <p>The <a href="https://en.wikipedia.org/wiki/Eight_queens_puzzle" rel="nofollow noreferrer">nQueens problem</a> is about counting the ways we can place n queens on an n by n chessboard without them attacking each other. By placing the queens row by row, we get a tree of solutions, and the solution corresponds to the number of leafs in this tree.</p> <p>It will be convenient notation to denote the set of nodes in the <span class="math-container">\$m\$</span>'th layer of this tree as <span class="math-container">\$T_m\$</span>.</p> <p>A subtree associated to a node x, is defined as all nodes y, whose unique path to the root of the tree hits x. The sequential algorithm is a recursive function nQueens that takes a node and returns the number of leafs in such a subtree. That function uses 3 numbers to encode a node, and is optimized, so I don't need feedback on that. If you're interested, <a href="https://www.cl.cam.ac.uk/%7Emr10/backtrk.pdf" rel="nofollow noreferrer">here</a> is an article explaining it.</p> <p><strong>Parallellisation</strong></p> <p>A path from a leaf to the root hits precisely one node in each layer, so the total amount of leafs is</p> <p><span class="math-container">$$\sum_{x \in T_m} nQueens(x) $$</span></p> <p>for any <span class="math-container">\$m\$</span>. We distribute <span class="math-container">\$T_m\$</span> over the processors and have each calculate nQueens on those nodes, and then add together the results.</p> <p><strong>Code</strong></p> <p>(I use symmetry to cut the computation time by half, but that is not really important.)</p> <pre><code>#include &quot;cuda_runtime.h&quot; #include &quot;device_launch_parameters.h&quot; #include &lt;iostream&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;vector&gt; #include &lt;string&gt; #define N 16 // Board size #define DONE 65535 // 2^N - 1 // Counts the number of non-zero bits in n int countBits(long n) { int counter = 0; while (n) { n &amp;= (n - 1); // This deletes the rightmost non-zero digit counter++; } return counter; } /* Given the diagonals and columns attacked by the already placed queens in bit form, returns the amount of solutions. So for the arguments 0, it finds all solutions, for 1, 2, 4 it finds all solutions with the first queen at the second column, etc. */ __host__ __device__ long nQueens(long leftDiagonal, long column, long rightDiagonal) { long counter = 0; // When all columns are occupied, we have found a solution if (column == DONE) { return 1; } // the binary representation has a 1 on the places we can put a queen long possibilities = ~(leftDiagonal | column | rightDiagonal) &amp; DONE; // &amp; DONE to get rid of bits beyond N and fractions // stops when possibilities is 0, so when there are no possibilities anymore while (possibilities) { long bit = possibilities &amp; (~possibilities + 1); // The right most non-zero bit in possibilities, the queen we place possibilities -= bit; // We have placed this queen, so remove it from the possibilities counter += nQueens((leftDiagonal | bit) &gt;&gt; 1, (column | bit), (rightDiagonal | bit) &lt;&lt; 1); // We add the solution and shift the diagonals because the // queens attack diagonally one place further in the next row } return counter; } // Fills nodes with nodes in the k'th layer long kLayer(std::vector&lt;long&gt;&amp; nodes, int k, long leftDiagonal, long column, long rightDiagonal) { long counter = 0; // When all columns are occupied, we have found a solution if (countBits(column) == k) { nodes.push_back(leftDiagonal); nodes.push_back(column); nodes.push_back(rightDiagonal); return 1; } // the binary representation has a 1 on the places we can put a queen long possibilities = ~(leftDiagonal | column | rightDiagonal) &amp; DONE; // &amp; DONE to get rid of bits beyond N and fractions // stops when possibilities is 0, so when there are no possibilities anymore while (possibilities) { long bit = possibilities &amp; (~possibilities + 1); // The right most non-zero bit in possibilities, the queen we place possibilities -= bit; // We have placed this queen, so remove it from the possibilities counter += kLayer(nodes, k, (leftDiagonal | bit) &gt;&gt; 1, (column | bit), (rightDiagonal | bit) &lt;&lt; 1); // We add the solution and shift the diagonals because the // queens attack diagonally one place further in the next row } return counter; } // Returns a vector with all the nodes in the k'th layer std::vector&lt;long&gt; kLayer(int k) { std::vector&lt;long&gt; nodes{}; kLayer(nodes, k, 0, 0, 0); return nodes; } // Takes an array of the nodes, an empty array solutions, where we fill the i'th member with the solutions // in the i'th subtree. __global__ void calculateSolutions(long* nodes, long* solutions, int numElements) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i &lt; numElements) { solutions[i] = nQueens(nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]); } } int main() { // Vector of nodes (each encoded by 3 consecutive numbers) in the 3'rd layer of the tree. std::vector&lt;long&gt; nodes = kLayer(4); // from layer 2 onwards we have an even amount of nodes in that layer, so we can use symmetry. // Layer 4 contains enough nodes (for N = 16, 9844). // There are no classes on the device, so we point to the first element and then copy to the device. size_t nodeSize = nodes.size() * sizeof(long); long* hostNodes = (long*)malloc(nodeSize); hostNodes = &amp;nodes[0]; long* deviceNodes = NULL; cudaMalloc((void**)&amp;deviceNodes, nodeSize); cudaMemcpy(deviceNodes, hostNodes, nodeSize, cudaMemcpyHostToDevice); // Allocate the device output long* deviceSolutions = NULL; int numSolutions = nodes.size() / 6; // We only need half of the nodes, and each node is encoded by 3 integers. size_t solutionSize = numSolutions * sizeof(long); cudaMalloc((void**)&amp;deviceSolutions, solutionSize); // Launch the nQueens CUDA Kernel int threadsPerBlock = 256; int blocksPerGrid = (numSolutions + threadsPerBlock - 1) / threadsPerBlock; calculateSolutions &lt;&lt;&lt;blocksPerGrid, threadsPerBlock &gt;&gt;&gt; (deviceNodes, deviceSolutions, numSolutions); // Copy results to host long* hostSolutions = (long*)malloc(solutionSize); cudaMemcpy(hostSolutions, deviceSolutions, solutionSize, cudaMemcpyDeviceToHost); // Add the subsolutions and print the result long solutions = 0; for (long i = 0; i &lt; numSolutions; i++) { solutions += 2*hostSolutions[i]; // Symmetry } std::cout &lt;&lt; &quot;We have &quot; &lt;&lt; solutions &lt;&lt; &quot; solutions on a &quot; &lt;&lt; N &lt;&lt; &quot; by &quot; &lt;&lt; N &lt;&lt; &quot; board.&quot; &lt;&lt; std::endl; return 0; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T12:06:33.903", "Id": "255596", "Score": "3", "Tags": [ "c++", "beginner", "cuda" ], "Title": "The nQueens problem in CUDA" }
255596
<p>Hackerrank problem to reverse an array of size <code>n</code>. <a href="https://www.hackerrank.com/challenges/30-arrays/" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/30-arrays/</a></p> <p>Sample Input:</p> <pre><code>4 1 4 3 2 </code></pre> <p>Sample output:</p> <pre><code>2 3 4 1 </code></pre> <p><strong>Much of this code was already given, you can skip to the &quot;This is what I did&quot; section.</strong></p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; vector&lt;string&gt; split_string(string); int main() { int n; cin &gt;&gt; n; cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'); string arr_temp_temp; getline(cin, arr_temp_temp); vector&lt;string&gt; arr_temp = split_string(arr_temp_temp); vector&lt;int&gt; arr(n); vector&lt;int&gt; arr2(n); for (int i = 0; i &lt; n; i++) { int arr_item = stoi(arr_temp[i]); arr[i] = arr_item; } for (int i = 0; i &lt;= n; i++){ arr2[n-i] = arr[i]; } for (int i = 1; i &lt;= n; i++){ cout &lt;&lt; arr2[i] &lt;&lt; &quot; &quot;; } return 0; } vector&lt;string&gt; split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &amp;x, const char &amp;y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector&lt;string&gt; splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; } </code></pre> <h3>This is what I did</h3> <p>I declared another array named <code>array2</code> of size <code>n</code> to hold the reversed value which would then be printed. I then wrote this snippet to reverse the array and copy it to <code>array2</code>:</p> <pre><code> for (int i = 0; i &lt;= n; i++){ arr2[n-i] = arr[i]; } for (int i = 1; i &lt;= n; i++){ cout &lt;&lt; arr2[i] &lt;&lt; &quot; &quot;; } </code></pre> <p>This code works, but I feel like I have made a mistake since I have iterated <code>n+1</code> times in the <code>for</code> loop. I tried iterating <code>n</code> times but one element of the array got the value <code>0</code>. Indexing is also done differently since I am indexing from <code>1</code> to <code>n</code>. This is confusing to me, because I declared <code>array2</code> as size <code>n</code>. How and when did the vector get resized?</p> <p>Is there a more elegant solution using <code>n</code> iterations? If not, why not?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T15:02:59.473", "Id": "504378", "Score": "2", "body": "It is indeed wrong because arr2[n] is not well defined. In your original solution, did you have arr2[n - 1 - i] and not arr2[n - i]? Remember, we start counting from 0, so the index of the last element in the array is n - 1, not n." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T15:06:18.720", "Id": "504379", "Score": "0", "body": "@PeldePinda, thanks." } ]
[ { "body": "<p>Instead of copying into another array, you could just print the original array in reverse way like below:</p>\n<pre><code>for (int i = 0; i &lt; n; ++i)\n std::cout &lt;&lt; arr[n - i - 1] &lt;&lt; &quot; &quot;;\nstd::cout &lt;&lt; &quot;\\n&quot; &lt;&lt; std::endl;\n</code></pre>\n<p>Also in your original code you're accessing vector out of bounds which may result in crash.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T14:56:31.867", "Id": "255604", "ParentId": "255602", "Score": "1" } }, { "body": "<p>Change the index like so:</p>\n<pre><code>for (int i = 0; i &lt; n; ++i){\n arr2[n-i-1] = arr[i]; \n }\n for (int i = 0; i &lt; n; ++i){\n cout &lt;&lt; arr2[i] &lt;&lt; &quot; &quot;; \n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T15:04:50.703", "Id": "255605", "ParentId": "255602", "Score": "0" } }, { "body": "<p>The first couple of lines show that this is shoddy code:</p>\n<blockquote>\n<pre><code>#include &lt;bits/stdc++.h&gt;\n\nusing namespace std;\n</code></pre>\n</blockquote>\n<p><code>&lt;bits/stdc++.h&gt;</code> is not a standard header, and dragging all of <code>std</code> into the default namespace is a maintainability disaster (see other Code Review answers, ad nauseum).</p>\n<p>None of the code which reads from <code>std::cin</code> ever checks whether the reading was successful, and there's no error handling whatsoever.</p>\n<p><code>arr</code> is a terrible name for a <em>vector</em>. <code>arr2</code> is worse.</p>\n<p>There's no need for handcrafted loops, when we could use <code>std::copy_n()</code> to read elements, and <code>std::reverse()</code> to reorder them.</p>\n<p>Actually, there's no need to reorder the stored data - just write the output using a reverse iterator.</p>\n<hr />\n<p>The low quality shows up when we analyse the memory accesses:</p>\n<pre class=\"lang-none prettyprint-override\"><code>valgrind ./255602 &lt;&lt;&lt;$'4\\n1 4 3 2 5'\n==5474== Memcheck, a memory error detector\n==5474== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==5474== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info\n==5474== Command: ./255602-orig\n==5474== \n==5474== Invalid write of size 4\n==5474== at 0x10B466: main (255602.cpp:30)\n==5474== Address 0x4d49000 is 0 bytes after a block of size 16 alloc'd\n==5474== at 0x480BDEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==5474== by 0x10E741: __gnu_cxx::new_allocator&lt;int&gt;::allocate(unsigned long, void const*) (new_allocator.h:115)\n==5474== by 0x10E437: allocate (allocator.h:173)\n==5474== by 0x10E437: std::allocator_traits&lt;std::allocator&lt;int&gt; &gt;::allocate(std::allocator&lt;int&gt;&amp;, unsigned long) (alloc_traits.h:460)\n==5474== by 0x10DE3F: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_allocate(unsigned long) (stl_vector.h:346)\n==5474== by 0x10D60C: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_create_storage(unsigned long) (stl_vector.h:361)\n==5474== by 0x10CEA0: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_Vector_base(unsigned long, std::allocator&lt;int&gt; const&amp;) (stl_vector.h:305)\n==5474== by 0x10C46C: std::vector&lt;int, std::allocator&lt;int&gt; &gt;::vector(unsigned long, std::allocator&lt;int&gt; const&amp;) (stl_vector.h:511)\n==5474== by 0x10B3B6: main (255602.cpp:21)\n==5474== \n==5474== Invalid read of size 4\n==5474== at 0x10B449: main (255602.cpp:30)\n==5474== Address 0x4d48fb0 is 0 bytes after a block of size 16 alloc'd\n==5474== at 0x480BDEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==5474== by 0x10E741: __gnu_cxx::new_allocator&lt;int&gt;::allocate(unsigned long, void const*) (new_allocator.h:115)\n==5474== by 0x10E437: allocate (allocator.h:173)\n==5474== by 0x10E437: std::allocator_traits&lt;std::allocator&lt;int&gt; &gt;::allocate(std::allocator&lt;int&gt;&amp;, unsigned long) (alloc_traits.h:460)\n==5474== by 0x10DE3F: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_allocate(unsigned long) (stl_vector.h:346)\n==5474== by 0x10D60C: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_create_storage(unsigned long) (stl_vector.h:361)\n==5474== by 0x10CEA0: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_Vector_base(unsigned long, std::allocator&lt;int&gt; const&amp;) (stl_vector.h:305)\n==5474== by 0x10C46C: std::vector&lt;int, std::allocator&lt;int&gt; &gt;::vector(unsigned long, std::allocator&lt;int&gt; const&amp;) (stl_vector.h:511)\n==5474== by 0x10B382: main (255602.cpp:20)\n==5474== \n==5474== Invalid read of size 4\n==5474== at 0x10B495: main (255602.cpp:33)\n==5474== Address 0x4d49000 is 0 bytes after a block of size 16 alloc'd\n==5474== at 0x480BDEF: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==5474== by 0x10E741: __gnu_cxx::new_allocator&lt;int&gt;::allocate(unsigned long, void const*) (new_allocator.h:115)\n==5474== by 0x10E437: allocate (allocator.h:173)\n==5474== by 0x10E437: std::allocator_traits&lt;std::allocator&lt;int&gt; &gt;::allocate(std::allocator&lt;int&gt;&amp;, unsigned long) (alloc_traits.h:460)\n==5474== by 0x10DE3F: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_allocate(unsigned long) (stl_vector.h:346)\n==5474== by 0x10D60C: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_M_create_storage(unsigned long) (stl_vector.h:361)\n==5474== by 0x10CEA0: std::_Vector_base&lt;int, std::allocator&lt;int&gt; &gt;::_Vector_base(unsigned long, std::allocator&lt;int&gt; const&amp;) (stl_vector.h:305)\n==5474== by 0x10C46C: std::vector&lt;int, std::allocator&lt;int&gt; &gt;::vector(unsigned long, std::allocator&lt;int&gt; const&amp;) (stl_vector.h:511)\n==5474== by 0x10B3B6: main (255602.cpp:21)\n==5474== \n2 3 4 1 ==5474== \n==5474== HEAP SUMMARY:\n==5474== in use at exit: 0 bytes in 0 blocks\n==5474== total heap usage: 9 allocs, 9 frees, 78,336 bytes allocated\n==5474== \n==5474== All heap blocks were freed -- no leaks are possible\n==5474== \n==5474== For counts of detected and suppressed errors, rerun with: -v\n==5474== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)\n</code></pre>\n<p>Such failures fall short of <em>working</em>, in my opinion.</p>\n<hr />\n<p>This is what a decent C++ program to do this looks like:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nint main()\n{\n // read the inputs\n std::size_t n;\n std::cin &gt;&gt; n;\n if (!std::cin) {\n std::cerr &lt;&lt; &quot;Failed to read number of elements\\n&quot;;\n return EXIT_FAILURE;\n }\n\n std::vector&lt;std::string&gt; elements;\n elements.reserve(n);\n std::copy_n(std::istream_iterator&lt;std::string&gt;{std::cin},\n n, std::back_inserter(elements));\n if (!std::cin) {\n std::cerr &lt;&lt; &quot;Failed to read element content\\n&quot;;\n return EXIT_FAILURE;\n }\n\n // write the values, in reverse order\n std::copy(elements.crbegin(), elements.crend(),\n std::ostream_iterator&lt;std::string&gt;{std::cout, &quot; &quot;});\n}\n</code></pre>\n<p>See - no loops or arithmetic required.</p>\n<p>Or, if you prefer an exception-based error handling strategy:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\n// read size from stream, then read that many elements into a vector\ntemplate&lt;typename T&gt;\nstd::vector&lt;T&gt; read_size_and_vector(std::istream&amp; is)\n{\n std::size_t n;\n is &gt;&gt; n;\n std::vector&lt;T&gt; elements;\n elements.reserve(n);\n std::copy_n(std::istream_iterator&lt;T&gt;{is}, n, std::back_inserter(elements));\n return elements;\n}\n\nint main()\n{\n std::cin.exceptions(std::istream::badbit|std::istream::failbit);\n try {\n auto const elements = read_size_and_vector&lt;std::string&gt;(std::cin);\n std::copy(elements.rbegin(), elements.rend(),\n std::ostream_iterator&lt;std::string&gt;{std::cout, &quot; &quot;});\n return EXIT_SUCCESS;\n } catch (std::ios_base::failure&amp;) {\n std::cerr &lt;&lt; &quot;Failed to read the input\\n&quot;;\n return EXIT_FAILURE;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T16:54:46.797", "Id": "255608", "ParentId": "255602", "Score": "4" } } ]
{ "AcceptedAnswerId": "255608", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T14:06:10.923", "Id": "255602", "Score": "0", "Tags": [ "c++", "c++14" ], "Title": "Reversing an array in C++ 14, my second array requires an extra element" }
255602
<p>I believe this set of code is very repetitive in a way where every method does almost the same task but it is repeated multiple times. This is what the code looks like and its main purpose is to display the intended design on the simulator:</p> <pre><code>private void configStart() { button1 = new JButton(&quot;start&quot;); button1.setBackground(Color.lightGray); button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(vehicle == null) { int selectedIndex = combobox.getSelectedIndex(); String vehicleName = vehicles[selectedIndex]; initialiseVehicle(vehicleName); speedlabel.setText(vehicle.printSpeed()); } if(simulationPane !=null) { frame.remove(simulationPane); } accelerate = false; decelerate = false; cruise = false; stop = false; button1.setBackground(Color.GREEN); button2.setBackground(Color.lightGray); button3.setBackground(Color.lightGray); button4.setBackground(Color.lightGray); button5.setBackground(Color.lightGray); simulationPane = new Simulator(); frame.add(simulationPane,BorderLayout.CENTER); frame.revalidate(); frame.repaint(); } }); } private void configAccelerate() { button2 = new JButton(&quot;accelerate&quot;); button2.setBackground(Color.lightGray); button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { accelerate = true; decelerate = false; cruise = false; stop = false; button1.setBackground(Color.lightGray); button2.setBackground(Color.green); button3.setBackground(Color.lightGray); button4.setBackground(Color.lightGray); button5.setBackground(Color.lightGray); Thread thread = new Thread(){ public void run(){ try { while(accelerate) { Thread.sleep(2 * 1000); if(currentvelocity&lt;=maximumvelocity) { currentvelocity = currentvelocity +1; vehicle.setCurrentSpeed(currentvelocity); speedlabel.setText(vehicle.printSpeed()); simulationPane.updateTimer(); } } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); } }); } private void configCruise() { button3 = new JButton(&quot;cruise&quot;); button3.setBackground(Color.lightGray); button3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { accelerate = false; decelerate = false; cruise = true; stop = false; button1.setBackground(Color.lightGray); button2.setBackground(Color.lightGray); button3.setBackground(Color.green); button4.setBackground(Color.lightGray); button5.setBackground(Color.lightGray); } }); } private void configDecelerate() { button4 = new JButton(&quot;decelerate&quot;); button4.setBackground(Color.lightGray); button4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { accelerate = false; decelerate = true; cruise = false; stop = false; button1.setBackground(Color.lightGray); button2.setBackground(Color.lightGray); button3.setBackground(Color.lightGray); button4.setBackground(Color.green); button5.setBackground(Color.lightGray); Thread thread = new Thread(){ public void run(){ try { while(decelerate) { Thread.sleep(2 * 1000); if(currentvelocity &gt;1) { currentvelocity = currentvelocity -1; vehicle.setCurrentSpeed(currentvelocity); speedlabel.setText(vehicle.printSpeed()); simulationPane.updateTimer(); } } } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); } }); } private void configStop() { button5 = new JButton(&quot;stop&quot;); button5.setBackground(Color.lightGray); button5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { accelerate = false; decelerate = false; cruise = false; stop = true; button1.setBackground(Color.lightGray); button2.setBackground(Color.lightGray); button3.setBackground(Color.lightGray); button4.setBackground(Color.lightGray); button5.setBackground(Color.green); currentvelocity = 1; vehicle.setCurrentSpeed(currentvelocity); speedlabel.setText(vehicle.printSpeed()); simulationPane.updateTimer(); } }); } </code></pre> <p>I would like to ask how it can be refactored to increase its modularity or reduce complexity. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T14:18:28.560", "Id": "504372", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T14:19:01.870", "Id": "504373", "Score": "1", "body": "Code Review requires concrete code from a project, **with sufficient context for reviewers to understand how that code is used**. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[ { "body": "<p>Since I cannot compile this code, there might be small mistakes in my code. I'm not writing Java for a long time. Hope it helps.</p>\n<p>I see your buttons work as a state machine, so I created a <code>enum</code> called <code>ButtonState</code> to represent each state:</p>\n<pre><code>enum ButtonState {\n Start,\n Accelerate,\n Cruise,\n Decelerate,\n Stop;\n}\n</code></pre>\n<p>I see you have a bunch of buttons named like button1, button2 ... etc. Don't name your variables with numbers. Instead name them with their associated actions, like startButton, accelerateButton etc. If you have a cluster of variables with same type, it indicates that you can store them in a container. I used array in this example. Since there is a button for each state we know the size of buttons:</p>\n<p><code>JButton[] buttons = new JButton[ButtonState.values().length()];</code>.</p>\n<p>To initialize buttons we can iterate through states:</p>\n<pre><code>for (ButtonState state : ButtonState.values()) {\n JButton button = new JButton(state.name().toLowerCase()); // button name\n button.setBackground(Color.lightGray); // button color\n button.addActionListener(...); // button action\n buttons[state.ordinal()] = button;\n}\n</code></pre>\n<p>You can get buttons with state ordinals, let's say you want to get cruise button, you can get it like <code>buttons[ButtonState.Cruise.ordinal()]</code>.</p>\n<p>I see you have a boolean variables for each state(except start). Let's assume you also have <code>bool start</code> to complete pattern. I see only one of them gets true and others get false each time. So instead of having booleans for each of state, we can have only one state that represents which state is true. In this case it is <code>ButtonState state</code>.</p>\n<p>Before:</p>\n<pre><code>accelerate = false;\ndecelerate = true;\ncruise = false;\nstop = false;\n</code></pre>\n<p>After:</p>\n<pre><code>state = ButtonState.Decelerate;\n</code></pre>\n<p>Before:</p>\n<pre><code>if (decelerate)\n</code></pre>\n<p>After:</p>\n<pre><code>if (state == ButtonState.Decelerate)\n</code></pre>\n<p>Now we can get rid of most repetitive pattern in your code: Setting a state boolean and highlighting the corresponding button. Let's gather it in a function:</p>\n<pre><code>private void setState(ButtonState state) {\n this.buttons[this.state.ordinal()].setBackground(Color.lightGray); // fade highlighted button\n this.buttons[state.ordinal()].setBackground(Color.green); // highlight new state button\n this.state = state; // set state\n}\n</code></pre>\n<p>Before:</p>\n<pre><code>accelerate = true;\ndecelerate = false;\ncruise = false;\nstop = false;\n\nbutton1.setBackground(Color.lightGray);\nbutton2.setBackground(Color.green);\nbutton3.setBackground(Color.lightGray);\nbutton4.setBackground(Color.lightGray);\nbutton5.setBackground(Color.lightGray);\n</code></pre>\n<p>After:</p>\n<pre><code>this.setState(ButtonState.Accelerate);\n</code></pre>\n<p>Bonus: In a scenario where multiple states combined, like accelerating and cruising at the same time, enums with bit flags can be used.</p>\n<p><strong>Refactored Code</strong></p>\n<pre><code>enum ButtonState {\n Start,\n Accelerate,\n Cruise,\n Decelerate,\n Stop;\n}\n\nprivate JButton[] buttons;\nprivate ButtonState state;\n\nprivate void setState(ButtonState state) {\n this.buttons[this.state.ordinal()].setBackground(Color.lightGray);\n this.buttons[state.ordinal()].setBackground(Color.green);\n this.state = state;\n}\n\nprivate void configButtons() {\n this.buttons = new JButton[ButtonState.values().length()];\n \n for (ButtonState state : ButtonState.values()) {\n JButton button = new JButton(state.name().toLowerCase());\n button.setBackground(Color.lightGray);\n \n switch(state) {\n case Start: \n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n start(e);\n }\n });\n break;\n \n case Accelerate: \n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n accelerate(e);\n }\n });\n break;\n \n case Cruise: return\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n cruise(e);\n }\n });\n break;\n \n case Decelerate:\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n decelerate(e);\n }\n });\n break;\n \n case Stop:\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n stop(e);\n }\n });\n break;\n }\n \n this.buttons[state.ordinal()] = button;\n }\n}\n\nprivate void start(ActionEvent e) {\n if(vehicle == null) {\n int selectedIndex = combobox.getSelectedIndex();\n String vehicleName = vehicles[selectedIndex];\n initialiseVehicle(vehicleName);\n speedlabel.setText(vehicle.printSpeed());\n }\n \n if(simulationPane !=null) {\n frame.remove(simulationPane);\n }\n \n this.setState(ButtonState.Start);\n\n simulationPane = new Simulator();\n frame.add(simulationPane,BorderLayout.CENTER);\n frame.revalidate();\n frame.repaint();\n}\n\nprivate void accelerate(ActionEvent e) {\n this.setState(ButtonState.Accelerate);\n\n Thread thread = new Thread(){\n public void run(){\n try {\n while(accelerate) {\n Thread.sleep(2 * 1000);\n\n if(currentvelocity&lt;=maximumvelocity) {\n currentvelocity = currentvelocity +1;\n vehicle.setCurrentSpeed(currentvelocity);\n speedlabel.setText(vehicle.printSpeed());\n simulationPane.updateTimer();\n } \n }\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n } \n }\n };\n\n thread.start();\n}\n\nprivate void cruise(ActionEvent e) {\n this.setState(ButtonState.Cruise);\n}\n\nprivate void decelerate(ActionEvent e) {\n this.setState(ButtonState.Decelerate);\n \n Thread thread = new Thread(){\n public void run(){\n try {\n while(decelerate) {\n Thread.sleep(2 * 1000);\n\n if(currentvelocity &gt;1) {\n currentvelocity = currentvelocity -1;\n vehicle.setCurrentSpeed(currentvelocity);\n speedlabel.setText(vehicle.printSpeed());\n simulationPane.updateTimer();\n } \n }\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n } \n }\n };\n\n thread.start();\n}\n\nprivate void stop(ActionEvent e) {\n this.setState(ButtonState.Stop);\n \n currentvelocity = 1;\n vehicle.setCurrentSpeed(currentvelocity);\n speedlabel.setText(vehicle.printSpeed());\n simulationPane.updateTimer();\n}\n</code></pre>\n<p>Happy Coding;P</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:46:58.067", "Id": "504446", "Score": "1", "body": "(`Since I cannot compile this code` more and more online compilation services are available (e.g., [tutorialspoint.com](https://www.tutorialspoint.com/compile_java_online.php)).)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:00:03.720", "Id": "504452", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T10:01:57.703", "Id": "504458", "Score": "0", "body": "@greybeard I don't know how rest of class looks like, there are lots of members I have no idea about them, plus I have to import packages for `JButton` etc. More explanatory edit incoming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T10:43:07.007", "Id": "504721", "Score": "0", "body": "@greybeard Have you even looked at the original code? I encourage you to actually try compiling it on Tutorialspoint. It just gives a continuous stream of errors. And even if those were fixed, it's a GUI. While it is barely possible to [compile a GUI online](https://stackoverflow.com/q/55953691/6660678) (see repl.it ), Tutorialspoint can't. I realize that you may be busy. But if you don't have time to glance at the code, perhaps you shouldn't have time to post. As is, you have simply been gratuitously rude." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T23:37:48.190", "Id": "255631", "ParentId": "255603", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T14:07:20.750", "Id": "255603", "Score": "1", "Tags": [ "java", "object-oriented" ], "Title": "How should I refactor my code to increase its modularity or reduce complexity?" }
255603
<p>I wrote my own implementation of generic hash table. I’m using linked list to resolve collision problem. I want to share my code with you and get your opinion about it, and if there are any advice or optimisations that you can point to.</p> <p>HashTable.h file</p> <pre><code>/** * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @Copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Feb 2021 */ #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* hash table node definition */ typedef struct _node { unsigned char *key; void *value; struct _node *next; } ht_node_t; /* hash table definition */ typedef struct { unsigned int size; unsigned int count; ht_node_t **items; } ht_table_t; /** * create new hash table with given size * @param size items table size * @return pointer to creates hash table */ ht_table_t* ht_create(int size); /** * create items table index from given key * @param key key value * @return index of items table between 0 and table size-1 */ unsigned int ht_hash(unsigned int maxSize, unsigned char *key); /** * inset new element to hash table by given key * @param table pointer to created hash table * @param key key for value to insert * @param value element to be inserted * @param size size of element in bytes * @return 1: inserted successfully * 0: error occured while inserting value */ unsigned char ht_insert(ht_table_t* table, unsigned char *key, void *value, size_t size); /** * find associated node to given key * @param table pointer to hash table * @param key key associated to the node * @param index index of found node in items table * @param prev pointer to previous node * @return node pointer if found or NULL otherwise */ ht_node_t* ht_find_node(ht_table_t* table, unsigned char *key, unsigned int *index, ht_node_t **prev); /** * find value in hash table by given key * @param table pointer to hash table * @param key key of the value searching */ void* ht_find(ht_table_t* table, unsigned char *key); /** * delete value by given key * @param table pointer to hash table * @param key value's key to delete * @return 1: deleted successfully * 0: error occured while deleting the value */ unsigned char ht_delete(ht_table_t* table, unsigned char *key); /** * delete all table items * @param table pointer to hash table */ unsigned char ht_delete_all(ht_table_t* table); /** * free allocated memory for given hash table * @param table pointer to hash table */ unsigned char ht_free(ht_table_t* table); </code></pre> <p>HashTable.c file</p> <pre><code>/** * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @Copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Feb 2021 */ #include &quot;hashTable.h&quot; /** * create new hash table with given size * @param size items table size * @return pointer to creates hash table */ ht_table_t* ht_create(int size) { // check given table items size, should be greather than 0 if(size &lt;= 0) return NULL; // create new hash table ht_table_t* table = (ht_table_t*) malloc(sizeof(ht_table_t)); table-&gt;size = size; table-&gt;count = 0; // create items table as pointer's table to nodes table-&gt;items = (ht_node_t**) malloc(size * sizeof(ht_node_t*)); // set all items pointers to NULL for(int i=0; i&lt;size; ++i) table-&gt;items[i] = NULL; // return created table return table; } /** * create items table index from given key * @param key key value * @return index of items table between 0 and table size-1 */ unsigned int ht_hash(unsigned int maxSize, unsigned char *key) { unsigned int hashedKey = 0; // create hash from key for(; *key != '\0'; ++key) hashedKey = (hashedKey * 19 + *key) % maxSize; // return created index return hashedKey; } /** * inset new element to hash table by given key * @param table pointer to created hash table * @param key key for value to insert * @param value element to be inserted * @param size size of element in bytes * @return 1: inserted successfully * 0: error occured while inserting value */ unsigned char ht_insert(ht_table_t* table, unsigned char *key, void *value, size_t size) { // check table and key are not NULL if(!table || !key) return 0; // index from key unsigned int index; // check whether the element with associated key already in table and get generated index ht_node_t *newNode = ht_find_node(table, key, &amp;index, NULL); if(newNode) { // reallocate memory for new content value newNode-&gt;value = (void*) realloc(newNode-&gt;value, size); // copy value to allocated node value memory memcpy(newNode-&gt;value, value, size); } else { // create new node newNode = (ht_node_t*) malloc(sizeof(ht_node_t)); // create node key and copy it's value newNode-&gt;key = (char*) malloc(strlen(key) + 1); strcpy(newNode-&gt;key, key); // create node value memory newNode-&gt;value = (void*) malloc(size); // copy value to allocated node value memory memcpy(newNode-&gt;value, value, size); // if index position is not empty link nodes if(table-&gt;items[index] != NULL) newNode-&gt;next = table-&gt;items[index]; else newNode-&gt;next = NULL; // add created node to items table table-&gt;items[index] = newNode; // increment table count ++table-&gt;count; } return 1; } /** * find associated node to given key * @param table pointer to hash table * @param key key associated to the node * @param index index of found node in items table * @param prev pointer to previous node * @return node pointer if found or NULL otherwise */ ht_node_t* ht_find_node(ht_table_t* table, unsigned char *key, unsigned int *index, ht_node_t **prev) { // get index for given key unsigned int _index = ht_hash(table-&gt;size, key); if(index) *index = _index; // get head items at index position ht_node_t* currentNode = table-&gt;items[_index]; ht_node_t* _prev = NULL; // search in linked array nodes until a NULL pointer while(currentNode) { if(strcmp(currentNode-&gt;key, key) == 0) break; // go to next linked node _prev = currentNode; currentNode = currentNode-&gt;next; } if(currentNode) { if(prev) *prev = _prev; // return found node return currentNode; } // value associated with the key not found return NULL; } /** * find value in hash table by given key * @param table pointer to hash table * @param key key of the value searching */ void* ht_find(ht_table_t* table, unsigned char *key) { // check table and key are not NULL if(!table || !key) return NULL; // get associated node to key ht_node_t *currentNode = ht_find_node(table, key, NULL, NULL); // node not found if(!currentNode) return NULL; // return node's value return currentNode-&gt;value; } /** * delete value by given key * @param table pointer to hash table * @param key value's key to delete * @return 1: deleted successfully * 0: error occured while deleting the value */ unsigned char ht_delete(ht_table_t* table, unsigned char *key) { // check table and key are not NULL if(!table || !key) return 0; ht_node_t *prevNode; unsigned int index; // get associated node to key ht_node_t* currentNode = ht_find_node(table, key, &amp;index, &amp;prevNode); // node not found if(!currentNode) return 0; // set previous node next element to current node next element if(currentNode-&gt;next != NULL) { if(prevNode != NULL) prevNode-&gt;next = currentNode-&gt;next; else table-&gt;items[index] = currentNode-&gt;next; } else if(prevNode == NULL) table-&gt;items[index] = NULL; // delete node free(currentNode-&gt;key); free(currentNode-&gt;value); free(currentNode); // decrement table count --table-&gt;count; return 1; } /** * delete all table items * @param table pointer to hash table */ unsigned char ht_delete_all(ht_table_t* table) { // check table is not NULL if(!table) return 0; // delete table items if not empty if(table-&gt;count != 0) { ht_node_t *currentNode = NULL, *nextNode = NULL; for (int i=0; i&lt;table-&gt;size; ++i) { // get next node nextNode = table-&gt;items[i]; while(nextNode) { currentNode = nextNode; nextNode = currentNode-&gt;next; // free memory allocated by current node free(currentNode-&gt;key); free(currentNode-&gt;value); free(currentNode); } table-&gt;items[i] = NULL; } // set table count to 0 table-&gt;count = 0; } } /** * free allocated memory for given hash table * @param table pointer to hash table */ unsigned char ht_free(ht_table_t* table) { // check table is not NULL if(!table) return 0; // delete table items if not empty if(table-&gt;count != 0) ht_delete_all(table); // free table parts free(table-&gt;items); free(table); return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T02:19:14.233", "Id": "504426", "Score": "0", "body": "why are you returning `unsigned char`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T11:57:34.157", "Id": "504473", "Score": "0", "body": "@IrAM to return just a byte of data" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T15:49:08.903", "Id": "255606", "Score": "2", "Tags": [ "c", "linked-list", "hash-map" ], "Title": "Hash table library implementation" }
255606
<p>I'm creating a class which has a raw pointer member which comes from a C function. In order to make it RAII approved, I just created a method <code>free()</code> that is called on the destructor of this class.</p> <p>Reading some guidelines I came across that Rule of 5 (and Rule of 3) which, from my understanding, I should also create a bunch of constructors and operator overloadings.</p> <p>This is what I've done:</p> <pre><code>/* header */ class SDL2_Font { public: SDL2_Font() {} SDL2_Font(const SDL2_Font&amp; other); // copy constructor SDL2_Font(SDL2_Font&amp;&amp; other); // move constructor ~SDL2_Font() { free(); } SDL2_Font&amp; operator=(const SDL2_Font&amp; other); // copy assignment SDL2_Font&amp; operator=(SDL2_Font&amp;&amp; other); // move assignment bool loadFont(const std::string&amp; path, int size); // more stuff private: void free(); TTF_Font* font_ = nullptr; FontInfo font_info_ {}; std::string path_ {}; int size_ = 0; } /* cpp file */ SDL2_Font::SDL2_Font(const SDL2_Font&amp; other) { if (other.font_ != nullptr) { SDL2_Font::loadFont(other.path_, other.size_); } } SDL2_Font::SDL2_Font(SDL2_Font&amp;&amp; other): font_{other.font_} { other.font_ = nullptr; } SDL2_Font&amp; SDL2_Font::operator=(const SDL2_Font&amp; other) { if (&amp;other != this &amp;&amp; other.font_ != nullptr) { SDL2_Font::loadFont(other.path_, other.size_); } return *this; } SDL2_Font&amp; SDL2_Font::operator=(SDL2_Font&amp;&amp; other) { if (&amp;other != this) { SDL2_Font::free(); font_ = other.font_; other.font_ = nullptr; } return *this; } void SDL2_Font::free() { if (font_ != nullptr &amp;&amp; TTF_WasInit()) { TTF_CloseFont(font_); font_ = nullptr; path_.clear(); size_ = 0; font_info_ = {}; } } bool SDL2_Font::loadFont(const std::string&amp; path, int size) { SDL2_Font::free(); font_ = TTF_OpenFont(path.c_str(), size); if (font_ == nullptr) { ktp::logSDLError(&quot;TTF_OpenFont&quot;); return false; } path_ = path; size_ = size; SDL2_Font::queryFontInfo(); return true; } </code></pre> <p>This works, or at least I looks to me. But because it's my first time doing this stuff I just want to somebody take a look at it. What do you think? Is the way I implemented the methods/overloads correct?</p> <p>Or maybe it's a bit overkill? Because I don't intend to copy/move/assign <code>SDL2_Font</code>s and just for that destructor I had to do all those methods.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T22:21:30.730", "Id": "504418", "Score": "0", "body": "Why do You need RAII approval?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T06:13:37.727", "Id": "504436", "Score": "0", "body": "I don't need it. I just want my code to be as modern, elegant and maintainable as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:47:04.200", "Id": "504447", "Score": "1", "body": "Can `TTF_WasInit()` actually be false after `TTF_OpenFont()`? If not (and given there's no other way to get a non-null `font_`), then there's no need to check for that, and the deleter can be much simpler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T17:04:52.750", "Id": "505086", "Score": "0", "body": "@AlexCB I don't know about mantainable (code already looks crazy complex), but \"elegant\" and \"modern\" are just buzzwords. :)" } ]
[ { "body": "<p>Because you</p>\n<blockquote>\n<p>don't intend to copy/move/assign <code>SDL2_Font</code>s</p>\n</blockquote>\n<p>you could formalize that with</p>\n<pre><code>SDL2_Font(const SDL2_Font&amp; other) = delete;\nSDL2_Font&amp; operator=(const SDL2_Font&amp; other) = delete;\n</code></pre>\n<p>(the move versions of these operations won't be generated if these two are defined or deleted).</p>\n<p>However, let's assume that one day we will want to be able to pass these fonts by value.</p>\n<p>The code looks correct to my eye, but you could avoid having to do the memory management yourself if you use a smart pointer instead of a raw pointer for the <code>font_</code> member. If you do that, you can follow the Rule of Zero (the best of these rules) and simply let the compiler create the appropriate copy operators and constructors - see worked code below.</p>\n<p><s>I notice that <code>free()</code> can only ever be called from the destructor.</s> (Edit - I see it's also called from <code>loadFont()</code> but less obviously so, by being class-qualified. This paragraph still applies, though.) <code>free()</code> does a lot of &quot;dead writes&quot; most times it's called - i.e. making assignments to variables that can never be read. That's a waste of your time and mine! Possibly also of your processor's, though a decent compiler should be able to optimise most of that away.</p>\n<hr />\n<p>Here's a simplified version using shared pointer (I'm assuming that copies don't each need their own font object, as we don't ever modify it):</p>\n<pre><code>#include &lt;SDL.h&gt;\n#include &lt;SDL_ttf.h&gt;\n\n#include &lt;memory&gt;\n#include &lt;string&gt;\n\nnamespace ktp {\n void logSDLError(const char*);\n}\n\n/* header */\nclass SDL2_Font {\npublic:\n SDL2_Font() {}\n\n bool loadFont(const std::string&amp; path, int size);\nprivate:\n struct FontInfo {};\n void queryFontInfo();\n\n std::shared_ptr&lt;const TTF_Font&gt; font_{};\n FontInfo font_info_ {};\n std::string path_ {};\n int size_ = 0;\n};\n</code></pre>\n\n<pre><code>// look, no constructors or assignment operators!\n\nbool SDL2_Font::loadFont(const std::string&amp; path, int size)\n{\n font_.reset(TTF_OpenFont(path.c_str(), size),\n &amp;TTF_CloseFont);\n if (!font_) {\n ktp::logSDLError(&quot;TTF_OpenFont&quot;);\n font_info_ = {};\n path_ = {};\n size_ = 0;\n return false;\n }\n path_ = path;\n size_ = size;\n queryFontInfo();\n return true;\n}\n</code></pre>\n<p>See how <code>reset()</code> takes care of releasing resources for us, and we don't need to write a destructor.</p>\n<p>I tried this with a simple <code>main()</code>:</p>\n<pre><code>int main()\n{\n if (TTF_Init()) {\n std::cerr &lt;&lt; &quot;TTF_Init: &quot; &lt;&lt; TTF_GetError() &lt;&lt; '\\n';\n return 1;\n }\n\n {\n SDL2_Font f;\n f.loadFont(&quot;/usr/share/fonts/truetype/unifont/unifont.ttf&quot;, 14);\n f.loadFont(&quot;/usr/share/fonts/truetype/unifont/unifont.ttf&quot;, 16);\n // important - f goes out of scope before TTF_Quit()\n }\n\n TTF_Quit();\n}\n</code></pre>\n<p>This runs cleanly under Valgrind:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==29172== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info\n==29172== Command: ./255607\n==29172== \n==29172== \n==29172== HEAP SUMMARY:\n==29172== in use at exit: 0 bytes in 0 blocks\n==29172== total heap usage: 155 allocs, 155 frees, 615,577 bytes allocated\n==29172== \n==29172== All heap blocks were freed -- no leaks are possible\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T06:05:35.413", "Id": "504434", "Score": "0", "body": "Headers are `#include \"./sdl2_log.h\" #include <SDL.h> #include <SDL_ttf.h> #include <string>'`. As you say, in another branch I'm trying the rule of zero approach, but I can't get the custom deleter for the smart pointer right, and reading the comments on this [SO](https://stackoverflow.com/questions/19053351/how-do-i-use-a-custom-deleter-with-a-stdunique-ptr-member?noredirect=1&lq=1) thread, it's looks that it causes a bit of overhead in all unique_ptr, isn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T11:30:34.093", "Id": "504469", "Score": "0", "body": "I've tried Toby's solution in my code and it looks like it works: the fonts are correctly rendered. But I'm not sure what happens when the `shared_ptr` is deconstructed because this only happens when I terminate the program. If you need a `main()` to try you can grab mine from github (user lyquid, repo KUGE), but it's full of other SDL stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T13:11:54.383", "Id": "504490", "Score": "0", "body": "@Alex I've updated to show a simple `main()` that exercises this class. That's a useful thing to do in any case - it's hard to properly test stuff if you can't isolate the pieces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T18:09:29.803", "Id": "504512", "Score": "0", "body": "My bad, i read this on a phone and the line truncation in the scroll box made it seem like the deleter wasn't there. Sorry for the confusion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T18:24:57.847", "Id": "504513", "Score": "0", "body": "Thanks @Emily - I was worried that I'd made a serious error. That raises a point that it's perhaps worth line-breaking after the comma, to make it more obvious to readers (even on normal screens, with a long first argument like that, the optional second argument is easily overlooked). I'm going to tidy up comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T18:40:47.643", "Id": "504514", "Score": "1", "body": "@Alex, to address your point about a custom deleter having overhead, that might or might not be true, depending on the cleverness of your compiler. But if it is, then I'd expect any overhead to be small relative to loading a font. And IMO well worth paying compared to the effort of maintaining pointer ownership by hand!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T17:50:39.537", "Id": "255612", "ParentId": "255607", "Score": "3" } } ]
{ "AcceptedAnswerId": "255612", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T16:05:27.657", "Id": "255607", "Score": "2", "Tags": [ "c++", "pointers", "sdl" ], "Title": "C++ wrapper for font opaque pointer" }
255607
<p><strong>Memory</strong>: O(log2(max)*2)~O(1)<br> <strong>Speed</strong>: O(log2(max)*n)~O(n)</p> <p>so i did before a <a href="https://codereview.stackexchange.com/questions/255443/msd-radix-sort-in-place-in-c-object-pointer-oriented">MSD Radix Sort in place</a> but i wanted to do one, with out the count, So i join together the quick sort and radix sort. Think as msd radix sort mod of 2.</p> <h1>Algorithm</h1> <p>i will explain this one directly with a table.</p> <p><a href="https://i.stack.imgur.com/uBEOu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uBEOu.png" alt="table quick radix sort" /></a></p> <h1>Code</h1> <ul> <li><p>start,finish,depth,mid are copy value because we can't modify because is a recursive funtion</p> </li> <li><p>s,f,mod_cal,auxiliar are static for fast calling and the memory usage</p> </li> </ul> <pre><code>#pragma once namespace leixor { //fast log in power of 2 we are using size so we can't use bit_width //is in excess on purpose static size_t&amp; logb2(size_t num) { size_t aux = 1; if (num == 0) return (aux = -1); while (0 &lt; (num &gt;&gt;= 1)) aux++; return aux; } //------------------------obj version--------------------------- //custom get_max because i don't wanna add lib,and normaly we will use this in a custom class template&lt;class obj_arr&gt; static size_t&amp; get_max(obj_arr*&amp; arr, const size_t&amp; size) { size_t i = size%2, aux = arr[0].get_size_t(), aux2=-1; if (size == 0)return aux2; for (; i &lt; size; i += 2) { aux2 = arr[i].get_size_t(); aux = aux2 * (aux &lt; aux2) + aux * (aux &gt;= aux2); aux2 = arr[i + 1].get_size_t(); aux = aux2 * (aux &lt; aux2) + aux * (aux &gt;= aux2); //aux= (aux &lt; aux2)?aux2:aux; are the same speed as the lane before } return aux; } //----------------------------pointer obj version--------------------- template&lt;class obj_arr&gt; static size_t&amp; get_max(obj_arr**&amp; arr, const size_t&amp; size) { size_t i = size%2, aux = arr[0]-&gt;get_size_t(), aux2=-1; if (size == 0)return aux2; for (; i &lt; size; i += 2) { aux2 = arr[i]-&gt;get_size_t(); aux = aux2 * (aux &lt; aux2) + aux * (aux &gt;= aux2); aux2 = arr[i + 1]-&gt;get_size_t(); aux = aux2 * (aux &lt; aux2) + aux * (aux &gt;= aux2); } return aux; } //--------------------------------------------------------------------- //-----------------object orientedversion--------- template&lt;class obj_arr&gt; void two_rad(obj_arr*&amp; arr, size_t start, size_t finish, size_t depth) { depth--; static size_t s, f; static bool mod_cal; static obj_arr auxiliar; f = finish - 1; s = start; while (s &lt; f) { auxiliar = arr[s]; if (mod_cal=(auxiliar.get_size_t() &gt;&gt; depth) % 2) { arr[s] = arr[f]; arr[f] = auxiliar; f--; } s+=!mod_cal; } size_t mid = s + !((arr[s].get_size_t() &gt;&gt; depth) % 2); if (depth &gt; 0) { if (mid - start &gt; 2) two_rad(arr, start, mid, depth); else if (mid - start &gt; 1) { mod_cal = arr[start].get_size_t() &gt; arr[start + 1].get_size_t(); auxiliar = arr[start]; arr[start] = arr[start + mod_cal]; arr[start + mod_cal] = auxiliar; } if (finish - mid &gt; 2) two_rad(arr, mid, finish, depth); else if (finish - mid &gt; 1) { mod_cal = arr[mid].get_size_t() &gt; arr[mid + 1].get_size_t(); auxiliar = arr[mid]; arr[mid] = arr[mid + mod_cal]; arr[mid + mod_cal] = auxiliar; } } } template&lt;class obj_arr&gt; bool qick_radix_sort(obj_arr* arr, size_t size) { if (arr == nullptr || size &lt; 2) return false; two_rad(arr, 0, size, logb2(get_max(arr, size))); return true; } //-----------------pointer orientedversion--------- template&lt;class obj_arr&gt; void two_rad(obj_arr**&amp; arr, size_t start, size_t finish, size_t depth) { depth--; static size_t s, f; static bool mod_cal; static obj_arr* auxiliar; f = finish - 1; s = start; while (s &lt; f) { auxiliar = arr[s]; if (mod_cal=(auxiliar-&gt;get_size_t() &gt;&gt; depth) % 2) { arr[s] = arr[f]; arr[f] = auxiliar; f--; } s+=!mod_cal; } size_t mid =s+ !((arr[s]-&gt;get_size_t() &gt;&gt; depth)%2); if (depth&gt;0){ if (mid-start&gt;2) two_rad(arr,start,mid,depth); else if (mid - start &gt; 1) { mod_cal = arr[start]-&gt;get_size_t() &gt; arr[start + 1]-&gt;get_size_t(); auxiliar = arr[start]; arr[start] = arr[start + mod_cal]; arr[start + mod_cal] = auxiliar; } if (finish - mid &gt; 2) two_rad(arr,mid,finish,depth); else if (finish - mid &gt; 1) { mod_cal = arr[mid]-&gt;get_size_t() &gt; arr[mid + 1]-&gt;get_size_t(); auxiliar = arr[mid]; arr[mid] = arr[mid + mod_cal]; arr[mid + mod_cal] = auxiliar; } } } template&lt;class obj_arr&gt; bool qick_radix_sort(obj_arr** arr, size_t size) { if (arr == nullptr || size &lt; 2) return false; two_rad(arr, 0, size, logb2(get_max(arr, size))); return true; } } </code></pre> <h2>needs</h2> <ul> <li><p>funtion inside a class as get_size_t return a size_t variable can be reference</p> </li> <li><p>and the calling of this sort is leixor::qick_radix_sort(arr, size);</p> </li> </ul> <p>ex:<code>std::vector&lt;D_CLASS&gt; a; leixor::qick_radix_sort(a.data(), a.size());</code></p> <h1>Runtimes</h1> <p>the runtimes are in miliseconds, avarge of 100 times</p> <p>optimization, new runtimes need it</p> <pre><code>/* -------------------------------------------------- ----------------object oriented version----------- -------------------------------------------------- ---------------------size pow 10------------------ -------------------------------------------------- | 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------- max|1 |0.002613|0.020518|0.216481|2.23518|22.4944|222.093|2197.06 -------------------------------------------------- num|2 |0.003194|0.033248|0.31865|3.20488|31.2802|319.138|3135.21 -------------------------------------------------- pow|3 |0.003617|0.039951|0.383426|3.9421|39.9787|419.901|4099.95 -------------------------------------------------- 2 |4 |0.003958|0.046783|0.478583|4.77747|47.9917|514.014|5001.75 -------------------------------------------------- |5 |0.003758|0.06327|0.604892|6.03168|58.432|579.918|5871.16 -------------------------------------------------- |6 |0.004298|0.064584|0.671869|6.92542|71.2283|703.449|6784.92 -------------------------------------------------- |7 |0.003727|0.062074|0.738229|7.47593|75.0941|752.692|7585.21 -------------------------------------------------- -------------------------------------------------- ----------------pointer oriented version----------- -------------------------------------------------- ---------------------size pow 10------------------ -------------------------------------------------- | 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------- max|1 |0.001209|0.006741|0.069374|0.888095|16.3528|186.809|1814.67 -------------------------------------------------- num|2 |0.001486|0.010471|0.107467|1.23582|27.598|312.24|3067.28 -------------------------------------------------- pow|3 |0.001785|0.014352|0.140364|1.69012|33.9956|428.07|4294.08 -------------------------------------------------- 2 |4 |0.002111|0.018542|0.176611|2.13729|39.5618|549.902|5661.17 -------------------------------------------------- |5 |0.002112|0.022938|0.216402|2.51519|50.7784|683.679|7022.75 -------------------------------------------------- |6 |0.002354|0.027141|0.260751|2.9174|57.0826|795.653|8816.75 -------------------------------------------------- |7 |0.00232|0.030715|0.290544|3.32639|61.756|917.006|10731 -------------------------------------------------- */ </code></pre> <h1>RunTime code</h1> <p>average of 100</p> <pre><code>#include &quot;qick_radix_sort.h&quot; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;iostream&gt; #include &lt;chrono&gt; #include&lt;string&gt; #include &lt;array&gt; #include &lt;math.h&gt; #include &lt;bitset&gt; class data { public: data() {} data(size_t&amp; A):m(A) {}; size_t&amp; get_size_t() { return m; }; void operator = (data&amp; A) { m = A.m; }; void operator = (size_t&amp; A) { m = A; }; size_t m; }; void object_version(const size_t pow10, const size_t pow2) { size_t size = pow(10, pow10); data* arr = new data[size]; size_t mod = 1 &lt;&lt; (2 + pow2); float mediana = 0.0; for (size_t i = 0; i &lt; 100; i++) { for (size_t i = 0; i &lt; size; i++) { arr[i].m = rand() % mod; } auto started = std::chrono::high_resolution_clock::now(); leixor::qick_radix_sort(arr, size); auto done = std::chrono::high_resolution_clock::now(); mediana += float(std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(done - started).count()) / float(1000000); } std::cout &lt;&lt; &quot;|&quot; &lt;&lt; mediana /100; delete[] arr; }; void pointer_object_version(const size_t pow10, const size_t pow2) { size_t size = pow(10, pow10); data** arr = new data * [size]; size_t mod = 1 &lt;&lt; (1+ pow2); float mediana = 0.0; for (size_t i = 0; i &lt; size; i++) arr[i] = new data(); for (size_t i = 0; i &lt; 100; i++) { for (size_t i = 0; i &lt; size; i++) { arr[i]-&gt;m = rand() % mod; } auto started = std::chrono::high_resolution_clock::now(); leixor::qick_radix_sort(arr, size); auto done = std::chrono::high_resolution_clock::now(); mediana += float(std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(done - started).count()) / float(1000000); } std::cout &lt;&lt; &quot;|&quot; &lt;&lt; mediana / 100; for (size_t i = 0; i &lt; size; i++) { delete arr[i]; } delete[] arr; }; int main() { std::cout &lt;&lt; &quot;starting...\n&quot;; std::array&lt;std::string, 7&gt; alfa = { &quot;\nmax|1 &quot;,&quot;\nnum|2 &quot;,&quot;\npow|3 &quot;,&quot;\n2 |4 &quot;,&quot;\n |5 &quot; ,&quot;\n |6 &quot; ,&quot;\n |7 &quot; }; std::cout &lt;&lt; &quot;\n --------------------------------------------------&quot; &lt;&lt; &quot;\n ----------------object oriented version-----------&quot; &lt;&lt; &quot;\n --------------------------------------------------\n\n&quot;; std::cout &lt;&lt; &quot;\n ---------------------size pow 10------------------&quot; &lt;&lt; &quot;\n --------------------------------------------------&quot; &lt;&lt; &quot;\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |&quot;; for (size_t z = 0; z &lt; 7; z++) { std::cout &lt;&lt; &quot;\n --------------------------------------------------&quot; &lt;&lt; alfa[z]; for (size_t i = 1; i &lt; 8; i++) { object_version(i, z); } } std::cout &lt;&lt; &quot;\n --------------------------------------------------\n&quot;; std::cout &lt;&lt; &quot;\n --------------------------------------------------&quot; &lt;&lt; &quot;\n ----------------pointer oriented version-----------&quot; &lt;&lt; &quot;\n --------------------------------------------------\n\n&quot;; std::cout &lt;&lt; &quot;\n ---------------------size pow 10------------------&quot; &lt;&lt; &quot;\n --------------------------------------------------&quot; &lt;&lt; &quot;\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |&quot;; for (size_t z = 0; z &lt; 7; z++) { std::cout &lt;&lt; &quot;\n --------------------------------------------------&quot; &lt;&lt; alfa[z]; for (size_t i = 1; i &lt; 8; i++) { pointer_object_version(i, z); } } std::cout &lt;&lt; &quot;\n --------------------------------------------------\n&quot;; } </code></pre>
[]
[ { "body": "<p><strong>Review:</strong></p>\n<pre><code>static size_t&amp; logb2(size_t num) {\n size_t aux = 1;\n if (num == 0) return (aux = -1);\n while (0 &lt; (num &gt;&gt;= 1))\n aux++;\n return aux;\n}\n</code></pre>\n<p>This is returning a reference to a local object. <code>aux</code> goes out of scope at the end of the function, so there's no way that the calling function can use a reference to it.</p>\n<p>It might work now, but on another compiler it might crash. It also might stop working (a crash, or worse: silently returning incorrect results) if you change your compiler options, or change your program slightly.</p>\n<p><code>get_max</code> has the same problem.</p>\n<hr />\n<pre><code> size_t i = size%2, aux = arr[0].get_size_t(), aux2=-1;\n if (size == 0)return aux2;\n</code></pre>\n<p>Accessing <code>arr[0]</code> is not safe if <code>size == 0</code>, so the size check needs to be done first.</p>\n<hr />\n<pre><code> static size_t s, f;\n static bool mod_cal;\n static obj_arr auxiliar;\n</code></pre>\n<p>These do not need to be <code>static</code>. Making them static is likely to make compiler optimization more difficult, and make the program slower.</p>\n<hr />\n<pre><code> depth--;\n</code></pre>\n<p>It would be more usual to decrement depth when calling the next level of recursive function. (Which would mean we don't need the &quot;off-by-one&quot; log base 2 function).</p>\n<hr />\n<pre><code> size_t mid =s+ !((arr[s]-&gt;get_size_t() &gt;&gt; depth)%2);\n if (depth&gt;0){\n if (mid-start&gt;2)\n two_rad(arr,start,mid,depth);\n else if (mid - start &gt; 1) {\n mod_cal = arr[start]-&gt;get_size_t() &gt; arr[start + 1]-&gt;get_size_t();\n \n auxiliar = arr[start];\n arr[start] = arr[start + mod_cal];\n arr[start + mod_cal] = auxiliar;\n }\n if (finish - mid &gt; 2)\n two_rad(arr,mid,finish,depth);\n else if (finish - mid &gt; 1) {\n mod_cal = arr[mid]-&gt;get_size_t() &gt; arr[mid + 1]-&gt;get_size_t();\n auxiliar = arr[mid];\n arr[mid] = arr[mid + mod_cal];\n arr[mid + mod_cal] = auxiliar;\n }\n }\n</code></pre>\n<p>Most of this special-case logic is unnecessary. We can simply call the next level function, and check the size there before doing any work. i.e.:</p>\n<pre><code>// ... at the top of two_rad()\nif (finish - start &lt; 2) return; // nothing to do!\n\n... processing ...\n\n// ... at the bottom of two_rad():\nif (depth == 0) return;\ntwo_rad(arr, start, mid, depth - 1);\ntwo_rad(arr, mid, finish, depth - 1);\n</code></pre>\n<hr />\n<p><strong>Changes:</strong></p>\n<p>I made a series of changes to see what happened performance-wise. (Only looking at the &quot;object-oriented&quot; version).</p>\n<p>Initial performance looked like this:</p>\n<pre><code> ---------------------size pow 10------------------\n --------------------------------------------------\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n --------------------------------------------------\nmax|1 |0.000244|0.001618|0.014842|0.146165|1.44533\n --------------------------------------------------\nnum|2 |0.0003|0.002286|0.020734|0.210913|2.11932\n --------------------------------------------------\npow|3 |0.000343|0.003042|0.028168|0.279006|2.77773\n --------------------------------------------------\n2 |4 |0.000356|0.003863|0.034078|0.345635|3.51738\n --------------------------------------------------\n |5 |0.000365|0.004637|0.040989|0.409529|4.11875\n --------------------------------------------------\n</code></pre>\n<p>Changes:</p>\n<ul>\n<li>Removing <code>data</code> class, and taking an array of <code>size_t</code> instead of a template argument.</li>\n<li>Using <code>*std::max_element(arr, arr + size);</code> instead of the custom <code>get_max</code> function.</li>\n</ul>\n<p>Results: (pretty much the same)</p>\n<pre><code> ---------------------size pow 10------------------\n --------------------------------------------------\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n --------------------------------------------------\nmax|1 |0.000215|0.001568|0.015363|0.146712|1.45304\n --------------------------------------------------\nnum|2 |0.000287|0.002171|0.020847|0.206735|2.07393\n --------------------------------------------------\npow|3 |0.000328|0.002852|0.026889|0.26842|2.70905\n --------------------------------------------------\n2 |4 |0.000332|0.003548|0.033133|0.329062|3.28266\n --------------------------------------------------\n |5 |0.000344|0.004271|0.039608|0.390457|3.90385\n --------------------------------------------------\n</code></pre>\n<p>Changes:</p>\n<ul>\n<li>Removing the unnecessary <code>static</code> variables.</li>\n<li>Use <code>std::swap</code>.</li>\n</ul>\n<p>Results: (pretty much the same)</p>\n<pre><code> ---------------------size pow 10------------------\n --------------------------------------------------\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n --------------------------------------------------\nmax|1 |0.000225|0.00159|0.015389|0.146791|1.5249\n --------------------------------------------------\nnum|2 |0.000288|0.002196|0.020787|0.203742|2.06895\n --------------------------------------------------\npow|3 |0.000339|0.002963|0.028822|0.264389|2.66769\n --------------------------------------------------\n2 |4 |0.000356|0.003552|0.033073|0.328369|3.27564\n --------------------------------------------------\n |5 |0.000348|0.004297|0.039552|0.387799|3.89064\n --------------------------------------------------\n</code></pre>\n<p>Changes:</p>\n<ul>\n<li>Simplify the recursion (remove checking for size 1 or size 2 arrays as described above, just call the next <code>two_rad</code> function).</li>\n</ul>\n<p>Results: (pretty much the same)</p>\n<pre><code> ---------------------size pow 10------------------\n --------------------------------------------------\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n --------------------------------------------------\nmax|1 |0.000222|0.00158|0.015265|0.148654|1.46329\n --------------------------------------------------\nnum|2 |0.000286|0.002178|0.020024|0.203993|2.07686\n --------------------------------------------------\npow|3 |0.000377|0.002855|0.025927|0.27132|2.68528\n --------------------------------------------------\n2 |4 |0.000504|0.003546|0.033194|0.329328|3.3009\n --------------------------------------------------\n |5 |0.000607|0.004372|0.038077|0.377845|3.9096\n --------------------------------------------------\n</code></pre>\n<p>Changes:</p>\n<ul>\n<li>Switch to using iterators (pointers).</li>\n<li>Change bit checking operation to <code>(value &amp; T{ 1 } &lt;&lt; bit);</code></li>\n</ul>\n<p>Results: (slightly faster)</p>\n<pre><code> ---------------------size pow 10------------------\n --------------------------------------------------\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n --------------------------------------------------\nmax|1 |0.000192|0.001295|0.013703|0.137851|1.25551\n --------------------------------------------------\nnum|2 |0.000288|0.001852|0.017461|0.1866|1.73913\n --------------------------------------------------\npow|3 |0.000376|0.002432|0.02283|0.222846|2.25643\n --------------------------------------------------\n2 |4 |0.000469|0.003089|0.027707|0.272459|2.7158\n --------------------------------------------------\n |5 |0.00058|0.003853|0.033452|0.32207|3.27698\n --------------------------------------------------\n</code></pre>\n<p>With this last version, we have one less function argument to pass in <code>two_rad</code>, so it's slightly faster because of that. The alternative method of checking the set bit is also slightly faster.</p>\n<hr />\n<p>The final code looked like this:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;bit&gt;\n#include &lt;cmath&gt;\n#include &lt;type_traits&gt;\n\ntemplate&lt;class T&gt;\nbool is_bit_set(T value, T bit)\n{\n return value &amp; (T{ 1 } &lt;&lt; bit);\n //return ((value &gt;&gt; bit) % 2);\n}\n\ntemplate&lt;class It&gt;\nvoid two_rad(It begin, It end, typename std::iterator_traits&lt;It&gt;::value_type bit)\n{\n if (begin == end) return;\n\n auto s = begin;\n auto f = std::prev(end);\n\n while (s != f)\n {\n if (is_bit_set(*s, bit))\n {\n std::swap(*s, *f);\n --f;\n }\n else\n ++s;\n }\n\n if (bit == 0) return;\n\n if (!is_bit_set(*s, bit))\n ++s;\n\n two_rad(begin, s, bit - 1);\n two_rad(s, end, bit - 1);\n}\n\ntemplate&lt;class It,\n class = std::enable_if_t&lt;std::is_unsigned_v&lt;typename std::iterator_traits&lt;It&gt;::value_type&gt;&gt; &gt;\nvoid quick_radix_sort(It begin, It end)\n{\n if (begin == end) return;\n\n auto max = *std::max_element(begin, end);\n if (max == 0) return;\n\n auto max_bit = std::bit_width(max) - typename std::iterator_traits&lt;It&gt;::value_type{ 1 };\n\n two_rad(begin, end, max_bit);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-13T07:01:50.563", "Id": "505213", "Score": "0", "body": "one question if a have a class like idk point with x,y and z how i implement that here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-13T09:52:20.570", "Id": "505220", "Score": "2", "body": "OPs comment that \"not using std::swap because it's slow\" immediately raised red flags for the kind of attitude where everything someone else or the standard library made must be slow because they didn't make it then selves... Thanks for setting the record straight with respect to std::swap." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:56:23.073", "Id": "255694", "ParentId": "255609", "Score": "4" } } ]
{ "AcceptedAnswerId": "255694", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T16:57:47.637", "Id": "255609", "Score": "1", "Tags": [ "c++", "performance", "sorting", "quick-sort", "radix-sort" ], "Title": "MSD Quick Radix Sort in Place in C++, Object/Pointer Oriented" }
255609
<p>I have a small bit of code and I wonder if I can make it more readable. I would appreciate it if some people could take a look at it and give me some feedback. I especially wonder if there is a beter way of doing this:</p> <pre><code>cv::Mat image = loadImage(path.string()); if (image.data == NULL) { continue; } </code></pre> <p>This is the bigger code:</p> <pre><code>cv::Mat Watermarker::loadImage(const std::string&amp; path) { if (!validFile(path)) { if (!std::filesystem::is_directory(path)) { std::cout &lt;&lt; path &lt;&lt; &quot; is invalid\n&quot;; } return cv::Mat{}; } cv::Mat image = cv::imread(path, cv::IMREAD_UNCHANGED); if (image.data == NULL) { std::cout &lt;&lt; &quot;Not enough permissions to read file &quot; &lt;&lt; path &lt;&lt; &quot;\n&quot;; return cv::Mat{}; } return image; } void Watermarker::mark(const std::string&amp; targetDirectory, const std::string&amp; watermarkPath) { cv::Mat watermarkImage = loadImage(watermarkPath); if (watermarkImage.data == NULL) { return; } // Loop through all the files in the target directory for (const std::filesystem::path&amp; path : std::filesystem::directory_iterator(targetDirectory)) { cv::Mat image = loadImage(path.string()); if (image.data == NULL) { continue; } cv::resize(watermarkImage, watermarkImage, image.size()); // Give the images 4 channels cv::cvtColor(image, image, cv::COLOR_RGB2RGBA); cv::cvtColor(watermarkImage, watermarkImage, cv::COLOR_RGB2RGBA); // Add the watermark to the original image cv::addWeighted(watermarkImage, 0.3, image, 1, 0.0, image); saveImage(targetDirectory + &quot;/watermarked_images/&quot; + path.filename().string(), image); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:15:42.740", "Id": "504408", "Score": "3", "body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T22:18:22.693", "Id": "504417", "Score": "2", "body": "You loop through stuff and You skip some, that is perfectly readable. I am pretty sure You are mistaken to think Your code is not readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T08:05:20.743", "Id": "504929", "Score": "0", "body": "(Some think this question should not be answered *as is* for *lack of review context*. Given the spotlight \"on the conditional continue\", there is enough context for *that*. For `::loadImage()` and `::mark()`, documenting comments should work miracles. Please heed [What (not) to do when someone answers](https://codereview.stackexchange.com/help/someone-answers).)" } ]
[ { "body": "<h1>Don't ignore errors</h1>\n<p>You are just skipping any file that cannot be read correctly. But probably, if the user tried to process the images in a given target directory, it wants all of them to be watermarked, and if something cannot be watermarked, the user probably wants to hear about it. So you should not just continue after loading an image failed, you should stop and report an error. There are several ways to do this, for example:</p>\n<h1>Consider throwing exceptions</h1>\n<p>I would recommend throwing exceptions here. I assume that not being able to open a file or parsing it correctly is an exceptional event for your program. The advantage of throwing an exception is that the caller of a function that throws doesn't have to handle the exception, it can just let it propagate up the stack until something does handle it, or if nothing handles the exception, the program will abort with an error. The latter can even be desirable. Here is an example of how to throw exceptions:</p>\n<pre><code>#include &lt;stdexcept&gt;\n\ncv::Mat Watermarker::loadImage(const std::string&amp; path)\n{\n cv::Mat image = cv::imread(path, cv::IMREAD_UNCHANGED);\n\n if (!image.data)\n throw std::runtime_error(&quot;Failed to read image&quot;);\n\n return image;\n}\n</code></pre>\n<p>I have removed the check for <code>path</code> being valid as well, since if it isn't valid, trying to call <code>cv::imread()</code> on it will fail as well.</p>\n<p>Inside <code>Watermarker::mark()</code>, you can now assume that when <code>loadImage()</code> returns, <code>image.data</code> is always non-NULL, so you don't need a check there. If you really want to continue parsing images, then you can catch the exception, and perhaps print a warning so the user does get to know what was wrong:</p>\n<pre><code>try {\n cv::Mat image = loadImage(path.string());\n cv.resize(...);\n ...\n} catch (std::runtime_error &amp;e) {\n std::cerr &lt;&lt; &quot;Could not load &quot; &lt;&lt; path &lt;&lt; &quot;: &quot; &lt;&lt; e.what() &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<h1>Write error messages to <code>std::cerr</code></h1>\n<p>Don't write warnings, errors and debug messages to <code>std::cout</code>, but use <code>std::cerr</code>. This is especially important if the program is printing normal output to <code>std::cout</code>, so that if standard output is redirect to a file for example, it will not contain error messages, and the error messages will still be printed to the console.</p>\n<h1>Avoid converting <code>std::filesystem::path</code>s to <code>std::string</code>s too early</h1>\n<p>Use <code>std::filesystem::path</code> as the type to pass paths in consistently. Only convert them to/from <code>std::string</code>s when really necessary. You can also make use of implicit conversions between <code>std::string</code> and <code>std::filesystem::path</code>. So for example:</p>\n<pre><code>cv::Mat Watermarker::loadImage(const std::filesystem::path&amp; path)\n{\n cv::Mat image = cv::imread(path, cv::IMREAD_UNCHANGED);\n ...\n}\n</code></pre>\n<p>And:</p>\n<pre><code>void Watermarker::mark(const std::fileystem::path&amp; targetDirectory, const std::filesystem::path&amp; watermarkPath)\n{\n auto watermarkImage = loadImage(watermarkPath);\n\n for (auth&amp; path : std::filesystem::directory_iterator(targetDirectory))\n {\n auto image = loadImage(path);\n cv::resize(watermarkImage, watermarkImage, image.size());\n ...\n saveImage(targetDirectory / &quot;watermarked_images&quot; / path.filename(), image);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T09:37:38.587", "Id": "504720", "Score": "0", "body": "Aborting the process (throwing) on error seems not great tho, that'd leave the target directory half processed and as you don't want to water mark files twice, recovering from that is annoying. I think printing an error is better, this is what most UNIX tools do too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T18:43:53.110", "Id": "504763", "Score": "0", "body": "@EmilyL. When a thrown exception is not caught, the program aborts with a diagnostic printed to standard error output (at least, on UNIX-like operating systems), and a non-zero exit code. As for not watermarking twice unnecessarily, that is useful even if there are no errors, and should be implemented by checking if a watermark image is already present and has a timestamp that is newer than the source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T10:47:09.063", "Id": "504939", "Score": "1", "body": "The convention with tools like cp, mv, convert etc is to keep going and print the (hopefully few) files that failed. Each to their own tho." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-12T09:58:11.033", "Id": "505122", "Score": "0", "body": "@EmilyL. cp and mv continuing even if some things fail is sometimes helpful, sometimes not. But I agree that it's better to follow the conventions of other commonly used programs so that there is the least amount of surprise." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:18:12.947", "Id": "255625", "ParentId": "255615", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T18:11:45.887", "Id": "255615", "Score": "1", "Tags": [ "c++", "opencv" ], "Title": "Watermarking an image" }
255615
<p>I'm trying to optimize the narrow phase of the contact detection in my code. I'm using OpenMP for multithreading.</p> <p>That is the starting code:</p> <pre><code>// Narrow Phase const unsigned int NbPairs = pair_manager_-&gt;get_n_pairs(); delete[] sum_rad_; sum_rad_ = new double[NbPairs]; delete[] distance_vector_; distance_vector_ = new Vector3d[NbPairs]; delete[] sq_dist_; sq_dist_ = new double[NbPairs]; const Pair * Pairs = pair_manager_-&gt;get_pairs(); int n_active = 0; auto * active = new bool[NbPairs]; #pragma omp parallel default(none) shared(active, Pairs, n_active) firstprivate(NbPairs) num_threads(current_num_threads_) { #pragma omp for schedule(static) for (int i = 0; i&lt;NbPairs; i++) { const int id_0 = Pairs[i].id_0_; const int id_1 = Pairs[i].id_1_; sum_rad_[i] = radius_[id_0]+radius_[id_1]; distance_vector_[i] = position_[id_1]-position_[id_0]; sq_dist_[i] = distance_vector_[i].squaredNorm(); } Pair * PairsNonConst = pair_manager_-&gt;get_pairs_non_const(); #pragma omp for schedule(static) reduction(+:n_active) for (int i = 0; i&lt;NbPairs; i++) { if (sq_dist_[i]&lt;sum_rad_[i]*sum_rad_[i]) { active[i] = true; n_active++; } else { PairsNonConst[i].data_id = -1; active[i] = false; } } } delete[] active_pairs_; active_pairs_ = new int[n_active]; n_active_pairs_ = n_active; int j = 0; // FIXME: is it possible to include it in the parallel loop? -&gt; I guess so, then do merge reduction for (int i = 0; i&lt;NbPairs; i++) { if (active[i]) { active_pairs_[j] = i; j++; } } assert(j==n_active_pairs_); delete[] active; </code></pre> <p>The pair manager contains the candidate contact pairs, which has to be checked in the narrow phase. I only have spherical objects, so this is fairly easy (if squared sum of radii is larger than the squared distance of the objects, then we have a contact).</p> <p>In a previous developing phase, I splitted the two for loops to get performance benefits, so that the first one does not contain any if statement. So, in the first one I calculate all the relevant quantities for all contact candidates, in the second one I have to check every candidate for actual contact.</p> <p>After that, I have to loop over the <code>active</code> array and save the indexes of each active contact pair. In another part of the code, I'll then loop over this array <code>active_pairs_</code> and calculate the contact forces, i.e. by indirectly accessing <code>sq_dist_</code> and <code>distance_vector_</code> in this way:</p> <pre><code>#pragma omp for schedule(static) for (int i=0; i&lt;n_active_pairs_; i++) { int id_pair = active_pairs_[i]; const Vector3d distance = distance_vector_[id_pair]; // ... } </code></pre> <p>Ideally, I would like to save only the quantities for the actual contact pairs in <code>sum_rad_</code>, <code>distance_vector_</code>, and <code>sq_dist_</code> so that in this for loop I can only loop over those arrays. Also, this would save me the last serial loop in the narrow phase. On the other hand it would mean merging the two loops in the parallel region (unless someone has a better idea on how to do that).</p> <p>Last but not least, with my approach, I cannot have a proper <em>first touch</em> (important on NUMA systems). It would be nice to get this somehow as well.</p> <p>What are your thoughts?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T22:29:44.923", "Id": "504420", "Score": "0", "body": "You say “if squared sum of radii is larger than the squared distance” - as you say all your objects are spheres, you _don’t need the squaring_ - simply “sum of radii larger than distance” is enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:03:38.857", "Id": "504438", "Score": "1", "body": "@Aganju Yes, but squaring the sum is cheaper than taking the square root of the norm of a vector" } ]
[ { "body": "<blockquote>\n<pre><code> delete[] sum_rad_;\n sum_rad_ = new double[NbPairs];\n delete[] distance_vector_;\n distance_vector_ = new Vector3d[NbPairs];\n delete[] sq_dist_;\n sq_dist_ = new double[NbPairs];\n</code></pre>\n</blockquote>\n<p>Why all these bare array-pointers that you have to manage yourself? You'd have much more maintainable code with <code>std::vector</code> or even just <code>std::unique_ptr&lt;T[]&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:49:00.460", "Id": "504413", "Score": "0", "body": "In general, I'm using plain array because of first touch (which is not - yet - true in this specific part of the code, though). With `std::vector`s you cannot guarantee first touch. That should instead be possible with unique pointers..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T22:03:32.537", "Id": "504415", "Score": "1", "body": "What do you mean with \"first touch\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:06:37.043", "Id": "504439", "Score": "0", "body": "@G. Sliepen First Touch w/ parallel code: all array elements are allocated in the\nmemory of the NUMA node containing the core executing the thread\ninitializing the respective partition" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:32:43.220", "Id": "504443", "Score": "2", "body": "@David Ah, I see. If you have special memory allocation requirements, you can always pass a custom allocator to `std::vector` (the same goes for all other STL containers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:56:41.087", "Id": "504448", "Score": "0", "body": "@G.Sliepen I've long looked at that but never found a solution that guaranteed first touch with stl vectors. How would you do that? By the way, it is actually just a personal code, where performance matters much more than maintainability (although, I agree it's good to always have good habits w.r.t. that)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:30:24.037", "Id": "255627", "ParentId": "255626", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T21:23:24.673", "Id": "255626", "Score": "1", "Tags": [ "c++", "performance", "simulation", "physics", "openmp" ], "Title": "Optimize narrow phase contact detection for phyiscs simulation code" }
255626
<p>I am working my way through some code challenges — partly to improve my problem solving, but also to improve my code quality.</p> <p>I think my current (fully-functional) solution to a challenge is pretty solid, and fairly understandable. I would love to know, however, if there is anything in my style which could be improved.</p> <p>Readers are encouraged to be opinionated, but to clearly-demarcate what is purely personal preference from what is a preference, but also strongly advised.</p> <blockquote> <p>Good morning! Here's your coding interview problem for today.</p> <p>This problem was asked by Facebook.</p> <p>Implement regular expression matching with the following special characters:</p> <p><code>.</code> (period) which matches any single character<br /> <code>*</code> (asterisk) which matches zero or more of the preceding element</p> <p>That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression.</p> <p>For example, given the regular expression <code>&quot;ra.&quot;</code> and the string <code>&quot;ray&quot;</code>, your function should return true. The same regular expression on the string <code>&quot;Raymond&quot;</code> should return false.</p> <p>Given the regular expression <code>&quot;.\*at&quot;</code> and the string <code>&quot;chat&quot;</code>, your function should return true. The same regular expression on the string <code>&quot;chats&quot;</code> should return false.</p> </blockquote> <pre class="lang-py prettyprint-override"><code># solution.py from collections import deque import logging from typing import Deque, NamedTuple, Optional, Union logging.basicConfig(level=logging.INFO,format=&quot;%(asctime)s - %(levelname)s - %(name)s - %(funcName)s - %(lineno)d : %(message)s&quot;) class Attempt(NamedTuple): matched_string : str remaining_string : str remaining_pattern : str class DecisionPoint(NamedTuple): greedy : Attempt non_greedy : Attempt def advance_attempt(attempt: Attempt, greedy = False) -&gt; Attempt: char = attempt.remaining_pattern[0] if greedy and char!= '*': raise RuntimeError(&quot;Can't perform a greedy advancement on a non wildcard char.&quot;) new_matched_string = attempt.matched_string + char if greedy: new_remaining_pattern = attempt.remaining_pattern else: new_remaining_pattern = attempt.remaining_pattern[1:] new_remaining_string = attempt.remaining_string[1:] return Attempt(matched_string=new_matched_string, remaining_pattern=new_remaining_pattern, remaining_string=new_remaining_string) def next_char_is_match(next_char : str, string : str) -&gt; bool: &quot;&quot;&quot;Returns true if the supplied next_char in the pattern matches the head of the string. Next char is expected to be a single char or an empty string.&quot;&quot;&quot; if next_char == '': return False if next_char == '*': return True if next_char == '.' and len(string) != 0: return True return next_char == string[0] def take_next_greedy(attempt: Attempt) -&gt; Attempt: return advance_attempt(attempt=attempt,greedy=True) def take_next_non_greedy(attempt : Attempt) -&gt; Attempt: return advance_attempt(attempt) def take_next(attempt : Attempt) -&gt; Optional[Union[DecisionPoint,Attempt]]: &quot;&quot;&quot;Returns None if no next match is possible; otherwise, returns either a single progression of the attempt — i.e., a single character moved into the matched field from the remaining field — or, in the case of a wildcard, both the greedy and non-greedy next possibilities.&quot;&quot;&quot; if (len(attempt.remaining_string) == 0 \ or len(attempt.remaining_pattern) == 0): return None next_char_to_match_in_pattern = attempt.remaining_pattern[0] next_char_to_match_in_string = attempt.remaining_string[0] if next_char_to_match_in_pattern == '*': return DecisionPoint(greedy=take_next_greedy(attempt), non_greedy=take_next_non_greedy(attempt)) if (next_char_to_match_in_pattern == next_char_to_match_in_string\ or next_char_to_match_in_pattern == '.'): return advance_attempt(attempt) def main_loop(queue : Deque[Attempt]) -&gt; bool: logging.debug(queue) logging.info(len(queue)) attempt = queue.popleft() logging.info(attempt) if attempt.remaining_pattern == ''\ and attempt.remaining_string == '': return True next_step = take_next(attempt) if next_step is None: return False elif isinstance(next_step,DecisionPoint): queue.appendleft(next_step.non_greedy) queue.appendleft(next_step.greedy) return False else: queue.appendleft(next_step) return False def main(pattern : str, string : str) -&gt; bool: q = deque() q.append(Attempt(matched_string='', remaining_string=string, remaining_pattern=pattern)) match_found = False while len(q) != 0 and not match_found: match_found = main_loop(q) logging.info(match_found) return match_found if __name__ == '__main__': main('.*at*.rq','chatsdafrzafafrq') </code></pre> <pre class="lang-py prettyprint-override"><code> # tests.py import unittest from .solution import main class BasicTests(unittest.TestCase): def test_given_which_is_expected_to_match_matches(self): computed_result = main('ra.','ray') self.assertTrue(computed_result) def test_given_which_is_expected_to_not_match_does_not_match(self): computed_result = main('ra.','raymond') self.assertFalse(computed_result) def test_other_given_which_is_expected_to_match_matches(self): computed_result = main('.*at','chat') self.assertTrue(computed_result) def test_complex_which_is_expected_to_match_matches(self): computed_result = main('.*jk*.wee*.weq','jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weq') self.assertTrue(computed_result) def test_complex_which_is_expected_not_to_match_does_not_match(self): computed_result = main('.*jk*.wee*.weqr','jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weqtjhuafjs') self.assertFalse(computed_result) if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T19:32:04.280", "Id": "504515", "Score": "2", "body": "Welcome to Code Review! 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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." } ]
[ { "body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> enumerates several conventions for Python programs</p>\n<h2>Imports</h2>\n<p>All <code>import ...</code> statements should precede <code>from ... import ...</code></p>\n<p>Reading through the PEP 8 documentation, I'm not seeing this, but my pylinter complains if this ordering is not obeyed.</p>\n<h2>Indentation</h2>\n<blockquote>\n<p>Use 4 spaces per indentation level.</p>\n</blockquote>\n<p>Functions like <code>advance_attempt</code> are indented too far.</p>\n<h2>Code Organization</h2>\n<ul>\n<li>Imports</li>\n<li>Classes &amp; function definitions</li>\n<li>Code</li>\n</ul>\n<p>Your <code>logging.basicConfig(level=logging.INFO, ...)</code> statement falls under the &quot;Code&quot; category, and should be after the class/function definitions.</p>\n<p>Moreover, it is <strong>EXECUTED</strong> when the module is imported. It should be inside the main-guard, to prevent unexpected side-effects.</p>\n<h2>Spaces</h2>\n<h3>Comma</h3>\n<p><code>logging.basicConfig(level=logging.INFO,format=&quot;...</code></p>\n<p>There should be a space after every comma.</p>\n<h3>Binary operators</h3>\n<p><code>if greedy and char!= '*':</code></p>\n<p>There should be a space on both sides of the binary operator <code>!=</code>.</p>\n<h3>Type Hints</h3>\n<p><code>def take_next_non_greedy(attempt : Attempt) -&gt; Attempt:</code></p>\n<p>There should be no space before the <code>:</code></p>\n<h1>Unnecessary line continuations</h1>\n<pre class=\"lang-py prettyprint-override\"><code> if (len(attempt.remaining_string) == 0 \\\n or len(attempt.remaining_pattern) == 0):\n return None\n</code></pre>\n<p>There is no need for the <code>\\</code>, since the expression is inside parenthesis.</p>\n<h1>Broken implementation</h1>\n<p>Why is <code>'.*jk*.wee*.weq'</code> expected to match <code>'jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weq'</code>?</p>\n<p>That pattern is:</p>\n<ul>\n<li><code>.*</code> any number of any character</li>\n<li><code>j</code> a single j</li>\n<li><code>k*</code> 0 or more k's</li>\n<li><code>.</code> any character</li>\n<li><code>we</code> two explicit characters</li>\n<li><code>e*</code> any number of e's</li>\n<li><code>.</code> any character</li>\n<li><code>weq</code> three explicit characters</li>\n</ul>\n<p>The given string does <strong>not</strong> match that pattern. The test asserts that it should match. If the pattern was written with <code>.*</code> instead of <code>*.</code> patterns, I could actually see the match succeeding. But it wasn't. Assuming a match is declared (I haven't run the code), then the implementation must be broken.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:14:40.753", "Id": "504455", "Score": "0", "body": "Appreciated! I was already aware of PEP8, but I didn't realise that it recommended putting all imports .... before from ... import ...\n\nBroken Implementation: I think I actually misread the brief: I thought that * matches any character, not that is matched any number of the preceding character. I'm not sure why I didn't realise that, given that that is how actual regex definitions work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T01:49:06.060", "Id": "255634", "ParentId": "255630", "Score": "3" } }, { "body": "<p>For completeness, here is an updated answer which incorporates the feedback:</p>\n<pre class=\"lang-py prettyprint-override\"><code># solution.py\nfrom __future__ import annotations\n\nimport logging\nfrom collections import deque\nfrom typing import Deque, List,NamedTuple, Optional, Union\n\n\nclass Attempt(NamedTuple):\n matched_string : str\n remaining_string : str\n remaining_tokens : List[Token]\n\nclass DecisionPoint(NamedTuple):\n greedy : Attempt\n non_greedy : Attempt\n\nclass Token(NamedTuple):\n character : str\n is_wildcarded : bool = False\n\ndef tokenize(pattern: str) -&gt; List[Token]:\n tokens = []\n while pattern:\n if len(pattern) == 1:\n tokens.append(Token(character=pattern))\n pattern = ''\n else:\n head = pattern[0]\n pattern = pattern[1:]\n if pattern[0] == '*':\n pattern = pattern[1:]\n tokens.append(Token(character=head,\n is_wildcarded=True))\n else:\n tokens.append(Token(character=head))\n return tokens\n\ndef advance_attempt(attempt: Attempt, greedy: bool = False) -&gt; Attempt:\n next_token = attempt.remaining_tokens[0]\n char = next_token.character\n\n new_matched_string = attempt.matched_string + char\n if greedy:\n new_remaining_tokens = attempt.remaining_tokens\n else:\n new_remaining_tokens = attempt.remaining_tokens[1:]\n new_remaining_string = attempt.remaining_string[1:]\n\n return Attempt(matched_string=new_matched_string,\n remaining_tokens=new_remaining_tokens,\n remaining_string=new_remaining_string)\n\ndef next_token_is_match(next_token: Token, string: str) -&gt; bool:\n &quot;&quot;&quot;Returns true if the supplied next_char in the pattern matches the \n head of the string. Next char is expected to be a single char or an \n empty string.&quot;&quot;&quot;\n\n if next_token.character == '.':\n return True\n return next_token.character == string[0]\n \n\ndef take_next_greedy(attempt: Attempt) -&gt; Attempt:\n return advance_attempt(attempt=attempt,greedy=True)\n\ndef take_next_non_greedy(attempt: Attempt) -&gt; Attempt:\n return advance_attempt(attempt)\n\ndef take_next(attempt : Attempt) -&gt; Optional[Union[DecisionPoint,Attempt]]:\n &quot;&quot;&quot;Returns None if no next match is possible; otherwise, returns either \n a single progression of the attempt — i.e., a single character moved into\n the matched field from the remaining field — or, in the case of a wildcard,\n both the greedy and non-greedy next possibilities.&quot;&quot;&quot;\n\n\n if (len(attempt.remaining_string) == 0 \n or len(attempt.remaining_tokens) == 0):\n return None\n next_token_to_match_in_pattern = attempt.remaining_tokens[0]\n next_char_to_match_in_string = attempt.remaining_string[0]\n \n if next_token_to_match_in_pattern.is_wildcarded:\n return DecisionPoint(greedy=take_next_greedy(attempt),\n non_greedy=take_next_non_greedy(attempt))\n\n if (next_token_to_match_in_pattern.character == next_char_to_match_in_string\n or next_token_to_match_in_pattern.character == '.'):\n return advance_attempt(attempt)\n \n \n \ndef main_loop(queue: Deque[Attempt]) -&gt; bool:\n logging.debug(queue)\n logging.info(len(queue))\n\n attempt = queue.popleft()\n logging.info(attempt)\n\n if (attempt.remaining_tokens == []\n and attempt.remaining_string == ''):\n return True\n\n next_step = take_next(attempt)\n\n if next_step is None:\n return False\n elif isinstance(next_step,DecisionPoint):\n queue.appendleft(next_step.non_greedy)\n queue.appendleft(next_step.greedy)\n return False\n else:\n queue.appendleft(next_step)\n return False\n\ndef main(pattern: str, string : str) -&gt; bool:\n q = deque()\n q.append(Attempt(matched_string='',\n remaining_string=string,\n remaining_tokens=tokenize(pattern)))\n match_found = False\n while len(q) != 0 and not match_found:\n match_found = main_loop(q)\n \n logging.info(match_found) \n return match_found\n\nlogging.basicConfig(level=logging.INFO,\n format=&quot;%(asctime)s - %(levelname)s - %(name)s - %(funcName)s\\\n - %(lineno)d : %(message)s&quot;)\n\nif __name__ == '__main__':\n main('.*at.*rq','chatsdatfrzafafrq')\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code># tests.py\n\nimport unittest\n\nfrom .solution import main, tokenize, Token\n\n\nclass TestTokenize(unittest.TestCase):\n def test_basic(self):\n test_pattern = 'a*.d.*'\n expected_result = [Token('a',True),\n Token('.'),\n Token('d'),\n Token('.',True)\n ]\n\n computed_result = tokenize(test_pattern)\n\n self.assertEqual(expected_result,computed_result)\nclass TestSolution(unittest.TestCase):\n def test_given_which_is_expected_to_match_matches(self):\n computed_result = main('ra.','ray')\n self.assertTrue(computed_result)\n\n def test_given_which_is_expected_to_not_match_does_not_match(self):\n computed_result = main('ra.','raymond')\n self.assertFalse(computed_result)\n\n def test_other_given_which_is_expected_to_match_matches(self):\n computed_result = main('.*at','chat')\n self.assertTrue(computed_result)\n \n def test_complex_which_is_expected_to_match_matches(self):\n computed_result = main('.*jk.*wee*.*weq','jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weq')\n self.assertTrue(computed_result)\n\n def test_complex_which_is_expected_not_to_match_does_not_match(self):\n computed_result = main('.*jk*.wee.*weqr','jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weqtjhuafjs')\n self.assertFalse(computed_result)\n\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T02:00:46.677", "Id": "504544", "Score": "2", "body": "FYI the updated implementation doesn't implement `*` matching 0 of the preceding character. For example, `main('.*chat','chat')` returns `False` when it should return `True`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T22:16:56.303", "Id": "255670", "ParentId": "255630", "Score": "0" } }, { "body": "<p>This has been very illuminating in that it highlights that even a fairly simple brief can have all kinds of corner cases which must be considered in testing.</p>\n<p>Hopefully, this solution is the one final one.</p>\n<pre class=\"lang-py prettyprint-override\"><code># solution.py\nfrom __future__ import annotations\n\nimport logging\nfrom collections import deque\nfrom typing import Deque, List, NamedTuple, Optional, Union\n\n\nclass Attempt(NamedTuple):\n matched_string: str\n remaining_string: str\n remaining_tokens: List[Token]\n\n\nclass DecisionPoint(NamedTuple):\n greedy: Attempt\n non_greedy: Attempt\n\n\nclass Token(NamedTuple):\n character: str\n is_starred: bool = False\n\n\ndef tokenize(pattern: str) -&gt; List[Token]:\n tokens = []\n while pattern:\n if len(pattern) == 1:\n tokens.append(Token(character=pattern))\n pattern = ''\n else:\n head = pattern[0]\n pattern = pattern[1:]\n if pattern[0] == '*':\n pattern = pattern[1:]\n tokens.append(Token(character=head,\n is_starred=True))\n else:\n tokens.append(Token(character=head))\n return tokens\n\n\ndef advance_attempt_starred(attempt: Attempt, greedy: bool = False) -&gt; Attempt:\n next_token = attempt.remaining_tokens[0]\n next_token_char = next_token.character\n\n new_matched_string = attempt.matched_string + next_token_char\n if greedy:\n new_remaining_tokens = attempt.remaining_tokens\n new_remaining_string = attempt.remaining_string[1:]\n else:\n new_remaining_tokens = attempt.remaining_tokens[1:]\n new_remaining_string = attempt.remaining_string\n\n return Attempt(matched_string=new_matched_string,\n remaining_tokens=new_remaining_tokens,\n remaining_string=new_remaining_string)\n\n\ndef advance_attempt(attempt: Attempt, greedy: bool = False) -&gt; Attempt:\n next_token = attempt.remaining_tokens[0]\n next_token_char = next_token.character\n\n new_matched_string = attempt.matched_string + next_token_char\n new_remaining_tokens = attempt.remaining_tokens[1:]\n new_remaining_string = attempt.remaining_string[1:]\n\n return Attempt(matched_string=new_matched_string,\n remaining_tokens=new_remaining_tokens,\n remaining_string=new_remaining_string)\n\n\n\n\ndef take_next_greedy(attempt: Attempt) -&gt; Attempt:\n return advance_attempt_starred(attempt, greedy=True)\n\n\ndef take_next_non_greedy(attempt: Attempt, starred: bool = False) -&gt; Attempt:\n if starred:\n return advance_attempt_starred(attempt)\n return advance_attempt(attempt)\n\n\ndef take_next(attempt: Attempt) -&gt; Optional[Union[DecisionPoint, Attempt]]:\n &quot;&quot;&quot;Returns None if no next match is possible; otherwise, returns either \n a single progression of the attempt — i.e., a single character moved into\n the matched field from the remaining field — or, in the case of a wildcard,\n both the greedy and non-greedy next possibilities.&quot;&quot;&quot;\n\n if (len(attempt.remaining_string) == 0\n or len(attempt.remaining_tokens) == 0):\n return None\n next_token_to_match_in_pattern = attempt.remaining_tokens[0]\n next_char_to_match_in_string = attempt.remaining_string[0]\n\n if next_token_to_match_in_pattern.is_starred:\n return DecisionPoint(greedy=take_next_greedy(attempt),\n non_greedy=take_next_non_greedy(attempt,\n starred=True))\n\n if (next_token_to_match_in_pattern.character == next_char_to_match_in_string\n or next_token_to_match_in_pattern.character == '.'):\n return take_next_non_greedy(attempt)\n\n\ndef main_loop(queue: Deque[Attempt]) -&gt; bool:\n logging.debug(queue)\n logging.info(len(queue))\n\n attempt = queue.popleft()\n logging.info(attempt)\n\n if (attempt.remaining_tokens == []\n and attempt.remaining_string == ''):\n return True\n\n next_step = take_next(attempt)\n\n if next_step is None:\n return False\n elif isinstance(next_step, DecisionPoint):\n queue.appendleft(next_step.non_greedy)\n queue.appendleft(next_step.greedy)\n return False\n else:\n queue.appendleft(next_step)\n return False\n\n\ndef main(pattern: str, string: str) -&gt; bool:\n q = deque()\n q.append(Attempt(matched_string='',\n remaining_string=string,\n remaining_tokens=tokenize(pattern)))\n match_found = False\n while len(q) != 0 and not match_found:\n match_found = main_loop(q)\n\n logging.info(match_found)\n return match_found\n\n\nlogging.basicConfig(level=logging.INFO,\n format=&quot;%(asctime)s - %(levelname)s - %(name)s - %(funcName)s\\\n - %(lineno)d : %(message)s&quot;)\n\nif __name__ == '__main__':\n main('.*at.*rq', 'chatsdatfrzafafrq')\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code># solution.py\nimport unittest\n\nfrom .solution import main, tokenize, Token\n\n\nclass TestTokenize(unittest.TestCase):\n def test_basic(self):\n test_pattern = 'a*.d.*'\n expected_result = [Token('a',True),\n Token('.'),\n Token('d'),\n Token('.',True)\n ]\n\n computed_result = tokenize(test_pattern)\n\n self.assertEqual(expected_result,computed_result)\n\nclass TestSolution(unittest.TestCase):\n def test_given_which_is_expected_to_match_matches(self):\n computed_result = main('ra.','ray')\n self.assertTrue(computed_result)\n\n def test_given_which_is_expected_to_not_match_does_not_match(self):\n computed_result = main('ra.','raymond')\n self.assertFalse(computed_result)\n\n def test_other_given_which_is_expected_to_match_matches(self):\n computed_result = main('.*at','chat')\n self.assertTrue(computed_result)\n \n def test_complex_which_is_expected_to_match_matches(self):\n computed_result = main('.*jk.*wee*.*weq','jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weq')\n self.assertTrue(computed_result)\n\n def test_complex_which_is_expected_not_to_match_does_not_match(self):\n computed_result = main('.*jk*.wee.*weqr','jkhkh;llkjkljklkjljl;weeklsfdjdsfj;weqtjhuafjs')\n self.assertFalse(computed_result)\n\n def test_starred_consumes_none_or_many(self):\n computed_result = main('.*chat','chat')\n self.assertTrue(computed_result)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-13T23:14:30.877", "Id": "505291", "Score": "1", "body": "This is very close, I think you just need to cover one more test case: `main('.*', '')` being `True` and then it should be complete." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-13T22:48:20.727", "Id": "256004", "ParentId": "255630", "Score": "0" } }, { "body": "<p>There are a few bugs that are still there starting from the original implementation, so I'm posting this as a late review because this won't fit in a comment. The shape of <code>Attempt</code> has changed from the original with the most recent updates from @Moye, but the root causes of the bugs are essentially the same.</p>\n<p>Let's temporarily add some debugging print statements to <code>take_next</code>:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def take_next(attempt: Attempt) -&gt; Optional[Union[DecisionPoint, Attempt]]:\n &quot;&quot;&quot;Returns None if no next match is possible; otherwise, returns either \n a single progression of the attempt — i.e., a single character moved into\n the matched field from the remaining field — or, in the case of a wildcard,\n both the greedy and non-greedy next possibilities.&quot;&quot;&quot;\n\n print(attempt)\n\n if (len(attempt.remaining_string) == 0\n or len(attempt.remaining_tokens) == 0):\n print(&quot; No next steps.&quot;)\n return None\n next_token_to_match_in_pattern = attempt.remaining_tokens[0]\n next_char_to_match_in_string = attempt.remaining_string[0]\n\n if next_token_to_match_in_pattern.is_starred:\n greedy = take_next_greedy(attempt)\n non_greedy = take_next_non_greedy(attempt, starred=True)\n print(f&quot; greedy --&gt; {greedy}&quot;)\n print(f&quot; non-greedy --&gt; {non_greedy}&quot;)\n return DecisionPoint(greedy=greedy, non_greedy=non_greedy)\n\n if (next_token_to_match_in_pattern.character == next_char_to_match_in_string\n or next_token_to_match_in_pattern.character == '.'):\n next_step = take_next_non_greedy(attempt)\n print(f&quot; --&gt; {next_step}&quot;)\n return next_step\n\n print(&quot; No next steps.&quot;)\n</code></pre>\n<hr />\n<p>The first bug: when comparing with a starred character in the pattern, we don't check if that character is the same as the current character in the string (either that, or if the starred character is the wildcard <code>.</code>).</p>\n<p>For example, for <code>main(pattern='x*', string='a')</code>, we have:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Attempt(matched_string='', remaining_string='a', remaining_tokens=[Token(character='x', is_starred=True)])\n greedy --&gt; Attempt(matched_string='x', remaining_string='', remaining_tokens=[Token(character='x', is_starred=True)])\n non-greedy --&gt; Attempt(matched_string='x', remaining_string='a', remaining_tokens=[])\nAttempt(matched_string='x', remaining_string='', remaining_tokens=[Token(character='x', is_starred=True)])\n No next steps.\nAttempt(matched_string='x', remaining_string='a', remaining_tokens=[])\n No next steps.\n</code></pre>\n<ul>\n<li>The greedy next step consumed <code>a</code> from the string, which shouldn't have happened given that the pattern is <code>x*</code>.</li>\n<li>The non-greedy next step didn't consume any characters from the string yet it has <code>matched_string='x'</code>. Only <code>matched_string</code> being wrong here makes this more of a cosmetic issue since the implementation doesn't depend on the value of <code>matched_string</code> for decision making.</li>\n<li>Examining an <code>Attempt</code> with <code>remaining_string='', remaining_tokens=[Token(character='x', is_starred=True)]</code> yields no next steps, which is incorrect. This is actually a concrete example of the second bug; more on this below.</li>\n</ul>\n<p>For this query the implementation returns the correct answer of <code>False</code>, but for the wrong reasons.</p>\n<hr />\n<p>The second bug: <code>take_next</code> immediately concludes that there are no valid next steps if either of the following are true:</p>\n<ul>\n<li><code>attempt.remaining_string</code> is an empty string</li>\n<li><code>attempt.remaining_tokens</code> is empty</li>\n</ul>\n<p>This is incorrect because even if <code>attempt.remaining_string</code> is an empty string, we can still have a match if all the tokens in <code>attempt.remaining_tokens</code> are starred.</p>\n<p>So for <code>main(pattern='.*', string='')</code>,</p>\n<pre class=\"lang-none prettyprint-override\"><code>Attempt(matched_string='', remaining_string='', remaining_tokens=[Token(character='.', is_starred=True)])\n No next steps.\n</code></pre>\n<p>the current implementation doesn't see a path forward from an <code>Attempt</code> with an empty <code>remaining_string</code> and immediately returns <code>None</code> from <code>take_next</code>. What it should return is <code>Attempt(matched_string='', remaining_string='', remaining_tokens=[])</code>.</p>\n<p>To summarize what we can conclude based on the state of <code>Attempt</code>:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th><code>Attempt</code> state</th>\n<th>Conclusion</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>remaining_string==''</code> and <code>remaining_tokens==[]</code></td>\n<td>pattern successfully matches the string (which you've correctly covered in <code>main_loop</code>)</td>\n</tr>\n<tr>\n<td><code>remaining_string==''</code> and <code>remaining_tokens</code> is not empty</td>\n<td>could have next valid steps; must inspect further to find out</td>\n</tr>\n<tr>\n<td><code>remaining_string</code> is not empty and <code>remaining_tokens==[]</code></td>\n<td>no possible next valid steps</td>\n</tr>\n<tr>\n<td><code>remaining_string</code> is not empty and <code>remaining_tokens</code> is not empty</td>\n<td>could have next valid steps; must inspect further to find out</td>\n</tr>\n</tbody>\n</table>\n</div>", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-07T00:48:01.437", "Id": "256826", "ParentId": "255630", "Score": "0" } } ]
{ "AcceptedAnswerId": "255634", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-04T23:15:41.463", "Id": "255630", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "reinventing-the-wheel", "regex" ], "Title": "A simplified regular expression matcher" }
255630
<p>The following short program is a collection of routines for detecting the dependencies among a project’s component files. Dependencies serve as a rough measure of the complexity of a program. Minimizing inter-file dependencies is a worthy goal, since understanding and refactoring a complex program is often challenging. However, Common Lisp can support a wide latitude of inter-file dependencies within a compilation unit, so it is generally not advisable to sacrifice program modularity in order to remove all dependencies.</p> <p>This analysis of inter-file dependencies is applied to the files in a specified directory. The pathname for this directory is assumed to be the value of <code>*default-pathname-defaults*</code>, which must be assigned before detecting dependencies. Which files are included is determined by supplying a standard Common Lisp filespec, which defaults to “*.lisp”.</p> <p>A simple example of a dependency is the situation where a function is defined in one file, but used in a different file. In this case the using file depends on the defining file. But there are a number of other kinds of definitional dependencies checked besides defun, including defmacro, defparameter, defvar, defmethod, and defstruct.</p> <p>More complex examples of dependencies include codependencies, where several files depend on each other. If two files each contain definitions used by the other, then they are codependent. Multiple files can be circularly dependent on each other, also making them codependent.</p> <p>The amount of information printed to the terminal can be controlled by the key parameter verbose. The verbose option indicates why the files are dependent. For example, entering (display-all-dependencies) at the REPL simply prints out all detected file dependencies. But entering (display-all-dependencies :verbose t) will additionally show which symbols in the dependent file have definitions in another file.</p> <p><strong>Interface</strong></p> <p>function: <code>display-all-dependencies (&amp;key (pathspec &quot;*.lisp&quot;) verbose)</code></p> <p>Prints out all the dependencies and codependencies among all the files matching the directory pathspec in <code>*default-pathname-defaults*</code></p> <p>function: <code>file-depends-on-what (file1 &amp;key (pathspec &quot;*.lisp&quot;) verbose)</code></p> <p>Prints out all the files which a given file depends on.</p> <p>function: <code>file1-depends-on-file2 (file1 file2 &amp;key verbose)</code></p> <p>Determines if file1 depends on file2.</p> <pre><code>;;; Filename: dependencies.lisp ;;; Finds the dependencies among files (ie, inter-file references) in a project directory. ;;; Assumes the project files have already been loaded, and ;;; that *default-pathname-defaults* points to the project directory. (in-package :cl-user) #-:alexandria (progn (ql:quickload :alexandria) (push :alexandria *features*)) #-:cl-ppcre (ql:quickload :cl-ppcre) (use-package :alexandria) (use-package :cl-ppcre) (defun purify-file (file) &quot;Transform problematic symbols to benign nil in file, before reading. Returns a string of altered file content.&quot; (let ((file-string (alexandria:read-file-into-string file))) (ppcre:regex-replace-all &quot;[ \t\r\n]'[A-Za-z0-9!@$%&amp;*_+:=&lt;.&gt;/?-]+&quot; file-string &quot; nil&quot;) (ppcre:regex-replace-all &quot;[(][qQ][uU][oO][tT][eE][ \t\r\n]+[A-Za-z0-9!@$%&amp;*_+:=&lt;.&gt;/?-]+[)]&quot; file-string &quot;nil&quot;))) (defun collect-symbols (tree) &quot;Collects all of the symbols in a form.&quot; (let ((all-items (alexandria:flatten tree))) (delete-if (lambda (item) (or (not (symbolp item)) (find-symbol (symbol-name item) :cl))) (delete-duplicates all-items)))) (defun collect-defs (forms) &quot;Collects all of the defined names in forms, excluding defstructs.&quot; (loop for form in forms when (member (first form) '(defun defmacro defparameter defvar defmethod)) collect (second form))) (defun collect-defstructs (forms) &quot;Collects all of the defined defstruct names in forms.&quot; (loop for form in forms when (member (first form) '(defstruct)) if (symbolp (second form)) collect (second form) else if (listp (second form)) collect (first (second form)))) (defun pseudo-load (file) &quot;Attempt to read a file doing what LOAD would do. May not always do the right thing. Returns list of all forms, including package prefixes. Based on function provided by tfb on Stack Overflow.&quot; (let ((file-string (purify-file file)) (*package* *package*)) (with-input-from-string (in-stream file-string) (loop for form = (read in-stream nil in-stream) while (not (eql form in-stream)) when (and (consp form) (eq (first form) 'in-package)) do (setf *package* (find-package (second form))) collect form)))) (defun file1-depends-on-file2 (file1 file2 &amp;key verbose) &quot;Determines if file1 depends on file2.&quot; (let* ((1forms (pseudo-load file1)) (all1-syms (collect-symbols 1forms)) (defstruct1-syms (collect-defstructs 1forms)) (1syms (set-difference all1-syms defstruct1-syms :test #'equal)) (forms2 (pseudo-load file2)) (def2-syms (collect-defs forms2)) (defstruct2-syms (collect-defstructs forms2)) (11syms (loop for defstruct2-sym in defstruct2-syms append (loop for 1sym in 1syms when (and (not (eql defstruct2-sym 1sym)) (search (format nil &quot;~S&quot; defstruct2-sym) (format nil &quot;~S&quot; 1sym))) collect 1sym)))) (when verbose (format t &quot;~%~A symbols:~%~S~%&quot; file1 1syms) (format t &quot;~%~A symbols:~%~S~%&quot; file2 def2-syms) (format t &quot;~%~A structures:~%~S~%&quot; file2 defstruct2-syms) (format t &quot;~%~A symbols dependent on ~A:~%&quot; file1 file2)) (append (intersection 1syms def2-syms) 11syms))) (defun file-depends-on-what (file1 &amp;key (pathspec &quot;*.lisp&quot;) verbose) &quot;Prints out all dependencies of a file in directory = *default-pathname-defaults*.&quot; (let ((files (mapcar #'file-namestring (directory pathspec)))) (loop for file2 in files unless (equal file1 file2) do (let ((deps (file1-depends-on-file2 file1 file2))) (when deps (if verbose (format t &quot;~%~A depends on ~A~%~S~%&quot; (file-namestring file1) (file-namestring file2) deps) (format t &quot;~%~A depends on ~A~%&quot; (file-namestring file1) (file-namestring file2)))))))) (defun all-path-cycles (node current-path adjacency-table) &quot;Recursively follow all paths in a dependency network.&quot; (if (member node current-path :test #'equal) (list (subseq current-path 0 (1+ (position node current-path :test #'equal)))) (loop for child in (gethash node adjacency-table) append (all-path-cycles child (cons node current-path) adjacency-table)))) (defun codependents (node-list dependencies) &quot;Returns all dependent cycles for all nodes.&quot; (let ((adjacency-table (make-hash-table :test #'equal))) (loop for dep in dependencies do (push (second dep) (gethash (first dep) adjacency-table))) (loop for node in node-list append (all-path-cycles node nil adjacency-table)))) (defun display-codependencies (dependencies) &quot;Prints out all codependencies among a group of files.&quot; (format t &quot;~%Codependent files (with circular reference):~%&quot;) (let* ((node-list (remove-duplicates (alexandria:flatten dependencies) :test #'equal)) (codependents (remove-duplicates (codependents node-list dependencies) :test (lambda (set1 set2) (alexandria:set-equal set1 set2 :test #'equal))))) (loop for co-set in codependents do (format t &quot;~S~%&quot; co-set)))) (defun display-all-dependencies (&amp;key (pathspec &quot;*.lisp&quot;) verbose) &quot;Prints out all dependencies of every pathspec file in directory = *default-pathname-defaults*.&quot; (let ((files (mapcar #'file-namestring (directory pathspec)))) (loop with dependencies for file1 in files do (loop for file2 in files unless (equal file1 file2) do (let ((deps (file1-depends-on-file2 file1 file2))) (when deps (push (list file1 file2) dependencies) (if verbose (format t &quot;~%~A depends on ~A~%~S~%&quot; (file-namestring file1) (file-namestring file2) deps) (format t &quot;~%~A depends on ~A~%&quot; (file-namestring file1) (file-namestring file2)))))) finally (display-codependencies dependencies)))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T08:24:48.337", "Id": "504716", "Score": "0", "body": "Nice. Will you publish it on Github or Gitlab?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:44:26.860", "Id": "504742", "Score": "0", "body": "Thanks. It’s on my github site, but does “publish” mean something else to make it freely available (don't use github much)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T00:08:06.527", "Id": "504795", "Score": "1", "body": "To me, it means the source code is visible on a forge, with whatever licence (but preferably with one licence), and *on its own repository* (not mangled with lots of utilities), so it's easy to download it and watch activity (and contribute). Bonus point if it has an ASDF file." } ]
[ { "body": "<p>Some general comments first. And to prefix that, at a glance the code\nitself looks quite alright to me, I just have some comments on the\ndetails to make it even nicer.</p>\n<p>Arguably the first thing to note is to create <a href=\"https://common-lisp.net/project/asdf/asdf/The-defsystem-form.html#The-defsystem-form\" rel=\"nofollow noreferrer\">an ASDF\ndefinition</a>\nand don't require QuickLisp as the main loading mechanism. That usually\nentails one more <code>.asd</code> file and is otherwise painless. It will also\nallow you and others to easily load the whole system with one function\nfrom other systems.</p>\n<p><code>#-:alexandria</code> - that's usually written as <code>#-alexandria</code> as the\n<code>*features*</code> list mostly contains keywords anyway and, more importantly,\nthe reader function for <code>#-</code> reads the argument as a keyword unless\notherwise specified.</p>\n<p>The <code>use-package</code> calls should go into the to-be-written\n<a href=\"http://clhs.lisp.se/Body/m_defpkg.htm\" rel=\"nofollow noreferrer\"><code>defpackage</code></a> declaration.</p>\n<p>The functions all have docstrings, which is good, though it might also\nhelp to specify a bit more what the types of the inputs and outputs are.\nYou could of course also add\n<a href=\"http://clhs.lisp.se/Body/m_check_.htm\" rel=\"nofollow noreferrer\"><code>check-type</code></a> /\n<a href=\"http://clhs.lisp.se/Body/d_type.htm\" rel=\"nofollow noreferrer\"><code>declare</code></a> statements to make\nthose explicit, but for me, the reader, something like &quot;Returns a LIST\nof all dependent cycles for all nodes.&quot; would already be enough to\nsatisfy my curiosity.</p>\n<p>IMO, <code>T</code> and <code>NIL</code> should be written uppercase. That's because they're\nway too special to not have them stand out more.</p>\n<p>Pathspecs should probably be written <code>#P&quot;*.lisp&quot;</code> to be very clear about\nthe type.</p>\n<p>I'm a bit wary of the <code>flatten</code> calls, but if you think that the\nadditional allocations aren't a problem, then it's probably fine. It's\njust a point for optimisation to avoid too many intermediate lists.</p>\n<p>If the <code>equal</code> tests could be replaced with <code>eql</code> or <code>eq</code>, it might also\nbe better, but I'm not sure that's possible.</p>\n<p>For <code>file1-depends-on-file2</code>, the name is actually mostly fine by me,\nthough usuallya boolean-ish result would warrant\n<code>file1-depends-on-file2-p</code> (&quot;predicate&quot;). Also the <code>verbose</code> can\nprobably be a regular argument if this isn't going to be called by a\nuser directly. In it though, the names keyed by their source file look\nvery awkward. Consider a helper function via <code>flet</code>/<code>labels</code> or even\n<code>defun</code> to get rid of the duplication and weird naming.</p>\n<p>It also stands out to me that <code>intersection</code> isn't using <code>:test</code>, but\nthe other call to <code>set-difference</code> does - is that a bug? It might even\nmake sense to define some helpers with the right equality relation baked\nin eventually.</p>\n<p>The <code>format</code> calls look good, only in <code>display-all-dependencies</code> I'd\nconsider merging the verbose and non-verbose case via <code>~@[~A~]</code> and the\nargument <code>(and verbose deps)</code> (so combined that'd be\n<code>(format T &quot;...~@[~A~]~%&quot; ... (and verbose deps))</code>).</p>\n<p><code>loop</code> is a bit over-used IMO when you have two loops inside each other.\nIt also looks like this would be better abstracted by a helper function\nthat creates a list of all those pairs of files, there might even be one\nin the <code>alexandria</code> or <code>arnesi</code> packages.</p>\n<p>Pairs like <code>(list file1 file2)</code> might very well just use a single cons\ncell too, so <code>(cons file1 file2)</code> would suffice (and makes it absolutely\nclear it's a pair).</p>\n<p>Lastly, for loading the files, the <code>purify-file</code> function attempts to\nthrow away &quot;problematic&quot; symbols, which are what, quoted symbols? I\ndon't exactly see why this function, like it is, helps a lot. Instead\nwhat I'd probably suggest, is to disable evaluation of code when <code>read</code>\nis called (e.g. you don't want to execute anything while reading the\nfiles, something like\n<code>(read-from-string &quot;#.(format T \\&quot;Hello, world!~%\\&quot;)&quot;)</code>) quite handily\ndemonstrates the dangers). Setting\n<a href=\"http://clhs.lisp.se/Body/v_rd_sup.htm#STread-suppressST\" rel=\"nofollow noreferrer\"><code>*read-suppress*</code></a>\nto true would be a start, or even setting\n<a href=\"http://clhs.lisp.se/Body/v_rd_eva.htm#STread-evalST\" rel=\"nofollow noreferrer\"><code>*read-eval*</code></a> to\nfalse. See also\n<a href=\"http://clhs.lisp.se/Body/m_w_std_.htm\" rel=\"nofollow noreferrer\"><code>with-standard-io-syntax</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T16:58:27.567", "Id": "506151", "Score": "1", "body": "Wow, thank you for such a thorough and informative analysis. Looking forward to investigating & trying to incorporate these improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T23:00:26.090", "Id": "506722", "Score": "1", "body": "Can you help me understand the extra allocations with `alexandria:flatten`? They are not apparent in bytes consed:\n`(time (alexandria:flatten '(a b (1 2 . 10) c)))\nEvaluation took:\n 0.000 seconds of real time\n 0.000000 seconds of total run time (0.000000 user, 0.000000 system)\n 100.00% CPU\n 3,936 processor cycles\n 0 bytes consed`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T10:18:14.393", "Id": "506766", "Score": "1", "body": "@davypough `TIME` isn't super accurate on some implementations (like SBCL). Try CCL and you should see more detail (e.g. I get `96 bytes of memory allocated.` for the `FLATTEN` call)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T14:14:43.103", "Id": "256336", "ParentId": "255635", "Score": "1" } } ]
{ "AcceptedAnswerId": "256336", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T02:47:40.143", "Id": "255635", "Score": "2", "Tags": [ "file-system", "common-lisp" ], "Title": "Detecting Dependencies in Common Lisp Project Files" }
255635
<p>I am learning C++ by implementing small design problems. I have tried to implement LRU cache and the implementation that I have attached here works fine.</p> <p>However, I am not sure whether my code is in line with C++ best practices. For eg. Unnecessary use of ref, pointers and const, or missing inline function, namespaces or macros.</p> <p>Please suggest how to make this code production grade.</p> <p>PS: This is my first question. All suggestions around the question detailing are welcome.</p> <p>Main.cpp</p> <pre><code>/****************************************************************************** Implement LRU Cache *******************************************************************************/ #include &quot;unordered_map&quot; #include &quot;string&quot; #include &quot;Page.h&quot; #include &quot;Disk.h&quot; #include &quot;Cache.h&quot; int main() { Disk disk(10); Cache cache(disk, 2); cache.getPage(1); cache.getPage(2); disk.writePage(2, &quot;Hello&quot;); cache.getPage(2); cache.getPage(1); cache.getPage(3); return 0; } </code></pre> <p>Page.h</p> <pre><code>struct Page { int id; std::string content; Page* prev; Page* next; Page(int id): id(id), content(&quot;---&quot;), prev(nullptr), next(nullptr) { } int getId() { return id; } std::string&amp; getContent() { return content; } void setContent(const std::string&amp; newContent) { content = newContent; } }; </code></pre> <p>Disk.h</p> <pre><code>class Disk { Page** pageAr = nullptr; size_t pageCount = 0; public: Disk(size_t pageCount): pageCount(pageCount) { pageAr = new Page*[pageCount]; for(int i=0; i&lt;pageCount; ++i) { pageAr[i] = new Page(i); } } Page* readPage(int pageIndex) { printf(&quot;Reading page %d from DISK\n&quot;, pageIndex); return pageAr[pageIndex]; } void writePage(int pageIndex, const std::string&amp; newContent) { printf(&quot;Updating page %d on DISK to %s\n&quot;, pageIndex, newContent.c_str()); Page* pg = pageAr[pageIndex]; pg-&gt;setContent(newContent); } ~Disk() { for(int i=0; i&lt;pageCount; i++) { delete pageAr[i]; } delete [] pageAr; pageAr = nullptr; pageCount = 0; } }; </code></pre> <p>Cache.h</p> <pre><code>class Cache { Disk&amp; disk; size_t cacheSize; Page* pageQueueStart; Page* pageQueueEnd; std::unordered_map&lt;int, Page*&gt; pageTable; void addPage(Page* p) { p-&gt;prev = nullptr; p-&gt;next = pageQueueStart; if(pageQueueStart != nullptr) pageQueueStart-&gt;prev = p; pageQueueStart = p; if(pageQueueEnd == nullptr) pageQueueEnd = p; pageTable[p-&gt;getId()] = p; } void removePage(Page* p) { if(p-&gt;prev != nullptr) { p-&gt;prev-&gt;next = p-&gt;next; } else { pageQueueStart = p-&gt;next; } if(p-&gt;next != nullptr) { p-&gt;next-&gt;prev = p-&gt;prev; } else { pageQueueEnd = p-&gt;prev; } p-&gt;prev = nullptr; p-&gt;next = nullptr; pageTable.erase(p-&gt;getId()); } void removeLeastRecentlyUsedPage() { printf(&quot;Remove Page %d from CACHE\n&quot;, pageQueueEnd-&gt;getId()); if(pageQueueEnd-&gt;prev) pageQueueEnd-&gt;prev-&gt;next = nullptr; pageQueueEnd-&gt;prev = nullptr; pageQueueEnd-&gt;next = nullptr; pageTable.erase(pageQueueEnd-&gt;getId()); } public: Cache(Disk&amp; disk, size_t cacheSize): disk(disk), cacheSize(cacheSize), pageQueueStart(nullptr), pageQueueEnd(nullptr) { } Page* getPage(int pageIndex) { printf(&quot;Reading page %d from CACHE\n&quot;, pageIndex); if(pageTable.find(pageIndex) == pageTable.end()) { printf(&quot;\tMISS\n&quot;); Page* pageFromDisk = disk.readPage(pageIndex); if(pageTable.size() &gt;= cacheSize) removeLeastRecentlyUsedPage(); addPage(pageFromDisk); } else { printf(&quot;\tHIT\n&quot;); Page* pageFromCache = pageTable[pageIndex]; removePage(pageFromCache); addPage(pageFromCache); } printf(&quot;Page content : %s\n&quot;, pageTable[pageIndex]-&gt;getContent().c_str()); return pageTable[pageIndex]; } ~Cache() { pageQueueStart = nullptr; pageQueueEnd = nullptr; } }; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T13:46:16.253", "Id": "504494", "Score": "3", "body": "To those that down voted this question or voted to close, please leave a comment why you down voted or voted to close. As far as I can tell this is a valid question for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T13:42:38.963", "Id": "504963", "Score": "0", "body": "I don't have time now to write a proper review, but object caches likely benefit from `std::weak_ptr` - you might want to keep a collection (perhaps a `std::unordered_map`) of weak pointers, which you can convert to shared pointer before giving out. Worth reading about, anyway." } ]
[ { "body": "<p>Some preliminary observations to get you started:</p>\n<h1>Allocation</h1>\n<p>Since <code>Disk</code> and <code>Cache</code> aren't memory management classes, do not\nwrite your own memory management code, since C++ memory management is\nerror-prone. Instead, use standard library facilities like\n<code>std::vector</code> whenever possible.</p>\n<h1>Move semantics</h1>\n<p>This always copies the argument:</p>\n<pre><code>void setContent(const std::string&amp; newContent)\n{\n content = newContent;\n}\n</code></pre>\n<p>Take a <code>std::string</code> and use <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"nofollow noreferrer\"><code>std::move</code></a> instead.</p>\n<h1>Encapsulation</h1>\n<p>When a class is all-public, you don't need getters and setters.\nTherefore, <code>Page</code> should either be simply</p>\n<pre><code>struct Page {\n int id;\n std::string content{&quot;---&quot;};\n Page* prev;\n Page* next;\n};\n</code></pre>\n<p>or have private data members and proper encapsulation.</p>\n<h1>Miscellaneous</h1>\n<p>Headers from the standard library are usually delimited with <code>&lt;&gt;</code>\ninstead of <code>&quot;&quot;</code>. Moreover, header files should be self-contained and\ninclude the necessary header files, rather than rely on the source\nfile to include them beforehand. (Multiple inclusions of the same\nheader will be elided by the compiler.) You are also missing some\n<code>#include</code>s, such as <code>&lt;cstddef&gt;</code> and <code>&lt;cstdio&gt;</code>.</p>\n<p>Names from the C standard library should still be qualified as <code>std::</code>\nin C++.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:23:53.923", "Id": "255680", "ParentId": "255639", "Score": "2" } }, { "body": "<p>Few things I noticed</p>\n<h1>Const correctness</h1>\n<p>It is good practice to make methods as getters <code>const</code></p>\n<h1>Setting values in a destructor</h1>\n<p>No reason that I am aware of to do <code>pageAr = nullptr; pageCount = 0;</code> during destruction.</p>\n<h1>Range-based for loop</h1>\n<p>They are less error-prone (you can't mess up with indices) so I would suggest using them if possible</p>\n<h1>Miscellaneous</h1>\n<blockquote>\n<pre><code>std::string&amp; getContent()\n{\n return content;\n}\n</code></pre>\n</blockquote>\n<p>It is better to return <code>const std::string&amp;</code> because it seems that it is not intended to give a possibility to alter <code>content</code> using this getter</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:21:28.350", "Id": "255684", "ParentId": "255639", "Score": "2" } }, { "body": "<p>When I see pointers in a <code>class</code> and/or <code>struct</code> in my mind comes e serious potential for memory leaks unless a careful implementation has been considered.\nSince you would like comments on how to make this code closer to a production-level code, avoiding memory leaks is definitely a very important aspect.</p>\n<p>I will explain myself using an example:</p>\n<p>Let's say a teammate in the company you work with, uses your user-defined datatypes (Page, Disk, Cache), and at some point in the code he writes, he passes an object which is an instance of some of your datatypes to a function (a fairly innocent action). If he pass the object by value, then probably the whole production code is in serious trouble. Because passing-by-value any datatype (built-in or user-defined) invokes a copy operation of the object, as defined by the class declaration. Since you do not explicitly create your own copy constructor, the default one will be used which will result in copies of the pointers of the class, and this is prone to segmentation-fault. The reason is because you are going to have the same pointer (memory address) belong to two different objects. Once the function call finishes, the object in the class will be destroyed and will dereference the pointers that the object in the main code hold. Afterward, once the whole program exits, those pointers will be dereferenced again (or at least will be attempted to) and this is undefined behavior, which could break the whole runtime.</p>\n<p>So, since you have pointers in your classes or structs make sure to learn how to write at least correctly the copy constructor and copy assignment operators.</p>\n<p>That was not the end of the story. Sometimes in your code, you may have heavy objects and do not want to copy them around for performance reasons. This means that except from copy you may also want to check how to implement the move constructor.</p>\n<p>Fortunately, there is a way to avoid writing all the stuff yourself. One good option is to use <code>std::vector</code> which handles the above correctly and efficiently. Otherwise, you can make your own implementation using pointers but check out how to do it correctly!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T08:38:37.723", "Id": "255838", "ParentId": "255639", "Score": "2" } } ]
{ "AcceptedAnswerId": "255680", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T05:53:37.423", "Id": "255639", "Score": "2", "Tags": [ "c++", "object-oriented", "c++11", "design-patterns" ], "Title": "LRU Cache Implementation in C++" }
255639
<p>I have the method below, which generates backtesting results. However, it's highly unreadable. What could you possibly suggest to me in order to make it more readable?</p> <pre class="lang-csharp prettyprint-override"><code>public DataTable GenerateResultTable(List&lt;BacktestResult&gt; data) { var table = new DataTable(); table.Columns.Add(&quot;Pair&quot;); table.Columns.Add(&quot;Buys&quot;); table.Columns.Add(&quot;Avg Profit %&quot;); table.Columns.Add(&quot;Cum Profit %&quot;); table.Columns.Add($&quot;Tot Profit {_backtestOptions.StakeCurrency}&quot;); table.Columns.Add(&quot;Tot Profit %&quot;); table.Columns.Add(&quot;Avg Duration&quot;); table.Columns.Add(&quot;Wins&quot;); table.Columns.Add(&quot;Draws&quot;); table.Columns.Add(&quot;Losses&quot;); // the number of the pairs in the backtest results var maxOpenOrders = data.GroupBy(e =&gt; e.Pair).Count(); // Split results for each pair var query = data.GroupBy(e =&gt; e.Pair).Select(e =&gt; new { Pair = e.Key, Count = e.Count(), Value = e }); // in case there are no records to show // if there are no rows, it throws an exception.. if (!query.Any()) { table.Rows.Add(&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;); } foreach (var result in query) { var _profitSum = result.Value.Sum(e =&gt; e.ProfitPercentage); var _profitTotal = _profitSum / maxOpenOrders; var key = result.Pair; var trades = result.Count; var profitMean = trades &gt; 0 ? result.Value.Average(e =&gt; e.ProfitPercentage) : 0; var profitMeanPercentage = trades &gt; 0 ? result.Value.Average(e =&gt; e.ProfitPercentage) * 100 : 0; var profitSum = _profitSum; var profitSumPercentage = _profitSum * 100; var profitTotalAbs = result.Value.Sum(e =&gt; e.ProfitAbs); var profitTotal = _profitTotal; var profitTotalPercentage = _profitTotal * 100; var avgDuration = trades &gt; 0 ? Math.Round(result.Value.Average(e =&gt; e.TradeDuration)) : 0; var wins = result.Value.Count(e =&gt; e.ProfitAbs &gt; 0); var draws = result.Value.Count(e =&gt; e.ProfitAbs == 0); var losses = result.Value.Count(e =&gt; e.ProfitAbs &lt; 0); table.Rows.Add(key, trades, $&quot;{profitMeanPercentage:f2}&quot;, $&quot;{profitSumPercentage:f2}&quot;, $&quot;{profitTotalAbs:f8}&quot;, $&quot;{profitTotalPercentage:f2}&quot;, $&quot;{TimeSpan.FromMinutes((double)avgDuration):h\\:mm\\:ss}&quot;, wins, draws, losses); } return table; } public class BacktestOptions { public string StakeCurrency { get; set; } public List&lt;string&gt; Pairs { get; set; } public string StrategyName { get; set; } public decimal StakeAmount { get; set; } public decimal OpenFee { get; set; } public decimal CloseFee { get; set; } } public class BacktestResult { public string Pair { get; set; } public decimal ProfitPercentage { get; set; } public decimal ProfitAbs { get; set; } public decimal OpenRate { get; set; } public decimal CloseRate { get; set; } public DateTime OpenDate { get; set; } public DateTime CloseDate { get; set; } public decimal OpenFee { get; set; } public decimal CloseFee { get; set; } public decimal Amount { get; set; } public decimal TradeDuration { get; set; } public SellType SellReason { get; set; } } </code></pre> <p>appsettings.json</p> <pre class="lang-csharp prettyprint-override"><code>{ &quot;BacktestConfiguration&quot;: { &quot;StakeCurrency&quot;: &quot;USDT&quot;, &quot;Pairs&quot;: [ &quot;TRXUSDT&quot; ], &quot;StrategyName&quot;: &quot;RsiStrategy&quot;, &quot;StakeAmount&quot;: 1000, &quot;OpenFee&quot;: 0.001, &quot;CloseFee&quot;: 0.001 } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T10:22:45.500", "Id": "504461", "Score": "0", "body": "Please share with use the code of the `BacktestResult` class and the declaration of `_backtestOptions`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T10:33:10.150", "Id": "504464", "Score": "0", "body": "@PeterCsala, added them both to the question. `_backtestOptions` is basically BacktestOptions retrieved from `appsettings.json`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T11:33:55.900", "Id": "504470", "Score": "0", "body": "Why do you generate a `DataTable`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T11:43:52.893", "Id": "504471", "Score": "0", "body": "@BCdotWEB, https://github.com/minhhungit/ConsoleTableExt" } ]
[ { "body": "<p>Here are my observations:</p>\n<ul>\n<li><p><code>List&lt;BacktestResult&gt; data</code>: Please try to use more expressive names than <code>data</code>. It is way too general and it does not help the reader / maintainer of the code. (same apply to <code>table</code> and <code>query</code>)</p>\n</li>\n<li><p>Populating columns: Your implementation has a lot of repetition in it: <code>tables.Columns.Add</code>.</p>\n<ul>\n<li>One way to reduce that by using the <code>AddRange</code>:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var table = new DataTable();\ntable.Columns.AddRange(new []\n{\n new DataColumn(&quot;Pair&quot;), \n new DataColumn(&quot;Buys&quot;), \n new DataColumn(&quot;Avg Profit %&quot;), \n new DataColumn(&quot;Cum Profit %&quot;), \n new DataColumn($&quot;Tot Profit {_backtestOptions.StakeCurrency}&quot;), \n new DataColumn(&quot;Tot Profit %&quot;), \n new DataColumn(&quot;Avg Duration&quot;), \n new DataColumn(&quot;Wins&quot;), \n new DataColumn(&quot;Draws&quot;), \n new DataColumn(&quot;Losses&quot;), \n});\n</code></pre>\n<p>We are almost there, here we have repeated the <code>new DataColumn</code>. With the following technique you can separate data and logic:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var columns = new[]\n{\n &quot;Pair&quot;, &quot;Buys&quot;, &quot;Avg Profit %&quot;, &quot;Cum Profit %&quot;, $&quot;Tot Profit {_backtestOptions.StakeCurrency}&quot;,\n &quot;Tot Profit %&quot;, &quot;Avg Duration&quot;, &quot;Wins&quot;, &quot;Draws&quot;, &quot;Losses&quot;\n};\n\ntable.Columns.AddRange(columns.Select(name =&gt; new DataColumn(name)).ToArray());\n</code></pre>\n<ul>\n<li><code>data.GroupBy(e =&gt; e.Pair)</code>: This has been called twice, but unnecessarily.\n<ul>\n<li>Materialize it by calling the <code>ToList</code> or <code>ToArray</code> on it:</li>\n<li>With this approach we could get rid of the <code>maxOpenOrders</code> variable.</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var resultsGroupByPair = data.GroupBy(e =&gt; e.Pair).ToArray();\nvar query = resultsGroupByPair.Select(br =&gt; new { Pair = br.Key, Count = br.Count(), Value = br });\n//...\nvar _profitTotal = _profitSum / resultsGroupByPair.Length; \n</code></pre>\n<ul>\n<li><code>query</code>: Same applies here, <em>Possible multiple enumeration</em>\n<ul>\n<li>Materialize it by calling the <code>ToList</code> or <code>ToArray</code> on it</li>\n</ul>\n</li>\n<li><code>if there are no rows, it throws an exception..</code>: This comment is not align with the code. Try to comment the <strong>Whys</strong> and <strong>Why not</strong>s, not the <strong>what</strong> and <strong>how</strong>. The latter two should be clear by the code itself, but the chosen strategy (and the excluded alternatives) might not be obvious from the code.</li>\n<li><code>profitMean</code>, <code>profitSum</code>, <code>profitTotal</code>: They are unused. If they are not needed then delete them.</li>\n<li><code>trades &gt; 0 ?</code>: This condition has been repeated several times.\n<ul>\n<li>Introduce a local variable and refer to that one instead: <code>bool isTradesPositive</code></li>\n</ul>\n</li>\n<li><code>result.Value.Average</code>, <code>result.Value.Sum</code>: Same as in the previous case. If you use the same expression multiple times then save its result into a variable.</li>\n<li><code>wins</code>, <code>draws</code>, <code>losses</code>: Instead do 3 iterations you can do it with a simple one.\n<ul>\n<li>For example with <code>Aggregate</code>:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var (wins, losses, draws) = result.Value.Aggregate((0, 0, 0), (outcome, e) =&gt;\n{\n if (e.ProfitAbs &gt; 0) outcome.Item1++;\n else if (e.ProfitAbs &lt; 0) outcome.Item2++;\n else outcome.Item3++;\n return outcome;\n});\n</code></pre>\n<p>or</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var (wins, losses, draws) = result.Value.Aggregate((0, 0, 0), \n ((int winCount, int loseCount, int drawCount) outcome, BacktestResult e) =&gt;\n {\n if (e.ProfitAbs &gt; 0) outcome.winCount++;\n else if (e.ProfitAbs &lt; 0) outcome.loseCount++;\n else outcome.drawCount++;\n return outcome;\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:01:13.023", "Id": "504474", "Score": "0", "body": "Thanks for your comprehensive answer! The second example with win, losses, draws doesn't work, because of `((int winCount, int loseCount, int drawCount) outcome, BacktestResult e)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:28:59.503", "Id": "504476", "Score": "0", "body": "@nop Could you please elaborate what do you mean by *doesn't work*? Does not compile? Does throw exception? Returns with three 0? or else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:48:27.640", "Id": "504480", "Score": "0", "body": "These are the exceptions https://pastebin.com/EXnVhAtL. https://i.imgur.com/XUno1Jy.png" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:52:53.890", "Id": "504485", "Score": "0", "body": "@nop This is compilation error. Let me check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:55:32.590", "Id": "504488", "Score": "0", "body": "@nop What C# and .NET version are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T13:37:47.333", "Id": "504492", "Score": "0", "body": "I'm using .NET 5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:18:18.343", "Id": "504496", "Score": "0", "body": "@nop It does compile, check [this dotnetfiddle](https://dotnetfiddle.net/zGgLHa). So, there should be something else in your project which causes this error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:32:55.263", "Id": "504500", "Score": "1", "body": "It's because of the specified types of the arguments. No idea why that is. I guess I will stick to the .Item1, 2, 3 way. Thanks again" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T10:58:47.227", "Id": "255644", "ParentId": "255640", "Score": "2" } } ]
{ "AcceptedAnswerId": "255644", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:30:18.110", "Id": "255640", "Score": "2", "Tags": [ "c#" ], "Title": "Making DataTable results more readable" }
255640
<p>everyone!I have created a bit ugly looking Tic Tac Toe console game using Java. I'm learning how to code and I would love to hear some comments about my code. Because it's quite streatforward, I'm not using classes and objects ( my assignment was not to use any ). Thank you in advance!</p> <pre><code>package com.company; import java.util.ArrayList; import java.util.Scanner; public class Main { public static Scanner scan = new Scanner(System.in); public static char[][] table = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} }; public static ArrayList&lt;Character&gt; picksTillNow = new ArrayList&lt;Character&gt;(); public static char playerOne = ' '; public static char playerTwo = ' '; public static void main(String[] args) { for(char i = '1'; i &lt;= '9'; i++){ picksTillNow.add(i); } printTable(); while (true){ playerOneChoice(); endGame(); playerTwoChoice(); endGame(); } } /** * Prints the table with no players choices made ( 1 - 9 ) */ public static void printTable() { for (int i = 0; i &lt; table.length; i++) { for (int j = 0; j &lt; table[i].length; j++) { System.out.print(table[i][j] + &quot; &quot;); } if (table[i][2] != 9) { System.out.println(); } } } /** * Prints the table with the players choice included * @param player - player 1 or player 2 * @param choice - char from 1 - 9 */ public static void printTable(int player, char choice){ for (int i = 0; i &lt; table.length ; i++) { for (int j = 0; j &lt; table[i].length; j++) { if(choice == table[i][j] &amp;&amp; player == 1){ //X table[i][j] = 'X'; }else if(choice == table[i][j] &amp;&amp; player == 2){ //O table[i][j] = 'O'; } System.out.print(table[i][j] + &quot; &quot;); } if(table[i][2] != 9){ System.out.println(); } } } /** * Asks for player one choice method and prints the table, checks if that position has been chosen */ public static void playerOneChoice(){ System.out.print(&quot;Играч 1: &quot;); playerOne = scan.next().charAt(0); if(picksTillNow.contains(playerOne)){ picksTillNow.remove(picksTillNow.indexOf(playerOne)); printTable(1, playerOne); }else{ playerOneChoice(); } } /** * Asks for player one choice method and prints the table, checks if that position has been chosen */ public static void playerTwoChoice(){ System.out.print(&quot;Играч 2: &quot;); playerTwo = scan.next().charAt(0); if(picksTillNow.contains(playerTwo)){ picksTillNow.remove(picksTillNow.indexOf(playerTwo)); printTable(2, playerTwo); }else{ playerTwoChoice(); } } /** * Checks for a winner. If yes - exits program */ public static void endGame(){ for(int i = 0; i &lt; table.length; i++){ if(table[i][0] == table[i][1] &amp;&amp; table[i][1] == table[i][2] &amp;&amp; table[0][i] != 'О'){ System.out.println(&quot;Победа!&quot;); System.exit(0); } } for(int j = 0; j &lt; table.length; j++){ if(table[0][j] == table[1][j] &amp;&amp; table[1][j] == table[2][j] &amp;&amp; table[j][0] != 'O'){ System.out.println(&quot;Победа!&quot;); System.exit(0); } } if(table[0][0] == table[1][1] &amp;&amp; table[1][1] == table[2][2] &amp;&amp; table[0][0] != 'O'){ System.out.println(&quot;Победа!&quot;); System.exit(0); } if(table[0][2] == table[1][1] &amp;&amp; table[1][1] == table[2][0] &amp;&amp; table[0][2] != 'O'){ System.out.println(&quot;Победа!&quot;); System.exit(0); } if(picksTillNow.isEmpty()) System.exit(0); } } </code></pre>
[]
[ { "body": "<p>Your formatting seems to be inconsistent, use an automatic code formatter (your IDE most likely has one).</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static Scanner scan = new Scanner(System.in);\n</code></pre>\n<p>The usage of the scanner (or streams in general) should most likely be scoped. Streams are rather easily associated with native resources which must be destroyed explicitly to be freed.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static char[][] table = {\n {'1', '2', '3'},\n {'4', '5', '6'},\n {'7', '8', '9'}\n };\n</code></pre>\n<p>Why is the table prefilled with values?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static ArrayList&lt;Character&gt; picksTillNow = new ArrayList&lt;Character&gt;();\n</code></pre>\n<p>Try to always use the most super-class you can use and get away with, makes it easier to make sure that you're coupling classes through methods of the actual implementation instead of the interface. In this case, declare the variable with <code>List</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static char playerOne = ' ';\n public static char playerTwo = ' ';\n</code></pre>\n<p>You're preparing these, but you only use them in a very limited scope, you should declare them there.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for(char i = '1'; i &lt;= '9'; i++){\n picksTillNow.add(i);\n }\n</code></pre>\n<p><a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">Autoboxing</a>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> while (true){\n</code></pre>\n<p>You could also have a <code>boolean</code> like <code>running</code> or <code>playing</code> or <code>gameRunning</code> and set it depending on the return value of `endGame().</p>\n<p>Or, as the number of turns is fixed, you might do a mixture of both:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int turn = 0;\n\nwhile (turn++ &lt; 9 &amp;&amp; nobodyHasWonYet) {\n // Logic.\n}\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> endGame();\n</code></pre>\n<p>That's a bad name for the method, as it does not always end the game.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for (int i = 0; i &lt; table.length; i++) {\n for (int j = 0; j &lt; table[i].length; j++) {\n</code></pre>\n<p>I'm a persistent advocate that you're only allowed to use single-letter variable names when dealing with dimensions (&quot;x&quot;, &quot;y&quot;, &quot;z&quot;), and that excludes using <code>i</code> and <code>j</code>). In this case actually, using <code>x</code> and <code>y</code> as variable names would improve the readability of the code. Even better would be using <code>row</code> and <code>column</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (table[i][2] != 9) {\n System.out.println();\n }\n</code></pre>\n<p>But the default value of this field is overwritten at some point, isn't it?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> }else{\n playerOneChoice();\n }\n</code></pre>\n<p>You're recursing here, so keeping to hit Return without entering something should at some point crash your game because of a stackoverflow.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public static void endGame(){\n for(int i = 0; i &lt; table.length; i++){\n if(table[i][0] == table[i][1] &amp;&amp; table[i][1] == table[i][2] &amp;&amp; table[0][i] != 'О'){\n System.out.println(&quot;Победа!&quot;);\n System.exit(0);\n }\n }\n\n for(int j = 0; j &lt; table.length; j++){\n if(table[0][j] == table[1][j] &amp;&amp; table[1][j] == table[2][j] &amp;&amp; table[j][0] != 'O'){\n System.out.println(&quot;Победа!&quot;);\n System.exit(0);\n }\n }\n\n if(table[0][0] == table[1][1] &amp;&amp; table[1][1] == table[2][2] &amp;&amp; table[0][0] != 'O'){\n System.out.println(&quot;Победа!&quot;);\n System.exit(0);\n }\n\n if(table[0][2] == table[1][1] &amp;&amp; table[1][1] == table[2][0] &amp;&amp; table[0][2] != 'O'){\n System.out.println(&quot;Победа!&quot;);\n System.exit(0);\n }\n\n if(picksTillNow.isEmpty()) System.exit(0);\n }\n</code></pre>\n<p>If I don't completely suck at math (and Tic Tac Toe), there should only be 8 winning positions, and even then there are only 4 and the other 4 are mirrored or rotated. So it might be more interesting and easier to maintain if these are hardcoded.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> System.exit(0);\n</code></pre>\n<p>Something to keep in mind is that <code>System.exit</code> is not &quot;exit the application&quot; but &quot;kill the JVM process&quot;. When invoking this not even <code>finally</code> block may run. In this case it does not matter, but something to keep in mind.</p>\n<hr />\n<p>If I read this right, you have the playing field with the numbers in it, which then get replaced with the player choices. Whether it is valid choice is validated through the remaining fields in your list. Instead I suggest you keep the state limited to only the playing field. Assuming your field definition, you can check whether a field is still free by calculating the position of the input and then checking whether there is an <code>O</code> or <code>X</code> placed, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int fieldChoice = getChoice();\nint row = fieldChoice % 3;\nint column = fieldChoice / 3; // Might be other way around...never can remember.\n\nchar selectedField = playingField[row][column];\n\nif (selectedField != 'X' &amp;&amp; selectedField != 'O') {\n // Set it.\n} else {\n // No dice.\n}\n</code></pre>\n<p><code>playerOneChoice</code> and <code>playerTwoChoice</code> can be rolled into one, by passing the wanted field player as parameter. Using my above example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void playerChoice(char playerCharacter) {\n int fieldChoice = getChoice();\n int row = fieldChoice % 3;\n int column = fieldChoice / 3; // Might be other way around...never can remember.\n \n char selectedField = playingField[row][column];\n \n if (selectedField != 'X' &amp;&amp; selectedField != 'O') {\n playingField[row][column] = playerCharacter;\n } else {\n // No dice.\n }\n}\n</code></pre>\n<p>Having said that, your print function would then boil down to this:</p>\n<pre><code>for (int row = 0; row &lt; 3; row++) {\n for (int column = 0; column &lt; 3; column++) {\n System.out.println(playingField[row][column] + &quot; &quot;);\n }\n \n System.out.println();\n}\n</code></pre>\n<p>Hardcoding the size here is not a bad thing, as long as you assume a Tic Tac Toe game with a 3x3 playing field. If you want to support larger playing fields, you'll have to adjust the rest of your logic anyway.</p>\n<p>Coming around to checking whether somebody has won, the winning conditions would boil down to:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Rows\nplayingField[0][0] == playingField[0][1] &amp;&amp; playingField[0][1] == playingField[0][2];\nplayingField[1][0] == playingField[1][1] &amp;&amp; playingField[1][1] == playingField[1][2];\nplayingField[2][0] == playingField[2][1] &amp;&amp; playingField[2][1] == playingField[2][2];\n\n// Columns\nplayingField[0][0] == playingField[1][0] &amp;&amp; playingField[1][0] == playingField[2][0];\nplayingField[0][1] == playingField[1][1] &amp;&amp; playingField[1][1] == playingField[2][1];\nplayingField[0][2] == playingField[1][2] &amp;&amp; playingField[1][2] == playingField[2][2];\n\n// Diagonal\nplayingField[0][0] == playingField[1][1] &amp;&amp; playingField[1][1] == playingField[2][2];\nplayingField[0][2] == playingField[1][1] &amp;&amp; playingField[1][1] == playingField[2][0];\n</code></pre>\n<p>You will notice, that is just as short as using your loops, and we can chain them with <code>||</code> directly for a return. However, that will not tell us who one. For that need some additional logic, namely an <code>if</code> on every line. But we could also assume that the winner is the player that last played, which is a fair assumption, actually. To make it more readable we can add us three helper functions:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static boolean isWinningRow(int rowIndex) {\n return playingField[row][0] == playingField[row][1] &amp;&amp; playingField[0][1] == playingField[row][2]; \n}\n\npublic static boolean isWinningColumn(int column) {\n return playingField[0][column] == playingField[1][column] &amp;&amp; playingField[1][column] == playingField[2][column]; \n}\n\npublic static boolean isLeftRightDiagonalWin() {\n return playingField[0][0] == playingField[1][1] &amp;&amp; playingField[1][1] == playingField[2][2]; \n}\n\npublic static boolean isRightLeftDiagonalWin() {\n return playingField[0][2] == playingField[1][1] &amp;&amp; playingField[1][1] == playingField[2][0]; \n}\n</code></pre>\n<p>This does not simplify the overall complexity, but does improve the readability:</p>\n<pre class=\"lang-java prettyprint-override\"><code>return isWinningRow(0)\n || isWinningRow(1)\n || isWinningRow(2)\n || isWinningColumn(0)\n || isWinningColumn(1)\n || isWinningColumn(2)\n || isLeftRightDiagonalWin()\n || isRightLeftDiagonalWin();\n</code></pre>\n<p>So you could rewrite your logic to something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int turn = 0;\nboolean running = true;\n\nwhile (turn &lt; 9 &amp;&amp; running) {\n int currentPlayer = (turn % 2) + 1;\n \n playerChoice(currentPlayer);\n printPlayingField();\n \n if (hasWon()) {\n System.out.println(&quot;Winner: &quot; + Integer.toString(currentPlayer);\n \n running = false;\n }\n \n turn++;\n}\n</code></pre>\n<p>I'm a little bit unhappy with the code to choose the player, but it should work. And overall should give you a good idea where to start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:41:56.590", "Id": "504596", "Score": "0", "body": "Lol, thanks a lot, Bobby! This was my first try, in trying to code something a bit different than a simple task solving. Very helpful notes, I will try rewriting my code! Thanks again! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T18:23:34.727", "Id": "255660", "ParentId": "255641", "Score": "2" } }, { "body": "<p>Adding to Bobby's very good answer, you could also explore alternative ways for checking the winning game.</p>\n<p>You can think of noughts and crosses as 1s and 0s (true and false):</p>\n<pre class=\"lang-java prettyprint-override\"><code>boolean[][] board = new boolean[][]{\n {false, false, false},\n {false, true, false},\n {false, false, true}\n};\n</code></pre>\n<p>and therefore transform the board to an integer number:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int intboard = 0;\nint exponent = 0;\nfor (int i = 0; i &lt; board.length; i++) {\n for (int j = 0; j &lt; board[0].length; j++) {\n intboard += board[i][j] ? Math.pow(2, exponent) : 0;\n exponent++;\n }\n}\n</code></pre>\n<p>Then you can simply check <code>intboard</code> against a set of pre-calculated integers for all winning boards:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;Integer&gt; winningBoards = List.of(\n 7, // Horizontal, row-0 --&gt; 000000111\n 56, // Horizontal, row-1 --&gt; 7 &lt;&lt; 3\n 448, // Horizontal, row-2 --&gt; 7 &lt;&lt; 6\n 73, // Vertical, column-0 --&gt; 001001001\n 146, // Vertical, column-1 --&gt; 73 &lt;&lt; 1\n 292, // Vertical, column-2 --&gt; 73 &lt;&lt; 2\n 273, // Diagonal-0 --&gt; 100010001\n 84 // Diagonal-1 --&gt; (273 &gt;&gt; 2) | 16\n);\n</code></pre>\n<blockquote>\n<p>Note that you can calculate some of these winning boards using bitwise operations too!</p>\n</blockquote>\n<p>Finally checking for the winning cases is a matter of applying the winningBoards masks on <code>intboard</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>final int boardToCheck = intboard;\nboolean youHaveWon = winningBoards.stream()\n .anyMatch(winningboard -&gt; (boardToCheck &amp; winningboard) == winningboard);\n\nSystem.out.println(&quot;Nought has won: &quot; + youHaveWon);\n</code></pre>\n<p>If you want to check for <code>crosses</code> you simply need to flip the bits of the winning boards using the complement operator <code>~</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>youHaveWon = winningBoards.stream()\n .anyMatch(winningboard -&gt; (~boardToCheck &amp; winningboard) == winningboard);\n\nSystem.out.println(&quot;Cross has won: &quot; + youHaveWon);\n</code></pre>\n<p>The advantage of this technique is not clear for a game as simple as noughts and crosses, but if you are working on more complex games and need to check many many boards (even millions or billions!) when performing Minimax or equivalent, you can get a very nice speed up by changing the representation of your game from using objects to bits.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:48:39.307", "Id": "255685", "ParentId": "255641", "Score": "3" } } ]
{ "AcceptedAnswerId": "255660", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:37:03.170", "Id": "255641", "Score": "2", "Tags": [ "java", "tic-tac-toe" ], "Title": "Java Tic Tac Toe console" }
255641
<p>Given an array as input, we have to calculate the tree height. For example, input [4, -1, 4, 1, 1] means that there are 5 nodes with numbers from 0 to 4, node 0 is a child of node 4, node 1 is the root, node 2 is a child of node 4, node 3 is a child of node 1 and node 4 is a child of node 1.</p> <p>I have a very low performing code that loops over the input more than once:</p> <pre><code>def height(array): di= {array.index(-1):-1} while (len(di)&lt;len(array)): for i, p in enumerate(array): if p in di.keys(): di[i] = di[p] - 1 max_distance = -1 for val in di.values(): if val &lt; max_distance: max_distance = val max_distance = abs(max_distance) return max_distance </code></pre> <p>Another method I'm trying is I group the child nodes together like this: input [9, 7, 5, 5, 2, 9, 9, 9, 2, -1] I group then to {9: [0, 5, 6, 7], 7: [1], 5: [2, 3], 2: [4, 8], -1: [9]} But I'm stuck and have no idea if I'm on the right track or what to do after this. Please let me know what you think. Much appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T10:45:22.677", "Id": "504465", "Score": "0", "body": "Is that testable online somewhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T10:53:08.857", "Id": "504467", "Score": "0", "body": "Are there limits?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T13:24:21.410", "Id": "504491", "Score": "0", "body": "I suggest you draw the trees as graphs to redesign your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:05:10.500", "Id": "504523", "Score": "0", "body": "This is from coursera data structures course and the grader output was time limit exceeded. I changed the code according to the advice from the answer and it works!" } ]
[ { "body": "<ul>\n<li>Standard indentation is four spaces.</li>\n<li>Missing spaces here and there.</li>\n<li>Unnecessary parentheses after <code>while</code>.</li>\n<li>Can't handle empty trees.</li>\n<li>Name <code>di</code> is really unclear, <code>i</code> and <code>p</code> could also be better.</li>\n<li>Using <code>.keys()</code> like that is pointless.</li>\n<li>Using negative values is pointless and confusing. Using <code>abs</code> on the result is particularly confusing, as it suggests that the value you give it could be negative or positive. Since you know it's negative, that should've been just <code>-max_distance</code>.</li>\n<li>No need to reinvent <code>max</code>.</li>\n</ul>\n<p>Rewritten accordingly:</p>\n<pre><code>def height(array):\n depth = {-1: 0}\n while len(depth) &lt;= len(array):\n for child, parent in enumerate(array):\n if parent in depth:\n depth[child] = depth[parent] + 1\n return max(depth.values())\n</code></pre>\n<p>For performance, instead of repeatedly searching for children with finished parents, first do one pass to collect each parent's children. Then when you finish a parent, simply go through its previously collected children to finish them, too. This is then linear instead of quadratic time.</p>\n<p>Or if the limits are small enough (so far you still haven't answered the comment asking about that), you could use a simple recursive <code>depth(node)</code> function decorated with <code>functools.cache</code>, apply it to all nodes, and take the max. Also linear time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T15:26:19.130", "Id": "255653", "ParentId": "255642", "Score": "0" } } ]
{ "AcceptedAnswerId": "255653", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T09:47:31.367", "Id": "255642", "Score": "1", "Tags": [ "python", "performance", "beginner", "time-limit-exceeded" ], "Title": "calculate tree height (arbitrary tree) - python" }
255642
<p>I wrote a simple piping operator in c++. I just wanted to make sure that my code was robust, modern c++ code, and made correct use of perfect forwarding.</p> <p>Here's the code:</p> <pre><code>#include &lt;concepts&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;deque&gt; //Accept an object on the left hand side and a function on the right template &lt;typename Any, typename... Args&gt; inline auto operator| (const Any&amp; obj, std::invocable&lt;Any&gt; auto func){ // Correct use of perfect forwarding?? return func(std::forward&lt;const Any&amp;&gt;(obj)); } //Version for a functor which accepts a reference. Do I need to cover other cases? template &lt;typename Any, typename... Args&gt; inline auto operator| (Any&amp; obj, std::invocable&lt;Any&amp;&gt; auto func){ return func(std::forward&lt;Any&amp;&gt;(obj)); } </code></pre> <p>And here is how the user uses it:</p> <pre><code>int main() { auto x = std::vector{1 , 2 , 3 , 4 , 5 , 6}; // Piping example 0 auto y = 5 | [] (int x) {return x * 2;} | [] (int x) {return x * 3;} ; std::cout &lt;&lt; y &lt;&lt; '\n'; // Piping example 1 x | [] (std::vector&lt;int&gt;&amp; vec) -&gt; std::vector&lt;int&gt;&amp; {vec.push_back(7); return vec;}; std::cout &lt;&lt; x[6]; return 0; } </code></pre> <p>And if you want to clean up the lambda syntax (I don't mind personally) and have a cleaner, neater syntax you can do:</p> <pre><code>namespace piping { template &lt;typename T&gt; auto push_back(const T&amp; obj) { return [obj] (auto&amp; vec) -&gt; auto&amp; {vec.push_back(obj); return vec;};; } } /* ... Some code */ int main() { auto x = std::vector{1 , 2 , 3 ,4 ,5 , 6}; // A bit cleaner... x | piping::push_back(7); } </code></pre> <p>Did I make correct use of modern c++ and perfect forwarding? Thanks in advance.</p>
[]
[ { "body": "<p>That seems a worthwhile objective. The syntax looks a bit clunky when we have to write lambdas inline like that, but you'll probably develop a library of useful filters (like standard Ranges ones) that look much more natural.</p>\n<p>I don't think we've got the use of forwarding references quite right - and you'll be pleased to hear that fixing that should simplify the code a bit.</p>\n<p>What we should do is use <code>typename Any&amp;&amp;</code>. Although that looks like an rvalue-reference, it's actually a <strong>forwarding reference</strong> because <code>Any</code> is a template parameter.</p>\n<p><code>Any&amp;&amp;</code> allows the template parameter to bind to <em>either</em> lvalue <em>or</em> rvalue, so we just need the one function:</p>\n<pre><code>template &lt;typename Any&gt;\nauto operator| (Any&amp;&amp; obj, std::invocable&lt;Any&gt; auto&amp;&amp; func) {\n return func(std::forward&lt;Any&gt;(obj));\n}\n</code></pre>\n<p>(Note also the <code>auto&amp;&amp;</code> for <code>func</code>, so it can be a mutable functor if we want).</p>\n<hr />\n<p>Having written that, I'm not so convinced that I like <code>operator|()</code> to be modifying its argument. I would prefer <code>a | b</code> to leave <code>a</code> alone, and have to write <code>a |= b</code> when I intend <code>a</code> to be modified in place.</p>\n<hr />\n<p>Minor points:</p>\n<ul>\n<li>There are headers included but not needed for the template:\n<blockquote>\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;deque&gt;\n</code></pre>\n</blockquote>\n</li>\n<li><code>inline</code> is implicit for a template function.</li>\n<li>We don't need to spell out the full return type for the &quot;append 7&quot; lambda in the example - <code>-&gt; auto&amp;</code> is easier.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:40:13.377", "Id": "504606", "Score": "0", "body": "Thank you for all your feedback and explaining perfect forwarding!! I had never quite understood it until now... About the \"inline\" keyword, the compiler (-O3) seemed to be better at optimising my code when the \"inline\" was there??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:41:15.060", "Id": "504607", "Score": "0", "body": "I'm surprised by that. If the `inline` is helpful, then continue using it. I don't think it can do any harm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:47:31.217", "Id": "504608", "Score": "0", "body": "It's worth searching the web for good articles on **perfect forwarding** and **forwarding references**. Another good search term is **universal references**, which is the older term for this construct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:48:27.867", "Id": "504609", "Score": "0", "body": "yes it surprised me as well. In fact both versions of my code inlined the function, but the version with \"inline\" straight up calculated everything at compile - time, while the version without inline had to call the lambda." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:54:07.730", "Id": "504610", "Score": "0", "body": "OOh - perhaps it would make sense to add `constexpr` to the declaration? I'm not 100% sure about that, though - I'm just a beginner with `constexpr`. IIRC, the lambda can also be declared `constexpr`, but I'm really walking on thin ice now..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T17:00:08.623", "Id": "504611", "Score": "0", "body": "No - constexpr doesn't really work (it would be up to the user to mark the lambda constexpr) - my piping operator just needs to do too many things at run-time to be constexpr. However, the compiler can do absolutely anything it wants as long as it does not have observable behaviour, so I think the \"inline\" just makes it a bit more transparent to the compiler" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T17:29:06.840", "Id": "504612", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/119430/discussion-between-cyrus-and-toby-speight)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:28:32.233", "Id": "255690", "ParentId": "255645", "Score": "3" } } ]
{ "AcceptedAnswerId": "255690", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T11:41:59.187", "Id": "255645", "Score": "3", "Tags": [ "c++20", "overloading" ], "Title": "Piping operator in c++" }
255645
<p>Okay, first things first:</p> <p>Yes, I am aware of the logrotate tool, which would usually be used for something like this. However, since the logfile i want to rotate already contains a timestamp in the filename, logrotate will never delete old logs.</p> <p>This script is supposed to:</p> <ol> <li>tell the application to create a new logfile (via SIGHUP)</li> <li>find all existing, unprocessed logfiles of the application</li> <li>compress all logfiles except the one currently in use by the application</li> <li>keep the most recent 7 logs and delete the rest.</li> </ol> <p>From what I can tell, everything seems to work just fine, but I'm curious if anything could be improved.</p> <pre><code>#!/usr/bin/bash procname=&quot;foo&quot; srcpath=&quot;/var/log&quot; srcname=&quot;*${procname}.log&quot; # example: 2021-02-05_1200_foo.log count=7 echo &quot;rotate $procname logs: ${srcpath}/${srcname} ($count rotations)&quot; pid=&quot;$(pidof $procname)&quot; if [[ ! $? == 0 ]] then # don't rotate anything if the application is not running echo &quot;$procname process not running&quot; exit 1 fi # ask the application to create a new logfile kill -HUP &quot;$pid&quot; sleep 1 #probably not necessary? # get array of all logfiles (should be exactly 2 in most cases) mapfile -t list &lt; &lt;(find &quot;$srcpath&quot; -maxdepth 1 -name &quot;$srcname&quot; | sort) size=${#list[@]} # don't do anything unless there are at least 2 files if [[ $size -lt 2 ]] then echo &quot;nothing to do&quot; exit 0 fi # find the active logfile (should be the last one) and delete it from the array for ((i=size-1; i&gt;=0; i--)); do if [[ $(find -L /proc/&quot;$pid&quot;/fd -inum &quot;$(stat -c '%i' &quot;${list[i]}&quot;)&quot;) ]] then unset &quot;list[i]&quot; break fi done # compress all remaining files (usually just one) gzip &quot;${list[@]}&quot; unset list unset size # get array of all compressed logfiles mapfile -t list &lt; &lt;(find &quot;$srcpath&quot; -maxdepth 1 -name &quot;$srcname.gz&quot; | sort) size=${#list[@]} if [[ $size -gt $count ]] then idx=(&quot;${!list[@]}&quot;) # remove $count most recent files from $list for i in &quot;${idx[@]: -$count:$count}&quot; do unset &quot;list[$i]&quot; done # delete the remaining old files rm -f &quot;${list[@]}&quot; fi exit 0 </code></pre>
[]
[ { "body": "<p>Shellcheck points out this one:</p>\n<blockquote>\n<pre><code>pid=&quot;$(pidof $procname)&quot;\nif [[ ! $? == 0 ]]\nthen\n</code></pre>\n</blockquote>\n<p>We can write that more clearly</p>\n<pre><code>if ! pid=&quot;$(pidof $procname)&quot;\nthen\n</code></pre>\n<p>Shortly after that is:</p>\n<blockquote>\n<pre><code># don't rotate anything if the application is not running\necho &quot;$procname process not running&quot;\n</code></pre>\n</blockquote>\n<p>That looks like an error message - redirect that to <code>&amp;2</code>.</p>\n<p>I'm a little concerned about</p>\n<blockquote>\n<pre><code># find the active logfile (should be the last one) and delete it from the array\n</code></pre>\n</blockquote>\n<p>If the daemon didn't get around to opening a new file by the time we reach here, then we'll be out of sync. That said, it probably doesn't matter - we'll just have one more unrotated file around until we next run, which isn't a big concern.</p>\n<p>Take care with commands like this:</p>\n<blockquote>\n<pre><code>gzip &quot;${list[@]}&quot;\n</code></pre>\n</blockquote>\n<p>It's a good idea to use <code>--</code> so we can be sure that filenames beginning with <code>-</code> aren't interpreted as options.</p>\n<p>Also, commands such as <code>gzip</code> can fail - do we really want to keep going if they do? (This question isn't so simple to answer, as one of the likely reasons is &quot;no space on device&quot;, and in that case we do want to delete some files!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:19:27.970", "Id": "504497", "Score": "0", "body": "Thanks! I didn't know you could have an assignment inside an if clause, that's much nicer than the `$?` version. Concerning the out-of-sync problem, that's why i added the `sleep 1`, which of course isn't a guarantee either, but hopefully better than nothing. Didn't think about the `--`, i will add it to `gzip` and `rm` to be safe (even though the filenames shouldn't begin with `-`). I'll need to think about the error handling... to be honest, i'm not quite sure what i want to do if gzip fails" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:24:42.843", "Id": "504498", "Score": "0", "body": "Yes, I saw the sleep, with its comment, so did know you're aware of it. Sorry I don't have anything better to suggest there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:25:36.103", "Id": "504499", "Score": "0", "body": "I *thought* the argument lists wouldn't start with `-`, but it's often easier just to drop `--` into the command to save precious brainpower reasoning about it!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:01:36.977", "Id": "255649", "ParentId": "255647", "Score": "2" } } ]
{ "AcceptedAnswerId": "255649", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:46:58.113", "Id": "255647", "Score": "3", "Tags": [ "bash", "shell" ], "Title": "Bash script for log rotation" }
255647
<p>I'm trying to make a simple code to upload an image directly from a url. However I have concerns about the safety of my code since a user can submit any url. How I can make it more safe?</p> <p>All the good examples I found are always related to files uploaded via a form.</p> <p>So I'm having difficulties in improving this code.</p> <pre><code>$img_url = &quot;https://i.ytimg.com/vi/wSdT-SArM2Q/maxresdefault.jpg&quot;; function getimg($url) { $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; $headers[] = 'Connection: Keep-Alive'; $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; $user_agent = 'php'; $process = curl_init($url); curl_setopt($process, CURLOPT_HTTPHEADER, $headers); curl_setopt($process, CURLOPT_HEADER, 0); curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here curl_setopt($process, CURLOPT_TIMEOUT, 30); curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1); $return = curl_exec($process); curl_close($process); return $return; } $imagename = basename($img_url); if (file_exists('./upload/' . $imagename)) { // } $image = getimg($img_url); file_put_contents('upload/' . $imagename, $image); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T16:25:36.997", "Id": "504505", "Score": "1", "body": "Welcome to Code Review! Can you please [edit] your post to explain what might happen in the line containing the comment (i.e. `//`)? Would it be a block to handle the file existing already?" } ]
[ { "body": "<blockquote>\n<p>I'm trying to make a simple code to upload an image directly from a\nurl.</p>\n</blockquote>\n<p>You mean download.</p>\n<blockquote>\n<p>How I can make it more safe?</p>\n</blockquote>\n<p>Is there any reason why you want to retain the original file name, after applying the basename function ? This should protect against basic path traversal attempts like ../../\nbut you could as well rename the file altogether. If you are storing a record in a database, using an ID would be a good choice + adding the file extension (but not allow <em>any</em> file extension - see below).</p>\n<p>This would be better than taking a chance and figuring out the possible pitfalls with your function. You are not controlling the file name and trusting user input is where the danger lies.\nNot to mention that there may some creative attempts involving Unicode characters or whatever. Easier said than done, but I can't guarantee your code is 100% safe at this point.</p>\n<p>The biggest problem here is that someone could supply the URL of a webshell with a .php extension, that your script will happily download to the upload folder. If that folder is under your website root, an attacker may then be able to call <a href=\"http://example.com/upload/shell.php\" rel=\"nofollow noreferrer\">http://example.com/upload/shell.php</a> to and take over your server. It's something you can test easily.</p>\n<p>Because that's what your script does, it will download anything upon request.\nAt a minimum, that upload folder should <strong>not</strong> be under the website root. So the problem is not just the file name but the extension, and where that upload folder resides.</p>\n<p>Also, there is no guarantee that the filename will be unique. You seem to be handling the scenario in some way that we don't know about.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T22:44:50.580", "Id": "255671", "ParentId": "255648", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T12:47:32.767", "Id": "255648", "Score": "2", "Tags": [ "php" ], "Title": "Upload Image From URL via PHP (In a safe way)" }
255648
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/254972/231235">A Generic Two Dimensional Data Plane with SubPlane Method in C#</a>. Thanks to <a href="https://codereview.stackexchange.com/a/255069/231235">aepot's answer</a>.</p> <p>I am trying to implement a series methods to enhance the ability and functionality of this two dimensional data plane.</p> <ul> <li><p><code>Cast</code> method in order to deal with casting between different types.</p> </li> <li><p>Some of statistical functions, including <code>Abs</code>, <code>Max</code>, <code>Min</code>, <code>Average</code>, <code>Contains</code>, <code>Count</code>, <code>PopulationVariance</code> and <code>PopulationStandardDeviation</code>.</p> </li> <li><p>Some of trigonometric functions, calculating the result of each elelment (convert to double first), including <code>Cosine</code>, <code>Cosecant</code>, <code>Cotangent</code>, <code>Secant</code>, <code>Sine</code> and <code>Tangent</code>.</p> </li> <li><p>Element-wise operation: <code>Add</code>, <code>Subtract</code>, <code>ElementWiseMultiplication</code> and <code>ElementWiseDivision</code>.</p> </li> </ul> <pre><code>[Serializable] public class Plane&lt;T&gt; where T : struct { public int Width { get; } public int Height { get; } public T[,] Grid { get; } public int Length { get; } public Plane() : this(1, 1) { } public Plane(in int width, in int height) { Width = width; Height = height; Grid = new T[height, width]; Length = Width * Height; } public Plane(in int width, in int height, T initVal) { Width = width; Height = height; Grid = new T[height, width]; Fill(Grid, initVal); Length = Width * Height; } // https://github.com/dotnet/runtime/issues/47213 private static void Fill&lt;T&gt;(T[,] array, T value) { for (int x = 0; x &lt; array.GetLength(0); x++) { for (int y = 0; y &lt; array.GetLength(1); y++) { array.SetValue(value, x, y); } } return; } public Plane(Plane&lt;T&gt; plane) : this(plane?.Grid ?? throw new ArgumentNullException(nameof(plane))) { } public Plane(in T[,] sourceGrid) { if (ReferenceEquals(sourceGrid, null)) { throw new ArgumentNullException(nameof(sourceGrid)); } Height = sourceGrid.GetLength(0); Width = sourceGrid.GetLength(1); Length = Width * Height; Grid = new T[Height, Width]; Array.Copy(sourceGrid, Grid, sourceGrid.Length); } public Plane&lt;double&gt; Abs() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; Math.Abs(x)); } public Plane&lt;T2&gt; Cast&lt;T2&gt;() where T2 : struct { T2[,] outputGrid = ConvertAllDetail(this.Grid, x =&gt; { return (T2)Convert.ChangeType(x, typeof(T2)); }); return new Plane&lt;T2&gt;(outputGrid); } public Plane&lt;TOutput&gt; ConvertAll&lt;TOutput&gt;(in Converter&lt;T, TOutput&gt; converter) where TOutput : struct { return new Plane&lt;TOutput&gt;(ConvertAllDetail(this.Grid, converter)); } public Plane&lt;T&gt; Add&lt;T2&gt;(Plane&lt;T2&gt; input) where T2 : struct { if (ReferenceEquals(input, null)) { throw new ArgumentNullException(nameof(input)); } if (input.Width != this.Width || input.Height != this.Height) { throw new InvalidOperationException(&quot;Size is different!&quot;); } var output = new Plane&lt;T&gt;(this.Width, this.Height); for (int x = 0; x &lt; this.Width; x++) { for (int y = 0; y &lt; this.Height; y++) { dynamic a = this.Grid[y, x]; dynamic b = input.Grid[y, x]; output.Grid[y, x] = a + b; } } return output; } public double Average() { return System.Linq.Enumerable.Average(this.Cast&lt;double&gt;().Grid.Cast&lt;double&gt;().ToArray()); } private static TOutput[,] ConvertAllDetail&lt;TInput, TOutput&gt;(in TInput[,] array, Converter&lt;TInput, TOutput&gt; converter) where TInput : struct where TOutput : struct { return (TOutput[,])ConvertArray(array, converter); } private static Array ConvertArray&lt;TInput, TResult&gt;(in Array array, in Converter&lt;TInput, TResult&gt; converter) where TInput : struct where TResult : struct { if (ReferenceEquals(array, null)) { throw new ArgumentNullException(nameof(array)); } if (ReferenceEquals(converter, null)) { throw new ArgumentNullException(nameof(converter)); } long[] dimensions = new long[array.Rank]; for (int i = 0; i &lt; array.Rank; i++) dimensions[i] = array.GetLongLength(i); Array result = Array.CreateInstance(typeof(TResult), dimensions); TResult[] tmp = new TResult[1]; int offset = 0; int itemSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TResult)); foreach (TInput item in array) { tmp[0] = converter(item); Buffer.BlockCopy(tmp, 0, result, offset * itemSize, itemSize); offset++; } return result; } public Plane&lt;T&gt; ConcatenateHorizontal(in Plane&lt;T&gt; input) { if (ReferenceEquals(input, null)) { throw new ArgumentNullException(nameof(input)); } if (this.Height != input.Height) { throw new ArgumentException(&quot;Height isn't match&quot;, nameof(input.Height)); } var output = new Plane&lt;T&gt;(this.Width + input.Width, this.Height); for (int row = 0; row &lt; this.Height; row++) { Array.Copy(this.Grid, row * this.Width, output.Grid, row * output.Width, this.Width); Array.Copy(input.Grid, row * input.Width, output.Grid, row * output.Width + this.Width, input.Width); } return output; } public Plane&lt;T&gt; ConcatenateHorizontalInverse(in Plane&lt;T&gt; input) { return input.ConcatenateHorizontal(this); } public bool Contains(in T value) { return System.Linq.Enumerable.Contains(this.Grid.Cast&lt;T&gt;().ToArray(), value); } public Plane&lt;double&gt; Cosine() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; Math.Cos(x)); } public Plane&lt;double&gt; Cosecant() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; 1 / Math.Sin(x)); } public Plane&lt;double&gt; Cotangent() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; 1 / Math.Tan(x)); } public int Count(in Func&lt;T, bool&gt; predicate) { return System.Linq.Enumerable.Count(this.Grid.Cast&lt;T&gt;().ToArray(), predicate); } public Plane&lt;T&gt; ElementWiseDivision&lt;T2&gt;(in Plane&lt;T2&gt; input) where T2 : struct { if (ReferenceEquals(input, null)) { throw new ArgumentNullException(nameof(input)); } if (input.Width != this.Width || input.Height != this.Height) { throw new InvalidOperationException(&quot;Size is different!&quot;); } var output = new Plane&lt;T&gt;(this.Width, this.Height); for (int x = 0; x &lt; this.Width; x++) { for (int y = 0; y &lt; this.Height; y++) { output.Grid[y, x] = (dynamic)this.Grid[y, x] / (dynamic)input.Grid[y, x]; } } return output; } public Plane&lt;T&gt; ElementWiseMultiplication&lt;T2&gt;(in Plane&lt;T2&gt; input) where T2 : struct { if (ReferenceEquals(input, null)) { throw new ArgumentNullException(nameof(input)); } if (input.Width != this.Width || input.Height != this.Height) { throw new InvalidOperationException(&quot;Size is different!&quot;); } var output = new Plane&lt;T&gt;(this.Width, this.Height); for (int x = 0; x &lt; this.Width; x++) { for (int y = 0; y &lt; this.Height; y++) { output.Grid[y, x] = (dynamic)this.Grid[y, x] * (dynamic)input.Grid[y, x]; } } return output; } public override bool Equals(object obj) { return obj is Plane&lt;T&gt; input &amp;&amp; this.Width == input.Width &amp;&amp; this.Height == input.Height &amp;&amp; this.Grid.Cast&lt;T&gt;().SequenceEqual(input.Grid.Cast&lt;T&gt;()); } public void ForEach(Action&lt;T&gt; action) { foreach (T item in this.Grid) { action.Invoke(item); } return; } public double Max() { return System.Linq.Enumerable.Max(this.Cast&lt;double&gt;().Grid.Cast&lt;double&gt;().ToArray()); } public double Min() { return System.Linq.Enumerable.Min(this.Cast&lt;double&gt;().Grid.Cast&lt;double&gt;().ToArray()); } public Plane&lt;T&gt; Paste(in Tuple&lt;int, int&gt; location, in Plane&lt;T&gt; plane) { var output = new Plane&lt;T&gt;(Math.Max(location.Item1 + plane.Width, this.Width), Math.Max(location.Item2 + plane.Height, this.Height)); for (int row = 0; row &lt; this.Height; row++) { Array.Copy(this.Grid, row * this.Width, output.Grid, row * output.Width, this.Width); } for (int row = 0; row &lt; plane.Height; row++) { Array.Copy(plane.Grid, row * plane.Width, output.Grid, (row + location.Item2) * output.Width + location.Item1, plane.Width); } return output; } public double PopulationVariance() { var avg = this.Average(); double output = 0.0; var doublePlane = this.Cast&lt;double&gt;(); for (int x = 0; x &lt; this.Width; x++) { for (int y = 0; y &lt; this.Height; y++) { output += Math.Pow(doublePlane.Grid[y, x] - avg, 2); } } return output / this.Length; } public double PopulationStandardDeviation() { return Math.Sqrt(this.PopulationVariance()); } public Plane&lt;double&gt; Secant() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; 1 / Math.Cos(x)); } public Plane&lt;double&gt; Sine() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; Math.Sin(x)); } public Plane&lt;T&gt; SubPlane(in int locationX, in int locationY, in int newWidth, in int newHeight) { if (locationX &lt; 0 || locationX &gt;= this.Width) throw new ArgumentException(&quot;Location must be inside the area&quot;, nameof(locationX)); if (locationY &lt; 0 || locationY &gt;= this.Height) throw new ArgumentException(&quot;Location must be inside the area&quot;, nameof(locationY)); Plane&lt;T&gt; outputPlane = new Plane&lt;T&gt;(newWidth, newHeight); for (int row = 0; row &lt; newHeight; row++) { Array.Copy(this.Grid, (row + locationY) * this.Width + locationX, outputPlane.Grid, row * newWidth, newWidth); } return outputPlane; } public Plane&lt;T&gt; Subtract&lt;T2&gt;(in Plane&lt;T2&gt; input) where T2 : struct { if (ReferenceEquals(input, null)) { throw new ArgumentNullException(nameof(input)); } if (input.Width != this.Width || input.Height != this.Height) { throw new InvalidOperationException(&quot;Size is different!&quot;); } var output = new Plane&lt;T&gt;(this.Width, this.Height); for (int x = 0; x &lt; this.Width; x++) { for (int y = 0; y &lt; this.Height; y++) { dynamic a = this.Grid[y, x]; dynamic b = input.Grid[y, x]; output.Grid[y, x] = a - b; } } return output; } public double Sum() { double output = 0.0; var doublePlane = this.Cast&lt;double&gt;(); for (int x = 0; x &lt; this.Width; x++) { for (int y = 0; y &lt; this.Height; y++) { output += doublePlane.Grid[y, x]; } } return output; } public Plane&lt;double&gt; Tangent() { return this.Cast&lt;double&gt;().ConvertAll(x =&gt; Math.Tan(x)); } public override string ToString() =&gt; $&quot;{nameof(Plane&lt;T&gt;)}&lt;{typeof(T).Name}&gt;[{Height}, {Width}]&quot;; public string ToDelimitedString(in string separator = &quot; &quot;) { var sb = new StringBuilder(); string[,] output = new string[this.Height, this.Width]; int maxLength = 0; for (int row = 0; row &lt; this.Height; row++) { for (int column = 0; column &lt; this.Width; column++) { string s = this.Grid[row, column].ToString(); output[row, column] = s; maxLength = Math.Max(maxLength, s.Length); } } for (int row = 0; row &lt; this.Height; row++) { for (int column = 0; column &lt; this.Width; column++) { sb.Append(output[row, column].PadLeft(maxLength)).Append(separator); } sb.Remove(sb.Length - separator.Length, separator.Length).AppendLine(); } return sb.ToString(); } public override int GetHashCode() { // Based on https://stackoverflow.com/a/61000527/6667035 byte[] encoded = System.Security.Cryptography.SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(this.ToDelimitedString())); return BitConverter.ToInt32(encoded, 0); } // https://stackoverflow.com/a/1145562/6667035 private T CastObject&lt;T&gt;(object input) { return (T)input; } private T ConvertObject&lt;T&gt;(object input) { return (T)Convert.ChangeType(input, typeof(T)); } } </code></pre> <p><strong>Test cases</strong></p> <p>The test cases for the usage of <code>Abs</code>, <code>Add</code>, <code>Subtract</code>, <code>ElementWiseMultiplication</code>, <code>ElementWiseDivision</code>, <code>GetHashCode</code>, <code>Sum</code>, <code>Max</code>, <code>Min</code>, <code>Average</code>, <code>Contains</code>, <code>Count</code>, <code>PopulationVariance</code>, <code>PopulationStandardDeviation</code>, <code>Sine</code>, <code>Cosine</code>, <code>Tangent</code>, <code>Cotangent</code>, <code>Secant</code> and <code>Cosecant</code> are listed as below.</p> <pre><code>Plane&lt;int&gt; plane = new Plane&lt;int&gt;(10, 10); // Set value for (int x = 0; x &lt; 10; x++) { for (int y = 0; y &lt; 10; y++) { plane.Grid[y, x] = x + y * 2; } } Console.WriteLine(&quot;Print content:&quot;); Console.WriteLine(plane.ToDelimitedString(&quot;\t&quot;)); Console.WriteLine(&quot;Abs:&quot;); Console.WriteLine(new Plane&lt;double&gt;(10, 10, -1).Abs().ToDelimitedString(&quot;\t&quot;)); Console.WriteLine(&quot;Add:&quot;); Console.WriteLine(plane.Add(plane).ToDelimitedString(&quot;\t&quot;)); Console.WriteLine(&quot;Subtract:&quot;); Console.WriteLine(plane.Subtract(plane).ToDelimitedString(&quot;\t&quot;)); Console.WriteLine(&quot;ElementWiseMultiplication:&quot;); Console.WriteLine(plane.ElementWiseMultiplication(plane).ToDelimitedString(&quot;\t&quot;)); Console.WriteLine(&quot;ElementWiseDivision:&quot;); Console.WriteLine(plane.Cast&lt;double&gt;().ElementWiseDivision(new Plane&lt;int&gt;(10, 10, 10)).ToDelimitedString(&quot;\t&quot;)); Console.WriteLine($&quot;GetHashCode:{plane.GetHashCode()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Sum:{plane.Sum()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Max:{plane.Max()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Min:{plane.Min()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Average:{plane.Average()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Contains zero:{plane.Contains(0)}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Count of zero:{plane.Count(x =&gt; x == 0)}&quot;); Console.WriteLine(); Console.WriteLine($&quot;PopulationVariance:{plane.PopulationVariance()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;PopulationStandardDeviation:{plane.PopulationStandardDeviation()}&quot;); Console.WriteLine(); Console.WriteLine($&quot;Sine:&quot;); Console.WriteLine(plane.Sine().ToDelimitedString()); Console.WriteLine($&quot;Cosine:&quot;); Console.WriteLine(plane.Cosine().ToDelimitedString()); Console.WriteLine($&quot;Tangent:&quot;); Console.WriteLine(plane.Tangent().ToDelimitedString()); Console.WriteLine($&quot;Cotangent:&quot;); Console.WriteLine(plane.Cotangent().ToDelimitedString()); Console.WriteLine($&quot;Secant:&quot;); Console.WriteLine(plane.Secant().ToDelimitedString()); Console.WriteLine($&quot;Cosecant:&quot;); Console.WriteLine(plane.Cosecant().ToDelimitedString()); </code></pre> <p>The output of the above test cases.</p> <pre><code>Print content: 0 1 2 3 4 5 6 7 8 9 2 3 4 5 6 7 8 9 10 11 4 5 6 7 8 9 10 11 12 13 6 7 8 9 10 11 12 13 14 15 8 9 10 11 12 13 14 15 16 17 10 11 12 13 14 15 16 17 18 19 12 13 14 15 16 17 18 19 20 21 14 15 16 17 18 19 20 21 22 23 16 17 18 19 20 21 22 23 24 25 18 19 20 21 22 23 24 25 26 27 Abs: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Add: 0 2 4 6 8 10 12 14 16 18 4 6 8 10 12 14 16 18 20 22 8 10 12 14 16 18 20 22 24 26 12 14 16 18 20 22 24 26 28 30 16 18 20 22 24 26 28 30 32 34 20 22 24 26 28 30 32 34 36 38 24 26 28 30 32 34 36 38 40 42 28 30 32 34 36 38 40 42 44 46 32 34 36 38 40 42 44 46 48 50 36 38 40 42 44 46 48 50 52 54 Subtract: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ElementWiseMultiplication: 0 1 4 9 16 25 36 49 64 81 4 9 16 25 36 49 64 81 100 121 16 25 36 49 64 81 100 121 144 169 36 49 64 81 100 121 144 169 196 225 64 81 100 121 144 169 196 225 256 289 100 121 144 169 196 225 256 289 324 361 144 169 196 225 256 289 324 361 400 441 196 225 256 289 324 361 400 441 484 529 256 289 324 361 400 441 484 529 576 625 324 361 400 441 484 529 576 625 676 729 ElementWiseDivision: 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 GetHashCode:-1863909712 Sum:1350 Max:27 Min:0 Average:13.5 Contains zero:True Count of zero:1 PopulationVariance:41.25 PopulationStandardDeviation:6.422616289332565 Sine: 0 0.8414709848078965 0.9092974268256817 0.1411200080598672 -0.7568024953079282 -0.9589242746631385 -0.27941549819892586 0.6569865987187891 0.9893582466233818 0.4121184852417566 0.9092974268256817 0.1411200080598672 -0.7568024953079282 -0.9589242746631385 -0.27941549819892586 0.6569865987187891 0.9893582466233818 0.4121184852417566 -0.5440211108893698 -0.9999902065507035 -0.7568024953079282 -0.9589242746631385 -0.27941549819892586 0.6569865987187891 0.9893582466233818 0.4121184852417566 -0.5440211108893698 -0.9999902065507035 -0.5365729180004349 0.4201670368266409 -0.27941549819892586 0.6569865987187891 0.9893582466233818 0.4121184852417566 -0.5440211108893698 -0.9999902065507035 -0.5365729180004349 0.4201670368266409 0.9906073556948704 0.6502878401571168 0.9893582466233818 0.4121184852417566 -0.5440211108893698 -0.9999902065507035 -0.5365729180004349 0.4201670368266409 0.9906073556948704 0.6502878401571168 -0.2879033166650653 -0.9613974918795568 -0.5440211108893698 -0.9999902065507035 -0.5365729180004349 0.4201670368266409 0.9906073556948704 0.6502878401571168 -0.2879033166650653 -0.9613974918795568 -0.7509872467716762 0.14987720966295234 -0.5365729180004349 0.4201670368266409 0.9906073556948704 0.6502878401571168 -0.2879033166650653 -0.9613974918795568 -0.7509872467716762 0.14987720966295234 0.9129452507276277 0.8366556385360561 0.9906073556948704 0.6502878401571168 -0.2879033166650653 -0.9613974918795568 -0.7509872467716762 0.14987720966295234 0.9129452507276277 0.8366556385360561 -0.008851309290403876 -0.8462204041751706 -0.2879033166650653 -0.9613974918795568 -0.7509872467716762 0.14987720966295234 0.9129452507276277 0.8366556385360561 -0.008851309290403876 -0.8462204041751706 -0.9055783620066238 -0.13235175009777303 -0.7509872467716762 0.14987720966295234 0.9129452507276277 0.8366556385360561 -0.008851309290403876 -0.8462204041751706 -0.9055783620066238 -0.13235175009777303 0.7625584504796027 0.956375928404503 Cosine: 1 0.5403023058681398 -0.4161468365471424 -0.9899924966004454 -0.6536436208636119 0.28366218546322625 0.960170286650366 0.7539022543433046 -0.14550003380861354 -0.9111302618846769 -0.4161468365471424 -0.9899924966004454 -0.6536436208636119 0.28366218546322625 0.960170286650366 0.7539022543433046 -0.14550003380861354 -0.9111302618846769 -0.8390715290764524 0.004425697988050785 -0.6536436208636119 0.28366218546322625 0.960170286650366 0.7539022543433046 -0.14550003380861354 -0.9111302618846769 -0.8390715290764524 0.004425697988050785 0.8438539587324921 0.9074467814501962 0.960170286650366 0.7539022543433046 -0.14550003380861354 -0.9111302618846769 -0.8390715290764524 0.004425697988050785 0.8438539587324921 0.9074467814501962 0.1367372182078336 -0.7596879128588213 -0.14550003380861354 -0.9111302618846769 -0.8390715290764524 0.004425697988050785 0.8438539587324921 0.9074467814501962 0.1367372182078336 -0.7596879128588213 -0.9576594803233847 -0.27516333805159693 -0.8390715290764524 0.004425697988050785 0.8438539587324921 0.9074467814501962 0.1367372182078336 -0.7596879128588213 -0.9576594803233847 -0.27516333805159693 0.6603167082440802 0.9887046181866692 0.8438539587324921 0.9074467814501962 0.1367372182078336 -0.7596879128588213 -0.9576594803233847 -0.27516333805159693 0.6603167082440802 0.9887046181866692 0.40808206181339196 -0.5477292602242684 0.1367372182078336 -0.7596879128588213 -0.9576594803233847 -0.27516333805159693 0.6603167082440802 0.9887046181866692 0.40808206181339196 -0.5477292602242684 -0.9999608263946371 -0.5328330203333975 -0.9576594803233847 -0.27516333805159693 0.6603167082440802 0.9887046181866692 0.40808206181339196 -0.5477292602242684 -0.9999608263946371 -0.5328330203333975 0.424179007336997 0.9912028118634736 0.6603167082440802 0.9887046181866692 0.40808206181339196 -0.5477292602242684 -0.9999608263946371 -0.5328330203333975 0.424179007336997 0.9912028118634736 0.6469193223286404 -0.2921388087338362 Tangent: 0 1.5574077246549023 -2.185039863261519 -0.1425465430742778 1.1578212823495777 -3.380515006246586 -0.29100619138474915 0.8714479827243188 -6.799711455220379 -0.45231565944180985 -2.185039863261519 -0.1425465430742778 1.1578212823495777 -3.380515006246586 -0.29100619138474915 0.8714479827243188 -6.799711455220379 -0.45231565944180985 0.6483608274590866 -225.95084645419513 1.1578212823495777 -3.380515006246586 -0.29100619138474915 0.8714479827243188 -6.799711455220379 -0.45231565944180985 0.6483608274590866 -225.95084645419513 -0.6358599286615808 0.4630211329364896 -0.29100619138474915 0.8714479827243188 -6.799711455220379 -0.45231565944180985 0.6483608274590866 -225.95084645419513 -0.6358599286615808 0.4630211329364896 7.2446066160948055 -0.8559934009085188 -6.799711455220379 -0.45231565944180985 0.6483608274590866 -225.95084645419513 -0.6358599286615808 0.4630211329364896 7.2446066160948055 -0.8559934009085188 0.3006322420239034 3.49391564547484 0.6483608274590866 -225.95084645419513 -0.6358599286615808 0.4630211329364896 7.2446066160948055 -0.8559934009085188 0.3006322420239034 3.49391564547484 -1.1373137123376869 0.15158947061240008 -0.6358599286615808 0.4630211329364896 7.2446066160948055 -0.8559934009085188 0.3006322420239034 3.49391564547484 -1.1373137123376869 0.15158947061240008 2.237160944224742 -1.5274985276366035 7.2446066160948055 -0.8559934009085188 0.3006322420239034 3.49391564547484 -1.1373137123376869 0.15158947061240008 2.237160944224742 -1.5274985276366035 0.00885165604168446 1.5881530833912738 0.3006322420239034 3.49391564547484 -1.1373137123376869 0.15158947061240008 2.237160944224742 -1.5274985276366035 0.00885165604168446 1.5881530833912738 -2.1348966977217008 -0.13352640702153587 -1.1373137123376869 0.15158947061240008 2.237160944224742 -1.5274985276366035 0.00885165604168446 1.5881530833912738 -2.1348966977217008 -0.13352640702153587 1.1787535542062797 -3.273703800428119 Cotangent: ∞ 0.6420926159343306 -0.45765755436028577 -7.015252551434534 0.8636911544506165 -0.2958129155327455 -3.436353004180128 1.1475154224051356 -0.1470650639494805 -2.210845410999195 -0.45765755436028577 -7.015252551434534 0.8636911544506165 -0.2958129155327455 -3.436353004180128 1.1475154224051356 -0.1470650639494805 -2.210845410999195 1.5423510453569202 -0.0044257413313241135 0.8636911544506165 -0.2958129155327455 -3.436353004180128 1.1475154224051356 -0.1470650639494805 -2.210845410999195 1.5423510453569202 -0.0044257413313241135 -1.5726734063976893 2.159728636267592 -3.436353004180128 1.1475154224051356 -0.1470650639494805 -2.210845410999195 1.5423510453569202 -0.0044257413313241135 -1.5726734063976893 2.159728636267592 0.13803371984040846 -1.1682333052318372 -0.1470650639494805 -2.210845410999195 1.5423510453569202 -0.0044257413313241135 -1.5726734063976893 2.159728636267592 0.13803371984040846 -1.1682333052318372 3.326323195635449 0.2862118326454602 1.5423510453569202 -0.0044257413313241135 -1.5726734063976893 2.159728636267592 0.13803371984040846 -1.1682333052318372 3.326323195635449 0.2862118326454602 -0.8792648757786926 6.596764247280111 -1.5726734063976893 2.159728636267592 0.13803371984040846 -1.1682333052318372 3.326323195635449 0.2862118326454602 -0.8792648757786926 6.596764247280111 0.4469951089489167 -0.6546651154860575 0.13803371984040846 -1.1682333052318372 3.326323195635449 0.2862118326454602 -0.8792648757786926 6.596764247280111 0.4469951089489167 -0.6546651154860575 112.9732103564319 0.6296622224002758 3.326323195635449 0.2862118326454602 -0.8792648757786926 6.596764247280111 0.4469951089489167 -0.6546651154860575 112.9732103564319 0.6296622224002758 -0.46840673886805423 -7.489155308722675 -0.8792648757786926 6.596764247280111 0.4469951089489167 -0.6546651154860575 112.9732103564319 0.6296622224002758 -0.46840673886805423 -7.489155308722675 0.8483537516655512 -0.305464410026718 Secant: 1 1.8508157176809255 -2.402997961722381 -1.0101086659079939 -1.5298856564663974 3.5253200858160887 1.0414819265951076 1.3264319004737049 -6.87285063669037 -1.097537906304962 -2.402997961722381 -1.0101086659079939 -1.5298856564663974 3.5253200858160887 1.0414819265951076 1.3264319004737049 -6.87285063669037 -1.097537906304962 -1.1917935066878957 225.95305931402496 -1.5298856564663974 3.5253200858160887 1.0414819265951076 1.3264319004737049 -6.87285063669037 -1.097537906304962 -1.1917935066878957 225.95305931402496 1.185039176093985 1.1019929988642352 1.0414819265951076 1.3264319004737049 -6.87285063669037 -1.097537906304962 -1.1917935066878957 225.95305931402496 1.185039176093985 1.1019929988642352 7.313297821227071 -1.316330012724367 -6.87285063669037 -1.097537906304962 -1.1917935066878957 225.95305931402496 1.185039176093985 1.1019929988642352 7.313297821227071 -1.316330012724367 -1.044212499898521 -3.634205076449851 -1.1917935066878957 225.95305931402496 1.185039176093985 1.1019929988642352 7.313297821227071 -1.316330012724367 -1.044212499898521 -3.634205076449851 1.5144248017882336 1.01142442505634 1.185039176093985 1.1019929988642352 7.313297821227071 -1.316330012724367 -1.044212499898521 -3.634205076449851 1.5144248017882336 1.01142442505634 2.4504875209567056 -1.8257195162269564 7.313297821227071 -1.316330012724367 -1.044212499898521 -3.634205076449851 1.5144248017882336 1.01142442505634 2.4504875209567056 -1.8257195162269564 -1.0000391751399944 -1.876760564452805 -1.044212499898521 -3.634205076449851 1.5144248017882336 1.01142442505634 2.4504875209567056 -1.8257195162269564 -1.0000391751399944 -1.876760564452805 2.357495261913165 1.0088752655170414 1.5144248017882336 1.01142442505634 2.4504875209567056 -1.8257195162269564 -1.0000391751399944 -1.876760564452805 2.357495261913165 1.0088752655170414 1.5457878061215053 -3.423030320189629 Cosecant: ∞ 1.1883951057781212 1.0997501702946164 7.086167395737187 -1.3213487088109024 -1.0428352127714058 -3.5788995472544056 1.5221010625637303 1.010756218400097 2.426486643551989 1.0997501702946164 7.086167395737187 -1.3213487088109024 -1.0428352127714058 -3.5788995472544056 1.5221010625637303 1.010756218400097 2.426486643551989 -1.8381639608896658 -1.000009793545209 -1.3213487088109024 -1.0428352127714058 -3.5788995472544056 1.5221010625637303 1.010756218400097 2.426486643551989 -1.8381639608896658 -1.000009793545209 -1.8636795977824385 2.3800058366134884 -3.5788995472544056 1.5221010625637303 1.010756218400097 2.426486643551989 -1.8381639608896658 -1.000009793545209 -1.8636795977824385 2.3800058366134884 1.0094817025647271 1.5377805615408537 1.010756218400097 2.426486643551989 -1.8381639608896658 -1.000009793545209 -1.8636795977824385 2.3800058366134884 1.0094817025647271 1.5377805615408537 -3.4733882595849295 -1.0401524951401468 -1.8381639608896658 -1.000009793545209 -1.8636795977824385 2.3800058366134884 1.0094817025647271 1.5377805615408537 -3.4733882595849295 -1.0401524951401468 -1.3315805352205023 6.672128486037505 -1.8636795977824385 2.3800058366134884 1.0094817025647271 1.5377805615408537 -3.4733882595849295 -1.0401524951401468 -1.3315805352205023 6.672128486037505 1.0953559364080034 1.1952348779358697 1.0094817025647271 1.5377805615408537 -3.4733882595849295 -1.0401524951401468 -1.3315805352205023 6.672128486037505 1.0953559364080034 1.1952348779358697 -112.97763609776322 -1.181725227926549 -3.4733882595849295 -1.0401524951401468 -1.3315805352205023 6.672128486037505 1.0953559364080034 1.1952348779358697 -112.97763609776322 -1.181725227926549 -1.104266667529635 -7.555623550585948 -1.3315805352205023 6.672128486037505 1.0953559364080034 1.1952348779358697 -112.97763609776322 -1.181725227926549 -1.104266667529635 -7.555623550585948 1.3113748846020408 1.0456139372602924 </code></pre> <p><a href="https://sharplab.io/#gist:90ee0820378bc5033593c2e0b18683bb" rel="nofollow noreferrer">sharplab.io</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/254972/231235">A Generic Two Dimensional Data Plane with SubPlane Method in C#</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>Trying to implement a series method to enhance the ability and functionality of two dimensional data plane, including <code>GetHashCode</code>, <code>Abs</code>, <code>Sum</code>, <code>Max</code>, <code>Min</code>, <code>Average</code>, <code>Contains</code>, <code>Count</code>, <code>PopulationVariance</code>, <code>PopulationStandardDeviation</code>, <code>Sine</code>, <code>Cosine</code>, <code>Tangent</code>, <code>Cotangent</code>, <code>Secant</code>, <code>Cosecant</code>, element-wise <code>Add</code>, element-wise <code>Subtract</code>, <code>ElementWiseMultiplication</code> and <code>ElementWiseDivision</code>.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any issue about potential drawback or unnecessary overhead of the implemented methods, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:41:09.890", "Id": "504501", "Score": "1", "body": "You should generally only be using `in` parameters with large structs as a potential perf gain. See https://stackoverflow.com/questions/52820372/why-would-one-ever-use-the-in-parameter-modifier-in-c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T00:00:00.890", "Id": "504533", "Score": "0", "body": "`this.Cast<double>().Grid.Cast<double>().ToArray()` two casts to the same type, one of them can be optimized out `this.Grid.Cast<double>().ToArray()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T00:45:47.237", "Id": "504702", "Score": "2", "body": "@aepot Thank you for the comments. I've tried that, however, the runtime error popped up \"System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Double'.'\"" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T14:04:26.620", "Id": "255650", "Score": "1", "Tags": [ "c#", "object-oriented", "generics", "classes", "lambda" ], "Title": "A Generic Two Dimensional Data Plane with Common Math Calculation Build-in Methods in C#" }
255650
<h3>Question</h3> <p>Recently I've written the following <code>splitv()</code> function, <strong>without</strong> using <code>strtok</code>. Any way to make it shorter and more efficient?</p> <h3>Descrption</h3> <p>The function calculates the <code>index-th</code> element of the string <code>str</code> split by <code>delim</code>. The element is written into <code>buff</code> and <code>0</code> is returned. When an index error is occurred, any <code>non 0</code> value is returned. This function was inspired by the python split function: <code>buff = str.split(delim)[index]</code>, but I think it works too hard and can be improved.</p> <pre><code>int splitv(char buff[], char str[], char delim[], int index) { // returns 0 if an element is written. Else non 0. char *start = str, *end; int i = 0, buff_i = 0; // check if delim not in str if ((end = strstr(str, delim)) == NULL) { if (index == 0) strcpy(buff, str); return index; } // delim is in str for (i = 0; i &lt; index; i++) { start = end + strlen(delim); end = strstr(start, delim); if (end == NULL) { // reached the last element if (i == index - 1) { end = str + strlen(str); break; } // index error: index &gt;= elements_count return -1; } } // copy element to buffer while (start != end) { buff[buff_i] = *start; start++; buff_i++; } buff[buff_i] = '\0'; return 0; } </code></pre> <p>Thanks in advance!</p>
[]
[ { "body": "<blockquote>\n<pre><code>int splitv(char buff[], char str[], char delim[], int index) {\n // returns 0 if an element is written. Else non 0.\n</code></pre>\n</blockquote>\n<p>A few points about this interface:</p>\n<ul>\n<li>Shouldn't <code>delim</code> be a pointer to <code>const char</code>? I think the function ought not to be modifying it. Similarly, if we can avoid modifying the input string (which is one major advantage to not using <code>strtok()</code>), then take that as pointer-to-const, too.</li>\n<li>Please accept an argument to indicate the capacity of <code>buff()</code> so that we can write code without buffer overflows!</li>\n<li><code>index</code> ought to be unsigned, as negative values make no sense here.</li>\n<li>We could make the return value more useful by returning the length of the match (or negative on failure). Like the interface to <code>snprintf()</code>, this is very useful in the event the buffer is too small. I'd even go as far as accepting <code>NULL, 0</code> for the buffer arguments in the same manner.</li>\n<li>It's more conventional to write the character pointer arguments as <code>char *arg</code> than with the indefinite array syntax. The two are identical as far as the compiler is concerned, of course, but keeping with convention makes code easier for other programmers to read.</li>\n</ul>\n<p>Let's see how we'd use the existing interface:</p>\n<pre><code>#include &lt;stdio.h&gt;\nint main(void)\n{\n char list[] = &quot;Alice, Bob, Charlie, Don&quot;;\n char delim[] = &quot;, &quot;;\n char buff[10]; /* is that enough?? */\n\n if (splitv(buff, list, delim, 2)) {\n fputs(&quot;Couldn't split the string.\\n&quot;, stderr);\n return 1;\n }\n\n printf(&quot;Found %s\\n&quot;, buff);\n}\n</code></pre>\n<p>See how much easier the new interface is:</p>\n<pre><code>int splitv(char *buff, size_t buff_len,\n const char *str, const char *delim,\n unsigned int index);\n\n\n#include &lt;stdio.h&gt;\nint main(void)\n{\n const char *list = &quot;Alice, Bob, Charlie, Don&quot;;\n char buff[10];\n\n int len = splitv(buff, sizeof buff, list, &quot;, &quot;, 2);\n if (len &lt; 0) {\n fputs(&quot;Couldn't split the string.\\n&quot;, stderr);\n return 1;\n }\n if ((size_t)len &gt;= sizeof buff) {\n fputs(&quot;Substring too long.\\n&quot;, stderr);\n return 1;\n }\n\n printf(&quot;Found %s\\n&quot;, buff);\n}\n</code></pre>\n<p>We don't have to guess if our buffer is big enough (and adaptive code can use the result to allocate a big enough buffer), and we can pass string literals as arguments.</p>\n<hr />\n<blockquote>\n<pre><code>const char *start = str, *end;\nint i = 0, buff_i = 0;\n</code></pre>\n</blockquote>\n<p>Prefer to declare one variable per line, and prefer to declare where you can also initialise:</p>\n<pre><code>const char *start = str;\n// check if delim not in str\nconst char *end = strstr(str, delim);\nif (!end) {\n</code></pre>\n\n<pre><code>for (int i = 0; i &lt; index; ++i) {\n</code></pre>\n<hr />\n<p>We have two bits of code doing the same thing when we reach the last element. It may help to rethink what this code does:</p>\n<ol>\n<li>Skip over zero or more substrings ending in <code>delim</code>.</li>\n<li>Find the next occurrence of <code>delim</code>, or the end of string.</li>\n<li>Copy the substring.</li>\n</ol>\n<p>Here's a simplified implementation that conforms to my suggested interface, and is structured according to those steps:</p>\n<pre><code>#include &lt;stdint.h&gt;\n#include &lt;string.h&gt;\n\nint splitv(char *buff, size_t buff_len,\n const char *str, const char *delim,\n unsigned int index)\n{\n /* returns length of the substring if it exists */\n /* returns negative on failure */\n\n /* useful constant */\n const size_t delim_len = strlen(delim);\n\n while (index--) {\n /* advance past next delimiter */\n const char *next = strstr(str, delim);\n if (!next) {\n /* not enough delimiters */\n return -1;\n }\n str = next + delim_len;\n }\n\n /* okay, we've found the right substring; now find its end */\n const char *end = strstr(str, delim);\n if (!end) {\n end = str + strlen(str);\n }\n\n /* decide how much to copy, and write it */\n size_t len = (size_t)(end - str);\n if (buff &amp;&amp; buff_len &gt; 0) {\n size_t write_size = len &lt; buff_len ? len : buff_len - 1;\n /* write the output */\n memcpy(buff, str, write_size);\n buff[write_size] = 0;\n }\n\n /* return the substring length (not including null terminator) */\n return (int)len;\n}\n</code></pre>\n<p>Note that I've hoisted <code>strlen(delim)</code> into a constant, as we know this doesn't need to be recomputed every time round the loop. I've also used standard <code>memcpy</code> function instead of the hand-rolled loop to write to <code>buff</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T04:07:34.477", "Id": "504552", "Score": "1", "body": "Further than making `index` unsigned, it should be a `size_t`, as this function won't work on most (all?) 64-bit systems with more than 4B occurrences" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:14:52.640", "Id": "504569", "Score": "2", "body": "Yes, I think so. In fact, in an early iteration I did exactly that, and I'm not sure why I changed it back. And `int` as return type is wrong, too (probably should be `size_t`, with `(size_t)-1` used as the error sentinel. Can I argue that my code isn't the finished item, just a step on the way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T07:15:13.023", "Id": "504927", "Score": "0", "body": "Yes, quite right. Thanks @chux" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T16:39:02.810", "Id": "255657", "ParentId": "255652", "Score": "3" } }, { "body": "<p>Before we talk about improving the efficiency of your function, lets talk about safety:</p>\n<ol>\n<li>You never check the validity of your function parameters.</li>\n<li>You have no way of knowing how big <code>buff</code> is.</li>\n</ol>\n<p>For the first issue, if <code>str</code> or <code>delim</code> is null, passing them directly in to <code>strstr</code> will cause a segfault and crash your program.</p>\n<p>The second issue is worse: if <code>buff</code> is smaller then <code>str</code>, your function may end up clobbering memory when it tries to copy from <code>str</code> to <code>buff</code>.<br />\nThis is undefined behavior, and the results are unpredictable.</p>\n<p>Now for some efficiency suggestions:</p>\n<ol>\n<li><p>Calculate string length only once.<br />\nSince <code>strlen</code> works by running over the string looking for '\\0' terminator, it is more efficient to call it only once at the beginning of your function and store the result in a variable.<br />\nThis can also allow you to implement a simple shortcut for edge cases such as where <code>str</code> or <code>delimiter</code> are empty strings, or delimiter is longer then <code>str</code>.</p>\n</li>\n<li><p>You don't need your own <code>while</code> loop at the end and the <code>buff_i</code> variable.<br />\nYou can simply use <code>memcpy</code> or <code>strncpy</code> to copy the element in to the buffer.<br />\n<code>memcpy</code> would be slightly more efficient, since it does not check for '\\0', while <code>strncpy</code> does.</p>\n</li>\n<li><p>Since your logic is that if delimiter is never found, but the requested element is 0 the result is &quot;success&quot;, you don't need to handle this as a separate edge case.<br />\nThat means you can get rid of the first <code>if</code> block, and handle everything in one loop.<br />\nYou can also get rid of the special checks in the <code>if</code> loop and just focus on the search.</p>\n</li>\n</ol>\n<p>The following code example does not include the suggested validity checks:</p>\n<pre><code>int i;\nchar *start = str;\nchar *end = start;\nsize_t delim_len = strlen(delim);\nsize_t copy_len;\n\nfor (i = 0; i &lt;= index &amp;&amp; end != NULL; i++) {\n end = strstr(start, delim);\n if (end != NULL &amp;&amp; i != index) start = end + delim_len;\n}\n\n/* element not found */\nif (i != index) return index;\n\nif (end == NULL) {\n copy_len = strlen(start);\n} else {\n copy_len = (ssize_t)(end - start);\n}\n\nmemcpy(buff, start, copy_len);\nbuff[copy_len] = '\\0';\n\nreturn 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T20:14:19.487", "Id": "505004", "Score": "1", "body": "@chux-ReinstateMonica typo on my side, thanks for pointing it out, fixed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T16:49:36.410", "Id": "255658", "ParentId": "255652", "Score": "4" } } ]
{ "AcceptedAnswerId": "255658", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T15:08:57.830", "Id": "255652", "Score": "2", "Tags": [ "algorithm", "c" ], "Title": "Split a string and write the i-th element into a buffer with C" }
255652
<p>Here is my memcpy algorithm I've been working on:</p> <pre><code>static void* memcpy(void* destination, const void* source, size_t size) { char* dest = (char*)destination; const char* src = (const char*)source; //check if length is greater than 16 bytes if ((size - 16) &lt; 33) { while (size &gt; 15) { //wtf even is this, assembly in c++? am i a assembly developer too now? auto val = _mm_loadu_si128((__m128i*)(src)); _mm_storeu_si128((__m128i*)dest, val); dest += 16; src += 16; size -= 16; } } #ifdef __AVX512__ else if((size - 32) &lt; 65){ while (size &gt; 31) { //wtf even is this, assembly in c++? am i a assembly developer too now? auto val = _mm256_loadu_si256((__m256i*)(src)); _mm256_storeu_si256((__m256i*)dest, val); dest += 32; src += 32; size -= 32; } } else if(size &gt; 65 ) { while (size &gt; 31) { //wtf even is this, assembly in c++? am i a assembly developer too now? auto val = _mm512_loadu_si512((__m512i*)(src)); _mm512_storeu_si512((__m512i*)dest, val); dest += 32; src += 32; size -= 32; } } #else else if (size &gt; 32) { while (size &gt; 31) { //wtf even is this, assembly in c++? am i a assembly developer too now? auto val = _mm256_loadu_si256((__m256i*)(src)); _mm256_storeu_si256((__m256i*)dest, val); dest += 32; src += 32; size -= 32; } } #endif while (size--) { *dest++ = *src++; } /*if (length &gt; 16) { src += length - 16; dest += length - 16; auto val = _mm_loadu_si128((__m128i*)(src)); _mm_storeu_si128((__m128i*)(dest), val); } else { for (; index &lt; length; ++index) { *dest++ = *src++; } }*/ return destination; } </code></pre> <p>I don't think my cpu supports AVX 512 so I disabled it for now. I'm trying to get this algorithm as close to std::memcpy as I can, but I'm not there just yet. Any ideas on how I can make this faster?</p> <p>Here are the times I tested with 999,999 iterations and averaged the result:</p> <pre><code>Copying 1361 bytes: Mine ms: 0.000233 C++ STL ms: 0.000230 </code></pre> <p>As you can see they are really close, but I know I can make it faster.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T05:05:09.587", "Id": "504556", "Score": "0", "body": "OK. This is fun exercise. But you are unlikely to beat `memcpy` in the standard library (not the STL). But if you do you should go talk to the standard library people they would incorporate your code into the compiler. But the standard library version has been optimized constantly over the last 60 years (approx) and utilizes hardware specific optimizations to be optimal for a particular processor." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T15:42:08.423", "Id": "255654", "Score": "3", "Tags": [ "c++", "performance", "algorithm", "memory-optimization" ], "Title": "Memcpy function optimzation" }
255654
<p>This game is pretty common for beginner projects. I wrote a version of this before all in Main - so here I challenge myself to recreate it in a more OO style.</p> <p>I wanted to take a more OO approach, so any feedback on where I could do better or am making some errors is appreciated. I also have some personal confusion if in some parts I'm coding this <em>procedurally</em>. I might be mistaken but I think this code is a bit of both styles, and if so, can someone help explain the distinctive differences? Is there too much recursion in some parts? How does the readability appear? What are your thoughts?</p> <p><em>The game will generate a random secret number and ask the user to input their guesses within the given number of attempts</em> Code below:</p> <pre><code>import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class GuessGame { private static final Scanner SC = new Scanner(System.in); private static final Random R = new Random(); private static int secret = R.nextInt(100) + 1; private static final int GIVEN_ATTEMPTS = 10; private int attempts = 0; public void playGame() { promptGuess(); } private int promptGuess() { try { printLine(&quot;Guess a number from 1-100&quot;); int guess = SC.nextInt(); if (guess &lt; 1) { promptGuess(); } else { return compare(guess); } } catch(InputMismatchException e) { printLine(&quot;Only numbers please&quot;); SC.nextLine(); promptGuess(); } return 0; } private int compare(int guess) { attempts++; if (attempts == GIVEN_ATTEMPTS) { return promptResult(4); } int difference = secret - guess; if (difference &gt; 0) { return promptResult(1); } else if (difference &lt; 0) { return promptResult(2); } else { return promptResult(3); } } private int promptResult(int n) { switch (n) { case 1: printLine(&quot;Guess was too low, try again&quot;); promptGuess(); break; case 2: printLine(&quot;Guess was too high, try again&quot;); promptGuess(); break; case 3: printLine(&quot;You got it! Nice guess! The number was &quot; + secret); printLine(&quot;In &quot; + attempts + &quot; attempts&quot;); printLine(&quot;Game Over&quot;); attempts = 0; secret = R.nextInt(100) + 1; playAgain(); case 4: printLine(&quot;Too many guesses! &quot; + GIVEN_ATTEMPTS + &quot;/&quot; + GIVEN_ATTEMPTS + &quot; used.&quot;); printLine(&quot;Secret number was: &quot; + secret + &quot; Game Over&quot;); attempts = 0; secret = R.nextInt(100) + 1; playAgain(); } return 0; } private void printLine(String s) { System.out.println(s); } private void playAgain() { printLine(&quot;Play again? (Enter Y for yes or N for no)&quot;); String reply = SC.next(); if (reply.equalsIgnoreCase(&quot;Y&quot;)) { playGame(); } else if (reply.equalsIgnoreCase(&quot;N&quot;)) { printLine(&quot;Thanks for playing&quot;); System.exit(0); } else { System.out.println(&quot;Please enter a valid answer&quot;); playAgain(); } } } public class Main { public static void main(String[] args) { GuessGame g = new GuessGame(); g.playGame(); } } </code></pre>
[]
[ { "body": "<p>Curious, this code looks a lot like <a href=\"https://codereview.stackexchange.com/questions/255641/java-tic-tac-toe-console\">the code in this question</a>. I'm not saying that you have another account, but you don't happen to be in the same class or something?</p>\n<hr />\n<p>Your formatting seems to be inconsistent, use an automatic code formatter (your IDE most likely has one).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final Scanner SC = new Scanner(System.in);\n</code></pre>\n<p>Don't shorten names just because you can, it makes the code harder to understand and maintain.</p>\n<p>The usage of the scanner (or streams in general) should most likely be scoped. Streams are rather easily associated with native resources which must be destroyed explicitly to be freed.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private static final Scanner SC = new Scanner(System.in);\n private static final Random R = new Random();\n private static int secret = R.nextInt(100) + 1;\n private static final int GIVEN_ATTEMPTS = 10;\n private int attempts = 0;\n</code></pre>\n<p>Some of your state is <code>static</code>, your methods are all <code>instance</code>. You most likely want to make all your state <code>instance</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (guess &lt; 1) {\n promptGuess();\n } else {\n return compare(guess);\n }\n</code></pre>\n<p>You're recursing here, so keeping to hit Return without entering something should at some point crash your game because of a stackoverflow.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if (attempts == GIVEN_ATTEMPTS) {\n</code></pre>\n<p>A check for greater-quals would be safer.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private int promptResult(int n) {\n</code></pre>\n<p>This does not prompt for a result, it displays whether the guess was correct or not, the method should be renamed.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> switch (n) {\n case 1:\n</code></pre>\n<p>Instead of using numbers here, you could either use constants or an enum. That way nobody would need to remember that <code>2</code> means &quot;too high&quot;.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private void printLine(String s) {\n System.out.println(s);\n }\n</code></pre>\n<p>Good idea, but you're gaining very, very little when it comes to readability with this method.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.exit(0);\n</code></pre>\n<p>Something to keep in mind is that <code>System.exit</code> is not &quot;exit the application&quot; but &quot;kill the JVM process&quot;. When invoking this not even <code>finally</code> blocks may run. In this case it does not matter, but something to keep in mind.</p>\n<hr />\n<p>Your logic is all over the place. Instead of chaining the methods together like you did, you should consider having a main method which handles the flow and calls the methods as needed. That way you'd have the logic of your game in one place but the &quot;details&quot; are hidden away in functions, which would make it rather easy to not only figure out how the game works, but also makes it easier possible to change single functions.</p>\n<p>Regarding on how to structure this more proper, there is not much to do except cleaning up the mixed state. What you can start with is to have the logic of the game separated from the logic to print to the terminal. So you'd have a <code>Game</code> class and that one would accept a <code>GameUi</code> interface as parameter, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public interface GameUi {\n public abstract int getGuess();\n // ...\n}\n\npublic class SimpleTerminalGameUi implements GameUi;\n\npublic class Game {\n public Game(GameUi gameUi);\n \n // Somewhere in your logic:\n int guess = gameUi.getGuess();\n}\n\nnew Game(new SimpleTerminalGameUi());\n</code></pre>\n<p>That would allow you to decouple the presentation from the internal state of the game.</p>\n<p>As further exercise, do the same with the secret provider.</p>\n<blockquote>\n<p>I might be mistaken but I think this code is a bit of both styles, and if so, can someone help explain the distinctive differences?</p>\n</blockquote>\n<p>Your code is not object-oriented at all, you're just using a single object as container. But to be fair, there isn't that much logic to shell out to different objects to begin with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T19:12:50.363", "Id": "504770", "Score": "0", "body": "Concord on separation of concerns: here decoupling _logic_ from `GameUI` (note: most Java naming conventions allow up to 3-letter acronyms like `UI` or `URL`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T20:34:36.450", "Id": "255666", "ParentId": "255659", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T17:16:14.483", "Id": "255659", "Score": "2", "Tags": [ "java", "object-oriented", "game", "recursion", "number-guessing-game" ], "Title": "Guess Number Game - Console based game using Java" }
255659
<p>I'm an undergraduate student with little to no experience in formal computer science or coding, and I specialise in quantitative social science research. Our professor asked us to fabricate some network data to analyse because of the pandemic, and I asked permission to create a Python program that simulates social networks. I successfully created one, but it runs painfully slow for larger groups and longer time periods. I'd like to ask for help with removing inefficiencies, of which I'm sure there are plenty in the code. Any help would be appreciated, and thanks for the assistance.</p> <pre><code>import sys import names import random import math import numpy as np import pandas as pd from statistics import mean # Logistic function to bind any inputs to output between [0, 1] def exp(x): return math.exp(x) / (1 + math.exp(x)) # Given two lists of values and two lists of maximum and minimum possible values, output a value based on distance # based on dissimilarity of traits. def distance(x, y): max_dist = len(x) dist = 0 for i in range(len(x)): if x[i] != y[i]: dist += 1 return dist - 4 class Student: def __init__(self, name, studentID, schoolSize, numberClasses, fresh=False): # Name, classID, and StudentID. Student ID also functions as position in class roster. self.name = name self.ID = studentID self.graduated = False # Probability density function for chance you interact with other people in the class/generally. Probability of # interacting with others is zero. # self.classPDF = [] # self.interactionPDF = [1 / (schoolSize - 1)] * schoolSize self.classPDF = {} self.interactionPDF = {studentID: 0} # Introversion-extraversion factor, which is a random number from 0 to 1 that determines your chance # at getting an extra chance to interact with people and how many tries you get to meet new people. self.IEFactor = np.random.normal(loc=0.5, scale=0.1) while self.IEFactor &gt; 1 or self.IEFactor &lt; 0: self.IEFactor = np.random.normal(loc=0.5, scale=0.1) # Trackers, which track total, successful, and failed interactions for each classmate. # Final list tracks sentiment, which represents the strength and direction of a relationship. self.interactionTracker = {} self.successInteractions = {} self.failedInteractions = {} self.sentimentTracker = {} # Various traits, drawn from UK census definitions. self.gender = \ random.choices([&quot;Male&quot;, &quot;Female&quot;, &quot;Trans Male&quot;, &quot;Trans Female&quot;], weights=[0.49, 0.49, 0.01, 0.01], k=1)[0] self.ethnicity = random.choices([&quot;Asian&quot;, &quot;Black&quot;, &quot;Mixed&quot;, &quot;White British&quot;, &quot;White Other&quot;, &quot;Other&quot;], weights=[0.185, 0.133, 0.05, 0.449, 0.149, 0.034], k=1)[0] self.income = random.choices([&quot;Managerial, Administrative&quot;, &quot;Intermediate&quot;, &quot;Small Employers/Freelancers&quot;, &quot;Lower Supervisory/Technical&quot;, &quot;Semi-Routine/Routine&quot;, &quot;Unemployed/Full-Time Students&quot;], weights=[0.304, 0.13, 0.093, 0.072, 0.259, 0.141], k=1)[0] self.birthday = random.randint(1, 365) if fresh: self.age = random.choices([14, 15, 16], weights=[0.10, 0.80, 0.10], k=1)[0] self.grade = &quot;Freshman&quot; else: self.age = random.choices([14, 15, 16, 17, 18, 19], weights=[0.025, 0.225, 0.225, 0.225, 0.225, 0.025], k=1)[0] if self.age in [14, 15]: grade = random.choices([&quot;Freshman&quot;, &quot;Sophomore&quot;, &quot;Junior&quot;], weights=[0.88, 0.10, 0.02], k=1)[0] elif self.age == 16: grade = random.choices([&quot;Freshman&quot;, &quot;Sophomore&quot;, &quot;Junior&quot;, &quot;Senior&quot;], weights=[0.10, 0.88, 0.10, 0.02], k=1)[0] elif self.age == 17: grade = random.choices([&quot;Sophomore&quot;, &quot;Junior&quot;, &quot;Senior&quot;], weights=[0.10, 0.80, 0.10], k=1)[0] else: grade = random.choices([&quot;Junior&quot;, &quot;Senior&quot;], weights=[0.10, 0.90], k=1)[0] self.grade = grade if self.grade == &quot;Freshman&quot;: assignedClass = random.choices(list(range(numberClasses)), weights=[1 / numberClasses] * (numberClasses), k=1)[0] elif self.grade == &quot;Sophomore&quot;: assignedClass = random.choices(list(range(numberClasses, 2 * numberClasses)), weights=[1 / numberClasses] * (numberClasses), k=1)[0] elif self.grade == &quot;Junior&quot;: assignedClass = random.choices(list(range(2 * numberClasses, 3 * numberClasses)), weights=[1 / numberClasses] * (numberClasses), k=1)[0] else: assignedClass = random.choices(list(range(3 * numberClasses, 4 * numberClasses)), weights=[1 / numberClasses] * (numberClasses), k=1)[0] self.assignedClass = assignedClass self.academics = random.choices([&quot;A+&quot;, &quot;A-&quot;, &quot;B+&quot;, &quot;B-&quot;, &quot;C+&quot;, &quot;C-&quot;, &quot;D&quot;, &quot;F&quot;], weights=[0.05, 0.05, 0.20, 0.20, 0.20, 0.20, 0.05, 0.05], k=1)[0] self.traits = [self.name, self.IEFactor, self.gender, self.ethnicity, self.income, self.age, self.grade, self.assignedClass, self.academics, self.graduated] def __hash__(self): return hash(str(self.name + self.academics + self.grade)) def __eq__(self, other): return self.ID == other.ID def __str__(self) -&gt; str: return [self.name, self.ID] def __repr__(self) -&gt; str: return self.name + &quot; -&gt; &quot; + str(self.ID) # Class object for classroom. class Classroom: def __init__(self, numberClasses, schoolSize): self.activeRoster = [] self.passiveRoster = [] self.classRosters = [[]] * (4 * numberClasses) self.classesPerGrade = numberClasses self.size = len(self.activeRoster) self.day = 0; for i in range(schoolSize): student = Student(names.get_full_name(), i, schoolSize = schoolSize, numberClasses = numberClasses) self.activeRoster.append(student) self.passiveRoster.append(student) self.classRosters[student.assignedClass].append(student) student.classID = len(self.classRosters[student.assignedClass]) - 1 for student in self.activeRoster: for other_student in self.activeRoster: student.sentimentTracker[other_student] = 0 student.failedInteractions[other_student] = 0 student.successInteractions[other_student] = 0 student.interactionTracker[other_student] = 0 if student == other_student: student.interactionPDF[other_student] = 0 student.classPDF[other_student] = 0 else: student.interactionPDF[other_student] = 1 / (len(self.activeRoster) - 1) student.classPDF[other_student] = 1 / (len(self.classRosters[student.assignedClass]) - 1) def roster(self): return self.roster def dayElapses(self): interaction_limit = {} for student in self.activeRoster: interaction_limit[student] = int(student.IEFactor * 20) for classRoster in self.classRosters: for student in classRoster: print(student.name + &quot; is in class!&quot;) interactions_remaining = random.choices([1, 2], weights=[1 - student.IEFactor, student.IEFactor], k=1)[ 0] while interactions_remaining &gt; 0: self.conversation(student, classRoster, student.classPDF, interaction_limit) interactions_remaining -= 1 for student in self.activeRoster: interactions_remaining = random.choices([1, 2], weights=[1 - student.IEFactor, student.IEFactor], k=1)[0] print(student.name + &quot; is on break!&quot;) while interactions_remaining &gt; 0: self.conversation(student, self.activeRoster, student.interactionPDF, interaction_limit) interactions_remaining -= 1 self.statusChanges(self.day) self.day += 1 def conversation(self, student, roster, PDF, interaction_limit): partner = self.discover(student, roster, PDF, interaction_limit) if partner is None: return self.interact(student, partner) def discover(self, student, roster, PDF, interaction_limit): try_limit = int(student.IEFactor * 10) partner = random.choices(list(PDF.keys()), weights=list(PDF.values()), k=1)[0] print(&quot;Wanna talk, &quot; + partner.name + &quot;?&quot;) while partner not in roster or interaction_limit[partner] &lt;= 0 or partner.ID == student.ID: print(&quot;I guess not.&quot;) partner = random.choices(list(PDF.keys()), weights=list(PDF.values()), k=1)[0] print(&quot;Wanna talk, &quot; + partner.name + &quot;?&quot;) try_limit -= 1 if try_limit == 0: return None interaction_limit[student] -= 1 interaction_limit[partner] -= 1 return partner def interact(self, student, partner, fam=0.0005, dec=1, discrim=5): print(distance(student.traits, partner.traits)) print(student.sentimentTracker[partner]) chance_of_success = exp(student.sentimentTracker[partner] + partner.sentimentTracker[student] * (distance(student.traits, partner.traits) / 4)) chances_of_success = [1 - chance_of_success, chance_of_success] print(chances_of_success) interaction_status = random.choices([0, 1], weights=chances_of_success, k=1)[0] if interaction_status == 0: print(&quot;That didn't go so well.&quot;) student.interactionTracker[partner] += 1 student.failedInteractions[partner] += 1 student.interactionPDF[partner] -= student.interactionPDF[partner] * exp(self.size) student.sentimentTracker[partner] -= 1 partner.interactionTracker[student] += 1 partner.failedInteractions[student] += 1 partner.interactionPDF[student] -= partner.interactionPDF[student] * exp(self.size) partner.sentimentTracker[student] -= 1 else: print(&quot;That went great!&quot;) student.successInteractions[partner] += 1 student.interactionTracker[partner] += 1 student.interactionPDF[partner] += discrim + exp(self.size) student.sentimentTracker[partner] += 1 partner.interactionTracker[student] += 1 partner.failedInteractions[student] += 1 partner.interactionPDF[student] += partner.interactionPDF[student] * exp(self.size) partner.sentimentTracker[student] += 1 student_sum = sum(student.interactionPDF.values()) other_sum = sum(partner.interactionPDF.values()) for k, v in student.interactionPDF.items(): student.interactionPDF[k] = v/student_sum for k, v in partner.interactionPDF.items(): partner.interactionPDF[k] = v/other_sum for student in self.activeRoster: for student in student.sentimentTracker.keys(): if student.sentimentTracker[student] &gt; 1: student.sentimentTracker[student] -= 1 * dec elif student.sentimentTracker[student] &lt; 1: student.sentimentTracker[student] += 2 * dec def statusChanges(self, day): for student in self.passiveRoster: if student.birthday == day or (day - student.birthday) % 365 == 0: student.age += 1 if day != 0 and day % 365 == 0: self.yearChanges() def yearChanges(self): newActiveRoster = [] self.classRosters = [[]] * (4 * self.classesPerGrade) # Promoting all students and changing their classes, if they aren't seniors. # Graduating seniors. Adding new freshmen. Removing seniors from active and class rosters. for student in self.activeRoster: if student.grade in [&quot;Freshman&quot;, &quot;Sophomore&quot;, &quot;Junior&quot;]: student.academics = self.academics = random.choices([&quot;A+&quot;, &quot;A-&quot;, &quot;B+&quot;, &quot;B-&quot;, &quot;C+&quot;, &quot;C-&quot;, &quot;D&quot;, &quot;F&quot;], weights=[0.05, 0.05, 0.20, 0.20, 0.20, 0.20, 0.05, 0.05], k=1)[0] if student.grade == &quot;Freshman&quot;: student.grade == &quot;Sophomore&quot; student.assignedClass = \ random.choices(list(range(self.classesPerGrade + 1, 2 * self.classesPerGrade + 1)), weights=[1 / self.classesPerGrade] * self.classesPerGrade - 1, k=1)[0] elif student.grade == &quot;Sophomore&quot;: student.grade == &quot;Junior&quot; student.assignedClass = \ random.choices(list(range(2 * self.classesPerGrade + 1, 3 * self.classesPerGrade + 1)), weights=[1 / self.classesPerGrade] * self.classesPerGrade - 1, k=1)[0] else: student.grade == &quot;Senior&quot; student.assignedClass = \ random.choices(list(range(3 * self.classesPerGrade + 1, 4 * self.classesPerGrade + 1)), weights=[1 / self.classesPerGrade] * self.classesPerGrade - 1, k=1)[0] self.classRosters[student.assignedClass].append(student) newActiveRoster.append(student) else: student.grade == &quot;Graduated&quot; student.graduated = True new_students = (len(self.passiveRoster) / 4) + \ random.randint(int(-len(self.passiveRoster) / 16), int(len(self.passiveRoster) / 16)) id = len(self.passiveRoster) - 1 for i in range(new_students): student = Student(names.get_full_name(), id, self.size, self.classesPerGrade, fresh=True) self.activeRoster.append(student) self.passiveRoster.append(student) self.classRosters[student.assignedClass].append(student) for other_student in self.activeRoster: if student.ID == other_student.ID: student.interactionPDF[other_student] = 0 student.classPDF[other_student] = 0 student.sentimentTracker[other_student] = 0 student.failedInteractions[other_student] = 0 student.successInteractions[other_student] = 0 student.interactionTracker[other_student] = 0 else: student.interactionPDF[other_student] = 1 / (len(self.activeRoster) - 1) other_student.interactionPDF[student] = mean(other_student.interactionPDF.values()) student.sentimentTracker[other_student] = 0 student.failedInteractions[other_student] = 0 student.successInteractions[other_student] = 0 student.interactionTracker[other_student] = 0 other_student.sentimentTracker[student] = 0 other_student.failedInteractions[student] = 0 other_student.successInteractions[student] = 0 other_student.interactionTracker[student] = 0 if other_student in self.classRosters[student.assignedClass]: student.classPDF[other_student] = 1 / (len(self.classRosters[student.assignedClass]) - 1) other_student.classPDF[student] = mean(student.classPDF.values()) def main(): # Check command line arguments if len(sys.argv) != 4: sys.exit(&quot;Usage: python sim.py class_size number_of_days classes_per_grade&quot;) print(&quot;Generating classroom.&quot;) working_classroom = Classroom(numberClasses=int(sys.argv[3]), schoolSize=int(sys.argv[1])) print(&quot;Setting up interactions.&quot;) print(sys.argv) for i in range(int(sys.argv[2])): working_classroom.dayElapses() root_list = [] supplementary_list = [] for student in working_classroom.passiveRoster: root_list.append(list(student.sentimentTracker.values())) supplementary_list.append(student.traits) root_list = np.array(root_list) print(root_list) print(len(root_list)) df = pd.DataFrame(data=root_list) df.to_csv('output.csv') supplementary_list = pd.DataFrame(data=supplementary_list) supplementary_list.to_csv('supplementary.csv') if __name__ == '__main__': main() </code></pre> <p>The code above produces an adjacency matrix for social network analysis in R, as well as a supplementary set of information on the network participants. While I am primarily looking for ways to speed up the programme for large datasets, opinions on the structure of the programme are also appreciated. This is my first time coding such a project independently, and so I look forward to learning from your criticism. Thanks for the assistance.</p> <p>Sincerely, Charles</p>
[]
[ { "body": "<p>In <code>distance(x, y)</code>, the value <code>max_dist</code> is never used.</p>\n<p>The function could be &quot;simplified&quot; to one line:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def distance(x, y):\n return sum(xi != yi for xi, yi in zip(x, y)) - 4\n</code></pre>\n<p>In <code>class Classroom</code>, the function <code>roster(self)</code> returns <code>self.roster</code> ... the function that was just called? This doesn't seem useful at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T23:01:35.373", "Id": "504629", "Score": "0", "body": "Thanks for the input, that was actually a good call. I thought I had properly scrubbed the code of relics, but it appears not. Thanks a lot. By the way, I've made some revisions to the code after editing since the behaviour appears to be bugged in some ways. May I edit the program presented above?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T02:21:24.770", "Id": "504634", "Score": "0", "body": "Editing your code after any answer has been posted would (likely) invalidate the answer(s), so is against the rules of this site. It would be better to post a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T03:00:49.970", "Id": "504637", "Score": "0", "body": "Thanks. The edits weren't that severe anyway, just changing the probabilities of getting into particular incomes or classes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T06:54:52.390", "Id": "255681", "ParentId": "255661", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T18:58:01.930", "Id": "255661", "Score": "2", "Tags": [ "python", "simulation" ], "Title": "Improving performance for social network simulation program" }
255661
<p>I made a small simple drawing app using HTML5 Canvas, learning how to use canvas.</p> <p>You can right click to change color, scroll to change brush size, and click + drag to draw on the screen.</p> <p>Any feedback is appreciated, but I am concerned about storing each move event circle that is created in an array may become quite messy eventually.</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>class Circle { constructor(x, y, radius = 2) { this.x = x; this.y = y; this.radius = radius; this.persist = []; this.color = "lightblue"; } draw() { this.persist.forEach(e =&gt; { c.beginPath(); c.arc(e.x, e.y, e.radius, 0, Math.PI * 2, false); c.fillStyle = e.color; c.fill(); }); c.beginPath(); c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false); c.fillStyle = this.color; c.fill(); } } const colors = [ "#ffadad", "#ffd6a5", "#fdffb6", "#caffbf", "#9bf6ff", "#a0c4ff", "#ffc6ff", "#bdb2ff" ] var c = null; var canvas = null; const main = function () { canvas = document.querySelector("canvas"); c = canvas.getContext("2d"); sizeCanvas(); window.addEventListener("resize", sizeCanvas); window.addEventListener("mousemove", function(e){ myCursor.x = event.x; myCursor.y = event.y; if (e.buttons == 1) { myCursor.persist.push({x: myCursor.x, y: myCursor.y, radius: myCursor.radius, color: myCursor.color}); } }); window.addEventListener("wheel", function(e){ e.preventDefault(); const amountToChange = -1 * e.deltaY / 25; if (myCursor.radius + amountToChange &lt; 1 || myCursor.radius + amountToChange &gt; 50) return; myCursor.radius += amountToChange; }, {passive: false}); window.addEventListener("contextmenu", function(e) { e.preventDefault(); myCursor.color = colors[Math.floor(Math.random()*colors.length)] }); putCursorOnCanvas(); // makeCanvasDrawable(); } function sizeCanvas() { canvas.height = innerHeight; canvas.width = innerWidth; } const myCursor = new Circle(0, 0, 10); function putCursorOnCanvas() { requestAnimationFrame(putCursorOnCanvas); c.clearRect(0, 0, innerWidth, innerHeight); myCursor.draw(); } function makeCanvasDrawable() { } window.onload = main;</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: lightblue; margin: 0; height: 100%; overflow: hidden; } canvas { background-color: black; cursor: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en" dir="ltr"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;draw a line :D&lt;/title&gt; &lt;link rel="stylesheet" href="main.css"&gt; &lt;script src="main.js" charset="utf-8"&gt;&lt;/script&gt; &lt;meta content="width=device-width, initial-scale=1" name="viewport"&gt; &lt;/head&gt; &lt;body&gt; &lt;canvas&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:45:02.147", "Id": "506128", "Score": "1", "body": "And why do you have this `persist` array? Why do you redraw everything in that array 60 times per second? I would say you don't even need the `requestAnimationFrame` if you just draw at the moment the mouse is \"down\" and then you can use the `mouseMove` event listener to draw. Because a canvas is persistent, you don't need to remember what was drawn before. (unless you want to add an undo function)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T19:11:32.897", "Id": "255662", "Score": "2", "Tags": [ "javascript", "html5", "canvas" ], "Title": "HTML 5 Canvas Drawing app" }
255662
<p>Any suggestions on how to improve the <code>Makefile</code>, e.g. how to best replace the multiple uses of <code>example1/example2</code>, <code>ex1_src/ex2_src</code>, <code>ex1_obj/ex2_obj</code> with static pattern rules?</p> <pre><code>build := ./build targets := $(build)/example1 $(build)/example2 src := ./src srcfiles := $(shell find $(src) \( -name &quot;*.cpp&quot; -or -name &quot;*.c&quot; \) ! -path '*/examples/*') objects := $(srcfiles:%=$(build)/%.o) ex1_src := $(shell find $(src) -name example1.cpp) ex1_obj := $(ex1_src:%=$(build)/%.o) ex2_src := $(shell find $(src) -name example2.cpp) ex2_obj := $(ex2_src:%=$(build)/%.o) all_obj := $(objects) $(ex1_obj) $(ex2_obj) depends := $(all_obj:%.o=%.d) incdirs := $(shell find $(src) -type d ! -path '*/examples') includes := $(addprefix -I,$(incdirs)) CXX := g++ CXXFLAGS := -std=c++17 $(includes) -Wall -MMD -MP LDFLAGS := -lpthread all: $(targets) $(build)/example1: $(objects) $(ex1_obj) $(build)/example2: $(objects) $(ex2_obj) $(targets): $(CXX) $(LDFLAGS) $^ -o $@ $(build)/%.cpp.o: %.cpp @mkdir -p $(dir $@) $(CXX) $(CXXFLAGS) -c $&lt; -o $@ .PHONY: clean clean: rm -rf $(build) -include $(depends) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T09:40:58.533", "Id": "504650", "Score": "1", "body": "Welcome to Code Review! Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." } ]
[ { "body": "<p>It's usually best to have the Makefile in the same directory as the build products, or at least have that as the working directory. Then there's no need to re-write the built-in rules for compiling and linking. Use <code>VPATH</code> to ensure the source files can be found.</p>\n<blockquote>\n<pre><code>LDFLAGS := -lpthread\n</code></pre>\n</blockquote>\n<p>That should go into <code>LIBS</code> (which gets expanded later in the command line), so that it gets used as needed. <code>LDFLAGS</code> is for flags such as <code>-L</code> which need expanding further to the left.</p>\n<p>I'm not convinced that <code>example1</code> and <code>example2</code> are great names for your programs - surely you can think of something more descriptive and memorable for your users?</p>\n<blockquote>\n<pre><code>ex1_src := $(shell find $(src) -name example1.cpp)\n</code></pre>\n</blockquote>\n<p>Do you really need to invoke a <code>find</code> there? I would expect there to be few enough matches that you could simply list them, and update the list when you add a new one. I'd do the same for <code>srcfiles</code> too - or create a library, so that the resultant programs only include the objects they need.</p>\n<p>I think generally there's too much use of shells here, despite them all being in <code>:=</code> assignments. You want makefile parsing to be <em>fast</em>, so you can see all your unit test results as quickly as possible.</p>\n<p>So I'd write</p>\n<pre><code>example1: example1.o object_a.o object_b.o object_c.o\nexample1: LINK.o = $(LINK.cc)\n</code></pre>\n<p>The target-specific <code>LINK.o</code> is necessary so that the C++ linker is used. It's cleaner and more portable than adding the C++ runtime library to <code>LIBS</code>.</p>\n<p>You're missing some very important <code>CXXFLAGS</code>:</p>\n<pre><code>CXXFLAGS += -Wall -Wextra\n</code></pre>\n<p>I'd likely add a few more:</p>\n<pre><code>CXXFLAGS += -Wpedantic -Warray-bounds -Weffc++\nCXXFLAGS += -Werror\n</code></pre>\n<p>Good use of <code>.PHONY</code> - that's often overlooked.</p>\n<p>You should also have <code>.DELETE_ON_ERROR:</code> so that interrupted builds don't cause problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:22:47.473", "Id": "504619", "Score": "1", "body": "Thanks! +1 Only one concern, I dont like to have all objects and deps in the top level build folder. Any good advice for that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T21:23:39.417", "Id": "504625", "Score": "1", "body": "I don't see why not - it's the way Make is designed to work. It's nice to have all the products in one place - then you can clean just by deleting the build directory. If you want to work against Make, then that's your choice of course. But I find it easier to let the built-in rules carry the load, and have a makefile that follows convention so that anyone else can follow it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T21:04:25.017", "Id": "255668", "ParentId": "255664", "Score": "1" } } ]
{ "AcceptedAnswerId": "255668", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T19:53:18.340", "Id": "255664", "Score": "1", "Tags": [ "makefile" ], "Title": "Makefile for multiple executables" }
255664
<p>This code integrates with <a href="https://dweet.io" rel="nofollow noreferrer">dweet</a> and <a href="https://freeboard.io" rel="nofollow noreferrer">freeboard</a> to produce a dashboard display of which occupants of a house are probably at home, based on the presence or absence of their phones' MAC addresses on the local network.</p> <p>An important distinction to meke is between <em>current</em> and <em>marked</em> presence. For instance, with a 15 minute grace period set through the config file, users marked as <em>currently</em> present at any time within the past 15 minutes will be <em>marked</em> present, even if they're not <em>currently</em> present right now. In other words, <em>current</em> presence is known for certain at the time that a line of code is run, whereas <em>marked</em> presence is 'probably accurate' and takes into account a longer period of time.</p> <p>The program also reads a config file in YAML format, stored by default at <code>/etc/homepresenced/homepresenced.yaml</code>. An example config file is shown below.</p> <pre><code>from time import sleep import subprocess import datetime import yaml import dweepy CONFIG_FILE_PATH = '/etc/homepresenced/homepresenced.yaml' class Occupant: def __init__(self, name, mac): self.name = name self.mac = mac self.lastPresent = None def registerPresence(self): self.lastPresent = datetime.datetime.now() with open(CONFIG_FILE_PATH) as f: # load configuration into conf dictionary conf = yaml.safe_load(f) # replace yaml-style occupant listings with instances of Occupant object for i, occupant in enumerate(conf['occupants']): conf['occupants'][i] = Occupant(occupant['name'], occupant['mac']) try: while True: occupancy_report = {} # data sent to dweepy about occupant presence # perform network scan. this takes time so it's more efficient to do it once per loop, rather than once per occupant per loop arp_scan = str(subprocess.check_output(&quot;sudo arp-scan -l&quot;, shell=True)) for occupant in conf['occupants']: if occupant.mac in arp_scan: occupant.registerPresence() # register occupant as CURRENTLY present if mac is in scan # should the occupant be MARKED as present (taking into account the 'grace period')? presence = datetime.datetime.now() - occupant.lastPresent &lt; datetime.timedelta(minutes=conf['presence_grace_period']) if occupant.lastPresent else None # format time of last CURRENT presence. if not set (==None) then use &quot;never&quot; lastPresent = occupant.lastPresent.strftime(conf['time_format']) if occupant.lastPresent else &quot;never&quot; print(f&quot;Occupant {occupant.name}'s device is {'PRESENT' if presence else 'ABSENT' if presence == False else 'UNSEEN'} (last present: {lastPresent})&quot;) # add to dictionary that will be sent to dweepy occupancy_report[occupant.name] = { 'presence': presence, 'lastPresent': lastPresent } dweepy.dweet_for(conf['dweet_thing'], occupancy_report) # catch keyboard ctrl+c interrupt signals and exit cleanly except KeyboardInterrupt: exit() </code></pre> <pre><code>presence_grace_period: 15 dweet_thing: identifier_for_dweet_io time_format: &quot;%Y/%m/%d at %HL%M:%S&quot; occupants: - name: User One mac: 11:aa:11:aa:11:aa - name: User Two mac: 22:bb:22:bb:22:bb - name: User Three mac: 33:cc:33:cc:33:9cc </code></pre>
[]
[ { "body": "<h2><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a></h2>\n<p>Use 4-space indents. You are using 8-space indents.</p>\n<p>Use snake case (<code>register_presence</code>, not <code>registerPresence</code>) for methods.</p>\n<p>Reduce the number of blank lines, and only use one at a time. This has too much blank space.</p>\n<p>Add <code>if __name__ == '__main__':</code> (this isn't PEP 8 but it's very common)</p>\n<h2>Other Style</h2>\n<p>Put the config file read and keyboard interrupt there in <code>if __name__</code>. Put all the other logic into a <code>main_loop</code> function (not a general rule, just something I'd recommend here).</p>\n<p>Define what &quot;current&quot; and &quot;marked&quot; are in comments in the code. If you need to explain it here, you need to explain it in the code.</p>\n<p>I'd recommend making a variable called <code>occupants</code>. Modifying <code>conf['occupants']</code> is a little dubious, and it's also shorter.</p>\n<p>Consider separating out checking whether the occupant is present, and acting on any changes. But for something this small, I think it's fine as-is.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T06:39:07.050", "Id": "267617", "ParentId": "255667", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T20:46:17.207", "Id": "255667", "Score": "2", "Tags": [ "python", "networking", "yaml" ], "Title": "MAC address-based presence detection" }
255667
<p>I am just getting a little more comfortable with Bash.</p> <p>I wanted a super simple log function to write to a file and output to the console for messages and errors. I also wanted the terminal and the file to interpret newline characters rather than printing them out. Here is what I came up with (it works fine):</p> <pre><code>#!/bin/bash log () { if [[ &quot;$3&quot; == '-e' || &quot;$3&quot; == '--error' ]]; then &gt;&amp;2 echo -e &quot;ERROR: $1&quot; &amp;&amp; printf &quot;ERROR: $1\n&quot; &gt;&gt; &quot;$2&quot; else echo -e &quot;$1&quot; &amp;&amp; printf &quot;$1\n&quot; &gt;&gt; &quot;$2&quot; fi } # Example implementation log_file=snip/init.log msg=&quot;\nthis is an error message with leading newline character&quot; log &quot;$msg&quot; $log_file -e msg=&quot;this is success message with no newline characters&quot; log &quot;$msg&quot; $log_file </code></pre> <p>I don't need any more functionality however I have some questions:</p> <ol> <li>Is an efficient and readable piece of code that won't break when passed strings with special characters?</li> <li>Syntactically, could I have done this 'better' such as using pipes instead of <code>&amp;&amp;</code>. <code>tee</code> instead of <code>printf</code> etc.?</li> <li>How can I refactor this code to allow for the optional <code>-e</code> flag to be passed in first?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T21:59:00.180", "Id": "504520", "Score": "1", "body": "Just as a small note, I'd switch the arguments around to `log [OPTIONS] LOG_FILE MESSAGE...\". So when called it would look like this `log \"$log_file\" \"Part1\" \"Part 2\" \"and so on\"` or `log --error \"$log_file\" \"Part1\" \"Part 2\" \"and so on\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T22:48:52.033", "Id": "504521", "Score": "0", "body": "@Bobby yeah I should swap the FILE and MSG arguments around. I do not know how to allow for the optional -e flag to be the first argument though since it may or may not be passed into the log function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T22:57:34.500", "Id": "504522", "Score": "2", "body": "You could easily pass `-e` first, using `if` and `shift`. But it might be better to have two different functions, and that's what I propose in my answer." } ]
[ { "body": "<p>There's quite a bit of repetition:</p>\n<ul>\n<li><code>echo &amp;&amp; print</code> with roughly the same arguments - <code>tee</code> is probably better here</li>\n<li>error and non-error paths - perhaps use one function to prepend the <code>ERROR:</code> tag and call the other?</li>\n</ul>\n<p>It might be best to have the filename first, then any number of message words? That would make the interface more like <code>echo</code>, for example.</p>\n<p>There's also a problem with our use of <code>printf</code> - any <code>%</code> characters in the error message will be interpreted as replacement indicators. Not what we want. We could use <code>printf %b</code> to expand escape sequences instead:</p>\n<pre><code># log FILE MESSAGE...\nlog () {\n local file=&quot;$1&quot;; shift\n printf '%b ' &quot;$@&quot; '\\n' | tee -a &quot;$file&quot;\n}\n\n# log_err FILE MESSAGE...\nlog_error () {\n local file=&quot;$1&quot;; shift\n local message=&quot;ERROR: $1&quot;; shift\n log &quot;$file&quot; &quot;$message&quot; &quot;$@&quot; &gt;&amp;2\n}\n</code></pre>\n<p>If we do want to have a single function with arguments (e.g. to add more options), then we might want to use the <code>while</code>/<code>case</code> approach of option parsing that's often used at the program level:</p>\n<pre><code>#!/bin/bash\n\nset -eu\n\n# log [-e] [-f FILE] MESSAGE...\nlog() {\n local prefix=&quot;&quot;\n local stream=1\n local files=()\n # handle options\n while ! ${1+false}\n do case &quot;$1&quot; in\n -e|--error) prefix=&quot;ERROR:&quot;; stream=2 ;;\n -f|--file) shift; files+=(&quot;${1-}&quot;) ;;\n --) shift; break ;; # end of arguments\n -*) log -e &quot;log: invalid option '$1'&quot;; return 1;;\n *) break ;; # start of message\n esac\n shift\n done\n if ${1+false}\n then log -e &quot;log: no message!&quot;; return 1;\n fi\n # if we have a prefix, update our argument list\n if [ &quot;$prefix&quot; ]\n then set -- &quot;$prefix&quot; &quot;$@&quot;\n fi\n # now perform the action\n printf '%b ' &quot;$@&quot; '\\n' | tee -a &quot;${files[@]}&quot; &gt;&amp;$stream\n}\n</code></pre>\n<p>There's a non-obvious trick in there that might need explanation: I've used <code>${1+false}</code> to expand to <code>false</code> when there's at least one argument remaining, or to an empty command when there are no arguments (empty command is considered &quot;true&quot; by <code>if</code> and <code>while</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T23:52:15.377", "Id": "504531", "Score": "0", "body": "I think I need to keep this code in one single function though since I will have another log function for logging to only a file (no console), I call that function `log_silent`. The thing is I dont really want 4 functions to get this job done. I would like to do this with just two functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:48:07.377", "Id": "504577", "Score": "1", "body": "Yes, `local` and `tee -a` and the newline are all good improvements (I should have tried the code before publishing!). Edited." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:48:40.693", "Id": "504578", "Score": "1", "body": "I've updated to show how you can parse options in a single function. It should be easy to add a \"silent\" option that sets `stream=/dev/null`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T22:56:24.893", "Id": "255672", "ParentId": "255669", "Score": "5" } } ]
{ "AcceptedAnswerId": "255672", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T21:28:58.310", "Id": "255669", "Score": "5", "Tags": [ "bash" ], "Title": "Simple log function in Bash" }
255669
<p>While experimenting with some of C++'s language features, I was able to successfully design an invokable nameless function call through the use of a lambda that generically creates an arbitrary class wrapper that returns a class object without having to have a direct implementation of that class within its own seperate translation unit. The wrapper class itself is still contained within a translation unit, as it is declared and defined within the scope of the lambda. This lambda then returns that type through the use of template type deduction.</p> <p>In my case, I have created a Wrapper class around a type <code>T</code> object in that it stores a pointer to that object and its constructor and destructor respectively calls new and delete on that pointer. The members are private and only accessible via the class's public interface, and they are declared as <code>const</code> non-modifiable meaning that the use of calling these methods will not change the state of the class object that is generated. To better illustrate this, here is what my source code looks like:</p> <p><strong>some.h</strong></p> <pre><code>#include &lt;string&gt; #include &lt;string_view&gt; template&lt;typename T&gt; auto create_dynamic_wrapper = [&amp;](const std::string_view name, T value) { class DynamicWrapper { public: DynamicWrapper() = default; DynamicWrapper(const std::string_view name_in, T value) : name_{ name_in } { this-&gt;pData_ = new T{ value }; } ~DynamicWrapper() { if (nullptr != this-&gt;pData_) { delete this-&gt;pData_; this-&gt;pData_ = nullptr; } } // define copy constructor and assignment operator here // wrt how you want this wrapper class to behave in order // to preserve the rule of 3 or 5. Meaning, do you want // to allow this class object to be copyable or not... auto value() const { return *(this-&gt;pData_); } auto ptr() const { return this-&gt;pData_; } auto name() const { return this-&gt;name_; } private: T* pData_ = nullptr; const std::string name_; }; return DynamicWrapper(name, value); }; </code></pre> <p>The driving program</p> <p><strong>main</strong></p> <pre><code>#include &lt;iostream&gt; #include &quot;some.h&quot; int main() { auto C = create_dynamic_wrapper&lt;int&gt;(&quot;Foo&quot;, 7); std::cout &lt;&lt; C.name() &lt;&lt; '\n'; std::cout &lt;&lt; C.ptr() &lt;&lt; '\n'; std::cout &lt;&lt; C.value() &lt;&lt; '\n'; std::cout &lt;&lt; typeid(C).name() &lt;&lt; '\n'; return 0; } </code></pre> <p>When I run this on my machine I get the following output:</p> <p><strong>Output</strong></p> <pre><code>Foo 00000000006857F0 7 class `public: __cdecl &lt;lambda_986b701ab3be1e8cd3d0d2d875c96c7d&gt;::operator()(class std::basic_string_view&lt;char,struct st d::char_traits&lt;char&gt; &gt;,int)const __ptr64'::`2'::DynamicWrapper </code></pre> <p>The second line will vary as this is using dynamic heap memory allocation. The fourth line will vary depending on the compiler, os, and other factors due to naming conventions, name mangling, symbol generation, etc...</p> <p>Now onto my questions and concerns...</p> <hr> <ul> <li>I don't know if this type of code structure/generation has a specific idiomatic name. If so, what would this Idiom be called?</li> <li>Is this considered a Well-Defined Program?</li> <li>What are the implications of using this kind of structure: <ul> <li>Will this invoke any kind of UB?</li> <li>Does this have the potential to introduce memory leaks, invalid or dangling pointers, or references?</li> <li>Would this be considered thread and exception-safe?</li> </ul> </li> <li>Explain to me what you believe are the pros and cons of using this kind of code generation?</li> <li>Without having to use <code>smart-pointers</code> is there anything else that I would need to be aware of when it comes to the use of dynamic memory while using new and delete within a self-contained object defined within this context?</li> <li>What are the side effects of using this kind of structure?</li> <li>What can I or do I need to do to improve this code snippet to make it a well-defined codebase that doesn't introduce any potential UB?</li> <li>What would be the potential exploits of using this type of implementation?</li> <li>If all of the necessary precautions are taken to eliminate any code smells... would this kind of code structure be a useful tool in any kind of production code?</li> </ul> <hr> <p><em>-Note to the Reader-</em></p> <p>There is something to be said about this code structure that I find interesting. The lambda itself internally and locally declares and defines a class object named <code>DynamicWrapper&lt;T&gt;</code> where this class is defined and declared within the scope of this lambda and through the use of <code>auto type deduction</code> it returns an instantiated class instance of that type.</p> <p>Then within some translation unit that calls and invokes this lambda and through the use of the <code>auto</code> specifier, the named object that is returned into the user's declared <code>auto variable</code> is in fact a <code>DynamicWrapper&lt;T&gt;</code> instance even though no such class declaration or definition exists outside of that invoked lambda. I find this to have a very interesting set of properties and behavior in regards to its overall design pattern and implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T12:35:25.517", "Id": "504580", "Score": "3", "body": "One thing missing from this review - what do you use it *for*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:32:43.860", "Id": "504595", "Score": "0", "body": "To Close-vote reviewers - this turns out to be hypothetical/example code, not finished real code ready for review - see the comments to [my answer](/a/255687/75307)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:48:53.497", "Id": "504598", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:21:56.380", "Id": "504603", "Score": "0", "body": "Given that you would always have a `value`, what is the justification for `pData` to be a pointer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:31:50.100", "Id": "504604", "Score": "0", "body": "@screwnut... It's hard to put in exact words... I'm not exactly interested in the details of the \"wrapper class itself\". It's the outer construct, the design pattern of using Lambda's to generically generate classes where they are only declared and defined within the Lambda's implementation body... if that makes more sense... I was only using a vague \"wrapper class\" to illustrate the use of the outer lambda that is generating that class, and the fact that the `auto` variable within some other translation unit is an instantiation of that contained class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:34:34.550", "Id": "504605", "Score": "0", "body": "@screwnut There are different Idioms in C++ in which I have used such as SFINAE, CRTP, Factory, Polymorphism, etc... I don't know if this kind of design pattern has an \"idiomatic name\", if it doesn't I don't know it otherwise I would use that within the question itself..." } ]
[ { "body": "<blockquote>\n<p>I don't know if this type of code structure/generation has a specific idiomatic name. If so, what would this Idiom be called?</p>\n</blockquote>\n<p>Not sure myself.</p>\n<blockquote>\n<p>Is this considered a Well-Defined Program?</p>\n</blockquote>\n<p>Looks good to me.</p>\n<blockquote>\n<p>What are the implications of using this kind of structure:</p>\n<ul>\n<li>Will this invoke any kind of UB?</li>\n</ul>\n</blockquote>\n<p>Looks well formed.</p>\n<blockquote>\n<ul>\n<li>Does this have the potential to introduce memory leaks, invalid or dangling pointers, or references?</li>\n</ul>\n</blockquote>\n<p>In the general case no.<br />\nIn this specific case: You did not implement the rule of three/five and you are managing a dynamically created resource inside the class. So there is definitely the possibility for resource mishandling.</p>\n<blockquote>\n<p>Would this be considered thread and exception-safe?</p>\n</blockquote>\n<p>Nothing is thread safe unless you explicitly make it so (apart from the things that are specifically designed for threading: <code>atomic</code>, <code>mutex</code>, <code>condition_variable</code> etc...).</p>\n<p>Exception safe. Yes as long as the rule of three issue is solved.</p>\n<blockquote>\n<p>Explain to me what you believe are the pros and cons of using this kind of code generation?</p>\n</blockquote>\n<p>Not sure you need a lambda to do this:<br />\nThe standard pattern is to use a <code>make_X</code> function. See: <code>make_pair()</code>.</p>\n<pre><code>template&lt;typename T&gt;\nclass DynamicWrapper {\npublic:\n DynamicWrapper() = default;\n\n DynamicWrapper(const std::string_view name_in, T value) : name_{ name_in } {\n this-&gt;pData_ = new T{ value };\n }\n\n ~DynamicWrapper() {\n if (nullptr != this-&gt;pData_) {\n delete this-&gt;pData_;\n this-&gt;pData_ = nullptr;\n }\n }\n\n auto value() const { return *(this-&gt;pData_); }\n auto ptr() const { return this-&gt;pData_; }\n auto name() const { return this-&gt;name_; }\nprivate:\n T* pData_ = nullptr;\n const std::string name_;\n};\n\ntemplate&lt;typename T&gt;\nDynamicWrapper&lt;T&gt; make_DynamicWrapper(std::string_view name_in, T&amp;&amp; value)\n{\n return DynamicWrapper&lt;T&gt;(std::move(name_in), std::forward&lt;T&gt;(value));\n}\n\nint main()\n{\n auto C = make_DynamicWrapper(&quot;Foo&quot;, 7);\n}\n</code></pre>\n<blockquote>\n<p>Without having to use smart-pointers is there anything else that I would need to be aware of when it comes to the use of dynamic memory while using new and delete within a self-contained object defined within this context?</p>\n</blockquote>\n<p>Obey the rule of three/five.</p>\n<blockquote>\n<p>What are the side effects of using this kind of structure?</p>\n</blockquote>\n<p>Nothing really.</p>\n<blockquote>\n<p>What can I or do I need to do to improve this code snippet to make it a well-defined codebase that doesn't introduce any potential UB?</p>\n</blockquote>\n<p>Looks good.</p>\n<blockquote>\n<p>What would be the potential exploits of using this type of implementation?</p>\n</blockquote>\n<p>Not sure what that means.</p>\n<blockquote>\n<p>If all of the necessary precautions are taken to eliminate any code smells...</p>\n</blockquote>\n<p>No smells.</p>\n<blockquote>\n<p>would this kind of code structure be a useful tool in any kind of production code?</p>\n</blockquote>\n<p>Sure is.</p>\n<hr />\n<p>A thing to note is that lambda expressions are just short hand notation for writing functors. So we could rewrite your lambda as follows (which shows what is effectively happening in the compiler).</p>\n<pre><code>template&lt;typename T&gt;\nstruct Lambda_986b701ab3be1e8cd3d0d2d875c96c7d\n{\n class DynamicWrapper {\n public:\n DynamicWrapper() = default;\n\n DynamicWrapper(const std::string_view name_in, T value) : name_{ name_in } {\n this-&gt;pData_ = new T{ value };\n }\n\n ~DynamicWrapper() {\n if (nullptr != this-&gt;pData_) {\n delete this-&gt;pData_;\n this-&gt;pData_ = nullptr;\n }\n }\n\n // define copy constructor and assignment operator here\n // wrt how you want this wrapper class to behave in order\n // to preserve the rule of 3 or 5. Meaning, do you want\n // to allow this class object to be copyable or not... \n\n auto value() const { return *(this-&gt;pData_); }\n auto ptr() const { return this-&gt;pData_; }\n auto name() const { return this-&gt;name_; }\n private:\n T* pData_ = nullptr;\n const std::string name_;\n };\n\n DynamicWrapper operator()(const std::string_view name, T value) const\n {\n return DynamicWrapper(name, value);\n }\n};\n\nint main()\n{\n auto c = Lambda_986b701ab3be1e8cd3d0d2d875c96c7d&lt;int&gt;{}(&quot;Fun&quot;, 7);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T02:55:48.483", "Id": "504547", "Score": "0", "body": "About the rule of 3 or 5... I did not include the `copy constructor` nor the `assignment operator` in that they should be \"self-explanatory\" or well understood and thought feel that they are in a sense irrelevant to the actual implementation of its design. Other than that, you're answer is very straightforward, concise, and to the point!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T03:00:23.897", "Id": "504548", "Score": "0", "body": "Now, since the above class generation handles its memory allocation internally, and the fact that it can not be modified from outside of its class, would it be safe to say that the default copy constructor and assignment operator would be viable within this context? I haven't decided if the generated wrapper object itself should be copyable or not... that's another reason for their direct omission. I guess I could have commented them out with a description explaining their omissions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T03:02:29.150", "Id": "504549", "Score": "0", "body": "I also know that I could have done this with a `class template` and a `function`. However, I combined the two into a single lambda expression just to explore some of the features and properties of lambdas within modern C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T03:10:23.907", "Id": "504550", "Score": "0", "body": "I added a comment to the class in regards to its copy constructor and assignment operator to reflect your statement about the rule of 3 or 5 so that future readers of this Q/A can see the reasoning for their explicit omission. The idea of leaving the comments is to state that they should be defined there, but that they are implementation-defined as to the designer's intended use of this class, making the class either copyable or non-copyable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T21:15:37.847", "Id": "504624", "Score": "0", "body": "“make” functions are kinda going the way of the dodo as of C++17; `make_pair()` is already obsolete. I’d say forget the lambda *and* the make function, and just use template parameter deduction (with an appropriate deduction guide if necessary): `auto c = DynamicWrapper{\"foo\", 7};`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T20:44:34.807", "Id": "504693", "Score": "0", "body": "@indi Can't really argue with that." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T02:41:48.387", "Id": "255677", "ParentId": "255676", "Score": "2" } }, { "body": "<p>Firstly, it's not clear at all what this is for, that's any different to <code>std::pair&lt;T, std::string&gt;</code>. What's the motivation?</p>\n<hr />\n<p>This won't work in C++20:</p>\n<pre class=\"lang-none prettyprint-override\"><code>255676.cpp:5:32: error: non-local lambda expression cannot have a capture-default\n 5 | auto create_dynamic_wrapper = [&amp;](const std::string_view name, T value) {\n | ^\n</code></pre>\n<p>We don't seem to need a default capture, so we could just use <code>[]</code> instead - but why not just write a function?</p>\n<p>Actually, I've just checked and it's not legal in C++17 either, so the code is invalid as presented.</p>\n<hr />\n<blockquote>\n<pre><code> DynamicWrapper() = default;\n</code></pre>\n</blockquote>\n<p>What's this default constructor for? We never use it.</p>\n<hr />\n<blockquote>\n<pre><code> DynamicWrapper(const std::string_view name_in, T value) : name_{ name_in } {\n this-&gt;pData_ = new T{ value };\n }\n</code></pre>\n</blockquote>\n<p>Why are you assigning to <code>pData</code> rather than simply initialising it as you do <code>name</code>? Also, making <code>name_in</code> a const parameter forces us to copy it into <code>name</code>, rather than being able to move it. I'd write:</p>\n<pre><code> DynamicWrapper(std::string name, T value)\n : pData_{new T{std::move(value)}},\n name_{std::move(name)}\n {\n }\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> ~DynamicWrapper() {\n if (nullptr != this-&gt;pData_) {\n delete this-&gt;pData_;\n this-&gt;pData_ = nullptr;\n }\n }\n</code></pre>\n</blockquote>\n<p>There's a lot of clutter here. First, we can ditch all the <code>this-&gt;</code> rubbish that only serves to make the code less readable. Why are we comparing against a null pointer? If <code>pData_</code> is null, then there's no need for the test because the <code>delete</code> will do nothing anyway. And that's a dead assignment to <code>pData_</code>, because the object is going out of scope. That can all be replaced with a much simpler destructor:</p>\n<pre><code> ~DynamicWrapper() {\n delete pData_;\n }\n</code></pre>\n<p>However, I think we should reconsider the type of <code>pData_</code>. As <code>g++ -Weffc++</code> warns us, we have a pointer data member but no copy-constructor and no copy-assignment operator, making this a dangerous class to use.</p>\n<p>If we replace <code>pData_</code> with a smart pointer, then the compiler-generated (or compiler-deleted) constructor, destructor and assignment will just do the Right Thing (that's the Rule of Zero).</p>\n<p>Here's a simpler version of the same thing:</p>\n<pre><code>#include &lt;memory&gt;\n#include &lt;string&gt;\n\ntemplate&lt;typename T&gt;\nauto create_dynamic_wrapper(std::string name, T value)\n{\n class DynamicWrapper {\n public:\n DynamicWrapper(std::string name, T value)\n : value_{new T{std::move(value)}},\n name_{std::move(name)}\n {\n }\n\n auto value() const { return *value_; }\n auto const&amp; ptr() const { return value_; }\n auto name() const { return name_; }\n private:\n const std::shared_ptr&lt;T&gt; value_;\n const std::string name_;\n };\n return DynamicWrapper(std::move(name), std::move(value));\n}\n</code></pre>\n<p>I still don't see the point, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:48:59.250", "Id": "504586", "Score": "0", "body": "I know I could have just written a function. That wasn't the point of my code design. It was the fact that I was able to create a class that exists only in the scope of a lambda via its declaration and definition. Then when the lambda is invoked in some translation unit, the contained class type is still instantiated and returned via auto. It's more about the `pattern` and its behavior. I explicitly stated I wasn't concerned with `smart_pointers` as I was working internally and directly with `new` and `delete`. I tagged C++17, not C++20. I was only using a wrapper object as an illustration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:52:25.580", "Id": "504587", "Score": "0", "body": "In Psudeo Code and Simply put: `auto obj = [](params...){ class Obj { pubic: members; } Obj o(params...); return o;};` then `obj` is of type `Obj`... This is the pattern that I am concerned with. Not how to take this and make a function out of it! It's the idea to be able to use a lambda to create an instance of a class externally from a class that it declares and defines internally. The only place that the class exists is within that lambda obj... and not within the file's global namespace... at least until you invoke the lambda." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:56:51.183", "Id": "504588", "Score": "1", "body": "Yes, I saw the C++17 tag, and initially thought I was warning about something you'd done that was incompatible with C++20. Then I found it's already broken in C++17. I still don't see why you find a named lambda better than an ordinary function - what's the advantage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:57:24.130", "Id": "504589", "Score": "0", "body": "I'm using Visual Studio 2017 and it worked for me without any issues" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:57:37.870", "Id": "504590", "Score": "0", "body": "\"*I was only using a wrapper object as an illustration*\" makes it sound like this isn't [**actual code from a real project**](https://codereview.stackexchange.com/help/on-topic). Can you tell us what you're using this for? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:59:06.857", "Id": "504591", "Score": "0", "body": "I'm working on a bigger project where I might be auto-generating a bunch of classes that all share a similar pattern. I was thinking of using templated lambdas to achieve this... So I wanted to know more about the design pattern itself. The `wrapper` class was just a special use case to illustrate the point of the design and use of invoking the lambda to create a class instance through auto type deduction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:02:03.597", "Id": "504592", "Score": "0", "body": "I know you \"*explicitly stated I wasn't concerned with smart_pointers*\", but IMO you should be - that's an important tool to creating maintainable code. Otherwise you'd shoot yourself in the foot the first time you passed one of these objects by value. If you're not interested in critique of all aspects of your code, then Code Review is probably the wrong place to be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:04:43.577", "Id": "504593", "Score": "0", "body": "I know all about using smart pointers. My focus wasn't on them... I was doing it the old fashion C way, just to make the code easier to read, just to illustrate that the class was using dynamic memory instead of local stack memory, nothing more. Within my real codebase, of course, I'd be using smart pointers, except in specific special cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:31:07.223", "Id": "504594", "Score": "0", "body": "You know about smart pointers *and still chose not to use one*? Are you sure that this is your **real, finished code**? Now you're talking about your \"*real codebase*\" I'm convinced that I've wasted my valuable time on an off-topic question that's hypothetical/example code. Please don't do that to us again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T15:44:05.627", "Id": "504597", "Score": "0", "body": "I made an edit to the bottom of the question in how I would be using this design pattern within my code. That's what I'm focusing on. My codebase is quite large and I'm working with a lot of components and I'm using Vulkan as my rendering API. I want to know about the `design pattern` itself. The idea of using `lambdas` to create class instances where those lambdas generates (declares & defines) the classes..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:06:02.153", "Id": "504600", "Score": "1", "body": "@FrancisCugler Visual Studio does not always follow the standards. If you want the code to port to non-windows systems you need to stick to the standards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:14:00.927", "Id": "504601", "Score": "0", "body": "@pacmaninbw I'm not targeting any platform specifically, but more than likely it will be used on a Window's machine as that will probably be the primary target audience." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T13:11:56.693", "Id": "255687", "ParentId": "255676", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T01:51:59.713", "Id": "255676", "Score": "-1", "Tags": [ "c++", "c++17", "template", "lambda", "wrapper" ], "Title": "Using a lambda to generically create an arbitrary class wrapper around some object of type T" }
255676
<p>In my job, we often write functions that do some calculation and write the result to a database. Sometimes mistakes are made and wrong stuff ends up being saved, therefore we also want to supply an interface to clean up after the function. This is an attempt of solving that problem.</p> <pre><code>from functools import wraps def revert(func): if not hasattr(func,'_revert'): raise NotImplementedError(func.__name__ + &quot; does not have a revert registered&quot;) @wraps(func._revert) def wrapper(*args,**kwargs): return func._revert(*args,**kwargs) return wrapper def register_revert(revert): def revert_added(func): func._revert = revert @wraps(func) def wrapper(*args,**kwargs): return func(*args,**kwargs) return wrapper return revert_added def _is_it_a_str(maybe_str): if not isinstance(maybe_str,str): raise ValueError(&quot;I need a string&quot;) def _revert_stuff(a_str): _is_it_a_str(a_str) print('revert stuff with ' + a_str) @register_revert(_revert_stuff) def do_stuff(a_str): _is_it_a_str(a_str) print('doing stuff with ' + a_str) do_stuff('something') # Oops: revert(do_stuff)('something') </code></pre> <p>The idea is to write your function doing your job - do_something in this case. And then when you are ready to take it to the next level, you write its revert, register it and you are done.</p> <p>I like that</p> <ul> <li>the solution does not require changing anything in the main functionality.</li> <li>you can use the same identical interface for many functions</li> <li>the syntax reads relatively intuitively</li> </ul> <p>I think it is inconvenient that</p> <ul> <li>I need to maintain two identical interfaces - the one on do_stuff and _revert_stuff needs to be identical (or at least _revert_stuff needs to work getting the one from do_stuff).</li> <li>sometimes I want to type-check the arguments which I then also have to repeat (exemplified here with _is_it_a_str). I thought about moving that to another decorator, but I'm afraid it gets too confusing.</li> </ul> <p>Edit: We use the newest stable version of Python</p> <p>p.s. My first question tried my best. Critique welcome!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T09:51:41.753", "Id": "504566", "Score": "1", "body": "python 3.x or 2.x? more specific version would also be helpful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T10:48:11.077", "Id": "504567", "Score": "1", "body": "Why are you doing something and then reverting it. In your example, you could do the type check or string validation before you run `do_stuff` by decorating the `do_stuff` function and checking its inputs, for example with pydantic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T11:25:01.260", "Id": "504571", "Score": "0", "body": "@Tweakimp The function gets called in error and now we need to clean up. Type checking: Yea I guess another decorator is the correct solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T12:45:30.910", "Id": "504581", "Score": "1", "body": "I'd like to hear more about how you would use this. I'm thinking of data manipulation, where functions may or may not be combined. In that scenario, you would have to revert all the changes you made, in reverse order, up to the change you want reverted. Then you could re-apply the non-reverted ones. It still leaves open the possibility of non-reversible operations (modulus, regexp), and so you would need a way to mark those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T12:52:14.637", "Id": "504583", "Score": "0", "body": "@aghast, How the reversion is done is left to the function registered, right? But yea, those are valid issues. Sometimes the ordering matters but that is somewhat logical if it mattered when calling the functions in the first place. Some stuff isn't reversible sure, but the solution definitely does not claim to be able to revert anything. You just don't register a revert.\n\nThe specific use case is a lot of functions that do a calculation and saves the result to a database - i updated the description slightly." } ]
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code>def revert(func):\n @wraps(func._revert)\n def wrapper(*args,**kwargs):\n return func._revert(*args,**kwargs)\n return wrapper\n</code></pre>\n<p>You are returning a wrapper, which takes arguments, calls a function, and returns results...</p>\n<p>I'm pretty sure that is just a long way of writing:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def revert(func):\n return func._revert\n</code></pre>\n<p>This begs the question: why store the revert function as <code>func._revert</code>, when you could store it as <code>func.revert</code>? Then instead of:</p>\n<pre><code>revert(do_stuff)('something')\n</code></pre>\n<p>you could write:</p>\n<pre><code>do_stuff.revert('something')\n</code></pre>\n<p>which is one character shorter. Even better: autocomplete can tell you whether there is a <code>.revert</code> member for <code>do_stuff</code>, which is not possible using <code>revert(...)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T06:19:47.293", "Id": "255787", "ParentId": "255682", "Score": "3" } }, { "body": "<p>I don't have any complaints about your code itself, so I'll bring up an alternate approach. You mentioned being annoyed at having to duplicate things like typechecking, and I also notice that it's possible to call <code>revert(do_stuff)(&quot;b&quot;)</code> without having ever called <code>do_stuff(&quot;b&quot;)</code> in the first place. Maybe that's desirable, but I feel like it probably isn't.</p>\n<p>One way to tackle both those things would be to bind the function's arguments to some undo object, and only make the revert function accessible that way. This way, an undo is guaranteed to undo an action that has been done, with the same arguments (meaning they shouldn't need to be typechecked a second time).</p>\n<p>Now, this has some disadvantages but it might be worth considering an approach like</p>\n<pre><code>class UndoableAction:\n def __init__(self, revert_func, args, kwargs):\n self._revert_func = revert_stuff\n self._args = args\n self._kwargs = kwargs\n self._has_been_undone = False\n\n def undo(self):\n if self._has_been_undone:\n raise RuntimeError(&quot;Could not undo: Action has already been undone&quot;)\n else:\n result = self._revert_func(*(self._args), **(self._kwargs))\n self._has_been_undone = True\n return result\n\n\ndef register_revert(revert_func):\n def bind(original_func):\n def bound_func(*args, **kwargs):\n result = original_func(*args, **kwargs)\n\n return (result, UndoableAction(revert_func, args, kwargs))\n\n return bound_func\n \n return bind\n\n\ndef _revert_stuff(a_str):\n # Since this should only be called as some_action.undo()\n # we can assume do_stuff() has already typechecked the argument\n # So we don't do it ourselves\n print('revert stuff with ' + a_str)\n\n\n@register_revert(revert_stuff)\ndef do_stuff(a_str):\n if not isinstance(a_str, str):\n raise ValueError(&quot;I need a string&quot;)\n\n print('do stuff with ' + a_str)\n\n\n_, stuff = do_stuff('something')\n# Oh no!\nstuff.undo()\n</code></pre>\n<p>The syntax remains fairly intuitive, and the same interface still works for many functions. Duplication is down, and while the two functions still need to be kept in sync to a degree, the undo function doesn't end up exposing much of an interface at all. And there is also no need to worry about trying to undo an operation that hasn't actually been done. But of course, it <em>does</em> look different to callers of the main functionality. It also might make it harder to undo an action if the action was initially done in an entirely different part of the program. If you don't have the undo object, you can't easily do something like <code>revert(create_user)(database.get_a_username())</code> for example -- but that might not be a major issue, assuming the same code is generally responsible for doing a thing and undoing it (which it sounds like).</p>\n<p>It's a tradeoff. Might be worth thinking about, depending on your use case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T23:15:58.700", "Id": "504903", "Score": "2", "body": "Nice answer (+1). You might want to ensure `*args` and `**kwargs` are immutable, so they actually contain the same content during the `.undo()`. Ok, easier said than done. Maybe try `hash((*args, *kwargs.values()))`: if you get `TypeError: unhashable type: '...'`, then mutable arguments (lists, dictionaries, ...) are being passed to the undoable function. Of course, just because they are mutable doesn't mean they have mutated ..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T22:45:46.150", "Id": "255830", "ParentId": "255682", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T09:18:40.360", "Id": "255682", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Good interface for reverting effect of function" }
255682
<p>I've recently finished Chapter 8 of The Book and have started doing the exercises at the end of the chapter. This post pertains to the first exercise which involves writing a program to output the averages of a list of integers. I thought the instructions for this particular exercise was a bit vague, so I tried to make it simple by not including REPL functionality in my implementation. Anyway, here's my current solution:</p> <pre class="lang-rust prettyprint-override"><code> // Given a list of integers, use a vector and return the mean (the average // value), median (when sorted, the value in the middle position), and // mode (the value that occurs most often; a hash map will be helpful // here) of the list. use std::collections::HashMap; struct Averages { mean: f64, median: f64, mode: Vec&lt;i32&gt; } fn sum(vector: &amp;Vec&lt;i32&gt;) -&gt; Option&lt;i32&gt; { match vector.len() { 0 =&gt; None, _ =&gt; { let mut accumulator = 0; for element in vector { accumulator += element; } Some(accumulator) } } } fn mean(vector: &amp;Vec&lt;i32&gt;) -&gt; Option&lt;f64&gt; { match vector.len() { 0 =&gt; None, length =&gt; Some((sum(vector).unwrap() as f64) / (length as f64)) } } fn is_even(number: &amp;usize) -&gt; bool { number % 2 == 0 } fn median(vector_original: &amp;Vec&lt;i32&gt;) -&gt; Option&lt;f64&gt; { match vector_original.len() { 0 =&gt; None, length =&gt; { let mut vector_cloned = vector_original.to_vec(); vector_cloned.sort_unstable(); match is_even(&amp;length) { true =&gt; { let length_halved = length / 2; Some((( &amp;vector_cloned[length_halved - 1] + &amp;vector_cloned[length_halved]) as f64) / 2.0) }, false =&gt; Some(vector_cloned[(( (length as f64) / 2.0).floor() as usize)] as f64) } } } } fn mode(vector: &amp;Vec&lt;i32&gt;) -&gt; Option&lt;Vec&lt;i32&gt;&gt; { match vector.len() { 0 =&gt; None, _ =&gt; { let mut counts = HashMap::new(); for number in vector { let count = counts.entry(number).or_insert(1u32); *count += 1u32; } let mut max_count = 0; for count in counts.values() { if count &gt; &amp;max_count { max_count = *count; } } let mut modes: Vec&lt;i32&gt; = Vec::new(); for (number, count) in &amp;counts { if count == &amp;max_count { modes.push(**number); } } Some(modes) } } } fn get_averages(vector: &amp;Vec&lt;i32&gt;) -&gt; Option&lt;Averages&gt; { match vector.len() { 0 =&gt; None, _ =&gt; Some( Averages { mean: mean(vector).unwrap(), median: median(vector).unwrap(), mode: mode(vector).unwrap() } ) } } fn print_averages(vector: &amp;Vec&lt;i32&gt;) { match vector.len() { 0 =&gt; println!(&quot;Vector is empty.&quot;), _ =&gt; { let averages: Averages = get_averages(vector).unwrap(); println!( &quot;Mean: {} Median: {} Mode(s): {:?}&quot;, &amp;averages.mean, &amp;averages.median, &amp;averages.mode ); } } } fn main() { print_averages(&amp;(10..=20).collect()); print_averages(&amp;vec![5,5,5,4,3,2,1,1,1]); print_averages(&amp;vec![]); } </code></pre> <p>I wrote the current implementation like I did as I was trying to write it such that each of the functions are reusable independent of each other and in contexts possibly outside of this particular program (hence the arguably redundant calls to <code>len</code>). But now I'm wondering if using so many <code>unwrap</code>s like I did is the idiomatic way to handle the <code>Option</code>s or if there's a better way to have written this instead. I'm especially worried that my implementation might be brittle because I encountered a couple of panics when I was writing and testing it.</p> <p>I'm also unsure if I'm doing borrowing and moving, as well as referencing and dereferencing optimally, especially in the <code>mode</code> function; despite it working properly, I'm a little confused as to what's its actually doing with the data and references, so some explanation about it would be really welcome.</p> <p>Any other constructive criticisms in general are also welcome, so please nitpick to your hearts content!</p>
[]
[ { "body": "<p>Good job in separating what you did into self-contained functions. Some comments on design and style:</p>\n<ul>\n<li><p>First things first: always run Clippy! (<code>cargo clippy</code>) Its feedback is usually helpful. Here it notices a few problems:</p>\n<ul>\n<li><p>Whenever you have a function with <code>&amp;Vec&lt;T&gt;</code> as an argument, it should almost always be rewritten as taking a slice <code>&amp;[T]</code>. Think of a slice as a more general vector-like memory, so a function which accepts <code>&amp;[T]</code> is more general than one that accepts <code>&amp;Vec&lt;T&gt;</code>. This also has the side effect of changing your main function a bit:</p>\n<pre><code> fn main() {\n let v: Vec&lt;i32&gt; = (10..=20).collect();\n print_averages(&amp;v);\n print_averages(&amp;[5, 5, 5, 4, 3, 2, 1, 1, 1]);\n print_averages(&amp;[]);\n }\n</code></pre>\n</li>\n<li><p>In the line <code>((&amp;vector_cloned[length_halved - 1] + &amp;vector_cloned[length_halved])</code>, you can remove both ampersands.</p>\n</li>\n</ul>\n</li>\n<li><p>In your <code>sum</code> function, returning <code>0</code> for the sum of an empty list (so, <code>fn sum(vector: &amp;[i32]) -&gt; i32</code>) is cleaner and more standard. Also, there is a built-in for this function: <code>vector.iter().sum()</code></p>\n</li>\n<li><p>Your <code>mean</code> function is clear, the use of <code>match vector.len()</code> is clever (the alternative is <code>if vector.is_empty() {</code>, but then you still have to call <code>.len()</code> again in the else branch. So I like your design choice better.)</p>\n</li>\n<li><p>However in contrast, in <code>mode</code> and <code>print_averages</code>, here it is clearer to use <code>if vector.is_empty() {</code> since you aren't using the length in the logic.</p>\n</li>\n<li><p>Relatedly, in <code>median</code> when you use <code>match is_even(&amp;length)</code>, here I think it is clearer to use an if statement, since there is no value associated with one of the match branches that you need access to.</p>\n</li>\n<li><p>Also in <code>median</code> I think some of the logic can be clearer using intermediate variables instead of complex expressions. In particular:</p>\n<pre><code> let ele1 = vector_cloned[length_halved - 1];\n let ele2 = vector_cloned[length_halved];\n Some(((ele1 + ele2) as f64) / 2.0)\n</code></pre>\n</li>\n</ul>\n<p>To answer your specific questions:</p>\n<blockquote>\n<p>But now I'm wondering if using so many unwraps like I did is the idiomatic way to handle the Options or if there's a better way to have written this instead. I'm especially worried that my implementation might be brittle because I encountered a couple of panics when I was writing and testing it.</p>\n</blockquote>\n<p>Using <code>unwraps</code> here is actually pretty justified: you statically know that these vectors are nonempty so your <code>unwrap</code>s should never panic. You are right to be concerned though as normally <code>unwrap</code>s are best avoided. If you prefer you can do <code>.expect(&quot;unreachable&quot;)</code> to indicate what exactly went wrong.</p>\n<blockquote>\n<p>I'm also unsure if I'm doing borrowing and moving, as well as referencing and dereferencing optimally, especially in the mode function.</p>\n</blockquote>\n<p>Edited to add: some comments on the mode function:</p>\n<p>Some improvements to your use of references:</p>\n<ul>\n<li><p>You created a <code>HashMap&lt;&amp;i32, u32&gt;</code>; this leads to some weird dereferencing in the code. It would be better to create a <code>HashMap&lt;i32, u32&gt;</code>. You can make sure you are doing it correctly by using a type annotation: <code>let mut counts: HashMap&lt;i32, u32&gt; = HashMap::new();</code></p>\n</li>\n<li><p>For the first for loop, you can use <code>.and_modify</code> to simplify the logic: (note vector is a reference / slice):</p>\n</li>\n</ul>\n<pre><code> let mut counts: HashMap&lt;i32, u32&gt; = HashMap::new();\n\n for &amp;number in vector {\n counts.entry(number).and_modify(|count| *count += 1).or_insert(1u32);\n }\n</code></pre>\n<ul>\n<li>The second for loop can be avoided using <code>.max()</code> directly on iterators:</li>\n</ul>\n<p><code>let max_count: u32 = *counts.values().max().unwrap()</code></p>\n<ul>\n<li>Once you have a <code>HashMap&lt;i32, u32&gt;</code>, the third for loop becomes much nicer. You can avoid references completely by consuming the hashmap in the for loop:</li>\n</ul>\n<pre><code> for (number, count) in counts {\n if count == max_count {\n modes.push(number);\n }\n }\n</code></pre>\n<p>But the most common way is to iterate by reference, which would normally be written this way:</p>\n<pre><code> for (&amp;number, &amp;count) in &amp;counts {\n if count == max_count {\n modes.push(number);\n }\n }\n</code></pre>\n<p>Or equivalently if you prefer:</p>\n<pre><code> for (number, count) in &amp;counts {\n if *count == max_count {\n modes.push(*number);\n }\n }\n</code></pre>\n<ul>\n<li><p>You can also do the last loop with a filter instead of an explicit for loop, though when learning it's always good to write out for loops for practice.</p>\n</li>\n<li><p>Also for larger projects, ultimately the best way to do this would probably be to use a dedicated multiset collection, for instance the <code>multiset</code> crate. The mode body should be really pretty short, like <code>let counts: MultiSet&lt;i32&gt; = vector.collect(); counts.iter().max_by_key(...)</code>.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T02:17:14.020", "Id": "255706", "ParentId": "255689", "Score": "7" } }, { "body": "<p>Read <a href=\"https://codereview.stackexchange.com/a/255706/188857\">6005's answer</a> first — the most important issues are\ncovered there. Here are some additions:</p>\n<h1>Formatting</h1>\n<p><code>rustfmt</code> formats your code according to the official <a href=\"https://github.com/rust-lang/rfcs/tree/master/style-guide\" rel=\"noreferrer\">Rust Style\nGuide</a>, which most Rustaceans are familiar with, to ease\ncommunication.</p>\n<h1>Argument passing</h1>\n<p>As 6005 pointed out, make your parameters <code>&amp;[i32]</code> instead of\n<code>Vec&lt;i32&gt;</code>. See <a href=\"https://stackoverflow.com/q/40006219/9716597\">Why is it discouraged to accept a reference to a\n<code>String</code> (<code>&amp;String</code>), <code>Vec</code> (<code>&amp;Vec</code>), or <code>Box</code> (<code>&amp;Box</code>) as a function\nargument?</a></p>\n<p>There is an exception: for <code>median</code>, you clone the numbers and sort\nthe clone. If the caller has a disposable collection that will not\nbe used after calculating the median, this would be wasteful. I\nsuggest taking a <code>Vec</code> by value here:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn median(mut numbers: Vec&lt;i32&gt;) -&gt; Option&lt;f64&gt; {\n // ...\n numbers.sort_unstable();\n // ...\n}\n</code></pre>\n<p>For <code>Copy</code> types like <code>usize</code>, there is no need to take a reference.\nSimply pass the <code>usize</code> instead.</p>\n<h1><code>mean</code></h1>\n<p>Since your <code>sum</code> checks for empty collections already, you can use the\nresult rather than check again in <code>mean</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn mean(numbers: &amp;[i32]) -&gt; Option&lt;f64&gt; {\n (sum(vector)? as f64) / (numbers.len() as f64)\n}\n</code></pre>\n<p>where the <a href=\"https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator\" rel=\"noreferrer\"><code>?</code> operator</a> automatically unwraps the <code>Option</code> if it\nis <code>Some</code> and returns <code>None</code> from the enclosing function otherwise.</p>\n<h1>Arithmetic</h1>\n<p>This is an unnecessary use of floating point arithmetic:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>(((length as f64) / 2.0).floor() as usize)\n</code></pre>\n<p>Integer division rounds toward zero, so what you want is simply\n<code>length / 2</code>.</p>\n<h1><code>None</code> vs <code>NaN</code></h1>\n<p>Since you're already returning <code>f64</code> for <code>mean</code> and <code>median</code>, an\nalternative to using <code>Option</code> might be to simply return <code>f64::NAN</code>\nwhen the collection is empty, as proper <code>f64</code> arithmetic should be\n<code>NAN</code>-aware anyway. <code>None</code> and <code>NAN</code> both have their pros and cons.\nPersonally, I like to use <code>NAN</code> to simplify the type, but the decision\nis up to you.</p>\n<h1>Control flow</h1>\n<p>In <code>median</code>, too many levels of indentation make the code less\nreadable. The <code>match</code>es can be eliminated using <code>if</code> and <code>return</code>.</p>\n<p>Combining the previous points, here's roughly how I would write\n<code>median</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn median(numbers: Vec&lt;i32&gt;) -&gt; f64 {\n let length = numbers.len();\n\n if length == 0 {\n return f64::NAN;\n }\n\n numbers.sort_unstable();\n\n if is_even(length) {\n let left = numbers[length / 2];\n let right = numbers[length / 2 + 1];\n\n (left as f64 + right as f64) / 2.0\n } else {\n numbers[length / 2] as f64\n }\n}\n</code></pre>\n<p>which hopefully looks simpler.</p>\n<h1><code>mode</code></h1>\n<p><code>usize</code> should be a more natural choice for the value type of the map.</p>\n<p>There are some functionalities from the standard library that you can\nuse to simplify the code, including <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max\" rel=\"noreferrer\"><code>max</code></a>, <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter\" rel=\"noreferrer\"><code>filter</code></a>, and\n<a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map\" rel=\"noreferrer\"><code>map</code></a>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn mode(numbers: &amp;[i32]) -&gt; Option&lt;Vec&lt;i32&gt;&gt; {\n let freqs = HashMap::&lt;i32, usize&gt;::new();\n\n for number in numbers {\n freqs.entry(number).or_insert(0) += 1;\n }\n\n let max_count = freqs.values().max()?;\n let mode = freqs\n .iter()\n .filter(|(_, &amp;count)| count == max_count)\n .map(|(&amp;number, _)| number)\n .collect();\n Some(mode)\n}\n</code></pre>\n<h1><code>get_averages</code> &amp; <code>print_averages</code></h1>\n<p>Empty collections aren't common — I wouldn't waste two branches\non them. Simply let the code run through:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn get_averages(numbers: Vec&lt;i32&gt;) -&gt; Option&lt;Averages&gt; {\n Some(Averages {\n mean: mean(vector)?,\n median: median(vector)?,\n mode: mode(vector)?,\n })\n}\n</code></pre>\n<p>The same applies to <code>print_averages</code> — you're wasting three\nbranches in total for non-empty collections. Personally, I think the\nmultiline string literal disrupts the aesthetics of the code, so I\ngot:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn print_averages(numbers: Vec&lt;i32&gt;) {\n match get_averages(numbers) {\n None =&gt; println!(&quot;Empty collection&quot;),\n Some(Average { mean, median, mode }) =&gt; {\n println!(&quot;Mean: {}&quot;, mean);\n println!(&quot;Median: {}&quot;, median);\n println!(&quot;Modes: {:?}&quot;, mode);\n }\n };\n}\n</code></pre>\n<h1>Doc comments &amp; tests</h1>\n<p>As a bonus, you can add <a href=\"https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments\" rel=\"noreferrer\">doc comments</a> and <a href=\"https://doc.rust-lang.org/book/ch11-00-testing.html\" rel=\"noreferrer\">tests</a> to document\nyour code if you have spare time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T05:06:54.223", "Id": "504639", "Score": "0", "body": "Good answer, nice use of `?` which I didn't touch on" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T05:11:43.397", "Id": "504640", "Score": "1", "body": "@6005 It seems that we are the only active Rust reviewers now. Let's keep up the good work :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T03:50:24.137", "Id": "255708", "ParentId": "255689", "Score": "6" } } ]
{ "AcceptedAnswerId": "255708", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T14:51:39.783", "Id": "255689", "Score": "7", "Tags": [ "beginner", "reinventing-the-wheel", "rust" ], "Title": "Idiomatic use of `Option` and `unwrap` in mean, median and mode Rust program for Chapter 8 of The Book" }
255689
<p>I recently finished a high school project of mine for a class revolving around creating my own multithreaded implementation of the &quot;cp&quot; terminal command in UNIX systems.</p> <p>I am seeking for help by experienced people in C to help me make my code better, offering constructive criticism all while improving myself at the same time.</p> <p>Specifically:</p> <ul> <li>Can my code become faster than it currently is?</li> <li>Are there any potential runtime errors in my code? ( I have tested it with multiple examples and all would work fine, I'm just trying to find the ones I didn't think of)</li> <li>Does my code have a good overall structure?</li> </ul> <p>Points of interest:</p> <p><code>src/crawler.c</code></p> <pre><code>#include &quot;../headers/crawler.h&quot; int dircrawler(char* path, char* dest, int pathsize) { // dirent variables and structures DIR* dp; struct dirent* entry; // buffers size_t bufsize; char *buf1, *buf2; buf1 = buf2 = NULL; struct cp_thr_args* args = NULL; if ((dp = opendir(path)) != NULL) { while ((entry = readdir(dp)) != NULL) { // skip over . and .. if (!(strcmp(entry-&gt;d_name, &quot;.&quot;)) || !(strcmp(entry-&gt;d_name, &quot;..&quot;))) continue; if (buf1 != NULL) free(buf1); if (buf2 != NULL) free(buf2); // printf(&quot;%s\n&quot;,entry-&gt;d_name); // buf1: absolute new path, buf2: relative destination path bufsize = snprintf(NULL, 0, &quot;%s/%s&quot;, path, entry-&gt;d_name) + 1; mmalloc(&amp;buf1, bufsize); // buf1 snprintf(buf1, bufsize, &quot;%s/%s&quot;, path, entry-&gt;d_name); bufsize = snprintf(NULL, 0, &quot;%s%s/%s&quot;, dest, (path + pathsize - 1), entry-&gt;d_name) + 1; mmalloc(&amp;buf2, bufsize); // buf2 snprintf(buf2, bufsize, &quot;%s%s/%s&quot;, dest, (path + pathsize), entry-&gt;d_name); if (entry-&gt;d_type == DT_DIR) { // make new directory in dest mkdir(buf2, 0755); if (dircrawler(buf1, dest, pathsize)) closedir(dp); } else { // thread copying section int found = 1; while (1) { // ((Point of interest)) // trying to find a non occupied thread // using status[] for (int i = 0; i &lt; THREADCOUNT; ++i) { if (status[i] == 1) { cp_thr_init(&amp;args, buf1, buf2, &amp;status[i]); pthread_create(&amp;cpthr[i], NULL, cp_thr, (void*)args); pthread_barrier_wait(&amp;can_free); cp_thr_free(args); found = 0; break; } } if (!found) break; } } } if (buf1 != NULL) free(buf1); if (buf2 != NULL) free(buf2); closedir(dp); return 0; } } </code></pre> <p><code>src/threads.c</code></p> <pre><code>#include &quot;../headers/threads.h&quot; int status[THREADCOUNT] = { 1, 1, 1, 1 }; pthread_mutex_t cp_lock = PTHREAD_MUTEX_INITIALIZER; void* cp_thr(void* args) { // extract args data before it gets rewritten struct cp_thr_args* temp = args; char* from; mmalloc(&amp;from, return_size(temp-&gt;from) + 1); char* dest; mmalloc(&amp;dest, return_size(temp-&gt;dest) + 1); int* status = temp-&gt;status; strcpy(from, temp-&gt;from); strcpy(dest, temp-&gt;dest); // send signal to release barrier and free args from crawl pthread_barrier_wait(&amp;can_free); // ((Point of interest)) // assign status to 0 to mark thread as occupied pthread_mutex_lock(&amp;cp_lock); *status = 0; pthread_mutex_unlock(&amp;cp_lock); copy_file(from, dest); free(from); free(dest); // assign status to 1 to mark thread as free to use pthread_mutex_lock(&amp;cp_lock); *status = 1; pthread_mutex_unlock(&amp;cp_lock); return (void*)0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T19:54:04.273", "Id": "504684", "Score": "2", "body": "Welcome to Code Review! Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." } ]
[ { "body": "<h1>Use <code>ftw()</code> to crawl directories</h1>\n<p><a href=\"https://linux.die.net/man/3/ftw\" rel=\"nofollow noreferrer\"><code>ftw()</code></a> is a POSIX function that will recursively crawl directories, and calls a callback function for every directory entry found.</p>\n<h1>Consider using <code>strdup()</code> and <code>asprintf()</code></h1>\n<p>Instead of copying strings using some kind of <code>strlen()</code>+<code>malloc()</code>+<code>strcpy()</code>, use the POSIX function <code>strdup()</code> if possible, which takes care of all this for you.</p>\n<p>Linux and most BSDs also implement <code>asprintf()</code>, which takes care of allocating a correctly sized buffer for you. Be aware that this is definitely not cross-platform.</p>\n<h1>Don't throw away threads</h1>\n<p>While thread creation and destruction is quite fast on Linux, it still has an overhead. If you are copying many small files, that overhead might start dominating. It would be much better to have a fixed number of threads that are waiting for work to do.</p>\n<p>A typical implementation would use a thread-safe queue for this. Have the directory crawler fill a queue of filenames to copy. The queue is guarded by a mutex, and has an associated condition variable. Whenever it pushes an item to the queue, it <a href=\"https://linux.die.net/man/3/pthread_cond_signal\" rel=\"nofollow noreferrer\">signals</a> the condition variable. The threads <a href=\"https://linux.die.net/man/3/pthread_cond_wait\" rel=\"nofollow noreferrer\">wait</a> for elements to be pushed, and when woken up, they will pop one entry from the queue and start copying it.</p>\n<p>However, assuming the directory crawler is much faster than files can be copied, it would be a waste of memory to fill a queue with all filenames encountered, especially if the directory tree is large. You only need a few entries in the queue for worker threads to pick up work. You can make the crawler block itself if the queue gets too large. You should add a second condition variable then that gets signalled whenever a worker dequeues a filename to copy.</p>\n<h1>Find the right number of threads to use</h1>\n<p>It's hard to predict how many threads will be optimal. It could be that one thread is optimal, depending on how fast the storage is compared to the overhead of having multiple threads. Having as many threads as files to copy might also not be ideal; even if they don't use much CPU time, performing I/O on multiple files at the same time might result in more disk seeks (which is mostly an issue on harddisks, but some solid state drives also have some performance penalty for doing non-sequential access). You could benchmark your code and optimize the number of threads for your system, but the performance might be different on other systems.</p>\n<h1>Alternatives for threads</h1>\n<p>Threads are a solution to the problem that there is some implicit serialization when doing regular I/O operations on files in a single thread. However, there are also other techniques to have multiple I/O operations submitted to the kernel simultaneously. POSIX <a href=\"https://linux.die.net/man/7/aio\" rel=\"nofollow noreferrer\">AIO</a> is one way to do this, however it has its limitations. In particular, I don't think you can easily hand off a file <em>copy</em> operation to it. What is more promising is Linux's <a href=\"https://github.com/axboe/liburing\" rel=\"nofollow noreferrer\">io_uring</a>, although this is of course not a cross-platform solution to your problem. If you are interested in the latter, then also see <a href=\"https://lwn.net/Articles/810414/\" rel=\"nofollow noreferrer\">this LWN article</a> and <a href=\"https://unixism.net/loti/\" rel=\"nofollow noreferrer\">this excellent guide</a>. Most BSD flavors have something similar called <a href=\"https://en.wikipedia.org/wiki/Kqueue\" rel=\"nofollow noreferrer\">kqueue</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T09:46:50.750", "Id": "504652", "Score": "1", "body": "IIRC, `asprintf()` was a GNU GPL function (not LGPL) but other versions exist with more permissive licences (e.g. [this implementation](https://github.com/littlstar/asprintf.c/blob/master/asprintf.c) with MIT licence). And it's not hard to write your own if you need it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T23:50:39.963", "Id": "255703", "ParentId": "255692", "Score": "3" } } ]
{ "AcceptedAnswerId": "255703", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:38:11.917", "Id": "255692", "Score": "3", "Tags": [ "c", "multithreading", "linux", "unix" ], "Title": "UNIX cp multithreaded implementation in C" }
255692
<p>I'm learning JavaScript at the moment (still very much a beginner) and this is the first app I've designed on my own, without using any tutorials. It's an app which takes the user's gender, age, height, and weight and then calculates their BMR. It works, but I would really appreciate it if someone more knowledgeable could take a look at the code to see if it's optimal (or even close!). I want to unlearn any bad habits I may have picked up as soon as possible.</p> <p>Here's a link to all the code on GitHub, along with a ReadMe that explains in detail how the app works:</p> <p><a href="https://github.com/neilmurrellcoding/bmr-calculator-version-one" rel="nofollow noreferrer">https://github.com/neilmurrellcoding/bmr-calculator-version-one</a></p> <p>The HTML code is:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;css/index.css&quot;&gt; &lt;title&gt;BMI Calculator&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;first-container&quot;&gt; &lt;div class=&quot;second-container&quot;&gt; &lt;div class=&quot;application&quot;&gt; &lt;h1 class=&quot;title&quot;&gt;DIET PLANNER&lt;/h1&gt; &lt;p class=&quot;intro&quot;&gt;Fill out the below fields to discover your BMR.&lt;/p&gt;&lt;br&gt; &lt;p class=&quot;intro&quot;&gt;Your BMR is the number of calories you burn off in 24 hours&lt;/p&gt; &lt;form&gt; &lt;div class=&quot;radio-buttons&quot;&gt; &lt;p class=&quot;label&quot;&gt;&lt;strong&gt;Select your gender&lt;/strong&gt;&lt;/p&gt; &lt;input type=&quot;radio&quot; checked=&quot;checked&quot; id=&quot;male&quot; name=&quot;gender&quot; value=&quot;male&quot;&gt;&lt;label for=&quot;male&quot; class=&quot;gender-label&quot;&gt;Male&lt;/label&gt; &lt;input type=&quot;radio&quot; id=&quot;female&quot; name=&quot;gender&quot; value=&quot;female&quot;&gt;&lt;label for=&quot;female&quot; class=&quot;gender-label&quot;&gt;Female&lt;/label&gt; &lt;/div&gt; &lt;p class=&quot;label&quot;&gt;&lt;strong&gt;Age&lt;/strong&gt;&lt;/p&gt; &lt;input type=&quot;number&quot; id=&quot;age&quot; class=&quot;age-field&quot; min=&quot;0&quot; max=&quot;130&quot; placeholder=&quot;Enter your age&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;p class=&quot;label&quot;&gt;&lt;strong&gt;Height&lt;/strong&gt;&lt;/p&gt; &lt;input type=&quot;number&quot; id=&quot;feet&quot; class=&quot;field&quot; min=&quot;0&quot; max=&quot;9&quot; placeholder=&quot;ft&quot;&gt; &lt;input type=&quot;number&quot; id=&quot;inches&quot; class=&quot;field&quot; min=&quot;0&quot; max=&quot;11&quot; placeholder=&quot;in&quot;&gt;&lt;br&gt; &lt;p class=&quot;label&quot;&gt;&lt;strong&gt;Weight&lt;/strong&gt;&lt;/p&gt; &lt;input type=&quot;number&quot; id=&quot;stone&quot; class=&quot;field&quot; min=&quot;0&quot; max=&quot;80&quot; placeholder=&quot;stone&quot;&gt; &lt;input type=&quot;number&quot; id=&quot;lbs&quot; class=&quot;field&quot; min=&quot;0&quot; max=&quot;13&quot; placeholder=&quot;lbs&quot;&gt;&lt;br&gt; &lt;input type=&quot;submit&quot; id=&quot;submit&quot; class=&quot;submit&quot;&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;results&quot;&gt; &lt;div class=&quot;results-container&quot;&gt; &lt;h1 class=&quot;title&quot;&gt;Your daily BMI is:&lt;/h1&gt; &lt;p id=&quot;bmi-result&quot;&gt;Placeholder text&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src=&quot;application.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The JS code is:</p> <pre><code>document.getElementById('results').style.display = 'none'; submit.addEventListener('click', function(e) { // Runs getValues when form's submit button is clicked. e.preventDefault(); getValues(); }) getValues = () =&gt; { // Converts values from form fields into integers, then assigns these integers to variables. const age = parseInt(document.getElementById(&quot;age&quot;).value); const gender = document.getElementsByName(&quot;gender&quot;); // This produces a node-list with 2 items, male and female. Male is checked by default. const heightFeet = parseInt(document.getElementById(&quot;feet&quot;).value); const heightInches = parseInt(document.getElementById(&quot;inches&quot;).value); const weightStone = parseInt(document.getElementById(&quot;stone&quot;).value); const weightLbs = parseInt(document.getElementById(&quot;lbs&quot;).value); x = calculateAge(age); // calls the calculateAge function below, passes 'age' as an argument, assigns return value to x. y = calculateWeight(weightStone, weightLbs); // calls the calculateWeight function below, passes 'weightStone' &amp; 'weightLbs' as args, assigns return value to y. z = calculateHeight(heightFeet, heightInches); // calls the calculateHeight function below, passes 'heightFeet' &amp; 'heightWeight' as args, assigns return value to z. finalResult(x, y, z, gender); // calls finalResult function below, passes return values of above 3 functions as args. } calculateAge = age =&gt; { // Multiplies user's age by 5 and saves this as finalAge. finalAge = age * 5; return finalAge; } calculateWeight = (weightStone, weightLbs) =&gt; { // Converts user's imperial weight into kg, multiplies it by 10, and returns finalWeight. kilogramWeight = ((weightStone * 14) + weightLbs) * 0.453; finalWeight = kilogramWeight * 10; return finalWeight; } calculateHeight = (heightFeet, heightInches) =&gt; { // Converts user's imperial height into cm, multiplies it by 6.25, and returns finalHeight. centimeterHeight = ((heightFeet * 12) + heightInches) * 2.54; finalHeight = centimeterHeight * 6.25; return finalHeight; } finalResult = (x, y, z, gender) =&gt; { result = z + y - x; // finalWeight + finalHeight - finalAge. for(i = 0; i &lt; gender.length; i++) { // This checks to see which gender the user checked. If 'male', +5 to finalResult. Else, -161 from finalResult. if(gender[i].checked) { finalResult = result + 5; break; } else { finalResult = result - 161; break; } } revealResult(finalResult); // Calls below function &amp; passes finalResult as an argument. return finalResult; } revealResult = finalResult =&gt; { finalResult = Math.floor(finalResult); let finalBmi = finalResult.toString() document.getElementById('results').style.display = 'block'; // Reveals the 'results' box which was originally hidden (see line 1) const calories = document.getElementById(&quot;bmi-result&quot;); // Grabs 'p' element. calories.classList.add(&quot;finalNumberStyling&quot;) // Applies simple styling to 'p' element. calories.innerText = finalBmi + ' calories per day'; // Inserts finalBmi string into 'p' element. } </code></pre> <p>I've not included the CSS code because the styling is very minimal, but it's all available at the GitHub link just in case.</p> <p>Any comments or suggestions you have would be very much appreciated.</p> <p>Thanks.</p> <p>EDIT: Made a few edits to the JS code to add some explanatory notes.</p>
[]
[ { "body": "<h2>Poor naming</h2>\n<p>The first thing that popped out at me was the naming. Starting with BMI</p>\n<p>(BMI) Body mass index is not a time dependent quantity. You show a calculated value under the heading <code>&lt;h1 class=&quot;title&quot;&gt;Your daily BMI is:&lt;/h1&gt;</code> which makes no sense at all.</p>\n<p>I don't know what the value you are calculating is. I will assume that the string '&quot; calories per day&quot;' found in the function <code>revealResult</code> defines the value you calculate.</p>\n<h2>Some more naming problems</h2>\n<ul>\n<li><p><code>getValues</code> What values? Maybe use <code>calculateDailyCalories</code></p>\n</li>\n<li><p>3 functions prefixed with calculate? but the user gives you the age weight and height. You are not calculating these values you are calculating some metric from the age weight and height.</p>\n<ul>\n<li><code>calculateAge</code> can be <code>ageMetric</code></li>\n<li><code>calculateWeight</code> can be <code>weightMetric</code></li>\n<li><code>calculateHeight</code> can be <code>heightMetric</code></li>\n</ul>\n</li>\n<li><p><code>finalResult</code> Great its final, but what is it? Maybe <code>dailyCalories</code> or just <code>calories</code> would be better</p>\n</li>\n<li><p>The arguments for <code>finalResult(x, y, z, gender)</code> ? This is very bad as it give no indication as to what they represent. Maybe use <code>(ageMetric, weightMetric, heightMetric, isMale)</code></p>\n</li>\n<li><p><code>revealResult</code> A little odd to use reveal, but reveal result give no indication as to what you are revealing. Maybe use <code>displayDailyCalories</code> or <code>displayCalories</code></p>\n</li>\n</ul>\n<p>Keep variable names as short as possible. For example the function <code>calculateHeight(heightFeet, heightInches)</code> It can be inferred that the variables <code>heightFeet</code> <code>heightInches</code> represent heights, thus the better names are <code>feet</code> and <code>inches</code></p>\n<p>Element names (ids) also do not give any indication as to what they are. See rewrite HTML</p>\n<h2>Strict Mode</h2>\n<p>To help spot bad habits early always use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Strict mode\">Strict_mode</a>. This is done by adding the directive &quot;use strict&quot; as the first line of the JS file or <code>script</code> tag</p>\n<h3>ALWAYS declare variables</h3>\n<p>If you used strict mode your code would have thrown errors for all the undeclared variables. Always declare variables using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. var\">var</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. let\">let</a>.</p>\n<h3>Comments</h3>\n<p>If you feel you need to add comments to explain the code, then first consider improving the naming and layout of the code. when commenting the assumption is that the reader knows how to code. If they don't know how to code they should not be editing your code in the first place.</p>\n<h3>Further points</h3>\n<ul>\n<li><p>Maintain a consistent style. In some places you neglected to add semi colon to the end of lines.</p>\n</li>\n<li><p>Use functions to reduce the amount of repeated code. (see rewrite)</p>\n</li>\n<li><p>Avoid single use variables.</p>\n</li>\n<li><p>Use <code>textContent</code> rather than <code>innerText</code> to set an elements text.</p>\n</li>\n<li><p>The code that check for gender is a very obscure. Make sure that the code is not ambiguous and that you do not need to hunt around to find out what the code does.</p>\n</li>\n</ul>\n<h2>CSS</h2>\n<p>Use a style class rather than directly setting the style property. For example hiding and showing the results you have</p>\n<blockquote>\n<pre><code>document.getElementById('results').style.display = 'none';\n// then later in a function\n document.getElementById('results').style.display = 'block'; \n</code></pre>\n</blockquote>\n<p>Rather create a style rule. Add the class to the HTML as default. Then remove the rule when you need to show the content</p>\n<pre><code>/* CSS */\n.hidden {display: none}\n\n&lt;!-- HTML --&gt; \n&lt;div id=&quot;results&quot; class=&quot;hidden&quot;&gt;\n\n// JavaScript\ndocument.getElementById('results').classList.remove(&quot;hidden&quot;)\n</code></pre>\n<h3>Don't add code when not needed</h3>\n<p>Why do you add the class <code>calEl.classList.add(&quot;finalNumberStyling&quot;); </code> in code. The element is hidden and you only add this when you show the element. Rather It should already be in the HTML</p>\n<h2>Rewrite</h2>\n<p>The rewrite adds some helper functions to remove the verbose DOM calls. <code>byId</code>, <code>byName</code> gets elements by id and name. <code>valById</code> gets a value of an input by its id</p>\n<p>The rest of the rewrite removes a lot of the code noise. Single use variables, Verbose DOM calls.</p>\n<p>The gender is taken directly from the <code>maleRadio</code> button (not iterating over the gender radio buttons) and passed to <code>calories</code> if <code>isMale</code> is false then not male.</p>\n<p>Rather than listen for the submit buttons <code>click</code> event the rewrite listens for the forms <code>submit</code> event. To add the listener the form has been given the id 'caloriesForm'</p>\n<p>I replaced some of the input headings with label tags. All the inputs should use <code>label</code> tags to label them rather than just text elements near them.</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>\"use strict\";\nconst byId = id =&gt; document.getElementById(id);\nconst byName = name =&gt; document.getElementsByName(name);\nconst valById = id =&gt; parseInt(byId(id).value, 10);\n\nconst ageMetric = age =&gt; age * 5;\nconst weightMetric = (stone, lbs) =&gt; (stone * 14 + lbs) * 0.453 * 10;\nconst heightMetric = (feet, inches) =&gt; (feet * 12 + inches) * 2.54 * 6.25;\n\nconst calories = (ageMetric, weightMetric, heightMetric, isMale) =&gt; \n Math.floor(heightMetric + weightMetric - ageMetric + (isMale ? 5 : -161)); \n \nconst displayCalories = calories =&gt; {\n byId(\"resultsContainer\").classList.remove(\"hidden\");\n byId(\"dailyCaloriesDisplay\").textContent = calories + ' calories per day'; \n}\n\nbyId(\"caloriesForm\").addEventListener('submit', event =&gt; { \n event.preventDefault();\n displayCalories(\n calories(\n ageMetric(valById(\"ageInput\")), \n weightMetric(valById(\"stoneInput\"), valById(\"lbsInput\")), \n heightMetric(valById(\"feetInput\"), valById(\"inchesInput\")),\n byId(\"maleRadio\").checked\n )\n );\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.hidden {display: none}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form id=\"caloriesForm\"&gt;\n &lt;div class=\"radio-buttons\"&gt;\n &lt;label for=\"gender\" class=\"label\"&gt;&lt;strong&gt;Gender&lt;/strong&gt;&lt;/label &gt;\n &lt;input type=\"radio\" checked=\"checked\" id=\"maleRadio\" name=\"gender\"&gt;&lt;label for=\"male\" class=\"gender-label\"&gt;Male&lt;/label&gt;\n &lt;input type=\"radio\" name=\"gender\"&gt;&lt;label for=\"female\" class=\"gender-label\"&gt;Female&lt;/label&gt;\n &lt;/div&gt;\n\n &lt;label for=\"ageInput\" class=\"label\"&gt;&lt;strong&gt;Age&lt;/strong&gt;&lt;/label &gt;\n &lt;input type=\"number\" id=\"ageInput\" class=\"age-field\" min=\"0\" max=\"130\" placeholder=\"Enter your age\"&gt;&lt;br&gt;\n\n &lt;p&gt;Height&lt;/p&gt;\n &lt;label for=\"feetInput\" class=\"label\"&gt;&lt;strong&gt;Feet&lt;/strong&gt;&lt;/label &gt;\n &lt;input type=\"number\" id=\"feetInput\" class=\"field\" min=\"0\" max=\"9\" placeholder=\"ft\"&gt;\n &lt;label for=\"inchesInput\" class=\"label\"&gt;&lt;strong&gt;inches&lt;/strong&gt;&lt;/label &gt;\n &lt;input type=\"number\" id=\"inchesInput\" class=\"field\" min=\"0\" max=\"11\" value=\"0\"&gt;&lt;br&gt;\n\n &lt;p&gt;Weight&lt;/p&gt;\n &lt;label for=\"stoneInput\" class=\"label\"&gt;&lt;strong&gt;Stone&lt;/strong&gt;&lt;/label &gt;\n &lt;input type=\"number\" id=\"stoneInput\" class=\"field\" min=\"1\" max=\"80\" placeholder=\"stone\"&gt;\n &lt;label for=\"lbsInput\" class=\"label\"&gt;&lt;strong&gt;lbs&lt;/strong&gt;&lt;/label &gt;\n &lt;input type=\"number\" id=\"lbsInput\" class=\"field\" min=\"0\" max=\"13\" value=\"0\"&gt;&lt;br&gt;\n\n &lt;input type=\"submit\" class=\"submit\"&gt;\n&lt;/form&gt;\n\n&lt;div id=\"resultsContainer\" class=\"hidden\" class=\"results-container hidden\"&gt;\n &lt;p id=\"dailyCaloriesDisplay\" class=\"finalNumberStyling\"&gt;&lt;/p&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>More to do.</h2>\n<p>You code does not check if the form has been completed. Displaying the value NaN (not a number) if any of the fields have not been set.</p>\n<p>You should detect if there are missing fields and prompt the use to add the missing information.</p>\n<p>Only when all fields are entered should you display the result.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T18:55:22.623", "Id": "504767", "Score": "0", "body": "Thanks so much for the detailed feedback. That was exactly the kind of thing I was after." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T15:28:09.067", "Id": "255723", "ParentId": "255696", "Score": "2" } } ]
{ "AcceptedAnswerId": "255723", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T18:38:22.327", "Id": "255696", "Score": "0", "Tags": [ "javascript", "html", "css", "calculator" ], "Title": "BMR calculator web app written in HTML/CSS/Vanilla JS" }
255696
<p>I'm currently working on a project where I'm dealing with somewhat large data sets. I have a dataframe <code>transactions</code> and another <code>users</code>.</p> <p>Iterating through the transactions dataframe is no problem. I used <code>timeit</code> and it takes just under a minute to do so. My second dataframe <code>users</code> has 1,000 rows. Both of these dataframes have a column <code>email</code>. Essentially what i'm trying to do is get the <code>userId</code> in the row in <code>users</code> that matches the <code>email</code> in each <code>transactions</code> row. My current approach looks like this:</p> <pre><code>for row in transactions.itertuples(): userId = users[users['email'] == getattr(row, 'email')]['userId'].values[0] </code></pre> <p>This simple lookup works, however it's too slow for my use case. I kept it running for over an hour and it still wasn't finished running. I'm wondering if there's potentially a faster way to do this lookup (maybe get the runtime down to minutes instead of hours)?</p> <p>Appreciate any help in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:11:55.370", "Id": "504617", "Score": "1", "body": "Hey, welcome to Code Review! Please add some more code, as we cannot review this without the context. Please also add some example input data (and example output), as this makes it easier to check if proposed changes do not change the intention of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:12:34.727", "Id": "504618", "Score": "1", "body": "Also, can there be more than one user with the same email?" } ]
[ { "body": "<p>You can use <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging\" rel=\"nofollow noreferrer\"><code>DataFrame#merge</code></a>.</p>\n<pre><code>df = transactions.merge(users, on=&quot;email&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:43:54.393", "Id": "255700", "ParentId": "255697", "Score": "0" } } ]
{ "AcceptedAnswerId": "255700", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T19:20:24.110", "Id": "255697", "Score": "0", "Tags": [ "python" ], "Title": "Optimize 950k+ lookups in pandas dataframe" }
255697
<p>If you simply implement it with <code>.push()</code> to <code>.enqueue()</code> and <code>.shift()</code> to <code>.dequeue()</code> that's easy but the the time complexity of <code>.enqueue()</code> is O(1) and <code>.dequeue()</code> is O(n).</p> <p>While still using arrays, I have come come up with a nice solution to make both <code>.enqueue()</code> and <code>.dequeue()</code> in O(1). I am using sparse arrays. It turns out to be super efficient but only when the <code>Queue</code> size is larger than 25000. My benchmarks are like this;</p> <pre><code>Queue size 100 Queue: 0.12999999523162842 Array: 0.03999999910593033 Queue size 1000 Queue: 1.1049999967217445 Array: 0.5250000059604645 Queue size 10000 Queue: 3.0750000029802322 Array: 1.7799999937415123 Queue size 100000 Queue: 13.944999992847443 Array: 887.390000000596 </code></pre> <p>OK <code>Queue</code> becomes much faster than <code>Array</code> as the size grows but i can not tell what to improve so that <code>Queue</code> doesn't fall behind <code>Array</code> at smaller scales. Is there anything that you can suggest in the below code?</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>class Queue extends Array { constructor(){ super(); Object.defineProperty(this,"head",{ value : 0 , writable: true }); } enqueue(x) { this.push(x); return this; } dequeue() { var first; return this.head &lt; this.length ? ( first = this[this.head] , delete this[this.head++] , first ) : void 0; } peek() { return this[this.head]; } } var p = Array(100000).fill().map(_ =&gt; ~~(Math.random()*1000)), q = p.reduce((r,e) =&gt; r.enqueue(e), new Queue()); var s,e; s = performance.now(); for (i=0; i &lt; 100000; i++){ q.dequeue(); } e = performance.now(); console.log("Queue:", e-s); s = performance.now(); for (i=0; i &lt; 100000; i++){ p.shift(); } e = performance.now(); console.log("Array:", e-s);</code></pre> </div> </div> </p> <p><strong>Edit:</strong> After some research, now i understand that what many of us have been told is in fact not correct. <code>.shift()</code> is not O(n). It's been optimized to O(1) many years ago and i think last ones to optimize were the Firefox guys in 2017. <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1348772#c2" rel="nofollow noreferrer">Here</a> the guys are discussing how to implement the optimization and it turns they do a very similar thing to what i implemented here. Unlike me, they just skip the &quot;<code>delete</code> out the dequeued item&quot; part since they write it in C++ and can move the pointer (<code>head</code> in above code) by leaving out freed spaces to GC. But in JS we have to <code>delete</code> them either in each <code>.dequeue()</code> operation or wait for <code>(this.length - this.head) &gt; 50000</code> and make a <code>.splice(0,this.head)</code> in order to prevent memory leak. This is inline with what i see with Chrome and new Edge (Chromium). Up until 50000 items <code>.shift()</code> works O(1) but then they switch to non optimized code. In Firefox this seems to be not the case as mentioned in a <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1348772#c7" rel="nofollow noreferrer">developer's comment</a>.</p> <p><strong>Verdict:</strong> You may safely and simply implement efficient <code>Queue</code>s with <code>.push()</code> and <code>.shift()</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T22:16:09.770", "Id": "505013", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/119602/discussion-on-question-by-redu-queue-with-o1-enqueue-and-dequeue-with-js-array)." } ]
[ { "body": "<h2>Review</h2>\n<p>I find your indentations and line breaks rather difficult to read.</p>\n<blockquote>\n<pre><code>Object.defineProperty(this,&quot;head&quot;,{ value : 0\n , writable: true\n });\n</code></pre>\n</blockquote>\n<p>I would suggest you use the idiomatic style.</p>\n<p>After <code>{</code> move to the next line and indent once. Place the comma at the end of lines and spaces after commas if not at end of line</p>\n<pre><code>Object.defineProperty(this, &quot;head&quot;, { \n value: 0,\n writable: true\n});\n</code></pre>\n<p>or if the line is short</p>\n<pre><code>Object.defineProperty(this, &quot;head&quot;, {value: 0, writable: true});\n</code></pre>\n<p>or</p>\n<pre><code>Object.defineProperty(\n this, \n &quot;head&quot;, { \n value: 0,\n writable: true\n }\n);\n</code></pre>\n<p>Same again with the ternary.</p>\n<blockquote>\n<pre><code>return this.head &lt; this.length ? ( first = this[this.head]\n , delete this[this.head++]\n , first\n )\n : void 0;\n</code></pre>\n</blockquote>\n<p>Why use the operator <code>void</code> that requires the additional expression <code>0</code> when you can just express <code>undefined</code>.</p>\n<p>I understand the reasoning for breaking up the group, but the indent is way to great. The idiomatic style is far more readable.</p>\n<pre><code>return this.head &lt; this.length ? ( \n first = this[this.head],\n delete this[this.head++],\n first\n ) : \n undefined; \n</code></pre>\n<p>or</p>\n<pre><code>return this.head &lt; this.length ?\n (first = this[this.head], delete this[this.head++], first) : \n undefined; \n</code></pre>\n<h2>Unsafe encapsulation</h2>\n<p>Extending the <code>Array</code> with the behaviors <code>enqueue</code> and <code>dequeue</code> is just asking for bugs as any of the existing functions can damage state.</p>\n<p>Rules of code: <em>&quot;If it is there it will be used.&quot;</em></p>\n<p>Good code enforces the rules by not exposing properties and behaviors that can damage state.</p>\n<p>Even just the basic use of <code>Queue</code> is un-trusted because you expose <code>head</code>.</p>\n<h2>JS Queue</h2>\n<p>Complexity and performance are two side of the same coin. Though linked they are vastly difference. With <code>shift</code> at <span class=\"math-container\">\\$O(1)\\$</span> its performance is still 10 times slower than <code>pop</code></p>\n<p>However you use <code>delete</code> to remove items. Again it is <span class=\"math-container\">\\$O(1)\\$</span> but it is even slower than <code>shift</code>.</p>\n<h3>Linked list</h3>\n<p>I have found that a simple linked list is the most effective and performant solution for a queue in JS</p>\n<p>Implementing it as a factory function allows closure to hold its state safely isolated from the code using the queue.</p>\n<pre><code>function Queue() {\n var head, tail;\n return Object.freeze({ \n enqueue(value) { \n const link = {value, next: undefined};\n tail = head ? tail.next = link : head = link;\n },\n dequeue() {\n if (head) {\n const value = head.value;\n head = head.next;\n return value;\n }\n },\n peek() { return head?.value }\n });\n}\n</code></pre>\n<p>This style offers robust encapsulation, maintains the ideal <span class=\"math-container\">\\$O(1)\\$</span> for <code>enqueue</code> and <code>dequeue</code> without sacrificing performance.</p>\n<h3>Test</h3>\n<p>The test compares the execution time of your Queue against a linked list version of a queue.</p>\n<p>There are two test cycles, First for 1000 items, then when done click the button for 500,000 items.</p>\n<p>I Have made minor changes to your code to favor performance. Not using define property and not returning the array in enqueue.</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>var size = 1000;\nconst COOL = 200;\n\nclass Queue extends Array {\n constructor(){\n super();\n this.head = 0;\n }\n enqueue(x) { this.push(x) }\n dequeue() {\n var first;\n return this.head &lt; this.length ? \n (first = this[this.head] , delete this[this.head++] , first) : \n void 0;\n }\n peek() { return this[this.head] }\n}\n\nfunction QueueLinked() {\n var head, tail;\n return Object.freeze({ \n enqueue(value) { \n const link = {value, next: undefined};\n tail = head ? tail.next = link : head = link;\n },\n dequeue() {\n if (head) {\n const value = head.value;\n head = head.next;\n return value;\n }\n },\n peek() { return head?.value }\n });\n}\n\n\nfunction fillQueue(queue, count = size) {\n while (count--) { queue.enqueue(count) }\n return queue;\n}\nfunction testOPQueue() {\n const q = fillQueue(new Queue());\n var ii = 0, val = 0;\n do {\n ii += val;\n val = q.dequeue();\n } while (val !== undefined);\n return ii;\n}\nfunction testLinkedQueue() {\n const q = fillQueue(QueueLinked());\n var ii = 0, val = 0;\n do {\n ii += val;\n val = q.dequeue();\n } while (val !== undefined);\n return ii;\n}\n\nif (testOPQueue() !== testLinkedQueue()) { throw new Error(\"Test results differ\") }\n\nconst funcTest = (name, call, bias = 1) =&gt; ({name, call, time: 0, cycles: 0, bias});\n\ntimeFunctions(50, 500, \"1000 items:\",\n funcTest(\"Array Queue\", testOPQueue),\n funcTest(\"Linked Queue\", testLinkedQueue),\n).then(() =&gt; {\n test2.classList.remove(\"hide\");\n test2.addEventListener(\"click\", () =&gt; {\n test2.classList.add(\"hide\");\n size = 500000;\n timeFunctions(50, 3, \"500,000 items:\",\n funcTest(\"Array Queue\", testOPQueue),\n funcTest(\"Linked Queue\", testLinkedQueue),\n );\n });\n});\n\n\nfunction timeFunctions(testCount, cycles, name, ...functions) {\n return new Promise(done =&gt; {\n const testGroup = () =&gt; {\n var i;\n for (const func of functions) {\n i = cycles;\n const now = performance.now();\n while (i--) { func.call() }\n func.time += performance.now() - now;\n func.cycles += cycles;\n }\n }\n const test = () =&gt; {\n testGroup();\n console.clear();\n console.log(name + \" \" + (testCount - count + 1) + \" of \" + testCount);\n for (const func of functions) {\n console.log(\n func.name.padEnd(maxNameLen + 2,\".\") + \": \" + \n (((func.time / func.cycles) / func.bias).toFixed(3) + \"ms\").padStart(9,\" \") +\n (\" Total: \" + func.time.toFixed(3) + \"ms\") \n );\n }\n if (--count) { setTimeout(test, COOL) }\n else { done() }\n }\n var count = testCount;\n var maxNameLen = 0\n for (const func of functions) {\n func.time = 0;\n func.cycles = 0;\n maxNameLen = Math.max(maxNameLen, func.name.length);\n }\n setTimeout(test, COOL);\n });\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.hide { display: none }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"test2\" class=\"hide\"&gt;Test 500000 items&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T18:47:06.713", "Id": "504764", "Score": "0", "body": "Many thanks for your time spared for this answer. As per indenting, that's my style and i will stick to it. I even bought an ultrawide monitor for this purpose. If you get used to wide indents you can not go back. For me it's how code should be written. Also thanks for the `head` exposed part. In trench soldiers shouldn't expose their heads right..? I agree and i can fix it while extending an array. Extending an array saves me from implementing many functionalities such as `.map()`. Why wouldn't you like your Queue type be a functor at no cost? As per the performance though ->" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T18:50:47.703", "Id": "504765", "Score": "0", "body": "when i `delete` the `dequeue`d item, yes it is it comes with a cost. I can defer it to a later stage though. Yet.. i would humbly adivise you to test your code against a simple array by using `.shift()` instead of `dequeue` at reasonable sizes below 10000. See how it turns out. Upvoted for the effort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T05:38:09.550", "Id": "504808", "Score": "0", "body": "@Redu Linked list is on par with a stack.. I have tested all possible combinations (including list sizes down to 100) and the link list is the fastest possible implementation of a queue (exception A fixed size queue, with head and tail that cycle eg `head = (head + 1) %.len` it is very fast but restricted size means its not really a queue). re `map` You could use `symbol.iterator` and use the spread operator and/or implement a simple map in a few lines. `map(cb) { const a=[];while(head) { a.push(cb(head.value, a.length, this)); head = head.next } return a }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T18:33:42.243", "Id": "504880", "Score": "0", "body": "I think you have good points in this answer. I just tried to stretch it further with a new answer. Having said that yours should be the accepted one in the first place. Thank you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T14:00:24.993", "Id": "255758", "ParentId": "255698", "Score": "2" } }, { "body": "<p>After thinkering a while, I really liked <a href=\"https://codereview.stackexchange.com/a/255758/105433\">BlindMan67</a>'s answer except for the indentation part. This self answer is here just to show how we can use the <code>Class</code> abstraction to achieve a similar <code>Queue</code> implementation. Perhaps we can do better with modern JS while still being in the realm of Chrome v74 or Node 12.0. I mean the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields\" rel=\"nofollow noreferrer\">private instance fields</a>.</p>\n<p>I think this might be considered somewhat better since now you have <code>enqueue</code>, <code>dequeue</code> and <code>peek</code> as prototype inherited functions, you may add more to them as you wish and for some reason you may even <code>extend</code> this type. The performance is not second to his good solution. Here it is;</p>\n<pre><code>class Queue {\n #HEAD;\n #LAST;\n constructor(){\n this.#HEAD;\n this.#LAST;\n };\n enqueue(value){\n var link = {value, next: void 0};\n this.#LAST = this.#HEAD ? this.#LAST.next = link\n : this.#HEAD = link;\n }\n dequeue(){\n var first;\n return this.#HEAD &amp;&amp; ( first = this.#HEAD.value\n , this.#HEAD = this.#HEAD.next\n , first\n );\n }\n peek(){\n return this.#HEAD &amp;&amp; this.#HEAD.value;\n }\n};\n</code></pre>\n<p>I forgot to mention that the <code>tail</code> name wouldn't be my first preference as i happen to understand it like representing all those items following the <code>head</code>. (Haskell terminology) so my choice here is <code>#LAST</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T18:31:41.310", "Id": "255817", "ParentId": "255698", "Score": "1" } } ]
{ "AcceptedAnswerId": "255758", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T19:34:17.023", "Id": "255698", "Score": "2", "Tags": [ "javascript", "queue" ], "Title": "Queue with O(1) enqueue and dequeue with JS arrays" }
255698
<p>I have the following code:</p> <pre><code>items = set() # use a set to not have duplicate items a = requests.get(f&quot;{BASE_URL}?{BASE_QUERIES}&amp;cursor=*&quot;) amount = a.json()[&quot;totalResults&quot;] # in the range of 30 million items.update(item[&quot;guid&quot;].split(&quot;?&quot;)[0] for item in a.json()[&quot;items&quot;]) # we only want the url before the query strings cursor = a.json()[&quot;nextCursor&quot;] # we have a cursor as each request only returns 100 items, the cursor shows use where to start while len(items) &lt; amount: # ensure we get all the items try: a = requests.get(f&quot;{BASE_URL}?{BASE_QUERIES}&amp;cursor={cursor}&quot;) items.update(item[&quot;guid&quot;].split(&quot;?&quot;)[0] for item in a.json()[&quot;items&quot;]) except: continue try: cursor = urllib.parse.quote(a.json()[&quot;nextCursor&quot;]) except KeyError: if len(items) == amount: # when we reach the final iteration the cursor will not be there break headers = { &quot;user-agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36&quot; } for link in items: # iterate over each item for _ in range(3): response = requests.get(link, headers=headers, stream=True) response.raw.decode_content = True parser = etree.HTMLParser() tree = etree.parse(response.raw, parser) setting = tree.xpath( &quot;/html/body/div[1]/div/div/main/div/div[2]/div/div[2]/div/div/div[1]/a/span[1]/text()&quot; )[0].strip() try: image = tree.xpath( &quot;/html/body/div[1]/div/div/main/div/div[2]/div/div[1]/div[1]/div/div/a/@href&quot; )[0] # most of the time this works except: try: image = tree.xpath( &quot;/html/body/div[1]/div/div/main/div/div[2]/div/div[1]/div[1]/div[1]/a/@href&quot; )[0] # about 1 in 10 times the above fails and this works except: print(f&quot;Image not found for link: {link}&quot;) break title = tree.findtext(&quot;.//title&quot;) title_for_file = ( fr&quot;{os.getcwd()}\IMAGES\IMAGE - &quot; + &quot;&quot;.join(c for c in title if c in valid_chars) + &quot;.jpeg&quot; ) # sometimes the file contains characters which aren't allowed in file names description = &quot;&quot;.join( tree.xpath( &quot;/html/body/div[1]/div/div/main/div/div[3]/div[1]/div/div/div/div/p/text()&quot; ) ) if setting not in [x, y]: # we only want items which have a specific setting break try: image_req = requests.get(image) with open(title_for_file, &quot;wb&quot;) as f: f.write(image_req.content) # write the image to the directory img = pyexiv2.Image(title_for_file) metadata = {&quot;Xmp.xmp.Title&quot;: title, &quot;Xmp.xmp.Description&quot;: description} # edit the metadata img.modify_xmp(metadata) img.close() break except Exception as e: print( f&quot;ERROR parsing image: {title_for_file}, it is most likely corrupt, &quot; f&quot;retrying ({link}), &quot; f&quot;error: {e}&quot; ) os.remove(title_for_file) else: print(&quot;ERROR more than 3 times moving to next&quot;) </code></pre> <p>The code has some fairly detailed comments to explain what it does, my issue is that it takes about 7 hours to do all the requests to get the links in <code>items</code>, then another (I'm not 100% sure but, I think about 1500 hours) to check each image and add the metadata. Is there <em>anything</em> in this code that can be sped up/refined to speed up this process?</p> <p>Similarly, is there anywhere I could reduce memory usage as I <em>suspect</em> this will use <strong>alot</strong> of memory with the amount of data it is parsing.</p> <p><strong>EDIT</strong></p> <p>A possible consideration would be to use <code>Threading</code> to download multiple images at once, how would one find the optimal number of threads to run at once? Or perhaps I would start each <code>Thread</code> with a small delay, perhaps 0.5 seconds?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:31:06.387", "Id": "504620", "Score": "0", "body": "How large are these images? If they were 3MB each, it would take [more than 80 days just to download them (sequentially, assuming 100 Mbit/s speed)(https://www.wolframalpha.com/input/?i=30E6+*+3MB+%2F+100Mbit%2Fs)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:34:13.353", "Id": "504621", "Score": "0", "body": "Approximately 500kB-1MB, so yes still a lot! Hence, why I need to reduce as much as possible, obviously the bulk of the time is the requests. But, I am not necessarily downloading all of these images, I expect to download about 1/2 as about 1/2 will not be in `x` or `y`" } ]
[ { "body": "<p>Before you can start thinking about doing fancy things like parallelizing this code, you should start by putting your code into functions that do one thing each.</p>\n<pre><code>def get_items(response):\n # we only want the url before the query strings\n # use a set to not have duplicate items\n return {item[&quot;guid&quot;].split(&quot;?&quot;)[0] for item in response[&quot;items&quot;]}\n\ndef get_all_items():\n url = f&quot;{BASE_URL}?{BASE_QUERIES}&quot;\n response = requests.get(url, params={&quot;cursor&quot;: &quot;*&quot;}).json()\n amount = response[&quot;totalResults&quot;] # in the range of 30 million\n items = get_items(response) \n while cursor := response.get(&quot;nextCursor&quot;):\n try:\n response = requests.get(url, params={&quot;cursor&quot;: cursor}).json()\n items.update(get_items(response))\n except Exception:\n continue\n if len(items) != amount:\n raise ValueError(&quot;Did not get all items&quot;)\n return items\n</code></pre>\n<p>Note that I changed your bare <code>except</code> to an <code>except Exception</code>, otherwise the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> would also be ignored.</p>\n<p>I also used the new walrus operator to continue iterating as long as a <code>nextCursor</code> is given in the response.</p>\n<pre><code>HEADERS = {\n &quot;user-agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36&quot;\n}\n\nALLOWED_SETTINGS = {x, y}\n\ndef handle_link(link, retries=3):\n for _ in range(retries):\n if parse(link, ALLOWED_SETTINGS):\n break\n\ndef parse(link, allowed_settings):\n response = requests.get(link, headers=HEADERS, stream=True)\n response.raw.decode_content = True\n parser = etree.HTMLParser()\n tree = etree.parse(response.raw, parser)\n setting = get_setting(tree)\n if setting not in allowed_settings: # we only want items which have a specific setting\n return False\n image = get_image(tree)\n if image is None:\n return False\n title = get_title(tree)\n file_name = get_file_name(title)\n description = get_description(tree)\n return save_image(image, file_name,\n {&quot;Xmp.xmp.Title&quot;: title, &quot;Xmp.xmp.Description&quot;: description})\n</code></pre>\n<p>Note that I aborted as soon as possible, no need to continue parsing if the <code>setting</code> already tells you that you will throw the result away.</p>\n<pre><code>def get_setting(tree):\n return tree.xpath(\n &quot;/html/body/div[1]/div/div/main/div/div[2]/div/div[2]/div/div/div[1]/a/span[1]/text()&quot;\n )[0].strip()\n\ndef get_image(tree):\n xpaths = [&quot;/html/body/div[1]/div/div/main/div/div[2]/div/div[1]/div[1]/div/div/a/@href&quot;,\n &quot;/html/body/div[1]/div/div/main/div/div[2]/div/div[1]/div[1]/div[1]/a/@href&quot;]\n for xpath in xpaths:\n try:\n return tree.xpath(xpath)[0]\n except Exception: \n continue\n print(f&quot;Image not found for link: {link}&quot;)\n\ndef get_title(tree):\n return tree.findtext(&quot;.//title&quot;)\n\ndef get_file_name(title):\n return (\n fr&quot;{os.getcwd()}\\IMAGES\\IMAGE - &quot; + &quot;&quot;.join(c for c in title if c in valid_chars) + &quot;.jpeg&quot;\n ) # sometimes the file contains characters which aren't allowed in file names\n\ndef get_description(tree):\n return &quot;&quot;.join(\n tree.xpath(\n &quot;/html/body/div[1]/div/div/main/div/div[3]/div[1]/div/div/div/div/p/text()&quot;\n )\n )\n\ndef save_image(url, file_name, metadata):\n try:\n image_req = requests.get(url)\n with open(file_name, &quot;wb&quot;) as f:\n f.write(image_req.content) # write the image to the directory\n img = pyexiv2.Image(file_name)\n img.modify_xmp(metadata)\n img.close()\n return True\n except Exception as e:\n print(\n f&quot;ERROR parsing image: {file_name}, it is most likely corrupt, &quot;\n f&quot;error: {e}&quot;\n )\n os.remove(file_name)\n return False\n</code></pre>\n<p>With this you could now start thinking about parallelization, since you actually have an encapsulated target function to execute.</p>\n<p>Since there are now also separate functions for getting some information, you can consider changing how you parse the links. I personally prefer using <code>BeautifulSoup</code> over <code>xpath</code>, as using CSS selectors on classes or IDs is IMO more readable than your lengthy paths.</p>\n<p>Note that in the end you will always be limited by your available internet connection. If you need to download 30 million 1 MB images with a 100Mbit/s internet connection, it will <a href=\"https://www.wolframalpha.com/input/?i=30E6%20*%201MB%20%2F%20100%20Mbit%2Fs\" rel=\"nofollow noreferrer\">take at least 27 days</a> and if you have a 1 Gbit/s connection it will still take almost three days no matter how you improve your code. If you download two images in parallel, each will just download at half the speed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T13:51:29.090", "Id": "504845", "Score": "2", "body": "Crikey, thanks so much a lot that's a lot of help! I actually have decided to use BeautifulSoup now, I didn't originally as from my experience it uses a lot more memory (https://stackoverflow.com/questions/11284643/python-high-memory-usage-with-beautifulsoup, for example) but in the end, the ease of BeautifulSoup outweighed the benefits of saving a small amount of memory using the lxml lib." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T13:53:17.063", "Id": "504846", "Score": "2", "body": "Just one small thing you might have done by accident, you have an accent in there in `ǵet_title(tree)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T12:00:30.973", "Id": "255753", "ParentId": "255699", "Score": "4" } } ]
{ "AcceptedAnswerId": "255753", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T20:14:02.777", "Id": "255699", "Score": "5", "Tags": [ "python", "performance", "web-scraping", "memory-optimization" ], "Title": "How to speed up scraping large amounts of data with Python" }
255699
<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-A function duplicatesNumber(text) { var counts = {}; let textLowered = text.toLowerCase(); textLowered.split("").forEach(function (x) { counts[x] = (counts[x] || 0) + 1; }); return Object.entries(counts).filter(arr =&gt; arr[1] &gt; 1).length } //Function-B function duplicateCount(text) { return text.toLowerCase().split('').filter(function (val, i, arr) { return arr.indexOf(val) !== i &amp;&amp; arr.lastIndexOf(val) === i; }).length; } //Function-B let start = performance.now(); console.log(duplicateCount("aaBBcDDcefgheeaas")) let end = performance.now(); console.log("Function-B: "+ (end-start)); //Function-A let start1 = performance.now(); console.log(duplicatesNumber("aaBBcDDcefgheeaas")) let end1 = performance.now(); console.log("Function-A: "+ (end1-start1)) </code></pre> </div> </div> </p> <ul> <li>I have two functions they both do the same thing. Return the number of duplicates.</li> <li>My question is about their performances. I have just started to learn data structures and algorithms in javascript. I covered Big O'Notation. But I didn't get it correctly I guess.</li> <li>Since Function-A has for each method which means it is O(n) clearly. Isn't that mean Function-A should be slower than the second one? How can be Function-A is faster than Function-B?</li> </ul>
[]
[ { "body": "<h2>Time Complexity</h2>\n<ul>\n<li>Function A cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span>\n<ul>\n<li><code>toLowerCase</code>, <code>split</code> cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span></li>\n<li><code>forEach</code> cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span></li>\n<li><code>Object.entries</code>, <code>filter</code> cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span>\n<ul>\n<li><code>counts[x]</code> read / write may cost <span class=\"math-container\">\\$\\mathcal{O}\\left(1\\right)\\$</span> on average</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Function B cost cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n^2\\right)\\$</span>\n<ul>\n<li><code>toLowerCase</code>, <code>split</code> still cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span></li>\n<li><code>filter</code> cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n^2\\right)\\$</span>\n<ul>\n<li><code>indexOf</code>, <code>lastIndexOf</code> cost <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span></li>\n<li><code>filter</code> repeat above operation <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\right)\\$</span> times, thus <span class=\"math-container\">\\$\\mathcal{O}\\left(n\\cdot n\\right)\\$</span></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>Time consume most occurred in loops. Not only <code>forEach</code>, <code>fliter</code>, but also <code>toLowerCase</code>, <code>split</code>, <code>indexOf</code> are loops. You didn't count the performance of nested loops correctly.</p>\n<p>Also, notice that big-O notation is targeted to describe how fast the time consume increase when size of input increase. It not necessarily means an algorithm with better big-O notation will always be faster.</p>\n<h2>Implementation</h2>\n<ul>\n<li>Do not use <code>str.split('')</code>, use <code>[...str]</code> if you can. The split one won't handle some unicode points correctly. For example, <code>[...'面'].length</code> is 3 but <code>'面'.split('').length</code> is 5.</li>\n<li>Use <code>Map</code> if you can (no need to support old browsers). <code>Object</code> is not an ideal way to use as a dictionary. Only if you want to keep ES5 support, you may use <code>Object.create(null)</code> instead.</li>\n<li>You may count how many entries has at least count 2 during iteration by tracking if <code>count[x] == 2</code> after increase. So there is no need to iterate <code>Object.entries</code> later.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T13:05:51.153", "Id": "504660", "Score": "0", "body": "Very clean and informative answer. I appreciate that!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T03:33:39.063", "Id": "255707", "ParentId": "255702", "Score": "4" } } ]
{ "AcceptedAnswerId": "255707", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T22:59:03.463", "Id": "255702", "Score": "0", "Tags": [ "javascript" ], "Title": "Evaluating two functions according to their performance" }
255702
<p>In Haskell, I tried to implement a parser for expressions containing <a href="https://en.wikipedia.org/wiki/Hyperoperation" rel="nofollow noreferrer">hyperoperations</a>, and finally succeeded. Valid expressions shall contain:</p> <ul> <li><p>Parentheses.</p> </li> <li><p>Nonnegative integers.</p> </li> <li><p>Addition represented by <code>+</code>. It has precedence of 6, and its associativity shall be exploited.</p> </li> <li><p>Multiplication represented by <code>*</code>. It has precedence of 7, and its associativity shall be exploited.</p> </li> <li><p>Exponentiation represented by <code>^</code>. It has precedence of 8.</p> </li> <li><p>Tetration represented by <code>^^</code>. It has precedence of 9.</p> </li> <li><p>Pentation represented by <code>^^^</code>. It has precedence of 10.</p> </li> <li><p><em>ad infinitum</em>.</p> </li> </ul> <p>I was struggling for months to implement this with <code>ReadPrec</code>. It was truly a &quot;Eureka&quot; moment when I found that I have a workaround:</p> <pre><code>import Control.Monad import Text.ParserCombinators.ReadPrec import Text.Read import Text.Read.Lex hyperOp :: Int -&gt; Integer -&gt; Integer -&gt; Integer hyperOp 0 _ y = y + 1 hyperOp 1 x y = x + y hyperOp 2 x y = x * y hyperOp 3 x y = x ^ y hyperOp n x 0 = 1 hyperOp n x y = hyperOp (n-1) x (hyperOp n x (y-1)) parseHyperOp :: Int -&gt; ReadPrec Integer parseHyperOp opn = parens . choice $ lift readDecP : prec 6 (do m &lt;- step (parseHyperOp opn) Symbol &quot;+&quot; &lt;- lexP n &lt;- parseHyperOp opn return (m + n)) : prec 7 (do m &lt;- step (parseHyperOp opn) Symbol &quot;*&quot; &lt;- lexP n &lt;- parseHyperOp opn return (m * n)) : fmap (\c -&gt; prec (7 + c) $ do m &lt;- step (parseHyperOp opn) Symbol op &lt;- lexP guard (replicate c '^' == op) n &lt;- step (parseHyperOp opn) return (hyperOp (2 + c) m n) ) [1 .. opn] highestOp :: String -&gt; Int highestOp &quot;&quot; = 0 highestOp ('^':str) = let (str1, str2) = span ('^'==) str in max (1 + length str1) (highestOp str2) highestOp (_ :str) = highestOp str parseOp :: Prec -&gt; ReadS Integer parseOp c str = readPrec_to_S (parseHyperOp (highestOp str)) c str </code></pre> <p>The trick is to find the highest operation within the input string. That makes the <code>choice</code> finite.</p> <p>Still, I think it's quite ugly to use <code>readPrec_to_S</code>. Can this be implemented without using <code>readPrec_to_S</code> and co?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T17:12:57.497", "Id": "504669", "Score": "0", "body": "\"Can this be implemented without using readPrec_to_S and co?\" I would cheekily answer \"remove the last two lines\". Why are you using `ReadS` and what is \"and co\"? And are you aware that a common way to parse arithmetic expressions is to use a stack?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T20:16:40.093", "Id": "504688", "Score": "0", "body": "@Li-yaoXia `parseHyperOp` is just an auxiliary function for implementing `parseOp`, and is not to be used on its own. I tried implementing `parseOp` without using `readPrec_to_S` and `readS_to_Prec` because using them might cause potential runtime errors thereafter (say, by invoking `gather`). And I don't know whether Haskell *has* stacks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T08:42:34.040", "Id": "504718", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>A simple rule of thumb is that you should never use <code>readS_to_Prec</code> and <code>readS_to_P</code>. Consider that once you've converted a parser to a <code>ReadS</code> to run it, there is no way back. (One handwavy explanation is that those functions are really dirty hacks, which is also why <code>gather</code> is undefined when they are used.)</p>\n<p>Under those constraints, the only place where you can find out the maximal level <code>opn</code> of hyperoperators is at the very top level where you actually apply your parser to a string; that is the one location where you can scan the string to compute <code>opn</code>. That means that all your parsers need to be parameterized by <code>opn</code> in order to pass it down to <code>parseHyperOp</code>.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>parseOp :: Int -&gt; P.ReadP Integer\nparseOp opn = readPrec_to_P (parseHyperOp opn) 0\n\n-- Top-level runner for parsers parameterized by opn\nrunP :: (Int -&gt; P.ReadP a) -&gt; ReadS a\nrunP parser str =\n let opn = highestOp str in\n P.readP_to_S (parser opn) str\n\nexample = runP parseOp &quot;(1 + 2) ^ 3 + 2 ^ 2&quot;\n</code></pre>\n<p>Having an infinite number of precedence levels makes top-down parsing (the popular approach using parser combinators) rather problematic, since there isn't really a &quot;top&quot; to start from. Consider giving up that feature (by making all operators beyond a certain level non-associative at the same level), or switching to <a href=\"https://en.wikipedia.org/wiki/Operator-precedence_parser\" rel=\"nofollow noreferrer\">a bottom-up parsing strategy</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T23:15:48.837", "Id": "255739", "ParentId": "255704", "Score": "2" } } ]
{ "AcceptedAnswerId": "255739", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T00:14:41.703", "Id": "255704", "Score": "2", "Tags": [ "parsing", "haskell" ], "Title": "Can this parser (concerning about infinite hierarchy of operators) be implemented purely in ReadPrec?" }
255704
<p>I am a JavaScript programmer beginning with Go. I tried to replicate <code>filter</code> and <code>map</code> functions like JavaScript's, as an exercise.</p> <p>Here is what I came up with.</p> <p>The <code>filter</code> function:</p> <pre><code>func Filter(slice interface{}, cb func(i interface{}) bool) []interface{}{ sliceValues := reflect.ValueOf(slice) newSlice := []interface{}{} for i := 0; i &lt; sliceValues.Len(); i++{ v := sliceValues.Index(i).Interface() passed := cb(v) if passed{ newSlice = append(newSlice, v) } } return newSlice } </code></pre> <p>Usage:</p> <pre><code>a := []int {1,2,3} result := Filter(a,func(i interface{}) bool{ v,_:= i.(int) return v &gt; 1 }) fmt.Println(result) // [2 3] </code></pre> <p>The <code>map</code> function:</p> <pre><code>func Map(slice interface{}, cb func(i interface{}) interface{}) []interface{}{ sliceValues := reflect.ValueOf(slice) newSlice := []interface{}{} for i := 0; i &lt; sliceValues.Len(); i++{ v := sliceValues.Index(i).Interface() modifiedValue := cb(v) newSlice = append(newSlice, modifiedValue) } return newSlice </code></pre> <p>}</p> <p>Usage:</p> <pre><code>a := []int {1,2,3} result := Map(a,func(i interface{}) interface{}{ v,_:= i.(int) return v + 1 }) fmt.Println(result) // [2 3 4] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:37:21.760", "Id": "505699", "Score": "0", "body": "Why are you reinventing the wheel?" } ]
[ { "body": "<p>From a mathematics and science genius:</p>\n<blockquote>\n<p>&quot;If I have seen further it is by standing on the shoulders of Giants.&quot; Isaac Newton</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Standing_on_the_shoulders_of_giants\" rel=\"nofollow noreferrer\">Wikipedia: Standing on the shoulders of giants</a></p>\n</blockquote>\n<p>For Go giants, you might start with Rob Pike.</p>\n<blockquote>\n<p><a href=\"https://github.com/robpike/filter\" rel=\"nofollow noreferrer\">GitHub - robpike/filter: Simple apply/filter/reduce package.</a></p>\n<p>I wanted to see how hard it was to implement this sort of thing in Go, with as nice an API as I could manage. It wasn't hard.</p>\n<p>Having written it a couple of years ago, I haven't had occasion to use it once. Instead, I just use &quot;for&quot; loops.</p>\n<p>You shouldn't use it either.</p>\n</blockquote>\n<p>Take Rob Pike's advice and use &quot;for&quot; loops.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T15:46:07.620", "Id": "504662", "Score": "1", "body": "OK, but my goal isn't just to make the functions. I need someone to point mistakes in my code so I can address them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T13:47:02.743", "Id": "255720", "ParentId": "255705", "Score": "0" } }, { "body": "<p>This answer is presuming your Filter and Map should take a slice given the first argument's name. There are other types that reflect's <code>Len()</code> works on which I'm ignoring for this answer. If you want to accept other types, I would suggest changing the name of the first argument to the functions to not be ‘slice’.</p>\n<ul>\n<li>Use <code>gofmt</code> (or derivative e.g. <code>goimports</code>) to consistently format your code. Your indentation is incorrect and there are spaces missing before open braces for blocks.</li>\n<li>Function parameter types should be restricted to the actual type expected by the function. Your functions take a parameter named <code>slice</code> but with type <code>interface{}</code>. Since this has to be a slice, you can restrict the type of the parameter to be <code>[]interface{}</code>, requiring that a slice is passed in rather than anything.</li>\n<li>Using a slice as the function parameter type means you can iterate using <code>range</code>. You then don't need reflection for this job.</li>\n<li>You're using <code>i</code> for the for loop's iteration variable name, but also using <code>i</code> as the name of the argument to the callback which is actually the element not the index. Using two different parameter names (or removing the parameter name) would make it clearer that the callback is passed the element (<code>v</code>) not the index.</li>\n</ul>\n<pre class=\"lang-golang prettyprint-override\"><code>func Filter(slice []interface{}, cb func(interface{}) bool) []interface{} {\n newSlice := []interface{}{} \n for _, v := range slice { \n if cb(v) { \n newSlice = append(newSlice, v)\n } \n } \n return newSlice \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T07:06:23.033", "Id": "256667", "ParentId": "255705", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T02:13:50.890", "Id": "255705", "Score": "0", "Tags": [ "beginner", "go" ], "Title": "filter and map functions" }
255705
<p>I have an array of dim <code>1000 x 150</code> where I have 1000 strings each of length 150. And the strings only contain <code>ATCGN</code> (these are DNA sequences).</p> <p>I am converting the letters to one-hot vectors such that <code>A</code> is <code>[1,0,0,0,0]</code> and <code>N</code> is <code>[0,0,0,0,1]</code>.</p> <p>I wrote the following code but it takes way too long when there are about 20 million strings.</p> <pre><code>def seqs2onehot(seqs, num_val): def one_hot_encode(seq): mapping = dict(zip(&quot;ACGTN&quot;, range(num_val))) seq = [mapping[i] for i in seq] return np.eye(num_val)[seq] onehotvecs = [] for i in seqs: onehotvecs.append(np.array(one_hot_encode(i), dtype='bool')) return onehotvecs </code></pre> <p>To generate input:</p> <pre><code>num_inputs = 1000 inputs = [] for num in range(num_inputs): inputs.append(''.join(random.choice('ATCGN') for i in range(150))) </code></pre> <p>Outputs are of dimension <code>1000 x 150 x 5 x 1</code>. You can create the final outputs by doing this:</p> <pre><code>inputs = np.array(inputs) inputs = np.expand_dims(np.array(seqs2onehot(inputs, 5)), -1) inputs.shape </code></pre> <p>Is there a way to do this without iterating through the list and just using matrix operations?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:49:53.233", "Id": "504744", "Score": "0", "body": "Can you provide an example of the expected formats for the input and output? I think that would help make this a bit clearer regarding your intentions. Otherwise, I'd say one of your main hangups is in using `append` 20 million times on a list. If you know your final size, pre-allocate your memory. Similarly, you do a lot of \"regeneration on the fly\" for things that could be defined statically and reused rather than created, used, and discarded, only to be re-created every single iteration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T20:07:59.493", "Id": "504776", "Score": "0", "body": "@zephyr good idea, I've added in input output code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T04:36:04.320", "Id": "504807", "Score": "1", "body": "What is the rationale for using “one hot vectors”? What is the rationale for encoding them in the way you have?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T18:12:43.467", "Id": "504877", "Score": "0", "body": "This is for a neural net that I'm training. But even otherwise, I come across similar coding problems and by learning through this example, I can extend it elsewhere..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T07:16:48.303", "Id": "255710", "Score": "2", "Tags": [ "python", "performance", "matrix" ], "Title": "Converting list of sequences into one-hot vectors" }
255710
<p>I am building a PowerShell class based tool that works with XML files of as much as a few hundred Kb size, and as many as a hundred of these files. I have extensive validation code that is time consuming, so I want to validate the XML and if it is valid hash it and write that hash as an attribute to the root element. My code can then hash on load, compare with that value and skip validation when possible. This is a pretty major speed improvement. To that end, I have this static method of my xml class.</p> <pre><code>static [String] GetHash ([Xml.XmlDocument]$xmlDocument) { $stringBuilder = [Text.StringBuilder]::new() $hashBuilder = [Security.Cryptography.MD5CryptoServiceProvider]::new() #[Security.Cryptography.SHA384CryptoServiceProvider] $encoding = [Text.Encoding]::UTF8 $xmlToHash = [Xml.XmlDocument]::new() $xmlToHash.AppendChild($xmlToHash.ImportNode($xmlDocument.DocumentElement, $true)) $string = [pxXML]::ToString($xmlToHash) $hashIntermediate = $hashBuilder.ComputeHash($encoding.GetBytes($string)) foreach ($intermediate in $hashIntermediate) { $stringBuilder.Append($intermediate.ToString('x2')) } return $stringBuilder.ToString() } </code></pre> <p>As well as this static <code>.ToString()</code> method that is used by the hasher and also used for writing results to the console in testing.</p> <pre><code>static [String] ToString ([Xml]$Xml) { $toString = [System.Collections.Generic.List[String]]::new() $stringWriter = [IO.StringWriter]::new() $xmlWriter = [Xml.XmlTextWriter]::new($stringWriter) $xmlWriter.Formatting = &quot;indented&quot; $xmlWriter.Indentation = 4 $Xml.WriteTo($xmlWriter) $xmlWriter.Flush() $stringWriter.Flush() $toString.Add($stringWriter.ToString()) $toString.Add(&quot;`r&quot; * 2) return [string]::Join(&quot;`n&quot;, $toString) } </code></pre> <p>As you might notice from the commented part of the <code>$hashBuilder</code> line, I have tested this with different algorithms, and there is little difference in performance. Which is a bit of a surprise. So I wonder if there is something else her that I am missing, that is the the/an actual bottleneck? Or is this code actually reasonable close to optimal performance already? Given that I am totally new to classes and digging this deep into .NET, I suspect there is a bit to learn here beyond just optimizing this code.</p>
[]
[ { "body": "<p>In general I don't really see the value in not defining an XSD or DTD and validating against that when loading it with an <code>XmlReader</code>, which feels most correct. You should be able to instance one <code>XmlSchemaSet</code> and compile it. Then that can be repeatedly used to validate the documents without reloading the schema, and that should perform well. That feels like the most correct solution. If you want valid data the most correct thing to do is to validate it. That covers every situation where your goal is to have valid data.</p>\n<p>What you're doing here just feels like a home grown <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-sign-xml-documents-with-digital-signatures\" rel=\"nofollow noreferrer\">XML digital signature</a>, so your method just raises conceptual concerns to me. If I were to look at what you're doing, I'd be confused by what you were trying to accomplish.</p>\n<p>If you just want to be able to verify what files you've previously validated, I'd prefer just maintaining a CSV file or database with the output of <code>Get-FileHash</code> and some file metadata. That seems much less complicated and doesn't require modifying the XML files.</p>\n<hr />\n<p>However, taking the code as face value, you <em>may</em> see some performance improvement like this on the first method:</p>\n<pre><code>static [String] GetHash ([Xml.XmlDocument]$xmlDocument) {\n $stringBuilder = [System.Text.StringBuilder]::new(32)\n\n $hashBuilder = [System.Security.Cryptography.HashAlgorithm]::Create('md5')\n $xmlToHash = [Xml.XmlDocument]::new()\n $xmlToHash.AppendChild($xmlToHash.ImportNode($xmlDocument.DocumentElement, $true))\n $hashBuilder.ComputeHash([System.Text.StringBuilder]::UTF8.GetBytes([pxXML]::ToString($xmlToHash))).ForEach({\n $stringBuilder.Append($_.ToString('x2'))\n })\n\n return $stringBuilder.ToString()\n}\n</code></pre>\n<p>When you know the length of the <code>StringBuilder</code> you can instance it with that initial capacity. MD5s are always 32 characters. That saves having to expand capacity.</p>\n<p>The <code>ComputeHash()</code> method is an inherited method from the <code>HashAlgorithm</code> class. You don't gain anything by instancing a more complex child class because you don't use it for anything else. You're just calling a hash function; there's nothing inherently cryptographic about what you're doing.</p>\n<p>The <code>.ForEach({})</code> collection method is somewhat higher performant in most cases, although it makes for less readable code and is more obscure.</p>\n<p>Eliminating variables that are only used once also tends to improve performance. Indeed, you could also just call <code>[System.Security.Cryptography.HashAlgorithm]::Create('md5').ComputeHash(...)</code>, but it's getting a bit hard to read on StackOverflow.</p>\n<p>Offhand, I'm not sure if <code>$stringBuilder.AppendFormat('{0:x2}',$_)</code> is better or worse than <code>$stringBuilder.Append($_.ToString('x2'))</code>, but I believe the latter is better here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-19T15:47:41.340", "Id": "259729", "ParentId": "255713", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T08:37:34.060", "Id": "255713", "Score": "0", "Tags": [ "performance", "powershell", "hashcode" ], "Title": "Optimizing PowerShell string hasher method" }
255713
<p>The aim is to provide a generic functor class which makes references able to bind to r-values. The trick is to trick the compiler into thinking that the r-value is an l-value by using a forwarding references. Here is the code:</p> <pre><code>#include &lt;type_traits&gt; template &lt;typename Functor&gt; struct Function { Functor func; template &lt;typename ...Args&gt; inline auto operator() (Args&amp;&amp;... args) { //I tried to provide a suitable error message if args were not valid parameters, but I can't get it to work... //static_assert(std::is_invocable_v&lt;Functor, Args...&gt;); return func(args...); } }; </code></pre> <p>Example use case:</p> <pre><code># include &lt;iostream&gt; # include &lt;vector&gt; int main () { // Define function auto push_back = Function([] (std::vector&lt;int&gt;&amp; vec, int num) {vec.push_back(num); return vec;}); auto x = std::vector{1 , 2 ,3 , 4}; // Works on l-values push_back(x, 5); std::cout &lt;&lt; x[4] &lt;&lt; '\n'; // 5 // Works on r-values auto y = push_back(std::vector{1 ,2 , 3 , 4 , 5}, 6); std::cout &lt;&lt; y[5] &lt;&lt; '\n'; // 6 return 0; } </code></pre> <p>And finally, one can do this if you want to use old-style c functions:</p> <pre><code>template &lt;typename R, typename ...Args&gt; inline auto CFunc(R (*iFunc) (Args...)) { return Function&lt;R (*) (Args...)&gt;(iFunc); } </code></pre> <p>Is this robust code? Are there edge cases I need to be aware about with which my functor class does not work? Also, how could I provide more suitable error messages, eg when <code>typename Functor</code> is not a functor, or when <code>args...</code> are not suitable parameters?</p>
[]
[ { "body": "<p>Assuming C++20, we can constrain the template (similar to your attempt at <code>static_assert</code>). The key is that <code>Args...</code> can contain rvalue-references, but we need to convert those to lvalue types, because that's what we present to the function:</p>\n<pre><code>#include &lt;concepts&gt;\n</code></pre>\n\n<pre><code> template&lt;typename... Args&gt;\n inline auto operator()(Args&amp;&amp;... args)\n requires std::invocable&lt;Functor, std::add_lvalue_reference_t&lt;Args&gt;...&gt;\n</code></pre>\n<p>I don't see anything else I would propose improving.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T12:48:12.363", "Id": "255718", "ParentId": "255715", "Score": "3" } } ]
{ "AcceptedAnswerId": "255718", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T10:23:33.467", "Id": "255715", "Score": "2", "Tags": [ "c++" ], "Title": "Ultimate functor class which can read/write to l-values/r-values" }
255715
<p>So I have the following code, that takes an image and modifies the RGB channels one at a time. It then creates a list of 9 images with the various modified channels.</p> <p>The Red channel is modified by 0.1, then by 0.5, then by 0.9. This is then applied to the Green channel then the Blue Channel.</p> <p>Resulting in a list of 9 images with the same modifications, but to different channels. The code works, but I just feel like there is a lot of repetition, and this really bugs me.</p> <pre><code>#%% from PIL import Image # Set the file and open it file = &quot;Final/charlie.png&quot; #Create an empty list to append the images to images = [] #Image processing function, depending on the counter def image_processing0(a): if count == 0 or count == 3 or count == 6: c = int(a * 0.1) return c elif count == 1 or count == 4 or count == 7: c = int(a * 0.5) return c elif count == 2 or count == 5 or count == 8: c = int(a * 0.9) return c #Set the count to 0 count = 0 #Create PixelMap while count &lt;9: #Creat Pic at the start of each loop pic = Image.open(file) #Convert the image to RGB, so we dont have to deal with the alpha channel pic = pic.convert('RGB') #Get the RGB value for every pixel for x in range(pic.size[0]): for y in range(pic.size[1]): #Split the RGB value into variables r, g and b r,g,b = pic.getpixel((x,y)) #Check the count, use logic to appy the processing to the correct channel if count &lt;3: r = image_processing0(r) pic.putpixel((x,y),(r,g,b)) elif count &lt; 6: g = image_processing0(g) pic.putpixel((x,y),(r,g,b)) elif count &lt; 9: b = image_processing0(b) pic.putpixel((x,y),(r,g,b)) #Add the images to the list images.append(pic) #Increment the counter count+=1 </code></pre> <p>Both my logic statement, and my function seem a bit repetitive:</p> <pre><code> #--------------------------------------------------- #Image processing function, depending on the counter def image_processing0(a): if count == 0 or count == 3 or count == 6: c = int(a * 0.1) return c elif count == 1 or count == 4 or count == 7: c = int(a * 0.5) return c elif count == 2 or count == 5 or count == 8: c = int(a * 0.9) return c #--------------------------------------------------- #Check the count, use logic to apply the processing to the correct channel if count &lt;3: r = image_processing0(r) pic.putpixel((x,y),(r,g,b)) elif count &lt; 6: g = image_processing0(g) pic.putpixel((x,y),(r,g,b)) elif count &lt; 9: b = image_processing0(b) pic.putpixel((x,y),(r,g,b)) #--------------------------------------------------- </code></pre> <p>I tried to change my logic to the following, but soon realized that when I put the pixel back, i had no way to specify exactly what channel I was placing back in the pic.putpixel((x,y),(r,g,b)) statement.</p> <pre><code>if count &lt;3: channel = r elif count &lt; 6: channel = g elif count &lt; 9: channel = b channel = image_processing0(channel) pic.putpixel((x,y),(r,g,b)) #No way to define which channel is being changed </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:05:25.023", "Id": "504739", "Score": "1", "body": "Entirely separately from the organisation of your code: multiplying sRGB coordinates by a constant fraction may not achieve what you want. See https://blog.johnnovak.net/2016/09/21/what-every-coder-should-know-about-gamma/" } ]
[ { "body": "<p>For the <code>image_processing0</code> function:</p>\n<ol>\n<li><p>You can replace things like <code>if a == x or a == y or a == z</code> with a simple <code>if a in [x, y, z]</code></p>\n</li>\n<li><p>The <code>elif</code> statements aren't necessary, as the <code>return</code> statements in the previous conditions already made sure that the other statements will only be evaluated if the previous condition didn't meet.</p>\n</li>\n</ol>\n<p>From:</p>\n<pre><code>def image_processing0(a):\n if count == 0 or count == 3 or count == 6:\n c = int(a * 0.1)\n return c\n elif count == 1 or count == 4 or count == 7:\n c = int(a * 0.5)\n return c\n elif count == 2 or count == 5 or count == 8:\n c = int(a * 0.9)\n return c\n</code></pre>\n<p>To:</p>\n<pre><code>def image_processing0(a):\n if count in [0, 3, 6]:\n c = int(a * 0.1)\n return c\n if count in [1, 4, 7]:\n c = int(a * 0.5)\n return c\n if count in [2, 5, 8]:\n c = int(a * 0.9)\n return c\n</code></pre>\n<p>For the <code>while</code> loop:</p>\n<ol>\n<li><p>Instead of using a <code>while</code> loop and constantly incrementing a variable to determine when to end the looping,\nuse a <code>for</code> loop with the built-in <code>range()</code> method:</p>\n</li>\n<li><p>As the <code>count</code> variable will never reach the <code>if</code> - <code>elif</code> statements without satisfying one of them, it is safe\nto unindent the repetitive line to where the <code>if</code> - <code>elif</code> statements end.</p>\n</li>\n</ol>\n<p>From:</p>\n<pre><code>count = 0\n\nwhile count &lt; 9:\n pic = Image.open(file)\n pic = pic.convert('RGB')\n for x in range(pic.size[0]):\n for y in range(pic.size[1]):\n r, g, b = pic.getpixel((x, y))\n if count &lt; 3:\n r = image_processing0(r)\n pic.putpixel((x, y), (r, g, b))\n elif count &lt; 6:\n g = image_processing0(g)\n pic.putpixel((x, y), (r, g, b))\n elif count &lt; 9:\n b = image_processing0(b)\n pic.putpixel((x, y), (r, g, b))\n \n images.append(pic) \n count += 1 \n</code></pre>\n<p>To:</p>\n<pre><code>for count in range(9):\n pic = Image.open(file)\n pic = pic.convert('RGB')\n for x in range(pic.size[0]):\n for y in range(pic.size[1]):\n r, g, b = pic.getpixel((x, y))\n if count &lt; 3:\n r = image_processing0(r)\n elif count &lt; 6:\n g = image_processing0(g)\n elif count &lt; 9:\n b = image_processing0(b)\n pic.putpixel((x, y), (r, g, b))\n \n images.append(pic) \n</code></pre>\n<p>So altogether:</p>\n<pre><code>file = &quot;Final/charlie.png&quot;\nimages = []\n\ndef image_processing0(a):\n if count in [0, 3, 6]:\n c = int(a * 0.1)\n return c\n if count in [1, 4, 7]:\n c = int(a * 0.5)\n return c\n if count in [2, 5, 8]:\n c = int(a * 0.9)\n return c\n \nfor count in range(9):\n pic = Image.open(file)\n pic = pic.convert('RGB')\n for x in range(pic.size[0]):\n for y in range(pic.size[1]):\n r, g, b = pic.getpixel((x, y))\n if count &lt; 3:\n r = image_processing0(r)\n elif count &lt; 6:\n g = image_processing0(g)\n elif count &lt; 9:\n b = image_processing0(b)\n pic.putpixel((x, y), (r, g, b))\n \n images.append(pic) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T16:24:41.067", "Id": "504665", "Score": "0", "body": "Thank you kindly for the great information, and flow of logic. This certainly helps me think and lean. Have a great weekend." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T01:55:07.283", "Id": "504705", "Score": "0", "body": "The elif statements can be made into ifs, but I'd prefer to leave them as elif statements, as it visually indicates to any future readers that these statements are joined and mutually exclusive. Sure that's obvious to anyone with half a brain in this particular code snippet, but for a more complex piece of code it might not be, and as far as I know there's no cost to leaving them as elif." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T13:30:45.003", "Id": "255719", "ParentId": "255717", "Score": "4" } }, { "body": "<p>Chocolate's advice for reducing repetition is excellent, but we can go further.</p>\n<p>We'll start with their version of the <code>image_processing0</code> function.</p>\n<pre><code>def image_processing0(a):\n if count in [0, 3, 6]:\n c = int(a * 0.1)\n return c\n if count in [1, 4, 7]:\n c = int(a * 0.5)\n return c\n if count in [2, 5, 8]:\n c = int(a * 0.9)\n return c\n</code></pre>\n<p>First, the <code>if</code> checks can be simplified</p>\n<pre><code>def image_processing0(a):\n if count%3 == 0: # 0, 3, 6\n c = int(a * 0.1)\n return c\n if count%3 == 1: # 1, 4, 7\n c = int(a * 0.5)\n return c\n if count%3 == 2: # 2, 5, 8\n c = int(a * 0.9)\n return c\n</code></pre>\n<p>Now, notice that the only difference between these <code>if</code> blocks is the value of the modifier.</p>\n<pre><code>def image_processing0(a):\n if count%3 == 0: # 0, 3, 6\n mod = 0.1\n if count%3 == 1: # 1, 4, 7\n mod = 0.5\n if count%3 == 2: # 2, 5, 8\n mod = 0.9\n c = int(a * mod)\n return c\n</code></pre>\n<p>This in turn opens us up to a clever little shortcut where you can use a <code>dict</code> as a simple case statement</p>\n<pre><code>MODIFIERS = {0:0.1, 1:0.5, 2:0.9}\ndef image_processing0(a):\n mod = MODIFIERS[count%3]\n c = int(a * mod)\n return c\n</code></pre>\n<p>In this particular case, the keys to the <code>dict</code> are the same as the indexes of a <code>list</code>, so we can use a <code>list</code> instead. Also, I've taken the liberty of adding <code>count</code> as an argument in preference to referencing it as a global variable, and condensing the <code>return</code> statement into the previous line.</p>\n<pre><code>#Image processing function, depending on the counter\nMODIFIERS = [0.1, 0.5, 0.9]\ndef image_processing0(a, count):\n mod = MODIFIERS[count%3]\n return int(a * mod)\n</code></pre>\n<p>We can use a similar trick to simplify which color is being modified</p>\n<pre><code>#Don't split the colors, but keep them in a single list\ncolors = list(pic.getpixel((x,y)))\n \n#Get the index needed from the count\nidx = count//3\n\n#Set that color to its modified value\ncolors[idx] = image_processing0(colors[idx], count)\n\n#Set the pixel to its modified color\npic.putpixel((x,y), colors)\n</code></pre>\n<p>Bring it all together, and you have your new script!</p>\n<pre><code>#%%\n\nfrom PIL import Image\n\n# Set the file and open it\nfile = &quot;Final/charlie.png&quot;\n\n#Create an empty list to append the images to\nimages = []\n\nMODIFIERS = [0.1, 0.5, 0.9]\nCOLOR_MODEL = 'RGB'\n\n#Image processing function, depending on the counter\ndef image_processing0(a, count):\n mod = MODIFIERS[count%len(MODIFIERS)]\n return int(a * mod)\n\n#Create PixelMap\nfor count in range(len(COLOR_MODEL)*len(MODIFIERS)):\n#Creat Pic at the start of each loop\n pic = Image.open(file)\n#Convert the image to RGB, so we dont have to deal with the alpha channel\n pic = pic.convert(COLOR_MODEL)\n \n#Get the RGB value for every pixel\n for x in range(pic.size[0]):\n for y in range(pic.size[1]):\n\n #Get the pixel colors\n colors = list(pic.getpixel((x,y)))\n \n #Set new colors\n idx = count//len(MODIFIERS)\n colors[idx] = image_processing0(colors[idx], count)\n pic.putpixel((x,y),colors)\n\n#Add the images to the list \n images.append(pic)\n</code></pre>\n<p>No repetitive <code>if</code> statements at all!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T11:01:47.247", "Id": "504723", "Score": "1", "body": "Kinda odd to split the modifiers information to inside/outside the function (outside the values, inside how to pick one (especially that there are three)). I'd just do `mod = (0.1, 0.5, 0.9)[count % 3]` inside the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T03:07:57.820", "Id": "504803", "Score": "0", "body": "@KellyBundy There's a minor computational gain by not having to recreate the list every time the function is called, but if you care about speed and efficiency you should really be using a numpy solution like yours anyways. More importantly, I like to pull the 'magic numbers' out of my functions and define them as constants before hand, where they're easy to adjust." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:55:33.167", "Id": "504827", "Score": "0", "body": "Thank you kindly, its been a huge learning journey for me to see all of these alternative approaches. I will experiment with them in order to gain a little more skill." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T13:37:00.593", "Id": "504843", "Score": "0", "body": "*\"not having to recreate the list every time\"* - That's why I made it a *tuple*. So that [it's just a LOAD_CONST](https://tio.run/##ZY3BCsMgGIPvPkUuAx1FHGWwDfYkYxSprvsP/oraw57e2l4XSE5fkvSr38jjLeXWKKSYKxwVIZz/gIJd/JRynH0pxIuRdsAcV67qIdAVosMT0ujLAKOve9zV6yBwwvg@oOzrmhnEVVqc947q81R0t/y7UK1t). And you still have the magic number 3 inside the function, separate from the magic data in your list outside the function even though they rather belong together." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T13:53:52.267", "Id": "504847", "Score": "0", "body": "Did a [benchmark](https://tio.run/##bZFNa8MwDIbv/hW6lNohhIbSsRV62wY9jMF2DMGkjdMaYsfYCmP785ntZk0/JkiMJT2vXiXmG4@dXj4aOwyN7RSgVEIiSGU6i2CFERUS8vb@vH3dvnx8wgaKRZansMhW4fVUklo08CXxyA9tt6taKtmagA8rsLcazmghSzI17zvtkGNvWnFL0KsB7JprpcNb4MZRBJpe7513e@EsvZucTpqEjCvX0pGmsxAEQOp4utM4Y6VGGhIZ57pSgnMWC57J/BNL7KKVEYIuuCiKEoIoPyuW5Hy3lT4Iuhx3@pudArpQ/ZEm6rqQcGNTCPS6Smp6@ke0rdSurtaRpTlLQfdqJ@xmBQnkiyR5YGxCXVYZI3RNcUqeLCd0PqtBOZjDDGgulh5HFl1hsIPOS//zCcaFh@EX) now, my constant-tuple way actually looks slightly *faster* than yours (see the three last lines on the bottom of the output)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T17:07:58.773", "Id": "504864", "Score": "0", "body": "@KellyBundy I didn't know that tuples were faster, but it makes sense. I most commonly use this trick with dicts, where a tuple wouldn't work." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T01:51:08.450", "Id": "255742", "ParentId": "255717", "Score": "2" } }, { "body": "<p>You can handle RGB channels as a single variable <code>color</code>. And your function receives a color, not a channel, returns processed color.</p>\n<p>And, you had combined two loops into one <code>for count in range(9)</code>. They should be <code>for factor in [0.1, 0.5, 0.9]</code> and <code>for channel in range(3)</code>. <code>count</code> is meaningless in the loop. But <code>factor</code> and <code>channel</code> are useful. So you do not need to calculate <code>factor</code> and <code>channel</code> variable from <code>count</code> later.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from PIL import Image\n\ndef convert_color(factor, channel):\n def convert(color):\n return (\n *color[:channel],\n int(color[channel] * factor),\n *color[channel + 1:]\n )\n return convert\n\npic = Image.open('image.png').convert('RGB')\nprocessed = []\nfor channel in range(3): # which channel\n for factor in [0.1, 0.5, 0.9]: # factor to multiple\n new_pic = Image.new('RGB', pic.size)\n new_pic.putdata(list(map(\n convert_color(factor, channel),\n pic.getdata()\n )))\n processed.append(new_pic)\n new_pic.save(f'image{len(processed)}.png')\n</code></pre>\n<p>Just one more thing (not related to duplicated codes): <code>getpixel</code> and <code>setpixel</code> may slow. Use <code>getdata</code>, <code>putdata</code> as above code would be a better choice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:56:39.140", "Id": "504828", "Score": "0", "body": "I never thought of it this way, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T06:40:22.700", "Id": "255745", "ParentId": "255717", "Score": "5" } }, { "body": "<p>Some style advice and much simpler/shorter/faster solutions.</p>\n<h1>Style</h1>\n<p>Your comments break the structure, making the code harder to read. <a href=\"https://www.python.org/dev/peps/pep-0008/#block-comments\" rel=\"noreferrer\">As PEP 8 says</a>:</p>\n<blockquote>\n<p>Block comments [...] are <strong>indented</strong> to the same level as that code. Each line of a block comment starts with a # and a single <strong>space</strong></p>\n</blockquote>\n<p>So</p>\n<pre><code>while count &lt;9:\n#Creat Pic at the start of each loop\n pic = Image.open(file)\n#Convert the image to RGB, so we dont have to deal with the alpha channel\n pic = pic.convert('RGB')\n</code></pre>\n<p>becomes</p>\n<pre><code>while count &lt;9:\n # Create pic at the start of each loop\n pic = Image.open(file)\n # Convert the image to RGB, so we dont have to deal with the alpha channel\n pic = pic.convert('RGB')\n</code></pre>\n<p>and I might remove the first comment, as it, unlike the second comment, doesn't contain any insight that's not easily seen in the code anyway.</p>\n<h1>NumPy</h1>\n<p>Taking <a href=\"https://codereview.stackexchange.com/a/255745/219610\">tsh's solution</a> further, to NumPy:</p>\n<pre><code>from PIL import Image\nimport numpy as np\n\nfile = &quot;Final/charlie.png&quot;\n\nim = Image.open(file).convert('RGB')\nimages = []\nfor channel in range(3):\n for factor in 0.1, 0.5, 0.9:\n data = np.copy(im)\n ch = data[:, :, channel]\n np.multiply(ch, factor, ch, casting='unsafe')\n images.append(Image.fromarray(data))\n</code></pre>\n<h1><code>Image.convert</code> with matrix</h1>\n<p>Or using <a href=\"https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.convert\" rel=\"noreferrer\"><code>convert</code></a>'s <code>matrix</code> parameter:</p>\n<pre><code>from PIL import Image\n\nfile = &quot;Final/charlie.png&quot;\n\nim = Image.open(file)\nimages = []\nfor channel in range(3):\n for factor in 0.1, 0.5, 0.9:\n matrix = [1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0]\n matrix[channel * 5] = factor\n images.append(im.convert('RGB', matrix))\n</code></pre>\n<h1>Speeds</h1>\n<p>Using some 575 x 575 sample image, I got roughly these times per new image:</p>\n<ul>\n<li>Yours: 2.9 seconds</li>\n<li>tsh's: 0.8 seconds</li>\n<li>My NumPy one: 0.003 seconds</li>\n<li>My <code>convert</code> one: 0.005 seconds</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T12:11:14.550", "Id": "504728", "Score": "0", "body": "I like the `convert` method used here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:53:13.570", "Id": "504825", "Score": "0", "body": "Thank you for the feedback, I have learnt a lot from this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T09:54:44.687", "Id": "255747", "ParentId": "255717", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T12:39:31.283", "Id": "255717", "Score": "5", "Tags": [ "python", "beginner", "image" ], "Title": "My code changes a single RGB value by a set amount, then does the same changes over the other channels" }
255717
<p>I'm looking for a way to speed this code up. It took about 4.5 hours to run on ~20k decks. I'm open to restructuring my SQL query, but feel adjusting the python would be more effective. The goal of this code is to see how many times a pair of cards occurs in all the decks. For example if <code>(&quot;card&quot;, &quot;name&quot;)</code> appears in 27/100 decks, it returns .27.</p> <p>This code takes every deck in a format, and returns the cards in those decks. This gives me a list of a lot of cards <code>((cardId, &quot;card name&quot;, deckId), ... (cardId &quot;card name&quot;, deckId))</code>. I use the <code>deckId</code> to make a bunch of lists representing each deck (<code>newList</code>). Using those lists I get each unique card and put it into a separate list (<code>superSet</code>).</p> <p>From there I loop through <code>superSet</code> twice to get each possible pair. Then loop through <code>newList</code> to see if a pair is in a deck.</p> <p>I know it's somewhat complicated and I probably didn't explain it the best. I'll gladly update this post to clarify anything I can.</p> <pre><code>from classes.general import Database def main(): dbm = Database() with dbm.con: dbm.cur.execute(&quot;&quot;&quot;SELECT c.id, c.name, ctd.deckId FROM cards c JOIN cardToDeck ctd ON ctd.cardId = c.id JOIN deckToEvent dte ON dte.deckId = ctd.deckId JOIN eventToFormat etf ON etf.eventId = dte.eventId WHERE etf.formatId = 5 ORDER BY ctd.deckId&quot;&quot;&quot;) decks = dbm.cur.fetchall() #print(decks) #I'm not entirely sure how this works #Somehow it takes everything with the same deckId (index:2) and puts them into one list values = set(map(lambda x:x[2], decks)) newlist = [[y[1] for y in decks if y[2] == x] for x in values] #print(newlist[0]) superSet = [] for l in newlist: for c in l: if c not in superSet: superSet.append(c) #print(superSet) count = 0 for x in superSet: for y in superSet: if x is y: continue #print(x) #print(y) for d in newlist: #print(d) if x in d and y in d: count += 1 deckPerc = count / len(newlist) if deckPerc != 0.0: print(count / len(newlist)) #needs to go into the db count = 0 if __name__== &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<h2>Creating your list of decks</h2>\n<pre><code>&quot;&quot;&quot;-- ORIGINAL CODE --&quot;&quot;&quot;\n#I'm not entirely sure how this works\n#Somehow it takes everything with the same deckId (index:2) and puts them into one list\nvalues = set(map(lambda x:x[2], decks))\nnewlist = [[y[1] for y in decks if y[2] == x] for x in values]\n</code></pre>\n<p><code>map()</code> takes the function in the first argument, and applies it to every item in the iterable in the second argument. In this case, each item is a <code>(cardId, &quot;card name&quot;, deckId)</code> tuple, and the function returns the value in index <code>2</code> of that tuple, namely <code>deckId</code>. <code>set()</code> takes the iterable returned by <code>map()</code> and converts it into a <a href=\"https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset\" rel=\"noreferrer\">set</a>, which contains exactly one of each unique value in the iterable - in this case, each unique <code>deckId</code>.</p>\n<p>Your second line uses two list comprehensions. The outer one iterates over <code>values</code> (your set of <code>deckId</code>s) and for each <code>deckId</code> it uses another list comprehension to iterate over <code>decks</code> and returns index <code>1</code> of each tuple (namely <code>&quot;card name&quot;</code>) if index <code>2</code> of the item equals the <code>deckId</code> currently being used from the outer list comprehension.</p>\n<p>You could also write this line as a double for-loop:</p>\n<pre><code>newlist = []\nfor x in values:\n temp = []\n for y in decks:\n if y[2] == x:\n temp.append(y[1])\n newlist.append(temp)\n \n</code></pre>\n<p>But in general, this is pretty messy. You loop over the entirely of <code>decks</code> in order to create <code>values</code>, then loop over <code>values</code> * <code>decks</code>. That's very inefficent</p>\n<p>You'd be much better off using a <a href=\"https://docs.python.org/3/library/stdtypes.html#mapping-types-dict\" rel=\"noreferrer\">dictionary</a>, where you can then fold this all into a single loop</p>\n<pre><code>deck_dict = {}\nfor (id, name, deck_id) in decks:\n if deck_id not in deck_dict:\n deck_dict[deck_id] = []\n deck_dict[deck_id].append(name)\n \n</code></pre>\n<p>You can even ditch the initial check to create the list if you use a <code>defaultdict</code></p>\n<pre><code>from collections import defaultdict\n\ndeck_dict = defaultdict(list)\nfor (id, name, deck_id) in decks:\n deck_dict[deck_id].append(name)\n \n</code></pre>\n<p>However, this is still the wrong structure, because you don't actually cares about which cards are in each deck - you care about which decks contain each card.</p>\n<pre><code>from collections import defaultdict\n\ncard_dict = defaultdict(set)\nfor (id, name, deck_id) in decks:\n card_dict[name].add(deck_id)\n \n</code></pre>\n<h2>Creating you superset</h2>\n<pre><code>&quot;&quot;&quot;-- ORIGINAL CODE --&quot;&quot;&quot;\nsuperSet = []\nfor l in newlist:\n for c in l:\n if c not in superSet:\n superSet.append(c)\n \n</code></pre>\n<p>Then you create loop through every item in an item in <code>newlist</code> to create your <code>superSet</code>. You have the same number of items in items in <code>newlist</code> as you had in <code>decks</code>, just organized differently, so all you get for using it instead is a slightly more complicated for loop</p>\n<pre><code>superSet = []\nfor (id, name, deck_id) in decks:\n if name not in superSet:\n superSet.append(name)\n \n</code></pre>\n<p>Notably, since now you're iterating over <code>decks</code>, you could roll this into the same loop you used to create <code>deck_dict</code>. But there's still room for improvement, because you made <code>superSet</code> a list, while it would make much more sense for it to be a set.</p>\n<pre><code>superSet = set()\nfor (id, name, deck_id) in decks:\n superSet.add(name)\n \n</code></pre>\n<p>Since a set only ever contains one of each unique value, this saves you from having to check whether each object is in <code>superSet</code> before you add it. The operation <code>x in s</code> is a lot faster for a set than a list (O(1) on average instead of O(n)).</p>\n<p>If superSet is a set, you can actually use the same assignment you were using earlier for <code>values</code>: <code>superSet = set(map(lambda x:x[1], decks))</code>. Note that we're using <code>x[1]</code> here instead of <code>x[2]</code> because we want the card name instead of the deckId. You can also replace map with a generator comprehension: <code>superSet = set(x[1] for x in decks)</code>, which is generally considered more 'pythonic' than using <code>map()</code>.</p>\n<h2>Counting your pairs</h2>\n<pre><code>&quot;&quot;&quot;-- ORIGINAL CODE --&quot;&quot;&quot;\ncount = 0\nfor x in superSet:\n for y in superSet:\n if x is y:\n continue\n #print(x)\n #print(y)\n for d in newlist:\n #print(d)\n if x in d and y in d:\n count += 1\n deckPerc = count / len(newlist)\n if deckPerc != 0.0:\n print(count / len(newlist)) #needs to go into the db\n count = 0 \n \n</code></pre>\n<p>Iterating over <code>superSet</code> twice like this actually gives you every pair you need twice - once as <code>x='Shock'</code> and <code>y='Bolt'</code>, and once as <code>x='Bolt'</code> and <code>y='Shock'</code>. Fortunately, the itertools library has you covered with the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"noreferrer\">combinations()</a> function. And with <code>card_dict</code> providing the set of decks that contain each card, finding out the total number of decks that contain a pair is simply a matter of taking the union of the sets like so:</p>\n<pre><code>from itertools import combinations\nfor card1, card2 in combinations(superSet, 2):\n shared_decks = card_dict[card1] &amp; card_dict[card2]\n count = len(shared_decks)\n if count &gt; 0:\n print(f'{card1} + {card2}: {count}')\n \n</code></pre>\n<p>Now, rather than calculate the deck percentage, I merely used the count of decks that share the pair. This is because I ditched <code>deck_dict</code> in favor of <code>card_dict</code>, and don't actually have a simple way of calculating the total number of decks at this point in the code. This isn't a problem for the code shown, as <code>if deckPerc != 0.0</code> is equivalent to <code>if count != 0</code>, but if you need the percentage for your actual use case, then we need to go back to before this loop and create it. You can use <code>deck_count = len(set(card[2] for card in decks))</code>, or you can fold the set construction into the existing loop through decks to avoid having to loop through it twice.</p>\n<h2>Bringing it all together</h2>\n<pre><code>from classes.general import Database\nfrom collections import defaultdict\nfrom itertools import combinations\n\ndef main():\n dbm = Database()\n with dbm.con:\n dbm.cur.execute(&quot;&quot;&quot;SELECT c.id, c.name, ctd.deckId FROM cards c \n JOIN cardToDeck ctd ON ctd.cardId = c.id \n JOIN deckToEvent dte ON dte.deckId = ctd.deckId \n JOIN eventToFormat etf ON etf.eventId = dte.eventId \n WHERE etf.formatId = 5\n ORDER BY ctd.deckId&quot;&quot;&quot;)\n decks = dbm.cur.fetchall()\n \n deck_set = set()\n card_set = set()\n card_dict = defaultdict(set)\n for card_id, card_name, deck_id in decks:\n deck_set.add(deck_id)\n card_set.add(card_name)\n card_dict[card_name].add(deck_id)\n \n deck_count = len(deck_set)\n \n for card1, card2 in combinations(card_set, 2):\n shared_decks = card_dict[card1] &amp; card_dict[card2]\n deckPerc = len(shared_decks) / deck_count\n if deckPerc &gt; 0:\n print(f'{card1} + {card2}: {count}') # needs to go into the db\n \nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>And there you have it! You have two loops, one of which iterates through <code>decks</code> once, and the other loops through <code>N*(N-1)/2</code> items, where <code>N</code> is the number of unique cards. Using sets and dicts mean that the time complexity of the operations inside the loops are all O(1), so this is pretty much as fast as you can make it.</p>\n<h2>Additional Notes</h2>\n<p>I know very little about databases, so there may be improvements possible in that area that I am unaware of. I noticed that you kept the entirety of the code in the <code>with</code> block with the connection open, even though you never use it after you create <code>decks</code>. This doesn't harm anything that I'm aware of, but it's good practice to exit a context as soon as you no longer need it (and it reduces the level of indenting your code is at, which is nice). On the other hand, if you plan on using the connection to modify the database at the end of the code, then obviously leave everything as it is.</p>\n<p>Style-wise, you could stand to improve your naming conventions. <code>values</code>, <code>newlist</code>, and <code>superSet</code> are not very descriptive names. Notice how I used <code>deck_set</code>, <code>card_set</code>, and <code>card_dict</code> to provide some indication as to what is in each object. Additionally, most python style guides (in particular <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> the style guide for Python's standard library) recommend using lower_case_with_underscores for the names of variables rather than camelCase as you are using. You are of course free to pick any naming convention you want, but you <em>should</em> conciously choose your convention, and (unless you have a reason not to) it is best to use one of the standard conventions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T21:39:01.663", "Id": "504694", "Score": "0", "body": "TIL PEP 8 covers variable names. I've always defaulted to camelCase due to my history with Java. I will also happily admit my variable names are trash and need to be updated.\n\nI am planning to use the connection again later, which is why I kept everything in the `with` block. Wanted to improve speed first. \n\nWhich is exactly what you helped me with. I'll need to read over it again to get everything, but this is great. Thank you so much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T22:06:31.280", "Id": "504698", "Score": "0", "body": "@raviga151 It's generally considered good etiquette to hold off on accepting an answer until 24 hrs have passed since the question's posting, to give everyone (particularly people in different time zones or with different work schedules) a chance to give their feedback. Also, I don't entirely follow the PEP 8 naming conventions myself, for similar reasons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T23:33:32.850", "Id": "504699", "Score": "0", "body": "I'll un-accept for now and wait the remaining time then." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T21:21:07.153", "Id": "255735", "ParentId": "255724", "Score": "4" } } ]
{ "AcceptedAnswerId": "255735", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T16:35:57.167", "Id": "255724", "Score": "4", "Tags": [ "python-3.x", "sql", "mysql" ], "Title": "Calculating the Percentage of a Pair Occurring Across a Lot of Lists" }
255724
<p>NB: There's a bug with my iterator, apparently. I can't use <code>const_iterator</code> because I get some compiler errors. I know using <code>const</code> there is wrong, but I have to find a way to fix it first...</p> <p>I finished implementing <code>std::vector</code> and decided to continue with <code>std::forward_list</code>. This time, I did not take the time to make it &quot;allocator aware&quot;, but opted for a more soft approach. What I'm really interested in is memory leaks and the correctness of the logic behind the functions, since I have suffered a lot to implement some stuff, and I'm quite sure that I've done it the worst way.</p> <pre><code>#ifndef FORWARD_LIST #define FORWARD_LIST #include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;cstddef&gt; #include &lt;concepts&gt; #include &lt;initializer_list&gt; #include &lt;iterator&gt; #include &lt;limits&gt; #include &lt;memory&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; namespace container{ template&lt;typename Type&gt; class ForwardList { private: struct Node { Type data; Node* next; Node() = default; template&lt;class... Args&gt; constexpr explicit Node(Args&amp;&amp;... args) : data{ std::forward&lt;Args&gt;(args)... } {} }; Node* m_head; Node* m_tail; std::size_t m_size{}; template&lt;typename T&gt; class forward_iterator { private: // Thanks to user Mooing Duck (from www.stackoverflow.com) for this simple alias fix (which solved code duplication for forward_iterator and its const version) Node* m_iterator; public: using value_type = T; using reference = T&amp;; using pointer = value_type*; using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t; constexpr forward_iterator(Node* forw_iter = nullptr) : m_iterator{ forw_iter } {} constexpr Node* getNodeAddress() const noexcept { return m_iterator; } constexpr Node* getNodeNextAddress() const noexcept { return m_iterator-&gt;next; } constexpr reference operator*() const noexcept { return m_iterator-&gt;data; } constexpr pointer operator-&gt;() const noexcept { return m_iterator; } constexpr forward_iterator&amp; operator++() noexcept { m_iterator = m_iterator-&gt;next; return *this; } constexpr forward_iterator operator++(int) noexcept { forward_iterator tmp(*this); m_iterator = m_iterator-&gt;next; return tmp; } constexpr friend bool operator== (const forward_iterator&amp; first, const forward_iterator&amp; second) noexcept { return (first.m_iterator == second.m_iterator); } constexpr friend bool operator!=(const forward_iterator&amp; first, const forward_iterator&amp; second) noexcept { return !(first.m_iterator == second.m_iterator); } }; /* Useful functions for internal purposes */ constexpr void deallocate(ForwardList&amp; other) noexcept { if (!other.m_head) { return; } Node* current_node = other.m_head; while (current_node != nullptr) { Node* next_node = current_node-&gt;next; delete current_node; current_node = next_node; } other.m_head = nullptr; other.m_tail = nullptr; other.m_size = 0; } public: using value_type = Type; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using reference = value_type&amp;; using const_reference = const value_type&amp;; using pointer = Type*; using const_pointer = const pointer; using iterator = forward_iterator&lt;value_type&gt;; using const_iterator = forward_iterator&lt;const Type&gt;; // Member functions constexpr ForwardList() noexcept : m_head{ nullptr } , m_tail{ nullptr } , m_size{ 0 } {} constexpr explicit ForwardList(size_type count, const_reference value) : m_size{ count } { Node* current_node = new Node(value); m_head = current_node; for (size_type index{ 0 }; index &lt; count - 1; ++index) { current_node-&gt;next = new Node(value); current_node = current_node-&gt;next; } m_tail = current_node; m_tail-&gt;next = nullptr; } // Type must be DefaultConstructible constexpr explicit ForwardList(size_type count) : ForwardList(count, Type{}) {} template&lt;std::input_iterator input_iter&gt; constexpr ForwardList(input_iter first, input_iter last) : m_size{ static_cast&lt;size_type&gt;(std::distance(first, last)) } { Node* current_node = new Node(*first); m_head = current_node; for (size_type index{ 0 }; index &lt; m_size - 1; ++index) { current_node-&gt;next = new Node(*(++first)); current_node = current_node-&gt;next; } m_tail = current_node; m_tail-&gt;next = nullptr; } constexpr ForwardList(const ForwardList&amp; other) { if (other.m_head) { m_size = other.m_size; Node* current_node = new Node(other.m_head-&gt;data); Node* current_other_node = other.m_head; m_head = current_node; while (current_other_node-&gt;next != nullptr) { current_node-&gt;next = new Node(current_other_node-&gt;next-&gt;data); current_node = current_node-&gt;next; current_other_node = current_other_node-&gt;next; } m_tail = current_node; m_tail-&gt;next = nullptr; } else { ForwardList(); } } constexpr ForwardList(ForwardList&amp;&amp; other) noexcept : ForwardList() { other.swap(*this); } constexpr ForwardList(std::initializer_list&lt;Type&gt; list) : m_size{ list.size() } { Node* current_node = new Node(*(list.begin())); m_head = current_node; for (auto it = list.begin() + 1; it != list.end(); ++it) { current_node-&gt;next = new Node(*it); current_node = current_node-&gt;next; } m_tail = current_node; m_tail-&gt;next = nullptr; } ~ForwardList() { Node* current_node = m_head; while (current_node != nullptr) { Node* next_node = current_node-&gt;next; delete current_node; current_node = next_node; } m_head = nullptr; } constexpr ForwardList&amp; operator=(const ForwardList&amp; other) { ForwardList temp_list(other); temp_list.swap(*this); return *this; } constexpr ForwardList&amp; operator=(ForwardList&amp;&amp; other) noexcept { other.swap(*this); deallocate(other); return *this; } constexpr ForwardList&amp; operator=(std::initializer_list&lt;Type&gt; list) { ForwardList temp_list{ list }; temp_list.swap(*this); return *this; } constexpr void assign(size_type new_size, const_reference value) { deallocate(*this); ForwardList temp_list(new_size, value); temp_list.swap(*this); } constexpr void assign(std::initializer_list&lt;Type&gt; list) { deallocate(*this); ForwardList temp_list{ list }; temp_list.swap(*this); } template&lt;typename input_iter&gt; constexpr void assign(input_iter first, input_iter last) { deallocate(*this); ForwardList temp_list(first, last); temp_list.swap(*this); } // Element access constexpr reference front() noexcept { return m_head-&gt;data; } constexpr const_reference front() const noexcept { return m_head-&gt;data; } // Iterators constexpr iterator begin() noexcept { return iterator(m_head); } constexpr const_iterator begin() const noexcept { return const_iterator(m_head); } constexpr const_iterator cbegin() const noexcept { return const_iterator(m_head); } constexpr iterator end() noexcept { if (m_tail == nullptr) { return nullptr; } return iterator(m_tail-&gt;next); } constexpr const_iterator end() const noexcept { if (m_tail == nullptr) { return nullptr; } return const_iterator(m_tail-&gt;next); } constexpr const_iterator cend() const noexcept { if (m_tail == nullptr) { return nullptr; } return const_iterator(m_tail-&gt;next); } constexpr bool empty() const noexcept { return m_size == 0; } constexpr size_type size() const noexcept { return m_size; } constexpr size_type max_size() const noexcept { return std::numeric_limits&lt;difference_type&gt;::max(); } //Modifiers constexpr void clear() noexcept { deallocate(*this); } template&lt;typename...Args&gt; constexpr iterator emplace_after(const iterator position, Args...args) { // Must be O(1) Node* temp = position.getNodeAddress(); Node* current_node = new Node(std::forward&lt;Args&gt;(args)...); if (temp == m_tail) { m_tail-&gt;next = current_node; current_node-&gt;next = nullptr; m_tail = m_tail-&gt;next; } else { Node* next_temp = position.getNodeNextAddress(); temp-&gt;next = current_node; current_node-&gt;next = next_temp; } m_size += 1; return iterator(current_node); } constexpr iterator insert_after(const iterator position, const_reference value) { return emplace_after(position, value); } constexpr iterator insert_after(const iterator position, Type&amp;&amp; value) { return emplace_after(position, std::move(value)); } constexpr iterator insert_after(const iterator position, size_type count, const_reference value) { iterator temp; for (size_type i{ 0 }; i &lt; count; ++i) { temp = emplace_after(position, value); } return (count == 0) ? position : temp; } constexpr iterator insert_after(const iterator position, std::initializer_list&lt;Type&gt; list) { iterator temp; for (auto current : list) { temp = emplace_after(position, current); } return (list.size() == 0) ? position : temp; } constexpr iterator erase_after(const iterator position) { Node* temp = position.getNodeAddress(); Node* next_temp = temp-&gt;next; if (temp!=nullptr &amp;&amp; next_temp-&gt;next == nullptr) { temp-&gt;next = nullptr; } else if (temp != nullptr) { temp-&gt;next = next_temp-&gt;next; delete next_temp; } m_size -= 1; auto pos = position; return (++pos != nullptr) ? pos : end(); } constexpr iterator erase_after(iterator first, iterator last) { Node* firstNode_temp = first.getNodeAddress(); Node* firstNode_next = first.getNodeNextAddress(); Node* lastNode_temp = last.getNodeAddress(); while (firstNode_next != lastNode_temp) { Node* temp = firstNode_next-&gt;next; delete firstNode_next; firstNode_next = temp; --m_size; } firstNode_temp-&gt;next = lastNode_temp; return last; } constexpr void push_front(const_reference value) { emplace_front(value); } constexpr void push_front(Type&amp;&amp; value) { emplace_front(std::move(value)); } template&lt;typename...Args&gt; constexpr reference emplace_front(Args...args) { Node* head_temp = m_head; Node* current = new Node(std::forward&lt;Args&gt;(args)...); m_head = current; m_head-&gt;next = head_temp; ++m_size; return m_head-&gt;data; } constexpr void pop_front() { Node* head_temp = m_head; Node* next_temp = m_head-&gt;next; m_head = next_temp; delete head_temp; --m_size; } constexpr void resize(size_type count, const_reference value=Type()) { if (count &lt; size()) { Node* tmp = m_head; for (size_type index{ 0 }; index &lt; count-1; ++index) { tmp = tmp-&gt;next; } Node* other_tmp = tmp; tmp = tmp-&gt;next; while (tmp-&gt;next != m_tail){ Node* tmpp = tmp-&gt;next; delete tmp; tmp = tmpp; } delete m_tail; m_tail = other_tmp; m_tail-&gt;next = nullptr; } else { Node* temp_tail = m_tail; for (size_type index{ 0 }; index &lt; count; ++index) { temp_tail-&gt;next = new Node(value); temp_tail = temp_tail-&gt;next; } m_tail = temp_tail; m_tail-&gt;next = nullptr; temp_tail = nullptr; } m_size = count; } constexpr void swap(ForwardList&amp; other) noexcept { Node* temp_node; temp_node = m_head; m_head = other.m_head; other.m_head = temp_node; temp_node = nullptr; Node* temp_tail; temp_tail = m_tail; m_tail = other.m_tail; other.m_tail = temp_tail; temp_tail = nullptr; std::swap(m_size, other.m_size); } constexpr void splice_after(const iterator position, ForwardList&amp; other) { Node* current_pos = position.getNodeAddress(); if (current_pos == m_tail) { m_tail-&gt;next = other.m_head; m_tail = other.m_tail; } else { Node* next_node = position.getNodeNextAddress(); Node* next_next = next_node-&gt;next; Node* temp_head = other.m_head; Node* temp_tail = other.m_tail; current_pos-&gt;next = temp_head; temp_tail-&gt;next = next_next; } m_size += other.m_size; other.m_size = 0; other.m_head = nullptr; other.m_tail = nullptr; } private: constexpr Node* _Remove(Node* beforeNode) noexcept { // Bug-&gt;Last element not removed/crash const auto to_remove = beforeNode-&gt;next; const auto removed_next = to_remove-&gt;next; beforeNode-&gt;next = removed_next; delete to_remove; return removed_next; } public: constexpr size_type remove(const_reference toRemove_value) { return remove_if([&amp;toRemove_value](auto other) { return other == toRemove_value; }); } template&lt;typename Predicate&gt; constexpr size_type remove_if(Predicate pred){ Node* before_begin = new Node(); Node* tmp_before_begin = before_begin; before_begin-&gt;next = m_head; size_type tot_removed{ 0 }; for (Node* first = m_head; first != nullptr;) { if (pred(first-&gt;data)) { // Lambda is true, remove the element - m_head might be changed if (first == m_head) { first = _Remove(before_begin); m_head = first; } else { first = _Remove(before_begin); } ++tot_removed; } else { // m_head is not removed before_begin = first; first = first-&gt;next; } } delete tmp_before_begin; m_size -= tot_removed; return tot_removed; } constexpr size_type unique() { size_type removed{ 0 }; for (Node* first = m_head; first != nullptr;) { if (first == m_tail) break; if (first-&gt;data == first-&gt;next-&gt;data) { first = _Remove(first); ++removed; } else { first = first-&gt;next; } } m_size -= removed; return removed; } constexpr void reverse() noexcept { Node* temp_data = m_head; ForwardList temp = ForwardList(); while (temp_data != nullptr) { temp.push_front(temp_data-&gt;data); temp_data = temp_data-&gt;next; } temp.swap(*this); } private: /*Example taken from geeksforgeeks*/ constexpr void _Sort(Node* (&amp;head_ref), Node* new_node) { Node* current; if (head_ref == nullptr || (head_ref)-&gt;data &gt;= new_node-&gt;data) { new_node-&gt;next = head_ref; head_ref = new_node; } else { current = head_ref; while (current-&gt;next != nullptr &amp;&amp; current-&gt;next-&gt;data &lt; new_node-&gt;data) { current = current-&gt;next; } new_node-&gt;next = current-&gt;next; current-&gt;next = new_node; } } public: constexpr void sort() { Node* sorted = nullptr; Node* current = m_head; while (current != nullptr) { Node* next = current-&gt;next; _Sort(sorted, current); current = next; } m_head = sorted; } constexpr bool operator&lt;=(const ForwardList&lt;Type&gt;&amp; other) { return !(other &lt; *this); } constexpr bool operator &gt;=(const ForwardList&lt;Type&gt;&amp; other) { return !(*this &lt; other); } }; template&lt;typename T&gt; constexpr bool operator== (const ForwardList&lt;T&gt;&amp; first, const ForwardList&lt;T&gt;&amp; other) { auto temp = first.m_head; bool notEqual = false; if (first.size() != other.size()) return false; else{ while (temp != nullptr) { if (!(temp-&gt;data == other-&gt;data)) { notEqual = true; break; } temp = temp-&gt;next; } } return notEqual == true ? false : true; } template&lt;typename T&gt; constexpr bool operator!= (const ForwardList&lt;T&gt;&amp; first, const ForwardList&lt;T&gt;&amp; other) { return !(first == other); } template&lt;typename T&gt; constexpr bool operator&lt;(const ForwardList&lt;T&gt;&amp; first, const ForwardList&lt;T&gt;&amp; other) { return (std::lexicographical_compare(first.begin(), first.end(), other.begin(), other.end())); } template&lt;typename T&gt; constexpr bool operator&gt;(const ForwardList&lt;T&gt;&amp; first, const ForwardList&lt;T&gt;&amp; other) { return !(std::lexicographical_compare(first.begin(), first.end(), other.begin(), other.end())); } } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T17:21:37.390", "Id": "504670", "Score": "1", "body": "Does posted code run and execute as expected. If it doesn't compile, then it doesn't run and is off-topic for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T17:45:02.533", "Id": "504671", "Score": "0", "body": "It should run fine. The \"NB\" in the beginning is just to tell that if I change the current iterator to const_iterator, it will not work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T17:45:03.900", "Id": "504672", "Score": "3", "body": "I checked, and it doesn’t compile. But it appears to be just a couple of typos. 1) In the `ForwardList(size_type, const_reference)` constructor, you have `new Node<Type>`… but `Node` is not a template. 2) In the `ForwardList` `operator<=`, the `return` is missing. With those two fixes, it *appears* to work, at a very cursory check. But really, you should check these things yourself, and more, by writing some simple tests. You should ***ALWAYS*** write tests, maybe even before the actual code itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T17:47:41.697", "Id": "504673", "Score": "0", "body": "Thanks, indi. For some reason it happened to work on VS2019. Fixed those two issues now. I guess I edited some stuff and forgot to re-test, so thanks for pointing that out!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T18:11:08.527", "Id": "504674", "Score": "2", "body": "Yeah, because it’s a template, compilers are *technically* not obligated to check it for correctness (other than syntactic correctness) it until it’s instantiated, so VS is *technically* not wrong to pass it (until you actually try to instantiate the problematic functions, then boom). On the other hand, when it’s obvious it can *never* be correct no matter what type it’s instantiated with, it’s nice to get a diagnostic, so kudos to GCC for that. But again, you should really write tests for all new code… ideally before the actual code. It’s *really* worth it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T19:02:59.520", "Id": "504676", "Score": "2", "body": "`using const_pointer = const pointer;` is also wrong. Have you seen https://quuxplusone.github.io/blog/2018/12/01/const-iterator-antipatterns/ and https://stackoverflow.com/questions/8054273/how-to-implement-an-stl-style-iterator-and-avoid-common-pitfalls/8054856 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T06:08:23.080", "Id": "504712", "Score": "0", "body": "@SomeoneWithPassion More often than not there are cases where your code would compile with MSVC but throw errors on other compilers like GCC, and the opposite. The good thing to do is to test on multiple to be sure." } ]
[ { "body": "<p>Sorry don't have time for a comprehensive review:</p>\n<h2>Code Review</h2>\n<p>Some nits:</p>\n<p>What happens when <code>count == 0</code></p>\n<pre><code> constexpr explicit ForwardList(size_type count, const_reference value)\n</code></pre>\n<hr />\n<p>What happens when <code>first == last</code></p>\n<pre><code> constexpr ForwardList(input_iter first, input_iter last)\n</code></pre>\n<hr />\n<p>You have a constructor that takes iterators. Why does the list version not reuse this:</p>\n<pre><code> constexpr ForwardList(std::initializer_list&lt;Type&gt; list)\n // Could forward the call to the list iterator.\n : ForwardList(std::begin(list), std::end(list))\n</code></pre>\n<hr />\n<p>Overall there is a lot of repeated code in your constructors. I am pretty sure you can <strong>DRY</strong> this up a lot.</p>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T21:40:11.147", "Id": "505011", "Score": "0", "body": "Ah, pity. I was planning to do a thorough review on the weekend. Oh well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-14T18:31:58.660", "Id": "505338", "Score": "0", "body": "Thanks for the review nonetheless. I'm currently reviewing the whole implementation and trying to remove all the duplicates." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T17:50:59.827", "Id": "255813", "ParentId": "255725", "Score": "1" } } ]
{ "AcceptedAnswerId": "255813", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T16:56:45.370", "Id": "255725", "Score": "3", "Tags": [ "c++", "linked-list", "iterator" ], "Title": "Forward List Implementation" }
255725
<p>I initially had a simple firebase cloud function that sent out a push notification to a topic when a new message child was created in my real-time database. But I wanted to add message filtering where notifications for messages from some filtered users would be sent only to admin users. For this, I have created user groups in my real-time database of the format <code>{userName: FIRToken}</code>, which gets written to from my iOS App every time it launches and I get a FIRToken. So now I will have to load 2 lists 1) Admin Users, 2) Filtered Users before I can actually decide where to send the notification.</p> <p>So I looked into ways to do this and <code>async/await</code> seemed better than doing a promise inside a promise for loading my 2 user lists. I then saw a firestore video tutorial where a similar usecase function was converted to use <code>async/await</code> instead of promises in promises. Following that, I refactored my code to await on the 2 snapshots for admin and filtered users, before going on to decide where to send the notification and return a promise. My refactoring seems correct. But unfortunately, my old iPhone is stuck on <a href="https://www.reddit.com/r/iOSProgramming/comments/j1hsl3/copying_cache_files_from_device/" rel="nofollow noreferrer">&lt;DeviceName&gt; is busy: Copying cache files from device</a>. Hence I can't physically login from 2 different devices and test if the notifications are going only to my admin user account. Which is why I am posting my function here to see if I have refactored my code correctly or missed something. Please let me know if I will get the intended results or I should fix something in the code.</p> <pre><code>functions.database .ref(&quot;/discussionMessages/{autoId}/&quot;) .onCreate(async (snapshot, context) =&gt; { // console.log(&quot;Snapshot: &quot;, snapshot); try { const groupsRef = admin.database().ref(&quot;people/groups&quot;); const adminUsersRef = groupsRef.child(&quot;admin&quot;); const filteredUsersRef = groupsRef.child(&quot;filtered&quot;); const filteredUsersSnapshot = await filteredUsersRef.once(&quot;value&quot;); const adminUsersSnapshot = await adminUsersRef.once(&quot;value&quot;); var adminUsersFIRTokens = {}; var filteredUsersFIRTokens = {}; if (filteredUsersSnapshot.exists()) { filteredUsersFIRTokens = filteredUsersSnapshot.val(); } if (adminUsersSnapshot.exists()) { adminUsersFIRTokens = adminUsersSnapshot.val(); } // console.log( // &quot;Admin and Filtered Users: &quot;, // adminUsersFIRTokens, // &quot; &quot;, // filteredUsersFIRTokens // ); const topicName = &quot;SpeechDrillDiscussions&quot;; const message = snapshot.val(); // console.log(&quot;Received new message: &quot;, message); const senderName = message.userName; const senderCountry = message.userCountryEmoji; const title = senderName + &quot; &quot; + senderCountry; const messageText = message.message; const messageTimestamp = message.messageTimestamp.toString(); const messageID = message.hasOwnProperty(&quot;messageID&quot;) ? message.messageID : undefined; const senderEmailId = message.userEmailAddress; const senderUserName = getUserNameFromEmail(senderEmailId); const isSenderFiltered = filteredUsersFIRTokens.hasOwnProperty( senderUserName ); console.log( &quot;Will attempt to send notification for message with message id: &quot;, messageID ); var payload = { notification: { title: title, body: messageText, }, data: { messageID: messageID, messageTimestamp: messageTimestamp, }, apns: { payload: { aps: { sound: &quot;default&quot;, }, }, }, }; console.log(&quot;Is sender filtered? &quot;, isSenderFiltered); if (isSenderFiltered) { adminFIRTokens = Object.values(adminUsersFIRTokens); console.log(&quot;Sending filtered notification with sendMulticast()&quot;); payload.tokens = adminFIRTokens; //Needed for sendMulticast return admin .messaging() .sendMulticast(payload) .then((response) =&gt; { console.log( &quot;Sent filtered message (using sendMulticast) notification: &quot;, JSON.stringify(response) ); if (response.failureCount &gt; 0) { const failedTokens = []; response.responses.forEach((resp, idx) =&gt; { if (!resp.success) { failedTokens.push(adminFIRTokens[idx]); } }); console.log( &quot;List of tokens that caused failures: &quot; + failedTokens ); } return true; }); } else { console.log(&quot;Sending topic message with send()&quot;); payload.topic = topicName; return admin .messaging() .send(payload) .then((response) =&gt; { console.log( &quot;Sent topic message (using send) notification: &quot;, JSON.stringify(response) ); return true; }); } } catch (error) { console.log(&quot;Notification sent failed:&quot;, error); return false; } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T05:30:42.223", "Id": "504711", "Score": "0", "body": "Hey @pacmaninbw the code is working as expected and sending notifications. I wanted to check if I have made any logical errors in checking edge cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T11:22:56.813", "Id": "504725", "Score": "0", "body": "I'm suggesting you refactor the question a little bit, `But unfortunately, my old iPhone is stuck on <DeviceName> is busy: Copying cache files from device.` might indicate the code isn't working to some people. Do you have to log in from a phone?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T17:29:04.047", "Id": "255726", "Score": "0", "Tags": [ "javascript", "async-await", "firebase" ], "Title": "Advice converting an onCreate firebase cloud function trigger with FCM Messaging to support async/await and database reads" }
255726
<p><a href="https://www.hackerrank.com/challenges/sequence-full-of-colors/problem" rel="nofollow noreferrer">This</a> is the challenge:</p> <blockquote> <p>You are given a sequence of <code>N</code> balls in 4 colors: red, green, yellow and blue. The sequence is full of colors if and only if all of the following conditions are true:</p> <ul> <li>There are as many red balls as green balls.</li> <li>There are as many yellow balls as blue balls.</li> <li>Difference between the number of red balls and green balls in every prefix of the sequence is at most 1.</li> <li>Difference between the number of yellow balls and blue balls in every prefix of the sequence is at most 1.</li> <li>Your task is to write a program, which for a given sequence prints True if it is full of colors, otherwise it prints False.</li> </ul> </blockquote> <p>and this is my solution:</p> <pre class="lang-hs prettyprint-override"><code>import Control.Monad (replicateM, foldM) main :: IO () main = do n &lt;- getLine list &lt;- replicateM (read n :: Int) getLine mapM_ (print . isgood) list isgood :: String -&gt; Bool isgood = isValidFinal . foldM step (0,0) where step (x,y) c | c == 'R' = wrapValidInJust (x - 1, y) | c == 'G' = wrapValidInJust (x + 1, y) | c == 'Y' = wrapValidInJust (x, y - 1) | c == 'B' = wrapValidInJust (x, y + 1) isValid (x,y) = abs x &lt;= 1 &amp;&amp; abs y &lt;= 1 wrapValidInJust xy = if isValid xy then Just xy else Nothing isValidFinal (Just x) = x == (0,0) isValidFinal Nothing = False </code></pre> <p>I'm kind of happy with <code>main</code> and <code>isgood</code>, but the <code>step</code> function seems very hard to read.</p> <p>Any feedback?</p>
[]
[ { "body": "<ul>\n<li><p><code>step</code> does two things: (1) step to the next state, and (2) check that the state is valid. Its name suggests only the first meaning. The repetition of <code>wrapValidInJust</code> suggests that they can be separated.</p>\n</li>\n<li><p>Instead of <code>==</code> you can use pattern-matching.</p>\n</li>\n</ul>\n<pre><code>isgood :: String -&gt; Bool\nisgood = isValidFinal . foldM (check . step) (0, 0)\n where\n\n step (x, y) 'R' = (x-1, y)\n step (x, y) 'G' = (x+1, y)\n step (x, y) 'Y' = (x, y-1)\n step (x, y) 'B' = (x, y+1)\n\n check (x, y) = if abs x &lt;= 1 &amp;&amp; abs y &lt;= 1 then Just (x, y) else Nothing\n\n ...\n</code></pre>\n<p>Another reason <code>step</code> is hard to read is that you need to keep track of differences, which complexifies the meaning of <code>x</code> and <code>y</code>. You can just as easily count the four colors independently and compute the difference only in <code>check</code>. This is also the opportunity to use a record or a map to make the update syntax more uniform:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>data RGBY = RGBY { r, g, b, y :: Int }\n\nisgood :: String -&gt; Bool\nisgood = isValidFinal . foldM (check . step) (RGBY 0 0 0 0)\n where\n\n step x 'R' = x { r = r x + 1 }\n step x 'G' = x { g = g x + 1 }\n step x 'Y' = x { y = y x + 1 }\n step x 'B' = x { b = b x + 1 }\n\n check x = if abs (r x - g x) &lt;= 1 &amp;&amp; abs (y x - b x) &lt;= 1\n then Just (x, y) else Nothing\n\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T20:22:29.887", "Id": "255734", "ParentId": "255730", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T18:35:11.340", "Id": "255730", "Score": "1", "Tags": [ "programming-challenge", "haskell", "recursion", "functional-programming" ], "Title": "\"Sequence full of colors\" challenge on HackerRank" }
255730
<p>This code hasn't been tested exhaustively - I would love suggestions about a testing library.</p> <p>Critical, Optional and Positive feedback are more then welcome.</p> <pre><code>const fs = require('fs'); /** * strip all comments and create a new file with only code * @param {int} file name to clean.. * @return {int} function returns 0 at the end. */ function clean(file) { const inputFileName = file; // create output file name. e.g: test.js -&gt; test_CLEAN.js let outputFileName = inputFileName.split('.'); outputFileName[0] += '_CLEAN'; outputFileName = outputFileName.join('.'); // clean output file old data fs.writeFile(outputFileName, ``, (err) =&gt; { if (err) { console.log(err); } }); // comments regex defentions // lines starts with // where // can have spaces before for indentation const singleLineComment = /^\s*\/\//; // start skipping lines on /* can have spaces before const multiLineCommentStart = /^\s*\/\*/; // stop skipping lines on */ end the end of the line const multiLineCommentEnd = /\*\/$/; // mixed lines with code and inline comments const singleLineCommentAfterCode = /[;]\s*\/\//; // skip lines bool let skipLine = false; // load input file to memory, split it by lines, filter white space lines, then loop over each line fs.readFileSync(inputFileName, 'utf-8') .split(/\n/) .filter((line) =&gt; line != '') .forEach((line) =&gt; { // return in a forEach() callback is equivalent to continue in a conventional for loop. if (multiLineCommentStart.test(line)) { skipLine = true; return; } if (multiLineCommentEnd.test(line)) { skipLine = false; return; } if (singleLineComment.test(line)) { return; } if (singleLineCommentAfterCode.test(line)) { line = line.split(' //')[0]; } // append lines to output file if (!skipLine) { // append additional \n at the end of a blocks (after '};') line = line === '};' ? line + '\n' : line; fs.appendFileSync(outputFileName, `${line}\n`, (err) =&gt; { if (err) { // append failed console.log(err); } }); } }); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T19:49:28.850", "Id": "504680", "Score": "1", "body": "You haven't even tested it? Don't you think it's rude to ask for a review before you've done at least the basics?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T19:52:41.250", "Id": "504681", "Score": "0", "body": "not sure what you mean, the code works.. what's the problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T19:53:51.527", "Id": "504683", "Score": "1", "body": "If you haven't tested it, how do you know that the code works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T19:54:49.753", "Id": "504685", "Score": "0", "body": "I've tested it manually with some files with JS code and some comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T20:22:23.123", "Id": "504689", "Score": "0", "body": "also, hostile work environment.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T20:25:09.903", "Id": "504690", "Score": "0", "body": "Ah, so you have tested it, then? Just that your tests aren't as thorough as you'd like? That's different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T20:28:10.523", "Id": "504691", "Score": "0", "body": "ho, I see what you did there with the edit. makes much more sense that way :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T04:07:12.770", "Id": "504805", "Score": "0", "body": "I wouldn't try to achieve such a task by hand, there will always be edge cases you won't catch (as the current answer shows). I've played around with a AST parser called \"acorn\" before - take a look at that. By default it doesn't store comments when it creates an AST tree, so theoritically it should be as simple as turnings the code into an AST tree and back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:45:13.093", "Id": "505754", "Score": "0", "body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)" } ]
[ { "body": "<p>To handle codes, use a parser. Build an AST from parser (maybe comments are already removed there). And then convert it to codes. A FSM implementation <em>may</em> work. (I'm not sure). But I believe your current RegExp approach are far from working.</p>\n<p>Anyway,</p>\n<h2>1. Line break</h2>\n<p>JavaScript support 5 different <a href=\"https://262.ecma-international.org/11.0/#prod-LineTerminatorSequence\" rel=\"nofollow noreferrer\">line terminator sequence</a>. Your code only support one or two of them.</p>\n<h2>2. Single line comment</h2>\n<p>Line end no need to have <code>;</code>.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = 42// comment\n</code></pre>\n<h3>3. Multi line comment</h3>\n<p>Start / end of multi line comment no need to take a single line. They may appear on the same line.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = 42; /* comment */\n</code></pre>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = 42; /*\n*/ var b = 42;\n</code></pre>\n<h2>3. Some more complex comments</h2>\n<p>After you fix above issues, you are ready to handle more complex situations:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = 3\n/*\n*// 3;\n/*/ /*/\n/* // */\n// /*\nvar b = 4;\n// */\n</code></pre>\n<h2>4. String and RegExp</h2>\n<p>Text in strings / regular expressions are not comments.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = '; // ';\n</code></pre>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = '\\\n// ';\n</code></pre>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = `\n// `;\n</code></pre>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = /[; //]/;\n</code></pre>\n<p>This would be more complex if mix them up.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var c = `; // ${function () {\n a = '}';\n // Wow, SO failed to use correct syntax highlight for this too!\n}}`\n</code></pre>\n<h2>5. HTML like comments</h2>\n<p>This could be optional. Most browsers supports HTML like comments. But this is not required to every JavaScript engine.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var a = 42;\n--&gt; this is comment\n&lt;!-- this is comment too\n</code></pre>\n<h2>6. Shebang</h2>\n<p>It is up to you if you want to handle shebang as comments. They work on some browsers.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>#!/usr/bin/node\n\nvar a = 42;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-12T05:17:21.930", "Id": "505100", "Score": "0", "body": "Thank you tsh, it gave me some things to think about." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T03:12:40.573", "Id": "255743", "ParentId": "255732", "Score": "5" } } ]
{ "AcceptedAnswerId": "255743", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T18:57:49.707", "Id": "255732", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "Strip all comments and create a new file with only (JS) code" }
255732
<p>I wrote this small Brainfuck interpreter in C++ where the different op codes are handled in one big switch-case statement instead of something like a tokenizer as Brainfuck is very simple in that regard. Furthermore, I split the logic into namespaces as I wanted to emulate or have the behaviour as if it was a static utility method (like <code>static</code> in Java).</p> <p>My <code>cells</code> array has a size of 30 000 but is technically an infinite tape as I read somewhere that that size is appropriate for Brainfuck. I also differentiate between handling the input and output as ASCII characters or just numbers in case the user wants to just print <code>Hello Word</code> or compute 1+1 but I feel like there must be a better solution. <code>unsigned char</code> is the datatype I store the current values in as it goes from 0 to 255 which is what Brainfuck specifies I believe.</p> <p>brainfuck.h</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; namespace Brainfuck { void execute(const std::string &amp;input, std::string &amp;output, const char &amp;ascii); } </code></pre> <p>brainfuck.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;brainfuck.h&quot; #include &lt;array&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; namespace Brainfuck { namespace { std::array&lt;unsigned char, 30'000&gt; cells; std::string input_; int current_index = 0; int current_char = 0; void remove_spaces(std::string &amp;input) { input.erase(std::remove_if(input.begin(), input.end(), ::isspace), input.end()); } void remove_new_lines(std::string &amp;input) { input.erase(std::remove(input.begin(), input.end(), '\n'), input.end()); } int find_matching_end_bracket(int current_char, const std::string &amp;input) { int new_index = 0; int expected = 0; int found = 0; for (;current_char &lt; input.length(); current_char++) { if(input[current_char] == '[') expected++; if(input[current_char] == ']') { found++; if(expected == found) { new_index = current_char; break; } } } return new_index; } int find_matching_start_bracket(int current_char, const std::string &amp;input) { int new_index = 0; int expected = 0; int found = 0; for (;current_char &gt;= 0; current_char--) { if(input[current_char] == ']') expected++; if(input[current_char] == '[') { found++; if(expected == found) { new_index = current_char; break; } } } return new_index; } void op_codes(const char &amp;cur, std::string &amp;output, const char &amp;ascii) { switch (cur) { case '&gt;': if(current_index == cells.size() - 1) { current_index = 0; } else { current_index++; } break; case '&lt;': if(current_index == 0) { current_index = cells.size() - 1; } else { current_index--; } break; case '+': cells[current_index]++; break; case '-': cells[current_index]--; break; case '.': if(ascii == 'n') { output += std::to_string(cells[current_index]); } if(ascii == 'y') { output += cells[current_index]; } break; case ',': { std::string in; std::cout &lt;&lt; &quot;Enter input between 0 and 255: &quot;; std::cin &gt;&gt; in; if(!in.empty() &amp;&amp; std::all_of(in.begin(), in.end(), ::isdigit)) { auto c_in = stoi(in); if(c_in &gt;= 0 &amp;&amp; c_in &lt;= 255) { cells[current_index] = c_in; } else { std::cout &lt;&lt; &quot;Not a valid input! Enter a number between 0 and 255!&quot; &lt;&lt; std::endl; } } else { std::cout &lt;&lt; &quot;Not a valid input!&quot; &lt;&lt; std::endl; } break; } case '[': if(cells[current_index] == 0) { current_char = find_matching_end_bracket(current_char, input_); } break; case ']': if(cells[current_index] != 0) { current_char = find_matching_start_bracket(current_char, input_); } break; default: std::cout &lt;&lt; &quot;Not a valid Brainfuck program! Unknown symbol at &quot; &lt;&lt; current_index &lt;&lt; std::endl; break; } } void reset() { std::fill(cells.begin(), cells.end(), 0); current_char = 0; current_index = 0; input_ = &quot;&quot;; } } void execute(const std::string &amp;input, std::string &amp;output, const char &amp;ascii) { input_ = input; remove_spaces(input_); remove_new_lines(input_); while(current_char &lt; input_.length()) { op_codes(input_[current_char], output, ascii); current_char++; } reset(); } } </code></pre> <p>main.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;brainfuck.h&quot; #include &lt;iostream&gt; #include &lt;string&gt; int main(int, char**) { std::string brainfuck_code; std::string output; char ascii; std::cout &lt;&lt; &quot;Enter your brainfuck code: &quot;; std::cin &gt;&gt; brainfuck_code; do { std::cout &lt;&lt; &quot;Do you wish your output to be letters? y/n &quot;; std::cin &gt;&gt; ascii; } while(ascii != 'y' &amp;&amp; ascii != 'n'); Brainfuck::execute(brainfuck_code, output, ascii); std::cout &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; output &lt;&lt; std::endl; return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T07:09:35.950", "Id": "504713", "Score": "1", "body": "*as it goes from 0 to 255* - That's true on most modern machines (C++ implementations), but ISO C++ in general allows `unsigned char` to be larger (not smaller). Use `uint8_t` if that's exactly what you need." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T12:21:43.040", "Id": "504729", "Score": "0", "body": "You know, you can translate Brainfuck to C quite easily, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:52:22.887", "Id": "504745", "Score": "0", "body": "It is such a ridiculous and pointless name for a psuedo-language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T01:03:03.130", "Id": "504796", "Score": "0", "body": "@PeterCordes thanks for the hint, I will change that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T01:34:49.503", "Id": "505035", "Score": "1", "body": "If `std::uint8_t` exists, then `unsigned char` *must* be 0 to 255 (and `std::uint8_t` probably *is* `unsigned char`). If `unsigned char` is not 0 to 255, then `std::uint8_t` can’t exist. If you want to be truly portable, you’d have to use `std::uint_fast8_t` or `std::uint_least8_t`… or `unsigned char`. (Or, maybe, `std::byte`.) `uint8_t` is actually the *least* portable option." } ]
[ { "body": "<pre><code>std::array&lt;unsigned char, 30'000&gt; cells; \nint current_index = 0;\n\ncase '&lt;':\n if(current_index == 0) {\n current_index = cells.size() - 1;\n } else {\n current_index--;\n }\n break;\n</code></pre>\n<p>Try using a truly infinite tape instead. (Well, up to the limits of your memory allocator, anyway.) Here's what part of that would look like. Can you fill in the rest?</p>\n<pre><code>std::deque&lt;unsigned char&gt; cells; \nint current_index = 0;\n\ncase '&lt;':\n if (current_index == 0) {\n cells.push_front(0);\n } else {\n current_index -= 1;\n }\n break;\n</code></pre>\n<hr />\n<blockquote>\n<p>I split the logic into namespaces as I wanted to emulate or have the behaviour as if it was a static utility method</p>\n</blockquote>\n<p>You know C++ has the <code>static</code> keyword too, right?</p>\n<pre><code>class Brainfuck {\npublic:\n static void execute(const std::string &amp;input, std::string &amp;output, bool ascii);\n};\n</code></pre>\n<p>(I'm not sure why you were taking the <code>ascii</code> parameter as <code>const char&amp;</code> — it's just a boolean <code>true</code> or <code>false</code>, isn't it?)</p>\n<hr />\n<p>Rather than using a bunch of global variables, consider making <em>each instance</em> of <code>class Brainfuck</code> represent an <em>individual program</em>, which you can execute by calling the <code>execute</code> method. So then you can juggle multiple Brainfuck programs within a single C++ program.</p>\n<hr />\n<p>You currently handle output by modifying a <code>std::string&amp; output</code>. It would be more &quot;C++-thonic&quot; to use the standard library's <code>&lt;iostream&gt;</code> facilities, like this:</p>\n<pre><code>class Brainfuck {\npublic:\n explicit Brainfuck(const std::string&amp; program);\n void execute(std::istream&amp; input, std::ostream&amp; output, bool outputAscii) const {\n ~~~\n case '.':\n if (this-&gt;outputAscii) {\n output &lt;&lt; char(cells[current_index]);\n } else {\n output &lt;&lt; int(cells[current_index]) &lt;&lt; ' ';\n }\n ~~~\n }\n};\n</code></pre>\n<p>You could even define your own &quot;output formatter&quot; class, something like</p>\n<pre><code>class Brainfuck {\npublic:\n explicit Brainfuck(const std::string&amp; program);\n\n template&lt;class Outputter&gt;\n void execute(std::istream&amp; input, const Outputter&amp; output) const {\n ~~~\n case '.':\n output(cells[current_index]);\n ~~~\n }\n};\n</code></pre>\n<p>which would be called like</p>\n<pre><code>Brainfuck bf(&quot;--[+++++++&lt;----&gt;&gt;--&gt;+&gt;+&gt;+&lt;&lt;&lt;&lt;]&lt;.&gt;++++[-&lt;++++&gt;&gt;-&gt;--&lt;&lt;]&gt;&gt;-.&gt;--..&gt;+.&lt;&lt;&lt;.&lt;&lt;-.&gt;&gt;+&gt;-&gt;&gt;.+++[.&lt;]&quot;);\nbf.execute(std::cin, [&amp;](char ch) {\n std::cout &lt;&lt; ch; // Hello world!\n});\nbf.execute(std::cin, [&amp;](char ch) {\n std::cout &lt;&lt; int(ch) &lt;&lt; ' '; // 72 101 108 ...\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T00:21:51.990", "Id": "504700", "Score": "0", "body": "`Try using a truly infinite tape instead. (Well, up to the limits of your memory allocator, anyway.)`\nGood idea, I agree I should use that as I am aware of that particular data structure and how it works.\n\nI know that C++ also has the static keyword but when I researched how one would implement such utility classes, lots of people suggested using namespaces instead of static functions in a separate class. (`ascii` is a `char` here just so I can check if the user actually typed in `y` or `n` which is of course not optimal and rather lazy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T00:22:13.227", "Id": "504701", "Score": "0", "body": "`Rather than using a bunch of global variables, consider making each instance of class Brainfuck represent an individual program, which you can execute by calling the execute method. So then you can juggle multiple Brainfuck programs within a single C++ program.`\nThat is what I was wondering when I researched how to best go about this design pattern wise, if a class is smart so each program is separate or the aforementioned namespaces.\nI will look into the `iostream` way you suggested, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T14:36:20.897", "Id": "504734", "Score": "0", "body": "\"ascii is a char here just so I can check if the user actually typed in y or n which is of course not optimal\" — Right. This and the iostreams thing are both examples of the \"Separation of Responsibilities\" or \"Single Responsibility Principle.\" `class Brainfuck` is for executing/manipulating BF programs; don't make it _also_ responsible for parsing a user-input `y/n` into a boolean! Write a separate argument-parsing function `bool yesno_to_bool(char ch)` for that, if you need it (but honestly it seems like you don't)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T23:16:49.407", "Id": "255740", "ParentId": "255737", "Score": "8" } } ]
{ "AcceptedAnswerId": "255740", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T21:56:54.117", "Id": "255737", "Score": "8", "Tags": [ "c++", "interpreter", "brainfuck" ], "Title": "Brainfuck interpreter in C++ with namespaces" }
255737
<p>I would like to create a taxi fare calculator which will take as params in a threshold the following:</p> <pre><code>const threshold = [ { id: 1, ord: 1, step_distance: 100, step_time: 120, step_price: 5, threshold: 100, }, { id: 2, ord: 2, step_distance: 100, step_time: 120, step_price: 0.3, threshold: 10000, }, ]; </code></pre> <p>When the ride starts it will take <code>ord</code>: 1 and for every second that is elapsed or new value for distance received it will run a loop to check which of <code>step_distance</code> or <code>step_time</code> has been reached. Then it calculates how many steps are available based on <code>threshold / step_distance</code>. For example in first threshold there is only one step and in second are 100. Once in step one the time reached 120s or 100m it will add $5 for the <code>fare_price</code>, will reset the timer to 0 and will move second threshold. Here every time 100m is reached or 120s the loop will run for 100 times adding to <code>fare_price</code>, $0.3 for each step .</p> <p>The way I've done it is working but I would like to know if there is a better version achieving this.</p> <pre><code>const [initialTime, setInitialTime] = useState(new Date()); const [totalTime, setTotalTime] = useState(0); const [currentOrd, setCurrentOrd] = useState(1); const [currentStep, setCurrentStep] = useState(0); const [currentPrice, setPrice] = useState(0); const [routeTime, setRouteTime] = useState(0); const { distance, time, currentTimeAndDate } = useTracking(true); useEffect(() =&gt; { const currentDistance = distance * 100; const diff = Math.round( moment.duration(moment().diff(initialTime)).asSeconds() ); const totalTime = Math.round( moment.duration(moment().diff(currentTimeAndDate)).asSeconds() ); setRouteTime(diff); setTotalTime(totalTime); if (diff || currentDistance) { track(currentDistance, diff); } return () =&gt; { null; }; }, [distance, time, currentTimeAndDate]); const track = (distance, time) =&gt; { const item = threshold.filter((item) =&gt; item.ord === currentOrd); if (item[0].ord === currentOrd) { const stepDistance = item[0].step_distance; const stepTime = item[0].step_time; const price = item[0].step_price; const thresholdDistance = item[0].threshold; // IF AVAILABLE JUST RUN if (distance &gt;= stepDistance * currentStep || time &gt;= stepTime) { if (thresholdDistance / stepDistance === currentStep) { console.log(&quot;IS MAXIMUM AVAILABLE&quot;); } else { setPrice(currentPrice + price); const currentOrder = currentStep + 1; setCurrentStep(currentOrder); } setInitialTime(new Date()); if (thresholdDistance / stepDistance - currentStep &lt;= 0) { const currentOrder = currentOrd + 1; setCurrentOrd(currentOrder); setCurrentStep(1); } } else { console.log(&quot;Current Distance:&quot;, distance); console.log(&quot;Current Time:&quot;, routeTime); } } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T05:49:37.977", "Id": "504809", "Score": "0", "body": "Didn't quite get the formula understand. To my understanding to the question: If distance reach 100, but time less than 120. We should add 5 to price, reset distance and time to 0, switch to 2nd threshold. If distance less than 100, but time reach 120. We should add 5 to price, reset time, keep distance, and continue use 1st threshold. Is this correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T11:38:13.863", "Id": "504832", "Score": "0", "body": "@tsh actually not. If distance reach 100 but time less than 120 or we reach time 120 while distance is less than 100 we add 5. Then we reset time and move to next threshold. Now if we reach 100 but time less than 120 or we reach 120 and distance less than 100 we add 0.3 and reset time then move to next step if available. In second threshold we have `thresholdDistance / stepDistance = 100 steps` so it will run second step for 100 times" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T09:45:03.997", "Id": "255746", "Score": "0", "Tags": [ "javascript" ], "Title": "Taxi fare calculator based on distance and time in a threshold" }
255746
<p>Recently, our High School teacher gave us a pseudocode <strong>assignment</strong> for the preparation of CAIE's which was a <strong>Railway Management System</strong>. Everyone completed the task in pseudocode which for me was quite an inflexible program. So I tried my own code which is very much flexible than others. It took me a day to complete the code but there were some bugs and errors which took me almost another day to fix. Hence, can anyone <strong>comment on my code</strong> and my <strong>programming skills</strong>? And <strong>guide</strong> me with some <strong>improvements</strong> where necessary?</p> <pre class="lang-py prettyprint-override"><code>departure = ['09:00', '11:00', '13:00', '15:00'] # Timings of Train Departures arrival = ['10:00', '12:00', '14:00', '16:00'] # Timings of Train Arrivals depart_trains = 4 arrival_trains = 4 coaches = 6 total_seats = 80 total_passengers = [0]*len(departure) ticket_price = 25 while departure: print(f&quot;&quot;&quot;{depart_trains} trains departing at: {departure} {arrival_trains} trains arriving at: {arrival} Price of Ticket/person: {ticket_price} dollars Each Train has {coaches} coaches, each coach holding {total_seats} passengers :) &quot;&quot;&quot;) commute = input(&quot;Enter Departure time: &quot;).strip() if commute in departure: index_train = departure.index(commute) print(f&quot;&quot;&quot;You chose Train departing at: {departure[index_train]} &quot;&quot;&quot;) run = True while run: current_passengers = int(input(&quot;How many passengers are to sit: &quot;)) if current_passengers &lt;= coaches*total_seats: total_passengers[index_train] += current_passengers if total_passengers[index_train] == coaches*total_seats: departure.remove(departure[index_train]) arrival.remove(arrival[index_train]) total_passengers.pop(index_train) depart_trains -= 1 arrival_trains -= 1 print(f&quot;&quot;&quot;Your total price is: {current_passengers*ticket_price} dollars &quot;&quot;&quot;) run = False elif total_passengers[index_train] &lt; coaches*total_seats: print(f&quot;&quot;&quot;Your total price is: {current_passengers*ticket_price} dollars &quot;&quot;&quot;) run = False elif total_passengers[index_train] &gt; coaches*total_seats: total_passengers[index_train] -= current_passengers print(f&quot;&quot;&quot;The Train departing at {departure[index_train]} has only {(coaches*total_seats)-total_passengers[index_train]} seats left :( &quot;&quot;&quot;) else: print(f'''Only {coaches*total_seats} seats are available in Train departing at {departure[index_train]} :( ''') else: print(&quot;All Trains are reserved. Come Tomorrow :( &quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T11:02:31.733", "Id": "504724", "Score": "0", "body": "Welcome to CodeReview. Does your code work as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T17:14:36.677", "Id": "504749", "Score": "2", "body": "Welcome to Code Review! 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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T17:16:20.313", "Id": "504750", "Score": "4", "body": "Note- in that version 4 you stated: \"_But I am getting an ```IndexError``` for something which I am not able to find yet. Can anyone suggest me the bug that is causing this?_\" that would me the post [off-topic](https://codereview.stackexchange.com/help/on-topic) so keep that in mind for future questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T07:59:03.420", "Id": "504814", "Score": "2", "body": "If you honestly believed your code was working, but discovered a bug after posting it, then it would have been [appropriate to write an answer](//codereview.meta.stackexchange.com/q/9078/75307) to your own question. A *really good* answer would show how you discovered the bug, and suggest a fix." } ]
[ { "body": "<p>There's nothing that looks bad at a first glance. Couple observations though:</p>\n<ul>\n<li><p>It isn't clear what happens if the time entered isn't in the departure list. Consider adding a default case, even if just to explain to the user that he has to punch in a time present in the list.</p>\n</li>\n<li><p>A negative number of passengers is valid according to your program, but I doubt this is intentional. Always validate user input.</p>\n</li>\n<li><p>An exception is thrown if I enter a string instead of a number when asked for the passenger count. See above ;)</p>\n</li>\n<li><p>At first read, I thought total_seats was, well, the total number of seats but it is the number of seats per coach according to the script output. You might want to clarify that or rename the variable.</p>\n</li>\n<li><p>You can use <code>\\n</code> in your prints to add newlines, I'm not a fan of binding the formatting of your code to the formatting of your output. Both of these lines print the same thing:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>print(f&quot;&quot;&quot;Your total price is: {current_passengers*ticket_price} dollars \n&quot;&quot;&quot;)\nprint(f&quot;&quot;&quot;Your total price is: {current_passengers*ticket_price} dollars \\n&quot;&quot;&quot;)\n</code></pre>\n<ul>\n<li>The <code>run</code> variable isn't as self-documenting as it could be if it was named <code>incorrectInput</code> or <code>retryInput</code> or something like that.</li>\n</ul>\n<p>Take these two more as suggestions than actual issues with your code:</p>\n<ul>\n<li>The fact that your timing system relies on list indexes isn't very pythonic (Explicit is better than implicit). You could use a dict to assign a unique ID to every train... But you'd need a bit more code to reproduce <code>index_train = departure.index(commute)</code>, and I'm not a fan of doing syntax gymnastics in &quot;exam code&quot; so I'd say that your solution is good enough.</li>\n<li>Another pythonic thing, &quot;Ask forgiveness not permission&quot;: you could get rid of the check for wether commut is in departure, do <code>index_train = departure.index(commute)</code> right away and handle the <code>ValueError</code> that gets thrown if commute isn't in departures using a <code>try except</code> block. Your solution is already fine though (and probably less verbose).</li>\n</ul>\n<p>Overall I don't see anything that doesn't work as intended, so it's already pretty solid (as long as the user isn't messing with the input like I did). If it is &quot;exam code&quot; I'd prioritize the formatting and documentation stuff so that your code is more readable. Readable = fast to grade, and fast to grade = less time spend analyzing and figuring out every minor issue with the code ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T17:10:31.107", "Id": "504748", "Score": "0", "body": "Thanks a lot, I have revamped my question thou, can you check it for me please?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T12:18:22.890", "Id": "255755", "ParentId": "255750", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T10:33:14.423", "Id": "255750", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "Railway Management System" }
255750
<p>I've been working on probably my biggest project yet, and I'd like you guys to give me some feedback on the code I wrote so far.</p> <p>It's an eLearning app which offers users a host of functionalities to get better at school subjects, basically. It's centered around mockup tests made up of multiple choice questions added by teachers.</p> <p>Here's the repository: <a href="https://github.com/samul-1/elearning" rel="nofollow noreferrer">https://github.com/samul-1/elearning</a> There, you'll find a more in-depth explanation of the features I'm working on.</p> <p>The project is already fully functional, but I'm working on polishing a few things. The backend is ran by Django, and the frontend is made with Vue.js. I've been at both of these frameworks for around 6-7 months now, so you could say I'm just starting out.</p> <p>Personally, I'm very proud of what I've been able to build so far, but I constantly strive to get better, so I'd like some feedback on these points:</p> <ul> <li>code best practices. Is my code well written, legible, and clear?</li> <li>software architecture. Does my choice of models, views, and data validation make sense?</li> <li>(this might be slightly off-topic so you can skip it) does the user interface look good? What could be done to improve it?</li> </ul> <p>I hope the question isn't too generic as it is right now. If in fact it is, just let me know and I'll edit it to ask about more specific aspects.</p> <p>What I can say already, is that I'm mostly interested in feedback about these files:</p> <pre><code>elearningapp/models.py elearningapp/views.py elearningapp/forms.py users/models.py </code></pre> <p>and the vue components at <code>elearningapp/vue_frontend/src/components</code> (these might be a sore spot).</p> <p>The core of this project can probably be boiled down to the models and views of the <code>elearningapp</code> Django app, so I'll share the code for those two files.</p> <p><code>elearningapp/models.py</code></p> <pre><code># imports class Course(models.Model): name = models.CharField(max_length=100) number_of_questions_per_test = models.IntegerField(default=10) # True if the course has a category distribution, i.e. tests choose a fixed amount of questions from each category uses_category_distribution = models.BooleanField(default=False) points_for_correct_answer = models.FloatField(default=1) points_for_unanswered = models.FloatField(default=0) points_for_wrong_answer = models.FloatField(default=-0.5) minimum_passing_score = models.FloatField(default=5) def __str__(self): return self.name # returns 'amount' random questions that user hasn't seen yet; if category is specified, # the questions will be from that category # raises OutOfQuestionsException if there aren't enough questions that satisfy requirements def get_questions_for(self, user, amount, category=None): # get list of questions already seen by user seen_questions = SeenQuestion.objects.filter(user=user) seen_question_ids = map(lambda q: q.question.pk, seen_questions) questions = Question.objects.filter(course=self).exclude( id__in=seen_question_ids ) if category: questions = questions.filter(category=category) # pick random questions try: random_questions = random.sample(list(questions), amount) except ValueError as err: # if there aren't enough questions left, return None raise OutOfQuestionsException return random_questions # returns an object containing info about the course def get_aggregated_info(self): subscribers = apps.get_model( &quot;users&quot;, model_name=&quot;CourseSpecificProfile&quot; ).objects.filter(course=self) taken_tests = TakenTest.objects.filter(course=self) avg_score = ( (sum([test.score for test in list(taken_tests)]) / taken_tests.count()) if taken_tests.count() &gt; 0 else 0 ) return { &quot;number_of_subscribers&quot;: subscribers.count(), &quot;number_of_tests_taken&quot;: taken_tests.count(), &quot;average_score&quot;: round(avg_score, 1), } # returns 'amount' questions, showing correct answer and solution too # (meant for use inside of course control panel) def get_complete_questions(self, amount, pk_greater_than=0, category=None): questions = self.question_set.filter(pk__gt=pk_greater_than) if category is not None: cat = Category.objects.get(pk=category) questions = questions.filter(category=cat) questions = questions.order_by(&quot;pk&quot;)[:amount] # TODO add sorting return list( map( lambda q: q.format_complete_question(), questions, ) ) # ? move this to CourseSpecificProfile def get_seen_questions(self, user, amount, pk_greater_than=0, category=None): questions = user.seenquestion_set.filter(pk__gt=pk_greater_than) if category is not None: cat = Category.objects.get(pk=category) questions = questions.filter(category=cat) questions = questions.order_by(&quot;pk&quot;)[:amount] # TODO add sorting return list( map( lambda q: q.serialize(), questions, ) ) # returns the 'quantity' hardest questions from this course, # i.e. those with the lowest percentage of times they were answered correctly def get_hardest_questions(self, quantity): return list( map( lambda q: q.format_complete_question(), self.question_set.all().order_by(&quot;percentage_of_correct_answers&quot;)[ :quantity ], ) ) # returns the last 'quantity' actions taken by course admins or collaborators def get_last_actions(self, quantity): return list( map( lambda a: a.serialize(), self.staffaction_set.all().order_by(&quot;-timestamp&quot;)[:quantity], ) ) # returns the profiles of users who are subscribed to this course def get_subscribed_users(self): return list(map(lambda u: u.serialize(), self.coursespecificprofile_set.all())) # returns all the reports that have been made to questions from this course # if resolved is specified, only reports with that status are returned def get_reports(self, resolved=None): reports = Report.objects.filter(question__course=self) if resolved is not None: reports = reports.filter(resolved=resolved) return list(map(lambda r: r.serialize(), reports)) def maximum_score(self): return self.points_for_correct_answer * self.number_of_questions_per_test # used to keep track of courses assistants' permissions # (it's meant to work kinda like Django built-in permission system, but on a per-instance basis rather than per-model) class CoursePermission(models.Model): user = models.OneToOneField(&quot;users.CourseSpecificProfile&quot;, on_delete=models.CASCADE) # course = models.ForeignKey(Course, on_delete=models.CASCADE) can_add_questions = models.BooleanField(default=True) can_edit_questions = models.BooleanField(default=True) can_manage_contributors = models.BooleanField(default=False) # can_edit_contributors = models.BooleanField(default=False) def serialize(self): return { &quot;can_add_questions&quot;: self.can_add_questions, &quot;can_edit_questions&quot;: self.can_edit_questions, &quot;can_manage_contributors&quot;: self.can_manage_contributors, } class Category(models.Model): course = models.ForeignKey( Course, on_delete=models.CASCADE, related_name=&quot;categories&quot; ) # many to one name = models.CharField(max_length=100) # how many questions from this category need to appear in each test of this course # (used only if the course has 'category distribution' enabled) quantity = models.PositiveIntegerField(default=None, null=True) def __str__(self): return self.name class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) # many to one category = models.ForeignKey( Category, null=True, blank=True, default=None, on_delete=models.SET_NULL ) # many to one rendered_text = ( models.TextField() ) # contains public text including html generated by mathjax text = models.TextField( default=&quot;&quot; ) # contains the actual test that was input upon creating the question correct_answer_index = models.PositiveIntegerField() solution_text_rendered = models.TextField() solution_text = models.TextField(default=&quot;&quot;) # TODO add logic to track who added a question added_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) number_of_appearances = models.PositiveIntegerField(default=0) percentage_of_correct_answers = models.FloatField(default=100.0) def __str__(self): return self.text # when model is saved, process the question text to render TeX as svg def save(self, re_render_text=True, *args, **kwargs): # TODO raise exception if question is saved to a category for a course different than that specified in fk Course if re_render_text: self.rendered_text = tex_to_svg(self.text) self.solution_text_rendered = tex_to_svg(self.solution_text) return super(Question, self).save(*args, **kwargs) # returns a dict containing the public information about the question; # i.e. its text and the text of its answers def format_question_for_user(self): output = {} output[&quot;text&quot;] = self.rendered_text # get all answers to the question answers = self.answer_set.all() # Answer.objects.filter(question=self) output[&quot;answers&quot;] = [a.rendered_text for a in list(answers)] return output # returns a dict containing all the information about the question; # i.e. all its public information, the index of the correct answer, and the solution, # as well as the source code for all the texts (question, solution, answers), used for editing a question def format_complete_question(self): info = self.format_question_for_user() info[&quot;textSource&quot;] = self.text info[&quot;solution&quot;] = self.solution_text_rendered info[&quot;solutionSource&quot;] = self.solution_text info[&quot;correctAnswerIndex&quot;] = self.correct_answer_index info[&quot;questionId&quot;] = self.pk info[&quot;category&quot;] = self.category.pk info[&quot;wrongAnswersPercentage&quot;] = 100 - self.percentage_of_correct_answers # get the source text for all the answers answers_sources = Answer.objects.filter(question=self) info[&quot;answersSources&quot;] = [a.text for a in list(answers_sources)] return info # returns the PERCENTAGE of times this question was answered correctly relative to # how many times it appeared in tests # this is intended to be called ONLY by Answer.save() each time this question is answered # to access this property from somewhere else, use the field percentage_of_correct_answers def get_percentage_right_answers(self): right_answer = self.answer_set.get(answer_index=self.correct_answer_index) if self.number_of_appearances == 0: return 100 return right_answer.selections / self.number_of_appearances * 100 # a report made by a user about a question containing a mistake class Report(models.Model): timestamp = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True ) question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) text = models.TextField(default=&quot;&quot;) resolved = models.BooleanField(default=False) def serialize(self): return { &quot;reportId&quot;: self.pk, &quot;timestamp&quot;: str(self.timestamp), &quot;userId&quot;: self.user.pk, &quot;username&quot;: self.user.username, &quot;firstName&quot;: self.user.first_name, &quot;lastName&quot;: self.user.last_name, &quot;question&quot;: self.question.format_complete_question(), &quot;text&quot;: self.text, &quot;resolved&quot;: 1 if self.resolved else 0, } class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) # many to one rendered_text = models.TextField() text = models.TextField(default=&quot;&quot;) answer_index = models.PositiveIntegerField() selections = models.PositiveIntegerField(default=0) def __str__(self): return self.text # when model is saved, process the question text to render TeX as svg # and update the percentage of times the corresponding question was answered correctly def save(self, re_render_text=True, *args, **kwargs): if re_render_text: self.rendered_text = tex_to_svg(self.text) instance = super(Answer, self).save(*args, **kwargs) # re-compute the percentage of correct answers to the question self.question.percentage_of_correct_answers = ( self.question.get_percentage_right_answers() ) self.question.save(re_render_text=False) return instance &quot;&quot;&quot; Models to manage history, active tests, and course cp logs &quot;&quot;&quot; class StaffAction(models.Model): ACTIONS = [ (&quot;C&quot;, &quot;Create&quot;), (&quot;E&quot;, &quot;Edit&quot;), ] course = models.ForeignKey(Course, on_delete=models.CASCADE) # many to one action = models.CharField(max_length=1, choices=ACTIONS) question = models.ForeignKey(Question, on_delete=models.CASCADE) # many to one user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) def __str__(self): return ( str(self.course) + &quot;: &quot; + str(self.user) + &quot; &quot; + str(self.action) + &quot; &quot; + str(self.question) ) def serialize(self): return { &quot;action&quot;: self.action, &quot;user&quot;: self.user.username, &quot;question&quot;: self.question.text, &quot;questionId&quot;: self.question.pk, &quot;timestamp&quot;: str(self.timestamp), } # a test that was taken by a user, detailed with its outcome class TakenTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # many to one course = models.ForeignKey( Course, on_delete=models.CASCADE, null=True ) # many to one timestamp = models.DateTimeField(auto_now=True) score = models.FloatField() passing = models.IntegerField(default=0) # boolean? # returns a json representation of self that the client can consume def serialize(self): json_self = { &quot;score&quot;: self.score, &quot;timestamp&quot;: str(self.timestamp), &quot;correctlyAnsweredQuestions&quot;: [], &quot;unansweredQuestions&quot;: [], &quot;incorrectlyAnsweredQuestions&quot;: [], &quot;passing&quot;: self.passing, } for answer in AnswersInTakenTest.objects.filter(test=self): # get question info and add the answer that was given to this question in the test question_with_your_answer = answer.question.format_complete_question() question_with_your_answer[&quot;yourAnswer&quot;] = answer.answer_index # append question to corresponding list based on whether it was answered correctly, # incorrectly, or left unanswered if answer.answer_index == -1: json_self[&quot;unansweredQuestions&quot;].append(question_with_your_answer) elif answer.answer_index == answer.question.correct_answer_index: json_self[&quot;correctlyAnsweredQuestions&quot;].append( question_with_your_answer ) else: json_self[&quot;incorrectlyAnsweredQuestions&quot;].append( question_with_your_answer ) return json_self # a question that appeared on a TakenTest, and its answer class AnswersInTakenTest(models.Model): test = models.ForeignKey(TakenTest, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) # ? should probably use null instead of -1 for unanswered answer_index = models.IntegerField() # -1 if unanswered # a question that was seen by the user, together with its answer # needs a separate model from TakenTest because the history of seen questions # is erasable, whereas that of taken tests isn't class SeenQuestion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, null=True, on_delete=models.CASCADE) # ? should probably use null instead of -1 for unanswered answer_index = models.IntegerField(default=-1) # -1 if unanswered timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { &quot;questionId&quot;: self.pk, &quot;question&quot;: self.question.format_complete_question(), &quot;givenAnswer&quot;: self.answer_index, } # a test currently, associated to a user: used in case they leave and come back to the test # to retrieve the data without generating a new one, as well as to keep track of what questions # the answers given by the user need to be checked against class ActiveTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) questions = models.ManyToManyField(Question) course = models.ForeignKey(Course, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) # chooses random questions that the requesting user hasn't seen yet according to the course distribution (if any) # and adds them to the ManyToMany relationship with Question def init_test(self): if not self.course.uses_category_distribution: # course doesn't have a category distribution (or questions for this course aren't grouped in categories) for question in self.course.get_questions_for( self.user, self.course.number_of_questions_per_test ): self.questions.add(question) else: chosen_questions = [] # get the right number of questions for each category for category in self.course.categories.all(): chosen_questions.extend( list( self.course.get_questions_for( self.user, category.quantity, category ) ) ) random.shuffle(chosen_questions) for question in chosen_questions: self.questions.add(question) self.save() # returns a list containing all questions of the test, # formatted to display their public information def format_test_for_user(self): output = [] i = 1 for question in self.questions.all(): # add question index to dict for displaying to the user temp = question.format_question_for_user() temp[&quot;idx&quot;] = i output.append(temp) i += 1 return output # takes in a dict containing the answers to the test's questions; computes the result, # updates data about questions and answers, saves the test questions to the history of # seen questions, and returns a TakenTest object detailing the outcome of the test def evaluate_answers(self, answers): taken_test = TakenTest(user=self.user, course=self.course, score=0) taken_test.save() # update the number of tests taken by the user user_profile = self.user.coursespecificprofile_set.get(course=self.course) user_profile.number_of_tests_taken += 1 user_profile.save() questions = self.questions.all() # ? could use select_related('answer_set') score = 0 for question, answer in zip( questions, map(lambda a: answers[a], answers) ): # map {index:answer} to answer # increment number of appearances of this question question.number_of_appearances += 1 question.save(re_render_text=False) # increment number of selections for this answer if answer != -1: given_answer = question.answer_set.get(answer_index=answer) print(given_answer) given_answer.selections += 1 given_answer.save(re_render_text=False) # record given answer for history ans = AnswersInTakenTest( answer_index=answer, question=question, test=taken_test ) ans.save() # record question for (deletable) history seen_question = SeenQuestion( user=self.user, question=question, answer_index=answer ) seen_question.save() if int(answer) == question.correct_answer_index: score += self.course.points_for_correct_answer elif int(answer) == -1: score += self.course.points_for_unanswered else: score += self.course.points_for_wrong_answer if score &gt; self.course.minimum_passing_score: taken_test.passing = 1 # using 1, 0 instead of True, False to make it easier to convert to JSON else: taken_test.passing = 0 taken_test.score = score taken_test.save() user_profile.last_score = score user_profile.save() return taken_test </code></pre> <p><code>elearningapp/views.py</code></p> <pre><code># imports @login_required def create_course(request): if not request.user.globalprofile.is_teacher: return HttpResponseForbidden() if request.method == &quot;POST&quot;: form_data = json.loads(request.body.decode(&quot;utf-8&quot;)) form = CourseForm(form_data, user=request.user.globalprofile) print(form_data) if form.is_valid(): new_course = form.save() CourseSpecificProfile.objects.create(user=request.user, course=new_course) else: print(form.errors) return JsonResponse({&quot;courseId&quot;: new_course.pk}, safe=False) # GET return render( request, &quot;elearningapp/createcourse.html&quot;, ) # course control panel @login_required def course_cp(request, course_id): course = get_object_or_404(Course, pk__exact=course_id) # reject with 403 if user isn't authorized to view the control panel for this course if course not in request.user.globalprofile.admin_of.all() and ( request.user.coursespecificprofile_set.filter(course=course).count == 0 or not hasattr( request.user.coursespecificprofile_set.get(course=course), &quot;coursepermission&quot;, ) ): return HttpResponseForbidden() aggregated_info = course.get_aggregated_info() context = { &quot;course&quot;: course, &quot;reports&quot;: course.get_reports(resolved=False), &quot;last_actions&quot;: course.get_last_actions(5), &quot;number_of_subscribers&quot;: aggregated_info[&quot;number_of_subscribers&quot;], &quot;number_of_tests_taken&quot;: aggregated_info[&quot;number_of_tests_taken&quot;], &quot;average_score&quot;: aggregated_info[&quot;average_score&quot;], &quot;hardest_questions&quot;: course.get_hardest_questions(3), &quot;admin&quot;: &quot;true&quot; if course in request.user.globalprofile.admin_of.all() else &quot;false&quot;, # using 'true' and 'false' to prevent issues with js frontend consuming the value } # get user's permissions, if they have a permission object associated to them (admins don't) if len( course_profile := request.user.coursespecificprofile_set.filter(course=course) ) != 0 and hasattr(course_profile[0], &quot;coursepermission&quot;): context[&quot;my_permissions&quot;] = json.dumps( course_profile[0].coursepermission.serialize() ) context[&quot;user_id&quot;] = course_profile[0].pk else: context[&quot;my_permissions&quot;] = {} context[ &quot;user_id&quot; ] = &quot;null&quot; # once again using 'null' as a string for easier passing of the value as a prop return render( request, &quot;elearningapp/course_cp.html&quot;, context, ) # accessed via GET, returns a list of users subscribed to the course @login_required def get_course_users(request, course_id): course = get_object_or_404(Course, pk__exact=course_id) return JsonResponse(course.get_subscribed_users(), safe=False) # accessed via GET, returns a lit of reports that have been made to questions from the course @login_required def get_course_reports(request, course_id): course = get_object_or_404(Course, pk__exact=course_id) return JsonResponse(course.get_reports(), safe=False) # if accessed via GET, gets the first 5 questions for the course and renders template containing the EditQuestion component # if accessed via PUT, updates the question # if question_id is specified, the id is passed via the context object to EditQuestion vue component @login_required def edit_question(request, course_id, question_id=None): course = get_object_or_404(Course, pk__exact=course_id) # reject with 403 if user isn't authorized to edit questions for this course if course not in request.user.globalprofile.admin_of.all() and ( request.user.coursespecificprofile_set.filter(course=course).count == 0 or not hasattr( request.user.coursespecificprofile_set.get(course=course), &quot;coursepermission&quot;, ) or not request.user.coursespecificprofile_set.get( course=course ).coursepermission.can_edit_questions ): return HttpResponseForbidden() if request.method == &quot;PUT&quot;: form_data = json.loads(request.body.decode(&quot;utf-8&quot;)) question = get_object_or_404(Question, pk=form_data[&quot;questionId&quot;]) form = QuestionForm(form_data, user=request.user, action=&quot;E&quot;, instance=question) print(form_data) if form.is_valid(): print(&quot;is valid&quot;) updated_question = form.save() print(updated_question) return JsonResponse(updated_question.format_complete_question(), safe=False) else: print(form.errors) # GET categories = Category.objects.filter(course=course) questions = course.get_complete_questions(5) context = { &quot;course_id&quot;: course_id, &quot;categories&quot;: [{c.pk: c.name} for c in categories], &quot;questions&quot;: questions, } if question_id is not None: context[&quot;editing_id&quot;] = question_id return render( request, &quot;elearningapp/edit_question.html&quot;, context, ) # if accessed via POST, creates a new report for the specified question # if accessed via PUT, updates the status of the specified report @login_required def report_question(request): if request.method != &quot;POST&quot; and request.method != &quot;PUT&quot;: return HttpResponseNotAllowed() form_data = json.loads(request.body.decode(&quot;utf-8&quot;)) if request.method == &quot;POST&quot;: question = get_object_or_404(Question, pk__exact=form_data[&quot;questionId&quot;]) form = ReportForm(form_data, user=request.user, question=question) if form.is_valid(): # add new report to db form.save() return JsonResponse({&quot;success&quot;: True}) else: print(form.errors) if request.method == &quot;PUT&quot;: report = get_object_or_404(Report, pk__exact=form_data[&quot;reportId&quot;]) # add report text to form data as it is a mandatory field that isn't supplied when the view is accessed via PUT # ? maybe there's a better way to do this form_data[&quot;text&quot;] = report.text form = ReportForm(form_data, instance=report, resolved=form_data[&quot;resolved&quot;]) print(form_data) if form.is_valid(): print(&quot;is valid&quot;) form.save() return JsonResponse({&quot;success&quot;: True}) else: print(form.errors) # if accessed via PUT, updates or creates the permissions of a user for a course, # if accessed via DELETE, deletes the permission object for the specified user and course def update_course_permissions(request, course_id): if request.method == &quot;GET&quot;: return HttpResponseNotAllowed() course = get_object_or_404(Course, pk__exact=course_id) # reject with 403 if user isn't authorized to add assistants for this course if course not in request.user.globalprofile.admin_of.all() and ( request.user.coursespecificprofile_set.filter(course=course).count == 0 or not hasattr( request.user.coursespecificprofile_set.get(course=course), &quot;coursepermission&quot;, ) or not request.user.coursespecificprofile_set.get( course=course ).coursepermission.can_manage_contributors ): return HttpResponseForbidden() form_data = json.loads(request.body.decode(&quot;utf-8&quot;)) print(form_data) editing_profile = get_object_or_404( CourseSpecificProfile, pk=form_data[&quot;profile_id&quot;] ) if request.method == &quot;PUT&quot;: # cannot edit permissions of a course admin if course in editing_profile.user.globalprofile.admin_of.all(): return HttpResponseForbidden() # retrieve or create permissions for this user # we don't need the boolean returned by get_or_create, hence the _ wildcard permissions, _ = CoursePermission.objects.get_or_create(user=editing_profile) form = PermissionForm(form_data[&quot;permissions&quot;], instance=permissions) print(form_data) if form.is_valid(): form.save() return JsonResponse({&quot;success&quot;: True}) else: print(form.errors) if request.method == &quot;DELETE&quot;: try: permissions = CoursePermission.objects.get(user=editing_profile) except CoursePermission.DoesNotExist: return HttpResponseNotFound() permissions.delete() return JsonResponse({&quot;success&quot;: True}) # accessed via GET by the client for infinite scrolling in the EditQuestion vue component @login_required def get_questions(request, course_id, amount, starting_from_pk, category=None): course = get_object_or_404(Course, pk__exact=course_id) questions = course.get_complete_questions( int(amount), pk_greater_than=int(starting_from_pk), category=category ) return JsonResponse(questions, safe=False) # accessed via GET by the client for infinite scrolling in the QuestionHistory vue component @login_required def get_seen_questions(request, course_id, amount, starting_from_pk, category=None): course = get_object_or_404(Course, pk__exact=course_id) questions = course.get_seen_questions( request.user, int(amount), pk_greater_than=int(starting_from_pk), category=category, ) print(questions) return JsonResponse(questions, safe=False) # renders template containing CreateQuestion vue component when accessed via GET, # handles question creation using Question ModelForm when accessed via POST @login_required def add_question(request, course_id): course = get_object_or_404(Course, pk__exact=course_id) # reject with 403 if user isn't authorized to add questions to this course if course not in request.user.globalprofile.admin_of.all() and ( request.user.coursespecificprofile_set.filter(course=course).count == 0 or not hasattr( request.user.coursespecificprofile_set.get(course=course), &quot;coursepermission&quot;, ) or not request.user.coursespecificprofile_set.get( course=course ).coursepermission.can_add_questions ): return HttpResponseForbidden() categories = Category.objects.filter(course=course) context = { &quot;course_id&quot;: course_id, &quot;categories&quot;: [{c.pk: c.name} for c in categories], } if request.method == &quot;POST&quot;: form_data = json.loads(request.body.decode(&quot;utf-8&quot;)) form = QuestionForm(form_data, user=request.user, action=&quot;C&quot;) if form.is_valid(): # add new question to db new_question = form.save() return JsonResponse(&quot;ok&quot;, safe=False) else: print(form.errors) return JsonResponse({&quot;success&quot;: True}) # GET return render( request, &quot;elearningapp/add_question.html&quot;, context, ) # renders a test for the user @login_required def render_test(request, course_id): requesting_user = request.user # User.objects.get(pk=user_id) course = Course.objects.get(pk=course_id) if ActiveTest.objects.filter(user=requesting_user, course=course).count() &gt; 0: # user already has an active test associated to them; use that one # instead of creating a new one current_test = ActiveTest.objects.get(user=requesting_user, course=course) else: # no active tests found for this user; # create a new test associated to requesting user in selected course try: current_test = ActiveTest(user=requesting_user, course=course) current_test.save() current_test.init_test() except OutOfQuestionsException: # delete the test that was attempted to be initialized if exception occurs current_test.delete() # TODO show an actual page return HttpResponse(&quot;out of questions&quot;) # get user's global data global_profile = GlobalProfile.objects.get(user=request.user) global_user_data = { &quot;name&quot;: global_profile.user.username, &quot;id&quot;: global_profile.user.pk, } context = { &quot;course_id&quot;: course.pk, &quot;questions&quot;: current_test.format_test_for_user(), &quot;global_user_data&quot;: global_user_data, } return render(request, &quot;elearningapp/test.html&quot;, context) # returns the list of questions that the user has seen in past tests @login_required def question_history(request, course_id): user_profile = get_object_or_404( CourseSpecificProfile, user__exact=request.user, course__pk__exact=course_id ) course = Course.objects.get(pk=course_id) seen_questions = course.get_seen_questions(user=request.user, amount=5) # seen_questions = map( # lambda sq: sq.serialize(), list(user_profile.get_seen_questions()) # ) return render( request, &quot;elearningapp/question_history.html&quot;, { &quot;questions&quot;: list(seen_questions), &quot;user_id&quot;: request.user.pk, &quot;course_id&quot;: course_id, }, ) # empties the list of seen question for given user and course @login_required def delete_question_history(request, course_id): user_profile = get_object_or_404( CourseSpecificProfile, user__exact=request.user, course__pk__exact=course_id ) for question in user_profile.get_seen_questions(): question.delete() return JsonResponse(&quot;ok&quot;, safe=False) # returns the list of tests that the user has taken in the past @login_required def test_history(request, course_id): user_profile = get_object_or_404( CourseSpecificProfile, user__exact=request.user, course__pk__exact=course_id ) taken_tests = map(lambda t: t.serialize(), list(user_profile.get_taken_tests())) return render( request, &quot;elearningapp/test_history.html&quot;, { &quot;tests&quot;: list(taken_tests), &quot;maxScore&quot;: Course.objects.get(pk=course_id).maximum_score(), }, ) # calls a method to evaluate the answers given, save the question and test outcome to user's history; # returns details about the outcome of the test @login_required def check_answers(request): if request.method != &quot;POST&quot;: return HttpResponseNotAllowed() answers = json.loads(request.body.decode(&quot;utf-8&quot;)) print(answers) # TODO check validity of sent json object requesting_user = request.user # ! TODO check course in addition to requesting user current_test = ActiveTest.objects.get(user=requesting_user) outcome = current_test.evaluate_answers(answers) # current_test.delete() return JsonResponse(outcome.serialize()) # retrieves context for rendering the course dashboard @login_required def view_course(request, course_id): course = get_object_or_404(Course, pk=course_id) # get course's data course_data = { &quot;name&quot;: course.name, &quot;id&quot;: course.pk, } # get user's global data global_profile = GlobalProfile.objects.get( user=request.user ) # we can assume this exists because it's created at signup time and the view has @login_required global_user_data = { &quot;name&quot;: global_profile.user.first_name if global_profile.user.first_name != &quot;&quot; else global_profile.user.username, &quot;id&quot;: global_profile.user.pk, } try: course_profile = CourseSpecificProfile.objects.get( user=request.user, course__pk=course_id ) except CourseSpecificProfile.DoesNotExist: # user isn't signed up to this course, give them a chance to return render( request, &quot;course_register.html&quot;, { &quot;global_user_data&quot;: global_user_data, &quot;course_data&quot;: course_data, }, ) # get user's course specific data course_specific_user_data = { &quot;number_of_tests_taken&quot;: course_profile.number_of_tests_taken, &quot;last_score&quot;: course_profile.last_score, &quot;average_score&quot;: round(course_profile.get_average_score(), 1), &quot;last_scores&quot;: course_profile.get_last_scores(5), } return render( request, &quot;elearningapp/course_dashboard.html&quot;, { &quot;global_user_data&quot;: global_user_data, &quot;course_specific_user_data&quot;: course_specific_user_data, &quot;course_data&quot;: course_data, }, ) </code></pre> <p>And here's a brief explanation of what the app does: teachers can sign up and create courses, to which they can add questions and categories to divide the questions into. Students can then sign up to courses and take tests made up of randomly chosen questions among those in the course. After the test is over, the questions are saved to the user's personal history (an erasable history) and don't show up again (unless the history is cleared), and the results of the tests are saved to a separate (persistent) history to check progress over time. There's a whole host of additional features like a course control panel for teachers to track stats about their course, add assistants, and so on, as well as the possibility for users to report errors in questions.</p> <p>I really love doing this and I want to be as good at it as I can. So thank you to anybody who will take time to review my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:14:28.390", "Id": "505878", "Score": "0", "body": "Well this is whole lot of review you are asking. It would be easier and faster more efficient to do it if you present a portion of the code base like one of the class or some dependent classes for system design and architectural decisions review. \nAnd I recommend to make those reviews separate as code review and system design reviews are two separate parts. The more specific we are, better review we can get.\nI have raised some issues in your project after just skimming through the README and code. \nI hope it helps." } ]
[ { "body": "<h1>Code Review - elearningapp/models.py - Course</h1>\n<p><em>FYKI - Im not a Python expert!</em></p>\n<blockquote>\n<p>Anit's recommendation are marked like this!</p>\n</blockquote>\n<p>Well the first thing I would do is make separate files for the classes.</p>\n<pre><code>class Course(models.Model):\n name = models.CharField(max_length=100)\n number_of_questions_per_test = models.IntegerField(default=10)\n</code></pre>\n<blockquote>\n<p>Lets remove comments as such! The code should be good enough to do it.\n# True if the course has a category distribution, i.e. tests choose a fixed amount of questions from each category</p>\n</blockquote>\n<blockquote>\n<p>I'm not against snake_case but I would prefer CamelCase. Why waste <code>_</code>.\n<code>uses_category_distribution</code> to <code>useDistribution</code>? Do you like this?</p>\n</blockquote>\n<pre><code> uses_category_distribution = models.BooleanField(default=False)\n points_for_correct_answer = models.FloatField(default=1)\n points_for_unanswered = models.FloatField(default=0)\n points_for_wrong_answer = models.FloatField(default=-0.5)\n minimum_passing_score = models.FloatField(default=5)\n\n def __str__(self):\n return self.name\n</code></pre>\n<blockquote>\n<p>It's good to see you are trying to document function but I believe that it helps a lot when we follow some standards. What do you think? Well this is a good resource: <a href=\"https://docs.python-guide.org/writing/documentation\" rel=\"nofollow noreferrer\">https://docs.python-guide.org/writing/documentation</a></p>\n</blockquote>\n<pre><code> # returns 'amount' random questions that user hasn't seen yet; if category is specified,\n # the questions will be from that category\n # raises OutOfQuestionsException if there aren't enough questions that satisfy requirements\n</code></pre>\n<blockquote>\n<p>The function name could be more specific and suttle. Simply <code>quesiton</code> or <code>makeQuestion</code> or <code>generateQuestion</code> would be sufficient I believe!</p>\n</blockquote>\n<pre><code> def get_questions_for(self, user, amount, category=None):\n</code></pre>\n<blockquote>\n<p>Would you think if we move this to another function it would help make this function be more clean? And probably just pass the ID here, which is easier to test?\n# get list of questions already seen by user\nseen_questions = SeenQuestion.objects.filter(user=user)\nseen_question_ids = map(lambda q: q.question.pk, seen_questions)</p>\n</blockquote>\n<pre><code> questions = Question.objects.filter(course=self).exclude(\n id__in=seen_question_ids\n )\n</code></pre>\n<blockquote>\n<p>The code below has the option to choose a question if the category exits, else it's doing something. Im sorry but I was a bit confused. So instead of why don;t we try to find some better way to do it? This definitely looks like more conditions are required to clarify things. Also we can find some better way to use try/catch.\nif category:\nquestions = questions.filter(category=category)</p>\n</blockquote>\n<pre><code> # pick random questions\n try:\n random_questions = random.sample(list(questions), amount)\n except ValueError as err: # if there aren't enough questions left, return None\n raise OutOfQuestionsException\n\n return random_questions\n\n\n # returns an object containing info about the course\n def get_aggregated_info(self):\n subscribers = apps.get_model(\n &quot;users&quot;, model_name=&quot;CourseSpecificProfile&quot;\n ).objects.filter(course=self)\n taken_tests = TakenTest.objects.filter(course=self)\n\n avg_score = (\n (sum([test.score for test in list(taken_tests)]) / taken_tests.count())\n if taken_tests.count() &gt; 0\n else 0\n )\n\n return {\n &quot;number_of_subscribers&quot;: subscribers.count(),\n &quot;number_of_tests_taken&quot;: taken_tests.count(),\n &quot;average_score&quot;: round(avg_score, 1),\n }\n\n\n # returns 'amount' questions, showing correct answer and solution too\n # (meant for use inside of course control panel)\n def get_complete_questions(self, amount, pk_greater_than=0, category=None):\n questions = self.question_set.filter(pk__gt=pk_greater_than)\n if category is not None:\n cat = Category.objects.get(pk=category)\n questions = questions.filter(category=cat)\n\n questions = questions.order_by(&quot;pk&quot;)[:amount]\n # TODO add sorting\n return list(\n map(\n lambda q: q.format_complete_question(),\n questions,\n )\n )\n\n\n # ? move this to CourseSpecificProfile\n def get_seen_questions(self, user, amount, pk_greater_than=0, category=None):\n questions = user.seenquestion_set.filter(pk__gt=pk_greater_than)\n</code></pre>\n<blockquote>\n<p>Condition are the important part of our understanding so IMHO it would be great to see a line above them.\nif category is not None:\ncat = Category.objects.get(pk=category)\nquestions = questions.filter(category=cat)</p>\n</blockquote>\n<pre><code> questions = questions.order_by(&quot;pk&quot;)[:amount]\n</code></pre>\n<blockquote>\n<p>Let's not have this comment here. Every implementation must be complete.\n# TODO add sorting</p>\n</blockquote>\n<pre><code> return list(\n map(\n lambda q: q.serialize(),\n questions,\n )\n )\n\n\n # returns the 'quantity' hardest questions from this course,\n # i.e. those with the lowest percentage of times they were answered correctly\n def get_hardest_questions(self, quantity):\n return list(\n map(\n lambda q: q.format_complete_question(),\n self.question_set.all().order_by(&quot;percentage_of_correct_answers&quot;)[\n :quantity\n ],\n )\n )\n\n # returns the last 'quantity' actions taken by course admins or collaborators\n def get_last_actions(self, quantity):\n return list(\n map(\n lambda a: a.serialize(),\n self.staffaction_set.all().order_by(&quot;-timestamp&quot;)[:quantity],\n )\n )\n</code></pre>\n<blockquote>\n<p>This functionality probably fits more in <code>user</code> model. What do you think?\n# returns the profiles of users who are subscribed to this course\ndef get_subscribed_users(self):\nreturn list(map(lambda u: u.serialize(), self.coursespecificprofile_set.all()))</p>\n</blockquote>\n<pre><code> # returns all the reports that have been made to questions from this course\n # if resolved is specified, only reports with that status are returned\n def get_reports(self, resolved=None):\n reports = Report.objects.filter(question__course=self)\n\n if resolved is not None:\n reports = reports.filter(resolved=resolved)\n return list(map(lambda r: r.serialize(), reports))\n</code></pre>\n<blockquote>\n<p>We can come up with a better function name :/)\ndef maximum_score(self):\nreturn self.points_for_correct_answer * self.number_of_questions_per_test</p>\n</blockquote>\n<hr />\n<p>From the model implementation perspective, I believe a Repository Pattern would be helpful. Furthermore, I can see a lot of <code>lambda</code> usage but it would be better if we can use write plain sql query to fetch the data instead of using objects instances of other <code>model</code> as that would be more efficient.</p>\n<hr />\n<h1>Recommended Read</h1>\n<p>This is really a great beginning in the start phases, a lot of learning awaits. I would recommend</p>\n<ul>\n<li>Clean Code <a href=\"https://github.com/codeanit/til/issues/215\" rel=\"nofollow noreferrer\">https://github.com/codeanit/til/issues/215</a></li>\n<li>Design Patterns, Principles <a href=\"https://trello.com/b/GGhug4Bh/journey-of-a-software-engineer\" rel=\"nofollow noreferrer\">https://trello.com/b/GGhug4Bh/journey-of-a-software-engineer</a></li>\n<li>Clean Architecture <a href=\"https://github.com/codeanit/til/issues/224\" rel=\"nofollow noreferrer\">https://github.com/codeanit/til/issues/224</a></li>\n</ul>\n<p>Well this is a long, long, a long way to go but the effort is appreciable!</p>\n<p>I wish you all the very best!</p>\n<p>I hope it helps.</p>\n<p>Cheers,</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T16:38:07.430", "Id": "256266", "ParentId": "255751", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T11:14:59.823", "Id": "255751", "Score": "3", "Tags": [ "python", "python-3.x", "django" ], "Title": "eLearning webapp made with Django" }
255751
<p>I am trying to read and parse an XML file inside of a ZIP archive as fast as possible. The XML file is roughly 85GB in size, so I know for a fact that I/O also plays a role here, as I need to essentially read 85GB total. However, reading 85GB on a 500 MB/s SSD, means I can do this in less than 3 minutes, if we ignore CPU, decompression, and so on.</p> <p>As I cannot store the ZIP file nor XML file in memory, I've streamed the content, and it works really well. Reading and parsing 100.000 XML nodes/elements (which is roughly 450.000 lines of XML) takes about 10 seconds. Don't get me wrong: Reading 400.000+ lines of XML and parsing it in ~10 seconds is fast. But it's not as fast as I want.</p> <p>Multi threading this is probably not an option, but I am interested in hearing, if it's possible to speed this up.</p> <p><code>_models</code> is just a <code>List&lt;Model&gt;</code> that I use to keep my objects in, which gets cleared once they're saved to the database.</p> <pre><code>public static async Task Main(string[] args) { XmlReaderSettings settings = new XmlReaderSettings(); settings.Async = true; using (var stream = new ZipInputStream(File.OpenRead($@&quot;C:\file.zip&quot;))) { // this is fine, as we know there is only 1 file in the ZIP stream.GetNextEntry(); using (XmlReader reader = XmlReader.Create(stream, settings)) { reader.MoveToContent(); while (await reader.ReadAsync()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == &quot;ns:ElementName&quot;) { await ExtractModel(reader); } } } } } // await save to database } private static async Task ExtractModel(XmlReader reader) { XElement el = XNode.ReadFrom(reader) as XElement; var serializer = new XmlSerializer(typeof(Model)); var model = (Model)serializer.Deserialize(el.CreateReader()); _models.Add(model); // save 100.000 models to database if (_models.Count == 100000) { //await save to database _models.Clear(); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T14:05:45.003", "Id": "504732", "Score": "0", "body": "You do a `new XmlSerializer(typeof(Model))` each time you call `ExtractModel`: why not do this once at class level and then re-use the same serializer? Also, you can do `var settings = new XmlReaderSettings { Async = true };`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T14:33:45.433", "Id": "504733", "Score": "0", "body": "@BCdotWEB The performance gained from not newing up a new XmlSerializer was next to nothing. Even if I do that, all of the checks and calls inside of Main (even the one to ExtractModel) says < 1 milliseconds. So nothing is \"taking too long\", it's simply slow because of the sheer amount of data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T15:10:36.663", "Id": "504737", "Score": "0", "body": "@MortenMoulder Have you used some sort of profiling tool like [CodeTrack](https://www.getcodetrack.com/) to know where does your code spend most of its time? If so, could you please share with us the results? Please also share with us the expected performance requirement. *But it's not as fast as I want.* << It is not a requirement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T18:55:09.963", "Id": "504766", "Score": "0", "body": "@PeterCsala I did not use a profiling tool, no. But if I put down a breakpoint and step through it, I can see how long each line of code takes to execute. And we're talking < 1 millisecond for each one. If I put a break point at the beginning of the code in the while loop, and one at the `save to database` line, it takes ~10 seconds for it to reach it. Simply because it has to run the exact same code 100.000 times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:06:28.453", "Id": "504781", "Score": "0", "body": "Tip: `as fast as possible` - don't use async file API then, use synchronous instead (even with `Task.Run`), it's slightly faster. There's a bug in .NET that makes whole async File API slow. You may also test and compare the performance to ensure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T23:06:53.457", "Id": "504791", "Score": "0", "body": "@aepot I removed everything that was async so the whole model is now synchronous instead. I implemented a Stopwatch before and after testing, and the only difference was maybe on average about 0.5 seconds per 100.000. Still takes ~10 seconds. Thanks, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T23:44:27.030", "Id": "504793", "Score": "0", "body": "OK, maybe bottle neck is out here, you may also play with buffers size for streams. Then run CPU profiler and see what exactly takes a lot of time. Also you may develop double-buffer mode. While you filling one `List` of 100k, you may dump already filled to DB at the same time. Then change the lists 2nd fill, 1st dump, etc. Async/concurrent work probably can be fine here, maybe with producer/consumer programming pattern. If you filling exactly 100k or less you may use arrays instead of lists with power of `ArrayPool<T>` to recycle arrays, instead allocating it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T00:04:29.833", "Id": "504794", "Score": "1", "body": "@aepot Thanks for the reply. I've moved to array instead of List, and it seems like it has improved the speed a bit. However, instead of doing the `XNode.ReadFrom(reader) as XElement` and so on, I can use `reader.ReadSubtree()` which gave a huge speed improvement. It's about 40% faster now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T08:08:25.373", "Id": "504816", "Score": "1", "body": "@MortenMoulder Why don't use proper dedicated tools to profile and measure. `Stopwatch` is not dedicated for performance measurement. Have you tried [Benchmark.net](https://github.com/dotnet/BenchmarkDotNet)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:26:42.530", "Id": "504823", "Score": "0", "body": "@PeterCsala Oh I know Stopwatch isn't exactly the best, but when we're talking 10+ seconds, it's fine for that. I don't exactly need perfect \"how much faster is it\". I just need \"is it faster or not\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T10:28:25.173", "Id": "504829", "Score": "0", "body": "How long does the deserialization to Model take?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T12:21:17.037", "Id": "504833", "Score": "0", "body": "I would get rid of `XmlSerializer` and `XElement`. I would manually take the data from the `XmlReader` and populate the model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T12:24:40.227", "Id": "504834", "Score": "0", "body": "And, of course, saving to the database should be done in a separate thread. So that the parsing thread doesn't wait." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T11:41:03.820", "Id": "255752", "Score": "2", "Tags": [ "c#", "xml", "stream", ".net-core" ], "Title": "Read compressed XML file inside ZIP and parse data as fast as possible" }
255752
<p>I've written a program which does the following things:</p> <ul> <li>calls third-party utility to get mp3 file fingerprint</li> <li>asks MusicBrainz IDs from AcoustID service</li> <li>asks metadata from MusicBrainz for each ID</li> </ul> <p>I've never used networking in C# before, so might have done some mistakes in my code (or some parts of it might be unreliable). That's why I'm posting this.</p> <p>P.S. I'm targeting .NET 4.0 and prefer to avoid using of 3rd-party external libraries for communicating with remote hosts, deserializing JSON documents, etc.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; namespace ConsoleApplication16 { [DataContract] class acoustid_mbids { [DataContract] public class result{ [DataMember] public double score { get; set; } [DataMember] public string id { get; set; } [DataMember] public recording[] recordings { get; set; } } [DataContract] public class recording { [DataMember] public string id { get; set; } } [DataMember] public string status { get; set; } [DataMember] public result[] results { get; set; } } [DataContract] class recording { [DataMember] public string title { get; set; } [DataMember] public string length { get; set; } [DataMember(Name = &quot;artist-credit&quot;)] public artist[] artists { get; set; } [DataMember] public genre[] genres { get; set; } [DataMember] public release[] releases { get; set; } [DataContract] public class artist { [DataMember] public string name; [DataMember] public string joinphrase; } [DataContract] public class genre { [DataMember] public int count; [DataMember] public string name; } [DataContract] public class release { [DataMember] public string title; [DataMember] public string date; [DataMember] public string id; //required for fetching artwork } } class Program { public static List&lt;recording&gt; avail_recordings = new List&lt;recording&gt;(); public static List&lt;string&gt; fpcalc_output = new List&lt;string&gt;(); public const string API_KEY=&quot;xxxxxxx&quot;; public static HttpWebRequest request; public static HttpWebResponse response; static void Main(string[] args) { DataContractJsonSerializer parseJson; using (Process proc = new Process()) { proc.StartInfo.FileName = &quot;fpcalc.exe&quot;; proc.StartInfo.Arguments = &quot; Kalimba.mp3&quot;; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); proc.Start(); proc.BeginOutputReadLine(); proc.WaitForExit(); } ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; request = (HttpWebRequest)HttpWebRequest.Create(&quot;http://api.acoustid.org/v2/lookup?client=&quot;+API_KEY+&quot;&amp;duration=&quot;+fpcalc_output[0].Replace(&quot;DURATION=&quot;,String.Empty)+&quot;&amp;fingerprint=&quot;+fpcalc_output[1].Replace(&quot;FINGERPRINT=&quot;,String.Empty)+&quot;&amp;meta=recordingids&quot;); request.Method = &quot;GET&quot;; response = (HttpWebResponse)request.GetResponse(); parseJson = new DataContractJsonSerializer(typeof(acoustid_mbids)); acoustid_mbids acoustid_session = (acoustid_mbids)parseJson.ReadObject(response.GetResponseStream()); parseJson = new DataContractJsonSerializer(typeof(recording)); response.Close(); response = null; for (int i = 0; i &lt; acoustid_session.results.Length; i++) { for (int j = 0; j &lt; acoustid_session.results[i].recordings.Length; j++) { request = (HttpWebRequest)HttpWebRequest.Create(&quot;http://musicbrainz.org/ws/2/recording/&quot; + acoustid_session.results[i].recordings[j].id + &quot;?fmt=json&amp;inc=artist-credits+releases+genres&quot;); request.KeepAlive = false; request.Method = &quot;GET&quot;; request.UserAgent = &quot;SimpleID3Editor/1.0 ( maxvoloshin71@mail.ru )&quot;; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { Console.WriteLine((int)((HttpWebResponse)ex.Response).StatusCode); break; } if (response != null) { avail_recordings.Add((recording)parseJson.ReadObject(response.GetResponseStream())); response.Close(); } } } Console.ReadKey(); } static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine(&quot;Called!&quot;); fpcalc_output.Add(e.Data); } } } </code></pre>
[]
[ { "body": "<p>Here are my observations:</p>\n<ul>\n<li>There are couple of unused namespaces\n<ul>\n<li>right click on the namespaces then select the <em>Remove and Sort Usings</em>\nmenuitem</li>\n</ul>\n</li>\n<li><code>acoustid_mbids</code> \\ <code>recording</code>: The general guideline is to prefer Pascal Case for class names.\n<ul>\n<li>So, <code>AcoustidMbids</code> and <code>Recording</code> would be the suggested names.</li>\n<li>Please applies these naming for the sub-classes as well.</li>\n</ul>\n</li>\n<li><code>DataMember</code>: This attribute can be really useful when you specify its <code>Name</code> property as well.\n<ul>\n<li>With that you can separete the naming of the json elements from your application logic:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>[DataContract(Name = &quot;acoustid_mbids&quot;)]\nclass AcoustidMbids\n{\n [DataContract(Name = &quot;result&quot;)]\n public class Result\n {\n [DataMember(Name =&quot;score&quot; )]\n public double Score { get; set; }\n [DataMember(Name = &quot;id&quot;)]\n public string Id { get; set; }\n [DataMember(Name = &quot;recordings&quot;)]\n public Recording[] Recordings { get; set; }\n }\n \n ...\n}\n</code></pre>\n<ul>\n<li><code>Main</code>: Please try to avoid to put everything into the <code>Main</code> method.\n<ul>\n<li>Try to split into smaller chunks, like this:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main(string[] args)\n{\n List&lt;string&gt; fpcalc_output = GetMetaFromMP3(&quot;Kalimba.mp3&quot;);\n AcoustidMbids acoustid_session = GetMetaFromAcoustid(fpcalc_output);\n List&lt;Recording&gt; avail_recordings = GetMetaFromMusicbrainz(acoustid_session);\n}\n</code></pre>\n<ul>\n<li><code>static HttpWebRequest request</code>: Please try to avoid to reuse <code>HttpWebRequest</code> and <code>HttpWebResponse</code> objects.\n<ul>\n<li>Each method (<code>GetMetaFromAcoustid</code> and <code>GetMetaFromMusicbrainz</code>) should take care of their own instances.</li>\n</ul>\n</li>\n<li><code>proc.StartInfo.FileName = &quot;fpcalc.exe&quot;;</code>: You can <a href=\"https://www.dotnetperls.com/process\" rel=\"nofollow noreferrer\">separate process and its ProcessStartInfo setup</a>.\n<ul>\n<li>This might increase legibility:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var processInfo = new ProcessStartInfo\n{\n FileName = &quot;fpcalc.exe&quot;,\n Arguments = &quot; Kalimba.mp3&quot;,\n RedirectStandardOutput = true,\n UseShellExecute = false,\n};\n\nusing (Process proc = Process.Start(processInfo))\n{\n proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);\n proc.BeginOutputReadLine();\n proc.WaitForExit();\n}\n</code></pre>\n<ul>\n<li><code>new DataReceivedEventHandler(proc_OutputDataReceived)</code>: You can make use of the Lambda expressions to create an anonymous delegate:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>proc.OutputDataReceived += (s, e) =&gt;\n{\n Console.WriteLine(&quot;Called!&quot;);\n fpcalc_output.Add(e.Data);\n};\n</code></pre>\n<ul>\n<li><code>(SecurityProtocolType)3072</code>: Please try to avoid using magic numbers and use constants instead.\n<ul>\n<li>Tls12 is not part of the .Net Framework 4.0 (it <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.securityprotocoltype?view=netframework-4.5\" rel=\"nofollow noreferrer\">was introduced</a> in .NET 4.5)</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>const int Tls12 = 3072;\n...\nServicePointManager.SecurityProtocol |= (SecurityProtocolType)Tls12;\n</code></pre>\n<ul>\n<li><code>request = (HttpWebRequest)HttpWebRequest.Create(</code>: As I stated earlier please try to use seperate instances for each call.\n<ul>\n<li><code>GET</code> is the default method so you don't have to specify that:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var request = (HttpWebRequest)WebRequest.Create(url);\n</code></pre>\n<ul>\n<li><code>&quot;&amp;duration=&quot; + fpcalc_output[0].Replace(&quot;DURATION=&quot;, String.Empty)</code>:\n<ul>\n<li>Please try to separate data retrieval logic from url creation:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var duration = fpcalc_output[0].Replace(&quot;DURATION=&quot;, string.Empty);\nvar fingerprint = fpcalc_output[1].Replace(&quot;FINGERPRINT=&quot;, string.Empty);\nvar url = &quot;http://api.acoustid.org/v2/lookup?client=&quot; + API_KEY + &quot;&amp;duration=&quot; + duration + &quot;&amp;fingerprint=&quot; + fingerprint + &quot;&amp;meta=recordingids&quot;;\n</code></pre>\n<ul>\n<li>Please try to prefer <code>string.Empty</code> over <code>String.Empty</code>. Please read this <a href=\"https://blog.paranoidcoding.com/2019/04/08/string-vs-String-is-not-about-style.html\" rel=\"nofollow noreferrer\">paranoid coding article</a> to better understand the difference.</li>\n<li>Please also bear in mind <code>fpcalc_output[1]</code> can throw <code>OutOfRangeException</code> if it does not have that many element in the collection.\n<ul>\n<li>Try to use some parsing logic to make your code more robust:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>string durationKey = &quot;DURATION=&quot;\nint durationIdx = fpcalc_output.FindIndex(a =&gt; a.Contains(durationKey));\nif(durationIdx == -1) throw new InvalidOperationException(&quot;Duration is missing from the fpcalc result&quot;); \nfpcalc_output[durationIdx].Replace(durationKey, string.Empty);\n</code></pre>\n<ul>\n<li>You should also consider to use some built-in utility to construct QueryParameters, like: <code>System.Web.HttpUtility.ParseQueryString</code>(<a href=\"https://stackoverflow.com/questions/829080/how-to-build-a-query-string-for-a-url-in-c\">Related SO topic</a>)</li>\n<li><code>response = (HttpWebResponse)request.GetResponse()</code>: Before you perform any further action, please check the <code>StatusCode</code> of the response.\n<ul>\n<li>If it is different than the expected then web api call most probably\nfailed so it does not make sense to run your code futher.</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>response = (HttpWebResponse)request.GetResponse();\nif(response.StatusCode != HttpStatusCode.OK)\n throw new InvalidOperationException(&quot;acoustid did not respond in the expected way.&quot;);\n</code></pre>\n<ul>\n<li><code>response.GetResponseStream()</code>: Please bear in mind that here you are using a stream. Which should be disposed if there is no further need for that. <a href=\"https://stackoverflow.com/questions/137285/what-is-the-best-way-to-read-getresponsestream\">Related SO topic</a></li>\n<li><code>parseJson.ReadObject</code>: This can throw <code>SerializationException</code> if the service response differs from the expected structure. Prepare for this case as well to make your solution more robust.</li>\n<li><code>for (int i = 0; i &lt; acoustid_session.results.Length; i++)</code>: Prefer foreach over for loop (this could highly improve legibility:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var result in acoustid_session.results)\nforeach (var record in result.Recordings)\n{\n ...\n}\n</code></pre>\n<ul>\n<li><code>response.Close()</code>: As said earlier please prefer using over explicit call of <code>Close</code>.\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/137285/what-is-the-best-way-to-read-getresponsestream\">Related SO topic</a></li>\n</ul>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T14:17:22.173", "Id": "255759", "ParentId": "255756", "Score": "3" } }, { "body": "<p>Some quick remarks:</p>\n<ul>\n<li><p>Properly name things. <code>avail_recordings</code> and <code>fpcalc_output</code> do not follow the Microsoft guidelines (e.g. don't use &quot;snake case&quot;, don't needlessly abbreviate,...).</p>\n</li>\n<li><p><code>request = (HttpWebRequest)HttpWebRequest.Create(&quot;http://api.acoustid.org/v2/lookup?client=&quot;+API_KEY+&quot;&amp;duration=&quot;+fpcalc_output[0].Replace(&quot;DURATION=&quot;,String.Empty)+&quot;&amp;fingerprint=&quot;+fpcalc_output[1].Replace(&quot;FINGERPRINT=&quot;,String.Empty)+&quot;&amp;meta=recordingids&quot;);</code> is nearly impossible to read.</p>\n<p>Consider using something like <code>new List&lt;KeyValuePair&lt;string, string&gt;&gt;</code> and store each key/value pair of the query string as a <code>KeyValuePair&lt;string, string&gt;</code> and then compile the query string from that collection with <code>.Select(x =&gt; string.Format(&quot;{0}={1}&quot;, x.Key, x.Value))</code> or <a href=\"https://stackoverflow.com/a/829138/648075\">use a <code>NameValueCollection</code></a>.</p>\n</li>\n<li><p>Split your code into smaller methods/classes which do a single thing. Have one method that calls <code>fpcalc</code>, another that calls <code>acoustid.org</code>, another that calls <code>musicbrainz.org</code>, etc.</p>\n</li>\n<li><p>Considering that you never use <code>i</code> and <code>j</code> except to access a particular item in a collection, why don't you use <code>foreach</code>?</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T14:20:58.077", "Id": "255760", "ParentId": "255756", "Score": "3" } } ]
{ "AcceptedAnswerId": "255759", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T12:18:44.043", "Id": "255756", "Score": "2", "Tags": [ "c#", "json", "http", "networking", "web-services" ], "Title": "Getting metadata from MusicBrainz service" }
255756
<p>I have an Oracle 18c table that has an <a href="https://docs.oracle.com/database/121/SPATL/sdo_geometry-object-type.htm#SPATL489" rel="nofollow noreferrer">SDO_GEOEMTRY</a> column.</p> <pre><code>create table a_test_sdo_geom (id number, shape mdsys.sdo_geometry); insert into a_test_sdo_geom (id, shape) values(1, sdo_util.from_wktgeometry ( 'MULTILINESTRING ((671834.096 4861699.7127, 671836.5099 4861701.9158), (671838.2206 4861700.7607, 671842.2311 4861703.3157))')); insert into a_test_sdo_geom (id, shape) values(2, sdo_util.from_wktgeometry ( 'MULTILINESTRING ((671800.123 4861600.1234, 671800.1234 4861700.1234)))')); commit; </code></pre> <p>And I have a sister table that stores the <strong>vertices</strong> of from that table as rows:</p> <pre><code>create table a_test_vertices (id number, vertex_num number, x number, y number); insert into a_test_vertices ( select a.id, v.id as vertex_num, v.x, v.y from a_test_sdo_geom a ,table(sdo_util.getvertices(a.shape)) v ); commit; ID VERTEX_NUM X Y ---------- ---------- ---------- ---------- 1 1 671834.096 4861699.71 1 2 671836.510 4861701.92 1 3 671838.221 4861700.76 1 4 671842.231 4861703.32 2 1 671800.123 4861600.12 2 2 671800.123 4861700.12 </code></pre> <hr /> <p>I have a <strong>trigger</strong> that will automatically update the vertices table whenever the source table's SHAPE gets updated:</p> <ul> <li>When a source row is created</li> <li>When a source row is deleted</li> <li>When the source SHAPE column is updated (but not when any of the other columns get updated)</li> </ul> <hr /> <pre><code>create or replace trigger a_test_sdo_geom_trig before insert or update of shape or delete on a_test_sdo_geom for each row begin case when inserting then insert into a_test_vertices (id, vertex_num, x, y) select :new.id, id, x, y from table(sdo_util.getvertices(:new.shape)); when deleting then delete a_test_vertices where id = :old.id; when updating('shape') then merge into a_test_vertices a using (select id, x, y from table(sdo_util.getvertices(:new.shape))) b on (a.vertex_num = b.id and a.id = :old.id) when matched then update set x = b.x ,y = b.y when not matched then insert(id, vertex_num, x, y) values(:old.id, b.id, b.x, b.y); end case; end a_test_sdo_geom_trig; </code></pre> <hr /> <p><strong>Question:</strong></p> <p>Can the trigger be improved?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T13:47:31.573", "Id": "255757", "Score": "0", "Tags": [ "geospatial", "oracle", "plsql" ], "Title": "Trigger to update vertices table" }
255757
<p>In my requestForm submit function I have this logic that checks three checkboxes and then displays the label with an error message. Is there better logic? I would be happy for any kind of feedback since this is quite critical a part of my application.</p> <pre><code>$(&quot;#requestForm&quot;).submit(function (e) { e.stopPropagation(); e.preventDefault(); var checked_sourcecheckboxes = $(&quot;#sources input[type=checkbox]:checked&quot;); if (checked_sourcecheckboxes.length == 0) { $(&quot;#lblSourcesError&quot;).show(); return false; } else { $(&quot;#lblSourcesError&quot;).hide(); } var checked_academicformatcheckboxes = $(&quot;#academicFormatsRow input[type=checkbox]:checked&quot;); if (checked_academicformatcheckboxes.length == 0) { $(&quot;#lblacademicFormatError&quot;).show(); return false; } else { $(&quot;#lblacademicFormatError&quot;).hide(); } var checked_academicmediaformatcheckboxes = $(&quot;#academicMediaFormatRow input[type=checkbox]:checked&quot;); if (checked_academicmediaformatcheckboxes.length == 0) { $(&quot;#lblacademicmediaFormatError&quot;).show(); return false; } else { $(&quot;#lblacademicmediaFormatError&quot;).hide(); } }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T16:08:30.460", "Id": "504860", "Score": "1", "body": "what about the `return false;` logic? that will stop the loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T18:39:43.843", "Id": "504881", "Score": "1", "body": "You also should post the HTML. Because I would suggest some change... It seems you only use `id` and you could have a way simpler logic if you'd use classes on the checkboxes and error messages." } ]
[ { "body": "<h2>Main Question</h2>\n<blockquote>\n<p>Is there better logic?</p>\n</blockquote>\n<h3>Repeated code</h3>\n<p>The first thing that I see with this code, which perhaps you see also, is that it is quite repetitive - select a list of checkboxes to see if any are checked - if none are checked then show an error message and return, otherwise hide any affiliated error message. This violates the <a href=\"https://deviq.com/principles/dont-repeat-yourself\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself principle</a>. It can be remedied by abstracting the common logic - e.g. putting the the selectors into a mapping:</p>\n<pre><code>var SELECTOR_ERROR_MAPPING = {\n &quot;#sources input[type=checkbox]:checked&quot;: &quot;#lblSourcesError&quot;, \n &quot;#academicFormatsRow input[type=checkbox]:checked&quot;: &quot;lblacademicFormatError&quot;,\n //...more entries\n};\n \n</code></pre>\n<p>Then use a loop to iterate over the mapping, checking each selector - e.g. using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every#browser_compatibility\" rel=\"nofollow noreferrer\"><code>Array.every()</code></a>:</p>\n<pre><code>return Object.keys(SELECTOR_ERROR_MAPPING).every(function(selector) {\n var errorSelector = SELECTOR_ERROR_MAPPING[selector];\n\n var showError = !$(selector).length;\n $(errorSelector).toggle(showError, errorSelector);\n return !showError;\n});\n</code></pre>\n<p>Those last three lines of the inner function could be placed into a separate function if desired, which would allow for better modularization/atomization and testing.</p>\n<h3>demo</h3>\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>var SELECTOR_ERROR_MAPPING = {\n \"#sources input[type=checkbox]:checked\": \"#lblSourcesError\",\n \"#academicFormatsRow input[type=checkbox]:checked\": \"#lblacademicFormatError\",\n \"#academicMediaFormatRow input[type=checkbox]:checked\": \"#lblacademicmediaFormatError\",\n //...more entries\n};\n$(\"#requestForm\").submit(function(e) {\n e.stopPropagation();\n e.preventDefault();\n\n var allValid = Object.keys(SELECTOR_ERROR_MAPPING).every(function(selector) {\n var errorSelector = SELECTOR_ERROR_MAPPING[selector];\n\n var showError = !$(selector).length;\n $(errorSelector).toggle(showError, errorSelector);\n return !showError;\n });\n console.log('result', allValid);\n return allValid;\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.error {\n color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;form id=\"requestForm\"&gt;\n &lt;div id=\"sources\"&gt;\n &lt;h3&gt; Source &lt;/h3&gt;\n &lt;label&gt;Audi \n &lt;input type=\"checkbox\" name=\"source\" value=\"Audi\" /&gt;\n &lt;/label&gt;\n &lt;label&gt;BMW \n &lt;input type=\"checkbox\" name=\"source\" value=\"BMW\" /&gt;\n &lt;/label&gt;\n &lt;div class=\"error\" id=\"lblSourcesError\" style=\"display: none\"&gt;Please select a source&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"academicFormatsRow\"&gt;\n &lt;h3&gt; Formats &lt;/h3&gt;\n &lt;label&gt;College \n &lt;input type=\"checkbox\" name=\"source\" value=\"college\" /&gt;\n &lt;/label&gt;\n &lt;label&gt;University\n &lt;input type=\"checkbox\" name=\"source\" value=\"university\" /&gt;\n &lt;/label&gt;\n &lt;div class=\"error\" id=\"lblacademicFormatError\" style=\"display: none\"&gt;Please select a format&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;div id=\"academicMediaFormatRow\"&gt;\n &lt;h3&gt; Media Formats &lt;/h3&gt;\n &lt;label&gt;DVD \n &lt;input type=\"checkbox\" name=\"source\" value=\"DVD\" /&gt;\n &lt;/label&gt;\n &lt;label&gt;Blue-ray\n &lt;input type=\"checkbox\" name=\"source\" value=\"blueray\" /&gt;\n &lt;/label&gt;\n &lt;div class=\"error\" id=\"lblacademicmediaFormatError\" style=\"display: none\"&gt;Please select a media format&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;button&gt;Submit&lt;/button&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Modern browsers support client-side validation using the <code>required</code> attribute on input elements<sup><a href=\"https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation\" rel=\"nofollow noreferrer\">1</a></sup> and it is supported for checkbox inputs<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#validation\" rel=\"nofollow noreferrer\">2</a></sup> but apparently setting a custom message for checkboxes still involves writing some JavaScript<sup><a href=\"https://stackoverflow.com/a/38853115/1575353\">3</a></sup>.</p>\n<h3>HTML layout</h3>\n<p>As one comment suggested, the dependence on the <em>id</em> attribute could be decreased - For example, if the location of the error message element was consistent within each section -e.g. a sibling of the list of checkbox inputs. Another solution might be to have each section of checkboxes and error message contained by a parent element with a consistent class name- then the JavaScript could loop over those container elements looking to see if the checkbox elements have any checked- if not, then display the error message.</p>\n<h1>Other review points</h1>\n<h2>ES6</h2>\n<p>With modern JavaScript, consider using newer EcmaScript-2015 (AKA ES6) features, like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loops</a>, the keywords <code>let</code> and <code>const</code> instead of <code>var</code>, etc.</p>\n<h2>jQuery</h2>\n<p>Also consider whether you really need jQuery because <a href=\"http://youmightnotneedjquery.com/\" rel=\"nofollow noreferrer\">it may be the case it can be replaced with “vanilla JS” features</a>. For example, to select elements with a CSS selector use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll\" rel=\"nofollow noreferrer\"><code>document.querySelectorAll()</code></a> and to add an event listener for the form submission, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\">the <code>addEventListener()</code> method</a> after selecting that form element - e.g. with <code>document.getElementById('requestForm')</code>, <code>document.forms[0]</code> unless it isn't the first form, etc..</p>\n<h2>Loose comparisons</h2>\n<p>In the original code the length property of the jQuery objects was compared with 0 using loose equality - i.e. <code>==</code>. A good habit and recommendation of many style guides is to use strict equality operators (i.e. <code>===</code>, <code>!==</code>) whenever possible. The problem with loose comparisons is that it has <a href=\"https://stackoverflow.com/q/359494\">so many weird rules</a> one would need to memorize in order to be confident in its proper usage.</p>\n<p>The suggested code above and below simplified this by using <code>!$(checkboxSelector).length;</code></p>\n<h3>demo</h3>\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 SELECTOR_ERROR_MAPPING = {\n \"#sources input[type=checkbox]:checked\": \"#lblSourcesError\",\n \"#academicFormatsRow input[type=checkbox]:checked\": \"#lblacademicFormatError\",\n \"#academicMediaFormatRow input[type=checkbox]:checked\": \"#lblacademicmediaFormatError\",\n //...more entries\n};\ndocument.forms[0].addEventListener('submit', e =&gt; {\n e.stopPropagation();\n e.preventDefault();\n\n for (const [selector, errorSelector] of Object.entries(SELECTOR_ERROR_MAPPING)) {\n const showError = !document.querySelectorAll(selector).length;\n document.querySelector(errorSelector).classList.toggle('hidden', !showError);\n if (showError) {\n return false;\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.error {\n color: red;\n}\n.hidden {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;form id=\"requestForm\"&gt;\n &lt;div id=\"sources\"&gt;\n &lt;h3&gt; Source &lt;/h3&gt;\n &lt;label&gt;Audi \n &lt;input type=\"checkbox\" name=\"source\" value=\"Audi\" /&gt;\n &lt;/label&gt;\n &lt;label&gt;BMW \n &lt;input type=\"checkbox\" name=\"source\" value=\"BMW\" /&gt;\n &lt;/label&gt;\n &lt;div class=\"error hidden\" id=\"lblSourcesError\"&gt;Please select a source&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"academicFormatsRow\"&gt;\n &lt;h3&gt; Formats &lt;/h3&gt;\n &lt;label&gt;College \n &lt;input type=\"checkbox\" name=\"source\" value=\"college\" /&gt;\n &lt;/label&gt;\n &lt;label&gt;University\n &lt;input type=\"checkbox\" name=\"source\" value=\"university\" /&gt;\n &lt;/label&gt;\n &lt;div class=\"error hidden\" id=\"lblacademicFormatError\"&gt;Please select a format&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;div id=\"academicMediaFormatRow\"&gt;\n &lt;h3&gt; Media Formats &lt;/h3&gt;\n &lt;label&gt;DVD \n &lt;input type=\"checkbox\" name=\"source\" value=\"DVD\" /&gt;\n &lt;/label&gt;\n &lt;label&gt;Blue-ray\n &lt;input type=\"checkbox\" name=\"source\" value=\"blueray\" /&gt;\n &lt;/label&gt;\n &lt;div class=\"error hidden\" id=\"lblacademicmediaFormatError\"&gt;Please select a media format&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;button&gt;Submit&lt;/button&gt;\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-16T19:05:42.477", "Id": "256107", "ParentId": "255764", "Score": "3" } } ]
{ "AcceptedAnswerId": "256107", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:15:50.930", "Id": "255764", "Score": "3", "Tags": [ "javascript", "jquery", "validation", "event-handling" ], "Title": "Submitting form jQuery checkboxlist" }
255764
<p>I have the following code below that takes a new row added to my Google Spreadsheet (has a header row) and extracts the video ID. If the ID does not exist in the playlist, it adds the video to the playlist. If it doesn't, it skips it. Not really comfortable with Google Apps Script, so I would like some constructive feedback.</p> <pre><code>function addVideoToYouTubePlaylist() { // retrieve video ID list from the playlist. var playlistId = &quot;PL6bCFcS8yqQxSPjwZ9IXFMfVm6kaNGLfi&quot;; var list = []; var pageToken = &quot;&quot;; do { var res = YouTube.PlaylistItems.list([&quot;snippet&quot;], {playlistId: playlistId, maxResults: 50, pageToken: pageToken}); if (res.items.length &gt; 0) list = list.concat(res.items); pageToken = res.nextPageToken || &quot;&quot;; } while (pageToken); var obj = list.reduce((o, e) =&gt; Object.assign(o, {[e.snippet.resourceId.videoId]: e.snippet.resourceId.videoId}), {}); // read the source videos from Google Sheet var sheet = SpreadsheetApp.getActiveSheet(); var data = sheet.getDataRange().getValues(); // iterate through all rows in the sheet for (var d=1,l=data.length; d&lt;l; d++) { var videoId = extractVideoID(data[d][0]); if (!obj[videoId]) { YouTube.PlaylistItems.insert({ snippet: { playlistId: playlistId, resourceId: { kind: &quot;youtube#video&quot;, videoId: extractVideoID(videoId) } } }, &quot;snippet&quot;); } else{ console.log(&quot;Already in playlist&quot;); } sheet.deleteRow(d+1); // delete row after video is checked } } function extractVideoID(url){ var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&amp;\?]*).*/; var match = url.match(regExp); if ( match &amp;&amp; match[7].length == 11 ){ return match[7]; } else if (!( match &amp;&amp; match[7].length == 11 )){ console.log(&quot;Could not extract video ID.&quot;); var trimmedVideoID = url.replace(&quot;https://youtu.be/&quot;, &quot;&quot;); trimmedVideoID = trimmedVideoID.replace('https://www.youtube.com/watch?v=', &quot;&quot;); trimmedVideoID = trimmedVideoID.replace('https://youtube.com/watch?v=', &quot;&quot;); trimmedVideoID = trimmedVideoID.replace(&quot;&amp;feature=youtu.be&quot;, &quot;&quot;); trimmedVideoID = trimmedVideoID.replace(&quot;&amp;feature=share&quot;, &quot;&quot;); console.log(trimmedVideoID); return trimmedVideoID; } } </code></pre>
[]
[ { "body": "<p>Let's start with <code>extractVideoID()</code>.</p>\n<p>Your regex <code>/^.*((youtu.be\\/)|(v\\/)|(\\/u\\/\\w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&amp;\\?]*).*/</code> doesn't guarantee the URL has a YouTube format. For example, the URL <code>www.google.com/watch?v=01$@T$89h</code> does match the regex and has the following groups: <code>[&quot;www.google.com/watch?v=0123456&quot;, &quot;watch?&quot;, undefined, undefined, undefined, undefined, &quot;watch?&quot;, &quot;01$@T$89h&quot;]</code>, where the 7th group <code>01$@T$89h</code> isn't a valid YouTube video ID.</p>\n<p>I suggest you replace your regex with <code>/^((?:https?:)?\\/\\/)?((?:www|m)\\.)?((?:youtube\\.com|youtu.be))(\\/(?:[\\w\\-]+\\?v=|embed\\/|v\\/)?)([\\w\\-]+)(\\S+)?$/</code> (<a href=\"https://regexr.com/3dj5t\" rel=\"nofollow noreferrer\">source</a>). This regex only matches valid YouTube URLs format, and the 5th group is the ID of the video. Notice that a valid YouTube URL along with a video ID <strong>doesn't guarantee that the video exist</strong>. You can use <a href=\"https://developers.google.com/youtube/v3/docs/videos/list\" rel=\"nofollow noreferrer\"><code>YouTube.Videos.list()</code></a> to test if the video for the given ID exists.</p>\n<pre><code> if ( match &amp;&amp; match[7].length == 11 ){\n return match[7];\n }\n else if (!( match &amp;&amp; match[7].length == 11 )){ // equivalent of else {}\n // multiple attempts to replace\n return trimmedVideoID;\n }\n</code></pre>\n<p>The <code>if..else if</code> block is bad. If you find a match, you return the ID. Done. So <code>extractVideoID()</code> has only one purpose: if the URL has a valid format, return the ID. Otherwise, i.e., if it doesn't find a match, then <code>extractVideoID()</code> should return <code>null</code>.</p>\n<pre><code>if (match &amp;&amp; match[5])\n return match[5];\n</code></pre>\n<p>In your code, the <code>else if</code> block is opposite of the first <code>if</code>, so it is actually an <code>else</code> block. This also means that, altought you couldn't find any match, you are returning anything anyway, even if <code>url</code> is garbage like <code>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</code>.</p>\n<p>Now, with <code>addVideoToYouTubePlaylist()</code>.</p>\n<p><code>pageToken = res.nextPageToken || &quot;&quot;;</code></p>\n<p>The <code>nextPageToken</code> is a string for the next page, so unless <code>YouTube.PlaylistItems.list()</code> fails - and thow an error, stopping everything - it won't evaluate to false. And if it does, you are restarting all over again, possibly heading to the same <code>falsy</code> value thus creating an infinite loop.</p>\n<p><code>for (var d=1,l=data.length; d&lt;l; d++) {</code></p>\n<p>You can test <code>d &lt; data.length</code> directly for improved reading.</p>\n<pre><code> var videoId = extractVideoID(data[d][0]);\n if (!obj[videoId]) {\n YouTube.PlaylistItems.insert({\n</code></pre>\n<p>You may want to test if the video with the given ID exists before of inserting it in the playlist.</p>\n<pre><code> resourceId: {\n kind: &quot;youtube#video&quot;,\n videoId: extractVideoID(videoId)\n }\n</code></pre>\n<p>Without chaning <code>extractVideoID()</code> and passing a valid ID to it returns <code>null</code>.</p>\n<p><code>sheet.deleteRow(d+1); // delete row after video is checked</code></p>\n<p>When you delete row number <code>d+1</code>, what was in row <code>(d+1)+1</code> now is in row <code>d+1</code>. Because of that, you need a counter of deleted rows, say <code>r</code>, and delete the row number <code>d+1-r</code> to compensate the upward &quot;shift&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T16:45:10.540", "Id": "505083", "Score": "0", "body": "Thank you for the in-depth explanation of everything. However, I'm having a hard time putting all this together. Do you think you could point me in the right direction?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T17:02:44.140", "Id": "505084", "Score": "0", "body": "You should start with `extractVideoID()` for it to test the url with the regex from the answer to test if there is a match and the match also has an id, i.e., the 5th group is not empty. Otherwise, don't return anything and move forward to the next url." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T13:49:28.237", "Id": "255845", "ParentId": "255765", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:18:45.870", "Id": "255765", "Score": "1", "Tags": [ "google-apps-script", "youtube" ], "Title": "New Spreadsheet Row to YouTube Playlist" }
255765
<p>I've written a function that returns which player is closer to a given 2D grid within a larger 2D grid. I would like to make the function shorter (in LOC) and better. I would appreciate any advice on this topic. it gets location for both players(x and y) and same for the carpet(the smaller grid), and than calculate the distance b/w each player to the carpet. the reason it takes so much if's is because i'm calculating x from x and y from y, and if the player is on the far side of x/y i have to add size to compassion. that's why i have an if for every corner plus if player is in the range of y/x</p> <pre><code>public static int getWhoIsCloser( int xFirstPlayer, int yFirstPlayer, int xSecondPlayer, int ySecondPlayer, int xCarpet, int yCarpet, int size) { size = size - 1; int xFirstPlayerProximity = 0; int yFirstPlayerProximity = 0; int xSecondPlayerProximity = 0; int ySecondPlayerProximity = 0; int firstPlayerResult; int secondPlayerResult; if (xFirstPlayer &gt;= xCarpet &amp;&amp; xFirstPlayer &lt;= xCarpet + size) { yFirstPlayer -= (yCarpet + size); firstPlayerResult = Math.abs(yFirstPlayer); } else if (yFirstPlayer &gt;= yCarpet &amp;&amp; yFirstPlayer &lt;= yCarpet + size) { xFirstPlayer -= (xCarpet + size); firstPlayerResult = Math.abs(xFirstPlayer); } else { if (xFirstPlayer &lt; xCarpet &amp;&amp; yFirstPlayer &lt; yCarpet) { xFirstPlayerProximity = xFirstPlayer - xCarpet; yFirstPlayerProximity = yFirstPlayer - yCarpet; } else if (xFirstPlayer &lt; xCarpet &amp;&amp; yFirstPlayer &gt; yCarpet) { xFirstPlayerProximity = xFirstPlayer - xCarpet; yFirstPlayerProximity = yFirstPlayer - (yCarpet + size); } else if (xFirstPlayer &gt; xCarpet &amp;&amp; yFirstPlayer &lt; yCarpet) { xFirstPlayerProximity = xFirstPlayer - (xCarpet + size); yFirstPlayerProximity = yFirstPlayer - yCarpet; } else if (xFirstPlayer &gt; xCarpet &amp;&amp; yFirstPlayer &gt; yCarpet) { xFirstPlayerProximity = xFirstPlayer - (xCarpet + size); yFirstPlayerProximity = yFirstPlayer - (yCarpet + size); } firstPlayerResult = Math.abs(xFirstPlayerProximity) + Math.abs(yFirstPlayerProximity); } if (xSecondPlayer &gt;= xCarpet &amp;&amp; xSecondPlayer &lt;= xCarpet + size) { ySecondPlayer -= (yCarpet + size); secondPlayerResult = Math.abs(ySecondPlayer); } else if (ySecondPlayer &gt;= yCarpet &amp;&amp; ySecondPlayer &lt;= yCarpet + size) { xSecondPlayer -= (xCarpet + size); secondPlayerResult = Math.abs(xSecondPlayer); } else { if (xSecondPlayer &lt; xCarpet &amp;&amp; ySecondPlayer &lt; yCarpet) { xSecondPlayerProximity = xSecondPlayer - xCarpet; ySecondPlayerProximity = ySecondPlayer - (yCarpet); } else if (xSecondPlayer &lt; xCarpet &amp;&amp; ySecondPlayer &gt; yCarpet) { xSecondPlayerProximity = xSecondPlayer - (xCarpet); ySecondPlayerProximity = ySecondPlayer - (yCarpet + size); } else if (xSecondPlayer &gt; xCarpet &amp;&amp; ySecondPlayer &lt; yCarpet) { xSecondPlayerProximity = xSecondPlayer - (xCarpet + size); ySecondPlayerProximity = ySecondPlayer - yCarpet; } else if (xSecondPlayer &gt; xCarpet &amp;&amp; ySecondPlayer &gt; yCarpet) { xSecondPlayerProximity = xSecondPlayer - (xCarpet + size); ySecondPlayerProximity = ySecondPlayer - (yCarpet + size); } secondPlayerResult = Math.abs(xSecondPlayerProximity) + Math.abs(ySecondPlayerProximity); } if (firstPlayerResult &gt; secondPlayerResult) { return 2; } else if (firstPlayerResult &lt; secondPlayerResult) { return 1; } else { return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:48:52.357", "Id": "504743", "Score": "2", "body": "Welcome to Code Review! I've [edited](https://codereview.stackexchange.com/posts/255768/revisions) your question to make it a bit more clear; please feel free to [edit](https://codereview.stackexchange.com/posts/255768/edit) it yourself to add any additional details or clarity. In particular, please add more details as to what you are actually trying to accomplish and why; currently that is unclear from the question, which makes this question **off topic**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T19:54:54.677", "Id": "504887", "Score": "0", "body": "(`compassion` looks the wrong word.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T20:05:29.997", "Id": "504888", "Score": "0", "body": "(0 both players outside: compare distance (as in, you *don't* need to know either exact distance or what it means: you just need to compare)1/2: one player inside: closer, definitely. 3 both inside: up to definition)" } ]
[ { "body": "<ol>\n<li>You are exactly duplicating the code for checking the distance for player 1 and player 2. You could move that code into a separate <code>getDistanceToCarpet</code> function, and have the <code>getWhoIsCloser</code> function call that twice.</li>\n<li>If I understand your code correctly, you seem to be using so-called <a href=\"https://en.wikipedia.org/wiki/Taxicab_geometry\" rel=\"nofollow noreferrer\">taxicab distance</a>, meaning the total distance is equal to the X distance plus the Y distance (this is perfectly valid, as long as you're doing it on purpose). This is convenient, because it lets you separately calculate the X and Y distances and then just add them together.</li>\n<li>Let's look at just the X distance for now. We can see that if X is on the carpet, the distance is 0. If is is less than <code>xCarpet</code>, it's equal to <code>xCarpet - xPlayer</code>, and if it's more than <code>xCarpet + size</code> the distance is equal to <code>xPlayer - (xCarpet + size)</code>.</li>\n<li>And hey, we're doing the same exact thing for Y. We could just copy-paste it and replace all the <code>x</code>es with <code>y</code>s, or we could break it out into another function. The copy-paste approach can be error-prone, so I'd recommend more functions.</li>\n</ol>\n<p>Put all that together, it might look a little something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static int singleAxisDistance(int playerCoordinate, int carpetCoordinate, int carpetSize) {\n if (playerCoordinate &lt; carpetCoordinate) {\n return carpetCoordinate - playerCoordinate;\n } else if (playerCoordinate &lt; carpetCoordinate + carpetSize - 1) {\n return 0;\n } else {\n return playerCoordinate - (carpetCoordinate + carpetSize - 1);\n }\n}\n\npublic static int getDistanceToCarpet(int xPlayer, int yPlayer, int xCarpet, int yCarpet, int sizeCarpet) {\n int xDistance = getSingleAxisDistanceToCarpet(xPlayer, xCarpet, sizeCarpet);\n int yDistance = getSingleAxisDistanceToCarpet(yPlayer, yCarpet, sizeCarpet);\n\n return xDistance + yDistance;\n}\n\npublic static int getWhoIsCloser(\n int xFirstPlayer,\n int yFirstPlayer,\n int xSecondPlayer,\n int ySecondPlayer,\n int xCarpet,\n int yCarpet,\n int size) {\n\n int firstPlayerResult = distanceToCarpet(xFirstPlayer, yFirstPlayer, xCarpet, yCarpet, size);\n int secondPlayerResult = distanceToCarpet(xSecondPlayer, ySecondPlayer, xCarpet, yCarpet, size);\n\n if (firstPlayerResult &gt; secondPlayerResult) {\n return 2;\n } else if (firstPlayerResult &lt; secondPlayerResult) {\n return 1;\n } else {\n return 0;\n }\n}\n</code></pre>\n<p>If I were to look past that function, I might eventually want to bundle the parameters into position and carpet objects, and put the distance calculations in their classes. Passing a single object is usually neater than passing multiple primitive values, and tends to have less of a risk of getting the parameters confused. And while I admit it's a matter of opinion, I do think this looks nicer on some level:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static int getWhoIsCloser(\n Point firstPlayerPosition,\n Point secondPlayerPosition,\n Carpet carpet) {\n\n int firstPlayerDistance = firstPlayerPosition.getDistanceTo(carpet);\n int secondPlayerDistance = secondPlayerPosition.getDistanceTo(carpet);\n\n if (firstPlayerDistance &gt; secondPlayerDistance) {\n return 2;\n } else if (firstPlayerDistance &lt; secondPlayerDistance) {\n return 1;\n } else {\n return 0;\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T20:04:46.700", "Id": "505003", "Score": "0", "body": "Wow thanks a lot Sara, worked like a charm with a few mild additions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T02:51:29.390", "Id": "255783", "ParentId": "255768", "Score": "3" } }, { "body": "<p>In addition to Sara J's fine answer, I'd just like to add a frame check, and ask if <code>getWhoIsCloser</code> is really necessary. Once you've got <code>getDistanceTo</code> then all <code>getWhoIsCloser</code> does on top of calling <code>getDistanceTo</code> is apply <code>&gt;</code> and <code>&lt;</code> to the results. You don't really need a function just to do that.</p>\n<p>Consider if you're going to <em>use</em> <code>getWhoIsCloser</code> somewhere, like:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (getWhoisCloser(player1.position, player2.position, carpet.position) == 1) {\n System.out.println(&quot;Player one wins!&quot;);\n} else if (getWhoisCloser(player1.position, player2.position, carpet.position) == 2) {\n System.out.println(&quot;Player two wins!&quot;);\n} else {\n System.out.println(&quot;It's a draw!&quot;);\n}\n</code></pre>\n<p>It's maybe more natural and readable to just write the logic inline:</p>\n<pre class=\"lang-java prettyprint-override\"><code> int firstPlayerDistance = firstPlayerPosition.getDistanceTo(carpet);\n int secondPlayerDistance = secondPlayerPosition.getDistanceTo(carpet);\n\n if (firstPlayerDistance &gt; secondPlayerDistance) {\n System.out.println(&quot;Player one wins!&quot;);\n } else if (firstPlayerDistance &lt; secondPlayerDistance) {\n System.out.println(&quot;Player two wins!&quot;);\n } else {\n System.out.println(&quot;It's a draw!&quot;);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T10:14:09.203", "Id": "255795", "ParentId": "255768", "Score": "1" } } ]
{ "AcceptedAnswerId": "255783", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:43:22.137", "Id": "255768", "Score": "0", "Tags": [ "java", "beginner" ], "Title": "Identifying the closest player to an internal 2D grid" }
255768
<p>Please consider this code for a <code>TaxReturnCalculator</code> (and ignore both the suboptimal use of <code>float</code> instead of <code>BigDecimal</code> and non-existing parameter validation):</p> <pre><code>public class TaxReturnCalculator { private static final float FIFTY_PERCENT = 0.5f; private static final float THIRTY_PERCENT = 0.3f; private static final float MAXIMUM_AMOUNT_TAX_RETURN = 1000f; public static float calculateTaxReturn(float income) { float basicTaxReturn = calculateBasicTaxReturn(income); float taxReturnAddition = calculateTaxReturnAddition(basicTaxReturn); float taxReturn = basicTaxReturn + taxReturnAddition; float taxReturnLimited = calculateTaxReturnLimited(taxReturn); return taxReturnLimited; } private static float calculateBasicTaxReturn(float income) { return income * FIFTY_PERCENT; // More complex calculation here } private static float calculateTaxReturnAddition(float basicTaxReturn) { return basicTaxReturn * THIRTY_PERCENT; // More complex calculation here } private static float calculateTaxReturnLimited(float taxReturn) { float taxReturnLimited; if(taxReturn &gt; MAXIMUM_AMOUNT_TAX_RETURN) { taxReturnLimited = MAXIMUM_AMOUNT_TAX_RETURN; } else { taxReturnLimited = taxReturn; } return taxReturnLimited; } } </code></pre> <p>I designed the <code>calculateTaxReturn(float income)</code> method to follow the</p> <blockquote> <p>One Level of Abstractoin per Function</p> </blockquote> <p>practice recommended in <em>Clean Code</em> by <em>Robert C. Martin</em>: The three functions inside this method are on the same level of abstraction.</p> <p>However, what doesn't seem well designed to me is that <code>calculateTaxReturnLimited(taxReturn)</code> is always called and thus always produces a <code>taxReturnLimited</code> -- even if the tax return is not to be limited (because it's smaller than the maximum amount)! Isn't this confusing?</p> <p>Of course I could avoid this by not having a <code>calculateTaxReturnLimited</code> function at all and put it's code directly inside of the <code>calculateTaxReturn</code>, but that would vialote the <em>One Level of Abstractoin per Function</em> principle.</p> <p>Renaming the function to something like <em>limitTaxReturnIfNecessary</em> doesn't seem good to me either, having multiple <em>...IfNecessary</em> functions seems like a clutter and code smell to me.</p> <p>Is this a trade-off? How can it be resolved best to follow best practices?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:58:26.873", "Id": "504746", "Score": "1", "body": "Welcome to Code Review! I think you are misunderstanding/mis-using the practice you reference. Specifically, deciding if you calculate whether a limited tax return is required is not a responsibility of actually doing the calculation. Additionally, I would argue that the overall abstraction is \"calculation of the tax return\", and thus internal helper functions are not required here, especially given their (current) simplicity" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T22:19:07.613", "Id": "504790", "Score": "0", "body": "Thanks for your comment! The requirements use the same structure/terms (`basic`, `addition`, `limited`), that's one reason why I structured the function like this, too. Thanks for the first part of your comment, too. However, I don't want to focus on that. Please assume that the \"limited\" function makes sense in the \"calculation\" context and that that function is complex enough that it makes sense to introduce internal helper functions. My question: How do you deal with helper functions which have \"if's\" inside (like in the example above) which makes it hard to name them in a meaningful way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T15:13:36.027", "Id": "504854", "Score": "0", "body": "In that case, I lean towards considering this off topic, because it is hypothetical/stub code" } ]
[ { "body": "<p>You don't need to write <code>...ifNecessary</code> if you just describe the property you want to have in the return value, and then you just know that after calling it, it has that property. You want the return amount to be <code>clamp</code>ed so it is less than or equal to the maximum amount. It doesn't matter that it might not change it, but it DOES matter to the business logic that it has been applied (i.e. checked). The actual name isn't that important in this case because I think I'd drop it anyway, as per below.</p>\n<p>First, I just rewrote your code to use a member variable instead of being static, and without all the intermediate variables:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class TaxReturn {\n\n private static final float MAXIMUM_RETURN_AMOUNT= 1000f;\n\n private final float income;\n\n public TaxReturn(float income) {\n this.income = income;\n }\n\n public float returnAmount() {\n return clampReturnAmount(base() + addition());\n }\n\n private float base() {\n return income * 0.5f; // More complex calculation here\n }\n\n private float addition() {\n return base() * 0.3f; // More complex calculation here\n }\n\n private static float clampReturnAmount(float returnAmount) {\n return returnAmount &gt; MAXIMUM_RETURN_AMOUNT ? MAXIMUM_RETURN_AMOUNT\n : returnAmount;\n }\n\n}\n</code></pre>\n<p>But this <code>clampReturnAmount</code> function is just <code>Math.min</code> by a different name. Using <code>Math.min</code> to enforce a limit is common enough to be well understood why we're calling it, especially if we're naming the second argument something like argument <code>MAXIMUM_RETURN_AMOUNT</code>. So just:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class TaxReturn {\n\n private static final float MAXIMUM_RETURN_AMOUNT = 1000f;\n\n private final float income;\n\n public TaxReturn(float income) {\n this.income = income;\n }\n\n public float returnAmount() {\n return Math.min(base() + addition(), MAXIMUM_RETURN_AMOUNT);\n }\n\n private float base() {\n return income * 0.5f; // More complex calculation here\n }\n\n private float addition() {\n return base() * 0.3f; // More complex calculation here\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:41:42.107", "Id": "255794", "ParentId": "255769", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T16:48:22.377", "Id": "255769", "Score": "0", "Tags": [ "java", "design-patterns" ], "Title": "Calculate tax return" }
255769
<p>The last couple of days I've been trying to get a simple algorithm for uniquely determining orthogonal polygons in 3D integer space, having already determined coplanar points.</p> <p>By the time we got here we know each point is unique and there are no collinear points.</p> <p>For example, given the coplanar points <code>pts</code> (lists or tuples)</p> <pre><code> pts = [ [0, 0, 0], [4, 0, 0], [1, 1, 0], [2, 1, 0], [3, 1, 0], [4, 1, 0], [1, 2, 0], [2, 2, 0], [3, 2, 0], [4, 2, 0], [0, 3, 0], [4, 3, 0] ] # Generate orthogonal polygons # 3 +-----------+ # | | # 2 | +__+ +--+ # | | | | # 1 | +--+ +__+ # | | # 0 +-----------+ # 0 1 2 3 4 # result = [ # [ # [0, 0, 0], [0, 3, 0], [4, 3, 0], [4, 2, 0], # [3, 2, 0], [3, 1, 0], [4, 1, 0], [4, 0, 0] # ], [ # [1, 1, 0], [1, 2, 0], [2, 2, 0], [2, 1, 0] # ] # ] </code></pre> <p>I found the basis of an algorithm for this <a href="http://www.science.smith.edu/%7Ejorourke/Papers/OrthoConnect.pdf" rel="nofollow noreferrer">in a paper</a> as authored by <a href="https://stackoverflow.com/users/387778/joseph-orourke">Joseph O'Rourke</a> The following seems to work for the few tests I set up (however it doesn't deal with orientation).</p> <pre><code> def polygonise(pts: list) -&gt; list: # axes gives us the varying columns (we can ignore z for this) axes = {i:set(c) for i,c in enumerate(zip(*pts)) if len(set(c))!=1} a, b = axes.keys() # construct dicts of axis-columns pts_by_axis = {axis: {col: [] for col in cols} for axis,cols in axes.items()} for pt in pts: for axis in axes: pts_by_axis[axis][pt[axis]].append(pt) # each axis-column (sorted by the other dimension) # will now be paired off into edges, and constructed into axis-edge-dicts edges = {} for axis in axes: other = a if axis != a else b for col,pt_list in pts_by_axis[axis].items(): pt_list.sort(key=lambda p:p[other]) for i in range(0,len(pt_list),2): v1 = tuple(pt_list[i]) v2 = tuple(pt_list[i + 1]) edges[tuple((axis,v1))] = other, v2 edges[tuple((axis,v2))] = other, v1 # now derive the polygons, starting at any point. axis, edge = next(iter(edges.keys())) result, poly = [], [edge] while edges: if (axis, edge) not in edges: # This polygon is now closed. keep it, and move to the next one. result.append(poly[:-1]) # if wanted looped, don't slice poly = [] axis, edge = next(iter(edges.keys())) else: # Get the next edge. change the axis (edge is on a different axis) axis, new_edge = edges.pop((axis,edge)) # delete any old reversed edge. del edges[(axis, edge)] edge = new_edge # add the edge to the existing polygon poly.append(edge) # capture the final polygon. result.append(poly[:-1]) # if wanted looped, don't slice. return result if __name__ == &quot;__main__&quot;: from mpl_toolkits.mplot3d.art3d import Poly3DCollection import matplotlib.pyplot as plt from random import shuffle pts = [ (0, 0, 0), (4, 0, 0), (1, 1, 0), (2, 1, 0), (3, 1, 0), (4, 1, 0), (1, 2, 0), (2, 2, 0), (3, 2, 0), (4, 2, 0), (0, 3, 0), (4, 3, 0) ] # shuffle just to make it different. shuffle(pts) result = polygonise(pts) # all the below is just to show the result fig = plt.figure() subplot = fig.add_subplot(111, projection='3d') subplot.axis('off') subplot.scatter([0.6, 3.1], [0.7, 3.3], [0, 0], alpha=0.0) subplot.add_collection3d(Poly3DCollection(result, edgecolors='k', facecolors='b', linewidths=1, alpha=0.2)) fig.tight_layout() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/Gvaq5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gvaq5.jpg" alt="result" /></a></p> <p>I think that the loops could be easier, and I'm not convinced that I need to store edges twice, (which means I have to delete the unused one).</p> <p>Any ideas for tidying the <code>polygonise()</code> method would be welcome.</p> <p>J. O'Rourke, &quot;Uniqueness of orthogonal connect-the-dots&quot;, <em>Computational Morphology</em>, G.T. Toussaint (editor), Elsevier Science Publishers, B.V.(North-Holland), 1988, 99-104. <a href="http://www.science.smith.edu/%7Ejorourke/Papers/OrthoConnect.pdf" rel="nofollow noreferrer">found here</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T11:04:00.020", "Id": "505064", "Score": "1", "body": "Welcome to Code Review. I have rolled back your latest edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T11:06:23.083", "Id": "505066", "Score": "0", "body": "@Heslacher, thanks - no convention was meant to be broken." } ]
[ { "body": "<h1>Type Hints</h1>\n<p>+1 for using type hints. But they could be a little more informative.</p>\n<p><code>def polygonise(pts: list) -&gt; list:</code></p>\n<p>Ok. The function takes a <code>list</code> of <code>pts</code>, but what are <code>pts</code>? It returns a list, but a list of what?</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Sequence\n\nPoint = Sequence[int]\nPolygon = list[Point]\n\ndef polygonise(points: list[Point]) -&gt; list[Polygon]:\n ...\n</code></pre>\n<p>Now we're giving the reader a lot of information. A point is a sequence of integers. Could be a <code>tuple</code>, could be a <code>list</code>. Not important. Instead of <code>pts</code>, we're a bit more explicit and say <code>points</code>. Finally, the function returns a specific kind of <code>list</code>: a <code>Polygon</code> list.</p>\n<p>You can help the reader out even more by including a nice <code>&quot;&quot;&quot;docstring&quot;&quot;&quot;</code> for the function.</p>\n<h1>Axes</h1>\n<p><code>axes = {i:set(c) for i,c in enumerate(zip(*pts)) if len(set(c))!=1}</code></p>\n<p>I really, really hate this statement. It takes the list of points, and explodes each point as an argument for <code>zip</code>. Then, it takes the first coordinate of each of those points, and returns it as a <code>tuple</code>. <code>enumerate</code> adds an index to this, to keep track of which coordinate axis we are processing. Then, we assign those to things to <code>i, c</code> ... really opaque variable names. <code>axis, coordinates</code> might be clearer. Then we turn the coordinates into a <code>set</code>, determine the <code>len</code> of the set, and if that is not 1, we turn the coordinates into a <code>set</code> again, for construction the dictionary.</p>\n<p>Yikes! That's a lot to unpack.</p>\n<p>Then we take the axes, and assign it into to variables <code>a</code> and <code>b</code>, hoping there are exactly 2 axis.</p>\n<p>Perhaps we should add some error checking.</p>\n<pre class=\"lang-py prettyprint-override\"><code> num_coord = len(points[0])\n if any(len(pt) != num_coord for pt in points):\n raise ValueError(&quot;All points should have the same number of coordinates&quot;)\n\n axes = ...\n\n if len(axes) != 2:\n raise ValueError(&quot;All coordinates must be in an orthogonal 2D plane&quot;)\n\n a, b = axes.keys()\n</code></pre>\n<p>That gives me a lot more confidence in the code.</p>\n<p>I still don't like the <code>axes = ...</code> statement. I would re-write it, and maybe use the walrus operator (<code>:=</code>) to avoid creating the set twice, but I'm about to significantly change it.</p>\n<h1>Useless code</h1>\n<p><code>edges[tuple((axis,v1))] = other, v2</code></p>\n<p>Here, <code>(axis, v1)</code> is creating a tuple, to pass to the <code>tuple(...)</code> function. That seems ... odd. You could simplify it to:</p>\n<p><code>edges[axis, v1] = other, v2</code></p>\n<h1>Alternate implementation</h1>\n<h2>Axes</h2>\n<p>Instead of a dictionary, let's just extract a list of axis which have varying coordinate data. A simple comparison of each coordinate of all points with the coordinate of the first point, for each coordinate, will tell us if that axis is important or not.</p>\n<pre class=\"lang-py prettyprint-override\"><code> axes = [axis for axis, first in enumerate(points[0])\n if any(pt[axis] != first for pt in points)]\n\n if len(axes) != 2:\n raise ValueError(&quot;All coordinates must be in an orthogonal 2D plane&quot;)\n\n a, b = axes\n</code></pre>\n<p>This is a much simpler concept. No sets are being created (twice). No dictionaries.</p>\n<h2>Sorted Edges</h2>\n<p>The <code>pts_by_axis</code> is very complex, a dictionary of dictionaries of arrays.</p>\n<p>Let's rework this, by simply sorting the <code>points</code> list. We'll sort it two ways, first by the <code>(a, b)</code> coordinate, then by the <code>(b, a)</code> coordinate. We'll use a helper function to generate the sort keys:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def point_key(first: int, second: int):\n def key(pt):\n return pt[first], pt[second]\n return key\n</code></pre>\n<p>Now we can say <code>sorted(points, key=point_key(a, b))</code>, and we'll have the points sorted in one direction. <code>sorted(points, key=point_key(b, a))</code> will sort it in the other direction.</p>\n<p>Since the points always come in pairs, to form edges, let's add another helper function, to extract pairs of points from the sorted array.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def in_pairs(iterable):\n it = iter(iterable)\n return zip(it, it)\n</code></pre>\n<p>With these, we can build our sorted edge structure. But instead of keying the <code>edges</code> dictionary with a tuple to encoding the axis of the edge, let's just use two dictionaries:</p>\n<pre class=\"lang-py prettyprint-override\"><code> a_edge = {}\n for v1, v2 in in_pairs(sorted(points, key=point_key(a, b))):\n a_edge[v1] = v2\n a_edge[v2] = v1\n\n b_edge = {}\n for v1, v2 in in_pairs(sorted(points, key=point_key(b, a))):\n b_edge[v1] = v2\n b_edge[v2] = v1\n</code></pre>\n<p>The loop at the end does some check to close a polygon and start the next one. Really, you have two loops. Loop while there are still edges. Inside that loop, loop until you've made a polygon. With that structure, the code reads much better:</p>\n<pre class=\"lang-py prettyprint-override\"><code> result = []\n while a_edge:\n v1 = next(iter(a_edge.keys()))\n poly = []\n\n while v1 in a_edge:\n v2 = a_edge.pop(v1)\n v3 = b_edge.pop(v2)\n a_edge.pop(v2)\n b_edge.pop(v1)\n poly.extend((v1, v2))\n v1 = v3\n\n result.append(poly)\n \n return result\n</code></pre>\n<p>Note that I use <code>poly = []</code> instead of <code>poly = [v1]</code>, which means no slice is required at the end to remove the extra point.</p>\n<p>Also, I'm popping <code>v2</code> out of the <code>a_edge</code> dictionary, not a <code>edge</code>, since what is popped out is just a vertex. I find that much clearer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T10:40:49.113", "Id": "505061", "Score": "0", "body": "Brilliant contribution, @AJNeufeld. I'm going to extend the question to include your answers - I'm not sure if that's the right way of 'responding'.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T11:05:43.707", "Id": "505065", "Score": "0", "body": "I got my knuckles rapped. Never mind - your answer is good enough for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T16:12:27.203", "Id": "505080", "Score": "2", "body": "@Konchog If your code has significantly improved, you can post a new question (with your new code) tomorrow. Feel free to add a hyperlink to your old question for bonus context." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T06:54:30.287", "Id": "255876", "ParentId": "255771", "Score": "5" } } ]
{ "AcceptedAnswerId": "255876", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T17:01:27.227", "Id": "255771", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Determining orthogonal polygons in a 3D integer lattice" }
255771
<p>I have a C program where the user can select from 10 different options. I've already split the core functionality of each option into different methods, but my <code>main()</code> function is still quite long. The rest of the code in <code>main()</code> involves getting user input and formatting strings to the display so that the program is clearer and looks nice.</p> <p>E.g. my code is similar to:</p> <pre><code>int actionOneFunction(char *name) { /* Action one logic */ } int actionTwoFunction(FILE *fptr) { /* Action two logic */ } void getUserInput(char *display_msg, char *input_variable, int variable_size) { printf(&quot;%s&quot;, display_msg); fgets(input_variable, variable_size, stdin); strtok(input_variable, &quot;\n&quot;); /* Remove newline added by fgets */ } void displayStartingText() { /* A bunch of printf statements */ } int main() { int result int action; displayStartingText(); printf(&quot;Select the action you would like to carry out: &quot;); scanf(&quot;%d&quot;, &amp;action); getChar(); /* Remove newline generated by scanf from buffer */ if (action &lt; 0 || action &gt; 10) { printf(&quot;Invalid action selected.\n&quot;); return 1; } if (action == 1) { char name[255]; printf(&quot;------------\n&quot;); printf(&quot; Action One \n&quot;); printf(&quot;------------\n&quot;); getUserInput(&quot;Enter the name: &quot;, name, sizeof(name)); result = actionOneFunction(name); if (result != 0) { return errno; } printf(&quot;Action one was successful!\n&quot;); } else if (action == 2) { FILE *fptr; char name[255]; char *content; printf(&quot;------------\n&quot;); printf(&quot; Action Two \n&quot;); printf(&quot;------------\n&quot;); getUserInput(&quot;Enter the file name: &quot;, name, sizeof(name)); fptr = openFile(name, &quot;r&quot;); content = actionTwoFunction(fptr); fclose(fptr); printf(&quot;Content: \n&quot;, content); } else if (action == 3) { /* ... */ } /* ... */ else if (action == 10) { /* ... */ } return 0; } </code></pre> <p>With all ten options and their functionality defined, my <code>main()</code> becomes rather long. Would it be better to put each of the <code>if</code> blocks into their own functions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T20:47:25.080", "Id": "504779", "Score": "4", "body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:27:22.850", "Id": "504786", "Score": "0", "body": "@TobySpeight My apologies. I was directed to CodeReview as the best place to ask about code formatting or stylistic questions, which is exactly my question here. Is there a better place on StackExchange to ask about this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T07:52:18.657", "Id": "504810", "Score": "1", "body": "It seems you were badly advised - you should have been pointed at our [help] before you asked. I think you should delete this question, then you have two options: if you're in a position to post some real code here, then create a new question using that; otherwise you might look to see if [softwareengineering.se] is appropriate (look at what is [on-topic](//softwareengineering.stackexchange.com/help/on-topic) there)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T07:54:05.957", "Id": "504811", "Score": "0", "body": "@TobySpeight I see. I, unfortunately, cannot delete the question due to the existence of an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T07:55:29.493", "Id": "504812", "Score": "2", "body": "Ah, yes. Not a problem - the community will likely close it. I hope the rest of my advice is more useful!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T08:01:00.310", "Id": "504815", "Score": "1", "body": "Definitely so! Thank you very much." } ]
[ { "body": "<p>I can't be very detailed here because I haven't worked in C lately. But basically, yes, you should move more of the code out of the <code>if</code> statements into the breakout functions.</p>\n<p>Specifically, each break-out function should have the same signature (type/arity). Based on the examples you've given so far, these appear to be quite open-ended effectful subroutines, each comparable to a mini <code>main</code>, so they might as well have signature <code>()-&gt;int</code>. Or maybe there'll be enough structure to their behavior that you can be more specific than that, IDK.</p>\n<p>If you're going to print out the fancy headers, abstract that away into a helper function.</p>\n<p>Anyway, you might consider even getting rid of the <code>if</code> itself, in favor of a lookup-table <em>of functions</em>. Exactly how to implement that will depend a bit on the context; it's not something I've ever done in C.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T19:29:25.000", "Id": "504772", "Score": "0", "body": "My current breakout functions already perform their own specialized tasks, so I want to avoid adding *anything* to them, if possible. Would it be fine to create new breakout functions for each `if` block that call the other specialized functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T23:38:02.173", "Id": "504792", "Score": "1", "body": "Yeah. Maybe you could even parameterize the wrapper in some way; it's hard to say without a sense of the space of functionality that's already included or might want to be added later." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T19:11:44.910", "Id": "255777", "ParentId": "255776", "Score": "1" } } ]
{ "AcceptedAnswerId": "255777", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T18:57:33.787", "Id": "255776", "Score": "0", "Tags": [ "c" ], "Title": "C program with 10 options" }
255776
<p>I wanted to write a program that takes from standard input an expression without left parentheses and prints the equivalent infix expression with the parentheses inserted. For example, given the input</p> <pre><code>1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) ) </code></pre> <p>the program should print</p> <pre><code>( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) ) </code></pre> <p>My solution is not best optimized. So, I am looking for suggestions on how to improve/optimize it.</p> <pre><code>import java.util.Scanner; import java.util.Stack; public class ParenthesesCompleter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); Stack&lt;Character&gt; operators = new Stack&lt;Character&gt;(); Stack&lt;String&gt; operands = new Stack&lt;String&gt;(); for (int i = 0; i &lt; line.length(); i++) { switch (line.charAt(i)) { case '+': case '-': case '*': case '/': // Operator case operators.push(line.charAt(i)); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // &quot;operand&quot; case String s = &quot;&quot;; s += line.charAt(i); operands.push(s); break; case ')': // closing paren case String a = operands.pop(); String b = operands.pop(); char c = operators.pop(); StringBuilder buf = new StringBuilder(); buf.append(&quot;(&quot;); buf.append(b); buf.append(c); buf.append(a); buf.append(&quot;)&quot;); operands.push(buf.toString()); break; case ' ': break; } } // case for no outer parentheses while (!operators.isEmpty()) { String a = operands.pop(); String b = operands.pop(); char c = operators.pop(); StringBuilder buf = new StringBuilder(); buf.append(b); buf.append(c); buf.append(a); operands.push(buf.toString()); } System.out.println(operands.pop()); sc.close(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T20:12:40.383", "Id": "504777", "Score": "10", "body": "How do you know that the right answer is not just adding opening parentheses to the beginning until the counts match?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T20:03:48.130", "Id": "255778", "Score": "1", "Tags": [ "java", "stack" ], "Title": "Add missing left parentheses in Java" }
255778
<p>In my React app, I had to build a system to check access based on roles and features. To make code more efficient I should move the function which makes a list of an featureList OBJ of features inside a custom hook, to avoid in this way repeating of the code or redundant scripts.</p> <p>The function where I have the fetureList I have to move</p> <pre><code>function doCheck(access, requirements, features = []) { const roles = access.roles || []; const actions = access.actions || []; const featureList = Object.entries(features) .filter(e =&gt; e[1]) .map(e =&gt; e[0]); if (requirements.roles) { if (!requirements.roles.find(role =&gt; roles.includes(role))) { return false; } } if (!isEmpty(requirements.features)) { if (!requirements.features.find(feature =&gt; featureList.includes(feature))) { return false; } } if (requirements.actions) { if (!requirements.actions.find(action =&gt; actions.includes(action))) { return false; } } if ( requirements.customCheck &amp;&amp; !requirements.customCheck(access, requirements.context) ) { return false; } return true; } </code></pre> <p>From above the code I need to move is</p> <pre><code>const featureList = Object.entries(features) .filter(e =&gt; e[1]) .map(e =&gt; e[0]); </code></pre> <p>And I need to move it inside this hook</p> <pre><code>function useFeatures(props) { const { data, loading } = useQuery(featureOptionsQuery, { variables: { studyId: props }, skip: !Boolean(props), }); const features = useMemo( () =&gt; ({ recruitmentPortal: data?.featureOptions?.recruitmentPortal, engagementPortal: data?.featureOptions?.engagementPortal, consenteesPortal: data?.featureOptions?.consenteesPortal, analyticsPortal: data?.featureOptions?.analyticsPortal, }), [data], ); if (loading) { return null; } return features; } </code></pre> <p>As I understood inside the use memo I need to make an obj and use it to return the feature list but I don't know the way of doing it.</p> <p>I was wondering to do</p> <p><code>const featuresObj = {OBJ}</code> and then use this to do the featureList thing to return but I don't know how to do this with <code>useMemo()</code></p> <p>I'm new to React and hooks and having some difficulties doing this refactor thing as required.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T20:06:16.047", "Id": "255779", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "Custom hook to have a featureList OBJ inside a useMemo()" }
255779
<p>Is there a better way to write this piece of code to extract data from a REST API with the requests library? It currently takes about 10 minutes to finish extracting the data from the REST API. I think the code below may not be the most efficient method.</p> <pre><code>import time import requests import datetime import pandas as pd def loan_rest_api(): ''' This function calls the rest api and stored the data in a pandas dataframe. ''' search_start = time.time() print(&quot;Extracting loan data from Rest API...&quot;) # Declaring variables for the first page number and the list that contains the results for each page in the REST API. num = 1 pages = [] # Declaring variable to look up the correct table in the REST API. table = 'loan' # The 'loan' table has about 50 columns, but these are the ones I need. # Declaring columns variable to choose the columns I'm interested in. columns = ''' loan_id, loan_name, loan_parent_id, loan_status, loan_type, loan_classification, loan_create_date, loan_last_update, loan_amount, loan_amount_last_update, loan_balance, loan_balance_last_update, loan_interest, loan_interest_last_update, city, office_location, project_name ''' # Infinitely loop needed to iterate through all of the pages of data that the loan # table contains. Since I don't know how many pages there are, I loop # through the entire table until it reaches the end. Once # it reaches the end, the While True condition no longer holds so the loop stops. while True: # Since the loan table in the rest api contains several pages, I had to implement a # pagination functionality to prevent the function from either timing out or crashing. pagination = {'pageSize': '5000', 'pageNumber': str(num), 'attributes': columns.replace(' ', '').replace('\n', '')} # Send a GET request to the REST API on the corresponding loan table. # the params parameter contains the pagination requirements. Start # with page 1, then page 2, etc. For each resulting data pull, append # the page to the pages list. # num increase by 1 on the next loop until it reaches the end. response = requests.get(REST_API_LINK + table, params=pagination) if response.status_code != 200: break results = response.json() pages.append(pd.DataFrame(results)) num += 1 # Create a pandas dataframe. This contains about 200,000 rows and it's # 40MB in size when exported as a csv file. final_df = pd.concat(pages, ignore_index=True) # Right now this takes about 800 seconds. search_end = time.time() print(f&quot; ...search completed in {search_end - search_start: .2f} seconds.&quot;) return print('Search Done.') <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:48:09.837", "Id": "504788", "Score": "0", "body": "Yes, I'm on it. Sorry about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T22:03:25.123", "Id": "504789", "Score": "0", "body": "Hi @Peilonrayz , I included descriptions on the code. I can elaborate on specific areas if needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T01:44:49.923", "Id": "504797", "Score": "1", "body": "Seems the most time consumed action here is downloading the json data from server. To speed up, maybe you can download multiple parts concurrency, and or increase pageSize (if the server not configured to limit request frequency)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T19:33:54.903", "Id": "504997", "Score": "0", "body": "Hi @tsh , I increased the pageSize from 5000 to 8000 and the extraction time improved by 6.5% going from 800 seconds to 750 seconds. At least it's something! I'll keep tinkering with the pagination parameter. All other tables in the REST API take about 1, 2, or 3 seconds. It's this Loan table with several pages of JSON data that take a while to extract." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T19:44:17.670", "Id": "505000", "Score": "0", "body": "pageSize is now 15000 and time decreased to 600 seconds! Thank you @tsh!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T20:21:06.113", "Id": "505005", "Score": "0", "body": "pageSize is now at 20000 and time is still at 600 seconds. Further increase in page size have no effect. Will leave it there for now, and I'll continue to read some other REST API python examples to see how others have written and optimized theirs. Thank you!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:20:36.333", "Id": "255780", "Score": "2", "Tags": [ "python", "api", "pandas", "rest" ], "Title": "Python REST API Data Extraction with requests library" }
255780
<p>I have an API Swagger generated, I'm not satisfied with how I'm handling my part of the contract e.g. how I have constructed my <code>db</code> and <code>handlers</code> modules.</p> <p>Specially how I'm dealing the the database connection, can this not be made more robust by using <code>interfaces</code>. For simplicity I'm just including one implemented endpoint.</p> <pre><code>// This file is safe to edit. Once it exists it will not be overwritten package restapi import ( &quot;crypto/tls&quot; &quot;net/http&quot; &quot;github.com/go-openapi/errors&quot; &quot;github.com/go-openapi/runtime&quot; &quot;github.com/go-openapi/runtime/middleware&quot; log &quot;github.com/sirupsen/logrus&quot; &quot;hairdoo.com/m/v2/handlers&quot; &quot;hairdoo.com/m/v2/models&quot; &quot;hairdoo.com/m/v2/restapi/operations&quot; &quot;hairdoo.com/m/v2/restapi/operations/company&quot; &quot;hairdoo.com/m/v2/restapi/operations/employee&quot; ) //go:generate swagger generate server --target ../../hairdoo --name Hairdoo --spec ../swagger.yml --principal interface{} //var db *gorm.DB func init() { // Log as JSON instead of the default ASCII formatter. /*log.SetFormatter(&amp;log.JSONFormatter{ TimestampFormat: &quot;2006-01-02 15:04:05&quot;, //PrettyPrint: true, })*/ // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example //log.SetOutput(os.Stdout) log.SetFormatter(&amp;log.TextFormatter{ DisableColors: false, FullTimestamp: true, }) // Only log the warning severity or above. //log.SetLevel(log.WarnLevel) log.SetLevel(log.InfoLevel) } func configureFlags(api *operations.HairdooAPI) { // api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... } } func configureAPI(api *operations.HairdooAPI) http.Handler { // configure the api here api.ServeError = errors.ServeError // Set your custom logger if needed. Default one is log.Printf // Expected interface func(string, ...interface{}) // // Example: //api.Logger = log.Printf api.UseSwaggerUI() // To continue using redoc as your UI, uncomment the following line // api.UseRedoc() api.JSONConsumer = runtime.JSONConsumer() //api.UrlformConsumer = runtime.DiscardConsumer api.JSONProducer = runtime.JSONProducer() api.CompanyAddCompanyHandler = company.AddCompanyHandlerFunc(func(params company.AddCompanyParams) middleware.Responder { //log.Debugf(&quot;Add commpay Handler Called&quot;) //log.Infof(&quot;Payload Data : %v&quot;, params.Body) response, err := handlers.AddCompany(params) if err != nil { return company.NewAddCompanyBadRequest().WithPayload(&amp;models.ErrorReponse400{ Error: err.Error(), }) } return company.NewAddCompanyCreated().WithPayload(response) }) </code></pre> <p><strong>handlers/company.go</strong></p> <pre><code>package handlers import ( &quot;hairdoo.com/m/v2/db&quot; &quot;hairdoo.com/m/v2/models&quot; &quot;hairdoo.com/m/v2/restapi/operations/company&quot; ) func AddCompany(params company.AddCompanyParams) (*models.Company, error) { result, err := db.AddCompany(params.Body) if err != nil { return nil, err } return result, nil } </code></pre> <p><strong>db/company.go</strong></p> <pre><code>import ( &quot;fmt&quot; &quot;time&quot; &quot;gorm.io/gorm&quot; &quot;hairdoo.com/m/v2/models&quot; ) type Company struct { gorm.Model Name string `gorm:&quot;uniqueIndex&quot;` Phone string Email string ContatctPerson string CategoryID int Category *Category Status string } type Category struct { ID int Name string `gorm:&quot;uniqueIndex&quot;` } func AddCompany(companyObj *models.Company) (*models.Company, error) { db := Open() var result *gorm.DB category := &amp;Category{} db.Where(&quot;name = ?&quot;, companyObj.Category.Name).First(category) company := convertToDBCompany(companyObj, false) if category.ID != 0 { result = db.Exec(&quot;INSERT INTO companies (created_at, updated_at, name, phone, email, contatct_person, category_id) values (?, ?, ?, ?, ?, ?, ?);&quot;, time.Now(), time.Now(), companyObj.Name, companyObj.Phone, companyObj.Email, companyObj.ContatctPerson, category.ID) } else { result = db.Create(company) } if result.RowsAffected &lt; 1 { return nil, result.Error } // add employee to db if object present var employees []*models.EmployeeItems0 if companyObj.Employee != nil { for _, employeeInput := range companyObj.Employee { result, err := AddEmployee(employeeInput) if err != nil { return nil, err } employees = append(employees, result) } } return convertToModelCompany(company, employees), nil } </code></pre> <p><strong>database.go</strong></p> <pre><code>package db import ( &quot;gorm.io/driver/mysql&quot; &quot;gorm.io/gorm&quot; ) func Open() *gorm.DB { connString := &quot;root:12345@tcp(0.0.0.0:3306)/test?charset=utf8mb4&amp;parseTime=True&amp;loc=Local&quot; db, err := gorm.Open(mysql.Open(connString), &amp;gorm.Config{}) if err != nil { panic(err) } db.AutoMigrate(Company{}, Category{}, Employee{}) return db } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:53:15.547", "Id": "255781", "Score": "0", "Tags": [ "go", "api" ], "Title": "Swagger API with Gorm DB connection" }
255781
<p>I currently have the following code to build this widget:</p> <p><a href="https://i.stack.imgur.com/8hI3y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8hI3y.png" alt="enter image description here" /></a></p> <pre class="lang-dart prettyprint-override"><code> MonthlyAnnualSection( title: 'Tax Expense', onValueChanged: (value) { setState(() { defaults.shouldDisplayTaxesExpensesMonthly = value == 'm'; }); }, children: [ Panel( key: Key( 'taxes${defaults.shouldDisplayTaxesExpensesMonthly ? 'Monthly' : 'Annual'}'), title: ' Taxes', isPercentage: defaults.shouldDisplayTaxesAsPercentage, onIsPercentageChanged: (val) { setState(() { defaults.shouldDisplayTaxesAsPercentage = val; }); }, child: Column( children: [ SizedBox(height: 10), if (defaults.shouldDisplayTaxesAsPercentage) PercentageTextField( value: defaults .shouldDisplayTaxesExpensesMonthly ? defaults.taxesPercent : defaults.taxesPercent * 12, placeholder: 'example: ${(defaults.shouldDisplayTaxesExpensesMonthly ? defaults.taxesPercent : defaults.taxesPercent * 12).toPercentage()}', onValueChanged: (val) { setState(() { defaults.taxesPercent = defaults .shouldDisplayTaxesExpensesMonthly ? val : val / 12; }); }, ), if (!defaults.shouldDisplayTaxesAsPercentage) CurrencyTextField( value: defaults .shouldDisplayTaxesExpensesMonthly ? defaults.taxes : defaults.taxes * 12, placeholder: 'example: ${(defaults.shouldDisplayTaxesExpensesMonthly ? defaults.taxes : defaults.taxes * 12).toCurrency()}', onValueChanged: (val) { setState(() { defaults.taxes = defaults .shouldDisplayTaxesExpensesMonthly ? val : val / 12; }); }, ), SizedBox(height: 10), ], ), ), ], ), </code></pre> <p>and this is the class where that <code>defaults</code> is coming from:</p> <pre class="lang-dart prettyprint-override"><code> class Defaults { bool shouldDisplayTaxesExpensesMonthly; bool shouldDisplayTaxesAsPercentage; double taxes; double taxesPercent; bool shouldDisplayManagementExpensesMonthly; bool shouldDisplayManagementAsPercentage; double management; double managementPercent; } </code></pre> <p>The problem as you can see, is that it takes a lot of ternary methods plus if I want to make a second similar widget below it (to use it for the management expenses, instead of tax) it takes a LOT of repeating.</p> <p>Ideally I would love to just have something like this:</p> <pre><code>Section( title: 'Tax Expense', subtitle: ' Taxes', value: defaults.taxes, percent: defaults.taxesPercent, shouldDisplayMonthly: defaults.shouldDisplayTaxesExpensesMonthly, shouldDisplayAsPercentage: defaults.shouldDisplayTaxesAsPercentage, ), Section( title: 'Management Expense', subtitle: ' Management', value: defaults.management, percent: defaults.managementPercent, shouldDisplayMonthly: defaults.shouldDisplayManagementExpensesMonthly, shouldDisplayAsPercentage: defaults.shouldDisplayManagementsAsPercentage, ), </code></pre> <p>And then it would be sorted... but apparently Dart doesn't support reflection, so I'm not sure how I could do that?</p> <p>Any help is appreciated</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T02:56:55.073", "Id": "255784", "Score": "1", "Tags": [ "dart", "flutter" ], "Title": "Flutter input widget with multiple options (monthly/annual/currency/percentage)" }
255784
<p>This is a PowerShell script I wrote a while ago that converts Windows Registry files to PowerShell commands(<code>New-Item</code>, <code>Remove-Item</code>, <code>Set-ItemProperty</code> and <code>Remove-ItemProperty</code>), it supports conversion of all six registry value types (REG_SZ, REG_DWORD, REG_QWORD, REG_BINARY, REG_EXPAND_SZ and REG_MULTI_SZ), and you got it right, I figured out how to correctly convert binary types.</p> <p>You can view my original script here:<a href="https://superuser.com/a/1615077/1250181">https://superuser.com/a/1615077/1250181</a></p> <p>Today I improved it, and this is the final version of my script, I used <code>reg add</code> to add REG_BINARY values because Set-ItemProperty can't add them, I used commas instead of &quot;\0&quot; because that's the correct way to add them with <code>Set-ItemProperty</code>, and Registry PSProvider does only provide 2 PSDrives by default: HKCU: and HKLM:, so if the registry files modifies other hives I added the lines to create them.</p> <p>Please review my code(Tested on PowerShell 7, lower versions may not work):</p> <pre><code>Function reg2ps1 { [CmdLetBinding()] Param( [Parameter(ValueFromPipeline=$true, Mandatory=$true)] [Alias(&quot;FullName&quot;)] [string]$path, $Encoding = &quot;utf8&quot; ) Begin { $hive = @{ &quot;HKEY_CLASSES_ROOT&quot; = &quot;HKCR:&quot; &quot;HKEY_CURRENT_CONFIG&quot; = &quot;HKCC:&quot; &quot;HKEY_CURRENT_USER&quot; = &quot;HKCU:&quot; &quot;HKEY_LOCAL_MACHINE&quot; = &quot;HKLM:&quot; &quot;HKEY_USERS&quot; = &quot;HKU:&quot; } [system.boolean]$isfolder=$false $addedpath=@() } Process { switch (test-path $path -pathtype container) { $true {$files=(get-childitem -path $path -recurse -force -file -filter &quot;*.reg&quot;).fullname;$isfolder=$true} $false {if($path.endswith(&quot;.reg&quot;)){$files=$path}} } foreach($File in $Files) { $Commands = @() if ($(Get-Content -Path $File -Raw) -match &quot;HKEY_CLASSES_ROOT&quot;) {$commands+=&quot;New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null&quot;} elseif ($(Get-Content -Path $File -Raw) -match &quot;HKEY_CURRENT_CONFIG&quot;) {$commands+=&quot;New-PSDrive -Name HKCC -PSProvider Registry -Root HKEY_CURRENT_CONFIG | Out-Null&quot;} elseif ($(Get-Content -Path $File -Raw) -match &quot;HKEY_USERS&quot;) {$commands+=&quot;New-PSDrive -Name HKU -PSProvider Registry -Root HKEY_USERS | Out-Null&quot;} [string]$text=$nul $FileContent = Get-Content $File | Where-Object {![string]::IsNullOrWhiteSpace($_)} | ForEach-Object { $_.Trim() } $joinedlines = @() for ($i=0;$i -lt $FileContent.count;$i++){ if ($FileContent[$i].EndsWith(&quot;\&quot;)) { $text=$text+($FileContent[$i] -replace &quot;\\&quot;).trim() } else { $joinedlines+=$text+$FileContent[$i] [string]$text=$nul } } foreach ($joinedline in $joinedlines) { if ($joinedline -match '\[' -and $joinedline -match '\]' -and $joinedline -match 'HKEY') { $key=$joinedline -replace '\[|\]' switch ($key.StartsWith(&quot;-HKEY&quot;)) { $true { $key=$key.substring(1,$key.length-1) $hivename = $key.split('\')[0] $key = &quot;`&quot;&quot; + ($key -replace $hivename,$hive.$hivename) + &quot;`&quot;&quot; $Commands += 'Remove-Item -Path {0} -Force -Recurse' -f $key } $false { $hivename = $key.split('\')[0] $key = &quot;`&quot;&quot; + ($key -replace $hivename,$hive.$hivename) + &quot;`&quot;&quot; if ($addedpath -notcontains $key) { $Commands += 'New-Item -Path {0} -ErrorAction SilentlyContinue | Out-Null'-f $key $addedpath+=$key } } } } elseif ($joinedline -match &quot;`&quot;([^`&quot;=]+)`&quot;=&quot;) { [System.Boolean]$delete=$false [System.Boolean]$binary=$false $name=($joinedline | select-string -pattern &quot;`&quot;([^`&quot;=]+)`&quot;&quot;).matches.value | select-object -first 1 switch ($joinedline) { {$joinedline -match &quot;=-&quot;} {$commands+=$Commands += 'Remove-ItemProperty -Path {0} -Name {1} -Force' -f $key, $Name;$delete=$true} {$joinedline -match '&quot;=&quot;'} { $type=&quot;String&quot; $value=$joinedline -replace &quot;`&quot;([^`&quot;=]+)`&quot;=&quot; } {$joinedline -match &quot;dword&quot;} { $type=&quot;Dword&quot; $value=$joinedline -replace &quot;`&quot;([^`&quot;=]+)`&quot;=dword:&quot; $value=&quot;0x&quot;+$value } {$joinedline -match &quot;qword&quot;} { $type=&quot;Qword&quot; $value=$joinedline -replace &quot;`&quot;([^`&quot;=]+)`&quot;=qword:&quot; $value=&quot;0x&quot;+$value } {$joinedline -match &quot;hex(\([2,7,b]\))?:&quot;} { $value=($joinedline -replace &quot;`&quot;[^`&quot;=]+`&quot;=hex(\([2,7,b]\))?:&quot;).split(&quot;,&quot;) $hextype=($joinedline | select-string -pattern &quot;hex(\([2,7,b]\))?&quot;).matches.value switch ($hextype) { {$hextype -match 'hex(\([2,7])\)'} { $ValueEx='$value=for ($i=0;$i -lt $value.count;$i+=2) {if ($value[$i] -ne &quot;00&quot;) {[string][char][int](&quot;0x&quot;+$value[$i])}' switch ($hextype) { 'hex(2)' {$type=&quot;ExpandString&quot;; invoke-expression $($ValueEx+'}')} 'hex(7)' {$type=&quot;MultiString&quot;; invoke-expression $($ValueEx+' else {&quot;,&quot;}}'); $value=0..$($value.count-3) | %{$value[$_]}} } $value=$value -join &quot;&quot; if ($type -eq &quot;ExpandString&quot;) {$value='&quot;'+$value+'&quot;'} } 'hex(b)' { $type=&quot;Qword&quot; $value=for ($i=$value.count-1;$i -ge 0;$i--) {$value[$i]} $value='0x'+($value -join &quot;&quot;).trimstart('0') } 'hex' { $type=&quot;REG_BINARY&quot; $value=$value -join &quot;&quot; $binary=$true } } } } if ($delete -eq $false) { switch ($binary) { $false {$line='Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3}'} $true {$line='Reg Add {0} /v {1} /t {2} /d {3} /f';$key=$key.replace(&quot;:\&quot;,&quot;\&quot;)} } $commands+=$line -f $key, $name, $type, $value } } elseif ($joinedline -match &quot;@=&quot;) { $name='&quot;(Default)&quot;';$type='string';$value=$joinedline -replace '@=' $commands+='Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3}' -f $key, $name, $type, $value } } $parent=split-path $file -parent $filename=[System.IO.Path]::GetFileNameWithoutExtension($file) $Commands | out-file -path &quot;${parent}\${filename}_reg.ps1&quot; -encoding $encoding } if ($isfolder -eq $true) { $allcommands=(get-childitem -path $path -recurse -force -file -filter &quot;*_reg.ps1&quot;).fullname | where-object {$_ -notmatch &quot;allcommands_reg&quot;} | foreach-object {get-content $_} $allcommands | out-file -path &quot;${path}\allcommands_reg.ps1&quot; -encoding $encoding } } } $path = $args[0] reg2ps1 $path </code></pre> <p>Usage example: .\reg2ps1.ps1 &quot;path\to\reg.reg&quot;</p> <p><em><strong>Sample Input</strong></em>:</p> <pre><code>Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DPS] &quot;DelayedAutoStart&quot;=dword:00000000 &quot;Description&quot;=&quot;@%systemroot%\\system32\\dps.dll,-501&quot; &quot;DisplayName&quot;=&quot;Diagnostic Policy Service&quot; &quot;ErrorControl&quot;=dword:00000001 &quot;FailureActions&quot;=hex:80,51,01,00,00,00,00,00,00,00,00,00,03,00,00,00,14,00,00,\ 00,01,00,00,00,c0,d4,01,00,01,00,00,00,e0,93,04,00,00,00,00,00,00,00,00,00 &quot;ImagePath&quot;=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,00,\ 74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,73,\ 00,76,00,63,00,68,00,6f,00,73,00,74,00,2e,00,65,00,78,00,65,00,20,00,2d,00,\ 6b,00,20,00,4c,00,6f,00,63,00,61,00,6c,00,53,00,65,00,72,00,76,00,69,00,63,\ 00,65,00,4e,00,6f,00,4e,00,65,00,74,00,77,00,6f,00,72,00,6b,00,20,00,2d,00,\ 70,00,00,00 &quot;ObjectName&quot;=&quot;NT AUTHORITY\\LocalService&quot; &quot;RequiredPrivileges&quot;=hex(7):53,00,65,00,43,00,68,00,61,00,6e,00,67,00,65,00,4e,\ 00,6f,00,74,00,69,00,66,00,79,00,50,00,72,00,69,00,76,00,69,00,6c,00,65,00,\ 67,00,65,00,00,00,53,00,65,00,43,00,72,00,65,00,61,00,74,00,65,00,47,00,6c,\ 00,6f,00,62,00,61,00,6c,00,50,00,72,00,69,00,76,00,69,00,6c,00,65,00,67,00,\ 65,00,00,00,53,00,65,00,41,00,73,00,73,00,69,00,67,00,6e,00,50,00,72,00,69,\ 00,6d,00,61,00,72,00,79,00,54,00,6f,00,6b,00,65,00,6e,00,50,00,72,00,69,00,\ 76,00,69,00,6c,00,65,00,67,00,65,00,00,00,53,00,65,00,49,00,6d,00,70,00,65,\ 00,72,00,73,00,6f,00,6e,00,61,00,74,00,65,00,50,00,72,00,69,00,76,00,69,00,\ 6c,00,65,00,67,00,65,00,00,00,00,00 &quot;ServiceSidType&quot;=dword:00000003 &quot;Start&quot;=dword:00000003 &quot;Type&quot;=dword:00000020 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DPS\Parameters] &quot;ServiceDll&quot;=hex(2):25,00,53,00,79,00,73,00,74,00,65,00,6d,00,52,00,6f,00,6f,\ 00,74,00,25,00,5c,00,73,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,\ 64,00,70,00,73,00,2e,00,64,00,6c,00,6c,00,00,00 &quot;ServiceDllUnloadOnStop&quot;=dword:00000001 &quot;ServiceMain&quot;=&quot;ServiceMain&quot; [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DPS\Security] &quot;Security&quot;=hex:01,00,14,80,8c,00,00,00,98,00,00,00,14,00,00,00,30,00,00,00,02,\ 00,1c,00,01,00,00,00,02,80,14,00,ff,01,0f,00,01,01,00,00,00,00,00,01,00,00,\ 00,00,02,00,5c,00,04,00,00,00,00,00,14,00,ff,01,0f,00,01,01,00,00,00,00,00,\ 05,12,00,00,00,00,00,18,00,ff,01,02,00,01,02,00,00,00,00,00,05,20,00,00,00,\ 20,02,00,00,00,00,14,00,8d,01,02,00,01,01,00,00,00,00,00,05,04,00,00,00,00,\ 00,14,00,8d,01,02,00,01,01,00,00,00,00,00,05,06,00,00,00,01,01,00,00,00,00,\ 00,05,12,00,00,00,01,01,00,00,00,00,00,05,12,00,00,00 </code></pre> <p><em><strong>Sample Output</strong></em>:</p> <pre><code>New-Item -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -ErrorAction SilentlyContinue | Out-Null Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;DelayedAutoStart&quot; -Type Dword -Value 0x00000000 Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;Description&quot; -Type String -Value &quot;@%systemroot%\\system32\\dps.dll,-501&quot; Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;DisplayName&quot; -Type String -Value &quot;Diagnostic Policy Service&quot; Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;ErrorControl&quot; -Type Dword -Value 0x00000001 Reg Add &quot;HKLM\SYSTEM\CurrentControlSet\Services\DPS&quot; /v &quot;FailureActions&quot; /t REG_BINARY /d 805101000000000000000000030000001400000001000000c0d4010001000000e09304000000000000000000 /f Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;ImagePath&quot; -Type ExpandString -Value &quot;%SystemRoot%\System32\svchost.exe -k LocalServiceNoNetwork -p&quot; Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;ObjectName&quot; -Type String -Value &quot;NT AUTHORITY\\LocalService&quot; Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;RequiredPrivileges&quot; -Type MultiString -Value SeChangeNotifyPrivilege,SeCreateGlobalPrivilege,SeAssignPrimaryTokenPrivilege,SeImpersonatePrivilege Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;ServiceSidType&quot; -Type Dword -Value 0x00000003 Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;Start&quot; -Type Dword -Value 0x00000003 Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS&quot; -Name &quot;Type&quot; -Type Dword -Value 0x00000020 New-Item -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters&quot; -ErrorAction SilentlyContinue | Out-Null Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters&quot; -Name &quot;ServiceDll&quot; -Type ExpandString -Value &quot;%SystemRoot%\system32\dps.dll&quot; Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters&quot; -Name &quot;ServiceDllUnloadOnStop&quot; -Type Dword -Value 0x00000001 Set-ItemProperty -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Parameters&quot; -Name &quot;ServiceMain&quot; -Type String -Value &quot;ServiceMain&quot; New-Item -Path &quot;HKLM:\SYSTEM\CurrentControlSet\Services\DPS\Security&quot; -ErrorAction SilentlyContinue | Out-Null Reg Add &quot;HKLM\SYSTEM\CurrentControlSet\Services\DPS\Security&quot; /v &quot;Security&quot; /t REG_BINARY /d 010014808c00000098000000140000003000000002001c000100000002801400ff010f0001010000000000010000000002005c000400000000001400ff010f0001010000000000051200000000001800ff01020001020000000000052000000020020000000014008d010200010100000000000504000000000014008d010200010100000000000506000000010100000000000512000000010100000000000512000000 /f </code></pre> <p><em><strong>Registry Editor View</strong></em>:</p> <p><a href="https://i.stack.imgur.com/9satO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9satO.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T11:54:45.810", "Id": "514915", "Score": "0", "body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>I don't use Windows much and have very little experience with the registry, so I have a hard time judging the functional parts. So most of my comments are about the code style.</p>\n<ul>\n<li>While PowerShell is not very sensitive when it comes to case, convention matters, and so does readability.\n<ul>\n<li>If a variable has multiple words in it, don't make it all lowercase with no separator. <code>$joinedLines</code> is conventional, but both <code>$joined_lines</code> and <code>${joined-lines}</code> are at least nicer than <code>$joinedlines</code></li>\n<li>Method names, property names and cmdlet flag names generally start with an uppercase letter. <code>Select-String -pattern &quot;...&quot;.matches.value</code> works, but <code>Select-String -Pattern &quot;...&quot;.Matches.Value</code> is more conventional.</li>\n<li>But above all else, be consistent in terms of how you refer to each variable. <code>$Commands</code> and <code>$commands</code> are the same, sure, but if you pick one and and stick to it it gets easier to read.</li>\n</ul>\n</li>\n<li>You can get rid of some duplication by re-using the same code for all three New-PSDrive command additions thanks to your <code>$hive</code> variable (if you remove the colons):</li>\n</ul>\n<pre><code>foreach ($root in $hive) {\n if ((Get-Content -Path $file -Raw) -match $root) {\n if ((Get-PSDrive).Name -notcontains $hive[$root]) {\n $commands += &quot;New-PSDrive -Name $($hive[$root]) -PSProvider Registry -Root $root&quot;\n }\n }\n}\n</code></pre>\n<ul>\n<li>Though if you do that, you'd have to replace <code>$hive.$hiveName</code> with something more like <code>&quot;$($hive[$hiveName]):&quot;</code> later on.</li>\n<li>You have a few <code>switch</code> statements where the only cases are <code>$true</code> and <code>$false</code>. It'd probably be clearer to just make those into <code>if</code> statements.</li>\n<li>You have a couple <code>if ($someVariable -eq $true)</code> and <code>if ($someVariable -eq $false)</code> -- you can just replace those with <code>if ($someVariable)</code> and <code>if ( ! $someVariable)</code></li>\n<li>At one point, you go <code>$command+=$Command+=&quot;...&quot;</code>, which <em>might</em> be intentional, but doesn't look like it. If it is, you should probably add a comment specifying that, and possibly spell the line out like <code>$command = $command + $command + &quot;...&quot;</code>.</li>\n<li>If you have multiple statements on a single line separated by <code>;</code>, consider splitting it into multiple lines instead (<code>for</code> loop headers not included)</li>\n<li>Code tends to look a lot more pleasant when statements and operators get some space to breathe. <code>for ($i=0;$i -lt $FileContent.count;$i++){</code> works exactly the same as <code>for ($i = 0; $i -lt $FileContent.count; $i++) {</code>, but the second is less of a hassle to read.</li>\n<li>As a Cmdlet, your <code>reg2psi</code> function should probably follow the <code>Verb-Noun</code> naming convention, with a name like <code>ConvertFrom-RegistryFile</code> perhaps?</li>\n<li>I'm not sure creating the <code>allcommands_reg.ps1</code> is your script's responsibility, and I'm also not sure it's well-behaved if you're working on a folder that contains a file called <code>allcommands.reg</code>. Might be best to just have your cmdlet create the individual <code>*_reg.ps1</code> files and making a separate script for combining them.</li>\n<li>The line joining removes <em>all</em> backslashes from lines that end with a backslash, which could be dangerous unless you know that a backslash will never appear in another position. Maybe that's the case (I don't know much about the Windows registry), but being explicit and replacing <code>\\\\$</code> instead is probably best.</li>\n<li>Also, when doing the line joining, you can just iterate over the lines directly rather than keeping track of an index:</li>\n</ul>\n<pre><code>foreach ($line in $fileContent) {\n if ($line.EndsWith(&quot;\\&quot;)) {\n # stuff\n } else {\n # stuff\n }\n}\n</code></pre>\n<ul>\n<li>Once the lines are joined...\n<ul>\n<li>I <em>think</em> that first series of matches can be reduced to just one like <code>$joinedLine -match '^\\[-?HKEY[^\\]]*\\]$'</code>. But again, I don't have much registry experience, I might be missing something.</li>\n<li>If instead of treating the key as starting with <code>-</code> you treat the line as starting with <code>[-</code> you might be able to get rid of some duplication:</li>\n</ul>\n</li>\n</ul>\n<pre><code>$key = $joinedLine -replace '^\\[-?|\\]$'\n$hiveName = $key.Split('\\')[0]\n$key = '&quot;' + ($key -replace $hiveName, &quot;$($hive[$hiveName]):&quot;) + '&quot;'\nif ($joinedLine -StartsWith '[-') {\n # Add a Remove-Item command\n} else {\n # Maybe add a New-Item command\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T16:01:13.117", "Id": "255806", "ParentId": "255785", "Score": "1" } }, { "body": "<p>Well, after numerous fixes and improvements, this is the final version of the script. I have tested it rigorously and made sure it is working properly.</p>\n<p>So here is the code:</p>\n<pre><code>Function reg2ps1 {\n\n [CmdLetBinding()]\n Param(\n [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [ValidateNotNullOrEmpty()]\n [Alias(&quot;FullName&quot;)]\n [string]$path,\n $Encoding = &quot;utf8&quot;\n )\n\n Begin {\n $hive = @{\n &quot;HKEY_CLASSES_ROOT&quot; = &quot;HKCR:&quot;\n &quot;HKEY_CURRENT_CONFIG&quot; = &quot;HKCC:&quot;\n &quot;HKEY_CURRENT_USER&quot; = &quot;HKCU:&quot;\n &quot;HKEY_LOCAL_MACHINE&quot; = &quot;HKLM:&quot;\n &quot;HKEY_USERS&quot; = &quot;HKU:&quot;\n }\n [system.boolean]$isfolder = $false\n $addedpath = @()\n }\n Process {\n if (test-path $path -pathtype container) { $files = (get-childitem -path $path -recurse -force -file -filter &quot;*.reg&quot;).fullname; $isfolder = $true }\n else { if ($path.endswith(&quot;.reg&quot;)) { $files = $path } }\n foreach ($File in $Files) {\n $Commands = @()\n foreach ($root in $hive.keys) {\n if ((Get-Content -Path $file -Raw) -match $root -and $hive[$root] -notin ('HKCU:', 'HKLM:')) {\n $commands += &quot;New-PSDrive -Name $($hive[$root].replace(':', '')) -PSProvider Registry -Root $root&quot;\n }\n }\n [string]$text = $nul\n $FileContent = Get-Content $File | Where-Object { ![string]::IsNullOrWhiteSpace($_) } | ForEach-Object { $_.Trim() }\n $joinedlines = @()\n foreach ($line in $FileContent) {\n if ($line.EndsWith(&quot;\\&quot;)) {\n $text = $text + ($line -replace &quot;\\\\$&quot;).trim()\n }\n else {\n $joinedlines += $text + $line\n [string]$text = $nul\n }\n }\n\n foreach ($joinedline in $joinedlines) {\n if ($joinedline -match &quot;\\[HKEY(.*)+\\]&quot;) {\n $key = $joinedline -replace '\\[-?|\\]'\n $hivename = $key.split('\\')[0]\n $key = '&quot;' + ($key -replace $hivename, $hive.$hivename) + '&quot;'\n if ($joinedline.StartsWith(&quot;[-HKEY&quot;)) {\n $Commands += 'Remove-Item -Path {0} -Force -Recurse' -f $key\n }\n else {\n if ($key -notin $addedpath) {\n $Commands += 'New-Item -Path {0} -ErrorAction SilentlyContinue | Out-Null' -f $key\n $addedpath += $key\n }\n }\n }\n elseif ($joinedline -match &quot;`&quot;([^`&quot;=]+)`&quot;=&quot;) {\n [System.Boolean]$delete = $false\n $name = ($joinedline | select-string -pattern &quot;`&quot;([^`&quot;=]+)`&quot;&quot;).matches.value | select-object -first 1\n switch ($joinedline) {\n { $joinedline -match &quot;=-&quot; } { $Commands += 'Remove-ItemProperty -Path {0} -Name {1} -Force' -f $key, $Name; $delete = $true }\n { $joinedline -match '&quot;=&quot;' } {\n $type = &quot;String&quot;\n $value = $joinedline -replace &quot;`&quot;([^`&quot;=]+)`&quot;=&quot;\n }\n { $joinedline -match &quot;dword&quot; } {\n $type = &quot;Dword&quot;\n $value = $joinedline -replace &quot;`&quot;([^`&quot;=]+)`&quot;=dword:&quot;\n $value = &quot;0x&quot; + $value\n }\n { $joinedline -match &quot;qword&quot; } {\n $type = &quot;Qword&quot;\n $value = $joinedline -replace &quot;`&quot;([^`&quot;=]+)`&quot;=qword:&quot;\n $value = &quot;0x&quot; + $value\n }\n { $joinedline -match &quot;hex(\\([2,7,b]\\))?:&quot; } {\n $value = ($joinedline -replace &quot;`&quot;[^`&quot;=]+`&quot;=hex(\\([2,7,b]\\))?:&quot;).split(&quot;,&quot;)\n $hextype = ($joinedline | select-string -pattern &quot;hex(\\([2,7,b]\\))?&quot;).matches.value\n switch ($hextype) {\n { $hextype -match 'hex(\\([2,7])\\)' } {\n $ValueEx = '$value = for ($i = 0; $i -lt $value.count; $i += 2) {if ($value[$i] -ne &quot;00&quot;) {[string][char][int](&quot;0x&quot; + $value[$i])}'\n switch ($hextype) {\n 'hex(2)' { $type = &quot;ExpandString&quot;; invoke-expression $($ValueEx + '}') }\n 'hex(7)' { $type = &quot;MultiString&quot;; invoke-expression $($ValueEx + ' else {&quot;,&quot;}}'); $value = 0..$($value.count - 3) | % { $value[$_] } }\n }\n $value = $value -join &quot;&quot;\n if ($type -eq &quot;ExpandString&quot;) { $value = '&quot;' + $value + '&quot;' }\n else {$value = foreach ($seg in $value.split(',')) {'&quot;' + $seg + '&quot;'}; $value = $value -join ','}\n }\n 'hex(b)' {\n $type = &quot;Qword&quot;\n $value = for ($i = $value.count - 1; $i -ge 0; $i--) { $value[$i] }\n $value = '0x' + ($value -join &quot;&quot;).trimstart('0')\n }\n 'hex' {\n $type = &quot;Binary&quot;\n $value = $value | %{'0x' + $_}\n $value = '([byte[]]$(' + $($value -join &quot;,&quot;) + '))'\n }\n }\n }\n }\n if (!$delete) {\n $Commands += 'Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3} -Force' -f $key, $name, $type, $value\n }\n }\n elseif ($joinedline -match &quot;@=&quot;) {\n $name = '&quot;(Default)&quot;'; $type = 'string'; $value = $joinedline -replace '@='\n $commands += 'Set-ItemProperty -Path {0} -Name {1} -Type {2} -Value {3}' -f $key, $name, $type, $value\n }\n \n }\n $Commands | out-file -path $($file.replace('.reg', '_reg.ps1')) -encoding $encoding\n }\n if ($isfolder) {\n $allcommands = (get-childitem -path $path -recurse -force -file -filter &quot;*_reg.ps1&quot;).fullname | where-object { $_ -notmatch &quot;allcommands_reg&quot; } | foreach-object { get-content $_ }\n $allcommands | out-file -path &quot;${path}\\allcommands_reg.ps1&quot; -encoding $encoding\n }\n }\n}\n$path = $args[0]\nreg2ps1 $path\n</code></pre>\n<p>This is truly the final version.</p>\n<p>The fixes include:</p>\n<ol>\n<li><p>Using a loop to add <code>HKCR</code>, <code>HKCC</code> and <code>HKU</code> PSDrives if necessary.</p>\n</li>\n<li><p>Removed unnecessary <code>$binary</code> boolean.</p>\n</li>\n<li><p>Added quotes to each substrings in a multistring value to ensure the command will run correctly if the substrings contain spaces.</p>\n</li>\n<li><p>Fixed a bug that removes colons from a <code>$key</code> variable and causes <code>set-itemproperty</code> commands modify keys without a colon, this would occur if the key contains a <code>reg_binary</code> value and the value the <code>set-itemproperty</code> line modifies comes after the <code>reg_binary</code> value in the same key.</p>\n</li>\n<li><p>Implemented the correct way to modify <code>REG_BINARY</code> values using <code>Set-ItemProperty</code>, so that <code>reg add</code> commands are not needed and the script thus becomes 100% PowerShell.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T07:23:56.923", "Id": "261267", "ParentId": "255785", "Score": "2" } } ]
{ "AcceptedAnswerId": "255806", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T05:06:49.177", "Id": "255785", "Score": "3", "Tags": [ "beginner", "programming-challenge", "converting", "powershell" ], "Title": "PowerShell script to convert .reg files to PowerShell commands" }
255785
<p>I am trying to write a code that should look on the laptop for a file, open it, if found, and read the context of that file (it should be .txt or .doc). So far, I wrote this code which is working:</p> <pre><code>def search(drive, target): file_path = '' if drive == &quot;D&quot;: for root, dirs, files in os.walk(r&quot;D:\\&quot;): for name in files: if name == target: file_path = os.path.abspath(os.path.join(root, name)) elif drive == &quot;C&quot;: for root, dirs, files in os.walk(r&quot;C:\\&quot;): for name in files: if name == target: file_path = os.path.abspath(os.path.join(root, name)) return file_path def path(): file_name = input(&quot;Enter the name of the desired file: &quot;) path = os.path.abspath(file_name) file_path = search(path[0], file_name) return file_path </code></pre> <p>The problem is that this piece of code is very slow, as it has to look on each directory on the drive (the only trick I used to save some time was to take the abspath and to look on what drive it is saved, thus it doesn't look on each existing drive).</p> <p>I am thinking of using multiprocessing, but I do not know how to use it. Can anybody help? Thank you very much for your time!</p>
[]
[ { "body": "<p>Since you are already requiring the filename to start with the correct drive name, your <code>target</code> will already look like a normal valid path. So you could at least check if what the user entered is actually the correct path, short-circuiting the whole search:</p>\n<pre><code>def search(drive, target):\n if os.path.isfile(target):\n return os.path.abspath(target)\n ...\n</code></pre>\n<p>You should also stop looking as soon as you have found your target and use the <code>in</code> keyword instead of manually checking all files yourself:</p>\n<pre><code> ...\n for root, dirs, files in os.walk(r&quot;D:\\\\&quot;):\n if target in files:\n return os.path.abspath(os.path.join(root, target))\n</code></pre>\n<p>Other than that, I am afraid you are mostly out of luck. There are only two ways to quickly find something in a big pile of somethings:</p>\n<ol>\n<li>You search through all somethings until you find the something you are looking for.</li>\n<li>You have a datastructure, called an index, which tells you how to find each (or at least some, including hopefully the one something you are looking for) of the somethings.</li>\n</ol>\n<p>In the Unix world there is the command line tool <a href=\"https://en.wikipedia.org/wiki/Locate_(Unix)\" rel=\"nofollow noreferrer\"><code>locate</code></a>, which uses a periodically updated database of files to make finding files fast (as long as they are in that database). I am not sure what the equivalent Windows (command line) tool is, though you may find some solution <a href=\"https://superuser.com/questions/327109/unix-type-locate-on-windows\">here</a>. You can then call that tool using <a href=\"https://docs.python.org/3/library/subprocess.html\" rel=\"nofollow noreferrer\"><code>subprocess</code></a>.</p>\n<p>Of yourse, if you need this search very often (twice is probably already often enough), you could also built such an index yourself, meaning you only have to check all files once:</p>\n<pre><code>from collections import defaultdict\n\nINDEX = {}\n\ndef build_index(drive):\n index = defaultdict(set)\n for root, _, files in os.walk(drive):\n for file in files:\n index[file].add(root)\n return dict(index)\n\ndef search(drive, target):\n if drive not in INDEX:\n INDEX[drive] = build_index(drive)\n root = next(iter(INDEX[drive][target]))\n return os.path.abspath(os.path.join(root, target))\n</code></pre>\n<p>Note that this arbitrarily chooses one result if a file name appears multiple times, similarly to your code which chooses the last one encountered (with the order of processing arbitrarily defined). On my machine, for example, there are 8708 files called <code>index.js</code> and it is not clear which one you want. It might be a better interface to return all of them instead of one arbitrary one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T20:31:59.200", "Id": "504892", "Score": "1", "body": "Great piece of code! I didn't think of this approach! I used your idea and it fits perfect in my code! Thank you so much for your kindly reply! I changed it a bit in the sense that after the search function is completed, the result will be stored in a repository from where my code can keep track of each file that had to be accessed at least once. Thank you very much! All the best!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T22:01:28.973", "Id": "504902", "Score": "1", "body": "`locate` ... _I am not sure what the equivalent Windows (command line) tool is_ ... `where` is quite fast." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:12:35.843", "Id": "255792", "ParentId": "255788", "Score": "3" } } ]
{ "AcceptedAnswerId": "255792", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T06:24:38.733", "Id": "255788", "Score": "2", "Tags": [ "python", "file" ], "Title": "Searching faster for a file on the drive using Python" }
255788
<p>I was trying to solve this time conversion problem on hackerrank but couldn't get the right output on test cases.</p> <p>I have given my best try along with the expected and my output below. Any optimisation in it will be helpful</p> <p>Following is the question.</p> <p><strong>Input Format</strong></p> <blockquote> <p>A single string containing a time in 12-hour clock format (i.e.:hh:mm:ssAM or hh:mm:ssPM), where 01 &lt;= hh &lt;= 12.</p> </blockquote> <p><strong>Output Format</strong></p> <blockquote> <p>Convert and print the given time in 24-hour format, where 00 &lt;= hh &lt;= 23.</p> </blockquote> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int main() { string s; cin&gt;&gt;s; if(s[8]=='A') { if(s[0]==1 &amp;&amp; s[1]==2) { s[0]=0; s[1]=0; string s1=s.substr(0,8); cout&lt;&lt;s1&lt;&lt;'\n'; } else { string s1=s.substr(0,8); cout&lt;&lt;s1&lt;&lt;'\n'; } } else { if(s[0]==1 &amp;&amp; s[1]==2) { string s1=s.substr(0,8); cout&lt;&lt;s1&lt;&lt;'\n'; } else { int x=(s[0]*10)+(s[1]); string s1=s.substr(2,6); cout&lt;&lt;12+x&lt;&lt;s1&lt;&lt;'\n'; } } return 0; } </code></pre> <p><strong>Input</strong> -- 07:05:45PM</p> <p><strong>My Output</strong> -- 547:05:45</p> <p><strong>Expected Output</strong> -- 19:05:47</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T08:24:47.547", "Id": "504817", "Score": "1", "body": "Hey, welcome to Code Review! Unfortunately, we can only review code that already works as intended (i.e. produces the correct output). The one exception to this is if you are trying to beat an online coding challenge and get a [tag:time-limit-exceeded] error, but are quite sure that your code would produce the correct output eventually, just not in the given time limit. Have a look at our [help/dont-ask] for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T08:50:20.000", "Id": "504819", "Score": "1", "body": "I will keep this in mind next time." } ]
[ { "body": "<p>The issue is at Line#36 - <code>int x=(s[0]*10)+(s[1]);</code>.</p>\n<p><strong>Issue</strong></p>\n<p>The values of <code>s[0]</code> and <code>s[1]</code> are implicitly being casted to integers, which means that the ASCII values of <code>s[0]</code> and <code>s[1]</code> are being used for computation.</p>\n<p><strong>Solution</strong></p>\n<p>Changing Line#36 to <code>int x=((s[0] - '0')*10)+(s[1] - '0');</code>, makes the code pass the test case mentioned in the question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T08:52:39.757", "Id": "504820", "Score": "3", "body": "For the future, please refuse to answer off-topic questions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T07:19:42.760", "Id": "255791", "ParentId": "255790", "Score": "-2" } } ]
{ "AcceptedAnswerId": "255791", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T06:45:20.270", "Id": "255790", "Score": "-2", "Tags": [ "c++", "performance", "programming-challenge" ], "Title": "Time Conversion Problem. What am I doing wrong?" }
255790
<p>I have a 3GB gz file that I am trying to break into chunks of smaller files which are not required to be gz (I tried to make files of 10000000 lines, this is not a requirement, the chunks could be of any size), but my method is taking ages to run (about 12 minutes). I have the requirement to not use any library such as Pandas, Spark, etc. I can only use pure Python. I tried profiling my code and the write seems to be the slowest thing. Here's my code :</p> <pre><code>import gzip import os class FileSplitter: def __init__(self): self.parse_args(sys.argv) @staticmethod def run(): splitter = FileSplitter() #run to split the big file into smaller files splitter.split() def split(self): file_number = 1 line_number = 0 print(&quot;Splitting %s into multiple files with %s lines&quot; % (os.path.join(self.working_dir, self.file_base_name), str(self.split_size))) out_file = self.get_new_file(file_number) a_file = gzip.open(self.in_file, 'rt') t = next(a_file) with a_file as f: for line in f: out_file.write(line) line_number += 1 if line_number == self.split_size: out_file.close() file_number += 1 line_number = 1 out_file = self.get_new_file(file_number) out_file.close() print(&quot;Created %s files.&quot; % (str(file_number))) def get_new_file(self,file_number): &quot;&quot;&quot;return a new file object ready to write to&quot;&quot;&quot; new_file_name = &quot;%s.%s&quot; % (self.file_base_name, str(file_number)) new_file_path = os.path.join(self.working_dir, 'pychunks', new_file_name) print (&quot;creating file %s&quot; % (new_file_path)) return open(new_file_path, 'w') def parse_args(self,argv): &quot;&quot;&quot;parse args and set up instance variables&quot;&quot;&quot; try: self.split_size = 10000000 if len(argv) &gt; 2: self.split_size = int(argv[2]) self.file_name = argv[1] self.in_file = self.file_name self.working_dir = os.getcwd() self.file_base_name = os.path.basename(self.file_name) except: print(self.usage()) sys.exit(1) def usage(self): return &quot;&quot;&quot; Split a large file into many smaller files with set number of rows. Usage: $ python file_splitter.py &lt;file_name&gt; [row_count] row_count is optional (default is 1000)&quot;&quot;&quot; if __name__ == &quot;__main__&quot;: FileSplitter.run() </code></pre> <p>To run my code I call a .py file containing this code with the name of my gz file, example : python myprogfile.py test.gz</p> <p>Would you do that differently? Would you use threading (i tried but I couldn't succeed yet as I don't have experience with that)? What would you change in this code?</p> <p>I don't know if it is my laptop that's too weak in terms of memory and CPU ...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:51:15.950", "Id": "504824", "Score": "1", "body": "How large are the uncompressed files in total? It might be that you are just hitting the write speed of your hard disk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:54:19.630", "Id": "504826", "Score": "0", "body": "In total they're 9Go (17 files of about 580 Mo each)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T10:30:09.733", "Id": "504830", "Score": "0", "body": "You mean 9Gb and 580Mb, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T10:31:17.767", "Id": "504831", "Score": "1", "body": "Yes, sorry wrote that in french measures" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T18:26:11.013", "Id": "504879", "Score": "0", "body": "A few questions to clarify the requirements the program must implement or the assumptions it is allowed to make. Is the decompressed input file always going to be a text file? Is it a requirement that each of the split files are readable text files as well (given that the command-line argument `row_count` specifies the number of lines per split file)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T19:08:49.890", "Id": "504883", "Score": "1", "body": "Yes the decompressed input file is always going to be a text file, and no it is not a requirement that the split files are readable text files" } ]
[ { "body": "<blockquote>\n<p>What would you change in this code?</p>\n</blockquote>\n<p>I'd simplify the <code>split</code> function. Not counting lines and files myself and opening/closing the output files at different places without a <code>with</code> statement. Just always try to read another line and if that succeeds, put it and the next up to <code>split_size - 1</code> lines into another output file.</p>\n<pre><code> def split(self):\n print(&quot;Splitting %s into multiple files with %s lines&quot; % (os.path.join(self.working_dir, self.file_base_name), str(self.split_size)))\n\n with gzip.open(self.in_file, 'rt') as fin:\n for file_number, line in enumerate(fin, start=1):\n with self.get_new_file(file_number) as fout:\n fout.write(line)\n fout.writelines(itertools.islice(fin, self.split_size - 1))\n\n print(&quot;Created %s files.&quot; % (str(file_number)))\n</code></pre>\n<p>While I do frequently use <code>f</code> when I only work on one file, I didn't like the very different names <code>f</code> and <code>out_file</code>. In such cases I use <code>fin</code> and <code>fout</code> (and I think that's rather common), so I changed that as well.</p>\n<p>I'd probably also change the inner <code>with</code> to <code>with open(...) as fout</code> and have <code>get_new_file</code> return only the filename, not open the file itself. I'd rather keep the <code>open</code> in the <code>with</code> statement and have <code>get_new_file</code> be a function without such side effects. Or if your only reason for having <code>get_new_file</code> at all was that you had two places for using it, then now you don't need it anymore and could just build the filename inside the <code>split</code> function.</p>\n<p>Still unfixed issues in your code:</p>\n<ul>\n<li>While you fixed one <code>line_number = 1</code> (from <a href=\"https://stackoverflow.com/q/66105913/12671057\">your original</a>) to <code>line_number = 0</code>, you forgot the other one. This makes your chunks one line too short. Wouldn't happen if you only had one place :-)</li>\n<li>Lacking import of <code>sys</code>, causing <code>NameError: name 'sys' is not defined</code>.</li>\n<li>Lacking creation of folder <code>pychunks</code>. Without that, the user gets a rather confusing traceback and <code>FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/p/pychunks/main.py.gz.1'</code>.</li>\n<li><code>t = next(a_file)</code> loses the first line, as that is never used. Might be what <em>you</em> want, but it's not documented and goes against common sense and the description that <em>is</em> there and gets shown when you run the script without arguments. Perhaps if you do want that, make it a command-line argument for skipping the first number of lines, with default <code>0</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T14:52:16.480", "Id": "255804", "ParentId": "255793", "Score": "2" } }, { "body": "<p>Since the split files do not need to be readable text files, I would read &amp; write in chunks of bytes, not in lines. This should be faster than reading and writing line by line. We can go with a chunk size of 4,096 bytes because 4,096 or 8,192 is a typical block size on most file systems.</p>\n<p>Although, I should note that when I tested your script on my system with a 9 GB text file which has 81 characters per line, it took about <strong>73 seconds</strong> to split it into files of 10,000,000 lines each, or about 772 MB per file. The fact that it takes 12 minutes on your laptop likely confirms @Graipher's suspicion that your disk's write speed is the bottleneck here.</p>\n<p>Using a refactored version of your script that reads &amp; writes in byte chunks (provided at the end of this review), when I ran it on the same file with <code>--size 772</code> (split into files of size 772 MB) it took about <strong>35 seconds</strong>. Still a decent improvement, but I'd be curious to know how it runs on your machine.</p>\n<p>To implement this, I personally like having a helper method like the following which tells us the chunk sizes to read/write:</p>\n<pre class=\"lang-python prettyprint-override\"><code>from typing import Iterator\n\ndef chunk_sizes(total_bytes: int, chunk_size: int) -&gt; Iterator[int]:\n for _ in range(total_bytes // chunk_size):\n yield chunk_size\n\n if remaining_bytes := total_bytes % chunk_size:\n yield remaining_bytes\n</code></pre>\n<p>For example, <code>list(chunk_sizes(10000, 4096))</code> which returns <code>[4096, 4096, 1808]</code> would tell us that in order to read 10,000 bytes in 4,096 byte chunks, we should read 4,096 bytes, followed by another 4,096 bytes, followed by 1,808 bytes.</p>\n<h1>General review</h1>\n<ul>\n<li><p>There's no reason to have <code>run()</code> be a <code>staticmethod</code>, and it's weird how <code>FileSplitter</code> creates an instance of itself inside this method.</p>\n<p>If you change the top-level invocation to <code>FileSplitter().run()</code> then <code>run()</code> could be simplified to</p>\n<pre class=\"lang-python prettyprint-override\"><code>def run(self):\n self.split()\n</code></pre>\n<p>But if you do that you might as well remove <code>run()</code> and make <code>FileSplitter().split()</code> the top-level call. My recommendation is to move the contents of <code>run()</code> under the <code>__name__ == &quot;__main__&quot;</code> guard and then remove <code>run()</code> entirely as it's no longer needed.</p>\n</li>\n<li><p>Always open files with a <code>with</code> block to ensure the file is closed properly.</p>\n</li>\n<li><p>I recommend using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> because you get a lot of stuff for free (input type validations, help/usage message with <code>-h</code>, etc.).</p>\n</li>\n<li><p>I would move the command-line argument parsing logic out of <code>FileSplitter</code>, because it should ideally only have one responsibility: splitting files.</p>\n</li>\n<li><p>Specify the exact exception you want to handle with a try-except. <a href=\"https://www.flake8rules.com/rules/E722.html\" rel=\"nofollow noreferrer\">Handling a bare <code>except</code> is considered a bad practice</a>.</p>\n</li>\n<li><p>I wouldn't use <code>sys.exit</code> inside methods you might want to test, because it exits the Python interpreter.</p>\n</li>\n<li><p>In Python 3, f-strings are a much more legible way of doing string interpolation.</p>\n<p>Before</p>\n<pre class=\"lang-python prettyprint-override\"><code>new_file_name = &quot;%s.%s&quot; % (self.file_base_name, str(file_number))\n</code></pre>\n<p>After</p>\n<pre class=\"lang-python prettyprint-override\"><code>new_file_name = f&quot;{self.file_base_name}.{file_number}&quot;\n</code></pre>\n</li>\n</ul>\n<h1>Refactored version</h1>\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport argparse\nimport gzip\nimport os\nimport itertools\n\nfrom typing import BinaryIO, Iterator\n\nCHUNK_SIZE = 4096 # bytes\n\n\ndef megabytes_to_bytes(megabytes: int) -&gt; int:\n return megabytes * 1024 * 1024\n\n\ndef chunk_sizes(total_bytes: int, chunk_size: int) -&gt; Iterator[int]:\n for _ in range(total_bytes // chunk_size):\n yield chunk_size\n\n if remaining_bytes := total_bytes % chunk_size:\n yield remaining_bytes\n\n\nclass FileSplitter:\n input_file_path: str\n output_directory: str\n output_file_base_name: str\n split_size: int # size of each partition, in MB\n\n def __init__(\n self, input_file_path: str, output_directory: str, split_size: int\n ) -&gt; None:\n self.input_file_path = input_file_path\n self.output_directory = output_directory\n name = os.path.basename(input_file_path)\n name_without_file_extension = os.path.splitext(name)[0]\n self.output_file_base_name = name_without_file_extension\n self.split_size = split_size\n\n def get_new_file(self, file_number: int) -&gt; BinaryIO:\n new_file_name = f&quot;{self.output_file_base_name}.{file_number}&quot;\n new_file_path = os.path.join(self.output_directory, new_file_name)\n return open(new_file_path, &quot;wb&quot;)\n\n def split(self) -&gt; None:\n bytes_per_file = megabytes_to_bytes(self.split_size)\n os.makedirs(self.output_directory, exist_ok=True)\n\n with gzip.open(self.input_file_path, mode=&quot;rb&quot;) as in_file:\n for file_number in itertools.count(start=1, step=1):\n with self.get_new_file(file_number) as out_file:\n for chunk_size in chunk_sizes(bytes_per_file, CHUNK_SIZE):\n chunk = in_file.read(chunk_size)\n # chunk == &quot;&quot; means we finished reading the input file\n if not chunk:\n return\n out_file.write(chunk)\n\n\nif __name__ == &quot;__main__&quot;:\n parser = argparse.ArgumentParser(\n description=&quot;Read a gzip-compressed file &quot;\n &quot;and split its uncompressed contents into separate files.&quot;\n )\n parser.add_argument(\n &quot;file_name&quot;, help=&quot;a gzip-compressed file, e.g. foo.gz&quot;\n )\n parser.add_argument(\n &quot;--size&quot;,\n type=int,\n default=500,\n help=&quot;desired size of each partition, in MB&quot;,\n )\n args = parser.parse_args()\n\n output_directory = os.path.join(os.getcwd(), &quot;pychunks&quot;)\n splitter = FileSplitter(args.file_name, output_directory, args.size)\n splitter.split()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T13:22:01.783", "Id": "504955", "Score": "0", "body": "Thank you so much for both the review and your suggestion! This took less than 2 minutes on my laptop, I am very curious about how chunks of bytes instead of lines made this gap of performance between the two programs, also one question that I am curious about too, how many lines does your 9GB file contain? Mine has about 162 000 000 lines, and does yield have any effect on time execution here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T19:47:00.537", "Id": "505001", "Score": "1", "body": "@AhlamAIS Nice, I'm glad it worked well for you! My 9GB file has 120,795,955 lines. I don't think `yield` has much of an effect on time execution here compared to the original, because in the original it is also iterating in a memory-efficient way (line by line)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T21:08:31.633", "Id": "505007", "Score": "1", "body": "What's the speed with chunk size 1 MB? That's what I usually use and I think 4 KB was slower for me in previous benchmarks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T22:12:04.043", "Id": "505012", "Score": "1", "body": "@KellyBundy That's a good catch! Yeah a chunk size of 1 MB for me was much faster (~8-9 seconds). I'd imagine the optimal value varies depending on one's system, so a nice enhancement to make to this script would be to allow the user to configure the chunk size to use via a command-line option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T14:30:15.960", "Id": "506060", "Score": "0", "body": "@Setris I am amazed at the way you have given this review. This comment might be against the rules of Stack Exchange but I would like to thank you for this answer. There was a lot for me to learn from it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:55:53.607", "Id": "506084", "Score": "0", "body": "@JohnDoe Thanks, I'm happy to know that you found it helpful!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T03:33:40.080", "Id": "255834", "ParentId": "255793", "Score": "4" } } ]
{ "AcceptedAnswerId": "255834", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T09:16:53.843", "Id": "255793", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "file" ], "Title": "Breaking a 3GB gz file into chunks" }
255793
<p>I am looking for some advice on how to create a new ViewModel within an already existing ViewModel.</p> <p>I am creating a Tic Tac Toe game, to improve my knowledge of the MVVM pattern, WPF and C#. I am looking to contain the buttons (<code>TileViewModel</code>) as separate ViewModels and implement these into the game window (<code>GameViewModel</code>). I have made a list of TileViewModels in the GameViewModel and added 9 of these views to the XAML, binding the list in the ViewModel with each View using <code>DataContext</code> with the index of the array.</p> <p>GameViewModel.cs</p> <pre class="lang-cs prettyprint-override"><code>using MvvmCross.Commands; using MvvmCross.ViewModels; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using TicTacToe.Core.Models; namespace TicTacToe.Core.ViewModels { public class GameViewModel : MvxViewModel, IBaseViewModel { private string nextValue = &quot;X&quot;; private bool _won; public List&lt;TileViewModel&gt; ViewTiles { get; set; } public GameViewModel() { Grid grid = new Grid(); grid.Start(); ViewTiles = new List&lt;TileViewModel&gt; { new TileViewModel(this), new TileViewModel(this), new TileViewModel(this), new TileViewModel(this), new TileViewModel(this), new TileViewModel(this), new TileViewModel(this), new TileViewModel(this), new TileViewModel(this) }; } public string GetNextValue() { // Get the next value to display on the TileViewModel nextValue = nextValue.Equals(&quot;X&quot;) ? &quot;O&quot; : &quot;X&quot;; return nextValue; } public bool Won { get { return _won; } set { _won = value; } } private void blockWon() { } public bool CheckForWin() { int AddValue(string tileValue) { if (tileValue.Equals(&quot;X&quot;)) { return 1; } else if(tileValue.Equals(&quot;O&quot;)) { return -1; } return 0; } // check rows int total = 0; for (int i=0; i&lt;ViewTiles.Count; i++) { if (i % 3 == 0) { if (Math.Abs(total) == 3) { Won = true; } total = 0; } total += AddValue(ViewTiles[i].Value); } // check columns total = 0; int loop_count = 0; for (int i=0; i&lt;ViewTiles.Count; i++) { if (i % 3 == 0 &amp;&amp; i != 0) { if (Math.Abs(total) == 3) { Won = true; } loop_count++; total = 0; } total += AddValue(ViewTiles[((i % 3) * 3) + loop_count].Value); } return false; } } } </code></pre> <p>GameView.xaml</p> <pre class="lang-xml prettyprint-override"><code>&lt;views:MvxWpfView xmlns:views=&quot;clr-namespace:MvvmCross.Platforms.Wpf.Views;assembly=MvvmCross.Platforms.Wpf&quot; xmlns:customviews=&quot;clr-namespace:TicTacToe.Wpf.Views&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; xmlns:local=&quot;clr-namespace:TicTacToe.Wpf.Views&quot; xmlns:mvx=&quot;clr-namespace:MvvmCross.Platforms.Wpf.Binding;assembly=MvvmCross.Platforms.Wpf&quot; xmlns:ViewModels=&quot;clr-namespace:TicTacToe.Core.ViewModels;assembly=TicTacToe.Core&quot; x:Class=&quot;TicTacToe.Wpf.Views.GameView&quot; mc:Ignorable=&quot;d&quot; d:DesignHeight=&quot;450&quot; d:DesignWidth=&quot;800&quot; &gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width=&quot;*&quot;/&gt; &lt;ColumnDefinition Width=&quot;*&quot;/&gt; &lt;ColumnDefinition Width=&quot;*&quot;/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height=&quot;*&quot;/&gt; &lt;RowDefinition Height=&quot;*&quot;/&gt; &lt;RowDefinition Height=&quot;*&quot;/&gt; &lt;/Grid.RowDefinitions&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[0]}&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;0&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[1]}&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;0&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[2]}&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;0&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[3]}&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;1&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[4]}&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[5]}&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;1&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[6]}&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;2&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[7]}&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;2&quot;/&gt; &lt;customviews:TileView DataContext=&quot;{Binding ViewTiles[8]}&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;2&quot;/&gt; &lt;/Grid&gt; &lt;/views:MvxWpfView&gt; </code></pre> <p>TielViewModel.cs</p> <pre class="lang-cs prettyprint-override"><code>using MvvmCross.ViewModels; using MvvmCross.Commands; using System; using System.Collections.Generic; using System.Text; namespace TicTacToe.Core.ViewModels { public class TileViewModel : MvxViewModel { private string _value = &quot;&quot;; private bool _enabled = true; private IBaseViewModel _baseViewModel; public IMvxCommand TileClick { get; set; } public TileViewModel(IBaseViewModel baseViewModel) { TileClick = new MvxCommand(Increment); _baseViewModel = baseViewModel; } public string Value { get { return _value; } set { _value = value; RaisePropertyChanged(() =&gt; Value); } } public bool Enabled { get { return _enabled; } set { _enabled = value; RaisePropertyChanged(() =&gt; Enabled); } } public void Increment() { Enabled = false; Value = _baseViewModel.GetNextValue(); _baseViewModel.CheckForWin(); } } } </code></pre> <p>TileView.xaml</p> <pre class="lang-xml prettyprint-override"><code>&lt;views:MvxWpfView x:Class=&quot;TicTacToe.Wpf.Views.TileView&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; xmlns:local=&quot;clr-namespace:TicTacToe.Wpf.Views&quot; mc:Ignorable=&quot;d&quot; xmlns:views=&quot;clr-namespace:MvvmCross.Platforms.Wpf.Views;assembly=MvvmCross.Platforms.Wpf&quot; xmlns:mvx=&quot;clr-namespace:MvvmCross.Platforms.Wpf.Binding;assembly=MvvmCross.Platforms.Wpf&quot; d:DesignHeight=&quot;450&quot; d:DesignWidth=&quot;800&quot;&gt; &lt;Grid&gt; &lt;Button mvx:Bi.nd=&quot;Command TileClick&quot; IsEnabled=&quot;{Binding Enabled}&quot;&gt; &lt;TextBlock Text=&quot;{Binding Value}&quot;/&gt; &lt;/Button&gt; &lt;/Grid&gt; &lt;/views:MvxWpfView&gt; </code></pre> <p>The solution I have implemented works well, I was just wondering if there was a better way to go about implementing a solution like this.</p> <p>I am specifically using MVVMCross, but I guess this is more of a generic MVVM solution.</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T20:36:34.417", "Id": "504893", "Score": "1", "body": "Just for reference: recently i wrote an answer for similar game in WPF+MVVM but in Russian StackOverflow Community. If you want, you may look at the code, here's [link](https://ru.stackoverflow.com/a/1239671/373567). There's implementation for Game field only, without internal game logic. 8x8 there but change it to 3x3 is job to replace 2 contants. :) Especially look, how I'm using `ItemsControl` there. Also there's no any MVVM framework, only pure WPF." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T20:45:06.080", "Id": "504894", "Score": "1", "body": "Here's a `Linq` trick to create 9 tiles `ViewTiles = Enumarable.Range(0, 9).Select(_ => new TileViewModel(this)).ToList()`. 9x `customviews:TileView` in `Grid` can be replaced with one [`UniformGrid`](https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.uniformgrid?view=netframework-4.8)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T21:00:44.343", "Id": "504896", "Score": "1", "body": "@aepot Thank you for the Linq hints, and the reference to the other question, I have tried to implement your code on the XAML but get the error ```The property 'ItemsSource' was not found in type 'UniformGrid'```, any ideas on this, my XAML knowledge is very basic. Is having nested ViewModels like this a correct approach for my application? Thanks again," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T21:20:12.323", "Id": "504897", "Score": "1", "body": "Ah, sorry, forgot some important things `<ItemsControl ItemsSource=\"{Binding ViewTiles}\"><ItemsControl.ItemTemplate><DataTemplate><customviews:TileView DataContext=\"{Binding}\"/></DataTemplate></ItemsControl.ItemTemplate><ItemsControl.ItemsPanel><ItemsPanelTemplate><UniformGrid Rows=\"3\" Columns=\"3\"/></ItemsPanelTemplate></ItemsControl.ItemsPanel></ItemsControl>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T21:24:11.223", "Id": "504898", "Score": "1", "body": "@aepot Thank you so much! That was exactly what I was looking for originally! I didn't like the hardcoding on the View!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T11:53:57.643", "Id": "255798", "Score": "2", "Tags": [ "c#", "beginner", "wpf", "mvvm" ], "Title": "Tic Tac Toe game using WPF+MVVM" }
255798
<p>I have a file output like this and want to do parsing and put the output into a List. The biggest problem here is the name of a wake-lock which appears after ID and runtime, in some cases, it contains spaces, &quot;:&quot; or () which made me hard to parse. Some cases also don't have runtime neither counts, instead all of that there is just word realtime. I have put my approach below, maybe it needs just a little improvement which I cannot see, or it a whole miss.</p> <pre><code>1000 ActivityManager-Sleep: 4s 493ms (0 times) max=4991 actual=4991 realtime u0a149 AudioIn: 1s 274ms (1 times) max=1274 realtime u0a138 *job*/com.android.vending/com.google.android.finsky.scheduler.process.mainimpl.PhoneskyJobServiceMain: 257ms (1 times) max=547 actual=547 realtime 1041 AudioIn: 133ms (3 times) max=126 realtime u0a136 GCoreFlp: 81ms (1 times) max=153 actual=153 realtime 1001 *telephony-radio*: 76ms (3 times) max=155 actual=157 realtime u0a188 Doze: 39ms (1 times) max=124 actual=124 realtime u0a188 Scrims: 36ms (1 times) max=115 actual=115 realtime u0a257 *job*/com.liverpool.echo/com.urbanairship.job.AndroidJobService: 32ms (1 times) max=96 actual=96 realtime 1000 startDream: 25ms (1 times) max=59 actual=59 realtime 1000 GCoreFlp: 23ms (1 times) max=84 actual=84 realtime u0a188 show keyguard: 22ms (0 times) max=48 actual=48 realtime u0a136 GCM_READ: 17ms (2 times) max=12 realtime 1000 AnyMotionDetector: 17ms (1 times) max=24 actual=24 realtime u0a145 *job*/com.google.android.apps.turbo/.nudges.broadcasts.BatteryHistoryLoggerJobService: 11ms (1 times) max=47 actual=47 realtime 1000 deviceidle_going_idle: 10ms (1 times) max=32 actual=32 realtime u0a136 NlpWakeLock: 9ms (6 times) max=11 actual=36 realtime u0a136 CMWakeLock: 8ms (1 times) max=13 actual=13 realtime 1002 bluetooth_timer: 8ms (4 times) max=8 actual=13 realtime u0a136 UlrDispSvcFastWL: 6ms (3 times) max=19 actual=23 realtime 1000 *alarm*: 6ms (1 times) max=6 realtime u0a136 *alarm*: 6ms (1 times) max=9 actual=9 realtime 1000 NlpWakeLock: 4ms (3 times) max=8 actual=13 realtime u0a136 GCM_HB_ALARM: 3ms (1 times) max=6 actual=6 realtime u0a166 GCoreFlp: 3ms (2 times) max=3 actual=6 realtime u0a145 *job*/com.google.android.apps.turbo/.deadline.library.DeadlineUpdateJobService: 3ms (1 times) max=11 actual=11 realtime u0a147 NlpWakeLock: 2ms (3 times) max=4 actual=8 realtime 1000 GnssLocationProvider: 2ms (4 times) max=4 actual=7 realtime 1000 WifiSuspend: 2ms (1 times) max=7 actual=7 realtime u0a136 *gms_scheduler*:internal: 1ms (1 times) max=5 actual=5 realtime u0a136 Wakeful StateMachine: GeofencerStateMachine: 1ms (1 times) max=2 actual=2 realtime 1027 NfcService:mRoutingWakeLock realtime </code></pre> <p>I need an Array output for each line with ID, name, runTime, timesTriggered, max, actual</p> <p>I tried to do this with split and substring, but I don't like my approach, also it won't work at some cases.</p> <pre><code> for (int k = 0; k &lt; wakelocksToParse.size(); k++) { String wakelockStat = wakelocksToParse.get(k); utils.writeFile(Data.PARTIAL_WAKELOCKS_NEW, wakelockStat, true); if (wakelockStat.lastIndexOf(&quot;:&quot;) != -1) { String UID; String wakelockName; String wakelockTime; String wakelockCount; long timeInMs = 0; UID = wakelockStat.substring(0, wakelockStat.indexOf(&quot; &quot;)); wakelockName = wakelockStat.substring(wakelockStat.indexOf(&quot; &quot;), wakelockStat.lastIndexOf(&quot;:&quot;)).trim(); if (wakelockName.length() == 0) wakelockName = &quot;unknown&quot;; wakelockTime = wakelockStat.substring(wakelockStat.lastIndexOf(&quot;:&quot;) + 2, wakelockStat.indexOf(&quot;(&quot;) - 1); String[] time = wakelockTime.replaceAll(&quot;[^0-9 ]&quot;, &quot;&quot;).split(&quot; &quot;); if (time.length == 5) { int days = utils.parseIntWithDefault(time[0], 0); int hours = utils.parseIntWithDefault(time[1], 0); int minutes = utils.parseIntWithDefault(time[2], 0); int seconds = utils.parseIntWithDefault(time[3], 0); int ms = utils.parseIntWithDefault(time[4], 0); timeInMs = (days * 86400000) + (hours * 3600000) + (minutes * 60000) + (seconds * 1000) + ms; } else if (time.length == 4) { int hours = utils.parseIntWithDefault(time[0], 0); int minutes = utils.parseIntWithDefault(time[1], 0); int seconds = utils.parseIntWithDefault(time[2], 0); int ms = utils.parseIntWithDefault(time[3], 0); timeInMs = (hours * 3600000) + (minutes * 60000) + (seconds * 1000) + ms; } else if (time.length == 3) { int minutes = utils.parseIntWithDefault(time[0], 0); int seconds = utils.parseIntWithDefault(time[1], 0); int ms = utils.parseIntWithDefault(time[2], 0); timeInMs = (minutes * 60000) + (seconds * 1000) + ms; } else if (time.length == 2) { int seconds = utils.parseIntWithDefault(time[0], 0); int ms = utils.parseIntWithDefault(time[1], 0); timeInMs = (seconds * 1000) + ms; } else if (time.length == 1) { timeInMs = utils.parseIntWithDefault(time[0], 0); } wakelockCount = wakelockStat.substring(wakelockStat.lastIndexOf(':') + 1).trim(); wakelockCount = wakelockCount.substring(wakelockCount.indexOf(&quot;(&quot;) + 1); wakelockCount = wakelockCount.substring(0, wakelockCount.indexOf(&quot; &quot;)).trim(); Log.d(&quot;aaaa&quot;, UID + &quot; &quot; + wakelockName + &quot; &quot; + timeInMs + &quot; &quot; + wakelockCount); if (timeInMs &gt;= 1000) data.add(new WakelocksData(UID, wakelockName, timeInMs, wakelockCount)); utils.writeFile(Data.PARTIAL_WAKELOCKS_OLD, UID + &quot; &quot; + wakelockName + &quot; &quot; + timeInMs + &quot; &quot; + wakelockCount, true); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T13:05:18.040", "Id": "504839", "Score": "0", "body": "Welcome to the Code Review Community where we review code that is working as expected and provide suggestions on how to improve that code. Questions about code that is not working as expected are off-topic for code review. For questions about languages Java, C, C++, etc. we need at least complete functions to review, classes or the entire program are even better. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) to learn more about the code review site." } ]
[ { "body": "<p>This was an interesting problem. I suspect the purpose of this assignment was to explore different <code>String</code> methods.</p>\n<p>The first thing I did was create a <code>LogMessage</code> class to hold the separated contents of one log message. The <code>runTime</code> value is in milliseconds.</p>\n<p>Here are the test results from one of my many, many test runs.</p>\n<pre><code>LogMessage [runTime=4493, timesTriggered=0, maxTimes=4991, actualTimes=4991, logID=1000, logName=ActivityManager-Sleep: ]\nLogMessage [runTime=1274, timesTriggered=1, maxTimes=1274, actualTimes=0, logID=u0a149, logName=AudioIn: ]\nLogMessage [runTime=257, timesTriggered=1, maxTimes=547, actualTimes=547, logID=u0a138, logName=*job*/com.android.vending/com.google.android.finsky.scheduler.process.mainimpl.PhoneskyJobServiceMain: ]\nLogMessage [runTime=133, timesTriggered=3, maxTimes=126, actualTimes=0, logID=1041, logName=AudioIn: ]\nLogMessage [runTime=81, timesTriggered=1, maxTimes=153, actualTimes=153, logID=u0a136, logName=GCoreFlp: ]\nLogMessage [runTime=76, timesTriggered=3, maxTimes=155, actualTimes=157, logID=1001, logName=*telephony-radio*: ]\nLogMessage [runTime=39, timesTriggered=1, maxTimes=124, actualTimes=124, logID=u0a188, logName=Doze: ]\nLogMessage [runTime=36, timesTriggered=1, maxTimes=115, actualTimes=115, logID=u0a188, logName=Scrims: ]\nLogMessage [runTime=32, timesTriggered=1, maxTimes=96, actualTimes=96, logID=u0a257, logName=*job*/com.liverpool.echo/com.urbanairship.job.AndroidJobService: ]\nLogMessage [runTime=25, timesTriggered=1, maxTimes=59, actualTimes=59, logID=1000, logName=startDream: ]\nLogMessage [runTime=23, timesTriggered=1, maxTimes=84, actualTimes=84, logID=1000, logName=GCoreFlp: ]\nLogMessage [runTime=22, timesTriggered=0, maxTimes=48, actualTimes=48, logID=u0a188, logName=show keyguard: ]\nLogMessage [runTime=17, timesTriggered=2, maxTimes=12, actualTimes=0, logID=u0a136, logName=GCM_READ: ]\nLogMessage [runTime=17, timesTriggered=1, maxTimes=24, actualTimes=24, logID=1000, logName=AnyMotionDetector: ]\nLogMessage [runTime=11, timesTriggered=1, maxTimes=47, actualTimes=47, logID=u0a145, logName=*job*/com.google.android.apps.turbo/.nudges.broadcasts.BatteryHistoryLoggerJobService: ]\nLogMessage [runTime=10, timesTriggered=1, maxTimes=32, actualTimes=32, logID=1000, logName=deviceidle_going_idle: ]\nLogMessage [runTime=9, timesTriggered=6, maxTimes=11, actualTimes=36, logID=u0a136, logName=NlpWakeLock: ]\nLogMessage [runTime=8, timesTriggered=1, maxTimes=13, actualTimes=13, logID=u0a136, logName=CMWakeLock: ]\nLogMessage [runTime=8, timesTriggered=4, maxTimes=8, actualTimes=13, logID=1002, logName=bluetooth_timer: ]\nLogMessage [runTime=6, timesTriggered=3, maxTimes=19, actualTimes=23, logID=u0a136, logName=UlrDispSvcFastWL: ]\nLogMessage [runTime=6, timesTriggered=1, maxTimes=6, actualTimes=0, logID=1000, logName=*alarm*: ]\nLogMessage [runTime=6, timesTriggered=1, maxTimes=9, actualTimes=9, logID=u0a136, logName=*alarm*: ]\nLogMessage [runTime=4, timesTriggered=3, maxTimes=8, actualTimes=13, logID=1000, logName=NlpWakeLock: ]\nLogMessage [runTime=3, timesTriggered=1, maxTimes=6, actualTimes=6, logID=u0a136, logName=GCM_HB_ALARM: ]\nLogMessage [runTime=3, timesTriggered=2, maxTimes=3, actualTimes=6, logID=u0a166, logName=GCoreFlp: ]\nLogMessage [runTime=3, timesTriggered=1, maxTimes=11, actualTimes=11, logID=u0a145, logName=*job*/com.google.android.apps.turbo/.deadline.library.DeadlineUpdateJobService: ]\nLogMessage [runTime=2, timesTriggered=3, maxTimes=4, actualTimes=8, logID=u0a147, logName=NlpWakeLock: ]\nLogMessage [runTime=2, timesTriggered=4, maxTimes=4, actualTimes=7, logID=1000, logName=GnssLocationProvider: ]\nLogMessage [runTime=2, timesTriggered=1, maxTimes=7, actualTimes=7, logID=1000, logName=WifiSuspend: ]\nLogMessage [runTime=1, timesTriggered=1, maxTimes=5, actualTimes=5, logID=u0a136, logName=*gms_scheduler*:internal: ]\nLogMessage [runTime=1, timesTriggered=1, maxTimes=2, actualTimes=2, logID=u0a136, logName=Wakeful StateMachine: GeofencerStateMachine: ]\nLogMessage [runTime=0, timesTriggered=0, maxTimes=0, actualTimes=0, logID=1027, logName=NfcService:mRoutingWakeLock ]\n</code></pre>\n<p>The code turned out to be rather involved. Here's a diagram of the internal method call tree.</p>\n<pre><code>main\n processLogFile\n parseLogLine\n parseLastPart\n append\n getTimesTriggered\n valueOf\n getRunTime\n valueOf\n getValue\n valueOf\n</code></pre>\n<p>Here's the complete runnable code. I put your input file in my resources folder. You can delete the lines where I get the complete path to the file.</p>\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class ProcessLogText {\n\n public static void main(String[] args) {\n ProcessLogText plt = new ProcessLogText();\n List&lt;LogMessage&gt; logMessages = plt.processLogFile(&quot;log.txt&quot;);\n \n for (LogMessage logMessage : logMessages) {\n System.out.println(logMessage);\n }\n }\n \n public List&lt;LogMessage&gt; processLogFile(String fileName) {\n List&lt;LogMessage&gt; logMessages = new ArrayList&lt;&gt;();\n \n ClassLoader classLoader = getClass().getClassLoader();\n File file = new File(classLoader.getResource(fileName).getFile());\n \n try {\n BufferedReader reader = new BufferedReader(new FileReader(file));\n String line = reader.readLine();\n \n while (line != null) {\n logMessages.add(parseLogLine(line));\n line = reader.readLine();\n }\n \n reader.close();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n \n return logMessages;\n }\n \n private LogMessage parseLogLine(String line) {\n int endIndex = line.lastIndexOf(&quot;: &quot;);\n String firstPart, lastPart;\n \n if (endIndex &gt;= 0) {\n firstPart = line.substring(0, endIndex + 2);\n lastPart = line.substring(endIndex + 2);\n } else {\n endIndex = line.lastIndexOf(&quot;realtime&quot;);\n firstPart = line.substring(0, endIndex);\n lastPart = line.substring(endIndex);\n }\n \n endIndex = firstPart.indexOf(&quot; &quot;);\n String logID = firstPart.substring(0, endIndex);\n String logName = firstPart.substring(endIndex + 1);\n \n List&lt;String&gt; parts = parseLastPart(lastPart);\n int timesTriggered = getTimesTriggered(parts);\n int runTime = getRunTime(parts);\n int maxTimes = getValue(parts, &quot;max&quot;);\n int actualTimes = getValue(parts, &quot;actual&quot;);\n \n return new LogMessage(logID, logName, runTime, \n timesTriggered, maxTimes, actualTimes);\n }\n \n private List&lt;String&gt; parseLastPart(String lastPart) {\n List&lt;String&gt; parts = new ArrayList&lt;&gt;();\n StringBuilder builder = new StringBuilder();\n boolean insideParenthesis = false;\n \n for (int i = 0; i &lt; lastPart.length(); i++) {\n char c = lastPart.charAt(i);\n if (c == '(') {\n insideParenthesis = true;\n continue;\n }\n \n if (c == ')') {\n insideParenthesis = false;\n continue;\n }\n \n if (c == ' ') {\n if (insideParenthesis) {\n builder.append(c);\n } else {\n append(parts, builder);\n }\n } else {\n builder.append(c);\n }\n }\n \n append(parts, builder);\n return parts;\n }\n \n private void append(List&lt;String&gt; parts, StringBuilder builder) {\n if (builder.length() &gt; 0) {\n parts.add(builder.toString());\n builder.delete(0, builder.length());\n }\n }\n \n private int getTimesTriggered(List&lt;String&gt; parts) {\n int timesTriggered = 0;\n \n for (int i = parts.size() - 1; i &gt;= 0; i--) {\n String s = parts.get(i);\n int endIndex = s.indexOf(&quot; times&quot;);\n if (endIndex &gt;= 0) {\n int number = valueOf(s.substring(0, endIndex));\n if (number &gt;= 0) {\n timesTriggered += number;\n }\n parts.remove(i);\n break;\n }\n }\n \n return timesTriggered;\n }\n \n private int getRunTime(List&lt;String&gt; parts) {\n int runTime = 0;\n \n for (String s : parts) {\n int endIndex = s.indexOf(&quot;ms&quot;);\n if (endIndex &gt;= 0) {\n int number = valueOf(s.substring(0, endIndex));\n if (number &gt;= 0) {\n runTime += number;\n }\n } else {\n endIndex = s.indexOf(&quot;s&quot;);\n if (endIndex &gt;= 0) {\n int number = valueOf(s.substring(0, endIndex));\n if (number &gt;= 0) {\n runTime += number * 1000;\n }\n }\n }\n }\n \n return runTime;\n }\n \n private int getValue(List&lt;String&gt; parts, String key) {\n key = key + &quot;=&quot;;\n for (String s : parts) {\n if (s.indexOf(key) == 0) {\n return Math.max(0, valueOf(s.substring(key.length())));\n }\n }\n \n return 0;\n }\n \n private int valueOf(String number) {\n try {\n return Integer.valueOf(number);\n } catch (NumberFormatException e) {\n return -1;\n }\n }\n \n public class LogMessage {\n \n private final int runTime;\n private final int timesTriggered;\n private final int maxTimes;\n private final int actualTimes;\n \n private final String logID;\n private final String logName;\n \n public LogMessage(String logID, String logName, int runTime, \n int timesTriggered, int maxTimes, int actualTimes) {\n this.logID = logID;\n this.logName = logName;\n this.runTime = runTime;\n this.timesTriggered = timesTriggered;\n this.maxTimes = maxTimes;\n this.actualTimes = actualTimes;\n }\n\n public String getLogID() {\n return logID;\n }\n\n public String getLogName() {\n return logName;\n }\n\n public int getRunTime() {\n return runTime;\n }\n\n public int getTimesTriggered() {\n return timesTriggered;\n }\n\n public int getMaxTimes() {\n return maxTimes;\n }\n\n public int getActualTimes() {\n return actualTimes;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n \n builder.append(&quot;LogMessage [runTime=&quot;);\n builder.append(runTime);\n builder.append(&quot;, timesTriggered=&quot;);\n builder.append(timesTriggered);\n builder.append(&quot;, maxTimes=&quot;);\n builder.append(maxTimes);\n builder.append(&quot;, actualTimes=&quot;);\n builder.append(actualTimes);\n builder.append(&quot;, logID=&quot;);\n builder.append(logID);\n builder.append(&quot;, logName=&quot;);\n builder.append(logName);\n builder.append(&quot;]&quot;);\n \n return builder.toString();\n }\n \n }\n\n}\n</code></pre>\n<p>So, here's what I did to parse the log message file.</p>\n<ol>\n<li><p>I split the message into two parts. The first part contains the message-id and message-name. The second part contains the remainder of the log message. I was able to split on either &quot;: &quot; or &quot;realtime&quot;. I didn't know whether the final colon was part of the message-name or not, so I left it in.</p>\n</li>\n<li><p>I split the first part on the first space and got the message-id and message-name.</p>\n</li>\n<li><p>I parsed the last part into pieces based on a space outside of the parenthesis.</p>\n</li>\n<li><p>I got the times triggered next. I did this first so I could delete the part when I finished processing it. Deleting the times triggered part made calculating the run time much easier because I could check for &quot;ms&quot; and &quot;s&quot; without getting a false &quot;s&quot; on &quot;times&quot;.</p>\n</li>\n<li><p>I calculated the run time from the parts.</p>\n</li>\n<li><p>I got the max value from the parts.</p>\n</li>\n<li><p>I got the actual value from the parts.</p>\n</li>\n</ol>\n<p>I have no idea how you might be able to do this with one or more regular expressions.</p>\n<p>By doing it this way, I was able to test each step along the way and fix any problems I found before I proceeded to the next step. Like the last log message not having a colon.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T18:12:56.167", "Id": "504991", "Score": "0", "body": "This approach looks pretty decent, tell me what do you mean by this \"I didn't know whether the final colon was part of the message-name or not, so I left it in.\"?\n\nYou mean about \": \" or realtime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T18:28:33.477", "Id": "504992", "Score": "0", "body": "Also some lines have days, hours and minutes `Wake lock 1001 *telephony-radio*: 1d 1h 4m 59s 720ms (449 times) max=113944 actual=349585 realtime`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T20:51:26.723", "Id": "505006", "Score": "0", "body": "@Danijel Markov: I didn't know whether the final colon was part of the message-name. I still don't. You didn't show those lines in your example. Feel free to modify my answer to process the file. Just remember, make changes step by step, and test each step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T23:34:06.040", "Id": "505014", "Score": "0", "body": "\": \" is not part of the name it's just a separator to divide UID (if exists) and name of it's statistics. I will adopt your code into mine and see how all works, this looks really promising. I hope there won't arrive another format of those lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T02:20:20.977", "Id": "505036", "Score": "0", "body": "I have published my final code, if you have free time to take a look, all work as it should. Thank you very much for your time and effort doing this. I had a whole different vision of parsing this, but you made it much simpler. Thing to check whole string char by char made whole thing more efficient, and I completely forgot about it. Thank you one more time. See ya" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T15:05:49.913", "Id": "255846", "ParentId": "255800", "Score": "0" } }, { "body": "<p>I want to post my final answer based on @Gilbert Le Blanc code, I have changed several things, but base is the same.</p>\n<pre><code> private void parseWakelockStat(String wakelockStat) {\n int endIndex = wakelockStat.lastIndexOf(&quot;: &quot;);\n String firstPart, lastPart;\n\n if (endIndex &gt;= 0) {\n firstPart = wakelockStat.substring(0, endIndex + 2);\n lastPart = wakelockStat.substring(endIndex + 2);\n\n } else {\n endIndex = wakelockStat.lastIndexOf(&quot;realtime&quot;);\n firstPart = wakelockStat.substring(0, endIndex);\n lastPart = wakelockStat.substring(endIndex);\n }\n\n endIndex = firstPart.indexOf(&quot; &quot;);\n\n List&lt;String&gt; parts = parseLastPart(lastPart);\n\n // UID of wakelocks (if exists, only partial wakelocks have UID)\n String UID = firstPart.substring(0, endIndex);\n\n // Wakelock name\n String wakelockName = firstPart.substring(endIndex + 1);\n\n // Runtime of wakelock\n int runTime = getRunTime(parts);\n\n // Wakelock trigger count\n int wakelockTriggerCount = getWakelockTriggerCount(parts);\n\n // Get max and actual wakelock count\n int maxTimes = getValue(parts, &quot;max&quot;);\n int actualTimes = getValue(parts, &quot;actual&quot;);\n\n wakelock = new Wakelock(UID, wakelockName, runTime, wakelockTriggerCount, maxTimes, actualTimes);\n }\n\n private List&lt;String&gt; parseLastPart(String lastPart) {\n List&lt;String&gt; parts = new ArrayList&lt;&gt;();\n StringBuilder builder = new StringBuilder();\n boolean insideParenthesis = false;\n\n for (int i = 0; i &lt; lastPart.length(); i++) {\n char c = lastPart.charAt(i);\n if (c == '(') {\n insideParenthesis = true;\n continue;\n }\n\n if (c == ')') {\n insideParenthesis = false;\n continue;\n }\n\n if (c == ' ') {\n if (insideParenthesis) {\n builder.append(c);\n } else {\n append(parts, builder);\n }\n } else {\n builder.append(c);\n }\n }\n\n append(parts, builder);\n return parts;\n }\n\n private void append(List&lt;String&gt; parts, StringBuilder builder) {\n if (builder.length() &gt; 0) {\n parts.add(builder.toString());\n builder.delete(0, builder.length());\n }\n }\n\n private int getWakelockTriggerCount(List&lt;String&gt; parts) {\n int timesTriggered = 0;\n\n for (int i = parts.size() - 1; i &gt;= 0; i--) {\n String s = parts.get(i);\n int endIndex = s.indexOf(&quot; times&quot;);\n if (endIndex &gt;= 0) {\n int number = utils.parseIntWithDefault(s.substring(0, endIndex), 0);\n if (number &gt;= 0) {\n timesTriggered += number;\n }\n parts.remove(i);\n break;\n }\n }\n\n return timesTriggered;\n }\n\n private int getRunTime(List&lt;String&gt; parts) {\n int runTime = 0;\n\n for (String part : parts) {\n if (part.endsWith(&quot;d&quot;)) {\n int time = utils.parseIntWithDefault(part.replaceAll(&quot;[^0-9 ]&quot;, &quot;&quot;), 0);\n if (time &gt;= 0)\n runTime += time * 86400000;\n\n } else if (part.endsWith(&quot;h&quot;)) {\n int time = utils.parseIntWithDefault(part.replaceAll(&quot;[^0-9 ]&quot;, &quot;&quot;), 0);\n if (time &gt;= 0)\n runTime += time * 3600000;\n\n } else if (part.endsWith(&quot;m&quot;)) {\n int time = utils.parseIntWithDefault(part.replaceAll(&quot;[^0-9 ]&quot;, &quot;&quot;), 0);\n if (time &gt;= 0)\n runTime += time * 60000;\n\n } else if (part.endsWith(&quot;s&quot;) &amp;&amp; !part.endsWith(&quot;ms&quot;)) {\n int time = utils.parseIntWithDefault(part.replaceAll(&quot;[^0-9 ]&quot;, &quot;&quot;), 0);\n if (time &gt;= 0)\n runTime += time * 1000;\n\n } else if (part.endsWith(&quot;ms&quot;)) {\n int time = utils.parseIntWithDefault(part.replaceAll(&quot;[^0-9 ]&quot;, &quot;&quot;), 0);\n if (time &gt;= 0)\n runTime += time;\n\n break;\n }\n }\n\n return runTime;\n }\n\n private int getValue(List&lt;String&gt; parts, String key) {\n key = key + &quot;=&quot;;\n for (String s : parts) {\n if (s.indexOf(key) == 0) {\n return Math.max(0, utils.parseIntWithDefault(s.substring(key.length()), 0));\n }\n }\n\n return 0;\n }\n\n public static class Wakelock {\n\n private final String UID;\n private final String wakelockName;\n private final int runTime;\n private final int wakelockTriggerCount;\n private final int maxTimes;\n private final int actualTimes;\n\n public Wakelock(String UID, String wakelockName, int runTime,\n int wakelockTriggerCount, int maxTimes, int actualTimes) {\n this.UID = UID;\n this.wakelockName = wakelockName;\n this.runTime = runTime;\n this.wakelockTriggerCount = wakelockTriggerCount;\n this.maxTimes = maxTimes;\n this.actualTimes = actualTimes;\n }\n\n private String getUID() {\n return UID;\n }\n\n private String getWakelockName() {\n String name;\n if (wakelockName.trim().length() == 0)\n name = UID.trim();\n else\n name = wakelockName.trim();\n\n // Remove : from the end of the name if exists\n return name.endsWith(&quot;:&quot;) ? name.substring(0, name.length() - 1) : name;\n }\n\n private int getRunTime() {\n return runTime;\n }\n\n private int getWakelockTriggerCount() {\n return wakelockTriggerCount;\n }\n\n private int getMaxTimes() {\n return maxTimes;\n }\n\n private int getActualTimes() {\n return actualTimes;\n }\n }\n</code></pre>\n<ul>\n<li>The first thing I've done is removing &quot;:&quot; from the end of a wakelock name.</li>\n<li>Managed getRunTime(), I have to parse also days, minutes, hours insted of just seconds and ms, my example hadn't it. Also applied break the loop when part ends with ms, to avoid checking next parts. They are not needed.</li>\n</ul>\n<p>And this is how I call whole function</p>\n<pre><code>for (int k = 0; k &lt; wakelocksToParse.size(); k++) {\n String wakelockStat = wakelocksToParse.get(k);\n\n utils.writeFile(Data.KERNEL_WAKELOCKS_OLD, wakelockStat, true);\n\n parseWakelockStat(wakelockStat);\n\n utils.writeFile(Data.KERNEL_WAKELOCKS_NEW, wakelock.getUID() + &quot; &quot; + wakelock.getWakelockName()\n + &quot; &quot; + wakelock.getRunTime() + &quot; &quot; +\n wakelock.getWakelockTriggerCount() + &quot; &quot; + wakelock.getMaxTimes() + &quot; &quot; + wakelock.getActualTimes(), true);\n \n data.add(new WakelocksData(wakelock.getUID(), wakelock.getWakelockName(), wakelock.getRunTime(), wakelock.getWakelockTriggerCount()));\n }\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-11T02:17:54.460", "Id": "255869", "ParentId": "255800", "Score": "0" } } ]
{ "AcceptedAnswerId": "255846", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-09T12:01:52.813", "Id": "255800", "Score": "0", "Tags": [ "java", "parsing", "regex" ], "Title": "Parse file and make output in custom List" }
255800