body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I posted <a href="https://stackoverflow.com/a/59510478/10147399">this</a> answer recently. OP in the StackOverflow question mentioned that it was for educational use, but I can imagine it being used as a debugging aid. Then I decided to improve it slightly and make it a compile-time function. Code:</p> <pre><code>#include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;string_view&gt; #include &lt;type_traits&gt; #include &lt;vector&gt; #ifndef __GNUC__ static_assert(false, "GCC specific"); #endif // !__GNUC__ // Finds a character in a nul terminated string. // Returns the last character if sought one isn't found. // Notes: // 1. Using this because std::strchr isn't constexpr. // `PChr` is a separate typename instead of just using Chr* to allow `Chr*` and // `Chr const*` as the pointer. // 2. pstr shall not be nullptr. template &lt;typename PChr, typename Chr&gt; [[gnu::pure, gnu::nonnull, gnu::returns_nonnull, nodiscard]] static constexpr auto* constexpr_strchr(PChr pstr, Chr const value) noexcept { // PChr must be a raw pointer type because of gnu::nonnull and // gnu::returns_nonnull static_assert(std::is_pointer_v&lt;PChr&gt;, "PChr must be a raw pointer type"); auto constexpr nul = Chr{}; while (*pstr != value &amp;&amp; *pstr != nul) { ++pstr; } return pstr; } // Returns distance from ptr to the end of the array. // Notes: // 1. ptr shall not be nullptr // 2. ptr shall be inside the array (arr) template &lt;typename T, auto size&gt; [[gnu::const, gnu::artificial, gnu::nonnull, gnu::always_inline, nodiscard]] inline static constexpr auto distance_to_end(const T (&amp;arr)[size], T const* const ptr) noexcept { return arr + size - ptr; } // Returns type T as a string_view. // Ex: std::string -&gt; "std::string" template &lt;typename T&gt; [[gnu::const, nodiscard]] static constexpr auto type_name_finder() noexcept { // __PRETTY_FUNCTION__ means "$FUNCTION_SIGNATURE [with T = $TYPE]". // +2 here to skip "= " auto const* const begin = constexpr_strchr(__PRETTY_FUNCTION__, '=') + 2; // -2 meaning up to "]\0" auto const size = static_cast&lt;std::size_t&gt;(distance_to_end(__PRETTY_FUNCTION__, begin) - 2); return std::string_view{begin, size}; } // Inline string_view with the type name. template &lt;typename T&gt; inline constexpr auto type_name = type_name_finder&lt;T&gt;(); // Example Class template &lt;typename T1, typename T2&gt; class my_class {}; int main() { // Example use-case my_class&lt;int&amp;, std::vector&lt;double&gt;&gt; my_arr[20]; std::cout &lt;&lt; type_name&lt;decltype(my_arr)&gt;; } </code></pre> <p>Code uses <code>__PRETTY_FUNCTION__</code> in GCC and Clang to get a variable's type as a string. I would appreciate any comments on correctness and readability. I used a lot of GCC specific attributes, because <code>__PRETTY_FUNCTION__</code> is GCC specific and for this reason the code can't be portable anyway. </p>
[]
[ { "body": "<pre><code> // __PRETTY_FUNCTION__ means \"$FUNCTION_SIGNATURE [with T = $TYPE]\".\n</code></pre>\n\n<p>When you call <code>type_name_finder()</code>, the only part that changes in <code>__PRETTY_FUNCTION__</code> is <code>$TYPE</code>. We can use this information to strip the static decoration surrounding that type.</p>\n\n<pre><code>template &lt;typename T&gt;\nstatic constexpr auto type_name_finder() {\n std::string_view name, prefix, suffix;\n\n#if defined(__clang__)\n name = __PRETTY_FUNCTION__;\n prefix = \"auto type_name_finder() [T = \";\n suffix = \"]\";\n#elif defined(__GNUC__)\n name = __PRETTY_FUNCTION__;\n prefix = \"constexpr auto type_name_finder() [with T = \";\n suffix = \"]\";\n#endif\n\n name.remove_prefix(prefix.size());\n name.remove_suffix(suffix.size());\n return name;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T08:16:50.790", "Id": "459201", "Score": "0", "body": "MSVC version won't work properly because for built in types `auto __cdecl type_name_finder<class` does not have the \"class\" word." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T08:17:58.737", "Id": "459202", "Score": "0", "body": "`std::string_view::remove_prefix` is not `noexcept`. I don't think it's very appropriate to mark `type_name_finder` not-throwing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T08:18:41.477", "Id": "459203", "Score": "0", "body": "Besides that, your implementation is great (+1). Thanks for this much improved version!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T09:46:29.017", "Id": "459206", "Score": "0", "body": "And what if the actual prefix or suffix isn't the one you expect? To me it looks like undefined behavior then." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T07:59:36.547", "Id": "234779", "ParentId": "234735", "Score": "4" } }, { "body": "<p>You're trying to reinvent the wheel... This specific challenge was discussed in answers to <a href=\"https://stackoverflow.com/q/81870/1593077\">this SO question</a>: Read <a href=\"https://stackoverflow.com/a/20170989/1593077\">HowardHinnant's long answer</a>, then read the final, pretty, <code>constexpr</code> answer <a href=\"https://stackoverflow.com/a/56766138/1593077\">here</a>. @Snowhawk quoted the code there - now you have some references and the build-up to the final form of the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T15:40:22.823", "Id": "467725", "Score": "0", "body": "I should have looked around before spending time on this thing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:36:51.050", "Id": "237216", "ParentId": "234735", "Score": "2" } } ]
{ "AcceptedAnswerId": "237216", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T13:17:52.207", "Id": "234735", "Score": "4", "Tags": [ "c++" ], "Title": "Type name as a string" }
234735
<p>This is <a href="https://www.hackerrank.com/challenges/frequency-queries/problem" rel="noreferrer">the problem</a>:</p> <blockquote> <p>You are given queries. Each query is of the form two integers described below:</p> <ul> <li>1 <strong><em>x</em></strong>: Insert x in your data structure. </li> <li>2 <strong><em>y</em></strong>: Delete one occurrence of y from your data structure, if present. </li> <li>3 <strong><em>z</em></strong>: Check if any integer is present whose frequency is exactly <em>z</em>. If yes, print 1 else 0.</li> </ul> <p>The queries are given in the form of a 2-D array <em>queries</em> of size <em>q</em> where <code>queries[i][0]</code> contains the operation, and <code>queries[i][1]</code> contains the data element. For example, you are given array <code>queries = [[1,1],[2,2],[3,2],[1,1],[1,1],[2,1],[3,2]]</code><br> … </p> <p>Return an array with the output=[0,1].</p> </blockquote> <p>I am getting a "Time Limit Exceeded" error on only one Test Case. How can I optimize and improve my code?</p> <p>Here is my code in JavaScript:</p> <pre><code>function freqQuery(queries) { const resultArray = [] const frequencyArray = []; for(let i=0 ; i&lt;queries.length ; i++){ const arr = queries[i] if(arr[0]== 1){ frequencyArray[arr[1]] = (frequencyArray[arr[1]] || 0) + 1 } else if(arr[0] == 2){ if(frequencyArray[arr[1]]){ frequencyArray[arr[1]] = frequencyArray[arr[1]] -1; } } else if(arr[0] == 3){ resultArray.push(frequencyArray.includes(arr[1]) ? 1 : 0 ); } } return resultArray; } </code></pre>
[]
[ { "body": "<p>There's a few general code hygiene things that I'll look at first, and then I'll comment on the algorithm design. </p>\n\n<p>First, <code>const</code> should mean constant. I know that in Javascript you don't get in trouble for changing the contents of a <code>const</code> array but it's still confusing to use it with a variable whose job is to change. <code>const arr</code> I like but <code>const resultArray</code> I don't.</p>\n\n<p>Second, although I appreciate that these practice challenges don't always give a huge amount of context to inform your purpose, it's important to think about variable names. In particular, <code>arr</code> is a very vague name at the best of times, and a moderately misinforming one in this context. I'd go for something like \"instruction\".</p>\n\n<p>Third, three if statements checking the same expression for fixed values just screams \"use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch\" rel=\"nofollow noreferrer\">switch statement</a>\". Efficiency questions notwithstanding, <code>switch</code> will immediately clue anyone reading the code into there being one value to check against several options. (Whereas with long <code>else if</code> chains we have to focus on each condition because they could be different)</p>\n\n<p>Fourth, avoid this little trick: <code>if(frequencyArray[arr[1]])</code>. Yes, Javascript will silently do all sorts of funky conversions, and this old implicit cast bool seems tame in comparison. But those conversions are hard to read and bug prone. If you want to check first whether it exists and then whether it is positive, check first whether it exists and then whether it is positive. </p>\n\n<p>Fifth, tiny style thing, but consistency is often more important than what decision you come to. So with Javascript, you can leave off semicolons, or you can add them in. Either works. Some people insist one way or the other, and I won't do that. But if you do use them, use them. As is, 4 statements end with semicolons and 3 end without semicolons, with nothing to tell them apart. </p>\n\n<p>As to the algorithm efficiency, you're making good use of the fact that Javascript \"arrays\" are dictionaries, so you can directly refer to <code>frequencyArray[arr[1]]</code> without having to worry about whether <code>arr[1]</code> being enormous. With that direct value lookup, your cases for <code>1</code> and <code>2</code> both consist of very quick operations. Case <code>3</code> is the one that will take time, even though it looks just as simple as the others. It's the <code>includes</code> function that's killing you. While the other cases just check one value in the array, <code>includes</code> has to check every single value. What you'll want to do is remember your frequency count as you go, taking a bit of extra time in your <code>1</code> and <code>2</code> cases to update an additional array/dictionary, so that in your <code>3</code> case you can just look up that already calculated value and output it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T18:42:46.893", "Id": "459160", "Score": "2", "body": "I disagree with your both your first and fourth points. I understand that using `const` for a mutating data structure sounds weird, but it's correct and appropriate usage of the language keyword. In the case of implicit casts, I agree that one should be careful with them, but `if(value){then_action;}` is certainly idiomatic for javascript (and not equivalent to \"exists and is positive\")." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T16:04:05.203", "Id": "234743", "ParentId": "234741", "Score": "4" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/234743/200133\">Josiah's answer</a> covers most stuff pretty well. The only additional suggestion I have is an alternative to a switch statement: a lookup table of actions.</p>\n\n<p>Something like:</p>\n\n<pre><code>const query_types = {\n 1: (x)=&gt;{\n frequencyArray[arr[1]] = (frequencyArray[arr[1]] || 0) + 1;\n },\n 2: (y)=&gt;{\n ...\n },\n 3: (z)=&gt;{\n ...\n }\n};\n\nfor(let i=0 ; i&lt;queries.length ; i++){ \n query_types[queries[i][0]](queries[i][1]);\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T18:51:56.903", "Id": "234750", "ParentId": "234741", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T15:24:23.293", "Id": "234741", "Score": "5", "Tags": [ "javascript", "performance", "programming-challenge", "time-limit-exceeded", "ecmascript-6" ], "Title": "Frequency Queries (Hackerrank)" }
234741
<p>I was playing around with Unity's new Entity Component System and I was trying to implement a rotator system. This is what I came up with:</p> <p>Component Data:</p> <pre><code>using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Jobs; using Unity.Mathematics; using Unity.Transforms; [GenerateAuthoringComponent] public struct RotatorComponent : IComponentData { public float3 radiansPerSecond; } </code></pre> <p>System:</p> <pre><code>using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Jobs; using Unity.Mathematics; using Unity.Transforms; public class RotatorSystem : JobComponentSystem { [BurstCompile] struct RotateJob : IJobForEach&lt;Rotation, RotatorComponent&gt; { public float DeltaTime; public void Execute(ref Rotation rotation, ref RotatorComponent rotator) { float3 rotationThisFrame = DeltaTime * rotator.radiansPerSecond; quaternion x = quaternion.AxisAngle(new float3(1.0f, 0.0f, 0.0f), rotationThisFrame.x); quaternion y = quaternion.AxisAngle(new float3(0.0f, 1.0f, 0.0f), rotationThisFrame.y); quaternion z = quaternion.AxisAngle(new float3(0.0f, 0.0f, 1.0f), rotationThisFrame.z); rotation.Value = math.mul(x, rotation.Value); rotation.Value = math.mul(y, rotation.Value); rotation.Value = math.mul(z, rotation.Value); } } protected override JobHandle OnUpdate(JobHandle inputDeps) { return new RotateJob { DeltaTime = Time.DeltaTime }.Schedule(this, inputDeps); } } </code></pre> <p>However, I think that the code shown in the system is not verry efficient. I am verry new to the new ECS stuff and I never did something with the new <em>Unity.Mathematics</em>. It would be nice if someone could show me whether the code shown in the system can be improved and if so how this would be possible.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T15:26:50.363", "Id": "234742", "Score": "2", "Tags": [ "c#", "unity3d" ], "Title": "Unity rotator script" }
234742
<p>I've written code that deletes a "post" the user has sent with my Android app. A "post" is made of an image (stored in Firestorage) named <strong>A</strong>, of a Firestore document named <strong>B</strong> which is the user UID (this document contains a field that is the sum of all the posts' number of likes), and of another Firestore document named <strong>C</strong> which is the post that is going to be deleted.</p> <p>So, if a user deleted a post:</p> <ol> <li><strong>A</strong> must be deleted</li> <li>AND <strong>B</strong> must be updated (by decreasing the number of likes of the user by the number of likes of the post that is going to be deleted)</li> <li>AND <strong>C</strong> must be deleted</li> </ol> <p>If at least one of these changes can't complete, nothing must be deleted or updated and an error or an exception must be thrown to the Android app.</p> <p><strong>Problem:</strong> you would think it'd be very simple; I would have to simply use a batch write, put these 3 operations in it and then commit the batch. However... <strong>A</strong> is a Firestorage document, not a Firestore document, while <strong>B</strong> and <strong>C</strong> are Firestore documents. <strong>Thus, it's simply technically <em>impossible</em> to do that.</strong></p> <h1>Question</h1> <p>I would want to know if the workaround I've found is correct or not, and if there is a way to correct it or improve it.</p> <p>I would also want to know if the exceptions mechanism I use is correct (these exceptions are thrown if the client doesn't send values that are expected by the Cloud Functions script, or if the post could not be deleted): will my Android app be able to handle these exceptions and is it the way to do it? In other words: should I throw exceptions or return values likes <code>-1</code>, <code>-2</code> (i.e.: error codes) for example?</p> <h1>The code</h1> <pre><code>exports.deletePost = functions.https.onCall((data, context) =&gt; { if(!context.auth) { throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.'); } if(data.the_post === null || data.the_post === '') { throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an adequat post.'); } if(data.stored_image_name === null || data.stored_image_name === '') { throw new functions.https.HttpsError('invalid-argument', 'The function must be called with an adequat post.'); } const the_post = data.the_post; const deleteDbEntry = admin_firestore.collection('list_of_slots').doc(the_post); const promise = deleteDbEntry.get().then(function(doc) { const stored_image_name = data.stored_image_name; const filePath = context.auth.uid + '/posts/' + stored_image_name; const batch = admin.firestore().batch(); batch.delete(deleteDbEntry); if(doc.data().number_of_likes &gt; 0) { const updateUserLikes = admin_firestore.collection("users").doc(context.auth.uid); batch.update(updateUserLikes, "likes", FieldValue.increment(-doc.data().number_of_likes)); } const batch_commit = batch.commit(); const deleteFile = storage.bucket('andr0d-XYZ-fXXXX.appspot.com').file(filePath).delete(); return Promise.all([deleteFile, batch_commit]).then(function() { return 1; }).catch(function(error) { console.log(error); throw new functions.https.HttpsError('unknown', 'Unable to delete the post. (2)'); }); }).catch(function(error) { console.log(error); throw new functions.https.HttpsError('unknown', 'Unable to delete the post. (1)'); }); return promise; }); </code></pre>
[]
[ { "body": "<p>I must admit that I haven't really used firebase or done any android development and thus cannot answer your questions about the correctness of the code. I did wonder if using a <a href=\"https://firebase.google.com/docs/firestore/manage-data/transactions\" rel=\"nofollow noreferrer\">transaction</a> would help satisfy the need to prevent deletion of items if other items cannot be deleted, but maybe the batch handles that... Maybe the process to delete the file (i.e. <code>deleteFile</code>) should be added to <code>batch</code>, although maybe that not possible because it is the firestorage document.</p>\n\n<h2>Good things</h2>\n\n<p>The code makes good use of <code>const</code> for values that don't get re-assigned.</p>\n\n<p>Indentation is consistent and helps readability of the code.</p>\n\n<p>Functions aren't overly long.</p>\n\n<p>There aren't many indentation levels because the first function will exit early in an error state.</p>\n\n<h2>Suggestions</h2>\n\n<p>I don't see any comments. The code does seem mostly explanatory as it is but it would be helpful to have some insights about the code - at least function parameter types, return types, etc. Over time it might become difficult to remember why you may have done something a certain way.</p>\n\n<p>Many variables are declared and then only used once. There is little point in doing this. Many of those variables can be eliminated - e.g. <code>the_post</code>, <code>promise</code>, <code>stored_image_name</code>, <code>filePath</code>, <code>updateUserLikes</code>. </p>\n\n<p>The variable name <code>deleteDbEntry</code> could be confusing to other readers of your code. A more appropriate name might be <code>dbEntryToDelete</code>.</p>\n\n<p>The lambda function passed to <code>.then()</code> of <code>Promise.all()</code> could be simplified to an arrow function - e.g. </p>\n\n<pre><code>return Promise.all([deleteFile, batch_commit]).then(_ =&gt; 1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T01:00:01.570", "Id": "235049", "ParentId": "234744", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T16:39:03.827", "Id": "234744", "Score": "5", "Tags": [ "android", "asynchronous", "promise", "firebase", "google-cloud-platform" ], "Title": "Cloud Function: Deleting from both Firestorage and Firestore in a kind of \"batch\"" }
234744
<p>I must access the elements of an object array very often by an identifier id, i.e.</p> <pre><code>[ {id:1, value:“test“, cat:2}, {id:2, value:“test“, cat:2}, {id:3, value:“test“, cat:2}, ... ] </code></pre> <p>To do so I use find, for example to fetch the value of object with id 3:</p> <pre><code> SomeVal = myArray.find(x =&gt; x.id === 3).value </code></pre> <p>However, as I would never change the initial array after creation, and as the id of each item is well defined (I fetch the objects from my sql db), I was thinking to use the array index as identifier. I would use splice to create such array initially and I would start with id 1. I have around 5k objects.</p> <p>This way I must not use find, but instead could access the array by the index directly:</p> <pre><code> SomeVal = myArray[3].value </code></pre> <p>As my id starts with 1, the array would be of same size in the end.</p> <p>I would think that’s an enormous performance boost, yet I have never seen anyone going such an approach when accessing elements by an identifier. What do you think?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T19:13:17.097", "Id": "459161", "Score": "0", "body": "Any example/real world scenario where you feel this approach is applicable or can be used? The above example is very specific one where all the conditions match" } ]
[ { "body": "<p>Your implementation is basically a <code>Map</code> or <code>Object</code> that revolves around a very specific rule. That rule being the id directly correlates to the index in the array. The advantage an <code>Array</code> has over other data structures, with superior search speeds, is the fact that they are ordered. If order doesn't matter and you're purely using it to leverage search, <code>Set</code>s and <code>Map</code>s do a better job</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T04:08:02.417", "Id": "234772", "ParentId": "234745", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T16:55:57.863", "Id": "234745", "Score": "2", "Tags": [ "javascript", "typescript" ], "Title": "Object array with identifier: use index to quickly access elements by id?" }
234745
<p>I made this anti SQL Injection, I tested if I can still send queries, and it is looks good. could you tell me if you see any problem I missed, before I launch this to the internet? (this is contact us form, no log in)</p> <pre><code>&lt;?php if(isset($_POST['submit'])) { $name = $_POST['username']; $email = $_POST['email']; $text = $_POST['textt']; $connection = mysqli_connect('localhost', 'root', '', 'database1'); if($name &amp;&amp; $email &amp;&amp; $text ) { echo "thanks you for contacting us, we will respond within 24 hours."; } else { echo "Please enter name, email and your message."; // echo $result; } $name = mysqli_real_escape_string($connection, $name); $email = mysqli_real_escape_string($connection, $email); $text = mysqli_real_escape_string($connection, $text); $query = "INSERT INTO info(username,email,textt) "; $query .= "VALUES ('$name', '$email', '$text')"; mysqli_query($connection, $query); } ?&gt; </code></pre>
[]
[ { "body": "<p>For security, bind user supplied values when including them in a query.</p>\n\n<p>Here's what that could look like using mysqli and the information provided\n<a href=\"https://www.php.net/manual/en/mysqli-stmt.bind-param.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/mysqli-stmt.bind-param.php</a></p>\n\n<pre><code>// renamed `textt` to `text`\n$stmt = $mysqli-&gt;prepare('INSERT INTO `info` (`username`,`email`,`text`) VALUES (?,?,?);');\n$stmt-&gt;bind_param($username, $email, $text);\n$stmt-&gt;execute();\n$stmt-&gt;close();\n</code></pre>\n\n<p>Here's what that would look like using PDO, should that connection be considered.\n<a href=\"https://www.php.net/manual/en/pdostatement.bindparam.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/pdostatement.bindparam.php</a></p>\n\n<p>Perhaps consider renaming your column <code>textt</code> to something more descriptive?</p>\n\n<p>Also, normally, you'd want to provide some validation on user supplied input to prevent bots and help prevent user error.</p>\n\n<p>e.g. for the email address:</p>\n\n<pre><code>if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {\n $email = $_POST['email'];\n} else {\n // often handled with a message or alert funciton\n echo 'Please enter a valid email';\n $error = true;\n}\n</code></pre>\n\n<p>e.g. for the username:</p>\n\n<pre><code>if(!ctype_space($_POST['username'])) {\n $username = trim($_POST['username']);\n} else {\n // as before often handled by a message/alert function\n echo 'Please provide a valid email address';\n $error = true;\n}\n</code></pre>\n\n<p>It's often helpful to store the IP address of the requester. The following can be spoofed, and there are better functions out there, but it is often better than nothing.</p>\n\n<pre><code>$ip_address = $_SERVER['REMOTE_ADDR'];\n</code></pre>\n\n<p>There are solutions to help ensure it's not a bot completing your form, e.g. reCAPTCHA and honey pots. They're not always appropriate from a UX, UI, security standpoint, but I feel that should be mentioned as well. </p>\n\n<p>I hope this was helpful!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T07:27:59.563", "Id": "459200", "Score": "0", "body": "`trim()` the username before testing its length, not after." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T15:25:57.897", "Id": "459218", "Score": "0", "body": "We'd be better off checking for all whitespace if you want to get technical, updated. And the username suggests a name is already in the database, which could be checked. Or have a format that could be checked with regex. But then again wouldnt they be authenticated by then anyways." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T00:47:45.667", "Id": "234769", "ParentId": "234746", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T17:29:10.510", "Id": "234746", "Score": "3", "Tags": [ "php" ], "Title": "(php , mysql) Contact us form mysql injection" }
234746
<p>I wrote a simple application that uses some weather api. It has got 2 options. It can fetch current forecast or it can fetch forecast for some days ahead.</p> <p>I have used <code>ObjectMapper</code> to map <code>HttpResponse&lt;JsonNode&gt;</code> to my customized model objects. I have been struggled with improving method that creates query for given host as only city is mandatory field, but if other fields (for example lang, units) will exist then they should be considered. </p> <p>Service: </p> <pre><code>package weatherapp; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.springframework.stereotype.Service; import weatherapp.model.currentforecastmodel.CurrentForecast; import weatherapp.model.futureforecastmodel.FutureForecast; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @Service public class ForecastService { private static final String X_RAPID_HOST = "community-open-weather-map.p.rapidapi.com"; private static final String X_RAPID_API_KEY = "..."; private static final String CHARSET = "UTF-8"; private static final String CURRENT_FORECAST_HOST = "https://community-open-weather-map.p.rapidapi.com/weather"; private static final String FORECAST_FOR_DAYS_AHEAD_HOST = "https://community-open-weather-map.p.rapidapi.com/forecast/daily"; private static final String NUMBER_OF_DAYS_AHEAD_QUERY = "cnt=%s"; private static final String CITY_QUERY = "q=%s"; private static final String LANGUAGE_AND_CITY_QUERY = "lang=%s&amp;q=%s"; private static final String UNITS_AND_CITY_QUERY = "units=%s&amp;q=%s"; public CurrentForecast getCurrentForecast(String city, String lang, String units) throws UnirestException, IOException { HttpResponse&lt;JsonNode&gt; response = getJsonResponseFromUrl(city, lang, units, null, CURRENT_FORECAST_HOST); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper.readValue(response.getBody().toString(), CurrentForecast.class); } public FutureForecast getForecastForDaysAhead(String city, String language, String units, Integer numberOfDaysAhead) throws UnirestException, IOException { HttpResponse&lt;JsonNode&gt; response = getJsonResponseFromUrl(city, language, units, numberOfDaysAhead, FORECAST_FOR_DAYS_AHEAD_HOST); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); return objectMapper.readValue(response.getBody().toString(), FutureForecast.class); } private HttpResponse&lt;JsonNode&gt; getJsonResponseFromUrl(String city, String language, String units, Integer numberOfDaysForFutureForecast, String hostUrl) throws IOException, UnirestException { String query = getQueryAccordingToGivenParameters(city, language, units, numberOfDaysForFutureForecast); return Unirest.get(hostUrl + "?" + query) .header("x-rapidapi-host", X_RAPID_HOST) .header("x-rapidapi-key", X_RAPID_API_KEY) .asJson(); } private String getQueryAccordingToGivenParameters(String city, String language, String units, Integer numberOfDaysAhead) throws UnsupportedEncodingException { String query; if (language == null &amp;&amp; units != null) { query = String.format(UNITS_AND_CITY_QUERY, URLEncoder.encode(units, CHARSET), URLEncoder.encode(city, CHARSET)); } else if (language != null &amp;&amp; units == null) { query = String.format(LANGUAGE_AND_CITY_QUERY, URLEncoder.encode(language, CHARSET), URLEncoder.encode(city, CHARSET)); } else { query = String.format(CITY_QUERY, URLEncoder.encode(city, CHARSET)); } //only for days ahead if (numberOfDaysAhead != null) { String newQuery = String.format(NUMBER_OF_DAYS_AHEAD_QUERY, URLEncoder.encode(String.valueOf(numberOfDaysAhead), CHARSET)); return new StringBuilder(query).insert(0, newQuery).toString(); } return query; } } </code></pre> <p>Controller:</p> <pre><code>package weatherapp.controller; import com.mashape.unirest.http.exceptions.UnirestException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import weatherapp.ForecastService; import weatherapp.model.currentforecastmodel.CurrentForecast; import weatherapp.model.futureforecastmodel.FutureForecast; import java.io.IOException; @RestController public class ForecastController { private final ForecastService forecastService; @Autowired public ForecastController(ForecastService forecastService) { this.forecastService = forecastService; } @GetMapping("/forecast") public CurrentForecast getCurrentWeather(@RequestParam String city, @RequestParam(required = false) String lang, @RequestParam(required = false) String units) throws UnirestException, IOException { return forecastService.getCurrentForecast(city, lang, units); } @GetMapping("/future/forecast") public FutureForecast getForecastForDays(@RequestParam String city, @RequestParam(required = false) String lang, @RequestParam(required = false) String units, @RequestParam(required = false) Integer numberOfDaysAhead) throws UnirestException, IOException { return forecastService.getForecastForDaysAhead(city, lang, units, numberOfDaysAhead); } } </code></pre> <p>Model classes are in my gh repository: <a href="https://github.com/must1/test" rel="nofollow noreferrer">https://github.com/must1/test</a></p> <p>Thanks!</p>
[]
[ { "body": "<p>so basically what you have is a set of key-value pairs (query param name and value) where the value may be specified or not and the end result is a String concatenation of the pairs.</p>\n\n<p>this is a classic case for <code>Map&lt;String, String&gt;</code></p>\n\n<p>I would convert of all the <code>_QUERY</code> constants to have the names of the query params, then I would populate the map with the (possibly null) arguments:</p>\n\n<pre><code>private static final String NUMBER_OF_DAYS_AHEAD_QUERY = \"cnt\";\nprivate static final String CITY_QUERY = \"q\";\n...\n\nprivate Map&lt;String, String&gt; queryMap = new HashMap&lt;&gt;();\n\nprivate void initQueryMap(String city, String language, String units, Integer numberOfDaysAhead) {\n queryMap.put(CITY_QUERY, city);\n queryMap.put(NUMBER_OF_DAYS_AHEAD_QUERY, String.valueOf(numberOfDaysAhead));\n ...\n}\n</code></pre>\n\n<p>now it is a simple matter of iterating over the map entries, filtering non-null values and producing the \"key=value\" string pattern. it is easily achievable with stream processing. I will leave that to you.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Here's how to create a query string from the map:</p>\n\n<pre><code> String queryStr = queryMap.entrySet().stream()\n .filter(ent -&gt; ent.getValue() != null)\n .map(ent -&gt; ent.getKey() + \"=\" + ent.getValue())\n .collect(Collectors.joining(\"&amp;\"));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T18:42:25.577", "Id": "459348", "Score": "0", "body": "I have made it like this: https://pastebin.com/AgizaF6g Good?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T06:57:44.057", "Id": "459399", "Score": "0", "body": "it can be done with stream processing with greater ease and clarity" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T08:30:21.763", "Id": "234814", "ParentId": "234748", "Score": "1" } } ]
{ "AcceptedAnswerId": "234814", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T17:39:54.120", "Id": "234748", "Score": "3", "Tags": [ "java" ], "Title": "Forecast fetcher" }
234748
<p>here's my code for moving a square on a canvas. Basicly I'm creating this thinking of some simple simulations or maybe a simple game. Would love some feedback how to optimize the 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>const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); class Map { constructor (x, y,) { this.width = x; this.height = y; } } // NPCs / PLAYER class Square { constructor(hp, dmg, speed, step) { // Combat stats this.hp = hp; this.dmg = dmg; this.speed = speed; this.step = step; // Init stats this.size = 10; this.color = 'black'; this.pos = [0,0]; this.step = 2; } } class Player extends Square { constructor() { super(); this.speed = 50; // The higher the slower the player this.pos = [250, 250]; this.step = 5; } } let player; function drawPlayer() { ctx.fillStyle = player.color; ctx.fillRect(player.pos[0], player.pos[1], player.size, player.size); } function createSquare() { const square = new Square(100, 15, 20); ctx.fillStyle = square.color; ctx.fillRect(square.pos[0], square.pos[1], square.size, square.size); } function initPlayer() { player = new Player(100, 15, 1, 5); ctx.fillStyle = player.color; ctx.fillRect(player.pos[0], player.pos[1], player.size, player.size); } // MOVEMENT function startMov() { initPlayer(); movePlayer(); } function moveUp(step) { ctx.clearRect(0,0, 500, 500); player.pos[1] -= step; drawPlayer(); } function moveLeft(step) { ctx.clearRect(0,0, 500, 500); player.pos[0] -= step; drawPlayer(); } function moveDown(step) { ctx.clearRect(0,0, 500, 500); player.pos[1] += step; drawPlayer(); } function moveRight(step) { ctx.clearRect(0,0, 500, 500); player.pos[0] += step; drawPlayer(); } let keyState = new Array(); function movePlayer() { console.log('start') checkIfStringInTable('a', keyState) ? moveLeft(player.step) : false; checkIfStringInTable('d', keyState) ? moveRight(player.step) : false; checkIfStringInTable('w', keyState) ? moveUp(player.step) : false; checkIfStringInTable('s', keyState) ? moveDown(player.step) : false; setTimeout(movePlayer,player.speed); } // Add keys to state window.addEventListener('keydown', e =&gt; { addKeyToState(e.key); }) // Remove keys from state window.addEventListener('keyup', e =&gt; { removeKeyFromState(e.key); }) function addKeyToState(key) { if((key == 'w' || key == 'a' || key == 's' || key == 'd') &amp;&amp; !checkIfStringInTable(key,keyState)) { keyState.push(key) } else false; } function removeKeyFromState(key) { keyState = keyState.filter(e =&gt; e !== key) } function checkIfStringInTable(string, table) { if(table.indexOf(string) &gt; -1) { return true; } else false; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;button onclick="createSquare()"&gt;Click&lt;/button&gt; &lt;button onclick="startMov()"&gt;Click 2&lt;/button&gt; &lt;div class="main"&gt; &lt;canvas class="canvas" id="canvas" width="500" height="500"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>To start press Click 2, I also suggest using SO's fullscreen mode for testing.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T18:23:28.823", "Id": "234749", "Score": "1", "Tags": [ "javascript", "canvas" ], "Title": "Moving square on a canvas" }
234749
<p>I want to create a backend for a simple REST API in OCaml. For this I use the libs <strong>httpaf</strong> and <strong>yojson</strong>. I have something that works but I would like some reviews.</p> <p>Here is the structure of my little server:</p> <pre><code>bin/ | - backend.ml | - lib.ml | - dune </code></pre> <ul> <li>dune:</li> </ul> <pre><code>(executable (name backend) (libraries httpaf httpaf-lwt-unix base stdio lwt lwt.unix yojson) ) </code></pre> <ul> <li>backend.ml</li> </ul> <pre class="lang-ml prettyprint-override"><code>open Base open Lwt.Infix open Httpaf_lwt_unix module String = Caml.String module Arg = Caml.Arg let request_handler (_: Unix.sockaddr) = Lib.request_handler let error_handler (_ : Unix.sockaddr) = Lib.error_handler let main port = let listen_address = Unix.(ADDR_INET (inet_addr_loopback, port)) in Lwt.async (fun () -&gt; Lwt_io.establish_server_with_client_socket listen_address (Server.create_connection_handler ~request_handler ~error_handler) &gt;|= fun _server -&gt; Stdio.printf "Starting server and listening at http://localhost:%d\n\n%!" port); let forever, _ = Lwt.wait () in Lwt_main.run forever let () = let port = ref 8080 in Arg.parse ["-p", Arg.Set_int port, " Listening port number (8080 by default)"] ignore "Echoes POST requests. Runs forever."; main !port </code></pre> <ul> <li>lib.ml</li> </ul> <pre class="lang-ml prettyprint-override"><code>open Httpaf open Base module String = Caml.String let invalid_request reqd status body = let headers = Headers.of_list [ "Connection", "close" ] in Reqd.respond_with_string reqd (Response.create ~headers status) body let request_handler reqd = let { Request.meth; target; headers; _ } = Reqd.request reqd in let build_headers response_body = Headers.of_list [ "Content-length", Int.to_string (String.length response_body); "Content-Type", "application/json"; "connection", "close"] in match meth with | `GET -&gt; let json_values = `List [ `Assoc [ ("id", `String "1"); ("name", `String "todo 1"); ( "description", `String "do this, do that"); ]; `Assoc [ ("id", `String "2"); ("name", `String "todo 2"); ( "description", `String "do this again, do that again"); ] ] in let response_body = Yojson.Basic.to_string json_values in let resp_headers = build_headers response_body in Reqd.respond_with_string reqd (Response.create ~headers:resp_headers `OK) response_body | `POST | `PUT -&gt; let request_body = Reqd.request_body reqd in let data = Buffer.create 1024 in let rec on_read buffer ~off ~len = let str = Bigstringaf.substring buffer ~off ~len in let () = Buffer.add_string data str in Body.schedule_read request_body ~on_eof ~on_read; and on_eof () = let json = (Buffer.sub data 0 (Buffer.length data)) |&gt; Bytes.to_string |&gt; Yojson.Basic.from_string in let () = Stdio.print_endline (Yojson.Basic.pretty_to_string json) in let response_body = Printf.sprintf "%s request on url %s\n" (Method.to_string meth) target in let resp_headers = build_headers response_body in Reqd.respond_with_string reqd (Response.create ~headers:resp_headers `OK) response_body in Body.schedule_read request_body ~on_eof ~on_read | `DELETE -&gt; let response_body = Printf.sprintf "%s request on url %s\n" (Method.to_string meth) target in let resp_headers = build_headers response_body in Reqd.respond_with_string reqd (Response.create ~headers:resp_headers `OK) response_body | meth -&gt; let response_body = Printf.sprintf "%s is not an allowed method\n" (Method.to_string meth) in invalid_request reqd `Method_not_allowed response_body let error_handler ?request:_ error start_response = let response_body = start_response Headers.empty in begin match error with | `Exn exn -&gt; Body.write_string response_body (Exn.to_string exn); Body.write_string response_body "\n"; | #Status.standard as error -&gt; Body.write_string response_body (Status.default_reason_phrase error) end; Body.close_writer response_body </code></pre> <p>I build build, run and test my server with:</p> <pre><code>dune build bin/backend.exe --profile=release dune exec bin/backend.exe --profile=release curl -i -X GET localhost:8080/toto curl -i -X POST -H "Content-Type: application/json" -d some_random_json localhost:8080/toto </code></pre> <p>In the <em>lib.ml</em> file, for the <code>POST</code> and <code>PUT</code> request, I read the data from the request body and transform it in json, is it the right way to do it?</p> <p>How can I improve this ?</p>
[]
[ { "body": "<p>In your request handler, you have:</p>\n<pre class=\"lang-ml prettyprint-override\"><code> [ &quot;Content-length&quot;, Int.to_string (String.length response_body);\n &quot;Content-Type&quot;, &quot;application/json&quot;;\n &quot;connection&quot;, &quot;close&quot;]\n</code></pre>\n<p>Httpaf seems to <a href=\"https://github.com/inhabitedtype/httpaf/issues/192\" rel=\"nofollow noreferrer\">require either a Content-Length or connection close</a>, but I think unconditionally closing the connection is probably undesirable (connection reuse makes HTTP faster). I'd recommend:</p>\n<pre class=\"lang-ml prettyprint-override\"><code> [ &quot;Content-length&quot;, Int.to_string (String.length response_body);\n &quot;Content-Type&quot;, &quot;application/json&quot;]\n</code></pre>\n<p>I could go either way for <code>invalid_request</code>, but you could consider leaving that connection open as well and passing a <code>Content-Length</code>.</p>\n<p>In <code>on_eof</code>, you do:</p>\n<pre class=\"lang-ml prettyprint-override\"><code> let json = (Buffer.sub data 0 (Buffer.length data)) |&gt; Bytes.to_string |&gt; Yojson.Basic.from_string in\n</code></pre>\n<p>But <code>Base.Buffer</code> has a built-in <a href=\"https://ocaml.janestreet.com/ocaml-core/latest/doc/base/Base/Buffer/index.html#val-contents\" rel=\"nofollow noreferrer\">contents</a> function for this:</p>\n<pre class=\"lang-ml prettyprint-override\"><code> let json = Buffer.contents data |&gt; Yojson.Basic.from_string in\n</code></pre>\n<p>If you expand this code more, you might want to factor out functions for things like adding the content-length header and reading the request body. I used your code as an example when I was learning Httpaf, but I ended up factoring out these two functions:</p>\n<pre class=\"lang-ml prettyprint-override\"><code>let with_body ?(buffer_size = 1024) reqd f =\n let request_body = Reqd.request_body reqd in\n let data = Buffer.create buffer_size in\n let rec on_read buffer ~off ~len =\n Buffer.add_string data (Bigstringaf.substring buffer ~off ~len);\n Body.schedule_read request_body ~on_eof ~on_read\n and on_eof () = f (Buffer.contents data) in\n Body.schedule_read request_body ~on_eof ~on_read\n;;\n\nlet respond ?(headers = Headers.empty) reqd status body =\n let headers =\n Headers.add headers &quot;Content-length&quot; (Int.to_string (String.length body))\n in\n Reqd.respond_with_string reqd (Response.create ~headers status) body\n;;\n</code></pre>\n<p>And in your code you could use these like:</p>\n<pre class=\"lang-ml prettyprint-override\"><code>let respond_json ?(headers = Headers.empty) reqd status body =\n let headers = Headers.add headers &quot;Content-Type&quot; &quot;application/json&quot; in\n respond ~headers reqd status (Yojson.Basic.to_string body)\n;;\n\nlet request_handler reqd =\n let { Request.meth; target; _ } = Reqd.request reqd in\n match meth with\n | `GET -&gt;\n let json_values =\n `List\n [ `Assoc\n [ &quot;id&quot;, `String &quot;1&quot;\n ; &quot;name&quot;, `String &quot;todo 1&quot;\n ; &quot;description&quot;, `String &quot;do this, do that&quot;\n ]\n ; `Assoc\n [ &quot;id&quot;, `String &quot;2&quot;\n ; &quot;name&quot;, `String &quot;todo 2&quot;\n ; &quot;description&quot;, `String &quot;do this again, do that again&quot;\n ]\n ]\n in\n respond_json reqd `OK json_values\n | `POST | `PUT -&gt;\n with_body reqd\n @@ fun data -&gt;\n let json = Yojson.Basic.from_string data in\n let () = Stdio.print_endline (Yojson.Basic.pretty_to_string json) in\n let response_body =\n Printf.sprintf &quot;%s request on url %s\\n&quot; (Method.to_string meth) target\n in\n respond reqd `OK response_body\n | `DELETE -&gt;\n let response_body =\n Printf.sprintf &quot;%s request on url %s\\n&quot; (Method.to_string meth) target\n in\n respond reqd `OK response_body\n | meth -&gt;\n let response_body =\n Printf.sprintf &quot;%s is not an allowed method\\n&quot; (Method.to_string meth)\n in\n respond reqd `Method_not_allowed response_body\n;;\n</code></pre>\n<p>In my opinion, this makes the code more readable because a lot of low-level details are moved out of the <code>request_handler</code> function, and the remaining code is easier to follow as a result.</p>\n<p>One other thing you might want to do is break out individual functions for your <code>GET</code>, <code>POST/PUT</code> and <code>DELETE</code> functions and just call them from your big function, which would make it easier for someone scanning the code to find the part they're looking for (if they only want to look at the GET code for example).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-14T00:21:23.207", "Id": "257123", "ParentId": "234751", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T19:03:28.533", "Id": "234751", "Score": "1", "Tags": [ "json", "ocaml" ], "Title": "OCaml backend for REST API and JSON data" }
234751
<p>i am new with nodejs, and i am trying to ameliorate, not only my experience but the power of my code, so i would like to ask you today to give :</p> <p>some way to optimise my code note on 10 (?? / 10) for my code and if there is any website where i can test my code, i ll be so grateful so here is my nodejs class.</p> <p>there is no problem with the code itself but it looks like isn't professional</p> <pre><code> const formidable = require('formidable'), jimp = require('jimp'), shortid = require('shortid'), validator = require('validator'), moment = require('moment'), ObjectId = require('mongodb').ObjectId, fs = require('fs'), dot = require('mongo-dot-notation'); // to update as an object class AdminList { constructor(router) { router.post('/adminlist/ajouter', this.AjouterAdmin.bind(this)); router.get('/adminList/recuperer', this.RecupererAdmin.bind(this)); router.delete('/adminList/supprimer/:id', this.SupprimerAdmin.bind(this)); router.get('/adminList/supprimer/:id', this.RecupererAdmin.bind(this)); router.put('/adminList/modifier', this.ModifierAdmin.bind(this)); } AjouterAdmin(req, res) { let form = new formidable.IncomingForm(), extensionList = ['jpg', 'jpeg', 'png', 'tiff'], db = req.app.db, imgExtension; form.parse(req, async (err, fields, files) =&gt; { if (err) return (err); if (files.avatar) imgExtension = files.avatar.name.split('.').pop(); switch (true) { case (fields.email === undefined || !validator.isEmail(fields.email)): ErrorMessage("Format email invalid", res); break; case (fields.dateNaissance === undefined || validator.toDate(fields.dateNaissance) === null): ErrorMessage("Date de naissance invalid", res); break; case (fields.phone === undefined || validator.isEmpty(fields.phone)): ErrorMessage("Numéro de telephone invalid", res); break; case (fields.adresse === undefined || !validator.isAlphanumeric(fields.adresse)): ErrorMessage("L'adresse doit être alphanumérique", res); break; case (fields.posteCode === undefined || !validator.isNumeric(fields.posteCode)): ErrorMessage("Code postale invalid", res); break; case (fields.displayName === undefined || validator.isEmpty(fields.displayName)): ErrorMessage("Nom et prénom invalid", res); break; case (fields.mdp === undefined || validator.isEmpty(fields.mdp)): ErrorMessage("Mot de passe invalid", res); break; case (fields.ville === undefined || validator.isEmpty(fields.ville)): ErrorMessage("Ville invalid", res); break; case (fields.pays === undefined || validator.isEmpty(fields.pays)): ErrorMessage("Pays invalid", res); break; case (files.avatar === undefined || !extensionList.includes(imgExtension)): ErrorMessage("le type d'image doit être jgp/jpeg/png/tiff", res); break; default: db.collection("utilisateur").findOne({ email: fields.email }, { projection: { _id: 1 } }, (err, user) =&gt; { if (err) ErrorMessage(err, res); if (user) ErrorMessage("Adresse email déja enregistrer", res); else { let newUser = createOrEditUser(fields, files, 'editeur', 'ajouter'); db.collection("utilisateur").insertOne(newUser, function (err) { if (err) { res.writeHead(500, { 'content-type': 'text/plain' }); res.end(err); } res.writeHead(200, { 'content-type': 'text/plain' }); res.end("success"); }) } }); break; } }); } RecupererAdmin(req, res) { let db = req.app.db; db.collection("utilisateur") .find({ "role": "editeur" }, { projection: { _id: 1, email: 1, name: 1, phone: 1, image: 1 } }) .skip((req.params.page - 1) * 15) .limit(15) .sort({ "dateInsert": -1 }) .toArray((err, admin) =&gt; { if (err) return res.json(err) return res.status(200).json(admin); }); } SupprimerAdmin(req, res) { let db = req.app.db; db.collection("utilisateur").updateOne({ _id: ObjectId(req.params.id) }, { $set: { desactive: true } }, (err) =&gt; { if (err) return res.json(err); return res.status(200).json({ message: "supprimer" }); }); } ModifierAdmin(req, res, cb) { let form = new formidable.IncomingForm(), extensionList = ['jpg', 'jpeg', 'png', 'tiff'], db = req.app.db, imgExtension; form.parse(req, async (err, fields, files) =&gt; { if (err) return (err); if (files.avatar) imgExtension = files.avatar.name.split('.').pop(); switch (true) { case (fields.id === undefined): ErrorMessage("id utilisateur invalid", res); case (fields.email !== undefined &amp;&amp; !validator.isEmail(fields.email)): ErrorMessage("Format email invalid", res); break; case (fields.dateNaissance !== undefined &amp;&amp; validator.toDate(fields.dateNaissance) === null): ErrorMessage("Date de naissance invalid", res); break; case (fields.phone !== undefined &amp;&amp; validator.isEmpty(fields.phone)): ErrorMessage("Numéro de telephone invalid", res); break; case (fields.adresse !== undefined &amp;&amp; !validator.isAlphanumeric(fields.adresse)): ErrorMessage("L'adresse doit être alphanumérique", res); break; case (fields.posteCode !== undefined &amp;&amp; !validator.isNumeric(fields.posteCode)): ErrorMessage("Code postale invalid", res); break; case (fields.displayName !== undefined &amp;&amp; validator.isEmpty(fields.displayName)): ErrorMessage("Nom et prénom invalid", res); break; case (fields.mdp !== undefined &amp;&amp; validator.isEmpty(fields.mdp)): ErrorMessage("Mot de passe invalid", res); break; case (fields.ville !== undefined &amp;&amp; validator.isEmpty(fields.ville)): ErrorMessage("Ville invalid", res); break; case (fields.pays !== undefined &amp;&amp; validator.isEmpty(fields.pays)): ErrorMessage("Pays invalid", res); break; case (files.avatar !== undefined &amp;&amp; !extensionList.includes(imgExtension)): ErrorMessage("le type d'image doit être jgp/jpeg/png/tiff", res); break; default: UtilisateurExist(req, fields.email).then(async (result) =&gt; { console.log('here'); if (result === true) { ErrorMessage("Adresse email déjà utilisé", res); } else { let newUser = await createOrEditUser(fields, files, 'editeur', 'modifier'); db.collection("utilisateur").updateOne({ _id: ObjectId(fields.id) }, dot.flatten(newUser), (err, user) =&gt; { if (err) ErrorMessage(err, res); if (user.result.n === 0) ErrorMessage("Utilisateur n'existe pas", res); else { res.writeHead(200, { 'content-type': 'text/plain' }); res.end("success"); } }); } }); break; } }); } } module.exports = AdminList; function createOrEditUser(fields, files, role, type) { let newUser = {}; if (fields.email) newUser.email = fields.email; if (fields.mdp) newUser.mdp = fields.mdp; if (fields.displayName) newUser.name = fields.displayName if (role !== undefined &amp;&amp; type !== 'modifier') newUser.role = role; if (type === 'ajouter') newUser.dateInsert = moment().utc(1).format("YYYY-MM-DD HH:mm:ss"); if (type === 'modifier') newUser.dateModif = moment().utc(1).format("YYYY-MM-DD HH:mm:ss"); if (fields.dateNaissance) newUser.dateNaissance = fields.dateNaissance; if (fields.phone) newUser.phone = fields.phone if (fields.pays) newUser.pays = fields.pays if (fields.ville) newUser.ville = fields.ville if (fields.posteCode) newUser.posteCode = fields.posteCode if (fields.adresse) newUser.adresse = fields.adresse; if (fields.PhototoDelete === true) { fs.unlink(`../../ assets / img50 / ${fields.PhototoDelete}`); fs.unlink(`../../ assets / img140 / ${fields.PhototoDelete}`); } if (files.avatar) { imgExtension = files.avatar.name.split('.').pop(); let imgName = generateImageName() + '.' + imgExtension; newUser.image = imgName; let imgSmallPath = `assets / img50 / ${imgName}`; let imgBigPath = `assets / img140 / ${imgName}`; genImgResize(files.avatar, imgBigPath, 140); genImgResize(files.avatar, imgSmallPath, 50); } return newUser; } function generateImageName() { return shortid.generate() } // 50* 50 image function genImgResize(file, savePath, size) { return jimp.read(file.path, (err, img) =&gt; { if (err) throw err; img.resize(size, size) .quality(60) .write(`${savePath}`) return savePath }).catch(err =&gt; { return { err: err } }); } function ErrorMessage(message, res) { res.writeHead(400, { 'content-type': 'text/plain' }); res.end(message); } async function UtilisateurExist(req, email) { let db = req.app.db; let userExist = await new Promise((resolve, reject) =&gt; { db.collection("utilisateur").findOne({ email: email }, { projection: { _id: 1 } }, (err, user) =&gt; { if (err) reject(err); if (user) resolve(true) else resolve(false) }); }); return userExist } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T19:05:23.873", "Id": "234752", "Score": "1", "Tags": [ "javascript", "performance", "node.js" ], "Title": "Check nodejs class optimisation" }
234752
<p>I created a monad in Haskell that lets you sample without replacement from user-defined urns, and then at the end gives you a list of all possible outcomes. It looks like it's similar to the list monad (except that one only ever samples with replacement), and to the ST monad. Here's the interface I want to present:</p> <pre class="lang-hs prettyprint-override"><code>data Draw s a data Urn s a instance MonadPlus (Draw s) newUrn :: [a] -&gt; Draw s (Urn s a) drawFrom :: Urn s a -&gt; Draw s a drawList :: [a] -&gt; Draw s a -- so that you can still sample with replacement, like in the list monad runDraw :: (forall s. Draw s a) -&gt; [a] </code></pre> <p>Here's an example of how I want to use it:</p> <pre class="lang-hs prettyprint-override"><code>runDraw $ do l &lt;- newUrn [1,2,3,3] x &lt;- drawFrom l y &lt;- drawFrom l return (x, y) -- produces [(1,2),(1,3),(1,3),(2,1),(2,3),(2,3),(3,1),(3,2),(3,3),(3,1),(3,2),(3,3)] </code></pre> <p>And here's what I came up with to implement that:</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE MagicHash, RankNTypes, RoleAnnotations #-} module Draw (Draw, Urn, newUrn, drawFrom, drawList, runDraw) where import Control.Applicative (Alternative(..)) import Control.Monad (MonadPlus, ap, liftM) import Data.List (genericSplitAt) import GHC.Exts (Any, unsafeCoerce#) import Numeric.Natural (Natural) newtype Draw s a = Draw { unDraw :: (Natural, [Any]) -&gt; [(a, (Natural, [Any]))] } type role Draw nominal representational newtype Urn s a = Urn Natural type role Urn nominal representational instance Functor (Draw s) where fmap = liftM instance Applicative (Draw s) where pure = drawList . pure (&lt;*&gt;) = ap instance Alternative (Draw s) where empty = drawList empty Draw m1 &lt;|&gt; Draw m2 = Draw $ \s -&gt; m1 s &lt;|&gt; m2 s instance Monad (Draw s) where Draw m &gt;&gt;= f = Draw $ \s -&gt; m s &gt;&gt;= uncurry (unDraw . f) instance MonadPlus (Draw s) drawList :: [a] -&gt; Draw s a drawList xs = Draw $ \s -&gt; flip (,) s &lt;$&gt; xs runDraw :: (forall s. Draw s a) -&gt; [a] runDraw (Draw f) = map fst (f (0, [])) newUrn :: [a] -&gt; Draw s (Urn s a) newUrn xs = Draw $ \(n, us) -&gt; pure (Urn n, (n + 1, us ++ [toAny xs])) drawFrom :: Urn s a -&gt; Draw s a drawFrom (Urn i) = Draw go where go :: (Natural, [Any]) -&gt; [(a, (Natural, [Any]))] go (n, us) = map (\(x, remainingContents) -&gt; (x, (n, before ++ toAny remainingContents : after))) (removeEach (fromAny urnContents)) where (before, urnContents:after) = genericSplitAt i us fromAny :: Any -&gt; [a] fromAny = unsafeCoerce# toAny :: [a] -&gt; Any toAny = unsafeCoerce# removeEach :: [a] -&gt; [(a, [a])] removeEach [] = [] removeEach (x:xs) = (x, xs):map (fmap (x:)) (removeEach xs) </code></pre> <p>This seems to work, at least with the example I posted above.</p> <p>Here's my concerns:</p> <ul> <li>I'm doing a lot of <code>unsafeCoerce#</code>, which is obviously not very safe</li> <li><code>(before, urnContents:after) = genericSplitAt i us</code> is an incomplete pattern match, which may be able to fail at runtime</li> <li>I'm building the list of urns with <code>xs ++ [x]</code>, which is quadratically slow</li> <li><s>I'm not confident that this satisfies all of the typeclass laws, in particular the monad law of associativity</s> I now realize that my type is isomorphic to <code>StateT (Natural, [Any]) []</code>, with equivalent instances, so I'm no longer concerned about this.</li> <li>I'm not sure if the way I'm handling the urns is correct, or if it's somehow possible to use an urn where it doesn't belong and thus break type safety</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T20:49:18.723", "Id": "459169", "Score": "0", "body": "I realize after asking this that what I really want is something akin to `STRef` but for `StateT s []`. However, this review question is still relevant, since the monstrosity I built to do that is the core of this." } ]
[ { "body": "<p>This is an interesting problem, and you've written an interesting solution.</p>\n\n<p>With respect to your inefficient urn \"store\" -- the mapping of immutable urn references (<code>Urn Natural</code>) to mutable urn contents -- it might be worth considering that because of the nature of your monad, most monadic computations involving urns will scale exponentially in the number of urns anyway, so big-O performance of urn list building and lookups is essentially irrelevant. You can start thinking about it when people want to use your monad for 100000-urn problems; or you could probably port everything over to a <code>Data.Map Int</code> or <code>Data.IntMap</code> in a few minutes).</p>\n\n<p>The bigger problem, as you've noted, is that because this all has to run in a specific monotyped monad, unless you want to pre-declare the set of urns and their element types as used in a particular computation, you need an ugly, unsafe generic type like <code>[Any]</code> to represent your set of urns.</p>\n\n<p>One method of dealing with this would be to represent the mutable contents of an urn by a set of always-integer indices while packaging the actual elements as part of the immutable <code>Urn</code> reference. That is, the <code>Urn</code> references you pass around can be represented as:</p>\n\n<pre><code>data Urn s a = Urn { tag :: Key\n , labels :: Int -&gt; a }\ntype role Urn nominal representational\n</code></pre>\n\n<p>with monotyped mutable state:</p>\n\n<pre><code>data UrnState = UrnState { nextTag :: Key\n , urns :: IntMap [Int] }\n</code></pre>\n\n<p>So <code>urns urnState ! tag1</code> is the set of integer indices still in play for that urn, and the actual elements are available by looking up those indices in the <code>labels urnRef</code> map.</p>\n\n<h2>SPOILERS</h2>\n\n<p>A complete code example, which seems to work on your test case is:</p>\n\n<pre><code>{-# LANGUAGE DeriveFunctor, RoleAnnotations, RankNTypes #-}\nimport Data.List\nimport Control.Monad\nimport qualified Data.IntMap as IntMap\nimport Data.IntMap (Key, IntMap, (!))\n\ndata Urn s a = Urn { tag :: Key\n , labels :: Int -&gt; a }\ntype role Urn nominal representational\n\ndata UrnState = UrnState { nextTag :: Key\n , urns :: IntMap [Int] }\n\nnewtype Draw s a = Draw { unDraw :: UrnState -&gt; [(a, UrnState)] } deriving (Functor)\ntype role Draw nominal representational\ninstance Applicative (Draw s) where\n pure x = Draw (\\s -&gt; [(x,s)])\n (&lt;*&gt;) = ap\ninstance Monad (Draw s) where\n Draw d &gt;&gt;= f = Draw $ \\s -&gt; do -- list monad\n (a', s') &lt;- d s\n unDraw (f a') s'\n\nevalDraw :: (forall s. Draw s a) -&gt; [a]\nevalDraw (Draw d) = map fst $ d $ UrnState 0 IntMap.empty\n\nnewUrn :: [a] -&gt; Draw s (Urn s a)\nnewUrn xs = Draw $ \\(UrnState nxttag urs) -&gt;\n let -- list of labels keyed by indexes [0..n-1]\n lbls = IntMap.fromAscList (zip [0..] xs)\n -- new urn has tag \"nxttag\" and the immutable labelling function\n u = Urn nxttag (lbls !)\n -- add urn to state\n urs' = IntMap.insert nxttag (IntMap.keys lbls) urs\n in [(u, UrnState (nxttag+1) urs')]\n\ndraws :: [a] -&gt; [(a,[a])]\ndraws xs = zipWith3 go (inits xs) xs (tail (tails xs))\n where go l a r = (a, l++r)\n\ndrawFrom :: Urn s a -&gt; Draw s a\ndrawFrom (Urn tg lbls) = Draw $ \\(UrnState nxttag urs) -&gt;\n case urs ! tg of\n [] -&gt; fail \"empty urn\"\n xs -&gt; do -- list monad\n (a, xs') &lt;- draws xs\n return $ (lbls a, UrnState nxttag $ IntMap.insert tg xs' urs)\n\nmain :: IO ()\nmain = print $ evalDraw $ do\n l &lt;- newUrn [1,2,3,3]\n x &lt;- drawFrom l\n y &lt;- drawFrom l\n return (x, y)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T23:08:15.500", "Id": "234929", "ParentId": "234755", "Score": "2" } } ]
{ "AcceptedAnswerId": "234929", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T20:11:39.297", "Id": "234755", "Score": "1", "Tags": [ "haskell", "monads" ], "Title": "Monad to sample without replacement" }
234755
<p>From <a href="https://leetcode.com/problems/3sum/" rel="noreferrer">here</a>:</p> <blockquote> <p>Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.</p> <p>Note:</p> <p>The solution set must not contain duplicate triplets.</p> </blockquote> <p>This solution works and is pretty fast but not very memory efficient. I have some comments which I added when writing it to keep track of what I was doing. Specific questions are at bottom.</p> <pre><code>class Solution: def threeSum(self, nums: List[int]) -&gt; List[List[int]]: # Early exit conditions if len(nums) &lt; 3: return [] results = {} vals = {} # Make easy to check if all target values exist for i, v in enumerate(nums): if v in vals: vals[v] += 1 else: vals[v] = 1 # Go through all matching numbers # This works because each result is unique for i, num in enumerate(vals.keys()): # Modified two sum problem to get -i-j for j in list(vals.keys())[i:]: # If checking itself but only is in input once, can't work if num == j and vals[num] &lt; 2: continue target_val = -(num+j) if target_val in vals: valid = False if vals[target_val] &gt; 2: valid = True else: # Check that this isn't either i/j (thus duplicate) if num != target_val and j != target_val: valid = True if valid and tuple(sorted((num, j, target_val))) not in results: results[tuple(sorted((num, j, target_val)))] = True return [list(r) for r in results.keys()] </code></pre> <ol> <li>I dislike the way I'm sorting then converting to a tuple. Is there a better way to do this?</li> <li>I feel like I can clean up some of the <code>if</code> logic but I'm not totally sure how is best.</li> <li>I dislike the <code>list(vals.keys())</code> approach - is there a better way to do what I'm doing here? I am not a huge fan of it</li> <li>This one might be out of scope for this Code Review question but this doesn't seem to generalize very well if there were say 4 elements or 8 elements in the target (vs 3). I'd have to continue to add nested lists in order for that to work and the strategy for <code>if</code> checking here would get <em>very</em> messy.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T22:26:25.777", "Id": "459172", "Score": "0", "body": "Is it passing all the test cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T02:32:34.883", "Id": "459190", "Score": "0", "body": "Yes this passes all test cases." } ]
[ { "body": "<ol>\n<li>Please don't have white space at the end of lines. There is never a need for anything other than a new line at the end of a line.</li>\n<li>You don't need to use <code>enumerate(nums)</code> to build <code>vals</code> - <code>i</code> is never used.</li>\n<li>You can use <code>collections.defaultdict(int)</code> to remove the need for the <code>if</code> in the <code>for</code> when you make <code>vals</code>.</li>\n<li>You can use <code>collections.Counter</code> to create <code>vals</code>.</li>\n<li>You can use <code>itertools.combinations_with_replacement</code> to reduce your nested for loops into one. This has the same <span class=\"math-container\">\\$O\\$</span>, but may help in the future if you want to do four sum.</li>\n<li>It is confusing to use <code>i</code> and <code>j</code> to not be related to the same thing. <code>i</code> is \"index\", where <code>j</code> is \"num2\".</li>\n<li>Since <code>valid</code> is just a Boolean, you can compress the <code>if</code>-<code>else</code> to not need the <code>if</code>.</li>\n<li><p>I believe your <code>vaild</code> check is erroneous. If <code>j</code> and <code>target_val</code> are the same but <code>vals[j] == 1</code> then your code will happily still plop it out. I also think your output is erroneous on <code>num == j</code> and <code>vals[num] == 2</code>.</p>\n\n<p>You can make a <code>collections.Counter</code> of the values and then check if this counter is a subset of the global one.</p></li>\n<li><p>I suggest making two functions:</p>\n\n<ol>\n<li>A generator function, one that produces values that add to the desired sum.</li>\n<li>A function to filter duplicate values and normalize output.</li>\n</ol></li>\n</ol>\n\n<pre><code>class Solution:\n def _three_sum(self, nums: List[int]) -&gt; Iterator[Tuple[int, int, int]]:\n if len(nums) &lt; 3:\n return\n\n vals = set(nums)\n for i, j in itertools.combinations_with_replacement(vals, 2):\n k = -(i+j)\n if k not in vals:\n continue\n yield i, j, k\n\n def threeSum(self, nums: List[int]) -&gt; List[List[int]]:\n output = set()\n amounts = collections.Counter(nums)\n for result in self._three_sum(nums):\n if all(\n amount &lt;= amounts[num]\n for num, amount in collections.Counter(result).items()\n ):\n output.add(tuple(sorted(result)))\n return [list(vals) for vals in output]\n</code></pre>\n\n<hr>\n\n<p>To answer your questions:</p>\n\n<ol>\n<li>No.</li>\n<li>If you change <code>_three_sum</code> to <code>_n_sum</code> then the <code>threeSum</code> function will work fine.</li>\n<li>I'm not sure what you mean by it but, <code>list(vals)</code> is a Pythonic way to write it. Albeit possibly more confusing. It is preferred to just use <code>itertools</code>.</li>\n<li><p>This is off-topic here, and no this would probably not be extendable to more than sum of three.</p>\n\n<p>I know of <a href=\"https://cs.stackexchange.com/a/108835\">this answer on CS.SE</a> that sets the foundation for an n-sum solution. Whilst the question clearly has a different goal, you should be able to dissect the answer and mold it to what you need.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T19:19:21.430", "Id": "459257", "Score": "0", "body": "`num+j` -> `i+j`, `ouput` -> `output`. The edit was too short, someone come up with something else to say :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T19:21:40.807", "Id": "459258", "Score": "0", "body": "@JollyJoker I'm not too sure what you mean, if you want you can add `<!-- filler -->` to pad to the edit character limit. Do it somewhere like the bottom of the answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T19:24:33.380", "Id": "459259", "Score": "0", "body": "Done, thanks for the tip! Apparently the edit won't be visible until it's peer reviewed though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T19:33:13.607", "Id": "459260", "Score": "1", "body": "@JollyJoker No problem. Approved it for you. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T23:35:43.213", "Id": "234766", "ParentId": "234757", "Score": "4" } }, { "body": "<p>For reference, what I think is the most straightforward solution, that is <em>not</em> fast enough since it does all combinations of three.</p>\n\n<pre><code>from itertools import combinations\n\nclass Solution:\n def threeSum(self, nums: List[int]) -&gt; List[List[int]]:\n return set(tuple(c) for c in combinations(sorted(nums), 3) if sum(c) == 0)\n</code></pre>\n\n<p>And a longer, but valid solution.</p>\n\n<ul>\n<li><p>Take positive and negative numbers separately.</p></li>\n<li><p>Add all combinations of two positive numbers where their negative sum is among the negative numbers. Repeat for negative numbers.</p></li>\n<li><p>For each number in both negative and positive, add <code>-n, 0, n</code></p></li>\n<li><p>If there are three or more zeroes, add <code>0,0,0</code></p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import combinations\n\nclass Solution:\n def threeSum(self, nums: List[int]) -&gt; List[List[int]]:\n positive = sorted([n for n in nums if n &gt; 0])\n posSet = set(positive)\n negative = sorted([n for n in nums if n &lt; 0])\n negSet = set(negative)\n zeroes = nums.count(0)\n valid = set((a,b,0-a-b) for (a,b) in combinations(positive, 2) if 0-a-b in negSet)\n valid = valid.union(set((a,b,0-a-b) for (a,b) in combinations(negative, 2) if 0-a-b in posSet))\n if(zeroes &gt; 0):\n valid = valid.union(set((-a,0,a) for a in positive if 0-a in negSet))\n if(zeroes &gt; 2):\n valid.add((0,0,0))\n return valid\n</code></pre>\n\n<p>Surprisingly good results:</p>\n\n<p><em>Runtime: 360 ms, faster than 98.52% of Python3 online submissions for 3Sum.\nMemory Usage: 16.4 MB, less than 97.14% of Python3 online submissions for 3Sum.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:17:24.357", "Id": "234792", "ParentId": "234757", "Score": "5" } }, { "body": "<p>I really liked @JollyJoker's answer but it was not written in Pythonic enough format for my taste. I added some changes that take his core logic and improve upon it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import combinations\n\nclass Solution:\n def threeSum(self, nums: List[int]) -&gt; List[List[int]]:\n positive = sorted(n for n in nums if n &gt; 0)\n posSet = set(positive)\n negative = sorted(n for n in nums if n &lt; 0)\n negSet = set(negative)\n zeroes = nums.count(0)\n valid = {(a, b, -a-b) for (a,b) in combinations(positive, 2) if -a-b in negSet}\n valid.update((a, b, -a-b) for (a,b) in combinations(negative, 2) if -a-b in posSet)\n if zeroes &gt; 0:\n valid.update((-a, 0, a) for a in positive if -a in negSet)\n if zeroes &gt; 2:\n valid.add((0, 0, 0))\n return valid\n</code></pre>\n\n<p>Results:</p>\n\n<p><em>Runtime: 340 ms, faster than 98.68% of Python3 online submissions for 3Sum.</em></p>\n\n<p><em>Memory Usage: 16.6 MB, less than 77.86% of Python3 online submissions for 3Sum.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:49:00.490", "Id": "234842", "ParentId": "234757", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T20:43:05.183", "Id": "234757", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge", "subset-sum-problem" ], "Title": "Leetcode Three Sum" }
234757
<p>I created a program where I was constantly needing o know the number of files in a folder, number of folders, and getting these file names into a vector, so I made this wrapper because I am planning on creating a program that will as well constantly need the informations above mentioned.</p> <p>mydirent.h</p> <pre><code>#ifndef MYDIRENT_H_INCLUDED #define MYDIRENT_H_INCLUDED #include &lt;string&gt; #include &lt;vector&gt; namespace dir { class DirentWrap { private: DIR *dp; struct dirent *ep; DirentWrap(){} public: static int number_of_files_in_directory(std::string file_path); static int number_of_folders_in_directory(std::string file_path); static void files_in_directory(std::string file_path, std::vector&lt;std::string&gt;&amp; files); static void folders_in_directory(std::string file_path, std::vector&lt;std::string&gt;&amp; folders); }; } #endif // MYDIRENT_H_INCLUDED </code></pre> <p>mydirent.cpp</p> <pre><code>#include "mydirent.h" #include &lt;dirent.h&gt; #include &lt;iostream&gt; #include &lt;sys/stat.h&gt; using namespace std; using namespace dir; class MyException : public exception { virtual const char* what() const throw() { return "error openning folder"; } } ex; int DirentWrap::number_of_files_in_directory(string file_path) { // a contagem vai começar apartir de -2 pk em todas as pastas parece sempre haver 2 ficheiros desconhecidos pra mim ( . , .. ) int counter = 0; string secure_file_path = file_path + "\\"; DirentWrap dr; dr.dp = opendir(secure_file_path.c_str()); struct stat s; if (dr.dp != nullptr) { while ((dr.ep = readdir(dr.dp))) { string path = secure_file_path + dr.ep-&gt;d_name; stat(path.c_str(), &amp;s); if(s.st_mode &amp; S_IFREG) ++counter; } } else { closedir(dr.dp); throw ex; } closedir(dr.dp); return counter; } int DirentWrap::number_of_folders_in_directory(string file_path) { // a contagem vai começar apartir de -2 pk em todas as pastas parece sempre haver 2 ficheiros desconhecidos pra mim ( . , .. ) int counter = -2; string secure_file_path = file_path + "\\"; DirentWrap dr; dr.dp = opendir(secure_file_path.c_str()); struct stat s; if (dr.dp != nullptr) { while ((dr.ep = readdir(dr.dp))) { string path = secure_file_path + dr.ep-&gt;d_name; stat(path.c_str(), &amp;s); if(s.st_mode &amp; S_IFDIR) ++counter; } } else { closedir(dr.dp); throw ex; } closedir(dr.dp); return counter; } void DirentWrap::files_in_directory(string file_path, vector&lt;std::string&gt;&amp; files) { string secure_file_path = file_path + "\\"; DirentWrap dr; dr.dp = opendir(secure_file_path.c_str()); struct stat s; if (dr.dp != nullptr) { while ((dr.ep = readdir(dr.dp))) { string path = secure_file_path + dr.ep-&gt;d_name; stat(path.c_str(), &amp;s); if(s.st_mode &amp; S_IFREG) { files.push_back(dr.ep-&gt;d_name); } } } else { closedir(dr.dp); throw ex; } closedir(dr.dp); } void DirentWrap::folders_in_directory(string file_path, vector&lt;std::string&gt;&amp; folders) { int counter = 0; string secure_file_path = file_path + "\\"; DirentWrap dr; dr.dp = opendir(secure_file_path.c_str()); struct stat s; if (dr.dp != nullptr) { while ((dr.ep = readdir(dr.dp))) { ++counter; if (counter &gt; 2) { string path = secure_file_path + dr.ep-&gt;d_name; stat(path.c_str(), &amp;s); if(s.st_mode &amp; S_IFDIR) { folders.push_back(dr.ep-&gt;d_name); } } } } else { closedir(dr.dp); throw ex; } closedir(dr.dp); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T04:48:46.123", "Id": "459196", "Score": "0", "body": "What if the directory entries have already been retrieved, and I just want to get the list of names multiple times? There is no caching mechanism in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T09:25:53.003", "Id": "459205", "Score": "0", "body": "@PaulMcKenzie I actually don't know about caching, I mean, I know what is it and what it is used for but that is it, I don't know how to implemement it and when it is needed (as in this wrapper). Any suggestion on how to get started?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:02:13.917", "Id": "459225", "Score": "1", "body": "Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), in particular the **Titling your question** section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T10:11:44.820", "Id": "459482", "Score": "0", "body": "I think you can do it without developing a C program. I think using the operating system shell is enough (you can use a cron or\n  task schedule if you need them to run at intervals)." } ]
[ { "body": "<ul>\n<li><p><strong>DRY</strong>.</p>\n\n<p>The <code>number_of_files_in_directory</code> and <code>number_of_folders_in_directory</code> methods are almost identical. Factor out the common code into a private method, say <code>number_of_entities_in_directory</code>, and rewrite public methods as</p>\n\n<pre><code>int DirentWrap::number_of_files_in_directory(string file_path)\n{\n return number_of_entities_in_directory(path, S_IFREG);\n}\n\nint DirentWrap::number_of_folders_in_directory(string file_path)\n{\n return number_of_entities_in_directory(path, S_IFDIR) - 2;\n}\n</code></pre></li>\n<li><p><strong>Portability</strong>.</p>\n\n<ul>\n<li><p><code>\"\\\\\"</code> as a path separator works for Windows only. Prefer <code>\"/\"</code>, which works for both Linux and Windows (the backslash is only required in <code>cmd.exe</code>).</p></li>\n<li><p><code>folders_in_directory</code> assumes that <code>.</code> and <code>..</code> always appear first. <code>readdir</code> does not guarantee it.</p></li>\n<li><p>Consider using <code>std::experimental::filesystem</code> library.</p></li>\n</ul></li>\n<li><p><strong>Error checking</strong>.</p>\n\n<ul>\n<li><p><code>stat</code> may fail. <code>readdir</code> may fail (if so it would return NULL, and you need to test <code>errno</code>, rather than blindly breaking a loop).</p></li>\n<li><p>Similarly, the exception you throw on <code>opendir</code> failure loses the important information, namely <em>why</em> <code>opendir</code> failed. Provide <code>errno</code> or <code>strerror(errno)</code>.</p></li>\n</ul></li>\n<li><p><strong>Why class?</strong></p>\n\n<p><code>class DirentWrap</code> does not have any state. There is no reason to have it. Its methods should be made free functions, with <code>dp</code> and <code>ep</code> being their local variables.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T16:41:14.553", "Id": "459339", "Score": "0", "body": "**Under Portability:** the . and .. always appear in the folders I read, I don't know why and if they mean something. \n\n\n**Under Error checking:** How would I implement the test `errno` with `stat` and `readdir`. I tried something like this: \n```if (readdir(dp)) while ((ep = readdir(dp)))```, \ndon't know if it is correct.\n\n\n**Why Class?**\nWhen using any of those functions I wanted to tell just by readding the code that the function comes from a simple wrap and not a header like `dirent.h` itself .\n\n Thanks for your review, I really appreciate it. Notes taken, changes made." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:46:11.450", "Id": "459359", "Score": "0", "body": "the code provided in the **Dry** section doesn't work, throws an error stating that it can't call the function without an object" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T19:43:03.510", "Id": "234795", "ParentId": "234760", "Score": "5" } }, { "body": "<h1>Use (inspiration from) C++17's <code>std::filesystem</code></h1>\n\n<p>C++17 introduced <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\"><code>std::filesystem</code></a>, which provides portable functions to query things like which files there are in a directory. If you can use C++17, then make use of these functions. If you need to be compatible with older C++ standards, then at least try to emulate what <code>std::filesystem</code> does as much as possible, including functions names and the general behavior.</p>\n\n<p>For example, <code>std::filesystem</code> provides iterators to loop over all elements in a directory. This avoids having to build up a vector, which might be inefficient if you are only going to use it to find an element in it and then discard it.</p>\n\n<h1>There is more to filesystems than files and directories</h1>\n\n<p>There can be things in a directory that are neither normal files nor other directories, for example:</p>\n\n<ul>\n<li>symbolic links</li>\n<li>block devices</li>\n<li>character devices</li>\n<li>fifos</li>\n<li>sockets</li>\n</ul>\n\n<p>The above is a list of things you can find on Linux and Mac OS X platforms, but even Windows has things like symbolic links and junctions.</p>\n\n<p>Your code currently checks whether something is a <em>regular</em> file, but many of the above filesystem elements can be accessed as if they are regular files. So think careful about what semantics you want your functions to have.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T22:04:25.557", "Id": "234800", "ParentId": "234760", "Score": "3" } }, { "body": "<ol>\n<li>Don't use a second instance of the class just to store variables. Further, don't even use member variables for things local to a function.</li>\n<li>In this case, caching would be making one, probably private, method to read the directory listing and populate internal variables with the data. This would allow all four current methods to just ensure the data has been loaded, and then return things from the internal variables. This allows you, for instance, to fetch the number of files and know that when you fetch the list of files, you will get the same number. This may entail adding a <code>reload()</code> method so that you can take a fresh look.</li>\n<li>Your <code>readdir()</code> function may return the file type. If it does, use it. This turns an O(n*n) operation into an O(n) operation. (If you don't follow that, try using a directory with 100,000 files in it.)</li>\n<li>It is probably unwise to assume that \".\" and \"..\" will be the first two entries in a directory.</li>\n<li><code>if(s.st_mode &amp; S_IFDIR)</code> is a mistake. The correct usage is: <code>if((s.st_mode &amp; S_IFMT) == S_IFDIR)</code> Alternatively, you can write <code>if(S_ISDIR(s.st_mode))</code> The same applies to the other tests.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T17:23:53.317", "Id": "459343", "Score": "0", "body": "I don't understand **1**.\nIn **2** I don't know how to implement a caching mechanism yet so I don't follow your suggestion very well.\nI don't follow **3**, on **4** I don't know why the `.` and `..` always appear, because they were always showing up so I assumed it they would always ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:34:43.213", "Id": "459384", "Score": "0", "body": "1: You should not make an instance of your class in a method just to use it's variables. [I admit to not noticing your methods are static.] Additionally, neither of the variables couldn't have just been local variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:36:12.443", "Id": "459385", "Score": "0", "body": "2: Learn about caching. Caching basically means calculating the values once and remembering them for later use. It thus trades off speed for memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:38:09.707", "Id": "459386", "Score": "0", "body": "3: Some modern readdir() functions will tell you if the entry is a file or a directory. If it can, you don't need to stat() the file. stat()ing the file require looking it up, which typically takes log(n) time for a directory with n entries. Avoiding that lookup can be a significant performance boost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:44:00.913", "Id": "459389", "Score": "0", "body": "4: Yes, they (normally) always show up because `.` is the current directory and `..` is the parent directory. But I don't believe they are ever guaranteed to be the first two entries. A filesystem could theoretically sort the entries for you,and put file `!` first. In theory, there could be an operating system that doesn't include these entries, or that names them differently. (It might not be posix compliant, but that doesn't mean your code has to fail.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T02:03:14.707", "Id": "459392", "Score": "0", "body": "Could you suggest some modern `readdir()` function you may know about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T10:33:21.103", "Id": "459422", "Score": "0", "body": "I've seen it in the Linux implementation." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T00:28:42.273", "Id": "234807", "ParentId": "234760", "Score": "5" } } ]
{ "AcceptedAnswerId": "234795", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T21:39:17.900", "Id": "234760", "Score": "2", "Tags": [ "c++" ], "Title": "What is there to say about this wrapper" }
234760
<p>I am new to Haskell and currently trying to port my solutions for the 2019 installment of the coding challenge <a href="https://adventofcode.com/" rel="nofollow noreferrer">AdventOfCode</a> to Haskell. So, I would very much appreciate any suggestions how to make the code more readable and, in particular, more idiomatic.</p> <p>This post shows my solution of <a href="https://adventofcode.com/2019/day/6" rel="nofollow noreferrer">day 6</a> part 2, but also includes the function <code>totalDecendantCount</code> used to solve part 1. If you have not solved these problems and still intend to do so, stop reading immediately.</p> <p>For both problems, you get a file with an <em>orbit specification</em> on each line of the form <code>A)B</code>, which tells you that <code>B</code> orbits <code>A</code>. This describes a tree of bodies orbiting each other with root <code>COM</code>.</p> <p>In part 1, you have to compute a check sum. More precisely, you have to compute the sum of the number of direct and indirect orbits of each body, which is the same as the sum of the number of descendants of each body in the tree. </p> <p>In part 2, which you cannot see if you have not finished part 1, you have to compute the minimal number of transfers between orbits from you (<code>YOU</code>) to Santa (<code>SAN</code>).</p> <p>I have kept the entire solution for each part of each day in a single module with a single exported function that prints the solution. For day 6 part 2 it starts as follows.</p> <pre class="lang-hs prettyprint-override"><code>module AdventOfCode20191206_2 ( distanceToSanta ) where import System.IO import Data.List.Split import Data.List import Data.Maybe import Data.Hashable import qualified Data.HashMap.Strict as Map distanceToSanta :: IO () distanceToSanta = do inputText &lt;- readFile "Advent20191206_1_input.txt" let orbitList = (map orbit . lines) inputText let orbits = orbitMap $ catMaybes orbitList let pathToSanta = fromJust $ path orbits "COM" "YOU" "SAN" let requiredTransfers = length pathToSanta - 3 print requiredTransfers </code></pre> <p>We subtract <code>3</code> from the length of the path because it consists of the bodies on the path and you only have to transfer from the body you already orbit to the body Santa orbits.</p> <p>To store the tree, I use a <code>HashMap.Strict</code> and introduce the following type aliases and helper function to make things a bit more descriptive.</p> <pre class="lang-hs prettyprint-override"><code>type OrbitSpecification = (String,String) type ChildrenMap a = Map.HashMap a [a] children :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; [a] children childrenMap = fromMaybe [] . flip Map.lookup childrenMap </code></pre> <p>Next follow the functions I use to read in the tree.</p> <pre class="lang-hs prettyprint-override"><code>orbit :: String -&gt; Maybe OrbitSpecification orbit str = case orbit_specification of [x,y] -&gt; Just (x,y) _ -&gt; Nothing where orbit_specification = splitOn ")" str orbitMap :: [OrbitSpecification] -&gt; ChildrenMap String orbitMap = Map.fromListWith (++) . map (applyToSecondElement toSingleElementList) applyToSecondElement :: (b -&gt; c) -&gt; (a,b) -&gt; (a,c) applyToSecondElement f (x,y) = (x, f y) toSingleElementList :: a -&gt; [a] toSingleElementList x = [x] </code></pre> <p>To solve part 1, I introduce two general helper function to generate aggregates over children or over all descendents.</p> <pre class="lang-hs prettyprint-override"><code>childrenAggregate :: (Eq a, Hashable a) =&gt; ([a] -&gt; b) -&gt; ChildrenMap a -&gt; a -&gt; b childrenAggregate aggregatorFnc childrenMap = aggregatorFnc . children childrenMap decendantAggregate :: (Eq a, Hashable a) =&gt; (b -&gt; b -&gt; b) -&gt; (ChildrenMap a -&gt; a -&gt; b) -&gt; ChildrenMap a -&gt; a -&gt; b decendantAggregate resultFoldFnc nodeFnc childrenMap node = foldl' resultFoldFnc nodeValue childResults where nodeValue = nodeFnc childrenMap node childFnc = decendantAggregate resultFoldFnc nodeFnc childrenMap childResults = map childFnc $ children childrenMap node </code></pre> <p>The <code>descendantAggragate</code> recursively applies a function <code>nodeFnc</code> to a node <code>node</code> and all its descendants and folds the results using some function <code>resultFoldFnc</code>. This allows to define the necessary functions to count the total number of descendants of a node as follows.</p> <pre class="lang-hs prettyprint-override"><code>childrenCount :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; Int childrenCount = childrenAggregate length decendantCount :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; Int decendantCount = decendantAggregate (+) childrenCount totalDecendantCount :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; Int totalDecendantCount = decendantAggregate (+) decendantCount </code></pre> <p>For part 2, we use that between two points in a tree, there is exactly one path (without repetition). First, we define a function to get a path from the root of a (sub)tree to the destination, provided it exists.</p> <pre class="lang-hs prettyprint-override"><code>pathFromRoot :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; a -&gt; Maybe [a] pathFromRoot childrenMap root destination | destination == root = Just [root] | null childPaths = Nothing | otherwise = Just $ root:(head childPaths) where rootChildren = children childrenMap root pathFromNewRoot newRoot = pathFromRoot childrenMap newRoot destination childPaths = mapMaybe pathFromNewRoot rootChildren </code></pre> <p>This function only finds paths down from the root of a (sub)tree. General paths come in three variations: path from the root of a (sub)tree, the inverse of such a path or the concatenation of a path to the root of a subtree and one from that root to the end point. Thus, we get the path as follows.</p> <pre class="lang-hs prettyprint-override"><code>path :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; a -&gt; a -&gt; Maybe [a] path childrenMap root start end = let maybeStartEndPath = pathFromRoot childrenMap start end in if isJust maybeStartEndPath then maybeStartEndPath else let maybeEndStartPath = pathFromRoot childrenMap end start in case maybeEndStartPath of Just endStartPath -&gt; Just $ reverse endStartPath Nothing -&gt; let rootPathToStart = pathFromRoot childrenMap root start rootPathToEnd = pathFromRoot childrenMap root end in if isNothing rootPathToStart || isNothing rootPathToEnd then Nothing else connectedPath (fromJust rootPathToStart) (fromJust rootPathToEnd) </code></pre> <p>To connect the paths in the last alternative, we follow both paths from the root to the last common point and then build it by concatenation the reverse of the path to the start with the path to the destination. </p> <pre class="lang-hs prettyprint-override"><code>connectedPath :: Eq a =&gt; [a] -&gt; [a] -&gt; Maybe [a] connectedPath rootToStart rootToEnd = case pathPieces of Nothing -&gt; Nothing Just (middle, middleToStart, middleToEnd) -&gt; Just $ (reverse middleToStart) ++ [middle] ++ middleToEnd where pathPieces = distinctPathPieces rootToStart rootToEnd distinctPathPieces :: Eq a =&gt; [a] -&gt; [a] -&gt; Maybe (a, [a], [a]) distinctPathPieces [x] [y] = if x == y then Just (x, [], []) else Nothing distinctPathPieces (x1:y1:z1) (x2:y2:z2) | x1 /= x2 = Nothing | y1 /= y2 = Just (x1, y1:z1, y2:z2) | otherwise = distinctPathPieces (y1:z1) (y2:z2) distinctPathPieces _ _ = Nothing </code></pre> <p>This solution heavily depends on the input describing a tree. In case a DAG is provided, a result will be produced that is not necessary correct. For <code>totalDescendantCount</code>, nodes after joining branches will be counted multiple times and <code>path</code> will find a path, but not nescesarily the shortest one. If there are cycles in the graph provided, the recursions in the functions will not terminate.</p>
[]
[ { "body": "<h2>Simplification</h2>\n\n<p>In <code>path</code>, notice how the code gets more nested as you try each possible path (either from start to end, or end to start, or from end to root and root to start). You can use the Alternative instance for <code>Maybe</code> to simplify this code:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>let maybeStartEndPath = pathFromRoot childrenMap start end\n maybeEndStartPath = pathFromRoot childrenMap end start\n maybeRootPath = [...] -- see below\nin \n maybeStartEndPath\n &lt;|&gt; fmap reverse maybeEndStartPath\n &lt;|&gt; maybeRootPath\n\n</code></pre>\n\n<p>This code will try <code>maybeStartEndPath</code> first. If it returns <code>Nothing</code>, it will move on to the next option and so on.</p>\n\n<p>For your final case (which I've named <code>maybeRootPath</code>), you do the following check:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>if isNothing rootPathToStart || isNothing rootPathToEnd\n then Nothing\n else connectedPath (fromJust rootPathToStart) (fromJust rootPathToEnd)\n\n</code></pre>\n\n<p>This is more consicely done with <code>liftA2</code> from <code>Control.Applicative</code>. <code>liftA2</code> lifts a binary function into an applicative context:</p>\n\n<pre><code>λ :set -XTypeApplications\nλ :t liftA2 @Maybe\nliftA2 @Maybe :: (a -&gt; b -&gt; c) -&gt; (Maybe a -&gt; Maybe b -&gt; Maybe c)\n</code></pre>\n\n<p>Then, if either argument is <code>Nothing</code>, the function will return <code>Nothing</code> without having to pattern match. So we can fill in <code>maybeRootPath</code> above with</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code> maybeRootPath = join $ liftA2 connectedPath rootPathToStart rootPathToEnd\n where\n rootPathToStart = pathFromRoot childrenMap root start\n rootPathToEnd = pathFromRoot childrenMap root end\n\n</code></pre>\n\n<p>The <code>join</code> is needed because <code>connectedPath</code> returns a <code>Maybe</code> already, and we've lifted it into <code>Maybe</code>, which leaves us with a return value of <code>Maybe (Maybe [a])</code>. <code>join</code> flattens nested monads, bringing us back to <code>Maybe [a]</code></p>\n\n<hr>\n\n<h2>Minor points</h2>\n\n<p>Your function <code>applyToSecondElement</code> is <code>second</code> from <code>Control.Arrow</code></p>\n\n<pre><code>λ :t second @(-&gt;)\nsecond @(-&gt;) :: (b -&gt; c) -&gt; (d, b) -&gt; (d, c)\n</code></pre>\n\n<hr>\n\n<p><code>toSingleElementList</code> can also be written as <code>(:[])</code> or <code>return</code></p>\n\n<p>So <code>orbitMap</code> can be written</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>orbitMap = Map.fromListWith (++) . map (second (:[]))\n</code></pre>\n\n<p>To your credit, your naming made both of these functions clear anyway, but it's more recognizable if you use functions that already exist.</p>\n\n<hr>\n\n<h2>Algorithm</h2>\n\n<p>I was going to suggest keeping each edge bidirectional instead of one-directional, so that you can directly check for a path from start to end instead of checking 3 cases. After reviewing the code, I think your approach is better from a functional perspective because it eliminates the need for you to check for cycles and keep a set as you search the graph. Good work.</p>\n\n<hr>\n\n<h2>Revised Code</h2>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Control.Applicative\nimport Control.Monad\nimport Control.Arrow\nimport System.IO\nimport Data.List.Split\nimport Data.List\nimport Data.Maybe\nimport Data.Hashable\nimport qualified Data.HashMap.Strict as Map\n\n\nmain :: IO ()\nmain = do\n inputText &lt;- readFile \"Advent20191206_1_input.txt\"\n let orbitList = catMaybes $ (map orbit . lines) inputText\n let orbits = orbitMap orbitList\n let pathToSanta = fromJust $ path orbits \"COM\" \"YOU\" \"SAN\"\n let requiredTransfers = length pathToSanta - 3\n print requiredTransfers\n\ntype OrbitSpecification = (String,String)\ntype ChildrenMap a = Map.HashMap a [a]\n\nchildren :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; [a]\nchildren childrenMap = fromMaybe [] . flip Map.lookup childrenMap\n\norbit :: String -&gt; Maybe OrbitSpecification\norbit str =\n case orbit_specification of\n [x,y] -&gt; Just (x, y)\n _ -&gt; Nothing\n where orbit_specification = splitOn \")\" str\n\norbitMap :: [OrbitSpecification] -&gt; ChildrenMap String\norbitMap = Map.fromListWith (++) . map (second (:[]))\n\nchildrenAggregate :: (Eq a, Hashable a) =&gt; ([a] -&gt; b) -&gt; ChildrenMap a -&gt; a -&gt; b\nchildrenAggregate aggregatorFnc childrenMap = aggregatorFnc . children childrenMap\n\ndecendantAggregate :: (Eq a, Hashable a) =&gt; (b -&gt; b -&gt; b) -&gt; (ChildrenMap a -&gt; a -&gt; b) -&gt; ChildrenMap a -&gt; a -&gt; b\ndecendantAggregate resultFoldFnc nodeFnc childrenMap node =\n foldl' resultFoldFnc nodeValue childResults\n where\n nodeValue = nodeFnc childrenMap node\n childFnc = decendantAggregate resultFoldFnc nodeFnc childrenMap\n childResults = map childFnc $ children childrenMap node\n\nchildrenCount :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; Int\nchildrenCount = childrenAggregate length\n\ndecendantCount :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; Int\ndecendantCount = decendantAggregate (+) childrenCount\n\ntotalDecendantCount :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; Int\ntotalDecendantCount = decendantAggregate (+) decendantCount\n\npathFromRoot :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; a -&gt; Maybe [a]\npathFromRoot childrenMap root destination\n | destination == root = Just [root]\n | null childPaths = Nothing\n | otherwise = Just $ root:(head childPaths)\n where\n rootChildren = children childrenMap root\n pathFromNewRoot newRoot = pathFromRoot childrenMap newRoot destination\n childPaths = mapMaybe pathFromNewRoot rootChildren\n\npath :: (Eq a, Hashable a) =&gt; ChildrenMap a -&gt; a -&gt; a -&gt; a -&gt; Maybe [a]\npath childrenMap root start end =\n let maybeStartEndPath = pathFromRoot childrenMap start end\n maybeEndStartPath = pathFromRoot childrenMap end start\n\n maybeRootPath = join $ liftA2 connectedPath rootPathToStart rootPathToEnd\n where\n rootPathToStart = pathFromRoot childrenMap root start\n rootPathToEnd = pathFromRoot childrenMap root end\n in\n maybeStartEndPath\n &lt;|&gt; fmap reverse maybeEndStartPath\n &lt;|&gt; maybeRootPath\n\nconnectedPath :: Eq a =&gt; [a] -&gt; [a] -&gt; Maybe [a]\nconnectedPath rootToStart rootToEnd =\n case pathPieces of\n Nothing -&gt; Nothing\n Just (middle, middleToStart, middleToEnd) -&gt;\n Just $ (reverse middleToStart) ++ [middle] ++ middleToEnd\n where pathPieces = distinctPathPieces rootToStart rootToEnd\n\ndistinctPathPieces :: Eq a =&gt; [a] -&gt; [a] -&gt; Maybe (a, [a], [a])\ndistinctPathPieces [x] [y] = if x == y then Just (x, [], []) else Nothing\ndistinctPathPieces (x1:y1:z1) (x2:y2:z2)\n | x1 /= x2 = Nothing\n | y1 /= y2 = Just (x1, y1:z1, y2:z2)\n | otherwise = distinctPathPieces (y1:z1) (y2:z2)\ndistinctPathPieces _ _ = Nothing\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-13T20:38:00.443", "Id": "461171", "Score": "1", "body": "Thank you very much! I already had the feeling that there had to be some function to apply a function to the second element, but did not know `Arrow`. I will need some time to look things up in order to fully understand your simplifications. But now I know some directions to look into to improve my Haskell." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T04:53:03.573", "Id": "235493", "ParentId": "234762", "Score": "1" } } ]
{ "AcceptedAnswerId": "235493", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T22:13:21.910", "Id": "234762", "Score": "2", "Tags": [ "haskell" ], "Title": "AdventOfCode 2019 day 6 in Haskell" }
234762
<p>I wrote a bunch of functions and macros for safer and simpler allocation. They are documented in their files.</p> <hr> <p>Disclaimer:</p> <p>The library requires POSIX extensions, GCC extensions, and LIBBSD extensions, but if someone wants to make it portable, it shouldn't be difficult to get rid of the extensions I used. But to me, they are of great help and make my life much easier.</p> <p>I use <code>goto</code> because it is cleaner to me (the way I use it), but if someone wants to get rid of it, it should be easy.</p> <p>I acknowledge some inconsistency in the parameter <code>nmemb</code> which is sometimes <code>ptrdiff_t</code> and some others <code>size_t</code>. I would like it to always be <code>ptrdiff_t</code>, but in the macros that call standard functions (instead of mine) those standard functions accept <code>size_t</code>, and the code to reject negative values of <code>ptrdiff_t</code> inside a macro would make the macros too long and dangerous. In functions and in macros that call functions of mine, I consistently use <code>ptrdiff_t</code>.</p> <hr> <p><code>libalx/base/stdlib/alloc/README.rst</code>:</p> <pre><code>&lt;libalx/base/stdlib/alloc/&gt; ============================ The following functions are added to the C / POSIX / GNU / BSD allocation functions (some of them may be implemented as macros; only when necessary). 1) Headers ---------- .. code-block:: c &lt;libalx/base/stdlib/alloc/callocs.h&gt; &lt;libalx/base/stdlib/alloc/callocs.hpp&gt; &lt;libalx/base/stdlib/alloc/mallocarray.h&gt; &lt;libalx/base/stdlib/alloc/mallocarray.hpp&gt; &lt;libalx/base/stdlib/alloc/mallocarrays.h&gt; &lt;libalx/base/stdlib/alloc/mallocarrays.hpp&gt; &lt;libalx/base/stdlib/alloc/mallocs.h&gt; &lt;libalx/base/stdlib/alloc/mallocs.hpp&gt; &lt;libalx/base/stdlib/alloc/reallocarrayf.h&gt; &lt;libalx/base/stdlib/alloc/reallocarrayf.hpp&gt; &lt;libalx/base/stdlib/alloc/reallocarrayfs.h&gt; &lt;libalx/base/stdlib/alloc/reallocarrayfs.hpp&gt; &lt;libalx/base/stdlib/alloc/reallocarrays.h&gt; &lt;libalx/base/stdlib/alloc/reallocarrays.hpp&gt; &lt;libalx/base/stdlib/alloc/reallocfs.h&gt; &lt;libalx/base/stdlib/alloc/reallocfs.hpp&gt; &lt;libalx/base/stdlib/alloc/reallocs.h&gt; &lt;libalx/base/stdlib/alloc/reallocs.hpp&gt; 2) Functions ------------ .. code-block:: c [[gnu::nonnull]] int callocs(type **restrict ptr, size_t nmemb); [[gnu::malloc]] [[gnu::warn_unused_result]] void *mallocarray(ptrdiff_t nmemb, size_t size); [[gnu::nonnull]] [[gnu::warn_unused_result]] int mallocarrays(type **restrict ptr, ptrdiff_t nmemb); [[gnu::nonnull]] [[gnu::warn_unused_result]] int mallocs(void **restrict ptr, size_t size); [[gnu::warn_unused_result]] void *reallocarrayf(void *ptr, ptrdiff_t nmemb, size_t size); [[gnu::nonnull]] [[gnu::warn_unused_result]] int reallocarrayfs(type **restrict ptr, ptrdiff_t nmemb); [[gnu::nonnull]][[gnu::warn_unused_result]] int reallocarrays(type **restrict ptr, ptrdiff_t nmemb); [[gnu::nonnull]] [[gnu::warn_unused_result]] int reallocfs(void **restrict ptr, size_t size); [[gnu::nonnull]] [[gnu::warn_unused_result]] int reallocs(void **restrict ptr, size_t size); To be able to use any of those functions, the corresponding headers should be included. 3) When to use each of the functions ------------------------------------ Functions ending in ``s`` should always be preferred. Reallocation functions ending in ``f`` (or ``fs``) free the memory upon failure to ease error handling. Functions containing ``array`` (and ``callocs()``) should be used when allocating arrays, or single elements (arrays of size 1). The other funtions should be used when and only when dealing with buffers of bytes. 4) More info ------------ For more detailed documentation about each of the functions, read the corresponding headers. </code></pre> <p><code>libalx/base/stdlib/alloc/callocs.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/callocs.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]] * int callocs(type **restrict ptr, size_t nmemb); * * Safe &amp; simple wrapper for `calloc()`. * * Features: * - Safely computes the element size (second argument to `calloc()`) * so the user can't make mistakes. * - Returns non-zero on error. * - Doesn't cast * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/callocs.h&gt; * * int *arr; * * if (callocs(&amp;arr, 7)) // int arr[7]; * goto err; * * // `arr` has been succesfully allocated here * free(arr); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;stdlib.h&gt; /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /* * callocs() * * ptr: Memory will be allocated, and a pointer to it will be stored * in *ptr. * nmemb: Number of elements in the array. * * return: * 0: OK. * != 0: Failed. */ #define alx_callocs(ptr, nmemb) ( \ { \ __auto_type ptr_ = (ptr); \ \ *ptr_ = calloc(nmemb, sizeof(**ptr_)); \ \ !(*ptr_); \ } \ ) /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) #define callocs(ptr, nmemb) alx_callocs(ptr, nmemb) #endif /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* prototypes *********************************************************** ******************************************************************************/ /****************************************************************************** ******* inline *************************************************************** ******************************************************************************/ /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/mallocarray.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/mallocarray.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::malloc]] [[gnu::warn_unused_result]] * void *mallocarray(ptrdiff_t nmemb, size_t size); * * Almost equivalent to `reallocarray(NULL, nmemb, size)`. * * Features: * - It fails safely if (nmemb &lt; 0). With `reallocarray()` the array would be * be allocated (it uses `size_t` instead of `ptrdiff_t`), and it's usage * would likely produce undefined behavior. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/mallocarray.h&gt; * * int *arr; * * arr = mallocarray(7, sizeof(*arr)); // int arr[7]; * if (!arr) * goto err; * * // `arr` has been succesfully allocated here * free(arr); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;errno.h&gt; #include &lt;stddef.h&gt; #include &lt;stdlib.h&gt; /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* prototypes *********************************************************** ******************************************************************************/ /* * mallocarray() * * nmemb: Number of elements in the array. * size: Size of each element in the array. * * return: * != NULL: OK. * NULL: Failed. */ __attribute__((malloc, warn_unused_result)) inline void *alx_mallocarray (ptrdiff_t nmemb, size_t size); /****************************************************************************** ******* static inline ******************************************************** ******************************************************************************/ /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) __attribute__((always_inline, malloc, warn_unused_result)) static inline void *mallocarray (ptrdiff_t nmemb, size_t size) { return alx_mallocarray(nmemb, size); } #endif /****************************************************************************** ******* inline *************************************************************** ******************************************************************************/ inline void *alx_mallocarray (ptrdiff_t nmemb, size_t size) { if (nmemb &lt; 0) goto ovf; return reallocarray(NULL, nmemb, size); ovf: errno = ENOMEM; return NULL; } /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/mallocarrays.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/mallocarrays.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]] [[gnu::warn_unused_result]] * int mallocarrays(type **restrict ptr, ptrdiff_t nmemb); * * Safe &amp; simple wrapper for `mallocarray()`. * * Features: * - Safely computes the element size (second argument to `mallocarray()`) * so the user can't make mistakes. * - Returns non-zero on error. * - Doesn't cast * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/mallocarrays.h&gt; * * int *arr; * * if (mallocarrays(&amp;arr, 7)) // int arr[7]; * goto err; * * // `arr` has been succesfully allocated here * free(arr); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;errno.h&gt; #include &lt;stddef.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include "libalx/base/stdlib/alloc/mallocarray.h" /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /* * mallocarrays() * * ptr: Memory will be allocated, and a pointer to it will be stored * in *ptr. * nmemb: Number of elements in the array. * * return: * 0: OK. * != 0: Failed. */ #define alx_mallocarrays(ptr, nmemb) ( \ { \ __auto_type ptr_ = (ptr); \ \ *ptr_ = alx_mallocarray(nmemb, sizeof(**ptr_)); \ \ !(*ptr_); \ } \ ) /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) #define mallocarrays(ptr, nmemb) alx_mallocarrays(ptr, nmemb) #endif /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* function prototypes ************************************************** ******************************************************************************/ /****************************************************************************** ******* inline functions ***************************************************** ******************************************************************************/ /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/mallocs.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/mallocs.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]] [[gnu::warn_unused_result]] * int mallocs(void **restrict ptr, size_t size); * * Safe &amp; simple wrapper for `malloc()`. * To be used for generic buffers of bytes, and not for arrays (use * `mallocarray()` family of functions for that purpose). * * Features: * - Returns non-zero on error. * - Doesn't cast * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/mallocs.h&gt; * * char *buf; * * if (mallocs(&amp;buf, 7)) // char buf[7]; * goto err; * * // `buf` has been succesfully allocated here * free(buf); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;stddef.h&gt; #include &lt;stdlib.h&gt; /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* prototypes *********************************************************** ******************************************************************************/ /* * mallocs() * * ptr: Memory will be allocated, and a pointer to it will be stored * in *ptr. * size: Size of the buffer (in bytes). * * return: * 0: OK. * != 0: Failed. */ __attribute__((nonnull, warn_unused_result)) inline int alx_mallocs (void **restrict ptr, size_t size); /****************************************************************************** ******* static inline ******************************************************** ******************************************************************************/ /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) __attribute__((always_inline, nonnull, warn_unused_result)) static inline int mallocs (void **restrict ptr, size_t size) { return alx_mallocs(ptr, size); } #endif /****************************************************************************** ******* inline *************************************************************** ******************************************************************************/ inline int alx_mallocs (void **restrict ptr, size_t size) { *ptr = malloc(size); return !(*ptr); } /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/reallocarrayf.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/reallocarrayf.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::warn_unused_result]] * void *reallocarrayf(void *ptr, ptrdiff_t nmemb, size_t size); * * Almost equivalent to `reallocarray()`. * * Features: * - Upon failure, the passed pointer is freed, to ease error handling and to * avoid memory leaks. * - It fails safely if (nmemb &lt; 0). With `reallocarray()` the array would be * be allocated (it uses `size_t` instead of `ptrdiff_t`), and it's usage * would likely produce undefined behavior. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/reallocarrayf.h&gt; * * int *arr; * * arr = mallocarray(5, sizeof(*arr); // int arr[5]; * arr = reallocarrayf(arr, 7, sizeof(*arr)); // int arr[7]; * if (!arr) * goto err; * * // `arr` has been succesfully reallocated here * free(arr); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;errno.h&gt; #include &lt;stddef.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; /****************************************************************************** ******* _Static_assert ******************************************************* ******************************************************************************/ _Static_assert(sizeof(size_t) == sizeof(ptrdiff_t), "sizeof(size_t) != sizeof(ptrdiff_t)"); /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* prototypes *********************************************************** ******************************************************************************/ /* * reallocarrayf() * * ptr: Pointer to allocated memory (or NULL). * nmemb: Number of elements in the array. * size: Size of each element in the array. * * return: * != NULL: OK. * NULL: Failed. */ __attribute__((warn_unused_result)) inline void *alx_reallocarrayf (void *ptr, ptrdiff_t nmemb, size_t size); /****************************************************************************** ******* static inline ******************************************************** ******************************************************************************/ /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) __attribute__((always_inline, warn_unused_result)) static inline void *reallocarrayf (void *ptr, ptrdiff_t nmemb, size_t size) { return alx_reallocarrayf(ptr, nmemb, size); } #endif /****************************************************************************** ******* inline *************************************************************** ******************************************************************************/ inline void *alx_reallocarrayf (void *ptr, ptrdiff_t nmemb, size_t size) { if (!size) goto out; if (nmemb &lt; 0) goto ovf; if ((size_t)nmemb &gt; (SIZE_MAX / size)) goto ovf; return reallocf(ptr, size * (size_t)nmemb); ovf: errno = ENOMEM; out: free(ptr); return NULL; } /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/reallocarrayfs.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/reallocarrayfs.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]] [[gnu::warn_unused_result]] * int reallocarrayfs(type **restrict ptr, ptrdiff_t nmemb); * * Safe &amp; simple wrapper for `reallocarrayf()`. * * Features: * - Safely computes the element size (second argument to `reallocarrayf()`) * so the user can't make mistakes. * - Returns non-zero on error. * - Doesn't cast. * - Upon failure, the passed pointer is freed, to ease error handling and to * avoid memory leaks. * - It fails safely if (nmemb &lt; 0). With `reallocarray()` the array would be * be allocated (it uses `size_t` instead of `ptrdiff_t`), and it's usage * would likely produce undefined behavior. * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/reallocarrayfs.h&gt; * * int *arr; * * if (mallocarrays(&amp;arr, 5)) // int arr[5]; * goto err; * if (reallocarrayfs(&amp;arr, 7)) // int arr[7]; * goto err; * * // `arr` has been succesfully reallocated here * free(arr); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include "libalx/base/stdlib/alloc/reallocarrayf.h" /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /* * reallocarrayfs() * * ptr: Pointer to a pointer to the memory to be reallocated. * A pointer to the reallocated memory will be stored * in *ptr. * nmemb: Number of elements in the array. * * return: * 0: OK. * != 0: Failed. */ #define alx_reallocarrayfs(ptr, nmemb) ( \ { \ __auto_type ptr_ = (ptr); \ \ *ptr_ = alx_reallocarrayf(*ptr_, nmemb, sizeof(**ptr_)); \ \ !(*ptr_); \ } \ ) /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) #define reallocarrayfs(ptr, nmemb) alx_reallocarrayfs(ptr, nmemb) #endif /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* function prototypes ************************************************** ******************************************************************************/ /****************************************************************************** ******* inline functions ***************************************************** ******************************************************************************/ /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/reallocarrays.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/reallocarrays.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]][[gnu::warn_unused_result]] * int reallocarrays(type **restrict ptr, size_t nmemb); * * Safe &amp; simple wrapper for `reallocarray()`. * * Features: * - Safely computes the element size (second argument to `reallocarray()`) * so the user can't make mistakes. * - Returns non-zero on error. * - Doesn't cast. * - Upon failure, the pointer is untouched (no memory leak). * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/reallocarrays.h&gt; * * int *arr; * * if (mallocarrays(&amp;arr, 5)) // int arr[5]; * goto err; * if (reallocarrays(&amp;arr, 7)) // int arr[7]; * goto err; * * // `arr` has been succesfully reallocated here * err: * free(arr); * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;stdlib.h&gt; #include "libalx/base/stdlib/alloc/reallocs.h" /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /* * reallocarrays() * * ptr: Pointer to a pointer to the memory to be reallocated. * A pointer to the reallocated memory will be stored * in *ptr. * nmemb: Number of elements in the array. * * return: * 0: OK. * != 0: Failed. */ #define alx_reallocarrays(ptr, nmemb) ( \ { \ __auto_type ptr_ = (ptr); \ __auto_type nmemb_ = (nmemb); \ void *vp_; \ \ vp_ = reallocarray(*ptr_, nmemb_, sizeof(**ptr_)); \ \ alx_reallocs__(ptr_, vp_, nmemb_); \ } \ ) /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) #define reallocarrays(ptr, nmemb) alx_reallocarrays(ptr, nmemb) #endif /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* function prototypes ************************************************** ******************************************************************************/ /****************************************************************************** ******* inline functions ***************************************************** ******************************************************************************/ /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/reallocfs.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/reallocfs.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]] [[gnu::warn_unused_result]] * int reallocfs(void **restrict ptr, size_t size); * * Safe &amp; simple wrapper for `reallocf()`. * To be used for generic buffers of bytes, and not for arrays (use * `reallocarray()` family of functions for that purpose). * * Features: * - Returns non-zero on error. * - Doesn't cast. * - Upon failure, the passed pointer is freed, to ease error handling and to * avoid memory leaks. * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/reallocfs.h&gt; * * char *buf; * * if (mallocs(&amp;buf, 5)) // char buf[5]; * goto err; * if (reallocfs(&amp;buf, 7)) // char buf[7]; * goto err; * * // `buf` has been succesfully reallocated here * free(buf); * err: * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;stddef.h&gt; #include &lt;stdlib.h&gt; /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* prototypes *********************************************************** ******************************************************************************/ /* * reallocfs() * * ptr: Pointer to a pointer to the memory to be reallocated. * A pointer to the reallocated memory will be stored * in *ptr. * size: Size of the buffer (in bytes). * * return: * 0: OK. * != 0: Failed. */ __attribute__((nonnull, warn_unused_result)) inline int alx_reallocfs (void **restrict ptr, size_t size); /****************************************************************************** ******* static inline ******************************************************** ******************************************************************************/ /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) __attribute__((always_inline, nonnull, warn_unused_result)) static inline int reallocfs (void **restrict ptr, size_t size) { return alx_reallocfs(ptr, size); } #endif /****************************************************************************** ******* inline *************************************************************** ******************************************************************************/ inline int alx_reallocfs (void **restrict ptr, size_t size) { *ptr = reallocf(*ptr, size); return !*ptr; } /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p><code>libalx/base/stdlib/alloc/reallocs.h</code>:</p> <pre><code>/****************************************************************************** ******* include guard ******************************************************** ******************************************************************************/ #pragma once /* libalx/base/stdlib/alloc/reallocs.h */ /****************************************************************************** ******* about **************************************************************** ******************************************************************************/ /* * [[gnu::nonnull]] [[gnu::warn_unused_result]] * int reallocs(void **restrict ptr, size_t size); * * Safe &amp; simple wrapper for `reallocf()`. * To be used for generic buffers of bytes, and not for arrays (use * `reallocarray()` family of functions for that purpose). * * Features: * - Returns non-zero on error. * - Doesn't cast. * - Upon failure, the pointer is untouched (no memory leak). * - The pointer stored in `*ptr` is always a valid pointer or NULL. * * example: * #define ALX_NO_PREFIX * #include &lt;libalx/base/stdlib/alloc/reallocs.h&gt; * * char *buf; * * if (mallocs(&amp;buf, 5)) // char buf[5]; * goto err; * if (reallocs(&amp;buf, 7)) // char buf[7]; * goto err; * * // `buf` has been succesfully reallocated here * err: * free(buf); * // No memory leaks */ /****************************************************************************** ******* headers ************************************************************** ******************************************************************************/ #include &lt;stdbool.h&gt; #include &lt;stddef.h&gt; #include &lt;stdlib.h&gt; /****************************************************************************** ******* macros *************************************************************** ******************************************************************************/ /****************************************************************************** ******* enum ***************************************************************** ******************************************************************************/ /****************************************************************************** ******* struct / union ******************************************************* ******************************************************************************/ /****************************************************************************** ******* prototypes *********************************************************** ******************************************************************************/ /* * reallocs() * * ptr: Pointer to a pointer to the memory to be reallocated. * A pointer to the reallocated memory will be stored * in *ptr. * size: Size of the buffer (in bytes). * * return: * 0: OK. * != 0: Failed. */ __attribute__((nonnull, warn_unused_result)) inline int alx_reallocs (void **restrict ptr, size_t size); /* * alx_reallocs__() * * This function safely assigns the result of a reallocation to the pointer * provided. If the reallocation failed, this function doesn't assign the * pointer, and keeps the old one. This function is only to be used within * this library, and should not be called directly by the user. * * ptr: Pointer to a pointer to the memory to be reallocated. * A pointer to the reallocated memory will be stored * in *ptr. * vp: Result of `realloc()`. * size: `size` passed to `realloc()`. * * return: * 0: OK. * != 0: Reallocation failed. */ __attribute__((nonnull(1), warn_unused_result)) inline int alx_reallocs__ (void **restrict ptr, void *restrict vp, size_t size); /****************************************************************************** ******* static inline ******************************************************** ******************************************************************************/ /* Rename without alx_ prefix */ #if defined(ALX_NO_PREFIX) __attribute__((always_inline, nonnull, warn_unused_result)) static inline int reallocs (void **restrict ptr, size_t size) { return alx_reallocs(ptr, size); } #endif /****************************************************************************** ******* inline *************************************************************** ******************************************************************************/ inline int alx_reallocs (void **restrict ptr, size_t size) { void *vp; vp = realloc(*ptr, size); return alx_reallocs__(ptr, vp, size); } inline int alx_reallocs__ (void **restrict ptr, void *restrict vp, size_t size) { bool failed; failed = !vp &amp;&amp; size; if (!failed) *ptr = vp; return failed; } /****************************************************************************** ******* end of file ********************************************************** ******************************************************************************/ </code></pre> <p>Any comments?</p>
[]
[ { "body": "<p>If you want people to use your library, then you want to think about how to make it easy for others to adopt it.</p>\n\n<p>I would consider revamping the implementation into a <a href=\"https://github.com/nothings/single_file_libs\" rel=\"nofollow noreferrer\">Single-file library</a>. Simply put, the more files, the more tedious it becomes to add someone else's code to your project. Which is why, single-file libraries are popular in the C/C++ world because they are easy to manage (package management facilities are lacking in these languages). Personally, I've used hashmaps, bignum libraries, red-black trees etc, all delivered as single-file C libraries. But if I have to add more than one (or two) files to use someone else's code, likely I won't bother.</p>\n\n<p>For me, the other dealbreaker would be Windows compatiblity. Windows compatiblity is very important for me and I can see that you are using several features not available on MSVC.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T11:48:47.583", "Id": "459213", "Score": "0", "body": "I would like to add Windows (x64) compatibility in the future, but that's something I may need help and time; mainly because I don't use Windows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T11:53:43.137", "Id": "459214", "Score": "1", "body": "For the single-file library: My library currently has over 47 k lines of code, so I don't see it fitting in one header & one source. What I did some time ago was to have a dummy header <libalx.h> to include all of the headers, but as I did it when I started writing the library, I realized that I had to continuously update that file and sometimes I forgot it. However, when I release the first stable version of the library, I could do that; it's a nice addition. I still prefer to include each header, because then I know where to go for documentation, but I can see the benefit of having that. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T12:00:13.353", "Id": "459215", "Score": "1", "body": "The idea I have for this library is to install it in the system (via apt-get or similar) and use it just by including the headers. That way, I ease the installation part. The separation into tiny files helps me organize and maintain the code and easily find a function. But then if I have a dummy header to include them all, the user could also be happy by ignoring the details of the library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:16:43.543", "Id": "459244", "Score": "0", "body": "@CacahueteFrito So these allocation functions are just one part of a much larger \"libalx\" library containing lots of other utility routines?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:50:56.557", "Id": "459252", "Score": "0", "body": "Exactly. It's a big library where I put all the code I repeatedly use." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T00:49:26.000", "Id": "234770", "ParentId": "234764", "Score": "2" } }, { "body": "<h2>Portability</h2>\n\n<p>While <code>#pragma once</code> is widely supported it is not part of the C programming standard. To make this library more portable, use include guards such as shown in the example below.</p>\n\n<h2>Ease of Use</h2>\n\n<p>Don't force the users of the library to include files in the proper order, functions that are written using other functions in the library need to include the header for the other function. There is no guarantee that the user of the library wants to include one header file that includes all the other header files.</p>\n\n<h2>Useless Comments</h2>\n\n<p>In the comments after another answer there is a statement that the is 47 KLOC (K lines of code). Comments don't count as lines of code and it appears that each file is about 70% comments. I agree with the author of the other answer that this could all be in a single file.</p>\n\n<p>There are a lot of boiler plate comments that are not useful, comments such as <code>include guard</code> really don't help anyone. The <code>About</code> comments don't need a header comment and should include the comment block that describes the entry point, here is one example:</p>\n\n<pre><code>#ifndef MALLOCARRAY_H\n#define MALLOCARRAY_H\n/*\n * About:\n * [[gnu::malloc]] [[gnu::warn_unused_result]]\n * void *mallocarray(ptrdiff_t nmemb, size_t size);\n *\n * Almost equivalent to `reallocarray(NULL, nmemb, size)`.\n *\n * Features:\n * - It fails safely if (nmemb &lt; 0). With `reallocarray()` the array would be\n * be allocated (it uses `size_t` instead of `ptrdiff_t`), and it's usage\n * would likely produce undefined behavior.\n *\n * example:\n * #define ALX_NO_PREFIX\n * #include &lt;libalx/base/stdlib/alloc/mallocarray.h&gt;\n *\n * int *arr;\n *\n * arr = mallocarray(7, sizeof(*arr)); // int arr[7];\n * if (!arr)\n * goto err;\n *\n * // `arr` has been succesfully allocated here\n * free(arr);\n * err:\n * // No memory leaks\n *\n * Parameters:\n * nmemb: Number of elements in the array.\n * size: Size of each element in the array.\n *\n * return:\n * != NULL: OK.\n * NULL: Failed.\n*/\n\n#include &lt;errno.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;stdlib.h&gt;\n#include \"reallocArray.h\"\n__attribute__((malloc, warn_unused_result))\ninline\nvoid *alx_mallocarray (ptrdiff_t nmemb, size_t size);\n\n#if defined(ALX_NO_PREFIX)\n__attribute__((always_inline, malloc, warn_unused_result))\nstatic inline\nvoid *mallocarray (ptrdiff_t nmemb, size_t size)\n{\n return alx_mallocarray(nmemb, size);\n}\n#endif\n\ninline\nvoid *alx_mallocarray (ptrdiff_t nmemb, size_t size)\n{\n\n if (nmemb &lt; 0)\n goto ovf;\n\n return reallocarray(NULL, nmemb, size);\n ovf:\n errno = ENOMEM;\n return NULL;\n}\n\n#endif // MALLOCARRAY_H\n</code></pre>\n\n<h2>Opinionated Summary</h2>\n\n<p>It is not clear who would benefit from this library, the C programming language has been around for almost 50 years. If a library like this was beneficial it would have been written before this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:32:47.837", "Id": "459219", "Score": "0", "body": "*\"Portability\"*: I've had many issues with header guards (more than once I forgot to change the name after copy&paste), and as you said, `#pragma once` is implemented by [most compilers](https://stackoverflow.com/q/23696115/6872717). Even MSVC has that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:35:20.127", "Id": "459220", "Score": "0", "body": "*\"Ease of use\"*: All of my headers include internally all they need. There's no proper order, and you can include any of the headers separately and it will work. If some header (or some source) needs some other header it will be included so the user doesn't have to care." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:40:55.780", "Id": "459221", "Score": "0", "body": "*\"Useless comments\"*: Although there are a lot of comments in these files, the rest of the library is mostly uncommented (yet). While I don't have a program to count LOC without comments or blank lines, I guess there will be at least 15 kLOC, which is still too much, and there are also C and C++ files, and although it would probably be possible to have a C header + a C++ header + a C source + a C++ source, it would be much more difficult to maintain such huge files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:46:56.097", "Id": "459222", "Score": "0", "body": "*\"Opinionated Summary\"*: I do benefit from this library. It makes my programs much shorter and easier to write and I hope someone might want to use it too, although I don't need that. There are many programs out there that have bugs still waiting to bite because the standard library is sometimes difficult to use safely (for example `strtol()` or `realloc()`). And even if someone knows how to use them safely, that means writing the same 4 or 5 lines for every `realloc()` call, while with this library I wrote them once and forgot about them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:52:28.073", "Id": "459223", "Score": "2", "body": "`more than once I forgot to change the name after copy&paste` It's obvious you use copy and paste which in and of itself is a rather bad programming practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:58:16.407", "Id": "459224", "Score": "0", "body": "I don't think it's the cause, but rather the symptom: The cause is having to write almost the same thing for every file. The cure: pragma once. With `realloc()` it's also the same: You have to take the element size & check that you don't overflow the multiplication & check that the function didn't fail before updating the pointer; in the end you have to write almost the same code for every call, and you either write a function/macro for not repeating yourself or copy&paste every time or write the same code every time. Again copy&paste is not bad in itself, but rather a symptom. IMHO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:06:16.697", "Id": "459228", "Score": "3", "body": "@CacahueteFrito If you don't want to accept a review, don't request one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:14:13.310", "Id": "459231", "Score": "0", "body": "@JL2210 It's not that I don't accept it. It's just that I feel a part of it is wrong (I think that the part of the include order is because he didn't understand that I don't require that; which may be a problem of mine becuase I should have explained that), and for the other part, I partially disagree, but give my reasons for that, so that he can give me counter arguments and maybe make me change my mind (it wouldn't be the first time). :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:32:05.443", "Id": "459235", "Score": "2", "body": "You want to look at the third answer on this question https://stackoverflow.com/questions/1143936/pragma-once-vs-include-guards. No experienced professional programmer enjoys fixing copy and paste and they will refactor it if they are allowed to because copy and paste code generally creates bugs, your experience with #include guards is just one example. Object Oriented Design and Programming and inheritance is/was in part an effort to reduce copy & paste errors. Writing a function for each memory allocation is effectively implementing the Single Responsibility Principle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:36:58.853", "Id": "459236", "Score": "0", "body": "One way to see how much code is comments and macros is to run the c pre-processor on the code and then look at the resulting c code. If you have any more comments ping me on https://chat.stackexchange.com/rooms/8595/the-2nd-monitor." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:15:13.303", "Id": "234786", "ParentId": "234764", "Score": "5" } }, { "body": "<h1>Use Doxygen to document your code</h1>\n\n<p>It's already mentioned by others, but you have a lot of comments. It's good to document all the functions, but you are not using a standard code documentation language as far as I can tell. I recomment that you use <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">Doxygen</a>. The advantage is that it understands C and C++, and will perform checks on your documentation, such as that you documented all the parameters and the return value. Furthermore, it allows the creation of a manual in PDF and HTML formats (amongs others), which are much nicer for a developer to read than having to read the source files.</p>\n\n<h1>Avoid (complex) macros</h1>\n\n<p>It's always better to use functions than macros. If you cannot avoid macros, for example to allow arbitrary type arguments to be passed, it is better to create a simple macro to deal with the parameter type, and then call a regular function to do the main work. For example:</p>\n\n<pre><code>static inline int alx_callocs_impl(void **ptr, size_t nmemb, size_t size) {\n *ptr = calloc(nmemb, size);\n return !*ptr;\n}\n\n#define alx_callocs(ptr, nmemb) alx_callocs_impl((ptr), (nmemb), sizeof(ptr))\n</code></pre>\n\n<h1>About the disclaimers</h1>\n\n<blockquote>\n <p>The library requires POSIX extensions, GCC extensions, and LIBBSD extensions</p>\n</blockquote>\n\n<p>That's a lot of requirements for such a low-level library, making it much less useful. Even if this library is only for your personal use, consider that in the future you might want to port your projects to platforms that don't support POSIX, libbsd or GCC.</p>\n\n<blockquote>\n <p>I use goto because it is cleaner to me (the way I use it)</p>\n</blockquote>\n\n<p>I think a lot of these uses of <code>goto</code> are unnecessary. For example, you can rewrite <code>alx_mallocarray()</code> like this:</p>\n\n<pre><code>inline void *alx_mallocarray(ptrdiff_t nmemb, size_t size) {\n if (nmemb &lt; 0) {\n errno = ENOMEM\n return NULL;\n }\n\n return reallocarray(NULL, nmemb, size);\n}\n</code></pre>\n\n<blockquote>\n <p>I acknowledge some inconsistency in the parameter nmemb which is sometimes ptrdiff_t and some others size_t. I would like it to always be ptrdiff_t, but in the macros that call standard functions (instead of mine) those standard functions accept size_t, and the code to reject negative values of ptrdiff_t inside a macro would make the macros too long and dangerous. In functions and in macros that call functions of mine, I consistently use ptrdiff_t.</p>\n</blockquote>\n\n<p>There is a reason that standard library and POSIX functions use unsigned types like <code>size_t</code> sometimes, and signed types like <code>int</code> or <code>ssize_t</code> at other times, and there is a consistency to it. When a parameter should never be a negative number, <code>size_t</code> is used. Doing so will make it easier to catch errors; and avoids you having to write checks like <code>if (nmemb &lt; 0)</code>.</p>\n\n<p>Another reason not to use different parameter types than those used by standard library functions is that it goes against users' expectations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T16:08:59.360", "Id": "459331", "Score": "0", "body": "There are good reasons to use `ptrdiff_t`. I'm searching for an article I read a long time ago, but while I find it, I can link you to this one, which isn't as extense, but is also good (it is C++, but it's meaningful in C too): https://www.aristeia.com/Papers/C++ReportColumns/sep95.pdf" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T16:09:37.063", "Id": "459332", "Score": "0", "body": "*\"Avoid (complex) macros\"*: Good solution :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T16:34:22.583", "Id": "459338", "Score": "1", "body": "Some words from Bjarne Stroustrup: https://www.youtube.com/watch?v=Puio5dly9N8&t=42m41s\n\nAnd from Google's C++ Coding Style: https://google.github.io/styleguide/cppguide.html#Integer_Types" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T07:45:36.323", "Id": "459478", "Score": "1", "body": "\"There is a reason the standard functions use `size_t` sometimes, and `ssize_t` at other times\" --> There a no standard C library function that uses `ssize_t` as `ssize_t` is not in the C spec. The point of the paragraph based on a false premise. OP's code used `ptrdiff_t` for `nmemb`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T12:09:12.903", "Id": "459492", "Score": "0", "body": "@chux-ReinstateMonica You are correct for the standard library. I was thinking about POSIX functions like `read()` that return `ssize_t`. I updated the answer. I don't know of any standard library or POSIX function that takes a `ptrdiff_t` argument or returns a `ptrdiff_t`; it's either `int` or `ssize_t`. C99's `calloc()` and `reallocarray()` functions use `size_t nmemb`, so that's why I pointed out it might be confusing to wrap those functions but use different argument types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T14:20:26.740", "Id": "460404", "Score": "0", "body": "There's nothing wrong with lots of comments such as these in header files, that's just your personal opinion. Doxygen doesn't really produce any complete, sensible documentation, it's just a way of writing glorified source code comments. When coding, I don't want to get handed some f-in auto-generated pdf that doesn't say more than what was written in the comments anyway. I either want brief source code comments or complete documentation written in detail, with rationales and explanations about the implementation etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T19:27:03.863", "Id": "460463", "Score": "0", "body": "@Lundin: nobody wants bad documentation. And Doxygen is not going to magically make good documentation. But the point is that if you are documenting each function, then it's good to use a standard way of doing that, so that you can use tools that help you with that." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:56:44.647", "Id": "234825", "ParentId": "234764", "Score": "4" } } ]
{ "AcceptedAnswerId": "234825", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-28T23:05:36.453", "Id": "234764", "Score": "0", "Tags": [ "c", "memory-management", "posix", "gcc" ], "Title": "Safer & simpler allocation functions and macros" }
234764
<p><strong>My Approach</strong></p> <p>The code for the library project is all over the place, how would you code this project using object-oriented programming. For example, would you use</p> <blockquote> <p><code>document.addEventListener()</code></p> </blockquote> <p>and just set if statements for elements that are dynamically created? </p> <p>Also, there is not a lot of comments in this code, I thought my naming for each variable made sense and so comments were unneeded. Do you disagree?</p> <p>I used a closure in my render function but that's actually my first time using a closure so i don't know if that is correct or would it just involve unexpected bugs. </p> <p>I did this project for <em>The Odin Project</em> Here's the link the project and steps to take <a href="https://www.theodinproject.com/courses/javascript/lessons/library" rel="nofollow noreferrer">https://www.theodinproject.com/courses/javascript/lessons/library</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/*------------------------------------------ Variables -------------------------------------------*/ let myLibrary = []; let bookIndex = 0; let mainRender = render(); /*------------------------------------------ Constructor -------------------------------------------*/ function Book(title, author, pages, status) { this.title = title; this.author = author; this.pages = pages; this.status = status; } /*------------------------------------------ Functions -------------------------------------------*/ function addBookToLibrary() { const title = document.querySelector('#title').value; const author = document.querySelector('#author').value; const pages = document.querySelector('#pages').value; const status = document.querySelector('#status').value; const book = new Book(title, author, pages, status); myLibrary.push(book); } function render() { let i = 0; return function() { const bookshelf = document.querySelector('.bookshelf__creation'); for (; i &lt; myLibrary.length; i++) { bookshelf.insertAdjacentHTML('beforeend', bookTemplate(myLibrary[i])); } } } function bookTemplate(book) { const statusBtnColor = book.status == 'unread' ? 'status__btn status__btn--change' : 'status__btn'; const HTML = ` &lt;tr class="bookshelf__book" data-index="${bookIndex++}"&gt; &lt;td class="title"&gt;${book.title}&lt;/td&gt; &lt;td class="author"&gt;${book.author}&lt;/td&gt; &lt;td class="pages"&gt;${book.pages}&lt;/td&gt; &lt;td class="status"&gt;&lt;button id="status-btn" class="${statusBtnColor}"&gt;${book.status}&lt;/button&gt;&lt;/td&gt; &lt;td class="delete"&gt;&lt;button class="btn btn--primary"&gt;x&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt;`; return HTML; } function toggleStatus(event) { const index = event.target.parentElement.parentElement.dataset.index; if (event.target.textContent == 'read') { event.target.textContent = 'unread'; myLibrary[index]['status'] = 'unread'; event.target.classList.add('status__btn--change'); } else if (event.target.textContent == 'unread') { event.target.textContent = 'read'; myLibrary[index]['status'] = 'read'; event.target.classList.remove('status__btn--change'); } } function removeBook(event) { const parentOfBookInfo = event.target.parentNode.parentNode; parentOfBookInfo.parentNode.remove(); myLibrary = myLibrary.filter( book =&gt; { console.log(`${book.title}\n${parentOfBookInfo.querySelector(".title").textContent}`); return book.title !== parentOfBookInfo.querySelector(".title").textContent; }); } function emptyInputs() { const modalInputs = document.querySelectorAll('.modal__input'); modalInputs.forEach(input =&gt; input.value = ''); } /*------------------------------------------ Event Listeners -------------------------------------------*/ document.addEventListener('click', event =&gt; { const modal = document.querySelector('.modal'); if (event.target.className == 'btn btn--primary') removeBook(event); if (event.target.id == 'status-btn') toggleStatus(event); if (event.target.className == 'bookshelf__open-modal') modal.style.display = 'block'; if (event.target.className == 'modal__add') { modal.style.display = 'none'; addBookToLibrary(); emptyInputs(); mainRender(); } if (event.target.className == 'modal__cancel') { modal.style.display = 'none'; emptyInputs(); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; -webkit-box-sizing: border-box; box-sizing: border-box; font-family: 'Roboto', sans-serif; } .background { padding: 2% 4%; margin-bottom: 2em; height: 12rem; width: 100%; color: #fff; background: linear-gradient(304deg, #020024 0%, #3a3d3d 0%, #282828 94%); display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .background__heading { margin-bottom: 0.2em; font-size: 2.5rem; } .bookshelf { max-width: 90%; margin: 0 auto; } .bookshelf__heading { font-size: 2rem; font-weight: 700; } .bookshelf__creation { text-align: left; } .bookshelf table { border-collapse: collapse; margin: 2em 0; } .bookshelf table th { padding: 0.6em 1em; } .bookshelf__book { border-top: 2px solid #ececec; } .bookshelf__book td { padding: 1em; text-align: center; } .bookshelf__open-modal { padding: 0.7rem; border: none; background-color: #383838; color: white; cursor: pointer; } .status__btn { padding: 0.4rem 2rem; border: none; background-color: #ececec; cursor: pointer; } .status__btn--change { background-color: #383838; color: white; } .delete .btn { width: 1.5rem; height: 1.5rem; color: white; border-radius: 50%; text-align: center; border: none; font-weight: 700; } .modal { padding: 1.25rem; width: 100%; position: absolute; top: 0; background: white; max-width: 50%; margin: 0 auto; -webkit-transform: translate(50%, 20%); transform: translate(50%, 20%); display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; border-radius: 6px; -webkit-box-shadow: 0 0.5em 1em -0.125em rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.02); box-shadow: 0 0.5em 1em -0.125em rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.02); color: #4a4a4a; } .modal .modal__add { padding: 0.7rem; border: none; background-color: #383838; color: white; cursor: pointer; } .modal .modal__cancel { padding: 0.7rem; border: 1.5px solid lightgray; border-radius: 5px; background-color: #fff; cursor: pointer; } .modal h2 { margin-bottom: 1em; } .modal * { -ms-flex-item-align: self-start; -ms-grid-row-align: self-start; align-self: self-start; } .modal label { font-size: 1rem; font-weight: 600; margin-bottom: 0.4em; } .modal input { width: 100%; margin-bottom: 1em; height: 3em; border: 1.5px solid lightgray; border-radius: 5px; } .modal select { width: 6rem; height: 2rem; border: 1.5px solid lightgray; border-radius: 5px; background-color: #fff; margin-bottom: 1em; cursor: pointer; } tbody:nth-child(even) { background-color: whitesmoke; border-top: 1px solid #a0a0a0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;title&gt;Librario&lt;/title&gt; &lt;!-- links --&gt; &lt;link href="https://fonts.googleapis.com/css?family=Roboto:400,700&amp;display=swap" rel="stylesheet"&gt; &lt;link rel="stylesheet" href="./index.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;header class="background"&gt; &lt;h1 class="background__heading"&gt;Librario&lt;/h1&gt; &lt;p class="background__intro-text"&gt;Your Pocket Bookshelf&lt;/p&gt; &lt;/header&gt; &lt;div class="bookshelf"&gt; &lt;h2 class="bookshelf__heading"&gt;Books&lt;/h2&gt; &lt;table class="bookshelf__creation"&gt; &lt;tr class="table"&gt; &lt;th class="table__heading"&gt;Title&lt;/th&gt; &lt;th class="table__heading"&gt;Author&lt;/th&gt; &lt;th class="table__heading"&gt;Pages&lt;/th&gt; &lt;th class="table__heading"&gt;Status&lt;/th&gt; &lt;/tr&gt; &lt;!-- JavaScript make this --&gt; &lt;!-- &lt;tr class="bookshelf__book" data-newBook=""&gt; &lt;td class="title"&gt;Harry Potter and the Sorceror Stone&lt;/td&gt; &lt;td class="author"&gt;J.K Rowling&lt;/td&gt; &lt;td class="pages"&gt;890&lt;/td&gt; &lt;td class="status"&gt;&lt;button class="status__btn"&gt;Read&lt;/button&gt;&lt;/td&gt; &lt;td class="delete"&gt;&lt;button class="btn btn--primary"&gt;x&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="bookshelf__book" data-newBook=""&gt; &lt;td class="title"&gt;Harry Potter and the Sorceror Stone&lt;/td&gt; &lt;td class="author"&gt;J.K Rowling&lt;/td&gt; &lt;td class="pages"&gt;890&lt;/td&gt; &lt;td class="status"&gt;&lt;button class="status__btn"&gt;Read&lt;/button&gt;&lt;/td&gt; &lt;td class="delete"&gt;&lt;button class="btn btn--primary"&gt;x&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; --&gt; &lt;/table&gt; &lt;button class="bookshelf__open-modal"&gt;Add New Book&lt;/button&gt; &lt;/div&gt; &lt;div class="modal" style="display: none;"&gt; &lt;h2&gt;Add New Book&lt;/h2&gt; &lt;label for="title"&gt;Title&lt;/label&gt; &lt;input class="modal__input" id="title" type="text"&gt; &lt;label for="author"&gt;Author&lt;/label&gt; &lt;input class="modal__input" id="author" type="text"&gt; &lt;label for="pages"&gt;Number of Pages&lt;/label&gt; &lt;input class="modal__input" id="pages" type="text"&gt; &lt;label for="status"&gt;Read Status&lt;/label&gt; &lt;select id="status"&gt; &lt;option value="read"&gt;Read&lt;/option&gt; &lt;option value="unread"&gt;Unread&lt;/option&gt; &lt;/select&gt; &lt;div class="modal__btn-container"&gt; &lt;button class="modal__add"&gt;Add Book&lt;/button&gt; &lt;button class="modal__cancel"&gt;Cancel&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Scripts --&gt; &lt;script src="./index.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>I agree, that your naming is mostly alright, no point to document these variables. Except for <code>event</code> variables.</p>\n\n<p>What I seriously don't like about your approach is how tightly it is bound to html.\nFor example <code>removeBook</code> takes as parameter event, which you use to extract element and use that one to extract data that you use to remove. That is bad from many reasons.</p>\n\n<p>Example:</p>\n\n<p>If you are removing book, I expect parameter to be \"book\", not some kind of event. What if I wanted to add keyboard shortcut to remove book? Or maybe drag &amp; drop?\nFirst step is to pass element, that represents the book <code>parentOfBookInfo</code>. But still, that element is both data and both it's html representation. Even that change makes your code cleaner and more flexible - you can remove that book/element based on different actions or events. Separating html and data is a bit harder and may be not worth it. It's better to keep \"database\" or \"memory\" of your <code>Book</code> objects and that then triggers UI update (or similar approach, depending on your pattern). But digging deeper and deeper into making this \"clean\" usually ends up making your own framework and then it is usually better to choose one, that is close to your mindset and what you are trying to do :)</p>\n\n<p>Having \"global\" click listener can be fine, but then again you end up making some kind of routing to make sure clicking on element, that you wanted will trigger correct function and in the end it may be easier to just attach event to element in the first place :)\nI don't like it in this case though. Again very much bound to css (and looks like visually-depended css) so if you change css for design, you break your functionality. Also theoretically it is possible with your code to trigger multiple events if your html allows it.\nEx. if element has both <code>modal__add</code> and <code>modal_cancel</code>, there will be 2 methods triggered. That seems bad and may lead to bugs hard to find in case someone messes up html. Better switch or explicit return after passing event to something to make sure it does not propagate further.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:43:36.023", "Id": "459251", "Score": "0", "body": "Thank you! Also what do you think about my way of using a constructor? Should I use more of prototype inheritance or just keep it as it is" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T07:56:51.630", "Id": "459281", "Score": "0", "body": "That depends on your targeting platform and compatibility + if you want to use babel. Imho best approach is to use modern javascript and then use babel if you need backwards compatibility. In that case you can even go further and use `class`, `constructor` keywords and other newer features. Another interesting alternative is Typescript." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T06:59:06.360", "Id": "234777", "ParentId": "234775", "Score": "3" } }, { "body": "<p>Because this question is tagged with <a href=\"/questions/tagged/object-oriented\" class=\"post-tag\" title=\"show questions tagged &#39;object-oriented&#39;\" rel=\"tag\">object-oriented</a>, I will focus on some improvements based on the oop-design.</p>\n\n<p>Currently your code uses objects, but this does not mean that it is object-oriented.</p>\n\n<p>When we take a look to your code all methods are global. With objects we can couple the methods to an object. For example:<br>\nThe methods <code>addBookToLibrary</code> and <code>removeBook</code> have a strong relationship to <code>myLibary</code> and <code>toggleStatus</code> to <code>Book</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Book(title, author, pages, status) {\n this.title = title;\n this.author = author;\n this.pages = pages;\n this.status = status;\n}\n\nBook.prototype.toggleStatus = function() {\n if (this.status === 'read') {\n this.status = 'unread';\n } else {\n this.status = 'read';\n }\n}\n\nconst zhivago = new Book('Doctor Zhivago', 'Boris Pasternak', '592', 'unread');\n\nconsole.log(zhivago.status);\n\nzhivago.toggleStatus();\n\nconsole.log(zhivago.status);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or the ES6-Version below which uses <code>class</code> to abstract the prototype change.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Book {\n constructor(title, author, pages, status) {\n this.title = title;\n this.author = author;\n this.pages = pages;\n this.status = status;\n }\n\n toggleStatus() {\n if (this.status === 'read') {\n this.status = 'unread';\n } else {\n this.status = 'read';\n }\n }\n}\n\nconst zhivago = new Book('Doctor Zhivago', 'Boris Pasternak', '592', 'unread');\n\nconsole.log(zhivago.status);\n\nzhivago.toggleStatus();\n\nconsole.log(zhivago.status);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Currently the program heavy rely on <code>string</code>s. Actually the <code>status</code> is an abstraction in <code>Book</code> and could be represent with an own datatype with to concrete types <code>Unread</code> and <code>Read</code>. The following example just shows how <a href=\"https://en.wikipedia.org/wiki/Object_composition\" rel=\"nofollow noreferrer\">composition</a> could work and is not a recommendation:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Book {\n constructor(title, author, pages, status) {\n this.title = title;\n this.author = author;\n this.pages = pages;\n this.status = status;\n }\n\n toggleStatus() {\n this.status = this.status.toggle();\n }\n}\n\nclass Unread {\n constructor() {\n this.status = 'unread';\n }\n\n toggle() {\n return new Read()\n }\n}\n\nclass Read {\n constructor() {\n this.status = 'read';\n }\n\n toggle() {\n return new Unread()\n }\n}\n\nconst zhivago = new Book('Doctor Zhivago', 'Boris Pasternak', '592', new Unread());\nconsole.log(zhivago.status)\nzhivago.toggleStatus();\nconsole.log(zhivago.status)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Possible Object Structure</h2>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Library {\n constructor() {\n this.books = [];\n }\n\n add(book) {\n this.books.push(book);\n }\n\n removeBookWithTitle(title) {\n this.books = this.books.filter(book =&gt; book.hasNot(title))\n }\n\n get(index) {\n return this.books[index];\n }\n\n numberOfBooks() {\n return this.books.length;\n }\n}\n\nclass Book {\n constructor(title, author, pages, status) {\n this.title = title;\n this.author = author;\n this.pages = pages;\n this.status = status;\n }\n\n toggleStatus() {\n this.status = this.status.toggle();\n }\n \n has(title) {\n return this.title === title;\n }\n\n hasNot(title) {\n return !this.has(title);\n }\n \n}\n\nclass Unread {\n constructor() {\n this.value = 'unread';\n }\n\n toggle() {\n return new Read()\n }\n}\n\nclass Read {\n constructor() {\n this.value = 'read';\n }\n\n toggle() {\n return new Unread()\n }\n}\n\nconst myLibrary = new Library();\nconst unread = new Unread();\n\nmyLibrary.add(new Book('title', 'author', 123, unread));\nmyLibrary.add(new Book('other title', 'other author', 321, unread));\n\nmyLibrary.removeBookWithTitle('title')\n\nconst aBook = myLibrary.get(0)\naBook.toggleStatus();\n\nconsole.log(JSON.stringify(myLibrary, null, 2))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>MVC</h1>\n\n<p><a href=\"https://codereview.stackexchange.com/users/214636/k-h\">@K.H.</a> mentions in his answer already that your Model is tightly coupled to the HTML. The <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">Model-View-Controller</a> is one of many patterns to logic is decoupled from how it gets represent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T10:09:38.503", "Id": "234817", "ParentId": "234775", "Score": "2" } } ]
{ "AcceptedAnswerId": "234817", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T06:27:07.237", "Id": "234775", "Score": "0", "Tags": [ "javascript", "object-oriented" ], "Title": "Library app with JavaScript" }
234775
<p>I am trying to analyse my running data, which comes in gpx form, import and writing of data is working wonderfully. </p> <p>Now I want to average the pace I calculated between two points overage a certain distance (for example 1000 m) and see the result as a list for each individual kilometer. If the kilometer is not finished at the end, I want the calculate the pace in the last segment as well.</p> <p>The function has the following input:</p> <pre class="lang-none prettyprint-override"><code>average_over_distance(input_datalist, input_distancelist, average_distance) input_datalist = [0, 5.3, 4.3, 4.6 ... ] input_distancelist = [0, 4.5, 7.8, 12.3 ... ] average_distance = 1000 </code></pre> <p>Where <code>input_datalist</code> is the pace at each datapoint and <code>input_distancelist</code> is the amount of meters covered from the beginning to this datapoint. I have already written some code which is working, but is surprisingly slow and has a minor bug, in which the last item needs to be removed, as it will always be a zero. </p> <p>If someone could take a look at it and suggest some improvements (especially in terms of performance), that would be very helpful.</p> <p>Typically, the files contain between 800 and 3000 datapoints. For a example, for a run of roughly 6 km "runtastic_20191117_1510", the input data is:</p> <pre><code>input_datalist = [0, 8.154297259068265, 7.699997924184752, 4.1290248509679355, 5.233554408345463, 3.736102600544462, 4.330745941935702, 5.230497758127484, 5.121644868994811, 4.015323039710534, 4.726542792381121, 3.740745581335375, 3.4118823620200422, 3.987048386430994, 3.7203695740533966, 4.410022185697186, 5.2436728280589415, 3.7116435736709072, 4.092616264885011, 4.223133016298036, 3.6989551972321575, 3.933683921646469, 5.299174480076175, 5.454088851201578, 4.885582841700339, 4.322790700547173, 5.077202464669111, 4.468306638956414, 5.10435062743631, 4.611544695366803, 4.276830319696586, 4.088270186235909, 3.9011269060681983, 5.041657604796356, 4.277273006103617, 4.406055316530598, 4.557975009670055, 4.406041751786603, 4.27732553606914, 4.745072973440513, 4.710883275762832, 4.640505059675511, 5.06935043569426, 4.490555199849174, 4.572841974069774, 5.045738092463033, 4.205832799143788, 4.505775599108849, 4.28371867045946, 4.263979223210943, 4.7588714454922725, 4.91203496026689, 4.696805096033936, 4.162071809512042, 4.535661818149418, 4.171066245852658, 4.143397024221024, 4.640261191080346, 4.399112208437336, 5.685874427165761, 4.505487986404551, 4.720550515635307, 4.846515601858323, 5.298586073902652, 4.696656283201031, 4.441343777394891, 5.337965772042491, 4.48485689638503, 5.769112947432504, 5.319572026762231, 5.116981287986407, 5.22259033813319, 4.853202942230398, 4.448933861887161, 4.789873410985746, 5.672882596467915, 5.5417906688838166, 6.457016910025886, 6.786483505021053, 5.198308170917069, 5.092476666244364, 4.111794944472009, 4.62311212962504, 4.936303165196316, 4.2158075941616495, 5.0052319036352255, 6.027735861446753, 4.451769206323267, 4.348499095726568, 4.716995991496699, 4.739598104126194, 3.803071758523529, 3.8735972911018113, 4.655091267145741, 5.07588762499882, 5.502452004107536, 4.90400116659635, 5.053913295715235, 4.58068413622591, 4.816772523066801, 5.8804125927899475, 4.6149157805783245, 4.633021535424502, 4.694860556377299, 4.162950942798815, 4.143781839386801, 4.210068875540942, 4.466337101965024, 4.806729632448732, 4.497942736910237, 4.936378303939041, 4.767575030726392, 4.467464723983651, 4.754562019764752, 4.434949315331764, 3.7991288006306982, 4.356167584044449, 4.899659810097845, 4.824108634407948, 4.634182253538913, 4.9030628045839, 4.820284931682572, 4.542769711287221, 5.007690356986818, 5.295531279293059, 4.501087763083377, 4.488216232376019, 3.639894520745288, 4.905012199105443, 5.343166287117647, 4.4175484463040045, 4.525020534675778, 4.670701777770286, 3.941406726590055, 4.655011763949892, 6.140477088073999, 7.0078624375573995, 5.545091724531036, 5.288132248589611, 4.8816938060736526, 4.419245209980266, 4.7858786837636815, 4.956721947840855, 3.8419543236293525, 4.584358093975693, 3.6157730397543, 3.679531116433433, 3.8551332359568007, 5.01671434928462, 6.037315646638342, 4.200679939449504, 5.553716753945233, 4.8052903165724645, 5.62792540716035, 4.496031477404894, 3.3585767502392505, 4.426144671921158, 4.16635108522084, 4.543574826368433, 4.023584939710059, 4.4773033732429965, 4.056618759180805, 4.288378568522181, 4.016701064525987, 3.6309957856654416, 4.68751694219872, 4.200361225258804, 4.4642917645643445, 4.611021161957354, 4.608897935198266, 4.375182381141827, 4.3219335803397305, 4.981445645654108, 4.833516446559961, 4.336397398785247, 4.203682658060733, 3.784297284926399, 4.424894795321563, 4.088044358642628, 5.20713570393957, 6.0627377944839695, 3.735901221369735, 3.772403843344582, 4.9605949817268975, 6.184966776447468, 5.575863638814157, 3.965755781299144, 5.054754982298068, 5.055491060388767, 4.734832940836844, 4.6680405144198405, 4.518231790785486, 5.352054360203661, 3.933386810266203, 4.073500276584424, 3.6496806936814843, 4.160556562775662, 4.231158566179572, 4.126957725155156, 5.593731232209662, 6.557381777970839, 4.642808962883382, 3.955271250935829, 4.328041504215481, 3.8714835731936508, 4.617792757235988, 4.316975631278537, 4.639702196406146, 3.816561586325325, 4.071972083203815, 4.105020127529573, 5.418019364469931, 5.979515822345107, 4.572346964592393, 5.072186750588375, 4.605953060201322, 4.52944254464933, 5.45304404918759, 4.214181255790554, 5.065635658544667, 4.646521009104833, 3.766190012573553, 4.747353072646974, 3.9823024273203877, 4.008735954584001, 4.498706648060665, 4.335661856552447, 5.4356808518186295, 5.975294162959008, 6.343006329478395, 4.713236251049612, 6.188658480557391, 5.124416742172999, 5.619545161380488, 4.049275101887822, 4.454425726867608, 4.429777695304846, 4.573400986105693, 3.7655872110826647, 6.033389303976118, 5.409110541159138, 4.522967609924991, 3.8649484408364314, 3.547691073057468, 3.8216406348013447, 3.7081335110051663, 5.148494271933852, 5.0951639784476335, 5.1868397841911404, 3.915056916229462, 4.406991109627597, 3.9763203810458996, 4.28549379742172, 4.054115252910068, 4.776024139760099, 5.520744481502811, 4.888183596040763, 4.124802660905125, 4.864276535037368, 5.177312990215, 4.86043806706891, 4.135061226941825, 3.570930298137865, 3.700051516827064, 4.826854581084116, 4.878739859154471, 3.926577500254844, 4.101678697318054, 5.533643097300404, 5.603894439072506, 5.5836491017136645, 4.132822241747506, 4.327310749268595, 4.901185832428964, 4.404933049474804, 4.353807464674405, 4.005766544385017, 4.506879230892712, 4.906734585665481, 5.123709595337477, 3.9234155679802045, 4.188877024821228, 4.932978861075624, 4.727035002624785, 4.6932702535094615, 5.883208720833115, 5.60566192288835, 4.560563955425492, 5.669761784806086, 5.275740020308531, 3.8030108229859043, 3.262000519242214, 4.002520224062654, 4.718094076517959, 4.478663977565892, 4.390544097105828, 4.19771623465651, 4.5480069304831785, 4.594856759883293, 3.8475266675044115, 4.929983554415432, 4.382543120384308, 3.6614842492966537, 4.101811441660566, 4.5657701468204115, 4.258297327206018, 6.2327786523192685, 6.141584317657115, 4.330490431701469, 3.6629381384362287, 3.6957939483910436, 5.121599558473292, 6.042316399492867, 4.75216860990142, 5.978575732467344, 6.00395603245871, 8.042208384599991, 5.1021107749039025, 4.517556660128847, 4.935516587555954, 5.632047276257036, 6.423600308741078, 6.00440093918871, 4.845324684406579, 5.055066910344564, 4.9389227035720875, 4.680938244648393, 4.9204120831447336, 4.678421499818818, 4.177438981630106, 4.353078428831223, 4.250867676745693, 4.968408209906815, 4.407893575868392, 4.216143959716419, 4.073363509236613, 3.5906037538507043, 3.691974738042348, 5.036374082670621, 5.303505234368339, 4.595696918891344, 4.1300635347916135, 4.578008133895794, 4.8718892710481585, 4.910747946403624, 3.906923185712786, 3.7330877569388266, 3.897689856046975, 5.802573172588164, 4.008559710782361, 4.392256205143359, 4.748812027698272, 4.07431196233908, 5.260360061285357, 9.359585548001148, 13.125105261196474, 5.380398263912016, 4.130980041632252, 3.2739945880797694, 3.928870358141829, 4.365717934322635, 4.310671755409893, 4.29005790128022, 4.707968241314882, 6.345982614926924, 6.131622489289469, 5.076782565165626, 4.865378764540353, 4.119554065730303, 4.124088634945004, 5.238130249873582, 5.579928645245936, 5.522380159660524, 5.121673937886574, 5.900959324337007, 4.858015036866666, 5.187047039414815, 4.879726213161024, 4.091664395550873, 4.837767172037724, 4.257922821251948, 4.67990874895055, 5.406604825715869, 5.579957583303129, 4.6204975750040305, 5.238908190956787, 4.6220244661279235, 4.865310773483241, 5.3436658704418, 4.7078411709655885, 5.522251283593757, 5.809488123591483, 5.857531981615105, 5.414726666730081, 5.08323718554349, 5.945605891365354, 5.607541690637272, 4.133746420689716, 4.135401205340503, 5.224387695688467, 5.228290701546441, 5.538561186853402, 5.446367710527512, 4.6423440977698816, 4.853491793936539, 4.607173624287225, 6.040282575425058, 5.186394503344894, 4.849786217055432, 4.8537653697490395, 4.776660374217542, 5.032812532554486, 5.53873330719436, 5.34336505487213, 4.322361773758633, 4.360275788289467, 4.6084726720321365, 4.769621387307082, 4.134098145663927, 4.901530424054935, 5.152005831962173, 5.487658037299265, 4.719588500446772, 4.870480538873378, 4.902862677085294, 4.620710345607096, 5.2355052862068945, 5.199863591781361, 5.766644251221267, 7.598788637776362, 7.133574355872142, 5.964849017616679, 5.598263679775067, 5.612157326648779, 4.8704106527246545, 4.532958071342506, 4.13961046938866, 6.027068718261925, 5.237024579091238, 5.102538323259633, 5.210318277513763, 3.778892100015756, 5.456404694376721, 4.8019619965987985, 4.878191938028389, 6.548044633747711, 5.768001662343498, 5.045591480188853, 4.720907855592685, 9.172196383817367, 5.2545597237758095, 4.681417777704229, 5.971315496784966, 3.684618597555957, 4.801114328452435, 4.680478088477566, 5.555867415427176, 5.27830765541006, 4.372746909313776, 4.125134248904619, 4.949176280889171, 5.195891869097251, 4.573216598940454, 9.425778187394444, 14.530948232708237, 15.593075826191377, 6.853818862628895, 7.0628011743550605, 6.877345450766101, 4.419415731769701, 4.365855944753687, 4.914215523401811, 5.890169505133561, 6.696349144225213, 5.455641272726224, 4.491935561060528, 5.045477445700691, 4.366653603581333, 4.667168036633596, 5.025731647884249, 5.452353090157114, 5.646332078214436, 5.675451738912615, 4.926132948232751, 4.853437603310502, 5.8863644009082, 6.872906850875094, 5.061691654041292, 4.020451529830195, 4.759392869964344, 4.642903720505812, 4.16820169937677, 3.8732898979294474, 4.591339181786737, 4.77128676701023, 4.394301688749651, 3.5827652905733913, 3.596804035306872, 3.6349118606187116, 4.187996663638694, 4.59958514622361, 4.467786796658763, 5.33258780981264, 5.446587239227867, 5.400921522256128, 4.994677705240711, 5.280729520522615, 5.596505350164431, 5.480381222725426, 5.276506641778495, 4.927198227898725, 5.5007019344073, 6.3927226627934415, 4.893321707184026, 5.469610714372455, 5.480731726644543, 5.809071390656785, 5.344346764147256, 8.784779754402654, 5.64251223436406, 5.200250666831702, 4.813288290089864, 4.204272390177281, 4.597767286104216, 5.542276227351737, 5.159232715823571, 4.97802276508083, 5.168328146529712, 5.869873943518415, 4.7577037646608495, 4.5594698514444385, 4.6486154469728485, 4.361110487388936, 4.445216263055807, 4.735657362747071, 5.855672069800528, 6.711408602885964, 6.277830805653751, 8.069971890956039, 6.523580156999423, 5.352097060441109, 4.5193744659476565, 4.670852116926712, 4.31749071218104, 5.9038388477506745, 5.156765629067522, 5.972383637211377, 4.863313642890077, 4.741459973381345, 5.013307214865355, 3.756380102752061, 3.6573548432696996, 3.9542882382964577, 4.846262971576997, 4.628820794382232, 4.634623072909339, 6.663578270926263, 5.1653246237832455, 4.057144047002918, 4.441839529076168, 4.847284940314969, 6.549024398459078, 5.516858945171008, 5.050030579321399, 7.508700305495534, 5.289871902784273, 7.261676530493964, 6.273114030218404, 5.891465813903992, 5.754975587418065, 5.611277253106119, 3.974445324538755, 3.866515171739321, 3.8148723957045867, 4.331822088552902, 4.236060975349821, 3.8929893685590025, 4.273716116286058, 5.122359735401137, 5.3881856603291105, 6.168689308793071, 7.496764045470881, 5.355983664117728, 4.457117100223586, 4.519838111870202, 4.76018042036791, 5.296781862809513, 5.209190890406699, 6.780529324328974, 5.735678685893203, 4.885659099536959, 4.295766299476571, 5.461881703955669, 4.234657086287799, 4.104718261660021, 5.047180653459006, 4.093515224120995, 3.5354341296045817, 4.024620321747599, 4.588147410590329, 5.051399703901492, 5.247352666742633, 4.684998126730578, 4.992099870242227, 4.61345790705681, 5.014806567272018, 4.618044173779868, 5.65158462801022, 5.548525993892823, 5.646393201598026, 6.159491988943552, 4.789419901289577, 4.6736512810108275, 4.363105511327151, 4.739391667120165, 4.897441960035855, 5.461516912637022, 5.243873127366143, 5.125065202894813, 4.351851614609344, 5.3655333223312445, 4.243655718883197, 3.7754875890613078, 4.719243395600352, 3.8813961449106613, 4.218969588152745, 4.257677718939865, 6.103674486703634, 7.791663380655756, 10.464238426233472, 8.594965185662373, 6.75186715111778, 6.031324685806287, 6.145523302453469, 6.75140945728926, 8.154059132392755, 4.106360394477029, 4.709620377998221, 6.028553163902719, 4.097065935296995, 5.0426994603803985, 3.2005053600326656, 4.092894804323027, 3.842959298407252, 5.233649653441752, 5.620989567976742, 6.240709912225148, 5.402477404353037, 4.949452795156887, 6.66384694626282, 6.878195322360906, 5.223144951942625, 4.420158019516105, 5.5748343085937835, 5.351436065486316, 2.803141976997137, 2.853987131694524, 3.628310473460109, 3.2999520776521822, 3.072156740561856, 4.022257331264973, 4.246632301136313, 3.2032110524464987, 3.890465629743822, 5.516141415478659, 4.606479518381352, 4.617117217288059, 5.2150682654367415, 4.3625251186388665, 4.610699586240319, 4.339292661652301, 5.338621562017436, 6.245388897091721, 5.252203657075473, 4.663563296139489, 5.613802045800598, 4.457795237559685, 4.511612941820016, 7.5219824401326605, 9.17922567246037, 6.09564157037004, 5.575136863116195, 8.148782813497581, 10.337371026863684, 11.397323448389315, 13.452285184002244, 19.5321880505188, 9.104925253521232, 5.54880509500184, 5.297901295579736, 5.988140824070068, 5.712105550155605, 6.082955341897327, 5.514548951533992, 5.464177314396885, 5.965901886583051, 5.349768122904307, 5.455309858192952, 5.298726867437543, 5.27469020516504, 4.649991348964344, 4.657421878443319, 5.590467970089882, 4.839346013516856, 4.563686472478843, 4.460033351195948, 4.796752890700532, 4.936679285281038, 4.9476732954772, 6.1392458938730945, 6.376675176853506, 7.1893167742280895, 7.830862993334671, 7.201136642310429, 8.819884427914946, 14.75778834627489, 10.720082995027086, 13.683835023100594, 9.083588248964963, 6.438601514845196, 5.770584825015614, 5.971641604445405, 5.947097347049473, 5.8707122742282944, 5.913629995689299, 8.46564700833827, 4.691928546549967, 4.93123094432014, 6.5383321864315365, 7.965339881360501, 9.553183457183184, 5.975672597974902, 7.285598168392091, 6.283135292771771, 5.087462116591565, 4.299544221293388, 4.452401951635002, 4.928524696311035, 4.3192558539968635, 5.270743879168626, 4.434409547593456, 6.315079614095595, 7.744781172450392, 8.08815578671949, 8.311096077776098, 7.919508946141913, 7.023719658943078, 4.2348297914384405, 5.297799056675912, 5.433120928375736, 6.883671910111391, 6.1792032956470955, 13.600344019383114, 6.080828732734664, 6.3592677654039225, 5.167408049888382, 5.908986243562096, 6.049967830296147, 5.389658284884827, 5.1795190101266915, 5.225140621772348, 4.885351697184914, 5.609925213863514, 6.063650915495623, 6.064491470070761, 5.417789742021097, 6.642258468903965, 4.4894790182232285, 5.328546012050812, 5.071869409181481, 4.934339573713094, 4.860577415921298, 6.361065045926173, 6.190369858616081, 7.752494922626216, 6.127335665675411, 5.952050620062956, 6.068822834066873, 4.265677036952063, 5.22676808371028, 4.947280614722526, 6.131532273754776, 5.640349902998796, 4.9605101666572144, 5.678809739479061, 4.719745254190277, 5.8758917407168365, 5.913293582954954, 5.485515502725772, 5.827580748165716, 5.104395243299189, 6.156313145512767, 5.704854390030226, 5.543713820717527, 6.963449964818909, 5.42907727323174, 4.9077764911701145, 5.223678986534636, 4.959746320310088, 5.887911278350437, 6.204625494405663, 4.813010715023378, 5.8089148090748335, 4.269984326680447, 4.503035786380268, 5.164840548106424, 4.593358661615181, 4.537538610033516, 4.23346846152204, 4.599166460471844, 4.658141927517007, 4.874112991746525, 6.166375609977758, 10.015845685546097, 6.486143999799107, 5.53486556416923, 5.270831174465323, 4.915667196745372, 6.0476493575518235, 6.313789492784983, 4.394310739262499, 4.966348552199283, 5.477472022486794, 4.400604850729746, 5.013639016806944, 5.014571233503277, 4.959505331690136, 4.5459152890121555, 4.760725343443551, 4.389542691319214, 4.5899672203500135, 4.871417868900642, 4.417547567530365, 5.431557397676423, 5.0063916174177425, 4.677939660871351, 4.912490579012375, 4.704522676025109, 4.676469616096843, 4.564527258579771, 4.31847476550115, 4.884535624222552, 4.361030312218816, 4.1987006350092715, 4.488650239277422, 4.964672710238733, 7.1043549698253825, 10.07783045950558, 13.138767501869758, 10.456322266224637, 9.166881106821982, 0] input_distancelist = [0.0, 4.087824158760445, 8.416829654805763, 16.489760803553693, 22.858918498786547, 31.78087190779509, 39.47777534665958, 45.85065511351118, 52.35898089281798, 60.66051304942781, 67.71288405240794, 76.62376361065739, 86.39354163829078, 94.75394515051694, 103.71362850181802, 111.27216946368478, 117.62903695453325, 126.60978434358435, 134.75453361297863, 142.64756781405455, 151.65912149772066, 160.13294247502517, 166.42323041679043, 172.53485313558602, 179.35764878011392, 187.0687168475811, 193.63401211900094, 201.09395970691278, 207.62433658857995, 214.85257257788373, 222.64650659949302, 230.7999142303188, 239.3444538302696, 245.9560359618332, 253.74916333195128, 261.3145094156179, 268.62769855391167, 276.1930679287745, 283.98609959125736, 291.0109300880504, 298.08674398155756, 305.26987015094574, 311.8453345533723, 319.2683216562706, 326.5577345689296, 333.1639699149783, 341.089471218815, 348.4873836536744, 356.2687847907752, 364.0862087481631, 371.0906705654512, 377.8767243299224, 384.97374723203956, 392.9825790972546, 400.3317454746838, 408.32330719262035, 416.3682358196568, 423.5517394977272, 431.1290259487073, 436.99150739467007, 444.3898920832804, 451.45121538083384, 458.3290088455969, 464.6199953216893, 471.717243091887, 479.2224791204489, 485.4670551924642, 492.899473685059, 498.6773694615957, 504.9435377107775, 511.4577951327448, 517.8403239499004, 524.7086403442719, 532.201072097167, 539.160198252126, 545.0361057412193, 551.05100874369, 556.2133513235237, 561.1250752389611, 567.5374179161081, 574.0830214638444, 582.1897811110265, 589.3999314164306, 596.1526231004325, 604.0593723030042, 610.7190703899448, 616.2490627617958, 623.7367225636532, 631.4022026751912, 638.4688470805338, 645.5017921955034, 654.2666368920637, 662.8719024445528, 670.0325210920518, 676.5995170139406, 682.6574223456819, 689.4545931050169, 696.0501422137825, 703.3270756023389, 710.2473387398869, 715.9158752256096, 723.1388311620137, 730.3335599320968, 737.4335223128868, 745.4406628704747, 753.4848443996515, 761.4023712427368, 768.8656084709943, 775.8003303884307, 783.2111257860241, 789.9637146843942, 796.9553893027283, 804.4167427532398, 811.4275532537163, 818.9436105890502, 827.7175519536598, 835.3695379459859, 842.1727313564011, 849.082470721635, 856.2753974365647, 863.0738690576441, 869.9890895904058, 877.326757016186, 883.9831856204079, 890.2778011321084, 897.6834184157178, 905.1102738984999, 914.2680484283256, 921.0638181390335, 927.302316351919, 934.8479796849883, 942.2144287602789, 949.3511150484037, 957.8083323937884, 964.9690733378777, 970.3975331880208, 975.1540953537805, 981.1654176166511, 987.4688404068477, 994.297071479403, 1001.8398376644643, 1008.8047725355505, 1015.5296470966207, 1024.2057870310082, 1031.476888600743, 1040.695756313634, 1049.7548815876291, 1058.4013618240147, 1065.045816941952, 1070.5670345300855, 1078.5022578305548, 1084.504244393815, 1091.4410434501328, 1097.363889067618, 1104.777834788606, 1114.7026737344358, 1122.2336822766545, 1130.2342882389257, 1137.5706554403384, 1145.8551414976243, 1153.300098998726, 1161.5171229075897, 1169.2900685094562, 1177.5887526280533, 1186.7689707557988, 1193.8800561650598, 1201.8158815728566, 1209.2825381202442, 1216.5115948004316, 1223.7439817619145, 1231.3627117780638, 1239.0753090944513, 1245.7668070459374, 1252.6630975006967, 1260.349969866839, 1268.2795249842825, 1277.0878534066046, 1284.6209891929236, 1292.7748472260105, 1299.176319211485, 1304.674385343202, 1313.5968196791698, 1322.4329185481022, 1329.1525425964517, 1334.5419544620527, 1340.5201016142348, 1348.925393107604, 1355.5198439662643, 1362.1133346747158, 1369.1533577863743, 1376.2941127199197, 1383.6716300490025, 1389.8997680853406, 1394.1369986122663, 1402.3199692935111, 1411.453188369646, 1419.4649369975978, 1427.3429998997478, 1435.4199746480365, 1441.379026298819, 1446.4623559663573, 1453.6419176497723, 1462.0694896716523, 1469.7712026290874, 1478.3811664073494, 1485.5996222986626, 1493.321077358964, 1500.5054465107498, 1509.2393114253803, 1517.4253531398674, 1525.5454919693434, 1531.6978017141046, 1537.2723890759723, 1544.5625911519437, 1551.1343786220061, 1558.3713897025916, 1565.7306470515364, 1571.843440755871, 1579.753241333986, 1586.3335277146512, 1593.5073537380388, 1602.3580312721115, 1609.3794878234246, 1617.7498549519107, 1626.0650280416266, 1633.4745650354876, 1641.1627414745603, 1647.2950612781008, 1652.8735871923507, 1658.1287188447377, 1665.2010003001624, 1670.5871972341272, 1677.092002563289, 1683.0236807287056, 1691.2556068129059, 1698.7388011408027, 1706.2636332263187, 1713.5521551456961, 1722.4042495110127, 1727.9290601363384, 1734.091502756006, 1741.4612953806952, 1750.085817503976, 1759.481599900724, 1768.203857307605, 1777.1931057352588, 1783.6674905889129, 1790.2096418276822, 1796.6361625455438, 1805.150300154924, 1812.714039791365, 1821.0969994472882, 1828.8751773910733, 1837.0972754948227, 1844.0765813688938, 1850.1144143903307, 1856.9335799716587, 1865.0147746550472, 1871.8674552321552, 1878.305801416041, 1885.163893808819, 1893.2250400661346, 1902.559675735365, 1911.568559309483, 1918.4743677968493, 1925.3067331812808, 1933.7958902986866, 1941.922644194629, 1947.9464033614597, 1953.8946476932801, 1959.8644593211461, 1967.9299727605141, 1975.6329863097415, 1982.434061492972, 1990.001335038096, 1997.657469032029, 2005.9788060255833, 2013.37490688066, 2020.168291106233, 2026.6739941936341, 2035.1699928345565, 2043.1275750542818, 2049.884817335686, 2056.936453999012, 2064.0388221842677, 2069.7046645697837, 2075.6510334004174, 2082.960070979789, 2088.8392127494944, 2095.1574417003185, 2103.922426835744, 2114.1411049557205, 2122.4691911282616, 2129.5341908490673, 2136.976886595009, 2144.5689600592764, 2152.509785848817, 2159.8390036452797, 2167.0934916685756, 2175.7570660148854, 2182.5184137892566, 2190.124347699705, 2199.228123945564, 2207.3546148404844, 2214.6553181745203, 2222.483173012267, 2227.8312424998508, 2233.258723685365, 2240.9560812616146, 2250.0562440472095, 2259.0755058888617, 2265.5838892469837, 2271.100537355006, 2278.114878820896, 2283.6903427482516, 2289.2422377243515, 2293.3870362348157, 2299.9202799850873, 2307.2988998544356, 2314.052667720879, 2319.9711786456464, 2325.1603765613345, 2330.711860159936, 2337.591344096401, 2344.185388037762, 2350.934498184642, 2358.055577675798, 2364.8300780164336, 2371.9549882740116, 2379.934358763901, 2387.5917749759683, 2395.433311308817, 2402.142368198882, 2409.704559245377, 2417.6106776445163, 2425.793923077375, 2435.0774128797752, 2444.1060048118557, 2450.724522973171, 2457.0096743702743, 2464.2628361695897, 2472.3337370292334, 2479.6149240342393, 2486.4568967226214, 2493.2447289830297, 2501.7765919731264, 2510.705750756328, 2519.2578250784086, 2525.002402930663, 2533.317941612467, 2540.907055675144, 2547.926355057581, 2556.1076955247445, 2562.4443973749953, 2566.0058086321906, 2568.5454708040347, 2574.740799048955, 2582.8099092836687, 2592.991151932846, 2601.475354844825, 2609.110601517834, 2616.843348343546, 2624.6132512447134, 2631.693446272542, 2636.946113251952, 2642.3824122725714, 2648.948250558034, 2655.7993786914226, 2663.8908693725684, 2671.973463197271, 2678.3370570262214, 2684.310849067762, 2690.346893738649, 2696.855182578897, 2702.5039816132944, 2709.3654946140514, 2715.7917585519035, 2722.6227428893917, 2730.7693869224604, 2737.659617921174, 2745.4881612585405, 2752.6108072590223, 2758.7761058905753, 2764.749866951605, 2771.9640971924473, 2778.3267460723937, 2785.538593083939, 2792.389816959504, 2798.6277319305195, 2805.7081180614086, 2811.744303599065, 2817.4820437620874, 2823.172722607368, 2829.328773574473, 2835.8862746543227, 2841.4926558949196, 2847.43703137571, 2855.500741613594, 2863.561225150303, 2869.9415581720737, 2876.317128169257, 2882.335538404113, 2888.455825374253, 2895.636105989244, 2902.5040136212247, 2909.7391074231195, 2915.2576130422026, 2921.684685512651, 2928.5578407078447, 2935.4253612396533, 2942.403737494589, 2949.026939355918, 2955.045162564108, 2961.2834287111946, 2968.995261981538, 2976.640038356202, 2983.8730927118513, 2990.8617676247154, 2998.9247918101223, 3005.7253888582904, 3012.195360830476, 3018.2695974368335, 3025.332360076029, 3032.176311728702, 3038.975060853193, 3046.188958899199, 3052.5557432898386, 3058.9661678605944, 3064.746537150112, 3069.1332012517587, 3073.80594056454, 3079.394235127384, 3085.348462230648, 3091.287948847506, 3098.131998704921, 3105.4855485963412, 3113.5378360228574, 3119.0684405159395, 3125.4333778634586, 3131.9660741846965, 3138.363636014497, 3147.184563537988, 3153.2935923216646, 3160.235199389139, 3167.0683321885026, 3172.1589103989104, 3177.9379193667737, 3184.5443466735055, 3191.605135477897, 3195.239306829935, 3201.5830035591785, 3208.7033536146864, 3214.2855964808155, 3223.3322135052867, 3230.275046158905, 3237.3968257513343, 3243.3964889615786, 3249.7116444071253, 3257.334617797681, 3265.4151628956215, 3272.1502904080617, 3278.5656150863106, 3285.8544308710375, 3289.390832075334, 3291.6847865234204, 3293.822487494344, 3298.6859561680035, 3303.4055189180303, 3308.2523502386266, 3315.794825388387, 3323.4298307012373, 3330.212873320064, 3335.872020022766, 3340.8498568433083, 3346.9597404787983, 3354.3804465152543, 3360.9870231360132, 3368.6206337585722, 3375.762723580857, 3382.3952570443907, 3388.508825403254, 3394.4123629337414, 3400.2856105388246, 3407.0522434502022, 3413.9202277651952, 3419.583032692493, 3424.432994150808, 3431.0184078052966, 3439.3093505230518, 3446.313044953006, 3453.492460107818, 3461.4895139304094, 3470.0954624165147, 3477.355508345067, 3484.341743916529, 3491.9273253568463, 3501.2311258098193, 3510.49861244688, 3519.6689402599072, 3527.6281952475583, 3534.875225636962, 3542.336041215329, 3548.586914997847, 3554.706955285324, 3560.878741562161, 3567.552512183708, 3573.864771352406, 3579.820869175551, 3585.903171113801, 3592.220482091751, 3598.985652030438, 3605.045484708306, 3610.259747095651, 3617.0717523812214, 3623.166031311483, 3629.2479442741783, 3634.986096052954, 3641.223216285674, 3645.0176578385913, 3650.92519192072, 3657.335139338436, 3664.2604119014704, 3672.1888547424273, 3679.438750454652, 3685.4531264918533, 3691.914035539646, 3698.610134554531, 3705.0596734360192, 3710.73838709394, 3717.7445680127535, 3725.055359490577, 3732.2259533402016, 3739.8692665352523, 3747.367964317488, 3754.4067618444265, 3760.099248195437, 3765.065915449015, 3770.3756051117743, 3774.5061440756945, 3779.615812774648, 3785.843901121496, 3793.219553124775, 3800.3560097067625, 3808.0765435898556, 3813.7225874933124, 3820.186587552854, 3825.7678320539017, 3832.6218693998303, 3839.652052828662, 3846.301023638688, 3855.1748150073818, 3864.2888700449107, 3872.7185371112887, 3879.596689107751, 3886.7979472281318, 3893.9901897921877, 3898.9925071625366, 3905.445796309138, 3913.661756340914, 3921.1661547135104, 3928.0428565669745, 3933.132673203049, 3939.174758684047, 3945.775378781245, 3950.2146734630337, 3956.516023277533, 3961.106331478863, 3966.4200135150513, 3972.0779150265334, 3977.8700044675747, 3983.8104226343803, 3992.1973371875956, 4000.818364612231, 4009.5560968023997, 4017.2510881136586, 4025.1200337042214, 4033.6824340032163, 4041.482047366937, 4047.989464857154, 4054.175839164697, 4059.579472199971, 4064.0258350748263, 4070.249403969677, 4077.7280796660507, 4085.102975073431, 4092.105510773697, 4098.398640110848, 4104.797586518191, 4109.713623561749, 4115.525199690537, 4122.347888841422, 4130.10746676292, 4136.210369597522, 4144.081923929813, 4152.202659923969, 4158.807007107478, 4166.949967743588, 4176.3783242371255, 4184.660679010621, 4191.925775431977, 4198.524606505984, 4204.877016082835, 4211.991924655188, 4218.66914149775, 4225.894379920831, 4232.541362787702, 4239.759425690303, 4245.6574765074365, 4251.665078052428, 4257.56855167589, 4262.980253386546, 4269.940038500471, 4277.0722208840325, 4284.712039184735, 4291.745290638626, 4298.551564935563, 4304.654875401599, 4311.011500080289, 4317.51548237392, 4325.175057259569, 4331.387549351381, 4339.242412125712, 4348.071293838873, 4355.134572957812, 4363.722548028855, 4371.6233713547535, 4379.452365358939, 4384.913556548925, 4389.191633219446, 4392.377085612214, 4396.255325094666, 4401.192231077453, 4406.718932933146, 4412.142935364318, 4417.080176031501, 4421.168119568838, 4429.285608082064, 4436.363319374688, 4441.892562034921, 4450.028465596091, 4456.638681730372, 4467.053703604603, 4475.197898588096, 4483.8717696195035, 4490.240811404983, 4496.17096532721, 4501.512238003262, 4507.682246841518, 4514.41699807825, 4519.419113763399, 4524.265346208263, 4530.647197303729, 4538.188405827532, 4544.167656777098, 4550.396514400627, 4562.287932533161, 4573.967499326983, 4583.154511733213, 4593.255668522451, 4604.105809367556, 4612.3930298480145, 4620.242386931371, 4630.648611431588, 4639.216566145926, 4645.259437570468, 4652.495621558766, 4659.715133597257, 4666.106868400471, 4673.74770310671, 4680.977263981335, 4688.659007512467, 4694.902816508124, 4700.240087554424, 4706.586629979226, 4713.734240339941, 4719.67198681931, 4727.149524830137, 4734.537865488608, 4738.9693213712335, 4742.600709739137, 4748.069097758433, 4754.048024222796, 4758.138614694556, 4761.363161172254, 4764.287824448178, 4766.765718194661, 4768.472302897158, 4772.1333250807775, 4778.140624447511, 4784.432424062794, 4789.998982083498, 4795.834541850496, 4801.314334395371, 4807.358950850187, 4813.459289732951, 4819.046598067387, 4825.277397714688, 4831.387652530603, 4837.678471847632, 4843.99795830784, 4851.166430425698, 4858.323465842141, 4864.2859959043235, 4871.17397895828, 4878.478015625643, 4885.951801292379, 4892.9009467023825, 4899.6531239063415, 4906.39029739025, 4911.819845890108, 4917.047230445359, 4921.6837396408955, 4925.940401181482, 4930.56930006079, 4934.3486390765975, 4936.607333438598, 4939.716762101491, 4942.152726381758, 4945.822348167744, 4950.999455845006, 4956.775877879188, 4962.357815902481, 4967.962791134621, 4973.640693879005, 4979.2773896745875, 4983.214871747783, 4990.319270930896, 4997.078908374307, 5002.177048447781, 5006.361845811085, 5009.851084082571, 5015.429256712817, 5020.004493030124, 5025.309700029515, 5031.861755370551, 5039.614515109188, 5047.101110815375, 5053.864459968983, 5061.581838716641, 5067.906056720303, 5075.423028929472, 5080.70139996678, 5085.005373518919, 5089.126626152068, 5093.137328593887, 5097.346343768947, 5102.092167200395, 5109.963400514358, 5116.255321551138, 5122.390530719636, 5127.232907545349, 5132.627346235659, 5135.078264630505, 5140.559973588018, 5145.801667217381, 5152.25235448874, 5157.893480048924, 5163.403151218812, 5169.587835213865, 5176.023439228092, 5182.402852864241, 5189.225971321105, 5195.167821178739, 5200.665059360467, 5206.161535610428, 5212.314106108835, 5217.332479526459, 5224.757246007833, 5231.012861190276, 5237.585059850004, 5244.3404387280425, 5251.1983345048175, 5256.438547125294, 5261.823255001341, 5266.122946089954, 5271.563048469208, 5277.163359263101, 5282.655912637079, 5290.470225123603, 5296.8476523978725, 5303.585360631793, 5309.02173963872, 5314.931538482158, 5321.651277423001, 5327.521052052287, 5334.5835801206695, 5340.256477921415, 5345.893494393828, 5351.970103477654, 5357.690029940076, 5364.220349741838, 5369.634845812043, 5375.477822872349, 5381.490639264271, 5386.277538502685, 5392.417317263559, 5399.20925927504, 5405.590457932012, 5412.311231774181, 5417.972548964183, 5423.344885032394, 5430.27055698847, 5436.008863441382, 5443.815293344428, 5451.217706941529, 5457.671600923901, 5464.928454957941, 5472.2745816133975, 5480.148346030518, 5487.396036154331, 5494.551965246234, 5501.390816415622, 5506.796476959458, 5510.124536753893, 5515.263696990602, 5521.286125710302, 5527.610238972517, 5534.391278452856, 5539.903061852088, 5545.182511439602, 5552.768077256673, 5559.479916545232, 5565.565448921571, 5573.140165230809, 5579.78869601286, 5586.435990822559, 5593.1570912356065, 5600.489681311339, 5607.4914154859935, 5615.085220963556, 5622.347436951842, 5629.1900717309545, 5636.735736565067, 5642.8727118177985, 5649.530867208073, 5656.6565113484085, 5663.441935726776, 5670.527316248631, 5677.655200329947, 5684.957891593467, 5692.676666194079, 5699.5009246083355, 5707.144378321542, 5715.083342356128, 5722.509479737396, 5729.223584629867, 5733.915542376195, 5737.223132582963, 5739.760153907725, 5742.948017908532, 5746.584296479717, 5746.584296479717] average_distance = 1000 </code></pre> <p>Running the function leads to a resulting average pace of </p> <pre><code>average_pace = average_over_distance(input_datalist, input_distancelist, average_distance) average_pace = [4.715677705829617, 4.596201931814222, 4.924473000260758, 5.385001220009992, 5.695676885416609, 5.730593560295301] </code></pre> <pre class="lang-py prettyprint-override"><code># import numpy import numpy as np # defined a function to find the nearest value to a given one def find_nearest(array,value): idx = np.searchsorted(array, value, side="left") if idx &gt; 0 and (idx == len(array) or math.fabs(value - array[idx-1]) &lt; math.fabs(value - array[idx])): return array[idx-1] else: return array[idx] # defined a function to calculate the average between two points of a list def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) # defined main function def average_over_distance(input_datalist, input_distancelist, average_distance): output_average_list = [] ratio_steps = int(input_distancelist[-1]/average_distance) distance_steps = range(average_distance,(ratio_steps+2)*average_distance,average_distance) for index1, elements1 in enumerate(input_distancelist): for index2, elements2 in enumerate(distance_steps): if elements1 == find_nearest(input_distancelist,elements2): if index2 == 0: cutoff_index_start = 0 cutoff_index_end = index1 else: cutoff_index_start = cutoff_index_end+1 cutoff_index_end = index1 output_average_list.append(mean(input_datalist[cutoff_index_start:cutoff_index_end])) # TODO: The last file will always be zero... Reason unclear... going from "distance_steps = range(average_distance,(ratio_steps+1)*average_distance,average_distance)" to "distance_steps = range(average_distance,(ratio_steps+2)*average_distance,average_distance) does not help del output_average_list[-1] return output_average_list </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T09:12:40.923", "Id": "459204", "Score": "2", "body": "Welcome to code review, I suggest you write a sample input and output to make it easier for people trying to review your code. ex: `Input: [1, 2, 3] Output(expected): [4, 5, 6]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T12:16:36.477", "Id": "459216", "Score": "1", "body": "@bullseye: Thanks for the remark, I added an input and output example" } ]
[ { "body": "<p>There are some logical errors with this function as well as inefficient techniques. </p>\n\n<ol>\n<li><code>cutoff_index_start</code> should not be <code>cutoff_index_end + 1</code>-- rather it should be just <code>cutoff_index_end</code>. This is because subarray slicing does not include the elements at the upper bound endpoint, meaning your original code is skipping elements occurring at <code>index1</code>s. </li>\n<li>The double for loop is unnecessary since you know the index at which your intervals are occurring. No need to check against every element in <code>input_distancelist</code>. </li>\n<li><code>np.searchsorted</code> can take an array of values to insert. </li>\n</ol>\n\n<p>With all those points, the code simply becomes:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def average_over_distance(input_datalist, input_distancelist, average_distance):\n\n output_average_list = []\n ratio_steps = int(input_distancelist[-1] / average_distance)\n\n distance_steps = range(0, (ratio_steps + 2) * average_distance, average_distance)\n\n breaks = np.searchsorted(input_distancelist, distance_steps)\n\n for index2, elements2 in enumerate(distance_steps[1:]):\n cutoff_index_start = breaks[index2]\n cutoff_index_end = breaks[index2 + 1]\n\n output_average_list.append(np.mean(input_datalist[cutoff_index_start:cutoff_index_end]))\n\n return output_average_list\n</code></pre>\n\n<p>You will notice slightly different results, this is due to numpy's float representation and the logical error I pointed out in #1 above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T18:40:52.843", "Id": "459664", "Score": "0", "body": "Thanks for your remarks !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T20:11:51.103", "Id": "234882", "ParentId": "234780", "Score": "1" } } ]
{ "AcceptedAnswerId": "234882", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T08:41:03.017", "Id": "234780", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Calculate average over a set interval of datapoints in python" }
234780
<p>I have this code to open an outlook appointment item:</p> <pre><code> Public Sub OpenOutlookAppt() Set myolApp = CreateObject("Outlook.Application") Set objExpCal = Session.GetDefaultFolder(olFolderCalendar).GetExplorer Set objNavMod = objExpCal.NavigationPane.Modules.GetNavigationModule(olModuleCalendar) Set objNavGroup = objNavMod.NavigationGroups.GetDefaultNavigationGroup(olPeopleFoldersGroup) MyCalendar = objNavMod.NavigationGroups.NavigationFolders("Trip Calendar") EntryID = Cells(ActiveCell.Row, 22) ReDim Newa(1 To MyCalendar.Folder.Items.count) r = 1 For Each Item In MyCalendar.Folder.Items Newa(r) = Item.EntryID r = r + 1 Next Item For r = 1 To UBound(Newa) If Newa(r) = EntryID Then MyCalendar.Folder.Items(r).Display Exit Sub End If Next r End Sub </code></pre> <p>This code works, but it is very slow, because it needs to loop through every single appointment item in the calendar folder. So my question is, would there be a faster way of doing this? Is there a way I can just simply reference the item I want to open without having to create a loop? I have the EntryID to reference the item, but I could just as easily store some other data from the item to reference it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:04:50.880", "Id": "459227", "Score": "2", "body": "When reviewing code for performance it helps to have the calling function as well. But with a quick look, does the code really need 2 for loops?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:14:11.070", "Id": "459230", "Score": "0", "body": "I see you’re iterating through all items in folder. Maybe try to filter them first with items.restrict. See: https://docs.microsoft.com/en-us/office/vba/api/outlook.items.restrict also check this answer https://stackoverflow.com/a/8896222/1521579" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:55:17.130", "Id": "459242", "Score": "0", "body": "This would work with the entryid https://docs.microsoft.com/en-us/office/vba/api/outlook.namespace.getitemfromid" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:01:45.467", "Id": "459308", "Score": "0", "body": "I realise that I don't need to loop twice. I can simply at the code line \"Calendar.Folder.Items(r).Display\" into the first loop (with an if function) to retrieve the corret appointment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:03:51.847", "Id": "459309", "Score": "0", "body": "@RicardoDiaz, I looked at the second link you provide, but am unable to make it work. I put in: \"Calendar.GetItemFromID(EntryID).Display\" but it doesn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:35:17.403", "Id": "459314", "Score": "0", "body": "Finally figured it out! I answered this question seperately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T14:02:19.407", "Id": "459316", "Score": "0", "body": "Awesome. Glad it worked" } ]
[ { "body": "<p>Use this code to directly reference and open:</p>\n\n<pre><code>Set NS = myolApp.GetNamespace(\"MAPI\")\nNS.Logon\nSet myAppt = NS.GetItemFromID(EntryID)\nmyAppt.Display\n</code></pre>\n\n<p>Works like a dream.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:37:04.127", "Id": "234826", "ParentId": "234781", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T10:16:44.460", "Id": "234781", "Score": "2", "Tags": [ "performance", "vba", "excel", "outlook" ], "Title": "Opening a specific Outlook item quickly" }
234781
<p>A while back I wrote a simple python script to to change the elementary icon theme, <a href="https://gist.github.com/rbtylee/225564776ef182e1084c3ee183232c9b" rel="nofollow noreferrer">elm_icon</a>, for <a href="https://www.bodhilinux.com/" rel="nofollow noreferrer">Bodhi Linux</a>. In elm_icon, the argument processing is done by simply parsing sys.argv. I decided just for educational value to rewrite the argument parsing part of the script using various argument processing python modules, focusing mostly on some of the modules I have heard of for this task but never got around to using. The goal, of course, was to more or simulate the way the original script, elm_icon, functioned. </p> <p>So when I got to trying to implement this with the python click module, it didn't seem so simple. But I admit I love the idea of argument parsing by simply adding a few decorators here and there to my code. But perhaps this program wasn't the best choice. It became rather difficult for me to achieve the desired functionality I wanted and I spent to much time closely going over the documentation, the code itself and various click related blogs and question/answers on the internet.</p> <p>So here is the code I ended up with:</p> <pre><code>#!/usr/bin/env python3 import click __version__ = '0.1.0' __license__ = 'WTFPLv2' CONTEXT_SETTINGS = {'help_option_names': ['-h', '--help']} ''' elm_icon - set the elementary icon theme. This is test code to illustrate how to use click to implement the command line argument processing implemented in the current version of elm_icon. elm_icon with no options or arguments show current theme elm_icon THEME sets the elm theme to THEME if it exists elm_icon -- THEME sets the elm theme to THEME if it exists. for use with THEME names that look like options. elm_icon [OPTION] OPTIONS: -h, --help Show this help screen -a, --all List all available icon themes -v, --version Show program version -l, --license Show program license Any invalid arguments such as elm_icon -h -all elm_icon theme1 theme2 elm_icon -h theme elm_icon -z and so on should display a usage or help screen and an Error message and exit with return 1 Invalid themes should also show an error message and exit with value 1 Successful execution exits with return 0. ''' # Seems overkill just to get the desired behavior ? # Pieced together from Stackoverflow posts primarily by Stephen Rauch # and studying the code for click class CliGroup(click.Group): """ Allow a default command for a group, customize parsing, and help/usage """ def parse_args(self, ctx, args): def invalid(args): largs = len(args) # should simplify this Boolean expression # or find a better way to determine this return largs &gt; 2 or largs == 2 and args[0] != '--' \ or largs == 1 and args[0] == '--' if invalid(args): ctx.fail('Invalid arguments or options') super(CliGroup, self).parse_args(ctx, args) def command(self, *args, **kwargs): default_command = kwargs.pop('default_command', False) if default_command and not args: kwargs['name'] = kwargs.get('name', '&lt;&gt;') decorator = super( CliGroup, self).command(*args, **kwargs) if default_command: def new_decorator(f): cmd = decorator(f) self.default_command = cmd.name return cmd return new_decorator return decorator def resolve_command(self, ctx, args): try: # test if the command parses return super( CliGroup, self).resolve_command(ctx, args) except click.UsageError: # command did not parse, assume it is the default command args.insert(0, self.default_command) return super( CliGroup, self).resolve_command(ctx, args) # is there a better way? def get_usage(self, ctx): formatter = ctx.make_formatter() self.format_usage(ctx, formatter) ret = formatter.getvalue().rstrip('\n') ret = ret.replace('COMMAND', '[THEME]').replace('[ARGS]...', '') return ret # both these seem very hackish def get_help(self, ctx): """Formats the help into a string and returns it. This creates a formatter and will call into the following formatting methods: """ ADD = "\n\nCommand:\n\n" \ "If THEME is '_elm', the icon theme is set the icon theme" \ " defined by the current elementary theme.\n\n" \ "If no option or theme is specified, prints the current " \ "elementary icon theme and exits." formatter = ctx.make_formatter() self.format_help(ctx, formatter) ret = formatter.getvalue() ret = ret.replace('COMMAND', '[THEME]').replace('[ARGS]...', '') return ret[:ret.index('Commands') - 2] + ADD def show(ctx, param, value): if not value or ctx.resilient_parsing: return if param.human_readable_name == 'all': click.echo('Not implemented: list all themes') else: click.echo(__license__) ctx.exit() @click.group(cls=CliGroup, context_settings=CONTEXT_SETTINGS, invoke_without_command=True) @click.pass_context @click.option('-l', '--license', is_flag=True, callback=show, expose_value=False, is_eager=True, help='Show the license and exit') @click.option('-a', '--all', is_flag=True, callback=show, expose_value=False, is_eager=True, help='List all elementary themes and exit') @click.version_option(__version__, message='%(prog)s v%(version)s') def cli(ctx): ''' A simple cli script to set the icon theme elementary apps are using. This avoids the need to open elementary_config. ''' if ctx.invoked_subcommand is None: click.echo('Print current theme here') @cli.command(default_command=True, context_settings={"ignore_unknown_options": True}) @click.argument('theme', nargs=1, type=click.Path(exists=False)) def set(theme): '''Set the elementary THEME and exit''' print('Not implemented: set themes here', theme) if __name__ == "__main__": cli() </code></pre> <p>The question is am I going about this the right way? Is there any way to simplify or clarify this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:52:30.343", "Id": "459381", "Score": "0", "body": "There's not really a way to improve this code from a logic perspective. I can offer suggestions, but none that are meaningful in the way I think you are expecting..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T14:26:52.150", "Id": "459432", "Score": "0", "body": "@Zchpyvr, I really wasn't sure what to expect posting this here. Perhaps I missed some easier way to implement this user case in the click code or documents, after all I mostly skimmed them hunting for relevant parts. I am up for suggestions tho, I can see room for minor improvements such as the replacing my super comand with `super().parse_args(ctx, args)` or adding the missing doc strings. Anything else would be appreciated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T11:59:09.957", "Id": "234782", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Argument Processing with python-click" }
234782
<p>For many years, there have been several JavaScript libraries for implementing custom events and event listeners. But, as <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events" rel="nofollow noreferrer">MDN web docs suggests</a>, there are now available constructable <a href="https://developer.mozilla.org/en-US/docs/Web/API/Event" rel="nofollow noreferrer">Event</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent" rel="nofollow noreferrer">CustomEvent</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget" rel="nofollow noreferrer">EventTarget</a> objects. So, what would now be the standard approach to equip my custom class with event-emitting qualities?</p> <p>This is the ES6 code I am using now, it works fine.</p> <pre><code>class MyObject extends EventTarget { constructor(name) { super(); this.name = name; } trigger(message) { const e = new CustomEvent('update', {detail: {message}}); this.dispatchEvent(e); } } const o = new MyObject('Good Boy'); o.addEventListener('update', e =&gt; { console.log('Update event by', e.target.name, 'triggered, message:', e.detail.message); }); // Should output to the console: Update event by Good Boy triggered, message: Hello o.trigger('Hello'); </code></pre> <p>Are there any risks with this approach? Other than that it would not work on certain older browser versions. I have some reservations about the fact that I have to inherit from the EventTarget class. If the MyObject class would inherit from some parent class, and I'd want to equip with event emitter only the child class, it appears there would be no clean way to do that.</p> <p>Here's my lousy attempt to mix in the EventTarget methods so that there's no need to inherit from the EventTarget class:</p> <pre><code>class MyObject { constructor(name) { this.name = name; this.eventEmitter = new EventTarget(); this.addEventListener = (...args) =&gt; this.eventEmitter.addEventListener(...args); this.removeEventListener = (...args) =&gt; this.eventEmitter.removeEventListener(...args); this.dispatchEvent = (...args) =&gt; this.eventEmitter.dispatchEvent(...args); } trigger(message) { const e = new CustomEvent('update', {detail: {emitter:this, message}}); this.dispatchEvent(e); } } const o = new MyObject('Good Boy'); o.addEventListener('update', e =&gt; { console.log('Update event by', e.detail.emitter.name, 'triggered, message:', e.detail.message); }); o.trigger('Hello'); </code></pre> <p>The ugly thing here is that now <code>e.target</code> does not point to MyObject instance but rather to its <code>eventEmitter</code> property. I am forced to pass it via the event details, it's not pretty but this kind of works.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-12T23:33:11.370", "Id": "461053", "Score": "0", "body": "What do you want to use the Events for? You are using DOM Events, thus you'd usually `. dispatch()` and `.addEventListener()` on _built-in_ DOM Elements or on _CustomElements_. Both have those methods built-in and you'd built wrappers around the actual CustomEvents instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T16:02:51.607", "Id": "461282", "Score": "0", "body": "In this case, it's an abstract application business logic model with no visual representation. It would emit events when it changes state. Of course, I can implement my own code for `addEventListener` and `removeEventListener` methods and handle the event callback. But why bother writing code for something that's available out-of-the-box?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T16:34:10.477", "Id": "461284", "Score": "0", "body": "Instead of abusing DOM Events for an offscreen event system that is not using the DOM specific semantics that are associated with DOM events (like _bubbling_) - I'd rather use an existing solution (e.g postal.js) or come up with a specific customized solution. Or to put it simply: I'd not fix a problem with a hammer, that is lying around if a screw would be a better fit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T21:41:29.887", "Id": "461325", "Score": "0", "body": "Oh, Ok. I wasn't aware those classes are meant for the DOM element business only. If so, that really is a hack to use the Event on non-elements. It was so satisfactory to see an inheritable Event class being available in the browser environment, event system is no less core to the application develompent than things like Promise." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T15:39:52.477", "Id": "234784", "Score": "2", "Tags": [ "javascript", "event-handling" ], "Title": "JavaScript: implement event listener in custom object" }
234784
<p>The backend part has the following purposes.</p> <ul> <li>An endpoint that takes a search term and returns a list of repositories.</li> <li>An endpoint that allows bookmarking a repository by its id.</li> <li>An endpoint to get all bookmarked repositories</li> <li>An endpoint to remove a bookmark. </li> </ul> <p>I have written the code for the <a href="https://github.com/mnaveenchand/conradchallenge" rel="nofollow noreferrer">application</a> using NodeJS and Express. The application is working well. I would like to have a code review for code quality and suggestions for improvements.</p> <pre class="lang-js prettyprint-override"><code>const express = require('express'); const timeout = require('express-timeout-handler'); const cors = require('cors'); require('dotenv').config(); const app = express(); const port = process.env.PORT || 3000; app.use(cors()); app.use(express.json()); let options = { timeout: 3000, onTimeout: function(req, res) { res.status(503).send('Service unavailable. Please retry.'); }, onDelayedResponse: function(req, method, args, requestTime) { console.log(`Attempted to call ${method} after timeout`); }, disable: ['write', 'setHeaders', 'send', 'json', 'end'] }; app.use(timeout.handler(options)); app.listen(port, () =&gt; console.log(`Server Listening on port ${port}`)); const listrepositoriesRoutes = require('./routes/repositories.route'); const bookmarksRoutes = require('./routes/bookmarks.route'); const authentication = require('./basic_auth/auth'); app.use('/userauth', authentication); app.use('/listallrepos', listrepositoriesRoutes); app.use('/bookmarks', bookmarksRoutes); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T20:35:51.310", "Id": "459262", "Score": "0", "body": "Welcome to CR! There doesn't really appear to be much substantial code in the question itself for review--this is a pretty standard set of Node imports and route boilerplate. You can also [omit some superfluous language](https://codereview.stackexchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:05:55.430", "Id": "234785", "Score": "2", "Tags": [ "javascript", "node.js", "express.js" ], "Title": "Backend application to bookmark GitHub repository" }
234785
<p>I have a basic python file editor/executor(still working on it) but I get know that this does not have the best performance so are there any sugestions about how to up the performance of this code:</p> <pre><code>import time start = time.time() from time import strftime import sys import log #package from os_sys from os.path import * home = expanduser("~") import os path = os.path.join(home, '.texteditrc\edit_settings.cfg') his = os.path.join(home, '.texteditrc\history-debug.cfg') import os if "-gui_logging" in sys.argv: logger = log.gui_logger("file_editor") elif "no_file" in sys.argv: logger = log.Logger("file_editor") else: logger = log.Logger("file_editor",make_file=True) def print(*msg, **kwargs): if "sep" in list(kwargs): sep = str(kwargs["sep"]) else: sep = " " if "file" in list(kwargs): if kwargs["file"] == sys.stderr: logger.warn(sep.join(msg)) else: logger.info(sep.join(msg)) else: logger.info(sep.join(msg)) try: os.mkdir(os.path.dirname(path)) except: pass if not os.path.isfile(his): open(his, 'w+').close() if os.path.isfile(path): try: settings = eval(open(path).read()) except: print('DEBUG: error while reading settings reseting the settings...', flush=True,file=sys.stderr) with open(path, 'w+') as fh: fh.write("{'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'}") settings={'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'} print('done!') else: with open(path, 'w+') as fh: fh.write("{'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white'}, 'text': 'normal'") settings={'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'} def update_settings(event=None): global settings, path, font, size settings['size'] = size settings['font'] = font with open(path, 'w+') as fh: fh.write(str(settings)) v=sys.version if "2.7" in v: from Tkinter import * import tkFileDialog else: from tkinter import * from tkinter.constants import * from tkinter.scrolledtext import ScrolledText as Text from tkinter import Tk import tkinter.filedialog as tkFileDialog from tkinter import messagebox as tkMessageBox from idlelib.undo import * class _Text(Text, UndoDelegator): def __init__(self, master, **kw): super().__init__(master, **kw) UndoDelegator.__init__(self) if "-debug" in sys.argv: debug = True try: if debug == True: DEBUG = True else: pass except: DEBUG=False if 'debug_run' in globals(): DEBUG=True def print_debug(*msg): import sys global DEBUG new = '' for i in msg: new += str(i) msg = new if DEBUG == True: print('DEBUG:', flush=True) print(msg,file=sys.stderr,flush=True) def print_startup(*msg): import sys global DEBUG new = '' for i in msg: new += str(i) msg = new stamp = strftime("%Y-%m-%d %H:%M:%S") if DEBUG == True: print('DEBUG:', flush=True) print(f'startup info(startup on python: {sys.version}, time: {stamp}), on operation system: {sys.platform}, starting in debug mode') print(msg,flush=True) else: if __name__ == '__main__': print(f'startup info(python version: {sys.version}, time: {stamp})') print(msg,flush=True) STARTUP = Print = PRINT_STARTUP = print_startup print_debug('mode: ' + str(__name__)) print_debug("STARTING:") print_debug("making Tk window") root=Tk("Text Editor", 'file: ', 'Text Editor') f = Frame(root) f.grid(column=3, row=0, rowspan=4) PRINT = debug_print = print_debug PRINT('making text widget') text=_Text(root, wrap=NONE, width=100, height=35) def crash(event=None, *args, **kwargs): global root, text with open('backup.text', 'w+') as file: try: file.write(text.get('1.0', END)) except: pass import subprocess try: try: current = __file__ except: current = os.path.abspath('') command = os.path.join(current, 'file_editor.exe') subprocess.getstatusoutput(command) except: pass text.place(x=0,y=30,width=880,height=630) PRINT('making menu buttons') font_=Menubutton(root, text="File") font_.grid(row=0, sticky=W) font_.menu=Menu(font_, tearoff=0) font_["menu"]=font_.menu Helvetica=IntVar() arial=IntVar() times=IntVar() Courier=IntVar() run=Menubutton(root, text="Run") run.place(x=60) run.menu = Menu(run, tearoff=0) run["menu"] = run.menu edit=Menubutton(root, text="Edit") edit.place(x=90) edit.menu=Menu(edit, tearoff=0) edit["menu"]=edit.menu #xscrollbar.config(command=text.xview) # # An Introduction to Tkinter # # Copyright (c) 1997 by Fredrik Lundh # # This copyright applies to Dialog, askinteger, askfloat and asktring # # fredrik@pythonware.com # http://www.pythonware.com # """This modules handles dialog boxes. It contains the following public symbols: SimpleDialog -- A simple but flexible modal dialog box Dialog -- a base class for dialogs askinteger -- get an integer from the user askfloat -- get a float from the user askstring -- get a string from the user """ from tkinter import * from tkinter import messagebox import tkinter # used at _QueryDialog for tkinter._default_root PRINT('making dialog classes') class SimpleDialog: def __init__(self, master, text='', buttons=[], default=None, cancel=None, title=None, class_=None): if class_: self.root = Toplevel(master, class_=class_) else: self.root = Toplevel(master) if title: self.root.title(title) self.root.iconname(title) self.message = Message(self.root, text=text, aspect=400) self.message.pack(expand=1, fill=BOTH) self.frame = Frame(self.root) self.frame.pack() self.num = default self.cancel = cancel self.default = default self.root.bind('&lt;Return&gt;', self.return_event) for num in range(len(buttons)): s = buttons[num] b = Button(self.frame, text=s, command=(lambda self=self, num=num: self.done(num))) if num == default: b.config(relief=RIDGE, borderwidth=8) b.pack(side=LEFT, fill=BOTH, expand=1) self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window) self._set_transient(master) def _set_transient(self, master, relx=0.5, rely=0.3): widget = self.root widget.withdraw() # Remain invisible while we figure out the geometry widget.transient(master) widget.update_idletasks() # Actualize geometry information if master.winfo_ismapped(): m_width = master.winfo_width() m_height = master.winfo_height() m_x = master.winfo_rootx() m_y = master.winfo_rooty() else: m_width = master.winfo_screenwidth() m_height = master.winfo_screenheight() m_x = m_y = 0 w_width = widget.winfo_reqwidth() w_height = widget.winfo_reqheight() x = m_x + (m_width - w_width) * relx y = m_y + (m_height - w_height) * rely if x+w_width &gt; master.winfo_screenwidth(): x = master.winfo_screenwidth() - w_width elif x &lt; 0: x = 0 if y+w_height &gt; master.winfo_screenheight(): y = master.winfo_screenheight() - w_height elif y &lt; 0: y = 0 widget.geometry("+%d+%d" % (x, y)) widget.deiconify() # Become visible at the desired location def go(self): self.root.wait_visibility() self.root.grab_set() self.root.mainloop() self.root.destroy() return self.num def return_event(self, event): if self.default is None: self.root.bell() else: self.done(self.default) def wm_delete_window(self): if self.cancel is None: self.root.bell() else: self.done(self.cancel) def done(self, num): self.num = num self.root.quit() class Dialog(Toplevel): '''Class to open dialogs. This class is intended as a base class for custom dialogs ''' def __init__(self, parent, title = None): '''Initialize a dialog. Arguments: parent -- a parent window (the application window) title -- the dialog title ''' Toplevel.__init__(self, parent) self.withdraw() # remain invisible for now # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) if self.parent is not None: self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50)) self.deiconify() # become visible now self.initial_focus.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() self.wait_window(self) def destroy(self): '''Destroy the window''' self.initial_focus = None Toplevel.destroy(self) # # construction hooks def body(self, master): '''create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method. ''' pass def buttonbox(self): '''add standard button box. override if you do not want the standard buttons ''' box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("&lt;Return&gt;", self.ok) self.bind("&lt;Escape&gt;", self.cancel) box.pack() # # standard button semantics def ok(self, event=None): if not self.validate(): self.initial_focus.focus_set() # put focus back return self.withdraw() self.update_idletasks() try: self.apply() finally: self.cancel() def cancel(self, event=None): # put focus back to the parent window if self.parent is not None: self.parent.focus_set() self.destroy() # # command hooks def validate(self): '''validate the data This method is called automatically to validate the data before the dialog is destroyed. By default, it always validates OK. ''' return 1 # override def apply(self): '''process the data This method is called automatically to process the data, *after* the dialog is destroyed. By default, it does nothing. ''' pass # override # -------------------------------------------------------------------- # convenience dialogues PRINT('making query dialog class') class _QueryDialog(Dialog): def __init__(self, title, prompt, initialvalue=None, minvalue = None, maxvalue = None, parent = None): if not parent: parent = tkinter._default_root self.prompt = prompt self.minvalue = minvalue self.maxvalue = maxvalue self.initialvalue = initialvalue Dialog.__init__(self, parent, title) def destroy(self): self.entry = None Dialog.destroy(self) def body(self, master): w = Label(master, text=self.prompt, justify=LEFT) w.grid(row=0, padx=5, sticky=W) self.entry = Entry(master, name="entry") self.entry.grid(row=1, padx=5, sticky=W+E) if self.initialvalue is not None: self.entry.insert(0, self.initialvalue) self.entry.select_range(0, END) return self.entry def validate(self): try: result = self.getresult() except ValueError: messagebox.showwarning( "Illegal value", self.errormessage + "\nPlease try again", parent = self ) return 0 if self.minvalue is not None and result &lt; self.minvalue: messagebox.showwarning( "Too small", "The allowed minimum value is %s. " "Please try again." % self.minvalue, parent = self ) return 0 if self.maxvalue is not None and result &gt; self.maxvalue: messagebox.showwarning( "Too large", "The allowed maximum value is %s. " "Please try again." % self.maxvalue, parent = self ) return 0 self.result = result return 1 PRINT('making ask functions:') class _QueryInteger(_QueryDialog): errormessage = "Not an integer." def getresult(self): return self.getint(self.entry.get()) PRINT('int') def askinteger(title, prompt, **kw): '''get an integer from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is an integer ''' d = _QueryInteger(title, prompt, **kw) return d.result class _QueryFloat(_QueryDialog): errormessage = "Not a floating point value." def getresult(self): return self.getdouble(self.entry.get()) PRINT('float') def askfloat(title, prompt, **kw): '''get a float from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a float ''' d = _QueryFloat(title, prompt, **kw) return d.result class _QueryString(_QueryDialog): def __init__(self, *args, **kw): if "show" in kw: self.__show = kw["show"] del kw["show"] else: self.__show = None _QueryDialog.__init__(self, *args, **kw) def body(self, master): entry = _QueryDialog.body(self, master) if self.__show is not None: entry.configure(show=self.__show) return entry def getresult(self): return self.entry.get() PRINT('string') def askstring(prompt='', file=None, **kw): '''get a string from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a string ''' title='input' d = _QueryString(title, prompt, **kw) return d.result PRINT('ADDING COMMANDS TO MENU\'S') #root.resizable(False, False) from idlelib.search import find, find_again, find_selection PRINT('making func: show_find') def show_find(event=None): find(text) PRINT('making func: show_find_again') def show_find_again(event=None): find_again(text) PRINT('making func: show_find_selection') def show_find_selection(event=None): find_selection(text) PRINT('adding search') edit.menu.add_command(label='search (ctrl-f)', command=show_find) PRINT('adding find again') edit.menu.add_command(label='find_again (ctrl-g)', command=show_find_again) PRINT('adding find selection') edit.menu.add_command(label='find selection (ctrl-f3)', command=show_find_selection) def replace(event=None): replace1 = askstring('what do you want to replace:') replace2 = askstring('with:') global text t = text.get("1.0", "end-1c") text.delete(1.0, END) text.insert(END, t.replace(replace1,replace2)) from idlelib.replace import replace as rplc PRINT('making rp(replace) func') def rp(): rplc(text) PRINT('adding replace') edit.menu.add_command(label='replace (ctrl-h)', command=rp) PRINT(DEBUG) debugger_on_now = DEBUG from idlelib.colorizer import * from idlelib.percolator import Percolator DEBUG = debugger_on_now PRINT('adding precolator') p = Percolator(text) PRINT(DEBUG) if DEBUG: PRINT(p) PRINT(Percolator) from idlelib.undo import * from idlelib.delegator import Delegator class Tracer(Delegator): def __init__(self, name): self.name = name self.delgate=text self.file=his def insert(self, *args): PRINT(self.name, ": insert", args) with open(self.file,'a') as fh: try: fh.write(' '.join(args)) except: fh.write(str(args)) fh.write('&lt;&lt;&lt;,&gt;&gt;&gt;') self.delegate.insert(*args) def delete(self, *args): PRINT(self.name, ": delete", args) with open(self.file,'a') as fh: try: fh.write(' '.join(args)) except: fh.write(str(args)) fh.write('&lt;&lt;&lt;,&gt;&gt;&gt;') self.delegate.delete(*args) d = UndoDelegator() #PRINT('adding trace filter') #_filter = Tracer('trac') #p.insertfilter(_filter) import re import string text.insert('1.0', ' ') text.edit_modified(False) PRINT('making func: update_text_color') def update_text_color(color): begin = time.time() color = color settings['color'] = color text.tag_add("here", "1.0", END) text.tag_config("here", foreground=color) if time.time() - begin &gt; 0.2: crash() try: update_text_color(settings['color']) except: settings['color'] = 'black' def command_root(): try: text.tag_add("NONEANYTTESUGEUHFEUIHDSIHDUIDGSUYjhghgfgvbfdfvdfvvgfgfg", "1.0", END) except: pass try: pok text.tag_config("NONEANYTTESUGEUHFEUIHDSIHDUIDGSUYjhghgfgvbfdfvdfvvgfgfg", foreground=color) except: pass root.after(100, command_root) root.after(10, command_root) class Monkey(object): def __init__(self, filename): if filename == '': self.init = False return self._cached_stamp = os.stat(filename).st_mtime self.filename = filename self.init = True self.started = False def start(self): self.started = True def ook(self): if self.init == False: return if self.started == False: return stamp = os.stat(self.filename).st_mtime if stamp != self._cached_stamp: self._cached_stamp = stamp if tkMessageBox.askquestion('file edited', 'the file you have opened now is edited by someone or something else.\ndo you want to reload the file?'): open_(True) else: self._cached_stamp = stamp def off(self): self.started = False def on(self): self.started = True def reload(self): self.self._cached_stamp = os.stat(self.filename).st_mtime def update_filename(self,filename): self._cached_stamp = os.stat(filename).st_mtime self.filename = filename self.started = False self.init = True monkey = Monkey('') def update_bg(color): text['bg'] = color settings['bg'] = color try: update_bg(settings['bg']) except: settings['bg'] = 'white' p.insertfilter(d) from threading import Thread class thread(Thread): def __init__(self, start, handler, wait=5): super().__init__() self._start=start self.handler=handler self.wait_time=wait def run(self): import time self.done=False while time.time() - self._start &lt;= self.wait_time: time.sleep(0.01) if self.done != False: return else: self.handler() handler = thread p.filter = True def exec_return(code, re=globals(), debug=False, window=True): import sys from io import StringIO import contextlib class Proxy(object): def __init__(self,stdout,stringio): self._stdout = stdout self._stringio = stringio def __getattr__(self,name): if name in ('_stdout','_stringio','write'): object.__getattribute__(self,name) else: return getattr(self._stringio,name) def write(self,data): self._stdout.write(data) self._stringio.write(data) @contextlib.contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = Proxy(sys.stdout,stdout) yield sys.stdout sys.stdout = old with stdoutIO() as s: request = re input = askstring re.update({'input': askstring}) if not debug: exec(code, re) elif debug: count = 0 line = 0 errors = [] l = code.split('\n') PRINT(len(l)) for i in l: if i.startswith(' '): continue try: exec(i.replace(' ', ''), re) PRINT(line+1) except Exception as ex: PRINT(ex) count += 1 errors.append({'count': count, 'line': line, 'traceback': str(ex), 'type': type(ex).__name__}) line += 1 if window: def thread(): from tkinter import Tk as tk window = tk('text editor pyshell','text editor pyshell','text editor pyshell') from idlelib.percolator import Percolator txt = Text(window) pk = Percolator(txt) dp1 = ColorDelegator() from idlelib.undo import UndoDelegator dl = UndoDelegator() import re import string pk.insertfilter(dl) pk.insertfilter(dp1) txt.grid() txt.insert(END, s.getvalue()) txt.insert(END, '\n&gt;&gt;&gt; ') def exec_enter(event=None): al = txt.get('1.0', END) command=al.split('&gt;&gt;&gt;')[-1] command=command.rstrip('\n') try: out = exec_return(command, window=False) except Exception as ex: out = str(ex.__class__).replace("&lt;class '", '', 1).replace("'&gt;", ' ', 1) + str(ex) txt.insert(END, '\n') txt.insert(END, out) txt.insert(END, '\n&gt;&gt;&gt;') txt.bind('&lt;Return&gt;', exec_enter) window.mainloop() from threading import Thread thread_class = Thread(target=thread) thread_class.start() if not debug: return s.getvalue() elif debug: return [s.getvalue(), {'counts': count, 'errors': errors}] def new_file(event=None): save() global text,file_name,root,file_open text.delete('1.0', END) file_name='' file_open=False root.title('Text Editor') def execute(event=None): global text t = text.get("1.0", "end-1c") if text.edit_modified(): tkMessageBox.showerror('ERROR!', 'you need to save an py file before execute') return try: out = exec_return(t) except Exception as ex: tkMessageBox.showerror('Error', ex.with_traceback(ex.__traceback__)) except Warning as warn: tkMessageBox.showwarning('Warning!', warn) else: tkMessageBox.showinfo('succes! output:', out) def debug(event=None): global text t = text.get("1.0", "end-1c") if text.edit_modified(): tkMessageBox.showerror('ERROR!', 'you need to save an py file before execute') return try: out = exec_return(t, debug=True) except: pass error_data = out[1] if error_data['counts'] == 0: tkMessageBox.showinfo('error count:', 'errors counted:\n' + str(error_data['counts'])) pass else: tkMessageBox.showinfo('error count:', 'errors counted:\n' + str(error_data['counts'])) for i in error_data['errors']: tkMessageBox.showwarning(f'error {i["count"]}', f"""error in line {i['line']}: type: {i['type']}: in line {i['traceback']} traceback:{i[traceback]}""") tkMessageBox.showinfo('succes! output:', out[0]) run.menu.add_command(label="execute (F5)", command=execute) run.menu.add_command(label="debug (F6)", command=debug) file_name='' file_open = False from tkinter import messagebox as tkMessageBox warner = tkMessageBox.askokcancel try: import docx except: try: import os_sys.docx as docx except: docx = None docx = None if docx != None: def getText(filename): doc = docx.getdocumenttext(docx.opendocx(filename)) docs = [] for i in doc: try: docs.append(''.join(i).replace('\n', '\n\n').replace('.', '.\n')) except: docs.append('error with processing this part of the file') return docs def protocolhandler(): now = time.time() global settings, size, font, root settings['size'] = size settings['font'] = font for i in range(0,3): update_settings() if file_name != '': save() PRINT('test') global DEBUG later = time.time() time_used = time.time() - now if time_used &gt; 0.5: with open('backup.text', 'w+') as file: file.write(text.get('1.0', END)) if __name__ == '__main__': tkMessageBox.showerror('ERROR!', 'restarting in debug mode') globals().update({'debug_run': True}) root.destroy() del root exec(open(__file__).read(), globals()) else: tkMessageBox.showerror('ERROR!', 'restarting in debug mode') root.destroy() del root globals().update({'debug_run': True}) from os_sys import text_editor as te exec(open(te.__file__).read(), globals()) if tkMessageBox.askokcancel("Exit", "Wanna leave?"): if DEBUG: PRINT('DEBUG:\nfirst') if tkMessageBox.askokcancel("Exit", "Are you sure?"): if DEBUG: PRINT('DEBUG:\nsecond') if text.edit_modified(): if tkMessageBox.askokcancel("Exit", "Really? becuse there are un saved changes"): pass else: return if DEBUG: PRINT('destroy') root.destroy() del root if len(open(his).read()) &gt;1000000000000000000000000: data = open(his).read() data = ''.join(data.split('&lt;&lt;&lt;,&gt;&gt;&gt;')[:100]) with open(his, 'w+') as fh: fh.write(data) for i in range(1001): try: root.destroy() except: pass else: PRINT('no') if DEBUG: PRINT('DEBUG:\nseccond say no') root.protocol("WM_DELETE_WINDOW", protocolhandler) class MultiStatusBar(Frame): def __init__(self, master, **kw): Frame.__init__(self, master, **kw) self.labels = {} def set_label(self, name, text='', side='left', width=0): if name not in self.labels: label = Label(self, borderwidth=0, anchor='w') label.pack(side=side, pady=0, padx=4) self.labels[name] = label else: label = self.labels[name] if width != 0: label.config(width=width) label.config(text=text) n = Label(root) n.place(y=659,x=0) kk = Label(root) kk.grid(row=3, column=0) kk.place(y=659, x=50) def update(event=None): global bar line, column = text.index(INSERT).split('.') n.config(text=f'line: {line}') kk.config(text=f'column: {column}') root.after(100, update) root.after(100, update) def check(): global text if file_open: if text.edit_modified(): return True return False dp = ColorDelegator() def open_(event=None): monkey.off() global text, dp, p global file_open if text.edit_modified(): if warner('Warning!', 'you are going to close this file\n but you have un saved changes\n are you shure you want to lose the changes?'): pass else: return text.delete(1.0, END) global file_name if event != 'RESTART': file_name = tkFileDialog.askopenfilename() if file_name == "": return import os a = os.path.getsize(file_name) if a &lt; 524288000: pass else: if warner("Warning!", 'This file is bigger then 500 mb and this editor can have a hard time rendering verything are you shure you want to continue?'): pass else: return pass monkey.update_filename(file_name) elif event == True: pass else: file_name = 'backup.text' if file_name.endswith('.py'): try: color_config(text) p.insertfilter(dp) except: pass else: try: p.removefilter(dp) except: pass if file_name.endswith('docx'): try: with open(file_name.replace('.docx', '.txt'), 'w+') as txt: txt.write('\n'.join(getText(file_name))) file_name=file_name.replace('.docx', '.txt') except: pass start = time.time() open_handler = handler(start,crash) open_handler.start() text.insert(END, open(file_name, 'rb').read()) open_handler.done=True if event != 'RESTART': root.title(f'Text Editor {file_name}') if event == 'RESTART': root.title('* Text Editor') file_open = True text.edit_modified(False) if '.py' in file_name: try: color_config(text) p.insertfilter(dp) except: pass else: try: p.removefilter(dp) except: pass global prev prev = text.get('1.0', END) monkey.start() font_.menu.add_command(label="Open (ctrl-o)", command=open_) def saveas(event=None): monkey.off() global text global file_name t = text.get("1.0", "end-1c") if type(t) == type(''): t = t.encode() savelocation=tkFileDialog.asksaveasfilename() if savelocation == "": return file1=open(savelocation, "wb") file1.write(t) file1.close() text.edit_modified(False) file_name = savelocation root.title(f'Text Editor {file_name}') global prev prev = text.get('1.0', END) monkey.update_filename(file_name) global dp, p if '.py' in file_name: color_config(text) p.insertfilter(dp) else: try: p.removefilter(dp) except: pass monkey.reload() monkey.on() font_.menu.add_command(label="Save as (ctrl-shift-s)", command=saveas) def monk(): monkey.ook() root.after(100, monk) root.after(100, monk) def copy(event=None): savelocation=tkFileDialog.asksaveasfilename() t = text.get("1.0", "end-1c") if type(t) == type(''): t = t.encode() file1=open(savelocation, "wb") file1.write(t) file1.close() def save(event=None): global dp, p global text global prev monkey.off() t = text.get("1.0", "end-1c") if type(t) == type(''): t = t.encode() global file_name if file_name == '': savelocation=tkFileDialog.asksaveasfilename() if savelocation == "": return file1=open(savelocation, "wb") file1.write(t) file1.close() text.edit_modified(False) file_name = savelocation root.title(f'Text Editor {file_name}') monkey.update_filename(file_name) prev = text.get('1.0', END) if '.py' in file_name: color_config(text) try: p.insertfilter(dp) except: pass else: try: p.removefilter(dp) except: pass monkey.reload() monkey.on() return savelocation=file_name file1=open(savelocation, "wb") file1.write(t) file1.close() text.edit_modified(False) prev = text.get('1.0', END) if '.py' in file_name: color_config(text) p.insertfilter(dp) else: try: p.removefilter(dp) except: pass monkey.reload() monkey.on() font_.menu.add_command(label="Save (ctrl-s)", command=save) size = settings['size'] font = settings['font'] fonts = ['System', 'Terminal', 'Fixedsys', 'Modern', 'Roman', 'Script', 'Courier', 'MS Serif', 'MS Sans Serif', 'Small Fonts', 'Marlett', 'Arial', 'Arabic Transparent', 'Arial Baltic', 'Arial CE', 'Arial CYR', 'Arial Greek', 'Arial TUR', 'Arial Black', 'Bahnschrift Light', 'Bahnschrift SemiLight', 'Bahnschrift', 'Bahnschrift SemiBold', 'Bahnschrift Light SemiCondensed', 'Bahnschrift SemiLight SemiConde', 'Bahnschrift SemiCondensed', 'Bahnschrift SemiBold SemiConden', 'Bahnschrift Light Condensed', 'Bahnschrift SemiLight Condensed', 'Bahnschrift Condensed', 'Bahnschrift SemiBold Condensed', 'Calibri', 'Calibri Light', 'Cambria', 'Cambria Math', 'Candara', 'Comic Sans MS', 'Consolas', 'Constantia', 'Corbel', 'Courier New', 'Courier New Baltic', 'Courier New CE', 'Courier New CYR', 'Courier New Greek', 'Courier New TUR', 'Ebrima', 'Franklin Gothic Medium', 'Gabriola', 'Gadugi', 'Georgia', 'Impact', 'Ink Free', 'Javanese Text', 'Leelawadee UI', 'Leelawadee UI Semilight', 'Lucida Console', 'Lucida Sans Unicode', 'Malgun Gothic', '@Malgun Gothic', 'Malgun Gothic Semilight', '@Malgun Gothic Semilight', 'Microsoft Himalaya', 'Microsoft JhengHei', '@Microsoft JhengHei', 'Microsoft JhengHei UI', '@Microsoft JhengHei UI', 'Microsoft JhengHei Light', '@Microsoft JhengHei Light', 'Microsoft JhengHei UI Light', '@Microsoft JhengHei UI Light', 'Microsoft New Tai Lue', 'Microsoft PhagsPa', 'Microsoft Sans Serif', 'Microsoft Tai Le', 'Microsoft YaHei', '@Microsoft YaHei', 'Microsoft YaHei UI', '@Microsoft YaHei UI', 'Microsoft YaHei Light', '@Microsoft YaHei Light', 'Microsoft YaHei UI Light', '@Microsoft YaHei UI Light', 'Microsoft Yi Baiti', 'MingLiU-ExtB', '@MingLiU-ExtB', 'PMingLiU-ExtB', '@PMingLiU-ExtB', 'MingLiU_HKSCS-ExtB', '@MingLiU_HKSCS-ExtB', 'Mongolian Baiti', 'MS Gothic', '@MS Gothic', 'MS UI Gothic', '@MS UI Gothic', 'MS PGothic', '@MS PGothic', 'MV Boli', 'Myanmar Text', 'Nirmala UI', 'Nirmala UI Semilight', 'Palatino Linotype', 'Segoe MDL2 Assets', 'Segoe Print', 'Segoe Script', 'Segoe UI', 'Segoe UI Black', 'Segoe UI Emoji', 'Segoe UI Historic', 'Segoe UI Light', 'Segoe UI Semibold', 'Segoe UI Semilight', 'Segoe UI Symbol', 'SimSun', '@SimSun', 'NSimSun', '@NSimSun', 'SimSun-ExtB', '@SimSun-ExtB', 'Sitka Small', 'Sitka Text', 'Sitka Subheading', 'Sitka Heading', 'Sitka Display', 'Sitka Banner', 'Sylfaen', 'Symbol', 'Tahoma', 'Times New Roman', 'Times New Roman Baltic', 'Times New Roman CE', 'Times New Roman CYR', 'Times New Roman Greek', 'Times New Roman TUR', 'Trebuchet MS', 'Verdana', 'Webdings', 'Wingdings', 'Yu Gothic', '@Yu Gothic', 'Yu Gothic UI', '@Yu Gothic UI', 'Yu Gothic UI Semibold', '@Yu Gothic UI Semibold', 'Yu Gothic Light', '@Yu Gothic Light', 'Yu Gothic UI Light', '@Yu Gothic UI Light', 'Yu Gothic Medium', '@Yu Gothic Medium', 'Yu Gothic UI Semilight', '@Yu Gothic UI Semilight', 'HoloLens MDL2 Assets', 'Agency FB', 'Algerian', 'Book Antiqua', 'Arial Narrow', 'Arial Rounded MT Bold', 'Baskerville Old Face', 'Bauhaus 93', 'Bell MT', 'Bernard MT Condensed', 'Bodoni MT', 'Bodoni MT Black', 'Bodoni MT Condensed', 'Bodoni MT Poster Compressed', 'Bookman Old Style', 'Bradley Hand ITC', 'Britannic Bold', 'Berlin Sans FB', 'Berlin Sans FB Demi', 'Broadway', 'Brush Script MT', 'Bookshelf Symbol 7', 'Californian FB', 'Calisto MT', 'Castellar', 'Century Schoolbook', 'Centaur', 'Century', 'Chiller', 'Colonna MT', 'Cooper Black', 'Copperplate Gothic Bold', 'Copperplate Gothic Light', 'Curlz MT', 'Dubai', 'Dubai Light', 'Dubai Medium', 'Elephant', 'Engravers MT', 'Eras Bold ITC', 'Eras Demi ITC', 'Eras Light ITC', 'Eras Medium ITC', 'Felix Titling', 'Forte', 'Franklin Gothic Book', 'Franklin Gothic Demi', 'Franklin Gothic Demi Cond', 'Franklin Gothic Heavy', 'Franklin Gothic Medium Cond', 'Freestyle Script', 'French Script MT', 'Footlight MT Light', 'Garamond', 'Gigi', 'Gill Sans MT', 'Gill Sans MT Condensed', 'Gill Sans Ultra Bold Condensed', 'Gill Sans Ultra Bold', 'Gloucester MT Extra Condensed', 'Gill Sans MT Ext Condensed Bold', 'Century Gothic', 'Goudy Old Style', 'Goudy Stout', 'Harlow Solid Italic', 'Harrington', 'Haettenschweiler', 'High Tower Text', 'Imprint MT Shadow', 'Informal Roman', 'Blackadder ITC', 'Edwardian Script ITC', 'Kristen ITC', 'Jokerman', 'Juice ITC', 'Kunstler Script', 'Wide Latin', 'Lucida Bright', 'Lucida Calligraphy', 'Leelawadee', 'Lucida Fax', 'Lucida Handwriting', 'Lucida Sans', 'Lucida Sans Typewriter', 'Magneto', 'Maiandra GD', 'Matura MT Script Capitals', 'Mistral', 'Modern No. 20', 'Microsoft Uighur', 'Monotype Corsiva', 'Niagara Engraved', 'Niagara Solid', 'OCR A Extended', 'Old English Text MT', 'Onyx', 'MS Outlook', 'Palace Script MT', 'Papyrus', 'Parchment', 'Perpetua', 'Perpetua Titling MT', 'Playbill', 'Poor Richard', 'Pristina', 'Rage Italic', 'Ravie', 'MS Reference Sans Serif', 'MS Reference Specialty', 'Rockwell Condensed', 'Rockwell', 'Rockwell Extra Bold', 'Script MT Bold', 'Showcard Gothic', 'Snap ITC', 'Stencil', 'Tw Cen MT', 'Tw Cen MT Condensed', 'Tw Cen MT Condensed Extra Bold', 'Tempus Sans ITC', 'Viner Hand ITC', 'Vivaldi', 'Vladimir Script', 'Wingdings 2', 'Wingdings 3', 'MT Extra'] def FontHelvetica(): global text, font text.config(font="Helvetica") font="Helvetica" def FontCourier(): global text, font text.config(font="Courier") font="Courier" def arial(): global text,font text.config(font="Arial") font="Arial" def down(): global size,font size = size - 1 settings['size'] = size if size &lt; 1: size = 1 text.config(font=(font, size, settings['text'])) def up(): global size,font if size == 150: return size += 1 settings['size'] = size text.config(font=(font, size, settings['text'])) def str_len(string): assert isinstance(string, str), 'needs to be an string' return len(string.encode("utf8")) size_label = Label(root, text=f'file size {str_len(text.get("1.0", END))}') size_label.place(x=220,y=659) def update_size_label(): size_label.config(text=f'file size {str_len(text.get("1.0", END))}') root.after(50, update_size_label) root.after(100, update_size_label) text.config(font=(font, size, settings['text'])) size_btn = Label(root, text=f'letter size: {size}') size_btn.place(x=125,y=659) def update_size_btn(): global size_btn, size size_btn.config(text=f'letter size: {size}') root.after(50, update_size_btn) root.after(100, update_size_btn) f_ont=Menubutton(root, text="Font") f_ont.place(x=30) f_ont.menu=Menu(f_ont, tearoff=0) f_ont["menu"]=f_ont.menu Helvetica=IntVar() arial=IntVar() times=IntVar() Courier=IntVar() COLORS = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace', 'linen', 'antique white', 'papaya whip', 'blanched almond', 'bisque', 'peach puff', 'navajo white', 'lemon chiffon', 'mint cream', 'azure', 'alice blue', 'lavender', 'lavender blush', 'misty rose', 'dark slate gray', 'dim gray', 'slate gray', 'light slate gray', 'gray', 'light grey', 'midnight blue', 'navy', 'cornflower blue', 'dark slate blue', 'slate blue', 'medium slate blue', 'light slate blue', 'medium blue', 'royal blue', 'blue', 'dodger blue', 'deep sky blue', 'sky blue', 'light sky blue', 'steel blue', 'light steel blue', 'light blue', 'powder blue', 'pale turquoise', 'dark turquoise', 'medium turquoise', 'turquoise', 'cyan', 'light cyan', 'cadet blue', 'medium aquamarine', 'aquamarine', 'dark green', 'dark olive green', 'dark sea green', 'sea green', 'medium sea green', 'light sea green', 'pale green', 'spring green', 'lawn green', 'medium spring green', 'green yellow', 'lime green', 'yellow green', 'forest green', 'olive drab', 'dark khaki', 'khaki', 'pale goldenrod', 'light goldenrod yellow', 'light yellow', 'yellow', 'gold', 'light goldenrod', 'goldenrod', 'dark goldenrod', 'rosy brown', 'indian red', 'saddle brown', 'sandy brown', 'dark salmon', 'salmon', 'light salmon', 'orange', 'dark orange', 'coral', 'light coral', 'tomato', 'orange red', 'red', 'hot pink', 'deep pink', 'pink', 'light pink', 'pale violet red', 'maroon', 'medium violet red', 'violet red', 'medium orchid', 'dark orchid', 'dark violet', 'blue violet', 'purple', 'medium purple', 'thistle', 'snow2', 'snow3', 'snow4', 'seashell2', 'seashell3', 'seashell4', 'AntiqueWhite1', 'AntiqueWhite2', 'AntiqueWhite3', 'AntiqueWhite4', 'bisque2', 'bisque3', 'bisque4', 'PeachPuff2', 'PeachPuff3', 'PeachPuff4', 'NavajoWhite2', 'NavajoWhite3', 'NavajoWhite4', 'LemonChiffon2', 'LemonChiffon3', 'LemonChiffon4', 'cornsilk2', 'cornsilk3', 'cornsilk4', 'ivory2', 'ivory3', 'ivory4', 'honeydew2', 'honeydew3', 'honeydew4', 'LavenderBlush2', 'LavenderBlush3', 'LavenderBlush4', 'MistyRose2', 'MistyRose3', 'MistyRose4', 'azure2', 'azure3', 'azure4', 'SlateBlue1', 'SlateBlue2', 'SlateBlue3', 'SlateBlue4', 'RoyalBlue1', 'RoyalBlue2', 'RoyalBlue3', 'RoyalBlue4', 'blue2', 'blue4', 'DodgerBlue2', 'DodgerBlue3', 'DodgerBlue4', 'SteelBlue1', 'SteelBlue2', 'SteelBlue3', 'SteelBlue4', 'DeepSkyBlue2', 'DeepSkyBlue3', 'DeepSkyBlue4', 'SkyBlue1', 'SkyBlue2', 'SkyBlue3', 'SkyBlue4', 'LightSkyBlue1', 'LightSkyBlue2', 'LightSkyBlue3', 'LightSkyBlue4', 'SlateGray1', 'SlateGray2', 'SlateGray3', 'SlateGray4', 'LightSteelBlue1', 'LightSteelBlue2', 'LightSteelBlue3', 'LightSteelBlue4', 'LightBlue1', 'LightBlue2', 'LightBlue3', 'LightBlue4', 'LightCyan2', 'LightCyan3', 'LightCyan4', 'PaleTurquoise1', 'PaleTurquoise2', 'PaleTurquoise3', 'PaleTurquoise4', 'CadetBlue1', 'CadetBlue2', 'CadetBlue3', 'CadetBlue4', 'turquoise1', 'turquoise2', 'turquoise3', 'turquoise4', 'cyan2', 'cyan3', 'cyan4', 'DarkSlateGray1', 'DarkSlateGray2', 'DarkSlateGray3', 'DarkSlateGray4', 'aquamarine2', 'aquamarine4', 'DarkSeaGreen1', 'DarkSeaGreen2', 'DarkSeaGreen3', 'DarkSeaGreen4', 'SeaGreen1', 'SeaGreen2', 'SeaGreen3', 'PaleGreen1', 'PaleGreen2', 'PaleGreen3', 'PaleGreen4', 'SpringGreen2', 'SpringGreen3', 'SpringGreen4', 'green2', 'green3', 'green4', 'chartreuse2', 'chartreuse3', 'chartreuse4', 'OliveDrab1', 'OliveDrab2', 'OliveDrab4', 'DarkOliveGreen1', 'DarkOliveGreen2', 'DarkOliveGreen3', 'DarkOliveGreen4', 'khaki1', 'khaki2', 'khaki3', 'khaki4', 'LightGoldenrod1', 'LightGoldenrod2', 'LightGoldenrod3', 'LightGoldenrod4', 'LightYellow2', 'LightYellow3', 'LightYellow4', 'yellow2', 'yellow3', 'yellow4', 'gold2', 'gold3', 'gold4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'goldenrod4', 'DarkGoldenrod1', 'DarkGoldenrod2', 'DarkGoldenrod3', 'DarkGoldenrod4', 'RosyBrown1', 'RosyBrown2', 'RosyBrown3', 'RosyBrown4', 'IndianRed1', 'IndianRed2', 'IndianRed3', 'IndianRed4', 'sienna1', 'sienna2', 'sienna3', 'sienna4', 'burlywood1', 'burlywood2', 'burlywood3', 'burlywood4', 'wheat1', 'wheat2', 'wheat3', 'wheat4', 'tan1', 'tan2', 'tan4', 'chocolate1', 'chocolate2', 'chocolate3', 'firebrick1', 'firebrick2', 'firebrick3', 'firebrick4', 'brown1', 'brown2', 'brown3', 'brown4', 'salmon1', 'salmon2', 'salmon3', 'salmon4', 'LightSalmon2', 'LightSalmon3', 'LightSalmon4', 'orange2', 'orange3', 'orange4', 'DarkOrange1', 'DarkOrange2', 'DarkOrange3', 'DarkOrange4', 'coral1', 'coral2', 'coral3', 'coral4', 'tomato2', 'tomato3', 'tomato4', 'OrangeRed2', 'OrangeRed3', 'OrangeRed4', 'red2', 'red3', 'red4', 'DeepPink2', 'DeepPink3', 'DeepPink4', 'HotPink1', 'HotPink2', 'HotPink3', 'HotPink4', 'pink1', 'pink2', 'pink3', 'pink4', 'LightPink1', 'LightPink2', 'LightPink3', 'LightPink4', 'PaleVioletRed1', 'PaleVioletRed2', 'PaleVioletRed3', 'PaleVioletRed4', 'maroon1', 'maroon2', 'maroon3', 'maroon4', 'VioletRed1', 'VioletRed2', 'VioletRed3', 'VioletRed4', 'magenta2', 'magenta3', 'magenta4', 'orchid1', 'orchid2', 'orchid3', 'orchid4', 'plum1', 'plum2', 'plum3', 'plum4', 'MediumOrchid1', 'MediumOrchid2', 'MediumOrchid3', 'MediumOrchid4', 'DarkOrchid1', 'DarkOrchid2', 'DarkOrchid3', 'DarkOrchid4', 'purple1', 'purple2', 'purple3', 'purple4', 'MediumPurple1', 'MediumPurple2', 'MediumPurple3', 'MediumPurple4', 'thistle1', 'thistle2', 'thistle3', 'thistle4', 'gray1', 'gray2', 'gray3', 'gray4', 'gray5', 'gray6', 'gray7', 'gray8', 'gray9', 'gray10', 'gray11', 'gray12', 'gray13', 'gray14', 'gray15', 'gray16', 'gray17', 'gray18', 'gray19', 'gray20', 'gray21', 'gray22', 'gray23', 'gray24', 'gray25', 'gray26', 'gray27', 'gray28', 'gray29', 'gray30', 'gray31', 'gray32', 'gray33', 'gray34', 'gray35', 'gray36', 'gray37', 'gray38', 'gray39', 'gray40', 'gray42', 'gray43', 'gray44', 'gray45', 'gray46', 'gray47', 'gray48', 'gray49', 'gray50', 'gray51', 'gray52', 'gray53', 'gray54', 'gray55', 'gray56', 'gray57', 'gray58', 'gray59', 'gray60', 'gray61', 'gray62', 'gray63', 'gray64', 'gray65', 'gray66', 'gray67', 'gray68', 'gray69', 'gray70', 'gray71', 'gray72', 'gray73', 'gray74', 'gray75', 'gray76', 'gray77', 'gray78', 'gray79', 'gray80', 'gray81', 'gray82', 'gray83', 'gray84', 'gray85', 'gray86', 'gray87', 'gray88', 'gray89', 'gray90', 'gray91', 'gray92', 'gray93', 'gray94', 'gray95', 'gray97', 'gray98', 'gray99', 'Black', 'Blue','Green','White'] def update_font(_font): global font font = _font settings['font'] = font bold = settings['text'] text.config(font=(font, size, bold)) try: update_font(settings['font']) except: update_font('Arial') PRINT('sorting colors') COLORS.sort(key=lambda s: s.casefold()) PRINT('sorting fonts') fonts.sort(key=lambda s: s.casefold()) sizes=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150] _bolds=['roman', 'italic', 'bold', 'normal'] def update_type(_font): settings['text'] = _font text.config(font=(settings['font'], settings['size'], settings['text'])) bolds = Menu(root) f_ont.menu.add_cascade(label='letter styles', menu=bolds) PRINT('adding letter styles') for i in _bolds: PRINT('adding: ' + i) exec(f'''def {str(i.replace(' ', '_'))}(): update_type('{i}')''', globals()) bolds.add_command(label=i.capitalize(), command=eval(i.replace(' ', '_'))) fonts_menu = Menu(root) f_ont.menu.add_cascade(label='fonts', menu=fonts_menu) PRINT('adding fonts') for i in fonts: PRINT('adding: '+i) exec(f'''def {str(i.replace(' ', '_')).replace('@', '_').replace('-', '_').replace('.', '_')}(): update_font('{i}')''', globals()) fonts_menu.add_command(label=i.capitalize(), command=eval(i.replace(' ', '_').replace('@', '_').replace('-', '_').replace('.', '_'))) f_ont.menu.add_command(label="smaller letters (ctrl-minus)", command=down) f_ont.menu.add_command(label="bigger letters (ctrl-+)", command=up) new = Menu(root) f_ont.menu.add_cascade(label="colors", menu=new) PRINT('adding colors') for i in COLORS: PRINT('adding: '+i) exec(f'''def {str(i.replace(' ', '_'))}(): update_text_color('{i}')''', globals()) new.add_command(label=i, command=eval(i.replace(' ', '_'))) _NEW = Menu(root) f_ont.menu.add_cascade(label="size", menu=_NEW) PRINT('adding sizes') for i in sizes: PRINT('adding: '+str(i)) exec(f'''def _{i}(): global text,font,size size = {i} text.config(font=(font, size, ''))''', globals()) _NEW.add_command(label=i, command=eval('_' + str(i))) NEW = Menu(root) f_ont.menu.add_cascade(label="bg colors", menu=NEW) PRINT('adding bg colors') for i in COLORS: PRINT('adding: '+i) exec(f'''def _{str(i.replace(' ', '_'))}(): update_bg('{i}')''', globals()) NEW.add_command(label=i, command=eval('_' + i.replace(' ', '_'))) #outputwindow.insert('end',Details1) def tab(event): begin = time.time() seltext = None try: seltext = text.get(SEL_FIRST, SEL_LAST) except TclError: pass if seltext != '' and seltext != None: text.delete(SEL_FIRST, SEL_LAST) info = text.winfo_pointerxy() text.insert(INSERT, ' ' * 4) if time.time() - start &gt; 1: crash() return 'break' def undo_event(event=None): d.undo_event(event) global added if added &lt;= 0: return added = added - 1 from time import sleep sleep(0.05) def redo_event(event=None): d.redo_event(event) global added added += 1 from time import sleep sleep(0.05) def resize(event=None): h = root.winfo_height() w = root.winfo_width() text.place(width=w-70,height=h-70) root.after(10,resize) n.place(y=h-40) kk.place(y=h-40) size_label.place(y=h-40) size_btn.place(y=h-40) root.after(0,resize) added = 0 prev = text.get('1.0', END) def checker(): begin = time.time() global text, prev import time as _t if prev == text.get('1.0', END): root.title(f'Text Editor {file_name}') prev = text.get('1.0', END) text.edit_modified(False) else: root.title(f'* Text Editor {file_name}') if time.time() - begin &gt; 1: crash() root.after(100, checker) root.after(100, checker) def add(event=None): global added added += 1 def rrkk(): update_settings() root.after(200, rrkk) root.after(100, rrkk) def main(): PRINT('MAIN:') global DEBUG, root if 'debug_run' in globals(): DEBUG=True PRINT('binding key combinations') text.bind('&lt;space&gt;', add) text.bind('&lt;a&gt;', add) text.bind('&lt;b&gt;', add) text.bind('&lt;c&gt;', add) text.bind('&lt;d&gt;', add) text.bind('&lt;e&gt;', add) text.bind('&lt;f&gt;', add) text.bind('&lt;g&gt;', add) text.bind('&lt;h&gt;', add) text.bind('&lt;i&gt;', add) text.bind('&lt;j&gt;', add) text.bind('&lt;k&gt;', add) text.bind('&lt;l&gt;', add) text.bind('&lt;m&gt;', add) text.bind('&lt;n&gt;', add) text.bind('&lt;o&gt;', add) text.bind('&lt;p&gt;', add) text.bind('&lt;q&gt;', add) text.bind('&lt;r&gt;', add) text.bind('&lt;s&gt;', add) text.bind('&lt;t&gt;', add) text.bind('&lt;u&gt;', add) text.bind('&lt;v&gt;', add) text.bind('&lt;w&gt;', add) text.bind('&lt;x&gt;', add) text.bind('&lt;y&gt;', add) text.bind('&lt;z&gt;', add) text.bind('&lt;A&gt;', add) text.bind('&lt;B&gt;', add) text.bind('&lt;C&gt;', add) text.bind('&lt;D&gt;', add) text.bind('&lt;E&gt;', add) text.bind('&lt;F&gt;', add) text.bind('&lt;G&gt;', add) text.bind('&lt;H&gt;', add) text.bind('&lt;I&gt;', add) text.bind('&lt;J&gt;', add) text.bind('&lt;K&gt;', add) text.bind('&lt;L&gt;', add) text.bind('&lt;M&gt;', add) text.bind('&lt;N&gt;', add) text.bind('&lt;O&gt;', add) text.bind('&lt;P&gt;', add) text.bind('&lt;Q&gt;', add) text.bind('&lt;R&gt;', add) text.bind('&lt;S&gt;', add) text.bind('&lt;T&gt;', add) text.bind('&lt;U&gt;', add) text.bind('&lt;V&gt;', add) text.bind('&lt;W&gt;', add) text.bind('&lt;X&gt;', add) text.bind('&lt;Y&gt;', add) text.bind('&lt;Z&gt;', add) text.bind('&lt;Tab&gt;', tab) text.bind('&lt;F5&gt;', execute) text.bind('&lt;F6&gt;', debug) search=show_find text.bind('&lt;Control-Shift-S&gt;', saveas) text.bind('&lt;Control-s&gt;', save) text.bind('&lt;Control-o&gt;', open_) text.bind('&lt;Control-Shift-s&gt;', saveas) text.bind('&lt;Control-S&gt;', save) text.bind('&lt;Control-O&gt;', open_) text.bind('&lt;Control-z&gt;', undo_event) text.bind('&lt;Control-Z&gt;', undo_event) text.bind('&lt;Control-Shift-z&gt;', redo_event) text.bind('&lt;Control-Shift-Z&gt;', redo_event) text.bind('&lt;Control-f&gt;', search) text.bind('&lt;Control-F&gt;', search) text.bind('&lt;Control-G&gt;', show_find_again) text.bind('&lt;Control-g&gt;', show_find_again) text.bind('&lt;F3&gt;', show_find_again) text.bind('&lt;Control-F3&gt;', show_find_selection) text.bind('&lt;Control-H&gt;', rp) text.bind('&lt;Control-h&gt;', rp) def event_down(event=None): down() text.bind('&lt;Control-_&gt;', event_down) text.bind('&lt;Control-minus&gt;', event_down) def event_up(event=None): up() text.bind('&lt;Control-+&gt;', event_up) text.bind('&lt;Control-=&gt;', event_up) tracer =Tracer('tr') def do(event=None): tracer.insert((repr(event.char), event.char, event)) PRINT('lift the root window') root.lift() PRINT('resizeing root window') root.geometry("950x700") PRINT('started main loop') end = time.time() end_time = end-start if DEBUG != True: if end_time &gt; 30: crash() if os.path.isfile("backup.txt"): open_(event="RESTART") os.remove("backup.txt") STARTUP(f'text editor startup completed in {end_time} sec') while True: try: root.mainloop() break except KeyboardInterrupt: sys.exit(1) except Exception: PRINT('restarting mainloop after error') STARTUP(f'text editor restart') if __name__ == '__main__': main() </code></pre> <ol> <li>List item</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:07:27.020", "Id": "459229", "Score": "4", "body": "Could you please make the title about what the code does. Also it might be helpful if there was a paragraph about what the code does as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:52:32.140", "Id": "459241", "Score": "0", "body": "There are performance profiling tools that can tell you which part of your code is the slowest. If you want help making it faster, I'd suggest using one of those tools to identify the particular function that you want to optimize, and then post a question about that particular function." } ]
[ { "body": "<p>There's too much code here to give it all a thorough review; I recommend using a profiler to identify the function that's the performance bottleneck and posting another question about that specific function.</p>\n\n<p>I will give a review of the first 100 lines, though, just to hopefully get you started on breaking some bad habits.</p>\n\n<ol>\n<li><p>Group your imports at the top of the script, and have one import statement per module. It looks like this script is assembled by copying and pasting different found fragments, each with their own dependencies; either separate the script into independent modules or collect all those dependencies in one place. Attempt to import only the members of each module that you need.</p></li>\n<li><p>Use an arg parsing library (e.g. <code>argparse</code>) instead of <code>if flag in sys.argv</code>. It'll make your code more readable and it will make it easier to add new arguments without messing up the parsing of your existing arguments.</p></li>\n<li><p>Add linebreaks between distinct blocks of code, <strong>especially</strong> around function and class definitions.</p></li>\n<li><p>The advice about not doing your own argument parsing goes quadruple for defining your own functions. Instead of:</p></li>\n</ol>\n\n<pre><code> def print(*msg, **kwargs):\n if \"sep\" in list(kwargs):\n sep = str(kwargs[\"sep\"])\n else:\n sep = \" \"\n if \"file\" in list(kwargs):\n if kwargs[\"file\"] == sys.stderr:\n logger.warn(sep.join(msg))\n else:\n logger.info(sep.join(msg))\n else:\n logger.info(sep.join(msg))\n</code></pre>\n\n<p>do:</p>\n\n<pre><code> def print(*msg, sep=\" \", file=None):\n if file == sys.stderr:\n logger.warn(sep.join(msg))\n else:\n logger.info(sep.join(msg))\n</code></pre>\n\n<p>There are entirely better ways to write this type of function IMO, but the above edit preserves everything about how it functions while dispensing with the manual <code>**kwargs</code> parsing.</p>\n\n<ol start=\"5\">\n<li>DRY (Don't Repeat Yourself). Instead of:</li>\n</ol>\n\n<pre><code>if os.path.isfile(path):\n try:\n settings = eval(open(path).read())\n except:\n print('DEBUG: error while reading settings reseting the settings...', flush=True,file=sys.stderr)\n with open(path, 'w+') as fh:\n fh.write(\"{'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'}\")\n settings={'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'}\n print('done!')\nelse:\n with open(path, 'w+') as fh:\n fh.write(\"{'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white'}, 'text': 'normal'\")\n settings={'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'}\n</code></pre>\n\n<p>you can do something like:</p>\n\n<pre><code>def write_default_settings(path: str) -&gt; Dict[str, Union[str, int]]:\n settings = settings={'font': 'Arial', 'size': 12, 'color': 'black', 'bg': 'white', 'text': 'normal'}\n with open(path, 'w+') as fh:\n fh.write(str(settings))\n return settings\n\nif os.path.isfile(path):\n try:\n settings = eval(open(path).read())\n except:\n print('DEBUG: error while reading settings reseting the settings...', file=sys.stderr)\n settings = write_default_settings(path)\n print('done!')\nelse:\n settings = write_default_settings(path)\n</code></pre>\n\n<p>(I'm not sure if this logic is even correct, just observing that there's a lot of unnecessary copying and pasting going on.)</p>\n\n<ol start=\"6\">\n<li>Avoid using globals if possible. Here's how I'd write the <code>update_settings</code> interface (with strong typing):</li>\n</ol>\n\n<pre><code>from typing import TypedDict\n\nclass Settings(TypedDict):\n font: str\n size: int\n color: str\n bg: str\n text: str\n\ndef update_settings(settings: Settings, path: str, font: str, size: int) -&gt; None:\n \"\"\"Update the font in the settings and write the new settings to the given path.\"\"\"\n settings['size'] = size\n settings['font'] = font\n with open(path, 'w+') as fh:\n fh.write(str(settings))\n</code></pre>\n\n<ol start=\"7\">\n<li>I'm going to ignore my own advice about globals and arg parsing and just fix this code as-is, because it's silly:</li>\n</ol>\n\n<pre><code>if \"-debug\" in sys.argv:\n debug = True\n\ntry:\n if debug == True:\n DEBUG = True\n else:\n pass\nexcept:\n DEBUG=False\n</code></pre>\n\n<p>Almost all of this code is pointless. You're creating a new variable only to assign its value to another variable, you have a <code>try</code>/<code>except</code> around code that can't possible raise, and you have an <code>else</code> that just <code>pass</code>es. This entire block can be much more simply and clearly written as a single line:</p>\n\n<pre><code>DEBUG = (\"-debug\" in sys.argv)\n</code></pre>\n\n<ol start=\"8\">\n<li>Again, ignoring my advice about globals because maybe in this case it's easier to just make <code>DEBUG</code> a global than to keep track of it everyplace that you might need debug traces, but get in the habit of returning early when something is a no-op, and not re-implementing the same code in multiple places and in different ways:</li>\n</ol>\n\n<pre><code>def print_debug(*msg):\n global DEBUG\n new = ''\n for i in msg:\n new += str(i)\n msg = new\n if DEBUG == True:\n print('DEBUG:', flush=True)\n print(msg,file=sys.stderr,flush=True)\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>def print_debug(*msg):\n global DEBUG\n if not DEBUG:\n return\n print('DEBUG:', file=sys.stderr)\n print(*msg, file=sys.stderr, sep=\"\")\n</code></pre>\n\n<p>Your <code>print</code> function already knows how to <code>join</code> the <code>*msg</code> arg list, so don't re-implement the join in the caller as a <code>for</code> loop; just pass it on through. Since the function should do nothing when <code>DEBUG</code> is false, just check that immediately and return if you know there's nothing to do.</p>\n\n<p>The <code>flush</code> arg you keep passing to your <code>print</code> function does nothing, so I've removed it. (Another drawback of the <code>*kwargs</code> syntax, since any keyword is accepted you can make coding errors like this and nothing will happen at runtime to let you know what you did wrong.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:36:45.660", "Id": "234794", "ParentId": "234787", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:18:54.597", "Id": "234787", "Score": "-1", "Tags": [ "python", "text-editor" ], "Title": "any performance suggestions?" }
234787
<p>What do you think about syntax of my strictly typed DSL snippet below? Does it look understandable and efficient to define object graphs at a first glance?</p> <pre><code> def Person(Name Name, Age Age) def Name (string First, string Last) def Full = $"{First} ${Last}" (string First, string Middle, string Last) def Full = $"{First} {Middle[0]}. {Last}" def Age (Date born, Date? died = null) =&gt; this(Died.Year ?? Date.Today.Year - Born.Year) (int years) =&gt; years </code></pre> <p>It could be used as:</p> <pre><code>// implicit val person = Person( ("Mark", "Twain"), ((1835, 11, 30), (1910, 04, 21))) // or explicit like val person1 = Person( Name("Mark", "Twain"), Age((1835, 11, 30), (1910, 04, 21))) // or fully qualified to resolve ambiguities val person2 = Person( Person.Name("Mark", "Twain"), Person.Age(Date(1835, 11, 30), Date(1910, 04, 21))) Assert(true, person.Name is Person.Name) Assert(person.Name("Mark", "Twain"), person.Name) Assert("Mark", person.Name.First) Assert("Twain", person.Name.Last) Assert("Mark Twain", person.Name.Full) Assert(74, person.Age); </code></pre> <p>One more example, closures:</p> <pre><code>def Greeter(string Salutation) def Greet(string name) =&gt; $"{Salutation}, {name}!" val greeter = Greeter("Hi") val message = greeter.Greet("Tom") Assert("Hi, Tom!", message) // or like this (surprise :) val greet = Greeter.Greet("Tom") val greeter = Greeter("Hi") val message = greeter(greet) Assert("Hi, Tom!", message) </code></pre> <p>Would you personally find it useful?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T14:56:29.957", "Id": "459433", "Score": "0", "body": "What is language of this dsl?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:42:45.493", "Id": "234788", "Score": "1", "Tags": [ "dsl" ], "Title": "DSL for hierarchical class API definitions" }
234788
<p>iOS: prettify random color for debugging</p> <p>I used to use random color to debug, from colors I like</p> <pre><code>extension CALayer{ func debug(){ let colors = [UIColor.blue, UIColor.magenta, UIColor.red, UIColor.green, UIColor.brown, UIColor.purple, UIColor.cyan] if let color = colors.randomElement().cgColor{ borderColor = color } } } </code></pre> <p>The effect case:</p> <p>The colors are not of regularity. Not very pretty. </p> <p><a href="https://i.stack.imgur.com/TR9y0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TR9y0.png" alt="111"></a></p> <p>I want to prettify it. Do some color alignment. The same color for the same UI hierarchy.</p> <p>achieve something like this.</p> <p><a href="https://i.stack.imgur.com/bE4A7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bE4A7.png" alt="000"></a></p> <p>In order to not make colors repeat, and to show more colors in a page. I use ring buffer.</p> <p>In order to do some color alignment, the same color for the same UI hierarchy,I use call stack trace. Use the call function as the key for its color.</p> <p>Here is the code:</p> <pre><code>// the color ring buffer struct ColorCluster { static var shared = ColorCluster() let colors = [UIColor.blue, UIColor.magenta, UIColor.red, UIColor.green, UIColor.brown, UIColor.purple, UIColor.cyan] var colorRegister = [String: Int]() var count = -1 mutating func get(_ k: String) -&gt; CGColor{ var index = 0 if let idx = colorRegister[k]{ index = idx } else{ count += 1 if count &gt;= colors.count{ count = 0 } index = count colorRegister[k] = count } return colors[index].cgColor } } extension CALayer{ func debug(){ // call stack trace, remove methods of the system let libs: Set&lt;String&gt; = ["UIKitCore", "QuartzCore", "CoreFoundation"] var methods = [String]() Out: for symbol in Thread.callStackSymbols{ for lib in libs { if symbol.contains(lib){ break Out } } methods.append(symbol) } var edgeColor = UIColor.black.cgColor // color place holder if let name = methods.last{ edgeColor = ColorCluster.shared.get(name) } borderColor = edgeColor borderWidth = 1 } } </code></pre> <p>Usage:</p> <pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = tableView.dequeue(for: PracticeDetailCell.self, ip: indexPath) cell.layer.debug() return cell } </code></pre> <p><a href="https://github.com/ForStackO/picker/tree/master/generic" rel="nofollow noreferrer">more code on github</a></p>
[]
[ { "body": "<p>I've had a look, and think it should be possible to trim down the ColorCluster-logic quite a bit, mostly by tightening up the <code>get(:</code> function a bit. Avoiding some if-elsing and only manipulating the index and count once.</p>\n<pre><code>struct ColorCluster {\n static var shared = ColorCluster()\n private init() { }\n \n private let colors: [UIColor] = [.blue, .magenta, .red, .green, .brown, .purple, .cyan]\n private var colorRegister = [String: Int]()\n private var count = 0\n\n mutating func getColor(for key: String) -&gt; CGColor {\n let countIsOutOfBounds = count &gt;= colors.count\n let nextAvailableIndex = countIsOutOfBounds ? 0 : count\n \n let index = colorRegister[key] ?? nextAvailableIndex\n count = countIsOutOfBounds ? 0 : count + 1\n \n return colors[index].cgColor\n }\n}\n</code></pre>\n<p>I also had a quick look at the debug-extension. I haven't actually tested it, but the gist is to go down the functional route when creating the array of method-names:</p>\n<pre><code>extension CALayer {\n func debug() {\n // call stack trace, remove methods of the system\n let libs: Set&lt;String&gt; = [&quot;UIKitCore&quot;, &quot;QuartzCore&quot;, &quot;CoreFoundation&quot;]\n \n let methodNames = Thread.callStackSymbols.reduce([String]()) { names, symbol in\n let containingSymbol = libs.filter({ symbol.contains($0) })\n if containingSymbol.isEmpty {\n return names\n }\n return names + [symbol]\n }\n \n var edgeColor = UIColor.black.cgColor // color place holder\n if let name = methodNames.last {\n edgeColor = ColorCluster.shared.getColor(for: name)\n }\n borderColor = edgeColor\n borderWidth = 1\n }\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-06T11:15:39.470", "Id": "253121", "ParentId": "234789", "Score": "1" } } ]
{ "AcceptedAnswerId": "253121", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T16:55:18.823", "Id": "234789", "Score": "1", "Tags": [ "swift", "ios", "uikit" ], "Title": "iOS: prettify random color for debugging" }
234789
<p>I want to parse a date string with the following general format: Weekday, DD-Mon-YYYY HH:MM:SS. The calendar should also accept:</p> <ol> <li>a date without the weekday</li> <li>spaces instead of dashes</li> <li>case-insensitive month (e.g., allow "Jan", "JAN" and "jAn")</li> <li>two-digit year</li> <li>a missing timezone</li> <li>allow multiple spaces wherever a single space is allowed.</li> </ol> <p>Return <code>null</code> when:</p> <p>Input isn't a valid date string, meaning only checks that don't require connecting different. Example: the weekday string "XXX" is invalid but "Fri, 09-Jun-2015" is considered valid even though it was a Tuesday </p> <p>My code:</p> <pre><code>public static Calendar parseDate(String input) { List&lt;String&gt; months = Arrays.asList("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Pattern pattern = Pattern.compile ("(?:[A-Z][a-z][a-z],\\s+)?([0-2][0-9]|[3][0-1])(?:\\s+|-)([a-zA-z]{3})(?:\\s+|-)([0-9]{2,4})(?:\\s+)([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-9]{2})(?:\\s+GMT|$)"); Matcher matcher = pattern.matcher (input); Calendar calendar = Calendar.getInstance (TimeZone.getTimeZone ("GTM")); if ( !matcher.find () ){ return null; } int dayOfMonth = Integer.parseInt (matcher.group (1)); //since the first group is the time zone int month = months.indexOf (months.indexOf(matcher.group(2).toLowerCase())); int year = Integer.parseInt (matcher.group (3)); if (year &gt;= 0 &amp;&amp; year &lt;= 69){ year += 2000; } if ( year &gt;= 70 &amp;&amp; year &lt;= 99 ) { year += 1900; } int hours = Integer.parseInt(matcher.group(4)); int minutes = Integer.parseInt(matcher.group(5)); int seconds = Integer.parseInt(matcher.group(6)); cal.set(year, month, dayOfMonth, hours, minutes, seconds); return calendar; } </code></pre> <p>My question is how to improve <code>"(?:[A-Z][a-z][a-z],\\s+)?([0-2][0-9]|[3][0-1])(?:\\s+|-)([a-zA-z]{3})(?:\\s+|-)([0-9]{2,4})(?:\\s+)([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-9]{2})(?:\\s+GMT|$)"</code>?<br> EDIT: I can only import regex matcher and pattern and ArrayList, and the only additional methods allowed are: months.indexOf, Calendar.set, Integer.parseInt and String.toLowerCase<br> Tester:</p> <pre><code>public void testParseDate() { DateFormat df = DateFormat.getDateTimeInstance(); df.setTimeZone(TimeZone.getTimeZone("GMT")); ArrayList&lt;String&gt; inputs = new ArrayList&lt;String&gt;(); ArrayList&lt;Long&gt; expect = new ArrayList&lt;Long&gt;(); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(Calendar.MILLISECOND, 0); cal.set(2012,4,23,1,23,31); long time1 = cal.getTimeInMillis(); inputs.add("Wed, 23-May-12 01:23:31 GMT"); expect.add(time1); inputs.add("23-May-12 01:23:31 GMT"); expect.add(time1); inputs.add("23-May-12 01:23:31"); expect.add(time1); inputs.add("23 May 2012 01:23:31 GMT"); expect.add(time1); inputs.add("23 May 2012 01:23:31 GMT"); expect.add(time1); inputs.add("Wed, 23 May 2012 01:23:31 GMT"); expect.add(time1); inputs.add("23 mAy 2012 01:23:31 GMT"); expect.add(time1); inputs.add("23 maY 12 01:23:31"); expect.add(time1); inputs.add("23 jan 12 01:23:31"); cal.set(2012,0,23,1,23,31); expect.add(cal.getTimeInMillis()); inputs.add("01 AUG 12 15:23:31 GMT"); cal.set(2012,7,1,15,23,31); expect.add(cal.getTimeInMillis()); inputs.add("01 bla 12 15:23:31 GMT"); expect.add(null); inputs.add("1 May 2012 15:23:31 GMT"); expect.add(null); inputs.add("01 May 2012 15:23:31 BLA"); expect.add(null); inputs.add("01 May 2012-15:23:31"); expect.add(null); inputs.add("01 May 2012-15/23:31"); expect.add(null); inputs.add("01 May 2012-15/23:31"); expect.add(null); for (int i = 0; i &lt; inputs.size(); ++i) { Long expectTime = expect.get(i); Calendar output = RegexpPractice.parseDate(inputs.get(i)); if (expectTime == null) { assertNull(String.format("Test %d failed: Parsing &lt;&lt;%s&gt;&gt; (should be null)", i, inputs.get(i)), output); continue; } else { assertNotNull(String.format("Test %d failed: Parsing &lt;&lt;%s&gt;&gt; (unexpected null)", i, inputs.get(i)), output); } output.set(Calendar.MILLISECOND, 0); long outTime = output.getTimeInMillis(); assertEquals(String.format("Test %d failed: Parsing &lt;&lt;%s&gt;&gt; (was %s not %s)", i, inputs.get(i), df.format(outTime), df.format(expectTime)), (long) expectTime, outTime); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:29:55.987", "Id": "459248", "Score": "0", "body": "I'd prefer to use the regex to match the particular weekday amd month names. That makes it a bit longer,, but better readable (semantically), and maybe even increases the performance of that function. Also leave case insensivity to the regex engine and setting it into case insensitive mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:32:27.770", "Id": "459249", "Score": "0", "body": "do you think there is no way to shorten it? It's hardly readable for me this way, but I do want it to be efficient" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:37:57.423", "Id": "459250", "Score": "0", "body": "Hmm, I am not a real expert with regex, but always write some when I need them. What I find strange, and hard to understand for instance are those many conditionals (`?:`) introduced. Are you sure that you need them? IMO those might be replaced with simple or (`|`) conditions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:51:12.143", "Id": "459253", "Score": "0", "body": "If I'm not mistaken, by using ?: instead of | I can address the group as a whole instead of group #1..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:52:47.430", "Id": "459254", "Score": "0", "body": "`?:` prevents the group from being captured. It's excluded from `matcher.group(x)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:53:24.890", "Id": "459255", "Score": "0", "body": "You can use or (`|`) for primitives and that wouldn't affect grouping at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:54:44.477", "Id": "459256", "Score": "3", "body": "WHY would you want to create a custom RegEx?! You can use a library like JodaTime to build the parser and have it spit out the RegEx. If you need to remove optional extra spaces a single `\"\\s+\" => \" '\" replacement will fix those prior to parsing. https://www.programcreek.com/java-api-examples/?class=org.joda.time.format.DateTimeFormat&method=forPattern" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T00:43:12.643", "Id": "459271", "Score": "2", "body": "`TimeZone.getTimeZone (\"GTM\")`? Surely, you mean `\"GMT\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T01:49:25.283", "Id": "459274", "Score": "0", "body": "yes, thanks for bringing it to my attention" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:49:44.333", "Id": "459360", "Score": "1", "body": "added the tester, it's clear there what is the expected" } ]
[ { "body": "<p>You could utilize <a href=\"https://www.regular-expressions.info/named.html\" rel=\"nofollow noreferrer\">Named Capturing Groups</a> that would clarify the meaning of capturing group in the regex, as well as the method calls in the <code>matcher</code>. furthermore, with Named Capturing Groups, you don't care about the order of the groups and don't need to \"skip\" captured groups that you do not want to read (like the time zone)</p>\n\n<p>you could also break the regex into separate Strings for the capturing groups to further enhance readability: </p>\n\n<pre><code>String timeZoneRegex = \"(?&lt;timeZone&gt;[A-Z][a-z][a-z],\\\\s+)\";\nString dayOfMonthRegex = \"(?&lt;dayOfMonth&gt;[0-2][0-9]|[3][0-1])\";\n...\nPattern pattern = Pattern.compile(timeZoneRegex + \"?\" + dayOfMonthRegex + ...\n</code></pre>\n\n<p>instead of <code>matcher.group(1)</code> --> <code>matcher.group(\"dayOfMonth\");</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T08:46:31.840", "Id": "234815", "ParentId": "234793", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T18:22:40.980", "Id": "234793", "Score": "4", "Tags": [ "java", "regex" ], "Title": "Simplifying Regex Expression: calendar" }
234793
<p>This is my first time ever making a game. It is a pong-like game, where the user has a paddle and has to prevent the ball from passing them. Since this is my first game, I want any recommendations/improvements/advice from more experienced people. The advice can range from simple Java errors I've missed to more game-development technicalities. I seek to make more advanced games in the future so any advice about this simple game can help me a lot.</p> <p>In addition, I've noticed some bugs in the program, but I cannot seem to find them.</p> <ul> <li>The game has a short but noticeable lag spike.</li> <li>The ball gets stuck in the paddle, and that causes the score to rapidly increase.</li> </ul> <p>Here is the code:</p> <p><strong>Main.java</strong></p> <pre><code>import java.awt.EventQueue; import javax.swing.JFrame; public class Main extends JFrame { private static final long serialVersionUID = 1L; public Main() { initUI(); } private void initUI() { add(new PaintSurface()); this.addKeyListener(new KeyEvents()); setTitle("Pong"); setResizable(false); pack(); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(() -&gt; { JFrame main = new Main(); main.setVisible(true); }); } } </code></pre> <p><strong>PaintSurface.java</strong></p> <pre><code>import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.util.Timer; import java.util.TimerTask; import javax.swing.JPanel; public class PaintSurface extends JPanel { private static final long serialVersionUID = 1L; private static final Dimension paintSurfaceDimension = new Dimension(400, 600); public static Ball ball; public static Paddle paddle; private Timer timer; public static Dimension getPaintSurfaceDimension() { return paintSurfaceDimension; } public PaintSurface() { initPaintSurface(); } private void initPaintSurface() { setBackground(Color.BLACK); setPreferredSize(paintSurfaceDimension); generateBall(); generatePaddle(); timer = new Timer(); timer.scheduleAtFixedRate(new ScheduleTask(), 100, 17); } private void generateBall() { final int diameter = 40; int x = 0, y = 0; ball = new Ball(x, y, diameter); } private void generatePaddle() { final int width = 70, height = 15; int x = 5; final int y = paintSurfaceDimension.height - height - 5; paddle = new Paddle(x, y, width, height); } public void paintComponent(Graphics g) { Graphics2D graphics = (Graphics2D) g; graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(graphics); ball.setGraphics(graphics); paddle.setGraphics(graphics); ball.drawBall(); paddle.drawPaddle(); graphics.setFont(new Font("Calibri", Font.PLAIN, 30)); graphics.drawString(Score.score + "", 200, 50); graphics.dispose(); } private class ScheduleTask extends TimerTask { public void run() { ball.move(); paddle.move(); System.out.println(Score.score); repaint(); } } } </code></pre> <p><strong>Ball.java</strong></p> <pre><code>import java.awt.Color; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.geom.Rectangle2D; public class Ball extends Rectangle2D.Float { private static final long serialVersionUID = 1L; private Color ballColor = new Color(255, 255, 255); float speedX = 10, speedY = 10; private Graphics2D graphics; public void setGraphics(Graphics2D graphics) { this.graphics = graphics; } public Ball(int x, int y, float diameter) { super(x, y, diameter, diameter); } public void move() { collisionDetection(); scoreDetection(); x += speedX; y += speedY; } private void collisionDetection() { if(x &lt; 0 || x &gt; PaintSurface.getPaintSurfaceDimension().width - width) speedX = -speedX; if(y &lt; 0 || y &gt; PaintSurface.getPaintSurfaceDimension().height - height) speedY = -speedY; if(this.intersects(PaintSurface.paddle)) { speedY = -speedY; } } private void scoreDetection() { if(y &gt;= PaintSurface.getPaintSurfaceDimension().height - PaintSurface.paddle.height - 15) Score.score++; } public void drawBall() { graphics.setColor(ballColor); graphics.fill(this); Toolkit.getDefaultToolkit().sync(); } } </code></pre> <p><strong>Paddle.java</strong></p> <pre><code>import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; public class Paddle extends Rectangle2D.Float { private static final long serialVersionUID = 1L; private Color paddleColor = new Color(255, 255, 255); private float speedX = 10; public boolean movingLeft = false, movingRight = false; private Graphics2D graphics; public void setGraphics(Graphics2D graphics) { this.graphics = graphics; } public Paddle(int x, int y, int width, int height) { super(x, y, width, height); } public void move() { collisionDetection(); if(movingLeft) x -= speedX; if(movingRight) x += speedX; } private void collisionDetection() { if(x &lt; 0) x = 0; if(x &gt; PaintSurface.getPaintSurfaceDimension().width - width) x = PaintSurface.getPaintSurfaceDimension().width - width; } public void drawPaddle() { graphics.setColor(paddleColor); graphics.fill(this); } } </code></pre> <p><strong>KeyEvents.java</strong></p> <pre><code>import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyEvents implements KeyListener { public void keyTyped(KeyEvent event) {} public void keyPressed(KeyEvent event) { switch(event.getKeyCode()) { case KeyEvent.VK_LEFT: PaintSurface.paddle.movingLeft = true; break; case KeyEvent.VK_RIGHT: PaintSurface.paddle.movingRight = true; break; } } public void keyReleased(KeyEvent event) { switch(event.getKeyCode()) { case KeyEvent.VK_LEFT: PaintSurface.paddle.movingLeft = false; break; case KeyEvent.VK_RIGHT: PaintSurface.paddle.movingRight = false; break; } } } </code></pre> <p><strong>Score.java</strong></p> <pre><code>public class Score { public static int score; } </code></pre> <p>Thank you. Any advice is appreciated.</p>
[]
[ { "body": "<h1>Main</h1>\n\n<p>You have your <code>Main</code> class extend <code>JFrame</code>. This is unnecessary. You are not adding any functionality to the <code>JFrame</code>; you are merely using one.</p>\n\n<p>You are inconsistent in your use of <code>this.</code>. You have it explicitly only for <code>this.addKeyListener(...)</code>, and implicitly reference it in <code>add(...)</code>, <code>setTitle(...)</code>, <code>setResizable(...)</code>, and so on. Why the distinction?</p>\n\n<p>Why doesn't <code>initUI()</code> show the frame? Not showing it makes your code more complex, since you have to return the <code>Main</code> object, and then call <code>.setVisible(...)</code>.</p>\n\n<p>Simplified code:</p>\n\n<pre><code>public class Main {\n\n private static void initUI() {\n JFrame frame = new JFrame();\n\n frame.add(new PaintSurface());\n frame.addKeyListener(new KeyEvents());\n\n frame.setTitle(\"Pong\");\n\n frame.setResizable(false);\n frame.pack();\n\n frame.setLocationRelativeTo(null);\n frame.setDefaultCloseOperation(EXIT_ON_CLOSE);\n\n frame.setVisible(true);\n }\n\n public static void main(String[] args) {\n EventQueue.invokeLater(Main::initUI);\n }\n}\n</code></pre>\n\n<h1>PaintSurface</h1>\n\n<h2>Extending JPanel</h2>\n\n<p><code>PaintSurface</code> does need to extend <code>JPanel</code> because it is overriding <code>paintComponent(...)</code>. However you should actually use the <code>@Override</code> annotation so you can be sure you're overriding an existing method, instead of accidentally creating a new one. Also, the method should be <code>protected</code>, not <code>public</code>:</p>\n\n<pre><code>public class PaintSurface extends JPanel {\n ...\n\n @Override\n protected void paintComponent(Graphics g) {\n ...\n }\n\n ...\n}\n</code></pre>\n\n<h2>java.util.Timer &amp; java.util.TimerTask</h2>\n\n<p><strong>NO! Absolutely not! Full Stop.</strong></p>\n\n<p>Swing is not a thread-safe GUI. All interactions with Swing components must be on the Event Dispatching Thread (EDT). <code>java.util.Timer</code> and <code>java.util.TimerTask</code> objects do not execute on the EDT, so you'd need to wrap the code in your <code>ScheduleTask::run()</code> method inside an <code>EventQueue.invokeLater()</code> runnable.</p>\n\n<p>Instead, just use <a href=\"https://docs.oracle.com/javase/9/docs/api/javax/swing/Timer.html\" rel=\"noreferrer\"><code>javax.swing.Timer</code></a> which executes on the EDT.</p>\n\n<p>In the <code>ActionListener</code>, update your game state (move ball, paddle, update score) and call <code>paint_surface.repaint()</code>.</p>\n\n<h2>Graphics2D</h2>\n\n<p>Don't store graphics contexts. Just pass them to the paint routines. So instead of:</p>\n\n<pre><code> ball.setGraphics(graphics);\n paddle.setGraphics(graphics);\n\n ball.drawBall();\n paddle.drawPaddle();\n</code></pre>\n\n<p>use:</p>\n\n<pre><code> ball.drawBall(graphics);\n paddle.drawPaddle(graphics);\n</code></pre>\n\n<p>And don't dispose of the <code>graphics</code> context yourself, as the code which called you <code>paintComponent(g)</code> method may still be using it.</p>\n\n<p>Do not create objects inside of paint routines. The <code>Font</code> should be created once, during construction of the <code>PaintSurface</code>, and stored in a member variable.</p>\n\n<h2>Static Members</h2>\n\n<p>Why is <code>ball</code> a static member of <code>PaintSurface</code>? <code>PaintSurface.ball</code> isn't used anywhere.</p>\n\n<p>Why is <code>paddle</code> a static member of <code>PaintSurface</code>? It would be better to pass the <code>PaintSurface</code> object to the <code>Ball</code> constructor, and store a copy of it there, so the ball could access the paint surface size, and paddle object without the need for a <code>static</code>. You could also pass the <code>PaintSurface</code> object to the <code>KeyEvents</code> constructor.</p>\n\n<h1>Score</h1>\n\n<p>Again, no. A class for a global variable is wrong. The score should simply be a member variable of the <code>PaintSurface</code>.</p>\n\n<h1>WTF</h1>\n\n<p>I've never used <code>Toolkit.getDefaultToolkit().sync();</code>. It is not necessary. Do your drawing only from the EDT, and only use Swing timers. If background processing is needed (it isn't here), use <code>SwingWorker</code> threads.</p>\n\n<h1>Bugs</h1>\n\n<blockquote>\n <p>In addition, I've noticed some bugs in the program, but I cannot seem to find them.</p>\n \n <ul>\n <li>The game has a short but noticeable lag spike.</li>\n <li>The ball gets stuck in the paddle, and that causes the score to rapidly increase.</li>\n </ul>\n</blockquote>\n\n<p>Code Review is not for debugging help on known bugs, so you're on your own for the ball getting stuck in the paddle.</p>\n\n<p>Using the <code>javax.swing.Timer</code> will help fix your lag issue, but may not entirely remove it. To achieve smooth animation, games typically measure the time from one update to the next, and use the duration and the objects' velocities to determine how far objects should move from their locations at the last update period.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:26:21.000", "Id": "459311", "Score": "0", "body": "Isn't it only the call to `repaint` that needs to be wrapped? E.g: `private class ScheduleTask extends TimerTask { public void run() { ... SwingUtilities.invokeLater(() -> repaint()); } }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:42:13.813", "Id": "459315", "Score": "0", "body": "Just using `javax.swing.Timer` is the easiest solution but produces choppy animation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T17:42:12.620", "Id": "459344", "Score": "0", "body": "@BjörnLindqvist `ball.move()` & `paddle.move()` don’t sound like they touch the Swing components, but are you sure? They call `collisionDetection()` and `scoreDetection()`, which in turn call `PaintSurface.getPaintSurfaceDimension()`, which sounds like it might query the Swing component for its size (but it doesn’t). So yes, today, you could just `SwingUtilities.invokeLater(this::repaint);` in this case. But it requires investigation to determine, and while it is ok with this revision of the code, is it future proof, or could a future change invalidate the research?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T17:43:48.423", "Id": "459345", "Score": "0", "body": "@BjörnLindqvist Fixing the choppy animation requires the steps indicates in the last paragraph of my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T02:05:28.143", "Id": "234812", "ParentId": "234797", "Score": "5" } }, { "body": "<p>A trick you can use which is very common in graphics programming is\n\"clamping.\" Instead of</p>\n\n<pre><code>if(x &lt; 0) x = 0;\n if(x &gt; PaintSurface.getPaintSurfaceDimension().width - width)\n x = PaintSurface.getPaintSurfaceDimension().width - width;\n</code></pre>\n\n<p>you write:</p>\n\n<pre><code>x = Math.max(0, Math.min(x, PaintSurface.getPaintSurfaceDimension().width - width));\n</code></pre>\n\n<p>The idiom is so common that many Java programmers have a <code>clamp</code>\nfunction in their personal library of utility functions:</p>\n\n<pre><code>public static &lt;T&gt; T clamp(T x, T lo, T hi) {\n return Math.max(lo, Math.min(x, hi));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:47:48.330", "Id": "234840", "ParentId": "234797", "Score": "2" } } ]
{ "AcceptedAnswerId": "234812", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T21:45:29.283", "Id": "234797", "Score": "6", "Tags": [ "java", "swing", "pong" ], "Title": "Pong-Like Game. First game I ever made. advice needed" }
234797
<p>I am having performence issues with image processing task (flash light effect). I used c#, and used couple references (LockBits Method, Extension). The program has bad frame rates.</p> <p><em>Edited the code, improvments were made but still doesn't match up to my expectations.</em></p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ImagePro { public partial class Form1 : Form { Bitmap Dog; Rectangle rect; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Dog = new Bitmap(@"D:\Programs\VS 2013\Projectss\ImageProcessing\ImageProcessing\dog.jpg"); rect = new Rectangle(0, 0, Dog.Width, Dog.Height); this.Width = Dog.Width; this.Height = Dog.Height; timer1.Interval = 100; timer1.Start(); this.DoubleBuffered = true; } private void Form1_Paint(object sender, PaintEventArgs e) { Bitmap tempImg = new Bitmap(Dog); BitmapData imgRawData = tempImg.LockBits(rect, ImageLockMode.ReadWrite, tempImg.PixelFormat); IntPtr arrStart = imgRawData.Scan0; int size = imgRawData.Stride * tempImg.Height; byte[] rgbValues = new byte[size]; System.Runtime.InteropServices.Marshal.Copy(arrStart, rgbValues, 0, size); var absPos = PointToClient(Cursor.Position); for (int x = 0; x &lt; tempImg.Width; x++) { for (int y = 0; y &lt; tempImg.Height; y++) { double distence = GetDistance(absPos.X, absPos.Y, x, y); //Distence from pixel to cursor int pixelIndex = x * 4 + y * imgRawData.Stride; for (int i = 0; i &lt; 3; i++) { if (distence &gt; rgbValues[pixelIndex + i]) { rgbValues[pixelIndex + i] = 0; //Sets pixel to black } else { rgbValues[pixelIndex + i] -= (byte)distence; //Reduce pixel brightness } } //rgbValues[pixelIndex]; //blue //rgbValues[pixelIndex + 1]; //green //rgbValues[pixelIndex + 2]; //red //rgbValues[pixelIndex + 3]; // alpha } } System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, arrStart, size); tempImg.UnlockBits(imgRawData); e.Graphics.DrawImage(tempImg,0,0); } private static double GetDistance(double x1, double y1, double x2, double y2) { return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)); } private void timer1_Tick(object sender, EventArgs e) { this.Invalidate(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T22:30:02.277", "Id": "459264", "Score": "3", "body": "You seem to be asking two questions here: 1) How can I speed up my method? 2) My visual effect is wrong, how can I get what I want? Question #2 may not be appropriate for Code Review since your current code is not working. Code Review is a place to ask about how to make working code better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T18:07:09.367", "Id": "459346", "Score": "2", "body": "@dbc There is no longer visual effect problem, the only thing left is the performance." } ]
[ { "body": "<p>I don't know much about C#, so this answer will focus solely on generic stuff. Performance problems in image processing applications usually happen inside loops over all pixels. I'm focusing on this section of the code:</p>\n\n<pre><code>for (int x = 0; x &lt; tempImg.Width; x++)\n{\n for (int y = 0; y &lt; tempImg.Height; y++)\n {\n double distence = GetDistance(absPos.X, absPos.Y, x, y); //Distence from pixel to cursor\n int pixelIndex = x * 4 + y * imgRawData.Stride;\n\n for (int i = 0; i &lt; 3; i++)\n {\n if (distence &gt; rgbValues[pixelIndex + i])\n {\n rgbValues[pixelIndex + i] = 0; //Sets pixel to black\n }\n else\n {\n rgbValues[pixelIndex + i] -= (byte)distence; //Reduce pixel brightness \n }\n }\n }\n}\n</code></pre>\n\n<p>You loop over all pixels, but only do something for those pixels close to <code>absPos</code>. The maximum distance over which your filter will have effect is 255, assuming that <code>rgbValues</code> is an 8-bit unsigned integer. Outside of that range, you always set pixels to 0.\nThus, you can loop over only those pixels within that range: <code>x</code> goes from <code>max(absPos.X - 255, 0)</code> to <code>min(absPos.X + 255, tempImg.Width - 1)</code>, and similarly for the y-coordinate (maybe this is <code>Math.Max</code> and <code>Math.Min</code> in C#?). Outside of that range simply fill with zeros.</p>\n\n<p>Next, <code>GetDistance</code> computes the square root, which is quite expensive. It is a lot cheaper to compute the square of a value. We also know that if <code>a &lt; b</code>, then <code>a*a &lt; b*b</code>. So instead write a function <code>GetSquareDistance</code>, which returns <code>Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2)</code>, and compare the square distance to the square of the pixel's value. By not computing the square root, all operations can be done as integers, which might or might not be faster.</p>\n\n<p>This function <code>GetSquareDistance</code> can actually be further improved by computing <code>Math.Pow((y2 - y1), 2)</code> once outside the loop over <code>x</code>, then adding only the square of the x-difference inside the loop.</p>\n\n<p>Finally, the innermost <code>if</code> statement also duplicates work. I presume that a good optimizing compiler will correct this, but in principle <code>distence &gt; rgbValues[pixelIndex + i]</code> computes the difference and compares to 0, then inside the loop you again compute the same difference. Using a <code>max</code> function would improve this conditional statement:</p>\n\n<pre><code>int diff = (int)rgbValues[pixelIndex + i] - (int)distence;\nrgbValues[pixelIndex + i] = (byte)max(diff, 0); // again, maybe Math.Max?\n</code></pre>\n\n<p>(using <code>int</code> in case integer subtraction is faster than floating-point subtraction.)</p>\n\n<hr>\n\n<p>Another issue I've just noticed: You loop over <code>y</code> in the inner loop, and over <code>x</code> in the outer loop. If you reverse these two loops, then the array will be accessed in storage order (<code>pixelIndex = x * 4 + y * imgRawData.Stride</code> will increase monotonically). With this access pattern, the cache will be used optimally, and the code should be quite a bit faster.</p>\n\n<p>The code would look like this (not tested, sorry for any typo):</p>\n\n<pre><code>int firstX = max(absPos.X - 255, 0); // max and min could be Math.Max and Math.Min?\nint lastX = min(absPos.X + 255, tempImg.Width - 1) + 1;\nint firstY = max(absPos.Y - 255, 0);\nint lastY = min(absPos.Y + 255, tempImg.Height - 1) + 1;\nint pixelIndex = 0;\nfor (int y = 0; y &lt; firstY; y++)\n{\n SetRowToZero(rgbValues + pixelIndex, tempImg.Width); // This function iterates over a line of the image and sets it to 0\n pixelIndex += imgRawData.Stride;\n}\nfor (int y = firstY; y &lt; lastY; y++)\n{\n int yDistance2 = absPos.Y - y;\n yDistance2 = yDistance2 * yDistance2;\n\n SetRowToZero(rgbValues + pixelIndex, firstX); // Here the function sets the first set of pixels in the line to 0\n\n int index = pixelIndex + firstX * 4;\n for (int x = firstX; x &lt; lastX; x++)\n {\n int xDistance2 = absPos.X - x;\n xDistance2 = xDistance2 * xDistance2;\n int distance2 = xDistance2 + yDistance2;\n for (int i = 0; i &lt; 3; i++)\n {\n int value2 = rgbValues[index + i];\n value2 = value2 * value2 - distance2;\n if (value2 &lt;= 0)\n {\n rgbValues[index + i] = 0; // Sets pixel to black\n }\n else\n {\n rgbValues[index + i] = (byte)Math.Sqrt(value2); // Reduce pixel brightness \n }\n }\n index += 4;\n }\n\n SetRowToZero(rgbValues + index, tempImg.Width - lastX); // Here the function sets the last set of pixels in the line to 0\n\n pixelIndex += imgRawData.Stride;\n}\nfor (int y = lastY; y &lt; tempImg.Height; y++)\n{\n SetRowToZero(rgbValues + pixelIndex, tempImg.Width);\n pixelIndex += imgRawData.Stride;\n}\n</code></pre>\n\n<hr>\n\n<p>Additional comments:</p>\n\n<ol>\n<li><p>Typo: \"distence\" should be \"distance\"</p></li>\n<li><p>Don't leave commented-out code in your source files. They tend to be confusing. If you do, at least add a clear bit of comment text to indicate <strong>why</strong> the code is commented out.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:12:07.137", "Id": "459377", "Score": "0", "body": "Thanks, Cris for the suggestions they are very good to consider, unfortunately i cannot escape the part of going through every pixel, also tested out the speed of the GetDistence method whit just Random number generator, and the performance didn't change at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:21:51.110", "Id": "459378", "Score": "0", "body": "@MountainGold: \"tested out the speed of the GetDistence method whit just Random number generator, and the performance didn't change at all\" I don't know what you tested, but you **should** see quite a difference when removing the square root computation. You are compiling with optimizations, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:27:41.657", "Id": "459379", "Score": "0", "body": "Didn't see nothing at all, comment out the all the computation(Math.Squrt,Math.Pow) and place Random.Next(0,200), it performed the same way. I have default compiler settings working with Visual Studio, so i am guessing optimizations are turned on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:46:29.790", "Id": "459380", "Score": "1", "body": "@MountainGold: I don't know how much computation is involved in `Random.Next`, can't imagine it being as expensive as `Sqrt`. In any case, I've just realized that you are iterating over the image in the wrong order, see the edited answer. I've also written a skeleton for how I would write a performance-critical bit of code (without going into SIMD operations etc.). The main purpose is to reduce the number of computations and to reduce the number of `if` statements inside loops." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T20:03:14.903", "Id": "234836", "ParentId": "234798", "Score": "3" } } ]
{ "AcceptedAnswerId": "234836", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T21:53:48.297", "Id": "234798", "Score": "2", "Tags": [ "c#", "performance", "image", "animation", "windows" ], "Title": "Flash Light Effect Windows Forms Edited" }
234798
<p>I've now tried to use the suggestions you can find <a href="https://codereview.stackexchange.com/questions/234731/sudoku-solver-with-gui-in-java">here</a> to improve my Sudoku-Solver.</p> <p>Here's the updated code:</p> <pre class="lang-java prettyprint-override"><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static javax.swing.WindowConstants.EXIT_ON_CLOSE; public class SudokuSolver { public static void main(String[] args) { SwingUtilities.invokeLater(SudokuSolver::createGUI); } private static void createGUI() { int[][] board = { { 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 }, }; JFrame frame = new JFrame(); frame.setSize(800, 700); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel panel = new JPanel(); JPanel subpanel1 = new JPanel(); subpanel1.setPreferredSize(new Dimension(500,500)); subpanel1.setLayout( new java.awt.GridLayout( 9, 9, 20, 20 ) ); JTextField[][] text = new JTextField[9][9]; Font font = new Font("Verdana", Font.BOLD, 40); for(int i = 0; i &lt; 9; i++) { for(int j = 0; j &lt; 9; j++) { text[i][j] = new JTextField(); text[i][j].setText("0"); text[i][j].setEditable(true); text[i][j].setFont(font); subpanel1.add(text[i][j]); } } JPanel subpanel2 = new JPanel(); JButton button = new JButton("OK"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { for(int i = 0; i &lt; 9; i++) { for(int j = 0; j &lt; 9; j++) { String s = text[i][j].getText(); board[i][j] = Integer.valueOf(s); } } boolean solve = solver(board); if(solve) { for(int i = 0; i &lt; 9; i++) { for(int j = 0; j &lt; 9; j++) { text[i][j].setText("" + board[i][j]); text[i][j].setEditable(false); } } } else { JOptionPane.showMessageDialog(null,"Not solvable."); } button.setVisible(false); } }); subpanel2.add(button); panel.add(subpanel1, BorderLayout.WEST); panel.add(subpanel2, BorderLayout.EAST); frame.add(panel); frame.setVisible(true); } //Backtracking-Algorithm public static boolean solver(int[][] board) { for (int i = 0; i &lt; 9; i++) { for (int j = 0; j &lt; 9; j++) { if (board[i][j] == 0) { for (int n = 1; n &lt; 10; n++) { if (checkRow(board, i, n) &amp;&amp; checkColumn(board, j, n) &amp;&amp; checkBox(board, i, j, n)) { board[i][j] = n; if (!solver(board)) { board[i][j] = 0; } else { return true; } } } return false; } } } return true; } public static boolean checkRow(int[][] board, int row, int n) { for (int i = 0; i &lt; 9; i++) { if (board[row][i] == n) { return false; } } return true; } public static boolean checkColumn(int[][] board, int column, int n) { for (int i = 0; i &lt; 9; i++) { if (board[i][column] == n) { return false; } } return true; } public static boolean checkBox(int[][] board, int row, int column, int n) { row = row - row % 3; column = column - column % 3; for (int i = row; i &lt; row + 3; i++) { for (int j = column; j &lt; column + 3; j++) { if (board[i][j] == n) { return false; } } } return true; } } </code></pre> <p>I think there are some improvements already, but I would appreciate any suggestions to further improve the code (especially the GUI).</p> <hr> <p>The follow-up question can be found <a href="https://codereview.stackexchange.com/questions/243074/sudoku-solver-with-gui-follow-up">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T23:32:14.187", "Id": "459270", "Score": "0", "body": "I think you can use something like \"de.sfuhrm\" % \"sudoku\" % \"3.0.0\" from maven, and implement only GUI. It's should be more clear. Than you should not use names like `some1`, `some2`. Use more clear names, like `digitsPanel`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T11:29:51.973", "Id": "459298", "Score": "0", "body": "Thanks for your comment, but that's not really what I want to do. I want to improve in coding, and I don't think it's a good idea to use the code of others, when you want to improve." } ]
[ { "body": "<h1>GUI Design Changes</h1>\n\n<h2>BorderLayout</h2>\n\n<p>You are adding subpanels with:</p>\n\n<pre><code> panel.add(subpanel1, BorderLayout.WEST);\n panel.add(subpanel2, BorderLayout.EAST);\n</code></pre>\n\n<p>but you declare <code>panel</code> with:</p>\n\n<pre><code> JPanel panel = new JPanel();\n</code></pre>\n\n<p>which by default uses <code>FlowLayout</code>. You probably want to explicitly use <code>BorderLayout</code>:</p>\n\n<pre><code> JPanel panel = new JPanel(new BorderLayout());\n</code></pre>\n\n<p>and then I find:</p>\n\n<pre><code> panel.add(subpanel1, BorderLayout.CENTER);\n panel.add(subpanel2, BorderLayout.PAGE_END);\n</code></pre>\n\n<p>produces a more pleasing layout.</p>\n\n<h2>Centred Text</h2>\n\n<p>With the <code>BorderLayout</code>, the 9x9 grid layout will expand to fill most of the application window. With larger windows, the left-aligned text fields look wrong, so instead, add:</p>\n\n<pre><code> text[i][j].setHorizontalAlignment(JTextField.CENTER);\n</code></pre>\n\n<h2>Grid Gaps</h2>\n\n<p>At this point, I removed the <code>GridLayout</code> hgap and vgap, and removed the preferred size for <code>subpanel1</code>:</p>\n\n<pre><code> JPanel subpanel1 = new JPanel(new GridLayout(9, 9));\n</code></pre>\n\n<h1>GUI Code Refactoring</h1>\n\n<h2>Member variables</h2>\n\n<p>The <code>createGUI()</code> method is a little large; it contains the event handler for the button. Let's move that out into its own function. Since it will need access to the <code>text[i][j]</code> and <code>button</code>, let's move those into members of a <code>SudokuSolver</code> object. Obviously, we'll create need to create a <code>SudokuSolver</code> object, so let's use <code>invokeLater</code> to create the object, and build the GUI inside the constructor.</p>\n\n<pre><code>public class SudokuSolver {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(SudokuSolver::new);\n }\n\n private final JTextField[][] text;\n private final JButton button;\n\n SudokuSolver() {\n JFrame frame = new JFrame();\n ...\n text = new JTextField[9][9];\n ...\n button = new JButton(\"OK\");\n button.addActionListener(this::solveBoard);\n ...\n panel.add(subpanel1, BorderLayout.CENTER);\n panel.add(subpanel2, BorderLayout.PAGE_END);\n frame.add(panel);\n frame.setVisible(true);\n }\n\n private void solveBoard(ActionEvent action_event) {\n ...\n }\n\n ...\n}\n</code></pre>\n\n<h2>The Board</h2>\n\n<p>The <code>createGUI()</code> method had a <code>board</code> matrix which was explicitly initialized to a 9x9 grid of 0's. The creation of the GUI didn't use this <code>board</code> at all; it was used by the <code>actionPerformed</code> handler. So it does not need to be included in the constructor's GUI creation code. It can be created as a local variable in the <code>solveBoard()</code> method.</p>\n\n<pre><code> private void solveBoard(ActionEvent action_event) {\n int board[][] = new int[9][9];\n\n for(int i = 0; i &lt; 9; i++) {\n for(int j = 0; j &lt; 9; j++) {\n board[i][j] = Integer.valueOf(text[i][j].getText());\n }\n }\n\n ...\n }\n</code></pre>\n\n<h2>Hiding UI elements</h2>\n\n<p>When you make something invisible, the entire UI may need to be updated, as components may grow to use the newly vacated space. It is usually preferable to disable components, instead of making them invisible, when they are no longer needed or appropriate:</p>\n\n<pre><code> button.setEnabled(false);\n</code></pre>\n\n<h1>Quality of Life Improvements</h1>\n\n<p>Suggestions for improvements</p>\n\n<h2>Input Validation</h2>\n\n<p>What happens if the user enters a bad input for one of the cells, and presses \"OK\"? The program might crash, which is usually unacceptable behaviour for a GUI application. The user might not even see a console message explaining why the crash occurred!</p>\n\n<p>What if the user enters bad, but valid input, like \"10\" or \"-1\" into a cell? The solver won't have any problem finding values that work to solve the puzzle, but does it make sense to even attempt solving it?</p>\n\n<p>Perhaps the \"OK\" button should only be enabled if all the cells contain only a single digit, and disabled otherwise?</p>\n\n<h2>Retry</h2>\n\n<p>After solving, or attempting to solve a puzzle, what can the user do? Only close the application. They can't reset the puzzle. What if they made a mistake, and want to change something? They have to reenter all the givens.</p>\n\n<p>This is most apparent if \"Not solvable.\" is displayed. None of the user inputs have been changed, all the cells are still editable, but the \"OK\" button to solve the puzzle is no longer available? Then the user see \"Oh, that cell was supposed to be a 7, not a 1\" ... and while they can change the cell value, they can't reattempt the solution! They have to relaunch the application, and enter the values again. Or you could be nice and in this one case, you could leave the \"OK\" available to try again.</p>\n\n<p>How about a \"Reset\" button, which is enabled after a successful solve, which removes the solved values and reenables all the input cells?</p>\n\n<h2>Uniqueness</h2>\n\n<p>Can you tell if there are multiple solutions?</p>\n\n<h1>Other Review Comments</h1>\n\n<h2>Naming</h2>\n\n<p><code>button</code>, <code>text</code> are poor variable names. <code>solve_button</code> would be a little clearer if there was more than one button. Similarly, <code>cell_text_field</code> might be better than <code>text</code>, but perhaps a little verbose; how about <code>cell_tf</code>? Or <code>tfCell</code> if you like Hungarian notation.</p>\n\n<p><code>subpanel1</code> could be called <code>grid_panel</code>, and <code>subpanel2</code> could be called <code>button_panel</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T00:23:34.847", "Id": "234806", "ParentId": "234801", "Score": "2" } } ]
{ "AcceptedAnswerId": "234806", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T22:34:37.323", "Id": "234801", "Score": "3", "Tags": [ "java", "swing", "gui", "sudoku" ], "Title": "Sudoku-Solver - follow-up" }
234801
<p>I'm following this <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04" rel="nofollow noreferrer">tutorial</a> for setting up Django with Nginx and Gunicorn. One of the main components is the collecstatic command.</p> <p>This is the code I used:</p> <pre><code>~/myprojectdir/manage.py collectstatic </code></pre> <p>and I replaced "myprojectdir" with the actual directory. </p> <p>First I received this error:</p> <pre><code>django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. </code></pre> <p>And so I changed a line in settings.py from</p> <pre><code>STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] </code></pre> <p>to</p> <pre><code>STATIC_ROOT = [os.path.join(BASE_DIR, 'static/')] </code></pre> <p>However after that change, I now get this error:</p> <pre><code>TypeError: expected str, bytes or os.PathLike object, not list </code></pre> <p>Could someone explain what this means and how to fix it? Thank you so much!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T08:41:38.470", "Id": "459282", "Score": "1", "body": "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": "2019-12-31T00:03:42.453", "Id": "459382", "Score": "1", "body": "My apologies! I'm new to StackExchange and still trying to figure out how everything works. Thank you for the note!" } ]
[ { "body": "<p>The brackets (<code>[]</code>) aren't purely decorative, they specify that you're creating a list. The <code>TypeError</code> you got told you that you're supposed to pass in a single string, not a list of strings.</p>\n\n<p>You probably also don't want the trailing <code>/</code> on that path, since it's (hopefully) not part of the actual directory name. In general you shouldn't hard-code path separators since they aren't OS-portable (that's why <code>os.path.join</code> exists).</p>\n\n<p>Give this a try:</p>\n\n<pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'static')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T01:29:15.337", "Id": "459272", "Score": "0", "body": "Yes that worked!!!!!! Thank you so much for your help and for your clear explanation!!!!!!!!!!!!!!!!!!!!! Really appreciate it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T14:08:54.107", "Id": "459320", "Score": "1", "body": "Please don't answer questions where the code is not working as expected on code review. If you answer the question on stackoverflow.com that is fine, but not on code review." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T23:40:13.407", "Id": "234804", "ParentId": "234802", "Score": "1" } } ]
{ "AcceptedAnswerId": "234804", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T23:21:41.810", "Id": "234802", "Score": "-3", "Tags": [ "python", "django" ], "Title": "error with django collectstatic" }
234802
<p>I think I finally finished a small coin flip project I found online. However, I'm pretty confident this is far from the optimal solution and would really appreciate any feedback on how this could be improved. Since I'm studying by myself using Head First and Code Academy any feedback would be very very helpful!</p> <p>The goals of the challenge are:</p> <ul> <li>As a user I want to be able to guess the outcome of a random coin flip (heads/tails).</li> <li>As a user I want to clearly see the result of the coin flip.</li> <li>As a user I want to clearly see whether or not I guessed correctly.</li> <li>As a user I want to clearly see the updated guess history (correct count/total count).</li> <li>As a user I want to be able to quit the game or go again after each cycle.</li> </ul> <p>This is my first time really using GitHub, but I included the .py file which hopefully you can access <a href="https://github.com/adarmec/coin_flip_challenge" rel="nofollow noreferrer">here</a>.</p> <pre class="lang-py prettyprint-override"><code>import random def random_flip(): #function to generate random Heads or Tails output random_choice = random.choice(["Heads","Tails"]) return random_choice def user_choice(): #function to ensure a valid input from the user, and returns that input. user_input = "" valid_guesses = ["Heads", "Tails"] while user_input not in valid_guesses: user_input = input("Heads or Tails?") return user_input def coin_flip_game(): #function that plays the coin flip game. guess_count = 1 #guesses set to 1 so that program considers 1st guess. guesses = [] #list of guesses made by user winner = False first_try = True #Variable to determine whether first try of user or not cancel_game = False #Variable to determine whether game was cancelled print("Lets start! Begin by choosing:") while winner == False: if first_try == True: user_input = user_choice() if user_input != random_flip(): guess_count += 1 guesses.append(user_input) first_try = False else: winner = True else: decision = input("You guessed wrong, do you want to continue? Yes or No ") if decision == "Yes": user_input = user_choice() if user_input != random_flip(): guess_count += 1 guesses.append(user_input) first_try = False else: winner = True else: winner = True cancel_game = True break if cancel_game == True: print("Game over") elif guess_count == 1: print("Congratulations, you guessed correctly on your first try!") else: print("Congratulations! After ", guess_count, "you guessed correctly!") print("Your previous guesses were: ", guesses) coin_flip_game() </code></pre>
[]
[ { "body": "<p>After getting user input, you check it by doing <code>decision == \"Yes\"</code>. This is pretty exact text to expect from the user. I'd at least upper-case their input, and unless you really needed them to be specific, only keep the first letter:</p>\n\n<pre><code>decision = input(\"You guessed wrong, do you want to continue? Yes or No \")\nstd_decision = decision[:1].upper() # [:1] discards all but the first letter\n\nif std_decision == \"Y\":\n . . .\n</code></pre>\n\n<hr>\n\n<p>In <code>coin_flip_game</code> you have</p>\n\n<pre><code>guess_count = 1 #guesses set to 1 so that program considers 1st guess\n</code></pre>\n\n<p>Then later:</p>\n\n<pre><code>if user_input != random_flip():\n guess_count += 1\n guesses.append(user_input)\n first_try = False\nelse:\n winner = True\n</code></pre>\n\n<p>You're only increasing <code>guess_count</code> if the guess was wrong. Regardless of if they were right or wrong though, they still made a guess. I think it makes more sense to add to the <code>guess_count</code> regardless, and start it at <code>0</code>.</p>\n\n<p>But then you're also only adding to <code>guesses</code> on wrong answers too. If you change it to append to <code>guesses</code> on both right and wrong answers, you'll have this:</p>\n\n<pre><code>guess_count = 0\n\n. . .\n\nguess_count += 1\nguesses.append(user_input)\n\nif user_input != random_flip():\n first_try = False\n\nelse:\n winner = True\n</code></pre>\n\n<p>Notice now though that <code>guess_count</code> will always be equal to the length of <code>guesses</code>, so it isn't needed. If you need to find out how many guesses were made, you can just do <code>len(guesses)</code>. <code>first_try</code> also isn't necessary. To check if it was their first guess or not, you can do:</p>\n\n<pre><code>if len(guesses) == 0:\n . . .\n</code></pre>\n\n<p>Or, more idiomatically:</p>\n\n<pre><code>if not guesses: # \"If no(t) guesses (have been made)\"\n . . .\n</code></pre>\n\n<p>I think that whole game loop part should be taken out into it's own function though; beyond what you've already done. I'd have a function that returns a list of guesses made until a correct guess was made. With how you have it set up now, I'm going to disregard cancelling since that will require some broader changes to accommodate, and it's highly unlikely that the user will have to guess more than a few times.</p>\n\n<pre><code>def guess_loop() -&gt; List[str]:\n guesses = []\n\n while True: # We're just going to return, so we don't need a condition\n user_input = user_choice()\n guesses.append(user_input)\n\n if user_input == random_flip():\n return guesses # Returning guesses means we won\n\n else:\n print(\"You guessed wrong. Try again.\")\n\ndef coin_flip_game():\n print(\"Lets start! Begin by choosing:\")\n guesses = guess_loop()\n\n if len(guesses) == 1:\n print(\"Congratulations, you guessed correctly on your first try!\")\n\n else:\n print(\"Congratulations! After\", len(guesses), \"you guessed correctly!\")\n print(\"Your guesses were: \", guesses)\n</code></pre>\n\n<p>The bulky bit was taken out so it can be dealt with as an isolated bit of code. To know the outcome of the game, all I care about (besides cancelling, which could be handled by returning <code>None</code>) is the list of guesses they made until they won. I can get all the information I need from just that. Needing to mix in <code>winner</code>, and <code>cancel</code> flags can suggest that that code should be moved out. By the time you're managing two or three flags to control execution in one block of code, it can become hard to follow.</p>\n\n<hr>\n\n<p><code>user_choice</code> can be cleaned up too. Again, you're using a condition to control a loop when I think returning directly from the loop leads to cleaner looking code:</p>\n\n<pre><code>def user_choice():\n while True:\n user_input = input(\"Heads or Tails?\").capitalize() # Capitalize to give the user some leeway\n\n if user_input in {\"Heads\", \"Tails\"}:\n return user_input\n\n else:\n print(\"Invalid input.\")\n</code></pre>\n\n<hr>\n\n<p>After the above and some small formatting touchups, I'm left with:</p>\n\n<pre><code>import random\nfrom typing import List\n\n\ndef random_flip() -&gt; str:\n return random.choice([\"Heads\", \"Tails\"])\n\n\ndef user_choice() -&gt; str:\n while True:\n user_input = input(\"Heads or Tails?\").capitalize() # Capitalize to give the user some leeway\n\n if user_input in {\"Heads\", \"Tails\"}:\n return user_input\n\n else:\n print(\"Invalid input.\")\n\n\ndef guess_loop() -&gt; List[str]:\n guesses = []\n\n while True: # We're just going to return, so we don't need a condition\n user_input = user_choice()\n guesses.append(user_input)\n\n if user_input == random_flip():\n return guesses # Returning guesses means we won\n\n else:\n print(\"You guessed wrong. Try again.\")\n\n\ndef coin_flip_game() -&gt; None:\n print(\"Lets start! Begin by choosing:\")\n guesses = guess_loop()\n\n if len(guesses) == 1:\n print(\"Congratulations, you guessed correctly on your first try!\")\n\n else:\n print(\"Congratulations! After\", len(guesses), \"you guessed correctly!\")\n print(\"Your guesses were: \", guesses)\n\ncoin_flip_game()\n</code></pre>\n\n<p>The <code>-&gt;</code> bits are <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> for the return type of the function. I think they're handy to have to make it clearer what type of data is being dealt with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:42:58.260", "Id": "459283", "Score": "2", "body": "I would just let the User Enter \"Head, Tails or Cancel\" and exit the game on cancel. The user should be able to exit the game at any time and not keep guessing in the hope the game will then (maybe?) end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:15:12.127", "Id": "459299", "Score": "0", "body": "@Falco That was my original idea. But then I would have probably scraped/completely rewritten `user_choice` because \"cancel\" is probably a long enough word that I'd want the user to be able to enter an abbreviated version of the input, and at the time, for whatever reason, that seemed to be beyond the scope that I had arbitrarily decided on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:31:10.293", "Id": "459353", "Score": "0", "body": "thanks a lot for the feedback here, i'll try to adjust for the cancel option in the input as it relly doeas make send. With the exception that on the very first try, im asking if he wants to quit which might not make much sense!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:33:32.343", "Id": "459354", "Score": "0", "body": "and thanks again on all the suggestions, one question though.. with the While True loops.. wont it get stuck in a infinite loop since the condition is always true? This applies to both the guess_loop and the user_choice functions. \n\nwhat is the While loop testing with While True? \n\nOther than that question, all your suggestions make a lot more sense than what I had created..makes the code easier to follow. Thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:38:43.857", "Id": "459356", "Score": "0", "body": "@DanielCastro I think the best way to handle cancelling would be to allow for the user to enter \"cancel\" (or just allow for \"c\"), and return None from `guess_loop` in that case, then check for that `None` in `coin_flip_game`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:40:31.023", "Id": "459357", "Score": "1", "body": "@DanielCastro And regarding `while True`, it isn't testing for anything. It will run forever if *I allow it to*. Note though how I'm `return`ing in the loop. You're right that that loop *would* run forever if I wasn't returning. `return` though will cause the function to exit regardless of where it is in the function. As soon as you reach a `return`, the function stops and returns; even if it's in a infinite loop. You may be used to only exiting loops via the condition. If that's the case, I'd practice using `break` and `return` in loops to get a better feel for what you can do with them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:35:14.260", "Id": "459372", "Score": "2", "body": "Great review as always. But is there a rationale behind detaching `else`s from their corresponding `if` blocks? I think this has a substantial negative impact on readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:40:17.067", "Id": "459373", "Score": "0", "body": "@ggorlen Thank you. And honestly, I overwhelmingly prefer that style. I don't like a lack of lines around \"bodies\". Except for a few fringe scenarios (like where it's the first thing in a function), I always put an empty line above language constructs; including `else`. I've always been in favor of more spaces instead of less. I find that too many people jam everything together, and that leads to giant blocks with less places to let your eyes rest. To me, code like that reads like sentences without periods (I think that's the best I can describe my mindset)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:41:50.167", "Id": "459374", "Score": "0", "body": "The other exception is where a variable is acting as an accumulator for the loop. Then I put the initial definition \"hugging\" the loop to indicate association." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:43:53.427", "Id": "459375", "Score": "0", "body": "I'm with you--the Python style guide and source code never uses separating lines between blocks, period. But to me, `if`/`else` is logically and irrevocably tied together, so that's the one time I always combine the blocks. If I see a dangling `else` as in this code, it looks like a mistake and my brain freaks out while it searches for its corresponding `if`. I never do a pre-loop variable hug, but I find it to be a reasonable practice when I do see it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:47:44.783", "Id": "459376", "Score": "1", "body": "@ggorlen Hmm, I can see the want to have `if` more tightly associated with `else`. Maybe I'll play around with that style and see how I find it. Really, this style is a carry over from Clojure, so it's pretty engrained and I've just kind of accepted it. Maybe I just need play around and question if it could be improved. That's for letting me know. I never thought that it would be considered less readable than the alternative." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T23:46:42.197", "Id": "234805", "ParentId": "234803", "Score": "11" } }, { "body": "<p>User input shouldn't require the full case-sensitive text.</p>\n\n<p>If there isn't already one in a library somewhere, write a function that compares two strings to see if one is a valid truncation of the other.\nThen use that function rather than <code>!=</code> for comparing the response to the flip.</p>\n\n<p>E.g. any of these should match \"True\": \"t\", \"tr\", \"tru\", and \"true\", regardless of case.</p>\n\n<p>And users shouldn't have to respond so many times. It gets annoying.\nAs \"Falco\" suggested, the input choices should be \"Heads\", \"Tails\", and \"Quit\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:34:31.643", "Id": "459355", "Score": "0", "body": "Thank you! I was wondering if there was a method available already for truncating text but writing one out makes sense. I'll definitely give this a try!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T15:04:31.443", "Id": "234829", "ParentId": "234803", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T23:22:03.343", "Id": "234803", "Score": "13", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Beginner Coin Flip project" }
234803
<p>I have 'n' microphones placed in square fashion and I want to make sure that all the channels must be aligned in time exactly the same if the signal is equidistant from all the 'n' microphones i.e. in the center of the square.</p> <p>I have written this script to do the difference in zero crossing timings for only two signals (.wav file) and if the difference is above some precision then print that and bail out.</p> <pre><code>from scipy.io import wavfile import numpy as np import argparse parser = argparse.ArgumentParser(description='diff the zero crossing of two files') parser.add_argument('-f1', '--file_name_1', help='provide first file name') parser.add_argument('-f2', '--file_name_2', help='provide second file name') parser.add_argument('-p', '--precision', help='precision to compare against', type=float, default=0.0001) args = parser.parse_args() print(args) files = [] files.append(args.file_name_1) files.append(args.file_name_2) sampling_rates = [] signals = [] for file in files: fs, signal = wavfile.read(file) signal = signal / max(abs(signal)) # scale signal sampling_rates.append(fs) signals.append(signal) assert min(signal) &gt;= -1 and max(signal) &lt;= 1 print 'fs ==&gt; ', fs, 'Hz' # sampling rate print 'len(signal) ==&gt; ', len(signal), 'samples' sampsPerMilli = 0 #files should have same sampling rates and length prev_rate = sampling_rates[0] for rate in sampling_rates[1:]: cur_rate = rate sampsPerMilli = int(rate / 1000) if prev_rate != cur_rate: print("rates doesn't match %d %d"% (prev_rate, cur_rate)) exit(0) cur_rate = rate #signal length also should be same prev_length = len(signals[0]) for signal in signals[1:]: cur_length = len(signal) if prev_length != cur_length: print("length of signals doesn't match for %d %d"% (prev_length, cur_length)) exit(0) cur_length = prev_length zccs = [] for signal in signals: zcc = [] DC = np.mean(signal) newSignal = signal - DC for i in range(1, int(len(newSignal))): if((newSignal[i] * newSignal[i-1]) &lt; 0): #print("crossing at %f seconds"% ((i/sampsPerMilli) * 0.001)) zcc.append((i/sampsPerMilli) * 0.001) zccs.append(zcc) for a, b in zip(zccs, zccs[1:]): if len(a) != len(b): print("length doesn't match %d %d"% (len(a), len(b))) for c, d in zip(a, b): if c-d &gt; args.precision: print("precision %f c %f d %f exceeded"% (args.precision, c, d)) exit(0) </code></pre> <p>Is there any better approach or can this script be improved?</p>
[]
[ { "body": "<ol>\n<li><p>This is more of a usability thing than a code thing, but I'd suggest making the non-optional arguments positional so the user doesn't need to type the flags out.</p></li>\n<li><p>A simple way to put two items into a list is <code>files = [file1, file2]</code>.</p></li>\n<li><p>You can also build <code>sampling_rates</code> and <code>signals</code> via list comprehension.</p></li>\n<li><p>Since you're explicitly only ever handling two files, building a loop to handle the second thru last files is unnecessary and confusing.</p></li>\n<li><p>Don't assign a value to a variable if you're going to overwrite it with something else before using it -- again, it's just adding lines of code that do nothing but make it harder to read the script (and use up an infinitesimal amount of processing power). Combined with (4) above, you have two loops that take seven lines of code to do what's really a single simple equality comparison.</p></li>\n<li><p>The rest of the script (everything starting at <code>zccs</code>) is hard to understand, but I attempted to condense some of the more magical logic into a function and use list comprehension instead of long loops; better variable names and/or type declarations (normally I'd add those as part of code review suggestions, but I'm not familiar with any of these libraries) would help someone who's not familiar with this particular domain be able to read the script and figure out what it's doing. Here's what I ended up with after making the above edits:</p></li>\n</ol>\n\n<pre><code>from scipy.io import wavfile\nimport numpy as np\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser(description='diff the zero crossing of two files')\nparser.add_argument('files', nargs=2, metavar='file', \n help='one of the files to diff')\nparser.add_argument('-p', '--precision', type=float, default=0.0001, \n help='precision to compare against')\n\nargs = parser.parse_args()\n\n# Read data from wav files, scale signals by the max in each file.\nsampling_rates, data = zip(*[wavfile.read(file) for file in args.files])\nsignals = [signal / max(abs(signal)) for signal in data]\n\n# check we didn't somehow bungle the signal normalization math\nassert all([min(signal) &gt;= -1 and max(signal) &lt;= 1 for signal in signals])\n\n# files should have same sampling rates and signal length\nassert sampling_rates[0] == sampling_rates[1], \"rates don't match\"\nassert len(signals[0]) == len(signals[1]), \"signal lengths don't match\"\n\nsamples_per_ms = int(sampling_rates[1] / 1000)\n\ndef zcc(signal):\n \"\"\"magic!!! (todo: write better docstring)\"\"\"\n norm_signal = signal - np.mean(signal)\n return [\n i * 0.001 / samples_per_ms # is this right? i is the index!\n if norm_signal[i] * norm_signal[i-1] &lt; 0 \n for i in range(1, len(norm_signal))\n ]\n\nfor a, b in zip(*[zcc(signal) for signal in signals]):\n if len(a) != len(b):\n print(\"length doesn't match %d %d\"% (len(a), len(b)))\n for c, d in zip(a, b):\n if c - d &gt; args.precision:\n print(\"precision %f c %f d %f exceeded\"% (args.precision, c, d))\n exit(0)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T02:36:27.893", "Id": "234813", "ParentId": "234810", "Score": "2" } } ]
{ "AcceptedAnswerId": "234813", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T01:14:22.667", "Id": "234810", "Score": "2", "Tags": [ "python", "signal-processing" ], "Title": "Script to check zero crossings to check if microphones phases are aligned" }
234810
<p><strong>Task</strong></p> <blockquote> <p>You have an array of positive integers. Your task is to find an integer <code>x</code> such that the following are true:</p> <ul> <li>Bitwise AND between <code>x</code> and each array element is non-zero.</li> <li>Number of ones in the binary expression of <code>x</code> is minimum.</li> <li>If there are many such <code>x</code>, you should find smallest of them.</li> </ul> <p><strong>Input Format</strong></p> <p>The first line contains a single integer <code>n</code>, the number of elements in the array. The second line contains <code>n</code> space-separated integers.</p> <p><strong>Constraints</strong></p> <ul> <li><p>1&lt;=<code>n</code>&lt;=10,000 </p></li> <li><p>array elements are in range <code>[1; 2^26)</code></p></li> </ul> </blockquote> <p>Please find a full description of the problem <a href="https://www.hackerrank.com/contests/world-codesprint-11/challenges/best-mask/problem" rel="nofollow noreferrer">here</a>.</p> <p><strong>My Effort</strong></p> <ul> <li>Count a number of binary <code>1's</code> for each number from <code>1</code> to <span class="math-container">\$2^{26} - 1\$</span>.</li> <li>Sort each number from <code>1</code> to <span class="math-container">\$2^{26} - 1\$</span> by its number of binary <code>1's</code>. Use a normal <code>std::sort()</code>. Unfortunately, the counting sort is not an option here as its space complexity is too high for <a href="https://www.hackerrank.com/environment" rel="nofollow noreferrer">Hackerrank environment</a>.</li> <li>Check each sorted number from the previous step against the array numbers. If its <code>AND</code> with all of them is not <code>0</code> - we've found the answer.</li> </ul> <p>This approach has a <span class="math-container">\$O(m \cdot \log(m) \cdot n)\$</span> time and <span class="math-container">\$O(m)\$</span> space complexity where <code>m</code> - maximum value of an array element and <code>n</code> - size of the array. So, it produces a timeout error for every test case. It produces the correct result, though - I ran it locally for a couple of test cases.</p> <p>I've tried a <span class="math-container">\$O(m \cdot n)\$</span> time and <span class="math-container">\$O(2 \cdot m)\$</span> space complexity solution (using the counting sort) but it didn't work due to a segmentation fault. As stated before, there's a limit as to how much memory one can use for this problem and that one was exceeded.</p> <p><strong>Code</strong></p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;bitset&gt; uint32_t solve(std::vector&lt;uint32_t&gt;&amp; array) { const uint32_t upperBoundValue = (1 &lt;&lt; 26); std::vector&lt;uint32_t&gt; candidateNumbers(upperBoundValue); for (uint32_t i = 0; i &lt; upperBoundValue; i++) { candidateNumbers[i] = i; } // sort all possible x's by their binary 1's in ascending order std::sort(candidateNumbers.begin(), candidateNumbers.end(), [](const auto&amp; a, const auto&amp; b) { std::bitset&lt;26&gt; bitSet1(a); std::bitset&lt;26&gt; bitSet2(b); size_t count1 = bitSet1.count(); size_t count2 = bitSet2.count(); if (count1 &lt; count2) { return true; } else if (count2 &lt; count1) { return false; } else { return a &lt; b; } }); // exclude duplicates from the array to reduce its size std::sort(array.begin(), array.end()); array.erase(unique(array.begin(), array.end()), array.end()); uint32_t candidateIndex; for (candidateIndex = 0; candidateIndex &lt; upperBoundValue; candidateIndex++) { bool candidateFound = true; for (uint32_t index = 0; index &lt; array.size(); index++) { if (!(candidateNumbers[candidateIndex] &amp; array[index])) { candidateFound = false; break; } } if (candidateFound) { break; } } return candidateNumbers[candidateIndex]; } int main() { //read an array size uint32_t size; std::cin &gt;&gt; size; //save each value into the corresponding array position std::vector&lt;uint32_t&gt; array(size); for (auto&amp; element : array) { std::cin &gt;&gt; element; } uint32_t bestMask = solve(array); std::cout &lt;&lt; bestMask &lt;&lt; "\n"; return 0; } </code></pre> <p><strong>Question</strong></p> <p>Is there a way to improve the time complexity of this solution without exceeding the space limitation? Should a completely different approach be used here?</p>
[]
[ { "body": "<blockquote>\n <p>Is there a way to improve the time complexity of this solution without\n exceeding the space limitation?</p>\n</blockquote>\n\n<p>Yes, there's a way. We don't actually need any additional array of numbers because we can check all numbers from <code>1</code> to the maximum possible mask for given elements of the array. Then, we will perform <code>AND</code> of the current number candidate with all array elements only if its <code>1's</code> count lower than that of the current best candidate. Please check the code for more details.</p>\n\n<blockquote>\n <p>Should a completely different approach be used here?</p>\n</blockquote>\n\n<p>I've come up with a similar brute force approach that requires only additional <code>O(1)</code> space. It's quite simple and also passes all the tests. </p>\n\n<p><strong>Remove duplicates from the original array</strong></p>\n\n<p>We can safely do it because duplicate elements do not influence the final answer. It also helps us to reduce the size of the array and thus improve the time complexity of the algorithm.</p>\n\n<p><strong>Sort the array by 1's count</strong></p>\n\n<p>By doing so, we won't perform a bitwise <code>AND</code> for most of best mask candidates with <strong>ALL</strong> array elements and thus save a lot of execution time.</p>\n\n<p><strong>Perform <code>AND</code> only for candidate numbers having fewer <code>1's</code></strong></p>\n\n<p>That's another important optimisation. Before checking a candidate against the array elements make sure it has fewer <code>1's</code> than the current best candidate. </p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;bitset&gt;\n\nuint8_t popCount(const uint32_t&amp; number) {\n std::bitset&lt;26&gt; bitSet(number);\n\n return bitSet.count();\n}\n\nuint32_t solve(std::vector&lt;uint32_t&gt;&amp; array) {\n // exclude duplicates from the array to reduce its size\n std::sort(array.begin(), array.end());\n array.erase(unique(array.begin(), array.end()), array.end());\n\n // sort array elements based on their 1's count in ascending order\n std::sort(array.begin(), array.end(), [](const auto&amp; a, const auto&amp; b) {\n uint8_t count1 = popCount(a);\n uint8_t count2 = popCount(b);\n\n if (count1 == count2) {\n return a &lt; b;\n }\n return count1 &lt; count2;\n });\n\n // Initially, bestMask is the maximum possible mask\n uint32_t maxPossibleMask = 0;\n for (const auto&amp; element : array) {\n maxPossibleMask |= element;\n }\n\n uint32_t bestMask = maxPossibleMask;\n for (uint32_t bestMaskCandidate = 1; bestMaskCandidate &lt; maxPossibleMask; bestMaskCandidate++) {\n if (popCount(bestMaskCandidate) &lt; popCount(bestMask)) {\n\n bool candidateFound = true;\n for (uint32_t index = 0; index &lt; array.size(); index++) {\n if (!(bestMaskCandidate &amp; array[index])) {\n candidateFound = false;\n break;\n }\n }\n\n if (candidateFound) {\n bestMask = bestMaskCandidate;\n }\n }\n }\n\n return bestMask;\n}\n\nint main() {\n //read an array size\n uint32_t size;\n std::cin &gt;&gt; size;\n\n //save each value into the corresponding array position\n std::vector&lt;uint32_t&gt; array(size);\n for (auto&amp; element : array) {\n std::cin &gt;&gt; element;\n }\n\n uint32_t bestMask = solve(array);\n std::cout &lt;&lt; bestMask &lt;&lt; \"\\n\";\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T00:37:45.057", "Id": "234843", "ParentId": "234811", "Score": "1" } } ]
{ "AcceptedAnswerId": "234843", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T01:47:03.993", "Id": "234811", "Score": "4", "Tags": [ "c++", "algorithm", "programming-challenge", "time-limit-exceeded", "c++14" ], "Title": "Find positive integer with a minimum number of binary 1's such that its bitwise AND with all array elements is not 0" }
234811
<p><strong>Background:</strong></p> <p>I have a TCP online multiplayer game server, which the player requests to log-in. However, the game server does not handle the authentication part of the login process, instead, it uses an outer micro-service which is an HTTP server to see if the user can authenticate with the given credentials. </p> <p><strong><em>Now why is that a problem?</em></strong> - Well I use <a href="https://netty.io/" rel="nofollow noreferrer">netty.io</a> networking framework, which is a non-blocking framework, it handles all connections in a sequence on the same thread. Since I don't want to cause any delays, I will not send an HTTP request on the same thread because I don't want to stop it.</p> <p>Instead I followed a pattern of callbacks like java script promise resolve-reject, and I Would like to hear what you think, and if it could be done better.</p> <p>Don't mind the generic types, just take the basic idea of it:</p> <p>First of all this is my <code>ServiceProvider</code>, the point of this class is to provide a singleton of each service that interacts with microservices such as UserService which is an HTTP server to handle everything related to user (authentication, data, etc):</p> <pre><code>public class ServiceProvider { private static ExecutorService executorService = Executors.newFixedThreadPool(ServicesConfig.SERVICES_THREAD_POOL_CAPACITY); private static UserService userService; /** * Provdes an user service singleton instance * @return The user service */ public static UserService getUserService() { if (userService == null) { userService = new UserService(); userService.setBaseUrl(ServicesConfig.USER_SERVICE_BASE_URL); } return userService; } public static void submitServiceTask(ServicePromise task) { executorService.submit(task); } } </code></pre> <p>Secondly is my <code>UserService</code> for example:</p> <pre><code>public class UserService extends HeroesHttpService { /** * Authenticates an user * @param username The username * @param password The password * @return ? */ public ServicePromise&lt;?&gt; authenticateUser(String username, String password) { ServicePromise&lt;HttpResponse&gt; promise = new ServicePromise&lt;HttpResponse&gt;() { @Override public void run() { HttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(getBaseUrl() + "/user/authenticate"); try { HttpResponse response = client.execute(request); resolve(response); } catch (IOException e) { e.printStackTrace(); } } }; ServiceProvider.submitServiceTask(promise); return promise; } } </code></pre> <p>Now this is my promise interface: </p> <pre><code>public abstract class ServicePromise&lt;T&gt; implements Runnable { private ServicePromiseCallback&lt;T&gt; callback; public ServicePromise&lt;T&gt; then(ServicePromiseCallback&lt;T&gt; cb) { this.callback = cb; return this; } @Override public void run() { } public void resolve(T data) { if (this.callback == null) { return; } this.callback.onResolve(data); } public void reject(T data) { if (this.callback == null) { return; } this.callback.onReject(data); } } </code></pre> <p>And that's the callback interface:</p> <pre><code>public interface ServicePromiseCallback&lt;T&gt; { void onResolve(T response); void onReject(T response); } </code></pre> <p>And finally, thats how I use it:</p> <pre><code> ServiceProvider.getUserService().authenticateUser(player.playerName, player.playerPass).then(new ServicePromiseCallback&lt;?&gt; () { @Override public void onResolve(Object response) { } @Override public void onReject(Object response) { } }); </code></pre> <p>Again, don't mind the types in resolve/reject, it's going to definitely be <code>AuthenticateUserResponseDto</code> and so on, but it doesn't matter right now </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:44:39.137", "Id": "459284", "Score": "0", "body": "I don't understand the use case: user authentication **should** be a synchronized action. the client must block until user is authenticated. so what kind of \"delay\" do you want to resolve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:46:18.743", "Id": "459285", "Score": "0", "body": "The client waits for the response, the game server is not an HTTP server, it doesn't wait for a response by protocol, it will just receive a success packet once the process is finished, or failure packet. I don't want to stop the main thread that handles all users for this login request" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:47:38.270", "Id": "459286", "Score": "0", "body": "You have to look at it like this; You have 1000 users, logging in every time, if you will send a request or bulk of requests every X time, each user has to wait for each login to finish. but if you handle each login request (the call to the user HTTP server) on a different thread, this solves the issue of waiting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:49:23.877", "Id": "459287", "Score": "0", "body": "for example player A tries to login, now player B tries to login, but the thread handles player A's http request, thread is locked, therefore B wont execute until A finishes, but what about C, D, E players which are already logged in? they will not receive an update, and in a game server it is important to send update packets otherwise the game will start \"lagging\" (unless the requests take less than 600ms which is the tick rate) in my game specifically" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:54:45.457", "Id": "459289", "Score": "1", "body": "please update the question with the new info. it is not specified that this is an online multi player scenario (I was thinking along the lines of online game service like kongregate)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T10:04:01.763", "Id": "459290", "Score": "0", "body": "This is example code, a hypothetical simplification of the real deal, isn't it? Please take a look at our [help/on-topic]." } ]
[ { "body": "<p>the <code>ServiceProvider</code> is supposed to provide a singleton instance of <code>UserService</code> but it does not follow all the principles of the Singleton design pattern. specifically, the locking mechanisms that prevent multiple threads from creating multiple instances of <code>UserService</code> (or rather, multiple calling of the constructor)</p>\n\n<p>and while on the subject - why not use <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a>?</p>\n\n<p>also, <code>reject(response)</code> is never called</p>\n\n<p>with regard to the issue of the \"javascript-like promise resolve-reject\": Java has such a mechanism: <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html\" rel=\"nofollow noreferrer\"><code>CompletableFuture</code></a> where you supply a <code>Runnable</code> and for the callbacks there are <code>thenApply()</code> <code>thenAccept()</code> and <code>thenRun()</code> methods. exceptions are handled by <code>exceptionally()</code> method. There are other capabilities like chaining <code>CompletableFuture</code> instances (<code>thenCompose()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T11:13:14.773", "Id": "459295", "Score": "0", "body": "So you are basically saying that multiple threads are going to use that user service reference provided, which may cause a conflict (because I don't synchronize them), should I make it a new instance of user service instead? And I dont use dependecy injeciton because the project is large, adding dependcy injection to it is an hassle, its either use it everywhere or nothing, can't break the convention" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T11:14:08.543", "Id": "459297", "Score": "0", "body": "Would love to see an example of firing a Runnable with thread pool Executors and received a CompletableFuture, I had issues with it which took me to a too complicated door" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:21:41.970", "Id": "459302", "Score": "0", "body": "`UserService` instance is static so there will always be one instance (if you have one class loader) but multiple threads may enter the `if` statement and call the constructor. You should look up singleton design pattern double checked locking mechanism. you should also be aware that in today's software applications singleton are injected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:22:40.153", "Id": "459303", "Score": "0", "body": "there are several tutorials about working with `CompletableFuture` with examples." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:10:34.417", "Id": "459310", "Score": "0", "body": "But that shouldn't be a problem should it? all threads read the same state of a reference, if userService is null, it will create new, but only once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:33:40.893", "Id": "459313", "Score": "0", "body": "no. OS causes context switch and makes threads go to sleep. so multiple threads can pass the if statement and go to sleep before the instance is created. you should **really** search and read on design pattern double checked locking to realize multiple threads issues" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T08:54:16.077", "Id": "459411", "Score": "0", "body": "Obviously you are right, dependency injection container would be a good choice to go there instead of using singleton I can just use a DI container to provide user service as a singleton injection. However that would require a big refactor since you have to map the DI container from the beginning of the application with guice or spring. I don't really have time for that, that is the main reason I used singleton. on the other hand i can just pass the instance of user service everywhere manually around my app but that can be very confusing don't you agree" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:00:51.363", "Id": "459413", "Score": "0", "body": "if you gonna stick with singleton, I suggest you initialize the instance in a static block. that would ensure the constructor is called one time only" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:06:18.970", "Id": "459415", "Score": "0", "body": "you mean init it with static constructor? `static { userService = new ... }` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:08:36.150", "Id": "459416", "Score": "1", "body": "yes, yes, yes,." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:13:00.513", "Id": "459417", "Score": "0", "body": "and if I init it with a static consuturctor does it *ensure* that its initialized before everything and I don't have to use an if statement or any locks when I get the instance with a static method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:25:55.857", "Id": "459419", "Score": "1", "body": "not sure about \"before everything\". the static block is executed by the class loader when the class is first referenced and is loaded into memory" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T10:43:26.267", "Id": "234819", "ParentId": "234816", "Score": "2" } } ]
{ "AcceptedAnswerId": "234819", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T09:38:30.507", "Id": "234816", "Score": "1", "Tags": [ "java", "multithreading", "networking" ], "Title": "Java implementing task on another thread with javascript-like promise resolve-reject" }
234816
<p>I have followed a mysqli tutorial to create a login with cookies and session with remember me authentication in pdo.</p> <p>in tutorial class had a new <code>db_connection</code>, I tried to inject my pdo connection in to class, same as in here: <a href="https://phpdelusions.net/pdo" rel="nofollow noreferrer">https://phpdelusions.net/pdo</a> and read some answers in stackowerflow by <code>Your Common Sence</code> and <code>dharman</code> answers for injecting pdo connection in to class.</p> <p>I was getting errors on it, so I changed it to <code>global $pdo;</code>.</p> <p>I need your reviews and your reccomendations on my login script, especially on <code>sessionCheck.php</code> security and corrections. I am not a perofessional coder yet :) but trying hard and learning very fast, so please dont yell on me, and if possible show your recommendations with examples, Thanks</p> <p>Here is my login handler class which is doing all queries simple:</p> <blockquote> <p>LoginHandler.php</p> </blockquote> <pre><code>class LoginHandler { function runBaseQuery($sql, $args) { global $pdo; if (!$args){ return $pdo-&gt;query($sql); } $stmt = $pdo-&gt;prepare($sql); $stmt-&gt;execute($args); if ($stmt-&gt;rowCount() &gt; 0) { while($row = $stmt-&gt;fetch()) { $resultset[] = $row; } } if(!empty($resultset)) { return $resultset; } } function bindQueryParams($sql, $args){ global $pdo; if (!$args){ return $pdo-&gt;query($sql); } $stmt = $pdo-&gt;prepare($sql); $stmt-&gt;execute($args); return $stmt; } } </code></pre> <blockquote> <p>Auth.php</p> </blockquote> <pre><code>require_once "../db.php"; require "LoginHandler.php"; class Auth { function getMemberByUsername($username) { global $pdo; $Lhandle = new LoginHandler(); $sql = "Select * from users where username = ?"; $result = $Lhandle-&gt;runBaseQuery($sql, array($username)); return $result; } function getTokenByUsername($username,$expired) { global $pdo; $Lhandle = new LoginHandler(); $sql = "Select * from Auth_tokens where username = ? and is_expired = ?"; $result = $Lhandle-&gt;runBaseQuery($sql, array($username, $expired)); return $result; } function markAsExpired($tokenId) { global $pdo; $Lhandle = new LoginHandler(); $sql = "UPDATE Auth_tokens SET is_expired = ? WHERE id = ?"; $expired = 1; $result = $Lhandle-&gt;bindQueryParams($sql, array($expired, $tokenId)); return $result; } function insertToken($username, $random_password_hash, $random_selector_hash, $expiry_date) { global $pdo; $Lhandle = new LoginHandler(); $sql = "INSERT INTO Auth_tokens (username, password_hash, selector_hash, expiry_date) values (?, ?, ?, ?)"; $result = $Lhandle-&gt;bindQueryParams($sql, array($username, $random_password_hash, $random_selector_hash, $expiry_date)); return $result; } } </code></pre> <blockquote> <p>Util.php</p> </blockquote> <pre><code>class Util { public function getToken($length) { $token = ""; $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $codeAlphabet .= "abcdefghijklmnopqrstuvwxyz"; $codeAlphabet .= "0123456789"; $max = strlen($codeAlphabet) - 1; for ($i = 0; $i &lt; $length; $i ++) { $token .= $codeAlphabet[$this-&gt;cryptoRandSecure(0, $max)]; } return $token; } public function cryptoRandSecure($min, $max) { $range = $max - $min; if ($range &lt; 1) { return $min; // not so random... } $log = ceil(log($range, 2)); $bytes = (int) ($log / 8) + 1; // length in bytes $bits = (int) $log + 1; // length in bits $filter = (int) (1 &lt;&lt; $bits) - 1; // set all lower bits to 1 do { $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))); $rnd = $rnd &amp; $filter; // discard irrelevant bits } while ($rnd &gt;= $range); return $min + $rnd; } public function redirect($url) { header("Location:" . $url); exit(); } public function clearAuthCookie() { if (isset($_COOKIE["member_login"])) { setcookie("member_login", ""); } if (isset($_COOKIE["random_password"])) { setcookie("random_password", ""); } if (isset($_COOKIE["random_selector"])) { setcookie("random_selector", ""); } } } </code></pre> <blockquote> <p>sessionCheck.php</p> </blockquote> <pre><code>require_once "Auth.php"; require_once "Util.php"; $auth = new Auth(); $util = new Util(); // Get Current date, time $current_time = time(); $current_date = date("Y-m-d H:i:s", $current_time); // Set Cookie expiration for 1 month $cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month $isLoggedIn = false; // Check if loggedin session and redirect if session exists if(!empty($_SESSION["uid"])) { $isLoggedIn = true; } // Check if loggedin session exists else if(!empty($_COOKIE["member_login"]) &amp;&amp; !empty($_COOKIE["random_password"]) &amp;&amp; !empty($_COOKIE["random_selector"])) { // Initiate auth token verification directive to false $isPasswordVerified = false; $isSelectorVerified = false; $isExpiryDateVerified = false; // Get token for username $userToken = $auth-&gt;getTokenByUsername($_COOKIE["member_login"],0); // Validate random password cookie with database if(password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) { $isPasswordVerified = true; } // Validate random selector cookie with database if(password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) { $isSelectorVerified = true; } // check cookie expiration by date if($userToken[0]["expiry_date"] &gt;= $current_date) { $isExpiryDareVerified = true; } // Redirect if all cookie based validation retuens true // Else, mark the token as expired and clear cookies if(!empty($userToken[0]["id"]) &amp;&amp; $isPasswordVerified &amp;&amp; $isSelectorVerified &amp;&amp; $isExpiryDareVerified) { $isLoggedIn = true; } else { if(!empty($userToken[0]["id"])) { $auth-&gt;markAsExpired($userToken[0]["id"]); } // clear cookies $util-&gt;clearAuthCookie(); } } </code></pre> <blockquote> <p>And finally login.php</p> </blockquote> <pre><code>require_once "../db.php"; require_once "../includes/functions.php"; require_once "Auth.php"; require_once "Util.php"; $auth = new Auth(); $Lhandle = new LoginHandler(); $util = new Util(); require_once "sessionCheck.php"; if ($isLoggedIn) { $util-&gt;redirect("dashboard.php"); } if (isset($_POST["login"])) { $isAuthenticated = false; $kulladi = test_input($_POST["username"]); $sifre = test_input($_POST["password"]); $furl = test_input(base64_decode($_POST["refurl"])); // Validate the username. if (empty($kulladi)) { $message[] = 'Please provide a username.'; } elseif (!preg_match('/^[a-zA-Z0-9]*$/', $kulladi)) { $message[] = 'The username contains invalid characters.'; } else { $username = test_input($kulladi); } // Validate the password. if (empty($sifre)) { $message[] = 'Empty password field.'; } else { $password = test_input($sifre); } // Validate if referer url set. if (isset($_POST['refurl']) &amp;&amp; !empty($_POST['refurl'])) { $refurl = $furl; } else { $refurl = 'dashboard.php'; } if(empty($message)){ if($user = $auth-&gt;getMemberByUsername($username)){ if(password_verify($password, $user[0]["password"])) { $isAuthenticated = true; $_SESSION["uid"] = $user[0]["uid"]; $_SESSION["username"] = $user[0]["username"]; // Set Auth Cookies if 'Remember Me' checked if (!empty($_POST["remember"])) { setcookie("member_login", $username, $cookie_expiration_time); $random_password = $util-&gt;getToken(16); setcookie("random_password", $random_password, $cookie_expiration_time); $random_selector = $util-&gt;getToken(32); setcookie("random_selector", $random_selector, $cookie_expiration_time); $random_password_hash = password_hash($random_password, PASSWORD_DEFAULT); $random_selector_hash = password_hash($random_selector, PASSWORD_DEFAULT); $expiry_date = date("Y-m-d H:i:s", $cookie_expiration_time); // mark existing token as expired $userToken = $auth-&gt;getTokenByUsername($username, 0); if (!empty($userToken[0]["id"])) { $auth-&gt;markAsExpired($userToken[0]["id"]); } // Insert new token $auth-&gt;insertToken($username, $random_password_hash, $random_selector_hash, $expiry_date); } else { $util-&gt;clearAuthCookie(); } $util-&gt;redirect($refurl); }else{ $message[] = "invalid user password"; } }else{ $message[] = "invalid user logins"; } } } </code></pre> <blockquote> <p>And html codes in login.php</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form action="" method="post" id="frmLogin"&gt; &lt;div class="error-message"&gt; &lt;?php if(isset($message)) {?&gt; &lt;?php echo implode('&lt;br/&gt;', $message); ?&gt; &lt;/div&gt; &lt;?php } else{ ?&gt; &lt;div class="success-message"&gt; You have successfully created your account. &lt;br/&gt;Would you like to &lt;a href="#"&gt;login&lt;/a&gt; now? &lt;/div&gt; &lt;?php } ?&gt; &lt;div class="field-group"&gt; &lt;div&gt; &lt;label for="login"&gt;Username&lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input name="username" type="text" value="&lt;?php if(isset($_COOKIE["member_login"])) { echo $_COOKIE["member_login"]; } ?&gt;" class="input-field"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="field-group"&gt; &lt;div&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;/div&gt; &lt;div&gt; &lt;input name="password" type="password" value="&lt;?php if(isset($_COOKIE["password"])) { echo $_COOKIE["password"]; } ?&gt;" class="input-field"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="field-group"&gt; &lt;div&gt; &lt;input type="checkbox" name="remember" id="remember" &lt;?php if(isset($_COOKIE["member_login"])) { ?&gt; checked &lt;?php } ?&gt; /&gt; &lt;label for="remember-me"&gt;Remember me&lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="field-group"&gt; &lt;div&gt; &lt;?php if(isset($_SERVER['HTTP_REFERER'])){ ?&gt; &lt;input type="hidden" name="refurl" value="&lt;?php echo base64_encode($_SERVER['HTTP_REFERER']); ?&gt;" /&gt; &lt;?php } ?&gt; &lt;input type="submit" name="login" value="Login" class="form-submit-button"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>And This is the function used for filter inputs. Note: didnt filter all inputs yet, but will.</p> <pre><code>function test_input($data) { $data = filter_var(trim($data), FILTER_SANITIZE_STRING); $data = stripslashes($data); $data = htmlspecialchars($data); $data = strip_tags($data); return $data; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T14:06:46.253", "Id": "459319", "Score": "0", "body": "Welcome to code review, does the code work as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:54:40.240", "Id": "459390", "Score": "0", "body": "FYI, `date()`'s default second parameter is `time()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T14:14:25.347", "Id": "459430", "Score": "0", "body": "@mickmackusa to find `date()` and `time()` and compare with cookie expiry time `userToken[0][\"expiry_date\"] >= $current_date`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:20:07.613", "Id": "459434", "Score": "0", "body": "Ah yes, I see now that you use time twice. Something else... `isset($_POST['refurl'])` is not needed if followed by `!empty()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:37:39.693", "Id": "459553", "Score": "2", "body": "For one, you don't need nor should you be using that `test_input()` function with those functions in there. They don't do much to prevent a potential SQL injection. A prepared statement will take care of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:47:15.257", "Id": "459555", "Score": "0", "body": "@FunkFortyNiner I use prepare statement in `LoginHandler.php` and `Auth.php` Do I need to use bindParam ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:49:28.277", "Id": "459557", "Score": "0", "body": "I noticed that you are using a prepared statement. I just wonder why you have that `test_input()` function. It doesn't help at all. It isn't even safe. You'd probably be doing more harm than good for passwords / usernames." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:51:47.407", "Id": "459558", "Score": "0", "body": "its a routine of me :) will remove test_input and use `htmlspecialchars` or `sanitize_string` if needed now on. actualy I was thinking to post in stackoverflow but code was to long so I just changed to global connect" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:53:38.800", "Id": "459559", "Score": "0", "body": "About your *\"but keep getting errors on it, so I changed it to global $pdo;\"* - I am wondering why you posted your question in code review. If this is about code not working, then it should be moved/migrated over to Stack Overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:59:31.480", "Id": "459560", "Score": "0", "body": "its working fine now, there was a few worthless functions in class I removed them all and droped two function so all queries on two functions now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:21:52.673", "Id": "459670", "Score": "0", "body": "_\"...and use htmlspecialchars or sanitize_string\"_ - It's better to store the data \"as is\" and then use the correct escape function when you fetch and _use_ the data. Like using `htmlspecialchars()` to prevent XSS. Different types of output can require different types of escaping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:30:14.827", "Id": "459672", "Score": "0", "body": "@MagnusEriksson Thanks for point I do that in both insert and select, but didnt know its not importand in insert part will remove htmlspecialchars too. I am afraid of sessionCheck.php getting parameters from cookies on user return and login in, I need to know if sessionCheck.php is safe ? I added brute force check login too." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T10:56:49.167", "Id": "234821", "Score": "2", "Tags": [ "php", "authentication", "pdo" ], "Title": "PHP Secure Remember Me for Login using PHP Session and Cookies with referer url" }
234821
<p>So I have a piece a code that, altough it does what is expected, it doesn't seam very performant to me. I just wanted to know if there's a better way to do this or if my code is alright as it is.</p> <p>The objective of the code is to recieve an image path, check if the image exists or if it isn't png, if the image isn't png convert it to png and return a byte[] of the stream.</p> <p>the code:</p> <pre><code> // the speed of the method, on my computer, as is, right now, is of 40ms per cycle, this means 10 cycles are around 400ms public static byte[] GetBytesFromImage(string imageName) { byte[] bytes = null; string imagePath = "..\\..\\Imagens"; imageName = imageName == "" ? "\\logotipos-prototipo_logo_prototipo_print.jpg" : imageName; string fpath = imagePath + imageName; if (File.Exists(fpath) &amp;&amp; !imageName.EndsWith("png")) { using (MemoryStream image = new MemoryStream()) using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(fpath)) using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height)) using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage)) { gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel); bmpNewImage.Save(image, ImageFormat.Png); bytes = image.ToArray(); } } return bytes; } </code></pre> <p><strong>1st Update:</strong> As the <a href="https://codereview.stackexchange.com/a/234823/185233">@Nkosi's answer</a> mentioned, I forgot to make a case for when the image is PNG, and also to deal with the method returning a potencial null <code>byte[]</code>.<br> Also in his change now the <code>MemoryStream</code> is shared in both cases, and the <code>string</code> comparison now ignores the <code>string</code> case.</p> <pre><code> readonly string BASEIMAGEPATH = "..\\..\\Imagens\\"; readonly string DEFAULTIMAGENAME = "logotipos-prototipo_logo_prototipo_print.jpg"; // the speed of the method, on my computer, as is, right now, is of 40ms per cycle, this means 10 cycles are around 400ms public static byte[] GetBytesFromImage(string imageName) { byte[] bytes = null; imageName = imageName == "" ? DEFAULTIMAGENAME : imageName; string path = Path.Combine(BASEIMAGEPATH, imageName); if (File.Exists(path)) { // Now both cases use the same MemoryStream using (MemoryStream image = new MemoryStream()) { // The comparison now ignores case if (imageName.EndsWith("png", StringComparison.InvariantCultureIgnoreCase)) { using (FileStream imageStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { imageStream.CopyTo(image); bytes = image.ToArray(); } } else { using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(path)) using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height)) using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage)) { gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel); bmpNewImage.Save(image, ImageFormat.Png); bytes = image.ToArray(); } } } } // I changed his code here because `Array.Empty&lt;byte&gt;()` didn't exist. return bytes ?? new byte[0]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:18:06.113", "Id": "459300", "Score": "0", "body": "Why the `for` loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:19:03.607", "Id": "459301", "Score": "0", "body": "that was just adde to test various iterations of that part of the method, it isn't doing nothing functionally" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:29:33.247", "Id": "459305", "Score": "1", "body": "I edited it, so that the for loop is no longer there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:42:56.117", "Id": "459358", "Score": "0", "body": "Please don't change your code after receiving an answer, as it invalidates the answer. You can always ask a new question using updated code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:14:00.977", "Id": "459418", "Score": "0", "body": "Oh! sorry, I can make an Update and distinguish both, or leave the old code." } ]
[ { "body": "<p>There is a lot of unnecessary noise in the function.</p>\n\n<p>If the base path is not expected to change it can be moved out into a constant.</p>\n\n<p><code>System.IO.Path</code> can be used to construct the path to the desired image.</p>\n\n<p>To avoid null reference errors when consuming this function, try to avoid returning null. An empty array should be returned.</p>\n\n<pre><code>const string BASEIMAGEPATH = \"..\\\\..\\\\Imagens\";\nconst string DEFAULTIMAGENAME = \"\\\\logotipos-prototipo_logo_prototipo_print.jpg\";\n\npublic static byte[] GetBytesFromImage(string imageName) {\n byte[] bytes = null;\n imageName = imageName == \"\" ? DEFAULTIMAGENAME : imageName;\n string path = Path.Combine(BASEIMAGEPATH, imageName);\n if (File.Exists(path) &amp;&amp; !imageName.EndsWith(\"png\", StringComparison.InvariantCultureIgnoreCase)) {\n using (MemoryStream image = new MemoryStream())\n using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(path))\n using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height))\n using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage)) {\n gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel);\n bmpNewImage.Save(image, ImageFormat.Png);\n bytes = image.ToArray();\n }\n }\n return bytes ?? Array.Empty&lt;byte&gt;();\n}\n</code></pre>\n\n<p>The logic should also be reviewed as it was stated</p>\n\n<blockquote>\n <p>The objective of the code is to receive an image path, check if the image exists or if it isn't png, if the image isn't png convert it to png and return a byte[] of the stream.</p>\n</blockquote>\n\n<p>but currently, if the image exists <strong>and</strong> is already a PNG, it wont return the contents of the file.</p>\n\n<pre><code>const string BASEIMAGEPATH = \"..\\\\..\\\\Imagens\";\nconst string DEFAULTIMAGENAME = \"\\\\logotipos-prototipo_logo_prototipo_print.jpg\";\n\npublic static byte[] GetBytesFromImage(string imageName) {\n byte[] bytes = null;\n imageName = imageName == \"\" ? DEFAULTIMAGENAME : imageName;\n string path = Path.Combine(BASEIMAGEPATH, imageName);\n if (File.Exists(path)) {\n using (MemoryStream image = new MemoryStream()) {\n if (imageName.EndsWith(\"png\", StringComparison.InvariantCultureIgnoreCase)) {\n using (FileStream imageStream = new FileStream(path, FileMode.Open, FileAccess.Read)) {\n imageStream.CopyTo(image);\n bytes = image.ToArray();\n }\n } else {\n using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(path))\n using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height))\n using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage)) {\n gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel);\n bmpNewImage.Save(image, ImageFormat.Png);\n bytes = image.ToArray();\n }\n }\n }\n }\n return bytes ?? Array.Empty&lt;byte&gt;();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:42:24.773", "Id": "459306", "Score": "0", "body": "thanks for your reply, you certainly have a point there, I hadn't considered that if the image is a PNG then it wont return the array. As for the path, I just put a generic path to help visualize the method." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:31:53.907", "Id": "234823", "ParentId": "234822", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:02:57.247", "Id": "234822", "Score": "1", "Tags": [ "c#", "performance", "image", "converting", "stream" ], "Title": "Image type convertion" }
234822
<p>Implementing signal slot mechanism again seems quite dumb because there are so many people already done this before but it is for learning and I intended some specific goals.</p> <p>I had some library in mind which is easy and safe to use and relies on C++14 only. The possibility of member function connection and disconnection must be possible too. Achieving normal function connection is easy but I saw a lot of nearly unreadable (but still very well designed) code to achieve member function connection. There is also a need to have a single signal class called an emitter which is able to emit different signals and holds all pointers to the slots.</p> <p>To achieve this there is the Emitter class which takes variadic template arguments of all signals you want to emit. This implies that you know your signals at compile time. The emitter contains a tuple which holds a SignalContainer where the actual function pointers are stored inside a vector. C++14 offers the ability to get a tuple element by type which is great to manage all possible signals inside a tuple without overblown code.</p> <p>Connecting signals to slot works with the connect() method of the emitter class. You must pass the signal type as template parameter because the emitter must know in which signal type it has to put the function pointer.</p> <h2>Code</h2> <pre><code>#ifndef EVENT_HPP_ #define EVENT_HPP_ #include &lt;atomic&gt; #include &lt;tuple&gt; #include &lt;mutex&gt; #include &lt;exception&gt; #include &lt;vector&gt; #include &lt;utility&gt; namespace events { namespace detail { struct Identifier { using id_type = unsigned int; static id_type get() { static std::atomic&lt;id_type&gt; id(0); return id++; } }; template&lt;typename TTuple, typename TFunc, std::size_t N&gt; struct TupleIterator { template&lt;typename ... TParams&gt; static constexpr void do_iterate(TTuple &amp;t, TParams ... params) { TFunc fn; fn(std::get&lt;N&gt;(t), params...); TupleIterator&lt;TTuple, TFunc, N-1&gt;::do_iterate(t, params...); } }; template&lt;typename TTuple, typename TFunc&gt; struct TupleIterator&lt;TTuple, TFunc, 0&gt; { template&lt;typename ... TParams&gt; static constexpr void do_iterate(TTuple &amp;t, TParams ... params) { TFunc fn; fn(std::get&lt;0&gt;(t), params...); } }; /** Iterate over a tuple in reverse order because * that was simple to implement. */ template&lt;typename TFunc, typename TTuple, typename ... TParams&gt; void iterate_tuple(TTuple &amp;t, TParams ... params) { TupleIterator&lt;TTuple, TFunc, std::tuple_size&lt;TTuple&gt;::value - 1&gt;::do_iterate(t, params...); } struct DisconnectAll { template&lt;typename TContainer&gt; void operator()(TContainer &amp;t) { t.slots.clear(); } }; /** Disconnects an object from a container. The * pointer to that object is given. */ struct DisconnectObject { template&lt;typename TObject, typename TContainer&gt; void operator()(TContainer &amp;t, TObject *obj) { t.slots.erase(std::remove_if(t.slots.begin(), t.slots.end(), [&amp;](typename TContainer::functional_type &amp;t){ /* Only delete when the pointer to an object * is different from nullptr to prevent deleting * non member function slots. */ if(t.getThisPtr() != nullptr &amp;&amp; t.getThisPtr() == obj) { return true; } else{ return false; } }), t.slots.end()); } }; template&lt;typename TSignal, typename TFunction, typename TObject&gt; struct FunctionalIdentifier { static detail::Identifier::id_type getID() { static detail::Identifier::id_type this_id = detail::Identifier::get() + 1; /* Start at 1 because zero is reserved */ return this_id; } }; /** The functional helper is the actual slot * which wraps functions and member functions * and keeps a unique identifier to be * able to compare which function or member * function is stored. */ template&lt;typename TSignal&gt; struct FunctionalHelper { FunctionalHelper() { this_ptr = nullptr; id = 0; } /** Normal function initialization. * */ template&lt;typename TFunction&gt; FunctionalHelper(TFunction f) : fn(f), this_ptr(nullptr) { id = FunctionalIdentifier&lt;TSignal, TFunction, std::nullptr_t&gt;::getID(); } template&lt;typename TObject&gt; FunctionalHelper(TObject *obj, typename TSignal::template member_function_pointer&lt;TObject&gt; ptr) { this_ptr = obj; id = FunctionalIdentifier&lt;TSignal, decltype(ptr), TObject&gt;::getID(); /* Use of C++14 generic lambda makes calling the member * function so much painless. Unpacking of the tuple happens inside the * CallHelper::call function. */ fn = [obj, ptr](auto &amp;&amp; ... args){ return (obj-&gt;*ptr)(std::forward&lt;decltype(args)&gt;(args)...); }; } template&lt;typename ... TArgs&gt; typename TSignal::return_type operator()(TArgs ... args) { return fn(std::forward&lt;TArgs&gt;(args)...); } std::size_t getID() const { return id; } void *getThisPtr() const { return this_ptr; } private: /** We use the std function here but there * is no safe way of comparing functions so we need * some more storage variables. */ typename TSignal::std_function_type fn; /** Keeping the pointer to an object is * required to delete that object later. */ void *this_ptr; /** This is an identifier which identifies * a signature. */ std::size_t id; }; } template&lt;typename TArgs&gt; struct Signal{}; /** This is nothing more than a containr for * a type you pass to the template argument list of the emitter * so the emitter knows which signal signatures you will * provide. There is no need to use this */ template&lt;typename TReturn, typename ...TParam&gt; struct Signal&lt;TReturn(TParam...)&gt; { public: using return_type = TReturn; using std_function_type = std::function&lt;TReturn(TParam...)&gt;; template&lt;typename TObject&gt; using member_function_pointer = return_type (TObject::*)(TParam...); detail::Identifier::id_type getID() const { static detail::Identifier::id_type this_id = detail::Identifier::get(); return this_id; } template&lt;typename TEmitter, typename TFunction&gt; static void connect(TEmitter &amp;e, TFunction fn) { e.template connect&lt;Signal&gt;(fn); } private: }; template&lt;class TSignal&gt; struct SignalContainer { using functional_type = typename detail::FunctionalHelper&lt;TSignal&gt;; std::vector&lt;detail::FunctionalHelper&lt;TSignal&gt;&gt; slots; std::mutex slots_mutex; }; /** Can emit events for the given event types. * */ template&lt;class ... TSignals&gt; class Emitter { public: /** * Connect a simple function to a specific signal. Use it the following way: * Emitter.connect&lt;SomeSignal&gt;(SomeStaticFunction). * * A call to this function will not check if the slot function has been registered * so a connection of the same function is possible and will raise the handler * multiple times when using emit(). * * The return is an identifier which is unique for types. It is not unique * for every call to connect(). */ template&lt;typename TSignal, typename TFunction&gt; std::size_t connect(TFunction fn) { auto &amp; container = getContainer&lt;TSignal&gt;(); std::lock_guard&lt;std::mutex&gt; lock(container.slots_mutex); container.slots.emplace_back(detail::FunctionalHelper&lt;TSignal&gt;(fn)); return container.slots.back().getID(); } template&lt;typename TSignal, typename TObject&gt; std::size_t connect(TObject *obj, typename TSignal::template member_function_pointer&lt;TObject&gt; ptr) { auto &amp; container = getContainer&lt;TSignal&gt;(); std::lock_guard&lt;std::mutex&gt; lock(container.slots_mutex); container.slots.emplace_back(detail::FunctionalHelper&lt;TSignal&gt;(obj, ptr)); return container.slots.back().getID(); } /** Disconnects all signals of the given type. * */ template&lt;typename TSignal&gt; void disconnect() { auto &amp; container = getContainer&lt;TSignal&gt;(); std::lock_guard&lt;std::mutex&gt; lock(container.slots_mutex); container.slots.clear(); } /** Disconnect all slots from a given object. */ template&lt;typename TObject&gt; void disconnect(TObject *obj) { detail::iterate_tuple&lt;detail::DisconnectObject&gt;(signals, obj); } /** Disconnects everything from the emitter. * */ void disconnect() { detail::iterate_tuple&lt;detail::DisconnectAll&gt;(signals); } template&lt;typename TSignal, typename ... TParams&gt; void emit(TParams &amp;&amp;...params) { auto &amp; container = getContainer&lt;TSignal&gt;(); std::lock_guard&lt;std::mutex&gt; lock(container.slots_mutex); for(auto &amp; it : container.slots) { /* Call the function. This does not * handle return parameters. */ it(std::forward&lt;TParams&gt;(params)...); } } private: /** This tuple contains the container * for every type which means we can get * the container for every specific type. * This relies on C++14 feature to get * a tuple element by its type. */ std::tuple&lt;SignalContainer&lt;TSignals&gt;...&gt; signals; /** Get the signal container for a specific signal * type. */ template&lt;typename TSignal&gt; SignalContainer&lt;TSignal&gt;&amp; getContainer() { return std::get&lt;SignalContainer&lt;TSignal&gt;&gt;(signals); } }; } #endif /* EVENT_HPP_ */ </code></pre> <hr> <h2>Example</h2> <pre><code>#include &lt;iostream&gt; static void test(int i) { std::cout &lt;&lt; "Received: " &lt;&lt; i &lt;&lt; std::endl; } struct Testclass { void test(int i) { std::cout &lt;&lt; "Received: " &lt;&lt; i &lt;&lt; std::endl; } void test1(unsigned int i) { std::cout &lt;&lt; "Received: " &lt;&lt; i &lt;&lt; std::endl; } }; struct Testclass1 { void test(int i) { std::cout &lt;&lt; "Received: " &lt;&lt; i &lt;&lt; std::endl; } void test1(unsigned int i) { std::cout &lt;&lt; "Received: " &lt;&lt; i &lt;&lt; std::endl; } }; int main(int argc, const char **argv) { using Signal1 = events::Signal&lt;void(int)&gt;; using Signal2 = events::Signal&lt;void(unsigned int)&gt;; Testclass tc; Testclass1 tc1; events::Emitter&lt;Signal1, Signal2&gt; em; std::cout &lt;&lt; "Connect: " &lt;&lt; em.connect&lt;Signal1&gt;(&amp;test) &lt;&lt; std::endl; std::cout &lt;&lt; "Connect: " &lt;&lt; em.connect&lt;Signal2&gt;(&amp;tc, &amp;Testclass::test1) &lt;&lt; std::endl; std::cout &lt;&lt; "Connect: " &lt;&lt; em.connect&lt;Signal1&gt;(&amp;tc, &amp;Testclass::test) &lt;&lt; std::endl; em.emit&lt;Signal1&gt;(123); em.disconnect(&amp;tc); em.emit&lt;Signal1&gt;(123); em.disconnect(); em.emit&lt;Signal1&gt;(123); } </code></pre> <h2>Notes</h2> <p>It may be useful to have some kind of slot which unregisters itself from classes. Another point is the connect method. You must always provide the signal as template parameter because the method must know what it needs to find inside the tuple. Maybe it could be useful to write a specialized function which checks if the emitter has just a single signal. I don't know how you guys would do that but I'm open to suggestions. </p>
[]
[ { "body": "<h2>Missing Include Headers</h2>\n\n<p>There are 2 missing include headers, in event.hpp <code>#include &lt;functional&gt;</code> and <code>#include &lt;algorithm&gt;</code> are missing (<code>std::remove_if()</code>). In the example code <code>#include \"event.hpp\"</code> is missing.</p>\n\n<h2>Indentation</h2>\n\n<p>This may be a copy and paste problem from your editor to the mark up editor, but <code>namespace detail {</code> and all the code in it should be indented since it is within <code>namespace events {</code>.</p>\n\n<p>To make the code easier to read and maintain it might be better if the <code>detail</code> namespace had it's own header file.</p>\n\n<h2>DisconnectObject</h2>\n\n<p>Since <code>(t.getThisPtr() != nullptr &amp;&amp; t.getThisPtr() == obj)</code> is a boolean expression the following code can be simplified:</p>\n\n<pre><code> struct DisconnectObject {\n\n template&lt;typename TObject, typename TContainer&gt;\n void operator()(TContainer &amp;t, TObject *obj) {\n t.slots.erase(std::remove_if(t.slots.begin(), t.slots.end(), [&amp;](typename TContainer::functional_type &amp;t){\n /* Only delete when the pointer to an object\n * is different from nullptr to prevent deleting\n * non member function slots.\n */\n if(t.getThisPtr() != nullptr &amp;&amp; t.getThisPtr() == obj) {\n return true;\n } else{\n return false;\n }\n }), t.slots.end());\n }\n };\n</code></pre>\n\n<p>To</p>\n\n<pre><code> struct DisconnectObject {\n\n template&lt;typename TObject, typename TContainer&gt;\n void operator()(TContainer &amp;t, TObject *obj) {\n t.slots.erase(std::remove_if(t.slots.begin(), t.slots.end(), [&amp;](typename TContainer::functional_type &amp;t){\n /* Only delete when the pointer to an object\n * is different from nullptr to prevent deleting\n * non member function slots.\n */\n return (t.getThisPtr() != nullptr &amp;&amp; t.getThisPtr() == obj);\n }), t.slots.end());\n }\n };\n</code></pre>\n\n<h2>Constructors for FunctionalHelper Inconsitently use Initializers</h2>\n\n<p>There are 3 different constructors for <code>FunctionalHelper</code> On doesn't use initializers at all, but could consist of only initializers</p>\n\n<pre><code> FunctionalHelper() {\n this_ptr = nullptr;\n id = 0;\n }\n</code></pre>\n\n<p>Could be refactored as </p>\n\n<pre><code> FunctionalHelper()\n : this_ptr{nullptr}, id{0}\n {\n }\n\n template&lt;typename TObject&gt;\n FunctionalHelper(TObject *obj, typename TSignal::template member_function_pointer&lt;TObject&gt; ptr) {\n this_ptr = obj;\n id = FunctionalIdentifier&lt;TSignal, decltype(ptr), TObject&gt;::getID();\n\n /* Use of C++14 generic lambda makes calling the member\n * function so much painless. Unpacking of the tuple happens inside the\n * CallHelper::call function.\n */\n fn = [obj, ptr](auto &amp;&amp; ... args){\n return (obj-&gt;*ptr)(std::forward&lt;decltype(args)&gt;(args)...);\n };\n }\n</code></pre>\n\n<p>Could be refactored as </p>\n\n<pre><code> template&lt;typename TObject&gt;\n FunctionalHelper(TObject *obj, typename TSignal::template member_function_pointer&lt;TObject&gt; ptr)\n : this_ptr {obj}\n {\n id = FunctionalIdentifier&lt;TSignal, decltype(ptr), TObject&gt;::getID();\n fn = [obj, ptr](auto &amp;&amp; ... args){\n return (obj-&gt;*ptr)(std::forward&lt;decltype(args)&gt;(args)...);\n };\n }\n</code></pre>\n\n<p>The functions <code>std::size_t getID()</code> and <code>void *getThisPtr()</code> are never used, this could indicate that the variables <code>id</code> and <code>this_ptr</code> are never used. Unused functions and unused variables can lead to problems during maintenance.</p>\n\n<p>The variable <code>this_ptr</code> is a raw pointer, perhaps a smart pointer should be used?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T15:53:02.320", "Id": "234831", "ParentId": "234824", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T12:54:07.523", "Id": "234824", "Score": "4", "Tags": [ "c++", "c++14" ], "Title": "Signal slot mechanism in C++14" }
234824
<p><strong>Ⅰ</strong> <a href="https://en.wikipedia.org/wiki/Roman_numerals" rel="nofollow noreferrer">Roman numerals</a> are composed of digits taken from a small set of uppercase characters. Lowercase characters were first used in the Middle Ages.</p> <p><span class="math-container">$$I,V,X,L,C,D,M$$</span></p> <p>With these digits we can represent numbers from 1 to 3999.</p> <p><strong>Ⅱ</strong> For the benefit of representing larger numbers, one extension adds an overline or <a href="https://en.wikipedia.org/wiki/Vinculum_(symbol)" rel="nofollow noreferrer">Vinculum</a> to the character in order to obtain a value that is a 1000 times bigger.</p> <p><span class="math-container">$$I,V,X,L,C,D,M,\overline{V},\overline{X},\overline{L},\overline{C},\overline{D},\overline{M}$$</span></p> <p>This way the numbers can range from 1 to 3999999.</p> <p><strong>Ⅲ</strong> For ease of inputting and outputting, my program uses the lowercase characters as a substitute for the digits with a vinculum.</p> <pre class="lang-none prettyprint-override"><code>I=1 V= 5 C= 100 v= 5000 c= 100000 X=10 D= 500 x=10000 d= 500000 L=50 M=1000 l=50000 m=1000000 </code></pre> <p><strong>Ⅳ</strong> The <em>RomanToInteger</em> conversion routine tries to use as many characters as possible of the submitted string. It will stop at the first non-roman-digit character, or even sooner if such digit cannot be legally appended. The value up to that point is returned in <code>EAX</code>.<br /> For the <em>IntegerToRoman</em> conversion routine it's much simpler. Just provide a valid number in <code>EAX</code> in the range of 1 to 3999999.</p> <p><strong>Ⅴ</strong> The Windows console application:</p> <pre class="lang-none prettyprint-override"><code>; Instant To and From Roman Numeral Conversion ; by MMXIX Sep Roland format pe console include 'win32axp.inc' cinvoke printf, msg1 Fresh: cinvoke printf, msg2 call Vitals ; -&gt; EBX ESI EBP mov byte [ebx+esi], 0 cinvoke printf, msg2 ; To position the cursor mov byte [ebx+esi], ' ' jmp Key xKey: cinvoke _getch ; Discard extended key Key: cinvoke _getch ; -&gt; AL cmp al, 0E0h je xKey cmp al, 0 jz xKey cmp al, 13 je isRET cmp al, 9 je isTAB cmp al, 8 je isBS Char: cmp esi, [ebp+8] ; Field length {7,27} jnb Key ; Field is full mov ecx, [ebp+16] ; Number of valid characters {10,13} lea edi, [ebp+20] ; List of valid characters repne scasb jne Key ; Digit is invalid mov [ebx+esi], al inc esi jmp Main_ isBS: test esi, esi jz Key ; Nothing to backspace over dec esi mov byte [ebx+esi], ' ' jmp Main_ isTAB: xor dword [info], infoR-infoD ; Changes fields infoD/infoR call Vitals ; -&gt; EBX ESI EBP mov eax, [ebp] ; {' -&gt; ',' &lt;- '} mov [form+18], eax ; Update directional arrow jmp Main isRET: mov eax, [infoD+12] add eax, [infoR+12] jz Quit cinvoke printf, crlf call WipeD ; -&gt; EDI (AL ECX) call WipeR ; -&gt; EDI (AL ECX) jmp Fresh Quit: cinvoke printf, wipe invoke system, &quot;pause&gt;0&quot; ; Facilitates taking a screenshot invoke exit, 0 ; -------------------------------------- Main_: mov [ebp+12], esi ; Current character position Main: cmp dword [info], 0 jne InputR ; Decimal input, then calculate and show roman InputD: call WipeR ; -&gt; EDI (AL ECX) xor eax, eax ; DecimalToInteger xor esi, esi jmp .b .a: imul eax, 10 movzx edx, byte [ebx+esi] ; EBX is address of the decimal field sub dl, '0' add eax, edx inc esi .b: cmp esi, [ebp+12] ; Repeat for all digits jb .a test eax, eax jz .c ; Invalid number cmp eax, 3999999 ja .c ; Invalid number mov edx, edi ; EDI is address of the roman field call IntegerToRoman ; -&gt; EDI sub edi, edx mov [infoR+12], edi ; Number of roman digits .c: jmp Fresh ; - - - - - - - - - - - - - - - - - - - ; Roman input, then calculate and show decimal InputR: call WipeD ; -&gt; EDI (AL ECX) mov esi, ebx ; EBX is address of the roman field call RomanToInteger ; -&gt; EAX ESI sub esi, ebx cmp esi, [ebp+12] jne .c ; Too many characters test eax, eax jz .c ; Invalid number mov ebx, 10 ; IntegerToDecimal xor ecx, ecx .a: xor edx, edx div ebx push edx inc ecx test eax, eax jnz .a mov [infoD+12], ecx ; Number of decimal digits .b: pop eax add al, &quot;0&quot; stosb ; EDI is address of the decimal field loop .b .c: jmp Fresh ; -------------------------------------- ; IN () OUT (ebx,esi,ebp) Vitals: mov ebp, infoD add ebp, [ebp-4] ; Info select {0=infoD,32=infoR} mov ebx, form add ebx, [ebp+4] ; Field offset {10,30} mov esi, [ebp+12] ; Current character position ret ; -------------------------------------- ; IN () OUT (edi) MOD (al,ecx) WipeR: mov edi, form add edi, [infoR+4] ; Offset to the roman field push edi mov ecx, [infoR+8] ; Length of the roman field mov al, ' ' rep stosb pop edi mov [infoR+12], ecx ; Number of roman digits is 0 ret ; -------------------------------------- ; IN () OUT (edi) MOD (al,ecx) WipeD: mov edi, form add edi, [infoD+4] ; Offset to the decimal field push edi mov ecx, [infoD+8] ; Length of the decimal field mov al, ' ' rep stosb pop edi mov [infoD+12], ecx ; Number of decimal digits is 0 ret ; -------------------------------------- ; IN (esi) OUT (eax,esi) RomanToInteger: push ebx ecx edx edi xor eax, eax ; EAX is value of resulting integer cdq ; EDX is value of current digit mov edi, 12 ; EDI is offset in list of characters mov cl, &quot;m&quot; cmp [esi], cl je .m sub edi, 2 .More: mov bl, cl ; -&gt; BL={&quot;m&quot;,&quot;c&quot;,&quot;x&quot;,&quot;M&quot;,&quot;C&quot;,&quot;X&quot;} mov cx, [infoR+20+edi] ; -&gt; CX={&quot;cd&quot;,&quot;xl&quot;,&quot;Mv&quot;,&quot;CD&quot;,&quot;XL&quot;,&quot;IV&quot;} cdq ; Can replace 'xor edx, edx' (EAX&lt;4M) cmp [esi], ch ; CH={&quot;d&quot;,&quot;l&quot;,&quot;v&quot;,&quot;D&quot;,&quot;L&quot;,&quot;V&quot;} je .dlvDLV cmp [esi], cl ; CL={&quot;c&quot;,&quot;x&quot;,&quot;M&quot;,&quot;C&quot;,&quot;X&quot;,&quot;I&quot;} jne .OK .cxMCXI:inc esi mov dl, 9 cmp [esi], bl ; BL={&quot;m&quot;,&quot;c&quot;,&quot;x&quot;,&quot;M&quot;,&quot;C&quot;,&quot;X&quot;} je .OK_ mov dl, 4 cmp [esi], ch ; CH={&quot;d&quot;,&quot;l&quot;,&quot;v&quot;,&quot;D&quot;,&quot;L&quot;,&quot;V&quot;} je .OK_ mov dl, 1 jmp .Repts .dlvDLV:inc esi mov dl, 5 cmp [esi], cl ; CL={&quot;c&quot;,&quot;x&quot;,&quot;M&quot;,&quot;C&quot;,&quot;X&quot;,&quot;I&quot;} jne .OK .m: inc esi inc edx ; -&gt; EDX={1,6} .Repts: cmp [esi], cl ; CL={&quot;m&quot;,&quot;c&quot;,&quot;x&quot;,&quot;M&quot;,&quot;C&quot;,&quot;X&quot;,&quot;I&quot;} jne .OK inc esi inc edx ; -&gt; EDX={2,7} cmp [esi], cl ; CL={&quot;m&quot;,&quot;c&quot;,&quot;x&quot;,&quot;M&quot;,&quot;C&quot;,&quot;X&quot;,&quot;I&quot;} jne .OK inc edx ; -&gt; EDX={3,8} .OK_: inc esi .OK: imul eax, 10 add eax, edx ; EDX=[0,9] sub edi, 2 jns .More pop edi edx ecx ebx ret ; -------------------------------------- ; IN (eax,edi) OUT (edi) IntegerToRoman: push eax ebx edx esi mov ebx, 10 ; Divider mov esi, -2 ; Offset in list of characters .a: add esi, 2 xor edx, edx div ebx push edx test eax, eax jnz .a .b: pop ebx ; -&gt; EBX=[0,9] mov dl, [codes+ebx] ; Encoding of a multicharacter digit jmp .d .c: movzx ebx, dh ; -&gt; EBX=[1,3] mov al, [infoR+20+esi+ebx-1] ; Sets are {&quot;m&quot;,&quot;cdm&quot;,&quot;xlc&quot;,&quot;Mvx&quot;, stosb ; &quot;CDM&quot;,&quot;XLC&quot;,&quot;IVX&quot;} .d: mov dh, 0 shl dx, 2 ; Each non-zero bitpair selects a char jnz .c ; from the current set of 3 characters sub esi, 2 jns .b ; Go for next lower order digit pop esi edx ebx eax ret ; -------------------------------------- ALIGN 4 info: dd 0 ; {0,infoR-infoD} infoD: dd ' -&gt; ', 10, 7, 0, 10 db '0123456789', 0, 0 infoR: dd ' &lt;- ', 30, 27, 0, 13 db 'IVXLCDMvxlcdm' codes: db 00000000b db 01000000b db 01010000b db 01010100b db 01100000b db 10000000b db 10010000b db 10010100b db 10010101b db 01110000b msg1: db 'Roman Numeral Convertor', 13, 10 db '=======================', 13, 10 db ' BS delete I=1 V= 5 C= 100 v= 5000 c= 100000', 13, 10 db ' TAB toggle X=10 D= 500 x=10000 d= 500000', 13, 10 db ' RET next/exit L=50 M=1000 l=50000 m=1000000', 13, 10 db '----------------------------------------------------' crlf: db 13, 10, 0 msg2: db 13 form: db 'DECIMAL : -&gt; ROMAN : ', 0 wipe: db 13, ' ', 13, 0 ; -------------------------------------- data import library msvcrt,'msvcrt.dll' import msvcrt,_getch,'_getch',\ exit,'exit',\ printf,'printf',\ system,'system' end data </code></pre> <p><strong>Ⅵ</strong> The program working:</p> <p><a href="https://i.stack.imgur.com/2XooG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2XooG.gif" alt="The screenshot" /></a></p> <p><strong>Ⅶ</strong> My aim was to write conversion routines that don't depend on big lookup tables. Currently using only 23 bytes of conversion data. Perhaps it made the code harder to understand. Improvements?</p> <h3>A happy <span class="math-container">\$\overline{\underline{MMXX}}\$</span> to all!</h3>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T15:03:52.370", "Id": "459326", "Score": "0", "body": "One improvement to the question would be to include your example program output _as text_, and not as an image." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T13:59:34.410", "Id": "234827", "Score": "3", "Tags": [ "converting", "windows", "assembly", "roman-numerals", "x86" ], "Title": "Instant to-and-from Roman Numeral Conversion" }
234827
<p>I have made a ID generator class for my <strong><a href="https://github.com/EmperorZoran/Repair-Shop-Software" rel="nofollow noreferrer">Repair Shop Software</a></strong>, that generates new ID for all data entities that are used in the software. It also converts <code>int</code> value of the ID to <code>String</code> value used for UI, and <code>String</code> values used for UI, to <code>int</code> value. I would like a general opinion on my <code>IDGenerator</code> class. Am I using some anti-pattern, and is my code clear enough. My project is on the <a href="https://github.com/EmperorZoran/Repair-Shop-Software" rel="nofollow noreferrer">GitHub</a>.</p> <p><strong>IDGenerator.java</strong></p> <pre><code>public class IDGenerator { private static final int WORKSTATION_ID = 1; private static final int DAY_ID_FORMATER = 100; private static final int MONTH_ID_FORMATER = 10000; private static final int YEAR_ID_FORMATER = 1000000; private static final int WORKSTATION_ID_FORMATER = 100000000; private static final int WORKSTATION_ID_VALUE = WORKSTATION_ID * WORKSTATION_ID_FORMATER; private static LocalDate lastTicketDate = LocalDate.MIN; public static int getNewID(EntityType entityType) { Objects.requireNonNull(entityType, "EntityType is null"); int entityCounter = DataManager.getEntityCounter(entityType); switch(entityType) { case TICKET: { checkNewWorkDay(); LocalDate today = LocalDate.now(); int dayIDValue = today.getDayOfMonth() * DAY_ID_FORMATER; int monthIDValue = today.getMonthValue() * MONTH_ID_FORMATER; int yearIDValue = (today.getYear() % DAY_ID_FORMATER) * YEAR_ID_FORMATER; return entityCounter + 1 + dayIDValue + monthIDValue + yearIDValue + WORKSTATION_ID_VALUE; } default: { return entityCounter + 1 + WORKSTATION_ID_VALUE; } } } private static void checkNewWorkDay() { if(lastTicketDate != LocalDate.now()) { DataManager.resetTicketCounter(); lastTicketDate = LocalDate.now(); } } public static String toString(EntityType entityType, int id) { Objects.requireNonNull(entityType, "EntityType is null"); String workstationID = String.valueOf(id / WORKSTATION_ID_FORMATER); switch(entityType) { case TICKET: { String date = String.valueOf((id % WORKSTATION_ID_FORMATER) / DAY_ID_FORMATER); String dailyTicketCounter = String.valueOf(id % DAY_ID_FORMATER); if(dailyTicketCounter.length() == 1) { dailyTicketCounter = '0' + dailyTicketCounter; } return workstationID + "-" + date + "-" + dailyTicketCounter; } default: { String entityCounter = String.valueOf(id % WORKSTATION_ID_FORMATER); return workstationID + "-" + entityCounter; } } } public static int toInt(EntityType entityType, String displayName) { Objects.requireNonNull(entityType, "EntityType is null"); if(LabelName.NULL_ITEM.equals(displayName)) return 0; int workstationID = Integer.parseInt(displayName.split("-")[0]) * WORKSTATION_ID_FORMATER; switch(entityType) { case TICKET: { int date = Integer.parseInt(displayName.split("-")[1]) * DAY_ID_FORMATER; int entityCounterNumber = Integer.parseInt(displayName.split("-")[2]); return workstationID + date + entityCounterNumber; } default: { int entityCounterNumber = Integer.parseInt(displayName.split("-")[1]); return workstationID + entityCounterNumber; } } } } </code></pre> <p><strong>IDGenertatorTest.java</strong></p> <pre><code>public class IDGeneratorTest { @ParameterizedTest @EnumSource(EntityType.class) public void getNewIDTest(EntityType entityType) { switch(entityType) { case TICKET: assertEquals(119123001, IDGenerator.getNewID(entityType)); break; default: assertEquals(100000001, IDGenerator.getNewID(entityType)); break; } } @ParameterizedTest @EnumSource(EntityType.class) public void toStringTest(EntityType entityType) { switch(entityType) { case TICKET: assertEquals("1-191230-01", IDGenerator.toString(entityType, 119123001)); break; default: assertEquals("1-21", IDGenerator.toString(entityType, 100000021)); break; } } @ParameterizedTest @EnumSource(EntityType.class) public void toIntTest(EntityType entityType) { switch(entityType) { case TICKET: assertEquals(119123001, IDGenerator.toInt(entityType, "1-191230-01")); break; default: assertEquals(100000021, IDGenerator.toInt(entityType, "1-21")); break; } } } </code></pre>
[]
[ { "body": "<p>Using plain addition is going to create identical ID's. For instance, if for 1 ID the <code>dayIDValue</code> is 6 and the <code>monthIDValue</code> is 5, you'll get the same ID if next time the <code>dayIDValue</code> is 5 and the <code>monthIDValue</code> is 6.</p>\n\n<p>I would suggest using the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html\" rel=\"nofollow noreferrer\"><code>UUID</code> class</a>. It allows you to choose different versions depending on how unique you need the ID's to be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T07:29:50.383", "Id": "459402", "Score": "0", "body": "Yes, I have consider using UUID numbers for ID's, but they are very large considering I plan to have entire database in RAM. I don't think you have read the code of my class, because the possible duplicate ID is only possible if the daily ticket counter is larger then 99, but that would be prohibited in the client. If you see the test class it will be clear. The **fifth** ticket on the workstation with the workstation ID of **2** on **31.12.2019.** will have **219123105 ID**. My ID also caries some information unlike UUID. Thank you for your suggestion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:47:47.397", "Id": "234847", "ParentId": "234828", "Score": "1" } }, { "body": "<p>Using static methods only for your <code>IDGenerator</code> class is antipattern. It's better to make those instance methods and create instance of your class when you need it. One reason may be extendability, another can be thread safety. I have a feeling, that static local variable <code>lastTicketDate</code> will probably cause trouble with race conditions.</p>\n\n<p>If you really want to have static access to it, consider making it singleton with static method to get the instance. It's not ideal, but still better approach and it's on the way to making your code non-static, keeping reference to your class in local/class variable rather than static access. Thread safety can still be issue since any thread can access statically your class as long as there is static method to get it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:24:29.660", "Id": "459435", "Score": "2", "body": "You may have some misconceptions about singletons. You don't have static access to a singleton since a singleton is an object (that guarantees that there is only one instance). Singletons are also usually an anti pattern. You should rely on dependency injection in order to guarantee against duplicate instantiations. Static access has nothing to do with guaranteeing thread safety. Same restrictions apply as with instance methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:39:19.160", "Id": "459716", "Score": "1", "body": "True it was a bit vague (edited a bit). I meant access to singleton using static factory. I never said that singleton is best way, I suggested it as mid-way to better code that doesn't require full refactor. I also never said that static access guarantees thread safety, quite opposite - I mentioned, that it can still cause issue. If you wanna talk this through or chat or something, I am happy to discuss." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:54:58.873", "Id": "459748", "Score": "0", "body": "Can you explain me what bad could potentially happen in the program with my solution regarding thread safety." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T14:52:03.487", "Id": "234871", "ParentId": "234828", "Score": "3" } }, { "body": "<p>First of all we should describe a <a href=\"https://en.wikipedia.org/wiki/User_story\" rel=\"nofollow noreferrer\">user-story</a> for your ID-generator. This description should contain use-cases (including examples), requirements, and related technical context.</p>\n\n<h3>Use-Story</h3>\n\n<p>As <em>creator of a <strong>new entity</strong></em> (system) I would like to make sure that this entity can be identified within the system by an <strong><a href=\"https://en.wikipedia.org/wiki/Identifier\" rel=\"nofollow noreferrer\">Identifier (ID)</a></strong>. So the ID should be <strong>automatically generated</strong> when the new entity is created and persisted.</p>\n\n<p>As <strong>administrator or user</strong> of the system I would like to <strong>read some information</strong> about the entity directly from the generated ID. So\nthe ID should be a <a href=\"https://en.wikipedia.org/wiki/Natural_key\" rel=\"nofollow noreferrer\">Natural Key</a> which encodes some business information.</p>\n\n<p><strong>Requirements:</strong></p>\n\n<ol>\n<li>the ID should be <strong>numerical</strong></li>\n<li>depending on the <strong>entity-type</strong> the ID could vary in shape/pattern</li>\n<li>the <strong>pattern</strong> and information encoded into the ID should <strong>tell something</strong> about it. Thus it contains <em>informational parts</em>, each encoded as a number. Parts may be <em>workstation-id</em>, <em>running-counter</em> or <em>creation-date</em></li>\n<li>the <em>informational parts</em> (numbers) of the ID are <strong>separated by</strong> a dash <code>-</code> </li>\n<li>the <strong>running-counter</strong> should be (at least) <strong>unique per entity-type</strong></li>\n<li>the <strong>default ID</strong> (if not specified separately for the entity-types) should contain two parts: (a) <em>workstation-id</em> as 1-digit, (b) <em>running counter</em> as 2-digits. So the pattern <code>&lt;workstation_id&gt;-&lt;count&gt;</code> can for example be represented as <code>1-01</code> for the first <strong>entity XY</strong> (<em>running counter</em> <code>01</code>) created on <em>workstation</em> <code>1</code>.</li>\n<li>the ID of an entity-type <strong>TICKET</strong> should consist of one extra information: (c) <em>creation-date</em> as 6-digit ISO-date in format <code>yyMMdd</code>. So the pattern <code>&lt;workstation_id&gt;-&lt;date_yyMMdd&gt;-&lt;count&gt;</code> can for example be represented as <code>1-191230-01</code> for the first <strong>ticket</strong> (<em>running counter</em> <code>01</code>) created on <em>workstation</em> <code>1</code> on <code>30th of December 2019</code>.</li>\n<li>additionally the <strong>running-counter</strong> of entity-type <strong>TICKET</strong> should be <strong>reset on each new creation-date</strong>. So that the <em>running-counter</em>\nis unique within each creation-date.</li>\n</ol>\n\n<h3>Design &amp; Modelling</h3>\n\n<p>Now you can <strong>model the data structures</strong> needed to fulfill the requirements, i.e. classes or interfaces.</p>\n\n<p><strong>class <code>EntityID</code></strong>:\nlearn from Java's <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html\" rel=\"nofollow noreferrer\">UUID</a> class and its implemented interfaces:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class EntityID implements Serializable, Comparable&lt;EntityID&gt; {\n public static final String SEPARATOR = \"-\";\n public static final int REQUIRED_PARTS = 2;\n\n protected int workstationId;\n protected int counter;\n\n public EntityID(int workstationId, int counter) {\n // could add some parameter validation (like only positive values)\n this.workstationId = workstationId;\n this.counter = counter;\n }\n\n @Override // implements Comparable&lt;EntityID&gt; \n public int compareTo(EntityID value) {\n // needed to make sure if compared objects are same, or for sorting: lesser, greater\n // left for you to implement\n return -1;\n }\n\n public static EntityID fromString(String name) {\n if (name == null || name.trim().isEmpty()) {\n throw new IllegalArumentException(\"ID to parse must not be null or empty!\");\n }\n String[] parts = name.split(SEPARATOR);\n if (parts.length != REQUIRED_PARTS) {\n throw new IllegalArumentException(String.format(\"ID to parse must consist of %d parts, separated by '%s', but was: %s\", REQUIRED_PARTS, SEPARATOR, name));\n }\n int workstationId = Integer.parseInt(parts[0]);\n int counter = Integer.parseInt(parts[1]);\n return new EntityID(workstationId, counter);\n }\n\n // getter and setter for all information parts\n // left to implement\n\n public String toString() {\n return String.format(\"%01d%s%02d\", workstationId, SEPARATOR, counter); \n }\n}\n</code></pre>\n\n<p>This class servers the <strong>default ID</strong>. For the special case <strong>TICKET</strong> you need to inherit this class, as follows.</p>\n\n<p><strong>class <code>TicketId</code></strong>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class TicketID extends EntityID implements Serializable, Comparable&lt;TicketID&gt; {\n public static final String SEPARATOR = \"-\";\n public static final int REQUIRED_PARTS = 3;\n public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(\"yyMMdd\");\n\n protected LocalDate creationDateUtc;\n\n public TicketID(int workstationId, int counter, LocalDate utcDate) {\n super(workstationId, counter);\n this.creationDateUtc = utcDate;\n }\n\n @Override // implements Comparable&lt;TicketID&gt; \n public int compareTo(TicketID value) {\n // needed to make sure if compared objects are same, or for sorting: lesser, greater\n // left for you to implement\n return -1;\n }\n\n public static TicketID fromString(String name) {\n if (name == null || name.trim().isEmpty()) {\n throw IllegalArumentException(\"ID to parse must not be null or empty!\");\n }\n String[] parts = name.split(SEPARATOR);\n if (parts.length != REQUIRED_PARTS) {\n throw new IllegalArumentException(String.format(\"ID to parse must consist of %d parts, separated by '%s', but was: %s\", REQUIRED_PARTS, SEPARATOR, name));\n }\n int workstationId = Integer.parseInt(parts[0]);\n LocalDate utcDate = LocalDate.parse(parts[1], DATE_FORMATTER);\n int counter = Integer.parseInt(parts[2]);\n return new TicketID(workstationId, counter, utcDate);\n }\n\n // getter and setter for all information parts\n // left to implement\n\n public String toString() {\n // could also use a DateFormatter like\n // return String.format(\"%01d-%s-%02d\", workstationId, DATE_FORMATTER.format(creationDateUtc), counter);\n return String.format(\"%01d-%tY%tm%td-%02d\", workstationId, creationDateUtc, counter);\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong></p>\n\n<p>How <strong>parsing</strong> (form <em>representation</em> String to <em>value</em> ID) and <strong>formatting</strong> (from <em>value</em> ID to <em>representation</em> String) was implemented using static facotry method <code>fromString</code> and instance method <code>toString</code>. </p>\n\n<p>The above classes implement requirements 1. - 4. and 6. - 7. </p>\n\n<p>Now the ID-generator comes into play. Using <a href=\"https://www.oodesign.com/factory-pattern.html\" rel=\"nofollow noreferrer\">Factory</a> <em>Design-Pattern</em> we can implement it like follows.</p>\n\n<p>The <code>counter</code> for each entity-type should be managed inside the generator, not be dependent on some DataManager. Thus make use of Java's <strong>concurrent</strong> counter classes [AtomicInteger](<a href=\"https://stackoverflow.com/questions/4818699/practical-uses-for-atomicinteger]\">https://stackoverflow.com/questions/4818699/practical-uses-for-atomicinteger]</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class EntityIdGenerator {\n\n protected AtomicInteger counter;\n protected Integer counterMax;\n protected Integer workstationId; \n\n // here the current value from DataManager can be injected as counterStart\n // counterMax = 99 (limit to 2-digits), workstationId = 1\n public EntityIdGenerator(int counterStart, int counterMax, int workstationId) {\n if (counterMax &lt;= counterStart || counterStart &lt; 0 || counterMax &lt; 1) {\n throw new IllegalArgumentException(\"CounterStart must positive and &gt;= 0, counterMax must be &gt; 1 and &gt; counterStart\"!); \n }\n this.counter = new AtomicInteger(counterStart);\n this counterMax = counterMax;\n this.workstationId = workstationId;\n }\n\n protected int rollToNextCounter() {\n // if current counter is 99 == counterMax, then reset \n boolean hasReachedMaxAndReset = this.counter.compareAndSet(counterMax, 0);\n // if counterStart was 0, the nextCounter will also be 0 (first used) \n return this.counter.getAndIncrement(); \n }\n\n public EntityID generateId() {\n return new EntityID(this.workstationId, rollToNextCounter());\n }\n\n}\n</code></pre>\n\n<p>The above class has some benefits:</p>\n\n<ul>\n<li>can now be <strong>tested isolated</strong> without need of some DataManager (independent)</li>\n<li>can now have different instances (each of it manages state for a special entity-type, and its counter).</li>\n</ul>\n\n<p>With the last (multiple instances) we implemented requirement 5.</p>\n\n<ul>\n<li>can be <em>specialized</em>, meaning it can be inherited to some class <code>TicketIdGenerator</code> which manages some property <code>lastIssuedDateUtc</code> in order to reset the counter even if the <code>counterMax</code> has not yet reached.</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class TicketIdGenerator extends EntityIdGenerator {\n private LocalDate lastIssuedDateUtc;\n\n public TicketIdGenerator(int counterStart, int counterMax, LocalDate lastIssuedDateUtc) {\n super(counterStart, counterMax);\n if (lastIssuedDateUtc &gt; todayUtc()) {\n throw new IllegalArgumentException(\"date (as UTC) must can be now or in the past; must not be in the future: \" + lastIssuedDateUtc);\n }\n this.lastIssuedDateUtc = lastIssuedDateUtc;\n }\n\n public LocalDate todayUtc() {\n return LocalDate.now(\"UTC\");\n }\n\n public TicketID generateId() {\n if (this.lastIssuedDateUtc &lt; todayUtc()) {\n this.lastIssuedDateUtc = todayUtc();\n }\n return new TicketID(this.workstationId, rollToNextCounter(), this.lastIssuedDateUtc);\n }\n\n // rest of logic and methods remain same as in EntityIdGenerator\n\n}\n</code></pre>\n\n<p>With above we implemented requirement 8.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T23:43:12.533", "Id": "459692", "Score": "1", "body": "This is not a code review. You are suggesting your own solution without considering the code in question. You also come up with your own requirements disregarding requirements that can be deriven from question/code in question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T23:44:27.430", "Id": "459693", "Score": "1", "body": "Above code is not yet tested plus there are at least 2 points not yet designed: (a) `TicketID` represented by non-UTC date (in local timezone); (b) assignment of each ID-generator instance to respective `EntityType`. If you see some mistakes (e.g. one method should be static), comment ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T23:50:54.343", "Id": "459694", "Score": "0", "body": "@purple Yes it's my proposal of an improved design (not one monolithic class, violating SRP, etc.). I will explain and provide _traditional_ review-comments to OP's source tomorrow. And please __list the requirements__ that _you can derive_ from OP's post !?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:54:54.947", "Id": "459758", "Score": "1", "body": "I appreciate your extensive answer, and I intend to implement some of your suggestions. **Test isolation** is one of my concerns, and I was thinking of re-implementing `IDGenerator` just because of that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T23:32:49.247", "Id": "234977", "ParentId": "234828", "Score": "3" } } ]
{ "AcceptedAnswerId": "234977", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T14:55:02.743", "Id": "234828", "Score": "3", "Tags": [ "java", "beginner", "generator" ], "Title": "ID generator class for my Repair Shop Software" }
234828
<p>The program below takes inputs for the temperature in various cities in a span of multiple days. It then outputs the ones where the minimal temperature is closer to the average than the maximal temperature, prefaced by the number of cities where this happens. </p> <p>For example: "3 5 10 15 12 10 10</p> <p>11 11 11 11 20</p> <p>12 16 16 16 20"</p> <p>returns "2 1 2".</p> <p>I've ran it with various particularly large inputs a few times, and the program seems to slow down with larger numbers. Is there any way to make the program faster?</p> <pre><code>class Program { static void Main(string[] args) { string input = Console.ReadLine(); string[] inputs = input.Split(); int cities = Convert.ToInt32(inputs[0]); int days = Convert.ToInt32(inputs[1]); int[] content = new int[days]; int i = 0; int y = 0; float max = 0; float average = 0; float min = 50; int how_many = 0; List&lt;int&gt; which = new List&lt;int&gt;(); for (i = 0; i &lt; cities; i++) { input = Console.ReadLine(); inputs = input.Split(); for (y = 0; y &lt; days; y++) { content[y] = Convert.ToInt32(inputs[y]); average += content[y]; if (content[y] &gt; max) { max = content[y]; } if (content[y] &lt; min) { min = content[y]; } } average = (float)average / days; if (max - average &gt; average - min) { how_many += 1; int position = i + 1; which.Add(position); } max = 0; average = 0; min = 50; y = 0; } Console.Write(how_many + " "); i = 0; for (i = 0; i &lt; which.Count(); ++i) { Console.Write(which[i] + " "); } Console.ReadKey(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T21:06:18.177", "Id": "459364", "Score": "0", "body": "How big is a \"particularly large inputs\"? 100 cities? 1,000 cities? 300 days? I fixed some small memory issues in your code testing it but it runs pretty quick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T21:14:16.577", "Id": "459367", "Score": "0", "body": "1,000 cities, 1,000 days. Could you send me the code if possible?" } ]
[ { "body": "<p>If you want to see how performance is you need to get the user input out of the loop. I'm assuming you don't want to measure the time it takes someone to type in or paste in the data elements. </p>\n\n<p>You don't need the variable <code>how_many</code> as it will always be the same as the <code>Count</code> of <code>which</code>, which by the way isn't a good name for a variable even something like results would be better name.</p>\n\n<p>You also don't need the <code>context</code> array variable. Just need to store the current value not save each element as it loops through. </p>\n\n<p>The variables <code>i, y, max, average, min</code> can all be declared in the loop scope and not need to be reset.</p>\n\n<p>Calling <code>Count()</code> on <code>which.Count()</code> is the Linq Count method, should just call the list Count property </p>\n\n<p>I'm also assuming this is a beginner question and won't get into Console as input and validating the data coming from it is valid. </p>\n\n<p>I personally didn't want to type in all the data so I made the computer generate random data, if in debug mode</p>\n\n<pre><code> static void Main(string[] args)\n {\n#if DEBUG\n var random = new Random();\n var inputs = \"1000 1000\".Split();\n#else\n var inputs = Console.ReadLine().Split();\n#endif\n var cities = Convert.ToInt32(inputs[0]);\n var days = Convert.ToInt32(inputs[1]);\n\n var data = new List&lt;int[]&gt;(cities);\n for (var i = 0; i &lt; cities; i++)\n {\n#if DEBUG\n var cityData = Enumerable.Range(0, days)\n .Select(_ =&gt; random.Next(100))\n .ToArray();\n#else\n var cityData = Console.ReadLine()\n .Split()\n .Select(x =&gt; Convert.ToInt32(x))\n .ToArray();\n#endif\n if (cityData.Length != days)\n {\n Array.Resize(ref cityData, days);\n }\n data.Add(cityData);\n }\n\n var timer = new Stopwatch();\n timer.Start();\n var results = new List&lt;int&gt;();\n for (var i = 0; i &lt; cities; i++)\n {\n float max = float.MinValue;\n float average = 0;\n float min = float.MaxValue;\n for (var y = 0; y &lt; days; y++)\n {\n var content = data[i][y];\n average += content;\n if (content &gt; max)\n {\n max = content;\n }\n if (content &lt; min)\n {\n min = content;\n }\n }\n average = average / days;\n\n if (max - average &gt; average - min)\n {\n int position = i + 1;\n results.Add(position);\n }\n }\n\n Console.Write(results.Count + \" \");\n Console.WriteLine(string.Join(\" \", results));\n timer.Stop();\n Console.WriteLine();\n Console.WriteLine($\"Total Processing Time: {timer.Elapsed}\");\n Console.ReadKey();\n }\n</code></pre>\n\n<p>This code runs in less than a second on my machine. I assume waiting for user input was what was taking the longest time in pervious one and not actually the processing of the data. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T21:40:27.367", "Id": "459368", "Score": "1", "body": "Thank you very much for the answer! This will help me a lot in learning programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T22:14:34.160", "Id": "459370", "Score": "0", "body": "@Pizza64210 FYI I fixed bug in the code. Needed Split() after the \"1000 1000\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T21:34:11.940", "Id": "234839", "ParentId": "234832", "Score": "2" } } ]
{ "AcceptedAnswerId": "234839", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T17:13:51.343", "Id": "234832", "Score": "4", "Tags": [ "c#", "performance" ], "Title": "C# program which measures the distance between the average and maximum/minimum temperature" }
234832
<p>I recently made a boggle solver in Rust to compensate for the fact that I'm really bad at boggle. This has also been a good Rust learning experience. The code does what it's supposed to quite well but it is a bit slow, even when compiling with the <code>-O</code> flag. Since I'm new to Rust, I'm not sure where the slow spots could be. I'm using a hashset to lookup the words, so I assume the lookup isn't the bottleneck. Any tips? (Also, if I'm doing any kind of bad practice, you can let me know). Thanks. </p> <pre class="lang-rust prettyprint-override"><code>use std::collections::HashSet; use std::fs; const MAX_WORD_LEN: usize = 12; #[derive(Clone, Debug, Copy)] struct Coordinate { row: i64, col: i64 } impl Coordinate { // Returns a new coordinate if the move is valid. None otherwise. fn move_c(&amp;self, a: i64, b: i64, h: i64, w: i64) -&gt; Option&lt;Coordinate&gt; { let h_range = 0..h; let w_range = 0..w; if h_range.contains(&amp;(self.row + a)) &amp;&amp; w_range.contains(&amp;(self.col + b)) { Some(Coordinate {row: self.row + a, col: self.col + b}) } else { None } } } impl PartialEq for Coordinate { fn eq(&amp;self, other: &amp;Self) -&gt; bool { self.row == other.row &amp;&amp; self.col == other.col } } fn boggle_solve(grid: &amp;Vec&lt;Vec&lt;char&gt;&gt;, dict: &amp;HashSet&lt;String&gt;) { for (i, row) in grid.iter().enumerate() { for (j, ch) in row.iter().enumerate() { boggle_solve_help(grid, dict, ch.to_string(), Coordinate{row: i as i64, col: j as i64}, vec![Coordinate{row: i as i64, col: j as i64}]) } } } fn boggle_solve_help(grid: &amp;Vec&lt;Vec&lt;char&gt;&gt;, dict: &amp;HashSet&lt;String&gt;, word: String, c: Coordinate, path: Vec&lt;Coordinate&gt;) { // Base case. // No more work if the string is long enough if word.len() &gt; MAX_WORD_LEN { return; } if word.len() &gt; 3 &amp;&amp; dict.contains(&amp;word) { println!("{}", word); } // For every possible direction the path can take, if it is valid, take it. for a in -1..=1 { for b in -1..=1 { match c.move_c(a, b, grid.len() as i64, grid[0].len() as i64) { Some(new_c) if !path.contains(&amp;new_c) =&gt; { let mut new_path = path.clone(); new_path.push(new_c); let new_word = format!("{}{}", &amp;word, &amp;grid[new_c.row as usize][new_c.col as usize]); boggle_solve_help(grid, dict, new_word, new_c, new_path); }, Some(_) =&gt; (), None =&gt; () } } } } fn main() { let contents = fs::read_to_string("words_alpha.txt").unwrap(); let dict: HashSet&lt;String&gt; = contents.split_whitespace().map(|s| s.to_string()).collect(); let grid: Vec&lt;Vec&lt;char&gt;&gt; = vec![ vec!['c', 's', 't', 'e', 't'], vec!['a', 'i', 'r', 'l', 's'], vec!['p', 'd', 'a', 'e', 's'], vec!['u', 'e', 'c', 's', 'e'], vec!['r', 'o', 't', 'r', 'i'] ]; boggle_solve(&amp;grid, &amp;dict) } </code></pre>
[]
[ { "body": "<p>The main thing that's going to get you a speed boost is returning early from the search if there's no word that starts with what you have so far.</p>\n\n<p>One simple way to do this is to keep a <code>HashSet</code> of all the prefixes of words in the dictionary. Or, better yet, a <code>HashMap</code> where the value indicates whether the prefix is actually a word or not.</p>\n\n<pre><code>struct PrefixMap&lt;'a&gt;(HashMap&lt;&amp;'a str, bool&gt;);\n\nimpl&lt;'a&gt; PrefixMap&lt;'a&gt; {\n fn new(words: impl IntoIterator&lt;Item = &amp;'a str&gt;) -&gt; Self {\n let mut map = HashMap::new();\n for word in words {\n // note that this gets every prefix except the whole word\n for (ending, _) in word.char_indices() {\n map.entry(&amp;word[..ending]).or_insert(false);\n }\n map.insert(word, true);\n }\n Self(map)\n }\n\n fn is_word(&amp;self, word: &amp;str) -&gt; bool {\n self.0.get(word).copied().unwrap_or(false)\n }\n\n fn is_prefix(&amp;self, prefix: &amp;str) -&gt; bool {\n self.0.contains_key(prefix)\n }\n}\n</code></pre>\n\n<p>Then, in the first part of <code>boggle_solve_help</code>, we can use <code>is_word</code> and <code>is_prefix</code> to determine whether to print the word or return early.</p>\n\n<pre><code>if !dict.is_prefix(&amp;word) {\n return;\n}\n\nif word.len() &gt; 3 &amp;&amp; dict.is_word(&amp;word) {\n println!(\"{}\", word);\n}\n</code></pre>\n\n<p>While this isn't the most efficient thing possible, that simple step makes the program run almost instantly on my computer (less than a second). If you still want to improve more, look up <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"noreferrer\">tries</a> for a memory efficient and quick way to do the same thing. Since creating the index of words takes a little while, you might try to cache it between runs using serde or something similar.</p>\n\n<hr>\n\n<p>Now for some more suggestions.</p>\n\n<ol>\n<li><p><strong>Derive <code>PartialEq</code>.</strong> Right now you implement <code>PartialEq</code> for <code>Coordinate</code> manually, but the same implementation can be done by adding <code>PartialEq</code> to the derive attribute.</p></li>\n<li><p><strong>Use descriptive variable names.</strong> The main offenders are the arguments to <code>move_c</code> and later on <code>c</code> in <code>boggle_solve_help</code>. I know sometimes this is annoying, but even just changing <code>a</code> and <code>b</code> to <code>dy</code> and <code>dx</code> (calculus shorthand for \"change in y/x\") makes everything clearer. It's probably worth spelling out <code>height</code> and <code>width</code> to make it clear that that's what you mean.</p></li>\n<li><p><strong>Don't forget to use <code>cargo fmt</code>.</strong> It's a simple step and will instantly make your code more standardized and easier to read for other Rust programmers.</p></li>\n<li><p><strong>Encapsulate the grid into its own type.</strong> Right now, you're using <code>Vec&lt;Vec&lt;char&gt;&gt;</code> directly, which is fine, but means that lots of annoying details are strewn about the functions that use it. The type can still be <code>Vec&lt;Vec&lt;char&gt;&gt;</code> under the surface, but having a method like <code>grid.get(coordinate)</code> rather than <code>grid[coordinate.row as usize][coordinate.col as usize]</code> makes things easier to read and make sense of. As a plus, this will also silence Clippy's complaint about using <code>&amp;Vec&lt;_&gt;</code> instead of <code>&amp;[_]</code>.</p></li>\n<li><p><strong>Consider switching to an iterative algorithm.</strong> You won't run into stack overflow here since you have a hard cap on how deep the recursion can go. Still, if you want a slightly faster algorithm, a depth-first search can be memory efficient and avoid the repeated <code>String</code> allocations you currently have (with <code>format!</code>).</p></li>\n<li><p><strong>Bonus: don't show duplicate words.</strong> Right now, a word will be duplicated if can be spelled with a different path of letters on the board. For example, \"trees\" can be written three different ways near the bottom right corner of the board so it gets printed 3 times. It also shows up in a few other places. I might suggest keeping a <code>HashSet</code> of all the words you've found so far to eliminate duplicates.</p></li>\n</ol>\n\n<p>Here's the code after applying the early return and the first three of my suggestions. I'll let you figure out the other two.</p>\n\n<pre><code>use std::collections::HashMap;\nuse std::fs;\n\nconst MAX_WORD_LEN: usize = 12;\n\n#[derive(Clone, Debug, Copy, PartialEq)]\nstruct Coordinate {\n row: i64,\n col: i64,\n}\n\nimpl Coordinate {\n // Returns a new coordinate if the move is valid. None otherwise.\n fn move_coord(&amp;self, dy: i64, dx: i64, height: i64, width: i64) -&gt; Option&lt;Coordinate&gt; {\n let height_range = 0..height;\n let width_range = 0..width;\n if height_range.contains(&amp;(self.row + dy)) &amp;&amp; width_range.contains(&amp;(self.col + dx)) {\n Some(Coordinate {\n row: self.row + dy,\n col: self.col + dx,\n })\n } else {\n None\n }\n }\n}\n\n// Keys consist of all prefixes of words\n// Values say whether the prefix is a word\n// Since we keep references rather than `String`s,\n// the lifetime of the map can't exceed the lifetime of wherever\n// the `&amp;str`s come from.\n// If you decide to make this more persistent, using `String` rather than `&amp;str`\n// might be appropriate.\nstruct PrefixMap&lt;'a&gt;(HashMap&lt;&amp;'a str, bool&gt;);\n\nimpl&lt;'a&gt; PrefixMap&lt;'a&gt; {\n // We can produce this from any iterator of `&amp;str`s.\n fn new(words: impl IntoIterator&lt;Item = &amp;'a str&gt;) -&gt; Self {\n let mut map = HashMap::new();\n for word in words {\n // note that this gets every prefix except the whole word\n for (ending, _) in word.char_indices() {\n map.entry(&amp;word[..ending]).or_insert(false);\n }\n map.insert(word, true);\n }\n Self(map)\n }\n\n fn is_word(&amp;self, word: &amp;str) -&gt; bool {\n self.0.get(word).copied().unwrap_or(false)\n }\n\n fn is_prefix(&amp;self, prefix: &amp;str) -&gt; bool {\n self.0.contains_key(prefix)\n }\n}\n\nfn boggle_solve(grid: &amp;Vec&lt;Vec&lt;char&gt;&gt;, dict: &amp;PrefixMap) {\n for (i, row) in grid.iter().enumerate() {\n for (j, ch) in row.iter().enumerate() {\n boggle_solve_help(\n grid,\n dict,\n ch.to_string(),\n Coordinate {\n row: i as i64,\n col: j as i64,\n },\n vec![Coordinate {\n row: i as i64,\n col: j as i64,\n }],\n )\n }\n }\n}\n\nfn boggle_solve_help(\n grid: &amp;Vec&lt;Vec&lt;char&gt;&gt;,\n dict: &amp;PrefixMap,\n word: String,\n coord: Coordinate,\n path: Vec&lt;Coordinate&gt;,\n) {\n // Base case.\n // No more work if the string is long enough\n if word.len() &gt; MAX_WORD_LEN {\n return;\n }\n\n if !dict.is_prefix(&amp;word) {\n return;\n }\n\n if word.len() &gt; 3 &amp;&amp; dict.is_word(&amp;word) {\n println!(\"{}\", word);\n }\n\n // For every possible direction the path can take, if it is valid, take it.\n for dy in -1..=1 {\n for dx in -1..=1 {\n match coord.move_coord(dy, dx, grid.len() as i64, grid[0].len() as i64) {\n Some(new_coord) if !path.contains(&amp;new_coord) =&gt; {\n let mut new_path = path.clone();\n new_path.push(new_coord);\n let new_word = format!(\n \"{}{}\",\n &amp;word, &amp;grid[new_coord.row as usize][new_coord.col as usize]\n );\n\n boggle_solve_help(grid, dict, new_word, new_coord, new_path);\n }\n\n Some(_) =&gt; (),\n\n None =&gt; (),\n }\n }\n }\n}\n\nfn main() {\n let contents = fs::read_to_string(\"words_alpha.txt\").unwrap();\n let dict = PrefixMap::new(contents.split_whitespace());\n\n let grid: Vec&lt;Vec&lt;char&gt;&gt; = vec![\n vec!['c', 's', 't', 'e', 't'],\n vec!['a', 'i', 'r', 'l', 's'],\n vec!['p', 'd', 'a', 'e', 's'],\n vec!['u', 'e', 'c', 's', 'e'],\n vec!['r', 'o', 't', 'r', 'i'],\n ];\n\n boggle_solve(&amp;grid, &amp;dict)\n}\n</code></pre>\n\n<p>(<a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=764730b00cd47c11c3a1da367e91e005\" rel=\"noreferrer\">playground</a> - but note that <code>words_alpha.txt</code> doesn't exist, so you can't run it)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T19:06:09.960", "Id": "459450", "Score": "0", "body": "Brilliant! Thank you! I realized that a lot of time was wasted on paths that could never become words as they went along, so killing them early should be a good idea. Thanks for the other suggestions, too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T03:29:22.987", "Id": "234850", "ParentId": "234833", "Score": "5" } } ]
{ "AcceptedAnswerId": "234850", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T17:30:15.330", "Id": "234833", "Score": "9", "Tags": [ "performance", "rust" ], "Title": "Boggle solver in Rust - Looking for speedup" }
234833
<p>I have recently started to work with <code>InnoDB</code> as well trying to use "helper" functions. The code below seems to work correctly however I am not sure if the true behavior in the background is what I am expecting. Here is the code:</p> <pre><code> try{ $mysqli-&gt;begin_transaction(); $sql1 = "SELECT password, active FROM users WHERE user_id=? LIMIT 1 FOR UPDATE"; run($mysqli, $sql1, [$user_id]); $sql2 = "UPDATE users SET password=?, active=? WHERE user_id=?"; run($mysqli, $sql2, [$new,$active,$user_id]); $mysqli-&gt;commit(); header("Location: ../login.php"); }catch(exception $e){ error($mysqli); } function run($mysqli, $sql, $params, $types = ""){ $types = $types ?: str_repeat("s", count($params)); $stmt = $mysqli-&gt;prepare($sql); $stmt-&gt;bind_param($types, ...$params); $stmt-&gt;execute(); return $stmt; } </code></pre> <p>Basically what I am needing to know is if my <code>LOCK</code> in the first statement is actually taking place and remaining in place until the end of the transaction. I havent been able to find decent examples combining transactions, prepared statements, and row level locking.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T18:58:41.210", "Id": "459349", "Score": "1", "body": "One of the requirements of posting code on Code Review is you must be reasonably sure the code works as intended. According to your description, you don't know. Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:03:29.990", "Id": "459351", "Score": "0", "body": "to \"the best of my knowledge\" the code does work, I am here for verification that what I believe to be happening is happening in the same manor I believe it is. And if my expectations are incorrect then I can adjust my technique @Mast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T21:10:22.117", "Id": "459365", "Score": "1", "body": "\"Basically what I am needing to know is if my `LOCK` in the first statement is actually taking place and remaining in place until the end of the transaction.\" Have you tried verifying whether this happens yourself? Can you share your SQL schema so we can reproduce the behaviour as exactly as possible?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:32:51.983", "Id": "459438", "Score": "0", "body": "@Mast since this is set up in a transaction, what would be a good way to view if the lock was initiated and when it was terminated? I havent found a way to check the status during the query" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T18:36:49.897", "Id": "234834", "Score": "1", "Tags": [ "php", "mysql", "mysqli" ], "Title": "InnoDB Row Locking with Transaction & Helper" }
234834
<p>This is my answer for <a href="https://www.hackerrank.com/challenges/construct-the-array/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/construct-the-array/problem</a> (Passes all the test cases)</p> <p><strong>Problem</strong></p> <blockquote> <p>Your goal is to find the number of ways to construct an array such that consecutive positions contain different values. </p> <p>Specifically, we want to construct an array with <span class="math-container">\$n\$</span> elements such that each element [contains a value] between <span class="math-container">\$1\$</span> and <span class="math-container">\$k\$</span>, inclusive. We also want the first and last elements of the array to be <span class="math-container">\$1\$</span> and <span class="math-container">\$x\$</span>. Given <span class="math-container">\$n\$</span>, <span class="math-container">\$k\$</span> and <span class="math-container">\$x\$</span>, find the number of ways to construct such an array.</p> <p>Since the answer may be large, only find answer modulo <span class="math-container">\$10^9 + 7\$</span></p> <p><strong>For example</strong>, for <span class="math-container">\$n=4\$</span>, <span class="math-container">\$k=3\$</span> and <span class="math-container">\$x=2\$</span> there are <span class="math-container">\$3\$</span> ways</p> </blockquote> <p><strong>Solution</strong></p> <pre><code>public class Solution { public static final long MOD = 1_000_000_007L; public static long countArray(int n, int k, int x) { if (n &lt; 3 || k &lt; 2) return 0; if (n == 3 &amp;&amp; x == 1) { return k - 1; } if (n == 3) { return k - 2; } long countOne = k - 1, countOther = k - 2, temp; for (int i = 4; i &lt; n; i++) { temp = countOther * (k - 1) % MOD; countOther = (countOne % MOD + countOther * (k - 2) % MOD) % MOD; countOne = temp; } if (x == 1) { return countOther * (k - 1) % MOD; } return (countOne % MOD + countOther * (k - 2) % MOD) % MOD; } } </code></pre>
[]
[ { "body": "<p>You are checking conditions multiple times, increasing the complexity of the code. For example:</p>\n\n<pre><code> if (n == 3 &amp;&amp; x == 1) {\n return k - 1;\n }\n if (n == 3) {\n return k - 2;\n }\n</code></pre>\n\n<p>checks <code>n == 3</code> twice. A nested <code>if</code> statement would be simpler &amp; clearer:</p>\n\n<pre><code> if (n == 3) {\n if (x == 1) {\n return k - 1;\n } else {\n return k - 2;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Despite passing all the tests, this code may give the wrong result if <code>n = 3</code> and <code>k &gt; MOD</code>, unless the problem imposed a limit on <code>k</code> not reflected in the above problem description. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:04:09.987", "Id": "459414", "Score": "0", "body": "You are correct k isn't larger than MOD :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T23:23:44.167", "Id": "234841", "ParentId": "234835", "Score": "3" } }, { "body": "<p><strong>\"Impossible\" check</strong></p>\n\n<p>Per task description, <code>k &gt;= 2</code> and <code>n &gt;= 3</code>. But nevertheless you're performing this \"impossible\" check:</p>\n\n<pre><code>if (n &lt; 3 || k &lt; 2) return 0;\n</code></pre>\n\n<p><strong>Redundant check</strong></p>\n\n<p>I don't understand why you're checking cases <code>n == 3</code> separately. You could remove these <code>2</code> checks and have this case handled in your <code>for</code> loop quite easily as below (please note that the values of <code>i</code>, <code>countOne</code> and <code>countOther</code> have changed):</p>\n\n<pre><code>long countOne = 0, countOther = 1, temp;\nfor (int i = 3; i &lt; n; i++) {\n temp = countOther * (k - 1) % MOD;\n countOther = (countOne % MOD + countOther * (k - 2) % MOD) % MOD;\n countOne = temp;\n} \n</code></pre>\n\n<p><strong>Variable naming</strong></p>\n\n<p><code>countOne</code> or <code>countOther</code> are not a good way to call your variables - their names don't convey their purpose. I'll leave it up to you to come up with better names. </p>\n\n<p><strong>Excessive modulo operation</strong></p>\n\n<p>You don't have to perform a modulo operation more times than is needed. Given you task constraints, your can perform a modulo operation twice per iteration as below:</p>\n\n<pre><code>temp = countOther * (k - 1) % MOD;\ncountOther = (countOne + countOther * (k - 2)) % MOD;\ncountOne = temp;\n</code></pre>\n\n<p><strong>Reduce scope of <code>temp</code></strong></p>\n\n<p>As @Barmar correctly pointed out, your <code>temp</code> variable should be local to the <code>for</code> loop. It's not needed anywhere out of it.</p>\n\n<p><strong>Simplify return statements</strong></p>\n\n<p>You don't have to calculate <code>countOne</code> or <code>countOther</code> once you leave the <code>for</code> loop. You can do it all there, just fix your loop condition from <code>i &lt; n</code> to <code>i &lt;= n</code> and swap <code>countOne</code> with <code>countOther</code> in your <code>return</code> statements.</p>\n\n<pre><code>for (int i = 3; i &lt;= n; i++) {\n long temp = countOther * (k - 1) % MOD;\n countOther = (countOne + countOther * (k - 2)) % MOD;\n countOne = temp;\n}\n\nif (x == 1) {\n return countOne;\n}\n\nreturn countOther;\n</code></pre>\n\n<p><strong>Final Code</strong></p>\n\n<pre><code>public static long countArray(int n, int k, int x) {\n\n long countOne = 0, countOther = 1;\n for (int i = 3; i &lt;= n; i++) {\n long temp = countOther * (k - 1) % MOD;\n countOther = (countOne + countOther * (k - 2)) % MOD;\n countOne = temp;\n }\n\n\n return x == 1 ? countOne : countOther;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:56:04.983", "Id": "459442", "Score": "1", "body": "I chose this answer becuase I like how you simplified my code. Thanks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T02:07:13.267", "Id": "234848", "ParentId": "234835", "Score": "7" } }, { "body": "<p>I suggest that you extract the similar evaluations in methods.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private static long countFirst(int k, long countOther, int i) {\n return countOther * (k - i) % MOD;\n }\n\n private static long countNext(int k, long countOne, long countOther) {\n return (countOne % MOD + countFirst(k, countOther, 2)) % MOD;\n }\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\n long countOne = k - 1;\n long countOther = k - 2;\n long temp;\n\n for (int i = 4; i &lt; n; i++) {\n temp = countFirst(k, countOther, 1);\n countOther = countNext(k, countOne, countOther);\n countOne = temp;\n }\n\n if (x == 1) {\n return countFirst(k, countOther, 1);\n }\n\n return countNext(k, countOne, countOther);\n//[...]\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T02:23:51.340", "Id": "234849", "ParentId": "234835", "Score": "6" } } ]
{ "AcceptedAnswerId": "234848", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-30T19:25:50.457", "Id": "234835", "Score": "6", "Tags": [ "java", "programming-challenge" ], "Title": "Construct the Array from HackerRank" }
234835
<p>This is a wrap that queries the number of files and folder from a given directory, also list the folders and files into a vector. I have posted <a href="https://codereview.stackexchange.com/q/234760/21571">another wrap in this discussion</a> that do the same things and following some really good suggestions I created another this time using <code>filesystem</code>.</p> <p>The filesystem I used is <a href="https://github.com/gulrak/filesystem" rel="nofollow noreferrer">this implementation</a> I found on GitHub because the filesystem I tried to use in codeblocks kept throwing errors even the filesystem from GCC 9.2.</p> <p>I didn't implement a cache mechanism because I don't know how to yet.</p> <p>wrap.h</p> <pre><code>#ifndef WRAP_H_INCLUDED #define WRAP_H_INCLUDED #include &lt;string&gt; #include &lt;vector&gt; #include &lt;ghc/filesystem.hpp&gt; namespace dir { class Wrap { private: Wrap() {} enum mode {FOLDER = 0, FILE_}; int number_of_entities_in_directory(std::string file_path, mode type_); std::vector&lt;std::string&gt; entities_in_directory(std::string file_path, mode type_); int number_of_entities_in_directory_recursively(std::string file_path, mode type_); std::vector&lt;std::string&gt; entities_in_directory_recursively(std::string file_path, mode type_); public: static int number_of_files_in_directory(std::string file_path); static int number_of_folders_in_directory(std::string file_path); static void files_in_directory(std::string file_path, std::vector&lt;std::string&gt;&amp; files); static void folders_in_directory(std::string file_path, std::vector&lt;std::string&gt;&amp; folders); static int number_of_files_in_directory_recursively(std::string file_path); static int number_of_folders_in_directory_recursively(std::string file_path); static void files_in_directory_recursively(std::string file_path, std::vector&lt;std::string&gt;&amp; files); static void folders_in_directory_recursively(std::string file_path, std::vector&lt;std::string&gt;&amp; folders); }; } #endif // WRAP_H_INCLUDED </code></pre> <p>wrap.cpp</p> <pre><code>#include "wrap.h" #include &lt;ghc/filesystem.hpp&gt; using namespace ghc::filesystem; using namespace std; using namespace dir; int Wrap::number_of_entities_in_directory(string file_path, mode type_) { int counter = 0; string secure_file_path = file_path + "/"; if ( ! exists(secure_file_path)) { throw runtime_error("directory does not exist"); } if(ghc::filesystem::is_empty(secure_file_path)) return 0; directory_iterator it (secure_file_path); directory_iterator endit; while(it != endit) { if(type_ == FILE_ &amp;&amp; is_regular_file(*it)) ++counter; else if(type_ == FOLDER &amp;&amp; is_directory(*it)) ++counter; ++it; } return counter; } vector&lt;string&gt; Wrap::entities_in_directory(string file_path, mode type_) { vector&lt;string&gt; entities; string secure_file_path = file_path + "/"; if ( ! exists(secure_file_path)) { throw runtime_error("directory does not exist"); } directory_iterator it(secure_file_path); directory_iterator endit; if( ! ghc::filesystem::is_empty(secure_file_path)) while (it != endit) { if(type_ == FILE_ &amp;&amp; is_regular_file(*it)) entities.push_back(it-&gt;path().filename()); else if(type_ == FOLDER &amp;&amp; is_directory(*it)) entities.push_back(it-&gt;path().filename()); ++it; } return entities; } int Wrap::number_of_entities_in_directory_recursively(string file_path, mode type_) { int counter = 0; string secure_file_path = file_path + "/"; if ( ! exists(secure_file_path)) { throw runtime_error("directory does not exist"); } if(ghc::filesystem::is_empty(secure_file_path)) return 0; recursive_directory_iterator it (secure_file_path); recursive_directory_iterator endit; while(it != endit) { if(type_ == FILE_ &amp;&amp; is_regular_file(*it)) ++counter; else if(type_ == FOLDER &amp;&amp; is_directory(*it)) ++counter; ++it; } return counter; } vector&lt;string&gt; Wrap::entities_in_directory_recursively(string file_path, mode type_) { vector&lt;string&gt; entities; string secure_file_path = file_path + "/"; if ( ! exists(secure_file_path)) { throw runtime_error("directory does not exist"); } recursive_directory_iterator it(secure_file_path); recursive_directory_iterator endit; if( ! ghc::filesystem::is_empty(secure_file_path)) while (it != endit) { if(type_ == FILE_ &amp;&amp; is_regular_file(*it)) entities.push_back(it-&gt;path().filename()); else if(type_ == FOLDER &amp;&amp; is_directory(*it)) entities.push_back(it-&gt;path().filename()); ++it; } return entities; } int Wrap::number_of_files_in_directory(string file_path) { if(file_path.empty()) return 0; Wrap dr; return dr.number_of_entities_in_directory(file_path, FILE_); } int Wrap::number_of_folders_in_directory(string file_path) { if(file_path.empty()) return 0; Wrap dr; return dr.number_of_entities_in_directory(file_path, FOLDER);; } void Wrap::files_in_directory(string file_path, vector&lt;std::string&gt;&amp; files) { if(file_path.empty()) return; Wrap dr; files = dr.entities_in_directory(file_path, FILE_); } void Wrap::folders_in_directory(string file_path, vector&lt;std::string&gt;&amp; folders) { if(file_path.empty()) return; Wrap dr; folders = dr.entities_in_directory(file_path, FOLDER); } int Wrap::number_of_files_in_directory_recursively(string file_path) { if(file_path.empty()) return 0; Wrap dr; return dr.number_of_entities_in_directory_recursively(file_path, FILE_); } int Wrap::number_of_folders_in_directory_recursively(string file_path) { if(file_path.empty()) return 0; Wrap dr; return dr.number_of_entities_in_directory_recursively(file_path, FOLDER);; } void Wrap::files_in_directory_recursively(string file_path, vector&lt;std::string&gt;&amp; files) { if(file_path.empty()) return; Wrap dr; files = dr.entities_in_directory_recursively(file_path, FILE_); } void Wrap::folders_in_directory_recursively(string file_path, vector&lt;std::string&gt;&amp; folders) { if(file_path.empty()) return; Wrap dr; folders = dr.entities_in_directory_recursively(file_path, FOLDER); } </code></pre> <p>main.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;wrap.h&gt; using namespace dir; using namespace std; int main() { string path = "D:/Music/"; vector&lt;string&gt; vec; Wrap::folders_in_directory(path, vec); for(auto i : vec) cout &lt;&lt; i &lt;&lt; endl; return 0; } </code></pre> <p>I created the wrapper as a static library project and added the header file to the <code>include</code> folder, hence the line:</p> <pre><code>#include &lt;wrap.h&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:42:54.820", "Id": "459387", "Score": "0", "body": "Can you provide some test code that exercises the wrap and demonstrates how to use it in code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:58:52.087", "Id": "459391", "Score": "0", "body": "@pacmaninbw done" } ]
[ { "body": "<h1>Avoid <code>using</code> too much <code>namespace</code></h1>\n\n<p>You risk having identical names mapped onto each other. Either be more selective in what you are <code>using</code>, or create short aliases if you want to avoid typing long namespace names, like:</p>\n\n<pre><code>namespace fs = ghc::filesystem;\n</code></pre>\n\n<p>You already ran into this problem with <code>is_empty()</code>.</p>\n\n<h1>Don't <code>#include</code> headers you don't need</h1>\n\n<p>In <code>wrap.h</code>, you <code>#include &lt;ghc/filesystem.hpp&gt;</code>, but nothing in that header file uses it. You should remove it, unless you plan to make the functions take <code>ghc::filesystem::path</code>'s as parameters instead of <code>std::string</code>s.</p>\n\n<h1>Use <code>enum class</code> where possible</h1>\n\n<p>A regular <code>enum</code> is not very type-safe. Prefer an <code>enum class</code>.</p>\n\n<h1>Be consistent in how you return results</h1>\n\n<p>Your private functions just return <code>std::vector&lt;std::string&gt;</code>, but the public functions take a reference to a <code>std::vector&lt;std::string&gt;</code>. Why is there a difference? Since the vector of strings is the result, just <code>return</code> it everywhere.</p>\n\n<h1>Make the private member functions <code>static</code></h1>\n\n<p>There is no reason for the private member functions not to be <code>static</code> in your class. But, then you'll realize that everything is <code>static</code>, which brings us to:</p>\n\n<h1>There is no need to use a <code>class</code></h1>\n\n<p>You are not storing any state in <code>class Wrap</code>, and all functions are or can be made <code>static</code>. So there is no reason to use a <code>class</code> here at all. You could move all the public member functions out of the class into <code>namespace dir</code>. The private member functions don't have to appear in <code>wrap.h</code> at all anymore.</p>\n\n<h1>Why the underscores?</h1>\n\n<p>Why write <code>FILE_</code> and <code>type_</code>? Unless they are macros you should be able to declare those symbols in your own classes and namespaces without the trailing underscore.</p>\n\n<h1>Avoid redundant tests for empty directories</h1>\n\n<p>There is no need to test for the directory being empty; your loops handle empty directories perfectly fine. You are adding unnecessary overhead in the common case where a directory is not empty, and if it is empty, your loops will just do nothing, so there is no performance penalty.</p>\n\n<h1>Use range-for where appropriate</h1>\n\n<p>You can use range-for to iterate over a directory, just like an STL container. So for example, in <code>Wrap::number_of_entities_in_directory()</code>, you can write:</p>\n\n<pre><code>for(auto entity: directory_iterator(secure_file_path)) {\n if(type == mode::FILE &amp;&amp; is_regular_file(entity))\n ++counter;\n else if(type == mode::FOLDER &amp;&amp; is_directory(entity))\n ++counter;\n}\n</code></pre>\n\n<h1>Consider using STL algorithms</h1>\n\n<p>Instead of writing your own loops, you could use STL algorithms. In fact, the whole function could be rewritten as:</p>\n\n<pre><code>#include &lt;algorithm&gt;\nnamespace fs = ghc::filesystem;\n...\nint Wrap::number_of_entities_in_directory(string file_path, mode type) {\n directory_iterator it(file_path);\n return std::count_if(fs::begin(it), fs::end(it), [type](const directory_entry &amp;ent){\n return type == FOLDER ? is_directory(ent) : is_regular_file(ent);\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:11:22.533", "Id": "459540", "Score": "0", "body": "**[Be consistent in how you return results]**\nDo you mean that instead of this: `void Wrap::files_in_directory(std::string file_path, vector<std::string>& files)` I should have it like this: `vector<std::string>Wrap::files_in_directory(std::string file_path)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:14:49.087", "Id": "459541", "Score": "0", "body": "Yes, that is what I meant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:21:35.180", "Id": "459542", "Score": "0", "body": "Actually that was the first way I implemented that function but then I changed it into how it is now, I just prefer it like this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:25:38.820", "Id": "459543", "Score": "0", "body": "**[There is no need to use a `class`]** I wanted to put all the function definition into a cpp file and have the header with only declarations of those functions. Don't know at what extent it is worth though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:27:29.023", "Id": "459544", "Score": "0", "body": "That's unrelated to whether you use a class or not. You can still have the declarations in the header file outside a class, and have the definitions in a cpp file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:28:32.283", "Id": "459545", "Score": "0", "body": "**[Why the underscores?]** I used `FILE_` to avoid any confusion to [link](http://www.cplusplus.com/reference/cstdio/FILE/)this. And the underscore in `type_` was random. Is there any convention for using underscores?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:34:06.110", "Id": "459546", "Score": "0", "body": "I tried that but when using the wrap I had `undefined references` (to those functions) errors, the lib file when using the wrap was added, so I thought it was not possible. Maybe I was wrong, I will try it again and check if I made any mistake" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:34:17.843", "Id": "459547", "Score": "0", "body": "Ah, if you use `enum class` you don't have to worry about conflicting with stdio's `FILE`, as it will then be in its own namespace. I personally avoid leading and trailing underscores. Some code styles use a single underscore at the start or end to indicate that something is a member variable, or in C it's sometimes used to indicate that something is meant to be private. Note that some uses of underscores are [reserved](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:38:31.937", "Id": "459548", "Score": "0", "body": "**[Avoid redundant tests for empty directories]** I did that to avoid the performance penalty but thanks to you now I know there's none. I will change the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:43:54.433", "Id": "459549", "Score": "0", "body": "**[Use `range-for` where appropriate]** I am new to `filesystem` so the `directory_iterator` was unknown to me until now. || \n**[Consider using STL algorithms]** wow, I see now that I am acturally not good with the STL algorithms, I will study it deeper and try to implement whenever I can. Answer upvoted, thanks for your review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:28:44.680", "Id": "459552", "Score": "0", "body": "You're welcome! If you find an answer useful, consider marking it as the [accepted answer](https://stackoverflow.com/help/someone-answers). You can always change it later if someone else provides a better answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:50:35.107", "Id": "459571", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/102774/discussion-between-hbatalha-and-g-sliepen)." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T11:44:52.340", "Id": "234896", "ParentId": "234844", "Score": "2" } } ]
{ "AcceptedAnswerId": "234896", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:06:05.583", "Id": "234844", "Score": "2", "Tags": [ "c++", "file-system", "c++17", "wrapper" ], "Title": "Wrap that uses filesystem in C++" }
234844
<p>I have recently made a hangman game using python. This is the main bulk of the code, however, there are other files that I have writen that get the words from a dictionary, or see if a word repeats any letters.</p> <pre><code>import Pick_Word, Unique_Chars word = (Pick_Word.get_word()).upper() wordlist = list(word) dict = dict(enumerate(wordlist)) slots = list('_' * len(word)) print(' '.join(slots)) def game(word): guess_num = 12 already = [] while '_' in slots: x = input("Guess the letter: ") while x in already: x = input("Guess the letter: ") for i in range(len(x)): if x[i] not in already: already.append(x[i]) turns = True for a,b in dict.items(): if x.upper() == word: return 'Win\nOnly {} more turns left over'.format(guess_word.title()) elif len(x) &gt; 1: single = Unique_Chars.unique(x) length = len(single) for idx in single: if b == idx.upper(): slots[a] = idx.upper() new_word = ' '.join(slots) elif b == x.upper(): slots[a] = x.upper() new_word = ' '.join(slots) new_word = ' '.join(slots) if len(x) &gt; 1: for i in range(length): if single[i].upper() not in word: guess_num -= 1 elif x.upper() not in word: guess_num -= 1 print(new_word, '\n{} turns left'.format(guess_num)) if guess_num == 0: return 'Lose\nActual Word was: {}'.format(word.title()) elif word == str(slots): return 'Win\nOnly {} more turns left over'.format(guess_word.title()) print(game(word)) </code></pre> <p>Is there anyway that I could shorten this code down, or make it run better, without completly rewirting the entire thing? Any feedback is much appreciated. Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T03:12:42.527", "Id": "459393", "Score": "0", "body": "Hi, I suggest you include those missing modules `Pick_Word` & `Unique_Chars` to help people reviewing your code understand as well as provide a better more meaningful review." } ]
[ { "body": "<ol>\n<li>Add type annotations. (This is usually my first piece of advice to all new Python coders: start using type annotations and mypy.) Adding some quick type annotations to your code and running <code>mypy</code> on it turned up the following bugs, which is a good demonstration of the sorts of mistakes that type checking can save you from:</li>\n</ol>\n\n<pre><code>hangman.py:18: error: Missing return statement\nhangman.py:31: error: Name 'guess_word' is not defined\nhangman.py:53: error: Name 'guess_word' is not defined\n</code></pre>\n\n<ol start=\"2\">\n<li><p>You probably want to use a <code>Set</code> rather than a <code>List</code> to track things like letters that have already been guessed (since you want it to be unique and you mostly want to check to see if things are in it).</p></li>\n<li><p>Look for opportunities to create functions for discrete tasks. \"Get a letter from the user\" is one that jumps out at me. Creating a function that takes over the task of getting a guess and making sure it's in the expected format (i.e. a single upper-case letter) lets us remove a lot of code that has to repeatedly try to normalize that input.</p></li>\n<li><p>Having tackled that, I see that there's a lot of code that tries to handle the case of the input being the complete word -- I'm not sure if that's a coding error or just confusion about the game design, but being as you're prompting the user to enter one letter at a time, it seems like we can get rid of all of this.</p></li>\n<li><p>Your <code>dict</code> variable is unnecessary and badly named; you created it from an iterable but the only thing you're doing with it is converting it back to an iterable. Just leave it as an iterable. :) The <code>wordlist</code> is unnecessary for the same reason.</p></li>\n<li><p>Use whitespace and comments to offset individual blocks of code that do different things.</p></li>\n<li><p>Again: delete unnecessary code.</p></li>\n<li><p>From a design standpoint, I think your <code>game</code> function should either return a string representing the output or it should print it (and be solely in charge of the printing), not do some of the printing and return the rest for the caller to do.</p></li>\n<li><p>Declare variables within the tightest scope possible. Specifically, there's no reason to declare <code>slots</code> outside of the <code>game</code> function definition since it's only used within that function. In this particular case it makes no functional difference, but it makes the code harder to read if you have to look outside the function to figure out where/how its state was initialized, and in a case where the function might be called multiple times you'd have to worry about keeping track of how changes to those shared variables affect different calls. Better to avoid this if at all possible.</p></li>\n</ol>\n\n<p>Here's the updated script after making the edits (I implemented my own stub <code>Pick_Word</code> for testing):</p>\n\n<pre><code>from typing import Set\n\nclass Pick_Word:\n @staticmethod\n def get_word() -&gt; str:\n return \"foobar\"\n\ndef get_guess(already_guessed: Set[str]) -&gt; str:\n \"\"\"Prompt the user for a letter guess.\n Return value is guaranteed to be a single upper-case letter\n that's not in the already_guessed set.\"\"\"\n while True:\n guess = input(\"Guess the letter: \").upper()\n if len(guess) == 1 and guess.isalpha() and guess not in already_guessed:\n return guess\n\ndef game(word: str) -&gt; None:\n \"\"\"Run the hangman game with the given word.\"\"\"\n word = word.upper()\n\n already: Set[str] = set()\n guess_num = 12\n slots = list('_' * len(word))\n\n # Let the game begin!\n print(' '.join(slots))\n\n while '_' in slots:\n # Get the next guess.\n guess = get_guess(already)\n already.add(guess)\n\n # Substitute the guess into matching slots.\n for i in range(len(word)):\n if word[i] == guess:\n slots[i] = guess\n\n # If the guess was a miss, subtract one turn.\n if guess not in word:\n guess_num -= 1\n\n print(' '.join(slots), '\\n{} turns left'.format(guess_num))\n\n if guess_num == 0:\n print('Lose\\nActual Word was: {}'.format(word.title()))\n return\n\n print('Win\\nOnly {} more turns left over'.format(guess_num))\n\ngame(Pick_Word.get_word())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T08:57:09.323", "Id": "234860", "ParentId": "234846", "Score": "3" } } ]
{ "AcceptedAnswerId": "234860", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T01:40:47.113", "Id": "234846", "Score": "1", "Tags": [ "python", "hangman" ], "Title": "Hangman Game Python" }
234846
<p>Here's the context: My code is meant to automate testing of OCR (Image to Text programs) for a science project which could easily be read and understood my others. The code includes sets of functions which serve different purposes. Basically, there are functions which deal with the drawing and saving of pages (<code>drawtext()</code>, <code>createpage()</code>, etc.), functions which run various OCR on an image (<code>tesseractocr()</code>, etc.) and a function which computes the difference between two strings (<code>levenshtein()</code>).</p> <p>Having all these functions in main.py results, in my opinion, in a cluttered piece of code. Is it better generally to:</p> <ol> <li>Keep all those functions in <code>main.py</code> so that the entire code is in one file.</li> <li>Put all these functions in one <code>functions.py</code> file</li> <li>Put each set of functions in a file, resulting in a <code>levenshtein.py</code>, <code>ocr.py</code>, and <code>pagemaker.py</code> in addition to the <code>main.py</code>.</li> </ol> <p>Honestly, I feel that either 2 or 3 is the choice to make, I'm just not sure. Additionally, what level of abstraction would you usually want in a <code>main.py</code> file? Should the file look like </p> <pre><code>import ocr, levenshtein, pagemaker import "a few other things" define vars, etc for page in pages: correct = pagemaker.drawpage(input1,input2,(input3,input4),etc) #also saves image tesseract_out = ocr.tesseract("img.png") tesseract_dist = levenshtein.levenshtein(correct, tesseract_out) print(f"Tesseract Distance: {tesseract_dist}") #etc for other ocr </code></pre> <p>Or is that too abstract? Also, is command-line argument parsing (which I didn't include above) generally in the main.py file or should you simply make a file called <code>parseocrargs.py</code> and run</p> <p><code>pages, color, etc = parseocrargs.argparse(aruments grabbed earlier)</code></p> <p>I guess the main question(s) are: Should a standalone (doesn't interact with other functions) but lengthy/ugly function go in a separate file than the other functions? Should almost all functions not be in <code>main.py</code>? If not, how many should be? Should <code>main.py</code> be extremely abstracted? If not, how abstracted should it be?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T04:45:44.307", "Id": "459395", "Score": "0", "body": "@Linny I posted it on StackOverflow and was told it was a better question for CodeReview" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T04:46:14.670", "Id": "459396", "Score": "0", "body": "If that's the case, do you mind posting the code in question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T04:48:05.707", "Id": "459397", "Score": "0", "body": "@Linny I can post the whole code dump in my question, is that okay?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T04:51:09.350", "Id": "459398", "Score": "0", "body": "@Linny The main reason I didn't dump the whole code is because only about 2/3 of it is done/in function form. The whole bottom of main.py is just a test of each function, and the arg parsing is still at the top without being in a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:00:01.447", "Id": "459412", "Score": "0", "body": "We have a character limit of just over 65k for questions. If it fits (code + current description), feel free to post it. But I'm not sure you want a review. I think you're really asking a design question here, which would fit better elsewhere. But it doesn't feel right to redirect you again (don't mind the people from Stack Overflow, half the time they don't have a clue what we do and don't do), so we can review the code with your concerns in mind. Hint: if the code is long enough, the best answer is never option 1." } ]
[ { "body": "<p>Putting all of your code into a single file is bad. As a very VERY loose rule of thumb I try to avoid having any source file be more than a thousand lines of code, but the real rule to follow is that code should be broken up into modules that have coherent and comprehensible purposes, and those modules should live in their own files. </p>\n\n<p>The origin of rules of thumb like \"no file longer than a thousand lines\" is that if a file is really long, it's no longer comprehensible by a normal human brain, and so you need to think about how to break your logic down into smaller and more mentally-digestible pieces. A function (or group of interrelated functions) that is long but is self-contained and doesn't interact with anything else would make a lot of sense to have in its own file/module.</p>\n\n<p>I'd probably do my argument parsing right in the main function unless the arg parsing was so complex that it felt like it needed to be its own module.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T18:00:29.387", "Id": "459448", "Score": "0", "body": "One more question - If the `main.py` file only needs to call the create_page() function from `drawimage.py`, should I only `from drawimage import create_page()` since that function calls the other functions in its file by itself, or do i still import everything?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T20:37:34.983", "Id": "459454", "Score": "0", "body": "Only import what you need (but don't include the `()` in the import statement, that's not how that works). In addition, if the other functions in that module are \"private\", you should prefix their names with underscores (e.g. `_private_function()`) to indicate that they're not meant to be imported or used elsewhere." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T09:05:18.160", "Id": "234861", "ParentId": "234853", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T04:39:22.117", "Id": "234853", "Score": "2", "Tags": [ "python", "python-3.x", "file", "modules" ], "Title": "Python Etiquette for Functions in Multiple Files" }
234853
<pre><code> static int[] PatternIndex(string given, string pattern) { var patternMap = new Dictionary&lt;int, string&gt;(); var patternArray = Array.Empty&lt;int&gt;(); var patternList = new List&lt;int&gt;(); if (string.IsNullOrEmpty(given) || string.IsNullOrEmpty(pattern)) return patternArray; string givenLower = given.ToLower(); string patternLower = pattern.ToLower(); for (int i = 0; i &lt; givenLower.Length - patternLower.Length; i++) { patternMap.Add(i, givenLower.Substring(i, patternLower.Length)); } foreach (var item in patternMap) { if (item.Value == patternLower) patternList.Add(item.Key); } patternArray = patternList.ToArray(); return patternArray; } </code></pre> <p>I added the following code as it comes up frequently in interview questions and it may help anyone trying to study for one, also if anyone wants to improve it for the greater good of the community.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T08:17:58.330", "Id": "459405", "Score": "2", "body": "Please add a textual description about what the code is supposed to do. Please also add a unit test that covers the basic scenarios as well as all edge cases. Without all this, your question is incomplete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T14:17:33.750", "Id": "459431", "Score": "1", "body": "Are two loops even necessary for this problem? Wouldn't you just do the check on the sub-string and if it matches the pattern add it to the list of indexes? Seems like only one loop is necessary (correct me if I'm wrong)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T17:34:18.397", "Id": "459446", "Score": "0", "body": "Came back to some comments, i am rewriting the function" } ]
[ { "body": "<pre><code> public static int[] PatternIndex(string given, string pattern)\n {\n var patternList = new List&lt;int&gt;();\n\n if (string.IsNullOrEmpty(given) || string.IsNullOrEmpty(pattern))\n return Array.Empty&lt;int&gt;();\n\n for (int i = 0; i &lt; given.Length - pattern.Length; i++)\n {\n if (given.ToLower().Substring(i, pattern.ToLower().Length) == pattern)\n patternList.Add(i);\n }\n\n return patternList.ToArray(); \n }\n</code></pre>\n\n<p>using advice from @Shelby i have rewritten the function, stripping out all unnecessary code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T17:44:14.290", "Id": "234878", "ParentId": "234855", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T07:13:26.760", "Id": "234855", "Score": "-3", "Tags": [ "c#" ], "Title": "Find the starting index of all occurrences of a pattern within a string" }
234855
<p>I have created class that uses <code>SharedPreferences</code> to store and retrieve application settings. Is it good idea to access <code>SharedPreferences</code> each time I need parameters? Will it drain system resources? </p> <pre><code>class MqttSettings { public static final String ADDRRESS ="address"; public static final String PORT ="port"; public static final String USERNAME ="username"; public static final String PASSWORD ="password"; public static final String CLIENTID ="clientid"; public SharedPreferences preferences; public void setAddress(String value) { preferences.edit().putString(ADDRRESS, value ).commit(); } public void setPort(int value) { preferences.edit().putInt(PORT, value ).commit(); } public void setUsername(String value) { preferences.edit().putString(USERNAME, value ).commit(); } public void setPassword(String value) { preferences.edit().putString(PASSWORD, value ).commit(); } public void setClientId(String value) { preferences.edit().putString(CLIENTID, value ).commit(); } public String getAddress() { return preferences.getString(ADDRRESS,"192.168.1.8"); } public int getPort() { return preferences.getInt(PORT,8883); } public String getUsername() { Log.d(Utils.LOGTAG,"getting username"); String r = null; try { r= preferences.getString(USERNAME,""); Log.d(Utils.LOGTAG,"getting username preferences"); } catch (Exception e) { Log.d(Utils.LOGTAG,"got exception "+e.getMessage()); e.printStackTrace(); } Log.d(Utils.LOGTAG,"getting username return"); return r; } public String getPassword() { Log.d(Utils.LOGTAG,"getting password"); return preferences.getString(PASSWORD,""); } public String getClientId() { return preferences.getString(CLIENTID,""); } public String getUri() { String uri ="tcp://"; uri=uri+getAddress()+":"+getPort(); Log.d(Utils.LOGTAG,uri); return uri; } public MqttSettings(SharedPreferences preferences) { this.preferences = preferences; } } </code></pre>
[]
[ { "body": "<p>Accessing SharedPreferences takes some definite amount of time because they are written and read from an actual file. So if you call this code too often from your mainThread, you will end up with ApplicationNotResponding errors and a bad user experience. The point is to call this on a background Thread (java) or coroutine(kotlin). The same goes for accessing the network, reading and writing to the database, long calculations etc </p>\n\n<p><a href=\"https://developer.android.com/training/articles/perf-anr\" rel=\"nofollow noreferrer\">https://developer.android.com/training/articles/perf-anr</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T08:07:36.430", "Id": "234857", "ParentId": "234856", "Score": "1" } }, { "body": "<p>It's fine as long as you don't do it in cycles and very often. If your app is slow, it is very likely due to other reasons.</p>\n\n<p>Still, if you don't need to read your value right after you write it, you can use <a href=\"https://developer.android.com/reference/android/content/SharedPreferences.Editor#apply()\" rel=\"nofollow noreferrer\">apply</a> instead of <a href=\"https://developer.android.com/reference/android/content/SharedPreferences.Editor#commit()\" rel=\"nofollow noreferrer\">commit</a>, which is faster and works asynchronously.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T08:55:39.913", "Id": "234858", "ParentId": "234856", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T07:42:58.090", "Id": "234856", "Score": "1", "Tags": [ "java", "android" ], "Title": "Does using SharedPreferences drain resources?" }
234856
<p>I have something like a shop. It is limited to a checkout page, which will send an email. Nothing big, but a nice thing to learn more OOP.</p> <p>Almost every time I develop new classes I am wondering how to organize the flow of depending methods. Here is an example, a first draft of what I have:</p> <pre><code>&lt;?php // Outside the class: if (!empty($cms-&gt;request-&gt;post('add_to_cart'))) { $cart-&gt;addStrt(); } </code></pre> <p>OPTION A</p> <pre><code>// OPTION A: Build a "method chain" and move from one to the other, to the next … Class Cart extends Shop { // This is the entry point and starts the "add process" public function addStart() { $this-&gt;checkQuantity(); // if qty is between min/max return false; } // Step 2 public function checkQuantity() { if ($quantity &lt; $max &amp;&amp; $quantity &gt; $min) { $this-&gt;checkInStock(); // move on to the next step } return false; } // Step 3 public function checkInStock() { if ($availabe &gt;= $qty_in_basket) { $this-&gt;addToCart(); // move on to the final step } return false; } // Step 4 public function addToCart() { // Final step, all requirements ok $product_id = $this-&gt;request-&gt;post-&gt;product_id; $cart = $this-&gt;getCart(); $product = $shop-&gt;getProduct($product_id); $cart-&gt;items-&gt;add($product); $added = $cart-&gt;save(); return $added; } } </code></pre> <p>OPTION B</p> <pre><code>// OPTION B: Have a single "add" method and check all requirements, sanitize, etc from a single method Class Cart extends Shop { public function add() { $continue = $this-&gt;checkQuantity(); // if qty is between min/max if ($continue == false) return false; $continue = $this-&gt;checkInStock(); // if product still available if ($continue == false) return false; // Perhaps more checks, sanitize, etc. // Everythiing mus be ok, put item into cart $product_id = $this-&gt;request-&gt;post-&gt;product_id; $cart = $this-&gt;getCart(); $product = $shop-&gt;getProduct($product_id); $cart-&gt;items-&gt;add($product); $added = $cart-&gt;save(); return $added; } } </code></pre> <p>I have read tutorials on some OOP patterns but can't seem to find which fits to my question. While Option B seems to be cleaner (to understand/extend) one thing I always read is never put multiple tasks into one method. Every method should only handle one specific task. But how/where do I control the flow?</p> <p>Is this "Encapsulation" or "Decorator pattern" or "Dependency Injection"? I have no idea what I should google.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:55:41.987", "Id": "459441", "Score": "0", "body": "I think the question might be clearer if you took the common code out of option a and created a section called common code, then the options just contain the code that is different and it is easier to compare. The suggestion in the answer to look up the Single Responsibility Principle is a good one, You also might want to look up SOLID programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:17:51.860", "Id": "459669", "Score": "0", "body": "Out of curiosity, why are most of your methods always returning `false`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:27:49.970", "Id": "459754", "Score": "0", "body": "You can simplify statements like `$continue = $this->checkInStock(); if ($continue == false) return false;` to just `if (!$this->checkInStock()) return false;` by the way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:31:53.517", "Id": "459755", "Score": "0", "body": "@MagnusEriksson It's fine for a method like `checkInStock()` to return a boolean which tells you if it's in stock or not. The methods in option A all returning `false` makes no sense though." } ]
[ { "body": "<p>It's good to have single method to control flow as you have in <code>B</code>, but this method should be mostly calling other methods of your class (you also call there <code>checkQuantity</code> for example, which is also in <code>A</code>). That way <code>add</code> is still very flexible - you can override those methods (probably protected methods, not public), that it calls or as last resort override that method itself.</p>\n\n<p>If you think <code>B</code> is more readable, imagine, there would be something like <code>this-&gt;addToCart</code> instead of this bit (and that extracted to separate method):</p>\n\n<pre><code> $product_id = $this-&gt;request-&gt;post-&gt;product_id;\n $cart = $this-&gt;getCart();\n $product = $shop-&gt;getProduct($product_id);\n\n $cart-&gt;items-&gt;add($product);\n $added = $cart-&gt;save();\n</code></pre>\n\n<p>I'd google for \"single responsibility principle\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T14:42:05.640", "Id": "234870", "ParentId": "234866", "Score": "2" } }, { "body": "<p>The problem I have with both versions is that you are adding functionality from all different items into 1 place.</p>\n\n<p>The first red flag for me is </p>\n\n<pre><code>Class Cart extends Shop {\n</code></pre>\n\n<p>Does a Cart really extend a Shop? You also have functionality for an order, a product etc. inside the Cart.</p>\n\n<p>What I have started to do is to break this down into what can be tangible classes, the scope of these classes will (hopefully) be clear enough to be extended to uses beyond what is here, but the idea is to look at what is responsible for what...</p>\n\n<pre><code>Class Shop {\n // Details including name, address, contact details etc.\n\n public function getProduct ( int $productID ) : Product {\n\n }\n}\n\n// Details of a particular Products\nClass Product {\n // Product description etc.\n</code></pre>\n\n<p>The next method can be used in a multitude of situations, so in itself it is worth becoming a public method...</p>\n\n<pre><code> public function getStock() {\n return $this-&gt;quantity;\n }\n}\n</code></pre>\n\n<p>An Order is created once a user has saved a Cart. You can use a Builder pattern to create an Order from all of the details required, you can include things like payment status/method, Customer details, delivery &amp; special instructions etc.</p>\n\n<p>For this example just say it is a Cart</p>\n\n<pre><code>// A user places an Order\nclass Order {\n public function __construct( Cart $cart ) {\n $this-&gt;cart = $cart;\n }\n</code></pre>\n\n<p>Again an Order can be processed all over the place, so other methods which allow you to update the items in a cart, change delivery details etc. can be used in different pages. Once they have been updated, the next method can process save of the Order.</p>\n\n<pre><code> // Save order - returns true/false depending on if saved OK\n public function save() {\n // Save order - all parts including items in the order, delivery details etc.\n return true;\n }\n}\n\n// A Cart is a list of items the customer wants to buy\nClass Cart {\n private $items = [];\n\n // Returns list of items out of stock or true if OK.\n public function checkStock () {\n $errors = [];\n // Check that each item in the cart has enough stock\n foreach ( $items as $item ) {\n if ( $item[\"product\"]-&gt;getStock() &gt; $item[\"quantity\"] ) {\n // Store list of messages about item being out of stock\n $errors[] = 'Not enough stock';\n }\n }\n\n return !empty($errors) ? $errors : true;\n }\n\n // Add a particular item to a cart\n public function addItem ( Product $product, $quantity ) : bool {\n $this-&gt;items[] = [ \"product\" =&gt; $product, \"quantity\" =&gt; $quantity];\n\n return true;\n }\n}\n</code></pre>\n\n<p>The above class are some of the tangible objects in the system, others may include Customers, Delivery types and anything else.</p>\n\n<p>You then need something to put these together. This is the controller in MVC, and links to the actions the user makes in the front end.</p>\n\n<p>When you click on save a cart (or depending on your requirements after payment etc.) This will call <code>checkoutCart()</code>. This uses the methods in the various other class, so asks a <code>Cart</code> to check the stock (which then calls the <code>Product</code> methods), it then creates an <code>Order</code> and assuming everything goes OK it calls the <code>Order</code> method to save the Order.</p>\n\n<pre><code>// Controller for Checkout page\nClass CheckoutController {\n // Final save to create an Order\n public function checkoutCart() {\n // Retrieve cart for session\n $checkCart = $cart-&gt;checkStock();\n if ( $checkCart !== true ) {\n // Stock levels no longer can fulfill order\n // Exit with information about items no longer available\n }\n $order = new Order($cart);\n if ( $order-&gt;save() ) {\n // Message order created\n }\n else {\n // Message order not created\n }\n }\n}\n\n// Controller for Item page\nClass ItemPageController {\n public function addItemToCart() {\n // Retrieve cart/shop for session\n\n $product = $shop-&gt;getProduct($this-&gt;request-&gt;post-&gt;product_id);\n $cart-&gt;addItem($product, $this-&gt;request-&gt;post-&gt;quantity);\n // Message to say item added\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T09:40:29.067", "Id": "235061", "ParentId": "234866", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T12:39:31.873", "Id": "234866", "Score": "3", "Tags": [ "php", "object-oriented", "design-patterns", "comparative-review" ], "Title": "Organise method flow" }
234866
<p>I have just completed my first Ruby OOP project. Fairly simple but still a bit time consuming as I am still learning the language.</p> <p>I would like feedback and ways I can improve on this and make the flow of code better or could have done something in a different way to save time or the "right way".</p> <p>I thank you all in advance!</p> <p>my code below</p> <pre><code>class Player attr_accessor :name def initialize(name) @name = name end end class Game def player_vs_AI? puts "Hello User..." puts "Will you be playing against another person or the computer?" puts "Choose 1 for another person or choose 2 for the computer" @answer = gets.chomp.to_s end def greeting names = ['Bob', 'Joseph', 'Catherine', 'Paul', 'Tom', 'Baker'] puts "Hi, please enter your name player 1: " name1 = gets.chomp @player1 = Player.new(name1) if @answer == '1' puts "Hi, please enter your name player 2: " name2 = gets.chomp @player2 = Player.new(name2) elsif @answer == '2' name2 = names.sample @player2 = Player.new(name2) puts "Player 2 will be named #{@player2.name}" end sleep(0.5) puts "Welcome to Rock-Paper-Scissor" sleep(0.5) puts "Welcome #{@player1.name} and #{@player2.name}\n\n" sleep(0.5) end def instruct puts "The rules of the game are simple\n" puts "Simply choose Rock(R), Paper(P) or Scissor(S) each turn\n " puts "Paper beats Rock, Scissor beats paper and Rock beats Scissor\n" puts "Ready....?" sleep(1.0) end def choice choices = ['r', 'p', 's'] puts "#{@player1.name}, please choose your choice of weapon: R(rock), P(paper), S(Scissor)" @choice_1=gets.chomp @choice_1.downcase! while !(@choice_1 == 'r' || @choice_1 == 'p' || @choice_1 == 's') do puts "#{@player1.name} That is not a valid choice, please choose from r, p, or s" @choice_1=gets.chomp @choice_1.downcase! end if @answer == '1' puts "#{@player2.name}, please choose your choice of weapon: R(rock), P(paper), S(Scissor)" @choice_2=gets.chomp @choice_2.downcase! while !(@choice_2 == 'r' || @choice_2 == 'p' || @choice_2 == 's') do puts "#{@player2.name} That is not a valid choice, please choose from r, p, or s" @choice_2=gets.chomp @choice_2.downcase! end elsif @answer == '2' @choice_2 = choices.sample end end def logic puts "Lets see who wins...will it be #{@player1.name} or will it be #{@player2.name}\n" sleep(2.0) if @choice_1 == @choice_2 puts "Opps, both players picked the same weapon, It is a TIE!!!" puts "Lets go back and choose again..." sleep(3.0) choice end if @choice_1 == 'r' &amp;&amp; @choice_2 == 'p' puts "#{@player2.name} win!!! Paper covers Rock" elsif @choice_1 == 'p' &amp;&amp; @choice_2 == 'r' puts "#{@player1.name} you Win!!! Paper covers Rock" elsif @choice_1 == 'p' &amp;&amp; @choice_2 == 's' puts "#{@player2.name} you win!!! Scissor cuts Paper " elsif @choice_2 == 's' &amp;&amp; @choice_1 == 'p' puts "#{@player1.name} you win!!! Scissor cuts Paper" elsif @choice_1 == 'r' &amp;&amp; @choice_2 == 's' puts "#{@player1.name} you win!!! Rock beats Scissor" else @choice_2 == 'r' &amp;&amp; @choice_1 == 's' puts "#{@player2.name} you win!!!! Rock beats Scissor" end end def play_again? sleep(0.5) puts "\n" puts "Would you like to play again?(yes/no) " input = gets.chomp if input == 'yes' start elsif input == 'no' puts "Thank #{@player1.name} and #{@player2.name} for playing!" end end end def start game = Game.new game.player_vs_AI? game.greeting game.instruct game.choice game.logic game.play_again? end start <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T03:49:30.723", "Id": "466797", "Score": "0", "body": "You can simplify the task of determining which player, if either, wins a given throw, by creating a hash `winners = { r: :s, :p :r, :s :p }`. Then if player 1 throws `p1` (`:r`, `:p` or `:s`) and player 2 throws `p2`, player 1 wins if `winners[p1] == p2`, else player 2 wins if `winners[p2] == p1` else it's a tie and they throw again." } ]
[ { "body": "<p>The biggest thing that will allow the code to clean up a fair bit is if you had made a subclass of <code>Player</code> for <code>AIPlayer</code>:</p>\n\n<pre><code>class AIPlayer &lt; Player\n NAMES = ['Bob', 'Joseph', 'Catherine', 'Paul', 'Tom', 'Baker']\n\n def initialize\n super NAMES.sample\n end\nend\n</code></pre>\n\n<p>that will allow you to add a method <code>get_weapon</code> to <code>Player</code>, which would ask for the user input and override it in <code>AIPlayer</code> to return a random selection. Your <code>choice</code> method then can become cleaner:</p>\n\n<pre><code>def choice\n @choice_1 = @player1.get_weapon\n @choice_2 = @player2.get_weapon\nend\n</code></pre>\n\n<p>and not care about if it's player vs player or vs ai. Your <code>player_vs_AI?</code> method can then return <code>true</code> or <code>false</code> and not have to assign an instance variable at all:</p>\n\n<pre><code>def player_vs_AI?\n puts \"Will you be playing against another person or the computer?\"\n puts \"Choose 1 for another person or choose 2 for the computer\"\n\n gets.chomp.to_s == '2'\nend\n</code></pre>\n\n<p>and can be then used to clean up like:</p>\n\n<pre><code>def greeting\n puts \"Hi, please enter your name player 1: \"\n name1 = gets.chomp\n @player1 = Player.new(name1)\n\n if player_vs_AI?\n @player2 = AIPlayer.new\n puts \"Player 2 will be named #{@player2.name}\"\n else\n puts \"Hi, please enter your name player 2: \"\n name2 = gets.chomp\n @player2 = Player.new(name2)\n end\n sleep(0.5)\n puts \"Welcome to Rock-Paper-Scissor\"\n sleep(0.5)\n puts \"Welcome #{@player1} and #{@player2}\\n\\n\"\n sleep(0.5)\nend\n</code></pre>\n\n<p>and you no longer need to call <code>player_vs_AI?</code> during <code>start</code>.</p>\n\n<p>Your <code>play_again?</code> method also shouldn't call <code>start</code> itself, instead the <code>start</code> method should check if they want to play again and just keep getting choices and checking the results:</p>\n\n<pre><code>def start\n game = Game.new\n game.greeting\n game.instruct\n loop do\n game.choice\n game.logic\n break unless game.play_again?\n end\nend\n</code></pre>\n\n<p>having trimmed down the <code>choice</code> method, it could be combined with the <code>logic</code> method and perhaps renamed <code>play</code> (or something more meaningful) and <code>start</code> could be renamed <code>run</code>.</p>\n\n<p>On a last note, I would try to make things consistent for the user. You're asking for input options 3 times, the first it's enter <code>1</code> or <code>2</code> (<code>player_vs_AI?</code>), the second it's <code>r</code>, <code>p</code>, or <code>s</code> (<code>choice</code>) and the last time in <code>play_again?</code> they have to enter <code>yes</code> or <code>no</code>. Only in <code>choice</code> is there input validation (what happens in <code>play_again?</code> if I try to enter <code>y</code> instead of <code>yes</code>?). This could be more consistent (always allow the full word to be entered, or just the first letter, for instance).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T14:11:33.830", "Id": "459615", "Score": "0", "body": "awesome! thank you for the feedback and great suggestions that i will make in my code. Also, do you think there would have been a better way to do my `logic` method instead of all the `if-else` loops" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T11:38:47.610", "Id": "234943", "ParentId": "234868", "Score": "3" } }, { "body": "<p>I am not a professional game developer, just trying to help you base on my experience with Ruby so far. Glad to see your willingness of coding correctly from the beginning.</p>\n\n<p>Some points to improve:</p>\n\n<p>1.Move the bot names and game mode options to CONSTANTS</p>\n\n<p>2.Prompting for user's input is duplicated many times, you should make a function that take prompting lines and accepted values as arguments then return only when user input is in accepted values.</p>\n\n<p>3.Beside <code>name</code>, a <code>Player</code> can have <code>weapon</code> as its instance variable also.</p>\n\n<p>4.About the <code>logic</code> method, I found a way to improve it, please consider. If we put all the options to an array by a specific order that the option at higher index will win ([r, p, s] or [p, s, r] or [s, r, p]) then the logic can patternized. The only exception is when the higher index is the last element but the smaller index is the first element, we can solve the exception with a simple <code>if</code></p>\n\n<p>5.You should also learn how to write test spec and apply it here especially for <code>logic</code> method</p>\n\n<p>6.Last but not least, your indentation :)</p>\n\n<pre><code>class Player\n attr_accessor :name, :weapon\n\n def initialize(name)\n @name = name\n end\nend\n\nclass Game\n BOT_NAMES = ['Bob', 'Joseph', 'Catherine', 'Paul', 'Tom', 'Baker']\n WEAPONS = {'r' =&gt; 'Rock', 'p' =&gt; 'Paper', 's' =&gt; 'Sissors'}\n\n def prompt_for_user_input(accepted_inputs=[], prompt_lines=[], is_case_sensitive=true)\n loop do\n prompt_lines.each { |line| puts line }\n user_input = gets.chomp\n return user_input.to_s if accepted_inputs.empty?\n is_valid_input = is_case_sensitive ? accepted_inputs.include?(user_input) : accepted_inputs.any?{ |s| s.casecmp(user_input) == 0 }\n return user_input.to_s if is_valid_input\n end\n end\n\n def mode_selection\n prompt_lines = [\n \"Hello User...\",\n \"Will you be playing against another person or the computer?\",\n \"Choose 1 for another person or choose 2 for the computer\"\n ]\n\n @mode = prompt_for_user_input(['1', '2'], prompt_lines)\n end\n\n def player_creation\n @player1 = Player.new(prompt_for_user_input([], [\"Hi, please enter your name player 1:\"]))\n @player2 = if (@mode == '1')\n Player.new(prompt_for_user_input([], [\"Hi, please enter your name player 2:\"]))\n else\n bot_name = BOT_NAMES.sample\n puts \"Player 2 will be named #{bot_name}\"\n Player.new(bot_name)\n end\n\n sleep(0.5)\n puts \"Welcome #{@player1.name} and #{@player2.name} to Rock-Paper-Scissor\"\n end\n\n def instruct\n puts \"The rules of the game are simple\\n\"\n puts \"Simply choose Rock(R), Paper(P) or Scissor(S) each turn\\n \"\n puts \"Paper beats Rock, Scissor beats Paper and Rock beats Scissor\\n\"\n puts \"Ready....?\"\n sleep(1.0)\n end\n\n def weapon_selection\n @player1.weapon = prompt_for_user_input(WEAPONS.keys, [\"#{@player1.name}, please chooose your choice of weapon: r(Rock), p(Paper), s(Sissor)\"], false)\n @player2.weapon = if (@mode == '1')\n prompt_for_user_input(WEAPONS.keys, [\"#{@player2.name}, please chooose your choice of weapon: r(Rock), p(Paper), s(Sissor)\"], false)\n else\n bot_weapon = WEAPONS.keys.sample\n puts \"#{@player2.name} chooses #{WEAPONS[bot_weapon]}\"\n bot_weapon\n end\n\n puts \"Let see who wins... will it be #{@player1.name} or will it be #{@player2.name}\"\n sleep(2.0)\n decider\n end\n\n def decider\n if @player1.weapon == @player2.weapon\n puts \"Opps, both players picked the same weapon, It is a TIE!!!\"\n puts \"Lets go back and choose again...\"\n sleep(3.0)\n weapon_selection\n end\n\n weapon_keys = WEAPONS.keys\n weapon_1_index = weapon_keys.find_index(@player1.weapon)\n weapon_2_index = weapon_keys.find_index(@player2.weapon)\n if weapon_1_index &gt; weapon_2_index\n if (weapon_1_index == weapon_keys.length - 1) &amp;&amp; (weapon_2_index == 0)\n @winner, @loser = @player2, @player1\n else\n @winner, @loser = @player1, @player2\n end\n else\n if (weapon_2_index == weapon_keys.length - 1) &amp;&amp; (weapon_1_index == 0)\n @winner, @loser = @player1, @player2\n else\n @winner, @loser = @player2, @player1\n end\n end\n\n end\n\n def result \n puts \"#{@winner.name} you win !!! #{WEAPONS[@winner.weapon]} beats #{WEAPONS[@loser.weapon]}\"\n end\n\n def again?\n prompt_for_user_input(['y', 'n'], prompt_lines=[\"Would you like to play again?(y/n)\"]) == 'y'\n end\n\n def play\n loop do\n mode_selection\n player_creation\n instruct\n weapon_selection\n decider\n result\n break unless again?\n end\n puts \"Thank #{@player1.name} and #{@player2.name} for playing!\"\n end\nend\n\ng = Game.new\ng.play\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:51:08.947", "Id": "459661", "Score": "0", "body": "Awesome! All the suggestions were great and made my code a lot better. I do have a question for the `logic` method that you suggested. When you wrote `weapon_keys.length - 1` is that because we are comparing it to the index of the array which starts at `0` so to make it equal we have to do `.length-1`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T04:00:14.950", "Id": "459699", "Score": "0", "body": "No, the `weapon_keys.length - 1` is to check if the weapon is the last element of the array. Last index of the last element is `array length - 1`, a common trick when working with array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:31:50.693", "Id": "459715", "Score": "0", "body": "Update: All the `Game` methods except for `play` should be private" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:16:49.157", "Id": "234955", "ParentId": "234868", "Score": "2" } } ]
{ "AcceptedAnswerId": "234943", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T13:57:10.927", "Id": "234868", "Score": "1", "Tags": [ "object-oriented", "ruby" ], "Title": "Rock, Paper, Scissors completed game" }
234868
<p>The F# web-development framework <a href="https://github.com/giraffe-fsharp/Giraffe" rel="nofollow noreferrer">Giraffe</a> supports a functional style of Dependency Injection using a form of the Reader monad, as explained in this <a href="https://zaid-ajaj.github.io/Fable.Remoting/src/dependency-injection.html" rel="nofollow noreferrer">GitBook</a>. I would like to use this pattern more generally, moving away from a service-locator pattern I use today in which my injection sites are coupled to the specific service locator. As such, I have created a small package to facilitate common DI scenarios using the Reader monad pattern. My goal is to be able to write code like this:</p> <pre><code>let logObject x = injected { let! log = inject&lt;ILogger&gt;() let! serializer = inject&lt;ISerializer&gt;() return x |&gt; serializer.Serialize |&gt; log.WriteLog } </code></pre> <p>First off, here's my implementation of the reader monad:</p> <pre><code>/// Defines a standard 'Reader' monad type Reader&lt;'a, 'b&gt; = Reader of ('a -&gt; 'b) module Reader = let run x (Reader f) = f x let create x = Reader (fun _ -&gt; x) let bind f x = let future state = let z = run state x run state (f z) Reader future let map f x = bind (f &gt;&gt; create) x type ReaderBuilder&lt;'t, 'u&gt; () = member __.Bind (x, f) = Reader.bind f x member __.Return (x) = Reader.create x member __.ReturnFrom x = x member __.Zero () = Reader.create () member __.Delay (f) = f() member __.Combine (a, b) = a |&gt; Reader.bind (fun () -&gt; b) member this.TryFinally(body, compensation) = try this.ReturnFrom(body()) finally compensation() member this.Using(resource : 'T when 'T :&gt; System.IDisposable, binder : 'T -&gt; Reader&lt;'a, 'b&gt;) : Reader&lt;'a, 'b&gt; = let body' = fun () -&gt; binder resource this.TryFinally(body', fun () -&gt; match resource with | null -&gt; () | disp -&gt; disp.Dispose()) member this.While (guard, body: unit -&gt; Reader&lt;_,_&gt;) = if not (guard()) then this.Zero() else this.Bind(body(), fun () -&gt; this.While(guard, body)) member this.For (sequence: seq&lt;_&gt;, body) = this.Using(sequence.GetEnumerator(), fun enum -&gt; this.While(enum.MoveNext, fun () -&gt; body enum.Current)) [&lt;AutoOpen&gt;] module ReaderMonad = let reader&lt;'a, 'b&gt; = ReaderBuilder&lt;'a, 'b&gt;() </code></pre> <p>Next, I created an <code>Injected</code> type that wraps up the specific case of <code>Reader</code> for <code>Reader&lt;IServiceProvider, Result&lt;_,_&gt;&gt;</code>, which will allow me to use this pattern with any IoC container that implements the <code>System.IServiceProvider</code> interface:</p> <pre><code>open System type DependencyInjectionError = | NoServiceFound of Type | UnexpectedDependencyInjectionError of exn /// Defines a specialized Reader monad for Dependency Injection type Injected&lt;'t, 'e&gt; = Reader&lt;IServiceProvider, Result&lt;'t, 'e&gt;&gt; module Injected = let run x f = Reader.run x f let create x = Reader.create (Ok x) let bind&lt;'a, 'b, 'e&gt; (f: 'a -&gt; Injected&lt;'b, 'e&gt;) (x: Injected&lt;'a, 'e&gt;) : Injected&lt;'b, 'e&gt; = let future state = let result = run state x match result with | Ok z -&gt; run state (f z) | Error e -&gt; Error e Reader future let bindResult&lt;'a, 'b, 'e&gt; (f: 'a -&gt; Injected&lt;'b, 'e&gt;) (x: Result&lt;'a, 'e&gt;) : Injected&lt;'b, 'e&gt; = match x with | Ok z -&gt; f z | Error e -&gt; Reader (fun _ -&gt; Error e) let map f x = bind (f &gt;&gt; create) x let mapError f (x: Injected&lt;_,_&gt;) : Injected&lt;_,_&gt; = let (Reader getResult) = x fun provider -&gt; let result = getResult provider match result with | Ok value -&gt; Ok value | Error e -&gt; Error (f e) |&gt; Reader let ofResult (result: Result&lt;_,_&gt;) : Injected&lt;_,_&gt; = Reader.create result let join (elements: Injected&lt;'a,'e&gt; seq) : Injected&lt;'a list, 'e&gt; = elements |&gt; Seq.fold (fun acc cur -&gt; fun provider -&gt; let result = run provider acc match result with | Ok values -&gt; let next = run provider cur match next with | Ok value -&gt; Ok (values @ [value]) | Error error -&gt; Error error | Error error -&gt; Error error |&gt; Reader) (create []) let ignore (i: Injected&lt;_,_&gt;) = i |&gt; map ignore type InjectionBuilder&lt;'t&gt; () = member __.Bind (x, f) : Injected&lt;_,_&gt; = Injected.bind f x member __.Bind (x, f) : Injected&lt;_,_&gt; = Injected.bindResult f x member __.Return (x) : Injected&lt;_,_&gt; = Injected.create x member __.ReturnFrom (x: Injected&lt;_,_&gt;) = x member __.ReturnFrom (x: Result&lt;_,_&gt;) = Injected.ofResult x member __.Zero () : Injected&lt;_,_&gt; = Injected.create () member __.Delay (f) : Injected&lt;_,_&gt; = f() member __.Combine (a, b) : Injected&lt;_,_&gt; = a |&gt; Injected.bind (fun () -&gt; b) member this.TryFinally(body: unit -&gt; Injected&lt;_,_&gt;, compensation) : Injected&lt;_,_&gt; = try this.ReturnFrom(body()) finally compensation() member this.Using(resource : 'T when 'T :&gt; System.IDisposable, binder : 'T -&gt; Injected&lt;'a, 'e&gt;) : Injected&lt;'a, 'e&gt; = let body' = fun () -&gt; binder resource this.TryFinally(body', fun () -&gt; match resource with | null -&gt; () | disp -&gt; disp.Dispose()) member this.While (guard, body: unit -&gt; Injected&lt;_,_&gt;) : Injected&lt;_,_&gt; = if not (guard()) then this.Zero() else this.Bind(body(), fun () -&gt; this.While(guard, body)) member this.For (sequence: seq&lt;_&gt;, body) : Injected&lt;_,_&gt; = this.Using(sequence.GetEnumerator(), fun enum -&gt; this.While(enum.MoveNext, fun () -&gt; body enum.Current)) </code></pre> <p>Finally, I created a <code>DependencyInjection</code> module to facilitate the actual usage of an <code>IServiceProvider</code> to resolve dependencies and execute the <code>injected</code> computation using the injected services:</p> <pre><code>open System module DependencyInjection = type IServiceProvider with member this.GetService&lt;'t&gt;() = let serviceType = typeof&lt;'t&gt; try match this.GetService(serviceType) with | null -&gt; Error &lt;| NoServiceFound serviceType | :? 't as service -&gt; Ok service | _ -&gt; Error &lt;| NoServiceFound serviceType with ex -&gt; Error &lt;| UnexpectedDependencyInjectionError ex let getService&lt;'t&gt; (context : IServiceProvider) = if typeof&lt;'t&gt;.IsAssignableFrom(typeof&lt;IServiceProvider&gt;) then context |&gt; unbox&lt;'t&gt; |&gt; Ok else context.GetService&lt;'t&gt;() let resolve (container: IServiceProvider) (reader: Injected&lt;_,_&gt;) = let (Reader f) = reader f container [&lt;AutoOpen&gt;] [&lt;CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)&gt;] module DependencyInjectionBuilder = let injected&lt;'t&gt; = InjectionBuilder&lt;'t&gt;() let inject&lt;'t&gt;() : Injected&lt;'t, DependencyInjectionError&gt; = Reader (fun (context: IServiceProvider) -&gt; DependencyInjection.getService&lt;'t&gt; context) </code></pre> <p>I plan to put these modules together into a NuGet package, then use that from my other F# projects to start decoupling my existing code from our specific service locator, replacing direct calls to <code>container.GetService&lt;'t&gt;()</code> with the new <code>injected</code> computation and the <code>inject&lt;'t&gt;()</code> function. This way, I hope to enable better interoperability with the built-in <code>Microsoft.Extensions.DependencyInjection</code> framework used in .NET Core and be able to leverage whichever DI framework is already wired-up in a given .NET Core application. </p> <p>Does this look like it would work as I'm intending? Are there any glaring oversights I haven't considered here?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:15:06.650", "Id": "234872", "Score": "3", "Tags": [ "functional-programming", "f#", "dependency-injection" ], "Title": "Functional Dependency Injection Abstraction" }
234872
<p>I have this method that creates book objects. I pass a list of strings (size 60000+) that contain the information of the book, the function then goes and extracts the information makes the book object and adds to a global list.</p> <p>This solution works, but is not memory that efficient and slow due to the replacements and regex that happen each loop and strings being made. So, can I make improvements to my regex and is there a better way perform many replacements per loop</p> <pre class="lang-java prettyprint-override"><code> private static void defineBooks(List&lt;String&gt; paragraphs) { // Pattern id = Pattern.compile("[^\\s]\\d+"); Pattern title = Pattern.compile("[\\S\\s]+"); Pattern author = Pattern.compile(", by(.*)(?=\\s*)"); Pattern subtitle = Pattern.compile("\\[Subtitle: [^\\[\\]]+]"); Pattern language = Pattern.compile("\\[Language: [^\\[\\]]+]"); Pattern contents = Pattern.compile("\\[Contents: [^\\[\\]]+]"); Pattern tempx = Pattern.compile("\\d{1,5}$"); Pattern tempy = Pattern.compile("^\\d{1,5}|\\d{1,5}[A-Z]?\\s?$"); Pattern i = Pattern.compile("^, by "); Pattern j = Pattern.compile("\\s+(?&lt;= )\\d+(\\w)?$|(?&lt;= )\\d+(\\w)?\\s+$|(?&lt;=\\D)\\d+(\\w)?$"); for (int i1 = 0, paragraphsSize = paragraphs.size(); i1 &lt; paragraphsSize; i1++) { String para = paragraphs.get(i1); Matcher mid = tempx.matcher(para.replaceAll("\n.+", "")); Matcher midy = tempy.matcher(para.replaceAll("\n.+", "")); Matcher mtitle = title.matcher(para); Matcher mauthor = author.matcher(para); Matcher msubtitle = subtitle.matcher(para); Matcher mlanguage = language.matcher(para); Matcher mcontents = contents.matcher(para); Book book = new Book(); Matcher temp = Pattern.compile("@\\d{1,5}[A-Z]?@?") .matcher(para.replaceAll("\\s{2,}", "@")); if (temp.find()) { book.setId(temp.group().replaceAll("@", "")); } else if (mid.find()) { book.setId(mid.group().trim()); } else if (midy.find()) { book.setId(midy.group().trim()); } if (mtitle.find()) { book.setTitle(para.replaceAll("\\[[^\\[]+(?:])", "") .replaceAll("(Passed | by|, by).*+", "") .replaceAll("\\s{2,}\\d{1,5}(\\s)?", "") .replaceAll("\n", " ") .replaceAll(",$", "") .replaceAll("\\s+", " ").trim()); } if (mauthor.find()) { String bauthor = i.matcher(mauthor.group()).replaceAll(""); book.setAuthor(j.matcher(bauthor).replaceAll("")); } if (msubtitle.find()) { book.setSubtitle(msubtitle.group() .replaceAll("\\[Subtitle: ", "") .replaceAll("]", "") .replaceAll("\\s{2,}", " ")); } else { book.setSubtitle(""); } if (mcontents.find()) { book.setContents(mcontents.group() .replaceAll("\\[Contents: ", "") .replaceAll("]", "") .replaceAll("\\s{2,}", " ")); } else { book.setContents(""); } if (mlanguage.find()) { book.setLanguage(mlanguage.group() .replaceAll("\\[Language: ", "") .replaceAll("]", "") .replaceAll("\\s{2,}", " ")); } else { book.setLanguage("English"); } if (!Objects.equals(book.getId(), "")) { books.add(book); } } </code></pre> <p><strong>Book</strong></p> <pre class="lang-java prettyprint-override"><code>public class Book { private String id; private String title; private String author; private String subtitle; private String contents; private String language; public void setId(String id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } public void setSubtitle(String subtitle) { this.subtitle = subtitle; } public void setContents(String contents) { this.contents = contents; } public String getContents() { return contents; } public void setLanguage(String language) { this.language = language; } public String getId() { return id; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T00:00:24.687", "Id": "459464", "Score": "0", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 3" } ]
[ { "body": "<p>You can check the <a href=\"https://en.wikipedia.org/wiki/Flyweight_pattern\" rel=\"nofollow noreferrer\">Flyweight Pattern</a> if you have duplicates in the data. This pattern uses a cache to prevent the recalculation of similar objects.</p>\n\n<p>Here is some general recommendation for your code; those changes won’t help for the performance issue, but will help when reading the code and make it shorter.</p>\n\n<p>1) Extract the <code>java.util.regex.Pattern#compile(java.lang.String)</code> into constants; so it will be loaded only once per <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/ClassLoader.html\" rel=\"nofollow noreferrer\">ClassLoader</a>, instead of each time you call the function.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static final Pattern TITLE = Pattern.compile(\"[\\\\S\\\\s]+\");\npublic static final Pattern AUTHOR = Pattern.compile(\", by(.*)(?=\\\\s*)\");\npublic static final Pattern SUBTITLE = Pattern.compile(\"\\\\[Subtitle: [^\\\\[\\\\]]+]\");\npublic static final Pattern LANGUAGE = Pattern.compile(\"\\\\[Language: [^\\\\[\\\\]]+]\");\npublic static final Pattern CONTENTS = Pattern.compile(\"\\\\[Contents: [^\\\\[\\\\]]+]\");\npublic static final Pattern TEMPX = Pattern.compile(\"\\\\d{1,5}$\");\npublic static final Pattern TEMPY = Pattern.compile(\"^\\\\d{1,5}|\\\\d{1,5}[A-Z]?\\\\s?$\");\npublic static final Pattern I = Pattern.compile(\"^, by \");\npublic static final Pattern J = Pattern.compile(\"\\\\s+(?&lt;= )\\\\d+(\\\\w)?$|(?&lt;= )\\\\d+(\\\\w)?\\\\s+$|(?&lt;=\\\\D)\\\\d+(\\\\w)?$\");\npublic static final Pattern ID = Pattern.compile(\"[^\\\\s]\\\\d+\");\n</code></pre>\n\n<p>2) Instead of using a <code>for</code> with index, I suggest a <code>for-each</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (String para : paragraphs) {\n //[...]\n}\n</code></pre>\n\n<p>3) For the two sections that don't have an <code>else</code> (Title &amp; Author), I suggest that you extract them in methods.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void defineBooks(List&lt;String&gt; paragraphs) {\n //[...]\n if (mtitle.find()) {\n replaceTitle(para, book);\n }\n\n if (mauthor.find()) {\n replaceAuthor(mauthor, book);\n }\n //[...]\n}\n\nprivate static void replaceAuthor(Matcher mauthor, Book book) {\n String bauthor = I.matcher(mauthor.group()).replaceAll(\"\");\n book.setAuthor(J.matcher(bauthor).replaceAll(\"\"));\n}\n\nprivate static void replaceTitle(String para, Book book) {\n book.setTitle(para.replaceAll(\"\\\\[[^\\\\[]+(?:])\", \"\")\n .replaceAll(\"(Passed | by|, by).*+\", \"\")\n .replaceAll(\"\\\\s{2,}\\\\d{1,5}(\\\\s)?\", \"\")\n .replaceAll(\"\\n\", \" \")\n .replaceAll(\",$\", \"\")\n .replaceAll(\"\\\\s+\", \" \").trim());\n}\n</code></pre>\n\n<p>4) For the rest, you can make methods that return a <code>String</code> in all cases.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void defineBooks(List&lt;String&gt; paragraphs) {\n //[...]\n book.setSubtitle(parseSubTitle(msubtitle, book));\n book.setContents(parseContents(mcontents));\n book.setLanguage(parseLanguage(mlanguage));\n //[...]\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String parseLanguage(Matcher mlanguage) {\n if(mlanguage.find()) {\n return mlanguage.group()\n .replaceAll(\"\\\\[Language: \", \"\")\n .replaceAll(\"]\", \"\")\n .replaceAll(\"\\\\s{2,}\", \" \");\n } else {\n return \"English\";\n }\n}\n\nprivate static String parseContents(Matcher mcontents) {\n if(mcontents.find()) {\n return mcontents.group()\n .replaceAll(\"\\\\[Contents: \", \"\")\n .replaceAll(\"]\", \"\")\n .replaceAll(\"\\\\s{2,}\", \" \");\n } else {\n return \"\";\n }\n}\n\nprivate static String parseSubTitle(Matcher msubtitle, Book book) {\n if (msubtitle.find()) {\n return msubtitle.group()\n .replaceAll(\"\\\\[Subtitle: \", \"\")\n .replaceAll(\"]\", \"\")\n .replaceAll(\"\\\\s{2,}\", \" \");\n } else {\n return \"\";\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T21:48:23.227", "Id": "234886", "ParentId": "234873", "Score": "2" } }, { "body": "<p>To avoid having to compile the regular expressions again and again, you can create a little helper class:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Patterns {\n private final Map&lt;String, Matcher&gt; matchers = new HashMap&lt;&gt;();\n\n public Matcher compile(String pattern) {\n return matchers.computeIfAbsent(pattern, any -&gt; Pattern.compile(pattern).matcher(\"\"));\n }\n\n public String replaceAll(String s, String pattern, String replacement) {\n Matcher m = compile(pattern);\n m.reset(s);\n return m.replaceAll(replacement);\n }\n}\n</code></pre>\n\n<p>This class compiles the regular expressions once. It allows you to use them many times in a convenient way:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Patterns pats = new Patterns();\nString replaced = pats.replaceAll(\"text\", \"..\", \"two letters\");\n</code></pre>\n\n<p>If that's still not enough, you can use <code>replace</code> instead of <code>replaceAll</code>, which (despite its name) also replaces <em>all</em> occurrences, it just operates on simple strings and since Java 9 is implemented efficiently.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T08:14:40.063", "Id": "234893", "ParentId": "234873", "Score": "1" } }, { "body": "<p>I have changed my code to use substring and indexOf to extract the text from each string, which has resulted in a 30% performance increase. The memory usage is still on the high end but the method is on its own thread so there is no noticeable performance drop when the gc runs.</p>\n\n<p><strong>Before (With subtitle example)</strong></p>\n\n<pre><code>private static void defineBooks(List&lt;String&gt; paragraphs) {\n ...\nPattern subtitle = Pattern.compile(\"\\\\[Subtitle: [^\\\\[\\\\]]+]\");\n ...\nfor (int i1 = 0, paragraphsSize = paragraphs.size(); i1 &lt; paragraphsSize; i1++) {\n ...\n Matcher msubtitle = subtitle.matcher(para);\n //...\n\n Book book = new Book();\n\n ... \n //Old subtitle code\n\n if (msubtitle.find()) {\n book.setSubtitle(msubtitle.group()\n .replaceAll(\"\\\\[Subtitle: \", \"\")\n .replaceAll(\"]\", \"\")\n .replaceAll(\"\\\\s{2,}\", \" \"));\n } else {\n book.setSubtitle(\"\");\n }\n\n ...\n\n if (!Objects.equals(book.getId(), \"\")) {\n books.add(book);\n }\n}\n</code></pre>\n\n<p><strong>After (along with Doi9t's answer)</strong></p>\n\n<pre><code>private static void defineBooks(List&lt;String&gt; paragraphs) {\n for (String para : paragraphs) {\n ...\n Book book = new Book();\n ...\n String subtitle = fastSubtitle(para);\n book.setSubtitle(subtitle);\n ...\n if (!Objects.equals(book.getId(), \"\")) {\n books.add(book);\n }\n }\n}\n\n\nprivate static String fastSubtitle(String para) {\n if (para.contains(\"[Subtitle:\")) {\n try {\n return para.substring(para.indexOf(\"[Subtitle:\") + 10, para.indexOf(\"]\", para.indexOf(\"Subtitle:\")));\n } catch (StringIndexOutOfBoundsException ex) {\n try {\n return para.substring(para.indexOf(\"[Language:\") + 10, para.indexOf(\"[\") - 1);\n } catch (StringIndexOutOfBoundsException ey) {\n return para.substring(para.indexOf(\"[Language:\") + 10, para.length() - 1);\n }\n }\n }\n return \"\";\n}\n</code></pre>\n\n<p>I am aware that I could use an if statements in the subtitle method but this does the job.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T20:55:32.950", "Id": "235090", "ParentId": "234873", "Score": "1" } } ]
{ "AcceptedAnswerId": "235090", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:17:22.117", "Id": "234873", "Score": "3", "Tags": [ "java", "performance", "strings", "regex", "android" ], "Title": "Java regex and replaceAll to extract strings into objects" }
234873
<p>I'm creating a data set to be used for a machine learning application. To do this I use my webcam to record videos at 1 frame per minute and did this for a few days. </p> <p>I then created a program to extract these frames (in gray scale) to create my data set and let it run over the weekend.</p> <p>After I noticed that not all my videos were set to 1 frame per minute (I assume that some were set to 60 frames per second). My data set is now saturated with extremely similar images (I believe this will cause issues when trying to train my ML application) and because of this I have decided to try to filter out similar images.</p> <p>The small python script I've written to do this compare images and if they are "similar" then they are moved to a folder that I'll delete after. The amount of files that this script has to compare is very large and I'm afraid that it'll start slowing down to a crawl. </p> <p>Would you be able to help review my code and offer any suggestions to optimize the performance of it. Thanks in advance. </p> <p>I think the place that would benefit from the greatest improvement is how I choose to compare two images. To determine if an image is similar I add up the differences in pixels between this image and each "unique" image I've currently found. If this is value is less than a threshold I have set (15 million) than I label the image as similar and move it if not I add it to the "unique" list. </p> <pre><code>#import 3rd party Lib import time import numpy as np import cv2 import sys import traceback import os from os import listdir from os.path import isfile, join import pickle import hashlib import time def Compare(dirTarget, dirDest): compareFiles = [] sourceFileList = [f for f in listdir(dirTarget) if isfile(join(dirTarget, f))] print("Files Read from HD") i = 0 startT = time.time() while len(sourceFileList) &gt; 0: file = sourceFileList.pop() targetImage = cv2.imread(dirTarget + file,0) isSimilar = False for compareImage in compareFiles: deltaArr = np.absolute(np.subtract(targetImage, compareImage)) dist = round(sum(map(sum, deltaArr))/1000000,0) if dist &lt; 15: isSimilar = True continue if isSimilar: os.rename(dirTarget + file, dirDest + file) else: compareFiles.append(targetImage) if i == 100: i = 0 endT = time.time() difference = int(endT - startT) startT = endT print("Unsimilar: " + str(len(compareFiles)) + " Left: " + str(len(sourceFileList)) + " Time: " + str(difference)) else: i += 1 hashedUniqueList = list() dir1 = "Superevised Set\One\\" dir0 = "Superevised Set\Zero\\" destdir1 = "ToDel\One\\" destdir0 = "ToDel\Zero\\" dirTarget = dir1 dirDest = destdir1 </code></pre> <p>The reason I choose 15 million as my threshold is because I did a quick sampling of how similar an image was to a subset of images and I got the following distribution. This is roughly 0.6% of my data. Do you think this number should be higher or (I doubt) lower. </p> <pre><code>Delta Count 11 1 12 16 13 32 14 112 15 306 16 436 17 995 18 1756 19 980 20 1195 21 822 22 651 23 1067 24 1656 25 4561 26 4676 27 3105 28 4008 29 2125 30 3587 31 4694 32 3557 33 2136 34 1491 35 1969 36 794 37 949 38 286 39 801 40 569 41 425 42 471 43 225 44 241 45 59 46 367 47 190 48 146 49 459 50 220 51 84 52 734 53 1100 54 257 55 521 56 1071 57 296 58 928 59 1624 60 764 61 1001 62 1792 63 1884 64 1496 65 4074 66 6557 67 11 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T18:42:50.537", "Id": "459449", "Score": "2", "body": "If this is a real problem you have - Do the files still have the original created date? if so, you'll probably get more accurate and much faster results by sorting by date, then running through the list and deleting images that are within 60seconds of the previous one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T19:06:48.723", "Id": "459451", "Score": "0", "body": "The created dates are from when I extracted the frames. My application has multiple files with the same creation date but I named my files \"timestamp + incremental number\" where incremental number was used when multiple frames were able to be extracted during the same timestamp. The problem is that I don't know if the difference between neighboring files (files extracted one after the other) is 1/60 of a second or 60 seconds (or another value). Not all videos had the same frame rate so I can't just take groups of 60 files and delete 59 of them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T20:16:09.567", "Id": "459453", "Score": "0", "body": "Are you opposed to using common libraries that are **dedicated** to finding similar images? Something like [image-match](https://github.com/EdjoLabs/image-match)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T21:34:37.963", "Id": "459459", "Score": "0", "body": "No I am not. Other than image-match which would you recommend for performance? And thank you for the link." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:28:56.880", "Id": "459656", "Score": "0", "body": "@Mandelbrotter I don't have personal recommendations, mostly since I haven't used these tools personally. However, I would recommend going through a list of [search results](https://github.com/search?q=image+duplication)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:33:19.887", "Id": "234874", "Score": "1", "Tags": [ "python", "performance" ], "Title": "Sorting out similar images" }
234874
<p>Would like some feedback on a <em>code style</em> exercise motivated by this <a href="https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships" rel="nofollow noreferrer">PythagTriple algorihtm</a>. I started with the <a href="https://rosettacode.org/wiki/Pythagorean_triples#C" rel="nofollow noreferrer">Rosetta Code - "efficient C" solution</a> (not the naive one) and refactored it heavily into modern C++17. </p> <p>It doesn't quite match their "Task spec". That that was not the focus. However, it could very easily be adopted to do so - just a few changes in <code>main()</code>.Performance appears very similar to the <code>C</code> code I started with and the <a href="https://godbolt.org/z/qdi4_M" rel="nofollow noreferrer">generated ASM</a> seems reasonable. </p> <p>But the <em>main focus</em> here is style, ease of readability, maintenance and correctness. </p> <p>Specific feedback points I am looking for:</p> <ul> <li>Use of the lambda to process each triple</li> <li>Way of constraining the <code>template</code> to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)</li> <li>Use of initialisers for static data. Also is there a way to get away from the <code>{{ .. {{ .. {},{},{} .. }} .. }}</code> craziness? 4 extra opening and closing braces. </li> <li>Use of specific type for <code>vec3</code> and a <code>using</code> alias for <code>trans</code></li> <li>Body of the <code>transform()</code> function. Is there a <code>map() ... splat</code> way? </li> <li>General function signatures / use of <code>const</code>, <code>constexpr</code>, attributes etc</li> <li>Use of "by value" vs "by ref" semantics for triples / tranforms etc. There are some "arguably redundant" <code>const T&amp;</code>s in there which were just as fast as "by value" (probably copy elided). </li> <li>More algorithmic question: The algorithm as implemented is constrained by <code>max_perimeter</code> and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) "weird order". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative <code>.find_XX()</code> methods to do that. </li> </ul> <p><strong>EDIT</strong>: There is updated code <a href="https://codereview.stackexchange.com/a/234905/212940">in a separate answer below</a>, integrating the feedback. </p> <pre><code>#include &lt;array&gt; #include &lt;iostream&gt; namespace pythag { class triple { public: const long _a; const long _b; const long _c; template &lt;typename F&gt; constexpr void find(long max_perim, F&amp;&amp; proc) { if (perimeter() &gt; max_perim) return; proc(*this); for (auto&amp; T : U) transform(T).find(max_perim, proc); } [[nodiscard]] constexpr long perimeter() const noexcept { return _a + _b + _c; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const triple t) noexcept { return stream &lt;&lt; t._a &lt;&lt; ", " &lt;&lt; t._b &lt;&lt; ", " &lt;&lt; t._c; } private: struct vec3 { // a strong type to distinguish from triple const int _x; const int _y; const int _z; }; using trans = std::array&lt;vec3, 3&gt;; [[nodiscard]] constexpr long dot(vec3 V) const noexcept { return V._x * _a + V._y * _b + V._z * _c; } [[nodiscard]] constexpr triple transform(const trans&amp; T) const noexcept { return triple{dot(T[0]), dot(T[1]), dot(T[2])}; } static constexpr auto U = std::array&lt;trans, 3&gt;{{ // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships // clang-format off {{{ 1, -2, 2}, // vec3 U[0][0] { 2, -1, 2}, // vec3 U[0][1] { 2, -2, 3}}}, // vec3 U[0][1] {{{ 1, 2, 2}, // vec3 U[1][0] { 2, 1, 2}, // vec3 U[1][1] { 2, 2, 3}}}, // vec3 U[1][2] {{{ -1, 2, 2}, // vec3 U[2][0] { -2, 1, 2}, // vec3 U[2][1] { -2, 2, 3}}}, // vec3 U[2][2] // clang-format on }}; }; } // namespace pythag int main() { // basic usage demo long sum_peri = 0; long count = 0; pythag::triple{3, 4, 5}.find( 100'000'000, // produces 7'023'027 "primitive" triples in &lt;100ms on i7 2600 // [](const auto&amp; t) { std::cout &lt;&lt; t &lt;&lt; "\n"; }); // print option. slow obviously [&amp;sum_peri, &amp;count](const auto&amp; t) { sum_peri += t.perimeter(); ++count; }); std::cout &lt;&lt; count &lt;&lt; "\n"; // these 2 lines are just a way to prevent return (sum_peri ^ count) &amp; 0xff; // entire programme being optimised away } </code></pre>
[]
[ { "body": "<blockquote>\n <p>Use of the lambda to process each triple</p>\n</blockquote>\n\n<p>Sure, why not. Nothing wrong with using a lambda in <code>main()</code> here instead of writing a normal function.</p>\n\n<blockquote>\n <p>Way of constraining the template to prevent unsuitable lambda's being passed. (C++20 concepts needed to do it cleanly?)</p>\n</blockquote>\n\n<p>If you could live with <code>pythag::triple::find()</code> not being <code>constexpr</code>, then you don't need C++20 for this at all. Just use <code>std::function&lt;&gt;</code> for the type of <code>proc</code>:</p>\n\n<pre><code>#include &lt;functional&gt;\n...\nvoid find(long max_perim, std::function&lt;void(triple &amp;)&gt; proc) {\n ...\n}\n</code></pre>\n\n<blockquote>\n <p>Use of initialisers for static data. Also is there a way to get away from the {{ .. {{ .. {},{},{} .. }} .. }} craziness? 4 extra opening and closing braces.</p>\n</blockquote>\n\n<p>Yes, by not using <code>std::array&lt;&gt;</code>, but just declaring a multidimensional, \"C-style\" array:</p>\n\n<pre><code> static constexpr vec3 U[3][3] {\n {{ 1, -2, 2}, // vec3 U[0][0]\n { 2, -1, 2}, // vec3 U[0][1]\n { 2, -2, 3}}, // vec3 U[0][1]\n\n {{ 1, 2, 2}, // vec3 U[1][0]\n { 2, 1, 2}, // vec3 U[1][1]\n { 2, 2, 3}}, // vec3 U[1][2]\n\n {{ -1, 2, 2}, // vec3 U[2][0]\n { -2, 1, 2}, // vec3 U[2][1]\n { -2, 2, 3}}, // vec3 U[2][2]\n };\n</code></pre>\n\n<p>You need to change <code>transform()</code> as well:</p>\n\n<pre><code> [[nodiscard]] constexpr triple transform(const vec3 T[3]) const noexcept {\n return triple{dot(T[0]), dot(T[1]), dot(T[2])};\n }\n</code></pre>\n\n<blockquote>\n <p>Use of specific type for vec3 and a using alias for trans</p>\n</blockquote>\n\n<p>I think you could've made <code>vec3</code> an array as well, either <code>std::array&lt;&gt;</code> (at the cost of even more braces) or just <code>int[3]</code>. Since you use <code>trans</code> in multiple places, it's good to have made an alias for it. But what's weird is that you write:</p>\n\n<pre><code>static constexpr auto U = std::array&lt;trans, 3&gt;{...};\n</code></pre>\n\n<p>The <code>auto</code> is totally unnecessary here, you could've written it simply as:</p>\n\n<pre><code>static constexpr std::array&lt;trans, 3&gt; U{...};\n</code></pre>\n\n<blockquote>\n <p>Body of the transform() function. Is there a map() ... splat way?</p>\n</blockquote>\n\n<p>There's <a href=\"https://en.cppreference.com/w/cpp/algorithm/inner_product\" rel=\"nofollow noreferrer\"><code>std::inner_product</code></a> which could replace <code>dot()</code>, and <a href=\"https://en.cppreference.com/w/cpp/algorithm/transform\" rel=\"nofollow noreferrer\"><code>std::transform()</code></a> could have replaced the body of <code>transform()</code>, if your triples and vectors were arrays. It would have looked like:</p>\n\n<pre><code>triple transform(const trans&amp; T) const {\n triple result;\n return std::transform(T.begin(), T.end(), result.values.begin(),\n [this](vec3 V){\n return std::inner_product(V.begin(), V.end(), this-&gt;values.begin(), 0);}\n }\n );\n}\n</code></pre>\n\n<p>Instead of <code>const long _a, _b, _c</code> you'd have to have something like <code>std::array&lt;long, 3&gt; values</code> to make it work.</p>\n\n<blockquote>\n <p>General function signatures / use of const, constexpr, attributes etc</p>\n</blockquote>\n\n<p>Does it really need to be <code>constexpr</code>? It is restricting you (you can't use <code>std::function&lt;&gt;</code> for <code>find()</code> for example), and I don't see any reason why you would ever need to know the number of Pythogorean triples up to some value at compile-time.</p>\n\n<p>Of course, marking things <code>const</code>, <code>constexpr</code>, <code>[[nodiscard]]</code> and so on where possible is a good thing. Keep doing that.</p>\n\n<p>I would however change the type of the components of <code>vec3</code> to <code>long</code>, to match that of the triple itself. You could even think of making an alias for the value type, or make the whole class templated, so you can decide which value type to use.</p>\n\n<blockquote>\n <p>Use of \"by value\" vs \"by ref\" semantics for triples / tranforms etc. There are some \"arguably redundant\" const T&amp;s in there which were just as fast as \"by value\" (probably copy elided).</p>\n</blockquote>\n\n<p>With optimization enabled, any decent compiler will probably generate the same assembly code here, regardless of whether you pass by value or by const reference.\nYou even missed the possibility to make <code>operator&lt;&lt;()</code> take a const reference.</p>\n\n<blockquote>\n <p>More algorithmic question: The algorithm as implemented is constrained by max_perimeter and due to recursive DFS flow and the matrix transforms the triples come out in a (subjectively) \"weird order\". Several other constraints and orderings are conceivably possible. One idea is to implement several alternative .find_XX() methods to do that.</p>\n</blockquote>\n\n<p>What algorithm is best depends on the application. Your recursive DFS algorithm is probably the most elegant one to implement, but apart from the weird output order, the main issue is that you can run out of stack space if the recursion goes too deep. So try to implement another algorithm that doesn't require recursive function calls.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:01:15.740", "Id": "459467", "Score": "0", "body": "Thanks for your comments. Yes. std::array<>. I can never decide, when I want a \"small, non-dynamically allocated\" set of pretty trivial types which container to use. `std::vector` is overkill. C-style arrays feel \"dirty\" (eventhough that's my history). So I end up with std::array.... well.. at least it remembers the size, and that was useful at least once here. \n\nSo yes, changing (back) to C-style [] arrays, opens up a couple of options. \n\nOther tradeoff which you are touching on is \"strong types\" vs \"primitives\" ie `struct { long,long,long}`. vs std::array. There are costs to both. \ntbc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:04:54.557", "Id": "459468", "Score": "0", "body": "Re: don't need `auto`.\n\nI was trying to stick to Herb Sutter's \"auto to stick\" style here.\n\nI am still trying to decide whether I like it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:07:28.310", "Id": "459469", "Score": "0", "body": "Re: \"does it need to be constexpr\"? No, ;-) it doesn't. But at least I am getting to the point where I am \"overremembering\" to put it in. ;-) And you are right, it resticts things slightly. I did almosty get it to the point of calling from main with constexpr, it can almost do it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:12:05.657", "Id": "459470", "Score": "1", "body": "Re: `std::function`. I have previously benchmarked this, and it really is seriously slow. So I tend to stay away from it almost as a matter of policy. \n\nAnd that lamda is in the inner loop..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:17:49.560", "Id": "459471", "Score": "0", "body": "Re: operator<< and `const triple&` That's a good spot. My analyser didn't help me spot this omission, probably because it is a `friend`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:22:39.180", "Id": "459472", "Score": "0", "body": "What did you mean with this: \"You need to change transform() as well:\"? The brace syntax? Or how it would change if I changed to C-style arrays?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:29:16.457", "Id": "459473", "Score": "0", "body": "Re the algorithm: Running out of stack space is unlikely I think. 3^30 is a BIG number and I think we are putting < 50bytes on the stack for each level. 8MB stack on linux..(1MB on windows) .. should be here for a while, given it's a cubic algorithm.\n\nI wrote an iterative BFS version. It spits them out in a different order. I cannot decide if that order is better. ;-) The \"naive algorithms\" (triple nested for-loop style) tend to do better here. Not sure how to get best of both worlds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:40:17.847", "Id": "459474", "Score": "0", "body": "On choice of `int` for `vec3` vs `long` for `triple`. That was a conscious decision. vec3 is a tranformation vector, right now, it is totally static, and will probably never change, it's a different \"kind of\" 3 value vector too, -- hence separate type. I thought about templating the whole class. Then I ran it both ways on 100'000'000 and there was zero measurable time difference. So I figured that these triples \"can and do get big\", so I will use long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:44:06.520", "Id": "459475", "Score": "0", "body": "reflecting on c-style arrays, actually the only thing that would buy us is less braces right? What would buy us more than that (eg use of inner_product/transform std::STL for the matrix multiply, which is arguably desirable)..is to use std::array<long|int, 3> as \"inner members\" for vec3 and triple. That's what you mean right? a std::array<> inside triple and one inside vec3? Still gives separate types. Best of both worlds? Slightly awkward accessor syntax?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T09:41:01.487", "Id": "459479", "Score": "0", "body": "If you want a better accessor syntax, you could create your own `template<typename T> class vec3` that has `x`, `y` and `z` members but also provides iterators so it can be used by STL algorithms. Then you can use it both for the triple and the transformation constants. Or use an existing library like https://glm.g-truc.net/ which provides vectors. It even allows you to write: `static constexpr glm::tvec3<glm::tvec3<glm::ivec3>> U{{{1, -2, 2}, {2, -1, 2}, {2, -2, 3}}, ...}`. However, GLM doesn't provide iterators, but you could add them yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:04:58.690", "Id": "459496", "Score": "0", "body": "I am playing with some ideas around the \"strong types\" vs \"c_arrays\" vs \"std::array\" and I think I have come up with a good middle ground. Shall I post that as an \"answer\" showing a possible way to solve that part and incorporating some of the other suggestions you made?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T15:19:23.533", "Id": "459519", "Score": "0", "body": "I have accepted your answer, integrated some of your suggestions in an updated answer below : https://codereview.stackexchange.com/a/234905/212940 and added a few wrinkles." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T00:50:22.720", "Id": "234888", "ParentId": "234875", "Score": "2" } }, { "body": "<p>An answer to document how to integrate some of the excellent feedback points from @G. Sliepen in <a href=\"https://codereview.stackexchange.com/a/234888/212940\">his accepted answer</a> above. </p>\n\n<p>The following have been changed from the original question above:</p>\n\n<ul>\n<li>Remove <code>constexpr</code> since it is not required and opens up options for using the STL algorithms (except for the static <code>U</code>, where constexpr allows <code>inline</code> definition of this constant) </li>\n<li>Use <code>std::array&lt;long|int, 3&gt;</code> to store both the <code>triple</code> and the <code>vec3</code> transform data. This allows more algorithmic use than <code>._a, ._b, ._c</code> and <code>._x, ._y, ._z</code>. (But see below for how I retained simple accessor syntax)</li>\n<li>Use <code>std::inner_product</code> and <code>std::transform</code> to do the matrix multiplication. <code>std::accumulate</code> for the perimeter. </li>\n<li>Addition of a \"Breadth first search\" (BFS) finder.</li>\n</ul>\n\n<p>Things I decided not to adopt:</p>\n\n<ul>\n<li><code>std::function</code>, which is known to be very slow, was deemed inappropriate for inner loop lambda. So the constraining of the lambda type remains a TODO. </li>\n<li>C-Arrays: Lose their size when you pass them around (since Kernighan and Ritchie) and decay to a pointer. So <code>std::array&lt;&gt;</code> adds value as we can easily use it in algorithms, because it knows its size and you can call <code>std::begin()</code> etc. We learn to live with the \"many braces\". </li>\n</ul>\n\n<p>The one extra wrinkle was to make <code>triple</code> <em>inherit from</em> <code>std::array&lt;long, 3&gt;</code> and <code>vec3</code> <em>inherit from</em> <code>std::array&lt;int, 3&gt;</code>. Then similarly for <code>trans</code>. This allows strong typing (ie not just a <code>using alias</code> which just decays away) but retains the easy and direct access via <code>operator[]</code> and usage in algorithms or <code>ranged for loops</code> without writing a single line of code. There is no <code>vtable</code> or similar overhead, because this is not <code>virtual</code>, <code>polymorphic</code> inheritance. </p>\n\n<p>Performance is identical to the original above. Code size looks bigger (<a href=\"https://godbolt.org/z/jYwDpn\" rel=\"nofollow noreferrer\">goldbolt link</a>), but that is all due to the new BFS algo which uses <code>std::queue</code>, heap allocators etc. If we remove that for a fairer comparison the code size is identical to above, and speed on <code>-O3</code> is identical. ie STL <code>std::inner_product</code> and <code>std::transform</code> and <code>std::accumulate</code> are truly \"zero cost\" here, and arguably \"negative cost\" given the improved readability and more general algorithm. </p>\n\n<p>An unrelated annoyance is the boilerplate in <code>operator&lt;&lt;</code>. Still haven't found a terse way of expressing that. </p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;array&gt;\n#include &lt;cstdio&gt;\n#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;numeric&gt;\n#include &lt;queue&gt;\n\nnamespace pythag {\n\nclass triple : public std::array&lt;long, 3&gt; {\npublic:\n template &lt;typename F&gt;\n void find(long max_perim, F&amp;&amp; proc) {\n // recursive DFS\n if (perimeter() &gt; max_perim) return;\n proc(*this);\n for (auto&amp; T: U) transform(T).find(max_perim, proc);\n }\n\n template &lt;typename F&gt;\n void find_by_level(int max_depth, F&amp;&amp; proc) {\n // iterative BFS with level tracking / limiting\n std::queue&lt;triple&gt; q;\n q.push(*this);\n int depth = 0;\n int cnt_this_depth = 1;\n int cnt_next_depth = 0;\n while (!q.empty()) {\n auto t = q.front();\n q.pop();\n proc(t);\n cnt_next_depth += U.size(); // always 3\n if (--cnt_this_depth == 0) {\n if (++depth &gt; max_depth) return;\n cnt_this_depth = cnt_next_depth;\n cnt_next_depth = 0;\n }\n for (auto&amp; T: U) q.push(t.transform(T));\n }\n }\n\n [[nodiscard]] long perimeter() const noexcept {\n return std::accumulate(this-&gt;begin(), this-&gt;end(), 0L);\n }\n\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const triple&amp; t) noexcept {\n // Frustrating boiler plate. Any terse alternatives, that do it quickly and correctly?\n char comma[] = {'\\0', ' ', '\\0'}; // NOLINT\n for (auto d: t) {\n stream &lt;&lt; comma &lt;&lt; d;\n comma[0] = ',';\n }\n return stream;\n }\n\nprivate:\n struct vec3 : public std::array&lt;int, 3&gt; {}; // strong types by inheritance\n struct trans : public std::array&lt;vec3, 3&gt; {}; // to distinguish from triple\n\n [[nodiscard]] triple transform(const trans&amp; T) const noexcept {\n auto res = triple{};\n std::transform(T.begin(), T.end(), res.begin(), [this](vec3 V) {\n return std::inner_product(V.begin(), V.end(), this-&gt;begin(), 0L);\n });\n return res;\n }\n\n static constexpr auto U = std::array&lt;trans, 3&gt;{{\n // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships\n {{{{{1, -2, 2}}, // vec3 U[0][0]\n {{2, -1, 2}}, // vec3 U[0][1]\n {{2, -2, 3}}}}}, // vec3 U[0][1]\n\n {{{{{1, 2, 2}}, // vec3 U[1][0]\n {{2, 1, 2}}, // vec3 U[1][1]\n {{2, 2, 3}}}}}, // vec3 U[1][2]\n\n {{{{{-1, 2, 2}}, // vec3 U[2][0]\n {{-2, 1, 2}}, // vec3 U[2][1]\n {{-2, 2, 3}}}}}, // vec3 U[2][2]\n }};\n};\n\n} // namespace pythag\n\nint main() {\n using pythag::triple;\n\n // basic usage demo\n auto print = [](const triple&amp; t) { std::cout &lt;&lt; t &lt;&lt; \"\\n\"; };\n std::cout &lt;&lt; \"Primitive triples up to a perimeter of 200\\n\";\n triple{{3, 4, 5}}.find(200, print);\n std::cout &lt;&lt; \"\\nPrimitive triples up to 2 levels of transformation away from {3,4,5}\\n\";\n triple{{3, 4, 5}}.find_by_level(2, print);\n\n // // performance test\n // long sum_peri = 0;\n // long count = 0;\n // pythag::triple{{3, 4, 5}}.find(\n // 100'000'000, // produces 7'023'027 triples in &lt;100ms on i7 2600\n // [&amp;sum_peri, &amp;count](const auto&amp; t) {\n // sum_peri += t.perimeter();\n // ++count;\n // });\n\n // // prevent entire programme being optimised away without &lt;iostream&gt;\n // return (sum_peri ^ count) &amp; 0xff;\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:01:22.767", "Id": "459526", "Score": "0", "body": "Turning `operator<<` into a one-liner: `return stream << std::accumulate(t.begin(), t.end(), std::string{}, [](const std::string &a, long b){return (a.empty() ? a : a + \", \") + std::to_string(b);});`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:14:23.873", "Id": "459529", "Score": "0", "body": "Yeah. The advantage of the `char[]` trick (which came from a cppreference example) is that it is branchless. The entire problem of `join`, as I would call it, is not that trivial and I would have hoped had been solved in the STL. the `std::accumulate` way also results in a ton of sting concatenations (with potential allocations) and then piping out. Anyway, probably a topic for another post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T17:20:01.543", "Id": "459531", "Score": "0", "body": "@G.Sliepen\n\nthis would be good: `return os::str::join(stream, t);` except it should say `std::join` instead of `os::str::join`. Internally that calls begin / end and uses them to feed the stream, inserting a \"glue\" and \"term\" which can be passed as optional params. There are 4 different overloads of it. \n\nI have a 300 line header file full of these little 1-10 line functions. 80% of them are string related. Am I missing a trick / lib or does everyone have one of those?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T15:17:26.020", "Id": "234905", "ParentId": "234875", "Score": "2" } }, { "body": "<p>Here are some comments on <a href=\"https://codereview.stackexchange.com/a/234905/16369\">your revised code</a>, many of which apply to your original code as well.</p>\n\n<pre><code>for (auto&amp; T: U) transform(T).find(max_perim, proc);\n</code></pre>\n\n<p>You're using the names <code>T</code> and <code>U</code> to refer to things that are <em>not</em> template type parameters. In fact, <code>U</code> is a reference to a static data member of the enclosing class, whose only declaration appears many lines below this use. This is extremely surprising code. I might instead write</p>\n\n<pre><code>for (auto&amp;&amp; formula : this-&gt;child_formulas) {\n this-&gt;transform(formula).find(max_perim, proc);\n}\n</code></pre>\n\n<p>Notice the use of braces around the loop body; the use of <a href=\"https://quuxplusone.github.io/blog/2018/12/27/autorefref-still-always-works/\" rel=\"nofollow noreferrer\"><code>auto&amp;&amp;</code>, Which Always Works</a>; the use of <code>this-&gt;</code> to clarify for the human reader what scope we're expecting to find these names in; and especially the descriptive name <code>child_formulas</code> for <code>U</code>. (<code>child_formulas</code> says <em>what</em> <code>U</code> is; <code>this-&gt;</code> says <em>whose</em> it is. Both of those things were in question, in the old code.)</p>\n\n<hr>\n\n<pre><code>class triple : public std::array&lt;long, 3&gt; {\n</code></pre>\n\n<p><a href=\"https://quuxplusone.github.io/blog/2018/12/11/dont-inherit-from-std-types/\" rel=\"nofollow noreferrer\">Don't inherit from standard types.</a> It's legal C++, but it's bad practice.</p>\n\n<blockquote>\n <p>If you (or your project, or your company) didn’t write class <code>Foo</code>, then class <code>Foo</code> should not be granted control over the API of your own class. And that’s what you’re doing when you inherit from a base class: you’re granting that class control over your API.</p>\n</blockquote>\n\n<p>I like your original <code>x, y, z</code> data members much better.</p>\n\n<hr>\n\n<pre><code>template &lt;typename F&gt;\nvoid find(long max_perim, F&amp;&amp; proc) {\n</code></pre>\n\n<p>You're passing <code>proc</code> by perfect-forwarding, but then when you use it, you're using it as a plain old lvalue. This is fine (in the wild-west anything-goes world of templates), but it doesn't express the meaning of <code>proc</code> quite as well as I'd like. <code>proc</code> is supposed to be a callback that gets called for each triple, right? Calling a callback doesn't modify the callback. So, we can and should require that <code>proc</code> be const-callable, and then we just write</p>\n\n<pre><code>template&lt;class F&gt;\nvoid find(int max_perim, const F&amp; proc) {\n</code></pre>\n\n<p>(Drive-by irrelevant style adjustments to save typing. <code>long</code> varies in size and is the same size as <code>int</code> on many platforms, so let's just use <code>int</code> until we're ready to step all the way up to a well-defined <code>int64_t</code> or <code>__int128_t</code>.)</p>\n\n<p>If you really want to support non-const and/or rvalue-callable <code>F</code>s, you <em>can</em> perfect-forward <code>proc</code> all over the place, but trust me, it's not worth it. (The <code>std::forward&lt;F&gt;(proc)</code>s will clutter your code, and all you're doing is enabling your users to write confusing and unintuitive client code.)</p>\n\n<p>Vice versa, re your question about concepts: You <em>can</em> constrain this template to SFINAE away in C++17 (or C++11) like this:</p>\n\n<pre><code>template&lt;class F, class = std::enable_if_t&lt;std::is_invocable_v&lt;const F&amp;, triple&amp;&gt;&gt;&gt;\nvoid find(int max_perim, const F&amp; proc) {\n</code></pre>\n\n<p>This is not <em>much</em> more boilerplate than the C++2a concepts version:</p>\n\n<pre><code>template&lt;class F&gt; requires std::is_invocable&lt;const F&amp;, triple&amp;&gt;\nvoid find(int max_perim, const F&amp; proc) {\n</code></pre>\n\n<p>Notice that in C++2a you will also be able to write \"simply\"</p>\n\n<pre><code>void find(int max_perim, const std::invocable&lt;triple&amp;&gt; auto&amp; proc) {\n</code></pre>\n\n<p>but (A) this doesn't express exactly the same SFINAE-constraint as the other two, and (B) IMHO it looks more confusing and scary.</p>\n\n<p>But <strong><em>should</em></strong> you constrain this function to SFINAE away when it's given a \"bad\" lambda type? IMHO, no, you shouldn't. There's no reason to SFINAE here. SFINAE is for when you need this version of <code>find</code> to drop out of the overload set so that some other more general version can pick up the call. That's not the situation that you have, here.</p>\n\n<p>Compare the error messages you get from <a href=\"https://godbolt.org/z/6PcAXX\" rel=\"nofollow noreferrer\">(A)</a> (or the C++2a Concepts version <a href=\"https://godbolt.org/z/2iAuyM\" rel=\"nofollow noreferrer\">(A2)</a>)</p>\n\n<pre><code>template&lt;class F, class = std::enable_if_t&lt;std::is_invocable_v&lt;const F&amp;, triple&amp;&gt;&gt;&gt;\nvoid find(int max_perim, const F&amp; proc) {\n proc(*this);\n}\n\nthis-&gt;find(42, 7);\n</code></pre>\n\n<p>versus <a href=\"https://godbolt.org/z/ApubPE\" rel=\"nofollow noreferrer\">(B)</a></p>\n\n<pre><code>template&lt;class F&gt;\nvoid find(int max_perim, const F&amp; proc) {\n static_assert(std::is_invocable_v&lt;const F&amp;, triple&amp;&gt;);\n proc(*this);\n}\n\nthis-&gt;find(42, 7);\n</code></pre>\n\n<p>versus <a href=\"https://godbolt.org/z/uCAAT3\" rel=\"nofollow noreferrer\">(C)</a></p>\n\n<pre><code>template&lt;class F&gt;\nvoid find(int max_perim, const F&amp; proc) {\n proc(*this);\n}\n\nthis-&gt;find(42, 7);\n</code></pre>\n\n<p>and see which version feels most \"user-friendly\" for the client programmer. (Remember that someone using <code>find</code> <em>correctly</em> will never see any of these error messages, so you should optimize to help the guy who doesn't know how to use it.)</p>\n\n<hr>\n\n<pre><code> cnt_next_depth += U.size(); // always 3\n if (--cnt_this_depth == 0) {\n if (++depth &gt; max_depth) return;\n cnt_this_depth = cnt_next_depth;\n cnt_next_depth = 0;\n }\n for (auto&amp; T: U) q.push(t.transform(T));\n</code></pre>\n\n<p>Code comments are usually a red flag, at least on CodeReview. ;) It seems that this <code>+=</code> corresponds to the three calls to <code>q.push</code> below; i.e., your algorithm requires that <code>cnt_next_depth</code> exactly track <code>q.size()</code>. But you can't use <code>q.size()</code> because you are reusing <code>q</code> to store <em>both</em> the elements at the current level <em>and</em> the elements at the next level.</p>\n\n<p>It would make more sense to use two different queues:</p>\n\n<pre><code>std::vector&lt;triple&gt; this_level = ...;\nstd::vector&lt;triple&gt; next_level;\nfor (int i=0; i &lt; max_depth; ++i) {\n for (auto&amp;&amp; t : this_level) {\n proc(t);\n for (auto&amp;&amp; formula : child_formulas) {\n next_level.push_back(t.transform(formula));\n }\n }\n this_level = std::move(next_level);\n next_level.clear();\n}\n</code></pre>\n\n<p>As a bonus, it turns out that we don't even need them to be queues anymore; they can be plain old vectors, and we save a bunch of heap traffic.</p>\n\n<hr>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const triple&amp; t) noexcept {\n // Frustrating boiler plate. Any terse alternatives, that do it quickly and correctly?\n char comma[] = {'\\0', ' ', '\\0'}; // NOLINT\n for (auto d: t) {\n stream &lt;&lt; comma &lt;&lt; d;\n comma[0] = ',';\n }\n return stream;\n}\n</code></pre>\n\n<p>No good answer. The idiomatic way would be</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const triple&amp; t) {\n bool first = true;\n for (auto&amp;&amp; d : t) {\n if (!first) stream &lt;&lt; \", \";\n stream &lt;&lt; d;\n first = false;\n }\n return stream;\n}\n</code></pre>\n\n<p>Notice that this function is <em>not</em> <code>noexcept</code>, because any of these stream operations might throw. (For example, if you're writing to a <code>stringstream</code> and it throws <code>bad_alloc</code>.)</p>\n\n<p>Also, in real life I'd write <code>for (int d : t)</code> to indicate exactly what type of \"elements\" I expect to be getting out of a <code>triple</code>. I'm using <code>auto&amp;&amp;</code> here only because I saw your comment that you want to stick with \"Almost Always Auto\" style.</p>\n\n<hr>\n\n<pre><code> triple transform(const trans&amp; T) const noexcept {\n auto res = triple{};\n std::transform(T.begin(), T.end(), res.begin(), [this](vec3 V) {\n return std::inner_product(V.begin(), V.end(), this-&gt;begin(), 0L);\n });\n return res;\n }\n</code></pre>\n\n<p>This is interesting use of STL algorithms, but algorithms are really meant for operating on big anonymous ranges of <em>data elements</em>, not for constant-size situations like we have here. In order to use STL algorithms, you've been forced to anonymize your formulas into faceless data ranges:</p>\n\n<pre><code> static constexpr auto U = std::array&lt;trans, 3&gt;{{\n // https://en.wikipedia.org/wiki/Pythagorean_triple#Parent.2Fchild_relationships\n {{{{{1, -2, 2}}, // vec3 U[0][0]\n {{2, -1, 2}}, // vec3 U[0][1]\n {{2, -2, 3}}}}}, // vec3 U[0][1]\n\n {{{{{1, 2, 2}}, // vec3 U[1][0]\n {{2, 1, 2}}, // vec3 U[1][1]\n {{2, 2, 3}}}}}, // vec3 U[1][2]\n\n {{{{{-1, 2, 2}}, // vec3 U[2][0]\n {{-2, 1, 2}}, // vec3 U[2][1]\n {{-2, 2, 3}}}}}, // vec3 U[2][2]\n }};\n</code></pre>\n\n<p>Compare that code to a more \"code-driven\" version:</p>\n\n<pre><code>triple transform(const Formula&amp; f) const noexcept {\n return f(x, y, z);\n}\n\nauto formulas[] = {\n +[](int x, int y, int z){ return triple{ x - 2*y + 2*z, 2*x - y + 2*z, 2*x - 2*y + 3*z}; },\n +[](int x, int y, int z){ return triple{ x + 2*y + 2*z, 2*x + y + 2*z, 2*x + 2*y + 3*z}; },\n +[](int x, int y, int z){ return triple{ -x + 2*y + 2*z, -2*x + y + 2*z, -2*x + 2*y + 3*z}; },\n};\n</code></pre>\n\n<p>In this version, <code>trans</code> is gone already, and <code>t.transform(f)</code> is hardly pulling its weight.</p>\n\n<hr>\n\n<pre><code>if (perimeter() &gt; max_perim) return;\n</code></pre>\n\n<p>Consider what you'd do if you wanted to find all triples up to some maximum side length, or up to some maximum hypotenuse length. Does this approach generalize to</p>\n\n<pre><code>triple.find(callback_on_each_triple, stopping_condition);\n</code></pre>\n\n<p>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:09:58.363", "Id": "459562", "Score": "0", "body": "Thanks! Some really useful stuff there. Especially on the constraining of the lambda template. I admit I was spraying around the `&&` because I know that \"works\", but was looking for input exactly in this area. \n\nI choose `T & U` because these are `Matrixes` and it is common in linear algebra to denote matrices with capitals. But I agree there is some \"domain overlap\" ther with template params. \n\nNot sure I agree with the \"formula approach\". Frankly `3x3 Matrix multiplication`, which is all this is, should be a bulk standard operation (without using `Eigen` et al)... TBC" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:21:12.147", "Id": "459564", "Score": "0", "body": "Your point on inheritance is well made. However I sort of feel a bit stuck with no where to go. a) use plain `std::array<> for everything` plus free functions perhaps some `using aliases`. Perhaps the best for what is will remain a minimalist academic article. b) My \"cheaty middle way\" where I get some typing by inheritance and the API I need. But tightly bound to STL type and intheriting stuff I don't need. c) The third way is fully stand alone types with their own iterators etc (unless we go back ot doing matrix multiply with `a,b,c * ,x,y,z` which works fine for the minimal example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:24:00.487", "Id": "459566", "Score": "0", "body": "I feel the `a,b,c` with a page of manually typed formulae (BTW very very similar to the original `C` code from Rosetta code) is missing the point that these are matrices and the operations are standardised. At the end of the day, it's an architecture question which will depend on the real life use case. And this will never have one. So it's just speculative opinion really? That's perhaps why 2 people have recommended going opposite ways on it already?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:25:47.003", "Id": "459567", "Score": "0", "body": "I think \"faceless data ranges\" perhaps illustrates that you didn't see these as, or didn't realise they were matrices and standard linear algebra matrix operations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:28:19.927", "Id": "459568", "Score": "0", "body": "On the BFS level limit algo. Sure. \"Not my code\". I already didnt't like it when I copy pasted that very piece ;-) In fact I think it's lame that we need a heap allocating queue or vector at all to implement this algo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:34:23.803", "Id": "459570", "Score": "0", "body": "I think the \"pure style\" comments on \"always use braces for one line loops or ifs\" or always use \"this->\" or \"use auto, don't use auto\".... are....well they are opinion aren't they. There are an equally large number of experienced C++ people out there who will say the opposite. I have 30yrs experience with other languages and 3months with C++. So I am trying to find \"my own style\" in a forest of opinion. If working for a company this is not an issue, there is a policy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:51:35.920", "Id": "459572", "Score": "0", "body": "Overall, thank you so much for the considerable time you have invested. Particularly the insight into when/how to use SFINAE or concepts or why perhaps we don't need to is invaluable to me as this is the part that is least clear to me and comes up all the time. For passing lambda's specifically and also more generally. \n\nIf you have a link to further <F> ... f(... F& func) discussion that would be great. I will dig out Nicolai's template book, he probably covers this. Just need more coffee for that ;-)\n\nThanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T23:03:13.623", "Id": "459573", "Score": "0", "body": "Last thought on the inheritance question (I wasn't very clear on c) above). You are right. If you were building a larger or commercial application, then yes.. Fully featured Standalone types, no inheritance from STL. But because I view this as mathematical problem with matrix algebra solution those types would need to contain std::arrays<> (not a,b,c) (by composition not inheritance), which would mean unnatural indirect accessors or implementing iterators. Just the iterators would be as long as that whole class. Hence overenginered for this this pico-project. Or just use Eigen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T23:18:55.087", "Id": "459575", "Score": "0", "body": "final, final thought (just making sure I am given respect to your work and points) The callback for stopping condition is good. I had that in a different version of this code, and it would also be relevant to some of the \"4 famous pythag triples solutions\". I also played with the \"process each triple\" lambda returning a `bool` or `enum` for \"stop /continue\". But when I did that, I found it hard to name the parameter which accepts the lambda? `F& process_this_triple_callback_telling_me_when_to_stop` ??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T00:42:27.867", "Id": "459589", "Score": "0", "body": "\"I found it hard to name the parameter ... `process_this_triple_callback_telling_me_when_to_stop`?\" Yeah, I have no good style recommendation there. The two I've seen are (1) if your function does two things, name it both of them. `if (exchange_then_old_value(x))`, `if (check_and_reset(flag))`, `if (process_and_should_stop(t))`. Or (2) the \"process and then `true`-means-stop\" idiom is common enough that we can just write `if (process(t))` or `if (callback(t))` and assume people won't be too terribly confused." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T01:50:39.143", "Id": "459591", "Score": "0", "body": "On: This is a \"Matrix operation\" vs \"this is a formula\". Really distilled down, the point of it is: \"when the pattern of the symbols and the operators is consistent\" (ie when it is always `a x, b y, c z` and `*+*+*`) then those pieces do not add any information. They are just noise that distracts from the real info. That info is the coefficients. Those \"faceless data ranges\", to people trained in Matrices, are much richer in content than the formulae. We can immediately see for example, just how similar those 3 transformations are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T06:46:11.860", "Id": "459594", "Score": "0", "body": "Very nice review, and good counterpoints to some of my earlier suggestions. One comment: you say \"`long` varies in size and is the same size as `int` on many platforms\", I would say that nowadays the opposite is true; on almost any 64-bit platform except Windows, `int` is 32 bits and `long` is 64 bits in size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:49:30.233", "Id": "459606", "Score": "0", "body": "@G.Sliepen Indeed. But if Windows is your primary platform then that feels like \"many\"? For me it is isn't, I haven't booted one for 20yrs. But the point is well made, to be portably 64bit I need to change to int64_t. I already changed it on my copy. clang-tidy did tell me to do it too based on a google style check I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:42:46.250", "Id": "459635", "Score": "0", "body": "\"To be portably 64-bit,\" I'd be content with `long long`; I'm not a stickler for `<cstdint>` types. But `long` alone is the worst of all worlds: it basically means \"I want a type that acts like either `int` or `long long` at the platform's discretion, but *also* isn't either of them for the purposes of overload resolution.\" \"Never use the `long` type at all\" is a very good rule for simplifying your code, IMO." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:58:14.853", "Id": "234923", "ParentId": "234875", "Score": "3" } } ]
{ "AcceptedAnswerId": "234888", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T15:49:09.767", "Id": "234875", "Score": "5", "Tags": [ "c++", "algorithm", "c++17" ], "Title": "Pythagorean Triple finder" }
234875
<p>I'm parsing out specific values on web pages with BeautifulSoup. However, since I'm using RegEx, my program is taking forever to run. Would love ideas on how to speed this up.</p> <pre><code>from bs4 import BeautifulSoup import datetime import json from progressbar import progressbar import pdb import pickle import re class Listing(): def __init__(self, custom_name, **entries): self.__dict__.update(entries) self.custom_name = custom_name self.date_accessed = datetime.datetime.today() def __hash__(self): return hash(self.custom_name) def __eq__(self, other): return self.custom_name == other.custom_name def __repr__(self): return self.custom_name def list_to_dict(rlist): # QUEST: There are multiple colons in many of the entries. I couldn't # figure out how to use re.split where it only split the first occurence # so instead I replace only the first occurence and then split that new str list_with_replace_str = [re.sub(":", ":REPLACE", e, 1) for e in rlist] temp_dict = dict(f.split(":REPLACE") for f in list_with_replace_str) clean_dict = {} for key in temp_dict.keys(): clean_key = key.strip() clean_value = temp_dict[key].strip() clean_dict[clean_key] = clean_value return clean_dict def parse_listings(listing_objs): def parse_financials_div(financials_soup, listing_obj): try: financials_text = financials_soup.text financials_list = financials_text.split("\r\n")[:-1] financials_dict = list_to_dict(financials_list) not_included = [] for key in financials_dict: if "*" in financials_dict[key]: not_included.append(key) financials_dict["notIncluded"] = not_included for key in financials_dict: try: financials_dict[key] = int( re.sub("[^0-9]", "", financials_dict[key])) except Exception: continue return financials_dict except Exception as e: print(f"error {e}") pdb.set_trace() def parse_details_div(details_soup, listing_obj): try: details_tag_list = details_soup.contents details_str = " ".join([str(element) for element in details_tag_list]) details_list = details_str.split("&lt;dt&gt;")[1:] strs_to_tags = [BeautifulSoup(detail, "html.parser") for detail in details_list] details_text = [tag.text for tag in strs_to_tags] details_dict = list_to_dict(details_text) return details_dict except Exception as e: print(f"error {e}") pdb.set_trace() def parse_category(product_json_soup, listing_obj): product_json_str = product_json_soup.contents[0].replace( "\r", "").replace("\n", "") product_json_str = product_json_str.replace( "\'", "").replace('\\"', '').replace("\t", "") product_dict = json.loads(product_json_str) category_str = product_dict["category"] category_list = category_str.split("&gt;") category_list = [category.strip() for category in category_list] listing_obj.category = {} listing_obj.category["parent_category"] = category_list[0] try: listing_obj.category["sub_category"] = category_list[1] except Exception: listing_obj.category["sub_category"] = "Not Present" def parse_address(address_json_soup, listing_obj): address_json_str = address_json_soup.contents[0].replace( "\r", "").replace("\n", "") address_json_str = address_json_str.replace( "\'", "").replace('\\"', '').replace("\t", "") address_dict = json.loads(address_json_str) listing_obj.address = address_dict["address"] # Parse available listing fields into a dict print("Parse financials and details for listings") for listing_obj in progressbar(listing_objs): try: index = listing_objs.index(listing_obj) length = len(listing_objs) soup = BeautifulSoup(listing_obj.response_text, "html.parser") # Parse category category_json_pattern = re.compile(r"\"@type\" : \"Product\"") category_json_soup = soup.find( "script", {"type": "application/ld+json"}, text=category_json_pattern) if category_json_soup: parse_category(category_json_soup, listing_obj) # Parse address address_json_pattern = re.compile(r"LocalBusiness") address_json_soup = soup.find( "script", {"type": "application/ld+json"}, text=address_json_pattern) if address_json_soup: parse_address(address_json_soup, listing_obj) # Price details financials_span_pattern = re.compile(r"Asking Price:") financials_span_soup = soup.find( "span", text=financials_span_pattern) if financials_span_soup: financials_soup = financials_span_soup.parent.parent.parent.parent financials_dict = parse_financials_div( financials_soup, listing_obj) listing_obj.financials = financials_dict else: print( f"Financials not present #{index} of {length} {listing_obj.url}") print(soup) # Listing Details details_soup = soup.find("dl", {"class": "listingProfile_details"}) if details_soup: details_dict = parse_details_div(details_soup, listing_obj) listing_obj.details = details_dict except Exception as e: print(f"error {e}") def run_listing_calculations(listing_obj): # All in price extra_costs = 0 price = listing_obj.financials["Asking Price"] for item in listing_obj.financials["notIncluded"]: if "Real Estate" not in item: extra_costs += listing_obj.financials[item] if isinstance(price, int): all_in_price = listing_obj.financials["Asking Price"] + extra_costs else: all_in_price = listing_obj.financials["Asking Price"] listing_obj.financials["allInPrice"] = all_in_price # Multiple all_in_price = listing_obj.financials["allInPrice"] cashflow = listing_obj.financials["Cash Flow"] try: listing_obj.financials["Multiple"] = all_in_price / cashflow except Exception: listing_obj.financials["Multiple"] = "N/A" def parse_listings_from_pkl(): with open("/Users/work/Dropbox/Projects/Working Data/bizbuysell/listings20191231.pkl", "rb") as infile: listing_objs = pickle.load(infile) print("Validate listing responses") listing_resp_validated = [] for listing_obj in progressbar(listing_objs): try: if "Soup test failed" not in listing_obj.response_text: listing_resp_validated.append(listing_obj) except Exception: continue parse_listings(listing_resp_validated) print("Perform listing calculations") for listing_obj in progressbar(listing_resp_validated): financials_present = hasattr(listing_obj, "financials") if financials_present: run_listing_calculations(listing_obj) pdb.set_trace() if __name__ == "__main__": parse_listings_from_pkl() </code></pre> <p>Here's a <a href="https://www.dropbox.com/s/30lf2kmtx6evwzl/listings20191231.pkl?dl=0" rel="nofollow noreferrer">link to the <code>.pkl</code> file</a> needed to run this.</p> <p><a href="https://gist.github.com/lancejohnson/b97469d8413d0bd8042aec80e3760af6" rel="nofollow noreferrer">Here's a gist</a> with the example HTML response and <code>product_json_soup</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T17:58:14.320", "Id": "459447", "Score": "3", "body": "`product_json_soup` is undefined in your code. Add more context and post a testable `category_json_soup` content" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T18:16:16.743", "Id": "459535", "Score": "0", "body": "Cleaned up the naming and added a gist with the responses to make it testable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:57:50.460", "Id": "459539", "Score": "0", "body": "\"program is taking forever to run\" - there should be other bottlenecks on your side, the above fragment takes about 1 second to run on my machine. Does your actual script implies some looping and more extended parsing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:22:15.250", "Id": "459565", "Score": "0", "body": "You're right @RomanPerekhrest. It's fast for one, but when I iterate over 40,000 it is a very slow step. I've added the ```cProfile``` for the larger program to the gist. Let me know if that helps. I could put in the entire function, but it's more or less just tweaks on this, and it seems the ```re``` operations take the longest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T10:25:26.677", "Id": "459609", "Score": "0", "body": "Can you share those 40,000 urls so I could test the loop and get the actual estimates?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T23:02:31.277", "Id": "459690", "Score": "0", "body": "I'd guess that `requests.get` operations take the longest…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T16:57:35.127", "Id": "459895", "Score": "0", "body": "The `listings20191231.pkl` is too large (I don't know how many items inside). Please share a less one (e.g. 20..100 items) for testing purposes." } ]
[ { "body": "<p>The most time is consumed by <code>BeautifulSoup</code> conversions, namely</p>\n\n<pre><code>soup = BeautifulSoup(listing_obj.response_text, \"html.parser\")\n</code></pre>\n\n<p>For proof, firstly create a <code>.pkl</code> file of a <em>reasonable</em> size for debugging:</p>\n\n<pre><code>if __name__ == \"__main__\":\n with open(\"D:\\\\Downloads\\\\listings20191231.pkl\", \"rb\") as infile:\n listing_objs = pickle.load(infile)\n data = listing_objs[222:666]\n with open(\"D:\\\\Python\\\\CR\\\\listings20191231.pkl\", \"wb\") as oufile:\n pickle.dump(data, oufile, pickle.HIGHEST_PROTOCOL)\n</code></pre>\n\n<p>Then, check and compare consumed time using following adapted code (moreover, I removed all the <code>progressbar</code> stuff from the rest of original code):</p>\n\n<pre><code>if __name__ == \"__main__\":\n import time\n import sys\n argcnt = len(sys.argv) - 1\n argtxt = 'parse_listings_from_pkl()' if argcnt == 0 else 'BeautifulSoup'\n startload = time.time()\n with open(\"D:\\\\Python\\\\CR\\\\listings20191231.pkl\", \"rb\") as infile:\n listing_objs = pickle.load(infile)\n\n length = len(listing_objs)\n print( 'checking time: ', argtxt, length, 'records')\n start0 = time.time()\n if argcnt == 0:\n parse_listings_from_pkl()\n else:\n for listing_obj in listing_objs: #progressbar(listing_objs):\n soap = BeautifulSoup(listing_obj.response_text, \"html.parser\")\n\n start1 = time.time()\n print(\"time consumed: \", argtxt, start1 - start0)\n</code></pre>\n\n<p><strong>Output</strong> shows that cca <strong>86 % of time</strong> (<code>100 * 32.761232137680054 / 38.00445818901062</code>) is consumed by converting original <code>html</code> to <code>BeautifulSoup</code> format:</p>\n\n<pre><code>D:\\Python\\CR\\234876.py\n</code></pre>\n\n<blockquote>\n<pre><code>checking time: parse_listings_from_pkl() 444 records\nValidate listing responses\nParse financials and details for listings\nPerform listing calculations\ntime consumed: parse_listings_from_pkl() 38.00445818901062\n</code></pre>\n</blockquote>\n\n<pre><code>D:\\Python\\CR\\234876.py 1\n</code></pre>\n\n<blockquote>\n<pre><code>checking time: BeautifulSoup 444 records\ntime consumed: BeautifulSoup 32.761232137680054\n</code></pre>\n</blockquote>\n\n<p>Although there are some <em>optimizable parts</em> in the rest of <em>pure <code>python</code> code</em> (and I tried them with only minor performance improvements), I found that the <code>BeautifulSoup</code> conversion time corresponds to original <code>html</code> size and there is most of <em>gubbins</em> of no use inside the analyzed <code>html</code>. </p>\n\n<p>Hence, I'd try cutting the <code>listing_obj.response_text</code> into pieces of useful parts and convert merely those parts to <code>&lt;class 'bs4.BeautifulSoup'&gt;</code> type. Maybe <a href=\"https://stackoverflow.com/questions/25539330/speeding-up-beautifulsoup\">Speeding up beautifulsoup</a> or <a href=\"https://docs.python.org/3/library/html.parser.html\" rel=\"nofollow noreferrer\">Simple HTML and XHTML parser</a> could help extracting useful info from the original <code>html</code>?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-09T14:52:06.433", "Id": "235366", "ParentId": "234876", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T16:34:21.713", "Id": "234876", "Score": "5", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Parse JSON from HTML Python" }
234876
<p>The code below uses information saved in a hidden worksheet based on values from another sheet with a codename of GeneralInfo and is called when specific cells in GeneralInfo are changed. I think there would be a more efficient way to write this code. <br><br> the <code>Processing.Label</code> refers to labels on a worksheet codename of Processing.</p> <pre><code>Option Explicit Sub PopulateServiceDates() Dim InHouseTitle As String, InHouseEval As String, ApprRev As String, ClsSentRev As String, HMDALast As String Dim BSASaved As String, oAppraisal As String, oTitle As String, IHTitleRec As String, IHEvalRec As String, ApprRec As String Dim TitleRec As String On Error GoTo ErrHandler InHouseTitle = SheetData.Range("Date_In_House_Title_Work_Ordered") InHouseEval = SheetData.Range("Date_In_House_Eval_Sent") ApprRev = SheetData.Range("Date_Appraisal_Review_Sent") ClsSentRev = SheetData.Range("Date_Docs_Sent_for_Review") HMDALast = SheetData.Range("HMDAClicked") BSASaved = SheetData.Range("Date_BSA_Saved") oAppraisal = SheetData.Range("Date_Outside_Appraisal_Ordered") oTitle = SheetData.Range("Date_Outside_Title_Ordered") IHTitleRec = SheetData.Range("Date_In_House_Title_Received") IHEvalRec = SheetData.Range("Date_In_House_Appraisal_Received") ApprRec = SheetData.Range("Date_Outside_Appraisal_Received") TitleRec = SheetData.Range("Date_Outside_Title_Received") Dim cap As String, cap2 As String, cap3 As String, cap4 As String, cap5 As String, cap6 As String cap = "In-House Title Work Ordered:" &amp; vbCrLf &amp; _ "In-House Evaluation Ordered:" &amp; vbCrLf &amp; _ "Appraisal Ordered:" &amp; vbCrLf &amp; _ "Title Work Ordered:" cap2 = IIf(ApprRev &lt;&gt; vbNullString, ApprRev, "Not sent yet") &amp; vbCrLf &amp; _ IIf(ClsSentRev &lt;&gt; vbNullString, ClsSentRev, "Not sent yet") &amp; vbCrLf &amp; _ IIf(HMDALast &lt;&gt; vbNullString, HMDALast, "HMDA Helper not saved yet.") &amp; vbCrLf &amp; _ IIf(BSASaved &lt;&gt; vbNullString, BSASaved, "N/A") cap3 = IIf(InHouseTitle &lt;&gt; vbNullString, InHouseTitle, "N/A") &amp; vbCrLf &amp; _ IIf(InHouseEval &lt;&gt; vbNullString, InHouseEval, "N/A") &amp; vbCrLf &amp; _ IIf(oAppraisal &lt;&gt; vbNullString, oAppraisal, "N/A") &amp; vbCrLf &amp; _ IIf(oTitle &lt;&gt; vbNullString, oTitle, "N/A") cap4 = "Appraisal Sent for Review:" &amp; vbCrLf &amp; _ "Closing Docs Sent for Review:" &amp; vbCrLf &amp; _ "HMDA Helper Last Updated:" &amp; vbCrLf &amp; _ "BSA Saved:" cap5 = "In-House Title Work Received:" &amp; vbCrLf &amp; _ "In-House Evaluation Received:" &amp; vbCrLf &amp; _ "Appraisal Received:" &amp; vbCrLf &amp; _ "Title Work Received:" cap6 = IIf(IHTitleRec &lt;&gt; vbNullString, IHTitleRec, "N/A") &amp; vbCrLf &amp; _ IIf(IHEvalRec &lt;&gt; vbNullString, IHEvalRec, "N/A") &amp; vbCrLf &amp; _ IIf(ApprRec &lt;&gt; vbNullString, ApprRec, "N/A") &amp; vbCrLf &amp; _ IIf(TitleRec &lt;&gt; vbNullString, TitleRec, "N/A") With Processing.Label12 .caption = cap .Font.Size = 14 .TextAlign = fmTextAlignRight End With With Processing.Label13 .caption = cap3 .Font.Size = 14 .TextAlign = fmTextAlignLeft End With With Processing.Label9 .caption = cap4 .Font.Size = 14 .TextAlign = fmTextAlignRight End With With Processing.Label11 .caption = cap2 .Font.Size = 14 .TextAlign = fmTextAlignLeft End With With Processing.Label6 .caption = cap5 .Font.Size = 14 .TextAlign = fmTextAlignRight End With With Processing.Label14 .caption = cap6 .Font.Size = 14 .TextAlign = fmTextAlignLeft End With ErrHandler: If Err.Number &lt;&gt; 0 Then If MsgBox("Error " &amp; str(Err.Number) &amp; " " &amp; Err.Description &amp; vbCrLf &amp; _ "occured in the PopulateServiceDates Subroutine " &amp; vbCrLf &amp; _ "Please let Zack know what caused the error before clicking OK.", vbOKOnly + vbCritical, UCase("error")) = vbOK Then Resume Next End If End If End Sub </code></pre>
[]
[ { "body": "<p>Declare your variables right before you use them. For your <code>cap</code> variables, assuming these stand for caption (more on that with descriptive variables), you have a Declare, Populate, Use in a 1-2-3 pattern.</p>\n\n<pre><code>Dim foo As String '&lt;-- 1 Declare\n\n'Code that does stuff\n\nfoo = \"bar\" '&lt;-- 2 Populate\n\n'More code\n\nbuzz.Caption = foo `&lt;-- 3 Use\n</code></pre>\n\n<p>You can, and IMO should, reduce down to the assigning the property all at once without the variable.</p>\n\n<pre><code>buzz.Caption = \"bar\"\n</code></pre>\n\n<hr>\n\n<p>Using a default member hides what's going on, making your code harder to read. Avoid using them. The code below is using the default member on the Range object.</p>\n\n<pre><code>Dim defaultMemberAccess As String\ndefaultMemberAccess = SheetData.Range(\"Foo\")\n</code></pre>\n\n<p>Be explicit about what you want it to obtain like as below. You now know it's accessing the <code>Value2</code> member of the Range object.</p>\n\n<pre><code>Dim explicitlyStatedMemberAccess as String\nexplicitlyStatedMemberAccess = SheetData.Range(\"Foo\").Value2\n</code></pre>\n\n<hr>\n\n<p>Explicitly qualify your Sub. Omitting any access modifier means its implicitly <code>Public</code>. Add that Public in to have <code>Public Sub PopulateServiceDates()</code> so it's obvious that it was intentional.</p>\n\n<hr>\n\n<p>Variable names. Use descriptive variables. <code>IHEvalRec</code> made me immediately think it was in interface. That's because an I prefix by convention indicates interface. If I saw <code>inHouseAppraisalReceivedText</code> that would be a lot more informative and take less guesswork. Future-you will also thank you when you come back to this code.</p>\n\n<p>This ties in to Label12, Label13, etc... Rename them labels because they aren't helping readability. Again future-you will thank you.</p>\n\n<hr>\n\n<p>Magic numbers. <code>14</code> has what meaning? Is that the default font size you want to use? We already went over that and this ties in as well. <code>Const DefaultFontSize As Double = 14</code> declares a constant and lets you know you want it to be the default font size so that <code>.Font.size = DefaultFontSize</code> is self describing.</p>\n\n<hr>\n\n<p>Usage of IIF feels odd, like your sometimes expecting an error. You're accessing named ranges and it should be a safe assumption they are there. I'm of the opinion they should be behind a worksheet property, and that the property should handle what occurs if there's a barf error. Something like</p>\n\n<pre><code>Private Property Get InHouseTitleWorkOrderedText() As String\n Dim temp As String\n temp = SheetData.Range(\"Date_In_House_Title_Work_Ordered\").Value2\n If temp = vbNullString Then\n InHouseTitleWorkOrderedText = \"N/A\"\n Else\n InHouseTitleWorkOrderedText = temp\n End If\nEnd Property\n</code></pre>\n\n<p>so that when you are populating the labels caption property you end up with </p>\n\n<pre><code> With Processing.Label13\n .Caption = InHouseTitleWorkOrderedText &amp; vbCrLf &amp; _\n InHouseEvaluationSentText &amp; vbCrLf &amp; _\n OutsideAppraisalOrderedText &amp; vbCrLf &amp; _\n OutsideTitleOrderedText\n .Font.Size = 14\n .TextAlign = fmTextAlign.fmTextAlignLeft\n End With\n</code></pre>\n\n<p>Once you have your properties set up like that you begin think about whether the property should doing any logic checking in the first place. Can that be done in the cell itself? If yes, the property reduces down to</p>\n\n<pre><code>Private Property Get InHouseTitleWorkOrderedText() As String\n InHouseTitleWorkOrderedText = SheetData.Range(\"Date_In_House_Title_Work_Ordered\").Value2\nEnd Property\n</code></pre>\n\n<hr>\n\n<p>Lastly and 2 minor things <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a>, to which I'm a contributor, helped me pick up that I forgot. You can use replace <code>Str(Err.Number)</code> with <code>Str$(Err.Number)</code> and <code>UCase(\"error\")</code> with <code>UCase$(\"error\")</code>. These are the alternate typed functions.</p>\n\n<p>In truth however <code>UCase$(\"error\")</code> should be just <code>\"ERROR\"</code>.</p>\n\n<hr>\n\n<p>Combining all the above I came up with</p>\n\n<pre><code>'SheetData\nPublic Property Get InHouseTitleWorkOrderedText() As String\n InHouseTitleWorkOrderedText = SheetData.Range(\"Date_In_House_Title_Work_Ordered\").Value2\nEnd Property\n\nPublic Property Get InHouseEvaluationSentText() As String\n InHouseEvaluationSentText = SheetData.Range(\"Date_In_House_Eval_Sent\").Value2\nEnd Property\n\nPublic Property Get AppriasalReviewSentText() As String\n AppriasalReviewSentText = SheetData.Range(\"Date_Appraisal_Review_Sent\").Value2\nEnd Property\n\nPublic Property Get DocumentSentForReviewText() As String\n DocumentSentForReviewText = SheetData.Range(\"Date_Docs_Sent_for_Review\").Value2\nEnd Property\n\nPublic Property Get HMDALastText() As String\n HMDALastText = SheetData.Range(\"HMDAClicked\").Value2\nEnd Property\n\nPublic Property Get BSASavedText() As String\n BSASavedText = SheetData.Range(\"Date_BSA_Saved\")\nEnd Property\n\nPublic Property Get OutsideAppraisalOrderedText() As String\n OutsideAppraisalOrderedText = SheetData.Range(\"Date_Outside_Appraisal_Ordered\")\nEnd Property\n\nPublic Property Get OutsideTitleOrderedText() As String\n OutsideTitleOrderedText = SheetData.Range(\"Date_Outside_Title_Ordered\")\nEnd Property\n\nPublic Property Get InHouseTitleReceivedText() As String\n InHouseTitleReceivedText = SheetData.Range(\"Date_In_House_Title_Received\")\nEnd Property\n\nPublic Property Get InHouseAppraisalReceivedText() As String\n InHouseAppraisalReceivedText = SheetData.Range(\"Date_In_House_Appraisal_Received\")\nEnd Property\n\nPublic Property Get OutsideAppraisalReceivedText() As String\n OutsideAppraisalReceivedText = SheetData.Range(\"Date_Outside_Appraisal_Received\")\nEnd Property\n\nPublic Property Get OutsideTitleReceivedText() As String\n OutsideTitleReceivedText = SheetData.Range(\"Date_Outside_Title_Received\")\nEnd Property\n</code></pre>\n\n<p>And the rewritten module</p>\n\n<pre><code>Module1\nOption Explicit\n\nPublic Sub PopulateServiceDates()\n Const DefaultFontSize As Double = 14\n\n On Error GoTo ErrHandler\n\n With Processing.Label12\n .Caption = \"In-House Title Work Ordered:\" &amp; vbCrLf &amp; _\n \"In-House Evaluation Ordered:\" &amp; vbCrLf &amp; _\n \"Appraisal Ordered:\" &amp; vbCrLf &amp; _\n \"Title Work Ordered:\"\n .Font.Size = DefaultFontSize\n .TextAlign = fmTextAlign.fmTextAlignRight\n End With\n\n With Processing.Label13\n .Caption = SheetData.InHouseTitleWorkOrderedText &amp; vbCrLf &amp; _\n SheetData.InHouseEvaluationSentText &amp; vbCrLf &amp; _\n SheetData.OutsideAppraisalOrderedText &amp; vbCrLf &amp; _\n SheetData.OutsideTitleOrderedText\n .Font.Size = DefaultFontSize\n .TextAlign = fmTextAlign.fmTextAlignLeft\n End With\n\n With Processing.Label9\n .Caption = \"Appraisal Sent for Review:\" &amp; vbCrLf &amp; _\n \"Closing Docs Sent for Review:\" &amp; vbCrLf &amp; _\n \"HMDA Helper Last Updated:\" &amp; vbCrLf &amp; _\n \"BSA Saved:\"\n .Font.Size = DefaultFontSize\n .TextAlign = fmTextAlign.fmTextAlignRight\n End With\n\n With Processing.Label11\n .Caption = SheetData.AppriasalReviewSentText &amp; vbCrLf &amp; _\n SheetData.DocumentSentForReviewText &amp; vbCrLf &amp; _\n SheetData.HMDALastText &amp; vbCrLf &amp; _\n SheetData.BSASavedText\n .Font.Size = DefaultFontSize\n .TextAlign = fmTextAlign.fmTextAlignLeft\n End With\n\n With Processing.Label6\n .Caption = \"In-House Title Work Received:\" &amp; vbCrLf &amp; _\n \"In-House Evaluation Received:\" &amp; vbCrLf &amp; _\n \"Appraisal Received:\" &amp; vbCrLf &amp; _\n \"Title Work Received:\"\n .Font.Size = DefaultFontSize\n .TextAlign = fmTextAlign.fmTextAlignRight\n End With\n\n\n With Processing.Label14\n .Caption = SheetData.InHouseTitleReceivedText &amp; vbCrLf &amp; _\n SheetData.InHouseAppraisalReceivedText &amp; vbCrLf &amp; _\n SheetData.OutsideAppraisalReceivedText &amp; vbCrLf &amp; _\n SheetData.OutsideTitleReceivedText\n .Font.Size = DefaultFontSize\n .TextAlign = fmTextAlign.fmTextAlignLeft\n End With\n\nErrHandler:\n If Err.Number &lt;&gt; 0 Then\n If MsgBox(\"Error \" &amp; Str$(Err.Number) &amp; \" \" &amp; Err.Description &amp; vbCrLf &amp; _\n \"occured in the PopulateServiceDates Subroutine \" &amp; vbCrLf &amp; _\n \"Please let Zack know what caused the error before clicking OK.\", vbOKOnly + vbCritical, UCase$(\"error\")) = vbOK Then\n Resume Next\n End If\n End If\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T20:49:14.747", "Id": "459455", "Score": "0", "body": "Thank you. I have some research to do on the `Public Property Get` functionality since I am not familiar with that at all and the difference between Value and Value2. I did rename the labels after I submitted this for review. I didnt even think about declaring the font size as a constant. I wish I could get RubberDuck but im not allowed to even though Ive asked numerous times and shown examples of how it would benefit me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T21:31:04.287", "Id": "459458", "Score": "0", "body": "Additional reading for the [Property Get statement](https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/property-get-statement). Differences for [.Text .Value and .Value2](https://stackoverflow.com/a/17363466/7420518)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T13:27:14.030", "Id": "459614", "Score": "0", "body": "Thank you for the additional reference material it helped a lot. I am going to wait a couple of days before accepting this answer to see if anyone else has anything they want to add as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:23:58.237", "Id": "459803", "Score": "0", "body": "From my understanding of the `Get` method now; i could use that in a class module instead of within the sheet object correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T18:05:04.210", "Id": "460309", "Score": "0", "body": "It's a property accessor, you can use it in either. If you have state saved you provide access to it via the Get statement. The other side is if you want to change the state you do so with the Property ( [Let](https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/property-let-statement) | [Set](https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/property-set-statement) ) statement. Let for value types and Set for reference types." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T20:04:11.470", "Id": "234881", "ParentId": "234877", "Score": "3" } } ]
{ "AcceptedAnswerId": "234881", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T16:56:12.490", "Id": "234877", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Populate dates in a label based on dates in a hidden sheet using IIF" }
234877
<p>I have implemented a QuadTree of my own, and I'm afraid I didn't use yield properly when I query my tree, my fear is that I create O(HN) iterators.</p> <p>Could you direct me how to better improve the performance of the following code?</p> <p>QuadTree</p> <pre><code>public IEnumerable&lt;T&gt; Query(string leafId, Circle shape) { // Gets the relevant parent by a leafId Query (this is O(lg H)) var startNode = GetParentIntersecting(leafId, shape); return startNode.Query(shape); } </code></pre> <p>QuadTreeNode</p> <pre><code> public IEnumerable&lt;T&gt; Query(IShape shape) { var results = new HashSet&lt;T&gt;(); foreach (var content in _contents) { if (shape.Contains(content.GetPosition())) { //Debug.Log(content.GetPosition()); yield return content; //results.Add(content); } } if (IsLeaf) yield break; foreach (var node in Nodes) { if (node.IsEmpty &amp;&amp; node.IsLeaf) continue; foreach (var result in node.Query(shape)) { results.Add(result); }; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T19:50:53.847", "Id": "459452", "Score": "4", "body": "Please provide all the relevant code. Also some tests would be useful. If I cannot copy your code and compile it without adding anything extra I vote to close for lack of concrete context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:01:16.113", "Id": "459525", "Score": "0", "body": "Please provide the full class, otherwise we can't really suggest performance improvements." } ]
[ { "body": "<p>You use yield properly, it's OK to yield from inside nested loops. But all the code behind your first foreach is kind of useless, it's not doing anything useful.</p>\n\n<p>First the <code>yield break</code> is useless, cause there are no more yields following, there are no more return values produced no matter if IsLeaf true or false. Iteration ends anyway.</p>\n\n<p>Second you fill up <code>results</code> with something, but the content of results is lost, then the Method exits. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:43:28.060", "Id": "234928", "ParentId": "234879", "Score": "1" } } ]
{ "AcceptedAnswerId": "234928", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T18:48:55.397", "Id": "234879", "Score": "0", "Tags": [ "c#", "performance", "iterator" ], "Title": "c# QuadTree yielding properly" }
234879
<p>I have created a blackjack game in Python3 but I am worried that it is not very efficient and also there are some problems with it.<br> Problem 1) The player almost always wins unless he goes bust as the program allows the player to take multiple cards but the computer only chooses 2 and I can't think of any solutions.<br> Problem 2) Because of how I have done the choosing of the suits it is entirely possible to get e.g. 2 Kings of spades which is impossible with a regular deck of cards. Since I am new to python any help would be much appreciated.</p> <pre class="lang-py prettyprint-override"><code>import random cards = { "Ace": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "Jack": 10, "Queen": 10, "King": 10 } suits = [" of spades", " of clubs", " of hearts", " of diamonds", " of spades", " of clubs", " of hearts", " of diamonds", " of spades", " of clubs", " of hearts", " of diamonds", " of spades", " of clubs", " of hearts", " of diamonds", " of spades", " of clubs", " of hearts", " of diamonds", ] again = "yes" while again == "yes": def firstcards(): global first_card global second_card global total total = 0 first_card = random.choice(list(cards)) second_card = random.choice(list(cards)) total += cards.get(first_card) total += cards.get(second_card) firstcards() def gameplay(): global total another_card = "yes" print("Your first card is the " + first_card + random.choice(suits)) print("Your second card is the " + second_card + random.choice(suits)) print("Your total is: " + str(total)) while another_card == "yes" and total &lt; 21: print("Would you like another card?") another_card = input("Y/N: ") if another_card == "Y": card = random.choice(list(cards)) total += cards.get(card) print("Your next card is the " + card + random.choice(suits)) print("Your total is now: " + str(total)) another_card = "yes" elif another_card == "N": num1 = random.randint(1, 10) num2 = random.randint(1, 10) computerTotal = num1 + num2 print("The computer got a total of " + str(computerTotal)) if computerTotal &gt; total: print("The computer wins!") else: print("You win!") another_card = "no" else: print("That is not a valid option.") another_card = "yes" if total &gt; 21: print("You have gone bust!") print("The computer wins!") def play_again(): global again print("") print("Would you like to play again?") again = input("yes/no: ") if again != "yes" and again != "no": print("That is not a valid option") play_again() elif again == "yes": print("") print("") elif again == "no": again = "no" play_again() gameplay() </code></pre> <p>Once again any help would be much appreciated.</p>
[]
[ { "body": "<p>It's hard to make small tweaks to this code to make it do what you want, so I'm going to give some pointers on how to do a wholesale rewrite.</p>\n<p>Before you can write a card game, you need to write a data model for a deck of cards. Picking the right data model makes everything else easy (part of why your program was hard to write and is hard to fix that the cards were modeled in a way that didn't make the rest of the program easy). Here's how I'd do it:</p>\n<pre><code>from enum import auto, Enum\nfrom random import shuffle\nfrom typing import List, NamedTuple\n\nclass Rank(Enum):\n ACE = 1\n TWO = 2\n THREE = 3\n FOUR = 4\n FIVE = 5\n SIX = 6\n SEVEN = 7\n EIGHT = 8\n NINE = 9\n TEN = 10\n JACK = 10\n QUEEN = 10\n KING = 10\n\nclass Suit(Enum):\n SPADES = auto()\n CLUBS = auto()\n DIAMONDS = auto()\n HEARTS = auto()\n\nclass Card(NamedTuple):\n rank: Rank\n suit: Suit\n def __repr__(self) -&gt; str:\n &quot;&quot;&quot;Pretty-print the name of the card, e.g. 'Queen of Hearts'&quot;&quot;&quot;\n return f&quot;{self.rank.name.title()} of {self.suit.name.title()}&quot;\n</code></pre>\n<p>There's my <code>Card</code> class -- every card has a <code>rank</code> and <code>suit</code>. Enums have the convenient built-in functions <code>name</code> and <code>value</code> that I can use for pretty-printing and also for scoring (I set the <code>value</code> of my <code>Rank</code> enum to correspond to standard scoring numbers).</p>\n<p>A <code>NamedTuple</code> is an easy way to build a class that contains multiple other values that never change; it automatically implements a constructor to set its member variables and in many cases you don't need to do anything other than declare what those variables are, but you can also add other methods to it. My <code>Card</code> implements a magic <code>__repr__</code> function so that anywhere we print one (including inside a list) it will get formatted as something like <code>Queen of Hearts</code> rather than the default <code>NamedTuple</code> formatting of <code>Card(rank=Rank.QUEEN, suit=Suit.HEARTS)</code>.</p>\n<p>And here's a really quick example of how you could use this class to implement a game like blackjack. This isn't an actual blackjack game, I've just implemented the dealer part to demonstrate how building a deck, shuffling, and dealing would work, but hopefully you can play with this code and see how simple everything is when you have a nice data model. In particular something like the <code>best_value</code> function is going to be really important to a blackjack game (and it's a lot easier to define it as its own function and then be able to call it in a bunch of places).</p>\n<pre><code>deck = [Card(rank, suit) for suit in Suit for rank in Rank]\nprint(&quot;Here's our deck fresh from the factory: &quot;, deck)\nshuffle(deck)\nprint(&quot;Here it is all shuffled: &quot;, deck)\n\ndef best_value(hand: List[Card]) -&gt; int:\n &quot;&quot;&quot;Get the best blackjack value for a hand of cards (highest without busting)&quot;&quot;&quot;\n value = sum([card.rank.value for card in hand])\n if value &lt; 12 and any([card.rank == Rank.ACE for card in hand]):\n # Count one of our aces as 11, adding 10 to the total.\n value += 10\n return value\n\nprint()\nprint(&quot;Deal me two!&quot;)\nhand = [deck.pop(), deck.pop()]\nprint(f&quot;My hand is {hand}, which is worth {best_value(hand)}&quot;)\n\nwhile best_value(hand) &lt; 17:\n print(&quot;Hit me!&quot;)\n card = deck.pop()\n hand.append(card)\n print(&quot;I got &quot;, card)\n\nif best_value(hand) &gt; 21:\n print(&quot;Bust!&quot;)\nprint(f&quot;{hand} = {best_value(hand)}&quot;)\n</code></pre>\n<p>Run this code, read through it, understand how it works, then take another crack at writing a blackjack program and hopefully it'll be easier this time around. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T15:00:11.773", "Id": "459517", "Score": "2", "body": "`best_value([10, 10, Ace])` should rather be 21, not 31." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:57:11.860", "Id": "459530", "Score": "0", "body": "oops, good catch! fixed" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T01:36:40.867", "Id": "234890", "ParentId": "234880", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T18:54:47.323", "Id": "234880", "Score": "7", "Tags": [ "python", "beginner", "python-3.x", "game" ], "Title": "Blackjack / 21 in Python3" }
234880
<p>I want to design an elevator system, which has functionality for pressing button from outside of the elevator (Not selecting a direction - Only calls the passenger’s existing floor). And also select floor functionality needed to select a floor for target.</p> <p>Inside controls have priority over outside controls.</p> <p>While traveling the elevator only stops a station (via outside control) if it is on its way. I have tried to implement state patterns but it didn't work as I expected.</p> <p>Can you please put a comment that how can I improve the following solution.</p> <p>Thanks.</p> <p>Elevator.java </p> <pre><code>package OOPDesign.elevatorStates; import java.util.LinkedList; import java.util.Queue; public class Elevator { public static Elevator instance; static Queue&lt;Integer&gt; requestQueue; static ElevatorStateContext elevatorStateContext; static int currentFloor; private Elevator(){ requestQueue = new LinkedList&lt;&gt;(); elevatorStateContext = new ElevatorStateContext(); currentFloor = 0; } public static Elevator getInstance(){ if(instance == null){ instance = new Elevator(); } return instance; } static void receiveRequest(int passengersFloor){ requestQueue.add(passengersFloor); processQueue(requestQueue); } static void processQueue(Queue&lt;Integer&gt; requestQueue) { int passengersFloor = requestQueue.peek(); System.out.println("Currently going "+ passengersFloor); if(passengersFloor&gt;currentFloor) elevatorStateContext.setState(State.UP); else elevatorStateContext.setState(State.DOWN); System.out.println("Direction "+ elevatorStateContext.getDirection()); requestQueue.remove(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Arrived "+ passengersFloor); if(requestQueue.isEmpty()){ elevatorStateContext.setState(State.IDLE); System.out.println("Direction "+ elevatorStateContext.getDirection()); } } } </code></pre> <p>ElevatorControlSystem.java</p> <pre><code>package OOPDesign.elevatorStates; public class ElevatorControlSystem { Elevator elevator; public ElevatorControlSystem(){ elevator = Elevator.getInstance(); } void pressButton(int passengersFloor){ dispatchRequest("OUTSIDE",passengersFloor); } void selectFloor(int targetFloor){ dispatchRequest("INSIDE",targetFloor); } private void dispatchRequest(String priority, int passengersFloor) { int elevatorFloor = Elevator.currentFloor; // If elevator is idle it can serve to any request if(Elevator.elevatorStateContext.getDirection() == State.IDLE){ Elevator.receiveRequest(passengersFloor); }else { if (priority == "INSIDE") { Elevator.receiveRequest(passengersFloor); } else { // Outside calls if (Elevator.elevatorStateContext.getDirection() == State.UP &amp;&amp; passengersFloor &gt; elevatorFloor) { Elevator.receiveRequest(passengersFloor); } else if (Elevator.elevatorStateContext.getDirection() == State.DOWN &amp;&amp; passengersFloor &lt; elevatorFloor) { Elevator.receiveRequest(passengersFloor); } else { System.out.println("Can not give service"); } } } } } </code></pre> <p>ElevatorState.java</p> <pre><code>package OOPDesign.elevatorStates; interface ElevatorState { public State status(ElevatorStateContext ctx); } </code></pre> <p>ElevatorStateContext.java</p> <pre><code>package OOPDesign.elevatorStates; public class ElevatorStateContext { private State elevatorState; public ElevatorStateContext(){ elevatorState = State.IDLE; } public void setState(State state){ elevatorState = state; } public State getDirection(){ return elevatorState; } } </code></pre> <p>Enum</p> <pre><code>package OOPDesign.elevatorStates; public enum State { IDLE, UP, DOWN; } </code></pre> <p>Test class</p> <pre><code>package OOPDesign.elevatorStates; public class ElevatorTest { public static void main(String[] args) { ElevatorControlSystem ecs = new ElevatorControlSystem(); ecs.pressButton(5); ecs.selectFloor(3); ecs.pressButton(6); ecs.selectFloor(1); ecs.pressButton(9); ecs.pressButton(10); ecs.pressButton(11); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T11:21:36.887", "Id": "459484", "Score": "0", "body": "`I have tried to implement state patterns but it didn't work as I expected` - could you please clarify what you mean by this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:15:58.963", "Id": "459503", "Score": "0", "body": "I have tried to implement state pattern at the code, actually it turn out a simple comparision. As an idea I was thinking to change the bhaviour according the state, if state is idle it can serve anyone, but if the state is \"moving up\", it only can server inside requests or outside requests on its way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:07:02.940", "Id": "459796", "Score": "0", "body": "Defining elevator position as an integer representing a floor is incorrect. An elevator position is a floating point number (maybe even millimeters from bottom, but not whole floors). Along the range of the position are zones where the elevator starts breaking when it arrives at a floor and zones where the doors can open if the speed is zero." } ]
[ { "body": "<p>If this design is for a school project, and you've already submitted it, I fear you will have already failed the assignment. This design is bad.</p>\n\n<h1>Static</h1>\n\n<p>As a guiding principle, Java programs should use the identifier <code>static</code> exactly once, specifically in the declaration <code>public static void main(String args[])</code>. Any other usages of <code>static</code> should sound warning bells; you might be doing something wrong.</p>\n\n<p>Consider a hotel. It often has multiple elevators. With <code>static int currentFloor</code>, every elevator must be on the same floor! With <code>static ElevatorStateContext elevatorStateContext</code>, every elevator is moving in the same direction! This is a poor design choice. Even if you have exactly one elevator, that elevator should own its own data, instead of having it stored as global class variables.</p>\n\n<p>Often, hotels have multiple elevator systems. There might be a main elevator bank, for guests, as well as service elevators for hotel staff. There could be elevators in multiple towers of the hotel, and parking garage elevators. In short, there could be more than one <code>ElevatorControlSystem</code>, and each would own its own set of elevators. Each time <code>ElevatorControlSystem</code> is constructed, it executes <code>elevator = Elevator.getInstance();</code> ... which means each control system is trying to operate the same elevator???</p>\n\n<hr>\n\n<h1>Identity -vs- Equality</h1>\n\n<p>The test <code>if (priority == \"INSIDE\")</code> is testing object identity. Only if the <code>String</code> stored in <code>priority</code> has the same identity as the <code>String</code> embedded in this compilation unit will the test pass. This is fragile, and will break as soon as you try passing in the String <code>\"INSIDE\"</code> created elsewhere. You should check for equality: <code>if (priority.equals(\"INSIDE\"))</code>.</p>\n\n<p>Or, use an <code>enum</code> for <code>INSIDE</code> -vs- <code>OUTSIDE</code>, like you are already using for elevator state.</p>\n\n<hr>\n\n<h1>Useless Items</h1>\n\n<h2>Useless Encapsulation</h2>\n\n<p><code>ElevatorStateContext</code> contains <code>State elevatorState</code>, and a setter and a getter, which add no additional behaviour, checks, or functionality.</p>\n\n<p>What is the purpose of this class? You could directly store and fetch the <code>State</code> in <code>Elevator</code>, and eliminate this class. Or was something else supposed to be included in the <code>ElevatorStateContext</code>, like whether the doors were open/opening/closed/closing or which floors have been requested?</p>\n\n<h2>Useless Queue</h2>\n\n<p>You have a queue which will only ever hold at most one item. These lines add the item, and then immediately pull the item off for processing:</p>\n\n<pre><code> requestQueue.add(passengersFloor);\n processQueue(requestQueue);\n</code></pre>\n\n<p>Inside <code>processQueue()</code>, you <code>peek()</code> and <code>remove()</code> items from the queue separately:</p>\n\n<pre><code> int passengersFloor = requestQueue.peek();\n ...\n requestQueue.remove();\n ...\n</code></pre>\n\n<p>But there is no point to peeking; you always remove the item, so the following simpler code would work:</p>\n\n<pre><code> int passengersFloor = requestQueue.remove();\n ...\n</code></pre>\n\n<hr>\n\n<h1>Unused Items</h1>\n\n<h2>Unused Singleton</h2>\n\n<p>You execute <code>elevator = Elevator.getInstance();</code> but nowhere are you actually using the <code>elevator</code> member variable.</p>\n\n<h2>Unused Interface</h2>\n\n<p>You declare <code>interface ElevatorState</code>, but nothing ever implements that interface.</p>\n\n<hr>\n\n<h1>Sequential Tests / Operation</h1>\n\n<p>Due to <code>dispatchRequest()</code> and <code>processQueue()</code> completely handling requests one at a time, the test code is completely incapable of testing an elevator in motion when another request comes in. If 5 people request the elevator on the main floor, and get in, and press the floors buttons 5, 2, 6, 3, 4 ...</p>\n\n<pre><code> ecs.pressButton(1);\n ecs.selectFloor(5);\n ecs.selectFloor(2);\n ecs.selectFloor(6);\n ecs.selectFloor(3);\n ecs.selectFloor(4);\n</code></pre>\n\n<p>the elevator will move to the 5th floor, bypassing 2, 3 and 4. And then it will move to the 2nd floor, bypassing 4 and 3. Then it will move to the 6th floor, bypassing 3 and 4. And then it will move to the 3rd floor bypassing 4. And finally it will move to the 4th floor. Painfully inefficient.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:04:19.567", "Id": "234924", "ParentId": "234884", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T21:26:00.400", "Id": "234884", "Score": "4", "Tags": [ "java", "object-oriented", "design-patterns" ], "Title": "Elevator Design" }
234884
<p>I just wanted to ask the following question. I have solved Kadanes algorithm using the recursive approach as shown below. The implementation works</p> <pre class="lang-java prettyprint-override"><code> public class Kadane { public static void main(String[] args) { int[] arr = {-2, -5, 6, -2, -3, 1, 5, -6}; Kadane k = new Kadane(); System.out.println(k.calculate(arr, 0, 0)); } public int calculate(int[] arr, int pointer, int sum) { if(pointer &gt;= arr.length ) return sum; return Math.max(sum, Math.max(calculate(arr, pointer+1, sum+arr[pointer]), calculate(arr, pointer+1, 0))); } } </code></pre> <p>My question is whether the way I am using recursion(top down) is correct or should recursion by definition should always be bottom up? Is this approach correct logically even though implementation wise it seems fine?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T02:10:46.547", "Id": "459477", "Score": "2", "body": "The implementation is correct, but the time complexity is awful (O(2^n) I think). You can convert it into an O(n) algorithm by using a technique called Dynamic Programming. Is this homework?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T11:54:02.787", "Id": "459489", "Score": "0", "body": "@log N Is a dp solution an option for you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-09T03:29:38.367", "Id": "460510", "Score": "0", "body": "I find the wording strange. Algorithms don't get solved. An algorithm solves a problem; the execution of an implementation solves a problem instance. The problem solved by *Kadane's algorithm* is the [maximum subarray problem](https://en.m.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm). I think using recursion with the biggest/original problem instance handled in the outermost call natural. There are tail recursive variants of simple loops, e.g., computing *fib(n)* sort of fast; I find them atypical." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T21:44:26.933", "Id": "234885", "Score": "2", "Tags": [ "java", "algorithm", "recursion" ], "Title": "Kadanes algorithm implementation" }
234885
<p>While we patiently wait for <code>ranges</code> in C++20, it can still get somewhat frustrating to write <code>begin()</code>, <code>end()</code> and <code>micro-lambda</code>s to specify "sort order" and "field extraction". </p> <p>It is the latter, "field extraction" which I find is very commonly needed, but rarely discussed. The <code>C++11 lambda</code> has made it easier but the syntax is still very verbose for a very common task. There was even a recent slack/cpplang question about it. Inspired by <a href="https://youtu.be/W2tWOdzgXHA?t=1608" rel="nofollow noreferrer">a comment</a> in Sean Parent's famous Seasoning talk, where he suggested using <code>std::bind</code> to abstract this syntax, I looked into modern alternatives. <code>std::bind</code> has a bad name for being large and slow. More modern is <code>std::invoke</code> from C++17. </p> <p>So my proof of concept below tries to get to some terser syntax for these common operations using <code>std::invoke</code>. </p> <p>I am looking for feedback on:</p> <ul> <li>Coding style</li> <li>Constraining that template - with / without c++20 concepts (it's wide open right now)</li> <li>The new, terser calling syntax for STL algos which operate on some user defined class and require field/member extraction and potentially sorting on those. </li> <li><code>std::sort</code> is just one example. This could work for std::accumulate or anything really. Would I need up to 115 such wrapper templates? is there a better way. </li> </ul> <p>Code size <em>may</em> still be a concern (even with <code>std::invoke</code> rather than <code>std::bind</code>) as shown by the the generated <a href="https://godbolt.org/z/byOAk6" rel="nofollow noreferrer">ASM here</a>. The base case of the traditional lambda generates ~2000 lines of assembly code (LOA). Then <strong>each</strong> of the "new syntax" lines generates a further 2000 LOA -bringin it to ~8000 LOA in total for <code>clang-9 -O3</code>. Because the <code>sortby</code> template is stamped out for each type of lambda. </p> <p>I haven't measured performance. Will all this code slow it down significantly with a lot of boilerplate and indirection, or is it just code size that suffers? </p> <p><strong>EDIT</strong>: Benchmark data has <a href="https://codereview.stackexchange.com/a/235215/212940">now been added below</a>.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;ostream&gt; #include &lt;string&gt; #include &lt;vector&gt; struct Employee { int id; std::string firstname; std::string lastname; int yob; [[nodiscard]] int getAge() const noexcept { return 2020 - yob; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const Employee&amp; e) { return stream &lt;&lt; e.id &lt;&lt; ", " &lt;&lt; e.firstname &lt;&lt; ", " &lt;&lt; e.lastname &lt;&lt; ", " &lt;&lt; e.yob &lt;&lt; ", " &lt;&lt; e.getAge(); } }; namespace os::algo { // the following 6 lines make it possible template &lt;typename Container, typename Member, typename Comparison = std::less&lt;&gt;&gt; void sortby(Container&amp; c, Member&amp;&amp; m, Comparison comp = Comparison()) { std::sort(c.begin(), c.end(), [&amp;m, &amp;comp](const auto&amp; a, const auto&amp; b) { return comp(std::invoke(m, a), std::invoke(m, b)); }); } } // namespace os::algo int main() { using os::algo::sortby; auto employees = std::vector&lt;Employee&gt;{ {1, "James", "Smith", 2008}, {2, "John", "Jones", 1998}, {3, "Sarah", "Evans", 1968}, {4, "Michelle", "Harris", 1978}, }; // BEFORE: This is what's required with normal STL calls std::sort(employees.begin(), employees.end(), [](const auto&amp; a, const auto&amp; b) { return a.firstname &lt; b.firstname; }); // AFTER: and now we can do this... // the easy part -- no begin(), end() // trivial, terse sorting by any member field sortby(employees, &amp;Employee::firstname); // trivially specify sort direction sortby(employees, &amp;Employee::yob, std::greater&lt;&gt;()); // can use getters too sortby(employees, &amp;Employee::getAge, std::greater&lt;&gt;()); for (const auto&amp; e: employees) std::cout &lt;&lt; e &lt;&lt; "\n"; // std::sort is but one example. The same technique applies to any STL algorithm return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T10:03:28.333", "Id": "459481", "Score": "0", "body": "Prefer `std::begin(c)` over `c.begin()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T11:22:01.430", "Id": "459485", "Score": "0", "body": "@G.Sliepen Thanks! I find that interesting. I have always wondered which is preferred and for what reason, but not found any content. Is your advice just for this case where we don't know what kind of container we have, or in general?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T11:27:42.280", "Id": "459487", "Score": "0", "body": "Really what I want to say in the template signature is: \n\na) `Container` is really a `Container<T>` b) you can call `begin/end` on `Container` and c) `std::invoke(Member, T)` gives me some type `F` (the field type), which when you call `Comparison(F,F)` you get a `bool`. And throw readable compile errors (or ignore the template) if any of the above are not true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T12:01:28.037", "Id": "459490", "Score": "0", "body": "The main reason for using `std::begin()` and `std::end()` is that they allow iteration over containers that don't implement the class member functions `begin()` and `end()`, such as regular C-style arrays. You can overload `std::begin()` and `std::end()` to provide iteration over classes that don't provide that functionality natively." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T12:04:53.593", "Id": "459491", "Score": "0", "body": "OK, yes, so in generic code, where we don't know what the container is (such as here) we should use `std::begin`. Makes. sense. But I shouldn't change the code above right ;-) ? Or because there are no answers yet, I should? Wouldn't want to upset any community police." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T12:31:25.837", "Id": "459493", "Score": "0", "body": "Don't change the code. It's also instructive for others to see the original code and the discussion around it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:04:15.233", "Id": "459494", "Score": "0", "body": "OK. No one will ever see that in the comments without an answer, I thought. but if you will write one, then that can be included there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:19:47.160", "Id": "459506", "Score": "0", "body": "@G.Sliepen I just tried this: Didn't work for me. Can you really use `std::begin()` on a C-style array? It only works when the array was declared in the same scope as you call `std::begin()` (or a ranged for loop in my case, which is juts syntactic sugar for that). As soon as you pass the C-style array to a function, it decays to a pointer, and you can't call `std::begin()` anymore. This is the state of the union since Kernigan and Ritchie. Don't think modern C++ has managed to change that? I don't want to pass sizes and use for(int i=0...) style loops. So `std::array<>` does add value here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:36:21.487", "Id": "459507", "Score": "0", "body": "It indeed only works if it's declared in the same scope, as soon as you pass it to a function it decays to a pointer, even in modern C++. I mentioned it to illustrate that `std::begin()` and `std::end()` are compatible with a lot more than just the STL containers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T11:43:05.520", "Id": "460249", "Score": "0", "body": "The type of an array is preserved when it's passed by reference and the size is in the signature, e.g. `template<std::size_t N> void f(const int (&array)[N])`." } ]
[ { "body": "<p>Indeed, your <code>sortby</code> <em>when used in the style shown, with data members,</em> will not be quite as fast as if you used the STL with a lambda. Look at the difference in assembly between</p>\n\n<pre><code>struct Date {\n int year, month, day;\n};\n\nvoid test1(std::array&lt;Date, 100&gt;&amp; a) {\n sortby(a, &amp;Date::month);\n sortby(a, &amp;Date::year);\n}\n\nvoid test2(std::array&lt;Date, 100&gt;&amp; a) {\n sortby(a, [](const auto&amp; x){ return x.month; });\n sortby(a, [](const auto&amp; x){ return x.year; });\n}\n</code></pre>\n\n<p>In <code>test1</code>, the difference between <code>&amp;Date::month</code> and <code>&amp;Date::year</code> is encoded in the runtime <em>value</em> of the member pointer. In <code>test2</code>, the difference is encoded in the compile-time <em>type</em> of the lambda. So <code>test2</code> instantiates two different template instantiations, whereas <code>test1</code> calls the same instantiation twice with different inputs. (But if both calls are inlined, the optimizer <em>might</em> be able to hide the difference.)</p>\n\n<p>However, this is not the fault of your <code>sortby</code> helper; it's the fault of using member pointers instead of custom lambdas. You can observe the same differences happening if you call <code>std::sort</code> with a function pointer, versus calling <code>std::sort</code> with an instance of some bespoke type such as <code>std::less&lt;&gt;</code> or <code>std::greater&lt;&gt;</code>.</p>\n\n<hr>\n\n<p>You pass <code>Member&amp;&amp; m</code> by forwarding reference, but then you use it as an lvalue (without forwarding it again). I think I've mentioned before: if you don't intend to forward an argument, then you shouldn't be using a forwarding reference with it. In this case, you just need to look at the value of the member-pointer <code>m</code> without modifying it, so <code>const Member&amp; m</code> would be appropriate. Or, since member data pointers and custom lambdas are both going to be small trivial types, and member function pointers are also trivial types (if slightly larger), we should seriously think about taking <code>Member m</code> directly by value.</p>\n\n<p>Notice that you already take <code>Comparison comp</code> by value.</p>\n\n<p>The comment about using <code>std::begin(c)</code> over <code>c.begin()</code> is accurate. If you want your <code>sortby</code> template to work for C-style arrays, then you should use <code>std::begin(c)</code>. Remember, you can't pass arrays <em>by value</em> (they decay to pointers) — but you can certainly pass arrays <em>by reference</em>, and that's what you're doing here when you <code>sortby</code> an array \"in place.\"</p>\n\n<p>The vast majority of lambdas you write should just take <code>[&amp;]</code>. I don't see any benefit to writing <code>[&amp;m, &amp;comp]</code> when it ends up meaning the same thing as <code>[&amp;]</code>.</p>\n\n<p>So I'd write your helper like this:</p>\n\n<pre><code>template&lt;class Container, class Member, class Comparison = std::less&lt;&gt;&gt;\nvoid sortby(Container&amp; c, Member m, Comparison comp = Comparison()) {\n using std::begin; using std::end;\n std::sort(begin(c), end(c), [&amp;](const auto&amp; a, const auto&amp; b) {\n return comp(std::invoke(m, a), std::invoke(m, b));\n });\n}\n</code></pre>\n\n<p><code>using std::begin;</code> is the \"<code>std::swap</code> two-step,\" familiar to anyone who's used <code>std::swap</code> before. It means \"consider using <code>std::begin</code> for unqualified calls, but if someone has provided a better-matching ADL version of <code>begin</code>, then we'll happily use that version instead.\" This is certainly overkill — I mean we could just write <code>std::begin(c), std::end(c),</code> — but the two-step is how all the <a href=\"http://eel.is/c++draft/iterator.range#1.sentence-2\" rel=\"nofollow noreferrer\">standard customization points</a> are meant to be used as far as I know, so we might as well stick to it.</p>\n\n<p>Vice versa, I would personally shy away from using the two-step in <code>main</code> —</p>\n\n<pre><code>using os::algo::sortby;\n</code></pre>\n\n<p>This seems more confusing than helpful. Are you expecting that someone else <em>might</em> provide a better-matching ADL <code>sortby</code>? If not, then <code>sortby(x,y,z)</code> will always mean <code>os::algo::sortby(x,y,z)</code>... and if it <em>is</em> <code>os::algo::sortby</code>, <a href=\"https://www.gsarchive.net/mikado/webopera/mk212d.html\" rel=\"nofollow noreferrer\">why not say so?</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T08:29:56.813", "Id": "460232", "Score": "0", "body": "Thanks! Super helpful again. Re forward ref: Yes this was written before the other question (or at least before your answer), so yes I have learned that lesson. The points about ADL and begin/end are useful too. I just tend to assume that c-style arrays will decay, if not now, then later when the code gets refactored in some way. But the general point is obviously still true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T08:31:27.313", "Id": "460233", "Score": "0", "body": "re [&] vs [&m,&comp] I understand it is not different, but I guess I felt that in a \"library style helper\" it is worth \"documenting\" and constraining what we are using. [&] always feels like a bit like a \"broad sweep\" to me. In \"application code\" I tend to write [&] because it is terser, unless the scope is more than say 10-15 lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T08:36:58.180", "Id": "460234", "Score": "0", "body": "The comments about ADL for os::algo::sortby are interesting. I didn't write `using os::algo::sortby` for any ADL reason (probably because I am not yet fully aware of all ADL implications yet). I wrote it quite simply for DRY terseness. My idea was, if I am going to call `sortby` more than say 2-3 times in a single scope and it has a somewhat verbose fully qualified name -> write one `using` statement and then don't repeat the namespace part. Is that flawed? I understand why statements like `using namespace std` are very bad. Is this too far in that direction? Should I stick to writing FQNs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T08:50:45.310", "Id": "460237", "Score": "0", "body": "Finally in the discussion about code size / speed ( I will do some more benchmarking and report back) it occurred to me that if code size were a concern then one could consider using type erasure https://quuxplusone.github.io/blog/2019/03/18/what-is-type-erasure/ for the callback inside `sortby`. This will probably be slower (?) due to virtual dispatch inside the type erased type, but might be a reasonable tradeoff in some situations. Although the virtual call would end up being once/twice per comparison right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T11:50:46.013", "Id": "460250", "Score": "0", "body": "benchmark data has been added below: https://codereview.stackexchange.com/a/235215/212940" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T10:54:25.020", "Id": "461248", "Score": "0", "body": "Why not `using std::begin, std::end;`?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T03:22:03.580", "Id": "235205", "ParentId": "234887", "Score": "4" } }, { "body": "<p>Some benchmarking data as promised:</p>\n\n<p>Cut to the chase, results:</p>\n\n<pre><code>--------------------------------------------------------\nBenchmark Time CPU Iterations\n--------------------------------------------------------\nstl/100 3940 ns 3940 ns 173735\nmember/100 4756 ns 4756 ns 147187\nlambda/100 3979 ns 3979 ns 177405\ngetter/100 8768 ns 8768 ns 79665\nstlgetter/100 3993 ns 3993 ns 179926\n</code></pre>\n\n<p>Summary: </p>\n\n<ul>\n<li>Passing a member variable to the helper does incur a cost (~15-20%, and ~ 10% for bigger containers) as predicted by @Quuxplusone and using a lambda (ie fixing the offset in a distinct compile time type) does get rid of that extra cost (back to normal STL levels). </li>\n<li>Slight shock (for me at least) was that passing the address of a getter into our helper slows things down by ~2x. Put in an extra benchmark with the STL using the getters, and as expected that is ~nil cost compared to base case. </li>\n</ul>\n\n<p>Attempt at a conclusion: </p>\n\n<ul>\n<li>This is not a zero cost abstraction.</li>\n<li>However, for the most commonly requested use-case (eg slack/cpplang query), which is \"sort by this public member\", there is \"only\" a 15-20% (and ~10% for bigger containers) penalty relative to a custom lambda, but this has a code size benefit and is not actually caused by the abstraction as such (but to do with static/runtime resolution of the \"address\"). </li>\n<li>passing \"getters\" seems to have a weirdly large costs, needs further investigation. </li>\n</ul>\n\n<p>Here is the benchmark code (using Google Benchmark):</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;benchmark/benchmark.h&gt;\n#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;random&gt;\n#include &lt;vector&gt;\n\nstruct Date {\n int year, month, day;\n [[nodiscard]] int get_year() const noexcept { return year; }\n [[nodiscard]] int get_month() const noexcept { return month; }\n [[nodiscard]] int get_day() const noexcept { return day; }\n};\n\nnamespace os::algo {\n\n// the following 6 lines make it possible\ntemplate &lt;typename Container, typename Member, typename Comparison = std::less&lt;&gt;&gt;\nvoid sortby(Container&amp; c, const Member&amp; m, const Comparison&amp; comp = Comparison()) {\n std::sort(std::begin(c), std::end(c), [&amp;](const auto&amp; a, const auto&amp; b) {\n return comp(std::invoke(m, a), std::invoke(m, b));\n });\n}\n\n} // namespace os::algo\n\nstd::vector&lt;Date&gt; get_random_dates(std::size_t size) {\n std::random_device rnd_device;\n std::mt19937 engine{1}; // rnd_device()};\n std::uniform_int_distribution&lt;int&gt; year_dist{1940, 2025};\n std::uniform_int_distribution&lt;int&gt; month_dist{1, 12};\n std::uniform_int_distribution&lt;int&gt; day_dist{1, 28}; // ignore complexities\n\n auto dates = std::vector&lt;Date&gt;{};\n dates.reserve(size);\n for (std::size_t i = 0; i &lt; size; ++i) {\n dates.push_back({year_dist(engine), month_dist(engine), day_dist(engine)});\n }\n return dates;\n}\n\nvoid stl(benchmark::State&amp; state) {\n auto ds = get_random_dates(state.range(0));\n for (auto _: state) {\n std::sort(ds.begin(), ds.end(), [](const auto&amp; a, const auto&amp; b) { return a.month &lt; b.month; });\n std::sort(ds.begin(), ds.end(), [](const auto&amp; a, const auto&amp; b) { return a.year &lt; b.year; });\n }\n}\nBENCHMARK(stl)-&gt;Arg(100);\n\nvoid member(benchmark::State&amp; state) {\n auto ds = get_random_dates(state.range(0));\n for (auto _: state) {\n os::algo::sortby(ds, &amp;Date::month);\n os::algo::sortby(ds, &amp;Date::year);\n }\n}\nBENCHMARK(member)-&gt;Arg(100);\n\nvoid lambda(benchmark::State&amp; state) {\n auto ds = get_random_dates(state.range(0));\n for (auto _: state) {\n os::algo::sortby(ds, [](const auto&amp; x) { return x.month; });\n os::algo::sortby(ds, [](const auto&amp; x) { return x.year; });\n }\n}\nBENCHMARK(lambda)-&gt;Arg(100);\n\nvoid getter(benchmark::State&amp; state) {\n auto ds = get_random_dates(state.range(0));\n for (auto _: state) {\n os::algo::sortby(ds, &amp;Date::get_month);\n os::algo::sortby(ds, &amp;Date::get_year);\n }\n}\nBENCHMARK(getter)-&gt;Arg(100);\n\nvoid stlgetter(benchmark::State&amp; state) {\n auto ds = get_random_dates(state.range(0));\n for (auto _: state) {\n std::sort(ds.begin(), ds.end(), [](const auto&amp; a, const auto&amp; b) { return a.get_month() &lt; b.get_month(); });\n std::sort(ds.begin(), ds.end(), [](const auto&amp; a, const auto&amp; b) { return a.get_year() &lt; b.get_year(); });\n }\n}\nBENCHMARK(stlgetter)-&gt;Arg(100);\n\n</code></pre>\n\n<p>I also did a quick study on code size. I compiled a stripped down version of above code (no random gen, and no google benchmark lib) using <code>clang-9</code> with <code>-O3</code> and checked the binary executable size. I commented out all sorting for the base case and then uncommented each one of the methods in turn. As well as binary size I recorded \"lines of assembly\" (LOA) <a href=\"https://godbolt.org/z/6goZwo\" rel=\"nofollow noreferrer\">shown in godbolt</a>. </p>\n\n<p>Results:</p>\n\n<pre><code>// base size without any sort function: 17248 bytes / 219 LOA\n\n// size with stl: 21864 bytes / 1913 LOA\n\n// size with member: 17984 bytes / 970 LOA\n\n// size with lambda: 22072 bytes / 1941 LOA\n\n// size with getter: 22656 bytes / 1128 LOA\n\n</code></pre>\n\n<p>The only anomaly is the highest binary size and very low LOA for \"getter\". But otherwise this makes sense. Generally:</p>\n\n<pre><code>\"Info encoded in Fixed types\" (ie lambdas) =&gt; \nbigger binary =&gt; \nhigher LOA =&gt; \nand (from above) faster performance \n</code></pre>\n\n<p>This \"code size conclusion\" is quite different from my initial impression in the original post. There I thought that the <code>sortby</code> helper was increasing code size. It is not. If that was really happening it was a compiler optimisation artefact. This more proper test shows the logical conclusion just above. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T16:06:07.060", "Id": "460284", "Score": "0", "body": "Getters having a bigger cost is not surprising: Lack of inlining means the function-call-protocol with registers preserved, reserved, potentially used and the like, as well as stack-interactions has to be adhered to. Also, there is the call and return itself. A different approach you might want to compare is building a comparator from a projection and a matching comparator, the latter potentially defaulted to `std::less<>`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T11:49:28.030", "Id": "235215", "ParentId": "234887", "Score": "1" } } ]
{ "AcceptedAnswerId": "235205", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T00:48:42.597", "Id": "234887", "Score": "5", "Tags": [ "c++", "algorithm", "c++17" ], "Title": "More ergonomic / convenient STL algorithm calls -- sort order & member field extraction using std::invoke" }
234887
<p>I'm working on a React app with websocket. In this app there is a socket event listener which returns 3 types: <code>add</code>, <code>change</code>, and <code>remove</code>. Certain state update operations will be performed based on the type received.</p> <p>Do I properly mutate the <code>users</code> state? I'm not sure whether it follows the principle of React regarding updating states.</p> <pre><code>ws.on("connect", () =&gt; { console.log("connected"); ws.emit("load"); }); ws.on("feed", response =&gt; { const prev = response.old_val; const next = response.new_val; const type = response.type; setUsers(users =&gt; { let currentUser = [...users]; let index; switch (type) { case "add": return [...users, next]; case "change": index = users.findIndex(u =&gt; u.id === next.id); currentUser[index].name = next.name; return currentUser; case "remove": index = users.findIndex(u =&gt; u.id === prev.id); currentUser.splice(index, 1); return currentUser; default: return currentUser; } }); }); </code></pre>
[]
[ { "body": "<p>This seems reasonable. The most important part is that you do not mutate the react state in-place. By doing <code>let currentUser = [...users];</code> you copy the state and instead mutate the copy, then assign it as the updated state.</p>\n\n<p>An alternative would be to use <code>.map</code> and <code>.filter</code> to make your changes. I see this pattern more often than the state copy approach.</p>\n\n<p>Example:</p>\n\n<pre><code>ws.on(\"feed\", response =&gt; {\n const { new_val: next, type } = response; // Use destructuring and inline renaming.\n\n setUsers(users =&gt; {\n switch (type) {\n case \"add\":\n return [...users, next];\n\n case \"change\":\n return users.map(u =&gt; {\n // Only change the user specified in the message\n if (u.id === next.id) return {...u, name: next.name } \n return u;\n // or return users.map(u =&gt; u.id !== next.id ? u : ({...u, name: next.name})) if you prefer one-liners\n })\n\n case \"remove\":\n return users.filter(u =&gt; u.id !== next.id);\n\n default:\n return users;\n }\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T09:03:40.087", "Id": "235154", "ParentId": "234891", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T03:31:33.267", "Id": "234891", "Score": "2", "Tags": [ "javascript", "react.js", "websocket" ], "Title": "Updating state with React and Websockets" }
234891
<p>I have this piece of code that is used to export an Excel file using Laravel-Excel. But I have doubts about it for the long run. Can the server handle it if there are a hundred requests?</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace App\Exports; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\WithHeadings; use Carbon\Carbon; use Carbon\CarbonPeriod; use Illuminate\Support\Facades\DB; use Illuminate\Support\Arr; class DailyGeneralSheetExport implements FromCollection, WithHeadings { use Exportable; public function __construct(array $request, int $diid, int $igid, str $date) { $this-&gt;request = $request; $this-&gt;diid = $diid; $this-&gt;igid = $igid; $this-&gt;date = $date; } public function collection() { $dt = Carbon::parse($this-&gt;date); $endDt = Carbon::parse($this-&gt;date)-&gt;lastOfMonth(); $period = CarbonPeriod::create($this-&gt;date, $endDt); $ipid = array_pluck($this-&gt;request, 'ip_id'); $inidArr = array_pluck($this-&gt;request, 'in_id'); $inid = array_unique($inidArr); $collection = []; foreach ($period as $key =&gt; $eachDate) { $reading = DB::table('instrument') -&gt;where('iv_inid', $inid) -&gt;whereIn('iv_ipid', $ipid) -&gt;whereDate('iv_date', $eachDate) -&gt;whereIn('iv_status', ['N', 'Y', 'A']) -&gt;orderBy('iv_date')-&gt;get()-&gt;toArray(); $row = array($eachDate-&gt;format('d/m/Y')); foreach ($reading as $columnKey =&gt; $columnValue) { array_push($row, $columnValue-&gt;iv_reading); } array_push($collection, $row); } return collect($collection); } /** * @return array */ public function headings(): array { $sheet_header = Arr::pluck($this-&gt;request, 'ip_label'); return Arr::prepend($sheet_header, 'Date'); } } </code></pre> <p>As you can see I have to create an array for one month and this makes me worry if this will impact the performance. And for some reason, I feel I wrote code that is not elegant as Laravel does. How do I optimize it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:07:27.210", "Id": "459528", "Score": "0", "body": "Have you tried load testing to see what happens with N hits at once?" } ]
[ { "body": "<p>The code looks OK. You may want to move the query outside of the <code>foreach</code> loop and group the results afterwards. But the <code>foreach</code> loop is limited to the number of days in a month, so I don't think that will do very much. That may cause the application to use more memory.</p>\n\n<p>Therefore, I advise testing if the performance is indeed an issue. If so you might want to delegate creating the export to a queue. Queues in Laravel are not hard to implement (surprise!) </p>\n\n<p><a href=\"https://laravel.com/docs/7.x/queues\" rel=\"nofollow noreferrer\">Laravel Queues Documentation 7.x</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T03:57:36.053", "Id": "468784", "Score": "0", "body": "Welcome to CodeReview@SE. This looks an assessment of a man-machine interface issue. I am not sure this provides me with an insight about the code presented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-17T15:03:38.653", "Id": "468869", "Score": "0", "body": "True, but I did not see any chance for optimising the code - it looks great." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-16T21:30:49.187", "Id": "239022", "ParentId": "234894", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T08:36:14.793", "Id": "234894", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "Export an Excel file using Laravel-Excel" }
234894
<p>I have implemented Binary search code for a given sorted array, written unit test too, Please review my BST unit test code and let me know your comments for improvements.</p> <pre><code>class BinarySearch { public int binSearch(int[] sortedArray, int key) { return search(0, sortedArray.length - 1, key, sortedArray); } private static int search(int start, int end, int key, int[] sortedArray) { int mid = start + ((end-start)/2); if (mid &gt;= start &amp;&amp; mid &lt;= end) { if (sortedArray[mid] == key) { return mid; } else if (sortedArray[mid] &gt; key) { return search(start, mid-1, key, sortedArray); } else if(sortedArray[mid] &lt; key){ return search(mid+1, end, key, sortedArray); } } return -1; } } public class BinarySearchTest { private BinarySearch binarySearchCUT; private static final int UNSUCCESSFUL = -1; @Before public void setUp(){ binarySearchCUT = new BinarySearch(); } @Test public void testShouldReturnUnsuccessfulOnEmptyArray() { assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{}, 0)); } @Test public void testShouldReturnUnsuccessfulOnLeftBound() { assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 0)); } @Test public void testShouldReturnUnsuccessfulOnRightBound() { assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 101)); } @Test public void testShouldReturnSuccessfulOnLeftBound() { assertEquals(0, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 1)); } @Test public void testShouldReturnSuccessfulOnRightBound() { assertEquals(12, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 100)); } @Test public void testShouldReturnSuccessfulOnMid() { assertEquals(7, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 19)); } @Test public void testShouldReturnSuccessfulOnMidGreaterThanGivenNumber() { assertEquals(5, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 12)); } @Test public void testShouldReturnSuccessfulOnMidLesserThanGivenNumber() { assertEquals(10, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 69)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:21:26.507", "Id": "459630", "Score": "1", "body": "DRY: You could create a helper-method `testSearch(int[] arr, int searchFor, int expected)` and put your test-array into a constant. The individual tests would then just be `testSeach(normArray, 4, normArray[4])` much shorter to read and reason about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:29:32.617", "Id": "459671", "Score": "0", "body": "Consider using `Optional`s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T06:40:22.630", "Id": "459712", "Score": "0", "body": "I have to disagree with @Falco . In unit testing, repeating yourself is fine. Martin Fowler actually mentions this in his Refactoring book, that repetition and copy-paste is acceptable in unit tests. (Seriously, read that book!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T09:16:00.820", "Id": "459724", "Score": "0", "body": "@markspace I did read the Fowler book - but I think there is a difference between acceptable and recommended. Unit Tests should be easy to read, understand, refactor and adapt. If repeating yourself makes the Tests more readable and easier to adapt it is fine. But in this case I think a more concise signature would make it easier to verify all Tests actually do what they're supposed to and prevent copy&paste errors with future tests." } ]
[ { "body": "<p>Your code looks good but just wanted to suggest below</p>\n\n<ol>\n<li><code>if (mid &gt;= start &amp;&amp; mid &lt;= end)</code> - this condition will never fail because <code>mid</code> will either equal to <code>start</code> or <code>end</code> so you can skip this because this is taking unnecessary condition check time</li>\n<li>You can check if <code>start</code> is less than or equal to <code>end</code> otherwise you will end up with wrong <code>mid</code> value. By putting this condition method will not calculate <code>mid</code> value but return -1 and it will improve performance.</li>\n</ol>\n\n<p>`</p>\n\n<pre><code>private static int search(int start, int end, int key, int[] sortedArray) {\n if(start &lt;= end) {\n int mid = start + ((end - start) / 2);\n //if (mid &gt;= start &amp;&amp; mid &lt;= end) {\n if (sortedArray[mid] == key) {\n return mid;\n } else if (sortedArray[mid] &gt; key) {\n return search(start, mid - 1, key, sortedArray);\n } else if (sortedArray[mid] &lt; key) {\n return search(mid + 1, end, key, sortedArray);\n }\n //}\n }\n return -1;\n}\n</code></pre>\n\n<p><span class=\"math-container\">`</span></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:13:50.913", "Id": "234899", "ParentId": "234897", "Score": "6" } }, { "body": "<h2>BinarySearch</h2>\n\n<p>The <code>BinarySearch</code> class should be <code>public</code> since it contains utility methods that are generally useful. To do this, write <code>public class BinarySearch</code> instead of <code>class BinarySearch</code>.</p>\n\n<p>The <code>binSearch</code> method should be <code>static</code> since it does not access any fields from the <code>BinarySearch</code> class. After all, that class doesn't have any fields that could be accessed. To do this, write <code>public static int binSearch</code> instead of <code>public int binSearch</code>.</p>\n\n<p>When you make the <code>binSearch</code> method static, you no longer need the <code>new BinarySearch()</code> in the unit test. This is good since it sounds weird to have a \"new binary search\". It's confusing to hear this, since \"binary search\" is an algorithm and not a countable thing. It makes more sense to speak of \"<em>the</em> binary search algorithm\", avoiding the word \"new\". On the other hand, \"new house\" or \"new sheet of paper\" sounds much more natural.</p>\n\n<hr>\n\n<p>The helper method currently is:</p>\n\n<pre><code>private static int search(int start, int end, int key, int[] sortedArray) {\n</code></pre>\n\n<p>The order of the parameters is not the usual one. Usually the array comes first, before its indexes. In this case, this would mean:</p>\n\n<pre><code>private static int search(int[] sortedArray, int start, int end, int key) {\n</code></pre>\n\n<hr>\n\n<p>When you compare your code with <a href=\"https://github.com/openjdk/jdk13/blob/dcd4014cd8a6f49a564cbb95387ad01a80a20bed/src/java.base/share/classes/java/util/Arrays.java#L1848\" rel=\"nofollow noreferrer\">the predefined Arrays.binarySearch</a> and <a href=\"https://github.com/openjdk/jdk13/blob/dcd4014cd8a6f49a564cbb95387ad01a80a20bed/src/java.base/share/classes/java/util/Arrays.java#L1909\" rel=\"nofollow noreferrer\">the helper function</a>, you can see that the code is quite similar, which is a good sign.</p>\n\n<p>One useful thing that the predefined <code>Arrays.binarySearch</code> does is that if the element is not found, it returns a hint about the index where it would be found. This is useful to see the closest existing value.</p>\n\n<h2>BinarySearchTest</h2>\n\n<p>Your existing unit tests look good. You can leave out the word <code>test</code> at the beginning of the method names to make the names a little shorter. They are quite long, but that's ok.</p>\n\n<p>There are test cases missing:</p>\n\n<ul>\n<li>An element from the middle cannot be found, for example 5 in <code>[1, 2, 6, 10]</code>.</li>\n<li>The array contains duplicate values, for example 3 in <code>[1, 2, 3, 3, 3, 3, 3, 3, 3]</code>.</li>\n</ul>\n\n<p>In the latter case, it is unspecified whether <code>binSearch</code> should return 2 or 3 or any other index. All you can do in your unit test is to check that <span class=\"math-container\">`</span>array[binSearch(array, key)] == key.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:08:13.313", "Id": "459622", "Score": "2", "body": "`it returns the index where it would be found.` But then you lose information about whether or not the object is included or not. The C# standard library solves this by returning the binary complement of the index (which would be a negative number)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:34:11.627", "Id": "459649", "Score": "0", "body": "@JAD That's exactly what Java is doing as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:05:23.783", "Id": "459713", "Score": "0", "body": "Well look at that. I initially misread `return -(low + 1);` as if it would just return `-1`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:43:13.960", "Id": "234900", "ParentId": "234897", "Score": "11" } }, { "body": "<p>I have some suggestions for you.</p>\n\n<p>1) In the <code>search</code> method, extract the <code>sortedArray[mid]</code> into a variable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nint currentMid = sortedArray[mid];\n\nif (currentMid == key) {\n//[...]\n} else if (currentMid &gt; key) {\n//[...]\n} else if(currentMid &lt; key){\n//[...]\n}\n</code></pre>\n\n<p>For the array part, instead of passing an array, you can use the <code>varargs</code>. In my opinion, it will be easier to test since you don’t need to create a new array each time, but it can be uglier since the other parameters are also integers.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class BinarySearchTest {\n private BinarySearch binarySearchCUT;\n private static final int UNSUCCESSFUL = -1;\n\n @Before\n public void setUp(){\n binarySearchCUT = new BinarySearch();\n }\n\n @Test\n public void testShouldReturnUnsuccessfulOnEmptyArray() {\n assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(0));\n }\n\n @Test\n public void testShouldReturnUnsuccessfulOnLeftBound() {\n assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(0, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n @Test\n public void testShouldReturnUnsuccessfulOnRightBound() {\n assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(101, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n @Test\n public void testShouldReturnSuccessfulOnLeftBound() {\n assertEquals(0, binarySearchCUT.binSearch(1, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n @Test\n public void testShouldReturnSuccessfulOnRightBound() {\n assertEquals(12, binarySearchCUT.binSearch(100, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n @Test\n public void testShouldReturnSuccessfulOnMid() {\n assertEquals(7, binarySearchCUT.binSearch(19, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n @Test\n public void testShouldReturnSuccessfulOnMidGreaterThanGivenNumber() {\n assertEquals(5, binarySearchCUT.binSearch(12, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n @Test\n public void testShouldReturnSuccessfulOnMidLesserThanGivenNumber() {\n assertEquals(10, binarySearchCUT.binSearch(69, 1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100));\n }\n\n static class BinarySearch {\n public int binSearch(int key, int... sortedArray) {\n return search(0, sortedArray.length - 1, key, sortedArray);\n }\n\n private static int search(int start, int end, int key, int... sortedArray) {\n int mid = start + ((end-start)/2);\n\n if (mid &gt;= start &amp;&amp; mid &lt;= end) {\n int currentMid = sortedArray[mid];\n\n if (currentMid == key) {\n return mid;\n } else if (currentMid &gt; key) {\n return search(start, mid-1, key, sortedArray);\n } else if(currentMid &lt; key){\n return search(mid+1, end, key, sortedArray);\n }\n }\n\n return -1;\n }\n }\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T09:20:46.230", "Id": "459726", "Score": "0", "body": "I think a vararg signature makes the whole method less easy to read and understand. And since he is using the same Array in all tests, he could just put it in a constant in his test-class. I think it is more error prone this way - e.g. counting of indexes in the array is harder. I would prefer the Tests to read like this: `arr=[]...; assert(binSearch(arr[10], arr)).is(10)` it is easier to see what the expected result represents." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:06:16.827", "Id": "234908", "ParentId": "234897", "Score": "3" } }, { "body": "<p>One significant issue that has not been addressed in previous answers (all of which make excellent points), is that of deterministic behaviour.</p>\n\n<p>Your code is going to produce unexpected, and inconsistent results if the data in the sorted array is not unique. You clearly indicate that the array is pre-sorted, but you do not specify any restraints on the uniqueness of the values.</p>\n\n<p>It is standard in search routines to return the index of the <em>first</em> value in the array that matches the search term, but your code will return the index of \"some\" matching value.</p>\n\n<p>When you find the match, scan backwards to find the first instance..., so your match code would change from:</p>\n\n<blockquote>\n<pre><code>if (sortedArray[mid] == key) {\n return mid;\n} else if\n</code></pre>\n</blockquote>\n\n<p>to more like:</p>\n\n<pre><code>if (sortedArray[mid] == key) {\n // Ensure we return the first matching instance in the array.\n while (mid &gt; 0 &amp;&amp; sortedArray[mid -1] == key) {\n mid--;\n }\n return mid;\n} else if\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:10:17.770", "Id": "459684", "Score": "0", "body": "Interesting. Wouldn't that make the worst case running time O(N) [since if the array is all the same number, you'd loop through N/2 or so times] versus O(log(N))?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:18:47.840", "Id": "459685", "Score": "0", "body": "Note that Java at least specifically says: \" If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found. \" It's a valid thing to think about, but I disagree it's a universal standard to return the first (https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#binarySearch for Java, though counter point is https://docs.python.org/2/library/bisect.html shows how to get the first (or last) with bisect)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:32:05.510", "Id": "459688", "Score": "0", "body": "(Check of https://github.com/python/cpython/blob/master/Lib/bisect.py suggests slightly tweaking the algorithm will support getting the first element for uniques but still be O(log(N)))" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T13:27:13.997", "Id": "234945", "ParentId": "234897", "Score": "3" } } ]
{ "AcceptedAnswerId": "234900", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T12:05:20.517", "Id": "234897", "Score": "11", "Tags": [ "java", "unit-testing", "binary-search" ], "Title": "Binary Search given sorted array Unit test" }
234897
<pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;malloc.h&gt; void nl(void) { //function to print new line printf("\n"); } int** allocate(_size) { int** matrix=(int**)malloc(sizeof(int*)*_size); for(int i=0;i&lt;_size;i++) { matrix[i]=(int*)malloc(sizeof(int)*_size); } return matrix; } void scanMatrix(_matrix,_size) int** _matrix; { printf("Enter the values: "); for(int i=0;i&lt;_size;i++) { for(int j=0;j&lt;_size;j++) { scanf("%d",&amp;_matrix[i][j]); } } } void printMatrix(_matrix,_size) int** _matrix; { for(int i=0;i&lt;_size;i++) { for(int j=0;j&lt;_size;j++) { printf("%d ",_matrix[i][j]); } nl(); } } void swap(num1,num2) int* num1; int* num2; { *num1=*num1+*num2; *num2=*num1-*num2; *num1=*num1-*num2; } void rotateMatrix(_matrix,_size) int** _matrix; { for(int i=0;i&lt;_size;i++) { for(int j=i+1;j&lt;_size;j++) { swap(&amp;_matrix[i][j],&amp;_matrix[j][i]); } } for(int i=0;i&lt;_size;i++) { for(int j=0;j&lt;_size/2;j++) { swap(&amp;_matrix[i][j],&amp;_matrix[i][_size-1-j]); } } } main(argc,argv) const char** argv; { int size=0; printf("Enter the size of the square matrix: "); scanf("%d",&amp;size); int** matrix=allocate(size); scanMatrix(matrix,size); printMatrix(matrix,size); nl(); rotateMatrix(matrix,size); nl(); printMatrix(matrix,size); return 0; } </code></pre> <p>This code doesn't use extra memory and also uses run-time allocation using <code>malloc</code>. However, has a time complexity of O(n^2). How do I further optimise it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:04:18.543", "Id": "459495", "Score": "0", "body": "How did you come up with O(n^2)? I'd say it Is O(size^2)=O(n). Anyway why is `swap()` so complicated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:06:29.543", "Id": "459497", "Score": "1", "body": "Even Swap doesn't use extra memory. Regarding n, why do you say that n=size^2? Will you please elaborate? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:06:31.443", "Id": "459498", "Score": "1", "body": "Btw how do you call the syntax with function argument types defined after the function prototypes? I have never seen this syntax. How do I refer to it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:08:17.280", "Id": "459499", "Score": "1", "body": "Just search for Kernighan and Ritchie notation on Google. :) It isn't standard syntax and was used by Ritchie. I use it because I learnt C from first edition of `The C programming language`. Don't use it if possible :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:08:46.993", "Id": "459500", "Score": "2", "body": "Well I suppose n Is the number of elements in the matrix. Since the matrix Is square i Believe number of elements Is size^2 where size Is the size of edge of the square Matrix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T13:35:09.877", "Id": "459505", "Score": "0", "body": "However, it does keep your function signature compact. And, I find it easy to read:\nThe first line shows the variable names.\nFrom second line it shows type. Also, from what I heard (I am not sure about this), the compiler finds it easy to parse this syntax, especially, if it is passing its output to a 2 pass assembler. .... To all of you reading this, is it true?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:45:09.207", "Id": "459508", "Score": "3", "body": "@slepic anytime you say \\$\\mathcal O(n)\\$, you must define what you mean by \\$n\\$. Otherwise it’s not reliable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:47:07.413", "Id": "459509", "Score": "1", "body": "@slepic This is C using the Original K&R C. I was surprised that it still compiled I spent 2 years converting this kind of code to the ANSI standard in the 1990s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:48:33.553", "Id": "459510", "Score": "0", "body": "Awesome grit. BTW, is it true that this syntax works more efficient in 2 pass assembler?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T08:52:28.920", "Id": "459598", "Score": "1", "body": "@RollandIllig Which I did. Whats your point? Anyway. No. Not Always. In a formal document maybe. In an informal discussion where it Is obvious from context? Not necesary... You also dont Always define what you mean by \"+\". Only if you mean something non standard. It Is pretty Common that n in O(n) Stands for number of elements. And from the context it Is obvious that this Is the case. And btw if you wanted to object So much, why not object to OP? He didnt specify what n Is in the first place. Nevertheless we all somehow understood what He means...." } ]
[ { "body": "<blockquote>\n <p>has a time complexity of O(n^2).</p>\n</blockquote>\n\n<p>I think you are incorrectly using \"n\" as if it is the size of the n×n matrix.</p>\n\n<p>The \"n\" in O() notation refers to the total size of the input data.</p>\n\n<p>So, for a m×m matrix, the \"n\" value for complexity would be m<sup>2</sup>.</p>\n\n<p>Your algorithm is O(n).</p>\n\n<hr>\n\n<blockquote>\n <p>This code doesn't use extra memory</p>\n</blockquote>\n\n<p>Is there a specific reason for doing the swap trick the way you did rather than simply using the more obvious method with an <code>auto int temp;</code> on the stack?</p>\n\n<p><code>auto</code> memory is allocated on a stack, so it exists only during the invocation of the function.\nAfter that, it can be reused by other functions.\nUnless a function is called recursively, there's no cumulative problem with using temporary stack space; that's what it's for.</p>\n\n<p>And if an algorithm should ever actually require persistent storage, it would be done using <code>static</code> rather than <code>auto</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>This is C using the Original K&amp;R C.</p>\n</blockquote>\n\n<p>The biggest drawback to using that is that you don't get the benefit of typechecking, which was introduced in C89.</p>\n\n<p>The compiler won't notice any problem with this:</p>\n\n<pre><code>swap(&amp;_matrix[i][j],&amp;_matrix[j][i]);\nswap(_matrix[i][j],_matrix[j][i]);\nswap(\"me\", \"you\");\n</code></pre>\n\n<p>but at runtime things will fail.</p>\n\n<p>I hope you are at least using <code>lint</code> on the source to check for such problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T15:19:26.550", "Id": "459520", "Score": "0", "body": "You answered your own question . I wanted to use as less memory as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:02:48.347", "Id": "459653", "Score": "1", "body": "@RayButterworth could your comment be part of your review? if so, please edit it into your answer appropriately with enough context to explain how it pertains to code in question. Comments are not meant to be used for additional review and could be deleted at any time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:32:29.237", "Id": "459868", "Score": "1", "body": "@d4rk4ng31 The suggested swap here does not use more more memory than the posted code (`printMatrix()` easily runs much deeper on the stack) so the question remains as to why use this problematic swap. Perhaps one could ask, why think the original code saves memory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:41:10.520", "Id": "459870", "Score": "1", "body": "Ray, Given `scanf(\"%d\",&size);`, algorithm is O(size*size). I agree the prompt `printf(\"Enter the size of the square matrix: \");` does leave room for confusion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:55:40.067", "Id": "459873", "Score": "1", "body": "Hmmm \"This is C using the Original K&R C.\" and apparently newer features too with `for(int i=0;i<_size;i++)` vs. `int i; ... for(i=0;i<_size;i++)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T15:26:51.527", "Id": "459891", "Score": "1", "body": "@chux-ReinstateMonica says \"*algorithm is O(size*size)*\". Correct. The size of the input is also \"size*size\", not simply \"size\". The \"n\" in O(n) notation would be the same as n=size*size. But the original question used \"n\" as if it represented \"size\" rather than \"size*size\". If one triples the \"size\", nine times as much processing is needed, but the size of the input matrix will also be nine times larger, so the effect is linear, hence it is an O(n) algorithm." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T15:17:42.203", "Id": "234906", "ParentId": "234898", "Score": "5" } }, { "body": "<p>regarding: </p>\n\n<pre><code>void rotateMatrix(_matrix,_size) \n</code></pre>\n\n<ol>\n<li>do NOT use leading underscores for variable and/or parameter names. </li>\n<li>a function signature must have the variable types as part of the signature. </li>\n<li>when compiling, always enable the warnings, then fix those warnings</li>\n</ol>\n\n<p>regarding:</p>\n\n<pre><code>main(argc,argv)\n</code></pre>\n\n<p>there are two valid signatures for the <code>main()</code> function, the are:</p>\n\n<pre><code>int main( int argc, char *argv[] )\nint main( void )\n</code></pre>\n\n<p>the posted signature is missing the return type and the parameters are missing the needed typing</p>\n\n<p>regarding:</p>\n\n<pre><code>main(argc,argv)\nconst char** argv;\n</code></pre>\n\n<ol>\n<li>This is an obsolete method of writing a function signature, that was replaced back in the late '80s.</li>\n<li>some 20+ years ago, the 'default' of a untyped variable and/or function parameter defaulting to <code>int</code> was discarded.</li>\n</ol>\n\n<p>regarding:</p>\n\n<pre><code>void nl(void) { //function to print new line\nprintf(\"\\n\");\n}\n</code></pre>\n\n<p>this function should be deleted. Then when wanting to print a newline, use:</p>\n\n<pre><code>puts( \"\" );\n</code></pre>\n\n<p>regarding this kind of statement:</p>\n\n<pre><code>int** matrix=(int**)malloc(sizeof(int*)*_size);\n</code></pre>\n\n<ol>\n<li>in C, the returned type is <code>void*</code> which can be assigned to any pointer. Casting just clutters the code. </li>\n<li>when calling any of the heap allocation functions: <code>malloc()</code> <code>calloc()</code> and/or <code>realloc()</code>, always check (!=NULL) the returned value to assure the operation was successful. If not successful, then call <code>perror( \"malloc failed\" );</code> to inform the user of the problem.</li>\n</ol>\n\n<p>Regarding:</p>\n\n<pre><code>scanf(\"%d\",&amp;size);\n</code></pre>\n\n<p>when calling any of the <code>scanf()</code> family of functions, always check the returned value (not the parameter values) to assure the operation was successful. Those functions return the number of successful 'input format conversion specifiers'. In the current statement suggest:</p>\n\n<pre><code>if( scanf(\"%d\",&amp;size) != 1 )\n{\n fprintf( stderr, \"scanf for size failed\\n\" );\n exit( EXIT_FAILURE );\n}\n</code></pre>\n\n<p>for readability and ease of understanding: Please insert a reasonable space:</p>\n\n<ol>\n<li>inside parens</li>\n<li>inside braces</li>\n<li>inside brackets</li>\n<li>after commas</li>\n<li>after semicolons</li>\n<li>around C operators</li>\n</ol>\n\n<p>regarding the function: <code>scanMatrix()</code></p>\n\n<ol>\n<li>The posted code fails to keep the user informed of where in the matrix the next number entered will be placed nor when all the numbers have been entered.</li>\n</ol>\n\n<p>Suggest the calls to <code>nl()</code> in <code>main()</code> be moved to the end of the functions: <code>rotateMatrix()</code> and <code>printMatrix()</code> </p>\n\n<p>the posted code has several memory leaks as it fails to pass the pointers to each of the allocated memory areas to <code>free()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:14:33.747", "Id": "459865", "Score": "1", "body": "Note: \"there are two valid signatures for the main() function,\" --> true, yet an implementation can have others. \"or in some other implementation-defined manner.\" § 5.1.2.2.1 1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:24:44.743", "Id": "459867", "Score": "2", "body": "Minor: Using `printf(\"\\n\")`, `puts( \"\" )` or `putchar( '\\n' )` will emit the same efficient code with a good compiler. Best to code for clarity than concern about an only potential small linear optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-14T03:17:28.993", "Id": "461222", "Score": "0", "body": "@chux-ReinstateMonica, Only emits the same efficient code if optimization turned up." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:29:04.163", "Id": "234971", "ParentId": "234898", "Score": "3" } }, { "body": "<p>As memory management is one of the question's tags, writing swap that way is <strong>NOT</strong> the way to go:</p>\n\n<ul>\n<li>Harder to understand</li>\n<li>Risks overflows</li>\n<li>Is less efficient when looking at the compilation result: <a href=\"https://godbolt.org/z/iBlZ8n\" rel=\"nofollow noreferrer\">https://godbolt.org/z/iBlZ8n</a></li>\n</ul>\n\n<p>The first thing to change if memory management is a concern is the allocation of the matrix. Allocate it as a continuous chunk of memory, without extra pointers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T12:02:47.360", "Id": "459874", "Score": "1", "body": "UV for the good memory squeezing idea. Even remaining with the extra level `int **`, the allocation of pointers and `int`s could be done in one step, saving the allocation overhead. Its somewhat ugly code to do that, but does save real memory over OP's `_size + 1` allocations" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:53:33.313", "Id": "234972", "ParentId": "234898", "Score": "3" } } ]
{ "AcceptedAnswerId": "234971", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T12:32:30.340", "Id": "234898", "Score": "4", "Tags": [ "c", "matrix", "memory-management" ], "Title": "Rotate square matrix clockwise by 90degrees" }
234898
<p>I have this code to get the current timestamp so that I can save it as a part of the key in leveldb database.</p> <pre><code>export default function timestamp() { var [seconds, nanoseconds] = process.hrtime() return seconds * 1000000000 + nanoseconds } </code></pre> <p>I am wondering are there any downsides to use this function. Or are there any better alternatives to get current timestamp in node.</p>
[]
[ { "body": "<p>The shortest one:) </p>\n\n<pre><code>+new Date() \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-24T17:03:42.593", "Id": "462531", "Score": "0", "body": "This is what I use (well, I use `timestamp = Date.now()`) but based on OPs code they are looking for nanoseconds. Date.now() only gives you millisecond precision. While that's good enough for me to use as a DB key, for very fast transactions it might not work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T20:16:03.620", "Id": "235251", "ParentId": "234902", "Score": "0" } }, { "body": "<p>Your code does not work - <code>process.hrtime()</code> does not return with a timestamp of any useful form unless you compare it to another <code>process.hrtime()</code> in the same running program (typically used for measuring performance).</p>\n\n<p>From <a href=\"https://nodejs.org/api/process.html#process_process_hrtime_time\" rel=\"nofollow noreferrer\">the documentation</a>: </p>\n\n<blockquote>\n <p>These times are relative to an arbitrary time in the past, and not\n related to the time of day and therefore not subject to clock drift.\n The primary use is for measuring performance between intervals</p>\n</blockquote>\n\n<p>Bottom line is that the <code>arbitrary time in the past</code> could be anything, and not the same \"epoch\" as <code>new Date()</code>.</p>\n\n<p>There is no way in native JavaScript or Node (without making OS system calls through libraries, etc.) that I know of to get a more granular resolution than the millisecond times from Date.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T22:33:54.703", "Id": "235261", "ParentId": "234902", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:48:05.550", "Id": "234902", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "Function to get current timestamp in node" }
234902
<p>I created a small script for automating password store management and quickly searching and launching notes, shortcuts and documents through some keybindings that will execute the script.</p> <p>Script is working fine, but would very much appreciate feedback from more experienced folks on how to improve. I thought about using a configuration file instead of hard-coding the default directories, but not sure if really something worth it as its something that rarely changes.</p> <p>The same code from below can also be found at the <a href="https://github.com/fsilveir/dmenu-launch" rel="nofollow noreferrer">following repository</a>.</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse import subprocess from collections import namedtuple from distutils.spawn import find_executable def main(): check_req_utils() args = get_args() scheme = dmenu_setup(args) choice = dmenu_input(scheme) take_action(scheme, choice) def check_req_utils(): &quot;&quot;&quot;Checks if dmenu and other mandatory utilities can be found on target machine.&quot;&quot;&quot; utils = (['dmenu', 'gpg', 'pass', 'xclip', 'exo-open']) for util in utils: if find_executable(util) is None: print(&quot;ERROR: Util '{}' is missing, install it before proceeding! Exiting!&quot;).format(util) sys.exit(1) def check_dir_exist(scheme): &quot;&quot;&quot;Checks required directories are present.&quot;&quot;&quot; if os.path.exists(scheme.prefix) is False: print(&quot;ERROR: Required directory '{}' is missing! Exiting!&quot;).format(scheme.prefix) sys.exit(1) def get_args(): &quot;&quot;&quot;Return arguments from stdin or print usage instructions.&quot;&quot;&quot; parser = argparse.ArgumentParser(description='Simple dmenu launcher for passwords, notes and application shortcuts.') group = parser.add_mutually_exclusive_group() group.add_argument('--pass', dest='passw', action='store_true', help='Copy password from password store.') group.add_argument('--apps', action='store_true', help='Quick launches a desktop application with exo-open.') group.add_argument('--notes', action='store_true', help='Opens a text/markdown note from a given directory with exo-open.') group.add_argument('--search', action='store_true', help='Quick search and launch from a given directory with exo-open.') if not len(sys.argv) &gt; 1: parser.print_help() sys.exit(1) return parser.parse_args() def dmenu_setup(args): &quot;&quot;&quot;Setup dmenu font, color and size based on user's input.&quot;&quot;&quot; scheme = namedtuple( 'dmenu', [ 'target', # pass / apps/ notes / search 'prefix', # location prefix (base dir) 'suffix', # file extension to look for 'font', # dmenu font name and size 'nb','nf','sb','sf', # dmenu color: # n = normal / s = selected, # b = background, f = foreground ]) dmenu = &quot;&quot; if args.passw: dmenu = scheme( target='pass', prefix = os.getenv('PASSWORD_STORE_DIR',os.path.normpath(os.path.expanduser('~/.password-store'))), suffix=&quot;.gpg&quot;, font='Dejavu Sans Mono:medium:size=18', nb='#191919', nf='#ff0000', sb='#ff9318', sf='#191919', ) if args.apps: dmenu = scheme( target='apps', prefix=&quot;/usr/share/applications&quot;, suffix=&quot;.desktop&quot;, font='Dejavu Sans Mono:medium:size=18', nb='#191919', nf='#2e9ef4', sb='#2e9ef4', sf='#191919', ) if args.notes: dmenu = scheme( target='notes', prefix=os.path.expanduser('~/git/notes'), suffix=&quot;.md&quot;, font='Dejavu Sans Mono:medium:size=18', nb='#191919', nf='#2aa198', sb='#2aa198', sf='#191919', ) if args.search : dmenu = scheme( target='search', prefix=os.path.expanduser('~/work'), suffix=&quot;&quot;, font='Dejavu Sans Mono:medium:size=18', nb='#191919', nf='#2aa198', sb='#2aa198', sf='#191919', ) check_dir_exist(dmenu) return dmenu def dmenu_input(scheme): &quot;&quot;&quot;Builds dmenu list of options and returns the value selected by user.&quot;&quot;&quot; choices = [] for basedir, dirs , files in os.walk(scheme.prefix, followlinks=True): dirs.sort() files.sort() dirsubpath = basedir[len(scheme.prefix):].lstrip('/') for f in files: if f.endswith(scheme.suffix): full_path = os.path.join(dirsubpath, f.replace(scheme.suffix, '', -1)) choices += [full_path] args = [&quot;-fn&quot;, scheme.font, &quot;-nb&quot;, scheme.nb, &quot;-nf&quot;, scheme.nf, &quot;-sb&quot;, scheme.sb, &quot;-sf&quot;, scheme.sf, &quot;-i&quot; ] dmenu = subprocess.Popen(['dmenu'] + args, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) choice_lines = '\n'.join(map(str, choices)) choice, errors = dmenu.communicate(choice_lines.encode('utf-8')) if dmenu.returncode not in [0, 1] \ or (dmenu.returncode == 1 and len(errors) != 0): print(&quot;'{} {}' returned {} and error:\n{}&quot; .format(['dmenu'], ' '.join(args), dmenu.returncode, errors.decode('utf-8'))) sys.exit(1) choice = choice.decode('utf-8').rstrip() return (scheme.prefix + &quot;/&quot; + choice + scheme.suffix) if choice in choices else sys.exit(1) def take_action(scheme, choice): &quot;&quot;&quot;Copies password to clipboard, launch app or notes depending on user's input.&quot;&quot;&quot; if (scheme.target == &quot;pass&quot;): _target = (str(choice).replace(scheme.prefix,'',-1)) target = (_target[1:].replace(scheme.suffix,'',-1)) # Copies the username to middle button clipboard username = target.rsplit('/',1)[1].strip('\n') run_subprocess('echo &quot;{}&quot; | xclip'.format(username)) # Copy password to clipboard for 45 seconds run_subprocess('pass show -c &quot;{}&quot;'.format(target)) if (scheme.target == &quot;notes&quot;): run_subprocess('exo-open &quot;{}&quot;'.format(choice)) if (scheme.target == &quot;apps&quot;) or (scheme.target == &quot;search&quot;): run_subprocess('exo-open &quot;{}&quot;'.format(choice)) def run_subprocess(cmd): &quot;&quot;&quot;Handler for shortening subprocess execution.&quot;&quot;&quot; subprocess.Popen(cmd, stdin =subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,) # Main if __name__ == &quot;__main__&quot;: main() # EOF </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T14:52:48.947", "Id": "234903", "Score": "5", "Tags": [ "python", "console", "automation" ], "Title": "Simple dmenu launcher for passwords, docs, notes and application shortcuts (Python)" }
234903
<p>This my program to change the formatting of sheets in different folders. I have over 5000 files in one folder and it is taking up to three hrs for one folder and there are multiple subfolders in the main folder. I want to cut down this time to 10 mins or as fast as possible.</p> <pre><code>Sub loopAllSubFolderSelectStartDirectory() 'Another Macro must call LoopAllSubFolders Macro to start to procedure Call LoopAllSubFolders("D:\HTTP\") End Sub 'Don’t run the following macro, it will be called from the macro above: 'List all files in sub folders Sub LoopAllSubFolders(ByVal folderPath As String) Dim fileName As String Dim fullFilePath As String Dim numFolders As Long Dim folders() As String Dim i As Long Set wc = ActiveWorkbook If Right(folderPath, 1) &lt;&gt; "\" Then folderPath = folderPath &amp; "\" fileName = Dir(folderPath &amp; "*.*", vbDirectory) While Len(fileName) &lt;&gt; 0 If Left(fileName, 1) &lt;&gt; "." Then fullFilePath = folderPath &amp; fileName If (GetAttr(fullFilePath) And vbDirectory) = vbDirectory Then ReDim Preserve folders(0 To numFolders) As String folders(numFolders) = fullFilePath numFolders = numFolders + 1 Else Set wb = Workbooks.Open(fullFilePath) Dim sht As Worksheet Dim fnd As Variant Dim rplc As Variant fnd = "&lt;*&gt;" rplc = "" For Each sht In wb.Worksheets On Error GoTo 0 sht.Cells.Replace what:=fnd, Replacement:=rplc, _ LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _ SearchFormat:=False, ReplaceFormat:=False Next sht Workbooks("New file to be saved.xlsm").Sheets("Sheet1").Range("A1:T1").Copy 'Now, paste to y worksheet: wb.ActiveSheet.Range("A1").PasteSpecial Range("G2:H100").Cut Range("Q2:R100") Range("B2:F100").Cut Range("F2:J100") wb.ActiveSheet.Cells.EntireColumn.AutoFit 'With wb.ActiveSheet.Range("A1:T1").Interior ' .Pattern = xlSolid ' .PatternColorIndex = xlAutomatic ' .ThemeColor = xlThemeColorDark1 ' .TintAndShade = -0.149998474074526 ' .PatternTintAndShade = 0 ' End With ' With wb.ActiveSheet.Range("A1:T1").Font ' .ThemeColor = xlThemeColorLight2 ' .TintAndShade = 0 ' End With ' Range("A1:T1").Font.Bold = True wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), FileFormat:=xlExcel8 wb.Close True Kill fullFilePath 'Insert the actions to be performed on each file 'This example will print the full file path to the immediate window 'Debug.Print folderPath &amp; fileName End If End If fileName = Dir() Wend For i = 0 To numFolders - 1 LoopAllSubFolders folders(i) Next i End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:04:14.587", "Id": "459527", "Score": "0", "body": "Have you measured how much time a single sheet takes to reformat?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T18:07:26.953", "Id": "459532", "Score": "0", "body": "Are you modifying both Excel and CSV formats? Or are you just converting CSV to `xls`? Why are you using the older `xls` instead of the new `xlsx` format?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T18:07:53.477", "Id": "459533", "Score": "0", "body": "`Application.ScreenUpdating = False` is going to give you a massive boost in speed. [Optimize VBA Code to run Macros Faster](https://analysistabs.com/vba/optimize-code-run-macros-faster/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T18:10:14.593", "Id": "459534", "Score": "0", "body": "where to place it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:21:12.320", "Id": "459536", "Score": "0", "body": "The first line of code will work. There are other optimizations that can be made but it is hard to determine without sample files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:22:55.113", "Id": "459537", "Score": "0", "body": "@MFaizanFarooq use @ and then the person's username when replying to comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:56:17.677", "Id": "459538", "Score": "0", "body": "While `Application.ScreenUpdating = False` at the beginning of your code will certainly increase your execution speed, remember that most of your execution time will likely be outside of Excel's control: interacting with the file system. This is true particularly if some or all of the external files are located in a network folder. Also, Excel will take \"X\" amount of time to open another workbook, so that execution time can't be increased either." } ]
[ { "body": "<p>I use the following sub to speed up processing: </p>\n\n<pre><code>Public Sub AppSpeed(Optional iWhat As Long = xlDown)\n\n Dim bDir As Boolean\n\n bDir = True\n If iWhat = xlUp Then bDir = False\n\n On Error Resume Next\n\n With Application\n .Calculation = IIf(bDir, xlCalculationAutomatic, xlCalculationManual)\n .ScreenUpdating = bDir\n .DisplayStatusBar = bDir\n .EnableEvents = bDir\n .DisplayPageBreaks = bDir\n .PrintCommunication = bDir\n End With\nEnd Sub\n</code></pre>\n\n<p>and I call it like</p>\n\n<pre><code>AppSpeed xlUp ' at the beginning of the app\n</code></pre>\n\n<p>and</p>\n\n<pre><code>AppSpeed xlDown ' az the end of processing\n</code></pre>\n\n<p>The inconvenience of this solution is that you can't monitor what's happening so Dim a counter like filecounter and put the following snippet somewhere in the loop e.g. after <code>wb.SaveAs</code> to see that something is happening</p>\n\n<pre><code> filecounter = filecounter + 1\n If 100 * (filecounter \\ 100) = filecounter Then\n AppSpeed xlDown\n Application.StatusBar = folderpath &amp; \" \" &amp; CStr(filecounter)\n DoEvents\n AppSpeed xlUp\n End If\n</code></pre>\n\n<p>Next advice is to reduce the number of files in one folder. The documenations do not really help in this matter. My experience is that it is worth to keep the number of files under 1000 in one folder because access time increases enormously over that. You have a flexible structure so can quickly test it by dividing the files to multiple folders. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T16:58:26.340", "Id": "459896", "Score": "0", "body": "You might want to explain why the `With` statement helps speed up the execution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T18:07:56.720", "Id": "459908", "Score": "0", "body": "@pacmaninbw One purpose of `With` is to simplify the syntax. In my example I could replace `Application.<property>` with <.property> with the help of the preceeding `With` statement 6 times. So what really speeds up the app is to disable a few automated operations of Excel like recalculating page breaks after a `.Cut` or a `.AutoFit` operation x10K times by issuing an `Application.DisplayPageBreaks = False` especially in those cases when it needs communication with the printer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T18:33:49.527", "Id": "459911", "Score": "1", "body": "One use of `With` is to put the address of Application into a register and that speeds up the access of the member properties." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T15:42:09.083", "Id": "235074", "ParentId": "234904", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T15:11:42.483", "Id": "234904", "Score": "1", "Tags": [ "performance", "vba", "excel" ], "Title": "Changing the formatting of sheets" }
234904
<h2>The Reason</h2> <p>The reason I designed this code was that in many cases, when I wanted to test code in the browser that would be running on a Node instance, the code that I was copying (Don't worry, copying my own code) was huge, around 2 thousand lines. The solution was to move parts of it that were identical across multiple clients (Actually, processes, or characters).</p> <h2>The Code</h2> <p>The code itself exposes a single function, and a map. The function checks to see which platform you are on (Node, or Browser) and does the respective means to acquire the code for the module you are requesting. Currently, the base path for browser is set to "<a href="https://example.com" rel="nofollow noreferrer">https://example.com</a>". Feel free to change it to test. Do note, that for it to work in node, a <code>parent</code> variable has to be defined, and can be set directly to <code>global</code></p> <p>I chose to make it async, because it forces the user to realize they are not using a normal require, and doesn't freeze the browser while fetching the code.</p> <h3>The Map</h3> <p>The map is designed so that the code can require the same module multiple times without having to fetch the code multiple times. It defines a map, then sets a property upon module request with the name, and the value is the code.</p> <h3>What's this thing, game_log?</h3> <p>game_log was an environment specific function that could log things with colors.</p> <pre class="lang-js prettyprint-override"><code>// Context: parent is a global variable, essentially just `global` const proxied_require = (function(root) { // Caches modules, persistent across code loads. parent.cached_modules = parent.cached_modules || new Map(); // Copy from parent to a local variable. const cached_modules = parent.cached_modules; // Please please please be careful loading modules. If you load them from external sources, you may be at risk. Since there is no sandboxing here, all of the browser is available, making this practically a giant XXS potential. function proxied_require(library, callback) { // Define things that are consistent across implementations const arg_names = ["module", "exports", "require"], _module = {}, _exports = _module.exports = {}, path = "./LIB/" + library; game_log(`Checking cache for library: ${library}`, "info"); // Is the library in the cache? if(cached_modules.has(library)) { game_log(`Cache hit! Library loaded: ${library}`, "green") const code = cached_modules.get(library); Function(...arg_names, code)(_module, _exports, proxied_require); callback(_module.exports); return; } game_log(`Cache miss! Loading library: ${library}`, "red"); // Rudimentary check to see if we are using node. if (typeof module != "undefined") { game_log("Node.js environment detected, using FS", "lightblue"); require('fs').readFile(path, (_, code) =&gt; { game_log(`Library loaded: ${library}`, "lightgreen"); // A bit hacky.... we wrap the code similar to how node.js does, but we also give it a copy of local variables. This enables it to access the character variable, and other things. Function(...arg_names, code)(_module, _exports, proxied_require); // Cache the module. cached_modules.set(library, code); // Call the callback with the results. callback(_module.exports); }); } else { game_log("Broswer environment detected, using XMLHTTPRequest", "lightblue"); const oReq = new XMLHttpRequest(); oReq.open("GET", root + path, true); oReq.send() oReq.addEventListener("load", () =&gt; { const code = oReq.responseText; game_log(`Library loaded: ${library}`, "lightgreen"); Function(...arg_names, code)(_module, _exports, proxied_require); cached_modules.set(library, code); callback(_module.exports); }); } } return proxied_require; })("https://example.com"); </code></pre> <p>Feel free to adjust any magic strings to test it out.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T16:15:01.890", "Id": "234909", "Score": "4", "Tags": [ "javascript", "node.js", "cross-browser" ], "Title": "Browser and Node.js compatible code require" }
234909
<p>I am currently learning how to create nodejs express rest api using async making it fully scaleable and secure.</p> <p>My goal is to ensure maximum functionality and speed, currently I am using MVC structure with route, controller, service and model.</p> <p>Database is mysql and using mysql2 pool.</p> <p>I am looking to know if the example snippets of code below are optimised as best as possible and correctly using async or is there a more efficient way ?</p> <p>Route</p> <pre><code>'use strict'; const express = require('express'); const app = express.Router(); const Stats_controller = require('../controllers/stats'); app.get('/stats', Stats_controller.getStats); module.exports = app; </code></pre> <p>Controller (unsure here about the async how its been used)</p> <pre><code>'use strict'; const statsService = require('../services/stats.js'); const getStats = async (req, res, next) =&gt; { statsService.getStats(function(err, result) { if (err) res.send(err); res.json(result); }); }; module.exports.getStats = getStats; </code></pre> <p>Service</p> <pre><code>'use strict'; var coinsModel = require('../models/stats.js'); const getStats = async function(result) { const res = await coinsModel.getStats(); var responseData = { "status":"success", "data":res } result(null, responseData); } module.exports.getStats = getStats; </code></pre> <p>Model</p> <pre><code>'use strict'; var db = require('../config/conf.js'); const getStats = async function() { return new Promise((resolve) =&gt; { db.connection.query("SELECT * FROM stats", function (err, res) { if(!err){ resolve(res) }else{ resolve([]) } }); }); } module.exports.getStats = getStats; </code></pre>
[]
[ { "body": "<p>Some comments:</p>\n\n<ol>\n<li>Use the built-in database promise support in mysql2 rather than promisify stuff yourself.</li>\n<li>In Model, don't hide low level database errors. If the database has an error, let the caller see the error. It's up to the caller what to do with errors.</li>\n<li>There's no reason for your <code>Model.getStats()</code> to be <code>async</code>.</li>\n<li>Service should use promises to communicate back the results, not a callback. That's the modern way to handle asynchronous results. When you already have a promise, don't introduce a plain callback.</li>\n<li>In <code>Controller.getStats()</code>, when you get an error and do <code>res.send(err)</code> and then <code>res.json(result)</code>. You can't call both of those. You send one response and only one response for each request. Then, your code doesn't send any response when there is no an error.</li>\n<li>Log every error somewhere so you can diagnose server problems when they are occuring.</li>\n<li>As currently shown, there's no reason for <code>Controller.getStats()</code> to be <code>async</code>. You only need a function to be <code>async</code> if you need to use <code>await</code> or you're trying to use <code>async</code> to catch synchronous exceptions for you. It appears you are throwing <code>async</code> in the function definition any time you have an asynchronous operation. That's not the right reason to use <code>async</code> on your functions.</li>\n<li>Performance/speed of this type of code is largely going to be determined entirely by your database configuration and performance as there's nothing in this code that really influences the performance/speed much. You aren't doing any processing of the data here. The extra Service layer isn't adding much value, but also probably doesn't really change much compared to the DB performance.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:46:28.317", "Id": "459550", "Score": "0", "body": "So basically \n\n- Controller = remove async.\n- Model = remove async and change to mysql2 promise\n- Service = async but instead of callback use promise" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:58:11.607", "Id": "459551", "Score": "0", "body": "@JojoBagings - I'd say \"use `async` when appropriate\". If your function implementation drives a need for it (usually driven by the desired use of `await` in the function), add it - otherwise don't." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T17:19:40.357", "Id": "234912", "ParentId": "234911", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T17:12:27.220", "Id": "234911", "Score": "2", "Tags": [ "javascript", "node.js", "api", "express.js" ], "Title": "Express Rest API Async and Scaling" }
234911
<p>I've written my first ever Rust application, I'm looking for advice and criticism.</p> <p>It is a very small application, using Tokio async, and is meant to be single threaded.</p> <p>Mostly I'd like to know if I am writing idiomatic Rust.</p> <p>The full source code can be found at <a href="https://github.com/arontsang/rust-doh-nut" rel="nofollow noreferrer">https://github.com/arontsang/rust-doh-nut</a></p> <pre><code>fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; { let mut rt = Runtime::new()?; let local = task::LocalSet::new(); local.block_on(&amp;mut rt, async { let binding_socket = SocketAddr::from(([0, 0, 0, 0], 15353)); let resolver = HyperResolver::new().await; let resolver = resolver.map(|x| async_std::sync::Arc::new(x)); let success = resolver.map(|x| crate::listener::udp::start(binding_socket, x)); let success = match success { Ok(future) =&gt; future.await, Err(err) =&gt; Err(err), }; match success { Ok(()) =&gt; {}, Err(e) =&gt;{ eprintln!("Application error: {}", e); } } }); Result::Ok(()) } </code></pre> <p>The following is the Http DNS Client</p> <pre><code>pub struct HyperResolver { client : Client } impl HyperResolver { pub async fn new() -&gt; Result&lt;HyperResolver, Box&lt;dyn Error&gt;&gt; { let client = reqwest::Client::builder() .tcp_nodelay() .build()?; Result::Ok(HyperResolver { client }) } } #[async_trait] impl DnsResolver for HyperResolver { async fn resolve(&amp;self, query: Bytes) -&gt; Result&lt;Bytes, Box&lt;dyn Error&gt;&gt; { let client = &amp;self.client; let request = client.request(Method::POST, "https://1.1.1.1/dns-query") .header("accept", "application/dns-message") .header("content-type", "application/dns-message") .header("content-length", query.len().to_string()) .body(Body::from(query)); let response = request.send().await?; let body = response.bytes().await?; Result::Ok(body) } } </code></pre> <p>This is the UDP DNS server component</p> <pre><code>pub async fn start&lt;T : DnsResolver + 'static &gt;(bind_address: SocketAddr, resolver: async_std::sync::Arc&lt;T&gt;) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; { let socket = tokio::net::UdpSocket::bind(bind_address).await; let socket = socket?; let (mut receiver, mut sender) = socket.split(); let (reply_queue, reply_tasks) = tokio::sync::mpsc::channel::&lt;(SocketAddr, Bytes)&gt;(100); let listen_request_task = task::spawn_local(async move { let mut queue = reply_tasks; loop { let success = match queue.recv().await { Some((client, payload)) =&gt; Some(sender.send_to(&amp;payload, &amp;client).await), None =&gt; None, }; match success { Some(Ok(_)) =&gt; {}, Some(Err(error)) =&gt; println!("Error sending reply: {}", error), None =&gt; {}, } } }); let request_dispatch_task = task::spawn_local(async move { loop { let mut local_reply_queue = reply_queue.clone(); let local_resolver_copy = resolver.clone(); let mut buffer = BytesMut::with_capacity(1500); { let mut read_buffer = arr![0u8; 1500]; match receiver.recv_from(&amp;mut read_buffer).await{ Ok((length, client)) =&gt; { buffer.put(&amp;read_buffer[0..length]); let query = buffer.freeze(); task::spawn_local(async move { match local_resolver_copy.resolve(query).await{ Err(error) =&gt; println!("Error resolving packet: {}", error), Ok(reply) =&gt; match local_reply_queue.send((client, reply)).await{ Err(error) =&gt; println!("Error replying packet: {}", error), Ok(_) =&gt; {}, } }; }); }, Err(error) =&gt; println!("Error receiving packet: {}", error), } } } }); listen_request_task.await?; request_dispatch_task.await?; Ok(()) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T17:26:49.213", "Id": "234913", "Score": "1", "Tags": [ "rust" ], "Title": "UDP to HTTP/2 DNS proxy" }
234913
<p>i'm currently trying to rewrite sql server newSequentialId() function in pure c# that is performing as fast as possible and eats minimum memory.</p> <p>Question is can I it be done better - current benchamark shows it is at most 2x slower than native function used by SqlServer (p/invoke)?</p> <pre><code>using System; using System.Buffers; using System.Linq; using System.Net.NetworkInformation; using System.Threading; namespace PerfBenchmarkDotNet { internal static class FastGuid { private static readonly byte[] macBytes; private static long baseDateTicks; private static long ClockSequenceNumber = 0; static FastGuid() { macBytes = GetDefaultMacAdress(); baseDateTicks = new DateTime(1582, 10, 15, 0, 0, 0, DateTimeKind.Utc).Ticks; } public static Guid NewGuid() { var guidArray = ArrayPool&lt;byte&gt;.Shared.Rent(16); var nowTicks = DateTime.UtcNow.Ticks; var sequenceNumber = Interlocked.Increment(ref ClockSequenceNumber) % 65536; var ticksDiff = nowTicks - baseDateTicks; var ticksDiffBytes = BitConverter.GetBytes(ticksDiff); // Copy the bytes into the guid // mac guidArray[15] = macBytes[5]; guidArray[14] = macBytes[4]; guidArray[13] = macBytes[3]; guidArray[12] = macBytes[2]; guidArray[11] = macBytes[1]; guidArray[10] = macBytes[0]; // sequence number guidArray[8] = (byte)(sequenceNumber &gt;&gt; 8); guidArray[9] = (byte)(sequenceNumber); // time guidArray[7] = ticksDiffBytes[0]; guidArray[6] = ticksDiffBytes[1]; guidArray[5] = ticksDiffBytes[2]; guidArray[4] = ticksDiffBytes[3]; guidArray[3] = ticksDiffBytes[4]; guidArray[2] = ticksDiffBytes[5]; guidArray[1] = ticksDiffBytes[6]; guidArray[0] = ticksDiffBytes[7]; var guid = new Guid(guidArray); ArrayPool&lt;byte&gt;.Shared.Return(guidArray); return guid; } private static byte[] GetDefaultMacAdress() { var nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(); if (nic != null) { return nic.GetPhysicalAddress().GetAddressBytes(); } var fallback = Guid.NewGuid().ToByteArray(); return fallback.Take(6).ToArray(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:46:26.837", "Id": "459554", "Score": "1", "body": "Did you try to benchmark against [this](https://github.com/phatboyg/NewId) library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:34:19.173", "Id": "459605", "Score": "0", "body": "Yup, newid is very fast and it looks like a have to do better ;)" } ]
[ { "body": "<p>You want to reduce both computation time and memory allocation. Memory allocation itself takes time, so that's a good place to start -- try to find all the places where you're allocating memory and see if they can be avoided.</p>\n\n<p><code>ArrayPool&lt;byte&gt;.Shared.Rent(16);</code> <em>can</em> avoid an allocation, but not always. Can we do better? Turns out we can; we'll see how.</p>\n\n<p><code>BitConverter.GetBytes(ticksDiff)</code> makes an allocation. <code>ticksDiff</code> is just an integer so it's quite easy to extract its binary representation using binary operators. We'll see how we can use this later on.</p>\n\n<p>But first:</p>\n\n<h1>Profiling</h1>\n\n<p>Profilers are your friend! You should always start the optimization journey by asking \"Where are the bottlenecks?\", which you can promptly answer with cold hard data from a profiling tool.</p>\n\n<p>As suspected, dotTrace reports that the <code>ArrayPool&lt;byte&gt;.Shared.Rent/Return</code> and <code>BitConverter.GetBytes(ticksDiff)</code> calls take a significant chunk (~21%) of the total running time. Let's get rid of those.</p>\n\n<h1>Guid constructor</h1>\n\n<p>You're using the <code>Guid</code> constructor that takes a <code>byte[]</code>, which has perpetuated an implementation that necessarily allocates a byte array <em>somewhere</em>. You can get clever with this to allocate on the stack instead of the heap (<code>Span&lt;byte&gt;</code> with <code>stackalloc</code>) or to minimize the number of allocations that actually need to happen (<code>ThreadLocal&lt;byte[]&gt;</code>), but the best solution is to <em>not allocate anything at all</em>. To accomplish this, you can use one of the other <code>Guid</code> constructors that takes its values directly, instead of taking a byte array.</p>\n\n<p>There's a constructor overload that takes an <code>int</code>, two <code>short</code>s, and eight <code>byte</code>s. You can pack these values directly (see the <a href=\"https://github.com/microsoft/referencesource/blob/master/mscorlib/system/guid.cs\" rel=\"noreferrer\">reference source</a> for endianness on the <code>int</code> and <code>short</code>s):</p>\n\n<pre><code>int a = ticksDiffBytes[7] | (ticksDiffBytes[6] &lt;&lt; 8) | (ticksDiffBytes[5] &lt;&lt; 16) | (ticksDiffBytes[4] &lt;&lt; 24);\nshort b = (short)(ticksDiffBytes[3] | (ticksDiffBytes[2] &lt;&lt; 8));\nshort c = (short)(ticksDiffBytes[1] | (ticksDiffBytes[0] &lt;&lt; 8));\n\nvar guid = new Guid(\n a,\n b,\n c,\n (byte)(sequenceNumber &gt;&gt; 8),\n (byte)(sequenceNumber),\n macBytes[0],\n macBytes[1],\n macBytes[2],\n macBytes[3],\n macBytes[4],\n macBytes[5]);\n</code></pre>\n\n<h1>Binary stuff</h1>\n\n<p>You can extract bits directly from <code>ticksDiff</code> to avoid the call to <code>BitConverter.GetBytes</code>:</p>\n\n<pre><code>var ticksDiff = nowTicks - baseDateTicks;\n\nint a = (int)(\n ((ticksDiff &gt;&gt; 56) &amp; 0xFF) |\n ((ticksDiff &amp; 0x00FF000000000000) &gt;&gt; 40) |\n ((ticksDiff &amp; 0x0000FF0000000000) &gt;&gt; 24) |\n ((ticksDiff &amp; 0x000000FF00000000) &gt;&gt; 8));\n\nshort b = (short)(\n ((ticksDiff &amp; 0x00000000FF000000) &gt;&gt; 24) |\n ((ticksDiff &amp; 0x0000000000FF0000) &gt;&gt; 8));\n\nshort c = (short)(\n ((ticksDiff &amp; 0x000000000000FF00) &gt;&gt; 8) |\n ((ticksDiff &amp; 0x00000000000000FF) &lt;&lt; 8));\n</code></pre>\n\n<p>If you can tolerate a change in endianness, the following is a lot cleaner to read (but provides no measurable change in runtime for me): </p>\n\n<pre><code>var ticksDiff = nowTicks - baseDateTicks;\n\nint a = (int)(ticksDiff);\nshort b = (short)(ticksDiff &gt;&gt; 32);\nshort c = (short)(ticksDiff &gt;&gt; 48);\n</code></pre>\n\n<h1>Remainder</h1>\n\n<p>You don't need to do a remainder when computing <code>sequenceNumber</code> because we're extracting the remainder bits directly anyhow when we pass <code>(byte)(sequenceNumber &gt;&gt; 8), (byte)(sequenceNumber)</code> to the <code>Guid</code> constructor.</p>\n\n<p>My numbers below make it hard to conclude if this helps at all. This is the kind of thing that might be optimized away by the jitter anyway.</p>\n\n<h1>Benchmarks</h1>\n\n<p>With these changes, my benchmarks look as follows:</p>\n\n<pre><code>| Method | Mean | Error | StdDev | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated |\n|------------------------------------------ |---------:|--------:|--------:|------:|-------:|------:|------:|----------:|\n| NewGuid_Original | 224.2 ns | 4.37 ns | 4.49 ns | 1.00 | 0.0041 | - | - | 20 B |\n| NewGuid_WithPackedValues | 153.6 ns | 2.51 ns | 2.35 ns | 1.00 | 0.0041 | - | - | 20 B |\n| NewGuid_WithPackedValuesAndNoBitConverter | 148.6 ns | 2.43 ns | 2.28 ns | 1.00 | - | - | - | - |\n| NewGuid_WithReorderedBytes | 148.9 ns | 2.92 ns | 3.00 ns | 1.00 | - | - | - | - |\n| NewGuid_WithReorderedBytesAndNoRemainder | 146.4 ns | 2.11 ns | 1.98 ns | 1.00 | - | - | - | - |\n</code></pre>\n\n<p>Final code:</p>\n\n<pre><code>public static Guid NewGuid_WithBinaryOptimizationsAndWithoutRemainder()\n{\n var nowTicks = DateTime.UtcNow.Ticks;\n var sequenceNumber = Interlocked.Increment(ref ClockSequenceNumber);\n\n var ticksDiff = nowTicks - baseDateTicks;\n\n int a = (int)(ticksDiff);\n short b = (short)(ticksDiff &gt;&gt; 32);\n short c = (short)(ticksDiff &gt;&gt; 48);\n\n var guid = new Guid(\n a,\n b,\n c,\n (byte)(sequenceNumber &gt;&gt; 8),\n (byte)(sequenceNumber),\n macBytes[0],\n macBytes[1],\n macBytes[2],\n macBytes[3],\n macBytes[4],\n macBytes[5]);\n\n return guid;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:43:27.020", "Id": "459678", "Score": "0", "body": "how did u format benchmark results?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T14:28:37.737", "Id": "459763", "Score": "0", "body": "I used BenchmarkDotNet which does the table formatting by default." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:36:46.600", "Id": "234963", "ParentId": "234914", "Score": "7" } }, { "body": "<p>So after updating my source code it looks that it performs fast enough and allocates no memory. Here are benchmark for comparing the most popular methods of generating GUIDs.</p>\n\n<blockquote>\n <p>Runtime=.NET Core 3.0 Force=True Server=True</p>\n \n <pre class=\"lang-cs prettyprint-override\"><code>| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen 0 | Gen 1 | Gen 2 | Allocated |\n|------------------------------------ |----------:|---------:|---------:|------:|--------:|-------:|------:|------:|----------:|\n| SqlServerNewSequentialGuid | 38.69 ns | 0.787 ns | 1.643 ns | 1.00 | 0.00 | 0.0009 | - | - | 80 B |\n| Guid_Standard | 61.44 ns | 0.665 ns | 0.622 ns | 1.60 | 0.06 | - | - | - | - |\n| NHibernate_GuidCombGenerator | 160.22 ns | 3.070 ns | 2.721 ns | 4.16 | 0.20 | 0.0012 | - | - | 104 B |\n| Guid_Comb_New | 291.56 ns | 5.421 ns | 4.805 ns | 7.57 | 0.37 | 0.0010 | - | - | 104 B |\n| EFCore_SequentialGuidValueGenerator | 82.04 ns | 1.623 ns | 1.667 ns | 2.13 | 0.11 | 0.0007 | - | - | 72 B |\n| NewId_Lib | 78.93 ns | 1.150 ns | 1.076 ns | 2.05 | 0.09 | - | - | - | - |\n| NewSequentialGuid_PureNetCore | 70.28 ns | 1.332 ns | 1.481 ns | 1.81 | 0.08 | - | - | - | - |\n</code></pre>\n</blockquote>\n\n<p>Full source code in c# .net core 2.2+:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Buffers;\nusing System.Linq;\nusing System.Net.NetworkInformation;\nusing System.Threading;\n\nnamespace PerfBenchmarkDotNet\n{\n internal readonly struct FastGuid\n {\n private static readonly byte[] _macBytes;\n private static long _baseDateTicks;\n private static long _clockSequenceNumber;\n\n static FastGuid()\n {\n _clockSequenceNumber = 0;\n _macBytes = GetDefaultMacAdress();\n _baseDateTicks = new DateTime(1582, 10, 15, 0, 0, 0, DateTimeKind.Utc).Ticks;\n }\n\n public static Guid NewGuid()\n {\n var nowTicks = DateTime.UtcNow.Ticks;\n var sequenceNumber = Interlocked.Increment(ref _clockSequenceNumber);\n var ticksDiff = nowTicks - _baseDateTicks;\n\n var a = (int)(ticksDiff);\n short b = (short)(ticksDiff &gt;&gt; 32);\n short c = (short)(ticksDiff &gt;&gt; 48);\n\n return new Guid(\n a,\n b,\n c,\n (byte)(sequenceNumber &gt;&gt; 8),\n (byte)(sequenceNumber),\n _macBytes[0],\n _macBytes[1],\n _macBytes[2],\n _macBytes[3],\n _macBytes[4],\n _macBytes[5]);\n }\n\n private static byte[] GetDefaultMacAdress()\n {\n var nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();\n\n if (nic != null)\n {\n return nic.GetPhysicalAddress().GetAddressBytes();\n }\n\n var fallback = Guid.NewGuid().ToByteArray();\n return fallback.Take(6).ToArray();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:00:17.850", "Id": "465565", "Score": "0", "body": "I'm curious as to how you profiled SqlServerNewSequentialGuid (`NEWSEQUENTIALID()`) since that can only be used in a default constraint expression, AFAIK." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:38:21.853", "Id": "234974", "ParentId": "234914", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T17:27:07.487", "Id": "234914", "Score": "5", "Tags": [ "c#", "sql-server", ".net-core" ], "Title": "NewSequentialId - pure net core 2.2 implementation of sql server function" }
234914
<p>I want to save and load an arbitrary Java <code>String</code> in a <code>Text</code> node in a XML file using the Java DOM API. </p> <p>The <code>Transformer</code> and the <code>DocumentBuilder</code> already escape and unescape predefined entities such as <code>"</code>, <code>&amp;</code>, <code>'</code>, <code>&lt;</code>, <code>&gt;</code> and a few other characters by replacing them with with <code>&amp;quot;</code>, <code>&amp;amp;</code>, <code>&amp;apos;</code>, <code>&amp;lt;</code>, <code>&amp;gt;</code> and <code>&amp;#c;</code>, where <code>c</code> is the Unicode code point.</p> <p>So this is not the kind of escaping I am talking about. I am talking about the characters which are not in the ranges #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] because these are according to the XML specifications invalid characters in XML files, even if escaped. </p> <p>However, I want to be able to save an arbitrary <code>String</code> which may or may not contains an invalid character. The idea is to use two functions <code>escapeInvalidXmlCharacters</code> and <code>unescapeInvalidXmlCharacters</code> before and after using the DOM API as in the following example. Invalid characters are replaced by <code>#c;</code>, where <code>c</code> is the Unicode code point and <code>#</code> is escaped by a leading <code>#</code>.</p> <pre class="lang-java prettyprint-override"><code> // should not be reviewed String string = "text#text##text#0;text" + '\u0000' + "text&lt;text&amp;text#"; Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element element = document.createElement("element"); element.appendChild(document.createTextNode(escapeInvalidXmlCharacters(string))); document.appendChild(element); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(new File("test.xml"))); // creates &lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;&lt;element&gt;text##text####text##0;text#0;text&amp;lt;text&amp;amp;text##&lt;/element&gt; document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("test.xml")); System.out.println(unescapeInvalidXmlCharacters(document.getDocumentElement().getTextContent()).equals(string)); // prints true </code></pre> <p>Here are the functions to be reviewed.</p> <pre class="lang-java prettyprint-override"><code> /** * Escapes invalid XML Unicode code points in a &lt;code&gt;{@link String}&lt;/code&gt;. The * DOM API already escapes predefined entities, such as {@code "}, {@code &amp;}, * {@code '}, {@code &lt;} and {@code &gt;} for * &lt;code&gt;{@link org.w3c.dom.Text Text}&lt;/code&gt; nodes. Therefore, these Unicode * code points are ignored by this function. However, there are some other * invalid XML Unicode code points, such as {@code '\u0000'}, which are even * invalid in their escaped form, such as {@code "&amp;#0;"}. * &lt;p&gt; * This function replaces all {@code '#'} by {@code "##"} and all Unicode code * points which are not in the ranges #x9 | #xA | #xD | [#x20-#xD7FF] | * [#xE000-#xFFFD] | [#x10000-#x10FFFF] by the &lt;code&gt;{@link String}&lt;/code&gt; * {@code "#c;"}, where &lt;code&gt;c&lt;/code&gt; is the Unicode code point. * * @param string the &lt;code&gt;{@link String}&lt;/code&gt; to be escaped * @return the escaped &lt;code&gt;{@link String}&lt;/code&gt; * @see &lt;code&gt;{@link #unescapeInvalidXmlCharacters(String)}&lt;/code&gt; */ public static String escapeInvalidXmlCharacters(String string) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0, codePoint = 0; i &lt; string.length(); i += Character.charCount(codePoint)) { codePoint = string.codePointAt(i); if (codePoint == '#') { stringBuilder.append("##"); } else if (codePoint == 0x9 || codePoint == 0xA || codePoint == 0xD || codePoint &gt;= 0x20 &amp;&amp; codePoint &lt;= 0xD7FF || codePoint &gt;= 0xE000 &amp;&amp; codePoint &lt;= 0xFFFD || codePoint &gt;= 0x10000 &amp;&amp; codePoint &lt;= 0x10FFFF) { stringBuilder.appendCodePoint(codePoint); } else { stringBuilder.append("#" + codePoint + ";"); } } return stringBuilder.toString(); } /** * Unescapes invalid XML Unicode code points in a &lt;code&gt;{@link String}&lt;/code&gt;. * Makes &lt;code&gt;{@link #escapeInvalidXmlCharacters(String)}&lt;/code&gt; undone. * * @param string the &lt;code&gt;{@link String}&lt;/code&gt; to be unescaped * @return the unescaped &lt;code&gt;{@link String}&lt;/code&gt; * @see &lt;code&gt;{@link #escapeInvalidXmlCharacters(String)}&lt;/code&gt; */ public static String unescapeInvalidXmlCharacters(String string) { StringBuilder stringBuilder = new StringBuilder(); boolean escaped = false; for (int i = 0, codePoint = 0; i &lt; string.length(); i += Character.charCount(codePoint)) { codePoint = string.codePointAt(i); if (escaped) { stringBuilder.appendCodePoint(codePoint); escaped = false; } else if (codePoint == '#') { StringBuilder intBuilder = new StringBuilder(); int j; for (j = i + 1; j &lt; string.length(); j += Character.charCount(codePoint)) { codePoint = string.codePointAt(j); if (codePoint == ';') { escaped = true; break; } if (codePoint &gt;= 48 &amp;&amp; codePoint &lt;= 57) { intBuilder.appendCodePoint(codePoint); } else { break; } } if (escaped) { try { codePoint = Integer.parseInt(intBuilder.toString()); stringBuilder.appendCodePoint(codePoint); escaped = false; i = j; } catch (IllegalArgumentException e) { codePoint = '#'; escaped = true; } } else { codePoint = '#'; escaped = true; } } else { stringBuilder.appendCodePoint(codePoint); } } return stringBuilder.toString(); } </code></pre> <p>You can additionally post your answer under my related SO question <a href="https://stackoverflow.com/q/59447599/3882565">https://stackoverflow.com/q/59447599/3882565</a> where I have started a +200 reputation bounty.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T21:47:44.777", "Id": "459556", "Score": "0", "body": "How would an answer that is acceptable here be acceptable on SO?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T23:34:58.783", "Id": "459581", "Score": "0", "body": "@FreezePhoenix Just wanted to link this question here and if someone has some major improvements, why shouldn't they be posted on SO too? Of course not in the form of a review, but rather as a finished version. If you don't think your answer is acceptable on SO, then just don't post it there." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:08:09.040", "Id": "234915", "Score": "1", "Tags": [ "java", "xml", "dom", "escaping" ], "Title": "Escaping invalid XML characters (e.g. for the Java DOM API)" }
234915
<p>I am solving an exercise. Essentially, it's a shell script that takes in file and/or directory arguments and outputs another (standalone) shell script that outputs these files, including any directory structure associated with them.</p> <p>Example usage:</p> <pre><code>bundle.sh dir1 dir2 file1 file2 file3 &gt;unpack.sh </code></pre> <p>This expects that <em>bundle.sh</em> can be found in the <code>PATH</code> environment variable. If not, just run it like this:</p> <pre><code>`pwd`/bundle.sh dir file1 file2 &gt;unpack.sh </code></pre> <p>Running <em>unpack.sh</em> should recreate everything.</p> <p>Accepted limitations:</p> <ul> <li>Only works for textual files</li> <li>Files may not contain the line <strong>End of <em>filename</em></strong></li> </ul> <p>Solution:</p> <pre><code>echo "# Run to unpack" for i; do (cd $i 2&gt;/dev/null &amp;&amp; echo "mkdir $i &amp;&amp; cd $i" &amp;&amp; $0 * &amp;&amp; echo cd ..) cd $i 2&gt;/dev/null || ( echo echo `ls -l $i` echo "cat &gt;$i &lt;&lt;'End of $i'" cat $i echo End of $i) done </code></pre> <p>This is my solution for exercises 3-17 and 3-18 in the Unix Programming Environment by Brian W. Kernighan and Rob Pike. It works but I would appreciate any feedback. I will mention that the book has not yet covered conditional statements, globbing, etc. So I am trying to stick to what I've learned so far for now and might come back to it later.</p> <p>One thing that I realize is that this doesn't deal with names that contain spaces. I have tried putting <code>\"</code>s around most <code>$i</code>s (except for the ones in the <em>echo</em>s, where it shouldn't matter) but that seems to make things worse. The other two is that I find my usage of <em>cd</em> to test for directories kind of a hack and the fact that I am not sure I am handling <code>$0</code> correctly, which is why I made explicit requirements on how to run <em>bundle.sh</em> (maybe there is some way to make it better?). However, I am not interested in just these issues, I want feedback in general given my requirements and constraints. Even advice regarding to style may be valuable to me.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:33:47.913", "Id": "234916", "Score": "2", "Tags": [ "bash", "shell", "unix", "sh" ], "Title": "Outputting a standalone shell script from arguments" }
234916
<p>So for an side exercise on <a href="https://exercism.io" rel="nofollow noreferrer">exercism</a> I implemented a BinarySearchTree. I was confident in implementing the creation of the binary tree. But I'm very unsure about the traversal of the tree. So I came up with two implementations of the traversal algorithm - which one is the "better" solution?</p> <p>I'm learning about F# because I want to learn Functional Programming. This is code review - so any criticism is welcome!</p> <pre><code>module BinarySearchTree type Node&lt;'a&gt; = { Left: Node&lt;'a&gt; option Right: Node&lt;'a&gt; option Data: 'a } let left (node: Node&lt;'a&gt;) = node.Left let right (node: Node&lt;'a&gt;) = node.Right let data (node: Node&lt;'a&gt;) : 'a = node.Data let rec insertNode (root: Node&lt;'a&gt; option) (nextValue: 'a) : Node&lt;'a&gt; = match root with | Some root -&gt; if nextValue &lt;= root.Data then { root with Left = Some(insertNode root.Left nextValue) } elif nextValue &gt; root.Data then { root with Right = Some(insertNode root.Right nextValue) } else root | None -&gt; { Left=None; Right=None; Data=nextValue } let create (items: 'a list) : Node&lt;'a&gt; = items |&gt; List.fold (fun (acc: Option&lt;Node&lt;'a&gt;&gt;) (item: 'a) -&gt; Some(insertNode acc item)) None |&gt; function | None -&gt; failwith "Failed to construct binary tree. You must pass a valid item list." | Some root -&gt; root let sortedData (node: Node&lt;'a&gt;) : ('a list) = let rec traverse (acc: 'a list) (node: Node&lt;'a&gt;) = match (node.Left, node.Right) with | Some left, Some right -&gt; seq { yield! node.Data::acc yield! (traverse [] left) yield! (traverse [] right)} |&gt; Seq.toList | Some left, None -&gt; traverse (node.Data::acc) left | None, Some right -&gt; traverse (node.Data::acc) right | None, None -&gt; node.Data::acc List.sort (traverse [] node) </code></pre> <p>And the alternative implementation of <code>sortedData</code>: </p> <pre><code>let sortedData (node: Node) : (int list) = let rec traverse (acc: int list) (node: Node) = match (node.Left, node.Right) with | Some left, Some right -&gt; (node.Data::acc)@(traverse [] left)@(traverse [] right) | Some left, None -&gt; traverse (node.Data::acc) left | None, Some right -&gt; traverse (node.Data::acc) right | None, None -&gt; node.Data::acc List.sort (traverse [] node) </code></pre>
[]
[ { "body": "<p>In general in F# we try to minimize the use of explicit type declaration on function arguments:</p>\n\n<pre><code>let left (node: Node&lt;'a&gt;) = node.Left\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>let left node = node.Left\n</code></pre>\n\n<p>etc.</p>\n\n<hr>\n\n<p>The function <code>insertNode</code> violates the single responsibility principle in that if <code>root = None</code> then it creates a new tree/root node instead of actual inserting the value.</p>\n\n<p>Personal I wouldn't allow <code>root</code> to be <code>Option/None</code></p>\n\n<p>Instead I would provide a function called <code>newTree</code> taking a <code>'a</code> value as argument and returning a <code>Node&lt;'a&gt;</code></p>\n\n<hr>\n\n<blockquote>\n <p><code>let rec insertNode (root: Node&lt;'a&gt; option) (nextValue: 'a) : Node&lt;'a&gt; = ...</code></p>\n</blockquote>\n\n<p>In general you should have object in question of the module as the last argument of a function in order to make use of the pipe operator:</p>\n\n<pre><code>let rec insertNode value root =...\n\nroot |&gt; BinarySearchTree.insertNode value\n</code></pre>\n\n<hr>\n\n<p><code>sortedData</code> seems overly complicated - maybe from the use of <code>List.sort</code>. In principle it's just a depth-first-search (dfs), where you for each node can concatenate the values in the left child node with the value of the node itself concatenated with the values in the right child node:</p>\n\n<p>For a list it could be:</p>\n\n<pre><code>let toList root =\n let rec dfs optNode =\n match optNode with\n | Some node -&gt; (dfs (left node))@(data node::dfs (right node))\n | None -&gt; []\n\n dfs (Some root)\n</code></pre>\n\n<p>Or if you prefer a Sequence (which I do):</p>\n\n<pre><code>let toSeq root =\n let rec dfs optNode =\n match optNode with\n | Some node -&gt; seq {\n yield! dfs (left node)\n yield data node\n yield! dfs (right node)\n }\n | None -&gt; Seq.empty\n\n dfs (Some root)\n</code></pre>\n\n<p>I call the functions <code>toList</code> and <code>toSeq</code>. Maybe <code>toOrderedList/Seq</code> are better names.</p>\n\n<hr>\n\n<p>You could consider to extend the <code>List</code>-module with a <code>toBinaryTree items</code> instead of the <code>create items</code> function. That way it is possible to write:</p>\n\n<pre><code>let data = [ 5; 8; 1; 5; 1; 2; 2; 4; 6; 3 ]\nlet root = data |&gt; List.toBinaryTree\n</code></pre>\n\n<p>which may be more intuitive</p>\n\n<hr>\n\n<p>In the <code>create items</code> function you should consider to sort the items and do a binary insertion in order to create a balanced tree, because if you provide a list of items that is sorted then your function will merely produce a singly linked list of nodes using only one of the child nodes instead of a tree.</p>\n\n<p>You should consider to provide a function that can balance an existing tree.</p>\n\n<hr>\n\n<p>As an alternative to the <code>Node&lt;'a&gt;</code> type as a record type, you could consider to define it as a discriminated union type with the following definition:</p>\n\n<pre><code>type Node&lt;'a&gt; =\n | Empty\n | Node of Data:'a * Left:Node&lt;'a&gt; * Right:Node&lt;'a&gt;\n</code></pre>\n\n<p>That is more in line with the functional style of F# and your functions become somewhat more simple and intuitive:</p>\n\n<pre><code>module BinaryTree =\n\nlet data = function Empty -&gt; failwith \"Empty Tree\" | Node (d, _, _) -&gt; d\nlet left = function Empty -&gt; Empty | Node (_, l, _) -&gt; l\nlet right = function Empty -&gt; Empty | Node (_, _, r) -&gt; r\n\nlet first root = \n let rec goLeft node =\n match node with\n | Empty -&gt; None\n | Node (d, ln, _) -&gt;\n match ln with\n | Empty -&gt; Some d\n | Node _ -&gt; goLeft ln\n\n goLeft root\n\nlet last root = \n let rec goRight node =\n match node with\n | Empty -&gt; None\n | Node (d, _, rn) -&gt;\n match rn with\n | Empty -&gt; Some d\n | Node _ -&gt; goRight rn\n\n goRight root\n\nlet rec insert data root =\n match root with\n | Empty -&gt; Node(data, Empty, Empty)\n | Node (d, l, r) -&gt;\n match data &lt;= d with\n | true -&gt; Node (d, l |&gt; insert data, r)\n | false -&gt; Node (d, l, r |&gt; insert data)\n\nlet toOrderedSeq root =\n let rec dfs node =\n match node with\n | Empty -&gt; Seq.empty\n | Node (d, ln, rn) -&gt; seq {\n yield! dfs ln\n yield d\n yield! dfs rn\n }\n\n dfs root\n\n\nmodule List =\n let toBinaryTree data = data |&gt; List.fold (fun n x -&gt; n |&gt; BinaryTree.insert x) Empty\n</code></pre>\n\n<p>As seen, the use of <code>option</code> is unnecessary and the <code>insert</code> function is consistent, because an <code>Empty</code> node as <code>root</code> is also a <code>Node&lt;'a&gt;/Tree</code> - just without any elements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T21:39:41.663", "Id": "460322", "Score": "0", "body": "Ah the `toOrderSeq` function is much better. Do I get a performance boost if I only iterate over the first sorted values instead of creating a list? Ty - the comments are really helpfull" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T17:45:17.420", "Id": "235241", "ParentId": "234917", "Score": "1" } } ]
{ "AcceptedAnswerId": "235241", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T19:45:29.230", "Id": "234917", "Score": "4", "Tags": [ "tree", "f#" ], "Title": "F# Binary Tree and Tree Traversal" }
234917
<p>I had to write some code that receives a number 'x' and an alternately sorted array (an array with all even indexes sorted upwards and all odd indexes sorted downwards) and checks if 'x' exists in the array. If it exists, the method will return the index, if not, the method will return -1.</p> <ul> <li><p>If there is more than one 'x' in the array, I can choose which one to return.</p></li> <li><p>An array example: {-3, 10, 0, 9, 2, 5, 3, 0, 6, -5}</p></li> </ul> <p>I've written the following code, and I will like to hear what you think, how I can improve it, and if you think of some cases when it won't work: </p> <pre><code>public static int find(int[] a, int x) { int topEven = a.length - 1, topOdd = a.length - 1, bottomEven = 0, midEven = 0, bottomOdd = 1, midOdd = 0; if (a.length == 0) { return -1; } else if (a[0] == x) { return 0; } else if (a[topOdd] == x) { return topOdd; } while (topEven &gt; bottomEven) { midEven = ((topEven + bottomEven) / 2); if (midEven % 2 != 0) { midEven++; } if (x &gt; a[midEven]) { bottomEven = midEven + 1; } else if (x &lt; a[midEven]) { topEven = midEven - 1; } else return midEven; } while (topOdd &gt; bottomOdd) { midOdd = ((topOdd + bottomOdd) / 2); if (midOdd % 2 == 0) { midOdd++; } if (x &gt; a[midOdd]) { topOdd = midOdd - 1; } else if (x &lt; a[midOdd]) { bottomOdd = midOdd + 1; } else return midOdd; } return -1; } </code></pre> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:21:00.963", "Id": "459599", "Score": "1", "body": "I assume you're doing this mostly as an exercise, so not worth an answer by itself, but you could split the array in two and use [Arrays.binarySearch()](https://www.tutorialspoint.com/java/util/arrays_binarysearch_object.htm)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:26:04.293", "Id": "459600", "Score": "0", "body": "Yes i am.\nI know i can split it and use binary search and that way avoid some repeating code, does it have any other benefits besides it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:28:35.777", "Id": "459601", "Score": "1", "body": "Mainly avoids implementing the search yourself, which could introduce bugs. Shorter code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:33:03.003", "Id": "459604", "Score": "2", "body": "Welcome to Code Review! I have rolled back your last edits. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:52:36.943", "Id": "459607", "Score": "0", "body": "Can you explain your alternative sort more clearly? Maybe add some examples. The way it is now, I dont get it. Btw I have sense for what Is front And back in context of sorting but no idea what up And Down means. Especially when refering to indices instead of values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T10:37:43.503", "Id": "459612", "Score": "1", "body": "Lol, nevermind, I\"m an idiot. Of course splitting the array would require accessing it all, defeating the purpose of using binary search completely. Thought too much about \"how\" and not enough about \"why\"" } ]
[ { "body": "<p>It seems you do not need those lines:</p>\n\n<pre><code>} else if (a[0] == x) {\n return 0;\n} else if (a[topOdd] == x) {\n return topOdd;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T23:38:57.100", "Id": "459584", "Score": "4", "body": "Welcome back to answering here… While I think your observation correct, do you have any advice what to do about it: what are the pros and cons of doing with or without those statements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:28:51.893", "Id": "459603", "Score": "0", "body": "@eagle i disagree actually, at least for the way the code is written right now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:13:45.753", "Id": "459642", "Score": "0", "body": "@RedYoel: You could try setting a breakpoint on those lines in a debugger and try to craft an input that reaches either of those statements, then after proving they're reached with some input, remove them to see if the function returns a wrong answer without them with the same input. Or the author of this answer could edit it to back up their assertion by explaining why those cases will already be handled earlier or later." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T22:13:43.040", "Id": "234926", "ParentId": "234918", "Score": "3" } }, { "body": "<p>here are some suggestions for your code.</p>\n\n<p>1) Since the array is not updated, I suggest that you extract the size in a variable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static int find(int[] a, int x) {\n //[...]\n int arrLength = a.length;\n //[...]\n}\n</code></pre>\n\n<p>2) In my opinion, there's no gain to check if the boundaries are the current value, since the value can be anywhere.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>else if (a[0] == x) {\n return 0;\n} else if (a[topOdd] == x) {\n return topOdd;\n}\n</code></pre>\n\n<p>3) I suggest that you move the check for the size before the variables, it will remove the calculation of the other variables when the array is empty.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int arrLength = a.length;\n\nif(arrLength == 0) {\n return -1;\n}\n\nint topEven = arrLength - 1;\nint topOdd = arrLength - 1;\nint bottomEven = 0;\nint midEven = 0;\nint bottomOdd = 1;\nint midOdd = 0;\n\nif (a[0] == x) {\n return 0;\n} else if (a[topOdd] == x) {\n return topOdd;\n}\n</code></pre>\n\n<p>4) I suggest that you add the parentheses on the <code>else</code>, since it make the code harder to read, in my opinion.</p>\n\n<p>5) I suggest that you make function to check if the number is odd or even.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private static boolean isEven(int value) {\n return value % 2 != 0;\n }\n\n private static boolean isOdd(int value) {\n return !isEven(value);\n }\n</code></pre>\n\n<p>6) I suggest that you extract the loop parts in methods. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static int find(int[] a, int x) {\n //[...]\n int maxLastArrayPosition = arrLength - 1;\n\n Integer evenPosition = findNumberEven(a, x, maxLastArrayPosition);\n if (evenPosition != null) {\n return evenPosition;\n }\n //[...]\n}\n\nprivate static Integer findNumberOdd(int[] a, int x, int maxLastArrayPosition) {\n int topOdd = maxLastArrayPosition;\n int midOdd = 0;\n int bottomOdd = 1;\n while (topOdd &gt; bottomOdd) {\n midOdd = ((topOdd + bottomOdd) / 2);\n\n if (isOdd(midOdd)) {\n midOdd++;\n }\n\n if (x &gt; a[midOdd]) {\n topOdd = midOdd - 1;\n } else if (x &lt; a[midOdd]) {\n bottomOdd = midOdd + 1;\n } else {\n return midOdd;\n }\n }\n\n return null;\n}\n\n</code></pre>\n\n<p>7) I suggest that you make a constant for the invalid value.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static final int INVALID = -1;\n</code></pre>\n\n<p><strong>Refactored code</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static final int INVALID = -1;\n\npublic static int find(int[] a, int x) {\n int arrLength = a.length;\n\n if (arrLength == 0) {\n return INVALID;\n }\n\n int maxLastArrayPosition = arrLength - 1;\n\n Integer evenPosition = findNumberEven(a, x, maxLastArrayPosition);\n if (evenPosition != null) {\n return evenPosition;\n }\n\n Integer oddPosition = findNumberOdd(a, x, maxLastArrayPosition);\n if (oddPosition != null) {\n return oddPosition;\n }\n\n return INVALID;\n}\n\nprivate static Integer findNumberOdd(int[] a, int x, int maxLastArrayPosition) {\n int topOdd = maxLastArrayPosition;\n int midOdd = 0;\n int bottomOdd = 1;\n while (topOdd &gt; bottomOdd) {\n midOdd = ((topOdd + bottomOdd) / 2);\n\n if (isOdd(midOdd)) {\n midOdd++;\n }\n\n if (x &gt; a[midOdd]) {\n topOdd = midOdd - 1;\n } else if (x &lt; a[midOdd]) {\n bottomOdd = midOdd + 1;\n } else {\n return midOdd;\n }\n }\n\n return null;\n}\n\nprivate static Integer findNumberEven(int[] a, int x, int maxLastArrayPosition) {\n int topEven = maxLastArrayPosition;\n int midEven = 0;\n int bottomEven = 0;\n while (topEven &gt; bottomEven) {\n midEven = ((topEven + bottomEven) / 2);\n if (isEven(midEven)) {\n midEven++;\n }\n if (x &gt; a[midEven]) {\n bottomEven = midEven + 1;\n } else if (x &lt; a[midEven]) {\n topEven = midEven - 1;\n } else {\n return midEven;\n }\n\n }\n\n return null;\n}\n\nprivate static boolean isEven(int midEven) {\n return midEven % 2 != 0;\n}\n\nprivate static boolean isOdd(int value) {\n return !isEven(value);\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T11:16:46.630", "Id": "459613", "Score": "0", "body": "Returning a null Integer seems to be a bad idea, perhaps a special value, such as -1 would be better (which is what the standard library uses)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T14:31:57.563", "Id": "459616", "Score": "1", "body": "In my opinion, all the choices are similar in this case, you can even throw an exception." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:06:43.243", "Id": "459640", "Score": "2", "body": "@PhilipRoman Almost certainly not. `-1` is a very valid value (the sample input even contains negative numbers). This is what [`OptionalInt`](https://docs.oracle.com/javase/8/docs/api/java/util/OptionalInt.html) is for." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T02:54:39.933", "Id": "234934", "ParentId": "234918", "Score": "5" } }, { "body": "<p>How about an alternate approach: instead of adapting the binary-search algorithm to work with all kinds of alternate sorted collections, how about adapting the collections to be able to run classic binary search on them.</p>\n\n<p>This enables one to use production ready searching methods without reinventing the wheel and risking bugs. Even if one decides to rewrite binary search as an exercise it is still easier as it doesn't have to take the alternating indexes into account.</p>\n\n<pre><code>public static int findInAlternateSortedArray(int[] haystack, int needle) {\n if (haystack.length &gt; 0) {\n List&lt;Integer&gt; sortedAscending = new EverySecondElement(haystack, 0);\n int index = Collections.binarySearch(sortedAscending, needle);\n if (index &gt;= 0) return index * 2;\n }\n if (haystack.length &gt; 1) {\n List&lt;Integer&gt; sortedDescending = new EverySecondElement(haystack, 1);\n int index = Collections.binarySearch(sortedDescending, needle, Comparator.reverseOrder());\n if (index &gt;= 0) return index * 2 + 1;\n }\n return -1;\n}\n</code></pre>\n\n<p>All that is needed to be able to use the standard library provided <code>Collections.binarySearch</code> is to provide two views into the original array, as if he had two independently sorted collections.</p>\n\n<p>Given an index into each of these lists, we can easily calculate the index from the original array from where to fetch an element in <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> time, thus the runtime of the entire search is still <span class=\"math-container\">\\$\\mathcal{O}(\\log N)\\$</span>.</p>\n\n<pre><code>static class EverySecondElement extends AbstractList&lt;Integer&gt; {\n private int[] array;\n private int offset;\n\n EverySecondElement(int[] array, int offset) {\n this.array = array;\n this.offset = offset;\n }\n\n @Override\n public int size() {\n return (array.length - offset + 1) / 2;\n }\n\n @Override\n public Integer get(int index) {\n return array[offset + index * 2];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:17:20.703", "Id": "459644", "Score": "0", "body": "Since constructing an instance of this wrapper should be cheap (doesn't copy the array, just a reference), you could just do it on the fly for searching and not need to implement \"lots of other methods\" which would partially defeat the benefit you're getting from this. I guess Java doesn't have array \"slices\" that would let you take a view of the array that only includes elements `1..size-1` instead of `0..size-1`, which would remove the need for an `offset`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:50:33.847", "Id": "459650", "Score": "0", "body": "Java's `Collection.binarySearch` expects a List which is quite a fat interface. A custom search method could do with a lighter interface that only provide `get` and `size`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T01:47:57.513", "Id": "459695", "Score": "2", "body": "Instead of implementing `java.util.List`, you may extend `java.util.AbstractList<Integer>`. It has default implementations for all methods other than those two." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T14:47:50.113", "Id": "234950", "ParentId": "234918", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-01T20:31:52.300", "Id": "234918", "Score": "5", "Tags": [ "java", "array", "binary-search" ], "Title": "Searching an element in an alternately sorted array" }
234918
<p>I'm trying to implement a regularization term for the loss function of a neural network. </p> <pre><code>from torch import nn import torch import numpy as np reg_sig = torch.randn([32, 9, 5]) reg_adj = torch.randn([32, 9, 9, 4]) Maug = reg_adj.shape[0] n_node = 9 n_bond_features = 4 n_atom_features = 5 SM_f = nn.Softmax(dim=2) SM_W = nn.Softmax(dim=3) p_f = SM_f(reg_sig) p_W = SM_W(reg_adj) Sig = nn.Sigmoid() q = 1 - p_f[:, :, 4] A = 1 - p_W[:, :, :, 0] A_0 = torch.eye(n_node) A_0 = A_0.reshape((1, n_node, n_node)) A_i = A B = A_0.repeat(reg_sig.size(0), 1, 1) for i in range(1, n_node): A_i = Sig(100 * (torch.bmm(A_i, A) - 0.5)) B += A_i C = Sig(100 * (B - 0.5)) reg_g_ij = torch.randn([reg_sig.size(0), n_node, n_node]) for i in range(n_node): for j in range(n_node): reg_g_ij[:, i, j] = q[:, i] * q[:, j] * (1 - C[:, i, j]) + (1 - q[:, i] * q[:, j]) * C[:, i, j] </code></pre> <p>I believe that my implementation is computationally not efficient and would like to have some suggestions on which parts I can change. Specifically, I would like to get rid of the loops and do them using matrix operations if possible. Any suggestions or working examples or links to useful torch functions would be appreciated</p>
[]
[ { "body": "<p>I don't have many improvements to offer-- just one major one. Like you suspected, your implementation is not efficient. This is because using a double for loop to set a Torch/NumPy array is not the preferred way to do sum reductions. What is preferred, is the use of <a href=\"https://pytorch.org/docs/stable/torch.html#torch.einsum\" rel=\"nofollow noreferrer\">torch.einsum</a>. It takes an indices equation and reduces the Tensors into a final representation.</p>\n\n<p>First to note is that your equation for <code>reg_g_ij</code> is <strong>not</strong> the most simplified form.</p>\n\n<p>In your code, we start with:</p>\n\n<p><code>q_i * q_j * (1 - C_ij) + (1 - q_i * q_j) * C_ij</code></p>\n\n<p>But it can be reduced to:</p>\n\n<p><code>q_i * q_j * (1 - 2 * C_ij) + C_ij</code></p>\n\n<p>You can prove it yourself with a few lines of algebra.</p>\n\n<p>The last small thing is call <code>.unsqueeze(0)</code> when you're expanding the dimensions of an array. In this case we used this method to expand an array's size from (9, 9) to (1, 9, 9). </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> A_0 = torch.eye(n_node).unsqueeze(0)\n A_i = A\n\n B = A_0.repeat(reg_sig.size(0), 1, 1)\n\n for i in range(1, n_node):\n A_i = Sig(100 * (torch.bmm(A_i, A) - 0.5))\n\n B += A_i\n\n C = Sig(100 * (B - 0.5))\n\n reg_g_ij = torch.einsum('ij,ik,ijk-&gt;ijk', q, q, 1 - 2 * C) + C\n</code></pre>\n\n<p>When profiling this approach, we see a pretty big reduction in time:</p>\n\n<pre><code>In [257]: %timeit new(reg_sig, reg_adj)\n1000 loops, best of 5: 745 µs per loop\n\nIn [258]: %timeit orig(reg_sig, reg_adj)\nThe slowest run took 4.85 times longer than the fastest. This could mean that an intermediate result is being cached.\n100 loops, best of 5: 5.44 ms per loop\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T01:11:32.243", "Id": "459829", "Score": "0", "body": "Thanks for suggestions, I got it down to this before seeing the post: `temp = torch.einsum('bi, bj->bij', q, q)` and then `reg_g_ij = torch.einsum('bij, bij->bij', temp, 1 - C) + torch.einsum('bij, bij->bij', 1 - temp, C)`, but I missed the algebra." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T21:46:00.690", "Id": "235041", "ParentId": "234933", "Score": "2" } } ]
{ "AcceptedAnswerId": "235041", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T02:51:38.993", "Id": "234933", "Score": "1", "Tags": [ "python", "pytorch" ], "Title": "Loops in PyTorch Implementation" }
234933
<p>Happy new year everyone, Following <a href="https://www.coursera.org/learn/machine-learning/" rel="nofollow noreferrer">Andrew NG's course on coursera</a> here's my implementation for the gradient descent algorithm(univariate linear regression) in Python using pandas, matplotlib with optional visualization which creates a GIF. Any optimizations/suggestions are welcome.</p> <p>For those who don't know what gradient descent algorithm is: Gradient descent is a first-order iterative optimization algorithm for finding the local minimum of a function. To find a local minimum of a function using gradient descent, one takes steps proportional to the negative of the gradient (or approximate gradient) of the function at the current point. If, instead, one takes steps proportional to the positive of the gradient, one approaches a local maximum of that function. You can check the <a href="https://en.wikipedia.org/wiki/Gradient_descent" rel="nofollow noreferrer">definition</a> on wikipedia.</p> <p><strong>Ex1 GIF:</strong></p> <p><a href="https://i.stack.imgur.com/ABt5u.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ABt5u.gif" alt="GIF 1"></a></p> <p><strong>Ex2 GIF:</strong></p> <p><a href="https://i.stack.imgur.com/onf2z.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/onf2z.gif" alt="GIF 2"></a></p> <p>Links for the datasets used:</p> <p><strong>ex1:</strong></p> <p><a href="https://drive.google.com/open?id=1tztcXVillZTrbPeeCd28djRooM5nkiBZ" rel="nofollow noreferrer">https://drive.google.com/open?id=1tztcXVillZTrbPeeCd28djRooM5nkiBZ</a></p> <p><strong>ex2:</strong></p> <p><a href="https://drive.google.com/open?id=17ZQ4TLA7ThtU-3J-G108a1fzCH72nSFp" rel="nofollow noreferrer">https://drive.google.com/open?id=17ZQ4TLA7ThtU-3J-G108a1fzCH72nSFp</a></p> <p><strong>CODE</strong></p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np import random import imageio import os def compute_cost(b, m, data): """ Compute cost function for univariate linear regression using mean squared error(MSE). Args: b: Intercept (y = mx + b). m: Slope (y = mx + b). data: A pandas df with x and y data. Return: Cost function value. """ data['Mean Squared Error(MSE)'] = (data['Y'] - (m * data['X'] + b)) ** 2 return data['Mean Squared Error(MSE)'].sum().mean() def adjust_gradient(b_current, m_current, data, learning_rate): """ Adjust Theta parameters for the univariate linear equation y^ = hθ(x) = θ0 + θ1x Args: b_current: Current Intercept (y = mx + b) or [Theta(0) θ0]. m_current: Current Slope (y = mx + b) or [Theta(1) θ1]. data: A pandas df with x and y data. learning_rate: Alpha value. Return: Adjusted Theta parameters. """ data['b Gradient'] = -(2 / len(data)) * (data['Y'] - ((m_current * data['X']) + b_current)) data['m Gradient'] = -(2 / len(data)) * data['X'] * (data['Y'] - ((m_current * data['X']) + b_current)) new_b = b_current - (data['b Gradient'].sum() * learning_rate) new_m = m_current - (data['m Gradient'].sum() * learning_rate) return new_b, new_m def gradient_descent(data, b, m, learning_rate, max_iter, visual=False): """ Optimize Theta values for the univariate linear regression equation y^ = hθ(x) = θ0 + θ1x. Args: data: A pandas df with x and y data. b: Starting b (θ0) value. m: Starting m (θ1) value. learning_rate: Alpha value. max_iter: Maximum number of iterations. visual: If True, a GIF progression will be generated. Return: Optimized values for θ0 and θ1. """ line = np.arange(len(data)) folder_name = None if visual: folder_name = str(random.randint(10 ** 6, 10 ** 8)) os.mkdir(folder_name) os.chdir(folder_name) for i in range(max_iter): b, m = adjust_gradient(b, m, data, learning_rate) if visual: data['Line'] = (line * m) + b data.plot(kind='scatter', x='X', y='Y', figsize=(8, 8), marker='x', color='r') plt.plot(data['Line'], color='b') plt.grid() plt.title(f'y = {m}x + {b}\nCurrent cost: {compute_cost(b, m, data)}\nIteration: {i}\n' f'Alpha = {learning_rate}') fig_name = ''.join([str(i), '.png']) plt.savefig(fig_name) plt.close() if visual: frames = os.listdir('.') frames.sort(key=lambda x: int(x.split('.')[0])) frames = [imageio.imread(frame) for frame in frames] imageio.mimsave(folder_name + '.gif', frames) return b, m if __name__ == '__main__': data = pd.read_csv('data.csv') data.columns = ['X', 'Y'] learning = 0.00001 initial_b, initial_m = 0, 0 max_it = 350 b, m = gradient_descent(data, initial_b, initial_m, learning, max_it, visual=True) </code></pre>
[]
[ { "body": "<h3>Nothing happens!</h3>\n\n<p>When I ran the script my first thought was that it had hung because\nnothing happened. Apparently the calculations are just slow on my\ncomputer.</p>\n\n<p>To reassure the user that the program is working, have some output\nindicating progress. Here's how I added it, but you can make it way\nfancier with progress bars and stuff:</p>\n\n<pre><code>n_reports = 20\nfor i in range(max_iter):\n if max_iter &gt;= n_reports and i % (max_iter // n_reports) == 1:\n print(f'{(i * 100 // max_iter)}% ', end = '', flush = True)\n ...\nprint('100%')\n</code></pre>\n\n<p><code>n_reports</code> is the number of times the completion percentage is\nprinted. An impatient user wants it printed more often, a patient one\n(or one with a faster computer) wants it printed less often.</p>\n\n<h3>Temporary directories</h3>\n\n<p>Python has a module for temporary files and directories which you\nshould use instead of creating your own. Also, never change the\nprocess current working directory (the <code>chdir</code> call) unless you have\nto. It can cause very strange problems.</p>\n\n<p>The <code>tempfile</code> and <code>pathlib</code> modules simplifies file handling:</p>\n\n<pre><code>if visual:\n save_dir = pathlib.Path(tempfile.mkdtemp())\n...\nfor i in range(max_iter):\n ...\n if visual:\n ...\n fig_name = f'{i:05}.png'\n plt.savefig(save_dir / fig_name)\n...\nif visual:\n frames = sorted([f.resolve() for f in save_dir.iterdir()])\n frames = [imageio.imread(frame) for frame in frames]\n image_file = save_dir.name + '.gif'\n imageio.mimsave(image_file, frames)\n print(f'Saved image as {image_file}')\n</code></pre>\n\n<p>I also made it so that filenames are padded with zeroes. That way, you\ncan rely on the lexicographical order and you don't have to write your\nown key function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:37:21.567", "Id": "459677", "Score": "0", "body": "What does the `flush = True` in the print statement do? and does the temporary directory (with the .png frames) disappear after the execution and if so, where the .gif file will be saved? and what do you think of the implementation of the algorithm? any suggestions you have regarding how to optimize close to `sklearn` auto-optimization done by the `LinearRegression()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:59:15.290", "Id": "459689", "Score": "0", "body": "It flushes so that the output becomes visible despite lacking an ending newline character. The temporary directory has to be removed with `shutil.rmtree(save_dir)`. The gif is saved in the current directory. Your gradient descent implementation is fine, but lacks learning rate scheduling and early stoppage (detection if an optima is reached). Of course, it is not the right tool for the job and there are better methods for univariate linear regression." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T23:15:48.570", "Id": "459691", "Score": "0", "body": "Thanks for the feedback and I know using `LinearRegression()` is sufficient for the job, I've done it for the sake of understanding how things work as i'm following Andrew NG's course(which is done in Octave and Matlab) so I have to convert everything I learn to Python." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:26:03.927", "Id": "234962", "ParentId": "234936", "Score": "2" } } ]
{ "AcceptedAnswerId": "234962", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T05:15:37.240", "Id": "234936", "Score": "3", "Tags": [ "python", "python-3.x", "animation", "machine-learning" ], "Title": "Gradient Descent Algorithm using Pandas + GIF Visualization" }
234936
<p>I have watched Professor Sheep's Leetcode 140: Word Break II</p> <p><a href="https://www.youtube.com/watch?v=pu9z4qxp76c" rel="nofollow noreferrer">YouTube video here</a></p> <p><a href="https://github.com/jzysheep/LeetCode/blob/master/140.%20Word%20Break%20II.cpp" rel="nofollow noreferrer">CPP code here</a></p> <p>My own Python translation code is below. I am thinking that the code can be optimized by traversing from right to left in this case as the code only start working with the last word. I have submitted both implementation to leetcode and traversing from left executed with 40ms and traversing from right executed with 36ms. </p> <p>I believe that left and right are not the same. Just like in functional programming where foldLeft generally (no language optimization or special cases) have advantage over foldRight. In this case, I believe that approaching from Right has advantage over Left.</p> <p>Please help me validate my thinking or prove me wrong convincingly.</p> <p>From Left (like Professor Sheep)</p> <pre><code>class Solution: def wordBreak(self, s: str, wordDict: List[str]) -&gt; List[str]: dic = set(wordDict) memo = {} def internal(sc): if not sc: return [] if sc in memo: return memo[sc] res = [] if sc in dic: res.append(sc) for pos in range(1, len(sc)): right = sc[pos:] if right not in dic: continue left = sc[:pos] lfls = internal(left) for lf in lfls: res.append(lf + " " + right) memo[sc] = res return res return internal(s) </code></pre> <p>From Right</p> <pre><code> def wordBreak(self, s: str, wordDict): dic = set(wordDict) memo = {} def internal(sc): if not sc: return [] if sc in memo: return memo[sc] res = [] if sc in dic: res.append(sc) for pos in range(len(sc), -1, -1): right = sc[pos:] if right not in dic: continue left = sc[:pos] lfls = internal(left) for lf in lfls: res.append(lf + " " + right) memo[sc] = res return res return internal(s) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:10:19.427", "Id": "459674", "Score": "0", "body": "It is not always the case that left folds have advantage over right folds, at least in lazy languages like Haskell (https://stackoverflow.com/q/384797/5309823) - fold direction is a generally confusing subject though (for me), so perhaps there are not similar issues in other functional languages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:27:41.160", "Id": "459687", "Score": "0", "body": "This algorithm has no relation to foldl or foldr apart from the movement direction. In functional programming, fold left is left associative and fold right is right associative. Fold left is lazy and fold right is not.\nAs for this algorithm, you may be able to find data set that favors one direction or other but, theoretically, the direction part are one and the same whether you go from left to right or right to left." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T03:50:01.367", "Id": "459698", "Score": "0", "body": "I agree that fold left and fold right has nothing to do with this algorithm. I just want to bring out the analogy about some code not treating left and right the same. I also agree that there might be some data that favours one direction over the other. However the majority of the data for the language related ones (cat, dog, words... etc) used in this code are left to right. Thus, I think that processing from the right here will have a bit of advantage." } ]
[ { "body": "<p>The difference in runtime of 4ms is very small compared to normal system variance due to scheduling and whatever background tasks are running. I don't believe that indicates a performance benefit right vs left.</p>\n\n<p>And the only difference between the two approaches (as far as I can see) is which order you iterate the string. Algorithmically speaking going right to left is equivalent to reversing the input strings and going left to right. There is no reason why that should be any faster as it's the exact same algorithm.</p>\n\n<p>There maybe be a small difference due to branch prediction and cache hits in the CPU but this is because the input is slightly different and it exercises the CPU every do slightly differently but it will benefit either method randomly based on the input. The expected relative performance, however, is the same.</p>\n\n<p>I'm sorry but I believe the is nothing to improve here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:00:18.130", "Id": "234939", "ParentId": "234938", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T07:37:31.580", "Id": "234938", "Score": "3", "Tags": [ "python", "performance", "interview-questions" ], "Title": "Traversing from left or from right - Leetcode 140: Word Break II" }
234938
<p>As a simple project to tackle during the holidays I've set to write a simple wrapper around <a href="https://citymapper.com/tools/1063/api-for-robots" rel="nofollow noreferrer">Citymapper's</a> api to familiarise with <code>httr</code>, <code>testthat</code> and a simple CI setup (on CircleCI).</p> <p>The API mainly revolves around 2 things: </p> <ul> <li>Cheking if a given point falls within their covered areas. As on their api docs there are 2 versions of this endpoint (a second one accepts multiple inputs via a JSON payload), I've implemented 2 different functions to reflect this, no idea if it'd make sense to collapse it into one.</li> <li>Computing travel time (using public transport) between two points.</li> </ul> <p>Below you can find the main methods, <a href="https://github.com/andodet/citymappR" rel="nofollow noreferrer">here</a> a link to the repo.</p> <p><strong>get_travel_time.R</strong></p> <pre class="lang-r prettyprint-override"><code>#' Get travel time between two points #' #' Computes estimated travel time between two points using public transport. #' If \code{time} and \code{time_type} are not specified, time of travel will be assumed to be the same time at which the request is made. #' #' @param start_coord Geographical coordinates of the start point in WGS84 '&lt;latitude&gt;,&lt;longitude&gt;' format. #' @param end_coord Geographical coordinates of the arrival point in WGS84 '&lt;latitude&gt;,&lt;longitude&gt;' format. #' @param time A date &amp; time in ISO-8601 format (e.g \code{2014-11-06T19:00:02-0500}). If omitted travel time will be computed for travel at the time of the request. #' @param time_type Required if `time` is provided. At the moment the only defined type is `arrival`, it computes the travel time for arriving at `end_coord` at the given time. #' @inheritParams citymappr_setup #' @return Estimated travel time in minutes (int). #' #' @examples #' \dontrun{ #' get_travel_time(start_coord = "45.448643,9.207645", #' end_coord = "45.452349,9.180225") #' } #' #' #' @importFrom httr GET stop_for_status content #' @importFrom jsonlite fromJSON #' #' @export get_travel_time &lt;- function(start_coord, end_coord, time="", time_type="", api_token = Sys.getenv("CITYMAPPER_API_TOKEN")) { resp &lt;-GET(url = "https://developer.citymapper.com/api/1/traveltime/", query = list( key = api_token, startcoord = start_coord, endcoord = end_coord, time = time, time_type = time_type ) ) stop_for_status(resp) return( fromJSON( content(resp, "text"))$travel_time_minutes ) } </code></pre> <p><strong>check_coverage.R</strong></p> <pre class="lang-r prettyprint-override"><code>#' Check if a point is in covered area #' #' Checks if a given point falls within Citymapper's covered areas. #' It is good practice to refresh this value regularly as covered areas might change. #' #' @inheritParams citymappr_setup #' @param point Geographical coordinates of the point in WGS84 \code{'&lt;latitude&gt;,&lt;longitude&gt;'} format. #' @return A tibble containing boolean responses for each point. #' #' @importFrom magrittr %&gt;% #' @importFrom rlang .data #' @importFrom httr GET content stop_for_status #' @importFrom jsonlite fromJSON #' @importFrom dplyr mutate #' @importFrom tibble as_tibble #' #' @examples #' \dontrun{ #' check_coverage("45.448643,9.207645") #' } #' #' @export check_coverage &lt;- function(point, api_token=Sys.getenv("CITYMAPPER_API_TOKEN")) { resp &lt;- GET(url="https://developer.citymapper.com/api/1/singlepointcoverage/", query = list(key = api_token, coord = point)) stop_for_status(resp) return( fromJSON( content(resp, "text"))[["points"]]$covered ) } </code></pre> <p><strong>check_coverage_multi.R</strong></p> <pre class="lang-r prettyprint-override"><code>#' Checks if multiple points are in covered area #' #' Checks if multiple points fall within Citymapper's covered areas. #' It is good practice to refresh this values regularly as covered areas might change. #' #' @inheritParams citymappr_setup #' @param points Dataframe containing geographical coordinates of the start point in WGS84 \code{'&lt;latitude&gt;,&lt;longitude&gt;'} format. #' Columns should be set as \code{id (optional)} and \code{coord}. #' @return A tibble containing boolean responses for each point. IDs column passed in \code{points} will be mirrored back in response. #' #' @examples #' \dontrun{ #' # Make dataframes with coordinates and (optional) ids #' #' } #' #' @seealso \code{\link{check_coverage}} #' #' @importFrom magrittr %&gt;% #' @importFrom jsonlite fromJSON toJSON #' @importFrom httr POST content stop_for_status #' @importFrom tibble as_tibble #' #' @export #TODO: there are problems with json parsin (coords are not parsed as a list) check_coverage_multi &lt;- function(points, api_token=Sys.getenv("CITYMAPPER_API_TOKEN")) { if (!is.data.frame(points)) { points &lt;- as_tibble(points) } # Check if column name respect c("id", "coord") convention if(!all(c("coord") %in% names(points))) { stop("Dataframe has wrong column names, make sure they are set as c('id', 'coord')") } # Get input in required JSON format points$coord &lt;- lapply( strsplit(as.character(points$coord), ","), as.numeric ) cured_input &lt;- toJSON(list(`points` = points)) resp &lt;- POST(paste0("https://developer.citymapper.com/api/1/coverage/?key=", api_token), body = cured_input, encode="json") stop_for_status(resp) return( fromJSON( content(resp, "text"))[["points"]] ) } </code></pre> <p>Even being quite a simple package, it'd be good to understand if project structure makes sense and if there's any room for improvement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-09T12:21:11.490", "Id": "460576", "Score": "0", "body": "By the way, on L41 of [`check_coverage_multi.R`](https://github.com/andodet/citymappR/blob/c0f0fd4cb1391bf425d0118353fab73e79f19e64/R/check_coverage_multi.R#L41), are you sure you don't mean `!all(c(\"id\", \"coord\") %in% names(points))`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-09T12:44:46.697", "Id": "460580", "Score": "0", "body": "Good questions, I am checking just for the `coord` columns as it's mandatory (`id` is optional as it'll be just mirrored back from the endpoint for quick reference). Is there a more elegant solution? I do believe I left that `if(!all(...))` there as I began checking for both fields in the first place." } ]
[ { "body": "<p>I think overall, it looks quite good. Some polishing is needed before you submit to CRAN (e.g. you didn't update the <code>Title</code> and <code>Description</code> fields in your <code>DESCRIPTION</code>). Below are also specific points you might want to consider.</p>\n\n<h2>Structure of your specific project</h2>\n\n<ul>\n<li><p>In terms of structure, I don't really understand the need of having two separate functions for checking coverage for a single point and for multiple points. I know the API has two different URLs for this but surely, it would be simpler for users if they have a single function that works no matter if they provide one or multiple points. Or am I missing something here?</p></li>\n<li><p>Currently, if the user didn't register an API key, they get a cryptic error message (<code>Forbidden (HTTP 403)</code>). It might be better to check if <code>api_token</code> is empty and return a more specific error message.</p></li>\n<li><p>You seem to import a lot of packages and functions that (as I far as I can tell) you're not using. If this is actually the case, it might be good to remove them from your dependency list.</p></li>\n</ul>\n\n<h2>General package structure comments</h2>\n\n<ul>\n<li><p>Add a <code>BugReports</code> field to your <code>DESCRIPTION</code> to guide users to the appropriate place to report issues and contribute patches.</p></li>\n<li><p><a href=\"https://cran.r-project.org/web/licenses/MIT\" rel=\"nofollow noreferrer\">According to CRAN</a>, your <code>LICENSE</code> file should only contain two lines with your name and the year, not the full license text.</p></li>\n<li><p>You have non-standard files in your package root, namely <code>circle.yml</code> (should be add to <code>.Rbuildignore</code>) and <code>citymappR_logo.png</code> (<a href=\"https://github.com/ropensci/rotemplate/issues/19#issuecomment-506315565\" rel=\"nofollow noreferrer\">should be moved to <code>man/figures</code></a>).</p></li>\n</ul>\n\n<h2>Specific points relevant to API packages:</h2>\n\n<ul>\n<li><a href=\"https://httr.r-lib.org/articles/api-packages.html#set-a-user-agent\" rel=\"nofollow noreferrer\">It is good practice to set a custom user agent for API package</a>, including your contact, so that API developers know where the requests come from and can reach you if necessary.</li>\n</ul>\n\n<h2>Optional:</h2>\n\n<ul>\n<li><a href=\"https://roxygen2.r-lib.org/articles/rd-formatting.html\" rel=\"nofollow noreferrer\">Your roxygen comments can use the markdown syntax</a> if you like. Personally I prefer it as I find it more readable in its unparsed state but it's not an obligation and it's up to you.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T15:32:14.627", "Id": "460134", "Score": "0", "body": "Many thanks for you time. I don't think I'll submit it to CRAN as it is just a pet project I've developed during some free time. Thanks for the spot-on feedback, especially regarding folder structure and the custom user-agent." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T12:29:10.000", "Id": "235162", "ParentId": "234940", "Score": "2" } } ]
{ "AcceptedAnswerId": "235162", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T09:22:19.650", "Id": "234940", "Score": "4", "Tags": [ "api", "r" ], "Title": "Citymapper API wrapper" }
234940
<p>I'm writing some Python code that will handle huge datasets.</p> <p>On a small scale, this snippet works fine, but as the datasets become bigger it grinds my script to a halt (I know it is this part as I have surrounded all the possible offenders with timers, and this one takes the longest):</p> <pre><code>#example variables neighbours = [1, 5, 2, 6, 3, 8] coverage = {1:0, 2:3, 3:1, 4:4, 5:1, 6:2, 7:4, 8:1} is_repeat = True for n in neighbours: if coverage.get(n,0)&lt;2: is_repeat = False break </code></pre> <p>The loop prevents the same list of values being handled more than twice - if at least one element of the list has not been handled twice then the list is still handled further on making the <code>is_repeat</code> flag crucial to the next steps.</p> <p>How can I optimise this section?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T10:33:54.103", "Id": "459610", "Score": "0", "body": "What is the purpose of your loop? Is `is_repeat` flag the crucial variable that coordinates further processing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T10:36:17.767", "Id": "459611", "Score": "0", "body": "@RomanPerekhrest the loop prevents the same list of values being handled more than twice - if at least one element of the list has not been handled twice then the list is still handled further on, so the is_repeat flag is indeed crucial to the next steps. I will edit my question to reflect that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:52:30.993", "Id": "459639", "Score": "0", "body": "I don't think there's a way to optimize this piece of code in isolation in such a way as to have it do the same thing, but maybe there's some other way to accomplish the wider aim? Could you maybe keep track of the aggregate \"is_repeat\" state for this list of values as you're handling it the previous time so you don't need to go back through it later to re-compute that state?" } ]
[ { "body": "<p>The more \"Pythonic\" way (aka using Pythonic syntactic sugar to make the code more concise) of writing this:</p>\n\n<pre><code>is_repeat = True\nfor n in neighbours:\n if coverage.get(n,0)&lt;2:\n is_repeat = False\n break\n</code></pre>\n\n<p>would be:</p>\n\n<pre><code>is_repeat = all([coverage.get(n, 0) &gt;= 2 for n in neighbors])\n</code></pre>\n\n<p>but I'm not sure this will necessarily be any more efficient.</p>\n\n<p>Is <code>is_repeat</code> true most of the time (forcing this iteration to go through all of the neighbors)? If so, maybe the thing to focus on is optimizing earlier detection of that case in some other part of the script where it'll be easier to figure out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:27:29.620", "Id": "459714", "Score": "0", "body": "It's True about half of the time.\nThank you for your answer though! I will see if there is anything I can do earlier in the code but this has given me some helpful pointers :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:21:58.407", "Id": "234961", "ParentId": "234941", "Score": "2" } } ]
{ "AcceptedAnswerId": "234961", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T10:02:58.937", "Id": "234941", "Score": "-1", "Tags": [ "python", "performance", "hash-map" ], "Title": "Comparing dictionary values from list" }
234941
<p>I'm a 14year old and still learning. I know everyone says "don't roll your own crypto", however I decided I must make my own cipher in javascript as soon as I have enough knowledge.</p> <p>I started simple with simple ciphers like caesar and vigenère.<br> But then learned about binary-based ciphers.<br> I even created my mutation of the aes <a href="https://github.com/Franatrtur/My#mycryptojs" rel="nofollow noreferrer">MCS</a></p> <p>But this was just copied aes. Now I created a smaller version of the previous crypto > MiniCiph.js.<br> I tried to make it compatible with all browsers.<br> It includes crc32 key-derivation function, encodings (Latin1, Hex, Base64, Utf8 and <strong>words↔bytes</strong>), null-padding and the new cipher <strong>Sentece</strong> (because it is word-based).<br> It is a binary <strong>32bit-words - based</strong> cipher I designed.<br> It takes a 128bit(4 words) block, 128bit key and produces 128bit output.<br> It is still a bit similar to AES, but just a bit.</p> <p>Sentece algorithm explanation:</p> <blockquote class="spoiler"> <p>input text gets converted to bytes grouped by four to 32bit words<br> words get grouped by 4 into 128bit blocks and goes through the encryption round below 7 times:<br> 1) <strong>Permute words</strong> every word get xored with 0xc9a74e5b, and goes through bluring step for bytes and gets converted to an entirely different word<br> 2) <strong>Rotate words</strong> every word gets rotated by (position * 8 - 5) bits:<br> 1st->by 3 bits, 2dn->by 11 bits, 3rd->by 19 bits, 4th->by 27bits<br> 3) <strong>Xor with key</strong> every word from the block gets xored with the responding word of the key<br> 4) <strong>Permute block</strong> the whole block goes through the bluring step for words for every word of the key to have impact on every word of the block<br> + <strong>Bluring step</strong> expects 4 input integers. Every int (except the 1st one) gets xored with the previous one, their order reverse and the same process is done again, ints in the original order are returned</p> </blockquote> <p>I thought it would be much faster since it is simpler and word-based, and it is, but when it comes to input data larger than 60kB, it is suddenly <strong>very slow</strong>. </p> <p>I wanted to ask why is it takes less than a second to encrypt 30kB file,<br> but it takes nearly 7 times more to encrypt a 80kB file?<br> Is it secure?<br> <strong>And any other suggestions about the code/performance/usage.</strong><br> Also I'm <em>not</em> putting the file-encryption script here (it is done with FileReader)</p> <p><strong>Sentence.js</strong></p> <pre><code>//Sentence.js v1.3 by FranaTrtur //Copyright (c) 2020 František Artur Čech var Sentence = {}; Sentence._SubWord = function(word, forwards){ forwards = typeof forwards == "undefined" ? true : !!forwards; if(forwards) word ^= 3383184987; var bytes = [word &gt;&gt;&gt; 24, word &lt;&lt; 8 &gt;&gt;&gt; 24, word &lt;&lt; 16 &gt;&gt;&gt; 24, word &lt;&lt; 24 &gt;&gt;&gt; 24]; var rot3 = function(byte){return (byte &lt;&lt; 3 | byte &gt;&gt; 5) &lt;&lt; 24 &gt;&gt;&gt; 24;}; if(forwards){ bytes[1] ^= bytes[0]; bytes[2] ^= bytes[1]; bytes[3] ^= bytes[2]; bytes[2] ^= rot3(bytes[3]); bytes[1] ^= rot3(bytes[2]); bytes[0] ^= rot3(bytes[1]); } else{ bytes[0] ^= rot3(bytes[1]); bytes[1] ^= rot3(bytes[2]); bytes[2] ^= rot3(bytes[3]); bytes[3] ^= bytes[2]; bytes[2] ^= bytes[1]; bytes[1] ^= bytes[0]; } var fin = bytes[0] &lt;&lt; 24 | bytes[1] &lt;&lt; 16 | bytes[2] &lt;&lt; 8 | bytes[3]; return forwards ? fin : fin ^ 3383184987; }; Sentence._DoExpandKey = function(key){ var rot21 = function(word){return word &lt;&lt; 21 | word &gt;&gt;&gt; 11;}; var rotWord = Sentence._SubWord(rot21(key[3]), true); var word0 = rotWord ^ key[0] ^ 452984832; var word1 = word0 ^ key[1]; var word2 = word1 ^ key[2]; var word3 = word2 ^ key[3]; return [word0, word1, word2, word3]; }; Sentence._DoCryptBlock = function(block, key, rounds){ rounds = typeof rounds == "number" ? rounds : 7; var rot = function(word, shift){return word &lt;&lt; shift | word &gt;&gt;&gt; (32 - shift);}; var temp = block.slice(0), tempkey = key.slice(0); for(var rnd = 0; rnd &lt; rounds; rnd++){ temp[0] = rot(Sentence._SubWord(temp[0], true), 3); temp[1] = rot(Sentence._SubWord(temp[1], true), 11); temp[2] = rot(Sentence._SubWord(temp[2], true), 19); temp[3] = rot(Sentence._SubWord(temp[3], true), 27); temp[0] ^= tempkey[0]; temp[1] ^= temp[0] ^ tempkey[1]; temp[2] ^= temp[1] ^ tempkey[2]; temp[3] ^= temp[2] ^ tempkey[3]; temp[2] ^= temp[3]; temp[1] ^= temp[2]; temp[0] ^= temp[1]; tempkey = Sentence._DoExpandKey(tempkey); } return temp; }; Sentence._DeCryptBlock = function(block, key, rounds){ rounds = typeof rounds == "number" ? rounds : 7; var rot = function(word, shift){return word &lt;&lt; shift | word &gt;&gt;&gt; (32 - shift);}; var schedule = [key]; for(var rn = 1; rn &lt; rounds; rn++) schedule.unshift(Sentence._DoExpandKey(schedule[0])); var temp = block.slice(0), tempkey; for(var rnd = 0; rnd &lt; rounds; rnd++){ tempkey = schedule[rnd]; temp[0] ^= temp[1]; temp[1] ^= temp[2]; temp[2] ^= temp[3]; temp[3] ^= temp[2] ^ tempkey[3]; temp[2] ^= temp[1] ^ tempkey[2]; temp[1] ^= temp[0] ^ tempkey[1]; temp[0] ^= tempkey[0]; temp[0] = Sentence._SubWord(rot(temp[0], 32 - 3), false); temp[1] = Sentence._SubWord(rot(temp[1], 32 - 11), false); temp[2] = Sentence._SubWord(rot(temp[2], 32 - 19), false); temp[3] = Sentence._SubWord(rot(temp[3], 32 - 27), false); } return temp; }; Sentence._DoXorBlocks = function(block1, block2){ return [ block1[0] ^ block2[0], block1[1] ^ block2[1], block1[2] ^ block2[2], block1[3] ^ block2[3] ]; }; Sentence._RandWords = function(quantity){ quantity = typeof quantity == "number" ? quantity : 4; var words = []; for(var wwr = 0; wwr &lt; quantity; wwr++) words[wwr] = Math.floor(Math.random() * 4294967296) &lt;&lt; 0; return words; }; Sentence._DoPad = function(bytes){ while(bytes.length % 16 != 0) bytes.push(0); return bytes; }; Sentence._UnPad = function(bytes){ while(bytes[bytes.length - 1] === 0) bytes.pop(); return bytes; }; Sentence._DoFormat = function(words, splitby){ splitby = typeof splitby == "number" ? splitby : 4; var blocks = []; for(var st = 0; st &lt; words.length; st += splitby) blocks.push(words.slice(st, st + splitby)); return blocks; }; Sentence._DeFormat = function(blocks){ var words = []; for(var block = 0; block &lt; blocks.length; block++) words = words.concat(blocks[block]); return words; }; Sentence.CFB = { encrypt: function(data, key, rounds, iv){ var blocks = Sentence._DoFormat(data); var init = [iv]; for(var state = 0; state &lt; blocks.length; state++){ init[state] = Sentence._DoCryptBlock(init[state], key, rounds); blocks[state] = Sentence._DoXorBlocks(init[state], blocks[state]); init[state + 1] = blocks[state]; } return Sentence._DeFormat(blocks); }, decrypt: function(data, key, rounds, iv){ var blocks = Sentence._DoFormat(data); var init = [iv].concat(blocks); for(var state = 0; state &lt; blocks.length; state++){ init[state] = Sentence._DoCryptBlock(init[state], key, rounds); blocks[state] = Sentence._DoXorBlocks(init[state + 1], init[state]); } return Sentence._DeFormat(blocks); } }; Sentence.CTR = { encrypt: function(data, key, rounds, iv, cnt){ var blocks = Sentence._DoFormat(data); var increment = function(cnt){ cnt.reverse(); for(var i = 0; i &lt; cnt.length; i++){ if(cnt[i] &gt;= 4294967295) cnt[i] = 0; else{ cnt[i]++; break; } } return cnt.reverse(); }; var counter = Array.isArray(cnt) ? cnt : [0, 0]; var init; for(var state = 0; state &lt; blocks.length; state++){ init = Sentence._DoXorBlocks(iv, counter); init = Sentence._DoCryptBlock(init, key, rounds); blocks[state] = Sentence._DoXorBlocks(init, blocks[state]); increment(counter); } return Sentence._DeFormat(blocks); }, decrypt: function(data, key, rounds, iv, cnt){ return Sentence.CTR.encrypt(data, key, rounds, iv, cnt); } }; Sentence.CBC = { encrypt: function(data, key, rounds, iv){ var blocks = Sentence._DoFormat(data); var init = [iv]; for(var state = 0; state &lt; blocks.length; state++){ blocks[state] = Sentence._DoXorBlocks(blocks[state], init[state]); blocks[state] = Sentence._DoCryptBlock(blocks[state], key, rounds); init[state + 1] = blocks[state]; } return Sentence._DeFormat(blocks); }, decrypt: function(data, key, rounds, iv){ var blocks = Sentence._DoFormat(data); var init = [iv].concat(Sentence._DoFormat(data)); for(var state = 0; state &lt; blocks.length; state++){ blocks[state] = Sentence._DeCryptBlock(blocks[state], key, rounds); blocks[state] = Sentence._DoXorBlocks(blocks[state], init[state]); } return Sentence._DeFormat(blocks); } }; Sentence.Enc = {}; Sentence.Enc.Latin1 = { parse: function(string){ var bytes = []; for(var chr = 0; chr &lt; string.length; chr++) bytes.push(string.charCodeAt(chr)); return bytes; }, stringify: function(bytes){ var string = ""; for(var byte = 0; byte &lt; bytes.length; byte++) string += String.fromCharCode(bytes[byte]); return string; } }; Sentence.Enc.Base64 = { parse: function(string){ return Sentence.Enc.Latin1.parse(atob(string)); }, stringify: function(bytes){ return btoa(Sentence.Enc.Latin1.stringify(bytes)); } }; Sentence.Enc.Utf8 = { parse: function(string){ return Sentence.Enc.Latin1.parse(unescape(encodeURIComponent(string))); }, stringify: function(bytes){ return decodeURIComponent(escape(Sentence.Enc.Latin1.stringify(bytes))); } }; Sentence.Enc.Hex = { parse: function(string){ var bytes = []; for(var hxcode = 0; hxcode &lt; string.length; hxcode += 2) bytes.push(parseInt(string.charAt(hxcode) + string.charAt(hxcode + 1), 16)); return bytes; }, stringify: function(bytes){ var string = ""; for(var byte = 0; byte &lt; bytes.length; byte++) string += ("00" + bytes[byte].toString(16)).substr(-2); return string; } }; Sentence.Enc.Words = { to: function(bytes){ var words = []; for(var byte = 0; byte &lt; bytes.length; byte += 4) words.push(bytes[byte] &lt;&lt; 24 | bytes[byte + 1] &lt;&lt; 16 | bytes[byte + 2] &lt;&lt; 8 | bytes[byte + 3]); return words; }, from: function(words){ var bytes = []; for(var word = 0; word &lt; words.length; word++) bytes = bytes.concat([words[word] &gt;&gt;&gt; 24, words[word] &lt;&lt; 8 &gt;&gt;&gt; 24, words[word] &lt;&lt; 16 &gt;&gt;&gt; 24, words[word] &lt;&lt; 24 &gt;&gt;&gt; 24]); return bytes; } }; Sentence.DeriveKey = function(string, salt){ var crc32 = function(str){ for(var temp, tab = [], idx = 0; idx &lt; 256; idx++){ temp = idx; for(var bb = 0; bb &lt; 8; bb++) temp = 1 &amp; temp ? 3988292384 ^ temp &gt;&gt;&gt; 1 : temp &gt;&gt;&gt; 1; tab[idx] = temp; } for(var crcint = -1, ix = 0; ix &lt; str.length; ix++) crcint = crcint &gt;&gt;&gt; 8 ^ tab[255 &amp; (crcint ^ str.charCodeAt(ix))]; return -1 ^ crcint; }; var key = []; var saltstr = Array.isArray(salt) ? Sentence.Enc.Latin1.stringify(Sentence.Enc.Words.from(salt)) : "ªU"; key[0] = crc32(string.split("").reverse().join("") + saltstr + string); key[1] = crc32(key[0] + string + saltstr.split("").reverse().join("")); key[2] = crc32(key[0] + string.split("").reverse().join("") + key[1] + saltstr); key[3] = crc32(key[2] + saltstr.split("").reverse().join("") + key[1] + string + key[0] + saltstr); return key; }; Sentence.encrypt = function(string, keyword, mode, dosalt){ mode = typeof mode == "object" ? mode : Sentence.CBC; dosalt = typeof dosalt == "undefined" ? true : !!dosalt; var salt = dosalt ? Sentence._RandWords(2) : false; var data = Sentence.Enc.Words.to(Sentence._DoPad(Sentence.Enc.Utf8.parse(string))); var key = Sentence.DeriveKey(keyword, salt); var iv = Sentence._DoCryptBlock(Sentence._DoXorBlocks(key, salt), Sentence._DoExpandKey(key)); var encrypted = mode.encrypt(data, key, 7, iv); return { mode: mode, words: encrypted, salt: salt, key: key, iv: iv, toBytes: function(){ return Sentence.Enc.Words.from(this.words); }, toString: function(enc, dosalt){ enc = typeof enc == "object" ? enc : Sentence.Enc.Base64; dosalt = this.salt == false ? false : typeof dosalt == "undefined" ? true : !!dosalt; var data = []; if(dosalt) data = Sentence.Enc.Latin1.parse("Salted__").concat(Sentence.Enc.Words.from(this.salt)); data = data.concat(this.toBytes()); return enc.stringify(data); } }; }; Sentence.decrypt = function(strOrObj, keyword, mode){ mode = typeof mode == "object" ? mode : Sentence.CBC; if(typeof strOrObj == "string"){ var parsed = Sentence.Enc.Base64.parse(strOrObj); var salt = Sentence.Enc.Latin1.stringify(parsed.slice(0, 8)) === "Salted__" ? Sentence.Enc.Words.to(parsed.slice(8, 16)) : false; var data = salt ? Sentence.Enc.Words.to(parsed.slice(16)) : parsed; } else if(typeof strOrObj == "object"){ var salt = strOrObj.salt; var data = strOrObj.words; } var key = Sentence.DeriveKey(keyword, salt); var iv = Sentence._DoCryptBlock(Sentence._DoXorBlocks(key, salt), Sentence._DoExpandKey(key)); var decrypted = mode.decrypt(data, key, 7, iv); decrypted = Sentence._UnPad(Sentence.Enc.Words.from(decrypted)); return { mode: mode, bytes: decrypted, salt: salt, key: key, iv: iv, toWords: function(){ return Sentence.Enc.Words.to(this.bytes); }, toString: function(enc){ enc = typeof enc == "object" ? enc : Sentence.Enc.Utf8; return enc.stringify(this.bytes); } }; }; </code></pre> <p>Usage example</p> <pre><code>var encrypted = MiniCiph.encrypt("string", "password"); var decrypted = MiniCiph.decrypt(encrypted, "password"); </code></pre> <p>Sorry for possible language errors, english is not my native language.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T14:53:50.197", "Id": "459618", "Score": "1", "body": "There are a lot of loops in your code, but since you don't want to show us the actual code doing the file-encryption I'm not sure we can help you. After all, it may still go wrong there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:36:04.257", "Id": "459632", "Score": "0", "body": "The file is provided as a string like: \"data:image/jpeg;base64,/9j/4AAQSkZJRgAB...\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-13T15:35:08.307", "Id": "461123", "Score": "0", "body": "Your cipher itself should not rely on being secret *itself*; using the hiding of the scheme is against Kerckhoffs principle. Make it as public as possible so everybody can analyze it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T14:40:01.337", "Id": "234949", "Score": "2", "Tags": [ "javascript", "cryptography", "aes" ], "Title": "Custom mini cipher" }
234949
<p>Hello this is a Console App(.Net Core) in Visual Studio 2019 and i am trying to split a string into sentences and then add them into a dictionary with Key the first word of the sentence and Value the sentence itself. I have the following code and i wonder if the way i did it has of course a better way to handle it.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace StringParse { class Program { static void Main(string[] args) { string phrase = @"MHD001|LOCCOD|GRCACS|20191117|133601|CB|trx_grcacs_tsk_20191117133601498| TSK001|GLS|GRCACS|59144|59144|2|TU|93000161357|TRACE|INF|DE 800|please send us the completely address information-thanks|68481|20191117|133555| TSA001|X| TSI001|3655|please send us the completely address information-thanks|66510| TSI001|5637|80337|61335| TSI001|5841|DE|61313| MTR001|5|"; ///////////////////////////////////////////////////////////////////// string sentenceSeparator = @"\b[A-Z]{3}\d{3}\b"; string[] words = phrase.Split('|'); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; words.Length; i++) { //If current word array matches the regex if (words[i].Equals(sentenceSeparator)) { // If the current array value doesn't match, then continue the current line. sb.Append(words[i]); sb.Append(" "); } else { if (i == 0) { // on the 1st iteration, we don't need a new line before the text value. sb.Append(words[i]); sb.Append(" "); } else { sb.Append(words[i]); sb.Append(" "); } } } string[] sentences = sb.ToString().Split('\r'); //////////////////////////////////////////////////////////////////////// Regex regx = new Regex(sentenceSeparator); MatchCollection matches = Regex. Matches(phrase, sentenceSeparator, RegexOptions.Compiled | RegexOptions.CultureInvariant); for (int i = 1; i &lt; matches.Count; ++i) { phrase = phrase .Replace(matches[i].Value, Environment.NewLine + matches[i].Value); } /////////////////////////////////////////////////////////////////////////////// Dictionary&lt;Match, string&gt; dic = matches.Zip(sentences, (x, y) =&gt; new { Key = x, Value = y }).ToDictionary(x =&gt; x.Key, y =&gt; y.Value); foreach (KeyValuePair&lt;Match, string&gt; kvp in dic) { Console.WriteLine("Key = {0}" + Environment.NewLine + "Value = {1}", kvp.Key, kvp.Value); } } } } </code></pre> <p>output will be like that:</p> <pre><code>Key = MHD001 Value = MHD001 LOCCOD GRCACS 20191117 133601 CB trx_grcacs_tsk_20191117133601498 Key = TSK001 Value = TSK001 GLS GRCACS 59144 59144 2 TU 93000161357 TRACE INF DE 800 please send us the completely address information-thanks 68481 20191117 133555 Key = TSA001 Value = TSA001 X Key = TSI001 Value = TSI001 3655 please send us the completely address information-thanks 66510 Key = TSI001 Value = TSI001 5637 80337 61335 Key = TSI001 Value = TSI001 5841 DE 61313 Key = MTR001 Value = MTR001 5 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:09:04.333", "Id": "459624", "Score": "1", "body": "Did you copy the code directly from your IDE? I am asking because in the first loop the whole `if..else..if..else` seems senseless because in each branch the code is doing the exactly same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:11:11.913", "Id": "459625", "Score": "0", "body": "Yes i did copy it from the IDE..\nfirst i split the phrase into words. then with stringbuilder and the regex i made it like sentence, then i added to another array. \nI do not have experience with C# and thats why i wonder if this is ok" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:31:33.993", "Id": "459648", "Score": "2", "body": "This code doesn't seem to work. It creates an error when compiling with Framework 4.8. `MatchCollection` doesn't contain a `Zip` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:53:00.917", "Id": "459651", "Score": "0", "body": "@tinstaafl good catch. Using `matches.Cast<Match>().Zip...` will succeed without an error, and the dictionary has duplicated keys, thats just strange!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:56:20.647", "Id": "459652", "Score": "0", "body": "Well, maybe it isn't that strange because the key is a `Match` which is different for each `Match` in the `MatchCollection`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:20:50.517", "Id": "459675", "Score": "0", "body": "@tinstaafl how do you say it doesn't work?\ni had it run ,the console app, several times and i got the output i provided.\nAs you can see in the phrase it has some keys that are the same.\n`Dictionary` contains `Zip` not the `MatchCollection`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:34:09.200", "Id": "459676", "Score": "0", "body": "Framework is 4.7.2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:02:11.547", "Id": "459682", "Score": "0", "body": "`matches` is a `MatchCollection` not a `Dictionary`. No version of `MatchCollection` contains a `Zip` method. It can't work as it is. As @Heslacher pointed out it only works with the added `Cast` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:24:01.843", "Id": "459686", "Score": "0", "body": "The one thing i do not understand is that i posted this code on this particular community in order to get my code reviewed and hope to get better solution and better explanation for my future coding style.\nEven though my code is being criticized about every little bit of things expert coders find. \nI do accept every criticism for the code i produced but that's not the point i believe in this StackExchange site. I do not hunt score or badges i just want to be a better coder.\nEven with `Cast` or not this code runs and it produces the output i provided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:07:39.007", "Id": "459703", "Score": "0", "body": "In order to review your code the question needs to be **on topic** which means your code needs to work. We just want to help you making your question on topic. `Zip` is an extension method taking `IEnumerable<T>` but `MatchCollection` only implements `IEnumerable`. I would like to suggest that you create a new console project pasting your posted code and see what your IDE tells you about the `Zip()` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T11:27:01.397", "Id": "459734", "Score": "0", "body": "@Heslacher i did copy-paste my code to a new console app and i just added this `using System.Linq;` and it works the same. Sorry but i can not understand the problem with `Zip`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T11:36:43.640", "Id": "459735", "Score": "0", "body": "@Heslacher i added the `matches.Cast<Match>().Zip...` also but still it needs this `using System.Linq;` in order to work.\ncan we talk somehow in a chat and don't fill the post with comments if thats ok with you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T11:52:38.377", "Id": "459737", "Score": "0", "body": "As it stands, the code as presented looks like it can't quite work as intended, notably how the `sentences` array is constructed would not produce the results outlined as target results. Additionally there is some ambiguity around the use of the `Zip` extension method that should be definitively resolved before this code can be reviewed. As such I have closed this question for now until the code for review is verified to be working as expected. Thanks for understanding" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:00:13.057", "Id": "459738", "Score": "0", "body": "@Vogel612 Sure i understand. I am using Console App(.Net Core) in Visual Studio 2019 and the only dependencies i am having is `Microsoft.NetCore.App`\nand the targeting framework is `4.7.2`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:03:41.403", "Id": "459739", "Score": "2", "body": "Alright, while I don't have a windows at hand, I was able to verify the code as posted works when running it against dotnet core 3.0.100 when targeting netcoreapp3.0. As such I have reopened the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:11:21.937", "Id": "459741", "Score": "1", "body": "Just add ```Cast<Match>()``` and it works ``` Dictionary<Match, string> dic = matches.Cast<Match>().Zip(sentences, (x, y) => new { Key = x, Value = y }).ToDictionary(x => x.Key, y => y.Value);\n```" } ]
[ { "body": "<p>The whole <code>if</code>..<code>else</code>..<code>if</code>..<code>else</code> inside the first loop is senseless because each branch does exactly the same. </p>\n\n<hr>\n\n<p>Using <code>Split('|')</code> and combining the resulting array with one space <code>\" \"</code> is the same like replacing <code>|</code> by a space. </p>\n\n<hr>\n\n<p>The <code>Regex regx = new Regex(sentenceSeparator);</code> is superflous because you don't use <code>regex</code> at all. </p>\n\n<hr>\n\n<p>The loop </p>\n\n<pre><code>for (int i = 1; i &lt; matches.Count; ++i)\n{\n phrase = phrase\n .Replace(matches[i].Value,\n Environment.NewLine + matches[i].Value);\n} \n</code></pre>\n\n<p>is superflous because you aren't using <code>phrase</code> afterwards. </p>\n\n<hr>\n\n<p>As it seems (untested) you can use <code>Zip()</code> with a <code>MatchCollection</code> if you use .NET Core 3.0.100 but to make your code runnable without .NET Core you should change </p>\n\n<pre><code>Dictionary&lt;Match, string&gt; dic = matches.Zip(sentences, (x, y)\n =&gt; new { Key = x, Value = y }).ToDictionary(x =&gt; x.Key, y =&gt; y.Value); \n</code></pre>\n\n<p>to </p>\n\n<pre><code>Dictionary&lt;Match, string&gt; dic = matches.Cast&lt;Match&gt;().Zip(sentences, (x, y)\n =&gt; new { Key = x, Value = y }).ToDictionary(x =&gt; x.Key, y =&gt; y.Value);\n</code></pre>\n\n<hr>\n\n<p>It comes for sure from copying the code (which seems to be posted using <code>Shift + Enter</code> for <code>phrase</code>) from this question to the IDE....if you inspect the result of <code>dict</code> you will see that from the second item on the <code>Value</code> is prepended by a <code>\\n</code>. This can be prevented by using <code>TrimStart('\\n')</code> on <code>y</code> at <code>new { Key = x, Value = y }</code>. </p>\n\n<hr>\n\n<p>Implementing the mentioned points will lead to </p>\n\n<pre><code> static void Main(string[] args)\n {\n string phrase = @\"MHD001|LOCCOD|GRCACS|20191117|133601|CB|trx_grcacs_tsk_20191117133601498|TSK001|GLS|GRCACS|59144|59144|2|TU|93000161357|TRACE|INF|DE 800|please send us the completely address information-thanks|68481|20191117|133555|TSA001|X|TSI001|3655|please send us the completely address information-thanks|66510|TSI001|5637|80337|61335|TSI001|5841|DE|61313|MTR001|5|\";\n\n string[] sentences = phrase.Replace('|',' ').Split('\\r');\n string sentencePattern = @\"\\b[A-Z]{3}\\d{3}\\b\";\n\n MatchCollection matches = Regex.\n Matches(phrase, sentencePattern,\n RegexOptions.Compiled |\n RegexOptions.CultureInvariant);\n\n Dictionary&lt;Match, string&gt; dic = matches.Cast&lt;Match&gt;().Zip(sentences, (x, y)\n =&gt; new { Key = x, Value = y.TrimStart('\\n') }).ToDictionary(x =&gt; x.Key, y =&gt; y.Value);\n\n foreach (KeyValuePair&lt;Match, string&gt; kvp in dic)\n {\n Console.WriteLine(\"Key = {0}\" + Environment.NewLine + \"Value = {1}\", kvp.Key, kvp.Value);\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T10:45:11.967", "Id": "459857", "Score": "0", "body": "thank you for your valuable comments and the great review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T17:41:41.680", "Id": "235026", "ParentId": "234951", "Score": "2" } } ]
{ "AcceptedAnswerId": "235026", "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T14:54:09.073", "Id": "234951", "Score": "1", "Tags": [ "c#", "strings", ".net-core" ], "Title": "String Split a phrase into sentences" }
234951
<p>I built a Brainfuck interpreter. It seems to be working. I ran <a href="http://www.linusakesson.net/programming/brainfuck/" rel="nofollow noreferrer">the game of life</a> and this <a href="https://github.com/mitxela/bf-tic-tac-toe/blob/master/tictactoe-comments.bf" rel="nofollow noreferrer">tic-tac-toe</a> and other programs on it. They worked fine. I'd appreciate any comments on correctness, readability and performance improvements:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;cstdlib&gt; #include &lt;deque&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;stack&gt; #include &lt;utility&gt; #include &lt;vector&gt; #ifdef _MSC_VER #include &lt;ciso646&gt; // and/or/not #endif // !_MSC_VER #ifdef __GNUC__ # define pure_attribute [[gnu::pure]] # define const_attribute [[gnu::const]] #else # define pure_attribut # define const_attribute #endif // __GNUC__ /* "Infinite" unsigned char buffer pointer */ class Pointer { public: using storage_type = std::deque&lt;char&gt;; using size_type = storage_type::size_type; explicit Pointer(size_type const preAllocatedMemory = 1) : mem_(preAllocatedMemory), index_{ 0 } { /* preAllocatedMemory must be at least 1 */ assert(preAllocatedMemory != 0); } auto&amp; operator+=(size_type const c) { index_ += c; /* Allocate memory if needed. */ if (mem_.size() &lt;= index_) mem_.resize(index_ + 1); return *this; } auto operator++() -&gt; Pointer&amp; { return (*this += 1); } auto&amp; operator-=(size_type const c) noexcept { assert(index_ - c &lt; index_); index_ -= c; return *this; } auto operator--() noexcept -&gt; Pointer&amp; { return (*this -= 1); } auto operator++(int) const-&gt;Pointer = delete; /* Expensive and pointless. Use preincrement instead */ auto operator--(int) const-&gt;Pointer = delete; /* Expensive and pointless. Use predecrement instead */ [[nodiscard]] auto operator*() const&amp; -&gt; const storage_type::value_type&amp; { assert(mem_.size() &gt; index_); return mem_[index_]; } [[nodiscard]] auto operator*() &amp; -&gt; storage_type::value_type&amp; { return const_cast&lt;storage_type::value_type&amp;&gt;(*std::as_const(*this)); } private: [[no_unique_address]] storage_type mem_; [[no_unique_address]] size_type index_; }; /* A class that contains one of "&gt;&lt;+-.,[]" and how many times it is supposed to be executed consecutively */ class Command { public: Command(char const ch, std::size_t const sz) : command_{ ch }, count_{ sz } {} [[nodiscard]] auto command() const noexcept { return command_; } [[nodiscard]] auto count() const noexcept { return count_; } enum ActionableCommands : char { PointerIncr = '&gt;', PointerDecr = '&lt;', CellValIncr = '+', CellValDecr = '-', Cout = '.', Cin = ',', LoopBegin = '[', LoopEnd = ']', }; private: char command_; std::size_t count_; }; const_attribute [[nodiscard]] bool operator==(Command const com, char const ch) noexcept { return com.command() == ch; } const_attribute [[nodiscard]] bool operator!=(Command const com, char const ch) noexcept { return not (com == ch); } template &lt;char op, typename T1, typename T2&gt; // Workaround for "-Wconversion" being buggy inline static void operation(T1&amp; t, T2 const t2) noexcept { #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif // __GNUC__ if constexpr (op == '+') t += static_cast&lt;T1&gt;(t2); else if constexpr (op == '-') t -= static_cast&lt;T1&gt;(t2); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ } /* Return false if `ch` is a comment, true if it is a command() */ bool interpret(Command const com, Pointer&amp; p) { auto const ch = com.command(); auto const count = com.count(); switch (ch) { case Command::PointerIncr: { p += count; break; } case Command::PointerDecr: { p -= count; break; } case Command::CellValIncr: { operation&lt;'+'&gt;(*p, count); break; } case Command::CellValDecr: { operation&lt;'-'&gt;(*p, count); break; } case Command::Cout: { std::fill_n(std::ostream_iterator&lt;unsigned char&gt;(std::cout), count, *p); break; } case Command::Cin: { for (std::size_t i = 0; i != count; ++i) { std::cin &gt;&gt; *p; } break; } default: /* Everything else is a comment */ return false; } return true; } /* Skips from `[` to the corresponding `]` taking account nested loops. */ template &lt;typename BidirIter&gt; [[nodiscard]] auto skipLoop(BidirIter p) noexcept { assert(*p == Command::LoopBegin); std::size_t bracketCount = 0; do { if (*p == Command::LoopBegin) ++bracketCount; else if (*p == Command::LoopEnd) --bracketCount; ++p; } while (bracketCount != 0); return p - 1; } /* Is `[` or `]` */ const_attribute [[nodiscard]] auto isLoopCommand(char const ch) noexcept -&gt; bool { switch (ch) { case Command::LoopBegin: case Command::LoopEnd: return true; default: return false; } } /* Is one of the actionable 8 characters */ const_attribute [[nodiscard]] auto isCommand(char const ch) noexcept -&gt; bool { switch (ch) { case Command::LoopBegin: case Command::LoopEnd: case Command::PointerIncr: case Command::PointerDecr: case Command::CellValIncr: case Command::CellValDecr: case Command::Cout: case Command::Cin: return true; default: return false; } } /* Skip all characters until for one `isCommand` returns true. */ template &lt;typename InputIter&gt; [[ nodiscard ]] auto skipComment(InputIter beg, InputIter const end) { while (beg != end and not isCommand(*beg)) ++beg; return beg; } template &lt;typename InputIter&gt; [[nodiscard]] auto generateSourceCode(InputIter beg, InputIter const end) { std::vector&lt;Command&gt; source_code; while (beg != end) { auto const ch = *beg; std::size_t count = 0; if (isLoopCommand(ch)) { // Executing more than 1 loop command doesn't work. ++count; ++beg; } else if (isCommand(ch)) { // Accumulate commands while ((beg = skipComment(beg, end)) != end and *beg == ch) { ++count; ++beg; } } else { /* Everything else is a comment and is ignored. */ ++beg; } source_code.emplace_back(ch, count); } return source_code; } int main(int const argc, char* const argv[]) { Pointer p; if (argc &lt; 2) { std::cerr &lt;&lt; "Source-code file name needed\n"; return EXIT_FAILURE; } std::ifstream f{ argv[1] }; if (not f.is_open()) { std::cerr &lt;&lt; "Can't open the source-code file \n"; return EXIT_FAILURE; } using StremIter = std::istream_iterator&lt;char&gt;; const auto sourceCode = generateSourceCode(StremIter{ f }, StremIter{}); auto it = sourceCode.cbegin(); auto const end = sourceCode.cend(); std::stack&lt;decltype(it)&gt; loopPos; /* Here we log loops */ while (it != end) { /* Firstly we consider loops */ if (*it == Command::LoopBegin) { /* If the current cell is zero, skip the loop. */ if (*p == 0) { it = skipLoop(it); } else /* Else, log the loop starting */ { loopPos.push(it); } ++it; } else if (*it == Command::LoopEnd) /* Jump to the last `]` */ { assert(not loopPos.empty()); it = loopPos.top(); loopPos.pop(); /* don't increment `it` */ } else { interpret(*it, p); ++it; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:31:14.157", "Id": "459647", "Score": "0", "body": "`[[no_unique_address]]` is C++20" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:09:45.883", "Id": "459654", "Score": "0", "body": "@Aganju yes, you're right. Thank you for the feedback. Since a confirming C++17 compiler should ignore unrecognized attributes, it should be alright." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T19:29:37.123", "Id": "459666", "Score": "0", "body": "If it is alright for `no_unique_address` then why do this `# define pure_attribute [[gnu::pure]]` You should be consistent in how you apply attributes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T20:13:31.007", "Id": "459668", "Score": "0", "body": "@MartinYork Which approach would you recommend? Ignored attributes cause warnings, do `#define` seems a little cleaner? I am open for all suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:05:45.473", "Id": "459683", "Score": "0", "body": "@Ayxan I don't mind either approach. But one of the core principles in programming is consistency. I don't want to have to figure out two different approaches in the same code base." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T02:29:32.413", "Id": "459696", "Score": "0", "body": "@Ayxan Define is better because it allows you to compile with `-Werror` (and `/WX` on MSVC)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T06:28:44.707", "Id": "459843", "Score": "0", "body": "@BjörnLindqvist Yes if one causes a warning and the other nothing. Then go with the variant with no warning (so you can compile clean)." } ]
[ { "body": "<h1>Be a bit more consistent formatting the code</h1>\n\n<p>You are not very consistent with spaces around operators in function declarations, for example:</p>\n\n<pre><code>auto operator--() noexcept -&gt; Pointer&amp; { return (*this -= 1); }\nauto operator++(int) const-&gt;Pointer = delete;\n</code></pre>\n\n<p>Also, I recommend that even for one-liner functions, you put the body of the function on a separate line. If the classes were split out into their own source and header files, then it would help when looking at the declaration of the class in the header file, because you can then more easily see which member functions are merely declared, or whether their definition is available in-line.</p>\n\n<h1>Use more whitespace to clarify the structure of your code</h1>\n\n<p>Use empty lines to separate sections inside functions from each other visually, so it is easier to see the structure of your code. For example, to make it easier to distinguish initialization, the main loop and the return statement in <code>skipLoop()</code>:</p>\n\n<pre><code>template &lt;typename BidirIter&gt;\n[[nodiscard]] auto skipLoop(BidirIter p) noexcept {\n assert(*p == Command::LoopBegin);\n std::size_t bracketCount = 0;\n\n do {\n if (*p == Command::LoopBegin)\n ++bracketCount;\n else if (*p == Command::LoopEnd)\n --bracketCount;\n\n ++p;\n } while (bracketCount != 0);\n\n return p - 1;\n}\n</code></pre>\n\n<h1>Avoid <code>const</code>-casting</h1>\n\n<p>You don't need a <code>const</code> version of <code>operator*()</code>. The following should be enough:</p>\n\n<pre><code>[[nodiscard]] auto operator*() &amp; -&gt; storage_type::value_type&amp; {\n assert(mem_.size() &gt; index_);\n return mem_[index_];\n}\n</code></pre>\n\n<p>This avoids the complicated <code>const</code>-casting that is going on. If you really need <code>const Pointer</code>s in the future, I would just write two copies of this function without any casts.</p>\n\n<h1>Safe checking of integer overflow</h1>\n\n<p>You have the following check in <code>operator-=()</code>:</p>\n\n<pre><code>assert(index_ - c &lt; index_);\n</code></pre>\n\n<p>Where both <code>index_</code> and <code>c</code> are of type <code>size_type</code>. This works for <code>storage_type = std::deque&lt;char&gt;</code>, since its <code>std::dequeue::size_type</code> is guaranteed to be an <code>unsigned</code> integer type. However, assuming that you want this code to be generic enough so you can safely use any other container, you should not make this assumption.</p>\n\n<p>If <code>size_type</code> were a <code>signed</code> integer type, then since signed integer wraparound is undefined behaviour in C++, the compiler is free to assume that wraparound never happens, and so it will likely optimize away this test. The proper way to test this is:</p>\n\n<pre><code>assert(c &gt; 0 &amp;&amp; c &lt;= index_);\n</code></pre>\n\n<p>Also note that you have no matching assertion in <code>operator+=()</code>.</p>\n\n<h1>Consider using <code>enum class</code></h1>\n\n<p>Make <code>ActionableCommands</code> an <code>enum class</code>. Yes, this will require a lot more <code>static_cast</code>ing, but it results in safer code. The compiler can warn if you miss a case in <code>switch</code>-statements, and you can't accidentily have something that is not a command implicitly converted to one.</p>\n\n<h1>Split <code>operation&lt;&gt;()</code> in separate functions</h1>\n\n<p>I don't see any good reason for a function <code>operation()</code> that is templated on a constant, and then does something completely different depending on that constant. Just make two functions, <code>operation_plus()</code> and <code>operation_minus()</code>. But:</p>\n\n<h1>Don't hide potentially unsafe <code>static_cast</code>s</h1>\n\n<p>The sole reason for <code>operation&lt;&gt;()</code> seems to be to do a <code>static_cast</code> and to tell the compiler to ignore potential unsafe behavior. It would be better if you could just write the following in <code>interpret()</code>:</p>\n\n<pre><code>case Command::CellVarIncr:\n *p += count;\n break;\ncase Command::CellVarDecr:\n *p -= count;\n break;\n</code></pre>\n\n<p>And if the compiler ever warns, find a way to fix the code instead of disabling the warnings.</p>\n\n<h1>Check for read errors when reading from a file</h1>\n\n<p>Even if you succesfully opened a <code>std::ifstream</code>, there can be an error later on while reading from the file. So be sure to check its state after reading in the source code, using <code>if (f.fail()) { /* handle error */ }</code>.</p>\n\n<h1>Don't overengineer</h1>\n\n<p>This might be a subjective thing, but I feel that you are overengineering your code. If you were implementing a library, a lot of the templating and attributes would certainly be justified, but if you are just writing an executable that parses and executes Brainfuck code, it's a bit of a wasted effort. <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a> and <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T17:22:35.967", "Id": "459899", "Score": "0", "body": "Thank you for the review. Here are a few questions/points:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T17:24:02.207", "Id": "459901", "Score": "0", "body": "(Avoid const-casting) I understand the suggestion to keep the code simple, but are you suggesting to duplicate the code instead? I think this is one of the very few situations `const_cast` was even created for. So I am thinking it's a bit of well known already? I may be wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T17:26:18.950", "Id": "459902", "Score": "0", "body": "(Don't hide potentially unsafe static_casts) Originally I had an explicit cast inplace instead of the function, but in my version of GCC `-Wconversion` was buggy. It was complaining about the explicit cast I had there, which shouldn't happen (it wasn't happening on MSVC) so I googled it, and turns out it was a bug. Hence the function to work around the compiler bug." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T17:30:12.637", "Id": "459903", "Score": "0", "body": "(Split operation<>() in separate functions) \"I don't see any good reason for a function `operation()` that is templated on a constant, and then does something completely different depending on that constant. Just make two functions, `operation_plus()` and `operation_minus()`\". Again, this function wasn't a planned thing, and I was planning to remove it once we upgraded to a newer and hopefully bug-free version of GCC. Here I was merely trying to avoid the duplication of the warning disabling bit of code so I can more easily identify and remove it all later on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T17:30:49.917", "Id": "459904", "Score": "0", "body": "I agree with everything else you commented (+1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T19:18:06.350", "Id": "459921", "Score": "0", "body": "I agree with you that you should try to avoid duplicated code. In the code your posted, the function is just two lines of code, so it's really not an issue. But if it were longer, then I recommend that you split out the common functionality into a third function. For example, if calculating the index would be more complex, put that into its own `private` member function (which can even do the `assert()`), and have both the `const` and non-`const` version call it before returning a reference to an element of `mem_[]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T19:19:53.990", "Id": "459922", "Score": "0", "body": "Out of curiosity, which version of GCC did you use that had the bugs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T10:51:53.203", "Id": "459967", "Score": "0", "body": "GCC 9.2.0. If I did `*p += static_cast<char>(count);` I would get: `error: conversion from 'int' to 'std::deque<char>::value_type' {aka 'char'} may change value [-Werror=conversion]` even though this is an explicit cast and and no `int` is involved whatsoever." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-22T07:03:47.300", "Id": "462147", "Score": "0", "body": "the sign-conversion bug seems to be fixed in GCC 10: [G++ no longer emits bogus -Wsign-conversion warnings with explicit casts.](https://gcc.gnu.org/gcc-10/changes.html)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T16:00:11.007", "Id": "235077", "ParentId": "234952", "Score": "3" } } ]
{ "AcceptedAnswerId": "235077", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T15:00:57.440", "Id": "234952", "Score": "2", "Tags": [ "c++", "interpreter", "brainfuck" ], "Title": "Brainfuck Interpreter in C++17" }
234952
<p>This is a Python program that takes data from Quandl Databases and formats it for my Neural Network to Train.</p> <p>The code works but I'm not so confident in my code styling conventions. If you would like to review this code with any styling suggestions on how to reformat the code (with respect to PEP8), feel free to review.</p> <pre><code> import pandas as pd import pandas_datareader as dr from sklearn import preprocessing import numpy as np from collections import deque import random class DataSet: ''' Represents a formatted, scaled, and preprocessed dataset for the neural network to use ''' def __init__(self,ticker,time_ahead): ''' :param ticker- the symbol for the stock: :param time_ahead- the time ahead we want to predict: ''' #Pandas dataframe to use for formatting the data self.df = pd.DataFrame() self.ticker = ticker self.time_ahead = time_ahead #Pandas dataframe for formatting the validation data self.val_df = pd.DataFrame() #Sequence Length self.seq_len = time_ahead*5 #List of Training Data and Prediction Set self.sequential_data = [] self.prediction_set = [] @staticmethod def __classifiy_target(current, future): ''' Classifies the data set whether to be BUY (1) or SELL (0) :param current price: :param future price: :return: 1 or 0 ''' if float(future) &gt; float(current): return 1 else: return 0 def __get_data_from_quandl(self): ''' Grab data from quandl database with api, from WIKI/Prices :return: ''' try: #Grab Data of specified stock from WIKI table self.df = dr.get_data_quandl('WIKI/{}'.format(self.ticker), api_key='mauS86cm-z7iYixknxcz') #Convert index to datetime stamp (original format is date string) self.df.index = pd.to_datetime(self.df.index).astype(int) / 10 ** 9 print(self.df.head()) except Exception as e: raise ValueError('The Following Error has occured: {} \n Make sure \'API Key\' and \'Stock Ticker\' are valid'.format(e)) def __shape_data(self): ''' take full data and leave only our metrics: historical close &amp; historical volume :return: ''' self.df = self.df[['AdjClose', 'AdjVolume']] self.df.rename(columns={'AdjClose': 'Close', 'AdjVolume': 'Volume'}, inplace=True) print(self.df.head()) def __add_target(self): ''' add target (y) column, for valiation training :return: ''' #shift current price *time_ahead* amount of spaces to make future price column self.df['Future'] = self.df['Close'].shift(-self.time_ahead) #classify wheter in the future we should buy or sell the stock self.df['Target'] = list(map(self.__classifiy_target, self.df['Close'], self.df['Future'])) print(self.df.head()) def __create_out_of_samples(self): ''' Out of sample test set, take last %5 of the training set for validation :return: ''' times = sorted(self.df.index.values) last_5pct = times[-int(0.05 * len(times))] #seprate validation data from stock data self.val_df = self.df[self.df.index &gt;= last_5pct] self.df = self.df[self.df.index &lt; last_5pct] def __scale_data(self, df): ''' scale dataframe values to normalize the data :param df: :return: ''' #in each column other than target (the answer) for col in df.columns: if col != 'Target': #change the numbers to the percent of change between two consecutive dates df[col] = df[col].pct_change() #drop any value that is null df.dropna(inplace=True) #use preprossesing from sklearn to scale values df[col] = preprocessing.scale(df[col].values) df.dropna(inplace=True) def __create_sequential_data(self, df): ''' create the list of data in sequence :param df: :return: ''' self.sequential_data = [] #a queue for keeping sequences of prices, when we reach max, the deque pushes out the front and adds a new value in the back curr_days = deque(maxlen=self.seq_len) #iterate over all values of dataframe for i in df.values: # the -1 is for excluding the target column curr_days.append([n for n in i[:-1]]) #when we reach the specified sequence length, add it to the list of sequences if len(curr_days) == self.seq_len: self.sequential_data.append([np.array(curr_days), i[-1]]) #save the first value of the list == sequnece for the CURRENT price of the stock self.prediction_set = self.sequential_data[0] #shuffle the list random.shuffle(self.sequential_data) def __balance_data(self): ''' balance the data so that the neural network wont just guess one value :return: ''' buy_stock = [] sell_stock = [] #sort the data into two: buys and sells for seq, target in self.sequential_data: if target == 1: buy_stock.append([seq,target]) elif target == 0: sell_stock.append([seq,target]) #get the shorter length between the lists lower_len = min(len(buy_stock),len(sell_stock)) print('Shortest list is {}'.format(lower_len)) random.shuffle(buy_stock) random.shuffle(sell_stock) #cut the length of the longer list to equal the shorter one buys = buy_stock[:lower_len] sells = sell_stock[:lower_len] #combine the lists back to main list, and shuffle self.sequential_data = buys + sells random.shuffle(self.sequential_data) def __finalize_training_data(self): ''' call the scaler and sequencer, and clean up the list of future column for the TRAINING DATA :return: X_train list, Y_train list ''' self.df = self.df.drop('Future', 1) self.__scale_data(self.df) self.__create_sequential_data(self.df) self.__balance_data() X_Train = [] Y_Train = [] for seq, target in self.sequential_data: X_Train.append(seq) Y_Train.append(target) return np.array(X_Train), np.array(Y_Train) def __finalize_test_data(self): ''' call the scaler and sequencer, and clean up the list of future column for the VALIDATION DATA :return:X_test list, Y_test list ''' self.val_df = self.val_df.drop('Future',1) self.__scale_data(self.val_df) self.__create_sequential_data(self.val_df) X_Test = [] Y_Test = [] for seq, target in self.sequential_data: X_Test.append(seq) Y_Test.append(target) return np.array(X_Test), np.array(Y_Test) def pre_proccess_data(self): ''' main function- puts evreything together and delivers the formatted data :return: x and y training and validation data, along with the prediction set ''' #Call the private class methods self.__get_data_from_quandl() self.__shape_data() self.__add_target() self.__create_out_of_samples() #get training sets x_train, y_train = self.__finalize_training_data() x_test, y_test = self.__finalize_test_data() return x_train, y_train, x_test, y_test, self.prediction_set </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T16:52:25.593", "Id": "234956", "Score": "1", "Tags": [ "python", "python-3.x", "numpy", "pandas" ], "Title": "DataSet Scaler with pandas" }
234956
<p>I'm not experienced with testing, therefore I'd like you to look at my code proposal of unit test. My solution has following projects</p> <ul> <li>Tests\Application.Tests</li> <li>Application</li> <li>Domain</li> <li>Infrastructure</li> <li>Web</li> </ul> <p>And I am not sure with Application Service Test. The tested class is <code>DeliveryDateService</code> </p> <pre><code>namespace Application.Services { public class DeliveryDateService : IDeliveryDateService { private readonly IHttpContextAccessor _httpAccessor; private readonly IDeliveryDateRepository _repository; public DeliveryDateService(IHttpContextAccessor httpAccessor, IDeliveryDateRepository repository) { _httpAccessor = httpAccessor; _repository = repository; } public void Handle(Import cmd) { var deliveryDates = new List&lt;DeliveryDate&gt;(); foreach (DeliveryDateDto item in cmd.Items) { deliveryDates.Add(new DeliveryDate( id: null, customerNumber: item.CustomerNumber, date: item.Date, modifiedBy: _httpAccessor.HttpContext.User.Identity.Name, modifiedOn: DateTime.Now )); } _repository.Import(deliveryDates); } } } </code></pre> <p>The real repository use entity framework to save data into database. But for the test the idea is that I will use Fake Repository, which will contains data only in memory. Therefore I am not testing the repositories, but only the service itself.</p> <pre><code>namespace Application.Tests.Fakes { public class DeliveryDateRepositoryFake : IDeliveryDateRepository { private List&lt;DeliveryDate&gt; Dates = new List&lt;DeliveryDate&gt;(); public List&lt;DeliveryDate&gt; FindAll() { return Dates; } public void Import(IList&lt;DeliveryDate&gt; dates) { Truncate(); foreach (var date in dates) { Dates.Add(date); } } public void Truncate() { foreach (var date in Dates) { Dates.Remove(date); } } } } </code></pre> <p>And the test looks like</p> <pre><code>namespace Application.Tests.Services { public class DeliveryDateServiceTests { private DeliveryDateRepositoryFake _repository; private IDeliveryDateService _service; private void Setup() { _repository = new DeliveryDateRepositoryFake(); _service = new DeliveryDateService( MockHelper.MockIHttpContextAccessor().Object, _repository); } private void Cleanup() { _repository = null; _service = null; } [Fact] public void Import() { Setup(); var items = new List&lt;DeliveryDateDto&gt; { new DeliveryDateDto(customerNumber: 123456, date: DateTime.Now), new DeliveryDateDto(customerNumber: 123457, date: DateTime.Now) }; _service.Handle(new Commands.DeliveryDate.Import(items)); Assert.Equal( expected: items.Count, actual: _repository.FindAll().Count); Cleanup(); } } } </code></pre> <p>Does it make sense, can it be improved ? I read, that Setup and Cleanup methods are not ideal, but also I don't want to repeat the code. Also I have to write Fake Repository for each Real Repository, it's extra work, but it's not complicated yet and it looks like it might work well.</p> <p><strong>Assertions (updated)</strong></p> <p>I added some assertions also on items data</p> <pre><code>// Assertions var actualCustomerOne = items.ToArray()[0]; var actualCustomerTwo = items.ToArray()[1]; var expectedCustomerOne = _repository.FindAll().ToArray()[0]; var expectedCustomerTwo = _repository.FindAll().ToArray()[1]; Assert.Equal(items.Count, _repository.FindAll().Count); Assert.Equal(actualCustomerOne.CustomerNumber, expectedCustomerOne.CustomerNumber); Assert.Equal(actualCustomerOne.Date, expectedCustomerOne.Date); Assert.NotNull(expectedCustomerOne.ModifiedBy); Assert.NotEqual(DateTime.MinValue, expectedCustomerOne.ModifiedOn); Assert.Equal(actualCustomerTwo.CustomerNumber, expectedCustomerTwo.CustomerNumber); Assert.Equal(actualCustomerTwo.Date, expectedCustomerTwo.Date); Assert.NotNull(expectedCustomerTwo.ModifiedBy); Assert.NotEqual(DateTime.MinValue, expectedCustomerTwo.ModifiedOn); </code></pre>
[]
[ { "body": "<h1>Fake Repository Responsibility</h1>\n\n<p>If the fake repository is meant to only provide testability of the service, then I would say you have hidden the true responsibility of the fake too much.</p>\n\n<p>It comes to what you want to know about the repository during the test? I would say you need to know how many times the <code>Import</code> method was called and what was the argument of each call.</p>\n\n<p>What you have there seems more like a (yet simple) real in-memory implementation of the repository. The fake has its own list of items and adds items from all calls to <code>Import</code> to the list, making it impossible to see which items were to be added in which call (not that you have shown us a test for multiple executions).</p>\n\n<p>I would expect the fake to have about this structure:</p>\n\n<pre><code>class DeliveryDateRepositoryFake : IDeliveryDateRepository\n{\n public int ImportCalled {get;};\n public IList&lt;DeliveryDate&gt; LastImportedDates {get;};\n\n // if you wanna keep track of all calls\n public IEnumerable&lt;IList&lt;DeliveryDates&gt;&gt; AllImportedDates{get;}\n}\n</code></pre>\n\n<p>The implementation could be using <code>List&lt;DeliveryDate&gt;</code> property, or a list of such lists if you wanna keep track of all consecutive calls.</p>\n\n<h1>Too Many Fakes</h1>\n\n<p>If you are worried about having to implement a fake repository for every entity. Then you should have been worried if you have to implement a real repository for every entity.</p>\n\n<p>What I mean is if you had a template interface for all repositories, maybe you might need just one template implementation of the fake.</p>\n\n<h1>Setup and Cleanup</h1>\n\n<p>You are repeating some code anyway (<code>Setup();</code> and <code>Cleanup();</code>). You could also have just one factory method, returning both the service and the respository as a tuple, destroying them automatically on the end of the test. And also removing need for properties definition and the \"nulling\" cleanup code.</p>\n\n<h1>Assertions</h1>\n\n<p>I'm not sure if you are just showing us the test in its simplests form or you are really just testing the counts of items. Anyway, I suggest you also test the items data, not just their count, because picking the data from command and passing them to the repository is responsibility of the service and thus should be subject of this test.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T09:29:24.927", "Id": "459727", "Score": "0", "body": "Thank you for great answer ! :-) yes, the fake repository is there only for testing purpose. I was thinking about implementing generic repository (and specific repositories only when needed), but for the simplicity I decided to implement each repository for each aggregate/entity for now. I will see how it will go. I will also look into factory, good idea. I added new assertions to test items data, it makes sense to test items data too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T18:09:19.730", "Id": "234967", "ParentId": "234960", "Score": "0" } } ]
{ "AcceptedAnswerId": "234967", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:08:08.740", "Id": "234960", "Score": "3", "Tags": [ "c#", "unit-testing", "asp.net-core", "xunit" ], "Title": "Basic Unit Test of Application Service, setup and cleanup methods" }
234960
<p>Simple Console Application for checking if one of the hosts is available. The implementation should be for around 5 hosts to check with different response times and the method should return fast when one Host can be pinged. Is the asynchronous implementation O.K.? </p> <pre><code>using System; using System.Net.NetworkInformation; using System.Threading; using System.Threading.Tasks; namespace PingMe { class Program { private static volatile bool _result; private readonly CancellationTokenSource _source; private readonly ParallelOptions _parallelOptions; private readonly string[] _hostsToPing = {"google.com", "reddit.com", "netflix.com"}; private Program() { _source = new CancellationTokenSource(); var token = _source.Token; _parallelOptions = new ParallelOptions { CancellationToken = token }; } private bool IsOneOfTheHostsAvailable() { try { Parallel.ForEach(_hostsToPing, _parallelOptions, (host) =&gt; { try { var ping = new Ping(); var reply = ping.Send(host); _parallelOptions.CancellationToken.ThrowIfCancellationRequested(); if (reply?.Status == IPStatus.Success) { _result = true; Console.WriteLine($"Pinged {host}"); if (!_source.IsCancellationRequested) _source.Cancel(); } } catch (Exception) { // we are only interested if one of the pings is successful, we don't care about the reason } }); } catch (OperationCanceledException) { // we are done } return _result; } private static void Main() { var program = new Program(); var oneOfTheHostsIsAvailable = program.IsOneOfTheHostsAvailable(); Console.WriteLine($"One of the hosts is available: {oneOfTheHostsIsAvailable}"); } } } </code></pre>
[]
[ { "body": "<p>It doesn't make sense to have the <code>CancellationTokenSource</code> private like you have now. Who is going to be able to cancel the operation? The user of your class can't access the source or provide their own token. The class doesn't offer any API to cancel.</p>\n\n<p>Instead, you should alter the <code>private bool IsOneOfTheHostsAvailable()</code> method to accept a <code>CancellationToken</code> as input. You can then let the user care about creating a source and possibly cancelling the operation. Or, if you don't feel like offering the option to the user, you should just do away with the cancellation token as a whole. Right now it isn't doing anything.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T16:17:49.303", "Id": "459772", "Score": "0", "body": "I want to cancel the other pings when one of the ping responses is successful. This should be the default behaviour - so I don't want to expose this implementation detail to the other clients. I changed all variables to private because I didn't create a seperate class and wanted just to Demo it from main." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:05:47.347", "Id": "459781", "Score": "0", "body": "@matthiasherrmann I completely missed that you call it yourself. That kinda makes this answer moot." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:40:30.240", "Id": "235009", "ParentId": "234964", "Score": "2" } }, { "body": "<p>Except all that @JAD said, which I totally agree with. I will give me five cents also after taking your comment in mind.</p>\n\n<blockquote>\n <p>I want to cancel the other pings when one of the ping responses is successful. This should be the default behaviour - so I don't want to expose this implementation detail to the other clients.</p>\n</blockquote>\n\n<p>First and foremost, there is a much cleaner and concise way of canceling your <code>Parallel.ForEach</code>. Check <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallelloopstate.break?view=netframework-4.8#System_Threading_Tasks_ParallelLoopState_Break\" rel=\"nofollow noreferrer\">ParallelLoopState.Break</a> method, I believe it does exactly the same thing you want to achieve without polluting your class with any unnecessary to business logic stuff - like <code>CancellationTokenSource</code> or <code>ParallelOptions</code>.</p>\n\n<p>Second, you probably forgot to put <code>Ping</code> class in <code>using</code> statement. <code>Ping</code> class inherits <code>IDisposable</code> type which means that it will be a good practice to put it in <code>using</code> statement. </p>\n\n<p>Third, I don't mind having fancy stuff like <code>volatile</code> field, but if I want to use something that fancy I want my code to \"scream out loud\" - <em>\"Hey, this makes sense here and it's probably the only way of achieving it.\"</em> However, this is not the case here. It is not obvious to me why this property is <code>static</code> in the first place (perhaps the example is not good enough) also I don't see why it is <code>volatile</code> as well.</p>\n\n<blockquote>\n <p>Although the volatile keyword can help you in thread safety in certain situations, it is <strong>not</strong> a solution to all of your thread concurrency issues. You should know that marking a variable or an object as volatile <strong>does not</strong> mean you don’t need to use the lock keyword. The volatile keyword is <strong>not</strong> a substitute for the lock keyword. It is only there to help you avoid data conflicts when you have multiple threads trying to access the same data.<sup><a href=\"https://www.infoworld.com/article/3229360/how-to-use-the-volatile-keyword-in-c.html\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>You are never accessing <code>_result</code> in your multithreaded code (unless I am wrong), you only try to assign it. With the same success, you can remove <code>volatile</code> keyword and the code will work as intended (again, unless I am missing something) because you are not changing the state. In other words, you don't care if <code>_result</code> is set to <code>true</code> one time, two times or three times and in what order simply because this is your business logic - you only need to know if at least one host is available.</p>\n\n<p>With all the comments above the code looks like this</p>\n\n<pre><code>using System;\nusing System.Net.NetworkInformation;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApp1\n{\n class Program\n {\n private bool _result = false;\n private readonly string[] _hostsToPing = { \"netflix.com\", \"google.com\", \"reddit.com\" };\n\n private bool IsOneOfTheHostsAvailable()\n {\n Parallel.ForEach(_hostsToPing, (host, state) =&gt;\n {\n if (state.ShouldExitCurrentIteration) return; // &lt;-- personal preference\n // I just hate .NET world putting brackets and new lines for nothing\n\n using (var ping = new Ping())\n {\n var reply = ping.Send(host);\n if (reply?.Status == IPStatus.Success)\n {\n _result = true;\n Console.WriteLine($\"Pinged {host}\");\n state.Break();\n }\n }\n\n });\n\n return _result; // you can even further remove _result by simply returning\n // IsCompleted property of ParallelLoopResult but many will argue this is more \n // readable so it's up to you\n }\n\n\n private static void Main()\n {\n var program = new Program();\n var oneOfTheHostsIsAvailable = program.IsOneOfTheHostsAvailable();\n Console.WriteLine($\"One of the hosts is available: {oneOfTheHostsIsAvailable}\");\n }\n }\n}\n</code></pre>\n\n<p>In the end, I will try to emphasize one thing - <em>Don't use features you don't fully understand.</em> This might not be the case for you but maybe the case for others, it is better that you do something in 50 lines of code but fully understands it than coding it in 5-6 lines with fancy stuff but then don't know why it works. Time will pass, you will gain more experience and you will eventually come to the place where you will do it in 5-6 lines, but don't try to force this process.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:14:03.127", "Id": "459785", "Score": "1", "body": "Ah I didn't know about the `Break` method. Your comments and the article about volatile helped a lot - ty" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:25:30.907", "Id": "459786", "Score": "0", "body": "@MatthiasHerrmann one of the applications that I can come up with for volatile is implementing double checked lock mechanism but again you can do it without volatile" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:06:11.020", "Id": "235030", "ParentId": "234964", "Score": "2" } } ]
{ "AcceptedAnswerId": "235030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:44:16.247", "Id": "234964", "Score": "1", "Tags": [ "c#", "task-parallel-library" ], "Title": "C# Ping - Checking availability of hosts" }
234964
<p>I started to learn React, and I wrote simple Blackjack game. I just need code review because I don't know anyone who know React well.</p> <p>Whole state and logic of my game I have in <code>Game.js</code> component:</p> <pre><code>import React, { Component } from 'react'; import Hand from './Hand'; import DealersHand from './DealersHand'; import Bet from './Bet'; import cards from '../../data/cards'; import { Redirect } from 'react-router'; class Game extends Component{ state = { gameStarted: false, bet: 5, deck: [], playerCards: [], dealerCards: [], money: 100, playerScore: 0, dealerScore: 0, playerWin: false, dealerWin: false, playerName: '', draw: false, finish: false } betLess = () =&gt; { if(this.state.bet &gt;= 1){ this.setState(state =&gt; ({ bet: state.bet - 5 })); } } betMore = () =&gt; { if(this.state.bet &lt;= this.state.money){ this.setState(state =&gt; ({ bet: state.bet + 5 })); } } letsPlay = () =&gt;{ this.setState({gameStarted: true}) } getRandomCards = () =&gt;{ for(let i = 0; i &lt; 2; i++){ setTimeout(this.getPlayerCard, 100); } this.getDealerCard(); } getDealerCard = () =&gt;{ const { deck, dealerCards, playerScore, money, bet } = this.state; let { dealerScore } = this.state const deckCards = deck.length &gt; 0 ? deck : cards; const randomIndex = Math.floor(Math.random() * deckCards.length); dealerScore += deckCards[randomIndex].cardValue; dealerCards.push(deckCards[randomIndex]); deckCards.splice(randomIndex, 1); const statesToSet = { dealerScore: dealerScore, dealerCards: dealerCards, deck: deckCards }; if(dealerCards.length === 2){ if(playerScore !== 21 &amp;&amp; dealerScore &lt; 15){ const randomIndex = Math.floor(Math.random() * deckCards.length); dealerScore += deckCards[randomIndex].cardValue; dealerCards.push(deckCards[randomIndex]); deckCards.splice(randomIndex, 1); statesToSet.deck = deckCards; statesToSet.dealerCards = dealerCards; statesToSet.dealerScore = dealerScore; this.setState(statesToSet); } if(dealerScore === playerScore){ statesToSet.draw = true; statesToSet.money = money + bet; } else if(dealerScore === 21){ statesToSet.dealerWin = true; statesToSet.money = money - bet; } else if(playerScore === 21){ statesToSet.playerWin = true; statesToSet.money = money + bet * 2; } else if(dealerScore &gt; playerScore){ statesToSet.dealerWin = true; statesToSet.money = money - bet; }else if(dealerScore &lt; playerScore){ statesToSet.playerWin = true; statesToSet.money = money + bet * 2; }else if(dealerScore &gt; 21){ statesToSet.dealerWin = true; statesToSet.money = money - bet; } } if(money === 0){ this.endGame(); } this.setState(statesToSet); } startNewGame = () =&gt;{ this.setState({ gameStarted: false, deck: [], playerCards: [], dealerCards: [], playerScore: 0, dealerScore: 0, playerWin: false, dealerWin: false, draw: false }); } getPlayerCard = () =&gt; { const { deck, playerCards, bet } = this.state; let { playerScore, playerWin, dealerWin, money } = this.state; const deckCards = deck.length &gt; 0 ? deck : cards; const randomIndex = Math.floor(Math.random() * deckCards.length); playerScore += deckCards[randomIndex].cardValue; playerCards.push(deckCards[randomIndex]); if(playerScore === 21){ playerWin = true; money = money + bet * 2; } if(playerScore &gt; 21){ dealerWin = true; money = money - bet; } this.setState({ deck: deckCards, playerCards: playerCards, playerScore: playerScore, playerWin: playerWin, dealerWin: dealerWin, money: money }); } endRound = () =&gt;{ this.getDealerCard(); } endGame = () =&gt;{ const { playerName, money } = this.state; const highscores = JSON.parse(localStorage.getItem('highscores')); highscores.push({name: playerName, score: money}); localStorage.setItem('highscores', JSON.stringify(highscores)) this.setState({finish: true}); } componentDidMount(){ this.getRandomCards(4); const playerName = localStorage.getItem('name'); this.setState({playerName: playerName}) } componentDidUpdate(){ if(this.state.deck.length === 0){ this.getRandomCards(); } } render(){ const { gameStarted, bet, money, dealerScore, playerScore, dealerCards, playerCards, playerWin, dealerWin, draw, finish } = this.state; if(finish){ return &lt;Redirect to="/highscores"/&gt; } if(gameStarted){ return( &lt;div className="col-md-12 col-xs-12"&gt; &lt;DealersHand cards={dealerCards} /&gt; &lt;div className="panel"&gt; &lt;h3&gt;Dealer's score: {dealerScore}&lt;/h3&gt; &lt;/div&gt; &lt;Hand cards={playerCards} /&gt; {draw || playerWin || dealerWin ? &lt;div className="game-status"&gt; {dealerWin ?&lt;div className="info lose"&gt;You lost.&lt;/div&gt; : null} {playerWin ?&lt;div className="info win"&gt; You won!&lt;/div&gt; : null} {draw ? &lt;div className="info draw"&gt;Draw.&lt;/div&gt; : null} &lt;div&gt; &lt;div className="buttons"&gt; &lt;button className="game-button" onClick={this.startNewGame}&gt;Play again&lt;/button&gt; &lt;button className="game-button" onClick={this.endGame}&gt;End game and save score&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; : null} &lt;div className="panel"&gt; &lt;h3&gt;Your score: {playerScore}&lt;/h3&gt; &lt;/div&gt; &lt;div className="panel"&gt; &lt;button className="game-button" onClick={this.getPlayerCard} disabled={playerScore &gt; 20 || playerWin || dealerWin || draw}&gt;Get card&lt;/button&gt; &lt;button className="game-button" onClick={this.endRound} disabled={playerScore &gt; 20 || playerWin || dealerWin || draw}&gt;End round&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ) }else{ return( &lt;Bet bet={bet} money={money} betLess={this.betLess} betMore={this.betMore} letsPlay={this.letsPlay} /&gt; ) } } } export default Game; </code></pre> <p><a href="https://github.com/gawel1908/blackjack-react" rel="nofollow noreferrer">GitHub</a></p> <p><a href="https://gawel1908.github.io/blackjack-react/#/" rel="nofollow noreferrer">GitHub Pages</a></p> <p>Can anyone tell me what can I do better or what I did wrong?</p>
[]
[ { "body": "<p>The code in componentDidUpdate looks a little odd to me. </p>\n\n<blockquote>\n <p><code>if(this.state.deck.length === 0){</code></p>\n</blockquote>\n\n<p>You are checking if there aren't any cards, then drawing some cards. This works because you are initialising the deck within getPlayerCard. What I would do is put the deck initialisation within the startNewGame method instead. </p>\n\n<p>getDealerCard and getPlayerCard are doing a bit too much; you could move the victory conditions to separate methods.</p>\n\n<p>In componentDidMount, <code>this.getRandomCards(4);</code> takes in a parameter but the method doesn't use any parameters.</p>\n\n<p>You have 3 variables in state which represent the victory state; playerWin, dealerWin, draw. These all cannot be true at the same time. It would be better to have one variable for the victory state; an option would be like an Enum in Typescript</p>\n\n<p>Looking at the code in your repository, there's a bug in DealersHand.js. You are rendering the second card twice; once in the map function, then again when you make the decision to render it face-down or face-up. Instead, you just need to conditionally render it when the dealer has only 1 card.</p>\n\n<pre><code>{\n cards.length == 1\n &amp;&amp;\n &lt;Card\n key=\"5\"\n className={ \"cards card-back\" }\n /&gt;\n}\n</code></pre>\n\n<p>The link on your ReadMe is also wrong. I used the link you provided in the question. I liked the game, but the lack of cards 2-8 took some adapting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:34:01.923", "Id": "237588", "ParentId": "234965", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T17:55:21.667", "Id": "234965", "Score": "4", "Tags": [ "javascript", "react.js" ], "Title": "React Blackjack game" }
234965
<h1>Goals</h1> <ul> <li>learn Python</li> <li>improve problem-solving skills</li> <li>improve my coding style</li> </ul> <h1>Hardware</h1> <p>This code runs on a Raspberry Pi 3 Model B (Raspbian OS) in combination with the Sense HAT. The 8x8 LED-Matrix on the Sense HAT is used for displaying the game-graphics and the included joystick is used for steering the snake. While developing the game, following online-tool has been used to emulate the hardware: <a href="https://trinket.io/sense-hat" rel="nofollow noreferrer">https://trinket.io/sense-hat</a> (NOTE: after clicking on the simulation, the arrow keys on the keyboard can be used for generating the joystick movement)</p> <h1>Code</h1> <pre class="lang-py prettyprint-override"><code> from sense_hat import SenseHat import time import random senseHat = SenseHat() senseHat.low_light = True GREEN = (0, 255, 0) RED = (255, 0, 0) START_DELAY = 3 MATRIX_MIN_VALUE = 0 MATRIX_MAX_VALUE = 7 MATRIX_SIZE = 8 while True: # variables: gameOverFlag = False growSnakeFlag = False generateRandomFoodFlag = False snakeMovementDelay = 0.5 snakeMovementDelayDecrease = -0.02 # start delay: time.sleep(START_DELAY) # set default snake starting position (values are chosen by preference): snakePosX = [3] snakePosY = [6] # generate random food position: while True: foodPosX = random.randint(0, 7) foodPosY = random.randint(0, 7) if foodPosX != snakePosX[0] or foodPosY != snakePosY[0]: break # set default snake starting direction (values are chosen by preference): movementX = 0 movementY = -1 # ----------------------------------- # game loop # ----------------------------------- while not gameOverFlag: # check if snake eats food: if foodPosX == snakePosX[0] and foodPosY == snakePosY[0]: growSnakeFlag = True generateRandomFoodFlag = True snakeMovementDelay += snakeMovementDelayDecrease # check if snake bites itself: for i in range(1, len(snakePosX)): if snakePosX[i] == snakePosX[0] and snakePosY[i] == snakePosY[0]: gameOverFlag = True # check if game-over: if gameOverFlag: break # check joystick events: events = senseHat.stick.get_events() for event in events: if event.direction == &quot;left&quot; and movementX != 1: movementX = -1 movementY = 0 elif event.direction == &quot;right&quot; and movementX != -1: movementX = 1 movementY = 0 elif event.direction == &quot;up&quot; and movementY != 1: movementY = -1 movementX = 0 elif event.direction == &quot;down&quot; and movementY != -1: movementY = 1 movementX = 0 # grow snake: if growSnakeFlag: growSnakeFlag = False snakePosX.append(0) snakePosY.append(0) # move snake: for i in range((len(snakePosX) - 1), 0, -1): snakePosX[i] = snakePosX[i - 1] snakePosY[i] = snakePosY[i - 1] snakePosX[0] += movementX snakePosY[0] += movementY # check game borders: if snakePosX[0] &gt; MATRIX_MAX_VALUE: snakePosX[0] -= MATRIX_SIZE elif snakePosX[0] &lt; MATRIX_MIN_VALUE: snakePosX[0] += MATRIX_SIZE if snakePosY[0] &gt; MATRIX_MAX_VALUE: snakePosY[0] -= MATRIX_SIZE elif snakePosY[0] &lt; MATRIX_MIN_VALUE: snakePosY[0] += MATRIX_SIZE # spawn random food: if generateRandomFoodFlag: generateRandomFoodFlag = False retryFlag = True while retryFlag: foodPosX = random.randint(0, 7) foodPosY = random.randint(0, 7) retryFlag = False for x, y in zip(snakePosX, snakePosY): if x == foodPosX and y == foodPosY: retryFlag = True break # update matrix: senseHat.clear() senseHat.set_pixel(foodPosX, foodPosY, RED) for x, y in zip(snakePosX, snakePosY): senseHat.set_pixel(x, y, GREEN) # snake speed (game loop delay): time.sleep(snakeMovementDelay) </code></pre> <h1>Questions</h1> <ul> <li>Would this example be better implemented in an object-oriented or procedural manner?</li> <li>Am I thinking too C/C++-like when implementing e.g. the for-loops?</li> <li>Would code like this ever be accepted in an &quot;professional environment&quot;?</li> <li>What can be improved and learned?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T18:23:58.250", "Id": "234969", "Score": "2", "Tags": [ "python", "beginner", "game", "snake-game", "raspberry-pi" ], "Title": "Snake Game for Raspberry Pi Sense HAT written in Python" }
234969
<p>I've completed the following coderbyte question and would like feedback as to whether it follows Python best practices, is efficient and so forth.</p> <p>The coderbyte problem:</p> <p>Have the function <code>calcpath(str)</code> read the str parameter being passed, which will represent the movements made in a 5x5 grid of cells starting from the top left position The characters in the input string will be entirely composed of: r, l, u, d, ?. Each of the characters stand for the direction to take within the grid, for example: r = right, l = left, u = up, d = down. Your goal is to determine what characters the question marks should be in order for a path to be created to go from the top left of the grid all the way to the bottom right without touching previously travelled on cells in the grid.</p> <p>For example: if str is "r?d?drdd" then your program should output the final correct string that will allow a path to be formed from the top left of a 5x5 grid to the bottom right. For this input, your program should, therefore, return the string rrdrdrdd. There will only ever be one correct path and there will always be at least one question mark within the input string.</p> <p>Examples</p> <p>Input: "???rrurdr?", Output: "dddrrurdrd"</p> <p>Input: "drdr??rrddd?", Output: "drdruurrdddd"</p> <p>Code:</p> <pre><code>import itertools import numpy as np def calcpath(s): _map = {"d": 1, "u": -1, "l": -1, "r": 1} q_count = s.count("?") move_combinations = itertools.product(_map.keys(), repeat=q_count) while True: arry = np.array([[0]*5 for i in range(5)]) arry[0][0] = 1 # start at 0, 0 current_x = 0 current_y = 0 try: moves = next(move_combinations) except StopIteration: return None ss = s[::].replace("?", "{}").format(*moves) for move in ss: if move in "lr": current_x += _map.get(move) elif move in "du": current_y += _map.get(move) if current_x &lt; 0 or current_x &gt; 4: break elif current_y &lt; 0 or current_y &gt; 4: break elif arry[current_x][current_y]: break else: arry[current_x][current_y] = 1 # check for completion if (current_x, current_y) == (4, 4): return ss assert calcpath("???rrurdr?") == "dddrrurdrd" assert calcpath("drdr??rrddd?") == "drdruurrdddd" assert calcpath("??ddd??lrlddd?") == None </code></pre>
[]
[ { "body": "<p><code>calcpath</code> should be <code>calc_path</code> <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">as per PEP8</a>. This seems like it's a name decided on by the challenge, but I thought I'd mention it.</p>\n\n<hr>\n\n<pre><code>_map = {\"d\": 1, \"u\": -1, \"l\": -1, \"r\": 1}\n</code></pre>\n\n<p>This should have a better name. \"map\" indicates that it's a mapping between things, but doesn't give any more information than that.</p>\n\n<p>I'd change it to something like:</p>\n\n<pre><code>DIRECTION_CHAR_TO_OFFSET = {\"d\": 1, \"u\": -1, \"l\": -1, \"r\": 1}\n</code></pre>\n\n<p>Capitalized to indicate that it's a constant. I'd also move it outside of <code>calc_path</code>. Its definition isn't dependent on anything within the function, and that function is quite long, so I think moving some stuff out would be a good idea.</p>\n\n<p>Arguably, a <code>Enum</code> would be a better fit here as well if you wanted to be strict. Using strings as keys opens the door for accidental mistypes, although the only opportunity for it here is in the definition of <code>DIRECTION_CHAR_TO_OFFSET</code> since all the data is supplied by the challenge.</p>\n\n<hr>\n\n<p>The <code>replace(\"?\", \"{}\")</code> bit should be taken out of the loop for performance reasons. It likely won't make any noticeable difference, but that part is entirely reliant on <code>s</code> which doesn't change, so there's no point in recalculating it repeatedly. There's also no reason to do a slice copy of the string before calling <code>replace</code> on it. <code>replace</code> returns a new string. Strings are immutable, so it can't modify <code>s</code>:</p>\n\n<pre><code>move_mask = s.replace(\"?\", \"{}\")\n. . .\nwhile True:\n . . .\n ss = move_mask.format(*moves)\n</code></pre>\n\n<hr>\n\n<p>[AJ's <code>for</code> suggestion is a much better idea than what I'm about to propose. Just go with what he suggests. I'm going to keep this section though to indroduce <code>:=</code> in case you don't know about it.]</p>\n\n<p>You can get rid of that <code>try</code> if you make use of Python 3.8's <a href=\"https://www.python.org/dev/peps/pep-0572/#syntax-and-semantics\" rel=\"noreferrer\">assignment expression</a>, and <code>next</code>'s second argument:</p>\n\n<pre><code>while moves := next(move_combinations, None):\n . . .\n</code></pre>\n\n<p>When <code>move_combinations</code> is exhausted, <code>next</code> will return <code>None</code> which will end the loop. This isn't <em>exactly</em> equivalent as your original version since it isn't returning directly from the loop. It does behave the same though since there is nothing after the loop. I added a <code>return None</code> at the bottom though to comply with PEP8.</p>\n\n<p>I won't say that I completely recommend this way since it requires the latest Python and uses new, fancy features. It does help reduce some bulk though.</p>\n\n<hr>\n\n<pre><code>DIRECTION_CHAR_TO_OFFSET.get(move)\n</code></pre>\n\n<p>Can simply be</p>\n\n<pre><code>DIRECTION_CHAR_TO_OFFSET[move]\n</code></pre>\n\n<p>Again, this isn't exactly equivalent, but it acts the same here. I'd say though that using <code>[]</code> <em>is</em> better in this scenario. <code>get</code> will return <code>None</code> on a bad lookup (should one be allowed to happen due to a typo or something). With <code>None</code> returned, you'll attempt to add <code>None</code> to <code>current_x</code>, which will cause:</p>\n\n<pre><code>TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'\n</code></pre>\n\n<p>Using <code>[]</code> though will cause a <code>KeyError</code>:</p>\n\n<pre><code>KeyError: 'a'\n</code></pre>\n\n<p>I think the latter gives more useful debugging information than the former.</p>\n\n<hr>\n\n<pre><code>if current_x &lt; 0 or current_x &gt; 4:\n break\nelif current_y &lt; 0 or current_y &gt; 4:\n break\n</code></pre>\n\n<p>This can make use of operator chaining if you're willing to add some negation to the condition:</p>\n\n<pre><code>if not 0 &lt;= current_x &lt;= 4:\n break\nelif not 0 &lt;= current_y &lt;= 4:\n break\n</code></pre>\n\n<p>And since those both result in the same operation, they can be combined:</p>\n\n<pre><code>if not (0 &lt;= current_x &lt;= 4 and 0 &lt;= current_y &lt;= 4):\n break\n</code></pre>\n\n<p>I adjusted the condition a bit using one of <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"noreferrer\">DeMorgan's Laws</a>:</p>\n\n<blockquote>\n <p>not (A and B) = not A or not B</p>\n</blockquote>\n\n<hr>\n\n<hr>\n\n<pre><code>import itertools\nimport numpy as np\n\nDIRECTION_CHAR_TO_OFFSET = {\"d\": 1, \"u\": -1, \"l\": -1, \"r\": 1}\n\ndef calc_path(s):\n q_count = s.count(\"?\")\n move_mask = s.replace(\"?\", \"{}\")\n\n move_combinations = itertools.product(DIRECTION_CHAR_TO_OFFSET.keys(), repeat=q_count)\n\n while moves := next(move_combinations, None):\n arry = np.array([[0]*5 for i in range(5)])\n arry[0][0] = 1 # start at 0, 0\n\n current_x = 0\n current_y = 0\n\n ss = move_mask.format(*moves)\n\n for move in ss:\n if move in \"lr\":\n current_x += DIRECTION_CHAR_TO_OFFSET[move]\n elif move in \"du\":\n current_y += DIRECTION_CHAR_TO_OFFSET[move]\n\n if not (0 &lt;= current_x &lt;= 4 and 0 &lt;= current_y &lt;= 4):\n break\n elif arry[current_x][current_y]:\n break\n else:\n arry[current_x][current_y] = 1\n\n # check for completion\n if (current_x, current_y) == (4, 4):\n return ss\n\n return None\n\nassert calc_path(\"???rrurdr?\") == \"dddrrurdrd\"\nassert calc_path(\"drdr??rrddd?\") == \"drdruurrdddd\"\nassert calc_path(\"??ddd??lrlddd?\") == None\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:28:02.007", "Id": "234973", "ParentId": "234970", "Score": "6" } }, { "body": "<h1>Unnecessary Import</h1>\n\n<p><code>numpy</code> is not required for this challenge. You are using none of its special capabilities. The following:</p>\n\n<pre><code>arry = np.array([[0]*5 for i in range(5)])\n</code></pre>\n\n<p>could easily and simply be replaced with</p>\n\n<pre><code>arry = [[0] * 5 for _ in range(5)]\n</code></pre>\n\n<p>Notice the throw-away <code>_</code> variable being used for the unused loop comprehension variable. If you don't use it, don't name it.</p>\n\n<h1>StopIteration</h1>\n\n<p>It is rarely necessary to use <code>try: ... except: ...</code> to catch the <code>StopIteration</code> exception. You just need to use a loop structure.</p>\n\n<pre><code> move_combinations = itertools.product(_map.keys(), repeat=q_count)\n\n while True:\n arry = np.array([[0]*5 for i in range(5)])\n arry[0][0] = 1 # start at 0, 0\n\n current_x = 0\n current_y = 0\n\n try:\n moves = next(move_combinations)\n except StopIteration:\n return None\n\n ...\n</code></pre>\n\n<p>could be written much more simply as:</p>\n\n<pre><code> for move in itertools.product(_map.keys(), repeat=q_count):\n\n arry = [[0] * 5 for _ in range(5)]\n arry[0][0] = 1 # start at 0, 0\n\n current_x = 0\n current_y = 0\n\n ...\n\n return None\n</code></pre>\n\n<h1>Variable Names</h1>\n\n<p><code>_map</code> is an odd local variable name. A single leading underscore is used to signify private/protected object members. Local variables are never visible in an outer scope, so do not need to be flagged as \"private\". A trailing underscore is usually used to avoid name collisions, in which case the variable should be named <code>map_</code>. But confusion may be better avoided by naming the variable not with its type but with its role; this dictionary mapping contains directions, so it may be better named <code>directions</code>.</p>\n\n<p><code>arry</code> is also a poor name. <code>visited</code> would be a better choice.</p>\n\n<h1>True / False</h1>\n\n<p>You are storing <code>0</code> and <code>1</code> in your <code>arry</code> matrix, and then testing for the truthiness of <code>arry[current_x][current_y]</code>. It would be clearer to store <code>False</code> and <code>True</code> in these.</p>\n\n<pre><code>visited = [[False] * 5 for _ in range(5)]\n\n...\n\n ...\n elif visited[current_x][current_y]:\n break\n else:\n visited[current_x][current_y] = True\n</code></pre>\n\n<h1>Unnecessary Slicing</h1>\n\n<p>Neither <code>s.replace(...)</code> nor <code>s[::].replace(...)</code> will modify the original <code>s</code> contents. There is no need to use slicing to create a copy prior to the replace operation:</p>\n\n<pre><code> ss = s.replace(\"?\", \"{}\").format(*moves)\n</code></pre>\n\n<p>(And as Carcigenicate mentioned, move it out of the loop)</p>\n\n<h1>Magic Numbers</h1>\n\n<p>The code is littered with 4's and 5's. What if you want to change this to work with a 5x6 or 4x7 grid? You need to correctly change a lot of numbers. Perhaps you should pass in the size of the grid, instead of using hard-coded values:</p>\n\n<pre><code>def calcpath(s, rows=5, columns=5):\n\n start = (0, 0)\n end = (columns - 1, rows - 1)\n\n ...\n\n visited = [[False] * columns for _ in range(rows)]\n current_x, current_y = start\n\n ...\n\n if current_x &lt; 0 or current_x &gt;= columns:\n break\n ...\n\n if (current_x, current_y) == end:\n ...\n\n ...\n</code></pre>\n\n<h1>Optimizations</h1>\n\n<p>There should be several obvious checks you can make. For the 5x5 grid case:</p>\n\n<ul>\n<li><code>len(s)</code> must be even</li>\n<li><code>len(s)</code> must be >= 8</li>\n<li><code>len(s)</code> must be &lt; 25</li>\n</ul>\n\n<p>Moreover, the directed counts of the left-right and up-down moves will produce a reduced search space.</p>\n\n<p>With <code>s = \"???rrurdr?\"</code>:</p>\n\n<pre><code>&gt;&gt;&gt; print(*(sum(c == dir for c in s) for dir in \"lrud?\"))\n0 4 1 1 4\n</code></pre>\n\n<p>There are 0 lefts, 4 rights, so we need to move +0 right to yield a net +4 right; there is 1 up and 1 down, so we need to move +4 down to yield a net +4 down. We have 4 moves up for grabs, so they all need to be downs. There is no point checking for combinations including up, left and right moves!</p>\n\n<p>You can expand the logic of this for other cases: <code>\"drdr??rrddd?\"</code> has a net 4 right, 5 down, so the additional moves must include 1 up. Then, it could add either a left/right pair, or an up/down pair, so you only need to check permutations of \"ulr\" and \"uud\", for a total of 12 possibilities, instead of your <span class=\"math-container\">\\$4^3\\$</span> search space.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:48:14.773", "Id": "459679", "Score": "1", "body": "Doh, idk why I didn't just think of iterating `product` with a `for` XD." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:49:15.173", "Id": "459680", "Score": "1", "body": "@Carcigenicate I don't know how I missed the moving of the `.replace` out of the loop. We're even." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T16:49:17.203", "Id": "459775", "Score": "0", "body": "Damn, didn't realize the lr or ud ambiguity. I thought you could figure out exactly what the missing letters are directly from the need to get to 4,4" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T21:44:41.277", "Id": "234975", "ParentId": "234970", "Score": "15" } } ]
{ "AcceptedAnswerId": "234975", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T18:51:16.357", "Id": "234970", "Score": "7", "Tags": [ "python", "python-3.x", "programming-challenge", "pathfinding" ], "Title": "Find the correct path through a 5 x 5 grid (coderbyte 'Correct path')" }
234970
<p>I've made this GUI program for my workplace that checks whether measured coordinates on machined components are within spec.</p> <p>It takes in specified coordinates, tolerance and measured coordinates and uses Pythagoras to check whether the tolerance has been exceeded.</p> <p>It then plots the measured point relative to the 'true point' on a Tkinter canvas which can be scaled up and down with the slider widget (points are scaled proportionally - this was the challenging bit for me). The tolerance value determines the radius of the circle shown below.</p> <p>I've ran the program through Pylint and am now getting good results (9.72). I'm now hoping for a bit of feedback on anything I could have done better. I was also trying to work to OOP ideas. Any comments about these or other areas would be much appreciated.</p> <p><a href="https://i.stack.imgur.com/IgxQp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IgxQp.png" alt="Geometrical Tolerancing Application"></a></p> <pre class="lang-py prettyprint-override"><code>**"""Validates points against engineering drawing according to specified tolerance"""** from tkinter import Tk, Label, Entry, GROOVE, Button, IntVar, Canvas, Scale, Checkbutton class TruePosition: """Populates Tk window object with widgets""" def __init__(self, master): self.master = master master.title('True Position Validator') #Labels self.truelabel = Label(master, text='True Point Location Details:', font=('Technic', 14)) self.hlabel = Label(master, text='Point Loc:', font=('Technic', 12)) self.commalabel = Label(master, text=', ') self.tollabel = Label(master, text='Tolerance:', font=('Technic', 12)) self.measlabel = Label(master, text='Measured Point Location Details', font=('Technic', 14)) self.mlab = Label(master, text='Point Loc:', font=('Technic', 12)) self.commalabel2 = Label(master, text=', ') self.labelout = Label(master, fg='black', font=('Technic', 12)) # Entries self.h_cor = Entry(master, relief=GROOVE) self.k_cor = Entry(master, relief=GROOVE) self.tol_cor = Entry(master, relief=GROOVE) self.x_cor = Entry(master, relief=GROOVE) self.y_cor = Entry(master, relief=GROOVE) self.entries = [self.h_cor, self.k_cor, self.tol_cor, self.x_cor, self.y_cor] # Running Variables self.cross = False self.checkvar = IntVar() self.stored_points = {} self.count = 0 self.line_length = 10 self.h_val = None self.k_val = None self.tol_val = None self.x_val = None self.y_val = None self.real = None self.clearance = None self.radius = None self.linea_x1 = None self.linea_x2 = None self.linea_y = None self.lineb_y1 = None self.lineb_y2 = None self.lineb_x = None self.linea = None self.lineb = None # Interactive / Function Call Elements self.retain = Checkbutton(master, text='Retain plots', variable=self.checkvar, command=lambda: self.box_check()) self.bsubmit = Button(master, text='Submit', font=('Technic', 10), command=lambda: self.submit_action()) self.master.bind("&lt;Return&gt;", lambda t: self.submit_action()) self.bclear = Button(master, text='Clear', font=('Technic', 10), command=lambda: self.clearcrosses()) self.slider = Scale(master, orient='horizontal', from_=0, to=100, command=lambda factor: self.scalar(factor=float(factor))) self.slider.set(100) # Base Graphics # Canvas self.display_canvas = Canvas(master, bg='white', border=2, highlightthickness=1, highlightbackground='black') self.truecircle = self.display_canvas.create_oval(0, 0, 0, 0, outline='black', dash=(4, 5)) # Circle Centre Point pointa_x1 = (self.display_canvas.winfo_reqwidth()/2)-self.line_length/2 pointa_x2 = (self.display_canvas.winfo_reqwidth()/2)+self.line_length/2 pointa_y = self.display_canvas.winfo_reqheight()/2 pointb_y1 = (self.display_canvas.winfo_reqheight()/2)-(self.line_length/2) pointb_y2 = (self.display_canvas.winfo_reqheight()/2)+(self.line_length/2) pointb_x = self.display_canvas.winfo_reqwidth()/2 points = (pointa_x1, pointa_x2, pointa_y, pointb_y1, pointb_y2, pointb_x) self.display_canvas.create_line(points[0], points[2], points[1], points[2]) self.display_canvas.create_line(points[5], points[3], points[5], points[4]) # Geometry Management self.truelabel.grid(row=0, column=0, columnspan=4, pady=8, sticky='w') self.hlabel.grid(row=1, column=0, sticky='w') self.commalabel.grid(row=1, column=2) self.tollabel.grid(row=2, column=0, sticky='w') self.measlabel.grid(row=4, sticky='w', pady=8) self.mlab.grid(row=5, column=0, sticky='w') self.commalabel2.grid(row=5, column=2) self.labelout.grid(row=7, sticky='w', columnspan=4) self.h_cor.grid(row=1, column=1) self.k_cor.grid(row=1, column=3) self.tol_cor.grid(row=2, column=1) self.x_cor.grid(row=5, column=1) self.y_cor.grid(row=5, column=3) self.retain.grid(row=8, column=3, sticky='e') self.bsubmit.grid(row=6, column=1, sticky='w') self.slider.grid(row=9, columnspan=4) self.bclear.grid(row=8, column=3, sticky='ne', padx=40) self.display_canvas.grid(row=8, columnspan=4, sticky='s') self.canvas_width = self.display_canvas.winfo_reqwidth() self.canvas_height = self.display_canvas.winfo_reqheight() # Functions def box_check(self): """Acknowledges box check &amp; stores existing point if switching from non retention mode""" if self.checkvar.get() == 1 and self.cross: self.store_points() elif self.checkvar.get() == 0: self.clearcrosses() print('ran box_check\n') def submit_action(self): """Accepts user input and runs subsequent functions""" try: self.calctrue() self.showtrue() self.meas_point(self.x_val, self.y_val) if not self.cross or self.checkvar.get() == 1: self.create_points() if self.checkvar.get() == 1: self.store_points() else: pass elif self.cross: self.move_points(self.linea, self.lineb) except ValueError: # Accounts for accidental pressing of submit before all data is entered self.labelout.config(fg='black') self.labelout['text'] = 'ValueError : Make sure all fields have been completed.' print('ran submit_action()\n') def scalar(self, factor): """Runs logic that changes circle size in response to slider and remeasures &amp; shifts existing points""" self.getplot_circ(factor) if self.checkvar.get() == 0 and self.cross: self.meas_point(self.x_val, self.y_val) self.move_points(self.linea, self.lineb) elif self.checkvar.get() == 1 and self.cross: for point in self.stored_points: self.meas_point(*self.stored_points[point][1]) self.move_points(*self.stored_points[point][0]) elif not self.cross: pass print('ran scalar\n') def getplot_circ(self, factor): """Changes circle size""" factor = 192 - (factor*1.27) self.radius = (self.canvas_width/2)- factor c1_x = (self.canvas_width/2) - self.radius c1_y = (self.canvas_height/2) - self.radius c2_x = (self.canvas_width/2) + self.radius c2_y = (self.canvas_height/2) + self.radius self.display_canvas.coords(self.truecircle, c1_x, c1_y, c2_x, c2_y) print('ran getplot_circ()') def calctrue(self): """Determines if point is within spec""" self.h_val = float(self.h_cor.get()) self.k_val = float(self.k_cor.get()) self.tol_val = float(self.tol_cor.get()) self.x_val = float(self.x_cor.get()) self.y_val = float(self.y_cor.get()) self.real = (((self.x_val-self.h_val)**2)+((self.y_val-self.k_val)**2))**0.5 self.clearance = self.tol_val - self.real print('ran calctrue()') def showtrue(self): """Provides non-graphical feedback about results of calctrue""" if self.tol_val &gt;= self.real: self.labelout.config(fg='green') self.labelout['text'] = f'Position is within spec by {self.clearance}' self.display_canvas.itemconfig(self.truecircle, outline='green') elif self.tol_val &lt; self.real: self.labelout.config(fg='red') self.labelout['text'] = f'Position is outwith spec by {abs(self.clearance)}' self.display_canvas.itemconfig(self.truecircle, outline='red') print('ran showtrue()') def meas_point(self, loc_x, loc_y): """defines new point in terms of current circle &amp; canvas geometry""" conversionfactor = self.radius/self.tol_val pix_x = (conversionfactor * (loc_x-self.h_val)) + self.canvas_width/2 pix_y = (-conversionfactor * (loc_y-self.k_val)) + self.canvas_height/2 self.linea_x1 = (pix_x - (self.line_length/2)) self.linea_x2 = (pix_x + (self.line_length/2)) self.linea_y = (pix_y) self.lineb_y1 = (pix_y - (self.line_length/2)) self.lineb_y2 = (pix_y + (self.line_length/2)) self.lineb_x = (pix_x) print('ran meas_point()') def move_points(self, linea, lineb): """Shifts cross point to measured locations""" self.display_canvas.coords(linea, self.linea_x1, self.linea_y, self.linea_x2, self.linea_y) self.display_canvas.coords(lineb, self.lineb_x, self.lineb_y1, self.lineb_x, self.lineb_y2) print('ran move_points()') def create_points(self): """Plots new cross point""" self.linea = self.display_canvas.create_line(self.linea_x1, self.linea_y, self.linea_x2, self.linea_y, tag='cross') self.lineb = self.display_canvas.create_line(self.lineb_x, self.lineb_y1, self.lineb_x, self.lineb_y2, tag='cross') if not self.cross: self.cross = True print('ran create_points()') def store_points(self): """stores points for rescaling if slider is used""" print(self.count) self.stored_points[self.count] = [[self.linea, self.lineb], [self.x_val, self.y_val]] self.count += 1 print('ran store_points()') def clearcrosses(self): """deletes all user input""" for item in self.display_canvas.find_withtag('cross'): self.display_canvas.delete(item) self.labelout['text'] = '' self.display_canvas.itemconfig(self.truecircle, outline='black') self.cross = False self.stored_points = {} for instance in self.entries: instance.delete(0, 'end') print('ran clearcrosses()\n') ROOT = Tk() MYAPP = TruePosition(ROOT) ROOT.mainloop() </code></pre>
[]
[ { "body": "<p>There is a lot to unpack here, so this review will be in multiple edits.</p>\n\n<h1>GUI Creation</h1>\n\n<p>You are creating and storing some widgets unnecessarily in member variables. For instance, <code>self.truelabel</code> is only used in the <code>TruePosition</code> constructor, it could be a local variable instead of a member variable. The same is true for almost all of the other labels.</p>\n\n<p>Your GUI creating is a very manually intensive process. You create each item, and later position it to absolute coordinates. Let's let Python help us out here, and figure out the coordinates itself.</p>\n\n<pre><code>class TruePosition:\n\n \"\"\"Populates Tk window object with widgets\"\"\"\n def __init__(self, master):\n self.master = master\n master.title('True Position Validator')\n\n self.heading('True Point Location Details:')\n self.heading('Measured Point Location Details')\n\n def heading(self, title):\n _, rows = self.master.grid_size()\n label = Label(self.master, text=title, font=('Technic', 14))\n label.grid(row=rows, columnspan=4, sticky='w')\n\n\nROOT = Tk()\nMYAPP = TruePosition(ROOT)\n\nROOT.mainloop()\n</code></pre>\n\n<p>This short little program just creates the two heading lines in your GUI. Note that the first heading is on <code>row=0</code> and the second on <code>row=1</code>, but we never specified that. We just created <code>self.heading(...)</code> lines, and the <code>heading(self, title)</code> method determine what the next row number was, created the <code>label</code> as a local variable, and positioned it all on its own.</p>\n\n<p>Building on that, lets add the first 5 entry fields. First, add this additional import:</p>\n\n<pre><code>from tkinter import DoubleVar\n</code></pre>\n\n<p>TkInter has some special \"Vars\" that can be used to pass data into and out of control widgets. A <code>DoubleVar</code> does this for floating point values, including the conversion to and from a string.</p>\n\n<pre><code> self.h_cor = DoubleVar()\n self.k_cor = DoubleVar()\n self.tol_cor = DoubleVar()\n self.x_cor = DoubleVar()\n self.y_cor = DoubleVar()\n\n self.heading('True Point Location Details:')\n self.row('Point Loc:', self.h_cor, ',', self.k_cor)\n self.row('Tolerance:', self.tol_cor)\n self.heading('Measured Point Location Details')\n self.row('Point Loc:', self.x_cor, ',', self.y_cor)\n</code></pre>\n\n<p>Now, we've created a <code>DoubleVar</code> for each of the 5 entry fields, and we're passing these variables, along with some text to <code>row()</code> functions. Let's define those:</p>\n\n<pre><code> def row(self, *fields):\n _, rows = self.master.grid_size()\n for col, field in enumerate(fields):\n if isinstance(field, str):\n label = Label(self.master, text=field, font=('Technic', 12))\n label.grid(row=rows, column=col, sticky='w')\n elif isinstance(field, DoubleVar):\n entry = Entry(self.master, textvar=field, relief=GROOVE)\n entry.grid(row=rows, column=col)\n</code></pre>\n\n<p>Again, we're letting Python keep track of which row we're on. For each of the <code>fields</code> we pass in (the arguments to the <code>row(...)</code> call), we check if we were given a string or not. If a string was given, we create a <code>label</code> and position it. Otherwise, we create an <code>entry</code> using that <code>field</code> as the <code>textvar</code>, and position it.</p>\n\n<p>If you run this short little program, you'd see we've created the first 5 lines of your GUI. Notice how easy it would be to add new items or change the layout; simply call the <code>heading()</code> or <code>row()</code> functions in the correct order.</p>\n\n<p>To use the <code>DoubleVar</code>, simply <code>.get()</code> the values. Ie)</p>\n\n<pre><code> self.h_val = float(self.h_cor.get())\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code> self.h_val = self.h_cor.get()\n</code></pre>\n\n<p>To add <code>Button</code> and <code>Slider</code> objects to our grid, it is useful to pass in other Widget objects (<code>from tkinter import Widget</code>) to our <code>row()</code> method. We can broaden <code>DoubleVar</code> to <code>Variable</code> to allow an <code>Entry</code> widget to be created if passed a <code>StringVar</code> or an <code>IntVar</code> as well.</p>\n\n<pre><code> def row(self, *fields):\n _, rows = self.master.grid_size()\n for col, field in enumerate(fields):\n if isinstance(field, str):\n label = Label(self.master, text=field, font=('Technic', 12))\n label.grid(row=rows, column=col, sticky='w')\n elif isinstance(field, Variable):\n entry = Entry(self.master, textvar=field, relief=GROOVE)\n entry.grid(row=rows, column=col)\n elif isinstance(field, Widget):\n field.grid(rows=row, column=col)\n</code></pre>\n\n<p>Sometimes, we will want to get the widgets that are created. For instance, we would want the <code>labelout</code> widget that gets created, so we can change the colour of the label programmatically. So, let's return a list of all the widgets that are created:</p>\n\n<pre><code> def row(self, *fields):\n _, rows = self.master.grid_size()\n widgets = []\n\n for col, field in enumerate(fields):\n widget = None\n if isinstance(field, str):\n widget = Label(self.master, text=field, font=('Technic', 12))\n elif isinstance(field, DoubleVar):\n widget = Entry(self.master, textvar=field, relief=GROOVE)\n elif isinstance(field, Widget):\n widget = field\n\n if widget:\n widget.grid(row=rows, column=col, sticky='w')\n widgets.append(widget)\n\n return widgets\n</code></pre>\n\n<p>Now we can create more of the GUI with:</p>\n\n<pre><code> self.heading('True Point Location Details:')\n self.row('Point Loc:', self.h_cor, ',', self.k_cor)\n self.row('Tolerance:', self.tol_cor)\n\n self.heading('Measured Point Location Details')\n self.row('Point Loc:', self.x_cor, ',', self.y_cor)\n btn = Button(master, text=\"Submit\", font=('Technic', 10),\n command=self.submit_action)\n self.row(None, None, btn)\n\n self.labelout = self.row(\"\")[0]\n\n self.display_canvas = Canvas(master, bg='white', border=2, highlightthickness=1,\n highlightbackground='black')\n self.display_canvas.grid(columnspan=4, sticky='s')\n</code></pre>\n\n<h1>Math</h1>\n\n<p>You're doing some calculations the hard way.</p>\n\n<pre><code> self.real = (((self.x_val-self.h_val)**2)+((self.y_val-self.k_val)**2))**0.5\n</code></pre>\n\n<p>could be written much simpler:</p>\n\n<pre><code> self.real = math.hypot(self.x_val - self.h_val, self.y_val - self.k_val)\n</code></pre>\n\n<h1>Don't use a Dictionary as a List</h1>\n\n<p>This code is a poor design choice:</p>\n\n<pre><code> self.stored_points = {}\n self.count = 0\n</code></pre>\n\n<p>First, <code>count</code> is keeping track of the number of elements in <code>store_points</code>. Python contains know how many items are in the container; just ask for the <code>len(container)</code>, and you'll get the equivalent of <code>count</code>.</p>\n\n<p>Secondly, the data is being stored using the current <code>count</code> value as a key, which means you store the data under key <code>0</code>, then <code>1</code>, then <code>2</code>, and so on. This is the hard-way of looking up items in a list! You should just use a list!</p>\n\n<pre><code> self.stored_points = []\n</code></pre>\n\n<p>And <code>append</code> new items to the list:</p>\n\n<pre><code> self.stored_points.append(((self.linea, self.lineb), (self.x_val, self.y_val)))\n</code></pre>\n\n<p>And iterate over the list:</p>\n\n<pre><code> for pnt0, pnt1 in self.stored_points:\n self.meas_point(*pnt1)\n self.move_points(*pnt0)\n</code></pre>\n\n<h1>Crosses</h1>\n\n<p>You are doing a lot of work to create crosses. A lot of unnecessary information is being stored in members (<code>linea</code>, <code>lineb</code>, <code>linea_x1</code>, <code>linea_x2</code>, ... <code>lineb_x</code>)</p>\n\n<p>Instead, it would make sense to have a function which creates crosses on the canvas, at an (x,y) location.</p>\n\n<pre><code> def cross(self, x, y, tag):\n scale = self.radius / self.tol_cor.get()\n half_len = self.line_length / 2\n center_x = self.canvas_width / 2\n center_y = self.canvas_height / 2\n x = center_x + scale * (x - self.h_cor.get())\n y = center_y - scale * (y - self.k_cor.get())\n\n self.display_canvas.create_line(x, y - half_len, x, y + half_len, tag=tag)\n self.display_canvas.create_line(x - half_len, y, x + half_len, y, tag=tag)\n</code></pre>\n\n<p>Calling <code>self.cross(self.h_cor.get(), self.k_cor.get(), None)</code> during the constructor would create the centre cross with no tag. Calling <code>self.cross(self.x_cor.get(), self.y_cor.get(), \"cross\")</code> would create a measurement point cross with the tag <code>\"cross\"</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T22:44:38.973", "Id": "460036", "Score": "0", "body": "Thanks very much for taking the time to go through that! I’ve implemented your suggestions and it’s looking a lot leaner!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T04:04:47.337", "Id": "460062", "Score": "0", "body": "Happy to help. When you are ready, post your updated code as a follow up question; I’d like to see the improvements, and be able to point out other improvements. I was busy over the holidays and didn’t get back to further review comments/points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T17:06:41.447", "Id": "460152", "Score": "0", "body": "Okay, brilliant. All of your suggestions were pretty straightforward to implement but I did have some trouble getting the last one to work. In the end I've approached it slightly differently but I think I've done the same thing in spirit! \n\nThere is a function that determined cross positions, the program would then either plot a new cross or move an existing one. I think the difficulty I had implementing your function might come from this. I've made it so I now no longer perform the same calcs in the constructor for the centre cross but I haven't been able to reduce the number of attributes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T17:13:03.107", "Id": "460156", "Score": "0", "body": "Here's the new question: <https://codereview.stackexchange.com/questions/235177/plotting-whether-measured-locations-for-components-are-within-spec-revision>\n\nHappy New Year!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T02:36:57.480", "Id": "234979", "ParentId": "234976", "Score": "2" } } ]
{ "AcceptedAnswerId": "234979", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-02T22:36:05.253", "Id": "234976", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "gui", "tkinter" ], "Title": "Plotting Whether Measured Locations for Components are Within Spec" }
234976
<p>This is a simple guessing game I have made, an improvised one. I will do a GUI version of this shortly.</p> <p>I'm looking for comments and interesting code ideas.</p> <pre><code>import random sec_no = random.randint(0, 10) ncount = 0 att = 5 while True: sec_no = random.randint(0, 10) ncount = 0 att = 4 minp = input(''' 1-start 2-help 3-quit ''') if minp.lower() == 'start' or minp == '1': while ncount != 4: att -= 1 try: uinp = int(input('Guess the no:')) if uinp == int(sec_no): print('correct!!!!') break else: print('incorrect!!!') print(f'attempts left:{att}') except ValueError: print('invalid value!!!') print(f'attempts left:{att}') if ncount == 3: print('You lose!!') print(f'correct number is :{sec_no}') break ncount += 1 elif minp.lower() == 'quit' or minp == '3': while True: print('are you sure you wanna quit? [Y/N]') linp = input('&gt;') if linp.lower() == 'y': print('Thanks for playing!!') exit() elif linp.lower() == 'n': break else: print("I don't understand that!!!") elif minp.lower() == 'help' or minp == '2': print('''You will be given 3 attempts,within these attempts you'll have to guess the right number from 0-10 good luck!!!''') else: print("I don't understand that!!") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T03:20:59.703", "Id": "459697", "Score": "3", "body": "The indentation here is off. Typo?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T04:42:06.977", "Id": "459701", "Score": "1", "body": "Welcome to CodeReview. I find it easier to create code blocks using lines just containing `~~~` before and after: you don't have to touch indentation. Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask), improving the title of this post, too." } ]
[ { "body": "<p>There are few improvements you can do:</p>\n\n<ol>\n<li>Remove the first <code>sec_no = random.randint(0, 10)</code>. You are already initializing it inside of the main while loop.</li>\n<li>Create a variable that contains <code>minp.lower()</code>. Instead of calculating it over and over - keep it in a variable and avoid code duplication.</li>\n<li>Get rid of <code>ncout</code> or <code>att</code>. They are practically saving the same thing, keep only <code>att</code> and change the while and if condition to <code>att &gt; 0</code>.</li>\n<li>Add some comments - File comments and function comments.</li>\n<li>General python tip: do not write code in main, Use functions. Function for each case, function for main loop, <a href=\"https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except\">function to check if string is int</a> and the <code>__main__</code> should look like this:</li>\n</ol>\n\n<pre><code>if __name__ == '__main__':\n main_function()\n</code></pre>\n\n<p>Except for that - good logic, nice code :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T15:38:25.080", "Id": "235019", "ParentId": "234978", "Score": "2" } }, { "body": "<p>You could implement a hint to the answer so you can broaden the range of numbers. This is just a quick example. </p>\n\n<pre><code>import random\n\nnum = random.randrange(1, 100)\nlives = 5\nprint('''\nWelcome to the guessing game. Guess a number between 1-100.\\nYou have {} lives\n'''.format(lives))\nwhile True:\n try:\n if lives == 0:\n print('You died!\\nThe number you were looking for is {}'.format(num))\n break\n guess = int(input('Guess: \\n'))\n if guess == num:\n print('You win!')\n break\n if guess &lt; num:\n lives -= 1\n print('Number is higher...\\nlives: {}\\n'.format(lives))\n if guess &gt; num:\n lives -= 1\n print('Number is lower...\\nlives: {}\\n'.format(lives))\n except ValueError:\n print('Numbers only!') \n</code></pre>\n\n<p>The result:</p>\n\n<pre><code>Welcome to the guessing game. Guess a number between 1-100.You have 5 lives\n\nGuess:\n50\nNumber is lower...\nlives: 4\n\nGuess:\n30\nNumber is lower...\nlives: 3\n\nGuess:\n25\nNumber is lower...\nlives: 2\n\nGuess:\n10\nNumber is higher...\nlives: 1\n\nGuess:\n16\nNumber is lower...\nlives: 0\n\nYou died!\nThe number you were looking for is 13\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T20:16:43.647", "Id": "460028", "Score": "1", "body": "Really nice, I usually like to use [`fstrings`](https://realpython.com/python-f-strings/) instead of `format`. Just notice that this works for python3 and above." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T21:24:14.097", "Id": "235092", "ParentId": "234978", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T02:26:13.697", "Id": "234978", "Score": "2", "Tags": [ "python", "number-guessing-game" ], "Title": "Just a simple guessing game" }
234978
<p>I have a block of Jinja2 (used in Sceptre/CloudFormation). It is not readable in my opinion, but I can't find any way to clean it up to improve it. </p> <pre class="lang-jinja2 prettyprint-override"><code>{% set args = "--kubelet-extra-args '--node-labels=nodegroup=" + sceptre_user_data.node_group_name %} {% if sceptre_user_data.node_labels != "None" %} {% set args = args + "," + sceptre_user_data.node_labels %} {% endif %} zone=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone) {% if sceptre_user_data.cni_custom_network == "Yes" %} {% set args = args + ",k8s.amazonaws.com/eniConfig=pod-netconfig-$zone" %} {% endif %} {% if sceptre_user_data.taints != "None" %} {% set args = args + " --register-with-taints=" + sceptre_user_data.taints %} {% endif %} {% set args = args + "'" %} eval "/etc/eks/bootstrap.sh ${EKSClusterName} {{ args }}" </code></pre> <p>I tried using <code>join</code> filters although that seemed to make it worse.</p> <p>(This has nothing to do with Flask, but is all about Jinja2 obviously. But there appears to be no Jinja2 tag.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T11:22:22.443", "Id": "460106", "Score": "2", "body": "This question lacks any indication of 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)." } ]
[ { "body": "<p>In the end I refactored like this:</p>\n\n<pre class=\"lang-jinja2 prettyprint-override\"><code>{% set node_group_name = sceptre_user_data.node_group_name %}\n{% set node_labels = sceptre_user_data.node_labels %}\n{% set taints = sceptre_user_data.taints %}\n{% set cni_custom_network = sceptre_user_data.cni_custom_network %}\n\n...\n\ndo_bootstrap() {\n {% set args = \"--kubelet-extra-args '--node-labels=nodegroup=\" + node_group_name %}\n\n {% if node_labels != \"None\" %}\n {% set args = args + \",\" + node_labels %}\n {% endif %}\n\n {% if cni_custom_network == \"Yes\" %}\n zone=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)\n {% set args = args + \",k8s.amazonaws.com/eniConfig=pod-netconfig-$zone\" %}\n {% endif %}\n\n {% if taints != \"None\" %}\n {% set args = args + \" --register-with-taints=\" + taints %}\n {% endif %}\n\n {% set args = args + \"'\" %}\n\n eval \"/etc/eks/bootstrap.sh ${EKSClusterName} {{ args }}\"\n}\n\ndo_bootstrap\n</code></pre>\n\n<p>I would still welcome feedback from anyone who knows a Jinja2 trick that might help that I don't know.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T23:40:32.647", "Id": "235137", "ParentId": "234981", "Score": "2" } } ]
{ "AcceptedAnswerId": "235137", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T02:59:25.657", "Id": "234981", "Score": "3", "Tags": [ "flask" ], "Title": "Jinja2 block that is unreadable" }
234981
<p>I created a Rock/Paper/Scissors game in C# that asks the player the number of rounds he wants to play, and then calculates the points and determines the winner. Is there a way I can fix my code? Is it appropriate to use switch and if/else together?</p> <pre><code>Console.Write("How many rounds do you want to play ? : "); int numberOfRounds = Convert.ToInt32(Console.ReadLine()); Random rnd = new Random(); string[] hands = { "Rock", "Paper", "Sci" }; // 0 1 2 int playerPoints = 0; int computerPoints = 0; for (int counter = 1; counter &lt;= numberOfRounds; counter++) { Console.Write("Player Hand : "); string playerHand = Console.ReadLine(); int randomNumber = rnd.Next(0, 3); string computerHand = hands[randomNumber]; Console.WriteLine("Computer Hand : " + computerHand); switch (playerHand) { case "Rock": if (computerHand == "Rock") { playerPoints++; computerPoints++; Console.WriteLine("Player And Computer Win a Point"); Console.WriteLine(); } if (computerHand == "Paper") { computerPoints++; Console.WriteLine("Computer wins a point"); Console.WriteLine(); } if (computerHand == "Sci") { playerPoints++; Console.WriteLine("Player wins a point"); Console.WriteLine(); } break; case "Paper": if (computerHand == "Paper") { playerPoints++; computerPoints++; Console.WriteLine("Player and Computer Win a Point"); Console.WriteLine(); } if (computerHand == "Sci") { computerPoints++; Console.WriteLine("Computer wins a point"); Console.WriteLine(); } if (computerHand == "Rock") { playerPoints++; Console.WriteLine("Player wins a point"); Console.WriteLine(); } break; case "Sci": if (computerHand == "Sci") { playerPoints++; computerPoints++; Console.WriteLine("Player and Computer Win a Point"); Console.WriteLine(); } if (computerHand == "Rock") { computerPoints++; Console.WriteLine("Computer wins a point"); Console.WriteLine(); } if (computerHand == "Paper") { playerPoints++; Console.WriteLine("Player wins a point"); Console.WriteLine(); } break; } } Console.WriteLine("*** RESULTS ***"); Console.WriteLine("Player Points : " + playerPoints); Console.WriteLine("Computer Points : " + computerPoints); if (playerPoints &gt; computerPoints) { Console.WriteLine("Player Wins"); } else { if (computerPoints &gt; playerPoints) { Console.WriteLine("Computer Wins"); } else { Console.WriteLine("Equal None Win"); } } Console.ReadLine(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:09:58.293", "Id": "459704", "Score": "3", "body": "Welcome to Code Review! Please post the whole method. We can't give you a good review If we need to guess about the remaining code either before or after your posted code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T02:51:30.917", "Id": "459951", "Score": "2", "body": "Welcome to Code Review! If your code needs to be \"fixed\" then we assume that it is not working as expected and code that isn't working as desired is off-topic for Code Review. would you please clarify your question?" } ]
[ { "body": "<p>Right at the start we can turn your <code>hands</code> array in to a dictionary so we can compare <code>Int</code> insted of <code>String</code>, which is way faster. </p>\n\n<blockquote>\n <p>In such a small application it is not mandatory such optimizations, but it is good to consider in the long run.</p>\n</blockquote>\n\n<pre><code>Dictionary&lt;string, int&gt; handsValues = new Dictionary&lt;string, int&gt;()\n {\n {\"Rock\", 0},\n {\"Paper\", 1},\n {\"Sci\", 2}\n };\n</code></pre>\n\n<p>Because we are going to compare only <code>Int</code> values we get rid of:</p>\n\n<pre><code>int randomNumber = rnd.Next(0, 3);\nstring computerHand = hands[randomNumber];\nConsole.WriteLine(\"Computer Hand : \" + computerHand); \n</code></pre>\n\n<p>We turn it into:</p>\n\n<pre><code>int computerHand = rnd.Next(0, 3);\nConsole.WriteLine(\"Computer Hand : \" + handsValues.Keys.ElementAt(computerHand));\n</code></pre>\n\n<p>Calling <code>.Keys</code> on a dictionary returns to us a collection of Index,Value pairs\n<a href=\"https://i.stack.imgur.com/CdNBx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CdNBx.png\" alt=\"Memory Visualization\"></a>\nThen calling <code>.ElementAt(int index)</code> we can get a value by its index</p>\n\n<hr>\n\n<p>The only clear problem with your code is the <code>computerHand</code> and <code>playerHand</code> logic, you can first check for equality of the hands before going to check each variation.</p>\n\n<pre><code>if (handsValues[playerHand] == computerHand)\n{\n playerPoints++;\n computerPoints++;\n Console.WriteLine(\"Player And Computer Win a Point\" + Environment.NewLine);\n}\nelse\n{\n switch (handsValues[playerHand])\n {\n case 0:\n if (computerHand == 1)\n {\n computerPoints++;\n Console.WriteLine(\"Computer wins a point\" + Environment.NewLine);\n }\n else\n {\n playerPoints++;\n Console.WriteLine(\"Player wins a point\" + Environment.NewLine);\n }\n break;\n\n case 1:\n if (computerHand == 2)\n {\n computerPoints++;\n Console.WriteLine(\"Computer wins a point\" + Environment.NewLine);\n }\n else\n {\n playerPoints++;\n Console.WriteLine(\"Player wins a point\" + Environment.NewLine);\n }\n break;\n\n case 2:\n if (computerHand == 0)\n {\n computerPoints++;\n Console.WriteLine(\"Computer wins a point\" + Environment.NewLine);\n }\n else\n {\n playerPoints++;\n Console.WriteLine(\"Player wins a point\" + Environment.NewLine);\n }\n break;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>A small detail, you can skip the <code>Console.WriteLine();</code>, by putting <code>\"\\r\\n\"</code> at the end of you string(not recommended due to OS compatibility problems) or by concatenating <code>Environment.NewLine</code> to your string.</p>\n\n<p>Your naming of variable is on point, excluding the unclear <code>hands</code> </p>\n\n<p>The full code you can check <a href=\"https://pastebin.com/AwE66frq\" rel=\"nofollow noreferrer\">HERE</a>, USE Ctrl + Click</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:31:10.180", "Id": "459705", "Score": "2", "body": "Calling `ElementAt` on a dictionary looks a lot like unspecified result. That's something you should explain in your answer since someone who writes rock paper scissors games probably doesn't know about this, and it's easy to wrongly assume that dictionaries were sorted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:33:36.527", "Id": "459706", "Score": "1", "body": "The slashes in `\"/r/n\"` should be backslashes instead:`\"\\r\\n\"`. It's still better to use WriteLine, to ensure the program works as expected on Linux and other operating systems as well. Windows is one of the very few operating systems that use `\\r\\n` as the line separator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:39:37.657", "Id": "459707", "Score": "1", "body": "You should post your rewritten code directly in this answer. And if you explain and fix the redundant code in `DeeperCheck` (which is a terrible method name, by the way), it's not even _that_ long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:43:55.840", "Id": "459708", "Score": "1", "body": "See https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys#remarks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T06:35:25.657", "Id": "459711", "Score": "0", "body": "@RolandIllig Thanks for the corrections! Hope you are satisfied with the edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T15:42:24.947", "Id": "459768", "Score": "0", "body": "Hmmm, I don't see any substantial changes in your answer. You show the dictionary but don't mention that the order is only the same _by coincidence_, which is the important point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T15:44:40.420", "Id": "459769", "Score": "0", "body": "The code you posted still contains lots of duplicated statements." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:22:13.750", "Id": "234986", "ParentId": "234982", "Score": "0" } }, { "body": "<p>I've got a few suggestions to improve your application. I would suggest using a few functions to clean up the organization of your code. This will also allow you to move some off your logic away from your main application logic which will help to remove duplicate code.</p>\n\n<p>First main change I would suggest is to move away from the array of strings to represent your choices. Right now you have to hard code string throughout your application. This will make it hard to make changes in the future and could cause errors if you misspell any of the values. Instead you could either use constant variable, which would allow you to change the value in a single place. See below:</p>\n\n<pre><code> // Initial string representation\n public const string Rock = \"Rock\";\n public const string Paper = \"Paper\";\n public const string Scissor = \"Scissor\";\n\n // Later could be changed to this.\n public const int Rock = 1;\n public const int Paper = 2;\n public const int Scissor = 3;\n\n</code></pre>\n\n<p>Instead of using const variable we can use enums to store the player's actions as well as the applications state. This will also give us a couple benefits that will be shown below. The following code will be using these enums.</p>\n\n<pre><code> public enum Action { Rock, Paper, Scissor };\n public enum Result { Tie, PlayerWon, ComputerWon }\n</code></pre>\n\n<p>When taking input from the user, you should be prepared for an incorrect input. The quick and easy way to handle parsing inputs is to use the 'TryParse' method found on the type you are trying to convert to. We can use the 'TryParse' method for both reading the amount of rounds the player desires and their hand choice.</p>\n\n<pre><code> public static int GetDesiredRounds() {\n int result;\n do {\n var input = Console.ReadLine();\n if(Int32.TryParse(input, out result)) {\n return result;\n } else {\n Console.WriteLine(\"Invalid input. Please input a number.\");\n }\n } while(true);\n }\n\n</code></pre>\n\n<p>Enums can also be parsed from a string using the 'TryParse' method. It also has an option to allow for case-insensitive parsing, which will allow the user to input either 'Rock' or 'rock' to get the same action.</p>\n\n<pre><code> public static Action GetPlayerAction() {\n Action result;\n do {\n var input = Console.ReadLine();\n // The second param tells code to ignore case of string string\n if(Action.TryParse(input, true, out result)) {\n return result; \n } else {\n Console.WriteLine(\"Invalid action {0}. Please input 'Rock', 'Paper' or 'Scissors'.\", input);\n }\n } while(true);\n }\n</code></pre>\n\n<p>Enum's have an underlying numeric type. Their values default to 0, 1, 2, 3... from the first enum value to the last (unless they are manually assigned, see enum reference below). You can cast an Enum to and from their underlying type. Below we have to cast the enum value to its underlying type in order to use it with the random.Next method, then we simply cast it back to an Action. </p>\n\n<pre><code> public static Action GetComputerAction() {\n // Gets a random number between 0 (Action.Rock) and 3 (Action.Scissor + 1)\n // This will result in the values 0 (Rock), 1 (Paper), or 2 (Scissor)\n // We use (Scissor + 1) since the 'Next' method does not include the max value\n return (Action)rand.Next((int)Action.Rock, (int)Action.Scissor + 1);\n }\n</code></pre>\n\n<p>With both the player and computer's choices, we then calculate the result. With the limited options, we could simply list out all the results using nested switch statements. One thing to observe is the throwing of an Exception. This exception should be never reached, since all the enum's values were used inside the switch. The compiler will complain if you remove the exception. (For a bit more information on this behavior see the reference link below).</p>\n\n<pre><code> public static Result CalculateResult(Action player, Action computer) {\n switch(player) {\n case Action.Rock:\n switch (computer) ) {\n case Action.Rock: return Result.Tie;\n case Action.Paper: return Result.ComputerWon;\n case Action.Scissor: return Result.PlayerWon;\n }\n break;\n case Action.Paper:\n switch (computer) ) {\n case Action.Rock: return Result.PlayerWon;\n case Action.Paper: return Result.Tie;\n case Action.Scissor: return Result.ComputerWon;\n }\n break;\n case Action.Scissor:\n switch (computer) ) {\n case Action.Rock: return Result.ComputerWon;\n case Action.Paper: return Result.PlayerWon;\n case Action.Scissor: return Result.Tie;\n }\n break;\n }\n\n // This should never be reached\n throw new Exception(string.Format(\"Unhandled action pair occured: {0}, {1}\", player, computer) ));\n }\n</code></pre>\n\n<p>Finally we can use our created functions to build the main body of the application. Another thing to observe is since we pulled the logic of calculating results out from the printing and point code, there is less code to repeat.</p>\n\n<pre><code> public static void Main() {\n // static variable used in GetComputerChoice\n rand = new Random();\n\n int playerPoints = 0;\n int computerPoints = 0;\n\n Console.WriteLine(\"How many rounds would you like to play?\");\n int rounds = GetDesiredRounds();\n\n for(var round = 1; round &lt;= rounds; round++) {\n Console.WriteLine(\"Round {0} Begins\", round);\n Console.WriteLine(\"Which hand do you choose(Rock, Paper, Scissor)? \");\n\n var playerAction = GetPlayerAction();\n Console.WriteLine(\"You picked: {0}\", playerAction.ToString());\n\n var computerAction = GetComputerAction();\n Console.WriteLine(\"Your opponent picked: {0}\", computerAction.ToString());\n\n switch(CalculateResult(playerAction, computerAction)) {\n case Result.PlayerWon:\n Console.WriteLine(\"You won the round! You gained a point.\");\n playerPoints++;\n break;\n case Result.ComputerWon:\n Console.WriteLine(\"Computer won the round! Computer gained a point.\");\n computerPoints++;\n break;\n case Result.Tie:\n Console.WriteLine(\"Round tied. You and the computer gained a point.\");\n playerPoints++;\n computerPoints++;\n break;\n }\n\n Console.WriteLine();\n }\n\n Console.WriteLine(\"Results - Player {0}, Computer {1}\", playerPoints, computerPoints);\n if (playerPoints == computerPoints) {\n Console.WriteLine(\"Tie Game\"); \n } else {\n bool isPlayerWinner = playerPoints &gt; computerPoints;\n Console.WriteLine(\"{0} won the game!\", isPlayerWinner ? \"Player\" : \"Computer\"); \n }\n }\n</code></pre>\n\n<p><strong>References</strong></p>\n\n<p><a href=\"https://github.com/steaks/codeducky/blob/master/blogs/enums.md\" rel=\"nofollow noreferrer\">Ins and Outs of enums in C#</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/4472765/in-c-sharp-is-default-case-necessary-on-a-switch-on-an-enum\">Enums in switch statements</a></p>\n\n<p><strong>Demo</strong></p>\n\n<p>The full example code can be found and ran <a href=\"https://dotnetfiddle.net/0iy1GX\" rel=\"nofollow noreferrer\">here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T20:42:25.937", "Id": "460176", "Score": "0", "body": "Great first answer. My only minor comment would be that you can extract the \"Tie\" comparison in CalculateResult out of the switch. eg if (player == computer) return Result.Tie;" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:41:52.567", "Id": "234989", "ParentId": "234982", "Score": "1" } }, { "body": "<p>My take on this:</p>\n\n<p>For console apps, I like to use a more OOP approach.</p>\n\n<p>A <code>Message</code> class to hold a string array to handle a multiline message, and if the message requires a response a string of the characters allowed, will allow you to replace all those string literals with named variables:</p>\n\n<pre><code>class Message\n{\n public String[] message { get; }\n public String choices { get; }\n public Message()\n {\n message = new String[0];\n choices = \"\";\n }\n public Message(String choices, params String[] message)\n {\n this.message = message;\n this.choices = choices.ToLower();\n }\n}\n</code></pre>\n\n<p>To compliment this class, a static storage class(<code>Messages</code>) to put names to the various messages that will be required. I put a simple print method in there as well:</p>\n\n<pre><code>static class Messages\n{\n public static Message startMessage = new Message(\"\", \"Welcome to RockScissorPaper\");\n public static Message instructions = new Message(\"\", \"When you're ready to play, press the desired number.\",\n \"The computer will reveal its choice and who won.\");\n public static Message rockWins = new Message(\"\", \"Rock breaks Scissors.\", \"Rock wins.\");\n public static Message scissorsWins = new Message(\"\", \"Scissors cuts Paper.\", \"Scissors wins.\");\n public static Message paperWins = new Message(\"\", \"Paper covers Rock.\", \"Paper wins.\");\n public static Message playAgain = new Message(\"yn\\n\", \"Would you like to play again?(y/n)\");\n public static Message continuePlay = new Message(\"\", \"Press any key to continue.\");\n public static Message choices = new Message(\"0123\", \"1 - Rock\", \"2 - Scissors\", \"3 - Paper\", \"0 - Quit\", \"\\nWhich do you choose?\");\n public static Message goodbye = new Message(\"\", \"Thank you for playing. Goodbye.\");\n public static Message tie = new Message(\"\", \"A tie. You both chose the same.\");\n public static Message wrongChoice = new Message(\"\", \"You made a wrong choice. Try again.\");\n\n public static void PrintMessage(TextWriter tOut, Message message)\n {\n tOut.WriteLine();\n foreach (var s in message.message)\n {\n tOut.WriteLine(s);\n }\n }\n}\n</code></pre>\n\n<p>This approach makes it very easy, with minimal refactoring, to create language choices for your app.</p>\n\n<p>For classes that require I/O, I like to keeps things flexible and use base classes instead of hard coding standard I/O. This makes it very easy to leverage networking at some point.</p>\n\n<p>For the game class(<code>RockScissorPaper</code>), a method to get the user's input, clears a lot of code from the <code>PlayGame</code> method.</p>\n\n<pre><code>private static char GetChoice(TextWriter tOut, TextReader tIn, Message message)\n{\n char choice = '\\0';\n bool done = false;\n do\n {\n Messages.PrintMessage(tOut, message);\n string response = tIn.ReadLine().ToLower();\n choice = response.Length &gt; 0 ? response[0] : '\\n';\n if (message.choices.Contains(choice))\n {\n return choice;\n }\n Messages.PrintMessage(tOut, Messages.wrongChoice);\n } while (!done);\n return choice;\n} \n</code></pre>\n\n<p>I find an enum for the different states of the game, helps with the decision process to decide a winner:</p>\n\n<pre><code>private enum State\n{\n None = 0,\n Tie = 1,\n Rock = 3,\n Scissors,\n Paper\n}\n</code></pre>\n\n<p>Notice the <code>Rock</code> constant starts at 3. This allows simple math and one conditional to decide which player is the winner. Once the winner is decided the <code>switch</code> block to select which message to display is very simple:</p>\n\n<pre><code>private static Message GetWinner(State comp, State player)\n{\n if (comp == State.None || player == State.None)\n {\n throw new ArgumentOutOfRangeException(\"Both 'comp' and 'player' must be 'Rock', 'Scissors' or 'Paper'.\");\n }\n int cmptr = (int)comp;\n int plyr = (int)player;\n State winner = State.None;\n if (player == comp)\n {\n winner = State.Tie;\n plyrScore++;\n compScore++;\n }\n else if(plyr % 3 == (cmptr - 1) % 3)\n {\n winner = player;\n plyrScore += 2;\n }\n else\n {\n winner = comp;\n compScore += 2;\n }\n switch (winner)\n {\n case State.Tie:\n return Messages.tie;\n case State.Rock:\n return Messages.rockWins;\n case State.Scissors:\n return Messages.scissorsWins;\n case State.Paper:\n return Messages.paperWins;\n default:\n return new Message(\"\", \"\");\n }\n}\n</code></pre>\n\n<p>I've incorporated the score calculation here, as well. I noticed you scored a tie the same a win. Typically a tie is considered half a win. I would prefer to see a win at 2 points and a tie at 1.</p>\n\n<p>With these helper methods done, the game play is almost trivial to code:</p>\n\n<pre><code>static class RockScissorsPaper\n{\n private static RandomEngine rnd = new RandomEngine();\n private enum State\n {\n None = 0,\n Tie = 1,\n Rock = 3,\n Scissors,\n Paper\n }\n static int plyrScore = 0;\n static int compScore = 0;\n public static void PlayGame(TextWriter tOut, TextReader tIn, String name, int rounds)\n {\n plyrScore = 0;\n compScore = 0;\n Messages.PrintMessage(tOut, Messages.startMessage);\n for(int round = 0; round &lt; rounds; ++round)\n {\n Messages.PrintMessage(tOut, Messages.instructions);\n int choice = GetChoice(tOut, tIn, Messages.choices) - '0';\n State compChoice = (State)Enum.GetValues(typeof(State)).GetValue((rnd.Next(0, 300) % 3) + 2);\n State playerChoice = (State)(choice + 2);\n tOut.WriteLine($\"The player chose {playerChoice}.\\nThe computer chose {compChoice}.\");\n Messages.PrintMessage(tOut, GetWinner(compChoice, playerChoice));\n tOut.WriteLine($\"The score is:\\n{name} - {plyrScore}\\nComputer - {compScore}\");\n Messages.PrintMessage(tOut, Messages.continuePlay);\n tIn.Read();\n }\n\n }\n\n private static char GetChoice(TextWriter tOut, TextReader tIn, Message message)\n {\n char choice = '\\0';\n bool done = false;\n do\n {\n Messages.PrintMessage(tOut, message);\n string response = tIn.ReadLine().ToLower();\n choice = response.Length &gt; 0 ? response[0] : '\\n';\n if (message.choices.Contains(choice))\n {\n return choice;\n }\n Messages.PrintMessage(tOut, Messages.wrongChoice);\n } while (!done);\n return choice;\n }\n private static Message GetWinner(State comp, State player)\n {\n if (comp == State.None || player == State.None)\n {\n throw new ArgumentOutOfRangeException(\"Both 'comp' and 'player' must be 'Rock', 'Scissors' or 'Paper'.\");\n }\n int cmptr = (int)comp;\n int plyr = (int)player;\n State winner = State.None;\n if (player == comp)\n {\n winner = State.Tie;\n plyrScore++;\n compScore++;\n }\n else if(plyr % 3 == (cmptr - 1) % 3)\n {\n winner = player;\n plyrScore += 2;\n }\n else\n {\n winner = comp;\n compScore += 2;\n }\n switch (winner)\n {\n case State.Tie:\n return Messages.tie;\n case State.Rock:\n return Messages.rockWins;\n case State.Scissors:\n return Messages.scissorsWins;\n case State.Paper:\n return Messages.paperWins;\n default:\n return new Message(\"\", \"\");\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T01:42:24.433", "Id": "235052", "ParentId": "234982", "Score": "2" } } ]
{ "AcceptedAnswerId": "235052", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T03:16:10.387", "Id": "234982", "Score": "1", "Tags": [ "c#", "rock-paper-scissors" ], "Title": "Rock/Paper/Scissors using C#" }
234982
<p>I'm developing a Python library to consume the Zendesk search API. Problem is, Zendesk limits search results to 1000 items. Thus in order to get all the results if they are greater than 1000 I need to call the endpoint several times with a recursive function storing the latest created <code>datetime</code> for a ticket once the 1000 limit is reached.</p> <p>My code at the moment works but it feels wrong. Could you help me to improve this recursive function? For instance I'd prefer not to declare an empty list at the constructor but instead inside the function.</p> <p>Here is the code:</p> <p><code>init.py</code></p> <pre><code>import requests import base64 from zdesktools.lib.api import SearchApi, TicketsApi class ZdeskTools(object): def __init__(self, zendeskApiUrl=None, username=None, password=None): session = self._begin_session(username, password) config = { 'zendeskApiUrl': zendeskApiUrl, 'session': session } self.search = SearchApi(**config) self.tickets = TicketsApi(**config) # self.metrics = MetricsApi(**config) def _begin_session(self, username, password): session = requests.Session() username_password = f'{username}/token:{password}' encoded_bytes = base64.b64encode(username_password.encode('utf-8')) encoded_string = str(encoded_bytes, 'utf-8') headers = { 'Authorization': f'Basic {encoded_string}' } session.headers.update(headers) return session </code></pre> <p><code>api.py</code></p> <pre><code>from urllib.parse import urlencode import json import pprint class SearchApi(object): def __init__(self, **config): self.session = config.get('session') self.url = config.get('zendeskApiUrl')+'/search.json?' self.created_at = [] self.tickets = [] def get_ticket_numbers(self, search_params): response = self.session.get(f'{self.url}{urlencode(search_params)}') data = response.json() if 'results' in data: for result in data['results']: self.created_at.append(result['created_at']) self.tickets.append(result['id']) if 'next_page' in data: if data['next_page'] is not None: self.url = data['next_page'] self.get_ticket_numbers(search_params) else: self.url = self.url[:self.url.index('?')+1] search_params['query'] = search_params['query'] + \ f' created_at&gt;={self.created_at[-1]}' self.get_ticket_numbers(search_params) return self.tickets </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T23:16:08.180", "Id": "459816", "Score": "0", "body": "I'm a little unclear on the purpose of that last else-clause. Are you trying to find all the tickets that were created since the search originally began?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T00:18:49.183", "Id": "459819", "Score": "0", "body": "This goes about the maximum pool size of a search which is limited to 1000 tickets paginated in 10 pages of 100 tickets each. However if the total results goes beyond 1000 I need to query the api again but this time including in the search parameter the latest ticket previously found creation date (that is the else clause)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T00:36:33.243", "Id": "459822", "Score": "0", "body": "So on the 10th page, is the 'next_page' key actually missing? Or does it have a value of `null`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T00:45:17.487", "Id": "459824", "Score": "0", "body": "It´s missing =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T01:00:42.803", "Id": "459825", "Score": "0", "body": "And in which cases do you expect the 'results' key to be missing? I can see from the API documentation that it will be missing if there is an error, but perhaps you had some other case in mind." } ]
[ { "body": "<p>My usual advice for implementors of recursive algorithms Is this: figure out how to do it without recursion (although i dont know how to prove it Is Always better, i can prove it Is never worse. And i can prove it Is Always possible.)</p>\n\n<p>This advice Is yet stronger in your case because there Is nothing recursive about pagination. Its you who made it recursive artificially.</p>\n\n<p>Further, the api has reasons to provide the data with a page limit. They dont want to run to memory issues when serving those data to you.</p>\n\n<p>Nor should you want to run into memory issues when processing the data. If Its not restricting you, you should also process the data page by page discarding the previous page before loading another one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:40:06.873", "Id": "459745", "Score": "1", "body": "I, on the other hand, disagree. A recursive algorithm allows you to express loops immutably, passing the state as a parameter, and if the language has halfway-decent tail-call optimisation then it'll all get optimised down to the same thing. Liberating yourself from the mutation of state often leads to simpler reasoning!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:43:30.510", "Id": "459746", "Score": "0", "body": "I take it back: Python does not have halfway-decent tail-call optimisation, and never will (https://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion). Carry on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:01:25.500", "Id": "459749", "Score": "0", "body": "@PatrickStevens \"The optimizer turns the recurisve version into machine code that is equivalent to that of the non-recurisve version.\" only confirms that the recursive version was not optimal. You just got the benefit of the optimizer opmizing it automaticaly for you. If optimizer is available, they yes it is probably a matter of preference. If it is not and the algorithm needs to stack everything, then difference would probably be neglegable and it is again matter of preference. In all other cases it depends what you want. If you want performance, go non-recursive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:03:16.943", "Id": "459750", "Score": "1", "body": "It depends what you mean by \"optimal\". In most situations, I prefer readability and correctness to speed; computers are fast enough for nearly everything I ever want to do anyway. In the OP's example, network requests will massively dominate the running time no matter what kind of looping construct is used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:08:48.830", "Id": "459752", "Score": "0", "body": "@PatrickStevens Well I usualy refer to performance when I say \"optimal\". But readability is also important. But I am just so used to non-recursivity that I actualy find it easier to read and understand. Anyway, in case of OP's code, I don't even see the reasoning for recursion from the logical point of view. You dont hold all the pages that you have read until you finish the book so you can turn those pages back one by one until you reach the first chanpter, the introduction and finally close the book... That's what it reminds me..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:21:15.200", "Id": "459753", "Score": "0", "body": "Well, the \"turn those pages back\" is absolutely trivial in a properly-formulated tail-recursive function, since there are no further instructions after the recursive call. It's perfectly reasonable for your mental model of a \"read the book\" program to keep holding onto the book as you read it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:44:49.640", "Id": "459757", "Score": "0", "body": "@PatrickStevens Alright, maybe that wasn't the best analogy... Anyway let's not turn this into discussion about recursion. Important has been said. We can settle that we prefer the opposite approaches. Recursion aside, there is still the argument of uncontrolled memory growth. I believe that it is generaly unwise to read paged resources completly into memory without any control and therefore in the case of OP i see the recursion as inappropriate, because it cannot easily grant the control." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T21:33:42.790", "Id": "459811", "Score": "0", "body": "I appreciate the feedback, guess I'll figure another way to do it" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:22:07.237", "Id": "234993", "ParentId": "234983", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T04:20:28.750", "Id": "234983", "Score": "4", "Tags": [ "python", "python-3.x", "recursion", "api" ], "Title": "Recursive function to get all Zendesk tickets" }
234983
<p><strong>Description:</strong></p> <p>This would make a first part of a currency exchange simulator The first phase includes downloading currency historical data from histdata.com api, plotting given period and given time frames using different plot types and adding some forex technical indicators to the data. I will be posting follow ups when I'm done with further phases of the project.</p> <p><strong>Feedback:</strong></p> <p>I need feedback regarding the whole program structure, and general suggestions for improvements/optimizations/features to add are welcome. I'm intending to add a simulation functionality with virtual money and automate a bot that runs on the historical data which predicts future values and maximize profit and maybe a GUI. I also need suggestions on predicting future values for a given time period in the future using machine learning I don't know maybe neural networks - regression - nlp ... I need guidance on focus points(what libraries/techniques...) for building a robust machine learning prediction system as I'm not quite experienced in ml.</p> <p><strong>Links:</strong> </p> <p>Please download the following zip file and extract the contents(2 folders beginning with 'DAT') in the same folder as the code's (to be able to run the simulator on the period(2017-2018) for <code>eurusd</code> pair:</p> <p><a href="http://2017-2018%20eurusd%20folders" rel="nofollow noreferrer">2017-2018 eurusd M1(1 minute data)</a></p> <p><strong>Files</strong></p> <ul> <li><code>forex_data_handler.py</code>: This is used to download forex historical data from <a href="https://www.histdata.com/" rel="nofollow noreferrer">histdata.com</a> api (Use pip3 install histdata beforehand if you're going to download extra data) and this is optional (Links are provided above for minimal trial-run) and of course feel free to download whatever data you want using this module for trying extra examples.</li> <li><p><code>fx_simulator.py</code>: This is the simulation part of the code and since it's the first part of the project, it contains the following features:</p> <p>A) The <code>FxSimulator</code> constructor accepts parameters such as currency pairs, years and a few other parameters(you'll find everything in the docstrings)</p> <p>B) <code>get_interval()</code> method which returns a specific time frame pandas DF. Time frames ex: M1 = 1 min, D5 = 5 days ... check the documentation.</p> <p>C) <code>compare_years()</code> and <code>compare_year_months()</code> methods to enable comparisons of months and years periods using a selection of parameters including <code>interval</code>, <code>comparison_value</code> ...</p> <p>D) <code>plot_initial_data()</code> method to plot the historical data (scatter, line, histogram ...</p> <p>E) <code>add_indicators()</code> method to add forex technical indicator values to the pandas df. <a href="https://www.tradingtechnologies.com/xtrader-help/x-study/technical-indicator-definitions/list-of-technical-indicators/" rel="nofollow noreferrer">Indicators</a> include(Bollinger Bands, RSI, Moving Averages ...) </p></li> <li><p><code>pairs.txt</code>: Contains a list of 66 different currency pairs to choose from while downloading the data(optional) from <a href="https://www.histdata.com/" rel="nofollow noreferrer">histdata.com</a> api.</p></li> </ul> <p><strong>Example Plots:</strong></p> <ul> <li><strong>2010-2018 period eurusd 'Close' 1 Day(D1) year comparisons(1 figure):</strong></li> </ul> <p><a href="https://i.stack.imgur.com/UNu3E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UNu3E.png" alt="2010-2018 period eurusd &#39;Close&#39; 1 Day(D1) year comparisons(1 figure)"></a></p> <ul> <li><strong>2010-2018 period eurusd 'Close' 1 Day(D1) year comparisons(Multiple plots):</strong></li> </ul> <p><a href="https://i.stack.imgur.com/jzNsE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jzNsE.png" alt="2010-2018 period for eurusd &#39;Close&#39; 1 Day(D1) year comparisons(Multiple plots)"></a></p> <ul> <li><strong>2019 Months comparison with Moving average(14 days) for eurusd 'Close' 1 Day(D1)</strong></li> </ul> <p><a href="https://i.stack.imgur.com/WNHRB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WNHRB.png" alt="2019 Months comparison for eurusd &#39;Close&#39; 1 Day(D1)"></a></p> <ul> <li><strong>2019 Seasonal decompose for eurusd 'Close' 1 Day(D1)</strong></li> </ul> <p><a href="https://i.stack.imgur.com/tM0PN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tM0PN.png" alt="2019 Seasonal decompose for eurusd &#39;Close&#39; 1 Day(D1)"></a></p> <p><code>forex_data_handler.py</code>:</p> <pre><code>from histdata import download_hist_data from concurrent.futures import ThreadPoolExecutor, as_completed from time import perf_counter import os def get_folder_name(year, platform, time_frame, pair, month=None, compressed=True): """ Produce folder name in histdata.com download format. Args: year: ex: 2010 platform: MT, ASCII, XLSX, NT, MS. time_frame: M1 (one minute) or T (tick data). pair: ex: 'eurgbp' month: int range(1, 12) inclusive compressed: If compressed, a folder name ending with '.zip' is returned """ if not month: folder_name = '_'.join(['DAT', platform, pair.upper(), time_frame, str(year)]) if compressed: return folder_name + '.zip' else: return folder_name if month and month &lt;= 9: month = '0' + str(month) folder_name = '_'.join(['DAT', platform, pair.upper(), time_frame, str(year) + str(month)]) if compressed: return folder_name + '.zip' if not compressed: return folder_name def download_fx_data(start_year, end_year, pairs, threads=50, time_frame='M1', platform='MT', output_directory='.', current_year=2019, current_month=12): """ Download Forex data over a given time range from histdata api. Args: start_year: int: The starting year. end_year: int: The ending year. pairs: A list of pairs ex: ['eurgbp', 'eurusd'] threads: Number of parallel threads. time_frame: M1 (one minute) or T (tick data). platform: MT, ASCII, XLSX, NT, MS. output_directory: Where to dump the data. current_year: Current year. current_month: Current month. """ month_pairs = [] if end_year &gt;= current_year: last_year = current_year - 1 else: last_year = end_year years_pairs = [(year, pair) for year in range(start_year, last_year + 1) for pair in pairs if get_folder_name(year, platform, time_frame, pair) not in os.listdir(output_directory)] if end_year &gt;= current_year: month_pairs.extend([(month, pair) for pair in pairs for month in range(1, current_month) if get_folder_name(current_year, platform, time_frame, pair, month) not in os.listdir(output_directory)]) with ThreadPoolExecutor(max_workers=threads) as executor: future_years_data = {executor.submit(download_hist_data, str(year), None, pair, time_frame, platform, output_directory): (year, pair) for year, pair in years_pairs} future_months_data = {executor.submit(download_hist_data, str(current_year), str(month), pair, time_frame, platform, output_directory): (month, pair) for month, pair in month_pairs} for future_file in as_completed(future_years_data): try: future_file.result() except AssertionError: print(f'Failure to retrieve {future_years_data[future_file]}') for future_file in as_completed(future_months_data): try: future_file.result() except AssertionError: print(f'Failure to retrieve {future_months_data[future_file]}') if __name__ == '__main__': start_time = perf_counter() # Change the next line for specific choices, this is set to download all the data available. # pair_list = [pair.rstrip() for pair in open('pairs.txt').readlines()] # download_fx_data(2000, 2020, pair_list) end_time = perf_counter() print(f'Process finished ... {end_time - start_time} seconds.') </code></pre> <p><code>fx_simulator.py</code>:</p> <pre><code>from statsmodels.tsa.seasonal import seasonal_decompose from forex_data_handler import get_folder_name import matplotlib.pyplot as plt import pandas as pd import os class FxSimulator: """A tool for conducting forex backtesting and simulation.""" def __init__(self, pair, years, history_data_path='.', platform='MT', time_frame='M1', current_year=2019, current_month=12): """ Initialize year data. Args: pair: A string of currency pair ex: 'eurusd' years: a list of years. history_data_path: Folder path containing the historical data. platform: MT, ASCII, XLSX, NT, MS. time_frame: M1 or T current_year: Current year ex: 2019 current_month: Current month ex: 8 """ not_supported_years = [yr for yr in years if yr not in range(2000, current_year + 1) or yr &gt; current_year] if not_supported_years: raise ValueError(f'Invalid year {not_supported_years[0]}' f'\nYears supported are in range 2000-current year.') self.currency_pair = pair self.years = years self.path = history_data_path self.platform = platform self.time_frame = time_frame self.current_year = current_year self.current_month = current_month self.column_names = {'M1': ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']} def combine_frames(self, folders, sep=','): """ Combine folder data. Args: folders: A list of folders. sep: Separator of the csv file. Return: A data frame of all folders combined. """ frames = [] for folder_name in folders: try: os.chdir(self.path + folder_name) current_frame = pd.read_csv(folder_name + '.csv', sep=sep, names=self.column_names[self.time_frame], parse_dates=True) frames.append(current_frame) except FileNotFoundError: print(f'Folder: {folder_name} not found.') if frames: return pd.concat(frames) def load_data(self, sep=',', year=None): """ Load data of the given year range from csv. Args: sep: Separator of the csv file. year: To load a particular year data. Return: A data frame with the following columns (check self.column_names) """ current_year_month_folders = [get_folder_name( self.current_year, self.platform, self.time_frame, self.currency_pair, month, False) for month in range(1, self.current_month)] if year: if year not in self.years: raise ValueError(f'Year {year} not included in self.years') if year != self.current_year: folder_name = get_folder_name(year, self.platform, self.time_frame, self.currency_pair, None, False) return self.combine_frames([folder_name], sep) if year == self.current_year: return self.combine_frames(current_year_month_folders, sep) folder_names = [get_folder_name(yr, self.platform, self.time_frame, self.currency_pair, None, False) for yr in self.years if yr != self.current_year] if self.current_year in self.years: folder_names.extend(current_year_month_folders) return self.combine_frames(folder_names, sep) def get_interval(self, interval, year=None, day_timing='12:30'): """ Set desired interval. Args: interval: 'M' + Minute interval(int 1 - 60) ex: M15 --&gt; 15 minute interval. 'H' + Hour interval(int 1 - 24) ex: H4 --&gt; 4 hour interval. 'D' + Day interval(int 1 - 31) ex: D1 --&gt; 1 day interval. 'W' + Week interval(int 1 - 4) year: If year, interval of the year will be returned. day_timing: Timing of the day to get intervals. Return: Adjusted data frame. """ if year: period_data = self.load_data(year=year) else: period_data = self.load_data() if 'M' in interval: current_minutes = period_data['Time'].apply(lambda timing: int(timing.split(':')[-1])) return period_data[current_minutes % int(interval[1:]) == 0] if 'H' in interval: hour_data = period_data[period_data['Time'].apply(lambda timing: timing.split(':')[-1] == '00')] only_hours = hour_data['Time'].apply(lambda timing: int(timing.split(':')[0])) valid_hours = only_hours % int(interval[1:]) == 0 return hour_data[valid_hours] if 'D' in interval: day_data = period_data[period_data['Time'] == day_timing] day_only = day_data['Date'].apply(lambda timing: int(timing.split('.')[-1])) return day_data[day_only % int(interval[1:]) == 0] if 'W' in interval: week_data = period_data[period_data['Date'].apply(lambda timing: int(timing.split('.')[-1]) % 7) == 0] valid_weeks = week_data[week_data['Date'].apply(lambda timing: int(timing.split('.')[-1]) % int(interval[1:])) == 0] return valid_weeks[valid_weeks['Time'] == day_timing] raise ValueError(f'Invalid interval: {interval}') def compare_years(self, interval, comparison_value): """ Get A monthly indexed data for years in self.years. Args: interval: Period string indication ex: 'M1', 'D5' ... comparison_value: A string indication of value to compare: ex: 'Open', Close ... Return: A data frame containing year data per month. """ frames = [] for year in self.years: data = self.get_interval(interval, year) data['Month'] = data['Date'].apply(lambda timing: timing.split('.')[1]) data.reset_index(drop=True, inplace=True) frames.append(data) all_years = pd.concat(frames, axis=1).dropna() all_years.set_index('Month', inplace=True) all_years.reset_index(inplace=True) all_years['Month'] = all_years['Month'].apply(lambda months: set(months).pop()) years_data = all_years[['Month', comparison_value]] years_data.columns = ['Month'] + [comparison_value + '(' + str(yr) + ')' for yr in self.years] return years_data def compare_year_months(self, year, interval): """ Get A certain year months. Args: year: A year specified in self.years interval: Period string indication ex: 'M1', 'D5' ... Return: A data frame containing months of a certain year. """ if year not in self.years: raise ValueError(f'Year {year} not included in self.years') year_data = self.get_interval(interval, year) year_data['Month'] = year_data['Date'].apply(lambda timing: timing.split('.')[1]) return year_data def plot_initial_data(self, plot_type, interval, year=None, years=False, comparison_value=None, moving_average=None, **kwargs): """ Plot initial data in several graph forms. Args: plot_type: A string indication to graph type. - li: Line plot. - h: Histogram. - bw: Box &amp; whiskers plot. - lp: Lag plot. - ac: Auto-correlation plot. - sda: Additive Seasonal decompose(Observed-Trend-Seasonal-Residual). - sdm: Multiplicative Seasonal decompose(Observed-Trend-Seasonal-Residual). interval: Period string indication ex: 'M1', 'D5' ... year: If True, only months of given year will be plotted. years: If True, years will be compared. comparison_value: If years, this would be a string indication of value to compare against ('Open', Close ...) moving_average: int representing the moving average window to be displayed (works when a comparison value is specified). **kwargs: Additional keyword arguments. Return: None """ if years and not comparison_value: raise ValueError(f'Comparison value not specified for years=True') if year and years: raise ValueError(f'Cannot compare a single year and all years, please specify year or years') if moving_average and not comparison_value: raise ValueError(f'Comparison value not specified for moving average {moving_average}') if plot_type in ['sda', 'sdm'] and not comparison_value: raise ValueError(f'Must specify a comparison value for seasonal decomposition') period_data = pd.DataFrame() if not year and not years: period_data = self.get_interval(interval) period_data.set_index('Date', inplace=True) if comparison_value: period_data = period_data.filter(like=comparison_value) if moving_average: period_data['Moving Average'] = period_data[comparison_value].rolling(moving_average).mean() if years: period_data = self.compare_years(interval, comparison_value) period_data.set_index('Month', inplace=True) if moving_average: for column in period_data.columns: if comparison_value in column: period_data['MA ' + column] = period_data[column].rolling(moving_average).mean() if year: period_data = self.compare_year_months(year, interval) period_data.set_index('Month', inplace=True) if comparison_value: period_data = period_data.filter(like=comparison_value) if moving_average: period_data['Moving Average'] = period_data[comparison_value].rolling(moving_average).mean() if plot_type == 'li': period_data.plot(**kwargs) if plot_type == 'h': period_data.hist(**kwargs) if plot_type == 'bw': period_data.boxplot(**kwargs) if plot_type == 'sda': result = seasonal_decompose(period_data.filter(like=comparison_value), model='additive', freq=1) result.plot() if plot_type == 'sdm': result = seasonal_decompose(period_data.filter(like=comparison_value), model='multiplicative', freq=1) result.plot() plt.show() def add_indicators(self, interval, indicators, significant_value='Close', year=None, day_timing='12:30', rsi_period=14, si_period=14, bb_period=20, kn_period=9, kj_period=26, fast_ema=12, slow_ema=26, signal_line=9, adx_period=14): """ Add Forex technical indicators for the specified interval. Args: interval: 'M' + Minute interval(int 1 - 60) ex: M15 --&gt; 15 minute interval. 'H' + Hour interval(int 1 - 24) ex: H4 --&gt; 4 hour interval. 'D' + Day interval(int 1 - 31) ex: D1 --&gt; 1 day interval. 'W' + Week interval(int 1 - 4). indicators: A list of Technical indicators including: - 'rsi': Relative strength indicator(RSI). - 'si': Stochastic oscillator indicator(SI). - 'bb': Bollinger Bands indicator. - 'ic': Ichimoku Cloud. - 'macd': Moving Average Convergence Divergence(MACD). - 'pp': Pivot Point. - 'adx': Average Directional movement(ADX) significant_value: Close - Open - High - Low. year: If year, interval of the year will be returned. day_timing: Timing of the day to get intervals. rsi_period: Period of averaging for the relative strength(RSI) indicator. si_period: Period of averaging for the stochastic indicator(SI). bb_period: Period of averaging for the Bollinger Bands indicator. kn_period: Period of averaging for the Ichimoku Cloud indicator(Kenkan-Sen). kj_period: Period of averaging for the Ichimoku Cloud indicator(Kijun Sen). fast_ema: Period of exponential moving average(12 days) slow_ema: Period of exponential moving average(26 days) signal_line: MACD signal line. adx_period: Average True Range(ATR) period. Return: Data frame with the adjusted technical indicators. """ period_data = self.get_interval(interval, year, day_timing).reset_index(drop=True) if 'rsi' in indicators: period_data['Change'] = period_data[significant_value] - period_data[significant_value].shift(1) period_data['Upward Movement'] = period_data['Change'].apply(lambda change: change if change &gt; 0 else 0) period_data['Downward Movement'] = period_data['Change'].apply(lambda change: abs(change) if change &lt; 0 else 0) period_data['Average Upward Movement'] = period_data['Upward Movement'].rolling(rsi_period).mean() period_data['Average Downward Movement'] = period_data['Downward Movement'].rolling(rsi_period).mean() period_data['Relative Strength(RS)'] = (period_data['Average Upward Movement'] / period_data['Average Downward Movement']) period_data['Relative Strength Index(RSI)'] = 100 - (100 / (1 + period_data['Relative Strength(RS)'])) if 'si' in indicators: period_data['Lowest Low'] = period_data['Low'].rolling(si_period).min() period_data['Highest High'] = period_data['High'].rolling(si_period).max() period_data['Stochastic Oscillator Index'] = 100 * (period_data['Close'] - period_data['Lowest Low']) / ( period_data['Highest High'] - period_data['Lowest Low']) if 'bb' in indicators: period_data['Bollinger Middle Band'] = period_data[significant_value].rolling(bb_period).mean() period_data['Bollinger Standard Deviation'] = period_data[significant_value].rolling(bb_period).std() period_data['Upper Bollinger Band'] = period_data['Bollinger Middle Band'] + ( 2 * period_data['Bollinger Standard Deviation']) period_data['Lower Bollinger Band'] = period_data['Bollinger Middle Band'] - ( 2 * period_data['Bollinger Standard Deviation']) if 'ic' in indicators: period_data['Lowest Low(Kenkan-Sen)'] = period_data['Low'].rolling(kn_period).min() period_data['Highest High(Kenkan-Sen)'] = period_data['High'].rolling(kn_period).max() period_data['Kenkan-Sen'] = ( period_data['Highest High(Kenkan-Sen)'] + period_data['Lowest Low(Kenkan-Sen)']) / 2 period_data['Lowest Low(Kijun Sen)'] = period_data['Low'].rolling(kj_period).min() period_data['Highest High(Kijun Sen)'] = period_data['High'].rolling(kj_period).max() period_data['Kijun-Sen'] = ( period_data['Highest High(Kijun Sen)'] + period_data['Lowest Low(Kijun Sen)']) / 2 period_data['Chikou-Span'] = period_data[significant_value].shift(-kj_period) period_data['Senkou(Span A)'] = ((period_data['Kenkan-Sen'] + period_data['Kijun-Sen']) / 2).shift( kj_period) period_data['Lowest Low(52)'] = period_data['Low'].rolling(2 * kj_period).min() period_data['Highest High(52)'] = period_data['High'].rolling(2 * kj_period).max() period_data['Senkou(Span B)'] = ((period_data['Lowest Low(52)'] + period_data['Highest High(52)']) / 2 ).shift(kj_period) if 'macd' in indicators: period_data['Fast EMA'] = period_data[significant_value].rolling(fast_ema).mean() period_data['Slow EMA'] = period_data[significant_value].rolling(slow_ema).mean() period_data['MACD'] = period_data['Fast EMA'] - period_data['Slow EMA'] period_data['MACD Signal'] = period_data['MACD'].rolling(signal_line).mean() period_data['MACD Histogram'] = period_data['MACD'] - period_data['MACD Signal'] if 'pp' in indicators: period_data['Pivot point'] = (period_data['High'] + period_data['Low'] + period_data['Close']) / 3 period_data['First Resistance(R1)'] = (2 * period_data['Pivot point']) - period_data['Low'] period_data['First Support(S1)'] = (2 * period_data['Pivot point']) - period_data['High'] period_data['Second Resistance(R2)'] = period_data['Pivot point'] + period_data[ 'High'] - period_data['Low'] period_data['Second Support(S2)'] = period_data['Pivot point'] - (period_data['High'] - period_data['Low']) period_data['Third Resistance(R3)'] = period_data['High'] + 2 * ( period_data['Pivot point'] - period_data['Low']) period_data['Third Support(S3)'] = period_data['Low'] - 2 * ( period_data['High'] - period_data['Pivot point']) if 'adx' in indicators: period_data['High-Low Difference'] = period_data['High'] - period_data['Low'] period_data['High-Previous Close Difference'] = period_data['High'] - period_data['Close'].shift(1) period_data['Previous Close and Current Low Difference'] = period_data['Close'].shift(1) - period_data[ 'Low'] period_data['True Range(TR)'] = period_data[['High-Low Difference', 'High-Previous Close Difference', 'Previous Close and Current Low Difference']].dropna().max( axis=1) period_data['Average True Range(ATR)'] = period_data['True Range(TR)'].rolling(adx_period).mean() period_data['High-Previous High Difference'] = period_data['High'] - period_data['High'].shift(1) period_data['Previous Low-Low Difference'] = period_data['Low'].shift(1) - period_data['Low'] positive_condition = period_data[ 'High-Previous High Difference'] &gt; period_data['Previous Low-Low Difference'] period_data['Positive DX'] = period_data['High-Previous High Difference'][positive_condition] period_data['Positive DX'] = period_data['Positive DX'].fillna(0) negative_condition = period_data[ 'High-Previous High Difference'] &lt; period_data['Previous Low-Low Difference'] period_data['Negative DX'] = period_data['Previous Low-Low Difference'][negative_condition] period_data['Negative DX'] = period_data['Negative DX'].fillna(0) period_data['Smooth Positive DX'] = period_data['Positive DX'].rolling(adx_period).mean() period_data['Smooth Negative DX'] = period_data['Negative DX'].rolling(adx_period).mean() period_data['Positive Directional Movement Index(+DMI)'] = ( period_data['Smooth Positive DX'] / period_data['Average True Range(ATR)']) * 100 period_data['Negative Directional Movement Index(-DMI)'] = ( period_data['Smooth Negative DX'] / period_data['Average True Range(ATR)']) * 100 period_data['Directional Index(DX)'] = abs( period_data['Positive Directional Movement Index(+DMI)'] - period_data['Negative Directional Movement Index(-DMI)']) / ( period_data[['Positive Directional Movement Index(+DMI)', 'Negative Directional Movement Index(-DMI)']] ).sum(axis=1) * 100 period_data['Average Directional Index(ADX)'] = period_data['Directional Index(DX)'].rolling( adx_period).mean() return period_data if __name__ == '__main__': test_years = [year for year in range(2017, 2019)] x = FxSimulator('eurusd', test_years) x.plot_initial_data('li', 'D1', comparison_value='Close') plt.show() </code></pre> <p><code>pairs.txt</code>:</p> <pre><code>eurusd eurchf eurgbp eurjpy euraud usdcad usdchf usdjpy usdmxn gbpchf gbpjpy gbpusd audjpy audusd chfjpy nzdjpy nzdusd xauusd eurcad audcad cadjpy eurnzd grxeur nzdcad sgdjpy usdhkd usdnok usdtry xauaud audchf auxaud eurhuf eurpln frxeur hkxhkd nzdchf spxusd usdhuf usdpln usdzar xauchf zarjpy bcousd etxeur eurczk eursek gbpaud gbpnzd jpxjpy udxusd usdczk usdsek wtiusd xaueur audnzd cadchf eurdkk eurnok eurtry gbpcad nsxusd ukxgbp usddkk usdsgd xagusd xaugbp </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T20:22:46.633", "Id": "464060", "Score": "0", "body": "Please don't add things like [feedback needed] to a post's title. Most, if not all, 'unanswered' questions are looking for feedback, if everyone added stuff like that to titles we'd have nonsense like \"[python][feedback needed][begginer]\\[help][on-topic][performance]... my program\". Makes me think of YouTube tags. There are mechanisms in place to increase the visibility of a post, such as bounties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T20:42:15.113", "Id": "464063", "Score": "0", "body": "@Peilonrayz I'll be more appreciative if you look into any of my unanswered questions and maybe try to provide some feedback" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-05T20:45:25.623", "Id": "464064", "Score": "0", "body": "I'd appreciate it if someone asking me for help, where I get nothing in return, weren't sassy. I may not be able to point to the reason why, but I think I'll take a pass on your posts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-06T17:17:05.280", "Id": "464161", "Score": "0", "body": "To be clear I won't be looking at your posts." } ]
[ { "body": "<p>What about your </p>\n\n<blockquote>\n <p>program structure, and general suggestions for\n improvements/optimizations/features</p>\n</blockquote>\n\n<p>I found <em>True/False Evaluations</em> and <em>docString</em> weakness and suggest you follow some code style guide like <a href=\"http://google.github.io/styleguide/pyguide.html#214-truefalse-evaluations\" rel=\"nofollow noreferrer\">Google</a>. Also, you can call <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a> on each <code>.py</code> files, like I was execute on your forex_data_handler.py <code>pylint forex_data_handler.py</code>, and get the next output:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>************* Module forex_data_handler\nforex_data_handler.py:33:0: C0301: Line too long (115/100) (line-too-long)\nforex_data_handler.py:54:0: C0301: Line too long (108/100) (line-too-long)\nforex_data_handler.py:61:0: C0301: Line too long (117/100) (line-too-long)\nforex_data_handler.py:62:0: C0301: Line too long (114/100) (line-too-long)\nforex_data_handler.py:63:0: C0301: Line too long (120/100) (line-too-long)\nforex_data_handler.py:82:0: C0304: Final newline missing (missing-final-newline)\nforex_data_handler.py:1:0: C0114: Missing module docstring (missing-module-docstring)\nforex_data_handler.py:1:0: E0401: Unable to import 'histdata' (import-error)\nforex_data_handler.py:7:0: R0913: Too many arguments (6/5) (too-many-arguments)\nforex_data_handler.py:20:8: R1705: Unnecessary \"else\" after \"return\" (no-else-return)\nforex_data_handler.py:7:0: R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)\nforex_data_handler.py:33:0: R0913: Too many arguments (9/5) (too-many-arguments)\nforex_data_handler.py:33:0: R0914: Too many local variables (16/15) (too-many-locals)\nforex_data_handler.py:77:4: C0103: Constant name \"start_time\" doesn't conform to UPPER_CASE naming style (invalid-name)\nforex_data_handler.py:81:4: C0103: Constant name \"end_time\" doesn't conform to UPPER_CASE naming style (invalid-name)\nforex_data_handler.py:2:0: C0411: standard import \"from concurrent.futures import ThreadPoolExecutor, as_completed\" should be placed before \"from histdata import download_hist_data\" (wrong-import-order)\nforex_data_handler.py:3:0: C0411: standard import \"from time import perf_counter\" should be placed before \"from histdata import download_hist_data\" (wrong-import-order)\nforex_data_handler.py:4:0: C0411: standard import \"import os\" should be placed before \"from histdata import download_hist_data\" (wrong-import-order)\n\n------------------------------------------------------------------\nYour code has been rated at 4.76/10 (previous run: 8.81/10, -4.05)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T13:40:19.260", "Id": "459756", "Score": "0", "body": "Answers should provide more in-depth reviews. This answer is however acceptable, because it does provide a review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:09:21.487", "Id": "235005", "ParentId": "234985", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T04:55:35.677", "Id": "234985", "Score": "2", "Tags": [ "python", "python-3.x", "pandas", "data-visualization", "matplotlib" ], "Title": "Forex Simulator in Python using pandas and matplotlib" }
234985
<p>I have a simple application which requires the user to input details about students and their grades. I have two different classes <code>Student</code> and <code>Database</code>. The <code>Student</code> class contains info about students, such as, their names and grades:</p> <p><code>Student.h</code> file:</p> <pre><code>#pragma once #ifndef STUDENT_H #define STUDENT_H #include &lt;string&gt; class Student { private: std::string name; public: Student(std::string name); const std::string getName() const; ~Student(); }; #endif // !STUDENT_H </code></pre> <p><code>Student.cpp</code> file:</p> <pre><code>#include "student.h" #include &lt;string&gt; #include &lt;iostream&gt; Student::Student(std::string name) { this-&gt;name = name; } const std::string Student::getName() const { return this-&gt;name; } Student::~Student() { std::cout &lt;&lt; "Student destructor\n"; } </code></pre> <p><code>Database.h</code> file:</p> <pre><code>#pragma once #ifndef DATABASE_H #define DATABASE_H #include &lt;string&gt; #include "student.h" #include &lt;vector&gt; class StudentDatabase { private: std::vector&lt;Student*&gt; student_list; public: void add_student(Student* stud_obj); ~StudentDatabase(); }; #endif // !DATABASE_H </code></pre> <p><code>Database.cpp</code> file:</p> <pre><code>#include "database.h" #include "student.h" #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;vector&gt; void StudentDatabase::add_student(Student* stud_obj) { std::cout &lt;&lt; "ADD STUDENT METHOD\n"; StudentDatabase::student_list.push_back(stud_obj); } StudentDatabase::~StudentDatabase() { std::cout &lt;&lt; "Database destructor\n"; std::vector&lt;Student*&gt;::iterator iter; for (iter = student_list.begin(); iter != student_list.end(); iter++) { delete* iter; } } </code></pre> <p><code>Main.cpp</code> file:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include "database.h" #include "student.h" int main() { std::string input; std::string name; StudentDatabase* database = new StudentDatabase(); for (;;) { std::cout &lt;&lt; "0: Add student \n"; std::cout &lt;&lt; "Enter a number (or q to quit) and press return... \n"; std::cin &gt;&gt; input; std::cin.ignore(); if (input == "q") { break; } else if (input == "0") { std::cout &lt;&lt; "Enter student's first name: "; std::getline(std::cin, name); Student* student_obj = new Student(name, surname, student_number, grade); database-&gt;add_student(student_obj); } } delete database; return 0; } </code></pre> <p>My question is: am I correctly deallocating memory for <code>Student</code>s from <code>~StudentDatabase()</code>?</p> <p>I know smart pointers are more appropriate but I want to make sure I understand raw pointers properly.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T06:29:08.263", "Id": "459710", "Score": "0", "body": "Welcome to Code Review! 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)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T11:18:25.280", "Id": "459733", "Score": "0", "body": "You should use smart pointers on your code in order to avoid issues with the memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T12:04:32.790", "Id": "459740", "Score": "2", "body": "Why are you even dynamically allocating objects in the first place!" } ]
[ { "body": "<p>You can easily check this for yourself. Just define a variable <code>std::size_t activeStudents = 0</code> in <code>Student.cpp</code>, which you increase in the <code>Student</code> constructor and decrease in the destructor. If at the end of <code>main</code> this variable has the value 0, you're fine.</p>\n\n<p>Same for the <code>StudentDatabase</code>.</p>\n\n<p>This approach is only appropriate as long as you are learning about memory allocation and resource management. As soon as you think you undersand these topics, you should use an automatic tool like Valgrind to do the boring work for you.</p>\n\n<p>By the way, your code doesn't compile. The <code>Student</code> constructor only accepts a single parameter, yet in <code>main</code> you pass 4 arguments:</p>\n\n<pre><code>new Student(name, surname, student_number, grade);\n</code></pre>\n\n<p>Next time you should better create a working example in your IDE, make sure that it compiles and then copy it directly to the Code Review question, without any furher edits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T06:23:25.807", "Id": "459709", "Score": "0", "body": "I just tried it and it deallocates properly. I have also edited the part of the code which was preventing it from compiling. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T00:43:49.447", "Id": "459823", "Score": "1", "body": "Beware of implicitly declared ctors though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-07T00:48:36.860", "Id": "460210", "Score": "0", "body": "you should prefer something like libasan over a user implemented reference count" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T06:00:43.217", "Id": "234990", "ParentId": "234988", "Score": "0" } }, { "body": "<p>You don't need to use <code>new</code> everywhere. Inside your main function, the <code>StudentDatabase</code> could very well reside on the stack so you don't need to delete it yourself.</p>\n\n<p>One of the issues with how <code>StudentDatabase</code> is written now is ownership semantics. Once a student pointer is added to the database, the database asumes ownership upon it and deletes it in the destructor. What if the same student pointer were to be added to multiple databases, or used after the database is deleted?</p>\n\n<p>Smart pointers help prevent such errors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T11:29:38.023", "Id": "235001", "ParentId": "234988", "Score": "3" } }, { "body": "<p>You should indeed use smart pointers. Consider what happens if you copy your database, which only copies the pointers to the students, then you delete the first database, which deletes the students and leaves you with dangling pointers. This is just bad design.</p>\n\n<p>Also: <code>delete* iter</code> is typographically weird, even though the interpretation by the compiler is correct. The star belongs with the <code>iter</code>: you dereference it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:38:50.647", "Id": "235033", "ParentId": "234988", "Score": "1" } }, { "body": "<h2>Overall</h2>\n<p>You look like a Java programmer that is coming over to C++.</p>\n<p>This:</p>\n<pre><code>{\n StudentDatabase* database = new StudentDatabase();\n ... STUFF\n delete database;\n}\n</code></pre>\n<p>Is very bad practice.</p>\n<ol>\n<li>There is no need to dynamically allocate this object (it can easily be an automatic variable thus creation and destruction is done automatically).</li>\n<li>You don't guarantee that the <code>delete</code> is called.</li>\n</ol>\n<p>You only need to dynamically allocate an object if the object lives past beyond the code that created it (here you don't). Even when this is needed you should be using smart pointers (probably <code>std::unique_ptr</code>) to correctly manage the lifespan of the dynamically created object.</p>\n<p>Much easier to do:</p>\n<pre><code>{\n StudentDatabase database{};\n ... STUFF\n}\n</code></pre>\n<hr />\n<p>You have not learned the rule of three. This is one of the most important concepts in C++. Until you have learned this rule you can not safely use pointers in the language.</p>\n<h2>Code Review</h2>\n<p>This is fine for very small programs.</p>\n<pre><code>#ifndef STUDENT_H\n#define STUDENT_H\n</code></pre>\n<p>But you should make it a habit to make these longer and more unique. Personally I always use namespaces (that I know is unique to me) and add this to the include guard. A lot of IDE allow you to generate these guards with GUID.</p>\n<hr />\n<p>When passing object to functions it is usually a good idea to pass them by reference to avoid a copy. To prevent accidental modification of the parameter you should pass by const reference.</p>\n<pre><code> Student(std::string name);\n\n // Here I would change to:\n\n Student(std::string const&amp; name);\n</code></pre>\n<hr />\n<p>The same applies to returning values (though there is more nuance to this, but as a beginner a good rule of thumb is return by const reference). Returning by reference (const if you don't want it to be changed). This will prevent the object being copied on returned. You then let the user of the function decide if they want a copy or to simply use the reference.</p>\n<pre><code> const std::string getName() const;\n\n // Here I would change to:\n\n std::string const&amp; getName() const;\n</code></pre>\n<hr />\n<p>Prefer to use the initializer list in the constructor rather than code in the constructor.</p>\n<pre><code>Student::Student(std::string name) {\n this-&gt;name = name;\n}\n</code></pre>\n<p>All member variables of a class are constructed before the code block of the constructor is executed. Thus in your case above you are constructing the object <code>name</code> then you are calling the <code>operator=</code> for the object <code>name</code> thus affectively initializing the variable twice. It works but this can potentially be inefficient if the constructor did a lot of work. Thus prefer to use the initializer list to prevent inefficiencies.</p>\n<pre><code>Student::Student(std::string const&amp; name)\n : name(name)\n{}\n</code></pre>\n<hr />\n<p>Also allow for the potential to use <strong>move semantics</strong>. This allows your object to take the content of the its parameters and avoid an extra copy.</p>\n<pre><code>Student::Student(std::string&amp;&amp; name) // Note the double &amp;&amp;\n : name(std::move(name)) // Move the name to this-&gt;name\n{}\n</code></pre>\n<hr />\n<p>Prefer not to use <code>this-&gt;</code>.</p>\n<p>This is actually an important one (in my opinion). This actually causes more bugs than you think. The only reason to use <code>this-&gt;name</code> rather than <code>name</code> directly is because you have <strong>shadowed</strong> variables and you need to disambiguate the two usages.</p>\n<p>The problem here is that when you make a mistake (and you will) the compiler can not detect the error.</p>\n<p>So the better approach is to use better variable names so that you know from context the correct usage. Then you can turn on your compiler warnings and get the compiler to warn you when you do have shadowing so that you never have shadowed variables and thus do not need to disambiguate two similar named variables with <code>this-&gt;</code>.</p>\n<hr />\n<p>I dislike this:</p>\n<pre><code>#include &lt;string&gt;\n#include &quot;student.h&quot;\n#include &lt;vector&gt;\n</code></pre>\n<p>Technically nothing wrong. But I order my includes in a specific order. Most specific to least specific.</p>\n<pre><code>#include &quot;ThisClass.h&quot;\n#include &quot;OtherClassesInThisLibrary.h&quot;\n---\n#include &quot;Other Local Libraries I Use .h&quot;\n#include &lt;Other Gloval Libraries I Use .h&gt;\n---\n#include &lt;C++ header Files&gt;\n#include &lt;C header Files&gt;\n</code></pre>\n<p>Now the reason I do it this way is to make sure I don't hide errors around missing #include statements in my local files.</p>\n<hr />\n<p>No reason to keep a vector of pointers.</p>\n<pre><code> std::vector&lt;Student*&gt; student_list;\n</code></pre>\n<p>As you are not using polymorphism there is no need to store pointers. Simply store the object.</p>\n<pre><code> std::vector&lt;Student&gt; student_list;\n</code></pre>\n<p>Ahh. I hear you say that it does not matter that much as I have fixed the destructor to correctly release the student objects. And yes you have. But you have forgotten to implement the rule of three. Which will make this code brittle and likely to cause errors.</p>\n<p>Rule of 3: If your object contains an &quot;owned&quot; pointer then the compiler version of the constructors and assignment operators do not work correctly and thus you need to explicitly define these methods.</p>\n<p>In your case you have a vector full of owned pointers (I know you own then because you try and delete them in the destructor).</p>\n<p>How does this break your code I hear you ask:</p>\n<pre><code>{\n StudentDatabase db1(\n\n db1.add_student(new Student(&quot;John&quot;));\n\n StudentDatabase db2(db1);\n}\n// Problem here.\n// The &quot;John&quot; Student is deleted twice as both databases has a copy\n// of the student.\n</code></pre>\n<p>But I will never copy the database (I hear you say). That's fine. Implement the rule of three by deleting the copy constructor and copy assignment operator and then nobody will ever have an accidental issue with your class.</p>\n<p>Or:</p>\n<p>Simply have a vector of Student (rather than vector of Student pointer). Alternatively If you want to share the object. Then we are back to using smart pointers.</p>\n<hr />\n<p>This looks very weird.</p>\n<pre><code> StudentDatabase::student_list.push_back(stud_obj);\n</code></pre>\n<p>This looks like you are accessing a class member (rather than a local object member). Looking back at your class definition it's a member of the local object.</p>\n<pre><code> student_list.push_back(stud_obj);\n</code></pre>\n<hr />\n<p>Sure this is fine.</p>\n<pre><code> for (iter = student_list.begin(); iter != student_list.end(); iter++) {\n delete* iter;\n }\n</code></pre>\n<p>But. If you look at other storage types (containers/arrays) they all destroy their objects in reverse order. So it may be holding to that standard and deleting them from the back rather than the front.</p>\n<p>OR. You don't care about the order. Then we have a better for loop to achieve this:</p>\n<pre><code> for (auto&amp; obj: student_list) {\n delete obj;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T11:37:59.833", "Id": "459869", "Score": "0", "body": "Good analysis. But: `StudentDatabase::student_list.push_back(stud_obj);` is legitimate: if you are in a derived class of `StudentDatabase` this is the syntax for getting the method of the base class. It's useful in case the derived class overrides the method. Not that that's the case here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-05T04:18:10.057", "Id": "459953", "Score": "0", "body": "@VictorEijkhout Yes it is valid. But that was not my point. It just looks weird. Looking weird is not a a good thing for maintenance. In this situation it is not required so best avoided to make the code look more standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T06:06:32.757", "Id": "460069", "Score": "0", "body": "Great in-depth answer. What exactly does the double `&&` in the `Student` constructor's parameter list do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T08:33:25.020", "Id": "460084", "Score": "1", "body": "@mhmrhiman The double `&&` indicates to the compiler that the method can be called with an r-value reference. This is used to indicate parameters that can be moved. i.e. It is the way to implement move semantics for your class. If you don't \"move\" the object you will need to \"copy\" the object." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T01:10:45.443", "Id": "235050", "ParentId": "234988", "Score": "2" } } ]
{ "AcceptedAnswerId": "235050", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T05:28:03.403", "Id": "234988", "Score": "2", "Tags": [ "c++", "object-oriented", "memory-management", "pointers" ], "Title": "I'm deallocating objects created but I'm unsure whether my code is leaking memory or not" }
234988
<p>[I made a little web-scraper that downloads the source html files as well. Now for the sake of saving storage space i wrote a small function to delete quite a bit of stuff in the html file (specific id's, classes and meta information as well as footers, headers, and links). The function takes the <code>html tree</code> as input and outputs the <em>shrunk</em> html to be saved on the machine.</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup from bs4 import Comment tags = ['script', 'noscript', 'footer', 'header'] div_classes = [&quot;head no-print&quot;, &quot;col-md-6&quot;, &quot;col-md-6 less-padding-left no-print&quot;, 'col-md-4 col-md-pull-8 less-padding-left no-print', &quot;col-sm-4 less-padding-left sidebar no-print hidden-xs&quot;,] div_ids = ['navwrapper', 'citations'] links = ['stylesheet', 'text/css', 'canonical', 'alternate'] meta = ['metasummary', 'viewport', 'og_title', 'og_description'] def reduce_filesize(webcontent_string, output_file): soup = BeautifulSoup(webcontent_string, features='lxml') # remove full tags for i in tags: for element in soup.find_all(i): element.decompose() # remove div's based on id for i in div_ids: for element in soup.find_all('div', {'id': i}): element.decompose() # remove div's based on class for i in div_classes: for element in soup.find_all('div', {'class': i}): element.decompose() # remove stylesheets and css for i in links: for element in soup.find_all('link', {'rel': i}): element.decompose() # removing meta text for i in meta: for element in soup.find_all('meta', {'id': i}): element.decompose() # remove comments comments = soup.find_all(string=lambda text: isinstance(text, Comment)) for c in comments: c.extract() with open(output_file, &quot;w&quot;, encoding='utf-8') as file: file.write(str(soup)) file.close </code></pre> <p>Now what's bugging me is the repetition of the if statements with only slight changes each time. I've tried handling this by creating a <code>dict</code> of all the list and use that but couldn't get it to work. To make it faster I tried using list comprehension for the inner loops instead which works just fine but I'm certain it can be improved further.</p> <p>Thank you for all input and advice!</p> <p><a href="https://sciencedaily.com/releases/2020/01/200102143429.htm" rel="nofollow noreferrer">Here a link to a page to be shrunk</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T08:30:03.953", "Id": "459720", "Score": "1", "body": "Can you share a testable html file with all implied \"stuff\" to be deleted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T08:36:34.783", "Id": "459723", "Score": "0", "body": "@RomanPerekhrest I added a link, hope that works for you" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T06:43:26.500", "Id": "234991", "Score": "1", "Tags": [ "python", "python-3.x", "html", "web-scraping", "beautifulsoup" ], "Title": "bs4 HTML cleaner function with repetitive nested if clauses," }
234991
<p>I am doing a practice project to create a calculator with OOP principles. Below is my CalculatorApp that communicates with Calculator(to calc integers) and StringParser(to tokenize input). For CalculatorApp to work, strict rules need to follow. For example, the input must use "add" not "plus" and "(" not any other kind. Therefore I have so many hardcoded variables in the class. Is it a bad design? Am I doing too much in <code>process</code> and is creating variables (i.e <code>wordToSign_map</code>) on the fly bad practice? Should I refactor all the variables to another class? This is for a job so I need to make sure I do my best. Any feedback will be greatly appreciated.</p> <pre><code>public class CalculatorApp { String input; Calculator calculator; int result; final String open_parentheses = "("; final String close_parentheses = ")"; final String delimiter = " "; public CalculatorApp(Calculator calculator){ this.calculator = calculator; } public CalculatorApp input (String input){ this.input = input; return this; } public CalculatorApp process (){ if(!isExpression()){ result=Integer.parseInt(input); return this; } Map&lt;String, String&gt; wordToSign_map = new HashMap&lt;&gt;(); wordToSign_map.put("add", "+"); wordToSign_map.put("multiply", "*"); Map&lt;String, String&gt; parentheses_spacing_map = new HashMap&lt;&gt;(); parentheses_spacing_map.put(open_parentheses, open_parentheses+delimiter); parentheses_spacing_map.put(close_parentheses, delimiter+close_parentheses); StringParser stringParser = new StringParser(input, wordToSign_map, parentheses_spacing_map, delimiter); String[] parsedString = stringParser.TokenizeExpression(); Set&lt;String&gt; operatorSigns = new HashSet&lt;&gt;(); operatorSigns.addAll(wordToSign_map.values()); try { Tree tree = new Tree(); tree.constructATree(parsedString, operatorSigns, open_parentheses, close_parentheses); result = evaluateExpressionTree(tree.getRoot()); } catch (EmptyStackException e) { System.out.println("Invalid input"); throw e; } return this; } public int output (){ return result; } private boolean isExpression(){ return input.contains(open_parentheses) &amp;&amp; input.contains(close_parentheses); } } </code></pre> <p>This is my Tree class. It takes a string list and creates nodes and children around the brackets and +,* signs. That's why the string has to be exactly one-spaced and can't contain any unknown signs. Should I leave the comments there? Is it too messy and hard to read? Is passing too many args in the method call bad, should I instead pass them in the constructor and hold them as fields?</p> <pre><code> public class Tree { Node root; public Node getRoot() { return root; } public void constructATree (String[] parsedString, Set&lt;String&gt; operatorSigns, String startExp, String endExp) throws EmptyStackException { Stack&lt;Node&gt; localRoot = new Stack&lt;&gt;(); for (int i = 0; i &lt; parsedString.length; i++) { if(parsedString[i].equals(startExp)) { // ignore ( continue; } if(operatorSigns.contains(parsedString[i])){ // operator for expression localRoot.push(new Node(parsedString[i], true)); } else if(parsedString[i].equals(endExp)) // end of an expression { Node tempNode = localRoot.pop(); // get the last node if(localRoot.empty()){ this.root = tempNode; // if there is only one expression return it as the root of the tree } else { Node tail = localRoot.peek(); // tail.addChild(tempNode); // add the children from last node to trailing node } } else { Node tempNode = localRoot.pop(); tempNode.addChild(new Node(parsedString[i], false)); // add values to children of operator node localRoot.push(tempNode); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:49:29.213", "Id": "459717", "Score": "3", "body": "To comply with the rules of this site, please, change the title so it describes what your code is doing. Most classes interact with other classes, the current title is of very little value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T09:18:18.550", "Id": "459725", "Score": "1", "body": "Shall we guess about `Node`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:08:48.240", "Id": "459782", "Score": "0", "body": "@greybeard Node class is a simple object that holds data(string), isOperator(boolean) and a list of children nodes. It has getters and setters methods for the fields" } ]
[ { "body": "<pre><code>app.input(input);\napp.process();\nvar result = app.output();\n</code></pre>\n\n<p>This is a bad practice. Every function/method has means of passing input, it has body and it has return value. Setting the input to class field, then calling method without arguments to process the set input, then storing result to another class field, then calling another method to retrive the result is utterly complicated, confusing and error prone.</p>\n\n<p>You can forget to call <code>input</code> and call <code>process</code> directly which will fail or process the previous input.</p>\n\n<p>You can forget to call <code>process</code> and retrieve an unexpected null result or retrieve the result of previous process.</p>\n\n<p>You can have momory occupied longer then necesary even if you don't care for the result anymore.</p>\n\n<p>Why not use all the channels of a function?</p>\n\n<pre><code>var result = app.process(input);\n</code></pre>\n\n<p>Now imagine the result has been printed for example and it is no longer needed. In your implementation the memory is still siezed (because app object holds reference to it) until the app object is destroyed. In my implementation the momory is released (once the scope of the variable is left) regardless of the app object being destroyed or not.</p>\n\n<h1>Returning <code>this</code></h1>\n\n<p>Be very thouthful when returning <code>this</code>. You hardly ever need to return <code>this</code>. It only leads to thoughts about saving outputs to the class fields, because it feels like return value is already siezed by <code>this</code> and thus the real result must be provided through a different channel. But true is that <code>this</code> is always available to the caller (because they know the reference to the object) and so if the return value channel can be used for something more meaningful, you should do it. And even if there is nothing meaningful to return, you should consider returning void, instead of <code>this</code>.</p>\n\n<h1>Comments</h1>\n\n<p>if your code needs a lot of comments to be understandable, it probably lacks some structure (split to more methods maybe...). But maybe some of the comments are not necesary, like here:</p>\n\n<pre><code>Node tempNode = localRoot.pop(); // get the last node\n</code></pre>\n\n<p>I dont think that comment tells me anything I couldn't infer from the code itself...</p>\n\n<h1>Passing too many arguments</h1>\n\n<p>That's disputable if it's bad to pass a lot of arguments. If they are needed, then they have to be there. If they repeat on more places a simple data structure could be introduced to condense them together.</p>\n\n<p>Passing them as constructor arguments versus passing them as method arguments is not a good question. They have different purpose. The method should accept all arguments that are available to the caller. Constructor should accept all arguments that are only known to the creator of the object.</p>\n\n<p>If some arguments known to the caller are to be passed through constructor, the caller of the method must also be the creator of the object and that's often not true. In fact, if you maintain single responsibility of all classes, it will never be true.</p>\n\n<p>Class fileds are like configuration of the object - how it should behave, what it can offer. Method arguments are more like a specification of what the caller wants.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:11:32.640", "Id": "459784", "Score": "0", "body": "thanks for your detailed feedback. I was reluctant to use input.process.output approach but I thought it would make it clear what my App is doing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T08:08:59.670", "Id": "234994", "ParentId": "234992", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T07:19:42.777", "Id": "234992", "Score": "0", "Tags": [ "java", "object-oriented" ], "Title": "Design practices for an app that interacts with other classes" }
234992
<p>I am trying to solve this question: <a href="https://open.kattis.com/problems/fenwick" rel="nofollow noreferrer">https://open.kattis.com/problems/fenwick</a></p> <blockquote> <p>A Fenwick Tree (also known as a Binary Indexed Tree) is a data structure on an array which enables fast ((log)) updates and prefix sum queries on the underlying data.</p> <p>For this problem, implement a Fenwick Tree to support operations of two types: (a) increment an element in the array or (b) query the prefix sum of a portion of the array.</p> <p>Input The first line of input contains two integers , , where 1≤≤5000000 is the length of the array and 0≤≤5000000 is the number of operations. Then follow lines giving the operations. There are two types of operations:</p> <p>“+ ” indicates that [] is incremented by , where 0≤&lt; and −10^9≤≤10^9 (both are integers)</p> <p>“? ” is a query for the value of [0]+[1]+…+[−1], where 0≤≤ (for =0 this is interpreted as an empty sum)</p> <p>You should assume that every array entry is initially 0.</p> </blockquote> <p>My implementation:</p> <pre><code>class SegmentTree: def __init__(self, n): self.nums = [0] * n self.tree = {} self._build() def _build(self): def build(l, r, index): if l == r: self.tree[index] = self.nums[l] else: mid = (l+r)//2 build(l, mid, index*2) build(mid+1, r, index*2+1) self.tree[index] = self.tree[index*2] + self.tree[index*2+1] build(0, len(self.nums)-1, 1) def get_sum(self, i, j): def get_sum(left_boundary, right_boundary, index, i, j): if j &lt; i: return 0 if left_boundary == right_boundary: return self.tree[index] if left_boundary == i and right_boundary == j: return self.tree[index] else: mid = (left_boundary + right_boundary)//2 left_sum = get_sum(left_boundary, mid, index*2, i, min(j, mid)) right_sum = get_sum(mid+1, right_boundary, index*2+1, max(i, mid+1), j) return left_sum + right_sum return get_sum(0, len(self.nums)-1, 1, i, j) def update(self, pos, num): def update(l, r, index): if l == r and l == pos: self.tree[index] = num else: mid = (l+r)//2 if pos &lt;= mid: update(l, mid, index*2) else: update(mid+1, r, index*2+1) self.tree[index] = self.tree[index*2] + self.tree[index*2+1] update(0, len(self.nums)-1, 1) def main(): n, q = map(int, input().split()) nums = [0] * n s = SegmentTree(n) def update(ops): plus, i, inc = ops.split() i = int(i) inc = int(inc) s.nums[i] += inc s.update(i, s.nums[i]) def prefix_sum(ops): q, j = ops.split() j = int(j) ans = s.get_sum(0, j-1) print(ans) for _ in range(q): ops = input() if len(ops.split()) == 3: update(ops) else: prefix_sum(ops) if __name__ == "__main__": main() </code></pre> <p>This sadly times out. How do I optimize it to run faster?</p>
[]
[ { "body": "<p>Segment trees and Fenwick trees are usually implemented as <a href=\"https://www.wisdomjobs.com/e-university/data-structures-tutorial-290/implicit-data-structure-7118.html\" rel=\"nofollow noreferrer\">implicit\ndata\nstructures</a>. That\nis, as an array with the tree structure implicitly given by the array\nindices. Your code instead stores the tree as a Python dictionary\nwhich is very inefficient.</p>\n\n<p>The second problem with your segment tree is that you are using\nrecursion. Refer to this <a href=\"https://codeforces.com/blog/entry/18051\" rel=\"nofollow noreferrer\">sample\ncode</a> for how to implement\niterative versions of <code>get_sum</code> and <code>update</code>.</p>\n\n<p>The third problem is that you have implemented a Segment tree and not\na Fenwick tree (aka Binary indexed tree). For this problem, they are\nslightly more efficient than Segment trees.</p>\n\n<p>The fourth problem is, sadly, Python. :) Number crunching code and\ntight loops just doesn't run as fast in Python as they do in\nlower-level languages. Plus, in this problem, IO and number parsing is\ndominating.</p>\n\n<p>Here is a Python solution using a Fenwick tree:</p>\n\n<pre><code>n, q = map(int, input().split())\n# One extra element so that we can use 1-based indexing.\nnums = [0] * (n + 1)\nfor _ in range(q):\n parts = input().split()\n if len(parts) == 3:\n _, i, inc = parts[0], int(parts[1]) + 1, int(parts[2])\n while i &lt;= n:\n nums[i] += inc\n i += i &amp; (-i)\n else:\n _, i = parts[0], int(parts[1])\n tot = 0\n while i &gt; 0:\n tot += nums[i]\n i -= i &amp; (-i)\n print(tot)\n</code></pre>\n\n<p>If you port it to a low-level language it will be very fast.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T08:36:19.703", "Id": "235060", "ParentId": "234996", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T08:57:30.393", "Id": "234996", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x", "time-limit-exceeded", "tree" ], "Title": "Python Fenwick Tree" }
234996
<p>I had to write a code (as an exercise) that receives a 2D row wise and col wise sorted array and an element, and return true is the element exists in the array.</p> <p>The first thing that came to mind when i heard "sorted" is binary search, but than i realized that the last element in each row isn't necessarily smaller than the first one in the next line.</p> <p>So, i figured out that the best complexity will be O(n), and wrote the following code:</p> <pre><code> public static boolean findN(int[][] a, int x) { if (a.length == 0 || a[0].length == 0 || x &gt; a[a.length - 1][a[0].length - 1] || x &lt; a[0][0]) { return false; } int LastRow = a.length - 1, Lastcol = a[0].length - 1, row = 0, col = 0; while (row &lt;= LastRow) { if (a[row][col] == x) { return true; } else if (col &lt; Lastcol) { col++; } else { col = 0; row++; } } return false; } </code></pre> <blockquote> <blockquote> <p>array example: </p> </blockquote> </blockquote> <pre><code>arr = {{1,2,7,30}, {2,4,18,50}, {3,6,19,90}, {4,7,20,91}} </code></pre> <ul> <li>After realizing that the best complexity will be O(n), I googled this problem so I'm almost certain that I'm right (although some people are claiming that they can do it in O(log(n))), but am I really?</li> <li>Any other thoughts and improvements are welcomed, <strong>thank you all in advance!</strong></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T15:46:08.577", "Id": "459770", "Score": "0", "body": "Find first row that has first element <= X. Find last row that has last element >= X. Execute binary search for rows in between." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T18:44:55.830", "Id": "459790", "Score": "0", "body": "Lat's take X=17.\nFirst row that has first element <=17: [0], last row that has last element >=17: [3]. If ill run binary search for all of this rows the complexity will be O(nlogn)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:09:17.620", "Id": "459797", "Score": "0", "body": "Your array example is misleading: The third column 7, 18, 16, 17 is not increasing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:32:34.763", "Id": "459806", "Score": "0", "body": "Edited, same for 18 now." } ]
[ { "body": "<p>Your function does a <em>linear search</em> over all elements of the nested array, until the given number is found, or all elements have been visited. The complexity is <span class=\"math-container\">\\$ O(mn) \\$</span> for an <span class=\"math-container\">\\$ m \\$</span>-by-<span class=\"math-container\">\\$n \\$</span> matrix. For a square <span class=\"math-container\">\\$ n \\$</span>-by-<span class=\"math-container\">\\$n \\$</span> matrix that makes <span class=\"math-container\">\\$ O(n^2) \\$</span>, and not <span class=\"math-container\">\\$ O(n) \\$</span> as you claimed.</p>\n\n<p>This can be improved, but let's first do a</p>\n\n<h3>Review of your current implementation</h3>\n\n<p>The Java <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html\" rel=\"nofollow noreferrer\">naming convention</a> for variables is “lower camel case,” e.g. <code>lastRow</code>, <code>lastCol</code> instead of <code>LastRow</code>, <code>LastCol</code>.</p>\n\n<p>The while-loop is a nested loop over all rows and columns in disguise, and can be more clearly written as nested for-loops:</p>\n\n<pre><code>int numRows = a.length;\nint numCols = a[0].length;\n\nfor (int row = 0; row &lt; numRows; row++) {\n for (int col = 0; col &lt; numCols; col++) {\n if (a[row][col] == x) {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>This also restricts the scope of <code>row</code> and <code>col</code> to the minimum needed.</p>\n\n<h3>A better algorithm</h3>\n\n<p>Your implementation does not take advantage of the fact that the numbers are sorted in each row and in each column. A better algorithm is described in <a href=\"https://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-matrix/\" rel=\"nofollow noreferrer\">Search in a row wise and column wise sorted matrix</a> on GeeksForGeeks:</p>\n\n<ol>\n<li>Start with top right element.</li>\n<li>Loop: compare this element e with x\n\n<ul>\n<li>if e = x, then return position of e, since we found x in the given matrix.</li>\n<li>if e > x then move left to check elements smaller than e (if out of bound of matrix, then break and return false)</li>\n<li>if e &lt; x then move below to check elements greater than e (if out of bound of matrix, then break and return false)</li>\n</ul></li>\n<li>repeat until you find the element, or return false</li>\n</ol>\n\n<p>I do not want to deprive you of the satisfaction of implementing it yourself. Just note that any element is now found after at most <span class=\"math-container\">\\$ m+n \\$</span> steps, so the complexity is reduced from <span class=\"math-container\">\\$ O(mn) \\$</span> to <span class=\"math-container\">\\$ O(m+n) \\$</span> for an <span class=\"math-container\">\\$ m \\$</span>-by-<span class=\"math-container\">\\$n \\$</span> matrix.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:19:00.847", "Id": "459799", "Score": "0", "body": "First of all, thank you for the naming convention correction, i totally missed it.\nBut about the rest, I had do disagree:\nIf ill change the loop the way you suggested, the complexity will be O(n^2) and I had to do it at the best complexity possible.\nFor the geeksforgeeks algorithm - I wrote something similar before, and than i realized that >>the last element in each row isn't necessarily smaller than the first one in the next line.\nIf you'll run this code, with my example array and 17 as element, you'll see this isn't working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:20:19.550", "Id": "459800", "Score": "1", "body": "@RedYoel: It does not work for 17 because the third column in your example is not sorted in increasing order (as I remarked in a comment to your question)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:22:25.563", "Id": "459802", "Score": "1", "body": "@RedYoel: And there is no difference between your while-loop and the nested for-loops: Both iterate linearly over *all* array elements (until the number is found, or the end of the array reached)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:30:11.367", "Id": "459804", "Score": "0", "body": "Really sorry for the mistake, I didn't uploaded the question from my computer and it made a mess, corrected the example.\nI understand that there is no difference between my while and the nested for loops, but mine goes for O(n), and the nested for loops goes for O(n^2) so it's better to do it on my way, no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:33:42.583", "Id": "459807", "Score": "1", "body": "@RedYoel: If n denotes the dimension (i.e. the row/column count) then your while loop is O(n^2) as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:40:23.237", "Id": "459808", "Score": "0", "body": "I was sure that because mine uses only one loop, this fill be O(n).I just started to learn about complexity and you helped a lot, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T20:40:51.937", "Id": "459810", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/102858/discussion-between-martin-r-and-redyoel)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T10:47:59.437", "Id": "459858", "Score": "0", "body": "The question did not specify that the array is square (N x N). It's just two dimensional. It could be N one element rows or one N element row or something in between. Did the original question fail to disclose all preconditions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-04T10:59:06.293", "Id": "459862", "Score": "0", "body": "@TorbenPutkonen: That's true. I have tried to clarify it in my answer now." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T19:57:32.137", "Id": "235038", "ParentId": "234997", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-03T09:40:08.617", "Id": "234997", "Score": "3", "Tags": [ "java", "array", "complexity" ], "Title": "Searching an element in a 2D sorted array" }
234997