body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have written a simple expect script to tell me if a passwordless connection is set up.</p> <pre><code>#!/usr/bin/expect -f if {[llength $argv] &lt; 2} { puts &quot;usage: test-nopass user server&quot; exit 1 } set user [lindex $argv 0] set server [lindex $argv 1] set pwd_prompt &quot;*assword:&quot; set prompt &quot;*$ &quot; set rc 0 log_user 0 spawn ssh $user@$server expect { &quot;$pwd_prompt&quot; { exit 1 } eof { exit 2 } timeout { exit 3 } &quot;$prompt&quot; { send &quot;hostname\r&quot; expect { &quot;*$server*&quot; { exit 0 } eof { exit 4 } timeout { exit 5 } } } } log_user 1 exit $rc <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>A couple of notes:</p>\n<ul>\n<li><p><code>expect</code> is an extension of Tcl, so you can use any Tcl command: <a href=\"http://www.tcl-lang.org/man/tcl8.6/TclCmd/contents.htm\" rel=\"nofollow noreferrer\">http://www.tcl-lang.org/man/tcl8.6/TclCmd/contents.htm</a></p>\n<ul>\n<li>specifically, you could write\n<pre><code>lassign $argv user server\n</code></pre>\nwhich is arguably a bit less readable, but is only one command.</li>\n</ul>\n</li>\n<li><p>You can speed up the timeouts: the default is 10 seconds, and you probably don't want to wait for 20 seconds to get the final exit status:</p>\n<pre><code>set timeout 1 ;# in seconds\n</code></pre>\n</li>\n<li><p>you never reset the <code>rc</code> variable, and the default exit status is zero already, so you can remove <code>set rc 0</code> and <code>exit $rc</code></p>\n</li>\n<li><p>expect is not bash: you don't need to quote all the variables.</p>\n</li>\n<li><p>you don't need to reset <code>log_user</code> just before exiting the script.</p>\n</li>\n<li><p>expect code written in this style can get pretty deeply nested: The last pattern in an <code>expect</code> command does not <em>need</em> an action block</p>\n<pre><code>expect {\n $pwd_prompt { exit 1 }\n eof { exit 2 }\n timeout { exit 3 }\n $prompt \n}\nsend &quot;hostname\\r&quot;\nexpect {\n *$server* { exit 0 }\n eof { exit 4 }\n timeout { exit 5 }\n}\n</code></pre>\n<p>If <code>$prompt</code> is seen, then that <code>expect</code> command ends, and the script continues with <code>send</code></p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T19:43:27.873", "Id": "247624", "ParentId": "247622", "Score": "2" } } ]
{ "AcceptedAnswerId": "247624", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T19:17:05.493", "Id": "247622", "Score": "2", "Tags": [ "beginner", "shell", "tcl", "expect" ], "Title": "Expect script that tests if a passwordless connection is setup" }
247622
<p>I started reading Robert Martin's <em>Clean Code</em>. I'm trying to &quot;translate&quot; all his examples into Python, so I can understand them better since my domain on Python is greater than on Java. Please take a look at the following:</p> <p><strong>Java original code of the book</strong></p> <pre class="lang-java prettyprint-override"><code>public class GuessStatisticsMessage { private String number; private String verb; private String pluralModifier; public String make(char candidate, int count) { createPluralDependentMessageParts(count); return String.format( &quot;There %s %s %s%s&quot;, verb, number, candidate, pluralModifier); } private void createPluralDependentMessageParts(int count) { if (count == 0) { thereAreNoLetters(); } else if (count == 1) { thereIsOneLetter(); } else { thereAreManyLetters(count); } } private void thereAreManyLetters(int count) { number = Integer.toString(count); verb = &quot;are&quot;; pluralModifier = &quot;s&quot;; } private void thereIsOneLetter() { number = &quot;1&quot;; verb = &quot;is&quot;; pluralModifier = &quot;&quot;; } private void thereAreNoLetters() { number = &quot;no&quot;; verb = &quot;are&quot;; pluralModifier = &quot;s&quot;; } } </code></pre> <p><strong>My Python version</strong></p> <pre class="lang-py prettyprint-override"><code>class GuessStatsMessage: def __init__(self, candidate, count): self.candidate = candidate self.count = count self.__number = self.__verb = self.__plural_modifier = '' def make_message(self): self.__create_pluraldependant_message_parts() guess_message = (f'There {self.__verb} ' f'{self.__number} ' f'{self.candidate}{self.__plural_modifier} ') print(guess_message) def __create_pluraldependant_message_parts(self): if self.count == 0: self.__there_are_no_letters() elif self.count == 1: self.__there_is_one_letter() else: self.__there_are_many_letters() def __there_are_no_letters(self): self.__number = 'no' self.__verb = 'are' self.__plural_modifier = 's' def __there_is_one_letter(self): self.__number = '1' self.__verb = 'is' self.__plural_modifier = '' def __there_are_many_letters(self): self.__number = str(self.count) self.__verb = 'are' self.__plural_modifier = 's' </code></pre> <p>It should be used as follows:</p> <pre class="lang-py prettyprint-override"><code>message = GuessStatsMessage('Foo', 10) message.make_message() # output: There are 10 Foos </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T00:18:19.863", "Id": "484833", "Score": "1", "body": "For those who don't know the book, it would help to know what is the goal of the original code. Any simplifying assumptions, etc. (no unusual plurals like oxen or mothers-in-law). It looks like a reasonable translation (except make_message prints and the original returned a string). But Python is not Java. For example, in Python one would would define a `__str__()` method and maybe a `__format__()` method instead of `make_message()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T00:35:07.663", "Id": "484835", "Score": "0", "body": "Thanks for taking the time to look at it. I will update the question (I don't know if I should call it like that here, in Code Review) to show what is the goal of the original code of Uncle Bob. @RootTwo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T10:11:03.173", "Id": "484857", "Score": "1", "body": "I get it: You translated the Java private methods to `__double_underscore` in Python. But be careful: Any identifier of the form `__spam` (at least two leading underscores, at most one trailing underscore) is textually replaced with `_classname__spam`, where classname is the current class name with leading underscore(s) stripped. But `__private` names don't work the same way as in Java. Actually I don't think this is a good practice in Python at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T15:19:27.140", "Id": "484866", "Score": "0", "body": "Thanks for letting that clear, Peter. I appreciate it. I knew about it, and about name mangling, but I don't really know another way of actually hiding those attributes and methods for the users of `GuessStatsMessage` class. @PéterLeéh" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T16:35:14.783", "Id": "484934", "Score": "0", "body": "So do you want to know if your Python translation is a correct translation or if the translation is *pythonic*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T17:19:46.570", "Id": "484944", "Score": "0", "body": "The second one: I wanted you guys to check how Pythonic is that version of the example. I'm especially unsure about initializing the private attributes. I also thought about making it using @classmethod and use the class like `GuessStatsMessage.make_message('foo', 10)` instead of instantiating the class. @DaniMesejo" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T19:45:24.537", "Id": "247625", "Score": "5", "Tags": [ "python", "java" ], "Title": "Python version of Clean Code book example" }
247625
<p><strong>The Challenge:</strong> Given a string, return a string where each word is reversed individually without changing its position. <em>EDIT: (i.e.: the input &quot;hello world I am a frog?&quot; should produce the output: &quot;olleh dlrow I ma a gorf?&quot;)</em></p> <p><strong>Thoughts and questions:</strong> Perhaps I was cheating the spirit of the challenge by using string builder? What do you think?</p> <p>Complexity? Would the complexity be? I feel like it is O(n) since it will basically look at almost every char twice. I'm thinking there is a more efficient way to do it where n is just looked at once, but I think that to achieve that we will double the use of memory. Not that that is a problem, but I think that is the trade off.</p> <p>Coding tests tend to be timed and I did this quickly. In evaluating the code, how do you factor in the pressure of time as you administer the test? I am talking myself into the idea that the answer should have been creating a new string and entering the chars one at a time using pointers so that each string char is looked at once and moved once. Is that really better then this solution? Perhaps there are points for easily readable code? Do you think this is readable?</p> <pre><code> public static string ReverseOnlyWords(string InitialValue) { if (InitialValue == null) { throw new System.NullReferenceException(); } StringBuilder seperatedValue = new StringBuilder(); StringBuilder currentWord = new StringBuilder(); foreach (char c in InitialValue) { if (c == ' ' || c == '.' || c == ',') { seperatedValue.Append(Reverse(currentWord.ToString())); seperatedValue.Append(c.ToString()); currentWord.Clear(); } else { currentWord.Append(c.ToString()); } } seperatedValue.Append(Reverse(currentWord.ToString())); string resultValue = seperatedValue.ToString(); return resultValue; } </code></pre> <p>In Reverse, perhaps I should have simply created a copy of toBeReversed and inserted/replaced characters in the reversed order instead of a string builder?</p> <pre><code> static public string Reverse(string toBeReversed) { if (toBeReversed == null) { throw new System.NullReferenceException(); } StringBuilder reversedString = new StringBuilder(); for (int i = (toBeReversed.Length - 1); i &gt;= 0; i--) { reversedString.Append(toBeReversed[i].ToString()); } return reversedString.ToString(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T20:30:20.897", "Id": "484812", "Score": "2", "body": "Small note: throw `System.ArgumentNullException`, not `System.NullReferenceException`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T23:23:50.697", "Id": "484825", "Score": "1", "body": "Using StringBuilder is OK." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T23:25:50.297", "Id": "484826", "Score": "4", "body": "Note on the reverse. Usually, no one ever considers that a string may contain Unicode surrogate pairs. Simply copying one char at a time will result in incorrect results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T23:28:22.140", "Id": "484828", "Score": "4", "body": "Other note. The string can be a combination of Unicode characters. Accent, umlaut, etc. Again, copying one character at a time will lead to a strange result when, for example, the accent is on a consonant letter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:54:39.650", "Id": "485112", "Score": "1", "body": "How is the string \"That's well-known\" supposed to be reversed? Or, in other words, what exactly is \"a word\"? I'd like it if the capitalization of the words were preserved, but that's just not mentioned in the original task." } ]
[ { "body": "<p>First, <code>NullReferenceException</code> is used by the CLR, and it's the default exception for nullity in most cases. The <code>ArgumentNullException</code> used to prevent <code>NullReferenceException</code> from thrown, and gives more meaningful exception to your code.</p>\n<p>So, in your current code, if you pass a null, the thrown exception message would be something like</p>\n<pre><code>Object reference not set to an instance of an object\n</code></pre>\n<p>. This would not give you any hint on what's going on your code, so if you used</p>\n<pre><code>throw new ArgumentNullException(nameof(InitialValue));\n</code></pre>\n<p>this would give you something like :</p>\n<pre><code>Value cannot be null. (Parameter 'InitialValue') \n</code></pre>\n<p>isn't clearer to point out the issue ?</p>\n<p>Another point is that you don't need to throw an exception all the time as a way to handle your code. Only throw exception when it's critical to the application. As exceptions like a <code>Stop</code> sign to the application, whenever it's thrown, it stops the application from running the code. if the code is related to other dependencies such as required class, extensions, databases, ..etc. Then, this code should throw an exception if it leaks the dependency requirements.</p>\n<p>In your case, it's not critical to pass null, yes it would break the code, but also it's not required to stop the code just for this, as you can simply return null to the caller. Same thing if <code>Empty</code> string or <code>Whitespace</code> passed. because you</p>\n<p>so if you do this :</p>\n<pre><code>if(string.IsNullOrWhitespace(value)) { return value; }\n</code></pre>\n<p>would be enough and better than thrown exception for this case.</p>\n<p>For the methods <code>ReverseOnlyWords</code> and <code>Reverse</code> I don't see what was the reason behind splitting them?. It should be one method that does the process. having two methods is confusing, because it's required to us (or any developer) to read both methods to understand the logic and to know which to use ! of course, splitting methods can be useful if there are independent procedures inside the method that can be reused or simply outside the main scope of the method, but not in your current code.</p>\n<p>Using <code>StringBuilder</code> is a good practice. However, you only need one, the other one is unnecessary. Also, you don't need <code>ToString()</code> when appending <code>char</code> in <code>StringBuilder</code></p>\n<p>this line :</p>\n<pre><code>if (c == ' ' || c == '.' || c == ',') { ... }\n</code></pre>\n<p>punctuations can't be handled like this, because if you keep it that way, you will miss other punctuations. if we assumed you'll process English context, then you only covered 3 out of 14 punctuations that I know of. What about other languages? So Instead, use the built in <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.char.ispunctuation?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>char.IsPunctuation</code></a> which covers most of the punctuations that in <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.globalization.unicodecategory?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>UnicodeCategory</code></a>.</p>\n<blockquote>\n<p>Complexity? Would the complexity be? I feel like it is O(n) since it\nwill basically look at almost every char twice.</p>\n</blockquote>\n<p>You're using 3 loops, so your complexity is <span class=\"math-container\">\\$O(N^2)\\$</span>. though, it can be simplified to two loops (one for the words, the other for the characters), and one <code>StringBuilder</code> is enough. However, the overall code can be written as follow :</p>\n<pre><code>public string Reverse(string value, char separator)\n{ \n if(string.IsNullOrEmpty(value)) { return value; } // just return the value, leave the handling to the caller.\n \n var words = value.Split(separator); // split it to words by spaces\n\n // initiate a string builder with a fixed size based on the original string size. \n // setting the capacity would avoid oversized allocation.\n var resultBuilder = new StringBuilder(value.Length);\n\n // iterate over words \n for(int x=0; x &lt; words.Length; x++)\n { \n // store the tailing punctuation\n char? punctuation = null;\n // iterate over characters in reverse \n for(int c = words[x].Length - 1; c &gt;= 0; c--)\n { \n var current = words[x][c];\n \n if(char.IsPunctuation(current))\n {\n if(c == 0) // for leading punctuation\n {\n // get the first poistion of the current word \n var index = resultBuilder.ToString().Length - (words[x].Length - 1);\n \n // insert the leading punctuation to the first poition (its correct poistion)\n resultBuilder.Insert(index, current); \n }\n else \n {\n // store tailing punctuation to insert it afterward\n punctuation = current;\n }\n \n }\n else \n {\n // everything else, just append\n resultBuilder.Append(current); \n } \n \n }\n \n if(punctuation != null)\n {\n // insert tailing punctuation \n resultBuilder.Append(punctuation);\n punctuation = null; //reset \n }\n\n resultBuilder.Append(separator); \n }\n\n return resultBuilder.ToString();\n} \n</code></pre>\n<p>this is just a revision of your code in its simplest form possible (at least to my knowledge) and it's one way process (process each word and character once). Using pointers would not increase the overall performance to the point where it would be recommended!. <code>Array.Reverse</code> also can be used, but still might add more memory allocation and slow down the performance specially with large strings.</p>\n<p>Other missing part that needs to be counted when dealing with strings is <code>Unicode</code> which in some cases invalidate the results if not handled correctly.</p>\n<p><strong>UPDATE :</strong></p>\n<p>Here is another version that uses one loop, and two <code>StringBuilder</code> (one stores the results, and one for the processing).</p>\n<pre><code>public static string ReverseString(string value , char separator)\n{\n if(string.IsNullOrEmpty(value)) { return value; }\n\n var tempBuilder = new StringBuilder(value.Length);\n\n var resultBuilder = new StringBuilder(value.Length);\n\n var isCompleted = false;\n\n for(int x = 0, index = value.Length - 1; index &gt;= 0; index--, x++)\n {\n var current = value[index];\n \n if(current == separator)\n {\n isCompleted = true;\n }\n else\n {\n tempBuilder.Append(current);\n\n if(index == 0)\n {\n isCompleted = true;\n }\n }\n\n if(isCompleted)\n {\n // handle the lead and tail punctuations\n if(char.IsPunctuation(tempBuilder[0]) &amp;&amp; char.IsPunctuation(tempBuilder[tempBuilder.Length - 1]))\n {\n var tail = tempBuilder[0];\n var lead = tempBuilder[tempBuilder.Length - 1];\n tempBuilder.Remove(0 , 1);\n tempBuilder.Remove(tempBuilder.Length - 1 , 1);\n tempBuilder.Insert(0 , lead);\n tempBuilder.Append(tail);\n }\n else if(char.IsPunctuation(tempBuilder[0]))\n {\n tempBuilder.Append(tempBuilder[0]);\n tempBuilder.Remove(0 , 1);\n }\n else if(char.IsPunctuation(tempBuilder[tempBuilder.Length - 1]))\n {\n tempBuilder.Insert(0 , tempBuilder[0]);\n tempBuilder.Remove(tempBuilder.Length - 1 , 1);\n }\n\n //store the results\n resultBuilder.Insert(0 , separator);\n resultBuilder.Insert(0 , tempBuilder);\n\n //reset\n tempBuilder.Clear();\n x = 0;\n isCompleted = false;\n\n }\n }\n\n return resultBuilder.ToString();\n}\n</code></pre>\n<p>it may need more work, but I thought it would be useful to share it. It still lakes the Unicode handling though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T16:50:50.760", "Id": "484940", "Score": "0", "body": "I had the reverse method at the start of coding. I was applying DRY, where I was using that method for others. and well also saving the time it took to code it. I do see that including it all in a single method could increase efficiency/speed and allow improvement to the algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T13:56:30.327", "Id": "485021", "Score": "1", "body": "I don't think the original is \\$O(N^2)\\$. It would require running through the string for each character in the string. A simple test indicates it is scaling linearly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T16:26:11.220", "Id": "485028", "Score": "0", "body": "Thank you @Johnbot, I agree. In fairness, iSR5 does have the fastest algorithm. I played with mine to get closer to iSR5's and managed to match+ the speed by removing the use of a second string builder. The change of incorporating the method made no discernable difference in the timing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:38:28.787", "Id": "485108", "Score": "0", "body": "@amalgamate check the updated version. I believe it's possible to use one StringBuilder to the updated version though. But it would add more handling , which adds more work ;)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T09:42:25.730", "Id": "247650", "ParentId": "247628", "Score": "4" } } ]
{ "AcceptedAnswerId": "247650", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T19:48:06.887", "Id": "247628", "Score": "6", "Tags": [ "c#", "strings" ], "Title": "Reverse character order of substrings delineated by white space chars" }
247628
<p>It is a practice from the site edabit.com and you have to check if the input is valid. That is the original task:</p> <blockquote> <p>Given an RGB(A) CSS color, determine whether its format is valid or not. Create a function that takes a string (e.g. &quot;rgb(0, 0, 0)&quot;) and return True if it's format is correct, otherwise return False.</p> </blockquote> <p>The rules are shown in the testing code:</p> <pre><code># True Tests Test.assert_equals(valid_color('rgb(0,0,0)'), True, 'rgb lowest valid numbers') Test.assert_equals(valid_color('rgb(255,255,255)'), True, 'rgb highest valid numbers') Test.assert_equals(valid_color('rgba(0,0,0,0)'), True, 'rgba lowest valid numbers') Test.assert_equals(valid_color('rgba(255,255,255,1)'), True, 'rgba highest valid numbers') Test.assert_equals(valid_color('rgba(0,0,0,0.123456789)'), True, 'alpha can have many decimals') Test.assert_equals(valid_color('rgba(0,0,0,.8)'), True, 'in alpha the number before the dot is optional') Test.assert_equals(valid_color('rgba( 0 , 127 , 255 , 0.1 )'), True, 'whitespace is allowed around numbers (even tabs)') Test.assert_equals(valid_color('rgb(0%,50%,100%)'), True, 'numbers can be percentages') # False Tests Test.assert_equals(valid_color('rgb(0,,0)'), False, 'INVALID: missing number') Test.assert_equals(valid_color('rgb (0,0,0)'), False, 'INVALID: whitespace before parenthesis') Test.assert_equals(valid_color('rgb(0,0,0,0)'), False, 'INVALID: rgb with 4 numbers') Test.assert_equals(valid_color('rgba(0,0,0)'), False, 'INVALID: rgba with 3 numbers') Test.assert_equals(valid_color('rgb(-1,0,0)'), False, 'INVALID: numbers below 0') Test.assert_equals(valid_color('rgb(255,256,255)'), False, 'INVALID: numbers above 255') Test.assert_equals(valid_color('rgb(100%,100%,101%)'), False, 'INVALID: numbers above 100%') Test.assert_equals(valid_color('rgba(0,0,0,-1)'), False, 'INVALID: alpha below 0') Test.assert_equals(valid_color('rgba(0,0,0,1.1)'), False, 'INVALID: alpha above 1') </code></pre> <p>I fear that my solution is not very elegant, efficent or short:</p> <pre><code>def create_rgbA_tuple(color): indexBracket1 = color.rfind(&quot;(&quot;) save = color[0] + color[1] + color[2] + color[3] if save != 'rgb(' and save != 'rgba': return False indexBracket2 = color.rfind(&quot;)&quot;) bracketArea = &quot;&quot; for i in range(indexBracket1 + 1, indexBracket2): bracketArea = bracketArea + color[i] bracketArea = bracketArea.split(',') # bracketArea is now an Array (r,g,b/A) if len(bracketArea) == 4 and save != 'rgba' or len(bracketArea) == 3 and save != 'rgb(': return False try: for i in range(len(bracketArea)): bracketArea[i] = float(bracketArea[i]) except: try: for i in range(len(bracketArea)): if bracketArea[i][-1] == &quot;%&quot;: bracketArea[i] = int(bracketArea[i].strip('%')) / 100 * 255 else: return False except: return False return bracketArea def valid_color(color): rgb = create_rgbA_tuple(color) if not rgb: return False for i in range(3): if int(rgb[i]) &lt; 0 or int(rgb[i]) &gt; 255: return False if color[3] == &quot;a&quot;: # if rgbA if rgb[3] &lt; 0 or rgb[3] &gt; 1: return False return True <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>One thing the tests don't indicate is whether space is allowed before/after the color string. I'm inclined to be generous, so I'd suggest just discarding any space before you start:</p>\n<pre><code>color = color.strip()\n</code></pre>\n<p>Next, you are doing a lot of work to replace some python built-in functions. Before you do anything else, you should probably read the <a href=\"https://docs.python.org/3/library/stdtypes.html#string-methods\" rel=\"nofollow noreferrer\">String Methods</a> documentation to see what tools are available to you.</p>\n<p>Try something like:</p>\n<pre><code>is_rgb = color.startswith('rgb(')\nis_rgba = color.startswith('rgba(')\n\nif not is_rgb and not is_rgba:\n return False\n\nif not color.endswith(')'):\n return False\n\n# strip off prefix &quot;...(&quot; and suffix &quot;)&quot; \ncolor = color[color.index('(') + 1:-1]\n</code></pre>\n<p>You can use <code>.endswith</code> to check for percent signs, also.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T21:19:23.670", "Id": "484814", "Score": "0", "body": "Thank you for your advise! You are right these inbuilt functions are far more elegant, I guess I'll start learning some." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T20:47:52.753", "Id": "247631", "ParentId": "247629", "Score": "3" } } ]
{ "AcceptedAnswerId": "247631", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T20:27:31.650", "Id": "247629", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Check if an inputted string is in the right format for a valid rgb color" }
247629
<p>I implemented the heaviest stone algorithm, but I am not sure about its time complexity. I'm doing sort which is O(nlogn), but it' inside a while loop.</p> <p>Problem:</p> <p>We have a collection of stones, each stone has a positive integer weight.</p> <p>Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x &lt;= y. The result of this smash is:</p> <p>If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)</p> <p>Example:</p> <pre><code>Input: [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. </code></pre> <p>My solution:</p> <pre><code>var lastStoneWeight = function(stones) { if(!stones || stones.length === 0) return 0; if(stones.length === 1) return stones[0]; stones.sort((a,b) =&gt; b-a); while(stones.length &gt; 1) { const x = stones[0]; const y = stones[1]; stones.splice(0, 2); if(x !== y) { stones.push(x-y); if(stones.length === 1) return stones[0]; stones.sort((a,b) =&gt; b-a); } } return stones.length &gt; 0 ? stones[0] : 0; }; </code></pre> <p>By the way, is there a way to have a better performance? Maybe not sorting?</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T00:03:44.133", "Id": "484831", "Score": "1", "body": "If you're worried about efficiency, couldn't you simply go through the entire list and find the two heaviest stones instead of sorting everytime? You can create a new function for this, and I think it should give you a significant increase in performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T01:38:42.673", "Id": "484837", "Score": "1", "body": "For this case it approximates $$O(n^2\\ln(n))$$ (as worst case in general) because you are sorting them in the while loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T05:15:59.617", "Id": "484840", "Score": "1", "body": "O(n^2 * log(n)) is yours. O(n^2) if you implement what @cliesens proposed. O(n * log(n)) if you are willing to implement heap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T19:46:36.660", "Id": "484872", "Score": "0", "body": "Thank you. Yes, it is what I thought O(n^2log(n)). Could you please show me how could I change it to O(nlog(n)) or O(n) if it's possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T21:21:56.837", "Id": "484876", "Score": "0", "body": "A follow up problem is: \"Each turn, we choose any two rocks and smash them together. At the end, there is at most 1 stone left. Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)\" Any idea how can I approach this problem in order to have the smallest possible weight" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T22:57:05.850", "Id": "484880", "Score": "1", "body": "The data structure you want is a priority queue, https://en.wikipedia.org/wiki/Priority_queue, this essentially solves the problem of having to repeatedly sort the collection. Unfortunately js doesn't come with priority queues built in, the lack of good built in datastructures is an unfortunate fact about the language imo, so you'll have to implement it yourself or use a dependency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T23:34:27.773", "Id": "484881", "Score": "0", "body": "Could you please show me an example of how a priority queue would solve this problem? I could using a Map() in javascript" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T09:29:57.627", "Id": "484897", "Score": "1", "body": "I added a C++ solution here: https://codereview.stackexchange.com/questions/247668/smashing-two-heaviest-stones-until-at-most-one-stone-is-left-counting-number-o\n\nIt's a bit more complex and the crucial parts are implemented by the C++'s standard library, but I'm sure you can find code of the 3 functions on wiki. Map won't help you in any way here. For the followup problem, it looks like NP hard, because you can try all permutations of the input to find the smallest result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T09:31:30.730", "Id": "484898", "Score": "1", "body": "But also it feels like smashing the two heaviest stones every time may already give the smallest possible result. So I would start by trying to logacily prove (or disprove) such statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:41:49.697", "Id": "485109", "Score": "1", "body": "If you dont mind i would like to hear back from you. Did it put you on the right path? After all I implemented the C++ solution just to show it to you..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:42:36.260", "Id": "485110", "Score": "1", "body": "And use @ and my name in further comments So i get a notification please :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T14:53:43.660", "Id": "485170", "Score": "0", "body": "@slepic I'm looking for a solution in Javascript" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:54:30.140", "Id": "485181", "Score": "1", "body": "I know but js does not have those heap functions. I meant it to show you how the stones problem can be solved using heap. But implementing the heap functions in js is up to you. Look them up on wiki, they are usualy called build-heap or heapify, sift-up and sift-down, or sometimes bubble-up and bubble-down." } ]
[ { "body": "<h1>Issue(s)</h1>\n<ol>\n<li>You sort descending, but then take and assign the heaviest stone to <code>x</code> and the second heaviest stone to <code>y</code> whereas in your problem you state &quot;...stones have weights x and y with x &lt;= y&quot;.</li>\n<li>Code isn't as DRY (Don't Repeat Yourself) as it <em>could</em> be.</li>\n</ol>\n<h1>Suggestions</h1>\n<ol>\n<li>Provide <code>stones</code> a default/initial empty array value.</li>\n<li>Sort descending and assign <code>const y = stones[0];</code> and <code>const x = stones[1];</code> and push new value <code>stones.push(y - x);</code> to match problem. (<em>Or normal sort ascending and take from array end, more on this later</em>)</li>\n<li>Use array destructuring to assign to <code>x</code> and <code>y</code> since array::splice returns an array of spliced out values.</li>\n<li>Sort once at the beginning of each iteration.</li>\n<li>Remove extraneous array length checks, let the while-loop condition handle it.</li>\n</ol>\n<h2>Code</h2>\n<pre><code>const lastStoneWeight = (stones = []) =&gt; {\n if (!stones || !stones.length) return 0;\n\n while (stones.length &gt; 1) {\n stones.sort((a, b) =&gt; a - b);\n const [x, y] = stones.splice(-2);\n if (x !== y) stones.push(y - x);\n }\n return stones[0] || 0;\n};\n</code></pre>\n<p>If you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\">Optional Chaining</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\">Nullish Coalescing</a></p>\n<pre><code>const lastStoneWeight = (stones = []) =&gt; {\n if (!stones?.length) return 0;\n\n while (stones.length &gt; 1) {\n stones.sort((a, b) =&gt; a - b);\n const [x, y] = stones.splice(-2);\n if (x !== y) stones.push(y - x);\n }\n return stones[0] ?? 0;\n};\n</code></pre>\n<p>Here I use the default sort (ascending) and splice off the last two elements, removes need to shift entire forward 2 indices.</p>\n<h2>Using a Heap Data Structure</h2>\n<p>Since you ask about improved performance and the going suggestion is to use a heap/priority queue. This is a very similar implementation.</p>\n<pre><code>const lastStoneWeightHeap = (stones = []) =&gt; {\n if (!stones?.length) return 0;\n\n const heap = new PriorityQueue(); // &lt;-- uses equivalent comparator as array::sort\n stones.forEach((stone) =&gt; heap.enq(stone)); // &lt;-- populate heap\n\n while (heap.size() &gt; 1) {\n const y = heap.deq();\n const x = heap.deq();\n if (x !== y) heap.enq(y - x);\n }\n return heap.size() ? heap.deq() : 0;\n};\n</code></pre>\n<p><code>t1</code> is regular algorithm\n<code>t2</code> is version using heap/priority queue data structure</p>\n<pre><code>10 iterations x 10000 runs\n # Elements t0 avg t1 avg \n1 8 0.00363 0.00106 \n2 16 0.01036 0.00157 \n3 32 0.01781 0.00224 \n4 64 0.09148 0.00432 \n5 128 0.22560 0.00944 \n6 256 0.56833 0.01618 \n7 512 2.37584 0.06091 \n8 1024 8.78741 0.12614 \n9 2048 34.29092 0.29697 \n10 4096 130.50169 0.63872 \n</code></pre>\n<p><em>Notes:</em></p>\n<ul>\n<li>Time is in milliseconds</li>\n</ul>\n<p><a href=\"https://www.npmjs.com/package/priorityqueuejs\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/priorityqueuejs</a></p>\n<h2>Conclusion</h2>\n<p>Using a heap data structure is orders of magnitude an improvement. With the naive implementation it is clearly at least an <span class=\"math-container\">\\$O(n^2)\\$</span> complexity as each time the dataset size doubles (2x) the runtime roughly quadruples (~4x) whereas the implementation using a heap roughly only doubles (~2x) the runtime with each doubling of the dataset.</p>\n<h1>Performance Benchmarking</h1>\n<p>performanceBenchmark.js</p>\n<pre><code>const measurePerf = (fn, data, runs = 1e3) =&gt;\n [...Array(runs).keys()]\n .map(() =&gt; {\n const start = performance.now();\n fn([...data]);\n const end = performance.now();\n return end - start;\n })\n .reduce((total, current) =&gt; total + current) / runs;\n\nconst toFixed = (val, fixed) =&gt;\n Number.isFinite(val) ? Number(val).toFixed(fixed) : val;\n\nexport const benchmark = async ({\n functions = [],\n createRunData,\n iterations = 5,\n runs = 1e3,\n logIntermediateResults\n}) =&gt; {\n logIntermediateResults &amp;&amp; console.log(`${iterations} x ${runs}`);\n\n const results = [];\n\n logIntermediateResults &amp;&amp;\n console.log(\n `\\t# Elements\\t${functions.map((_, i) =&gt; `t${i} avg`).join(&quot;\\t&quot;)}`\n );\n\n for (let i = 0; i &lt; iterations; i++) {\n const data = createRunData(i);\n\n const res = await Promise.all(\n functions.map((fn) =&gt; measurePerf(fn, data, runs))\n );\n\n results.push(res);\n\n logIntermediateResults &amp;&amp;\n console.log(\n `${i + 1}\\t${data.length}\\t${res\n .map((t) =&gt; `${toFixed(t, 5)}`)\n .join(&quot;\\t&quot;)}`\n );\n }\n\n return results;\n};\n</code></pre>\n<p>Setup &amp; benchmark</p>\n<pre><code>const ITERATIONS = 10;\nconst RUNS = 1e4;\nconst SEED = 8;\n\nconst functions = [\n lastStoneWeight,\n lastStoneWeightHeap,\n];\n\nconst createRunData = (i) =&gt; {\n const dataLength = SEED &lt;&lt; i;\n const stones = [...Array(dataLength).keys()].map(() =&gt;\n Math.floor(Math.random() * dataLength)\n );\n return stones;\n};\n\nbenchmark({\n functions,\n createRunData,\n iterations: ITERATIONS,\n runs: RUNS,\n logIntermediateResults: true\n});\n</code></pre>\n<p>Extended heap implementation benchmark</p>\n<pre><code>15 x 10000 \n # Elements t0 avg \n1 8 0.00100 \n2 16 0.00171 \n3 32 0.00242 \n4 64 0.00434 \n5 128 0.00933 \n6 256 0.01825 \n7 512 0.05681 \n8 1024 0.13715 \n9 2048 0.27621 \n10 4096 0.59631 \n11 8192 1.24577 \n12 16384 4.75092 \n13 32768 6.09799 \n14 65536 13.07677 \n15 131072 28.88058 \n</code></pre>\n<p><a href=\"https://codesandbox.io/s/solitary-microservice-hbpxw?fontsize=14&amp;hidenavigation=1&amp;module=%2Fsrc%2Findex.js&amp;theme=dark\" rel=\"nofollow noreferrer\"><img src=\"https://codesandbox.io/static/img/play-codesandbox.svg\" alt=\"Edit solitary-microservice-hbpxw\" /></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T09:24:56.570", "Id": "487207", "Score": "1", "body": "The default [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) in JavaScript is *alphabetical*, even for numbers. It converts them to strings, so 10 would be before 2. You need to provide a sorting function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-31T10:29:09.083", "Id": "487221", "Score": "0", "body": "@Kruga Thanks, I added a test case in the sandbox for an array with values like that and updated implementations." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-29T10:25:24.993", "Id": "248609", "ParentId": "247632", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T21:19:13.247", "Id": "247632", "Score": "10", "Tags": [ "javascript", "array" ], "Title": "Heaviest Stone algorithm time complexity" }
247632
<p>This code is designed for my 30 LED NeoPixel clock, the reason for not using the ds3231 library is due to the fact that I use codebender to download programs to my Arduino, I wanted some critique on things that could be improved and any glaring problems that should be fixed.</p> <pre><code>/*This code is for a 30 LED NeoPixel Clock, it includes code for IR remote control of a solenoid controlled RGB lamp and the colors and position of them on the clock along with brightness Base code for clock with no library comes from: https://forum.arduino.cc/index.php?topic=514601.0 */ #include &quot;Wire.h&quot; #include &lt;Adafruit_NeoPixel.h&gt; #include &lt;IRremote.h&gt; #include &lt;FastLED.h&gt; //Clock Timing Functions #define DS3231_I2C_ADDRESS 0x68 byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; // Convert normal decimal numbers to binary coded decimal byte decToBcd(byte val){ return ( (val / 10 * 16) + (val % 10) ); } // Convert binary coded decimal to normal decimal numbers byte bcdToDec(byte val){ return ( (val / 16 * 10) + (val % 16) ); } //LED Strip Defint CRGB leds[30]; //Color Values for LEDS int rMin =0, gMin=255, bMin=0; int rHour=0, gHour=0, bHour=255; int rSec=255, gSec=0, bSec=0; CRGB c1, c2, c3; CRGB min,sec,hr; bool onOff, pallete; int cCount,lCount; //Values to keep time int tMin1, tMin2; int hourNum1, hourNum2, hourNum3; //IR setup IRrecv irrecv(2); decode_results result; void setup(){ //Pins for solenoid control pinMode(10, OUTPUT); pinMode(11, OUTPUT); //Setting starting Colors min=CRGB(255,0,0); sec=CRGB(0,255,0); hr=CRGB(0,0,255); Wire.begin(); //Neopixel Declaration FastLED.addLeds&lt;NEOPIXEL, 9&gt;(leds, 30).setCorrection( TypicalLEDStrip ); FastLED.clear(); FastLED.show(); Serial.begin(9600); irrecv.enableIRIn(); // set the initial time here: // DS3231 seconds, minutes, hours, day, date, month, year // setDS3231time(30,17,15,7,18,11,17); } //More Time Code void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year){ // sets time and date data to DS3231 Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0); // set next input to start at the seconds register Wire.write(decToBcd(second)); // set seconds Wire.write(decToBcd(minute)); // set minutes Wire.write(decToBcd(hour)); // set hours Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday) Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31) Wire.write(decToBcd(month)); // set month Wire.write(decToBcd(year)); // set year (0 to 99) Wire.endTransmission(); } void readDS3231time(byte *second, byte *minute, byte *hour, byte *dayOfWeek, byte *dayOfMonth, byte *month, byte *year){ Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0); // set DS3231 register pointer to 00h Wire.endTransmission(); Wire.requestFrom(DS3231_I2C_ADDRESS, 7); // request seven bytes of data from DS3231 starting from register 00h *second = bcdToDec(Wire.read() &amp; 0x7f); *minute = bcdToDec(Wire.read()); *hour = bcdToDec(Wire.read() &amp; 0x3f); *dayOfWeek = bcdToDec(Wire.read()); *dayOfMonth = bcdToDec(Wire.read()); *month = bcdToDec(Wire.read()); *year = bcdToDec(Wire.read()); } void displayTime(){ // retrieve data from DS3231 readDS3231time(&amp;second, &amp;minute, &amp;hour, &amp;dayOfWeek, &amp;dayOfMonth, &amp;month, &amp;year); } //Loop Here void loop() { //Serial.println(String(hour)+&quot;:&quot;+String(minute)+&quot;:&quot;+String(second)); displayTime(); // display the real-time clock data on the Serial Monitor, //If reciever IR translate it, otherwise run through time code if (irrecv.decode(&amp;result)) { //delay(100); Serial.println(result.value); remoteCodes(); //Method holding if statement of IR values irrecv.resume(); // Receive the next value //delay(100); }else{ //Call methods to display the time displaySeconds(); displayMinutes(); displayHours(); displayOverlap(); } delay(100); //Show updated pattern FastLED.show(); } //Code to generate hour number positions and display them void hourNumbers() { if (hour == 1 || hour == 13) { hourNum1 = 2; hourNum2 = 2; hourNum3 = 1; } else if (hour == 2 || hour == 14) { hourNum1 = 4; hourNum2 = 5; hourNum3 = 2; } else if (hour == 3 || hour == 15) { hourNum1 = 7; hourNum2 = 7; hourNum3 = 3; } else if (hour == 4 || hour == 16) { hourNum1 = 9; hourNum2 = 10; hourNum3 = 4; } else if (hour == 5 || hour == 17) { hourNum1 = 12; hourNum2 = 12; hourNum3 = 5; } else if (hour == 6 || hour == 18) { hourNum1 = 14; hourNum2 = 15; hourNum3 = 6; } else if (hour == 7 || hour == 19) { hourNum1 = 17; hourNum2 = 17; hourNum3 = 7; } else if (hour == 8 || hour == 20) { hourNum1 = 19; hourNum2 = 20; hourNum3 = 8; } else if (hour == 9 || hour == 21) { hourNum1 = 22; hourNum2 = 22; hourNum3 = 9; } else if (hour == 10 || hour == 22) { hourNum1 = 24; hourNum2 = 25; hourNum3 = 10; } else if (hour == 11 || hour == 23) { hourNum1 = 27; hourNum2 = 27; hourNum3 = 11; } else if (hour == 12 || hour == 00) { hourNum1 = 29; hourNum2 = 0; hourNum3 = 12; } } void displayHours(){ hourNumbers(); leds[hourNum1]=CRGB(hr); leds[hourNum2]=CRGB(hr); } //Code to generate minute number positions and display them void minuteNumbers() { tMin1 = minute / 2; if (minute % 2 == 0) tMin2 = minute / 2 - 1; else tMin2 = minute / 2; if (tMin2 == -1) tMin2 = 29; } void displayMinutes(){ minuteNumbers(); leds[tMin1]=CRGB(min); leds[tMin2]=CRGB(min); } //Code that sets overlapping minutes and hours to void displayOverlap(){ if(minute&gt;=30){ leds[hourNum2+1]=hr; if(tMin1==hourNum2+1) leds[hourNum2+1]=CRGB(255,255,255); else if(tMin2==hourNum2+1) leds[hourNum2+1]=CRGB(255,255,255); } if(tMin1==hourNum1) leds[tMin1]=CRGB(255,255,255); else if(tMin1==hourNum2) leds[tMin1]=CRGB(255,255,255); else if(tMin2==hourNum1) leds[tMin2]=CRGB(255,255,255); else if(tMin2==hourNum2) leds[tMin2]=CRGB(255,255,255); } //Animation run at the hour void hourAnimation(){ for (int j = 0; j &lt; hourNum3; j++) { for (int i = 0; i &lt; 30; i++) { leds[i]= CRGB(255, 255, 255); leds[i-3]=CRGB(0,0,0); if (i == 0) leds[27]==CRGB(0,0,0); if (i == 1) leds[28]==CRGB(0,0,0); if (i == 2) leds[29]==CRGB(0,0,0); FastLED.show(); delay(15); } } } //Code to display the seconds void displaySeconds(){ if(second&lt;=1){ for(int i=30; i&gt;second/2; i--){ Serial.println(&quot;A&quot;); leds[i]=CRGB(0,0,0); displayHours(); displayMinutes(); displayOverlap(); delay(35); FastLED.show(); } }else{ for(int i=1; i&lt;=second; i++){ if(i%2!=0){ leds[i/2]=CRGB(sec); leds[i/2].fadeToBlackBy(225); } leds[i/2-1]=CRGB(sec); } } } //If statement method for IR values recieved void remoteCodes(){ if(result.value==551508135){ //&quot;Mutes&quot; the LEDS if(onOff==true){ onOff=!onOff; FastLED.setBrightness(0); }else{ onOff=!onOff; FastLED.setBrightness(255); } Serial.println(&quot;Mute&quot;); }else if(result.value==551485695){ //Increases Brightess if(FastLED.getBrightness()+25&gt;255) FastLED.setBrightness(255); else FastLED.setBrightness(FastLED.getBrightness()+25); onOff=false; Serial.println(&quot;UpBrightness&quot;); }else if(result.value==551518335){ //Decreases Brightness if(FastLED.getBrightness()-25&lt;0){ FastLED.setBrightness(0); onOff=true; }else FastLED.setBrightness(FastLED.getBrightness()-25); Serial.println(&quot;DownBrightness&quot;); }else if(result.value==551520375){ //First Color Values rSec = (255); gSec = (0); bSec = (0); rMin = (0); gMin = (255); bMin = (0); rHour = (0); gHour = (0); bHour = (255); cCount=0; colorSwap(); Serial.println(&quot;1&quot;); }else if(result.value==0000){ //Second Color Values rSec = (235); gSec = (22); bSec = (242); rMin = (29); gMin = (242); bMin = (22); rHour = (242); gHour = (128); bHour = (22); cCount=0; colorSwap(); Serial.println(&quot;2&quot;); }else if(result.value==000){ //Third Color Values rSec = (38); gSec = (70); bSec = (83); rMin = (233); gMin = (196); bMin = (106); rHour = (231); gHour = (111); bHour = (81); cCount=0; colorSwap(); Serial.println(&quot;3&quot;); }else if(result.value==551495895){ //Fourth Color Values rSec = (0); gSec = (255); bSec = (255); rMin = (255); gMin = (0); bMin = (255); rHour = (255); gHour = (255); bHour = (0); cCount=0; colorSwap(); Serial.println(&quot;4&quot;); }else if(result.value==000){ //Fith Color Values rSec = (64); gSec = (93); bSec = (99); rMin = (156); gMin = (77); bMin = (60); rHour = (105); gHour = (139); bHour = (104); cCount=0; colorSwap(); Serial.println(&quot;5&quot;); }else if(result.value==551512215){ //Sixth Color Values rHour = (5); gHour = (148); bHour = (33); rSec = (148); gSec = (34); bSec = (5); rMin = (34); gMin = (5); bMin = (148); cCount=0; colorSwap(); Serial.println(&quot;6&quot;); }else if(result.value==551536695){ //Seventh Color Values rSec = 86; gSec = 18; bSec = 204; rMin = 204; gMin = 192; bMin = 18; rHour = 204; gHour = 98; bHour = 18; cCount=0; colorSwap(); Serial.println(&quot;2&quot;); }else if(result.value==551528535){ //Eight Color Values rSec = 255; gSec = 3; bSec = 192; rMin = 3; gMin = 255; bMin = 192; rHour = 66; gHour = 255; bHour = 3; cCount=0; colorSwap(); Serial.println(&quot;5&quot;); }else if(result.value==551504055){ //Ninth Color Values rSec = 5; gSec = 148; bSec = 33; rMin = 148; gMin = 34; bMin = 5; rHour = 35; gHour = 5; bHour = 148; cCount=0; colorSwap(); Serial.println(&quot;3&quot;); }else if(result.value==551544345){ //Unused Button cCount=0; Serial.println(&quot;PIC&quot;); }else if(result.value==551487735){ //Changes Solenoid Controlled Lamp Serial.println(&quot;0&quot;); lampSwap(); }else if(result.value==551550720){ //Swaps the Colors Around the Clock colorSwap(); Serial.println(&quot;-&quot;); }else if(result.value==551540775){ //Alt Color Swap colorSwap(); Serial.println(&quot;info&quot;); }else if(result.value==551544855){ //7th rHour=random(0,255); gHour=random(0,255); bHour=random(0,255); Serial.println(&quot;7&quot;); cCount=0; colorSwap(); }else if(result.value==551491815){ //8th rMin=random(0,255); gMin=random(0,255); bMin=random(0,255); Serial.println(&quot;8&quot;); cCount=0; colorSwap(); }else if(result.value==551524455){ //9th rSec=random(0,255); gSec=random(0,255); bSec=random(0,255); Serial.println(&quot;9&quot;); cCount=0; colorSwap(); } //Serial.println(&quot; is &quot;+String()+&quot; gMin is &quot;+String(gMin)+&quot; is &quot;+String()); } //Code to cycle through lamp colors void lampSwap(){ switch(lCount){ case 0:{ lCount+=1; digitalWrite(10,HIGH); digitalWrite(11,HIGH); break; } case 1:{ lCount+=1; digitalWrite(10,HIGH); digitalWrite(11,LOW); break; } case 2:{ lCount+=1; digitalWrite(10,LOW); digitalWrite(11,HIGH); break; } case 3:{ lCount=0; digitalWrite(10,LOW); digitalWrite(11,LOW); break; } } } //Code to cycle through Hour-Min-Second-Colors void colorSwap(){ FastLED.clear(); Serial.println(&quot;ColorSwapped&quot;); Serial.println(cCount); Serial.println(&quot;=&quot;+String(rMin)+&quot; GMIN=&quot;+String(gMin)+&quot; =&quot;+String(bMin)); switch(cCount){ case 0:{ Serial.println(&quot;SUCCESS1&quot;); sec=CRGB(rSec,gSec,bSec); min=CRGB(rMin,gMin,bMin); hr=CRGB(rHour,gHour,bHour); break; } case 1:{ Serial.println(&quot;SUCCESS2&quot;); hr=CRGB(rSec,gSec,bSec); sec=CRGB(rMin,gMin,bMin); min=CRGB(rHour,gHour,bHour); break; } case 2:{ Serial.println(&quot;SUCCESS3&quot;); min=CRGB(rSec,gSec,bSec); hr=CRGB(rMin,gMin,bMin); sec=CRGB(rHour,gHour,bHour); break; } case 3:{ Serial.println(&quot;SUCCESS4&quot;); hr=CRGB(rSec,gSec,bSec); sec=CRGB(rMin,gMin,bMin); min=CRGB(rHour,gHour,bHour); break; } case 4:{ Serial.println(&quot;SUCCESS5&quot;); sec=CRGB(rSec,gSec,bSec); hr=CRGB(rMin,gMin,bMin); min=CRGB(rHour,gHour,bHour); break; } case 5:{ Serial.println(&quot;SUCCESS6&quot;); min=CRGB(rSec,gSec,bSec); sec=CRGB(rMin,gMin,bMin); hr=CRGB(rHour,gHour,bHour); break; } } if(cCount==5) cCount=0; else cCount+=1; //Serial.println(&quot;=&quot;+String()+&quot; GMIN=&quot;+String(gMin)+&quot; =&quot;+String()); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T21:57:47.863", "Id": "247634", "Score": "4", "Tags": [ "arduino" ], "Title": "Control 30 LED NeoPixel clock with IR color and brightness changing" }
247634
<p>I have a list of 2,888,991 channel objects. Each object has a name and a sample rate. I am trying to put them into a QTreeView. Each channel name is split on ':' '-' and '_'. If the name is H1:IOP-LSC0_DCU_ID and the sample rate is 16.0 then it should go into the tree as:</p> <pre><code>H1 IOP LSC0 H1:IOP-LSC0_DCU_ID 16.0 </code></pre> <p>The split name is in the first column and the sample rate is in the second column.</p> <p>I have code that seems to accomplish this, but it takes a prohibitive amount of time to run. I am looking for suggestions on improving it, especially the speed.</p> <p>The code:</p> <pre><code>from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QHBoxLayout, QLabel, QStyleFactory, QTreeView, QTableView, QListView from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont from PyQt5.QtCore import QSize import nds2 import sys import re def find_or_add_and_return(parent, text_list): parent.setColumnCount(2) item_list = [QStandardItem(text) for text in text_list] # If the list has a length less than 2, then elements are appended until the list has a length of 2. # If the list has a length greater than 2, then all but the first 2 items are truncated. item_list.extend([QStandardItem()] * 2) item_list = item_list[0:2] assert (len(item_list) == parent.columnCount()) for r in range(parent.rowCount()): if item_list[0].text() == parent.child(r, 0).text() and item_list[1].text() == parent.child(r, 1).text(): return parent.child(r, 0) parent.appendRow(item_list) return parent.child(parent.rowCount() - 1, 0) class MainWindow(QMainWindow): def __init__(self): super(QMainWindow, self).__init__() centralWidget = QWidget() layout = QHBoxLayout() tree_view_model = QStandardItemModel() parent_item = tree_view_model.invisibleRootItem() conn = nds2.connection('h1nds1', 8088) channel_list = conn.find_channels() for channel in channel_list: text_list_list = [[x] for x in re.split('[:\-_]', channel.name, 3)] text_list_list[-1] = [channel.name, str(channel.sample_rate)] parent = parent_item for text_list in text_list_list: parent = find_or_add_and_return(parent, text_list) tree_view = QTreeView() tree_view.setHeaderHidden(True) tree_view.header().setSectionResizeMode(3) # QHeaderView::ResizeToContents tree_view.setModel(tree_view_model) layout.addWidget(tree_view) centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) app = QApplication([]) window = MainWindow() window.show() sys.exit(app.exec_()) </code></pre> <p>EDIT: This code seems faster:</p> <pre><code>from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QHBoxLayout, QLabel, QStyleFactory, QTreeView, QTableView, QListView from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont from PyQt5.QtCore import QSize import nds2 import sys import re class TrieNode(): def __init__(self, item): self.child_dict = {} self.item = item def insert(self, text_list, data): parent = self for text in text_list: if text in parent.child_dict: parent = parent.child_dict[text] else: item_list = [QStandardItem(text), QStandardItem()] parent.item.appendRow(item_list) parent.child_dict[text] = TrieNode(item_list[0]) parent = parent.child_dict[text] parent.item.appendRow([QStandardItem(data[0]), QStandardItem(data[1])]) class MainWindow(QMainWindow): def __init__(self): super(QMainWindow, self).__init__() centralWidget = QWidget() layout = QHBoxLayout() tree_view_model = QStandardItemModel() parent_item = tree_view_model.invisibleRootItem() conn = nds2.connection('h1nds1', 8088) channel_list = conn.find_channels() t = TrieNode(parent_item) for channel in channel_list: text_list = re.split('[:\-_]', channel.name, 5) del text_list[-1] t.insert(text_list, [channel.name, str(channel.sample_rate)]) tree_view = QTreeView() tree_view.setHeaderHidden(True) tree_view.header().setSectionResizeMode(3) # QHeaderView::ResizeToContents tree_view.setModel(tree_view_model) layout.addWidget(tree_view) centralWidget.setLayout(layout) self.setCentralWidget(centralWidget) app = QApplication([]) window = MainWindow() window.show() sys.exit(app.exec_()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T00:36:15.630", "Id": "484836", "Score": "1", "body": "I can't really help you with PyQt, but I can tell you that the secret to making a large tree like this is to NOT enumerate everything. Instead, build only the root level, and then fill in each level as it is expanded." } ]
[ { "body": "<p>I suspect there is more structure to your data than you are reporting.</p>\n<h1>Micro-optimizations</h1>\n<p>At the detail level, is it possible that there is a structure other than &quot;delimited by :, -, _&quot; to the names? Could the first field be always 2 characters? Are any of the subfields constant length? Do the delimiters always appear in a specific order?</p>\n<p>If you have subfields of a constant width, you can use a slice instead of a regex to extract them. It's a <em>lot</em> faster to say</p>\n<pre><code>f1 = name[0:2] \nf2 = name[3:6]\nf3 = name[7:11]\n</code></pre>\n<p>rather than</p>\n<pre><code>f = re.split(r'[-:_]', name)\n</code></pre>\n<p>Alternatively, some fields may be variable length, but if you can count on the sequence of delimiters you might be able to do something like this using <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=str%20partition#str.partition\" rel=\"nofollow noreferrer\"><code>str.partition</code></a>:</p>\n<pre><code>f1, _, rest = name.partition(':')\nf2, _, rest = rest.partition('-')\nf3, _, rest = rest.partition('_')\n</code></pre>\n<p>Using &quot;string methods&quot; instead of &quot;regex methods&quot; is frequently (but <strong>not</strong> always) faster.</p>\n<h1>Macro-optimizations</h1>\n<p>Can you &quot;step back&quot; from the problem and find a higher-level approach that would give better performance?</p>\n<p>In particular, I would suggest looking for a function or method in the <code>nds2</code> interface that allows you to extract some of the prefix data without pulling all the names.</p>\n<h2>Caching</h2>\n<p>If you can't get the data from the API, you should first submit a bug/enhancement/issue to the API guys explaining what you are doing and what support you <em>wish</em> you could get from them. They might be happy to add a call that would solve your problem for you.</p>\n<p>If not, consider building a local data structure <strong>not</strong> part of the Qt tree, and caching it.</p>\n<p>For example, you have a tree of prefixes. Convert that into a tree of dictionaries, and serialize it. You could create a user-local cache using <code>pickle</code> or if the data only rarely changes you might just create a <code>json</code> or <code>toml</code> file and ship it with your package.</p>\n<p>If you could get the first three levels of the tree stored as json, and if new high-level identifiers only appeared once a year when the budget expanded, you could do your updates manually.</p>\n<p>Alternatively, you might be able to perform a query, or have the API guys add a query, that let you ask &quot;are there any channel objects that don't match these first3 tree prefixes?&quot;</p>\n<h2>Late Querying</h2>\n<p>Especially in combination with caching, or a pre-built tree, above, @DavidG's suggestion to only build the parts of the tree you need makes <em>huge</em> amounts of sense. Why transfer 2+ million records when you only need to list 100?</p>\n<p>I couldn't find a <code>nds2</code> package on pypi, but I did see one called <code>nds2utils</code>. That package appears to support some kind of globbing for channel names, so I assume you can do a similar thing?</p>\n<p>Just query for <code>f&quot;{tree0}:{tree1}-{tree2}*&quot;</code> and you can get the values you need for the subtree below tree1/tree2/tree3. Hopefully that's something you can get fast enough to keep the interface snappy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:22:10.383", "Id": "247786", "ParentId": "247635", "Score": "1" } } ]
{ "AcceptedAnswerId": "247786", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T22:37:46.003", "Id": "247635", "Score": "6", "Tags": [ "python", "pyqt" ], "Title": "Putting millions of items in a QTreeView" }
247635
<p>I need some opinions about method naming and single responsibility principle.</p> <p>First of all, let's talk about method naming. The class below was created to provide a connection pool and whenever a pool is needed the <code>get_pool</code> is called. In the end <code>get_pool</code> will return a pool but the method will do more than only one responsibility, which is creating a pool if one doesn't exist and returning a pool. Besides, <code>get_pool name</code> is a very usual and comfortable name. Shouldn't something related to pool creation be mentioned in the method name, like <code>get_pool_or_create_if_not_exists()</code>?</p> <p>I understand that &quot;get&quot; methods should only do &quot;read&quot; operations but if you will do more than these then it should be mentioned in the method name, isn't it?</p> <pre><code>class DBPoolNameEnum(Enum): DESIGN = &quot;db&quot; CENTRAL = &quot;db_central&quot; class AsyncDatabasePoolManager: connection_pools = {} lock = asyncio.Lock() @staticmethod async def get_pool(db_pool_name_enum: DBPoolNameEnum): db_config = config[db_pool_name_enum.value] pool_name = db_pool_name_enum.value if pool_name not in AsyncDatabasePoolManager.connection_pools: async with AsyncDatabasePoolManager.lock: if pool_name not in AsyncDatabasePoolManager.connection_pools: AsyncDatabasePoolManager.connection_pools[pool_name] = await aiomysql.create_pool( maxsize=100, autocommit=True, pool_recycle=2 * 60 * 60, connect_timeout=2 * 60, conv=AsyncDatabasePoolManager._get_conversions(), user=db_config[&quot;user&quot;], password=db_config[&quot;password&quot;], host=db_config[&quot;host&quot;], db=db_config[&quot;database&quot;]) return AsyncDatabasePoolManager.connection_pools[pool_name] @staticmethod async def shutdown(): for pool in AsyncDatabasePoolManager.connection_pools.values(): pool.close() await pool.wait_closed() @classmethod def _get_conversions(cls): conversions[FIELD_TYPE.BIT] = ord return conversions </code></pre> <p>Continue the discussion, there is another implementation of this class (see below) which splits <code>get_pool</code> into two methods, one to create a pool and assign to a dict and another to get a pool from a dict.</p> <p>The way to use it is, in the beginning of the program, create a pool should be called and whenever a pool is needed <code>get_pool</code> should be called. If <code>get_pool</code> is called before <code>create_pool</code>, then an exception will be raised because a pool was never created.</p> <p>These approach intent to separate concerns and keep methods names concise.</p> <ol> <li>Does it make sense?</li> <li>What approach is better? Please consider which approach will be better understood for a future programmer, best practices of class design, best practice of naming conventions, etc.</li> </ol> <pre><code>class AsyncDatabasePoolManager: connection_pools = {} lock = asyncio.Lock() @staticmethod async def create_pool(pool_name, user, password, host, database): if pool_name not in AsyncDatabasePoolManager.connection_pools: async with AsyncDatabasePoolManager.lock: if pool_name not in AsyncDatabasePoolManager.connection_pools: AsyncDatabasePoolManager.connection_pools[pool_name] = await aiomysql.create_pool( maxsize=100, autocommit=True, pool_recycle=2 * 60 * 60, connect_timeout=2 * 60, # read_timeout=3*60, # write_timeout=3*60, conv=AsyncDatabasePoolManager._get_conversions(), user=user, password=password, host=host, db=database) @staticmethod def get_pool(pool_name): return AsyncDatabasePoolManager.connection_pools[pool_name] @staticmethod async def shutdown(): for pool in AsyncDatabasePoolManager.connection_pools.values(): pool.close() await pool.wait_closed() @classmethod def _get_conversions(cls): conversions[FIELD_TYPE.BIT] = ord return conversions <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T01:52:25.680", "Id": "247640", "Score": "3", "Tags": [ "python", "python-3.x", "design-patterns", "comparative-review", "connection-pool" ], "Title": "Providing a connection pool" }
247640
<p>Made an Angular app using Firebase, RXJS and NGRX.</p> <pre><code>@Effect() createQuiz$: Observable&lt;Action&gt; = this.actions$.pipe( ofType&lt;quizAction.CreateQuiz&gt;(quizAction.CREATE_QUIZ), switchMap((action) =&gt; { return this.quizService.createQuiz(action.payload) .pipe( map(() =&gt; { return new quizAction.CreateQuizCompleted() }), catchError(error =&gt; { console.log(error); return of(new quizAction.CreateQuizCompleted()); }) ); }) ); @Effect() updateQuiz$: Observable&lt;Action&gt; = this.actions$.pipe( ofType&lt;quizAction.UpdateQuiz&gt;(quizAction.UPDATE_QUIZ), switchMap((action) =&gt; { return this.quizService.updateQuiz(action.payload) .pipe( map(() =&gt; { return new quizAction.UpdateQuizCompleted() }), catchError(error =&gt; { console.log(error); return of(new quizAction.UpdateQuizCompleted()); }) ); }) ); @Effect() deleteQuiz$: Observable&lt;Action&gt; = this.actions$.pipe( ofType&lt;quizAction.DeleteQuiz&gt;(quizAction.DELETE_QUIZ), switchMap((action) =&gt; { return this.quizService.deleteQuiz(action.payload) .pipe( map(() =&gt; { return new quizAction.DeleteQuizCompleted() }), catchError(error =&gt; { console.log(error); return of(new quizAction.DeleteQuizCompleted()); }) ); }) ); </code></pre> <p>These are the NGRX effects. They are triggering a reducer function, then call a service function and then trigger another reducer function upon completion.</p> <pre><code>export class QuizComponent implements OnInit { constructor( private quizService: QuizService, private store:Store&lt;{app: fromApp.State}&gt;, ) { } ngOnInit(): void { } trackByIdx = (index: number): number =&gt; index; onCreate(): void { this.store.select(fromApp.selectUserId).pipe( take(1) ).subscribe(userId =&gt; this.handleCreate(userId)); } onDelete(id: string): void { this.store.dispatch(new AppAction.DeletePoll(id)); } onEdit(): void { let value = this.quizService.createCustomQuiz(); if (this.quizService.hasPermission(userId) &amp;&amp; this.pollService.validateQuiz(value)) { this.store.dispatch(new quizAction.UpdatePoll(value)); } } handleCreate(userId: string): void { let value = this.quizService.createDefaultQuiz(); if (this.quizService.hasPermission(userId) &amp;&amp; this.quizService.validateQuiz(value)) { this.store.dispatch(new quizAction.CreateQuiz(value)); } } } </code></pre> <p>This is the component that dispatches the actions.</p> <pre><code> createQuiz(quiz:Quiz) { const id = this.db.createId(); return from( this.db .collection('quizzes') .doc(id) .set({...quiz, id: id}) ); } updateQuiz(quiz:Quiz) { return from( this.db .collection('quizzes') .doc(quiz.id) .set(quiz, { merge: false }) ); } deleteQuiz(id:string) { return from( this.db .collection('quizzes') .doc(id) .delete() ); } </code></pre> <p>These are the service methods. I am wondering if there's any improvement and if switchmap and map are correctly used.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T03:31:07.243", "Id": "247641", "Score": "3", "Tags": [ "javascript", "angular-2+" ], "Title": "Simple Effects in Angular 2+ application using Firebase, NGRX and RXJS" }
247641
<p>I need some help with making my code run faster. It currently works by going through all cells in a 201x151 table. If the value in a cell is not equal to zero, then it will return the row number, the column number, and the actual value, and put it in a different table.</p> <p>Here is the code:</p> <pre><code>function rearranger() { var range = SpreadsheetApp.getActiveSheet().getRange('A2:C10000'); var ratings = SpreadsheetApp.getActiveSheet().getRange('TopChampionsVSUser!A1:EU201'); var iterationNumber = SpreadsheetApp.getActiveSheet().getRange('I1:I2').getValues(); var tr = SpreadsheetApp.getActiveSheet().getRange('L1').getCell(1, 1).getValue(); var r = iterationNumber[0]; var c = iterationNumber[1]; for(r; r &lt; 3000; r++){ SpreadsheetApp.getActiveSheet().getRange('I1').getCell(1, 1).setValue(r); if(c &gt;= 151){ c = 2; } for(c; c &lt; 152; c++){ SpreadsheetApp.getActiveSheet().getRange('I2').getCell(1, 1).setValue(c); var currentCellValue = ratings.getCell(r, c).getValue(); if(currentCellValue != 0){ range.getCell(tr, 1).setValue(r-1); range.getCell(tr, 2).setValue(ratings.getCell(1, c).getValue()); range.getCell(tr, 3).setValue(currentCellValue); tr++; SpreadsheetApp.getActiveSheet().getRange('L1').getCell(1, 1).setValue(tr); } } } } </code></pre> <p>Do you see something you think can be improved or made more efficient?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T06:21:15.577", "Id": "247644", "Score": "3", "Tags": [ "javascript", "performance", "google-apps-script", "google-sheets" ], "Title": "Rearranging data from one table to another in spreadsheets using apps script" }
247644
<p>I'm solving a problem on HackerRank where I'm required to implement a simple stack.</p> <p><a href="https://i.stack.imgur.com/Yn9aB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Yn9aB.png" alt="enter image description here" /></a></p> <p>It's passing all the tests except for the last 4 where it fails due to surpassing the time constraint of 10s. These 4 failing tests are running 200,000 operations on the stack.</p> <p>How can I optimize my code below:</p> <pre><code># operations of the form ['push -36', 'pop', 'push 16', 'pop', 'inc 1 -17', ...] from collections import deque def superStack(operations): def push(v): S.append(int(v)) def pop(): return S.pop() def inc(i,v): i, v = int(i), int(v) for pos in range(i): S[pos] += v S = deque() funcs = locals() for operation in operations: op, *args = operation.split(' ') funcs[op](*args) print(S[-1] if S else &quot;EMPTY&quot;) </code></pre> <hr /> <p>A few notes:</p> <ul> <li><p>Some constraints:</p> <p><a href="https://i.stack.imgur.com/jzfHd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jzfHd.png" alt="enter image description here" /></a></p> </li> <li><p>I've chosen <code>deque</code> over <code>list</code>, to avoid the &quot;contiguous memory block&quot; problem that lists may encounter.</p> </li> <li><p>Since <code>pop</code> and <code>append</code> are both O(1), the heaviest operation is the <code>inc</code> (especially so if <code>i</code> is large). So I keep all items as integers to avoid conversion from string to int multiple times in the <code>inc</code> loop</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T15:21:29.793", "Id": "484867", "Score": "0", "body": "Please link to the problem so we can try it ourselves." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T15:34:29.033", "Id": "484868", "Score": "0", "body": "@superbrain Unfortunately, I can't do that, I think it was part of a private test suite. And I no longer have access." } ]
[ { "body": "<p>Just be lazy. Don't do what you're told. They'll never know.</p>\n<p>Instead of truly increasing the bottom <code>i</code> values right away, just make a note at the <code>i</code>-th value from the bottom to increase it by <code>v</code> when it gets popped. And when that pop happens, move the note to the value below, so it gets increased by <code>v</code> as well (when it gets popped). And so on, so that this will add <code>v</code> to <em>all</em> bottom <code>i</code> values (when they get popped).</p>\n<p>To support multiple <code>inc</code> operations: If a value already has a note to add <code>w</code> to it (and all values below it), change that to <code>w + v</code>.</p>\n<p>For easier coding, just store <em>all</em> values along with such a note, but with initial adding value <code>0</code>.</p>\n<p>Now all three operations are O(1).</p>\n<p>Oh wait. Not quite O(1), since you're using a deque so you can't access an arbitrary index in O(1). That's actually a problem in your solution as well. Your increasing the bottom <code>i</code> values isn't O(i) but only O(i<sup>2</sup>). If you switch to a list, yours would be O(i) and mine would be O(1). This loses the O(1) of appending/popping to/from a deque, but the list still does them in <em>amortized</em> O(1). So then all three operations are amortized O(1). Alternatively you could keep your deque and store the notes in a separate <em>dict</em>, but then it's O(1) just as much as dict access is O(1) (i.e., not truly, but practically), and I suspect it would be a bit slower than the list version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-09T19:20:52.067", "Id": "507383", "Score": "0", "body": "How do you handle the case with multiple inc operations where the i value is lesser than previous inc operations. \nFor example: \n\n`['push 1', 'push 2', 'push 3', 'inc 3 5', 'inc 1 5']`\n\nSo the bottom-most element is now incremented by 10, while the top two are incremented by 5." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-09T19:30:24.047", "Id": "507384", "Score": "1", "body": "As described in the answer. There's nothing special about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-09T19:36:04.300", "Id": "507385", "Score": "0", "body": "+1, makes sense to me now, good solution!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T16:10:56.507", "Id": "247656", "ParentId": "247651", "Score": "8" } } ]
{ "AcceptedAnswerId": "247656", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T09:42:34.240", "Id": "247651", "Score": "7", "Tags": [ "python", "performance", "python-3.x", "stack" ], "Title": "Optimizing Efficiency in a Stack" }
247651
<p>I just created my first GTK+ 3 app with Python using <a href="https://pygobject.readthedocs.io/en/latest/" rel="nofollow noreferrer">PyGObject</a>. It is very nice to be able to make GTK applications using Python, as I love that language. I'm not completely sure if the way I designed the code is the most conventional and efficient way, so would like some people with more experience to take a look at it.</p> <p>It's a very simple app that can temporarily disable the automatic screen lock when your screensaver kicks in. Sometimes when I am watching a movie with my partner and we pause it to get some food, my screensaver kicks in and the computer is locked and I need to re-enter my password again. This is a bit annoying sometimes, so I made this little tool that temporarily disables the screen lock and enables it again after some time, so that my computer isn't left insecure.</p> <p>Here's the code:</p> <pre><code>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gio, GLib class ScreenLockDisableWindow(Gtk.Window): def __init__(self): super().__init__(title=&quot;Screen lock disable&quot;) self.screensaver_settings = Gio.Settings('org.gnome.desktop.screensaver') self.initial_lock_enabled = self.screensaver_settings.get_boolean('lock-enabled') self.main_ui_stack = Gtk.Stack() self.quantity_input = Gtk.SpinButton.new_with_range(min=1, max=60, step=1) self.unit_radio_minutes = Gtk.RadioButton.new_with_label_from_widget(None, &quot;minutes&quot;) self.unit_radio_hours = Gtk.RadioButton.new_with_label_from_widget(self.unit_radio_minutes, &quot;hours&quot;) self.time_left_label = Gtk.Label() self.seconds_left = 0 self.set_border_width(25) self.add(self.main_ui) def start(self): self.show_all() self.reinit_main_ui_stack() self.connect('destroy', self.exit) Gtk.main() def exit(self, app): self.screensaver_settings.set_boolean('lock-enabled', self.initial_lock_enabled) Gtk.main_quit() @property def main_ui(self): self.main_ui_stack.add_named(self.screen_lock_ui, 'main') self.main_ui_stack.add_named(self.timer_ui, 'timer') self.main_ui_stack.add_named(self.already_disabled_ui, 'already_disabled') return self.main_ui_stack def reinit_main_ui_stack(self): if self.seconds_left &gt; 0: self.main_ui_stack.set_visible_child_name('timer') elif not self.screensaver_settings.get_boolean('lock-enabled'): self.main_ui_stack.set_visible_child_name('already_disabled') else: self.main_ui_stack.set_visible_child_name('main') @property def screen_lock_ui(self): header_label = Gtk.Label(halign=Gtk.Align.START) header_label.set_markup('&lt;big&gt;&lt;b&gt;Screen lock&lt;/b&gt;&lt;/big&gt;') description_label = Gtk.Label( halign=Gtk.Align.START, label=&quot;Disable the screen lock for:&quot; ) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) box.add(header_label) box.add(description_label) box.add(self.time_picker) box.add(self.start_button) return box @property def time_picker(self): self.quantity_input.props.value = 1 radio_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) radio_box.add(self.unit_radio_minutes) radio_box.add(self.unit_radio_hours) box = Gtk.Box() box.add(self.quantity_input) box.add(radio_box) return box @property def start_button(self): button = Gtk.Button.new_with_label(&quot;Start&quot;) button.connect('clicked', self.on_start_button_click) return button def on_start_button_click(self, button): self.screensaver_settings.set_boolean('lock-enabled', False) quantity = int(self.quantity_input.get_text()) if self.unit_radio_hours.get_active(): minutes = 60 * quantity else: minutes = quantity self.seconds_left = minutes * 60 self.update_time_left_label() self.reinit_main_ui_stack() GLib.timeout_add_seconds(1, self.update_seconds_left) def update_seconds_left(self): self.seconds_left -= 1 self.update_time_left_label() self.update_lock_enabled() return self.seconds_left &gt; 0 def update_lock_enabled(self): if self.seconds_left &lt; 1: self.screensaver_settings.set_boolean('lock-enabled', True) self.reinit_main_ui_stack() def update_time_left_label(self): self.time_left_label.set_text(f&quot;{self.seconds_left} seconds&quot;) @property def timer_ui(self): header_label = Gtk.Label() header_label.set_markup(&quot;&lt;big&gt;&lt;b&gt;Screen lock disabled&lt;/b&gt;&lt;/big&gt;&quot;) message_label = Gtk.Label(&quot;Enabling screen lock again after:&quot;) enable_now_button = Gtk.Button.new_with_label(&quot;Enable now&quot;) enable_now_button.connect('clicked', self.on_enable_now_button_click) box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) box.add(header_label) box.add(message_label) box.add(self.time_left_label) box.add(enable_now_button) return box def on_enable_now_button_click(self, button): self.seconds_left = 0 self.update_lock_enabled() @property def already_disabled_ui(self): return Gtk.Label( halign=Gtk.Align.START, label=&quot;The screen lock is already disabled&quot; ) ScreenLockDisableWindow().start() </code></pre> <p>Some things I'm a bit confused about:</p> <ul> <li>I put the <code>Gtk.main()</code> and <code>Gtk.main_quit()</code> inside my window class. Not sure if this makes sense. If there are multiple window classes, how would GTK know which window to show?</li> <li>I used the <code>Gtk.Stack</code> widget to switch between views in the app. Is this the way to go, or would you normally use <code>hide()</code> and <code>show()</code> on the widgets? Seems to me that's more cumbersome. Also I noticed that <code>hide()</code>, <code>show()</code> and the <code>Gtk.Stack.set_visible_child_name()</code> methods don't seem to work in <code>__init__()</code> but do work in a callback function, from a button click for example. That's why I put the <code>reinit_main_ui_stack()</code> method in the <code>start()</code> method that is called after <code>__init__()</code>.</li> <li>Is there a way to add/remove widgets after initialization? Or re-render a widget so that you can give it new contents? I am coming from web development and am used to libraries like React where you have a <code>render()</code> method that re-renders the complete content of the component when it is called again, so you can easily set a new state, which re-renders the component, and in the render function you can have different content rendered with a different state. I guess that's not the way it is done in GTK+.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T22:30:21.117", "Id": "247659", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Ubuntu GTK+ 3 desktop app, made with Python library PyGObject" }
247659
<p>I'm working on some stuff that works better with (immutable async) linked lists such as this:</p> <pre><code>{ value: 'one', next: async () =&gt; { value: 'two', next: async () =&gt; null } } </code></pre> <p>Here <code>next</code> is an async function that returns either <code>null</code> or the next linked list. But I'd also be able to convert from and to iterables. So here is my <code>iterableToLinked</code> function:</p> <pre><code>Utils.iterableToLinked = async function(iterable) { var iterator = (iterable[Symbol.asyncIterator] || iterable[Symbol.iterator]).call(iterable); var cache = []; var listFromGenerator = async function(index) { var length = cache.length; if (index &lt; length) { return cache[index]; } else { var item = await iterator.next(); if (item.done) return null; cache.push({ value: item.value, next: async () =&gt; await listFromGenerator(length + 1) }); return await listFromGenerator(index); } }; return await listFromGenerator(0); }; </code></pre> <p>That method should work with iterables and iterators (since if I understand correctly, iterators are also iterables but not the other way around), both async and sync, so I can pass arrays, generators and async generators to it.</p> <p>For symmetry, I want the reverse function to return an iterable (not an iterator):</p> <pre><code>Utils.linkedToIterable = function(node) { return { [Symbol.asyncIterator]: async function*() { var current = node; while (current) { yield await current.value; current = await current.next(); } } }; } </code></pre> <p>I'm still a little confused with the difference between (sync and async) generators, iterables and iterators, so I wonder if anyone can spot issues with my code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T22:38:53.093", "Id": "247660", "Score": "2", "Tags": [ "javascript", "linked-list", "iterator", "async-await", "generator" ], "Title": "Async linked list to and from async iterable" }
247660
<p>Task:</p> <blockquote> <p>Write a function which returns true if a given substring is found within a given string. If the substring isn't found, then return false.</p> </blockquote> <p>My implementation:</p> <pre><code>#!/usr/bin/env ruby def custom_include?(string, substring) len = substring.size last_feasible = string.size - len for i in 0..last_feasible current_slice = string[i...i + len] if current_slice == substring return true end end false end puts custom_include? &quot;The Ruby Programming Language is amazing!&quot;, &quot;Language&quot; # true puts custom_include? &quot;The Ruby Programming Language is amazing!&quot;, &quot;language&quot; # false puts custom_include? &quot;The Ruby Programming Language is amazing!&quot;, &quot;amazing!&quot; # true puts custom_include? &quot;The Ruby Programming Language is amazing!&quot;, &quot;The&quot; # true puts custom_include? &quot;The Ruby Programming Language is amazing!&quot;, &quot;Test&quot; # false </code></pre> <p>Is there a way to avoid the <code>for</code>-loop? Should I try to &quot;save&quot; variables?</p> <p>Using variables make it easier for me to development a solution for such an exercise. Moreover I think it makes the script for readable and understandable. What's your opinion about that approach?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T06:22:07.843", "Id": "484891", "Score": "0", "body": "You could just do `def custom_include?(string, substring) string.include?(substring) end`. Nothing in the task prevents this and it sounds like they just want it as a function instead of a method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T20:15:21.433", "Id": "485755", "Score": "0", "body": "I would definitely add a test case where the substring is longer than the string." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T05:31:32.060", "Id": "247664", "Score": "1", "Tags": [ "strings", "ruby" ], "Title": "Custom include? method for a substring" }
247664
<p>This is an implementation of a dictionary (hash map) in Rust. It is loosely based on Python's dictionary implementation, using the same <a href="https://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l33" rel="noreferrer">&quot;random&quot; probing</a> and capacity/size management. Does it use too much memory or waste too many CPU cycles? Is it documented enough to be easily understood? I tried to mitigate the use of clone(), so let me know if I could have done more in that department.</p> <p>This is not meant to be a package, so it does not necessarily follow Cargo package guidelines. lib.rs contains unit tests, and dictionary.rs contains the struct and its methods.</p> <p>dictionary.rs</p> <pre class="lang-rust prettyprint-override"><code>use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::clone::Clone; use std::fmt; use std::fmt::Write; #[derive(Copy, Clone)] enum Bucket&lt;K: Clone, V: Clone&gt; { Entry((K, V, usize, usize)), Empty, Tombstone } /* capacity is the number of objects the dict can hold, resizes when * it is at 2/3 capacity * * size is the number of items in the dict, will never be more than * 2/3 capacity * * table is where the data is stored. it is in the format of a vec * full of Bucket enums, which either encode an empty spot, a * spot where an item was deleted, or an item * * This is meant to be a hashmap for keys that can be hashed */ pub struct Dictionary&lt;K: Clone + Hash, V: Clone&gt; { capacity: usize, size: usize, table: Vec&lt;Bucket&lt;K, V&gt;&gt; } #[allow(dead_code)] impl&lt;K: Clone + Hash + PartialEq, V: Clone&gt; Dictionary&lt;K, V&gt;{ pub fn new() -&gt; Dictionary&lt;K, V&gt; { Dictionary { capacity: 8, size: 0, table: vec![Bucket::Empty; 8] } } pub fn with_capacity(size: usize) -&gt; Dictionary&lt;K, V&gt; { if size == 0 { panic!(&quot;Cannot create a zero-sized dict&quot;); } Dictionary { capacity: size, size: 0, table: vec![Bucket::Empty; size] } } /* Performs a lookup using almost the exact same algorithm as insertion * Returns an Some(value) if the key exists, and None otherwise * Probing uses two numbers that are used in the calculation of each index: perturb and PERTURB_SHIFT * perturb is used in the calculating of the &quot;random&quot; probing and is shifted to the right by PERTURB_SHIFT * bits after every iteration in the probing */ fn lookup(&amp;self, key: &amp;K) -&gt; Option&lt;(K, V, usize)&gt; { let key_hash: usize = self.get_hash(&amp;key); let mut index = (key_hash % self.capacity) as usize; const PERTURB_SHIFT: u8 = 5; let mut perturb: usize = key_hash; loop { let current: Bucket&lt;K, V&gt; = self.table.get(index).unwrap().clone(); match current { Bucket::Entry(d) =&gt; { if d.0 == *key { break Some((d.0, d.1, index)); } else { perturb &gt;&gt;= PERTURB_SHIFT; index = ((5*index) + 1 + perturb) % self.capacity as usize; continue; } }, Bucket::Tombstone =&gt; { perturb &gt;&gt;= PERTURB_SHIFT; index = ((5*index) + 1 + perturb) % self.capacity as usize; continue; }, Bucket::Empty =&gt; { break None; } }; } } // Inserts new items without regard for size of the dict, it is separated from // the insert() function to prevent recursion on resizing. fn force_insert(&amp;mut self, key: K, value: V, key_hash: usize) { let mut index = (key_hash % self.capacity) as usize; const PERTURB_SHIFT: u8 = 5; let mut perturb: usize = key_hash; loop { let current: Bucket&lt;K, V&gt; = self.table.get(index).unwrap().clone(); match current { Bucket::Entry(d) =&gt; { if d.0 == key { self.table[index] = Bucket::Entry((d.0, value, d.2, index)); break; } else { perturb &gt;&gt;= PERTURB_SHIFT; index = ((5*index) + 1 + perturb) % self.capacity as usize; continue } }, _ =&gt; { self.table[index] = Bucket::Entry((key, value, key_hash, index)); break; } }; } } // Empties the table and makes a table twice the size, then reinserts all the entries fn resize(&amp;mut self, new_capacity: usize) { self.capacity = new_capacity; let _table = self.table.clone(); self.table = vec![Bucket::Empty; self.capacity]; for entry in _table.iter() { if let Bucket::Entry(d) = entry.clone() { self.force_insert(d.0, d.1, d.2); } } } //Checks if a resize is needed before inserting the new item, resizes if needed pub fn insert(&amp;mut self, key: K, value: V) { self.size += 1; if 2 * (self.capacity/3) &lt; self.size { // Double capacity if 2/3 full or more self.resize(2 * self.capacity); } let hash = self.get_hash(&amp;key); self.force_insert(key, value, hash); } //Returns a Result::Err if the vectors are different sizes pub fn from_vecs(mut key_vec: Vec&lt;K&gt;, mut value_vec: Vec&lt;V&gt;) -&gt; Dictionary&lt;K, V&gt; { if key_vec.len() != value_vec.len() { panic!(&quot;Differently sized vecs&quot;); } else if key_vec.is_empty() { panic!(&quot;Cannot create a zero-sized dict&quot;); } else { let mut dict: Dictionary&lt;K, V&gt; = Dictionary::with_capacity(key_vec.len()); for _ in 0..key_vec.len() { let key = key_vec.pop().unwrap(); let value = value_vec.pop().unwrap(); dict.insert(key, value); } dict } } pub fn from_tuples(tuples: Vec&lt;(K, V)&gt;) -&gt; Dictionary&lt;K, V&gt; { if tuples.is_empty() { panic!(&quot;Cannot create a zero-sized vec&quot;); } let mut dict: Dictionary&lt;K, V&gt; = Dictionary::with_capacity(tuples.len()); for (key, value) in tuples { dict.insert(key, value); } dict } pub fn size(&amp;self) -&gt; usize { self.size } pub fn capacity(&amp;self) -&gt; usize { self.capacity } pub fn get(&amp;self, key: &amp;K) -&gt; Result&lt;V, String&gt; { match self.lookup(key) { Some(v) =&gt; Ok(v.1), None =&gt; Err(format!(&quot;Key does not exist&quot;)) } } pub fn remove (&amp;mut self, key: &amp;K) -&gt; Option&lt;(K, V)&gt;{ let output: Option&lt;(K, V)&gt;; // If the key exists, remove it from the dictionary and add the key and value to the output match self.lookup(key) { Some(v) =&gt; { self.table[v.2] = Bucket::Tombstone; self.size -= 1; output = Some((v.0, v.1)); }, None =&gt; {output = None;} }; if self.size &lt; self.capacity/3 + 1 { // If current size is less than 2/3 half capacity, aka less than 1/3 capacity self.resize(self.capacity/2); } output } pub fn contains(&amp;self, key: &amp;K) -&gt; bool { self.lookup(key).is_some() } fn get_hash(&amp;self, key: &amp;K) -&gt; usize { let mut s = DefaultHasher::new(); key.hash(&amp;mut s); s.finish() as usize } // Returns a vector of keys contained in the dict pub fn keys(&amp;self) -&gt; Vec&lt;&amp;K&gt; { let mut key_vec: Vec&lt;&amp;K&gt; = Vec::new(); for item in self.table.iter() { if let Bucket::Entry(n) = item { key_vec.push(&amp;n.0); } } key_vec } // Returns a vector of values contained in the dict pub fn values(&amp;self) -&gt; Vec&lt;&amp;V&gt; { let mut value_vec: Vec&lt;&amp;V&gt; = Vec::new(); for item in self.table.iter() { if let Bucket::Entry(n) = item { value_vec.push(&amp;n.1); } } value_vec } // Returns a vector of (key, value) tuples containing every // key value pairing in the dict pub fn items(&amp;self) -&gt; Vec&lt;(&amp;K, &amp;V)&gt; { let mut item_vec: Vec&lt;(&amp;K, &amp;V)&gt; = Vec::new(); for item in self.table.iter() { if let Bucket::Entry(n) = item { item_vec.push((&amp;n.0, &amp;n.1)); } } item_vec } } impl&lt;K, V&gt; fmt::Display for Dictionary&lt;K, V&gt; where K: fmt::Display + Clone + Hash, V: fmt::Display + Clone { fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result { let mut output_str = String::new(); output_str.push_str(&quot;{&quot;); for k in self.table.iter() // Iterate over all buckets containing an entry .filter(|v| match v { Bucket::Entry(_n) =&gt; true, _ =&gt; false }) { if let Bucket::Entry(d) = k { write!(output_str, &quot;{}: {}, &quot;, d.0, d.1)?; } } let len = output_str.len(); if len &gt; 1 { output_str = String::from(&amp;output_str[..len - 2]); } output_str.push_str(&quot;}&quot;); write!(f, &quot;{}&quot;, output_str) } } </code></pre> <p>lib.rs</p> <pre class="lang-rust prettyprint-override"><code>mod dictionary; use dictionary::Dictionary; /* * Creates the dictionary * { * 1: 6, * 2: 7, * 3: 8, * 4: 9, * 5: 0 * } */ #[allow(dead_code)] fn create_dict() -&gt; Dictionary&lt;u8, u8&gt; { let tuples: Vec&lt;(u8, u8)&gt; = vec![(1, 6), (2, 7), (3, 8), (4, 9), (5, 0)]; Dictionary::from_tuples(tuples) } #[allow(dead_code)] fn has_same_elements&lt;T: PartialEq&gt;(vec1: &amp;Vec&lt;T&gt;, vec2: &amp;Vec&lt;T&gt;) -&gt; bool { for i in vec1 { if vec2.contains(i) { continue; } return false; } true } #[cfg(test)] mod tests{ use super::*; #[test] fn make_dict() { let _d: Dictionary&lt;u8, u8&gt; = Dictionary::new(); assert_eq!(_d.capacity(), 8); } #[test] fn create_sized() { let _d: Dictionary&lt;u8, u8&gt; = Dictionary::with_capacity(16); assert_eq!(_d.capacity(), 16); } #[test] #[should_panic] fn zero_sized_dict() { let _d: Dictionary&lt;u8, u8&gt; = Dictionary::with_capacity(0); } #[test] fn create_from_vecs() { let vec1: Vec&lt;usize&gt; = vec![1, 2, 3, 4, 5]; let vec2: Vec&lt;usize&gt; = vec![6, 7, 8, 9, 0]; let _d: Dictionary&lt;usize, usize&gt; = Dictionary::from_vecs(vec1, vec2); assert_eq!(_d.size(), 5); } #[test] fn create_from_tuples() { let tuples: Vec&lt;(u8, u8)&gt; = vec![(1, 2), (3, 4)]; let _d: Dictionary&lt;u8, u8&gt; = Dictionary::from_tuples(tuples); assert_eq!(_d.get(&amp;1).unwrap(), 2); } #[test] #[should_panic] fn zero_sized_tuple_dict() { let tuples: Vec&lt;(u8, u8)&gt; = Vec::new(); let _d: Dictionary&lt;u8, u8&gt; = Dictionary::from_tuples(tuples); } #[test] #[should_panic] fn paniced_from_vecs() { let vec1: Vec&lt;usize&gt; = vec![1, 2, 3, 4]; let vec2: Vec&lt;usize&gt; = vec![5, 6, 7]; let _d = Dictionary::from_vecs(vec1, vec2); } #[test] #[should_panic] fn zero_sized_vecs() { let vec1: Vec&lt;u8&gt; = Vec::new(); let vec2: Vec&lt;u8&gt; = Vec::new(); let _d = Dictionary::from_vecs(vec1, vec2); } #[test] fn lookup() { let _d = create_dict(); assert_eq!(_d.get(&amp;1).unwrap(), 6); } #[test] fn insert() { let mut _d: Dictionary&lt;u8, u8&gt; = Dictionary::new(); _d.insert(1, 2); assert_eq!(_d.get(&amp;1).unwrap(), 2); } #[test] fn size() { let _d = create_dict(); assert_eq!(_d.size(), 5); } #[test] fn resize() { let mut _d: Dictionary&lt;u8, u8&gt; = Dictionary::with_capacity(4); assert_eq!(_d.capacity(), 4); for i in 0..4{ _d.insert(i, i); } assert_eq!(_d.capacity(), 8); } #[test] fn contains() { let mut _d = create_dict(); assert!(_d.contains(&amp;1)); } #[test] fn remove() { let mut _d = create_dict(); let _r = _d.remove(&amp;1); assert!((!_d.contains(&amp;1)) &amp;&amp; _r.is_some() &amp;&amp; _r.unwrap() == (1, 6) &amp;&amp; _d.size() == 4); } #[test] fn down_size() { let mut _d = create_dict(); _d.remove(&amp;1); _d.remove(&amp;2); assert_eq!(_d.capacity(), 5); } #[test] fn remove_panic() { let mut _d: Dictionary&lt;u8, u8&gt; = Dictionary::new(); _d.remove(&amp;1); } #[test] fn keys() { let _d = create_dict(); let expected_keys: Vec&lt;u8&gt; = vec![1, 2, 3, 4, 5]; let keys = _d.keys().into_iter().map(|x| *x).collect(); assert!(has_same_elements(&amp;keys, &amp;expected_keys)); } #[test] fn values() { let _d = create_dict(); let expected_values: Vec&lt;u8&gt; = vec![6, 7, 8, 9, 0]; let values = _d.values().into_iter().map(|x| *x).collect(); assert!(has_same_elements(&amp;values, &amp;expected_values)); } #[test] fn items() { let tuples: Vec&lt;(u8, u8)&gt; = vec![(1, 6), (2, 7), (3, 8), (4, 9), (5, 0)]; let _t = tuples.clone(); let _d: Dictionary&lt;u8, u8&gt; = Dictionary::from_tuples(_t); let expected_items = _d.items().into_iter().map(|x| (*x.0, *x.1)).collect(); assert!(has_same_elements(&amp;expected_items, &amp;tuples)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T03:55:37.663", "Id": "484981", "Score": "1", "body": "Just asking: is there some specific reason that prevents you from sticking to the standard guidelines?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-18T22:00:44.070", "Id": "489297", "Score": "0", "body": "Use [Rustdoc](https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html) documentation instead of `/* ... */` comments to document your functions. It will allow you to generate nice HTML documentation." } ]
[ { "body": "<pre><code>#[derive(Copy, Clone)]\nenum Bucket&lt;K: Clone, V: Clone&gt; {\n Entry((K, V, usize, usize)),\n Empty,\n Tombstone\n}\n</code></pre>\n<p>The general recommendation is not to put type constraints on your structs/enums but only on your impls. This enum works fine K and V aren't clone, so you don't need restrictions.</p>\n<pre><code>pub struct Dictionary&lt;K: Clone + Hash, V: Clone&gt; {\n capacity: usize,\n size: usize,\n table: Vec&lt;Bucket&lt;K, V&gt;&gt;\n}\n</code></pre>\n<p><code>capacity</code> is just <code>table.len()</code> You don't really need your own copy of the vec length, just use the one on Vec.</p>\n<pre><code>fn lookup(&amp;self, key: &amp;K) -&gt; Option&lt;(K, V, usize)&gt; { \n</code></pre>\n<p>Throughout your api you return Clones of your keys and values. This generally decreases the usefulness of your implementation because it is only useful for things with cheap clones. Generally, such an item returns borrows not object to overcome this.</p>\n<pre><code> let mut index = (key_hash % self.capacity) as usize;\n</code></pre>\n<p>You unnecessarily cast to usize a lot. As long as you stick to usize you shouldn't be needing to cast at all.</p>\n<pre><code> let current: Bucket&lt;K, V&gt; = self.table.get(index).unwrap().clone();\n</code></pre>\n<p>If you are just going to <code>.unwrap()</code> how about using <code>self.table[index]</code> instead?</p>\n<pre><code>pub fn from_vecs(mut key_vec: Vec&lt;K&gt;, mut value_vec: Vec&lt;V&gt;) -&gt; Dictionary&lt;K, V&gt; {\n</code></pre>\n<p>Typically such methods would be defined to a generatic Iterator or IntoIter rather than being restricted to Vec.</p>\n<pre><code>pub fn from_tuples(tuples: Vec&lt;(K, V)&gt;) -&gt; Dictionary&lt;K, V&gt; {\n</code></pre>\n<p>Rust has a standard interface: std::iter::FromIterator which would typically want to implement in this case.</p>\n<pre><code>pub fn get(&amp;self, key: &amp;K) -&gt; Result&lt;V, String&gt; {\n</code></pre>\n<p>Typically, looking up a missing a key wouldn't be considered an error and would return Option rather than Error. As it stands creating an error with a String will be somewhat ineffecient because it'll allocate memory for the string.</p>\n<pre><code>pub fn keys(&amp;self) -&gt; Vec&lt;&amp;K&gt; {\n</code></pre>\n<p>Such functions are typically implemented as Iterators not Vecs.</p>\n<pre><code>impl&lt;K, V&gt; fmt::Display for Dictionary&lt;K, V&gt;\n</code></pre>\n<p>This should probably be implementing std::fmt::Debug instead</p>\n<pre><code> let mut output_str = String::new();\n output_str.push_str(&quot;{&quot;);\n</code></pre>\n<p>Firstly, its not helpful to build your String and write it into the formatter, just write directly to the formatter. Secondly, Formatter has a number of methods to help write debug style format like this. In particular, checkout the debug_map() method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:49:33.303", "Id": "485298", "Score": "0", "body": "Thank you for the advice!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T04:22:38.267", "Id": "247703", "ParentId": "247665", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T06:45:33.620", "Id": "247665", "Score": "5", "Tags": [ "rust", "hash-map" ], "Title": "Dictionary implementation in Rust" }
247665
<p>In what way can I improve this? Be that performance, readability, etc. I'm thinking implementing NumPy would improve performance.</p> <p>Usage: Calculate* the nth factorial of n 1s in a row.</p> <p>*No need for a precise calculation. Magnitude and leading digits is enough.</p> <p>Examples:</p> <p>2nd factorial of 11. (11 x 9 x 7 x 5 x 3 x 1)</p> <p>3rd factorial of 111. (111 x 108 x 105....)</p> <p>...</p> <pre><code>import multiprocessing import argparse import datetime import math parser = argparse.ArgumentParser( formatter_class=argparse.HelpFormatter, description=&quot;Calcs x factorial&quot;, usage=&quot;&quot; ) parser.add_argument(&quot;-n&quot;, &quot;--number&quot;, type=int) args = parser.parse_args() def first_n_digits(num, n): return num // 10 ** (int(math.log(num, 10)) - n + 1) def getones(): if args.number == 1 : print(1) exit() num = &quot;&quot; for _ in range(0, args.number) : num += &quot;&quot;.join(&quot;1&quot;) return int(num) def getlog(send_end, i, threads, num): inc = int(num/threads) inc -= int(inc%args.number) start = num-inc*i end = num-inc*(i+1) if i &lt; threads-1 else 0 output = 0 for j in range(start, end, -args.number): if j &gt; 0: output += math.log10(j) send_end.send(output) def main(): num = getones() threads = multiprocessing.cpu_count() if getones()/multiprocessing.cpu_count() &gt; multiprocessing.cpu_count() else 1 jobs = [] pipe_list = [] for i in range(threads): recv_end, send_end = multiprocessing.Pipe(False) p = multiprocessing.Process(target=getlog, args=(send_end, i, threads, num)) jobs.append(p) pipe_list.append(recv_end) p.start() i = 0 for proc in jobs: proc.join() i+=1 result_list = [output.recv() for output in pipe_list] magnitude = int(sum(result_list)) normalized = 10**(sum(result_list)-magnitude) fnd = str(first_n_digits(normalized, 3)) print(&quot;{}.{}{}e{}&quot;.format(fnd[0], fnd[1], fnd[2], magnitude)) if __name__ == '__main__': start = datetime.datetime.now() main() end = datetime.datetime.now() print(end-start) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T08:13:58.797", "Id": "484894", "Score": "0", "body": "When I try to run it, I get `TypeError: 'NoneType' object cannot be interpreted as an integer`: https://repl.it/repls/FearfulGruesomeParameters#main.py" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T08:22:25.547", "Id": "484895", "Score": "0", "body": "What's the largest n you need to handle?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T08:38:43.397", "Id": "484896", "Score": "0", "body": "@superbrain This is moreso a personal project, so as high as I can make it within a reasonable amount of time lmao. The error is because it doesn't have an argument passed to it and I haven't assigned a default value yet (or any error handling) because I haven't had a need." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T00:03:53.910", "Id": "484970", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>One thing I'd change is to not use <code>args</code> everywhere. You use the name &quot;n&quot; in the problem description, so I'd use that in the program as well. Reading <code>args</code> only once, to store the value in <code>n</code>.</p>\n<p>Your <code>getones</code> function is rather lengthy and inefficient, taking O(n<sup>2</sup>) time to build the string. Although the rest of the program can't handle large n anyway, so efficiency doesn't really matter here. (And maybe the conversion to <code>int</code> takes quadratic time, not sure.)</p>\n<p>Here's a shorter solution:</p>\n<pre><code>e = sum(map(log10, range(int('1' * n), 0, -n)))\nprint('%.2fe%d' % (10**(e % 1), e // 1))\n</code></pre>\n<p>Demo:</p>\n<pre><code>&gt;&gt;&gt; n = 9\n&gt;&gt;&gt; from math import log10\n&gt;&gt;&gt; e = sum(map(log10, range(int('1' * n), 0, -n)))\n&gt;&gt;&gt; print('%.2fe%d' % (10**(e % 1), e // 1))\n9.22e93968682\n</code></pre>\n<p>Comparison with yours (<a href=\"https://repl.it/repls/JealousWornKeyboardmapping#main.py\" rel=\"nofollow noreferrer\">at repl.it</a>) for n=9, same result and mine's about three times as fast:</p>\n<pre><code>n = 9\nyours:\n9.22e93968682\n0:00:11.911943\nmine:\n9.22e93968682\n0:00:03.964518\n</code></pre>\n<p>We have a different result for example for n=2:</p>\n<pre><code>n = 2\nyours:\n1.03e4\n0:00:00.011884\nmine:\n1.04e4\n0:00:00.000085\n</code></pre>\n<p>The exact result is:</p>\n<pre><code>&gt;&gt;&gt; math.prod(range(11, 0, -2))\n10395\n</code></pre>\n<p>So I'd say yours isn't rounding correctly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T21:16:09.693", "Id": "484955", "Score": "0", "body": "Interesting, I haven't done the string multiplication before, and I can definitely see how that would be more efficient. From my understanding, everything else is effectively the same as what I'm doing, just a little more condensed? (and rounding instead of truncating)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T22:52:56.760", "Id": "484961", "Score": "0", "body": "@Kadragon Yeah, I guess effectively the same, as I see sum and logarithm in yours as well. To be honest, I didn't read it fully, you kinda lost me at multiprocessing :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T23:49:48.297", "Id": "484968", "Score": "0", "body": "Haha, I lost myself a few times when doing it. After implementing some of your suggestions It's gone from 1m 16s to 50s on my machine. Main impact was the sum(map(log10....)))(slightly adjusted for parallelization). Doing it as a map instead of a for loop must've been more efficient. I'm going to update the code block if you want to take a look and see if they're anything I missed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:50:09.660", "Id": "247686", "ParentId": "247666", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T07:47:19.577", "Id": "247666", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "nth Factorial of n 1s in a row" }
247666
<p>I started to code in c++ recently and my goal is to develop games using c++. After learning basics I tried to implement my own version of snake console based game in c++ with the help of some online tutorials. I used OOP approach. I would like to hear ideas about this code and what mistakes i have made or ways to improve/optimize this code. I really value your opinions. Thank you!.</p> <p><a href="https://i.stack.imgur.com/J452E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J452E.png" alt="enter image description here" /></a></p> <pre><code>#include &lt;iostream&gt; #include &lt;Windows.h&gt; #include &lt;sstream&gt; #include &lt;thread&gt; #include &lt;list&gt; #include &lt;chrono&gt; #include &quot;main.h&quot; using namespace std::chrono_literals; //initialize console/window variables const int SCREEN_WIDITH = 120; const int SCREEN_HEIGHT = 30; const int HORIZONTAL_OFFSET = 20; const int VERTICAL_OFFSET = 5; static wchar_t* screen = new wchar_t[SCREEN_WIDITH * SCREEN_HEIGHT]; //enum to set snake move direction enum EDirection { UP, DOWN, LEFT, RIGHT }; //point objects defines x,y cordinates in the screen buffer struct Point { int m_X{}; int m_Y{}; Point(int x, int y) :m_X(x),m_Y(y) { } Point() { } //copy contructer to determine two points are equals/unequals bool operator==(const Point&amp; other) { return (m_X == other.m_X) &amp;&amp; (m_Y == other.m_Y) ? true : false; } }; //food class creates an object which can be consumed by snake class Food { private: Point m_CurrentPosiiton; //gives currrent position of the spawned food public: Food() { MoveFood(); //initial position update for food } void MoveFood() { //determining a random location within boundries to spawn food //rand()%(max-min+1)+min; m_CurrentPosiiton.m_X = rand() % (SCREEN_WIDITH - 2 * HORIZONTAL_OFFSET) + HORIZONTAL_OFFSET+1; m_CurrentPosiiton.m_Y = rand() % (SCREEN_HEIGHT- 3*VERTICAL_OFFSET +1) + VERTICAL_OFFSET; //if the determined positon is already have a character then determine again if (screen[m_CurrentPosiiton.m_X + m_CurrentPosiiton.m_Y * SCREEN_WIDITH] != L' ') { MoveFood(); } } //draws food to screen void DrawFood() { screen[m_CurrentPosiiton.m_X+ m_CurrentPosiiton.m_Y*SCREEN_WIDITH] = L'%'; } //getter to get current postion of food Point GetCurrenPos() { return m_CurrentPosiiton; } }; //snake class creates an snake object which user can control class Snake { private: unsigned char m_Size = 5; //size of the snake Point m_DefaultPosition{ 60,12 }; //initial start positon of snake std::list&lt;Point&gt; m_SnakeBody; //snake body represented as a list of points wchar_t snakeArt = L'O'; //snake art for drawing snake public: Snake(unsigned char size) : m_Size(size) { //constrcuter automatically determines snake body positions for (int i = 0; i &lt; m_Size; i++) { m_SnakeBody.push_back({ m_DefaultPosition.m_X+i,m_DefaultPosition.m_Y}); } } //used to update snake art void ChangeSnakeArt(const wchar_t&amp; art) { snakeArt = art; } //draws snake body in to screen void DrawSnake() const { for (const Point &amp;point : m_SnakeBody) { screen[point.m_X + SCREEN_WIDITH * point.m_Y ] = snakeArt; } } //Updates snakes body after eating food void IncreaseSize() { m_Size++; m_SnakeBody.push_back({ GeTailPos().m_X+1,GeTailPos().m_Y }); } //Handles movement of snake based on player inputs void MoveSnake(const EDirection&amp; direction) { switch (direction) { case UP: m_SnakeBody.push_front({ m_SnakeBody.front().m_X, m_SnakeBody.front().m_Y - 1 }); m_SnakeBody.pop_back(); break; case DOWN: m_SnakeBody.push_front({ m_SnakeBody.front().m_X, m_SnakeBody.front().m_Y + 1 }); m_SnakeBody.pop_back(); break; case LEFT: m_SnakeBody.push_front({ m_SnakeBody.front().m_X - 1, m_SnakeBody.front().m_Y }); m_SnakeBody.pop_back(); break; case RIGHT: m_SnakeBody.push_front({ m_SnakeBody.front().m_X + 1, m_SnakeBody.front().m_Y }); m_SnakeBody.pop_back(); break; } } //check if snake hits its own body bool HitSelf() { for(auto i= m_SnakeBody.begin();i!=m_SnakeBody.end();i++) { if(m_SnakeBody.begin()!=i) { if(GetHeadPos()==*i) { return true; } } } return false; } //helper to get snake head coordinates Point GetHeadPos() { return m_SnakeBody.front(); } //helper to get snake tail coordinates Point GeTailPos() { return m_SnakeBody.back(); } }; //to draw level borders void DrawLevel(wchar_t* screen) { //Draw top &amp; bottom horizontal line for (int i = 0; i &lt; (SCREEN_WIDITH - HORIZONTAL_OFFSET * 2); i++) { screen[SCREEN_WIDITH * 4 + HORIZONTAL_OFFSET + i] = L'_'; screen[SCREEN_WIDITH * 20 + HORIZONTAL_OFFSET + i] = L'_'; } //Draw vertical left &amp; right line for (int i = VERTICAL_OFFSET - 1; i &lt;= SCREEN_HEIGHT - VERTICAL_OFFSET * 2; i++) { screen[SCREEN_WIDITH * i + HORIZONTAL_OFFSET] = L'|'; screen[SCREEN_WIDITH * i + HORIZONTAL_OFFSET * 5] = L'|'; } } void ClearScreen() { //Clear screen for (int i = 0; i &lt; SCREEN_HEIGHT * SCREEN_WIDITH; i++) { screen[i] = L' '; } } void DrawInfo(const int&amp; score) { //Draw Stats &amp; Border for (int i = 0; i &lt; SCREEN_WIDITH; i++) { screen[i] = L'='; screen[SCREEN_WIDITH * 2 + i] = L'='; } wsprintf(&amp;screen[SCREEN_WIDITH + 3], L&quot;Verison:1 Saki Games - SNAKE!! SCORE: %d&quot;,score); } void DrawEndScreen() { wsprintf(&amp;screen[23*SCREEN_WIDITH + 45], L&quot;GAME OVER - PRESS SPACE TO RESTART&quot;); } int main() { // Create Screen Buffer for (int i = 0; i &lt; SCREEN_WIDITH * SCREEN_HEIGHT; i++) screen[i] = L' '; HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL); SetConsoleActiveScreenBuffer(hConsole); DWORD dwBytesWritten = 0; while (1) { Snake snake = Snake(5); Food food = Food(); bool isDead{}; int score{}; EDirection snakeDirection = EDirection::LEFT; while (!isDead) { //Timing &amp; input auto t1 = std::chrono::system_clock::now(); while ((std::chrono::system_clock::now() - t1)&lt;200ms) { if (GetAsyncKeyState(VK_LEFT) &amp;&amp; snakeDirection != EDirection::RIGHT) { snakeDirection = EDirection::LEFT; } else if (GetAsyncKeyState(VK_RIGHT) &amp;&amp; snakeDirection != EDirection::LEFT) { snakeDirection = EDirection::RIGHT; } else if (GetAsyncKeyState(VK_UP) &amp;&amp; snakeDirection != EDirection::DOWN) { snakeDirection = EDirection::UP; } else if (GetAsyncKeyState(VK_DOWN) &amp;&amp; snakeDirection != EDirection::UP) { snakeDirection = EDirection::DOWN; } } //Game Logic snake.MoveSnake(snakeDirection); //Colision detection if (snake.GetHeadPos() == food.GetCurrenPos()) { score++; food.MoveFood(); snake.IncreaseSize(); } //Colision detection with self isDead = snake.HitSelf(); //Coliision detection with boundry for (int i = 0; i &lt; (SCREEN_WIDITH - HORIZONTAL_OFFSET * 2); i++) { int snakeCor = snake.GetHeadPos().m_X + SCREEN_WIDITH * snake.GetHeadPos().m_Y; if (((SCREEN_WIDITH * 4 + HORIZONTAL_OFFSET + i) == (snakeCor)) || ((SCREEN_WIDITH * 20 + HORIZONTAL_OFFSET + i) == (snakeCor))) { isDead = true; } } for (int i = VERTICAL_OFFSET - 1; i &lt;= SCREEN_HEIGHT - VERTICAL_OFFSET * 2; i++) { int snakeCor = snake.GetHeadPos().m_X + SCREEN_WIDITH * snake.GetHeadPos().m_Y; if (((SCREEN_WIDITH * i + HORIZONTAL_OFFSET) == (snakeCor)) || ((SCREEN_WIDITH * i + HORIZONTAL_OFFSET * 5) == (snakeCor))) { isDead = true; } } //Draw stuff to screen ClearScreen(); DrawInfo(score); DrawLevel(screen); //check for dead condition if (isDead) { DrawEndScreen(); snake.ChangeSnakeArt(L'X'); } //draws snake and food to screen snake.DrawSnake(); food.DrawFood(); //Display Frame WriteConsoleOutputCharacter(hConsole, screen, SCREEN_WIDITH * SCREEN_HEIGHT, { 0,0 }, &amp;dwBytesWritten); } //wait till space bar input to restart game while (GetAsyncKeyState(VK_SPACE) == 0); } return 0; } </code></pre>
[]
[ { "body": "<p>According to <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">S</a> from SOLID objects should have only one responsibility. Therefore I would move draw and input logic from current objects into a separate one. It could be something like UI and InputController classes. The idea here is to hide all I/O related stuff in a way that allows changing I/O without changing game logic. It is a very common problem and popular solution is called <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC</a></p>\n<p>Another thing that I would improve is the code in the main function - it could be moved into Game class. Game class may contain UI, InputController, and GameLogic (the place were all game rules live)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T04:47:52.617", "Id": "484985", "Score": "0", "body": "Cool suggestion. I'll use these techniques in my next console game. Thank you for the answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T11:07:25.327", "Id": "247671", "ParentId": "247667", "Score": "2" } }, { "body": "<p>To start, I think you should be proud of your work so far! There are still many ways to improve (I'm not going to cover all of them) but now you can say you have created a fun game in C++ and show it to your friends and family and the internet. Many people cannot say that.</p>\n<h1>Grouping and Naming</h1>\n<p>Regardless of which paradigm you're aiming for, this is a fundamental concept of programming that just takes different forms based on which paradigm and language you're working in. It is clear that you have this concept in mind but it's so fundamental that I will expand on it further.</p>\n<h2>Naming Meaningful Operations</h2>\n<p>Within your code you represent the screen as a one dimensional array and frequently access it like so <code>screen[x + y * screen_width]</code>. This isn't a meaningless fragment of some strange formula, this formula is how you access an (x, y) coordinate of your screen representation. In the context of OOP, you could create a screen class containing a member function that serves this purpose, so instead of writing screen[x + y * SCREEN_WIDTH] you would write screen.at(x, y). Notice that now you only have to make sure the calculation is correct on one line of code instead of like 8++.</p>\n<h2>Grouping and Naming Meaningful Data</h2>\n<p>Within your code the variables SCREEN_WIDITH, SCREEN_HEIGHT, and screen appear together frequently. These values work together to describe the visual state of your application. In the context of OOP classes are employed so you could create a class called Screen to hold these three variables. Notice now that if you have to pass this information on to another function, class, thread, etc... you only have to worry about one variable of type Screen instead of three of types (wchar_t*, int, int).</p>\n<h2>Grouping Meaningful Data and Operations</h2>\n<p>Having code that is conceptually related grouped together means it is easier to find, consume and understand. (Whether through a plain header file, a class, or any other grouping method). The advantages of this become clearer in larger projects when you are either searching for the definition of data that a function works on, searching for functionality related to some data definition, or trying to figure out the concepts behind some code.</p>\n<h2>Un-grouping Meaningless Data and Operations</h2>\n<p>Within your main function you have the variable dwBytesWritten which holds how many bytes have been written to the window. main() is an important function because it (usually) communicates every single thing our application is doing, and so it is essential to understanding any application. dwBytesWritten could not be less important to understanding how this snake game works, so we should un-group them. Now I personally don't think it has much meaning anywhere else at the moment but, since I'm assuming it is required for WriteConsoleOutputCharacter, the most logical place to put it is the Screen class.</p>\n<p>So we apply these concepts to the screen representation and we arrive at this</p>\n<pre><code>class Screen\n{\nprivate:\n const int WIDTH;\n const int HEIGHT;\n wchar_t *screen;\n HANDLE hConsole;\n DWORD dwBytesWritten;\n\npublic:\n Screen(int width, int height) : WIDTH(width),\n HEIGHT(height),\n dwBytesWritten(0)\n {\n this-&gt;screen = new wchar_t[this-&gt;WIDTH * this-&gt;HEIGHT];\n this-&gt;clear();\n this-&gt;hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);\n SetConsoleActiveScreenBuffer(this-&gt;hConsole);\n }\n\n ~Screen()\n {\n CloseHandle(this-&gt;hConsole);\n delete[] this-&gt;screen;\n }\n\n void clear()\n {\n for (int i = 0; i &lt; this-&gt;WIDTH * this-&gt;HEIGHT; ++i)\n this-&gt;screen[i] = L' ';\n }\n\n wchar_t &amp;at(int x, int y)\n {\n return this-&gt;screen[x + y * this-&gt;WIDTH];\n }\n\n const wchar_t &amp;at(int x, int y) const\n {\n return this-&gt;at(x, y);\n }\n\n void display()\n {\n WriteConsoleOutputCharacter(this-&gt;hConsole, this-&gt;screen, this-&gt;WIDTH * this-&gt;HEIGHT, {0, 0}, &amp;this-&gt;dwBytesWritten);\n }\n\n int getWidth() const\n {\n return this-&gt;WIDTH;\n }\n\n int getHeight() const\n {\n return this-&gt;HEIGHT;\n }\n};\n</code></pre>\n<p>Now the start of main would look like</p>\n<pre><code>int main()\n{\n Screen screen(120, 30);\n\n while (1)\n {\n Snake snake = ...\n</code></pre>\n<p>and your Food::DrawFood member function would look like</p>\n<pre><code>void DrawFood(Screen&amp; screen)\n{\n screen.at(m_CurrentPosiiton.m_X, m_CurrentPosiiton.m_Y) = L'%';\n}\n</code></pre>\n<p>It's important to not be blind to the fact that the class itself generates more lines of code than if we hadn't grouped anything. This is why it is important not to apply the concepts without thought: we must always try to know that the benefits of the decisions we are making right now outweigh the drawbacks. This is not easy, but to get you started consider how sooo many classes are using the horizontal and vertical offset. Why should Food have to know it's absolute position in the console, rather than just where it is within the arena. Wouldn't it simplify many calculations if the top left square of the snake arena could be called (0, 0) instead of (horizontalOffset, verticalOffset)?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T04:46:58.720", "Id": "484984", "Score": "0", "body": "First of all thank you for your valuable input. You have shown me many areas which can improve and most importantly you have given me confidence to do more these stuff. So thank you you for that. I clearly understand every thing you are suggesting and i'm gonna use it on my next console game. Again thank you for taking your valuable time to write this awesome review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T20:15:04.063", "Id": "247694", "ParentId": "247667", "Score": "3" } } ]
{ "AcceptedAnswerId": "247694", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T08:32:06.673", "Id": "247667", "Score": "5", "Tags": [ "c++", "object-oriented", "game", "console", "snake-game" ], "Title": "Object oriented approach for snake game in C++" }
247667
<p>Based on this question: <a href="https://codereview.stackexchange.com/questions/247632/heaviest-stone-algorithm-time-complexity">Heaviest Stone algorithm time complexity</a></p> <blockquote> <p>Problem:</p> <p>We have a collection of stones, each stone has a positive integer weight.</p> <p>Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x &lt;= y. The result of this smash is:</p> <p>If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)</p> </blockquote> <p>I implemented an <code>O(n * log(n))</code> solution using <code>std::*_heap</code> functions in C++.</p> <p>Since those functions have an optional generic argument - the comparision function - I decided to implement my functions with that generic argument as well.</p> <pre><code>#include &lt;algorithm&gt; template&lt;class Iterator, class Compare&gt; typename Iterator::value_type stone_smash_destructive(Iterator first, Iterator last, Compare comp) { std::make_heap(first, last, comp); while (first &lt; last) { std::pop_heap(first, last--, comp); auto y = *last; if (first &lt; last) { std::pop_heap(first, last--, comp); auto x = *last; if (comp(x, y)) { *last = y - x; std::push_heap(first, ++last, comp); } } else { return y; } } return {0}; } #include &lt;functional&gt; template&lt;class Iterator&gt; typename Iterator::value_type stone_smash_destructive(Iterator first, Iterator last) { return stone_smash_destructive(first, last, std::less&lt;typename Iterator::value_type&gt;()); } #include &lt;vector&gt; template&lt;class Iterator&gt; std::vector&lt;typename Iterator::value_type&gt; make_vector(Iterator first, Iterator last) { return {first, last}; } template&lt;class Iterator, class Compare&gt; typename Iterator::value_type stone_smash(Iterator first, Iterator last, Compare comp) { auto v = make_vector(first, last); return stone_smash_destructive(v.begin(), v.end(), comp); } template&lt;class Iterator&gt; typename Iterator::value_type stone_smash(Iterator first, Iterator last) { auto v = make_vector(first, last); return stone_smash_destructive(v.begin(), v.end()); } </code></pre> <p>To take use of it I implemented a comparator that counts number of it's invocations.</p> <pre><code>#include &lt;cstddef&gt; template&lt;class BinaryCondition&gt; struct binary_condition_counter { std::size_t &amp; count; BinaryCondition condition; public: using result_type = typename BinaryCondition::result_type; using first_argument_type = typename BinaryCondition::first_argument_type; using second_argument_type = typename BinaryCondition::second_argument_type; binary_condition_counter(std::size_t &amp; count, BinaryCondition &amp;&amp; condition): count(count), condition(condition) {} bool operator () (first_argument_type a, second_argument_type b) const { ++count; return condition(a, b); } }; #include &lt;utility&gt; template&lt;class BinaryCondition&gt; binary_condition_counter&lt;BinaryCondition&gt; make_binary_condition_counter(std::size_t &amp; count, BinaryCondition &amp;&amp; condition) { return {count, std::move(condition)}; } </code></pre> <p>The code of the tests may be a bit messy and they just spit out the numbers of comparisions to the <code>std::cout</code> but I am not much concerned about that.</p> <pre><code>#include &lt;cassert&gt; #include &lt;iostream&gt; void test_stone_smash(std::size_t expected, std::vector&lt;std::size_t&gt; v) { std::size_t count = 0; auto comp = make_binary_condition_counter(count, std::less&lt;std::size_t&gt;()); assert(expected == stone_smash(v.begin(), v.end(), comp)); assert(expected == stone_smash(v.cbegin(), v.cend(), comp)); assert(expected == stone_smash_destructive(v.begin(), v.end(), comp)); std::cout &lt;&lt; &quot;{&quot;; if (v.size()) { auto limit = v.end() - 1; for (auto i = v.begin(); i &lt; limit; ++i) { std::cout &lt;&lt; *i &lt;&lt; &quot;, &quot;; } std::cout &lt;&lt; *limit; } std::cout &lt;&lt; &quot;}(&quot; &lt;&lt; v.size() &lt;&lt; &quot;): &quot; &lt;&lt; count / 3 &lt;&lt; &quot; comparisions.\n&quot;; } void test_stone_smashes_logarithmic(std::size_t exp, std::size_t base = 2) { assert(exp &lt; 23); std::size_t count; auto comp = make_binary_condition_counter(count, std::less&lt;std::size_t&gt;()); std::size_t limit = ipow(base, exp) + 1; std::vector&lt;std::size_t&gt; v; v.reserve(limit); std::size_t mod = base; for (std::size_t i = 1; i &lt;= limit; ++i) { v.push_back(i); if (i % mod == 0 || (mod &gt; base &amp;&amp; (i - 1) % (mod / base) == 0)) { count = 0; auto result = stone_smash(v.begin(), v.end(), comp); std::cout &lt;&lt; &quot;[1, &quot; &lt;&lt; i &lt;&lt; &quot;] = &quot; &lt;&lt; result &lt;&lt; &quot;: &quot; &lt;&lt; count &lt;&lt; &quot; comparisions.\n&quot;; assert(((i - 1) % 4 &lt; 2 ? 1 : 0) == result); if (i % mod == 0) { mod *= base; } } } } void test_stone_smashes_linear(std::size_t n, std::size_t step = 1, std::size_t start = 1) { std::size_t count; auto comp = make_binary_condition_counter(count, std::less&lt;std::size_t&gt;()); std::vector&lt;std::size_t&gt; v; v.reserve(n); for (std::size_t i = 0; i &lt; n; ++i) { auto val = start + i * step; v.push_back(val); count = 0; auto result = stone_smash(v.begin(), v.end(), comp); std::cout &lt;&lt; &quot;[&quot; &lt;&lt; start &lt;&lt; &quot;, &quot; &lt;&lt; val &lt;&lt; &quot;](n=&quot; &lt;&lt; i + 1 &lt;&lt; &quot;,step=&quot;&lt;&lt; step &lt;&lt; &quot;) = &quot; &lt;&lt; result &lt;&lt; &quot;: &quot; &lt;&lt; count &lt;&lt; &quot; comparisions.\n&quot;; if (step == 1 &amp;&amp; start == 1) { assert(((val - 1) % 4 &lt; 2 ? 1 : 0) == result); } } } int main() { test_stone_smash({0}, {}); test_stone_smash({0}, {0}); test_stone_smash({2}, {0, 1, 2, 5}); test_stone_smash({1}, {1}); test_stone_smash({0}, {5, 5}); test_stone_smash({1}, {1, 2}); test_stone_smash({1}, {2, 1}); test_stone_smash({0}, {3, 1, 2}); test_stone_smash({1}, {1, 2, 3, 4, 5}); test_stone_smash({0}, {1, 1, 2, 3, 5, 8, 13, 21}); test_stone_smash({4}, {1, 3, 8}); test_stone_smashes_logarithmic(20); test_stone_smashes_linear(2000); test_stone_smashes_linear(100, 3); return 0; } </code></pre> <p>I am more concerned about standard algorithm and templates usage. For example, is there a standard alternative to my make_vector function with type deduction?</p> <p>Also I know I should use some testing framework, but I am not concerned about that as well. Actually with asserts it should be just copy-paste from this post without need to install additional libs.</p> <p>The <code>ipow(base, exponent)</code> (used in tests) is just an exponentiation <code>base^exponent</code>, I am not including it here.</p> <p>The <code>#include</code>s are located above the code that uses them but I am not actualy showing the file system structure. Module separation is also no concern here.</p> <p>But of course, feel free to comment on anything you want :)</p> <p>The tests output:</p> <pre><code>{}(0): 0 comparisions. {0}(1): 0 comparisions. {2, 2, 3, 5}(4): 12 comparisions. {1}(1): 0 comparisions. {5, 5}(2): 2 comparisions. {1, 2}(2): 2 comparisions. {1, 2}(2): 2 comparisions. {1, 1, 3}(3): 6 comparisions. {1, 1, 1, 3, 5}(5): 19 comparisions. {1, 1, 2, 2, 5, 8, 8, 21}(8): 36 comparisions. {4, 5, 8}(3): 6 comparisions. [1, 2] = 1: 2 comparisions. [1, 3] = 0: 6 comparisions. [1, 4] = 0: 12 comparisions. [1, 5] = 1: 19 comparisions. [1, 8] = 0: 42 comparisions. [1, 9] = 1: 47 comparisions. [1, 16] = 0: 108 comparisions. [1, 17] = 1: 115 comparisions. [1, 32] = 0: 263 comparisions. [1, 33] = 1: 270 comparisions. [1, 64] = 0: 629 comparisions. [1, 65] = 1: 638 comparisions. [1, 128] = 0: 1450 comparisions. [1, 129] = 1: 1465 comparisions. [1, 256] = 0: 3296 comparisions. [1, 257] = 1: 3303 comparisions. [1, 512] = 0: 7350 comparisions. [1, 513] = 1: 7365 comparisions. [1, 1024] = 0: 16250 comparisions. [1, 1025] = 1: 16278 comparisions. [1, 2048] = 0: 35607 comparisions. [1, 2049] = 1: 35571 comparisions. [1, 4096] = 0: 77263 comparisions. [1, 4097] = 1: 77261 comparisions. [1, 8192] = 0: 166782 comparisions. [1, 8193] = 1: 166815 comparisions. [1, 16384] = 0: 358181 comparisions. [1, 16385] = 1: 358585 comparisions. [1, 32768] = 0: 766300 comparisions. [1, 32769] = 1: 765531 comparisions. [1, 65536] = 0: 1629347 comparisions. [1, 65537] = 1: 1629708 comparisions. [1, 131072] = 0: 3455996 comparisions. [1, 131073] = 1: 3455976 comparisions. [1, 262144] = 0: 7305131 comparisions. [1, 262145] = 1: 7307617 comparisions. [1, 524288] = 0: 15401610 comparisions. [1, 524289] = 1: 15413884 comparisions. [1, 1048576] = 0: 32400609 comparisions. [1, 1048577] = 1: 32380097 comparisions. ... </code></pre> <p>To compile: <code>g++ -Wall -std=c++17 stone_smash_test.cpp -o stone_smash_test</code></p> <pre><code>$ g++ --version g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T09:26:05.600", "Id": "247668", "Score": "3", "Tags": [ "c++", "algorithm", "programming-challenge" ], "Title": "Smashing two heaviest stones until at most one stone is left - counting number of stone comparisions" }
247668
<p>I started learning programming about a year ago, starting with Python. Half a year ago, I moved onto C++ and this is my first large project with that language. Have I understood the basics of the language?</p> <p>In Main.cpp:</p> <pre><code>#pragma warning(disable : 4996) #pragma warning(disable : 4244) #include &lt;memory&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;SFML\Graphics.hpp&gt; #include &quot;Snake.h&quot; #include &quot;SnakeFood.h&quot; #include &quot;HighScoreFile.h&quot; class Snake; class SnakeFood; class HighScoreFile; void displayScores(sf::RenderWindow&amp; window, HighScoreFile&amp; highScorefile, int score, const sf::Font&amp; font); void displayNewBest(sf::RenderWindow&amp; window, const sf::Font&amp; font); bool playAgain(sf::RenderWindow&amp; window); std::unique_ptr&lt;sf::Font&gt; newFont(std::string&amp;&amp; fileName); std::unique_ptr&lt;sf::SoundBuffer&gt; newSoundBuffer(std::string&amp;&amp; fileName); int main() { srand(time(NULL)); static auto scoredSoundBuffer = newSoundBuffer(&quot;Sound Effects\\Scored.wav&quot;); static auto celebrationSoundbuffer = newSoundBuffer(&quot;Sound Effects\\Celebration.wav&quot;); static auto defeatSoundBuffer = newSoundBuffer(&quot;Sound Effects\\Defeat.wav&quot;); static auto startupSoundBuffer = newSoundBuffer(&quot;Sound Effects\\Startup.wav&quot;); sf::Sound scoredSoundEffect{ *scoredSoundBuffer }; sf::Sound celebrationSoundEffect{ *celebrationSoundbuffer }; sf::Sound defeatSoundEffect{ *defeatSoundBuffer }; sf::Sound startupSoundEffect{ *startupSoundBuffer }; scoredSoundEffect.setVolume(30.f); celebrationSoundEffect.setVolume(30.f); defeatSoundEffect.setVolume(30.f); startupSoundEffect.setVolume(30.f); static auto gameTextFont = newFont(&quot;Arcade Classic.ttf&quot;); sf::RenderWindow window(sf::VideoMode(665, 595), &quot;Snake&quot;, sf::Style::Close | sf::Style::Titlebar); while (true) { Snake snake{}; SnakeFood food{ window, snake }; int score{ 0 }; HighScoreFile highScoreFile{ &quot;high-score-file.txt&quot; }; startupSoundEffect.play(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::W: case sf::Keyboard::Up: snake.changeDirection(Direction::Up); break; case sf::Keyboard::S: case sf::Keyboard::Down: snake.changeDirection(Direction::Down); break; case sf::Keyboard::A: case sf::Keyboard::Left: snake.changeDirection(Direction::Left); break; case sf::Keyboard::D: case sf::Keyboard::Right: snake.changeDirection(Direction::Right); break; } break; case sf::Event::Closed: exit(0); break; default: //No need to handle unrecognised events break; } } snake.checkIfOutOfBounds(window); snake.move(); if (snake.isTouchingFood(food)) { scoredSoundEffect.play(); snake.grow(); score++; food.setToRandomPosition(window, snake); } window.clear(sf::Color::Black); snake.drawBody(window); window.draw(food); sf::Text scoreText{ std::to_string(score), *gameTextFont, 30 }; scoreText.setPosition(10.f, 5.f); window.draw(scoreText);; window.display(); if (snake.isTouchingSelf()) { if (score &gt; highScoreFile.getHighScore()) { celebrationSoundEffect.play(); displayNewBest(window, *gameTextFont); highScoreFile.editHighScore(score); _sleep(1500); } else { defeatSoundEffect.play(); } _sleep(1000); displayScores(window, highScoreFile, score, *gameTextFont); if (!playAgain(window)) { exit(0); } break; } } } return 0; } void displayScores(sf::RenderWindow&amp; window, HighScoreFile&amp; highScoreFile, int score, const sf::Font&amp; font) { window.clear(sf::Color::Black); sf::Text scoreText{ &quot;SCORE: &quot; + std::to_string(score), font, 90 }; if (score &lt; 10) { scoreText.setPosition(85.f, 85.f); } else { scoreText.setPosition(55.f, 85.f); } //scoreText.setPosition(85.f, 85.f); scoreText.setFillColor(sf::Color::Green); sf::Text highScoreText{ &quot;HI SCORE: &quot; + std::to_string(highScoreFile.getHighScore()), font, 80 }; highScoreText.setFillColor(sf::Color::Green); if (highScoreFile.getHighScore() &lt; 10) { highScoreText.setPosition(40.f, 375.f); } else { highScoreText.setPosition(10.f, 375.f); } //highScoreText.setPosition(40.f, 375.f); window.draw(scoreText); window.draw(highScoreText); window.display(); } void displayNewBest(sf::RenderWindow&amp; window, const sf::Font&amp; font) { sf::Text newBest{ &quot;NEW BEST!&quot;, font, 75 }; newBest.setPosition(110.f, 250.f); newBest.setFillColor(sf::Color::Red); window.draw(newBest); window.display(); } bool playAgain(sf::RenderWindow&amp; window) { while (true) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } switch (event.key.code) { case sf::Keyboard::Q: return false; break; case sf::Keyboard::Z: return true; break; default: //No need to handle unrecognised events break; } } } } std::unique_ptr&lt;sf::Font&gt; newFont(std::string&amp;&amp; fileName) { auto font = std::make_unique&lt;sf::Font&gt;(); if (!font-&gt;loadFromFile(fileName)) { exit(0); } return font; } std::unique_ptr&lt;sf::SoundBuffer&gt; newSoundBuffer(std::string&amp;&amp; fileName) { auto buffer = std::make_unique&lt;sf::SoundBuffer&gt;(); if (!buffer-&gt;loadFromFile(fileName)) { exit(0); } return buffer; } </code></pre> <p>In SnakeRect.h:</p> <pre><code>#pragma once #include &lt;SFML\Graphics.hpp&gt; enum class Direction { Left, Right, Up, Down }; class SnakeRect : public sf::RectangleShape { using RectangleShape::RectangleShape; public: SnakeRect(Direction dir); Direction direction() const; Direction oppositeDirection() const; private: Direction direction_; }; </code></pre> <p>In SnakeRect.cpp:</p> <pre><code>#include &quot;SnakeRect.h&quot; SnakeRect::SnakeRect(Direction dir) : RectangleShape{}, direction_{ dir } { } Direction SnakeRect::direction() const { return direction_; } Direction SnakeRect::oppositeDirection() const { switch (direction_) { case Direction::Up: return Direction::Down; break; case Direction::Down: return Direction::Up; break; case Direction::Right: return Direction::Left; break; case Direction::Left: return Direction::Right; break; default: break; } } </code></pre> <p>In Snake.h:</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;SFML/Audio.hpp&gt; #include &quot;SnakeRect.h&quot; #include &quot;SnakeFood.h&quot; class Snake { public: Snake(); Snake(sf::Vector2f startingPos, Direction startingDir); bool isTouchingFood(const SnakeFood&amp; food); bool isTouchingSelf(); void move(); void changeDirection(Direction dir); void checkIfOutOfBounds(const sf::RenderWindow&amp; window); void grow(); void drawBody(sf::RenderWindow&amp; window); friend class SnakeFood; private: std::vector&lt;SnakeRect&gt; body_; static const float thickness; static const float speed; static const sf::Color color; static const float startingLength; static const sf::Vector2f defaultStartingPos; static const Direction defaultStartingDir; }; </code></pre> <p>In Snake.cpp:</p> <pre><code>#pragma warning(disable : 4996) #include &lt;chrono&gt; #include &quot;Snake.h&quot; const float Snake::thickness{ 35.f }; const float Snake::speed{ 35.f }; const sf::Color Snake::color{ sf::Color::Green }; const float Snake::startingLength{ 3.f }; const sf::Vector2f Snake::defaultStartingPos{280.f, 280.f}; const Direction Snake::defaultStartingDir{Direction::Right}; Snake::Snake() : Snake{defaultStartingPos, defaultStartingDir} { } Snake::Snake(sf::Vector2f startingPos, Direction startingDir) { SnakeRect newRect{ startingDir }; newRect.setSize(sf::Vector2f(startingLength*speed, (float)thickness)); newRect.setPosition(startingPos); newRect.setFillColor(color); body_.push_back(newRect); } bool Snake::isTouchingFood(const SnakeFood&amp; food) { const SnakeRect&amp; frontRect{ (body_.at(body_.size() - 1)) }; return (frontRect.getGlobalBounds().intersects(food.getGlobalBounds())); } bool Snake::isTouchingSelf() { SnakeRect&amp; frontRect{ body_.at(body_.size() - 1) }; for (auto it = body_.begin(); it != std::prev(body_.end()); it++) { if (frontRect.getGlobalBounds().intersects(it-&gt;getGlobalBounds())) { return true; } } return false; } void Snake::move() { SnakeRect&amp; backRect{ body_.at(0) }; SnakeRect&amp; frontRect{ body_.at(body_.size() - 1) }; for (int i{ 0 }; i &lt; 2; i++) { SnakeRect&amp; currentRect{ (i == 0) ? backRect : frontRect }; float modifier{ (i == 0) ? -(float)speed : (float)speed }; switch (currentRect.direction()) { case Direction::Up: currentRect.setSize(sf::Vector2f(currentRect.getSize().x, (currentRect.getSize().y) + modifier)); currentRect.move(0, (i == 1) ? -modifier : 0); break; case Direction::Down: currentRect.setSize(sf::Vector2f(currentRect.getSize().x, (currentRect.getSize().y) + modifier)); currentRect.move(0, (i == 0) ? fabs(modifier) : 0); break; case Direction::Left: currentRect.setSize(sf::Vector2f((currentRect.getSize().x) + modifier, currentRect.getSize().y)); currentRect.move((i == 1) ? -modifier : 0, 0); break; case Direction::Right: currentRect.setSize(sf::Vector2f((currentRect.getSize().x) + modifier, currentRect.getSize().y)); currentRect.move((i == 0) ? fabs(modifier) : 0, 0); break; default: //Will never execute since Direction is an enum break; } } if (backRect.getSize().x &lt;= 0 || backRect.getSize().y &lt;= 0) { body_.erase(body_.begin() + 0); } _sleep(150); } void Snake::changeDirection(Direction dir) { SnakeRect frontRect{ body_.at(body_.size() - 1) }; float frontRectX{ frontRect.getPosition().x }; float frontRectY{ frontRect.getPosition().y }; if (dir != frontRect.direction() &amp;&amp; dir != frontRect.oppositeDirection()) { float xPosition{}; float yPosition{}; switch (frontRect.direction()) //Can shorten this down, will look into it { case Direction::Up: xPosition = (dir == Direction::Left ? frontRectX : frontRectX + (float)thickness); yPosition = frontRectY; break; case Direction::Down: xPosition = (dir == Direction::Left ? frontRectX : frontRectX + float(thickness)); yPosition = frontRectY + frontRect.getSize().y - (float)thickness; break; case Direction::Right: xPosition = frontRectX + frontRect.getSize().x - (float)thickness; yPosition = (dir == Direction::Up ? frontRectY : frontRectY + (float)thickness); break; case Direction::Left: xPosition = frontRectX; yPosition = (dir == Direction::Up ? frontRectY : frontRectY + (float)thickness); break; default: break; //Will never execute } float xSize{ (dir == Direction::Up || dir == Direction::Down) ? (float)thickness : 0.f }; float ySize{ (dir == Direction::Up || dir == Direction::Down) ? 0.f : (float)thickness }; SnakeRect newRect{dir}; newRect.setSize(sf::Vector2f(xSize, ySize)); newRect.setPosition(xPosition, yPosition); newRect.setFillColor(sf::Color::Green); body_.push_back(newRect); } } void Snake::checkIfOutOfBounds(const sf::RenderWindow&amp; window) { const SnakeRect&amp; frontRect{ body_.at(body_.size() - 1) }; float xPositionWithSize{ frontRect.getPosition().x + frontRect.getSize().x }; float yPositionWithSize{ frontRect.getPosition().y + frontRect.getSize().y }; bool isLeft{ frontRect.direction() == Direction::Left }; bool isRight{ frontRect.direction() == Direction::Right }; bool isUp{ frontRect.direction() == Direction::Up }; bool isDown{ frontRect.direction() == Direction::Down }; bool xOutOfBounds{ (frontRect.getPosition().x - (isLeft ? (float)speed : 0.f)) &lt; 0 || xPositionWithSize + (isRight ? (float)speed : 0.f) &gt; window.getSize().x }; bool yOutOfBounds{ (frontRect.getPosition().y - (isUp ? (float)speed : 0.f)) &lt; 0 || yPositionWithSize + (isDown ? (float)speed : 0.f) &gt; window.getSize().y }; if (xOutOfBounds || yOutOfBounds) { SnakeRect newRect{frontRect.direction()}; newRect.setFillColor(sf::Color::Green); sf::Vector2f newRectSize{}; sf::Vector2f newRectPos{}; switch (frontRect.direction()) { case Direction::Up: newRectSize = sf::Vector2f((float)thickness, 0.f); newRectPos = sf::Vector2f(frontRect.getPosition().x, (float)window.getSize().y); break; case Direction::Down: newRectSize = sf::Vector2f((float)thickness, 0.f); newRectPos = sf::Vector2f(frontRect.getPosition().x, 0.f); break; case Direction::Right: newRectSize = sf::Vector2f(0.f, (float)thickness); newRectPos = sf::Vector2f(0.f, frontRect.getPosition().y); break; case Direction::Left: newRectSize = sf::Vector2f(0.f, (float)thickness); newRectPos = sf::Vector2f((float)window.getSize().x, frontRect.getPosition().y); break; default: break; } newRect.setSize(newRectSize); newRect.setPosition(newRectPos); body_.push_back(newRect); } } void Snake::grow() { SnakeRect&amp; backRect{ body_.at(0) }; switch (backRect.direction()) { case Direction::Up: backRect.setSize(sf::Vector2f(backRect.getSize().x, (backRect.getSize().y) + (float)speed)); break; case Direction::Down: backRect.setSize(sf::Vector2f(backRect.getSize().x, (backRect.getSize().y) + (float)speed)); backRect.move(0, -(float)speed); break; case Direction::Left: backRect.setSize(sf::Vector2f((backRect.getSize().x) + (float)speed, backRect.getSize().y)); break; case Direction::Right: backRect.setSize(sf::Vector2f((backRect.getSize().x) + (float)speed, backRect.getSize().y)); backRect.move(-(float)speed, 0); break; default: //Will never execute since Direction is an enum break; } } void Snake::drawBody(sf::RenderWindow&amp; window) { for (const SnakeRect&amp; rect : body_) { window.draw(rect); } } </code></pre> <p>In SnakeFood.h:</p> <pre><code>#pragma once #include &lt;SFML\Graphics.hpp&gt; class Snake; class SnakeFood : public sf::RectangleShape { using RectangleShape::RectangleShape; public: SnakeFood(const sf::RenderWindow&amp; window, const Snake&amp; snake); bool isTouching(const Snake&amp; snake); void setToRandomPosition(const sf::RenderWindow&amp; window, const Snake&amp; s); }; </code></pre> <p>In SnakeFood.cpp:</p> <pre><code>#include &quot;SnakeFood.h&quot; #include &quot;Snake.h&quot; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; SnakeFood::SnakeFood(const sf::RenderWindow&amp; window, const Snake&amp; snake) : RectangleShape{} { setSize(sf::Vector2f(15.f, 15.f)); setFillColor(sf::Color::Red); setToRandomPosition(window, snake); } void SnakeFood::setToRandomPosition(const sf::RenderWindow&amp; window, const Snake&amp; snake) { do { float xPosition, yPosition; xPosition = float(rand() % (window.getSize().x - int(getSize().x))); yPosition = float(rand() % (window.getSize().y - int(getSize().y))); setPosition(xPosition, yPosition); } while (isTouching(snake)); } bool SnakeFood::isTouching(const Snake&amp; s) { for (const SnakeRect&amp; rect : s.body_) { if (rect.getGlobalBounds().intersects(this-&gt;getGlobalBounds())) { return true; } } return false; } </code></pre> <p>In HighScoreFile.h:</p> <pre><code>#pragma once #include &lt;fstream&gt; class HighScoreFile { public: HighScoreFile(std::string fileName); int getHighScore(); void editHighScore(int score); private: const std::string highScoreFileName_; std::fstream highScoreFile_; }; </code></pre> <p>In HighScoreFile.cpp:</p> <pre><code>#include &quot;HighScoreFile.h&quot; HighScoreFile::HighScoreFile(const std::string fileName) : highScoreFileName_{fileName} { } int HighScoreFile::getHighScore() { highScoreFile_.open(highScoreFileName_, std::ios::in); if (!highScoreFile_){ exit(0); } int highScore{}; highScoreFile_ &gt;&gt; highScore; highScoreFile_.close(); return highScore; } void HighScoreFile::editHighScore(int score) { highScoreFile_.open(highScoreFileName_, std::ios::out, std::ios::trunc); if (!highScoreFile_) { exit(0); } highScoreFile_ &lt;&lt; score; highScoreFile_.close(); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T11:06:26.423", "Id": "484901", "Score": "0", "body": "Why did you disable these warning numbers? What exactly are they telling you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T11:20:05.733", "Id": "484902", "Score": "0", "body": "@πάνταῥεῖ One of them just warned me about the loss of data occouring with srand(time(NULL)), and the other warned me about using _sleep() but I have read online that using _sleep() works just fine. So I figured I didn't need those warnings" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T11:57:44.553", "Id": "484903", "Score": "0", "body": "Well, there are casts and `std::thread::sleep`; fixing warnings is always better than disabling them. It also makes the code unportable, not all c++ compilers use the same warning numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T13:04:16.040", "Id": "484905", "Score": "0", "body": "@πάνταῥεῖ Okay, got it. I'll remove the warning disablers and fix the actual warnings. Thanks!" } ]
[ { "body": "<h1>1) Remove unused headers</h1>\n<p>You don't need <code>stdlib.h</code> and <code>stdio.h</code>. These are C headers, and you'll rarely use them in C++ (and if you need to use them, use <code>cstdlib</code> and <code>cstdio</code>). Similarly, don't use <code>time.h</code> in C++; C++ provides much better functionality in the form of the <code>chrono</code> library.</p>\n<h1>2)Forward declarations</h1>\n<p>You don't need to forward declare your classes, since you're already including them.</p>\n<h1>3) Random number generation</h1>\n<p>Don't use <code>srand</code> and <code>rand</code>. These are C methods for random number generations, and truthfully aren't that random at all. Prefer using <code>random</code> library provided by the STL.</p>\n<h1>4) Static</h1>\n<p>Your use of <code>static</code> in the <code>main</code> method doesn't make sense, since <code>main</code> is not a function you will be calling repeatedly.</p>\n<h1>5) while(true)</h1>\n<p>The <code>while(true)</code> doesn't make any sense; it's not doing anything. You can safely remove it from the code.</p>\n<h1>6) Don't use <code>exit</code></h1>\n<p>I suspect you're using <code>exit</code> because the outer infinite loop; once you've removed the loop, you should use <code>window.Close()</code> method. This exits the game loop, and allows you to do any resource cleanup or post game-loop activity.</p>\n<h1>7) Separate simulation and render logic</h1>\n<p>Your simulation and render logic are interspersed together. You first check if the snake is in contact with the food, then render the frame, and then check if the snake is biting itself. Ideally, you'd want the simulation and render logic grouped together, possibly as separate functions.</p>\n<h1>8) Use <code>std::this_thread::sleep_for</code> instead of <code>_sleep</code>.</h1>\n<h1>9) Call <code>sf::display</code> only once per frame.</h1>\n<p>You have multiple <code>display</code> calls per frame. You only want to call display once per frame, after you've sent all data to be displayed by using <code>sf::draw</code>.</p>\n<h1>10) <code>playAgain</code></h1>\n<p>playAgain can be consolidated into the main game loop, instead of running a separate infinite loop. Just something for you to look into.</p>\n<h1>11) Better error messages</h1>\n<p>Suppose your <code>newFont</code> methods cannot find the font. It just silently exits. The developer has no idea what happened. Instead, provide the developer with a complete error message explaining what failed. Something like &quot;Unable to allocate font: &lt;font_path&gt;&quot;. This allows the developer to fix the issue. Better yet, have a backup font in case font allocation fails; this allows the game to run even if it can't find the font.</p>\n<h1>12) You don't need a <code>break</code> statement in the switch body if you're returning a value.</h1>\n<h1>13) <code>static</code> data members in Snake</h1>\n<p>The use of static data members in the <code>Snake</code> class binds all instances to a particular configuration for Snake. If I want to have multiple snakes (I don't know; maybe you're creating a local multiplayer version), each with different colors or thickness, I'm out of luck. Consider making them instance data members.</p>\n<h1>14) <code>SnakeFood::isTouching()</code> should be <code>const</code>. Similarly, <code>Snake::isTouchingFood</code> and <code>Snake::isTouchingSelf</code> should be <code>const</code>.</h1>\n<h1>15) <code>body.begin() + 0</code> is the same as <code>body.begin()</code>.</h1>\n<h1>16) General advice</h1>\n<p>One way you can improve your design is to have <code>snake</code> contain a <code>simulate</code> or <code>update</code> method, which simulate the snake i.e. moving, checking if out of bounds, check if eating the food or biting itself; then inside your game loop, you can simply do <code>snake.simulate()</code>, it's much cleaner code.</p>\n<p>Learn to use STL features, instead of C library features; the former is much more robust than the latter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T08:03:10.610", "Id": "485009", "Score": "0", "body": "Thank you so much for taking the time to go through my code! Just a few questions about 4 and 5.The reason I declared the sound buffers and fonts with static is because I wanted to make sure that they would be destructed when I called exit(). I was afraid that the data allocated by std::make_unique() wouldn't be deallocated otherwise. But if I remove exit() they don't need to be static anymore. Also, are you sure that I don't need the while(true) loop? If playAgain() returns true then we break out of the window loop, and the while(true) restarts. Are you saying I should do this some other way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T17:00:57.850", "Id": "485031", "Score": "0", "body": "4) In a normal program flow, the memory is deallocated when the scope exits. In an abnormal program flow (such as `exit`), the memory is claimed back by the operating system. Regardless, all heap allocations are deallocated when the program finishes.\n\n5) I'm sure there are better ways. One thing you might look into is the concept of game states. Each game states defines a separate scene (such as Main Menu, Playing, Paused, Game Finished), with each state managing their own resources and inputs. Here's a good introduction: http://gamedevgeek.com/tutorials/managing-game-states-in-c/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T17:48:15.010", "Id": "485034", "Score": "0", "body": "So you're saying that the unique_ptr's will be destructed when I call exit regardless of whether they're static or not? (Will look into game states)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:23:45.630", "Id": "485036", "Score": "0", "body": "The destructor will not be called. Here's a quick example: https://godbolt.org/z/9KvW3d In the call to `exit`, the memory held by the `unique_ptr` is claimed by the operating system, even if it is not released by the object. See this: https://stackoverflow.com/questions/2975831/is-leaked-memory-freed-up-when-the-program-exits" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T09:37:01.077", "Id": "485359", "Score": "0", "body": "But if allocated memory gets claimed by the operating system regardless of whether or not delete has been called on the pointer, how do memory leaks happen?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:42:28.347", "Id": "485400", "Score": "0", "body": "Memory leaks happen when you fail to deallocate heap-allocated memory. Suppose you're allocating on the heap every frame but not deallocating. Eventually, there'll come a point when you cannot allocate anymore (actually, virtual memory allows you to allocate more than physical memory) and your program crashes. Once the program crashes, all allocations are reclaimed by the OS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:58:50.643", "Id": "485403", "Score": "0", "body": "So memory leaks don't matter if they happen as a result of program termination?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T01:29:28.217", "Id": "485461", "Score": "0", "body": "Program termination may happen as a result of memory leak." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T20:08:43.803", "Id": "247693", "ParentId": "247670", "Score": "5" } } ]
{ "AcceptedAnswerId": "247693", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T11:02:42.497", "Id": "247670", "Score": "4", "Tags": [ "c++", "game", "snake-game", "sfml" ], "Title": "Snake game in C++ with SFML" }
247670
<p>I made a random maze generator that is also playable. The performance is crap and I'd like to improve it. I'll be working on this for a few more days to make it run better myself, but just thought I'd leave this here if people want to help.</p> <pre><code>import random, sys, time, pygame from fractions import gcd from pygame.locals import * from random import * #End goal: Make a random labyrinth generator #Generate random, completable walls #Have generate_maze be actually completable (Atm moves before assigning, which creates a lot of problems when moving out of already assigned tiles) #This is stolen. Credit to John Millikin from stackoverflow.com and john-millikin.com. I'd never come up with a solution this compact def gcd(a, b): while b: a, b = b, a%b return a if input('Would you like to enable blind mode (recommended)? y/n &gt;&gt;&gt; ') == 'y': blind_mode = True else: blind_mode = False tile_amount_multiplier = 1 #!!! NEVER SET ABOVE 2! IF YOU DO, THE RESULTS ARE TOTALLY INTENTIONAL GAME DESIGN THAT I JUST DON'T WANT YOU TO SEE pygame.init() window_resolution = 800, 600 window = pygame.display.set_mode((window_resolution[0], window_resolution[1])) score = 0 stag_line_width = 5 line_width = stag_line_width tile_width_height = gcd(window_resolution[0], window_resolution[1]) // 4 // tile_amount_multiplier touched = [] wall_drawn = False player_posx = 0 player_posy = 0 border = window_resolution[0]//100 *2 * tile_amount_multiplier -1, window_resolution[1]//100 *2 * tile_amount_multiplier -1 goal_posx = randint(0, border[0]) goal_posy = randint(0, border[1]) player_pos = player_posx, player_posy goal_pos = goal_posx, goal_posy keys = pygame.key.get_pressed() tile_amount = window_resolution[0] // tile_width_height * (window_resolution[1] // tile_width_height) def is_border(coordinates, direction): if direction == 'right': if coordinates[0] &gt;= border[0]: return True else: return False elif direction == 'left': if coordinates[0] &lt;= 0: return True else: return False elif direction == 'up': if coordinates[1] &lt;= 0: return True else: return False elif direction == 'down': if coordinates[1] &gt;= border [1]: return True else: return False else: print('You are safe from the end of the fucking world') return False print('Unexpected error in determining border location. You should probably fix that') def is_wall(dire): if is_border(player_pos, dire) == False: for pos in no_wall_tiles: if (dire == 'right' or 'left') and ((player_pos[1] == pos[0][1]) or (player_pos[1] == pos[1][1])): if dire == 'right': if ((player_pos[0] == pos[0][0]) or (player_pos[0] == pos[1][0])) and (((player_pos[0] + 1) == pos[1][0]) or ((player_pos[0] + 1) == pos[0][0])): return False elif dire == 'left': if ((player_pos[0] == pos[0][0]) or (player_pos[0] == pos[1][0])) and (((player_pos[0] - 1) == pos[1][0]) or ((player_pos[0] - 1) == pos[0][0])): return False if (dire == 'up' or 'down') and ((player_pos[0] == pos[1][0]) or (player_pos[0] == pos[0][0])): if dire == 'up': if ((player_pos[1] == pos[0][1]) or (player_pos[1] == pos[1][1])) and (((player_pos[1] - 1) == pos[1][1]) or ((player_pos[1] - 1) == pos[0][1])): return False elif dire == 'down': if ((player_pos[1] == pos[0][1]) or (player_pos[1] == pos[1][1])) and (((player_pos[1] + 1) == pos[1][1]) or ((player_pos[1] + 1) == pos[0][1])): return False return True else: return True def random_direction(): digit = randint(1, 4) if digit == 1: return 'right' if digit == 2: return 'left' if digit == 3: return 'up' return 'down' def generate_maze(): wall_generated = False generation_visited = [] global no_wall_tiles no_wall_tiles = [] generation_pos = [randint(0, border[0]), randint(0, border [1])] generation_last_pos = [] first_run = True while wall_generated == False: if tuple(generation_pos) in generation_visited: is_visited = True else: is_visited = False if is_visited == False: generation_visited.append(tuple(generation_pos)) if first_run == False: no_wall_tiles.append((tuple(generation_last_pos), tuple(generation_pos))) direction = random_direction() generation_last_pos = generation_pos.copy() if is_border(tuple(generation_pos), direction) == False: #Checks for bounds if direction == 'right': #Checks every direction possible generation_last_pos = generation_pos.copy() generation_pos[0] += 1 elif direction == 'left': # ^ generation_last_pos = generation_pos.copy() generation_pos[0] -= 1 elif direction == 'up': # ^ generation_last_pos = generation_pos.copy() generation_pos[1] -= 1 elif direction == 'down': # ^ generation_last_pos = generation_pos.copy() generation_pos[1] += 1 first_run = False if len(generation_visited) == tile_amount: print(no_wall_tiles) wall_generated = True def is_touched(x): return x in touched def draw_walls(): opposite_cord = 0 line_color = 100, 0 , 100 if blind_mode == True: line_color = 0,0,0 for z in range(window_resolution[0] // tile_width_height): global line_width coordinatex = window_resolution[0] // 10 coordinatey = window_resolution[1] // 10 posx = 0 for x in range(coordinatex // 10 * 4 * tile_amount_multiplier): for i in range(1, 4): if i == 1: for coord in no_wall_tiles: if (x, z) in coord and (x, z+1) in coord: should_draw = False break should_draw = True if should_draw == True: pygame.draw.line(window,(line_color),(posx, opposite_cord + tile_width_height), (tile_width_height + posx, opposite_cord + tile_width_height), line_width) elif i == 2: for coord in no_wall_tiles: if (x, z) in coord and (x+1, z) in coord: should_draw = False break should_draw = True if should_draw == True: pygame.draw.line(window,(line_color),(posx + tile_width_height, opposite_cord), (posx + tile_width_height, opposite_cord + tile_width_height), line_width) posx += tile_width_height line_width = stag_line_width for y in range(coordinatey // 10 * 4 * tile_amount_multiplier): posx += tile_width_height line_width = stag_line_width opposite_cord += tile_width_height posx = 0 def is_victory (): if player_pos == goal_pos: return True return False def draw_tileset(): opposite_cord = 0 for z in range(window_resolution[0] // tile_width_height): global line_width rect_color = 0,0,0 rect_coror_perma = rect_color coordinatex = window_resolution[0] // 10 coordinatey = window_resolution[1] // 10 posx = 0 for x in range(coordinatex // 10 * 4 * tile_amount_multiplier): if goal_posx == x and goal_posy == z: line_width = 0 rect_color = (255, 0, 0) elif player_posx == x and player_posy == z: rect_color = (0, 0, 255) line_width = 0 elif is_touched((x, z)): rect_color = 50,200,200 line_width = 0 pygame.draw.rect(window, rect_color, (posx, opposite_cord, tile_width_height, tile_width_height), line_width) rect_color = rect_coror_perma posx += tile_width_height line_width = stag_line_width for y in range(coordinatey // 10 * 4 * tile_amount_multiplier): if player_posy == z and player_posy == y: line_width = 1 pygame.draw.rect(window,(rect_color),(opposite_cord, posx, tile_width_height, tile_width_height), line_width) posx += tile_width_height line_width = stag_line_width opposite_cord += tile_width_height posx = 0 #Dumb ass system to coordinates conversion guide: coord main_coordinate = main_coordinate, secondary coordinate = z generate_maze() draw_tileset() draw_walls() pygame.display.update() while True: player_pos = player_posx, player_posy if is_victory() == True: score += 1 print('Your score is now', score) player_posx = 0 player_posy = 0 goal_posx = randint(0, border[0]) goal_posy = randint(0, border[1]) goal_pos = goal_posx, goal_posy touched = [] generate_maze() window.fill((0, 0, 0)) draw_tileset() draw_walls() pygame.display.update() for event in pygame.event.get(): if event.type == QUIT: print('You got a score of', score) pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == K_a and is_wall('left') == False: if player_pos not in touched: touched.append(player_pos) player_posx -= 1 window.fill((0, 0, 0)) draw_tileset() draw_walls() pygame.display.update() elif event.key == K_d and is_wall('right') == False: if player_pos not in touched: touched.append(player_pos) player_posx += 1 window.fill((0, 0, 0)) draw_tileset() draw_walls() pygame.display.update() elif event.key == K_s and is_wall('down') == False: if player_pos not in touched: touched.append(player_pos) player_posy += 1 window.fill((0, 0, 0)) draw_tileset() draw_walls() pygame.display.update() elif event.key == K_w and is_wall('up') == False: if player_pos not in touched: touched.append(player_pos) player_posy -= 1 window.fill((0, 0, 0)) draw_tileset() draw_walls() pygame.display.update() </code></pre>
[]
[ { "body": "<p>I'm going to just touch on style issues mostly.</p>\n<pre><code>if input('Would you like to enable blind mode (recommended)? y/n &gt;&gt;&gt; ') == 'y':\n blind_mode = True\nelse: blind_mode = False\n</code></pre>\n<p>This could be made a little cleaner and more succinct. First, I'm personally not a fan of putting things on the same line as <code>else:</code>. In the vast majority of cases (here included), I think it hurts readability.</p>\n<p>I'd suggest something closer to this though:</p>\n<pre><code>answer = input('Would you like to enable blind mode (recommended)? y/n &gt;&gt;&gt; ')\nblind_mode = answer.lower() == 'y'\n</code></pre>\n<ul>\n<li>I'm using <code>lower</code> so the user can enter <code>'Y'</code> as well, and it will still match.</li>\n<li><code>==</code> already evaluates to a Boolean value. Using an <code>if</code> here to dispatch to <code>True</code>/<code>False</code> is redundant.</li>\n</ul>\n<p>Along the same lines, you have this function:</p>\n<pre><code>def is_victory ():\n if player_pos == goal_pos:\n return True\n return False\n</code></pre>\n<p>The <code>if</code> is redundant:</p>\n<pre><code>def is_victory ():\n return player_pos == goal_pos\n</code></pre>\n<p>And also here:</p>\n<pre><code>line_color = 100, 0 , 100\nif blind_mode == True:\n line_color = 0,0,0\n</code></pre>\n<p>Can be:</p>\n<pre><code>line_color = (0, 0, 0) if blind_mode else (100, 0 , 100)\n</code></pre>\n<p>And the bits like:</p>\n<pre><code>if coordinates[0] &lt;= 0:\n return True\nelse: \n return False\n</code></pre>\n<p>Can simply be:</p>\n<pre><code>return coordinates[0] &lt;= 0\n</code></pre>\n<hr />\n<pre><code>while wall_generated == False:\n</code></pre>\n<p>Would be arguably better as:</p>\n<pre><code>while not wall_generated:\n</code></pre>\n<p>If you ever write <code>something == True</code> or <code>something == False</code>, you're better off just writing <code>something</code> and <code>not something</code>. Comparing against <code>True</code> and <code>False</code> is again redundant.</p>\n<hr />\n<p>Then directly below that you have:</p>\n<pre><code>if tuple(generation_pos) in generation_visited:\n is_visited = True\nelse:\n is_visited = False\n</code></pre>\n<p>This would be more succinct as:</p>\n<pre><code>is_visited = tuple(generation_pos) in generation_visited\n</code></pre>\n<p>I'd also rethink if the <code>tuple</code> conversion is necessary. You're constantly converting a list to a tuple just to do a comparison. I'd just keep it as a list instead of converting to the coordinates to a tuple, unless you <em>really</em> want/need to immutability benefits of tuples.</p>\n<hr />\n<pre><code>if (dire == 'right' or 'left') . . .\n. . .\nif (dire == 'up' or 'down') . . .\n</code></pre>\n<p>This code is actually broken. <code>dire == 'up' or 'down'</code> will never (ever) be false. It will always be True. See <a href=\"https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value\">here</a> for an explanation of why.</p>\n<p>You want something like:</p>\n<pre><code>if (dire in {'right', 'left'}) . . .\n</code></pre>\n<p><code>{. . .}</code> is a set, and <code>in</code> is doing a membership lookup.</p>\n<hr />\n<pre><code>from random import *\n</code></pre>\n<p>Try to limit (or outright avoid) using <code>from . . . import *</code> statements like that. Wildcard imports like that have two main problems:</p>\n<ul>\n<li>You're polluting the namespace. Because you're dumping all the names from the module into your file, that reduces what names you have available to you to use, and increases the chance of a name collision.</li>\n<li>It makes it harder for readers of your code to know where functions in your code come from, and what the purpose of the imported modules are.</li>\n</ul>\n<p>I'd explicitly import exactly what you need:</p>\n<pre><code>from random import randint\n</code></pre>\n<p>Or, use a qualified import:</p>\n<pre><code>import random\n. . .\nrandom.randint(. . .)\n</code></pre>\n<p>Now it's clear what's being import, why you're using the <code>random</code> modules, and there is no longer any chance of a collision.</p>\n<hr />\n<p>You have magic numbers floating around in a few places, like:</p>\n<pre><code>for y in range(coordinatey // 10 * 4 * tile_amount_multiplier):\n</code></pre>\n<p>Why <code>4</code>? Why <code>10</code>? Why not <code>40</code>? If those numbers have well-defined purposes, ideally, they should have a name attached to them.</p>\n<pre><code># At the top of your file\nMY_MULT = 4 # These are poor names because I don't know their purpose\nMY_OTHER_MULT = 10\n\n. . .\n\nmax_coord = coordinatey // MY_OTHER_MULT * MY_MULT * tile_amount_multiplier\nfor y in range(max_coord):\n</code></pre>\n<p>When those variables are given proper names, it will be much easier for readers of your code to know what exactly is going on math-wise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:02:51.220", "Id": "485419", "Score": "0", "body": "Sorry for the very late reply. Could you explain why the `line_color = (0, 0, 0) if blind_mode else (100, 0 , 100)` line works? Maybe how the computer interprets it? To me it looks like it'd produce an error, but it doesn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:05:16.630", "Id": "485420", "Score": "1", "body": "@Aakoo7 `if` can take two forms: as a statement and as an expression. As a statement like you're use to, it takes the form `if <condition>: <do_if_true> else: <do_if_false>`. When used as an expression however (meaning, we want it to evaluate to a value), it takes the form `<value_if_true> if <condition> else <value_if_false>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:08:43.077", "Id": "485422", "Score": "1", "body": "@Aakoo7 As another example, here's how a conditional expression (the second form of `if`) can be used to write an `abs` function: `def abs(n): return n if n > 0 else -n`. \"The absolute value of `n` is `n` if `n` is greater than 0, else it's `n` multiplied by -1\"." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T16:22:28.867", "Id": "247687", "ParentId": "247674", "Score": "2" } }, { "body": "<p>First of all, everything @Carcigenicate said.</p>\n<p>Next:</p>\n<ol>\n<li><p>Replace strings with constants:</p>\n<pre><code>LEFT = &quot;l&quot;\nRIGHT = r&quot;\n\n...\n\nif dire == LEFT:\n</code></pre>\n</li>\n<li><p>Replace a &quot;complete&quot; list of if statements on directions with a dictionary of lambda functions:</p>\n<pre><code> _BORDER_CHECK = {\n RIGHT: lambda c, b: c[0] &gt;= b[0],\n LEFT: lambda c, b: c[0] &lt;= 0,\n ...\n}\n\ndef is_border(coordinates, direction):\n return _BORDER_CHECK[direction](coordinates, border)\n</code></pre>\n<p>Doing this lets you replace 4 comparisons with a single dictionary lookup, which is implemented in C.</p>\n</li>\n<li><p>Don't use the global symbols <code>True</code> and <code>False</code> if you can avoid them.</p>\n<p>You may not realize this, but Python treats those as <em>symbols.</em> They are not magically replaced in the compiler, as they are in C or Java.</p>\n<p>Older versions of Python would see &quot;True&quot; and do this:</p>\n<pre><code>load the symbol string &quot;True&quot;\ngo a global name lookup\nuse the result\n</code></pre>\n<p>Newer versions know about constants somewhat, so they do this:</p>\n<pre><code>fetch the constant &quot;True&quot; (still a global name lookup)\nuse the result\n</code></pre>\n<p>Here's an example:</p>\n<pre><code>&gt;&gt;&gt; import dis\n&gt;&gt;&gt; def f(x):\n... if x == True:\n... print(&quot;true&quot;)\n... \n&gt;&gt;&gt; dis.dis(f)\n\n 2 0 LOAD_FAST 0 (x)\n 2 LOAD_CONST 1 (True)\n 4 COMPARE_OP 2 (==)\n 6 POP_JUMP_IF_FALSE 16\n</code></pre>\n<p>On the other hand, if you skip using <code>True</code> and <code>False</code>, you can get better code, like this:</p>\n<pre><code>&gt;&gt;&gt; def f(x):\n... if x:\n... print(&quot;true&quot;)\n... \n&gt;&gt;&gt; dis.dis(f)\n 2 0 LOAD_FAST 0 (x)\n 2 POP_JUMP_IF_FALSE 12\n</code></pre>\n<p>That's literally 4 opcodes versus 2. Either 50% or 100% faster, depending on whether you work in marketing...</p>\n</li>\n<li><p>Use <code>random.choice</code> to pick a direction.</p>\n</li>\n<li><p>Use <code>collections.namedtuple</code> to create a Position class, instead of converting from list to tuple over and over again, and indexing all the time.</p>\n<p>Turn this code:</p>\n<pre><code>if (dire == 'up' or 'down') and ((player_pos[0] == pos[1][0]) or (player_pos[0] == pos[0][0])):\n</code></pre>\n<p>Into something like:</p>\n<pre><code>if dire in (UP, DOWN) and (player_pos.x == pos[0].x or player_pos.x == pos[1].x):\n</code></pre>\n</li>\n<li><p>Write a Position <a href=\"https://docs.python.org/3/library/functions.html?highlight=classmethod#classmethod\" rel=\"nofollow noreferrer\">class method</a> called <code>random</code> that takes border parameters and returns a random location therein. You can use that to get rid of the other calls to <code>random.randint</code>.</p>\n</li>\n<li><p>Promote all your &quot;against the wall&quot; code to either global constants (with NAMES_LIKE_THIS) or to an init function that you call from <code>main</code>.</p>\n</li>\n<li><p>Add the <code>if __name__ == &quot;__main__&quot;:</code> block that <strike><a href=\"https://www.pep8.org\" rel=\"nofollow noreferrer\">PEP-8</a> mentions.</strike> is mentioned in <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">the documentation</a>.</p>\n</li>\n<li><p>In <code>generate_maze</code>, and other places, stop using lists for unique collections. Use <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=set#set\" rel=\"nofollow noreferrer\"><code>set</code></a> instead, which has <span class=\"math-container\">\\$O(1)\\$</span> query time. (Lists have <span class=\"math-container\">\\$O(n)\\$</span> query time for <code>if x in list</code>.)</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T17:19:13.123", "Id": "485428", "Score": "0", "body": "Sorry for the late reply. I have a couple of questions:\n1. #5 is very unclear to me. Could you rephrase the question or maybe provide an example?\n2. What's a class method? I tried looking it up but I understand nothing.\n3. In #9, do you mean sets? If not, I have no idea what you mean.\n4. In #8, I could not find that block in the document. I'm pretty sure I misunderstood, so please clarify." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T21:18:35.560", "Id": "485450", "Score": "1", "body": "I have edited the answer to address most of your questions. Sorry about the PEP-8 confusion-- it's in the documentation. Yes, I meant sets in #9, with the `set` keyword." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T19:09:10.303", "Id": "247691", "ParentId": "247674", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T12:16:38.403", "Id": "247674", "Score": "5", "Tags": [ "python", "beginner", "algorithm", "python-3.x", "pygame" ], "Title": "Optimizing performance of randomly generated pygame maze game" }
247674
<h2>The Huffman-Algorithm</h2> <p>The Huffman-Algorithm, named after David A. Huffman who first published this algorithm in 1952, is a algorithm for lossless data compression. As most encoding-methods, the words for often used symbols are shorter than the ones for not so commonly used symbols. The algorithm returns a binary code-word for every source symbol. The result is a optimal prefix-free code.</p> <h2>The Algorithm in detail</h2> <p>The first step is to count the number of occurences of every char in the text. After that, the algorithm creates a so called forest of tree-nodes, where every node contains one char and the number of occurences of this char:</p> <p>After that, the algorithm looks at this node as roots of trees.</p> <p>Then, while there is more than one tree left, the algorithm creates a new node with two children. The children are always the nodes with the two smallest numbers of occurences. For the new node, the number of occurences of the children are added together.</p> <p>After that, the code-words for every char are created by looking at the path to every leaf.</p> <h2>The code</h2> <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>/* * Attribution: * https://stackoverflow.com/a/38362821/13634030 * https://stackoverflow.com/a/14313213/13634030 */ /* * This program is an implementation of the Huffman-algorithm. * Huffman-coding is an algorithm for lossless data compression. It was * first published by David A. Huffman in 1952. * The algorithm returns a binary code-word for every source symbol. Like * most encoding methods, the words for often used symbols are shorter than * the ones for not so commonly used symbols. The result is a optimal prefix- * free code. * For more information see https://en.wikipedia.org/wiki/Huffman_coding. */ document.getElementById('startHuff').addEventListener('click', huffman); /* * ================================ * Data-structures for this program * ================================ */ /** * Provides the structure called a node for a binary tree */ class Node { /** * Creates a node * @param {number} value Number of occurences * @param {char} c The char this node represents * @param {Node} left The left child-node * @param {Node} right The right child-node */ constructor(value, c, left, right) { this.value = value; this.c = c; this.left = left; this.right = right; } } /** * Provides a recursive binary-tree structure */ class Tree { /** * Creates a Tree * @param {Node} root The root of the tree */ constructor(root) { this.root = root; } } /* * ================== * Main-functionality * ================== */ let input; // The text the user wants to compress let occurences; // Array that contains the number of occurences of every char let forest; // Array that contains the nodes for every char let code; // Array that contains the code-words for every char let text; // Compressed text let codeWords; // Array code as user-friendly string let ascii; // ASCII-text /** * This is the only function that has to be called from outside * this script. */ function huffman() { // get user input input = document.getElementById('Input').value; // reset variables forest = []; ascii = ''; text = ''; codeWords = ''; /* * Program only creates huffman-tree if * user only entered (non-extended) ascii- * chars */ if (input != '' &amp;&amp; isASCII(input)) { // Count occurences of every ascii-char count(); // Create node for every char that occures at least once createForest(); // Apply huffman-algorithm on the created nodes createTree(); /* * "translates" the position of the leafs to the codeword * of the char represented by the leaf * * # * 0/ \ * / \ * # # * / \1 * / \ * # * 0/ * / * A * * The code-word of 'A' would be 010 in this example */ code = new Array(128); createCode('', code, forest[0].root); // Creating html-table with created code-words getCode(); // Creates string with every char replaced by the code-word getText(); // Creates string with every char replaced by the binary ascii-value getAscii(); // Output document.getElementById('Text').value = text; document.getElementById('CodeWords').innerHTML = codeWords; document.getElementById('numOfCharsText').innerHTML = ' ' + text.length; document.getElementById('Ascii').value = ascii; document.getElementById('numOfCharsAscii').innerHTML = ' ' + ascii.length; document.getElementById('compression').innerHTML = ' ' + text.length + ' / ' + ascii.length + ' = ' + (text.length / ascii.length).toFixed(4); } else { window.alert('Please only enter ASCII-characters.'); } } /** * Counts the number of occurences of every ascii-char in input */ function count() { occurences = new Array(128); // Initialize with zero for (let i = 0; i &lt; occurences.length; i++) { occurences[i] = 0; } // Count occurences for (let i = 0; i &lt; input.length; i++) { // charCodeAt(i) returns the ascii-code of the i-th character in the string occurences[input.charCodeAt(i)]++; } } /** * Creates the forest with one tree for every char */ function createForest() { // Create tree (with only one node) for every char the text contains for (let i = 0; i &lt; occurences.length; i++) { // Only chars that really occur in the text will be taken into account if (occurences[i] &gt; 0) { // String.fromCharCode(i) returns the char with ascii-code i const x = String.fromCharCode(i); forest.push(new Tree(new Node(occurences[i], x, null, null))); } } } /** * Creates the huffman-tree */ function createTree() { /* * The result of the algorithm is just one tree, so the algorithm has * not finished yet, if there are more than one trees. */ while (forest.length &gt; 1) { // Find the two trees with the smallest number of occurences let minIndex = findMinimum(); const min1 = forest[minIndex].root; /* * removes the minIndex-th element; the second parameter tells us that * only one element should be removed, starting at index minIndex */ forest.splice(minIndex, 1); minIndex = findMinimum(); const min2 = forest[minIndex].root; forest.splice(minIndex, 1); // Create new node that has min1 and min2 as child-nodes forest.push(new Tree(new Node(min1.value + min2.value, null, min1, min2))); } } /** * Creates the code-words from the created huffman-tree * @param {String} str (Part of) the codeword for the current leaf * @param {Array} code Array of codewords that has to be filled * @param {Node} node Current node */ function createCode(str, code, node) { if (node == null) { return; } // case the node is a leaf if (node.left == null &amp;&amp; node.right == null) { code[node.c.charCodeAt()] = str; // Recursive calls if node is not a leaf } else { createCode(str + '0', code, node.left); createCode(str + '1', code, node.right); } } /* * ================ * Helper-functions * ================ */ /** * Creates a html-table with the codewords */ function getCode() { codeWords = '&lt;table&gt;&lt;tr&gt;&lt;th&gt;Character&lt;/th&gt;&lt;th&gt;' + 'Occurences&lt;/th&gt;&lt;th&gt;Huffman-code&lt;/th&gt;&lt;/tr&gt;'; for (let i = 0; i &lt; code.length; i++) { if (occurences[i] &gt; 0) { codeWords += '&lt;tr&gt;'; codeWords += '&lt;td&gt;' + String.fromCharCode(i) + '&lt;/td&gt;'; codeWords += '&lt;td&gt;' + occurences[i] + '&lt;/td&gt;'; codeWords += '&lt;td&gt;' + code[i] + '&lt;/td&gt;'; codeWords += '&lt;/tr&gt;'; } } codeWords += '&lt;/table&gt;'; } /** * Replaces every char with its codeword. */ function getText() { for (let i = 0; i &lt; input.length; i++) { text += code[input.charCodeAt(i)] + ' '; } } /** * Replaces every char with its ASCII-code. */ function getAscii() { for (let i = 0; i &lt; input.length; i++) { ascii += '00'.concat(input.charCodeAt(i).toString(2)).slice(-8) + ' '; } } /** * Finds the minimum. * @return {number} index of minimum */ function findMinimum() { let min = forest[0].root.value; let minIndex = 0; for (let i = 0; i &lt; forest.length; i++) { if (min &gt; forest[i].root.value) { minIndex = i; min = forest[i].root.value; } } return minIndex; } /** * Returns true, if str only contains ascii-chars. * @param {String} str String the function will be applied on * @return {Boolean} test True if str only contains ascii-chars */ function isASCII(str) { /* * returns true if str only contains (non-extended) ascii-chars; * see https://www.ascii-code.com/ for reference */ const test = /^[\x00-\x7F]*$/.test(str); return test; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Just minimal working example --&gt; &lt;!DOCTYPE html&gt; &lt;html lang='en'&gt; &lt;!-- Head --&gt; &lt;head&gt; &lt;meta charset='utf-8'&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;script&gt; window.onerror=function(msg, url, linenumber) { alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber); return true; } &lt;/script&gt; &lt;title&gt;Huffman&lt;/title&gt; &lt;link rel='stylesheet' type='text/css' href='../css/style.css'&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Input Area --&gt; &lt;h4&gt;Input:&lt;/h4&gt; &lt;div&gt; &lt;textarea id='Input' rows='8' style='resize: none; background: LightGray; position: relative; width: 80%;'&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;button type='button' id='startHuff'&gt;Huffman&lt;/button&gt; &lt;!-- Output Area --&gt; &lt;h4&gt;Compressed text:&lt;/h4&gt; &lt;div&gt; &lt;textarea id='Text' rows='8' style='resize: none; background: LightGray; position: relative; width: 80%;' readonly&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;p&gt;Number of chars:&lt;span id=numOfCharsText&gt;&lt;/span&gt;&lt;/p&gt; &lt;h4&gt;ASCII text:&lt;/h4&gt; &lt;div&gt; &lt;textarea id='Ascii' rows='8' style='resize: none; background: LightGray; position: relative; width: 80%;' readonly&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;p&gt;Number of chars:&lt;span id=numOfCharsAscii&gt;&lt;/span&gt;&lt;/p&gt; &lt;h4&gt;Code:&lt;/h4&gt; &lt;div id='CodeWords'&gt; &lt;/div&gt; &lt;p&gt;Compression:&lt;span id=compression&gt;&lt;/span&gt;&lt;/p&gt; &lt;script src='huffman.js'&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I've checked the code with eslint and it didn't show me any errors for this version.</p> <h2>Question</h2> <p>All suggestions to improve the code are appreciated.</p>
[]
[ { "body": "<p>Warning: this is pretty opinionated I just didn't want to sprinkle the word &quot;maybe&quot; halfway through an explanation</p>\n<p>There's a lot of things going on here. I see you use a lot of type hints. I'd recommend using TypeScript, as it enforces the hints such that they become rules rather than suggestions. In general, though, the code appears to have a lot of noisy comments. The worst offender is right here.</p>\n<pre><code>/**\n * Returns true, if str only contains ascii-chars.\n * @param {String} str String the function will be applied on\n * @return {Boolean} test True if str only contains ascii-chars\n */\nfunction isASCII(str) {\n /*\n * returns true if str only contains (non-extended) ascii-chars;\n * see https://www.ascii-code.com/ for reference\n */\n const test = /^[\\x00-\\x7F]*$/.test(str);\n return test;\n}\n</code></pre>\n<p>The code here is pretty much self explanatory from the method name. Adding the block style comments makes this section appear more complex than it actually is.</p>\n<pre><code>let input; // The text the user wants to compress\nlet occurences; // Array that contains the number of occurences of every char\nlet forest; // Array that contains the nodes for every char\nlet code; // Array that contains the code-words for every char\nlet text; // Compressed text\nlet codeWords; // Array code as user-friendly string\nlet ascii; // ASCII-text\n</code></pre>\n<p>That's a lot of global state to be hanging to for a function that requires no persistence. None of these variables need to live in the global scope.</p>\n<p>The code is littered with references to the DOM and your output statistics. Only the encoded output and the huffman encoding dictionary are required for the analysis, so generate the DOM elements elsewhere.</p>\n<p>With the global state and the DOM references removed, the main <code>huffman()</code> function can be written as such.</p>\n<pre><code>function huffman(input) {\n if (input === '' || !isASCII(input))\n throw 'invalid_input';\n const histogram = createHistogram(input);\n const leafs = createLeafs(histogram);\n const tree = createTree(leafs);\n const code = createCode('',tree);\n const encoded = encode(code,input);\n return {\n output:encoded,\n code\n };\n}\n</code></pre>\n<p>Note how all of the variables are kept in the scope of the function.</p>\n<p>The <code>Tree</code> structure is entirely unnecessary. Sometimes, adding an object like this can help readability. However, in this case, the code is infected with a bunch of <code>.root</code> properties. This is particularly strange in the case where the trees are being joined, and trees must be converted to nodes when they are added to another tree.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*\n * Attribution:\n * https://stackoverflow.com/a/38362821/13634030\n * https://stackoverflow.com/a/14313213/13634030\n */\n\n/*\n * This program is an implementation of the Huffman-algorithm.\n * Huffman-coding is an algorithm for lossless data compression. It was\n * first published by David A. Huffman in 1952.\n * The algorithm returns a binary code-word for every source symbol. Like\n * most encoding methods, the words for often used symbols are shorter than\n * the ones for not so commonly used symbols. The result is a optimal prefix-\n * free code.\n * For more information see https://en.wikipedia.org/wiki/Huffman_coding.\n */\n\nconst MAX_CODE = 128;\n\nclass Node {\n constructor(count, char, left, right) {\n this.count = count;\n this.char = char;\n this.left = left;\n this.right = right;\n }\n}\n\nfunction isASCII(str) {\n const test = /^[\\x00-\\x7F]*$/.test(str);\n return test;\n}\n\nfunction huffman(input) {\n if (input === '' || !isASCII(input))\n throw 'invalid_input';\n const histogram = createHistogram(input);\n const leafs = createLeafs(histogram);\n const tree = createTree(leafs);\n const code = createCode('',tree);\n const encoded = encode(code,input);\n return {\n output:encoded,\n code\n };\n}\n\n// builds histogram of letter frequency\nfunction createHistogram(input) {\n const histogram = {};\n\n for (let i = 0; i &lt; input.length; i++) {\n const code = input.charCodeAt(i);\n ++histogram[code];\n }\n\n return histogram;\n}\n\n// creates the forest with one tree for every char\nfunction createLeafs(histogram) {\n return Object.entries(histogram).map(([code,freq])=&gt;{\n const char = String.fromCharCode(code);\n return new Node(freq,char,null,null);\n })\n}\n\n// splits trees into small and big\nfunction splitTrees(forest) {\n const sorted = forest.sort((a,b)=&gt;a.count-b.count);\n const small = sorted.slice(0,2);\n const big = sorted.slice(2);\n return [small,big];\n}\n\nfunction createTree(forest) {\n if (forest.length===1)\n return forest[0]\n const [small_trees,big_trees] = splitTrees(forest);\n const new_tree = new Node(\n small_trees[0].count+small_trees[1].count,\n null,\n small_trees[0],small_trees[1]\n );\n const new_trees = [...big_trees,new_tree];\n return createTree(new_trees);\n}\n\n// Creates the code-words from the created huffman-tree\nfunction createCode(prefix, node) {\n // empty root node\n if (!node) return {};\n // leaf node\n if (!node.left &amp;&amp; !node.right) {\n return {[node.char] : prefix};\n }\n // recursive call\n return {\n ...createCode(prefix + '0', node.left),\n ...createCode(prefix + '1', node.right)\n }\n}\n\nfunction encode(code,string) {\n return Array.from(string).map(\n c=&gt;code[c]\n );\n}\n\nconsole.log(huffman(\"hi dude\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T02:05:02.643", "Id": "247700", "ParentId": "247676", "Score": "5" } }, { "body": "<h1>Overall feedback</h1>\n<p>It seems there are quite a few global variables referenced within various functions. This isn't totally bad but it makes things difficult - like unit testing. If functions accepted parameters and returned certain output then testing might be easier.</p>\n<p>The answer by Ted Brownlow suggests using a Plain-old Javascript object (A.K.A. a POJO) to store the occurrences instead of an array - i.e. a mapping of characters to counts. This can eliminate the need to initialize the array and set all values to zero.</p>\n<p>You may be interested to read other posts involving Huffman Encoding, including <a href=\"https://codereview.stackexchange.com/q/242296/120114\">this one</a>.</p>\n<h1>Suggestions</h1>\n<h2>Initializing an array of zeroes</h2>\n<p>In the function <code>count()</code> there is this code:</p>\n<blockquote>\n<pre><code>occurences = new Array(128);\n// Initialize with zero\nfor (let i = 0; i &lt; occurences.length; i++) {\n occurences[i] = 0;\n}\n</code></pre>\n</blockquote>\n<p>The loop can be avoided by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>array.fill()</code></a>.</p>\n<h2>Excess variables</h2>\n<p>in the function <code>isASCII</code> there is the variable <code>test</code> that is returned immediately after being assigned. While this may be leftover from debugging the variable can be eliminated. The whole function could be expressed as a one-line arrow function.</p>\n<h2>Avoid excess DOM lookups</h2>\n<p>The code in <code>huffman()</code> accesses DOM elements each time. While it may not be as much of an issue with todays browsers, it is wise to cache DOM references one they are available (e.g. in the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event\" rel=\"nofollow noreferrer\"><code>DOMContentLoaded</code> event</a>).</p>\n<p><a href=\"https://i.stack.imgur.com/ybMID.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ybMID.jpg\" alt=\"bridge toll\" /></a></p>\n<blockquote>\n<p><em>”...DOM access is actually pretty costly - I think of it like if I have a bridge - like two pieces of land with a toll bridge, and the JavaScript engine is on one side, and the DOM is on the other, and every time I want to access the DOM from the JavaScript engine, I have to pay that toll”</em><br>\n    - John Hrvatin, Microsoft, MIX09, in <a href=\"https://channel9.msdn.com/Events/MIX/MIX09/T53F\" rel=\"nofollow noreferrer\">this talk <em>Building High Performance Web Applications and Sites</em></a> at 29:38, also cited in the <a href=\"https://books.google.com/books?id=ED6ph4WEIoQC&amp;pg=PA36&amp;lpg=PA36&amp;dq=John+Hrvatin+%22DOM%22&amp;source=bl&amp;ots=2Wrd5G2ceJ&amp;sig=pjK9cf9LGjlqw1Z6Hm6w8YrWOio&amp;hl=en&amp;sa=X&amp;ved=2ahUKEwjcmZ7U_eDeAhVMGDQIHSfUAdoQ6AEwAnoECAgQAQ#v=onepage&amp;q=John%20Hrvatin%20%22DOM%22&amp;f=false\" rel=\"nofollow noreferrer\">O'Reilly <em>Javascript</em> book by Nicholas C Zakas Pg 36</a>, as well as mentioned in <a href=\"https://www.learnsteps.com/javascript-increase-performance-by-handling-dom-with-care/\" rel=\"nofollow noreferrer\">this post</a></p>\n</blockquote>\n<h2>Alerts</h2>\n<p>There are two places <code>alert()</code> is called (one in <code>huffman()</code> and one in the <code>window.onerror</code> handler). This can be an issue because some users may have disabled alerts in a browser setting. It is better to use HTML5 <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\" rel=\"nofollow noreferrer\"><code>&lt;dialog&gt;</code></a> element - it allows more control over the style and doesn't block the browser. Bear in mind that it <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#Browser_compatibility\" rel=\"nofollow noreferrer\">isn't supported by IE and Safari</a> (And seemingly Chrome on iOS) but <a href=\"https://github.com/GoogleChrome/dialog-polyfill\" rel=\"nofollow noreferrer\">there is a polyfill</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T20:10:46.567", "Id": "247921", "ParentId": "247676", "Score": "2" } } ]
{ "AcceptedAnswerId": "247921", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T13:27:17.900", "Id": "247676", "Score": "9", "Tags": [ "javascript", "beginner", "ecmascript-6", "compression" ], "Title": "Huffman encoding" }
247676
<p>Looking for a most elegant way to copy dictionary type alias to original collection.</p> <pre><code>using System; using System.Collections.Generic; public class SmallDictionary: Dictionary&lt;string, JToken&gt; public class NestedDictionary : Dictionary&lt;string, SmallDictionaly&gt; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Adp.Configuration.Events.Entities; using Newtonsoft.Json.Linq; public static Dictionary&lt;string, Dictionary&lt;string, JToken&gt;&gt; ToDictionary(this NestedDictionary configurationEntry) { Dictionary&lt;string, Dictionary&lt;string, JToken&gt;&gt; resultDictionary = new Dictionary&lt;string, Dictionary&lt;string, JToken&gt;&gt;(); foreach (KeyValuePair&lt;string, SmallDictionary&gt; pair in configurationEntry) { resultDictionary.Add(pair.Key, pair.Value); } return resultDictionary; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T19:12:45.553", "Id": "484950", "Score": "0", "body": "basically found shorter way to do this, which also create a new collection\n\n\n`return configurationEntry.ToDictionary(entry => entry.Key, entry => (Dictionary<string, JToken>)entry.Value);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T22:33:23.733", "Id": "484959", "Score": "1", "body": "This question currently has 3 votes to close it as off-topic due to lack of context. We really can't review questions that don't provide the requirements or show the usage of the code being reviewed. I suggest you read or re-read the [help center](https://codereview.stackexchange.com/help/how-to-ask) for how to ask good questions on code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T00:22:15.910", "Id": "484972", "Score": "0", "body": "@pacmaninbw and to make matters worse, I believe I misunderstood the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T08:59:31.140", "Id": "485013", "Score": "0", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>You definitely don't want to extend a type in order to alias it.</p>\n<p>This introduces complexity, is not idiomatic, and most importantly doesn't create an alias.</p>\n<p>I believe what you're looking for is the type alias syntax</p>\n<pre><code>using System;\nusing System.Collections.Generic;\n\nusing SmallDictionary = Dictionary&lt;string, JToken&gt;;\nusing NestedDictionary = Dictionary&lt;string, SmallDictionaly&gt;;\n</code></pre>\n<p>As their name implies, type aliases do not create any new types, they simply introducing a scoped alias that refers to the aliased type.</p>\n<p>The only real drawback to type aliases is that they cannot be generic.</p>\n<p>Moving on the the logic itself,</p>\n<p>There's no need to write a loop over the dictionary entries to copy them into it new dictionary.</p>\n<p><code>Dictionary&lt;TKey, TValue&gt;</code> provides a constructor which takes an <code>IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;</code> allowing us to specify its initial contents.</p>\n<pre><code>return new Dictionary&lt;string, Dictionary&lt;string, JToken&gt;&gt;(configurationEntry);\n</code></pre>\n<p>or</p>\n<pre><code>return new NestedDictionary(configurationEntry);\n</code></pre>\n<p>Thanks to the type alias</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T19:11:33.560", "Id": "484949", "Score": "0", "body": "Thanks for an answer, accepting your answer, also can't gave up on type alias, since it's design guideline of my task :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T21:29:54.527", "Id": "484956", "Score": "1", "body": "You mean you have a requirement to create subtypes that don't add any functionality butter nominally differentiated from their base types? That's a very odd guideline. What's the use case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T01:04:02.150", "Id": "484975", "Score": "1", "body": "You asked the correct questions, what is the use case and what are the requirements. Just next time don't answer a question until the use cases and requirements are clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T06:55:04.657", "Id": "485122", "Score": "0", "body": "Use case is just to give name to complex dictionaries in domain objects of ASP.Net web service, since it used in a multiple places, we didn't wanted to use type alias, but actual class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T09:44:58.207", "Id": "485138", "Score": "0", "body": "That rational seems weak. It's also an abuse of incidental extensibility. Consider sealed types and value types. For example your approach wouldn't work for `KeyValuePair<string, IEnumerable<Func<string, bool>>>`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T16:35:11.777", "Id": "247688", "ParentId": "247677", "Score": "1" } } ]
{ "AcceptedAnswerId": "247688", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T14:07:05.307", "Id": "247677", "Score": "3", "Tags": [ "c#" ], "Title": "Most elegant way to copy type alias class to original collection" }
247677
<p>This code below converts number from decimal to fraction. I don't know if there's a better way or better methods to do this job so any advice would be appreciated.</p> <pre><code>const toFraction = (inputNumber) =&gt; { // Only two digits after decimal point inputNumber = inputNumber.toFixed(2); // destructure number let [int, dec] = inputNumber .toString() .split(&quot;.&quot;) .map((el) =&gt; parseInt(el)); // Round it up to nearst multiple of 5 dec = Math.ceil(dec / 5) * 5; // Keep Dividing until it's impossible const divide = [9, 8, 7, 6, 5, 4, 3, 2]; let hundred = 100; let notOver = true; while (notOver) { notOver = false; for (let num of divide) { if (dec % num === 0 &amp;&amp; hundred % num === 0) { dec /= num; hundred /= num; notOver = true; } } } return int === 0 ? `${dec}${hundred}` : `${int} ${dec}/${hundred}`; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T14:58:35.807", "Id": "484916", "Score": "0", "body": "Why limit it to 2 decimal places?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:03:05.637", "Id": "484917", "Score": "0", "body": "I have used it in a project that only needs two decimal points but you're right. I'll edit it to cover more digits" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:08:13.873", "Id": "484918", "Score": "1", "body": "I suggest that you also add few test cases; with \"console.log\" outputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:11:34.427", "Id": "484920", "Score": "0", "body": "You seem to have missed a \"/\" in the first part of the output test `${dec}/${hundred}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:39:04.307", "Id": "484924", "Score": "0", "body": "Thanks for advice! I've added tests and missing \"/\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:41:52.723", "Id": "484925", "Score": "1", "body": "Great. You had my upvote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T04:42:17.230", "Id": "484983", "Score": "1", "body": "Please don't change or add to the code in your question after you have received answers. This makes it hard to understand the answers with respect to the version of code that they are referring to. You can put the improvements in a new follow-up question instead. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)" } ]
[ { "body": "<p>You can remove the <code>toString()</code> bit from here:</p>\n<pre><code> let [int, dec] = inputNumber\n .toString()\n .split(&quot;.&quot;)\n .map((el) =&gt; parseInt(el));\n</code></pre>\n<p><code>toFixed</code> returns a string. So, there is no need to call <code>toString</code> again.</p>\n<hr />\n<p>The calculation part:</p>\n<p>If the decimal part is <code>12</code>, your output is <code>3/25</code>. How do you get this? You get the <a href=\"https://en.wikipedia.org/wiki/Greatest_common_divisor\" rel=\"noreferrer\">greatest common divisor</a> between 12 and 100 and divide both of them with it. GCD of 12 and 100 is 4. So, (12/4) / (100/4)</p>\n<p>There's already a simple recursive implementation of <a href=\"https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations\" rel=\"noreferrer\">euclidean algorithm</a> for that:</p>\n<pre><code>function gcd(a, b)\n if b = 0\n return a\n else\n return gcd(b, a mod b)\n</code></pre>\n<p>You can get the <code>precision</code> required as an option parameter which defaults to a predefined <code>MAX_PRECISION</code>. Get the GCD between the <code>dec</code> and 10 <sup>precision</sup> (eg: 100 for precision = 2)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const MAX_PRECISION = 5\n\nfunction toFraction(inputNumber, precision = MAX_PRECISION) {\n let [int, dec] = inputNumber\n .toFixed(precision)\n .split(\".\")\n .map(n =&gt; +n)\n \n const powerOf10 = 10 ** precision,\n gcd = getGCD(dec, powerOf10),\n fraction = `${dec/gcd}/${powerOf10/gcd}`;\n \n return int ? `${int} ${fraction}` : fraction\n};\n\nfunction getGCD(a, b) {\n if (!b) return a;\n\n return getGCD(b, a % b);\n};\n\nconsole.log( toFraction(1.14) );\nconsole.log( toFraction(5.71) );\nconsole.log( toFraction(3.34) );\nconsole.log( toFraction(5.1044) );\nconsole.log( toFraction(0.67) );\nconsole.log( toFraction(0.84) );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:28:01.487", "Id": "484922", "Score": "0", "body": "Thanks for your great solution. Actually i round the number to nearest multiple of 5 so 0.12 becomes 0.15 and it's get divided by 5 and result become 3/20" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:35:58.637", "Id": "484923", "Score": "0", "body": "@user3756068 Is it required to round it to nearest multiple of 5? You can still add that part to the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:43:04.990", "Id": "484926", "Score": "1", "body": "I'm using this code for a food recipe ingredients to calculate amount of the unit. It can be more precise but in this case it's not required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T06:23:18.963", "Id": "484996", "Score": "0", "body": "The above information that the code is used in a food recipe should have gone into the question instead. It's important to have these details in the description since then we can decide whether the precision is good enough." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:16:51.357", "Id": "247680", "ParentId": "247678", "Score": "7" } } ]
{ "AcceptedAnswerId": "247680", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T14:28:27.057", "Id": "247678", "Score": "7", "Tags": [ "javascript", "mathematics" ], "Title": "Convert Decimal to Fraction" }
247678
<p>I've been working on my Rust a bit and want to know how idiomatic my rust code is for the following Project Euler problem: <code>What is the largest prime factor of the number 600851475143 ?</code></p> <p>I'm not looking for ways to improve efficiency or how to improve the strategy, but purely what I can improve with my Rust technique. There's two files: <code>src/prime/sieve.rs</code> which has a function for generating a vector of prime numbers, and <code>src/p003.rs</code> which is where the problem is solved.</p> <pre><code>// src/prime/sieve.rs pub fn sieve(ceil: usize) -&gt; Vec&lt;usize&gt; { let mut is_prime = vec![true; ceil + 1]; is_prime[0] = false; if ceil &gt;= 1 { is_prime[1] = false } for num in 2..ceil + 1 { if is_prime[num] { let mut factor = num * num; while factor &lt;= ceil { is_prime[factor] = false; factor += num; } } } is_prime .iter() .enumerate() .filter_map(|(p, &amp;is_p)| if is_p { Some(p) } else { None }) .collect() } </code></pre> <pre><code>// src/prime/mod.rs pub mod sieve; </code></pre> <pre><code>// src/p003.rs // https://projecteuler.net/problem=3 mod prime; use prime::sieve::sieve; fn biggest_prime_factor(n: usize) -&gt; usize { for p in sieve((600851475143_f32.sqrt()) as usize).iter().rev() { if n % *p == 0 { return *p; } } return 0; } fn main() { println!(&quot;{}&quot;, biggest_prime_factor(600851475143)); } </code></pre>
[]
[ { "body": "<p>I think</p>\n<pre class=\"lang-rust prettyprint-override\"><code> for p in sieve((600851475143_f32.sqrt()) as usize).iter().rev() {\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rust prettyprint-override\"><code> for p in sieve(((n as f32).sqrt()) as usize).iter().rev() {\n</code></pre>\n<h3>Alternative approach</h3>\n<p>You could chain an iterator in runtime:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[test]\nfn main_playground() {\n // Sieve iterator-style\n let number: u128 = 600851475143;\n let upper_limit: u128 = (number as f32).sqrt().floor() as _;\n\n let mut sieve: Box&lt;dyn Iterator&lt;Item = _&gt;&gt; = Box::new(2..=upper_limit);\n\n while let Some(prime_number) = sieve.next() {\n sieve = Box::new(sieve.filter(move |&amp;x| x % prime_number != 0));\n if number % (prime_number as u128) == 0 {\n dbg!(prime_number);\n }\n }\n}\n</code></pre>\n<p>The answer is still <code>6857</code>. But output is</p>\n<pre><code>running 1 test\n[src\\problem_003.rs:12] prime_number = 71 \n[src\\problem_003.rs:12] prime_number = 839 \n[src\\problem_003.rs:12] prime_number = 1471\n[src\\problem_003.rs:12] prime_number = 6857\n</code></pre>\n<p>I can think of many more approaches to this. I'd actually build a <code>Sieve</code> iterator\nif I were you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T11:42:59.283", "Id": "258917", "ParentId": "247681", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:17:32.450", "Id": "247681", "Score": "5", "Tags": [ "rust" ], "Title": "Largest Prime factor (Project Euler in Rust)" }
247681
<p>So I have been working on this Chess project and for that I need a move generator. I wish to know if I can improve my code for the move generation for the <strong>Knight</strong>. Here is my current code;</p> <p>Let me tell a few things so you can better understand it. I am using <code>vector&lt;vector&lt;int&gt;&gt;</code> for the main <em>pseudo</em> moves. I use add the move to a <code>vector&lt;int&gt;</code> first, then I add it to the <code>pseudomoves</code>.</p> <p>The board is simply represented with <code>int board[8][8]</code>. Here are the values and the pieces that they correspond to;</p> <ul> <li>1-Pawn</li> <li>2-Bishop</li> <li>3-Knight</li> <li>5-Rook</li> <li>6-Queen</li> <li>10-King</li> </ul> <p>The negative of the same numbers correspond to the black pieces!</p> <p>This is the code for generating all moves of the knight.</p> <pre><code> if (row &gt; 0 &amp;&amp; col &lt; 6 &amp;&amp; board[row-1][col+2] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row-1); move.push_back(col+2); pseudomoves.push_back(move); move.clear(); } if (row &gt; 1 &amp;&amp; col &lt; 7 &amp;&amp; board[row-2][col+1] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row-2); move.push_back(col+1); pseudomoves.push_back(move); move.clear(); } if (row &lt; 7 &amp;&amp; col &lt; 6 &amp;&amp; board[row+1][col+2] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row+1); move.push_back(col+2); pseudomoves.push_back(move); move.clear(); } if (row &lt; 6 &amp;&amp; col &lt; 7 &amp;&amp; board[row+2][col+1] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row+2); move.push_back(col+1); pseudomoves.push_back(move); move.clear(); } if (row &lt; 6 &amp;&amp; col &gt; 0 &amp;&amp; board[row+2][col-1] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row+2); move.push_back(col-1); pseudomoves.push_back(move); move.clear(); } if (row &lt; 7 &amp;&amp; col &gt; 1 &amp;&amp; board[row+1][col-2] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row+1); move.push_back(col-2); pseudomoves.push_back(move); move.clear(); } if (row &gt; 1 &amp;&amp; col &gt; 0 &amp;&amp; board[row-2][col-1] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row-2); move.push_back(col-1); pseudomoves.push_back(move); move.clear(); } if (row &gt; 0 &amp;&amp; col &gt; 2 &amp;&amp; board[row-2][col-1] &lt;= 0){ move.push_back(row); move.push_back(col); move.push_back(row-2); move.push_back(col-1); pseudomoves.push_back(move); move.clear(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T22:44:05.863", "Id": "484960", "Score": "4", "body": "Welcome to code review. This question currently has 3 votes to close because it is a snippet of code and not even a full function. We have no context on how the code is being used by the class or the program. To help optimize the code we need to have a good idea of how the code is being used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T22:57:50.847", "Id": "484963", "Score": "2", "body": "While the purpose of the program was different, you might want to looks at KMMoveFilters.cpp in my [third question on code review](https://codereview.stackexchange.com/questions/132876/knights-tour-improved-refactored-recursive-breadth-first-search-for)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T05:28:46.240", "Id": "484987", "Score": "0", "body": "Okay i am sorry for that, i just joined this community i didn't know i have to post the full code" } ]
[ { "body": "<p>Of course this can be improved. Look at all the repetition... then, factor it out into a function. You'll end up with something like this:</p>\n<pre><code>pseudomoves.push_back_if_legal(row, col, row-1, col+2);\npseudomoves.push_back_if_legal(row, col, row-2, col+1);\npseudomoves.push_back_if_legal(row, col, row+1, col+2);\npseudomoves.push_back_if_legal(row, col, row+2, col+1);\npseudomoves.push_back_if_legal(row, col, row+2, col-1);\npseudomoves.push_back_if_legal(row, col, row+1, col-2);\npseudomoves.push_back_if_legal(row, col, row-2, col-1);\npseudomoves.push_back_if_legal(row, col, row-2, col-1);\n</code></pre>\n<p>As a bonus, it is now relatively obvious where the bug is!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:49:40.590", "Id": "484928", "Score": "0", "body": "I am looking to decrease the time taken to run it. I wanted to know if there was anything to improce in the LOGIC part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:51:16.217", "Id": "484929", "Score": "0", "body": "Also , pseudo moves is a vector of vectors. This means i need to make another vector. Add the values. Then add it to pseudomoves." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T16:20:48.543", "Id": "484930", "Score": "3", "body": "\"Make it correct; *then* make it fast.\" Your way of writing it failed to make it correct. I offer you a better path. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T16:29:07.420", "Id": "484932", "Score": "0", "body": ":), Thanks for this! I will implement it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:40:49.580", "Id": "247684", "ParentId": "247682", "Score": "3" } } ]
{ "AcceptedAnswerId": "247684", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T15:23:19.483", "Id": "247682", "Score": "0", "Tags": [ "c++", "chess" ], "Title": "Move generation n c++ for Knight" }
247682
<p>I am writing some code that takes and returns interfaces following the patterns in <em>Effective Java Third Edition</em>. I understand the principle - we want to take in interfaces because in many cases we don't really care about the discrete implementation but rather just the features of this interface. We return interfaces for the same reason. It gives the caller the ability to use the preferred implementation class. Take this extreme contrived example:</p> <pre><code>import java.util.*; public class Main { public static List&lt;Integer&gt; op(List&lt;Integer&gt; is) { ArrayList&lt;Integer&gt; results = new ArrayList&lt;&gt;(); for (Integer i : is) { results.add(i + 1); } return results; } public static void main(String[] args) { ArrayList&lt;Integer&gt; nums = new ArrayList(Arrays.asList(1,2,3,4)); // This line ArrayList&lt;Integer&gt; results = (ArrayList&lt;Integer&gt;) op(nums); System.out.println(results); } } </code></pre> <p>So if the caller of <code>op</code> wanted to use a <code>LinkedList</code> they could through simple casting. But to me this feels clunky. In my codebase it is littered with various casts that seem to hinder readability.</p> <p>Is there a smarter way to do this? Or is this explicit casting the only way to do this properly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T18:13:14.393", "Id": "484947", "Score": "0", "body": "Why would the caller want a linked list? Why would the caller need to know what type of list is used? Why not just declare results as List<Integer> ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T18:29:24.520", "Id": "484948", "Score": "1", "body": "@TedBrownlow One idea could be that the caller may want a different access type. For example, appending to a LinkedList is O(1) vs ArrayList O(N) and they may want to append more after running `op` on the list. A similar argument could be made for removal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T20:26:24.633", "Id": "484952", "Score": "0", "body": "try with `public static <T, K extends List<T>> K op(List<T> is)` and `return (K)results` I can tell that such construction worked fine in a different context for me." } ]
[ { "body": "<p>Let me clarify something fist</p>\n<blockquote>\n<p>It gives the caller the ability to use the preferred implementation class.</p>\n</blockquote>\n<p>Even if we return interface from method, that doesn't mean that that caller can choose implementation.'</p>\n<blockquote>\n<p>So if the caller of op wanted to use a LinkedList they could through simple casting.</p>\n</blockquote>\n<p>If you mean something like <code>(LinkedList&lt;Integer&gt;) op(nums)</code>, then this wont work and will throw <code>java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.LinkedList</code>.</p>\n<p>When method returns interface, in general, you shouldn't assume specific implementation, and thus should avoid such castings. Having interface here, for example, will give more freedom to the author of this method for future changes: imagine someone will write <code>SuperPerfectList</code> which works better than any other list and author decides to use it. In this case even if method changes, we won't need to refactor every place in our code where we call this method, because signature of this method hasn't changed.</p>\n<p>If we talk about the situation where we want another implementation of this interface, then, in case of list, we can do <code>new LinkedList(result)</code> and get what we want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:09:30.577", "Id": "485124", "Score": "0", "body": "Or if we feel that copying the results is too inefficient, you could change the method signature to take an empty results list as a parameter, which obviously could be any List implementation you wish." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T11:09:59.417", "Id": "247711", "ParentId": "247690", "Score": "2" } }, { "body": "<p>Another way could be to pass a factory method. It is pretty close to the comment of tgdavies, passing an empty list. But with a factory method, multiple new instances can be requested if necessary. For example:</p>\n<pre><code>public static &lt;T extends List&lt;Integer&gt;&gt; T op(final List&lt;Integer&gt; list, final Supplier&lt;T&gt; factory) {\n final T results = factory.get();\n ...\n return results;\n}\n</code></pre>\n<p>Calling it would look like:</p>\n<pre><code>final ArrayList&lt;Integer&gt; list = op(asList(1, 2, 3), ArrayList::new);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:06:45.860", "Id": "247847", "ParentId": "247690", "Score": "0" } }, { "body": "<p>I feel like you are misunderstanding a few things about working with interfaces. In your <code>op()</code> method you are creating an <code>ArrayList</code>. The type of the List is then &quot;locked in&quot; and cannot be changed. Even if you return only the <code>List</code> interface, the underlying object will still be an <code>ArrayList</code>. As Flame's answer already mentioned, you cannot cast this object to <code>LinkedList</code> because they are not compatible.</p>\n<p>So there are two options:</p>\n<ol>\n<li><p>Be specific about which kind of List implementation you are using. This means changing the return type of <code>op()</code> to <code>ArrayList</code>. The caller can then use all the functionality specified by <code>ArrayList</code>.</p>\n</li>\n<li><p>Keep your declaration as it is. The caller then has to work with only the <code>List</code> interface and cannot work with any extended functionality that the <code>ArrayList</code> provides. That is because it cannot make any guarantees which implementation is used.</p>\n</li>\n</ol>\n<p>I'd choose option 2 since very rarely does one need functionality which isn't already provided by the <code>List</code> interface. And again, in general, you cannot change the implementation from <code>ArrayList</code> to <code>LinkedList</code> by casting. You'd need to create a new List with the desired implementation and copy all the contents into it. An easy way to do this is: <code>new LinkedList&lt;&gt;(someArrayList);</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T09:59:43.747", "Id": "247891", "ParentId": "247690", "Score": "0" } } ]
{ "AcceptedAnswerId": "247711", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T18:10:06.160", "Id": "247690", "Score": "3", "Tags": [ "java", "interface", "casting" ], "Title": "Returning interfaces in Java without significant casting" }
247690
<p>I have an app whose sole purpose is to seed data files and add the data to different CSVs which are zipped and exported by the user. My application controller is filled with lines that all look like this:</p> <pre><code> def export_tips @appointments = Appointment.order('service_id') send_data @appointments.to_csv_tips, filename: 'tips.csv' end def export_ticketpayments @appointments = Appointment.order('service_id') send_data @appointments.to_csv_ticketpayments, filename: 'ticketspaymentitems.csv' end def export_batchmanifest @batchmanifests = Batchmanifest.all send_data @batchmanifests.to_csv_batchmanifest, filename: &quot;batch_manifest-#{Date.today}.csv&quot; end def export_pets @clients = Client.all send_data @clients.to_csv_pets, filename: 'pets.csv' end def export_clients @clients = Client.all send_data @clients.to_csv_clients, filename: 'clients.csv' end </code></pre> <p>I have it in the application controller because I used it in multiple different areas including creating single CSV exports and creating complex zip files with multiple zips and CSVs inside.</p> <p>Some things that I have tried to cleanup the code include:</p> <ul> <li>Different variables of this: def csv_export (model, filename) @model.pluralize = (model.titleize).all send_data @model.pluralize.filename, filename: filename end</li> <li>Having each one in its own controller (could not access them from different views and other controllers easily)</li> <li>I also tried to figure out how to create my own module, but was unable to do so.</li> </ul> <p>My application record is just as bad with repeated lines simply meant to export the CSVs:</p> <pre><code> def self.to_csv_appointments attributes = %w[appointment_id location_id employee_id client_id child_id notes has_specific_employee start_time end_time] CSV.generate(headers: true) do |csv| csv &lt;&lt; attributes all.each do |appointment| csv &lt;&lt; attributes.map { |attr| appointment.send(attr) } end end end def self.to_csv_appointmentservices attributes = %w[appointment_id service_id price duration] CSV.generate(headers: true) do |csv| csv &lt;&lt; attributes all.each do |appointment| csv &lt;&lt; attributes.map { |attr| appointment.send(attr) } end end end def self.to_csv_tickets attributes = %w[ticket_id location_id client_id ticket_status employee_id employee_id start_time] headers = %w[ticket_id location_id client_id status employee_id closed_by_employee_id closed_at] CSV.generate(headers: true) do |csv| csv &lt;&lt; headers all.each do |appointment| csv &lt;&lt; attributes.map { |attr| appointment.send(attr) } end end end </code></pre> <p>For the application record, I have tried similar methods as those listed for the application controller, but to no avail. Again, I use the code in application record instead of in the individual model files because I need to access these in multiple parts of the site.</p> <p>The code from the application controller is used mostly in the static controller and buttons on the view files. I need the ability to create the file sets, as listed below, but also allow the user to export just one CSV.</p> <p>Examples from static controller to built the zip files:</p> <pre><code>def create_appointments_zip file_stream = Zip::OutputStream.write_buffer do |zip| @appointments = Appointment.order('service_id') zip.put_next_entry &quot;appointment_manifest.csv&quot;; zip &lt;&lt; File.binread(&quot;#{Rails.root}/app/assets/csvs/appointment_manifest.csv&quot;) zip.put_next_entry &quot;appointments.csv&quot;; zip &lt;&lt; @appointments.to_csv_appointments zip.put_next_entry &quot;appointment_services.csv&quot;; zip &lt;&lt; @appointments.to_csv_appointmentservices zip.put_next_entry &quot;appointment_statuses.csv&quot;; zip &lt;&lt; @appointments.to_csv_appointmentstatuses end file_stream.rewind File.open(&quot;#{Rails.root}/app/assets/csvs/appointments.zip&quot;, 'wb') do |file| file.write(file_stream.read) end end def export_salonset create_appointments_zip create_tickets_zip create_inventory_zip create_memberships_zip file_stream = Zip::OutputStream.write_buffer do |zip| @saloncategories = Saloncategory.all @salonservices = Salonservice.all @clients = Client.all @locations = Location.all @salonpricings = Salonpricing.all @staffs = Staff.order(&quot;location_id&quot;) zip.put_next_entry &quot;batch_manifest.csv&quot;; zip &lt;&lt; File.binread(&quot;#{Rails.root}/app/assets/csvs/batch_manifest_simple_salon.csv&quot;) zip.put_next_entry &quot;categories.csv&quot;; zip &lt;&lt; @saloncategories.to_csv_saloncategories zip.put_next_entry &quot;clients.csv&quot;; zip &lt;&lt; @clients.to_csv_clients zip.put_next_entry &quot;employees.csv&quot;; zip &lt;&lt; @staffs.to_csv_staff zip.put_next_entry &quot;locations.csv&quot;; zip &lt;&lt; @locations.to_csv_locations zip.put_next_entry &quot;pricings.csv&quot;; zip &lt;&lt; @salonpricings.to_csv_pricings zip.put_next_entry &quot;services.csv&quot;; zip &lt;&lt; @salonservices.to_csv_salonservices zip.put_next_entry &quot;appointments.zip&quot;; zip &lt;&lt; File.binread(&quot;#{Rails.root}/app/assets/csvs/appointments.zip&quot;) zip.put_next_entry &quot;inventories.zip&quot;; zip &lt;&lt; File.binread(&quot;#{Rails.root}/app/assets/csvs/inventories.zip&quot;) zip.put_next_entry &quot;tickets.zip&quot;; zip &lt;&lt; File.binread(&quot;#{Rails.root}/app/assets/csvs/tickets.zip&quot;) zip.put_next_entry &quot;addonmappings.csv&quot;; zip &lt;&lt; File.binread(&quot;#{Rails.root}/app/assets/csvs/addonmappings.csv&quot;) end file_stream.rewind respond_to do |format| format.zip do send_data file_stream.read, filename: &quot;salon_set.zip&quot; end end file_stream.rewind File.open(&quot;#{Rails.root}/app/assets/csvs/salon_set.zip&quot;, 'wb') do |file| file.write(file_stream.read) end end </code></pre> <p>Link to my repository, if that is helpful <a href="https://github.com/atayl16/data-wizard/blob/master/app/controllers/application_controller.rb" rel="nofollow noreferrer">https://github.com/atayl16/data-wizard/blob/master/app/controllers/application_controller.rb</a> <a href="https://github.com/atayl16/data-wizard/blob/master/app/models/application_record.rb" rel="nofollow noreferrer">https://github.com/atayl16/data-wizard/blob/master/app/models/application_record.rb</a></p> <p>I know there must be a better way than writing these same lines over and over. The code works, my site works (amazingly), but I would be embarrassed for any seasoned developer to see the repository without laughing. Any help is appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T22:25:45.217", "Id": "484957", "Score": "3", "body": "Welcome to Code Review, I hope someone here can help you. You might want to try creating a list of CSV files that you can pass into a generic function that generates the zip files. I don't know ruby so I can't help beyond that." } ]
[ { "body": "<p>First thing I would do is separate CSV serialization from export data generation. For example the export data generation could be:</p>\n<pre><code> def self.to_export\n attributes = %w[appointment_id location_id employee_id client_id child_id notes \n has_specific_employee start_time end_time]\n all.map do |appointment|\n attributes.map { |attr| appointment.send(attr) }\n end\n end\n end\n</code></pre>\n<p>Then you'd have a method that takes an array of primitive Ruby objects and serializes to CSV.</p>\n<p>The fancy name for this is <a href=\"https://www.rubyguides.com/2019/09/rails-patterns-presenter-service/\" rel=\"nofollow noreferrer\">presenter pattern</a>.</p>\n<p>Your zip file method is similar in that it does data processing, CSV serialization and zip export. Have one method that builds the data you want, (re)use the CSV serialization we just went over, add another method that takes a file and creates a zip file from it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T20:13:15.717", "Id": "248053", "ParentId": "247695", "Score": "2" } }, { "body": "<p>Thank you everyone for the advice! Adding in another thing I did to get the controllers cleaned up. I ended up using metaprogramming to clean my export controllers up. Here is an example in which I excluded some items from the array for brevity:</p>\n<pre><code> [&quot;bundle&quot;, &quot;attendee&quot;, &quot;location&quot;, &quot;membership&quot;, &quot;client&quot;, &quot;staff&quot;].each do |new_method|\n define_method(&quot;#{new_method.pluralize}&quot;) do\n instance_variable_set(&quot;@#{new_method.pluralize}&quot;, new_method.camelcase.constantize.all)\n instance_var = instance_variable_get(&quot;@#{new_method.pluralize}&quot;)\n send_data instance_var.public_send(&quot;to_csv_#{new_method.pluralize}&quot;), filename: &quot;#{new_method.pluralize}.csv&quot;\n end\n end\n</code></pre>\n<p>I was able to remove 30 methods from my newly created export controller. Here is the code after pushing up the changes <a href=\"https://github.com/atayl16/data-wizard/blob/0011b6cf8c1fe967d73a569fa573cedc52cb8c72/app/controllers/export_controller.rb\" rel=\"nofollow noreferrer\">https://github.com/atayl16/data-wizard/blob/0011b6cf8c1fe967d73a569fa573cedc52cb8c72/app/controllers/export_controller.rb</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T09:50:44.047", "Id": "248081", "ParentId": "247695", "Score": "0" } }, { "body": "<p>Noticed that you call <code>new_method.pluralize</code> five times in each pass through the loop. It's a small thing, but setting a variable once on each pass through would be slightly more efficient...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-30T07:05:45.270", "Id": "248647", "ParentId": "247695", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T21:02:47.827", "Id": "247695", "Score": "4", "Tags": [ "beginner", "ruby", "ruby-on-rails" ], "Title": "App to seed DB, generate CSVs, and export individually or in complex zip files Rails 5" }
247695
<p>Wrote this program out of curiosity after initially solving the Word Chains puzzle. Explanation of puzzle in link below.</p> <p><a href="http://rubyquiz.com/quiz44.html" rel="nofollow noreferrer">http://rubyquiz.com/quiz44.html</a></p> <p>NWordChains#find_word_chains will take in a number as an arg and return that amount of random word chains from a given dictionary. Initialize NWordChains.new and then run find_word_chains with the number of pairs that you would like returned.</p> <p>My question is are there any quick glaring spots where this code could be DRYed up? Looking for any quick feedback, trying to learn how to think DRYily.</p> <p>NOTE: You will need a dictionary.txt file of your own to run the code. I found one here if you'd like to use it: <a href="https://github.com/dwyl/english-words/blob/master/words.txt" rel="nofollow noreferrer">https://github.com/dwyl/english-words/blob/master/words.txt</a></p> <pre><code>require_relative &quot;word_chains&quot; require 'set' class NWordChains &lt; WordChains def initialize words = File.readlines(&quot;dictionary.txt&quot;).map(&amp;:chomp) @dictionary = Array.new(words) @all_paths = Hash.new { |h, k| h[k] = [] } @invalid_comps = Set.new end def find_word_chains(num) count = 0 until count == num word_pair = two_rand_eql_length_words redo if invalid_pair?(word_pair) word1 = word_pair[0] word2 = word_pair[1] path_search = WordChains.new(word1, word2) if path_search.find_path == false @invalid_comps &lt;&lt; [ word1, word2 ] else all_paths_key = &quot;#{word1.upcase + ' ' + &quot;to&quot; + ' ' + word2.upcase}&quot; @all_paths[all_paths_key] &lt;&lt; path_search.path count += 1 end end @all_paths end attr_reader :all_paths def two_rand_eql_length_words word1 = @dictionary.sample narrowed_dict = self.narrow_dict_params(word1) word2 = narrowed_dict.sample [ word1, word2 ] end def invalid_pair?(word_pair) @invalid_comps.include?(word_pair) || @invalid_comps.include?(word_pair.reverse) end end #---------------------------------------------------- class WordChains def initialize(beginning_word, target_word) @origin_word = beginning_word @current_word = beginning_word @target_word = target_word words = File.readlines(&quot;dictionary.txt&quot;).map(&amp;:chomp) @dictionary = Array.new(words) @narrowed_dict = self.narrow_dict_params(@origin_word) @path = [ @origin_word ] end attr_accessor :current_word, :target_word, :dictionary, :path, :dead_ends, :invalid_words def find_path return false if @origin_word == @target_word until @path.include?(@origin_word) &amp;&amp; @path.include?(@target_word) valid_words = find_valid_words(@current_word) if !valid_words.empty? find_and_move_to_next_word(@current_word, valid_words) else # In my version of the puzzle solution, if a dead end has been reached # than the program assumes no path could be found. return false end end return false if @path.length == 2 @path end def narrow_dict_params(origin_word) narrowed_dict = @dictionary.select { |word| word.length == origin_word.length } narrowed_dict end def find_and_move_to_next_word(current_word, valid_words) next_word = word_moving_towards_target(valid_words) @path &lt;&lt; next_word @current_word = next_word end def word_moving_towards_target(valid_words) count_hash = Hash.new { |h, k| h[k] = 0 } valid_words.each do |word| count = 0 (0...word.length).each do |i| count += 1 if word[i] == @target_word[i] end count_hash[word] += count end sorted_hash = count_hash.sort_by { |k, v| v } sorted_hash[-1][0] end def find_valid_words(current_word) valid_words = @narrowed_dict.select { |word| word if valid_word?(word) } valid_words end def valid_word?(word) word != @current_word &amp;&amp; last_word_compatible?(word) &amp;&amp; target_compatible?(word) &amp;&amp; !path.include?(word) end def last_word_compatible?(word) count = 0 (0...word.length).each do |i| count += 1 if word[i] != @current_word[i] end return false if count &gt; 1 true end def target_compatible?(word) count = 0 (0...word.length).each do |i| count += 1 if word[i] == @target_word[i] end return true if count &gt;= 1 false end end </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T23:17:50.827", "Id": "247696", "Score": "1", "Tags": [ "beginner", "ruby" ], "Title": "Random Word Chain Finder in Ruby" }
247696
<p>I have just written this code that takes an initial coordinate and returns a new vector depending on a user-supplied range and bearing.</p> <p>The calculation of the new position is done using Complex Numbers. I am sure there are easier ways to do this, but I wanted to play around with complex numbers. Any thoughts on these would be great.</p> <p>The calculator is in a file called GenGeo, as this is where I keep lots of little modules like this that may be called again in other programs.</p> <p>I have used <code>**kwargs</code> for <code>a_e</code> and <code>a_n</code> as these may not be required by the user. However, I have never really used <code>*args</code> and <code>**kwargs</code> before, so presume that I may have messed something up here.</p> <p>This is the calculator module in GenGeo:</p> <pre class="lang-py prettyprint-override"><code>class CmO: &quot;&quot;&quot; This class will contain specific code that is required to run a C-O calculation This includes range and bearing calc &quot;&quot;&quot; def __init__(self, *args, **kwargs): &quot;&quot;&quot; :param a_e: initial easting :param a_n: initial northing &quot;&quot;&quot; self.a_e = kwargs.get('a_e', None) self.a_n = kwargs.get('a_n', None) def complex_randb(self, r, b): &quot;&quot;&quot; An equation that using imaginary numbers to calculate the coordinates of a new point from a range and bearing of an old point :param r: range from original coordinate to new coordinate :param b: bearing from original coordinate to new coordinate &quot;&quot;&quot; # -b is required as geodetic bearings are opposite to mathematical bearings t = complex(cos(radians(-b)), sin(radians(-b))) * complex(0, r) delta_easting = t.real delta_northing = t.imag if self.a_e and self.a_n is not False: new_easting = self.a_e + delta_easting new_northing = self.a_n + delta_northing return new_easting, new_northing else: return delta_easting, delta_northing </code></pre> <p>and this is the program that I have used to call it:</p> <pre class="lang-py prettyprint-override"><code>from GenGeo import CmO initial_E = 100 initial_N = 100 input_range = 3 input_bearing = 310 a = CmO(a_e=initial_E, a_n=initial_N) nE, nN = a.complex_randb(input_range, input_bearing) print(f&quot;The delta Easting and Northing are {round(nE, 3)}mE and {round(nN, 3)}mN&quot;) </code></pre> <p>Next project is writing something to calculate the range and bearing between two points</p> <p>Any thoughts or improvements would be greatly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T00:12:25.113", "Id": "484971", "Score": "1", "body": "Why are the initial easting and northing optional? Removing them from the second snippet results in an error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T00:32:57.880", "Id": "484974", "Score": "0", "body": "@TedBrownlow - Very good point, oops. I have updated the code so that this is now actually an optional statement" } ]
[ { "body": "<h1>Keyword-only parameters</h1>\n<p>You are not using <code>**kwargs</code> correctly. <code>**kwargs</code> should be used when you can accept any number of keywords, but you don't know what the keywords will be, such as dictionary creation. If you only accept 2 keyword parameters, you should list those keyword parameters explicitly:</p>\n<pre><code> def __init__(self, *, a_e=None, a_n=None):\n &quot;&quot;&quot;\n :param a_e: initial easting\n :param a_n: initial northing\n &quot;&quot;&quot;\n\n self.a_e = a_e\n self.a_n = a_n\n</code></pre>\n<p>That <code>*</code> marks the end of positional parameters. <code>a_e</code> and <code>a_n</code> can be specified by keyword only. Since both default to <code>None</code>, both are optional. Any other keywords is reject with an error message, instead of silently being ignored.</p>\n<h1>Operator Precedence</h1>\n<pre><code> if self.a_e and self.a_n is not False:\n</code></pre>\n<p>This statement does not do what you think it does. <code>is not</code> is higher precedence than <code>and</code>, so it reads:</p>\n<pre><code> if self.a_e and (self.a_n is not False):\n</code></pre>\n<p>thus, if <code>a_n</code> is never given as <code>False</code>, the result of <code>is not</code> will be <code>True</code>, and the <code>and</code> will always result in the truthiness of <code>a_e</code> only.</p>\n<p>You probably intended the evaluation to be:</p>\n<pre><code> if (self.a_e and self.a_n) is not False:\n</code></pre>\n<p>which tests the truthiness of both <code>a_e</code> and <code>a_n</code>. Sort of. There are very few ways of getting something for which <code>is not False</code> is not true out of that expression. The only way to get to the <code>else</code> expression is if <code>a_e == False</code>, or if <code>a_e</code> held a truthy value and <code>a_n == False</code>. Again, since if the values are not given, they are defaulted to <code>None</code>, and since <code>None and None</code> evaluates to <code>None</code>, and <code>None is not False</code> is a true statement, the <code>if</code> clause would be executed.</p>\n<p>So you probably wanted to write:</p>\n<pre><code> if self.a_e is not None and self.a_n is not None:\n</code></pre>\n<h1>Why not Zero?</h1>\n<p>If you used <code>0</code> as the default for <code>a_n</code> and <code>a_e</code>, then</p>\n<pre><code> new_easting = self.a_e + delta_easting\n new_northing = self.a_n + delta_northing\n</code></pre>\n<p><code>new_easting</code> would simply become <code>delta_easting</code> and <code>new_northing</code> would become <code>delta_northing</code>, and you could always do the addition and return `new_easting, new_northing.</p>\n<pre><code> def __init__(self, *, a_e=0, a_n=0):\n &quot;&quot;&quot;\n :param a_e: initial easting\n :param a_n: initial northing\n &quot;&quot;&quot;\n\n self.a_e = a_e\n self.a_n = a_n\n\n def complex_randb(self, r, b):\n &quot;&quot;&quot;\n An equation that using imaginary numbers to calculate the coordinates of a new\n point from a range and bearing of an old point\n :param r: range from original coordinate to new coordinate\n :param b: bearing from original coordinate to new coordinate\n &quot;&quot;&quot;\n\n # -b is required as geodetic bearings are opposite to mathematical bearings\n t = complex(cos(radians(-b)), sin(radians(-b))) * complex(0, r)\n delta_easting = t.real\n delta_northing = t.imag\n\n new_easting = self.a_e + delta_easting\n new_northing = self.a_n + delta_northing\n\n return new_easting, new_northing\n</code></pre>\n<h1>Naming</h1>\n<p>Your parameter names <code>a_e</code>, <code>a_n</code>, <code>r</code>, and <code>b</code> are too short and cryptic. You should used <code>easting</code> <code>northing</code>, <code>range</code>, and <code>bearing</code>.</p>\n<p><code>complex_randb</code> is also confusing. The input is real, the output is real. The fact that complex numbers are internally used is an internal detail irrelevant to the caller. What is <code>randb</code>, some kind of random b? Oh, <code>range_and_bearing</code>! But it is not a range and bearing function, it is a new coordinate function:</p>\n<pre><code> def new_coordinate(self, range, bearing):\n &quot;&quot;&quot;Doc-string without the complex number internal detail mentioned&quot;&quot;&quot;\n ...\n</code></pre>\n<p>The class name <code>CmO</code> is also quite cryptic. Is that &quot;C minus O&quot; because it runs &quot;C-O&quot; calculations? You need a better class name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T16:45:13.547", "Id": "247722", "ParentId": "247697", "Score": "3" } } ]
{ "AcceptedAnswerId": "247722", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T23:25:00.140", "Id": "247697", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "complex-numbers" ], "Title": "Python Simple Range and Bearing Calculator using Complex Numbers" }
247697
<p>The spreadsheet can be found just above the references section at this link.</p> <p><a href="https://www.sciencedirect.com/science/article/pii/S1872497316301429" rel="nofollow noreferrer">https://www.sciencedirect.com/science/article/pii/S1872497316301429</a></p> <p>It's a publication for STR DNA locus frequencies to calculate match probabilities. I'd like to build a match probability calculator and scale it up to do hundreds of thousands of calculations rather than just one. The first step is loading the frequencies into memory and is the subject of this code. I figured a dataframe for each population set would be alright.</p> <p><strong>The first row</strong> in each worksheet is just a population label. It can be ignored.</p> <p><strong>The second row is the header:</strong> The first column &quot;Allele&quot; is the STR allele call. This is what will be compared to for matching. This will typically be an integer but sometimes can have a decimal of .1, .2, or .3 most commonly. Sometimes they are a string with a greater than or less than symbol (e.g.; &quot;&lt;9.2&quot;, &quot;&gt;17&quot;) although I don't know if there are any in the excel file.</p> <p>The 2nd through 25th columns are the different locations that are tested. Each is independent.</p> <p>I will ignore anything after the 25th column and anything past the last row of frequencies. Most of the data points within these bounds are empty. They will be filled with what is called the minimum allele frequency. If you are interested in anything further I'd be happy to chat, but it's probably not pertinent to the discussion at hand.</p> <p>I'm sure there is a more elegant way to do this and probably a quicker way to do it. That's why I am here. If there's a better structure to put this in, or a faster/more elegant way to do it, please let me know. This is my first stab at it. The frames take about 3 seconds to load all the data. I'm guessing it should be much quicker than that. Anyway, here's my code.</p> <pre><code># -*- coding: utf-8 -*- import pandas as pd #create dataframes for population tables caucasian_freq = pd.DataFrame() swh_freq = pd.DataFrame() seh_freq = pd.DataFrame() agg_aa_freq = pd.DataFrame() aa_freq = pd.DataFrame() bah_freq = pd.DataFrame() jam_freq = pd.DataFrame() trin_freq = pd.DataFrame() cham_freq = pd.DataFrame() fili_freq = pd.DataFrame() apa_freq = pd.DataFrame() nav_freq = pd.DataFrame() #get the file name expanded_frequencies = '1-s2.0-S1872497316301429-mmc1.xlsx' #for the number of columns containing frequencies data_columns = [0,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] #for minimum allele frequency min_freq = [0.0124, 0.0120, 0.0095, 0.0046, 0.012, 0.0159, 0.0141, 0.0316, 0.0263, 0.0550, 0.0130, 0.0175] #import the different freq sets - ignore the first row, don't read anything past column 25 caucasian_freq = pd.read_excel(expanded_frequencies, &quot;Caucasian&quot;, header=1, usecols= data_columns) swh_freq = pd.read_excel(expanded_frequencies, &quot;SW Hispanic&quot;, header=1, usecols= data_columns) seh_freq = pd.read_excel(expanded_frequencies, &quot;SE Hispanic&quot;, header=1, usecols= data_columns) agg_aa_freq = pd.read_excel(expanded_frequencies, &quot;African Amer Bahamian Jamaican&quot;, header=1, usecols= data_columns) aa_freq = pd.read_excel(expanded_frequencies, &quot;African American&quot;, header=1, usecols= data_columns) bah_freq = pd.read_excel(expanded_frequencies, &quot;Bahamian&quot;, header=1, usecols= data_columns) jam_freq = pd.read_excel(expanded_frequencies, &quot;Jamaican&quot;, header=1, usecols= data_columns) trin_freq = pd.read_excel(expanded_frequencies, &quot;Trinidadian&quot;, header=1, usecols= data_columns) cham_freq = pd.read_excel(expanded_frequencies, &quot;Chamorro&quot;, header=1, usecols= data_columns) fili_freq = pd.read_excel(expanded_frequencies, &quot;Filipino&quot;, header=1, usecols= data_columns) apa_freq = pd.read_excel(expanded_frequencies, &quot;Apache&quot;, header=1, usecols= data_columns) nav_freq = pd.read_excel(expanded_frequencies, &quot;Navajo&quot;, header=1, usecols= data_columns) #truncate rows without data - the row after the last row of data is a duplicate of #the header row. Use it to find the last row of data caucasian_freq = caucasian_freq.truncate(after=caucasian_freq.loc[caucasian_freq['Allele'] == 'Allele'].index[0]-1) swh_freq = swh_freq.truncate(after=swh_freq.loc[swh_freq['Allele'] == 'Allele'].index[0]-1) seh_freq = seh_freq.truncate(after=seh_freq.loc[seh_freq['Allele'] == 'Allele'].index[0]-1) agg_aa_freq = agg_aa_freq.truncate(after=agg_aa_freq.loc[agg_aa_freq['Allele'] == 'Allele'].index[0]-1) aa_freq = aa_freq.truncate(after=aa_freq.loc[aa_freq['Allele'] == 'Allele'].index[0]-1) bah_freq = bah_freq.truncate(after=bah_freq.loc[bah_freq['Allele'] == 'Allele'].index[0]-1) jam_freq = jam_freq.truncate(after=jam_freq.loc[jam_freq['Allele'] == 'Allele'].index[0]-1) trin_freq = trin_freq.truncate(after=trin_freq.loc[trin_freq['Allele'] == 'Allele'].index[0]-1) cham_freq = cham_freq.truncate(after=cham_freq.loc[cham_freq['Allele'] == 'Allele'].index[0]-1) fili_freq = fili_freq.truncate(after=fili_freq.loc[fili_freq['Allele'] == 'Allele'].index[0]-1) apa_freq = apa_freq.truncate(after=apa_freq.loc[apa_freq['Allele'] == 'Allele'].index[0]-1) nav_freq = nav_freq.truncate(after=nav_freq.loc[nav_freq['Allele'] == 'Allele'].index[0]-1) #fill in nas with the minimum allele frequency caucasian_freq.fillna(min_freq[0], inplace = True) swh_freq.fillna(min_freq[1], inplace = True) seh_freq.fillna(min_freq[2], inplace = True) agg_aa_freq.fillna(min_freq[3], inplace = True) aa_freq.fillna(min_freq[4], inplace = True) bah_freq.fillna(min_freq[5], inplace = True) jam_freq.fillna(min_freq[6], inplace = True) trin_freq.fillna(min_freq[7], inplace = True) cham_freq.fillna(min_freq[8], inplace = True) fili_freq.fillna(min_freq[9], inplace = True) apa_freq.fillna(min_freq[10], inplace = True) nav_freq.fillna(min_freq[11], inplace = True) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T11:10:03.167", "Id": "485150", "Score": "0", "body": "Please do not update the code in your question after receiving 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*](https://codereview.meta.stackexchange.com/a/1765/52915)." } ]
[ { "body": "<h2>No need to create dataframes beforehand</h2>\n<p>The following code is not needed:</p>\n<pre><code>#create dataframes for population tables\ncaucasian_freq = pd.DataFrame()\nswh_freq = pd.DataFrame()\nseh_freq = pd.DataFrame()\nagg_aa_freq = pd.DataFrame()\naa_freq = pd.DataFrame()\nbah_freq = pd.DataFrame()\njam_freq = pd.DataFrame()\ntrin_freq = pd.DataFrame()\ncham_freq = pd.DataFrame()\nfili_freq = pd.DataFrame()\napa_freq = pd.DataFrame()\nnav_freq = pd.DataFrame()\n</code></pre>\n<p>You do not have to create the dataframes at this point, they will be created in the moment\nyou load the Excel files, that is here:</p>\n<pre><code>caucasian_freq = pd.read_excel(expanded_frequencies, &quot;Caucasian&quot;, header=1, usecols= data_columns)\n</code></pre>\n<h2>Use <code>range</code></h2>\n<p>Generally, instead of defining a long list like this manually</p>\n<pre><code>data_columns = [0,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]\n</code></pre>\n<p>you can use the <code>range</code> function and then convert to a list</p>\n<pre><code>data_columns = list(range(26))\n</code></pre>\n<p>Depending on the application the conversion to list is not necessary.</p>\n<p>Also check out the documentation of pandas' <code>read_excel</code> function. The <code>use_cols</code> parameter can take ranges, too, meaning you do not have to pass every single column index but just the start and end column.</p>\n<h2>More efficient loading of the Excel sheets</h2>\n<p>You can load all the sheets at once by passing <code>None</code> to the <code>sheet_name</code> parameter:</p>\n<pre><code>all_sheets = pd.read_excel(expanded_frequencies, sheet_name=None, header=1, usecols= data_columns) \n</code></pre>\n<p>This outputs an ordered dictionary (search for OrderedDict).</p>\n<p>You can then access the individual sheets like this, for example:</p>\n<pre><code>all_sheets['Caucasian']\n</code></pre>\n<h2>Use for loops</h2>\n<p>You should use for loops to avoid repetitions. Now that you have all the dataframes in one container variable (<code>all_sheets</code>) this has become a lot easier. For example the following block of code</p>\n<pre><code>caucasian_freq = caucasian_freq.truncate(after=caucasian_freq.loc[caucasian_freq['Allele'] == 'Allele'].index[0]-1)\nswh_freq = swh_freq.truncate(after=swh_freq.loc[swh_freq['Allele'] == 'Allele'].index[0]-1)\nseh_freq = seh_freq.truncate(after=seh_freq.loc[seh_freq['Allele'] == 'Allele'].index[0]-1)\nagg_aa_freq = agg_aa_freq.truncate(after=agg_aa_freq.loc[agg_aa_freq['Allele'] == 'Allele'].index[0]-1)\naa_freq = aa_freq.truncate(after=aa_freq.loc[aa_freq['Allele'] == 'Allele'].index[0]-1)\nbah_freq = bah_freq.truncate(after=bah_freq.loc[bah_freq['Allele'] == 'Allele'].index[0]-1)\njam_freq = jam_freq.truncate(after=jam_freq.loc[jam_freq['Allele'] == 'Allele'].index[0]-1)\ntrin_freq = trin_freq.truncate(after=trin_freq.loc[trin_freq['Allele'] == 'Allele'].index[0]-1)\ncham_freq = cham_freq.truncate(after=cham_freq.loc[cham_freq['Allele'] == 'Allele'].index[0]-1)\nfili_freq = fili_freq.truncate(after=fili_freq.loc[fili_freq['Allele'] == 'Allele'].index[0]-1)\napa_freq = apa_freq.truncate(after=apa_freq.loc[apa_freq['Allele'] == 'Allele'].index[0]-1)\nnav_freq = nav_freq.truncate(after=nav_freq.loc[nav_freq['Allele'] == 'Allele'].index[0]-1)\n</code></pre>\n<p>can be replaced by a for loop like this:</p>\n<pre><code>for population in all_sheets:\n current_sheet = all_sheets[population]\n truncation_index = current_sheet.loc[current_sheet['Allele'] == 'Allele'].index[0]-1\n all_sheets[population] = current_sheet.truncate(after=truncation_index)\n</code></pre>\n<p>This improves both readability and maintainability. The same should be done for the <code>fillna</code> operation in your code, I would put it in the same for loop.\nAlso, I introduced an intermediate variable <code>truncation_index</code> to make things more readable.</p>\n<p><strong>Edit:</strong> Please note that the name <code>all_sheets</code>, that I used here, is not optimal when we are writing actual programs (instead of just examples). In my opinion, telling names like <code>allele_frequencies</code> would be preferable</p>\n<p>I hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T10:31:02.113", "Id": "485148", "Score": "0", "body": "You are welcome. I made some small edits to my answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T19:58:24.747", "Id": "247735", "ParentId": "247698", "Score": "1" } } ]
{ "AcceptedAnswerId": "247735", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T00:48:04.720", "Id": "247698", "Score": "2", "Tags": [ "python", "excel", "pandas" ], "Title": "Load multiple worksheets from Excel file to multiple DataFrames" }
247698
<p>I've been trying to learn java recently and I finally finish my first code. Any suggestions on where I can improve? Also, is it possible to send an argument to a class using something like an <strong>init</strong> function in python and are there any good and bad habits that I should keep in mind?</p> <pre><code>class LIFO { //Create an empty list with the lenght of the given size //Initialize our top value as 0 int my_list[] = new int[5]; int top = 0; //Adds a value to the list //Add one to our top public void push(int data) { my_list[top] = data; top++; } //Removes the top value from the list //Substract one from our top public int pop() { int data; top--; data = my_list[top]; my_list[top] = 0; return data; } //Prints our list public void show() { for(int n : my_list) { System.out.print(n + &quot; &quot;); } } } //Driver Class class Main { public static void main(String args[]) { LIFO s = new LIFO(); s.push(1); s.push(2); s.push(3); s.show(); System.out.println(&quot;\n&quot; + s.pop() + &quot; Popped from stack&quot;); s.show(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T05:35:37.487", "Id": "484989", "Score": "2", "body": "Title says LILO, code says LIFO, which one is it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:07:35.580", "Id": "485188", "Score": "0", "body": "Oh my mistake, it's suppose to be Last In First Out" } ]
[ { "body": "<p>I believe what you're looking for is a constructor.</p>\n<pre><code>class LIFO {\n \n //Create an empty list with the lenght of the given size\n //Initialize our top value as 0\n int my_list[];\n int top = 0;\n\n public LIFO(int size) {\n my_list = new int[size];\n }\n...\n</code></pre>\n<p>Call like so.</p>\n<pre><code>public static void main(String[] args) {\n LIFO lifo = new LIFO(10);\n lifo.push(10);\n lifo.push(20);\n System.out.println(lifo.pop());\n System.out.println(lifo.pop());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T04:00:39.223", "Id": "484982", "Score": "0", "body": "Thank you so much! I don't know why I though it would be super different from python lol." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T02:11:25.943", "Id": "247701", "ParentId": "247699", "Score": "3" } }, { "body": "<p>@Ted Brownlow has answered your constructor question, but here's a few other points to consider going forward...</p>\n<h1>Consider your class interface</h1>\n<p>Your class needs to present an interface that is functional,usable and focused. At the moment, your class is responsible for both implementing a LIFO and outputting them to the console. These are really different concerns. Consider if instead of writing to the console you wanted to write to a web page / different window. Building the display logic straight into the class makes it less flexible. A good exercise might be to remove the <code>show</code> method and decide what method(s) you would need to add to your class in order to allow it to be implemented from outside the class.</p>\n<h1>Bounds checking</h1>\n<p>At the moment your class has a fixed maximum size of 5. However, other than by reading the class there's no way for the client to know (possibly missing a <code>maxSize</code> method or similar). There's also no way for the client to know how many items are in the list, unless they keep track of it themselves (possibly missing a <code>currentSize</code> method or similar).</p>\n<p>Without this size information, there's no way for the client to know if it's safe to call <code>push</code> or <code>pop</code>. Consider what would happen if you already had 5 items when <code>push</code> was called. What would happen if 0 items were present and pop was called? At the moment, you're relying on the framework to handle these scenarios. This can be ok, if it's a conscious decision, but you probably want to consider adding some bounds checks and throwing exceptions that more explicitly help the user of your class know what they did wrong.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:50:36.197", "Id": "485374", "Score": "0", "body": "While I absolutely support thinking about edge cases, I don't support the \"exceptions that more explicitly help the user\" approach. Exceptions are meant for situations where a method can't fulfill its contract, and specifying exception types and situations makes exceptions part of the contract." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T06:02:46.653", "Id": "485776", "Score": "0", "body": "Thank you, those are really good points. I'll keep them in mind when writing code for now on." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:10:10.060", "Id": "247843", "ParentId": "247699", "Score": "4" } } ]
{ "AcceptedAnswerId": "247701", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T02:03:45.787", "Id": "247699", "Score": "4", "Tags": [ "java", "beginner" ], "Title": "Tips on my LIFO java code" }
247699
<p>(Sorry for my bad English) Hi, I'm interested in getting feedback of my own implementation of Conway's Game of Life.</p> <p>Some details:</p> <ul> <li>Uses <a href="https://hackage.haskell.org/package/gloss" rel="noreferrer">gloss</a> for animation</li> <li>Uses <a href="https://hackage.haskell.org/package/rio" rel="noreferrer">rio</a> for shorter dependency list</li> </ul> <p>My implementation suffers from performance issue when the population grows larger than 2000 cells.</p> <p>My code:</p> <ul> <li>Main.hs:</li> </ul> <pre class="lang-hs prettyprint-override"><code>module Main where import Lib import qualified RIO.ByteString as B import System.Environment import qualified Graphics.Gloss as G main :: IO () main = do [file] &lt;- getArgs initialGrid &lt;- B.readFile file let patt = parse initialGrid G.simulate G.FullScreen G.white 20 patt golPic (\_ _ ps -&gt; eval ps) golPic :: [Point] -&gt; G.Picture golPic ps = G.pictures [ G.translate (fromIntegral x * dIMENSION) (fromIntegral y * dIMENSION) (G.color G.black (G.rectangleSolid dIMENSION dIMENSION)) | (x, y) &lt;- ps ] parse :: B.ByteString -&gt; [Point] parse bs = map fst . filter ((== 42) . snd) . concatMap (\(x', xs) -&gt; [ ((y', -x'), c) | (y', c) &lt;- zip [1 .. length xs] xs ]) $ zip [1 .. length bs'] bs' where bs' = map B.unpack $! B.split 10 bs dIMENSION :: Float dIMENSION = 10 </code></pre> <ul> <li>Lib.hs:</li> </ul> <pre class="lang-hs prettyprint-override"><code>module Lib where import qualified RIO.Map as M type Point = (Int, Int) adjacents :: Point -&gt; [(Point, Int)] adjacents (x, y) = [ ((x + m, y + n), 1) | m &lt;- [-1, 0, 1], n &lt;- [-1, 0, 1], (m, n) /= (0, 0) ] eval :: [Point] -&gt; [Point] eval cs = [ x | (x, y) &lt;- M.toList . M.fromListWith (+) . concatMap adjacents $ cs , case y of 2 -&gt; x `elem` cs 3 -&gt; True _ -&gt; False ] </code></pre> <p>Any suggestion is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T04:54:18.700", "Id": "484986", "Score": "0", "body": "Maybe Point can be a data type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:16:50.507", "Id": "485352", "Score": "1", "body": "@Evgeny also make the fields strict and unpack them `data Point = Point {-# UNPACK #-} !Int {-# UNPACK #-} !Int` https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#unpack-pragma" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:32:29.290", "Id": "485409", "Score": "0", "body": "@DanielDíazCarrete - `{-# UNPACK #-}` is quite deep int optimisation that I know little about, thank you for the link!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T13:15:48.367", "Id": "485663", "Score": "0", "body": "Many unpacking here: https://github.com/simonmar/parconc-examples/blob/master/kmeans/KMeansCore.hs" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T02:23:19.767", "Id": "247702", "Score": "5", "Tags": [ "haskell", "game-of-life" ], "Title": "Yet another implementation of Conway's Game of life in Haskell" }
247702
<p>I have implemented the following program below for an assignment for practice on STL templates and algorithms. All I'm doing is implementing the code for the printing of empty files, un-empty files, etc.. I would love to know if there is any way to make the code more optimized.</p> <p>Note: From the requirements of my school (Must be adhered to):</p> <ul> <li><p>Code with the comment &quot;helper function&quot; should <strong>not</strong> be modified. These are <code>empty_check()</code>, <code>split()</code>, and <code>print_filename()</code>.</p> </li> <li><p>Functions commented as &quot;Can modify&quot; means the code within that function can be modified.</p> </li> <li><p><code>int main()</code> should <strong>not</strong> be modified</p> </li> <li><p>No extra headers allowed.</p> </li> <li><p>No definition of any new complex types or templates</p> </li> <li><p>No using of other functions other than the helper functions.</p> </li> <li><p>No use of lambda expressions.</p> </li> <li><p>No use of operators:</p> <ul> <li><code>.</code> (member access)</li> <li><code>-&gt;</code> (member access via a pointer)</li> <li><code>*</code> (dereference).</li> </ul> </li> <li><p>No use of explicit iteration (<code>for</code>, <code>while</code>, <code>do while</code>) or selection (<code>if</code>, <code>switch</code>, <code>?:</code>) statements or operators.</p> </li> <li><p>No use of keyword <code>auto</code>.</p> </li> <li><p>No use of <code>std::cout</code>, <code>std::cerr</code> or any other functions that perform printing of the text. I'll have to use the provided helper function to do it.</p> </li> </ul> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;utility&gt; using name_file = std::string; using sizeFile = size_t; using record_in_file = std::pair&lt;name_file, sizeFile&gt;; using file_datas = std::map&lt;name_file, sizeFile&gt;; bool empty_check( //helper function const record_in_file&amp; dataRecord, bool true_if_its_not ) { sizeFile size; std::tie(std::ignore, size) = dataRecord; bool result = (size == 0); if (true_if_its_not) { result = !result; } return result; } name_file split(const record_in_file&amp; dataRecord) //helper function { name_file name; std::tie(name, std::ignore) = dataRecord; return name; } void print_filename(const name_file&amp; name1) //helper function { std::cout &lt;&lt; &quot; * &quot; &lt;&lt; name1 &lt;&lt; std::endl; } void file_names_print(const file_datas&amp; map1) //can modify { std::vector&lt;name_file&gt; files; std::transform(std::begin(map1), std::end(map1), std::back_inserter(files), split); std::for_each(std::begin(files), std::end(files), print_filename); } size_t files_un_empty_print(const file_datas&amp; map1) //can modify { std::vector&lt;record_in_file&gt; files; std::copy_if(std::begin(map1), std::end(map1), std::back_inserter(files), std::bind(empty_check, std::placeholders::_1, true)); std::vector&lt;name_file&gt; file_names; std::transform(std::begin(files), std::end(files), std::back_inserter(file_names), split); std::for_each(std::begin(file_names), std::end(file_names), print_filename); return std::count_if(std::begin(map1), std::end(map1), std::bind(empty_check, std::placeholders::_1, true)); } size_t files_empty_print(const file_datas&amp; map1) //can modify { std::vector&lt;record_in_file&gt; files; std::copy_if(std::begin(map1), std::end(map1), std::back_inserter(files), std::bind(empty_check, std::placeholders::_1, false)); std::vector&lt;name_file&gt; file_names; std::transform(std::begin(files), std::end(files), std::back_inserter(file_names), split); std::for_each(std::begin(file_names), std::end(file_names), print_filename); return std::count_if(std::begin(map1), std::end(map1), std::bind(empty_check, std::placeholders::_1, false)); } std::tuple&lt;file_datas&amp;&gt; get_param(file_datas&amp; map1) //can modify { return std::forward_as_tuple&lt;file_datas&amp;&gt;(map1); } void empty_removal(file_datas&amp; map1) //can modify { std::vector&lt;record_in_file&gt; files; std::copy_if(std::begin(map1), std::end(map1), std::back_inserter(files), std::bind(empty_check, std::placeholders::_1, true)); file_datas n_map{ std::begin(files),std::end(files) }; std::swap(map1, n_map); } int main() { file_datas map = { {&quot;readme.txt&quot;, 2000}, {&quot;main.exe&quot;, 10000}, {&quot;save.bak&quot;, 0}, {&quot;library.dll&quot;, 1243}, {&quot;0.res&quot;, 121100}, {&quot;1.res&quot;, 121100}, {&quot;2.res&quot;, 115600}, {&quot;errors.log&quot;, 0} }; std::cout &lt;&lt; &quot;Files:&quot; &lt;&lt; std::endl; file_names_print(map); std::cout &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Files that are not empty:&quot; &lt;&lt; std::endl; size_t Count_of_unemptyFiles = files_un_empty_print(map); std::cout &lt;&lt; &quot; There are &quot; &lt;&lt; Count_of_unemptyFiles &lt;&lt; &quot; non-empty files.\n&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Files that are empty:&quot; &lt;&lt; std::endl; size_t Count_of_emptyFiles = files_empty_print(map); std::cout &lt;&lt; &quot; There are &quot; &lt;&lt; Count_of_emptyFiles &lt;&lt; &quot; empty files.\n&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Files after removing the empty ones:&quot; &lt;&lt; std::endl; auto parameters = get_param(map); std::apply(empty_removal, parameters); file_names_print(map); } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Avoid creating temporary vectors</h1>\n<p>You should avoid creating unnecessary temporary vectors. For example, in <code>file_names_print()</code>, you can use a nested <code>std::bind()</code> to avoid the vector <code>files</code>:</p>\n<pre><code>void file_names_print(const file_datas&amp; map1) //can modify \n{\n std::for_each(std::begin(map1), std::end(map1),\n std::bind(print_filename, std::bind(split, std::placeholders::_1)));\n}\n</code></pre>\n<p>This can be done with all the <code>std::transform()</code> + <code>std::for_each()</code> combinations. Given the restrictions you have, I don't see how to avoid the temporary vectors for <code>std::copy_if</code>.</p>\n<h1>Avoid unnecessary counting</h1>\n<p>In those cases where you used <code>std::copy_if()</code>, you then no longer need to call <code>std::count_if()</code> to count matching elements in the original input, you can just get the <code>std::size()</code> of the temporary vector. For example:</p>\n<pre><code>size_t files_un_empty_print(const file_datas&amp; map1) //can modify\n{\n std::vector&lt;record_in_file&gt; files;\n std::copy_if(std::begin(map1), std::end(map1), std::back_inserter(files), std::bind(empty_check, std::placeholders::_1, true));\n std::for_each(std::begin(files), std::end(files), std::bind(print_filename, std::bind(split, std::placeholders::_1)));\n\n return std::size(files);\n}\n</code></pre>\n<h1>Removing elements from a container</h1>\n<p>If you can use C++20, then you would simply write:</p>\n<pre><code>void empty_removal(file_datas&amp; map1) //can modify\n{\n std::erase_if(map1, std::bind(empty_check, std::placeholders::_1, true));\n}\n</code></pre>\n<p>If you cannot use C++20, then the typical way would be to use a <code>for</code>-loop that calls <code>erase()</code> on matching elements. Of course, you are restricted from doing that, and then you indeed have to make a copy.</p>\n<h1>Copy directly into a <code>std::map</code></h1>\n<p>In <code>empty_removal()</code>, you first create a <code>std::vector</code> of files, and then convert that to a map. That can be avoided by creating an empty <code>std::map</code> and inserting in that instead:</p>\n<pre><code>void empty_removal(file_datas&amp; map1) //can modify\n{\n file_datas files;\n std::copy_if(std::begin(map1), std::end(map1),\n std::inserter(files, std::end(files)),\n std::bind(empty_check, std::placeholders::_1, true));\n\n std::swap(map1, files);\n}\n</code></pre>\n<h1>About those restrictions</h1>\n<p>It might be a way to force you to use STL algorithms, but there are several drawbacks. Unfortunately, due to the fact you have to pass multiple iterators to STL algorithms, and never get a container as a return value, it is very hard to compose multiple STL algorithms. You then have to use intermediate copies, which is very inefficient. A <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based <code>for</code> loop</a> is then usually clearer and more efficient. In the real world, you would be able to use all the tools that C++ provides, and select the ones that are most appropriate to the task. You would likely combine <code>for</code>-loops, algorithms and lambdas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T03:56:05.583", "Id": "485101", "Score": "0", "body": "Hey, many thanks for the much needed suggestions! Anyway, for the 'empty_removal()\", std::inserter is part of #include<iterator> header which is not covered in any of the headers above. *No extra headers allowed*. Any other substitute for std::inserter? I tried back_inserter intuitively, but of course, it doesn't work for all container types, std::map, etc.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:00:19.783", "Id": "485123", "Score": "1", "body": "@starrk It compiles for me without explicitly including `<iterator>` when using GCC (version 10.2.0) or Clang (version 10.0.1). And you were already using `std::back_inserter`, which is also part of `<iterator>`. Technically, if you are not able to add `#include <iterator>`, then you cannot safely use any iterator class. If it works it is only through luck that another header includes it for you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T19:45:48.327", "Id": "247734", "ParentId": "247705", "Score": "3" } }, { "body": "<p>Apologies for being a bit brief with this review, however, my time is limited\ntoday. My review is a bit less technical than G. Sliepen's and is focused more\non code style.</p>\n<h2>Prefer consistent names</h2>\n<p>Looking at the first two lines after the list of includes:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>using name_file = std::string;\nusing sizeFile = size_t;\n...\n</code></pre>\n<p>Pick a style (<code>two_words</code>, <code>twoWords</code>, <code>TwoWords</code>, etc.) and stick with it\nthroughout your code.</p>\n<h2>Choose names which improve code readability and follow proper grammar</h2>\n<pre class=\"lang-cpp prettyprint-override\"><code>size_t files_un_empty_print(const file_datas&amp; map1); // what does &quot;files_un_empty&quot; mean?\nvoid file_names_print(const file_datas&amp; map1); // what is &quot;map_1&quot;?\nbool empty_check(\n const record_in_file&amp; dataRecord,\n bool true_if_its_not // &quot;is_empty&quot; is concise and better communicates the intent\n);\nvoid empty_removal(file_datas&amp; map1); // &quot;remove&quot; or &quot;delete_empty_files&quot; are clearer\n</code></pre>\n<p>For the second point about proper grammar, this may be an insignificant nitpick\non my part, however, if you can use proper English grammar when choosing names,\ndo so:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>using name_file = std::string; // &quot;file_name&quot; is a more natural and familiar way to say the same thing\nusing file_datas = std::map&lt;name_file, sizeFile&gt;; // the word &quot;data&quot; is plural\n</code></pre>\n<p>There may be additional examples in your code but this should illustrate the\npoint.</p>\n<h2>Using declarations</h2>\n<p>You created an alias:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>using sizeFile = size_t;\n</code></pre>\n<p>and then reverted to using <code>size_t</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>size_t files_un_empty_print(const file_datas&amp; map1);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T20:07:04.447", "Id": "247736", "ParentId": "247705", "Score": "3" } } ]
{ "AcceptedAnswerId": "247734", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T05:56:20.183", "Id": "247705", "Score": "5", "Tags": [ "c++", "algorithm", "homework", "stl" ], "Title": "C++ Practice on STL templates and algorithms" }
247705
<p><a href="https://leetcode.com/problems/my-calendar-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/my-calendar-ii/</a></p> <blockquote> <p>Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking.</p> <p>Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start &lt;= x &lt; end.</p> <p>A triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)</p> <p>For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar. Your class will be called like this: <code>MyCalendar cal = new MyCalendar();</code> <code>MyCalendar.book(start, end)</code></p> </blockquote> <p><strong>Example 1:</strong></p> <pre><code>MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(50, 60); // returns true MyCalendar.book(10, 40); // returns true MyCalendar.book(5, 15); // returns false MyCalendar.book(5, 10); // returns true MyCalendar.book(25, 55); //returns true </code></pre> <blockquote> <p><strong>Explanation:</strong></p> <ul> <li>The first two events can be booked. The third event can be double booked.</li> <li>The fourth event (5, 15) can't be booked, because it would result in a triple booking.</li> <li>The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.</li> <li>The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event; the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.</li> </ul> </blockquote> <blockquote> <p><strong>Note:</strong></p> <p>The number of calls to MyCalendar.book per test case will be at most 1000. In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].</p> </blockquote> <p>Please review for style and performance</p> <pre><code>using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { [TestClass] public class MyCalender2Test { [TestMethod] public void TestMethod1() { MyCalendarTwo myCalendar = new MyCalendarTwo(); Assert.IsTrue(myCalendar.Book(10, 20)); // returns true Assert.IsTrue(myCalendar.Book(50, 60)); // returns true Assert.IsTrue(myCalendar.Book(10, 40)); // returns true Assert.IsFalse(myCalendar.Book(5, 15)); // returns false Assert.IsTrue(myCalendar.Book(5, 10)); // returns true Assert.IsTrue(myCalendar.Book(25, 55)); // returns true } } public class MyCalendarTwo { private SortedDictionary&lt;int, int&gt; _dict; public MyCalendarTwo() { _dict = new SortedDictionary&lt;int, int&gt;(); } /// &lt;summary&gt; /// foreach start you add a pair of (start,1) /// foreach end you add a pair of (end,-1) /// the list is sorted we add and remove events. /// if we can more then 3 events added at the same time. /// we need to remove the event /// &lt;/summary&gt; /// &lt;param name=&quot;start&quot;&gt;&lt;/param&gt; /// &lt;param name=&quot;end&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public bool Book(int start, int end) { // s1------e1 // s-----e // s---e // s------------e // s---------e //s--e good // s--e if(!_dict.TryGetValue(start, out var temp)) { _dict.Add(start, temp + 1); } else { _dict[start]++; } if (!_dict.TryGetValue(end, out var temp1)) { _dict.Add(end, temp1 - 1); } else { _dict[end]--; } int active = 0; foreach (var d in _dict.Values) { active += d; if (active &gt;= 3) { _dict[start]--; _dict[end]++; if (_dict[start] == 0) { _dict.Remove(start); } return false; } } return true; } } /** * Your MyCalendarTwo object will be instantiated and called as such: * MyCalendarTwo obj = new MyCalendarTwo(); * bool param_1 = obj.Book(start,end); */ } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T21:32:04.583", "Id": "485203", "Score": "1", "body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Not too much to say on style, it all reads well to me. That said, there are a couple things I'd change.</p>\n<p>You can get away with <code>_dict</code> as a field here but I think <code>_bookings</code> would be slightly nicer.</p>\n<p>You can simplify the dictionary access too:</p>\n<pre><code>if(!_dict.TryGetValue(start, out var temp))\n{\n _dict.Add(start, temp + 1);\n}\nelse\n{\n _dict[start]++;\n}\n</code></pre>\n<p>I believe you could do:</p>\n<pre><code>var existingCount = _bookings.TryGetValue(start, out var count) ? count : 0;\n_bookings[start] = existingCount + 1;\n</code></pre>\n<p>You could also filter your list when you iterate. Once you get to the end of the booking you're currently looking at, you don't need to keep going.</p>\n<pre><code>foreach (var d in _bookings.TakeWhile(kvp =&gt; kvp.Key &lt; end).Select(kvp =&gt; kvp.Value))\n</code></pre>\n<p>It would be nice if you didn't have to add the start and end in to the dictionary but it does seem to be the simplest solution here. This can be a dangerous strategy because you have to ensure the entries you've added are always removed but I can't see any way your code can throw in the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T08:03:09.487", "Id": "485130", "Score": "0", "body": "thanks you very much i appreciate the review" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:35:36.390", "Id": "247726", "ParentId": "247706", "Score": "3" } }, { "body": "<p>Because the default value is returned for the value parameter in <code>_dict.TryGetValue()</code> if it returns false and the default value for <code>int</code> is <code>0</code> it should be save to do:</p>\n<pre><code> _dict.TryGetValue(start, out int count);\n _dict[start] = count + 1;\n _dict.TryGetValue(end, out count);\n _dict[end] = count - 1;\n</code></pre>\n<hr />\n<p>As a micro optimization, you can reduce this:</p>\n<pre><code> _dict[start]--;\n if (_dict[start] == 0)\n {\n _dict.Remove(start);\n }\n</code></pre>\n<p>to</p>\n<pre><code> if (_dict[start] == 1)\n _dict.Remove(start);\n else\n _dict[start]--;\n</code></pre>\n<p>so that at least when you can remove start you do one operation less (two instead of three).</p>\n<hr />\n<p>I wonder if you can remove <code>end</code> as well if it becomes <code>0</code> when incrementing it if <code>active &gt;= 3</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T19:31:53.803", "Id": "485200", "Score": "1", "body": "I had wondered about doing that with the dictionary too but I wasn't sure the value of the out parameter was specified when the method returns false. It is and you're quite right that it's default(TValue) so 0 for the int. I'm never sure about code that ignores a return value but I think it's fine here. Nice observation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T21:28:25.240", "Id": "485202", "Score": "1", "body": "@Henrik Hansen yes i can remove end as well. i just missed it when uploaded the code. i fixed it later." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T17:44:35.250", "Id": "247785", "ParentId": "247706", "Score": "2" } } ]
{ "AcceptedAnswerId": "247726", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T07:06:29.803", "Id": "247706", "Score": "7", "Tags": [ "c#", "programming-challenge" ], "Title": "LeetCode: my calender 2 C#" }
247706
<h2>Description</h2> <p>I have created a darkroom timer, which is used for enlarging and developing film.</p> <p>It has four separate timers, and can toggle mains via a relay to turn on the enlarger for a specified amount of time. Something like a mix between <a href="https://www.patersonphotographic.com/product/paterson-triple-timer/" rel="nofollow noreferrer">a triple timer for development</a> and an <a href="https://www.patersonphotographic.com/product/paterson-2000d-enlarger-timer/" rel="nofollow noreferrer">enlarger timer</a>.</p> <p>For this project, I used an Arduino Uno, with the following hardware configuration:</p> <ul> <li><a href="https://thepihut.com/products/four-digit-seven-segment-display-red" rel="nofollow noreferrer">Seven segment display</a> connected on pins 2-13</li> <li>Safelight connected to pin 1 (red LED strip)</li> <li><a href="http://www.ignorantofthings.com/2018/07/the-perfect-multi-button-input-resistor.html" rel="nofollow noreferrer">Voltage divider button array</a> connected to pin A0 (4 mode switches, rotary encoder button, and the enlarger switch)</li> <li><a href="https://thepihut.com/products/rotary-encoder-extras" rel="nofollow noreferrer">Rotary encoder</a> connected to A1 and A2</li> <li><a href="https://thepihut.com/products/gravity-relay-module-v3-1" rel="nofollow noreferrer">Relay</a> connected to A3</li> <li><a href="https://thepihut.com/products/16mm-illuminated-pushbutton-red-latching-on-off-switch" rel="nofollow noreferrer">Latching switch</a> connected to A4</li> <li><a href="https://thepihut.com/products/small-enclosed-piezo-w-wires" rel="nofollow noreferrer">Piezo buzzer</a> connected to A5</li> </ul> <p><a href="https://i.stack.imgur.com/pV6FR.png" rel="nofollow noreferrer">See CAD render of hardware</a>.</p> <h2>Included libraries</h2> <ul> <li><a href="https://github.com/DeanIsMe/SevSeg" rel="nofollow noreferrer">SevSeg</a></li> <li><a href="https://www.arduino.cc/en/Reference/EEPROM" rel="nofollow noreferrer">EEPROM</a> (native)</li> </ul> <h2>Code</h2> <pre class="lang-cpp prettyprint-override"><code>#include &lt;SevSeg.h&gt; #include &lt;EEPROM.h&gt; const byte SAFELIGHT_PIN = 1; const byte BUTTON_ARRAY_PIN = A0; const byte ENCODER_A_PIN = A1; const byte ENCODER_B_PIN = A2; const byte RELAY_PIN = A3; const byte SAFELIGHT_BUTTON_PIN = A4; const byte BUZZER_PIN = A5; // Changable if EEPROM ever wears out at these addresses const int EEPROM_ADDRESSES[] = { 0, 1, 2, 3 }; const byte NUM_DIGITS = 4; const byte DIGIT_PINS[] = { 5, 4, 3, 2 }; const byte SEGMENT_PINS[] = { 11, 13, 9, 7, 6, 12, 10, 8 }; SevSeg screen; int buttonArrayValue; unsigned long lastButtonArrayTime; unsigned long lastTimerUpdate; unsigned long timerUpdate; boolean lastEncoderAValue; boolean encoderAValue; boolean encoderBValue; byte activeTimer = 0; int timers[] = { EEPROM.read(EEPROM_ADDRESSES[0]), EEPROM.read(EEPROM_ADDRESSES[1]), EEPROM.read(EEPROM_ADDRESSES[2]), EEPROM.read(EEPROM_ADDRESSES[3]) }; boolean timerRunning = false; boolean safelightOn = false; void setup() { pinMode(BUZZER_PIN, OUTPUT); pinMode(RELAY_PIN, OUTPUT); pinMode(ENCODER_A_PIN, INPUT); pinMode(ENCODER_B_PIN, INPUT); pinMode(SAFELIGHT_BUTTON_PIN, INPUT); // Type, digits, segments, digit pins, segment pins, resistors on pins, update with delay, leading zeroes. screen.begin(COMMON_CATHODE, NUM_DIGITS, DIGIT_PINS, SEGMENT_PINS, true, false, true); screen.setBrightness(10); lastEncoderAValue = digitalRead(ENCODER_A_PIN); } void loop() { // Read rotary encoder encoderAValue = digitalRead(ENCODER_A_PIN); encoderBValue = digitalRead(ENCODER_B_PIN); if (encoderAValue != lastEncoderAValue &amp;&amp; encoderAValue == true &amp;&amp; timerRunning == false) { if (encoderBValue != encoderAValue) { timers[activeTimer]++; } else { timers[activeTimer]--; } // Minimum timer is 0, maximum timer is 99 minutes, 99 seconds = 6039 seconds timers[activeTimer] = min(max(0, timers[activeTimer]), 6039); } lastEncoderAValue = encoderAValue; // Button array buttonArrayValue = analogRead(BUTTON_ARRAY_PIN); if (millis() - lastButtonArrayTime &gt; 100 &amp;&amp; timerRunning == false) { if (buttonPressed(buttonArrayValue, 516)) { startTimer(); } else if (buttonPressed(buttonArrayValue, 344)) { startTimer(); digitalWrite(RELAY_PIN, HIGH); } else if (buttonPressed(buttonArrayValue, 257)) { activeTimer = 0; } else if (buttonPressed(buttonArrayValue, 205)) { activeTimer = 1; } else if (buttonPressed(buttonArrayValue, 171)) { activeTimer = 2; } else if (buttonPressed(buttonArrayValue, 146)) { activeTimer = 3; } lastButtonArrayTime = millis(); } timerUpdate = millis() - lastTimerUpdate; // Clear timer if (timerUpdate &gt; 1000 &amp;&amp; timerRunning == true &amp;&amp; timers[activeTimer] &lt;= 0) { timers[activeTimer] = EEPROM.read(EEPROM_ADDRESSES[activeTimer]); tone(BUZZER_PIN, 880, 1000); timerRunning = false; digitalWrite(RELAY_PIN, LOW); } // Update timer every second if (timerUpdate &gt; 1000 &amp;&amp; timerRunning == true) { timers[activeTimer]--; // Beep every second, with a higher beep every 30 seconds. if (timers[activeTimer] % 30 == 0) { tone(BUZZER_PIN, 880, 250); } else { tone(BUZZER_PIN, 440, 50); } lastTimerUpdate += timerUpdate; // Use the timerUpdate so average time is correct } // Update displays (safelight and screen). safelightOn = digitalRead(SAFELIGHT_BUTTON_PIN); if (safelightOn == true) { digitalWrite(SAFELIGHT_PIN, HIGH); screen.setNumber(secondsToMinutes(timers[activeTimer]), 3 - activeTimer); } else { digitalWrite(SAFELIGHT_PIN, LOW); screen.blank(); } screen.refreshDisplay(); } // Calculates if a number is within a margin of +/- 15. If so, it returns true. // This is used for the analogue buttons to see if they were pressed. boolean buttonPressed (int buttonArrayValue, int target) { if (abs(buttonArrayValue - target) &lt; 15) { return true; } else { return false; } } // Returns a seconds value in MMSS format. int secondsToMinutes (int seconds) { if (seconds &lt; 60) { return seconds; } else { return (floor(seconds / 60) * 100) + (seconds % 60); } } // Stores the current time if it is new, and starts the timer. void startTimer () { EEPROM.update(EEPROM_ADDRESSES[activeTimer], timers[activeTimer]); timerRunning = true; } </code></pre> <h2>Notes</h2> <ul> <li>I used all-capitals for <code>const</code> variables, however should I use <code>#define</code>? I didn't run into memory allocation problems.</li> <li>Everything is within the main <code>loop()</code> function. I tried splitting some parts off (such as reading the rotary encoder), but it didn't work - the encoder 'read' massively large numbers instead for some reason.</li> <li>I try to avoid writing to EEPROM where possible, since it expires. Reading is <a href="https://electronics.stackexchange.com/questions/10939/will-reading-ee-e-prom-wear-it-out">apparently fine</a>.</li> <li>I have preferred <code>if (someVariable == true) {</code> rather than <code>if (someVariable) {</code> - I thought it was more readable with other Boolean operators such as <code>&amp;&amp;</code>.</li> <li><strong>I would like a review of readability, idiomaticity, and efficiency.</strong> I am a novice with Arduino/C++ type code.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T07:34:48.803", "Id": "485003", "Score": "0", "body": "I'm not sure if this is too waffly. If so, I can cut out the description at the top." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T07:56:18.793", "Id": "485007", "Score": "1", "body": "I don't see any problems with this question. Welcome to Code Review! I prefer too much description over not enough description, but I don't think you have too much. When in doubt, there's [the FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T07:34:22.067", "Id": "247707", "Score": "4", "Tags": [ "arduino" ], "Title": "Arduino-based darkroom timer" }
247707
<p>Is there a way to rewrite these last 2 recursive functions with fewer arguments (preferably 2) while keeping them recursive?</p> <p>The entire code can be seen here: <a href="https://github.com/GirkovArpa/hutton-typescript" rel="nofollow noreferrer">https://github.com/GirkovArpa/hutton-typescript</a></p> <p>Maybe it's perfectly standard to have so many arguments. I don't know.</p> <p>Also, the <code>encrypt</code> and <code>decrypt</code> functions are so similar, maybe they should be combined into one that accepts a parameter to tell it whether to encrypt or decrypt?</p> <p>But then the function would take 6 arguments!</p> <pre><code>'use strict'; type char = string; const ALPHABET: string = 'abcdefghijklmnopqrstuvwxyz'; const ALL_LOWER_CASE: RegExp = /[a-z]/g; const ENTIRELY_LOWER_CASE: RegExp = /^[a-z]*$/; const validate = (...args: string[]): void =&gt; { args.forEach((s: string) =&gt; { if (!ENTIRELY_LOWER_CASE.test(s)) throw new Error(`String must consist of lowercase letters only. Received ${JSON.stringify(s)}.`); }); } const mod = (n: number, m: number): number =&gt; ((n % m) + m) % m; const rotate = (s: string): string =&gt; { const [c]: char = s; const sliced: string = s.slice(1); const rotated: string = sliced.concat(c); return rotated; } const swap = (s: string, i: number, j: number): string =&gt; { let a: string[] = [...s]; [a[i], a[j]] = [a[j], a[i]]; const swapped: string = a.join(''); return swapped; } const nothingIfIn = (set: Set&lt;char&gt;) =&gt; (c: char): string =&gt; set.has(c) ? '' : c; const permutate = (key: string): string =&gt; { const set: Set&lt;char&gt; = new Set(key); const uniques: string = [...set].join(''); const diff: string = ALPHABET.replace(ALL_LOWER_CASE, nothingIfIn(set)); const perm: string = uniques.concat(diff); return perm; } const encrypt = (pt: string, pw: string, k: string, ct: string = '', perm: string = permutate(k)): string =&gt; { validate(pt, pw, k, ct, perm); const [pwC]: char = pw; const pwC_i: number = ALPHABET.indexOf(pwC); const [permC]: char = perm; const permC_i: number = ALPHABET.indexOf(permC); const shift: number = (pwC_i + permC_i + 2); const [ptC]: char = pt; const ctC_i: number = (shift + perm.indexOf(ptC)) % ALPHABET.length; const ctC: char = perm[ctC_i]; const ptC_i: number = perm.indexOf(ptC); const ptSlice: string = pt.slice(1); const pwRotated: string = rotate(pw); const ctNew: string = ct.concat(ctC); const permSwapped: string = swap(perm, ptC_i, ctC_i); return (pt.length === 0) ? ct : encrypt(ptSlice, pwRotated, k, ctNew, permSwapped); } const decrypt = (ct: string, pw: string, k: string, pt: string = '', perm: string = permutate(k)): string =&gt; { validate(pt, pw, k, ct, perm); const [pwC]: char = pw; const pwC_i: number = ALPHABET.indexOf(pwC); const [permC]: char = perm; const permC_i: number = ALPHABET.indexOf(permC); const shift: number = -(pwC_i + permC_i + 2); const [ctC]: char = ct; const ptC_i: number = mod((shift + perm.indexOf(ctC)), ALPHABET.length); const ptC: char = perm[ptC_i]; const ctC_i: number = perm.indexOf(ctC); const ctSlice: string = ct.slice(1); const pwRotated: string = rotate(pw); const ptNew: string = pt.concat(ptC); const permSwapped: string = swap(perm, ctC_i, ptC_i); return (ct.length === 0) ? pt : decrypt(ctSlice, pwRotated, k, ptNew, permSwapped); } </code></pre> <p>Usage example:</p> <pre><code>const plaintext = 'helloworld'; const password = 'foo'; const key = 'bar'; const ciphertext = encrypt(plaintext, password, key); console.log(ciphertext); // pwckfenttc console.log(decrypt(ciphertext, password, key)); // helloworld </code></pre> <p>Here's a link describing how the cipher works (as explained to someone performing it by hand): <a href="https://hutton-cipher.netlify.app/howto.html" rel="nofollow noreferrer">https://hutton-cipher.netlify.app/howto.html</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T23:59:15.537", "Id": "485082", "Score": "0", "body": "why are you exporting everything?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:01:35.423", "Id": "485083", "Score": "0", "body": "I'll remove the `export`s from the question. It's because I copied and pasted the contents of `main.ts` in the repo, where the functions are exported for tests." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T07:51:58.297", "Id": "247708", "Score": "4", "Tags": [ "javascript", "recursion", "functional-programming", "typescript" ], "Title": "This recursive function encrypts a string" }
247708
<p>I've written a .NET Core console application to monitor the operation of a sensor network and I'd like a review of the task scheduling performed by the main program loop. There are three tasks that are all declared as <code>public static async Task</code> that perform the following operations:</p> <ul> <li><p><code>CheckGateways.CheckAll</code> connects to an external API at one minute intervals and is the most likely to fail or take a long time. Normally it'll take a few seconds but I'd like other tasks to continue meanwhile.</p> </li> <li><p><code>CheckNodes.CheckAll</code> is an internal database check that may take a few seconds but is not time critical and runs once per minute.</p> </li> <li><p><code>CheckAlerts.CheckAll</code> checks for alert conditions on the sensors and is the most time critical so I'm checking that once per second.</p> </li> </ul> <p>While the code seems to be working it hasn't been well stress-tested and a few things I'd like reviewed are:</p> <ul> <li><p>Are there any potential race conditions with the way I'm checking the status of the first two tasks?</p> </li> <li><p>I'm repeating the code to start / check the first two tasks so perhaps there's a cleaner way to do that without introduction too much extra code as there's unlikely to be any more tasks added.</p> </li> <li><p>Also any general comments on coding / naming standards would be appreciated.</p> <pre><code>static async Task Main() { IConfiguration configuration = new ConfigurationBuilder() .AddJsonFile(&quot;appsettings.json&quot;, optional: false, reloadOnChange: true) .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.FromLogContext() .MinimumLevel.Override(&quot;Microsoft&quot;, LogEventLevel.Warning) .CreateLogger(); Task checkGateways = null; DateTime lastGatewayCheck = DateTime.UtcNow; Task checkNodes = null; DateTime lastNodeCheck = DateTime.UtcNow; while (true) { try { // Check gateway connectivity loss at one minute intervals if (DateTime.UtcNow.Subtract(lastGatewayCheck).TotalMinutes &gt;= 1 &amp;&amp; (checkGateways == null || checkGateways.IsCompleted)) { lastGatewayCheck = DateTime.UtcNow; checkGateways = CheckGateways.CheckAll(configuration); } if (checkGateways?.Status == TaskStatus.Faulted) { throw checkGateways.Exception; } // Check node connectivity loss at one minute intervals if (DateTime.UtcNow.Subtract(lastNodeCheck).TotalMinutes &gt;= 1 &amp;&amp; (checkNodes == null || checkNodes.IsCompleted)) { lastNodeCheck = DateTime.UtcNow; checkNodes = CheckNodes.CheckAll(configuration); } if (checkNodes?.Status == TaskStatus.Faulted) { throw checkNodes.Exception; } // Check for pending alerts to send at one second interval await CheckAlerts.CheckAll(configuration); } catch (AggregateException ae) { foreach (var ex in ae.InnerExceptions) { LogException(ex); } } catch (Exception ex) { LogException(ex); } await Task.Delay(1000); } } public static void LogException(Exception ex) { ConsoleMessage(ex.ToString()); Serilog.Log.Error(ex, &quot;Error occured in TelemetryService&quot;); } public static void ConsoleMessage(string msg) { Console.WriteLine($&quot;{DateTime.Now:yyyy-MM-dd HH:mm:ss}: {msg}&quot;); } </code></pre> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T12:20:49.897", "Id": "485018", "Score": "3", "body": "Welcome to Code Review." } ]
[ { "body": "<ul>\n<li>Keep a single <code>var now = DateTime.UtcNow;</code></li>\n<li>Initialize the check-tasks to <code>Task.CompletedTask</code> to get rid of all the null checks.</li>\n<li>Check if the tasks are faulted, and use <code>Task.IsFaulted</code>, before rescheduling the task to avoid swallowing last second exceptions.</li>\n<li>If one of the 1-minute tasks fails early the rest of the checks won't run until the task is rescheduled.</li>\n<li>Use timers instead of loops over tasks.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:22:42.807", "Id": "485247", "Score": "0", "body": "can you elaborate more on last bullet point, thanks :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T12:59:19.490", "Id": "247715", "ParentId": "247713", "Score": "5" } }, { "body": "<p><strong>No way to stop the cycle.</strong></p>\n<p>The standard with TPL is to use the CancellationToken. Even if it is not need now, which I don't know why, it would be easier in the future if it supported it. For example if it gets turned into a service can just cancel the Token Source or if stays a console app could trap Esc key and cancel token source.</p>\n<p><strong>Numbers for Task Delay.</strong></p>\n<p>It's easier to read/maintain</p>\n<pre><code>Task.Delay(TimeSpan.FromSeconds(1))\n</code></pre>\n<p>then</p>\n<pre><code>Task.Delay(1000)\n</code></pre>\n<p>For each Task instead of checking their time you can combine them with Task.Delay()</p>\n<p>For example</p>\n<pre><code>Task.WhenAll(lastNodeCheck, Task.Delay(TimeSpan.FromMinutes(1)));\n</code></pre>\n<p>Now we have one task that will only complete when either a minute has passed and the main task has completed. We can make a helper method for this</p>\n<pre><code> public static Task DelayedTask(Task task, TimeSpan delay, CancellationToken token)\n {\n return Task.WhenAll(task, Task.Delay(delay, token));\n }\n</code></pre>\n<p>The downside to this is even if the task failed right away it will still wait the delay time before it gets logged that it failed. I don't think that's a big deal breaker but only you know that for sure.</p>\n<p><strong>Optional but you can make this into a queue</strong></p>\n<p>We can create a dictionary that waits for task to be complete then re-adds them if needed. This will make the code a bit more complex but easier to add new task later on.</p>\n<p>Something like</p>\n<pre><code> private static async Task TaskQueue(CancellationToken token, params Func&lt;Task&gt;[] tasks)\n {\n if (tasks.Length == 0)\n {\n return;\n }\n \n var queue = new ConcurrentDictionary&lt;Task, Func&lt;Task&gt;&gt;();\n foreach (var task in tasks)\n {\n queue.TryAdd(task(), task);\n }\n\n while (!token.IsCancellationRequested)\n {\n await Task.WhenAny(queue.Keys).ContinueWith(completedTask =&gt;\n {\n Func&lt;Task&gt; factory;\n var mainTask = completedTask.Unwrap();\n queue.TryRemove(mainTask, out factory);\n if (!mainTask.IsCanceled)\n {\n queue.GetOrAdd(factory(), factory);\n }\n\n if (mainTask.IsFaulted)\n {\n foreach (var ex in mainTask.Exception.InnerExceptions)\n {\n LogException(ex);\n }\n }\n });\n }\n }\n</code></pre>\n<p>I haven't tested this with all options but with basic test seems to work. We create a concurrent dictionary and load it with tasks that are in flight and factories to make the task. As task complete we remove from the dictionary and re-add them. Continue until we get told to cancel.</p>\n<p>Now in the main method can look something similar to this</p>\n<pre><code> var cancellation = new CancellationTokenSource();\n var cancelToken = cancellation.Token;\n Func&lt;Task&gt; checkGateWayFactory = () =&gt; DelayedTask(CheckGateways.CheckAll(configuration), TimeSpan.FromMinutes(1), cancelToken);\n Func&lt;Task&gt; checkNodeFactory = () =&gt; DelayedTask(CheckNodes.CheckAll(configuration), TimeSpan.FromMinutes(1), cancelToken);\n Func&lt;Task&gt; checkAlertFactory = () =&gt; DelayedTask(CheckAlerts.CheckAll(configuration), TimeSpan.FromSeconds(1), cancelToken);\n await TaskQueue(cancelToken, \n checkAlertFactory, \n checkGateWayFactory, \n checkNodeFactory);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T19:06:36.860", "Id": "247731", "ParentId": "247713", "Score": "7" } } ]
{ "AcceptedAnswerId": "247731", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T11:48:09.587", "Id": "247713", "Score": "5", "Tags": [ "c#", "async-await", "scheduled-tasks", ".net-core" ], "Title": "Simple async task scheduler" }
247713
<p>I am new to python, I made a calculator but I need to make it calculating unlimited numbers and to shorten the code more, how can I improve it? Any help is appreciated.</p> <pre><code>while(True): print() try: nums = int(input(&quot;How many numbers you want to calculate?\n&quot;)) # x = float(input(&quot;Enter the first number: &quot;)) # y = float(input(&quot;Enter the second number: &quot;)) # z = float(input(&quot;Enter the third number: &quot;)) # w = float(input(&quot;Enter the forth number: &quot;)) # v = float(input(&quot;Enter the fifth number: &quot;)) if nums == 2: x = float(input(&quot;Enter the first number: &quot;)) y = float(input(&quot;Enter the second number: &quot;)) print() func = int(input('''What do you want to do? 1 to add 2 to subtract 3 to multiply 4 to divide ''')) if func == 1: print(x+y) if func == 2: print(x-y) if func == 3: print(x*y) if func == 4: print(x/y) if nums == 3: x = float(input(&quot;Enter the first number: &quot;)) y = float(input(&quot;Enter the second number: &quot;)) z = float(input(&quot;Enter the third number: &quot;)) print() func = int(input('''What do you want to do? 1 to add 2 to subtract 3 to multiply 4 to divide ''')) if func == 1: print(x+y+z) if func == 2: print(x-y-z) if func == 3: print(x*y*z) if func == 4: print(x/y/z) if nums == 4: x = float(input(&quot;Enter the first number: &quot;)) y = float(input(&quot;Enter the second number: &quot;)) z = float(input(&quot;Enter the third number: &quot;)) w = float(input(&quot;Enter the forth number: &quot;)) print() func = int(input('''What do you want to do? 1 to add 2 to subtract 3 to multiply 4 to divide ''')) if func == 1: print(x+y+z+w) if func == 2: print(x-y-z-w) if func == 3: print(x*y*z*w) if func == 4: print(x/y/z/w) if nums == 5: x = float(input(&quot;Enter the first number: &quot;)) y = float(input(&quot;Enter the second number: &quot;)) z = float(input(&quot;Enter the third number: &quot;)) w = float(input(&quot;Enter the forth number: &quot;)) v = float(input(&quot;Enter the fifth number: &quot;)) print() func = int(input('''What do you want to do? 1 to add 2 to subtract 3 to multiply 4 to divide ''')) if func == 1: print(x+y+z+w+v) if func == 2: print(x-y-z-w-v) if func == 3: print(x*y*z*w*v) if func == 4: print(x/y/z/w/v) if nums &gt; 5: print(&quot;The calculator handles 5 numbers maximum!&quot;) except(ZeroDivisionError): print(&quot;You can never divide by Zero!&quot;) except(ValueError): print(&quot;Check your input.&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T13:21:24.457", "Id": "485020", "Score": "0", "body": "are you familiar with for loops?" } ]
[ { "body": "<p>Loops would be the perfect tool here to reduce duplication; although getting it exactly as you have will be difficult due to you currently spelling out numbers (&quot;first&quot;, &quot;second&quot;, &quot;third&quot;...). For the sake of simplicity, I'm going to ignore the numeric words, because producing those is non-trivial and a whole project on its own unless you use an existing library.</p>\n<p>In their place, I'm going to use a simple function. This can be optimized using a dictionary acting as a <code>case</code>, but I think it's fine as-is besides some minor duplication:</p>\n<pre><code>def format_number(n: int) -&gt; str:\n last_digit = str(n)[-1]\n if last_digit == &quot;1&quot;:\n return f&quot;{n}st&quot;\n elif last_digit == &quot;2&quot;:\n return f&quot;{n}nd&quot;\n elif last_digit == &quot;3&quot;:\n return f&quot;{n}rd&quot;\n else:\n return f&quot;{n}th&quot;\n\n&gt;&gt;&gt; format_number(2)\n'2nd'\n&gt;&gt;&gt; format_number(5)\n'5th'\n&gt;&gt;&gt; format_number(1)\n'1st'\n</code></pre>\n<p>It goes a little bit wonky in the teens (<code>&quot;12nd&quot;</code>), but like I said, it isn't a super straightforward problem, and I don't want to sidetrack the review.</p>\n<hr />\n<p>First, you can ask for numbers using a loop, and in the loop, place the entered numbers into a list:</p>\n<pre><code>nums = int(input(&quot;How many numbers you want to calculate?\\n&quot;)) \n\nentered_nums = []\nfor n in range(nums):\n x = float(input(f&quot;Enter the {format_number(n + 1)} number: &quot;))\n entered_nums.append(x)\n</code></pre>\n<p>When run, I get:</p>\n<pre><code>How many numbers you want to calculate?\n3\nEnter the 1st number: 9\nEnter the 2nd number: 8\nEnter the 3rd number: 7\n</code></pre>\n<p>And <code>entered_nums</code> now holds <code>[9, 8, 7]</code>.</p>\n<p>If you're at all familiar with list comprehensions though, you'll notice that that loop can be simplified a bit:</p>\n<pre><code>entered_nums = [float(input(f&quot;Enter the {format_number(n + 1)} number: &quot;))\n for n in range(nums)]\n</code></pre>\n<p>And this will have the same effect with a bit less bulk.</p>\n<hr />\n<p>Once you have the numbers to do math on, you need to ask for the operation to apply, then apply that operation.</p>\n<p>For the first, I'm going to import the <code>operator</code> module because it'll make life much easier. <code>operator.add</code> for example is the same thing as <code>+</code>; only it can be stored as an object.</p>\n<p>I'm going to use a dictionary to store the menu code to operator relationship:</p>\n<pre><code>from operator import add, sub, mul, truediv\n. . .\n\nfunc = int(input('''What do you want to do?\n 1 to add\n 2 to subtract\n 3 to multiply\n 4 to divide\n '''))\n\ncode_to_op = {1: add,\n 2: sub,\n 3: mul,\n 4: truediv}\n</code></pre>\n<p>This allows for easily doing math:</p>\n<pre><code>&gt;&gt;&gt; code_to_op = {1: add,\n 2: sub,\n 3: mul,\n 4: truediv}\n\n&gt;&gt;&gt; op = code_to_op[3]\n&gt;&gt;&gt; op(3, 5)\n15\n</code></pre>\n<p>Note though that a bad dictionary lookup will cause an error. <code>code_to_op[5]</code> for example will raise a <code>KeyError</code>. I didn't handle that for simplicity and because you currently aren't handling bad input. It should be dealt with though.</p>\n<hr />\n<p>So now once we can get the operator that the user wants, we need to apply it to the numbers they entered. Again, a loop (or something that acts as a loop) is our friend here. We'll need to keep track of the current result of the equation (the &quot;accumulator&quot;), and a loop to do the math:</p>\n<pre><code>acc = entered_nums[0] # The first number they entered will be our starting accumulator\nfor entered_num in entered_nums[1:]: # And we'll loop over all the numbers after the first\n acc = op(acc, entered_num)\n\nprint(acc)\n</code></pre>\n<p>If the user entered in the numbers 2, 3, and 4, and then entered in 1 for the operator (add), <code>acc</code> would hold <code>9.0</code> at the end of that loop.</p>\n<p>The acc+loop pattern is incredibly common in programming though. So common in fact that it has its own name: <a href=\"https://docs.python.org/3.8/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>reduce</code></a>:</p>\n<pre><code>from functools import reduce\n\n. . .\n\nresult = reduce(op, entered_nums)\n</code></pre>\n<p><code>reduce</code> here automates the looping for us. It's essentially equivalent to the previous loop that calculated the same value.</p>\n<hr />\n<p>After taking that all into consideration, I'm left with:</p>\n<pre><code>from operator import add, sub, mul, truediv\nfrom functools import reduce\n\ndef format_number(n: int) -&gt; str:\n if n == 1:\n return f&quot;{n}st&quot;\n elif n == 2:\n return f&quot;{n}nd&quot;\n elif n == 3:\n return f&quot;{n}rd&quot;\n else:\n return f&quot;{n}th&quot;\n\nwhile True:\n try:\n nums = int(input(&quot;How many numbers you want to calculate?\\n&quot;))\n\n entered_nums = [float(input(f&quot;Enter the {format_number(n + 1)} number: &quot;))\n for n in range(nums)]\n\n code_to_op = {1: add,\n 2: sub,\n 3: mul,\n 4: truediv}\n\n func = int(input('''What do you want to do?\n 1 to add\n 2 to subtract\n 3 to multiply\n 4 to divide\n '''))\n\n op = code_to_op[func]\n\n acc = entered_nums[0] # The first number they entered will be our starting accumulator\n\n for entered_num in entered_nums[1:]: # And we'll loop over all the numbers after the first\n acc = op(acc, entered_num)\n\n print(acc, &quot;\\n&quot;)\n\n except(ZeroDivisionError):\n print(&quot;You can never divide by Zero!&quot;)\n\n except(ValueError):\n print(&quot;Check your input.&quot;)\n</code></pre>\n<p>And an example run:</p>\n<pre><code>How many numbers you want to calculate?\n6\nEnter the 1st number: &gt;? 9\nEnter the 2nd number: &gt;? 8\nEnter the 3rd number: &gt;? 7\nEnter the 4th number: &gt;? 6\nEnter the 5th number: &gt;? 5\nEnter the 6th number: &gt;? 4\nWhat do you want to do?\n 1 to add\n 2 to subtract\n 3 to multiply\n 4 to divide\n &gt;? 1\n39.0\n</code></pre>\n<p>There is still a lot that can be mentioned (grouping things into functions, fixing some error handling), but I need to start studying for an exam :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:19:31.393", "Id": "485068", "Score": "0", "body": "It's actually mostly ununderstandable for a beginner in python..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:27:28.747", "Id": "485071", "Score": "1", "body": "@LyZeN77 If you are unfamiliar with loops, practice their use then revisit my answer. Loops are fundamental to all of programming, and looping of some form will be required to clean up this code. Attempting to teach their use in general would also be fairly senseless, as many guides already exist on the topic; including in the official documentation. If there are particular points in the code I showed that you'd like clarification on, I can try to edit my answer to improve it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:46:13.393", "Id": "485074", "Score": "0", "body": "I know about loops, but the confusing part was when you changed the (first, second, third) to (1st, 2nd, 3rd) is there a way to make it unlimited amount of numbers? or even a simpler way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:49:33.323", "Id": "485075", "Score": "1", "body": "@LyZeN77 If you wanted to, you could replace the `x = float(input(f\"Enter the {format_number(n + 1)} number: \"))` line with just `x = float(input(\"Enter the next number: \"))` and get rid of the function. I only included that bit because you had \"first\", \"second\"... in your original output. It's purely stylistic." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T14:51:00.907", "Id": "247717", "ParentId": "247714", "Score": "7" } }, { "body": "<p>You can store your numbers in a list after taking them as input as a string separated by spaces, then splitting them into a list using the list.split() function and finally converting each of them to integers.</p>\n<pre><code>input_string = input('Enter the numbers separated by space: ')\nlist_of_numbers = []\nfor character in input_string.split():\n list_of_numbers.append(int(character))\nnums = len(list_of_numbers)\n</code></pre>\n<p>In this case, you have your variable nums, and all the numbers you took as input are in the list list_of_numbers. This can also be written in the following way -</p>\n<pre><code>list_of_numbers = [int(number) for number in input('Enter all the numbers you want to calculate: ').split()]\nnums = len(list_of_numbers)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T15:35:18.703", "Id": "247718", "ParentId": "247714", "Score": "3" } } ]
{ "AcceptedAnswerId": "247717", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T12:39:17.110", "Id": "247714", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "calculator" ], "Title": "Simple console calculator in python" }
247714
<p>I wanted to do a very little project of a team scrambler. There are two teams of 5 players. Each player has a unique color (in his team) from a limited pool. You can use 2 actions :</p> <ul> <li>Scramble the teams which mix all players between the two teams</li> <li>Request new color for a team which reassign new color for each player of this team</li> </ul> <p>At first, I tried to place players inside an array that I shuffled but since VueJs cannot detect a change on array reassignment natively it ends complicating the code way too much.</p> <p>So I end up with this solution (<a href="https://codesandbox.io/s/scrambler-rtzoy?file=/pages/index.vue:0-4481" rel="nofollow noreferrer">Sandbox</a> for better readability) where I added a position property in my players :</p> <pre><code>&lt;template&gt; &lt;div class=&quot;container mx-auto&quot;&gt; &lt;!-- header --&gt; &lt;div class=&quot;my-4 flex flex-row justify-center space-x-4&quot;&gt; &lt;button class=&quot;btn btn-red&quot; @click=&quot;scrambleTeam1Colors&quot;&gt;Color 1&lt;/button&gt; &lt;button class=&quot;btn btn-red&quot; @click=&quot;scrambleTeams&quot;&gt;SCRAMBLE&lt;/button&gt; &lt;button class=&quot;btn btn-red&quot; @click=&quot;scrambleTeam2Colors&quot;&gt;Color 2&lt;/button&gt; &lt;/div&gt; &lt;!-- teams --&gt; &lt;div class=&quot;my-2 flex flex-row justify-between&quot;&gt; &lt;!-- team 1 --&gt; &lt;div class=&quot;w-2/5 flex flex-col space-y-px&quot;&gt; &lt;div class=&quot;flex att-title items-center&quot;&gt; &lt;h3 class=&quot;flex-grow text-center&quot;&gt;Team 1&lt;/h3&gt; &lt;/div&gt; &lt;Player v-for=&quot;player in team1&quot; :key=&quot;player.id&quot; :player=&quot;player&quot;/&gt; &lt;/div&gt; &lt;div class=&quot;w-1/5&quot;/&gt; &lt;!-- team 2 --&gt; &lt;div class=&quot;w-2/5 flex flex-col space-y-px&quot;&gt; &lt;div class=&quot;flex def-title items-center&quot;&gt; &lt;h3 class=&quot;flex-grow text-center&quot;&gt;Team 2&lt;/h3&gt; &lt;/div&gt; &lt;Player v-for=&quot;player in team2&quot; :key=&quot;player.id&quot; :player=&quot;player&quot;/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import Player from &quot;@/components/Player.vue&quot;; export default { components: { Player }, data() { return { player1: { id: 1, name: &quot;Player 1&quot;, color: &quot;red&quot;, position: 0 }, player2: { id: 2, name: &quot;Player 2&quot;, color: &quot;blue&quot;, position: 1 }, player3: { id: 3, name: &quot;Player 3&quot;, color: &quot;green&quot;, position: 2 }, player4: { id: 4, name: &quot;Player 4&quot;, color: &quot;orange&quot;, position: 3 }, player5: { id: 5, name: &quot;Player 5&quot;, color: &quot;indigo&quot;, position: 4 }, player6: { id: 6, name: &quot;Player 6&quot;, color: &quot;red&quot;, position: 5 }, player7: { id: 7, name: &quot;Player 7&quot;, color: &quot;blue&quot;, position: 6 }, player8: { id: 8, name: &quot;Player 8&quot;, color: &quot;green&quot;, position: 7 }, player9: { id: 9, name: &quot;Player 9&quot;, color: &quot;orange&quot;, position: 8 }, player10: { id: 10, name: &quot;Player 10&quot;, color: &quot;indigo&quot;, position: 9 }, colors: [ &quot;red&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;orange&quot;, &quot;indigo&quot;, &quot;yellow&quot;, &quot;teal&quot;, &quot;purple&quot;, &quot;pink&quot; ] }; }, computed: { players() { return [ this.player1, this.player2, this.player3, this.player4, this.player5, this.player6, this.player7, this.player8, this.player9, this.player10 ]; }, team1() { return this.players.filter(player =&gt; player.position &lt; 5); }, team2() { return this.players.filter(player =&gt; player.position &gt; 4); } }, methods: { scrambleTeams() { let positionsToAssign = Array.from(Array(10).keys()); positionsToAssign = this.shuffle(positionsToAssign); this.players.forEach( player =&gt; (player.position = positionsToAssign.pop()) ); this.scrambleTeam1Colors(); this.scrambleTeam2Colors(); }, scrambleTeam1Colors() { let colorsToAssign = this.shuffle([...this.colors]); this.team1.forEach(player =&gt; (player.color = colorsToAssign.pop())); }, scrambleTeam2Colors() { let colorsToAssign = this.shuffle([...this.colors]); this.team2.forEach(player =&gt; (player.color = colorsToAssign.pop())); }, shuffle(array) { let currentIndex = array.length; let temporaryValue; let randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } } }; &lt;/script&gt; &lt;style lang=&quot;postcss&quot; scoped&gt; .att-title { @apply font-bold bg-red-400 text-white; } .def-title { @apply font-bold bg-teal-400 text-white; } .btn { @apply font-bold py-2 px-4 rounded; } .btn-red { @apply bg-red-500 text-white; } .btn-red:hover { @apply bg-red-700; } &lt;/style&gt; </code></pre> <p>Since I am not really experienced in either javascript or vuejs I was wondering if I was missing a way easier way to manage my pool of players and the shuffling. Also, is there an alternative to declaring a computed for my array &quot;players&quot;.</p> <p>Note: The shuffle method is just an algorithm I copied so it is not part of the review</p>
[]
[ { "body": "<h1>Overall assessment</h1>\n<p>For a beginner this is a great start. The use of computed properties is nice- especially with the filtering of players into teams. The selection of colors are ascetically pleasing.</p>\n<h1>Suggestions</h1>\n<h2>UI</h2>\n<h3>Button Labels</h3>\n<p>The labels on the top three buttons are <em>Color 1</em>, <em>SCRAMBLE</em> and <em>Color 2</em>, yet it seems that all three lead to some sort of scramble effect. For the first and last buttons it might make sense to each label contain the word <em>Scramble</em>, or else abstract the word <em>Scramble</em> out into a parent container - e.g.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link href=\"//unpkg.com/tailwindcss@0.5.2/dist/tailwind.min.css\" rel=\"stylesheet\"&gt;\n&lt;fieldset&gt;\n &lt;legend&gt;Scramble&lt;/legend&gt;\n &lt;button class=\"btn bg-red text-white rounded-full p-2\"&gt;Team 1&lt;/button&gt;\n &lt;button class=\"btn bg-red text-white rounded-full p-2\"&gt;Both Teams&lt;/button&gt;\n &lt;button class=\"btn bg-red text-white rounded-full p-2\"&gt;Team 2&lt;/button&gt;\n&lt;/fieldset&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Spacing between player squares and labels</h3>\n<p>It would be wise to add some spacing between the squares and the player labels:</p>\n<p><a href=\"https://i.stack.imgur.com/1tLSK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1tLSK.png\" alt=\"screenshot with arrow\" /></a></p>\n<h2>JavaScript / VueJS</h2>\n<h3>use <code>const</code> as default</h3>\n<p>It is wise to use <code>const</code> for declaring variables to avoid accidental re-assignment (e.g. <code>colorsToAssign</code> in <code>scrambleTeam1Colors()</code> and <code>scrambleTeam2Colors()</code>. Then when re-assignment is deemed necessary use <code>let</code> - e.g. <code>positionsToAssign</code> in <code>scrambleTeams</code>.</p>\n<h3>Setting up <code>data</code></h3>\n<p>The values setup in <code>data</code> are a bit redundant. A <code>for</code> loop could be used for that:</p>\n<pre><code>data() {\n const data = {\n players: [],\n colors\n };\n for (let i = 1; i &lt;= 10; i++) {\n data.players.push({\n id: i + 1,\n name: &quot;Player &quot; + i,\n color: colors[(i - 1) % 5],\n position: i - 1\n });\n }\n return data;\n},\n</code></pre>\n<p>where <code>colors</code> is moved out above the <code>export default</code> statement. This allows the <code>players</code> section of <code>computed</code> to be removed completely.</p>\n<h3>spreading items into an array</h3>\n<p>Instead of calling <code>Array.from()</code> - e.g.</p>\n<blockquote>\n<pre><code>let positionsToAssign = Array.from(Array(10).keys());\n</code></pre>\n</blockquote>\n<p>the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> can be used for the same result, without the need to call a function:</p>\n<pre><code>let positionsToAssign = [...Array(10).keys()];\n</code></pre>\n<h3>Swapping values</h3>\n<p>instead of this</p>\n<blockquote>\n<pre><code>temporaryValue = array[currentIndex];\narray[currentIndex] = array[randomIndex];\narray[randomIndex] = temporaryValue;\n</code></pre>\n</blockquote>\n<p>One could use <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">Destructuring assignment</a> to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Swapping_variables\" rel=\"nofollow noreferrer\">swap variables</a></p>\n<pre><code>[array[randomIndex], array[currentIndex]] = [array[currentIndex], array[randomIndex]];\n</code></pre>\n<p>However <a href=\"https://jsperf.com/swap-array-vs-variable/9\" rel=\"nofollow noreferrer\">it seems that is slower than other techniques</a> even though the V8 blog claims &quot;<em>Once we unblocked escape analysis to eliminate all temporary allocation, array destructuring with a temporary array is as fast as a sequence of assignments.</em>&quot;<sup><a href=\"https://v8.dev/blog/v8-release-68#performance\" rel=\"nofollow noreferrer\">1</a></sup>. There is a &quot;hack&quot; suggested in <a href=\"https://stackoverflow.com/a/16201730/1575353\">this SO answer by showdev</a> that <a href=\"https://jsperf.com/swap-array-vs-variable/9\" rel=\"nofollow noreferrer\">appears to be the fastest method to swap variables</a>:</p>\n<pre><code>array[randomIndex] = [array[currentIndex], (array[currentIndex] = array[randomIndex])][0];\n</code></pre>\n<p>This eliminates the need for ‘temporaryValue`.</p>\n<h3>Decrement operator</h3>\n<p>Decrement by one can be simplified using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Decrement\" rel=\"nofollow noreferrer\">decrement operator <code>--</code></a> - e.g. from</p>\n<blockquote>\n<pre><code>currentIndex -= 1;\n</code></pre>\n</blockquote>\n<p>To:</p>\n<pre><code>currentIndex--;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T19:20:14.640", "Id": "248157", "ParentId": "247716", "Score": "2" } } ]
{ "AcceptedAnswerId": "248157", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T14:24:35.567", "Id": "247716", "Score": "6", "Tags": [ "javascript", "ecmascript-6", "vue.js" ], "Title": "Team scrambler VueJs" }
247716
<p>I have written a script which does parsing to the input file and take out some values from them with respect to the node and print the data accordingly.</p> <p>Below is my script, and it works as expected:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use Time::Local 'timelocal'; use List::Util qw(reduce); use POSIX qw( strftime ); my $i = 0; print &quot;*&quot;x20; print &quot;\n&quot;; while(&lt;DATA&gt;){ chomp; next unless ($_); my @data = split / /, $_; $i++; my ($node, $time, $date, $time1, $unit); my %hash; if (scalar @data == 3){ if( $data[0] =~ /FileName=([^_]+(?=_))_(\S+)_file.csv:(\S+),/gm ){ ($node, $time, $unit) = ($2, $1, $3); if( $time =~ /[a-zA-Z](\d+).(\d+)/gm ){ $date = $1; $time1 = $2; } } print &quot;Node_$i:$node\n&quot;; my $datetime = $date.$time1; my ($second,$minute,$hour,$day,$month,$year); my $unix_time; if ($datetime =~ /(....)(..)(..)(..)(..)/){ ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1); $unix_time = timelocal($second,$minute,$hour,$day,$month-1,$year); } my @vol = split /,/, $data[2]; foreach my $element (@vol){ $hash{$unix_time} = $element; $unix_time += 6; } my $key = reduce { $hash{$a} &lt;= $hash{$b} ? $a : $b } keys %hash; my $val = $hash{$key}; my $dt = strftime(&quot;%Y-%m-%d %H:%M:%S&quot;, localtime($key)); print &quot;Text_$i:First occured on $dt on the Unit:$unit and the value is $val\n&quot;; } } print &quot;*&quot;x20; print &quot;\n&quot;; print &quot;TotalCount=$i\n&quot;; __DATA__ Node=01:FileName=A20200804.1815+0530-1816+0530_Network=NODE01_file.csv:Unit=R1,Meter=1 Vol 19,12,17,20,23,15,16,11,13,17 Node=02:FileName=A20200804.1830+0530-1831+0530_Network=NODE02_file.csv:Unit=R5,Meter=3 Vol 12,13,15,16,10,15,15,13,14,11 </code></pre> <p>So, here we have 2 lines of data in input file which is giving output something like below:</p> <pre><code>******************** Node_1:Network=NODE01 Text_1:First occured on 2020-08-04 18:15:42 on the Unit:Unit=R1 and the value is 11 Node_2:Network=NODE02 Text_2:First occured on 2020-08-04 18:30:24 on the Unit:Unit=R5 and the value is 10 ******************** TotalCount=2 </code></pre> <p>So, logic in parser is each line data belongs to each node (node will be unique in the input file). Here you can see the Volume data which is generated based on the time. For example, NODE01 volume data it shows for 18:15 to 18:16 (10 volume values, that means each value is been generated in 6secs interval and its fixed through out all the node volume data).</p> <p>From the list of volumes I should take the least number and its respective time with seconds. I am able to fetch as per the logic explained.</p> <p>Here I need experts feedback on regex (which I am using) also there are couple of <code>if</code> conditions which looks really odd to me.</p> <p>Is there any possiblity to simply the script?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T16:49:44.317", "Id": "485030", "Score": "1", "body": "@Emma the format is fixed. there will not be any deviation. But yeah thanks for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T14:48:25.287", "Id": "485290", "Score": "1", "body": "What it the purpose of the output? What is it used for? You show two lines of input, what will be a realistic input? Where does the input come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:50:51.323", "Id": "485391", "Score": "1", "body": "@HåkonHægland: The output I am using to create a alarm on the nodes (network elements). I have Network System `A` & `B`. The input shown is from `A` and that need to captured in a file and send to System `B`. From `B` script should read the file and create a Alarm for a nodes which are already available in `B`. So basically this script will act as an parser to read a input file, and help to generate an alarm." } ]
[ { "body": "<p>The code looks fine and it is working for the given input\ndata. However, it can be difficult to\nassess which inputs will be regarded as valid, and how it will behave\nin case of unexpected input. One approach to uncertainty about code\n(will it work?) is to let it pass through a testing framework. This\nrequires splitting your code into smaller units that can easily be\ntested.</p>\n<p>At the end of this post, I will present an example of how the code can\nbe adapted to a testing framework, but before that there are some\nminor issues I would like to mention.</p>\n<h2>Unecessary <code>g</code> and <code>m</code> flag</h2>\n<p>Consider this line:</p>\n<pre><code>if( $data[0] =~ /FileName=([^_]+(?=_))_(\\S+)_file.csv:(\\S+),/gm ){\n</code></pre>\n<p>Since the code is only processing a single line at a time and there is only one\nnode on each line, global matching is not necessary. Also the <code>m</code> is\nnot needed. It allows <code>^</code> and <code>$</code> to match internal the start and end of\ninternal lines for a multiline string.</p>\n<h2>Unnecessary use of lookahead regex</h2>\n<p>Consider this line:</p>\n<pre><code>if( $data[0] =~ /FileName=([^_]+(?=_))_(\\S+)_file.csv:(\\S+),/gm ){\n</code></pre>\n<p>First, as commented above we can remove the <code>g</code> and <code>m</code> flags. Then</p>\n<pre><code>/[^_]+(?=_)_/ \n</code></pre>\n<p>is simpler written as</p>\n<pre><code>/[^_]+_/\n</code></pre>\n<h2>Make code easier to read</h2>\n<p>This code:</p>\n<pre><code>($node, $time, $unit) = ($2, $1, $3);\n</code></pre>\n<p>is easier to read (my opinion) if written as:</p>\n<pre><code>($time, $node, $unit) = ($1, $2, $3);\n</code></pre>\n<p>such that the capture variables are sorted in numerical order. Similar\nfor this line:</p>\n<pre><code>my ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);\n</code></pre>\n<p>it can be written as:</p>\n<pre><code>my ($year, $month, $day, $hour, $minute, $second ) = ( $1, $2, $3, $4, $5, 0);\n</code></pre>\n<h2>Shebang</h2>\n<p>See <a href=\"https://www.cyberciti.biz/tips/finding-bash-perl-python-portably-using-env.html\" rel=\"nofollow noreferrer\">this</a> blog for more information.\nI usually use <code>#!/usr/bin/env perl</code> instead of <code>#!/usr/bin/perl</code>.\nMost systems have <code>/usr/bin/env</code>, and it allows your script to run if you e.g.have multiple <code>perl</code>s on your system. For example if you are using <code>perlbrew</code>.</p>\n<h2><code>say</code> vs <code>print</code></h2>\n<p>I prefer to use <code>say</code> instead of <code>print</code> to avoid typing a final\nnewline character for print statements.\nThe <code>say</code> function was introduced in\nperl 5.10, and is mad available by adding <code>use v5.10</code> or use <code>use feature qw(say)</code> to the top of your script.</p>\n<h2>Declare variable as close to their definition as possible</h2>\n<p>By declaring variable in the same scope as they are used and as close\nthe their first usage point as possible will help a reader to quickly\nreason about the code, which will help producing correct code. For example,\nin this code</p>\n<pre><code>my ($second,$minute,$hour,$day,$month,$year);\nif ($datetime =~ /(....)(..)(..)(..)(..)/){\n ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);\n</code></pre>\n<p>the variables are only used within the <code>if</code> clause, so we can write it as:</p>\n<pre><code>if ($datetime =~ /(....)(..)(..)(..)(..)/){\n my ($second,$minute,$hour,$day,$month,$year) = (0, $5, $4, $3, $2, $1);\n</code></pre>\n<h2>Easier parsing of dates using <a href=\"https://perldoc.perl.org/Time/Piece.html\" rel=\"nofollow noreferrer\"><code>Time::Piece</code></a></h2>\n<p>In the program below, I show how you can use <code>Time::Piece</code> instead of\n<code>timelocal</code> to simplify the parsing of dates.</p>\n<h1>Example code with unit tests</h1>\n<h2>Main script <code>p.pl</code>:</h2>\n<pre><code> #! /usr/bin/env perl\n\npackage Main;\nuse feature qw(say);\nuse strict;\nuse warnings;\n\nuse Carp;\nuse Data::Dumper qw(Dumper);\n\n# Written as a modulino: See Chapter 17 in &quot;Mastering Perl&quot;. Executes main() if\n# run as script, otherwise, if the file is imported from the test scripts,\n# main() is not run.\nmain() unless caller;\n\nsub main {\n my $self = Main-&gt;new();\n $self-&gt;run_program();\n}\n\n# ---------------------------------------------\n# Methods and subroutines in alphabetical order\n# ---------------------------------------------\n\nsub bad_arguments { die &quot;Bad arguments\\n&quot; }\n\nsub init_process_line {\n my ( $self ) = @_;\n\n $self-&gt;{lineno} = 1;\n}\n\nsub new {\n my ( $class, %args ) = @_;\n\n my $self = bless \\%args, $class;\n}\n\nsub process_line {\n my ($self, $line) = @_;\n\n my $proc = ProcessLine-&gt;new( $line, $self-&gt;{lineno} );\n $self-&gt;{lineno}++;\n return $proc-&gt;process();\n}\n\nsub read_data {\n my ( $self ) = @_;\n\n # TODO: Read the data from file instead!\n my $data = [\n'Node=01:FileName=A20200804.1815+0530-1816+0530_Network=NODE01_file.csv:Unit=R1,Meter=1 Vol 19,12,17,20,23,15,16,11,13,17',\n'Node=02:FileName=A20200804.1830+0530-1831+0530_Network=NODE02_file.csv:Unit=R5,Meter=3 Vol 12,13,15,16,10,15,15,13,14,11'\n ];\n\n $self-&gt;{data} = $data;\n}\n\nsub run_program {\n my ( $self ) = @_;\n $self-&gt;read_data();\n $self-&gt;init_process_line();\n for my $line ( @{$self-&gt;{data}} ) {\n my ($node, $dt, $unit, $val) = $self-&gt;process_line($line);\n my $res = {\n node =&gt; $node,\n dt =&gt; $dt,\n unit =&gt; $unit,\n val =&gt; $val,\n };\n # TODO: write the data to STDOUT or to file in correct format\n print Dumper($res);\n }\n}\n\npackage ProcessLine;\nuse feature qw(say);\nuse strict;\nuse warnings;\n\nuse Carp;\nuse POSIX qw( strftime );\nuse Time::Piece;\n\nsub convert_date_to_epoch {\n my ( $self, $date ) = @_;\n\n my $unix_time = Time::Piece-&gt;strptime( $date, &quot;%Y%m%d.%H%M%z&quot; )-&gt;epoch();\n return $unix_time;\n}\n\n# INPUT:\n# - $time_piece : initialized Time::Piece object\n#\n#\nsub convert_epoch_to_date {\n my ( $self, $time_piece ) = @_;\n\n my $dt = $time_piece-&gt;strftime(&quot;%Y-%m-%d %H:%M:%S&quot;);\n\n return $dt;\n}\n\nsub get_volumes {\n my ( $self, $data ) = @_;\n\n $self-&gt;parse_error(&quot;No volumes&quot;) if !defined $data;\n my @vols = split /,/, $data;\n $self-&gt;parse_error(&quot;No volumes&quot;) if @vols == 0;\n for my $vol ( @vols ) {\n if ( $vol !~ /^\\d+$/ ) {\n $self-&gt;parse_error(&quot;Volume not positive integer&quot;);\n }\n }\n return \\@vols;\n}\n\n# INPUT:\n# - $volumes : list of volumes (integers).\n#\n# RETURNS: - index of smallest item (if there are multiple minimal, the index of\n# the first is returned.\n#\n# ASSUMES:\n# - Length of list &gt;= 1\n# - Each item is a positive integer.\n# - NOTE: The items do not need to be unique.\n#\nsub find_min_vol {\n my ( $self, $volumes) = @_;\n\n my $min = $volumes-&gt;[0];\n my $idx = 0;\n for my $i (1..$#$volumes) {\n my $value = $volumes-&gt;[$i];\n if ( $value &lt; $min) {\n $min = $value;\n $idx = $i;\n }\n }\n return $idx;\n}\n\nsub new {\n my ( $class, $line, $lineno ) = @_;\n\n my $self = bless {line =&gt; $line, lineno =&gt; $lineno}, $class;\n}\n\nsub parse_error {\n my ( $self, $msg ) = @_;\n\n croak ( sprintf( &quot;Line %d: %s : '%s'\\n&quot;, $self-&gt;{lineno}, $msg,\n $self-&gt;{line} // &quot;[undef]&quot; ) );\n}\n\nsub process {\n my ($self) = @_;\n\n my $line = $self-&gt;{line};\n chomp $line;\n $self-&gt;parse_error(&quot;Empty line&quot;) if !$line;\n\n my ($field1, $field3) = $self-&gt;split_line( $line );\n my $date = $field1-&gt;get_date();\n my $node = $field1-&gt;get_node();\n my $unit = $field1-&gt;get_unit();\n my $unix_time = $self-&gt;convert_date_to_epoch( $date );\n my $volumes = $self-&gt;get_volumes( $field3 );\n my $idx = $self-&gt;find_min_vol($volumes);\n my $vol = $volumes-&gt;[$idx];\n my $vol_epoch = $unix_time + $idx*6;\n my $time_piece = localtime($vol_epoch); # convert to local time zone\n my $dt = $self-&gt;convert_epoch_to_date( $time_piece );\n return ($node, $dt, $unit, $vol);\n}\n\n# INPUT:\n# - $line: defined string\n#\nsub split_line {\n my ( $self, $line ) = @_;\n\n my @data = split / /, $line;\n my $N = scalar @data;\n $self-&gt;parse_error( &quot;Expected 3 fields (space-separated). Got $N fields.&quot;) if $N !=3;\n return (Field0-&gt;new($self, $data[0]), $data[2]);\n}\n\npackage Field0;\nuse feature qw(say);\nuse strict;\nuse warnings;\n\nsub get_date {\n my ( $self ) = @_;\n my $data = $self-&gt;{data};\n my $date;\n if( $data =~ s/FileName=([^_]+)_// ) {\n my $time = $1;\n if( $time =~ /[a-zA-Z](\\d{8}\\.\\d{4}[+-]\\d{4})-\\d{4}[+-]/ ) {\n $date = $1;\n }\n else {\n $self-&gt;{parent}-&gt;parse_error(&quot;Could not parse time info&quot;);\n }\n }\n else {\n $self-&gt;{parent}-&gt;parse_error(&quot;Could not parse time info&quot;);\n }\n $self-&gt;{data} = $data;\n return $date;\n}\n\nsub get_node {\n my ( $self ) = @_;\n my $data = $self-&gt;{data};\n my $node;\n if( $data =~ s/(\\S+)_// ) {\n $node = $1;\n }\n else {\n $self-&gt;{parent}-&gt;parse_error(&quot;Could not parse node info&quot;);\n }\n $self-&gt;{data} = $data;\n return $node;\n}\n\nsub get_unit {\n my ( $self ) = @_;\n my $data = $self-&gt;{data};\n my $unit;\n if( $data =~ s/file\\.csv:(\\S+),// ) {\n $unit = $1;\n }\n else {\n $self-&gt;{parent}-&gt;parse_error(&quot;Could not parse unit info&quot;);\n }\n $self-&gt;{data} = $data;\n return $unit;\n}\n\nsub new {\n my ( $class, $parent, $data ) = @_;\n return bless {parent =&gt; $parent, data =&gt; $data}, $class;\n}\n</code></pre>\n<h2>Unit test script <code>t/main.t</code>:</h2>\n<pre><code>use strict;\nuse warnings;\nuse Test2::Tools::Basic qw(diag done_testing note ok);\nuse Test2::Tools::Compare qw(is like);\nuse Test2::Tools::Exception qw(dies lives);\nuse Test2::Tools::Subtest qw(subtest_buffered);\nuse lib '.';\nrequire &quot;p.pl&quot;;\n\n{\n subtest_buffered &quot;split line&quot; =&gt; \\&amp;split_line;\n subtest_buffered &quot;get_date&quot; =&gt; \\&amp;get_date;\n subtest_buffered &quot;get_node&quot; =&gt; \\&amp;get_node;\n # TODO: Complete the test suite..\n done_testing;\n}\n\nsub get_date {\n my $proc = ProcessLine-&gt;new( &quot;&quot;, 1 );\n my $fld = Field0-&gt;new($proc, &quot;Node=01:FileName=A20200804.1815+0530-1816+0530_N&quot;);\n is($fld-&gt;get_date(), '20200804.1815+0530', 'correct');\n $fld = Field0-&gt;new($proc, &quot;ileName=A20200804.1815+0530-1816+0530_N&quot;);\n like(dies { $fld-&gt;get_date() }, qr/Could not parse/, &quot;bad input&quot;);\n $fld = Field0-&gt;new($proc, &quot;FileName=A20200804.1815-1816+0530_N&quot;);\n like(dies { $fld-&gt;get_date() }, qr/Could not parse/, &quot;bad input2&quot;);\n}\n\nsub get_node {\n my $proc = ProcessLine-&gt;new( &quot;&quot;, 1 );\n my $fld = Field0-&gt;new($proc, &quot;Node=01:FileName=A20200804.1815+0530-1816+0530_N&quot;);\n # TODO: complete this sub test..\n}\n\nsub split_line {\n my $proc = ProcessLine-&gt;new( &quot;&quot;, 1 );\n like(dies { $proc-&gt;split_line( &quot;&quot; ) }, qr/Got 0 fields/, &quot;zero fields&quot;);\n like(dies { $proc-&gt;split_line( &quot; &quot; ) }, qr/Got 0 fields/, &quot;zero fields&quot;);\n like(dies { $proc-&gt;split_line( &quot;1&quot; ) }, qr/Got 1 fields/, &quot;one field&quot;);\n like(dies { $proc-&gt;split_line( &quot;1 2&quot; ) }, qr/Got 2 fields/, &quot;two fields&quot;);\n my ($f1, $f3);\n ok(lives { ($f1, $f3) = $proc-&gt;split_line( &quot;1 2 3&quot; ) }, &quot;three fields&quot;);\n is($f1-&gt;{data}, &quot;1&quot;, &quot;correct value&quot;);\n is($f3, &quot;3&quot;, &quot;correct value&quot;);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-02T17:13:44.957", "Id": "490642", "Score": "1", "body": "Re \"*Unecessary g and m flag*\", In fact, `g` isn't just unnecessary in `if (//g)`; it's wrong. It can lead to subtle and hard to debug problems. Example: `perl -le'$_ = \"ab\"; print /b/g ? 1 : 0; print /a/g ? 1 : 0;'`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-23T20:38:26.123", "Id": "248336", "ParentId": "247720", "Score": "6" } } ]
{ "AcceptedAnswerId": "248336", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T16:27:35.333", "Id": "247720", "Score": "8", "Tags": [ "parsing", "regex", "perl" ], "Title": "Parse data from Input file and print results" }
247720
<p>I'm practicing algorithms, and I just can not come up with a faster solution to this problem, but I'm not hitting the benchmark.</p> <p><strong>Problem</strong>: In a large list of large integers, I must find the one element, that is present in odd numbers. E.g. [<em>1,1,1,1, 2,2</em>, <strong>3,3,3</strong>, <em>4,4,4,4</em>].</p> <p>I wrote several solutions, but I can not increase the speed of the execution.</p> <pre class="lang-py prettyprint-override"><code>import random def testdata(): space = [] for i in range(10000): space = ( space + [random.randint(0,1000000000)] * (random.randint(1,10) * 2) ) odd = random.randint(0,1000000000) print(odd) space = space + [odd] random.shuffle(space) return space def solution(A): A.sort() index = 0 while True: count = A.count(A[index]) if count%2: return(A[index]) else: index = index + count def solution_b(A): for elem in set(A): if A.count(A)%2: return(elem) </code></pre> <p>I'm not only looking for a better solution, but I'd appreciate it if someone explained, how to approach this kind of <em>Big O notation</em> problems. Without using pandas or numpy, etc.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T17:26:17.893", "Id": "485033", "Score": "0", "body": "Can you give numpy a try ? https://stackoverflow.com/a/35549699/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:12:47.627", "Id": "485064", "Score": "1", "body": "The only way to find out about better algorithms (not brute force) is to either see them used or be a mathematician (or be good at google for clever algorithms)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T12:47:22.793", "Id": "485157", "Score": "0", "body": "@anki I can not, this is a test, where you can not use the scientific python libraries, like pandas, numpy, scipy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:51:49.913", "Id": "485347", "Score": "3", "body": "If you don't sort, you can just linearly go through the list and keep a map on the side with the count. If we say that the list is `n` elements of `k` different numbers, this solution would be `O(n)` in time and `O(k)` in space." } ]
[ { "body": "<p>In both solutions, <code>A.count()</code> searches the entire list.</p>\n<p>Try using a set. For each element in the list, check if the element is in the set. If it isn't in the set, add it; if it is in the set then remove it. When you reach the end of the list, the set will contain only items that had an odd number of them in the list.</p>\n<pre><code>def solution(A):\n odd = set()\n\n for item in A:\n if item in odd:\n odd.remove(item)\n else:\n odd.add(item)\n\n return odd.pop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:13:48.320", "Id": "485065", "Score": "2", "body": "Until I read vnp's answer this is how I would have done it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:35:22.310", "Id": "485107", "Score": "3", "body": "@MartinYork this would be the best solution for non integers or if we cannot grant exactly one number to be present odd number of times in which case it can reveal all such numbers or tell that there is no such number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T00:01:04.780", "Id": "485205", "Score": "4", "body": "@MartinYork, this is still how I'd do it in any situation except a \"clever coding\" competition. It's more robust against unexpected situations, such as two unpaired elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T00:08:10.703", "Id": "485206", "Score": "2", "body": "@Mark: I would have histogrammed into an array of counters (or hash table is the keys can be scattered), then looked for odd counts. Although using 1-bit counters (and thus toggling) will basically reduce to set add / remove. I'd probably avoid actually removing elements from a dictionary after seeing a pair if I was using a hash table, since that costs more work and might slow down seeing a 3rd one. (Unless there are a lot of unique pairs, so freeing up space to keep the hash table small is good.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:55:17.010", "Id": "485348", "Score": "0", "body": "@PeterCordes my solution too, also since OP mentions that are large integers, hash table is probably a better guess. In term of space complexity, I would say that using counters or sets should not be that much different in the worst case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:00:48.580", "Id": "485349", "Score": "0", "body": "@bracco23: worst case sure, but choice of algorithm and data structure is usually based on having a good *average* or typical case for your expected inputs, with maybe a constraint of having a worst case that's equal or not much worse. e.g. sometimes you'd use QuickSort over MergeSort, even though it has a rare pathological worst-case of O(N^2), while MergeSort is fixed at O(N logN) time complexity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:03:36.717", "Id": "485350", "Score": "2", "body": "In this case, probably for a large input array, you'd use a space-efficient hash set and actually take the time to decide between adding or removing an element, instead of just finding and flipping a boolean counter. Worst case still O(N) space if you see all the unique elements first, before finding any pairs. But hopefully in most cases, you can get away with much less than O(N) space by recycling entries. But for medium to small input arrays, where the *typical* space for an add-only hash table still fits in L2 or even L1 cache, you might just index and flip a counter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:08:42.210", "Id": "485351", "Score": "0", "body": "Especially if lots of repeats of the same values are common (over the whole input, not contiguous), a hash table of counters is nice if it's hot in cache, trading off a bit more space for less work per input element. That extra space doesn't cost speed as long as it fits in cache. (Except at the end when you have to scan to find odd elements. But shrinking / re-compacting a hash set costs that work during the operation as you remove elements, instead of at the end. Scanning through the array and looking for buckets with odd counts can be as cheap as looking for used elements.)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:52:19.480", "Id": "247729", "ParentId": "247723", "Score": "14" } }, { "body": "<p>This is not a review, but an extended comment.</p>\n<p>The linear time/constant space solution is too well known to be spelled out again. However, here it goes.</p>\n<p><code>XOR</code> of two equal numbers is 0, and <code>XOR</code> of a number and 0 leaves the number unchanged. <code>XOR</code> is commutative and associative operation; we may perform it in any order we wish, and arrive to the same result. In other words, if we <code>XOR</code> all of them, each pair of numbers would cancel to 0, and the final result would be the number without a pair, the one we are looking for.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:10:54.207", "Id": "485062", "Score": "4", "body": "That's clever. I learn something new every day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T05:09:08.110", "Id": "485114", "Score": "0", "body": "My upvote is for pointing out that it's well known :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T06:15:18.860", "Id": "485119", "Score": "14", "body": "Obligatory 1-line implementation of the above: `return functools.reduce(operator.xor, A)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:18:14.837", "Id": "485191", "Score": "12", "body": "Not only would I argue that this is not widely known, it also only works if there is a single number that is repeated an odd amount of times. If there are multiple odd repeats, you won't magically get a list of all offending numbers, you'll just get a (for all intents and purposes) random number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:45:38.403", "Id": "485193", "Score": "6", "body": "@vnp I've never seen this before and think it's great. However, while I think this answer would be really cool for Stack Overflow it misses the mark for Code Review. I know you're posting it as an \"extended comment\" but that's not really a thing, since now it's on top by a wide margin and doesn't review OP's code. Maybe in the future you could post it as an actual comment, either broken up as two comments or a link to another place explaining it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T19:05:57.013", "Id": "485197", "Score": "6", "body": "Note that this algorithm will return 0 if 0 is unpaired and if there are no unpaired numbers. Unless it is guaranteed that there is exactly one unpaired number, a separate check is needed to see how many zero elements there are when the XOR procedure returns 0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T03:44:45.737", "Id": "485220", "Score": "1", "body": "@MarkH but thats only if we cannot grant exactly one unpaired number in the list, but that's also the assumption that we made (that we CAN grant it) to allow this algorithm to work. And so if the check for zero was necesary we are already using a bad algorithm." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T19:42:21.590", "Id": "247733", "ParentId": "247723", "Score": "42" } }, { "body": "<p>You can use <code>collections.Counter</code> to solve this problem with a time complexity of O(N) and a space complexity of also O(N).</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nmy_array = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4]\nmy_counter = Counter(my_array)\n\n# Thanks to @AlexeyBurdin and @Graipher for improving this part.\nprint(next(k for k, v in my_counter.items() if v % 2))\n</code></pre>\n<p>This will print out the first element which occurs an odd number of times.</p>\n<p>You can read more about <code>collections.Counter</code> <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\">here</a>.</p>\n<p>This is the simplest and fastest solution I can think of.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:11:58.797", "Id": "485125", "Score": "3", "body": "I would use `[k for k,v in my_counter.items() if v % 2]` instead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T09:05:06.817", "Id": "485133", "Score": "4", "body": "Even better: `next(k for k, v in counter.items() if v % 2)`, since you know there is only one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T20:10:39.513", "Id": "485315", "Score": "2", "body": "That would be O(N) average case or does Counter always gets a perfect hash? otherwise it would be worst case O(N**2) using hash or O(n lg N) using red-black tree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T23:54:57.707", "Id": "485320", "Score": "0", "body": "@Surt IIRC the hash used is just the integer itself, and the hashtable implementation makes some efforts to keep that from being a problem for well-crafted inputs targeting a particular table size like `[1, 65, 129, ...]`, but it's a best-effort to satisfy common cases, and malicious inputs are easy to construct." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T20:52:27.913", "Id": "247739", "ParentId": "247723", "Score": "16" } }, { "body": "<p>Okay so I do not really understand the issue or why this should not be trivially linear. Note: I dont know python or those fancy shortcuts used in previous answers. Just using simple basic functions (Java style, translate to whatever floats your boat):</p>\n<ol>\n<li>Iteration through an array: O(n)</li>\n<li>Array element access: O(1) it seems.. (<a href=\"https://stackoverflow.com/questions/37120776/accessing-elements-really-o1\">https://stackoverflow.com/questions/37120776/accessing-elements-really-o1</a>)</li>\n</ol>\n<p>So..</p>\n<pre class=\"lang-java prettyprint-override\"><code>int[] numbers = [1,1,2,2,3,3,3];\nint maxNumber = 0; //or maxNegative if you include negative\n\n//find maxNumber by iterating once in O(n)\nfor(int i = 0; i &lt; numbers.length; i++){\n if(numbers[i]&gt;maxumber)\n maxNumber = numbers[i];\n }\n}\n \n//new array of length maxNumber\nint[] numberOccurences = new int[maxNumber];\n\n//initialize array in O(n)\nfor(int i = 0; i &lt; numberOccurences.length; i++){\n numberOccurences[i] = 0;\n}\n \n//count all number occurences in O(n)\nfor(int num : numbers){\n numberOccurences[num]++;\n}\n\n//get all numbers with odd occurences in O(n)\nfor(int i = 0; i &lt; numberOccurences.length; i++){\n if(numberOccurences[i]%2!=0){\n print(i)\n }\n }\n</code></pre>\n<p>So as far as I can see that solves it in 4x O(n) = O(n) with just simple loops. If you need negative numbers, just use 2 arrays, that wont change anything. If you have double values, multiply them by 10 to the power of maximum number of decimal places. Please correct me if I am wrong.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T00:18:45.647", "Id": "485208", "Score": "0", "body": "If your values aren't small to medium integers, use a hash table (dictionary) to map num -> count, but yes, histogram and then look for odd count buckets is the obvious way here. The pythonic version of this is apparently `collections.Counter`, as suggested by a different answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T00:18:51.463", "Id": "485209", "Score": "0", "body": "If you have an upper bound on max, you can avoid the first pass through the list, especially useful if that `max` is much less than N (i.e. there are a lot of repeats.) Or use a data structure that can realloc and grow on the fly for amortized O(1) if you pick too low. To minimize cache footprint (and the amount of memory you have to zero to start with), the count array can be bytes instead of `int`, or even single-bit counters because you only care about the low bit of the count, and wrapping the high part doesn't affect that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T00:22:08.590", "Id": "485210", "Score": "1", "body": "(If the array values are scattered, a hash table could perform better than a very sparse array where each element you access is in a different page of virtual memory.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:02:33.003", "Id": "485258", "Score": "0", "body": "Yea I would use HashMaps in reality (I love them), but those have O(log n) accessing time in worst case so the O(n) wouldn't be guaranteed or harder to argue. And your optimizations are totally true, this is a very basic way and only targets speed not memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T17:28:32.670", "Id": "485301", "Score": "0", "body": "[Java 8 HashMap](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) was my first google hit. It provides O(1) amortized *average* time. I'd be surprised if the worst case is as good as log(n), probably n when it has to reallocate to grow. But it'll grow exponentially (e.g. by a factor of 2) to make growth as infrequent as O(N / N) = O(1) *on average*. Perhaps with O(log(N)) you're thinking of an *ordered* map based on a tree? HashMap is unordered, like C++ `std::unordered_map` or `unordered_set`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:03:42.203", "Id": "485431", "Score": "0", "body": "Frankly when writing the answer I just googled \"hashmap access o notation\" to see if its O(1) and took this at face value: https://stackoverflow.com/questions/1055243/is-a-java-hashmap-really-o1. One comment said O(log n) worst case and I just believed it. They're fast in practice and but not O(1) in theory, that's all I needed to know ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:36:49.050", "Id": "485435", "Score": "0", "body": "Oh right, [this answer](//stackoverflow.com/a/29314354/224132) comments on what happens when multiple entries collide at one bucket. That's rare with a reasonable load factor (like the default 0.75) except in pathological cases where many inputs hash to the same bucket even though lots of other buckets are unused. So yes, that *does* make the worst case amortized O(log N), and worst case for a single access still O(N). (Where N is the number of unique keys in the table). But that log(N) worst case is not going to happen by accident, probably only with malicious input crafted to collide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:39:22.810", "Id": "485438", "Score": "0", "body": "So HashMap does have O(1) amortized time per get / put on average in the normal case, and actually pretty robust handling of the worst possible case if you run this on malicious data from the Internet and someone wants to grind your server to a halt with a DOS attack that uses up its CPU time." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T23:00:19.567", "Id": "247789", "ParentId": "247723", "Score": "2" } }, { "body": "<p>A refinement for your first <code>solution()</code>: after you sort the list, you can just go through it in double-steps, comparing the neighboring elements. When they differ, the first one is what you are looking for:</p>\n<pre><code>def solution(A):\n A.sort()\n index = 0\n while True:\n if A[index] != A[index+1]:\n return A[index]\n index += 2\n</code></pre>\n<p>Like with the example sorted list from the question:</p>\n<pre><code>[1,1,1,1,2,2,3,3,3,4,4,4,4]\n 1=1 1=1 2=2 3=3 3!4\n ^ this is the one missing a pair\n</code></pre>\n<p>This approach has the complexity of the sorting algorithm, <code>O(n log n)</code> I would assume.</p>\n<hr>\nThen comes the comment below and handling the unlucky event of having the pair-less element at the very end.\n<p>Sticking to minimal modifications:</p>\n<pre><code>def solution(A):\n A.sort()\n index = 0\n while True:\n if index+1 &gt;= len(A):\n return A[-1]\n if A[index] != A[index+1]:\n return A[index]\n index += 2\n</code></pre>\n<p>However if I wrote it from scratch, I would probably use a loop which simply exits and I would also cache <code>len(A)</code>:</p>\n<pre><code>def solution(A):\n A.sort()\n limit = len(A) - 2\n index = 0\n while index&lt;limit:\n if A[index] != A[index+1]:\n return A[index]\n index += 2\n return A[-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:26:33.310", "Id": "485393", "Score": "0", "body": "Fails `solution([0])`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:02:03.570", "Id": "485404", "Score": "0", "body": "@superbrain yes, thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:49:43.517", "Id": "247853", "ParentId": "247723", "Score": "0" } } ]
{ "AcceptedAnswerId": "247733", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T17:19:31.467", "Id": "247723", "Score": "15", "Tags": [ "python", "performance" ], "Title": "Finding an element without pair in a list O(n**2)" }
247723
<p>I am asking this, because after studying I am confused that it is necessary to declare base class object, then declare derived class object and then store reference of derived class object in base class in c++ to use polymorphism. But what do you think, did I use polymorphism in <code>Accounts</code>, <code>CurrentAccount</code>, <code>SavingAccount</code> and also between <code>Person</code>, <code>Customer</code>, <code>Manager</code> classes or not?</p> <p>The code runs correctly with no issues, but the concept is confusing.</p> <p>Accounts.h</p> <pre><code>#pragma once #include&lt;iostream&gt; #include&lt;string&gt; #include &lt;vector&gt; using namespace std; class Accounts { public: Accounts(); ~Accounts(); virtual void WithDraw(int) = 0; virtual void Deposit(int, string, int, int) = 0;//Also can be named as add Account virtual void Balance() {}; virtual void DeleteAccount(int)=0; virtual int getAccountsNumber()=0; }; //Definning classes methods Accounts::Accounts() { cout &lt;&lt; &quot;\nThe Accounts class started\n&quot;; //no need to initialize vectors.They work perfect without initializing.C++ has done work for it } Accounts::~Accounts() { cout &lt;&lt; &quot;\nThe Accounts class Ended\n&quot;; } </code></pre> <p>CurrentAccount.h</p> <pre><code>#pragma once #include&quot;Accounts.h&quot; class CurrentAccount:public Accounts { public: CurrentAccount(); ~CurrentAccount(); void WithDraw(int); void Deposit(int, string, int, int);//Also can be named as add Account void Balance(); void DeleteAccount(int); int getAccountsNumber(); protected: vector&lt;int&gt; Account_ID_Current; vector&lt;string&gt; AccountType_Current; vector&lt;int&gt; Customer_ID_Current; vector&lt;int&gt; Account_Balance_Current; }; CurrentAccount::CurrentAccount() { cout &lt;&lt; &quot;\nCreate Account Class started&quot;; } CurrentAccount::~CurrentAccount() { cout &lt;&lt; &quot;\nCreate Account Class ENDED&quot;; } void CurrentAccount::Deposit(int AID, string AT, int CID, int AB) { Account_ID_Current.push_back(AID); AccountType_Current.push_back(AT); Customer_ID_Current.push_back(CID); Account_Balance_Current.push_back(AB); } void CurrentAccount::WithDraw(int index) { cout &lt;&lt; &quot;\nThe Account ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; Account_ID_Current[index] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Account Type of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; AccountType_Current[index] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Customer ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; Customer_ID_Current[index] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Account Balance of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; Account_Balance_Current[index] &lt;&lt; endl; } void CurrentAccount::DeleteAccount(int index) { Account_ID_Current.erase(Account_ID_Current.begin() + index); AccountType_Current.erase(AccountType_Current.begin() + index); Customer_ID_Current.erase(Customer_ID_Current.begin() + index); Account_Balance_Current.erase(Account_Balance_Current.begin() + index); //Displaying that the account is successfully removed from the bank cout &lt;&lt; &quot;\nThe Account ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; cout &lt;&lt; &quot;\nThe Account Type of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; cout &lt;&lt; &quot;\nThe Customer ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; cout &lt;&lt; &quot;\nThe Account Balance of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; } //It will display all the balance in the bank void CurrentAccount::Balance() { //The static int is not changed on the iteration where ever used in the loop or where ever static int sum = 0;//To store the sum of all balance for (int i = 0; i &lt; Account_ID_Current.size(); i++) { sum = sum + Account_Balance_Current[i]; } cout &lt;&lt; &quot;\nThe total balance in the bank in the current account is equal to : &quot; &lt;&lt; sum; } int CurrentAccount::getAccountsNumber() { return Account_ID_Current.size(); } </code></pre> <p>SavingAccount</p> <pre><code>#pragma once #include&quot;Accounts.h&quot; class SavingAccount :public Accounts { public: SavingAccount(); ~SavingAccount(); void WithDraw(int); void Deposit(int, string, int, int);//Also can be named as add Account void Balance(); void DeleteAccount(int); int getAccountsNumber(); protected: vector&lt;int&gt; Account_ID_Saving; vector&lt;string&gt; AccountType_Saving; vector&lt;int&gt; Customer_ID_Saving; vector&lt;int&gt; Account_Balance_Saving; }; SavingAccount::SavingAccount() { cout &lt;&lt; &quot;\nSaving Account Class started&quot;; } SavingAccount::~SavingAccount() { cout &lt;&lt; &quot;\nSaving Account Class ENDED&quot;; } void SavingAccount::Deposit(int AID, string AT, int CID, int AB) { Account_ID_Saving.push_back(AID); AccountType_Saving.push_back(AT); Customer_ID_Saving.push_back(CID); Account_Balance_Saving.push_back(AB); } void SavingAccount::WithDraw(int index) { cout &lt;&lt; &quot;\nThe Account ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; Account_ID_Saving[index] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Account Type of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; AccountType_Saving[index] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Customer ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; Customer_ID_Saving[index] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Account Balance of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; person is equal to: &quot; &lt;&lt; Account_Balance_Saving[index] &lt;&lt; endl; } void SavingAccount::DeleteAccount(int index) { Account_ID_Saving.erase(Account_ID_Saving.begin() + index); AccountType_Saving.erase(AccountType_Saving.begin() + index); Customer_ID_Saving.erase(Customer_ID_Saving.begin() + index); Account_Balance_Saving.erase(Account_Balance_Saving.begin() + index); //Displaying that the account is successfully removed from the bank cout &lt;&lt; &quot;\nThe Account ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; cout &lt;&lt; &quot;\nThe Account Type of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; cout &lt;&lt; &quot;\nThe Customer ID of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; cout &lt;&lt; &quot;\nThe Account Balance of &quot; &lt;&lt; (index + 1) &lt;&lt; &quot; was successfully removed from the bank&quot;; } //It will display all the balance in the bank void SavingAccount::Balance() { //The static int is not changed on the iteration where ever used in the loop or where ever static int sum = 0;//To store the sum of all balance for (int i = 0; i &lt; Account_ID_Saving.size(); i++) { sum = sum + Account_Balance_Saving[i]; } cout &lt;&lt; &quot;\nThe total balance in the bank is equal to : &quot; &lt;&lt; sum; } int SavingAccount::getAccountsNumber() { return Account_ID_Saving.size(); } </code></pre> <p>Bank.h</p> <pre><code>#include&quot;Accounts.h&quot; #include&quot;CurrentAccount.h&quot; #include&quot;SavingAccount.h&quot; #include&quot;Customer.h&quot; #include&quot;Manager.h&quot; using namespace std; class Bank { Customer customers; CurrentAccount accountsC; SavingAccount accountsS; public: Bank(); ~Bank(); //Methods for current accounts void Add_Current_Account(int, string, int, int); int Get_Current_NoOfAccounts(); void Delete_Current_Account(int); void getAll_current_Balance(); //Methods for current accounts //Methods for saving accounts void Add_Saving_Account(int, string, int, int); int Get_Saving_NoOfAccounts(); void Delete_Saving_Account(int); void getAll_saving_Balance(); //Methods for saving accounts void AddCustomer(string, int); void DeleteCustomer(int); string GetCustomer_Name(int); void driverProgram(); }; Bank::Bank() { cout &lt;&lt; &quot;\nThe program is in the bank class\n&quot;; } //Current Account void Bank::Add_Current_Account(int AID, string AT, int CID, int AB) { accountsC.Deposit(AID, AT, CID, AB); } void Bank::Delete_Current_Account(int index) { accountsC.DeleteAccount(index); } int Bank::Get_Current_NoOfAccounts() { int num = accountsC.getAccountsNumber(); return num; } void Bank::getAll_current_Balance() { accountsC.Balance(); } //Current Account //Saving Account void Bank::getAll_saving_Balance() { accountsS.Balance(); } void Bank::Add_Saving_Account(int AID, string AT, int CID, int AB) { accountsS.Deposit(AID, AT, CID, AB); } void Bank::Delete_Saving_Account(int index) { accountsS.DeleteAccount(index); } int Bank::Get_Saving_NoOfAccounts() { int num = accountsS.getAccountsNumber(); return num; } //Saving Account void Bank::AddCustomer(string name, int ID) { customers.AddCustomer(name, ID); } void Bank::DeleteCustomer(int index) { customers.DeleteCustomer(index); } string Bank::GetCustomer_Name(int index) { string name = customers.getCustomerName(index); return name; } void Bank::driverProgram() { Manager m1; //For Polymorphism and using virtual functions pointers or refrences one is necessary to use otherwise //we cannot use virtual functions and polymorphism Accounts* currentAccount; currentAccount = new CurrentAccount(); //I am declaring current account pointer //Declaring Saving Account Accounts* savingAccount; savingAccount = new SavingAccount(); //Declaring Saving Account Bank b1; char options; cout &lt;&lt; &quot;\n\nEnter what you want to do \n1 for entering the managers data,\n2 for showing the managers data &quot; &lt;&lt; &quot;\n3 for adding a customer in the bank\n4 for adding an Account in the bank \n5 for deleting the customer\n&quot; &lt;&lt; &quot;\n6 for deleting the Account\n7 for getting customer name\n8 for getting the No. of Accounts&quot; &lt;&lt; &quot;\n9 for seeing all the balance in the bank\nPress 'e' for exit&quot;; cin &gt;&gt; options; switch (options) { case '1': { string name; string branch; int id; //The manager class data cout &lt;&lt; &quot;\nEnter the Data of managers Class: \n&quot;; cout &lt;&lt; &quot;\nEnter the name of manager: \t&quot;; cin &gt;&gt; name; cout &lt;&lt; &quot;\nEnter the branch of manager: \t&quot;; cin &gt;&gt; branch; cout &lt;&lt; &quot;\nEnter the Id of manager: \t&quot;; cin &gt;&gt; id; m1.TakeManagersData(name, branch, id); break; } case '2': { cout &lt;&lt; &quot;\nThe data of Manager is : &quot;; m1.Print_ManagerDetails(); break; } case '3': { string Cname; int CID; cout &lt;&lt; &quot;\nEnter the name of customer: &quot;; cin &gt;&gt; Cname; cout &lt;&lt; &quot;\nEnter the Customer ID: &quot;; cin &gt;&gt; CID; b1.AddCustomer(Cname, CID); break; } case '4': { char optionB; cout &lt;&lt; &quot;There are two options available for creating account.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; int AID; int CID; int AB; string AT; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nEnter the Account ID: &quot;; cin &gt;&gt; AID; cout &lt;&lt; &quot;\nEnter the Customer ID: &quot;; cin &gt;&gt; CID; cout &lt;&lt; &quot;\nEnter the Account BALANCE: &quot;; cin &gt;&gt; AB; cout &lt;&lt; &quot;\nEnter the Account Type: &quot;; cin &gt;&gt; AT; b1.Add_Saving_Account(AID, AT, CID, AB); cout &lt;&lt; &quot;\nSuccessfully created a Saving account\tBut delete it as soon as possible\n&quot;; break; } case'2': { cout &lt;&lt; &quot;\nEnter the Account ID: &quot;; cin &gt;&gt; AID; cout &lt;&lt; &quot;\nEnter the Customer ID: &quot;; cin &gt;&gt; CID; cout &lt;&lt; &quot;\nEnter the Account BALANCE: &quot;; cin &gt;&gt; AB; cout &lt;&lt; &quot;\nEnter the Account Type: &quot;; cin &gt;&gt; AT; b1.Add_Current_Account(AID, AT, CID, AB); cout &lt;&lt; &quot;\nSuccessfully created a Current account\nKeep It as long as you want\n&quot;; break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case '5': { int index; cout &lt;&lt; &quot;\nEnter the customer which you want to delete: &quot;; cin &gt;&gt; index; b1.DeleteCustomer(index); break; } case '6': { char optionB; cout &lt;&lt; &quot;There are two options available for DELETING account.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; int index; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nEnter the account number you want to delete\n&quot;; cin &gt;&gt; index; b1.Delete_Saving_Account(index); cout &lt;&lt; &quot;\nSuccessfully deleted Saving account at the given address\n&quot;; break; } case'2': { cout &lt;&lt; &quot;\nEnter the account number you want to delete\n&quot;; cin &gt;&gt; index; b1.Delete_Current_Account(index); cout &lt;&lt; &quot;\nSuccessfully deleted a Current account at current index\n&quot;; break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case '7': { int cn; cout &lt;&lt; &quot;\nEnter the customer ID which you want to get name: &quot;; cin &gt;&gt; cn; b1.GetCustomer_Name(cn); break; } case '8': { char optionB; cout &lt;&lt; &quot;There are two options available for getting number of account.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nThe number of accounts of Saving account type are: \t&quot; &lt;&lt; b1.Get_Saving_NoOfAccounts() &lt;&lt; endl; break; } case'2': { cout &lt;&lt; &quot;\nThe number of accounts of Current account type are: \t&quot; &lt;&lt; b1.Get_Current_NoOfAccounts() &lt;&lt; endl; break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case '9': { char optionB; cout &lt;&lt; &quot;There are two options available for getting the balance in the bank.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nThe Balance of Saving account type is: \t&quot; &lt;&lt; endl; b1.getAll_saving_Balance(); break; } case'2': { cout &lt;&lt; &quot;\nThe Balance of Current account type is: \t&quot; &lt;&lt; endl; b1.getAll_current_Balance(); break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case 'e': { cout &lt;&lt; &quot;The program is ending now: &quot;; break; } default: { cout &lt;&lt; &quot;\n\nEnter right value please: \n&quot;; } delete currentAccount; delete savingAccount; currentAccount = nullptr; savingAccount = nullptr; } } Bank::~Bank() { cout &lt;&lt; &quot;\nThe Bank class ended \n&quot;; } </code></pre> <p>Customer.h</p> <pre><code>#pragma once #include&lt;iostream&gt; #include&lt;string&gt; #include&lt;vector&gt; #include&quot;Person.h&quot; using namespace std; class Customer:protected Person { public: Customer(); void AddCustomer(string, int); void PrintAllCustomersData(); void DeleteCustomer(int); void Print_CustomerDetails(int); string getCustomerName(int); }; Customer::Customer() { cout &lt;&lt; &quot;\nThe customer class started\n&quot;; } void Customer::AddCustomer(string n, int id) { Name.push_back(n); ID.push_back(id); cout &lt;&lt; &quot;\nThe customer &quot; &lt;&lt; n &lt;&lt; &quot;with Id: &quot; &lt;&lt; id &lt;&lt; &quot; was successfully added in the Bank.&quot;; } void Customer::PrintAllCustomersData() { for (unsigned int i = 0; i &lt; ID.size(); i++) { cout &lt;&lt; &quot;\nThe ID of &quot; &lt;&lt; (i + 1) &lt;&lt; &quot;Customer is : &quot; &lt;&lt; ID[i] &lt;&lt; &quot; and NAME is : &quot; &lt;&lt; Name[i]; } } void Customer::DeleteCustomer(int index) { Name.erase(Name.begin() + index); ID.erase(ID.begin() + index); cout &lt;&lt; &quot;\nThe customer with Name : &quot; &lt;&lt; Name[index] &lt;&lt; &quot; and ID: &quot; &lt;&lt; ID[index] &lt;&lt; &quot; was successfully deleted\n&quot;; } void Customer::Print_CustomerDetails(int index) { cout &lt;&lt; &quot;The Customer Name is : &quot; &lt;&lt; Name[index] &lt;&lt; endl; cout &lt;&lt; &quot;The Id of Customer is : &quot; &lt;&lt; ID[index] &lt;&lt; endl; } string Customer::getCustomerName(int index) { return (Name[index]); } </code></pre> <p>Manager.h</p> <pre><code>#pragma once #include&quot;Person.h&quot; class Manager:protected Person { public: void Print_ManagerDetails(); void TakeManagersData(string, string, int); }; void Manager::Print_ManagerDetails() { cout &lt;&lt; &quot;\nName.size: &quot; &lt;&lt; Name.size(); cout &lt;&lt; &quot;\nID.size: &quot; &lt;&lt; ID.size(); cout &lt;&lt; &quot;\nBranch.size: &quot; &lt;&lt; Branch.size(); for (int i = 0; i &lt; Name.size(); i++) { cout &lt;&lt; &quot;\nThe ID of Manager is : &quot; &lt;&lt; ID[i] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Name of Manager is : &quot; &lt;&lt; Name[i] &lt;&lt; endl; cout &lt;&lt; &quot;\nThe Branch of Manager is : &quot; &lt;&lt; Branch[i] &lt;&lt; endl; } } void Manager::TakeManagersData(string n, string b, int id) { Name.push_back(n); Branch.push_back(b); ID.push_back(id); } </code></pre> <p>Person.h</p> <pre><code>#pragma once #include&lt;iostream&gt; using namespace std; class Person { protected: vector&lt;string&gt; Name; vector&lt;int&gt; ID; vector&lt;string&gt; Branch; public: Person(); ~Person(); }; Person::Person() { cout &lt;&lt; &quot;\nPerson class started\n&quot;; } Person::~Person() { cout &lt;&lt; &quot;\nPerson class ENDED\n&quot;; } </code></pre> <p>Source.cpp</p> <pre><code>#pragma once #include&lt;iostream&gt; #include&quot;Bank.h&quot; #include&quot;Customer.h&quot; #include&quot;Manager.h&quot; #include&quot;Accounts.h&quot; #include&lt;vector&gt; #include&lt;string&gt; using namespace std; int main() { Manager m1; //For Polymorphism and using virtual functions pointers or refrences one is necessary to use otherwise //we cannot use virtual functions and polymorphism //I am declaring current account pointer //Declaring Saving Account //Declaring Saving Account Bank b1; bool check = true; while (check == true) { /// &lt;summary&gt; /// char options; cout &lt;&lt; &quot;\n\nEnter what you want to do \n1 for entering the managers data,\n2 for showing the managers data &quot; &lt;&lt; &quot;\n3 for adding a customer in the bank\n4 for adding an Account in the bank \n5 for deleting the customer\n&quot; &lt;&lt; &quot;\n6 for deleting the Account\n7 for getting customer name\n8 for getting the No. of Accounts&quot; &lt;&lt; &quot;\n9 for seeing all the balance in the bank\nPress 'e' for exit&quot;; cin &gt;&gt; options; switch (options) { case '1': { string name; string branch; int id; //The manager class data cout &lt;&lt; &quot;\nEnter the Data of managers Class: \n&quot;; cout &lt;&lt; &quot;\nEnter the name of manager: \t&quot;; cin &gt;&gt; name; cout &lt;&lt; &quot;\nEnter the branch of manager: \t&quot;; cin &gt;&gt; branch; cout &lt;&lt; &quot;\nEnter the Id of manager: \t&quot;; cin &gt;&gt; id; m1.TakeManagersData(name, branch, id); break; } case '2': { cout &lt;&lt; &quot;\nThe data of Manager is : &quot;; m1.Print_ManagerDetails(); break; } case '3': { string Cname; int CID; cout &lt;&lt; &quot;\nEnter the name of customer: &quot;; cin &gt;&gt; Cname; cout &lt;&lt; &quot;\nEnter the Customer ID: &quot;; cin &gt;&gt; CID; b1.AddCustomer(Cname, CID); break; } case '4': { char optionB; cout &lt;&lt; &quot;There are two options available for creating account.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; int AID; int CID; int AB; string AT; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nEnter the Account ID: &quot;; cin &gt;&gt; AID; cout &lt;&lt; &quot;\nEnter the Customer ID: &quot;; cin &gt;&gt; CID; cout &lt;&lt; &quot;\nEnter the Account BALANCE: &quot;; cin &gt;&gt; AB; cout &lt;&lt; &quot;\nEnter the Account Type: &quot;; cin &gt;&gt; AT; b1.Add_Saving_Account(AID, AT, CID, AB); cout &lt;&lt; &quot;\nSuccessfully created a Saving account\tBut delete it as soon as possible\n&quot;; break; } case'2': { cout &lt;&lt; &quot;\nEnter the Account ID: &quot;; cin &gt;&gt; AID; cout &lt;&lt; &quot;\nEnter the Customer ID: &quot;; cin &gt;&gt; CID; cout &lt;&lt; &quot;\nEnter the Account BALANCE: &quot;; cin &gt;&gt; AB; cout &lt;&lt; &quot;\nEnter the Account Type: &quot;; cin &gt;&gt; AT; b1.Add_Current_Account(AID, AT, CID, AB); cout &lt;&lt; &quot;\nSuccessfully created a Current account\nKeep It as long as you want\n&quot;; break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case '5': { int index; cout &lt;&lt; &quot;\nEnter the customer which you want to delete: &quot;; cin &gt;&gt; index; b1.DeleteCustomer(index); break; } case '6': { char optionB; cout &lt;&lt; &quot;There are two options available for DELETING account.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; int index; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nEnter the account number you want to delete\n&quot;; cin &gt;&gt; index; b1.Delete_Saving_Account(index); cout &lt;&lt; &quot;\nSuccessfully deleted Saving account at the given address\n&quot;; break; } case'2': { cout &lt;&lt; &quot;\nEnter the account number you want to delete\n&quot;; cin &gt;&gt; index; b1.Delete_Current_Account(index); cout &lt;&lt; &quot;\nSuccessfully deleted a Current account at current index\n&quot;; break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case '7': { int cn; cout &lt;&lt; &quot;\nEnter the customer ID which you want to get name: &quot;; cin &gt;&gt; cn; b1.GetCustomer_Name(cn); break; } case '8': { char optionB; cout &lt;&lt; &quot;There are two options available for getting number of account.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nThe number of accounts of Saving account type are: \t&quot; &lt;&lt; b1.Get_Saving_NoOfAccounts() &lt;&lt; endl; break; } case'2': { cout &lt;&lt; &quot;\nThe number of accounts of Current account type are: \t&quot; &lt;&lt; b1.Get_Current_NoOfAccounts() &lt;&lt; endl; break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case '9': { char optionB; cout &lt;&lt; &quot;There are two options available for getting the balance in the bank.\nOne is saving account(INTEREST)\t&quot; &lt;&lt; &quot;Press '1' for it and \nSecond one is Current Account(NO INTEREST)\tPress '2' for it\n&quot;; cin &gt;&gt; optionB; switch (optionB) { case '1': { cout &lt;&lt; &quot;\nThe Balance of Saving account type is: \t&quot; &lt;&lt; endl; b1.getAll_saving_Balance(); break; } case'2': { cout &lt;&lt; &quot;\nThe Balance of Current account type is: \t&quot; &lt;&lt; endl; b1.getAll_current_Balance(); break; } default: cout &lt;&lt; &quot;\nSorry Try Again!\nEnter right value only one or two\n&quot;; break; } break; } case 'e': { cout &lt;&lt; &quot;The program is ending now: &quot;; break; } default: { cout &lt;&lt; &quot;\n\nEnter right value please: \n&quot;; } } /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; char option; cout &lt;&lt; &quot;Enter y for opening menu again and n for exiting\t&quot;; cin &gt;&gt; option; while (option != 'y' &amp;&amp; option != 'n') { cout &lt;&lt; &quot;Enter right value Please! only y or n: &quot;; char option1; cin &gt;&gt; option1; if (option1 == 'y' || option1 == 'n') { break; } } if (option == 'y') { check = true; } else if (option == 'n') { check = false; cout &lt;&lt; &quot;The program is ending now! &quot;; } } } </code></pre> <p>The link to view code on github is <a href="https://github.com/Muhammad-Bilal-7896/Program-Bank-With-Inheritance-and-Polymorphism" rel="nofollow noreferrer">https://github.com/Muhammad-Bilal-7896/Program-Bank-With-Inheritance-and-Polymorphism</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:25:30.853", "Id": "485037", "Score": "0", "body": "Technically it's obvious you are using polymorphsm (your `Accounts` class is abstract and has pure virtual functions). Can you elaborate about your doubs please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:27:38.110", "Id": "485038", "Score": "0", "body": "@πάντα Yes my doubts are that if I will remove virtual keyword from base classes than the same program works .i.e making function normal from pure virtual does not changes anything then where goes the polymorphism" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:31:37.417", "Id": "485039", "Score": "0", "body": "Well, then you never call these functions through a reference or pointer to the `Accounts` class, otherwise it wouldn't work. Given that, you don't use polymorphism at all (neither static, nor dynamic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:34:15.563", "Id": "485040", "Score": "0", "body": "@ πάντα ῥεῖ then clearing my doubt I think that for using polymorphism it is necessary to use refrence or pointer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:37:16.030", "Id": "485041", "Score": "1", "body": "_\"I think that for using polymorphism it is necessary to use refrence or pointer \"_ To the base class, yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:39:30.617", "Id": "485042", "Score": "1", "body": "@ πάντα ῥεῖ thank you I just wanted to learn about that your conversation was quite helpful.Its cleared now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:56:24.890", "Id": "485044", "Score": "3", "body": "See https://codereview.stackexchange.com/questions/56363/casting-base-to-derived-class-according-to-a-type-flag/56380#56380 for how polymorphism works in C++." } ]
[ { "body": "<blockquote>\n<p>But what do you think, did I use polymorphism in <code>Accounts</code>, <code>CurrentAccount</code>, <code>SavingAccount</code> and also between <code>Person</code>, <code>Customer</code>, <code>Manager</code> classes or not?</p>\n</blockquote>\n<p>No, you didn't use polymorphism anywhere in your program. You only work with concrete classes of <code>CurrentAccount</code>, <code>SavingAccount</code>, <code>Customer</code> and <code>Manager</code>.</p>\n<p>Polymorphism means, that you call the concrete classes functions via a reference or pointer to their base class. E.g.:</p>\n<pre><code>class Bank\n{\n Customer customers;\n Accounts* accountsC;\n Accounts* accountsS;\n // ...\n};\n\nBank::Bank()\n{\n accountsC = new CurrentAccount();\n accountsS = new SavingAccount();\n cout &lt;&lt; &quot;\\nThe program is in the bank class\\n&quot;;\n}\n//Current Account\nvoid Bank::Add_Current_Account(int AID, string AT, int CID, int AB)\n{\n accountsC-&gt;Deposit(AID, AT, CID, AB);\n}\n\n// ...\nBank::~Bank()\n{\n delete accountsC;\n delete accountsS;\n cout &lt;&lt; &quot;\\nThe Bank class ended \\n&quot;;\n \n}\n</code></pre>\n<hr />\n<p>Also the whole program structure and class hierarchy seems a bit suspect to me:</p>\n<ul>\n<li>Shouldn't a <code>Bank</code> instance have many <code>CustomerAccount</code>s?</li>\n<li>A <code>Customer</code> instance could have more than one account at the same <code>Bank</code>, no?</li>\n<li>What's the actual role of a <code>Manager</code> instance? Could they do something to manipulate a <code>Customer</code>s accounts?</li>\n<li>I don't fully understand what <code>accountsS</code> (<code>SavingAccount</code>) is for. Are you sure that you need it at all?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T01:25:11.553", "Id": "485095", "Score": "0", "body": "I tried to make polymorphism between them just for learning purpose for clearing the concept there was really no need for that in reality.I did this for my learning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:01:50.727", "Id": "485102", "Score": "0", "body": "A customer can have as many accounts in the bank for this vectors are used because they actually grow as the accounts grow dynamically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T05:25:50.020", "Id": "485116", "Score": "0", "body": "@BilalMohib You should rather have something like `std::vector<Customer>` and `std::vector<Account*>` inside the `Bank` class, than managing vectors of the properties inside of these classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:26:25.947", "Id": "485249", "Score": "0", "body": "yaa good suggestion" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T21:15:33.917", "Id": "247740", "ParentId": "247725", "Score": "3" } } ]
{ "AcceptedAnswerId": "247740", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T18:20:19.377", "Id": "247725", "Score": "3", "Tags": [ "c++", "object-oriented", "classes", "polymorphism" ], "Title": "Banking system using polymorphism" }
247725
<p>I am still learning PowerShell and I would like your opinion on my folder deployment PowerShell function. It basically check if a defined folder exists and creates it if it does not and writes it actions to log and console.</p> <p>&lt;#</p> <p><strong>.SYNOPSIS</strong></p> <p>Creates folder if it does not already exists.</p> <p><strong>.DESCRIPTION</strong></p> <p>This function check if defined transfer folder exists and if not it creates it on remote computer.</p> <p><strong>.PARAMETER Path</strong></p> <p>Full path of the folder.</p> <p><strong>.PARAMETER Cancel</strong></p> <p>If Cancel parameter set to true the folder deployment is canceled. This is used in pipeline when it is important to skip this operation if last operation failed.</p> <p><strong>.EXAMPLE</strong></p> <p>Deploy-Folder -Path 'D:\Folder\Folder'</p> <p>#&gt;</p> <pre><code>function Deploy-Folder { param ( [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [String] $Path, [Parameter(Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName)] [boolean] $Cancel = $false ) begin { Import-Module '.\Write-Log.psm1' } process { if(-not $Cancel) { if((Test-Path $Path) -eq $true) { $Message = &quot;Successfully accessed &quot; + $Path + &quot; folder&quot; $OperationResult = 'Success' } else { try { New-Item -Path $Path -ItemType &quot;Directory&quot; } catch { $Message = &quot;Failed to create &quot; + $Path + &quot; folder `n&quot; + $_.Exception $OperationResult = 'Fail' } if((Test-Path $Path) -eq $true) { $Message = &quot;Successfully created &quot; + $Path + &quot; folder&quot; $OperationResult = 'Success' } } } else { $Message = &quot;Canceled &quot; + $Path + &quot; folder deployment&quot; $OperationResult = 'Success' } Write-Log -OperationResult $OperationResult -Message $message if($OperationResult -ne 'Fail') { $Cancel = $false } else { $Cancel = $true } New-Object -TypeName psobject -Property @{ Cancel = $Cancel } } } </code></pre>
[]
[ { "body": "<ol>\n<li>The code is very cleanly written, and its easy to see what is going on.</li>\n<li>The verb you are using for the command is not officially 'supported'. Every command should stick to the official list of verbs, that can be checked with <code>get-verb</code>. would suggest <code>New-Folder</code></li>\n<li>I don't know why you go through this much code to create a folder when you could append a -force to the back end of the <code>new-item</code> command. I guess if you have a system that required you to log every instance where one would create a folder, this would make sense.</li>\n<li>If you have a system where you do commands to an external module, i would suggest you look into the <code>#require</code> tag in powershell, instead of having <code>import-module</code> at the start of your command</li>\n<li>you can easily cast to a psobject just by doing <code>[PSCustomObject]@{cancel=$cancel}</code>.</li>\n<li>use <code>[CmdletBinding()]</code> at the start of your function to get powershell standard switches (-verbose, -debug, -erroraction etc..). just put it between the function definition line and the param definition line (line 2)</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-01T14:39:29.617", "Id": "250080", "ParentId": "247730", "Score": "4" } } ]
{ "AcceptedAnswerId": "250080", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T19:02:07.577", "Id": "247730", "Score": "2", "Tags": [ "powershell" ], "Title": "Deploy folder to desired path - PowerShell function" }
247730
<p>Here is MIPS code to return 1 if a number is even, 0 otherwise:</p> <pre><code>isEven: andi $t0, $a0, 1 li $t1, 1 sub $v0, $t1, $t0 jr $ra </code></pre> <p>My question is whether this can be done in fewer instructions. I could implement <code>isOdd</code> in two instructions (by eliminating the <code>li</code> and <code>sub</code>), but I don't see a single-instruction way to invert just the bottom bit of <code>$t0</code> into <code>$v0</code>.</p>
[]
[ { "body": "<p>As was helpfully pointed out by G. Sliepen in a comment, you can flip the bottom bit using xor.</p>\n<p>That enables the above code to be rewritten in one fewer instruction:</p>\n<pre><code>isEven:\n andi $t0, $a0, 1\n xori $v0, $t0, 1\n jr $ra\n</code></pre>\n<p>This takes advantages of the properties:</p>\n<pre><code>A xor 1 = !A\nA xor 0 = A\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T01:26:03.993", "Id": "500426", "Score": "1", "body": "sub or add 1 also flips the low bit, and can be done before `and`. You can do the same 2-instruction trick even on x86 where one of the only copy-and-operate instructions is LEA. A similar question came up on Stack Overflow not long after this: [Check if a number is even](https://stackoverflow.com/a/64113177)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T01:32:35.000", "Id": "500427", "Score": "1", "body": "MIPS can also implement bitwise NOT with `nor $v0, $zero, $a0`, so `return (~x)&1` also works. Also, don't forget to try asking a compiler for micro-optimization ideas: https://godbolt.org/z/Trd8TG shows that gcc (and clang) know this trick for MIPS, using andi/xori for `return x%2 == 0` for unsigned x." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T20:51:54.673", "Id": "500473", "Score": "0", "body": "@PeterCordes Perhaps both questions were inspired by this tweet: https://twitter.com/ctrlshifti/status/1288745146759000064?lang=en" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T20:41:08.350", "Id": "247826", "ParentId": "247737", "Score": "3" } } ]
{ "AcceptedAnswerId": "247826", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T20:15:43.743", "Id": "247737", "Score": "7", "Tags": [ "performance", "assembly" ], "Title": "Can I shorten this assembly code to test if a number is even?" }
247737
<p>I wrote this login system in the evening and i would like to know what should I fix / change, if should I use classes and, about readability, if this code is OK. I'm a begginer in coding so made this small project only for exercising, but good to know wether if i'm things doing right or wrong.</p> <pre><code>import os.path credentials = [] database_path = &quot;C:\\Users\\filip\\PycharmProjects\\database&quot; database = os.listdir(database_path) def initialize(): choose_option = int(input('0. Exit\n1. Login\n2. Sign up\n\nOption: ')) if choose_option == 1: login_func() elif choose_option == 2: get_username(), get_password(), add_credentials_to_database() elif choose_option == 0: exit('Exiting...') else: print(&quot;You should enter '0', '1', or '2'.&quot;) initialize() def get_username(): username = input('Enter username: ') if f'{username}.txt' not in database: if len(username) &gt;= 8: credentials.append(username) else: print('Username too short (min 8 characters)\n\n') get_username() else: print('Username already exists') get_username() def get_password(): password = input('Enter password: ') if len(password) &gt;= 8: confirm_password = input('Confirm password: ') if password == confirm_password: credentials.append(password) else: print('Password does not match with confirmation\n\n') get_password() else: print('Password too short (min 8 characters)\n\n') get_password() def add_credentials_to_database(): credentials_file = os.path.join(database_path, f'{credentials[0]}.txt') file = open(credentials_file, 'w') file.write(credentials[1]) file.close() print('Account created successfully\n\n') initialize() def login_func(): database = os.listdir(database_path) #Refreshes the database, so if you create an account you can login without having to run the program again enter_login = input('Enter username: ') if f'{enter_login}.txt' in database: for file in database: if f'{enter_login}.txt' == file: enter_password = input('Enter password: ') file = open(f&quot;C:\\Users\\filip\\PycharmProjects\\database\\{file}&quot;, 'r') if enter_password == file.read(): print('WELCOME!') else: print('Invalid password\n\n') login_func() else: print('Invalid username\n\n') login_func() if __name__ == '__main__': initialize() </code></pre> <p>Also, if you remember, please tell me in the comments simple projects that you did when you were learning, so I can do it too. ps: I know this login system is not secure at all but maybe later I could do some encryptation on those credencials...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:13:24.330", "Id": "485085", "Score": "3", "body": "I made a program that could score a Scrabble game, very fun indeed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:20:31.413", "Id": "485087", "Score": "0", "body": "did it have an real interface?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T06:52:19.673", "Id": "485120", "Score": "2", "body": "Did you test this? Does it work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T08:40:14.323", "Id": "485132", "Score": "4", "body": "Minesweeper is a great starter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T10:15:00.337", "Id": "485146", "Score": "0", "body": "yes it works fine @Mast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T10:15:43.060", "Id": "485147", "Score": "0", "body": "Thank you @konjin for your suggestion, maybe i'll try it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T07:44:16.787", "Id": "485233", "Score": "1", "body": "@filip augusto yes it was a CLI interface" } ]
[ { "body": "<p>When entering passwords, you may want to opt for using the <a href=\"https://docs.python.org/3.8/library/getpass.html#getpass.getpass\" rel=\"noreferrer\"><code>getpass</code></a> library. It allows you (if the console supports it) to hide passwords as they're being typed. You'd use <code>getpass.getpass</code> just as you are using <code>input</code> to ask for the password. The only difference is, the password won't show in the console as it's typed.</p>\n<hr />\n<p>You're using recursion in <code>get_password</code> in order to ask the user again. This isn't a good idea. If the user fails too many times, your program can crash. Just use a loop:</p>\n<pre><code>def get_password():\n while True:\n password = input('Enter password: ')\n if len(password) &gt;= 8:\n confirm_password = input('Confirm password: ')\n if password == confirm_password:\n credentials.append(password)\n return\n else:\n print('Password does not match with confirmation\\n\\n')\n else:\n print('Password too short (min 8 characters)\\n\\n')\n</code></pre>\n<p>I'm looping until correct input is entered, then I'm just returning from within the infinite loop.</p>\n<p>And the same goes for the rest of your functions. Recursion is great when used properly, but it carries more problems than most other looping methods. Use it in cases where it's appropriate (like when the problem itself is recursive), not just for general looping.</p>\n<hr />\n<p><code>add_credentials</code> would be safer if it used a <code>with</code> block to close the file for you:</p>\n<pre><code>def add_credentials_to_database():\n credentials_file = os.path.join(database_path, f'{credentials[0]}.txt')\n with open(credentials_file, 'w') as file:\n file.write(credentials[1])\n print('Account created successfully\\n\\n')\n initialize()\n</code></pre>\n<p>Now, even if an error were to happen half-way through the function, there's a greater chance that the file would be closed. Making a practice of using <code>with</code> also prevents you from forgetting to add a call to <code>file.close()</code>.</p>\n<hr />\n<p>At the top you have:</p>\n<pre><code>credentials = []\ndatabase_path = &quot;C:\\\\Users\\\\filip\\\\PycharmProjects\\\\database&quot;\ndatabase = os.listdir(database_path)\n</code></pre>\n<p>A few things to note:</p>\n<ul>\n<li><p><code>credentials</code> shouldn't be a global here. Global mutable states (which <code>credentials</code> is) tend to complicate code and make it harder to understand. In this set up, I would probably make <code>credentials</code> a local variable of <code>initialize</code>, have <code>get_password</code> and the like to <code>return</code> the data instead of adding it to the list directly, and manually pass that data to <code>add_credentials_to_database</code>.</p>\n</li>\n<li><p><code>database_path</code> is a module-level constant, and as such should be in upper-case like <code>DATABASE_PATH</code> according to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>.</p>\n</li>\n<li><p>Arguably <code>database</code> is also (effectively) constant, so it should also be in upper-case.</p>\n</li>\n</ul>\n<hr />\n<p>In <code>initialize</code>, I would get rid of the <code>int</code> conversion of <code>choose_option</code>. All the call to <code>int</code> is doing is allowing for a <code>ValueError</code> to be raised if the user enters in a dumb menu option like <code>&quot;a&quot;</code>. Just use the raw string value and compare against it:</p>\n<pre><code>choose_option = input('0. Exit\\n1. Login\\n2. Sign up\\n\\nOption: ')\nif choose_option == &quot;1&quot;:\n . . .\n</code></pre>\n<p>If you actually needed it as an integer to do math on it or something, it would be different. It's simply an &quot;indicator value&quot; though, so the type of <code>choose_option</code> doesn't really matter, and keeping it as a string has less problems.</p>\n<hr />\n<hr />\n<p>And my favorite projects that I still do whenever I learn a new language are:</p>\n<ul>\n<li>A naïve, bruteforce prime number finder (and then maybe a sieve). Fairly basic.</li>\n<li>Conway's Game of Life. Harder, and has the potential to turn into a large project.</li>\n<li>A Mandelbrot Set image generator. Even harder, and usually becomes a larger project.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T02:04:40.337", "Id": "485096", "Score": "1", "body": "Thank you so much this was very usefull, tomorrow i'll applicate the changes you suggested!! Then I will post it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T02:20:59.367", "Id": "485097", "Score": "4", "body": "@filipaugusto No problem. And just note, code in questions can't be altered once posted. If you'd like a review of the new code, it needs to be as a separate question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T10:14:08.930", "Id": "485145", "Score": "0", "body": "Ok, but could you do a really quick look at it? would be nice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T13:39:21.827", "Id": "485162", "Score": "0", "body": "@filipaugusto If you post it as a separate question, I should have time to review it later." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:44:28.140", "Id": "247746", "ParentId": "247743", "Score": "17" } }, { "body": "<p>As you mentioned, as-is the system is not at all secure. However, it is easy to hash passwords properly, and this is a great opportunity to learn the concept.</p>\n<p>The idea of password hashing is to add a random salt, which makes it harder to use precomputed tables for breaking the password, and a one-way function which can only be &quot;encrypted&quot;, but not &quot;decrypted&quot;. The output of the one-way function is stored. When the user inputs a new password, the one-way function is applied again and the output is compared to the stored value. There is no way to decrypt the password without first knowing it.</p>\n<p>One of the best current password hashing schemes is <strong>bcrypt</strong>. For Python, this is provided by the <code>bcrypt</code> module, which has to be installed. On Linux distributions, it is usually available in package <code>python3-bcrypt</code>. On Windows and Mac, you can install it with <code>pip install bcrypt</code>.</p>\n<p>There is a <a href=\"http://zetcode.com/python/bcrypt/\" rel=\"noreferrer\">good tutorial on bcrypt usage here</a>. When applied to your code, you'd generate the salt and compute hash when user first provides the password:</p>\n<pre><code> credentials.append(password)\n</code></pre>\n<p>becomes:</p>\n<pre><code> password_utf8 = password.encode('utf-8') # Convert to UTF-8 for hashing\n salt = bcrypt.gensalt() # Generate random salt\n hash = bcrypt.hashpw(password_utf8, salt) # Apply one-way function\n credentials.append(hash) # Store the hash\n</code></pre>\n<p>And when verifying, use <code>bcrypt.checkpw()</code>:</p>\n<pre><code>if enter_password == file.read():\n</code></pre>\n<p>becomes:</p>\n<pre><code>if bcrypt.checkpw(enter_password, file.read()):\n</code></pre>\n<p>If you then look into the file, you'll see a string like <code>$2b$12$viuQE9cX.ZCoqZewzRqJz.Ae76yYRH.4fkOKe9CJPl3ssm6n50AiC</code>, which is the hashed password.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:51:08.753", "Id": "485368", "Score": "0", "body": "That just added a whole new level of security, didn't know that was that easy. Also, about storing credentials, do you know a more efficient and safe way of doing it? Because seems that creating a .txt file than writing the password on it is not good. When I was first writing the project, I just improvised a way to store, and that was what came to my mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:37:15.563", "Id": "485383", "Score": "0", "body": "@filipaugusto For scalability of storing more information (multiple users, usernames, access rights etc.), one can consider a range of formats from JSON to a sqlite database. But the security aspect will remain the same - whoever can read the file, can read the stored data, and there is no simple way to avoid that. In real systems the solution is to restrict access to the file with file permissions and system-level user accounts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T10:37:36.623", "Id": "485480", "Score": "0", "body": "Ok I got it, so i'll keep it the same" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T12:42:14.623", "Id": "247775", "ParentId": "247743", "Score": "11" } }, { "body": "<p>You loop over the database when it isn't necessary:</p>\n<pre><code> if f'{enter_login}.txt' in database:\n for file in database:\n if f'{enter_login}.txt' == file:\n enter_password = input('Enter password: ')\n file = open(f&quot;C:\\\\Users\\\\filip\\\\PycharmProjects\\\\database\\\\{file}&quot;, 'r')\n if enter_password == file.read():\n print('WELCOME!')\n else:\n print('Invalid password\\n\\n')\n login_func()\n else:\n print('Invalid username\\n\\n')\n login_func()\n</code></pre>\n<p>can become:</p>\n<pre><code> if f'{enter_login}.txt' in database:\n enter_password = input('Enter password: ')\n file = open(f&quot;C:\\\\Users\\\\filip\\\\PycharmProjects\\\\database\\\\{enter_login}.txt&quot;, 'r')\n if enter_password == file.read():\n print('WELCOME!')\n else:\n print('Invalid password\\n\\n')\n login_func()\n else:\n print('Invalid username\\n\\n')\n login_func()\n</code></pre>\n<p>The way you had it would probably only get slow if you have hundreds or thousands of users, but it's good to be aware of when you're doing unnecessary work.</p>\n<p>I also recommend using <code>pathlib</code> instead of manually manipulating strings that represent file paths.</p>\n<p>Here's what that would look like: (incorporating Carcigenicate's answer)</p>\n<pre><code>from pathlib import Path\nfrom getpass import getpass \n\ncredentials = []\nDATABASE_PATH = Path(&quot;C:\\\\Users\\\\filip\\\\PycharmProjects\\\\database&quot;)\n\ndef get_user_file(username):\n return DATABASE_PATH / f'{username}.txt'\n\n\ndef initialize():\n while True:\n choose_option = input('0. Exit\\n1. Login\\n2. Sign up\\n\\nOption: ')\n if choose_option == '1':\n login_func()\n return\n elif choose_option == '2':\n username = get_username()\n password = get_password()\n\n add_credentials_to_database(username, password)\n elif choose_option == '0':\n exit('Exiting...')\n return\n else:\n print(&quot;You should enter '0', '1', or '2'.&quot;)\n \n\ndef get_username():\n while True:\n username = input('Enter username: ')\n if get_user_file(username).exists():\n print('Username already exists')\n elif len(username) &gt;= 8:\n return username\n else:\n print('Username too short (min 8 characters)\\n\\n')\n\n\ndef get_password():\n while True:\n password = getpass('Enter password: ')\n if len(password) &gt;= 8:\n confirm_password = getpass('Confirm password: ')\n if password == confirm_password:\n return password\n else:\n print('Password does not match with confirmation\\n\\n')\n else:\n print('Password too short (min 8 characters)\\n\\n')\n \n\ndef add_credentials_to_database(username, password):\n get_user_file(username).write_text(password)\n print('Account created successfully\\n\\n')\n\n\ndef login_func():\n while True:\n login = get_user_file(input('Enter username: '))\n if login.exists():\n enter_password = getpass('Enter password: ')\n if enter_password == login.read_text():\n print('WELCOME!')\n return\n else:\n print('Invalid password\\n\\n')\n else:\n print('Invalid username\\n\\n')\n\n\nif __name__ == '__main__':\n initialize()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:51:52.980", "Id": "485369", "Score": "0", "body": "That was a cleaver answer, thank you Jasmijn, made it much shorter!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:57:43.453", "Id": "485370", "Score": "0", "body": "As you mentioned path, if I were to make this .py into a .exe, how would I store their credentials if I don't know their path, like, In the code above the program goes through `\\Users\\filip`, what if I don't know their user?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:11:08.817", "Id": "485380", "Score": "1", "body": "I'd use the appdirs library for that (https://pypi.org/project/appdirs/)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:32:58.373", "Id": "247810", "ParentId": "247743", "Score": "3" } } ]
{ "AcceptedAnswerId": "247746", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:05:05.677", "Id": "247743", "Score": "14", "Tags": [ "python", "python-3.x" ], "Title": "Implementations and analysis of my python login system (~80 lines)" }
247743
<p>Mind that this is my first actual program in C++ and I tried to prepare for any possible input. Also the reason I included <code>static_cast&lt;void&gt;(generator(range))</code> is to throw away the first random value because I read on <a href="https://learncpp.com" rel="nofollow noreferrer">LearnCpp.com</a> that throwing away the first is a common practice to produce more random results. Anyways here is the code, all suggestions are welcome.</p> <pre><code>#include &lt;iostream&gt; #include &lt;limits&gt; #include &lt;random&gt; bool validateInput(int input) { using namespace std; if (1 &lt;= input &amp;&amp; input &lt;= 100) return true; else if (!input) return false; else return false; } int generateRandomNumber() { std::random_device dev; std::mt19937_64 range(dev()); std::uniform_int_distribution&lt;std::mt19937_64::result_type&gt; generator(1, 100); static_cast&lt;void&gt;(generator(range)); return static_cast&lt;int&gt;(generator(range)); } bool placement(int input, int target) { using namespace std; if (input &gt; target) { cout &lt;&lt; &quot;Guess is too high.&quot;; return false; } else if (input &lt; target) { cout &lt;&lt; &quot;Guess is too low.&quot;; return false; } else { cout &lt;&lt; &quot;Guess is correct!&quot;; return true; } } int main() { using namespace std; cout &lt;&lt; &quot;You have 7 guesses to guess what number I am thinking of between 1 and 100.\n&quot;; int winning_num{ generateRandomNumber() }; static int tries{ 1 }; do { int num; cout &lt;&lt; &quot;\nGuess#&quot; &lt;&lt; tries &lt;&lt; &quot;: Enter a number -&gt; &quot;; cin &gt;&gt; num; if (!cin) { cin.clear(); cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'); continue; } cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n'); if (validateInput(num)) ; else { continue; } if (!placement(num, winning_num)) { cout &lt;&lt; &quot;\nIncorrect!\n&quot;; ++tries; } else { cout &lt;&lt; &quot;\nCorrect!\n&quot;; exit(0); } } while (tries &lt;= 7); cout &lt;&lt; &quot;\nYou did not guess the number in the alloted amount of guesses :(\nTry Again!\n&quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:48:29.403", "Id": "485090", "Score": "0", "body": "`else if (!input) return false; else return false;` It should be `return false;` after the if and that's all, both else return the same value and the if returns a value so you can omit the else and go `return` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:49:54.550", "Id": "485091", "Score": "1", "body": "Also, in the first function it is unnecessary to place `using namespace std` since you aren't calling anything within `std`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:51:45.947", "Id": "485092", "Score": "1", "body": "`if (validateInput(num)); else { continue; }` is equivalent to write `if (!validateInput(num)) continue;` because `!` is the not operator. It inverts `true` to `false` and `false` to `true`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T07:46:41.243", "Id": "485234", "Score": "0", "body": "@Miguel Avila Yeah that is a good point, I should’ve thought of that. Thanks for pointing it out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T07:47:39.423", "Id": "485235", "Score": "0", "body": "@anki If you read the description up above, it is a common practice to throw away the first value of a random number generator, which that line of code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T07:50:41.753", "Id": "485237", "Score": "0", "body": "@Miguel Avila For your first comment you’re absolutely correct, I ran into some problems with my code and i added that ‘else if’ statement to try something else and I forgot to remove it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T08:39:09.347", "Id": "485243", "Score": "1", "body": "Please do not update the code in your question after receiving 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-08-13T02:25:27.627", "Id": "485324", "Score": "0", "body": "@Mast Alright sorry I did not know, I just forgot to remove a useless line before uploading it." } ]
[ { "body": "<p>Well Your code is working fine but there were some extra code which I have removed and now its like this working same as before.<br>\nYou can have more simple code if you use using namespace std; at the top of you document.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;limits&gt;\n#include &lt;random&gt;\nusing namespace std;\nbool validateInput(int input)\n{\n\n if (1 &lt;= input &amp;&amp; input &lt;= 100)\n return true;\n else\n return false;\n}\n\nint generateRandomNumber()\n{\n random_device dev;\n mt19937_64 range(dev());\n uniform_int_distribution&lt;std::mt19937_64::result_type&gt; generator(1, 100);\n static_cast&lt;void&gt;(generator(range));\n return static_cast&lt;int&gt;(generator(range));\n}\n\nbool placement(int input, int target)\n{\n if (input &gt; target)\n {\n cout &lt;&lt; &quot;Guess is too high.&quot;;\n return false;\n }\n\n else if (input &lt; target)\n {\n cout &lt;&lt; &quot;Guess is too low.&quot;;\n return false;\n }\n else\n {\n cout &lt;&lt; &quot;Guess is correct!&quot;;\n return true;\n }\n}\n\nint main()\n{\n bool end;\n cout &lt;&lt; &quot;You have 7 guesses to guess what number I am thinking of between 1 and 100.\\n&quot;;\n int winning_num{ generateRandomNumber() };\n static int tries{ 1 };\n do\n {\n end=true;\n int num;\n cout &lt;&lt; &quot;\\nGuess#&quot; &lt;&lt; tries &lt;&lt; &quot;: Enter a number -&gt; &quot;;\n cin &gt;&gt; num;\n \n if (validateInput(num))\n ;\n else\n {\n continue;\n }\n if (!placement(num, winning_num))\n {\n cout &lt;&lt; &quot;\\nIncorrect!\\n&quot;;\n ++tries;\n }\n else\n {\n cout &lt;&lt; &quot;\\nCorrect!\\n&quot;;\n exit(0);\n }\n if(tries&gt;7)\n {\n cout&lt;&lt;&quot;\\nDo you want to guess more\\nnPress y for it and \\nPress n for closing\\n&quot;;\n char guess;\n cin&gt;&gt;guess;\n switch(guess)\n {\n case 'y':\n {\n cout&lt;&lt;&quot;\\nOk Lets go\\n&quot;;\n break;\n }\n case 'n':\n {\n cout&lt;&lt;&quot;\\nEnding the program\\n&quot;;\n exit(0);\n }\n default:\n {\n cout&lt;&lt;&quot;\\nEnter right choice\\n&quot;;\n }\n \n }\n }\n\n }while (end==true);\n cout &lt;&lt; &quot;\\nYou did not guess the number in the alloted amount of guesses :(\\nTry Again!\\n&quot;;\n\n}\n</code></pre>\n<p>You can also ask from user when he want to do more guesses or want to end the program making the program user friendly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T12:10:14.300", "Id": "485154", "Score": "3", "body": "Please provide a review of the code, not only changes. [answer]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T02:33:14.953", "Id": "247750", "ParentId": "247744", "Score": "1" } }, { "body": "<p>I like that your code (read functions) follows <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>.</p>\n<p>And also that you've put the number comparison code in a separate function unlike</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/q/247749/205955\">User guesses the number generated by computer</a></li>\n<li><a href=\"https://codereview.stackexchange.com/q/247383/205955\">Computer tries to guess your inputted number</a></li>\n</ul>\n<p>And also that you use <code>static_cast</code>. All are good coding practices!</p>\n<hr>\n<p>I'd prefer if you do the text printing in the <code>placement</code> function itself and call it something like <code>compare_with_guess</code>. That way, you don't have to return values and use another if-else block in the caller. Also, the output messages can also be controlled all at one place.</p>\n<p>Another way is to use struct like:</p>\n<pre><code>struct InputNum{\nprivate:\n const int input;\npublic:\n InputNum(const int num):input(num){};\n\n int get() const{\n return input;\n }\n bool greater_than(const int target) const {\n return input &gt; target;\n }\n bool less_than(const int target) const {\n return input &lt; target;\n }\n bool equals(const int target) const {\n return input == target;\n }\n}\n</code></pre>\n<hr>\n<p>Use <code>const</code> whenever possible.</p>\n<pre><code>const int winning_num{ generateRandomNumber() };// +1 for {} initialiser syntax. \n</code></pre>\n<pre><code>void compare_with_guess(const int input, const int guess){ // After making the changes I suggested above.\n</code></pre>\n<pre><code>bool validateInput(const int input){\n\n</code></pre>\n<hr>\n<p>Avoid <code>using namespace std;</code> completely, let alone using it multiple times in the code.</p>\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a></p>\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T08:00:37.730", "Id": "485239", "Score": "0", "body": "Thank you for your feedback this helps me very much. The only parts of your answer I do not understand is the line right after public in the struct, and the const outside the function curly brackets. If you could explain those it would be much appreciate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T08:08:44.613", "Id": "485241", "Score": "1", "body": "@unkn0wn.dev When you pass an `const` or a `const &` etc to a function, you can only call its member functions that are marked `const`. It indicates that calling those functions will not modify the data in the struct. https://ideone.com/qjMS6K this won't compile since `equals` is not a `const` function (sorry I need to lookup the correct term for that) while the `num` is `const&.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T08:10:42.443", "Id": "485242", "Score": "1", "body": "It is the constructor https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors It takes `num` which is `const` since we only read it and then initialises `input` equals to `num`. in the `{}`, you can add a `std::cout` to print both of them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T02:27:54.043", "Id": "485325", "Score": "0", "body": "Thank you, I understand it better now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T02:30:47.260", "Id": "485326", "Score": "0", "body": "Could you also explain the advantages of using a struct instead of a class for this instance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:50:09.423", "Id": "485390", "Score": "0", "body": "@unkn0wn.dev https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c2-use-class-if-the-class-has-an-invariant-use-struct-if-the-data-members-can-vary-independently https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-class Yeah you're right. Class should be used here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T17:27:10.010", "Id": "485526", "Score": "0", "body": "Alright thank you for clearing that up." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T12:01:10.957", "Id": "247772", "ParentId": "247744", "Score": "2" } } ]
{ "AcceptedAnswerId": "247772", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T00:07:23.067", "Id": "247744", "Score": "5", "Tags": [ "c++", "c++17", "number-guessing-game" ], "Title": "Guess the Number In C++" }
247744
<p>I solved this exercise on jshero.com but I know the solution can be written more cleanly, I just don't know how.</p> <p>Here are the directions:</p> <p>Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.</p> <p>This challenge also supposes that you use if...else if...else to solve the exercise. The course also hasn't touched on functions within functions, so I'm mainly concerned with simplification and readability, but also curious about ternaries. Here is my attempt which works,</p> <pre><code>function addWithSurcharge(num1, num2) { let surcharge = 0; if (num1 &lt;= 10) { surcharge += 1; } else if (num1 &gt; 10 &amp;&amp; num1 &lt;= 20) { surcharge += 2; } else { surcharge += 3; } if (num2 &lt;= 10) { surcharge += 1; } else if (num2 &gt; 10 &amp;&amp; num2 &lt;= 20) { surcharge += 2; } else { surcharge += 3; } return surcharge + num1 + num2; } </code></pre> <p>Thank you, much appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:25:12.627", "Id": "485105", "Score": "0", "body": "Welcome to CodeReview. The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<p>First, why not write a function to compute surcharges? They're the same for both numbers, right? So you would be adding</p>\n<pre><code>num1 + surcharge(num1) + num2 + surcharge(num2)\n</code></pre>\n<p>which I think takes care of a lot of the DRY you're looking for.</p>\n<p>As for ternary operators, you can use them in a tabular form depending on operator precedence. Something like this:</p>\n<pre><code>return num &lt;= 10 ? 1 :\n num &lt;= 20 ? 2 : \n 3;\n</code></pre>\n<p>It's really one long line, but you're relying on operator precedence to group the second and later ternary expressions together in the else-clause of the first expression.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T03:11:06.447", "Id": "247751", "ParentId": "247748", "Score": "1" } }, { "body": "<p>From a short review;</p>\n<ul>\n<li>You are dealing with amounts, but you call your variable <code>num1</code> and <code>num2</code></li>\n<li>Your code now has tons of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>, you should use named constants</li>\n<li>I understand you are not yet in to 'functions within functions', but that is how you apply DRY in this case</li>\n</ul>\n<p>So the DRY version could look like this;</p>\n<pre><code>function addSurcharge(amount){\n const FLOOR = 10;\n const CEILING = 20;\n\n if (amount &lt;= FLOOR) {\n return amount + 1;\n } else if (amount&lt;= CEILING) {\n return amount + 2;\n } else {\n return amount + 3;\n } \n}\n\nfunction addWithSurcharge(amount1, amount2) {\n return addSurcharge(amount1) + addSurcharge(amount2);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T08:06:02.663", "Id": "247762", "ParentId": "247748", "Score": "3" } }, { "body": "<p>Hi if you can use <code>reduce()</code> and ternary operators your code will be much shorter and cleaner. First sums all args and then sums Surcharge.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const addWithSurcharge = (...args) =&gt; {\n const sumArgs = args.reduce((a, b) =&gt; a + b);\n return args.reduce((acc, cur) =&gt; \n cur &lt;= 10 ? acc + 1 :\n cur &lt;= 20 ? acc + 2 :\n acc + 3, sumArgs);\n }\nconsole.log(addWithSurcharge(10, 30));\nconsole.log(addWithSurcharge(10, 40, 30, 15, 20));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T12:14:18.493", "Id": "247773", "ParentId": "247748", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T01:40:26.930", "Id": "247748", "Score": "3", "Tags": [ "javascript" ], "Title": "Simple surcharge algorithm could use DRY" }
247748
<p><strong>This is my code, which chooses a random number from 0 to 10 for the user to guess.</strong></p> <pre><code>//guess the number game //my code #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; using namespace std; int main() { unsigned int secretNumber; int guess; int maxNumber = 10; int maxTries = 4; int numTries = 1; srand(static_cast&lt;unsigned int&gt;(time(0))); secretNumber = (rand() % 10)+ 1; cout &lt;&lt; &quot;GUESS A NUMBER FROM 0 TO 10!!\n&quot;; do { cout &lt;&lt; &quot;\nGuess: \n&quot;; cin &gt;&gt; guess; if (guess &lt; secretNumber) { cout &lt;&lt; &quot;too low:(:(!! &quot;; numTries++; cout &lt;&lt; &quot;Guesses Left: &quot; &lt;&lt; maxTries - numTries; } ***//Would it be better to add a bool in the condition?*** else if (guess &gt; secretNumber &amp;&amp; guess &lt;= maxNumber) { cout &lt;&lt; &quot;Too high:D:D!! &quot;; numTries++; cout &lt;&lt; &quot;Guesses Left: &quot; &lt;&lt; maxTries - numTries; } else if (guess &gt; maxNumber) { cout &lt;&lt; &quot;Do you know how to count to 10?\n&quot;; cout &lt;&lt; &quot;Only from 0 TO 10!! &quot;; numTries++; cout &lt;&lt; &quot;Guesses Left: &quot; &lt;&lt; maxTries - numTries; } else { cout &lt;&lt; &quot;WOW! you GUESSED IT?! AMAZING!!!!&quot;; cout &lt;&lt; &quot;You're right! the number is &quot; &lt;&lt; guess; cout &lt;&lt; &quot;\nYou got it right in &quot; &lt;&lt; numTries &lt;&lt; &quot; guesses!!!&quot;; } if (numTries == maxTries) { cout &lt;&lt; &quot;\n\nYou LOOSE :( LOL!&quot;; } } while (guess != secretNumber &amp;&amp; maxTries != numTries); return 0; } </code></pre> <p><strong>This is the teacher's code, which is simpler and includes a bool variable. Should my previous code be simpler, just as this one?</strong></p> <pre><code>int main() { int secretNumber = 7; int guess; int numTries = 0; int maxTries = 3; bool outOfGuesses = false; while (secretNumber != guess &amp;&amp; !outOfGuesses) { if (numTries != maxTries) {cout &lt;&lt; &quot;Guess a Number: &quot;; cin &gt;&gt; guess; numTries++;} else { outOfGuesses = true; } } if (outOfGuesses) { cout &lt;&lt; &quot;You loose!&quot;; } else { cout &lt;&lt; &quot;You win!&quot;; } return 0; } </code></pre> <p><em>Is my code as efficient and simple as the teacher's code? //Is there a simpler way to do what I intended to do in my code?</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T03:34:40.783", "Id": "485100", "Score": "8", "body": "The teacher's code doesn't do as much as yours does, and it also has Undefined Behavior (using \"guess\" before it is initialized). So there's not really much basis to compare them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:23:24.867", "Id": "485103", "Score": "2", "body": "Welcome to Code Review. The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:24:14.977", "Id": "485104", "Score": "2", "body": "Also, keep in mind that every content you post is licensed under CC-BY-SA. Your teacher's code is most-likely not available under that license." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T12:04:09.857", "Id": "485152", "Score": "0", "body": "@Zeta I don't understand what that means, it's illegal to post it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T13:56:01.320", "Id": "485164", "Score": "4", "body": "A small bug in your code about the secret number: `rand()%10` returns a number between 0 and 9 (inclusive). Then `(rand()%10)+1` would then return a number between 1 and 10 (inclusive). If you want to a random number between 0 and 10, you need to `rand()%11`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:33:30.373", "Id": "485180", "Score": "4", "body": "@NellaCrystal What Zeta is saying is that you should not post code that you have not personally written. So it is probably best not to post your teachers code. Though your teacher should probably ask for his own code review :-)" } ]
[ { "body": "<h1>Preface</h1>\n<p>I'm going to ignore your teacher's code, at least for the moment, and just review yours.</p>\n<p>Based on what you've said, I'm guessing you're still pretty close to the beginning of the learning curve. Based on that, I'm going to go into a little more detail that normal about <em>how</em> to move in a direction I think you'll find beneficial, rather than just talking about where you might like to end up.</p>\n<h1>Approach</h1>\n<p>First of all, you currently have all your code in <code>main</code>. It can be extremely helpful to define small, self-contained functions to carry out the overall task, instead of having it all inline in a single function like this.</p>\n<p>To do this, I'd start with a really basic outline of what the program is supposed to do:</p>\n<ol>\n<li>generate a random number</li>\n<li>While they haven't used up their guesses or gotten the right answer:\n<ul>\n<li>get a guess at the random number from the user</li>\n<li>check whether their guess is high, low, or correct\n<ul>\n<li>print out the result</li>\n</ul>\n</li>\n</ul>\n</li>\n</ol>\n<p>Then I'd consider which of those is easily turned into a separate, self-contained piece of code (hint: most of them).</p>\n<p>Then I'd write code in main that worked at pretty much that level, and have it delegate the details to other code. A first stab at it might look something like this:</p>\n<pre><code>int main() { \n int secretNumber = generate_random();\n int maxTries = 3;\n\n for (int guessCount = 0; guessCount &lt; maxTries; guessCount++) {\n int guess = get_guess();\n if (check_guess(guess, secretNumber))\n break;\n }\n}\n</code></pre>\n<p>Initially, I wouldn't worry a lot about getting every detail precisely correct. Just try to get something that fits reasonably well with the outline you write in English.</p>\n<p>From there, you have a couple of choices. One is to start by writing &quot;mock&quot; versions of most of those. They need to do roughly the right <em>sort</em> of thing, but don't put any effort into really making them do the job correctly. For example, we can write a &quot;mock&quot; &quot;generate a random number&quot; as something like:</p>\n<pre><code>int generate_random() { \n return 7;\n}\n</code></pre>\n<p>That obviously won't do in the long term, but it's enough that we can use it to write and test the rest of the code. Then do roughly the same with the other functions:</p>\n<pre><code>bool check_guess(int guess, int secretNumber) {\n // Todo: add code to print out current result\n return guess == secretNumber;\n}\n\nint get_guess() { \n static int guess;\n\n return guess++;\n}\n</code></pre>\n<p>Now we have enough that we can test the basic flow of the program. For example, we can check that when we run it, it doesn't get stuck in a loop; it runs to termination. Once we've established that, we can add enough more to print out each guess, and whether it was right or wrong, and see that as-is, it guesses values for 0 through 10, then quits because it used up the allotted number of guesses. If so, great. If not, we figure out why not and fix that.</p>\n<p>Then we change the random number to (say) 5, so it should guess correctly before it runs out of guesses. Then we run that to be sure it does what it should (like, print out the message that you got the right answer, and then quit asking for more guesses once <code>5</code> is guessed).</p>\n<p>Once we're done verifying that the basic flow of the code in <code>main</code> works correctly, we can expand out those subordinate functions to do their jobs correctly, so <code>generate_random()</code> actually generates a random number, <code>get_guess()</code> really asks the user for input, and do on.</p>\n<p>The important point here so to break the large, somewhat complex task down into a number of smaller tasks, each of which is quite simple. This way, it's much easier to define and understand what each piece needs to do, and test the code so we can be sure that it does what it's really supposed to.</p>\n<h1>Other Points</h1>\n<p>I think it's worth pointing out that I'm positively impressed with a number of things about your code. You've chosen good, clear variable names, and structured the code so it's really quite clean and understandable. It's longer than your teacher's, but length is rarely a good measure of much of anything, and its length doesn't seem (to me) particularly excessive for what it does. A fair amount of the extra length is simply because your teacher's code is closer to what I've recommended as the first step on the way toward better code--for example, it chooses the same &quot;random&quot; number every time it's run. That's simple and easy to test with, but yours is clearly a more complete program in this regard.</p>\n<p>As far as the specific question of whether to use a Boolean variable: it doesn't strike me as necessary in this case, but it's also fairly harmless. I can see writing the code either with or without it, and doubt that either is necessarily much better than the other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T14:37:01.397", "Id": "485168", "Score": "2", "body": "https://xkcd.com/221/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:07:03.693", "Id": "485245", "Score": "0", "body": "To me it's a bit confusing to have `guessCount` start at 0. What do you think about `for (int guessCount = 1; guessCount <= maxGuesses; guessCount++) { ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:24:33.860", "Id": "485295", "Score": "1", "body": "@ToivoSäwén Given that as of now the variable is not used in the loop body, the initial value is not actually important, with a 0-start loop being more natural for C code. Ultimately though, it depends on what exactly guessCount means to you. It could be 'number of guesses at the start of loop body' or 'number of guesses reached in this iteration'. In this kind of situation I'd just leave a comment with the intended interpretation so that future me knows what's going on quicker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:37:30.253", "Id": "485297", "Score": "1", "body": "@ToivoSäwén: In programming, it's common enough for a loop of N iterations to go from 0 through N-1 that it's probably best to just get used to that being how things are done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:13:02.820", "Id": "485340", "Score": "0", "body": "@MrRedstoner my gripe with `guessCount` is that somebody might get the idea of `std::cout << \"You have done \" << guessCount << \" guesses.\" << std::endl;` as the variable name is so descriptive, and then you'd have a bug. Then again, I am in the habit of using `i` for loops so maybe I should be banned from cr.se :-) Thanks for the input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:22:10.047", "Id": "485389", "Score": "1", "body": "@ToivoSäwén fair enough, that's exactly why I would have had a comment with the intended interpretation of the name. And I too would have made just an `i` indexed loop for simple code like this." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:27:08.333", "Id": "247759", "ParentId": "247749", "Score": "15" } }, { "body": "<ul>\n<li><p>This is not a good practice! At most, use <code>using std::cout</code> or <code>using std::cin</code> if they look ugly to you.</p>\n<pre><code>using namespace std;\n</code></pre>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a></li>\n</ul>\n</li>\n<li><p>Use const</p>\n<pre><code>unsigned int secretNumber; // Initialise it right away! \nint maxNumber = 10;\nint maxTries = 4;\n</code></pre>\n<p>This avoids unintentional edits of variables.</p>\n<ul>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconst-immutable\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconst-immutable</a></li>\n</ul>\n</li>\n<li><p>Use lambda to store variables that will not be modified after initialisation.</p>\n<pre><code>const unsigned int guess = [](){\n unsigned int n;\n std::cin &gt;&gt; n;\n return n;\n}(); \n</code></pre>\n<p>One can also use a struct with initialiser list constructor to initialise the <code>const</code> members which will be <code>const</code> later on.</p>\n<pre><code>struct InputNum{\nprivate:\n const int input;\npublic:\n InputNum(const int num):input(num){};\n\n int get() const{\n return input;\n }\n bool greater_than(const int target) const {\n return input &gt; target;\n }\n bool less_than(const int target) const {\n return input &lt; target;\n }\n bool equals(const int target) const {\n return input == target;\n }\n\n}\n</code></pre>\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors</a></li>\n</ul>\n</li>\n<li><p>Prefer while instead of do-while unless necessary. The condition of the loop is easy to find at the top, instead of the bottom. Or errors like this happen:</p>\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/63221443/forgot-do-in-do-while-loop\">https://stackoverflow.com/questions/63221443/forgot-do-in-do-while-loop</a></p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-do\" rel=\"nofollow noreferrer\">https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-do</a></p>\n</li>\n</ul>\n</li>\n</ul>\n<hr>\n<p>Read some more comments at the same question at:</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/questions/247383/computer-tries-to-guess-your-inputted-number/247447#247447\">Computer tries to guess your inputted number</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/247744/guess-the-number-in-c/247772#247772\">Guess the Number In C++</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T11:47:22.987", "Id": "247771", "ParentId": "247749", "Score": "5" } }, { "body": "<p>One small thing I haven't noticed the others mention. You check and handle cases</p>\n<pre><code>guess &lt; secret\nsecret &lt; guess &lt;= max\nguess &gt; max\n</code></pre>\n<p>Yet</p>\n<pre><code>min &gt; guess\n</code></pre>\n<p>seems oddly missing. Your guess is an <code>int</code>, so nothing is preventing me from putting in a negative number. And because your else doesn't check its assumption (<code>secret==guess</code>) I will instantly get the message about winning, yet the loop will continue, because it does its check separately.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:12:32.770", "Id": "247797", "ParentId": "247749", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T02:13:05.607", "Id": "247749", "Score": "5", "Tags": [ "c++", "beginner" ], "Title": "User guesses the number generated by computer" }
247749
<p>I reimplemented <code>cat(1)</code> for fun. I followed the <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/cat.html" rel="nofollow noreferrer">Open Group Base Specifications (Issue 7, 2018 edition)</a>, not the GNU variant and its command line arguments.</p> <h1>Buffered and <code>-u</code>nbuffered behaviour</h1> <p>While the specification defines the behaviour for <code>-u</code>, it doesn't define how the arguments should be concatenated when the <code>-u</code>nbuffered argument is missing. To get used to <code>BufRead</code> and <code>BufWriter</code>, I used a buffered approach that simply uses Rust's already existing methods.</p> <p>I'm not entirely happy about the return code issue. I currently use <code>io::Result</code> in <code>main</code> to return the last error if it occurred, however, this also means that the last error will get reported twice. I could use <a href="https://doc.rust-lang.org/std/process/fn.exit.html" rel="nofollow noreferrer"><code>std::process::exit</code></a>, but that would need a wrapper around <code>main</code>.</p> <h1>Argument parsing and additional dependencies</h1> <p>I'll admit, the argument handling part of <code>main</code> won't win a beauty contest. However, I didn't want to add <code>clap</code> or other argument handling libraries and instead focus on using <code>std</code>. The program <em>should</em> follow the <a href="https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02" rel="nofollow noreferrer">Utility Argument Syntax</a>, however, it doesn't follow guidelines 5 (e.g. <code>-uuuu</code> is not the same as <code>-u -u -u -u</code>) and 9 (<code>-u</code> does not need to be the first argument). Argument grouping is a non-goal for this toy program, however.</p> <p>Also, comparing to GNU <code>cat</code>, unknown options are interpreted as files names, whereas GNU <code>cat</code> will exit with an error message. I'm not sure whether that violates the specifications, though.</p> <h1>Implementation</h1> <p>The application is split into two parts, namely <code>main.rs</code> (mostly argument parsing) and <code>lib.rs</code> (the actual implementation). Any comments on the organisation are fine.</p> <pre><code>// main.rs use std::ffi::OsString; use std::path::Path; use cat::{cat_buffered_single, cat_unbuffered_single}; fn main() -&gt; std::io::Result&lt;()&gt; { let mut args: Vec&lt;OsString&gt; = std::env::args_os().skip(1).collect(); // Only parse arguments up to &quot;--&quot; let args_up_to = if let Some(index) = args.iter().position(|arg| arg == &quot;--&quot;) { args.remove(index); index } else { args.len() }; // Keep all arguments after &quot;--&quot; as-is let verbatim_args = args.split_off(args_up_to); // Check for &quot;-u&quot; in valid positions and remove the first one let cat_func = if args.iter().any(|arg| arg == &quot;-u&quot;) { args = args.into_iter().filter(|x| x != &quot;-u&quot;).collect(); cat_unbuffered_single } else { cat_buffered_single }; // Recombine arguments args.extend(verbatim_args); // Fallback to stdin behaviour if args.is_empty() { args.push(&quot;-&quot;.into()); } let mut result = Ok(()); for arg in args { let path = Path::new(&amp;arg); match cat_func(path) { Ok(()) =&gt; continue, Err(e) =&gt; { eprintln!(&quot;cat: {}: {}&quot;, path.to_string_lossy(), e); result = Err(e); } } } result } </code></pre> <pre><code>// lib.rs use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, Write}; use std::path::Path; // Dumps all bytes from `src` into `dest`, using both buffer functionalities. fn dump_buffered_single(src: &amp;mut dyn BufRead, dest: &amp;mut BufWriter&lt;impl Write&gt;) -&gt; io::Result&lt;()&gt; { loop { let buf = src.fill_buf()?; if buf.is_empty() { break; } dest.write_all(buf)?; let bytes = buf.len(); src.consume(bytes); } dest.flush() } /// Dumps the file given by `path` on `stdout` using buffered IO. /// /// If `path` is `&quot;-&quot;`, then `stdin` is used as input instead of a file. /// /// Example /// ``` /// # use cat::cat_buffered_single; /// cat_buffered_single(&quot;hello.txt&quot;.as_ref()); /// ``` pub fn cat_buffered_single(path: &amp;Path) -&gt; io::Result&lt;()&gt; { let stdout = io::stdout(); let handle = stdout.lock(); let mut writer = io::BufWriter::new(handle); if path == Path::new(&quot;-&quot;) { dump_buffered_single(&amp;mut io::stdin().lock(), &amp;mut writer)?; } else { let input = BufReader::new(File::open(path)?); let mut reader = BufReader::new(input); dump_buffered_single(&amp;mut reader, &amp;mut writer)?; } Ok(writer.flush()?) } // Dumps all bytes from `src` into `dest`, byte by byte. fn dump_unbuffered_single(src: &amp;mut dyn Read, dest: &amp;mut dyn Write) -&gt; io::Result&lt;()&gt; { for byte in src.bytes() { dest.write_all(std::slice::from_ref(&amp;byte?))?; } Ok(()) } /// Dumps the file given by `path` on `stdout` without buffering /// /// If `path` is `&quot;-&quot;`, then `stdin` is used as input instead of a file. /// /// Example /// ``` /// # use cat::cat_unbuffered_single; /// cat_unbuffered_single(&quot;hello.txt&quot;.as_ref()); /// ``` pub fn cat_unbuffered_single(path: &amp;Path) -&gt; io::Result&lt;()&gt; { let stdout = io::stdout(); let mut handle = stdout.lock(); if path == Path::new(&quot;-&quot;) { dump_unbuffered_single(&amp;mut io::stdin().lock(), &amp;mut handle)?; } else { let mut file = File::open(path)?; dump_unbuffered_single(&amp;mut file, &amp;mut handle)?; } Ok(()) } #[cfg(test)] mod test { use super::*; fn test_dump_buffered_single(test_bytes: &amp;[u8]) { let src = test_bytes; let mut reader = BufReader::new(src); let mut dest = vec![]; { let mut writer = BufWriter::new(&amp;mut dest); dump_buffered_single(&amp;mut reader, &amp;mut writer).unwrap(); } assert_eq!(dest, src); } #[test] fn dumps_all_buffered_data() { test_dump_buffered_single(b&quot;Hello, World&quot;); } #[test] fn dumps_no_buffered_data() { test_dump_buffered_single(b&quot;&quot;); } fn test_dump_unbuffered_single(bytes: &amp;[u8]) { let source = bytes; let mut reader = source.clone(); let mut destination = vec![]; dump_unbuffered_single(&amp;mut reader, &amp;mut destination).unwrap(); assert_eq!(destination, source); } #[test] fn dumps_all_unbuffered_data() { test_dump_unbuffered_single(b&quot;Hello, World&quot;); } #[test] fn dumps_no_unbuffered_data() { test_dump_unbuffered_single(b&quot;&quot;); } } </code></pre> <p>I've used <code>cargo fmt</code> and <code>cargo clippy</code> on the code above. By the way, I see myself as a Rust beginner, so feel free to comment any part of the code.</p>
[]
[ { "body": "<p>First of all, I would like to point out that it has been a great\npleasure to read the code with consistent formatting, helpful\ncomments, and clear logic. The following points might be subjective\nand nitpicky, but they don't represent my general impression.</p>\n<h1>Argument parsing</h1>\n<blockquote>\n<p>The program <em>should</em> follow the <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02\" rel=\"nofollow noreferrer\">Utility Argument Syntax</a>,\nhowever, it doesn't follow guidelines [...] 9 (<code>-u</code> does not need\nto be the first argument).</p>\n</blockquote>\n<p>Wouldn't requiring <code>-u</code> to come before the operands make the\nimplementation easier though? I'm thinking along these lines:</p>\n<pre><code>let (buffered, operands) = match args.get(0) {\n None =&gt; {\n args.push(&quot;-&quot;.into());\n (true, &amp;args[..])\n }\n Some(arg) if *arg == &quot;-u&quot; =&gt; (false, &amp;args[1..]),\n Some(_) =&gt; (true, &amp;args[..]),\n};\n</code></pre>\n<h1><code>BufRead</code> and <code>Write</code></h1>\n<p>Instead of <code>&amp;mut dyn BufRead</code>, it's more common to take <code>BufRead</code> by\nvalue. The reason is that mutable references to <code>BufRead</code>\nautomatically implement <a href=\"https://doc.rust-lang.org/std/io/trait.BufRead.html#impl-BufRead-3\" rel=\"nofollow noreferrer\"><code>BufRead</code></a>.</p>\n<p>Instead of taking an argument of type <code>&amp;mut BufWriter&lt;impl Write&gt;</code>, it\nsuffices to take <code>Write</code>, since the functionality of <code>BufWriter</code> can\nbe accessed via <code>Write</code>.</p>\n<p>Result:</p>\n<pre><code>fn dump_buffered_single&lt;R, W&gt;(mut src: R, mut dest: W) -&gt; io::Result&lt;()&gt;\nwhere\n R: BufRead,\n W: Write,\n{\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T07:28:07.893", "Id": "485708", "Score": "0", "body": "Thanks for the review! Yeah, the argument parsing would be easier if I supported `-u` only at the start. However, `-u` may be used several times (e.g. `-u -u` or `-uuuu`), so it's a little bit more complicated due to guideline 5. But I'll keep that in mind for future minimal argument parsing :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:49:29.807", "Id": "247760", "ParentId": "247752", "Score": "2" } } ]
{ "AcceptedAnswerId": "247760", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T04:18:02.847", "Id": "247752", "Score": "6", "Tags": [ "beginner", "reinventing-the-wheel", "rust" ], "Title": "Buffered and unbuffered cat(1) implementation" }
247752
<h1>Goal</h1> <ul> <li>Return a deep copy of a double LinkedList.</li> <li>Each node also contains an additional random pointer, potentially to any node or null.</li> </ul> <h1>Code to start</h1> <pre class="lang-kotlin prettyprint-override"><code>data class Node&lt;T&gt;( var data: T?, var previous: Node&lt;T&gt;? = null, var next: Node&lt;T&gt;? = null, var random: Node&lt;T&gt;? = null class LinkedList { // TODO: Implement deep copy here. } </code></pre> <h1>Questions</h1> <ul> <li>Generics - Is there a better approach to handle the generic variance as to not need <code>as T</code> when passing in a generic type? i.e. <code>linkedList.add(data = 1 as T)</code></li> <li><em>Add thread-safety for operations</em> - Are there any specific recommendations on thread-safety for this solution or broader topics to research to understand thread-safety considerations further?</li> </ul> <h1>Implement</h1> <p><strong>See the <a href="https://github.com/AdamSHurwitz/DSA-LC-LinkedList-DeepCopy" rel="noreferrer"><em>full code on GitHub</em></a>.</strong></p> <p><em>LinkedList.kt</em></p> <pre class="lang-kotlin prettyprint-override"><code>class Node&lt;T&gt;( var prev: Node&lt;T&gt;? = null, var next: Node&lt;T&gt;? = null, var rand: Node&lt;T&gt;? = null, var data: T ) class LinkedList&lt;T&gt;( var first: Node&lt;T&gt;? = null, var last: Node&lt;T&gt;? = null, val randMap: HashMap&lt;Node&lt;T&gt;?, Node&lt;T&gt;?&gt; = hashMapOf() ) { // Add Node to the end of LinkedList fun add(data: T): Node&lt;T&gt; { val temp = last val newNode = Node(prev = temp, data = data) last = newNode if (temp == null) first = newNode else temp.next = newNode return newNode } fun deepCopyWithoutRandoms(prev: Node&lt;T&gt;?, node: Node&lt;T&gt;?): Node&lt;T&gt;? { return if (node == null) null else { val newNode = Node(data = node.data) if (node.rand != null) { newNode.rand = node.rand randMap.put(node.rand, null) } newNode.prev = prev newNode.next = deepCopyWithoutRandoms(newNode, node.next) if (randMap.containsKey(node)) randMap.put(node, newNode) return newNode } } fun updateRandoms(node: Node&lt;T&gt;?): Node&lt;T&gt;? { if (node != null) { if (node.rand != null) node.rand = randMap.get(node.rand!!) updateRandoms(node.next) return node } else return null } fun clear() { var node = first while (node != null) { node.prev = null node.next = null node.rand = null node.data = 0 as T node = node.next } } fun toString(first: Node&lt;T&gt;?): String { var output = &quot;&quot; var node = first while (node != null) { output += String.format(&quot;(prev:%s next:%s data:%s random:%s)\n&quot;, node.prev, node.next, node.data, node.rand) node = node.next } return output } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T21:56:12.760", "Id": "485977", "Score": "0", "body": "Does this answer your question? [Double LinkedList Deep Copy in Kotlin](https://codereview.stackexchange.com/questions/244600/double-linkedlist-deep-copy-in-kotlin)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T22:01:00.480", "Id": "485979", "Score": "0", "body": "Thanks for the suggestion @CarsonGraham. The linked question does not answer the question above as it does not cover the topics of Generics and Thread Safety." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T22:02:49.810", "Id": "485980", "Score": "2", "body": "ah, I see now. Give me a minute" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T22:44:16.913", "Id": "485987", "Score": "1", "body": "This question ended up in the close vote queue as a duplicate of the original, which it wasn't. When you ask a follow up question to something closely related I recommend you provide a link to the original question as well." } ]
[ { "body": "<p>I'm not going to touch on your question on thread safety as it is a broad topic I am not familiar with. However, I can help with your questions about generics.</p>\n<p>Right now, you're using generics great, except in one single place</p>\n<pre><code>node.data = 0 as T\n</code></pre>\n<p>The type of <code>node.data</code> is <code>T</code>. This code will fail if <code>T</code> is not <code>Int</code> - for example, if <code>T</code> is <code>String</code>, the code will look like this:</p>\n<pre><code>node.data = 0 as String\n</code></pre>\n<p>and that will throw a runtime exception.</p>\n<p>Here's the important thing, though. There's no reason to do <code>node.data = &lt;anything&gt;</code>.\nI assume the reason for having it originally was to &quot;zero out&quot; or get rid of the data as it's removed from the list - but that's what java will do for you automatically!</p>\n<p>Let's say you have the following structure</p>\n<pre><code>linked list /--&gt; node 1 /--&gt; value 1\n----------- | ------ | --------\nfirst node ---/ data ---/ 7\n</code></pre>\n<p>when you delete the pointer to <code>node 1</code>, you end up in this situation</p>\n<pre><code>linked list node 1 /--&gt; value 1\n----------- ------ | --------\nfirst node-&gt;null data ---/ 7\n</code></pre>\n<p>now that there is no reference anywhere to <code>node 1</code>, the jvm garbage collector deletes it</p>\n<pre><code>linked list value 1\n----------- ------\nfirst node-&gt;null 7\n</code></pre>\n<p>and because there is no reference to <code>value 1</code>, it's also deallocated.</p>\n<p>This means that there's no reason to set the data field to anything - and, besides the point, there is no possible value you could set it to that would work for any value of T (in java, though, you could use null)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-20T20:14:02.287", "Id": "486072", "Score": "0", "body": "Thank you for the thorough response regarding generic usage _@Carson Graham_. I've refactored the `clear` function in this _[commit](https://github.com/AdamSHurwitz/DSA-LC-LinkedList-DeepCopy/commit/40ad5bd2f735a49297d8c3fd1f79f3ed6d78069d)_ to not \"zero out\" the data as the Java garbage collection will delete unreferenced resources as you outlined." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T22:10:33.270", "Id": "248164", "ParentId": "247754", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T05:20:22.007", "Id": "247754", "Score": "5", "Tags": [ "multithreading", "linked-list", "thread-safety", "generics", "kotlin" ], "Title": "Double LinkedList Deep Copy in Kotlin with Generics and Thread Safety" }
247754
<p>I'm finding it difficult to decide on the best architectural pattern for a SwiftUI app but, for the moment, I'm sticking with MVVM as I found this a good fit conceptually.</p> <p>I'm trying to avoid the SwiftUI layer knowing too much about the business logic and navigation structure but am struggling to decide how best to achieve this.</p> <p>Here is the prototype view model (without implementation for the navigation):</p> <pre><code>@dynamicMemberLookup final class PatientListViewModel: ViewModelType { struct State { var patients: [PatientSummaryViewModel] } @Published var state: State = State(patients: []) { willSet { print(&quot;Received: \(newValue)&quot;) } } enum Input { case onNewPatient } private let service: PatientServiceType private var cancellables = Set&lt;AnyCancellable&gt;() init(service: PatientServiceType) { self.service = service service.fetchAll() .receive(on: DispatchQueue.main) .map { patients in patients.map { PatientSummaryViewModel(patient: $0) } } .sink { [weak self] patientViewModel in self?.state.patients = patientViewModel } .store(in: &amp;cancellables) } func action(_ input: Input) { switch input { case .onNewPatient: print(&quot;Create new view and associated viewModel here but how does SwiftUI access it?&quot;) } } subscript&lt;Value&gt;(dynamicMember keyPath: KeyPath&lt;State, Value&gt;) -&gt; Value { state[keyPath: keyPath] } } </code></pre> <p>Associated SwiftUI view:</p> <pre><code>struct PatientListView: View { @ObservedObject var viewModel: PatientListViewModel var body: some View { NavigationView { List(viewModel.patients) { viewModel in NavigationLink( destination: PatientSummaryView(viewModel: viewModel), label: { PatientCell(patient: viewModel.patient) }) } .navigationBarItems(leading: EditButton(), trailing: Button(action: { // call to viewmodel to get new view and correctly constructed viewModel }, label: { Image(systemName: &quot;plus&quot;) .font(.title2) })) .navigationBarTitle(&quot;Patients&quot;) } } } </code></pre> <p>At this point in time, there are several solutions that present themselves:</p> <ol> <li><p>Modify <code>action(_ input:)</code> to create the View in situ, returning it to the View that called it. Not all actions will need navigation to take place and so I'd need to add <code>@discardableresult</code> with many actions having to return <code>EmptyView()</code> and then there's the little dance I'd need to do with type erasing the views to consider.</p> </li> <li><p>Modify the view model State internal struct to include a &quot;next view&quot; property that is updated by <code>action(_:)</code> when new views are required. Although the idea of keeping state in one place appeals this feels a little clunky somehow.</p> </li> <li><p>Finally I have some vague ideas about a callback/closure that is passed to the view model and used to construct the required view but I'm struggling to visualise this as I still find closure syntax confusing, doubly so when working with Views.</p> </li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T05:37:06.897", "Id": "247755", "Score": "3", "Tags": [ "swift", "mvvm", "swiftui" ], "Title": "Navigation strategies for a SwiftUI-based app using MVVM pattern" }
247755
<p>For the sections between count=1s and the start and end; combine overlapping positions and output the median of the counts.</p> <p>Input</p> <pre><code>chr start stop strand count chr1 0 13320 - 1 chr1 13320 13321 - 2 chr1 13321 13328 - 1 chr1 13328 13342 - 2 chr1 13342 13343 - 18 chr1 13343 13344 - 36 chr1 13344 13345 - 18 chr1 13345 13346 - 6 chr1 13346 16923 - 1 chr1 16923 16942 - 3 chr1 16942 16943 - 2 </code></pre> <p>Output</p> <pre><code>chr1 13320 13321 2 chr1 13328 13346 18 chr1 16923 16943 2.5 </code></pre> <p>For the second value:</p> <ul> <li>Start 13328 - this is because the 4th value in the table has the start 13328.<br /> This is the row <em>after</em> the second count=1.</li> <li>Stop 13346 - this is because the 8th value in the table has the stop 13346.<br /> This is the row <em>before</em> the third count=1.</li> <li>Count 18 - this is the median of counts between the 4th and 8th inclusive.</li> </ul> <p>Here is my code.</p> <pre class="lang-py prettyprint-override"><code>from pathlib import Path import pandas as pd file = Path(&quot;bed_file.bed&quot;) # load with pandas df = pd.read_csv(file, sep='\t', header=None) # set colnames header = ['chr','start','stop','strand','count'] df.columns = header[:len(df.columns)] # index where count=1 col_count = df['count'].tolist() li = [i for i, n in enumerate(col_count) if n == 1] # create new dataframe newDF = pd.DataFrame(columns=['chr','start', 'stop', 'count']) # last position end = df.index[-1] # parse dataframe for idx, elem in enumerate(li): if elem != li[-1]: next_elem = li[(idx + 1) % len(li)] # next element where count=1 start = df.iloc[elem]['stop'] # start position stop = df.iloc[next_elem-1]['stop'] # stop position if next_elem - (elem+1) == 1: # cases where only one position and we cannot compute median count = df.iloc[elem+1]['count'] #print(f&quot;start={start}\tstop={stop}\tcount={count}&quot;) else: count = df.iloc[elem+1:next_elem]['count'].median() #print(f&quot;start={start}\tstop={stop}\tcount={count}&quot;) newDF = newDF.append({ 'chr' : df.loc[0,'chr'], 'start' : start, 'stop' : stop, 'count' : count },ignore_index=True) else: # last element in the list start = df.iloc[elem]['stop'] stop = df.iloc[end]['stop'] count = df.iloc[elem+1:end+1]['count'].median() #print(f&quot;start={start}\tstop={stop}\tcount={count}&quot;) newDF = newDF.append({ 'chr' : df.loc[0,'chr'], 'start' : start, 'stop' : stop, 'count' : count },ignore_index=True) </code></pre> <p>Is there a better way to do this? Is my code Pythonic?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:58:52.090", "Id": "485129", "Score": "2", "body": "Welcome to Code Review. \"combines overlapping positions in the interval between the position where count=1\" I may be misinterpreting your output, but it looks like your output actually combines the intervals where the count is **not** 1. Where count is 1, line is filtered out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T13:21:54.490", "Id": "485158", "Score": "1", "body": "Please double check that my rewording of your question is correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T06:41:41.500", "Id": "485231", "Score": "0", "body": "@Mast yes you are right, my mistake" } ]
[ { "body": "<p>I'll first offer some critique of your code, and then I'll show you how I would approach the problem.</p>\n<ul>\n<li>Commented out code should be removed before asking for a code review <code>#print(f&quot;start={start}\\tstop={stop}\\tcount={count}&quot;)</code></li>\n<li>Many of the comments don't add value. <code># last position</code> doesn't mean much on its own. Why do you want the last position? Why doesn't the code do a good enough job explaining that?</li>\n<li>Generally an if/else in a loop where one of branches is only taken once, either at the start or end, can be removed. You can iterate less, and deal with the case explicitly. You can add a sentinel value so you don't have to check if you are at the end of the iterator. You can used the available libraries or built-in functions, which will deal with the case for you.</li>\n</ul>\n<hr />\n<pre><code># load with pandas\ndf = pd.read_csv(file, sep='\\t', header=None)\n\n# set colnames\nheader = ['chr','start','stop','strand','count']\ndf.columns = header[:len(df.columns)]\n\n# index where count=1\ncol_count = df['count'].tolist()\nli = [i for i, n in enumerate(col_count) if n == 1]\n</code></pre>\n<p>If the header is cut short <code>len(df.columns) &lt; len(header)</code>, the first thing to be cut off is the column <code>df['count']</code>. You then assume it exists straight away after by using it. Which is it? Will it always exist, or sometimes will there not be enough columns? Erring on the side of it always exists, the code becomes</p>\n<pre><code># load with pandas\ndf = pd.read_csv(file, sep='\\t', names=('chr', 'start', 'stop', 'strand', 'count'), header=None)\n\n# index where count=1\ncol_count = df['count'].tolist()\nli = [i for i, n in enumerate(col_count) if n == 1]\n</code></pre>\n<hr />\n<pre><code># index where count=1\ncol_count = df['count'].tolist()\nli = [i for i, n in enumerate(col_count) if n == 1]\n\n...\n\nfor idx, elem in enumerate(li):\n</code></pre>\n<p>If you are using pandas (or numpy) it is generally not the best to move the data back and forth between the library and Python. You lose most of the efficiency of the library, and the code generally becomes far less readable.</p>\n<p>Don't use names like <code>li</code>. It doesn't give any information to the reader. If you have a list of indices, what will you use the list for? That would make a much better name.</p>\n<p>Using pandas more, and renaming gives something like</p>\n<pre><code>splitting_indices = df.index[df['count'] == 1].tolist()\n\nfor idx, elem in enumerate(splitting_indices):\n</code></pre>\n<hr />\n<pre><code>if next_elem - (elem+1) == 1: # cases where only one position and we cannot compute median\n count = df.iloc[elem+1]['count']\n #print(f&quot;start={start}\\tstop={stop}\\tcount={count}&quot;)\nelse:\n count = df.iloc[elem+1:next_elem]['count'].median()\n</code></pre>\n<p>Finding this logic in amongst getting the data out from the dataframe is not easy. This is the core logic, and should be treated as such. Put this in a function at the very least.</p>\n<pre><code>def extract_median(df, elem, next_elem):\n if next_elem - (elem+1) == 1: # cases where only one position and we cannot compute median\n count = df.iloc[elem+1]['count']\n else:\n count = df.iloc[elem+1:next_elem]['count'].median()\n return count\n</code></pre>\n<p>Now it should be much more apparent that the comment is bogus. You CAN compute the median of a single element list. So why are we special casing this? <code>df.iloc[elem+1:next_elem]</code> works even if <code>next_elem</code> is only one bigger than <code>elem+1</code>.</p>\n<pre><code>def extract_median(df, elem, next_elem):\n return df.iloc[elem+1:next_elem]['count'].median()\n</code></pre>\n<p>And now we can see that a function is probably not necessary.</p>\n<hr />\n<p>The approach I would take to implementing this is to try and stay using pandas as long as possible. No loops. No tolist. Since I won't want loops, indices are probably not needed too, so I can limit usage of iloc and df.index.</p>\n<p>First, read in the data</p>\n<pre><code>df = pd.read_csv(file, sep='\\t', names=('chr', 'start', 'stop', 'strand', 'count'), header=None)\n\n chr start stop strand count\n0 chr1 0 13320 - 1\n1 chr1 13320 13321 - 2\n2 chr1 13321 13328 - 1\n3 chr1 13328 13342 - 2\n4 chr1 13342 13343 - 18\n5 chr1 13343 13344 - 36\n6 chr1 13344 13345 - 18\n7 chr1 13345 13346 - 6\n8 chr1 13346 16923 - 1\n9 chr1 16923 16942 - 3\n10 chr1 16942 16943 - 2\n</code></pre>\n<p>Then, find every row of interest. That would be everywhere <code>count</code> is not 1.</p>\n<pre><code>df['count'] != 1\n\n0 False\n1 True\n2 False\n3 True\n4 True\n5 True\n6 True\n7 True\n8 False\n9 True\n10 True\n</code></pre>\n<p>I want to group all the consecutive rows that are True together. The usual method to group consecutive rows by a column value is</p>\n<ol>\n<li>Keep a running tally.</li>\n<li>Compare each value in the column with the next one.</li>\n<li>If they are the same, don't do anything.</li>\n<li>If they are different, add 1 to a running tally.</li>\n<li>Associate the tally to that value.</li>\n<li>Groupby the tally.</li>\n</ol>\n<p>In code</p>\n<pre><code>mask = df['count'] != 1\ntally = (mask != mask.shift()).cumsum()\n\n count mask tally\n0 1 False 1\n1 2 True 2\n2 1 False 3\n3 2 True 4\n4 18 True 4\n5 36 True 4\n6 18 True 4\n7 6 True 4\n8 1 False 5\n9 3 True 6\n10 2 True 6\n</code></pre>\n<p>Grouping then gives</p>\n<pre><code>df.groupby(tally).groups\n\n{1: Int64Index([0], dtype='int64'),\n 2: Int64Index([1], dtype='int64'),\n 3: Int64Index([2], dtype='int64'),\n 4: Int64Index([3, 4, 5, 6, 7], dtype='int64'),\n 5: Int64Index([8], dtype='int64'),\n 6: Int64Index([9, 10], dtype='int64')}\n</code></pre>\n<p>Since you only want the rows where count is not 1, we can reuse the mask to filter them out.</p>\n<pre><code>df[mask].groupby(tally).groups\n\n{2: Int64Index([1], dtype='int64'),\n 4: Int64Index([3, 4, 5, 6, 7], dtype='int64'),\n 6: Int64Index([9, 10], dtype='int64')}\n</code></pre>\n<p>And finally the median is quick to get from a grouper</p>\n<pre><code>df[mask].groupby(tally).median()\n\n start stop count\ncount \n2 13320.0 13321.0 2.0\n4 13343.0 13344.0 18.0\n6 16932.5 16942.5 2.5\n</code></pre>\n<hr />\n<p>In the end, the code is a lot shorter</p>\n<pre><code>df = pd.read_csv(file, sep='\\t', names=('chr', 'start', 'stop', 'strand', 'count'), header=None)\nmask = df['count'] != 1\ntally = (mask != mask.shift()).cumsum()\ndf[mask].groupby(tally).median()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:55:19.710", "Id": "485256", "Score": "0", "body": "Thanks a lot for all your explanations. It is much more clear now. I did'nt know the shift() function, very usefull ! Nevertheless, the output is not the one I expected. It seems that median is calculated also on start and stop position in the output. I tried `df[mask].groupby(tally)[['count']].median() `but then I don't have start and stop position anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:04:20.267", "Id": "485259", "Score": "0", "body": "I found the answer using agg() function ! `df[mask].groupby(tally).agg({'start': np.min, 'stop': np.max, 'count' : np.median})`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:56:02.003", "Id": "247784", "ParentId": "247757", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:13:43.813", "Id": "247757", "Score": "5", "Tags": [ "python", "pandas" ], "Title": "Parse bed file with Pandas" }
247757
<p>I have written the following method that allows me to import from another API all the items stored there using Feign. The only issue is that the external API provides a size limit of 2000 and therefore I need to take pagination into account to get all the records.</p> <p>I think that my solution is not very clean and maintainable and I'd like to use streams and newer Java features to make it shorter (like I did in the final part) but I am still learning and I cannot think of good solutions for the main part of the code.</p> <pre><code>@Service public class ClientService { @Autowired private Client Client; @Autowired private ItemRepository itemRepository; public List&lt;Code&gt; importItems() { int itemsPerPage = 2000; RestPage&lt;Item&gt; restPage = Client.getItems(itemsPerPage, 0); List&lt;Item&gt; items = restPage.getContent(); int totalpages = restPage.getTotalPages(); List&lt;Item&gt; result = new ArrayList&lt;Item&gt;(); result.addAll(items); for (int pageNumber = 1; pageNumber &lt; totalpages; pageNumber ++) { result.addAll(Client.getItems(itemsPerPage, pageNumber).getContent()); } return result.stream() .filter(itemo -&gt; !itemRepository.existsByCode(item.getCode())) .map(item -&gt; itemRepository.save(new Code(item.getCodemsl))) .collect(Collectors.toList()); } } </code></pre> <p>Can you help me in improving this?</p>
[]
[ { "body": "<p>I see these lines in your code :</p>\n<pre><code>List&lt;Item&gt; items = restPage.getContent();\nList&lt;Item&gt; result = new ArrayList&lt;Item&gt;();\nresult.addAll(items);\n</code></pre>\n<p>You can use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-\" rel=\"nofollow noreferrer\">ArrayList(Collection&lt;? extends E&gt; c)</a> constructor obtaining the same result:</p>\n<pre><code>List&lt;Item&gt; result = new ArrayList&lt;&gt;(restPage.getContent());\n</code></pre>\n<p>Your filtering code looks good to me and for the for loop adding elements to an existing list for me you made the right choice. Although it is possible to add new elements to an existing list using streams this is discouraged because easy cause of errors, see for example this <a href=\"https://stackoverflow.com/questions/22753755/how-to-add-elements-of-a-java8-stream-into-an-existing-list\">thread</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T09:01:36.057", "Id": "247764", "ParentId": "247758", "Score": "3" } }, { "body": "<p>You could basically turn the logic around, something like:</p>\n<pre><code>int totalpages = -1;\nint currentPage = 0;\ndo {\n RestPage&lt;Item&gt; page = Client.getItems(itemsPerPage, currentPage);\n result.addAll(page.getContent());\n totalpages = page.getTotalPages(); // provided, that *every* page contains the total number\n currentPage++;\n}\nwhile(currentPage &lt; totalpages); // or &lt;=, I don't know that API\n</code></pre>\n<p>This way, you don't duplicate the fetch-code.</p>\n<p>As streams are no goal in itself, I recommend keeping it this simple, as long as you don't have any problems with caching all results in memory at once. You <em>could</em> write a Spliterator which basically performs the loop-body internally, but this is a complex problem in itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T06:04:09.957", "Id": "247792", "ParentId": "247758", "Score": "2" } } ]
{ "AcceptedAnswerId": "247764", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T07:16:10.873", "Id": "247758", "Score": "2", "Tags": [ "java", "api", "http", "spring", "data-importer" ], "Title": "Get all data from an external and paginated Swagger API using Java / Feign / Spring" }
247758
<p>I'm using NumPy to find out langrage polynomial interpolation. I'm using 2 for loop to find out langrage polynomial, but I want to reduce 2nd for loop so that my code time complexity can be less. Can you guys please suggest me how I can cut a for loop to increase my time complexity.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt class LagrangePolynomial: def __init__(self, data_x, data_y): assert type(data_x) == np.ndarray, &quot;data_x is not numpy array&quot; assert type(data_y) == np.ndarray, &quot;data_y is not numpy array&quot; assert len(data_x) == len(data_y), &quot;length of data_x and data_y must be equal&quot; self.x = data_x self.y = data_y self.degree = len(data_x) - 1 def __str__(self): strL = f&quot;LagrangePolynomial of order {self.degree}\n&quot; strL += &quot;p(x) = &quot; count=0 for i in self.y: if i == 0: continue elif i &gt;= 0: strL += f&quot;+ {i}*l_{count + 1}(x) &quot; else: strL += f&quot;- {-i}*l_{count + 1}(x) &quot; count+=1 return strL def __call__(self,x): y_interp = np.zeros(len(x)) for i in range(len(x)): #remove this for loop. for j in range(self.degree + 1): upper=np.prod(np.delete(self.x - x[i],j)) lower=np.prod(np.delete(self.x[j] - self.x, j)) y_interp[i] +=(upper/lower)*self.y[j] return y_interp data_x = np.array([-3.,-2.,-1.,0.,1.,3.,4.]) data_y = np.array([-60.,-80.,6.,1.,45.,30.,16.]) p = LagrangePolynomial(data_x, data_y) #generating 100 points from -3 to 4 in order to create a smooth line x = np.linspace(-3, 4, 100) print(p) y_interp = p(x) plt.plot(x, y_interp, 'g--') plt.plot(data_x, data_y, 'ro') plt.legend(['interpolated', 'node points'], loc = 'lower right') plt.xlabel('x') plt.ylabel('y') plt.title('Lagrange Polynomial') plt.show() </code></pre>
[]
[ { "body": "<p>The second loop can be eliminated by creating a 2D array by tiling the <code>self.x</code> array with the <code>np.tile</code> method. The removal of elements in de 1D array with <code>np.delete</code> can than be replaced with a <em>boolean mask</em> (unfortunately this results in a 1D array which needs to be reshaped).</p>\n<p>The calculation of the 2D array can be done outside the first loop, as can be the calculation of <code>lower</code> as they do not depend on <code>x</code>.</p>\n<p>See my rewrite of the <code>__call__</code> method:</p>\n<pre><code>def __call__(self,x):\n\n y_interp = np.zeros(len(x))\n \n n = self.degree + 1\n mask = ~np.eye(n, dtype=np.bool)\n\n tiled = np.tile(self.x, (n,1))\n masked = np.reshape(tiled[mask], (n, n-1))\n\n lower = np.prod(self.x[:,np.newaxis] - masked, axis=1)\n \n for i in range(len(x)):\n\n upper = np.prod(masked -x[i], axis=1)\n \n y_interp[i] = np.sum((upper/lower) * self.y)\n \n return y_interp\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T07:28:14.393", "Id": "485784", "Score": "0", "body": "thanks a lot for your code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:53:34.127", "Id": "247783", "ParentId": "247765", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T09:18:35.417", "Id": "247765", "Score": "1", "Tags": [ "python", "numpy", "scipy" ], "Title": "Reduce one for loop to decrease time complexity" }
247765
<p>I would like to get any feedback about my implementation of Dijkstra algorithm in Rust following this <a href="https://www.youtube.com/watch?v=pVfj6mxhdMw" rel="nofollow noreferrer">youtube video</a>.</p> <p>Please be aware that this my first code in Rust as well as my first Dijkstra implementation in any language.</p> <pre><code>type Vertex = char; #[derive(Debug)] struct Connection { peers : (Vertex, Vertex), weight : u32, } #[derive(Debug)] struct Graph { connections : Vec&lt;Connection&gt;, vertices : Vec&lt;Vertex&gt;, } #[derive(Debug)] #[derive(Clone)] struct Road { vertex : Vertex, distance : u32, via_vertex : Vertex, } #[derive(Debug)] #[derive(Clone)] struct DijkstraTable { start_vertex : Vertex, roads : Vec&lt;Road&gt;, unvisited : Vec&lt;Vertex&gt;, } impl DijkstraTable { fn get_distance(&amp;self, vertex: Vertex) -&gt; u32 { let mut ret = 0; for r in &amp;self.roads { if r.vertex == vertex { ret = r.distance; } } ret } fn get_road_mut(&amp;mut self, vertex: &amp;Vertex) -&gt; Option&lt;&amp;mut Road&gt; { for r in &amp;mut self.roads { if r.vertex == *vertex { return Some(r); } } None } fn get_road(&amp;self, vertex: &amp;Vertex) -&gt; Option&lt;&amp;Road&gt; { for r in &amp;self.roads { if r.vertex == *vertex { return Some(r); } } None } fn get_next_unvisited(&amp;self) -&gt; Option&lt;&amp;Vertex&gt; { let mut min = u32::MAX; let mut next = None; for v in &amp;self.unvisited { match self.get_road(&amp;v) { None =&gt; break, Some(r) =&gt; { if r.distance &lt; min { min = r.distance; next = Some(v); } } } } next } fn remove(&amp;mut self, v : &amp;Vertex) { let mut index = 0; while index &lt; self.unvisited.len() { let toremove = &amp;self.unvisited[index]; if v == toremove { self.unvisited.remove(index); break } index += 1; } } } impl Road { fn new(from: Vertex) -&gt; Road { Road { vertex : from, distance : u32::MAX, via_vertex : '-', } } } impl Graph { fn get_weight(&amp;self, peers: (Vertex, Vertex)) -&gt; u32 { let mut ret : u32 = 0; for c in &amp;self.connections { let (a, b) = peers; if c.peers == peers || c.peers == (b, a) { ret = c.weight; break; } } ret } fn get_neighbours(&amp;self, vertex: &amp;Vertex) -&gt; Vec&lt;&amp;Vertex&gt; { let mut neighbours : Vec&lt;&amp;Vertex&gt; = Vec::new(); for c in &amp;self.connections { if c.peers.0 == *vertex { neighbours.push(&amp;c.peers.1); } else if c.peers.1 == *vertex { neighbours.push(&amp;c.peers.0); } } neighbours } fn vertices_from_connections(conns : &amp;Vec&lt;Connection&gt;) -&gt; Vec&lt;Vertex&gt; { let mut verts : Vec&lt;Vertex&gt; = Vec::new(); for c in conns.iter() { if ! verts.contains(&amp;c.peers.0) { verts.push(c.peers.0); } if ! verts.contains(&amp;c.peers.1) { verts.push(c.peers.1); } } verts } fn new(conns: Vec&lt;Connection&gt;) -&gt; Graph { Graph { vertices : Graph::vertices_from_connections(&amp;conns), connections : conns, } } fn dijkstra(&amp;self, start: Vertex) -&gt; DijkstraTable { let mut table = DijkstraTable { start_vertex : start, roads : Vec::new(), unvisited : self.vertices.clone(), }; for v in &amp;self.vertices { let mut road = Road::new(*v); if v == &amp;start { road.distance = 0; } table.roads.push(road); } loop { let xx = table.clone(); match xx.get_next_unvisited() { None =&gt; break, Some(v) =&gt; { //println!(&quot;{}##################&quot;,v); for n in self.get_neighbours(v) { match table.get_road_mut(n) { None =&gt; println!(&quot;Error&quot;), Some(rn) =&gt; { let d = self.get_weight((*v, *n)); let k = d + xx.get_distance(*v); if k &lt; rn.distance { rn.via_vertex = *v; rn.distance = k; } } } } table.remove(v); //println!(&quot; {:#?} &quot;, table); } } } table } } fn main() { let graph = Graph::new( vec![ Connection { peers: ('A', 'B'), weight: 6, }, Connection { peers: ('A', 'D'), weight: 1, }, Connection { peers: ('D', 'E'), weight: 1, }, Connection { peers: ('D', 'B'), weight: 2, }, Connection { peers: ('E', 'B'), weight: 2, }, Connection { peers: ('E', 'C'), weight: 5, }, Connection { peers: ('B', 'C'), weight: 5, }, ] ); println!(&quot; Dijkstra of 'A': {:#?}&quot;, graph.dijkstra('A')); } </code></pre> <p><strong>Edit</strong>:</p> <p>The code and feedbacks are pushed to <a href="https://github.com/zskdan/rust-dijkstra" rel="nofollow noreferrer">this github repo</a>.</p>
[]
[ { "body": "<p>The call to clone() in Graph::dijkstra feels wrong. Without actually re-factoring the code, I am not sure of the solution, I can see you have some problems with borrowing / mut.</p>\n<p>My intuition is that you need to make the method that constructs DijkstraTable a method of DijkstraTable rather than Graph. It would take a (non-mutable) reference to the Graph.</p>\n<p>Edit:</p>\n<p>After taking a much closer look, I made some changes to eliminate the cloning ( the #derive(Clone)s are no longer needed ), and other changes:</p>\n<pre><code>type Vertex = char;\n\n#[derive(Debug)]\nstruct Connection {\n peers : (Vertex, Vertex),\n weight : u32,\n}\n\n#[derive(Debug)]\nstruct Graph {\n connections : Vec&lt;Connection&gt;,\n vertices : Vec&lt;Vertex&gt;,\n}\n\n#[derive(Debug)]\nstruct Road {\n vertex : Vertex,\n distance : u32,\n via_vertex : Vertex,\n}\n\n#[derive(Debug)]\nstruct DijkstraTable {\n start_vertex : Vertex,\n roads : Vec&lt;Road&gt;,\n unvisited : Vec&lt;Vertex&gt;,\n}\n\nimpl DijkstraTable {\n fn get_distance(&amp;self, vertex: Vertex) -&gt; u32 {\n let mut ret = 0;\n\n for r in &amp;self.roads {\n if r.vertex == vertex {\n ret = r.distance;\n }\n }\n\n ret\n }\n\n fn get_next_unvisited(&amp;self) -&gt; Option&lt;Vertex&gt; {\n let mut min = u32::MAX;\n let mut next = None;\n\n for vertex in &amp;self.unvisited {\n for r in &amp;self.roads\n {\n if r.vertex == *vertex \n {\n if r.distance &lt; min {\n min = r.distance;\n next = Some(*vertex);\n }\n }\n }\n }\n next\n }\n\n fn remove(&amp;mut self, v : Vertex) {\n let mut index = 0;\n while index &lt; self.unvisited.len() {\n let toremove = self.unvisited[index];\n if v == toremove {\n self.unvisited.remove(index);\n break\n }\n index += 1;\n }\n }\n\n\n fn new( graph: &amp;Graph, start: Vertex ) -&gt; DijkstraTable {\n let mut table = DijkstraTable {\n start_vertex : start,\n roads : Vec::new(),\n unvisited : graph.vertices.clone(),\n };\n\n for v in &amp;graph.vertices {\n let mut road = Road::new(*v);\n\n if *v == start {\n road.distance = 0;\n }\n\n table.roads.push(road);\n }\n\n loop {\n match table.get_next_unvisited() {\n None =&gt; break,\n Some(v) =&gt; {\n //println!(&quot;{}##################&quot;,v);\n\n for n in graph.get_neighbours(v) {\n let d = graph.get_weight((v, n));\n let k = d + table.get_distance(v);\n for road in &amp;mut table.roads\n { \n if road.vertex == n\n {\n if k &lt; road.distance {\n road.via_vertex = v;\n road.distance = k;\n }\n break;\n }\n }\n }\n table.remove(v);\n // println!(&quot; {:#?} &quot;, table);\n }\n }\n }\n table\n }\n}\n\nimpl Road {\n fn new(from: Vertex) -&gt; Road {\n Road {\n vertex : from,\n distance : u32::MAX,\n via_vertex : '-',\n }\n }\n}\n\nimpl Graph {\n fn get_weight(&amp;self, peers: (Vertex, Vertex)) -&gt; u32 {\n let mut ret : u32 = 0;\n\n for c in &amp;self.connections {\n let (a, b) = peers;\n\n if c.peers == peers || c.peers == (b, a) {\n ret = c.weight;\n break;\n }\n }\n ret\n }\n\n fn get_neighbours(&amp;self, vertex: Vertex) -&gt; Vec&lt;Vertex&gt; {\n let mut neighbours : Vec&lt;Vertex&gt; = Vec::new();\n\n for c in &amp;self.connections {\n if c.peers.0 == vertex {\n neighbours.push(c.peers.1);\n } else if c.peers.1 == vertex {\n neighbours.push(c.peers.0);\n }\n }\n\n neighbours\n }\n\n fn vertices_from_connections(conns : &amp;Vec&lt;Connection&gt;) -&gt; Vec&lt;Vertex&gt; {\n let mut verts : Vec&lt;Vertex&gt; = Vec::new();\n\n for c in conns.iter() {\n if ! verts.contains(&amp;c.peers.0) {\n verts.push(c.peers.0);\n }\n if ! verts.contains(&amp;c.peers.1) {\n verts.push(c.peers.1);\n }\n }\n verts\n }\n\n fn new(conns: Vec&lt;Connection&gt;) -&gt; Graph {\n Graph {\n vertices : Graph::vertices_from_connections(&amp;conns),\n connections : conns,\n }\n }\n}\n\nfn main() {\n let graph = Graph::new(\n vec![\n Connection {\n peers: ('A', 'B'),\n weight: 6,\n },\n Connection {\n peers: ('A', 'D'),\n weight: 1,\n },\n Connection {\n peers: ('D', 'E'),\n weight: 1,\n },\n Connection {\n peers: ('D', 'B'),\n weight: 2,\n },\n Connection {\n peers: ('E', 'B'),\n weight: 2,\n },\n Connection {\n peers: ('E', 'C'),\n weight: 5,\n },\n Connection {\n peers: ('B', 'C'),\n weight: 5,\n },\n ]\n );\n let dt = DijkstraTable::new( &amp;graph, 'A' );\n println!(&quot; Dijkstra of 'A': {:#?}&quot;, dt );\n}\n</code></pre>\n<p>I ought ideally to explain the changes in more detail, but I hope the above helps. In particular you had functions returning &amp;Vertex rather than simply Vertex, which I think caused problems. Also, I have eliminated the functions get_road_mut and get_road. I'm not sure if this was strictly necessary or not, but having functions that return references is I think generally problematic.</p>\n<p>Edit 2:</p>\n<p>It is possible to have a function get_road that returns a mutable reference:</p>\n<pre><code>fn get_road(&amp;mut self, n: Vertex) -&gt; &amp;mut Road\n{\n for road in &amp;mut self.roads\n { \n if road.vertex == n { return road; }\n }\n panic!(&quot;Road not found&quot;);\n}\n</code></pre>\n<p>Which is used like this:</p>\n<pre><code> let road = table.get_road( n );\n if k &lt; road.distance {\n road.via_vertex = v;\n road.distance = k;\n } \n</code></pre>\n<p>Besides, since we have a keyed set of values, it may be easier to use a <a href=\"https://doc.rust-lang.org/book/ch08-03-hash-maps.html\" rel=\"nofollow noreferrer\">Hash Map</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:19:46.143", "Id": "485280", "Score": "0", "body": "Indeed I was forced to do the `clone()` to handle ownership issues (Cannot borrow as immutable because it is also borrowed as mutable).\nI think you're right, It seems now (After reading your comment) obvious that I should move `dijkstra()` method to `DijkstraTable`.\nI'll try that. Thanks @George for your feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:49:58.467", "Id": "485284", "Score": "0", "body": "Your changes makes the code more clear and clean. In fact I still don't feel comfortable with references. And when should I return references.\nWith `get_road_mut` and `get_road` I was hoping to factorize them in a single call. But this seems not possible since they are returning different object type.\nCan you please elaborate on why having functions that return references is problematic ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T13:39:46.083", "Id": "485288", "Score": "0", "body": "The reason is that the lifetime of the return value will be limited, also returning a mutable reference ( allowing part of a struct to be modified ) feels not quite right to me, but it is possible, see my latest edit to my answer above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:33:55.983", "Id": "485296", "Score": "0", "body": "My understanding of returning references is that the lifetime will be rather guaranteed by the compiler. \nAnd they may be helpful to avoid wasting memory on copying the object -like returning pointer in C- (so it worth it for Road object but not for Vertex(char))." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T21:11:39.973", "Id": "247787", "ParentId": "247767", "Score": "1" } }, { "body": "<p>Many of your methods can be simplified (?) with iterators. Here's a few examples:</p>\n<hr />\n<pre><code>fn get_distance(&amp;self, vertex: Vertex) -&gt; u32 {\n let mut ret = 0;\n\n for r in &amp;self.roads {\n if r.vertex == vertex {\n ret = r.distance;\n }\n }\n\n ret\n}\n</code></pre>\n<p>becomes</p>\n<pre><code>fn get_distance(&amp;self, vertex: Vertex) -&gt; u32 {\n self.roads\n .iter()\n .rev()\n .find(|road| road.vertex == vertex)\n .map(|road| road.distance)\n .unwrap_or(0)\n}\n</code></pre>\n<hr />\n<pre><code>fn get_road_mut(&amp;mut self, vertex: &amp;Vertex) -&gt; Option&lt;&amp;mut Road&gt; {\n for r in &amp;mut self.roads {\n if r.vertex == *vertex {\n return Some(r);\n }\n }\n\n None\n}\n</code></pre>\n<p>becomes</p>\n<pre><code>fn get_road_mut(&amp;mut self, vertex: &amp;Vertex) -&gt; Option&lt;&amp;mut Road&gt; {\n self.roads\n .iter_mut()\n .find(|road| road.vertex == vertex)\n}\n</code></pre>\n<hr />\n<pre><code>fn remove(&amp;mut self, v : &amp;Vertex) {\n let mut index = 0;\n while index &lt; self.unvisited.len() {\n let toremove = &amp;self.unvisited[index];\n if v == toremove {\n self.unvisited.remove(index);\n break\n }\n index += 1;\n }\n}\n</code></pre>\n<p>becomes</p>\n<pre><code>fn remove(&amp;mut self, v: &amp;Vertex) {\n let index = self.unvisited.iter().position(|vertex| vertex == v);\n if let Some(index) = index {\n self.unvisited.remove(index);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:03:05.557", "Id": "485361", "Score": "0", "body": "Thanks @L.F. now the code looks more rust idiomatic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:38:44.227", "Id": "485373", "Score": "0", "body": "The new `remove()` code trig a compilation issue since `iterator::position` return an `Option`. So I had to adapt it to: \n`match self.unvisited.iter().position(|vertex| vertex==v) {\n None => (), \n Some(index) => {\n self.unvisited.remove(index); \n }\n }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:53:25.357", "Id": "485375", "Score": "0", "body": "@Zskdan That's right. I've modified the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:58:45.857", "Id": "485377", "Score": "0", "body": "I'm not sure of understanding the syntax of the new code: Does `let Some(index) = index` is handled as condition which return `False` in case of `index == None` and `True` otherwise?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:54:09.863", "Id": "485387", "Score": "0", "body": "Yes. `if let` is a control flow that works the way you described - enter the block if the `let` binding matches." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T00:36:22.887", "Id": "247834", "ParentId": "247767", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T09:24:12.063", "Id": "247767", "Score": "7", "Tags": [ "beginner", "rust", "dijkstra" ], "Title": "Dijkstra's implementation in rust" }
247767
<p>I am still learning PowerShell and I would like your opinion on my log writing function. It creates a log entry with timestamp and message passed thru a parameter Message or thru pipeline, and saves the log entry to log file, to report log file, and writes the same entry to console. In Configuration.cfg file paths to report log and permanent log file are contained, and option to turn on or off whether a report log and permanent log should be written. If Configuration.cfg file is absent it loads the default values. Depending on the OperationResult parameter, log entry can be written with or without a timestamp. Format of the timestamp is &quot;yyyy.MM.dd. HH:mm:ss:fff&quot;, and this function adds &quot; - &quot; after timestamp and before the main message.</p> <pre><code>function Write-Log { param ( [Parameter(Position = 0, ValueFromPipelineByPropertyName)] [ValidateSet('Success', 'Fail', 'Partial', 'Info', 'None')] [String] $OperationResult = 'None', [Parameter(Position = 1, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [String] $Message ) begin { if (Test-Path -Path '.\Configuration.cfg') { $Configuration = Get-Content '.\Configuration.cfg' | ConvertFrom-StringData $LogFile = $Configuration.LogFile $ReportFile = $Configuration.ReportFile $WriteLog = $Configuration.WriteLog -eq 'true' $SendReport = $Configuration.SendReport -eq 'true' } else { $LogFile = '.\Log.log' $ReportFile = '.\Report.log' $WriteLog = $true $SendReport = $true } if (-not (Test-Path -Path $LogFile)) { New-Item -Path $LogFile -ItemType File } if (-not (Test-Path -Path $ReportFile)) { New-Item -Path $ReportFile -ItemType File } } process { $Timestamp = Get-Date -Format 'yyyy.MM.dd. HH:mm:ss:fff' $LogEntry = $Timestamp + &quot; - &quot; + $Message switch ($OperationResult) { 'Success' { $ForegroundColor = 'Green' break } 'Fail' { $ForegroundColor = 'Red' break } 'Partial' { $ForegroundColor = 'Yellow' break } 'Info' { $ForegroundColor = 'Cyan' break } 'None' { $ForegroundColor = 'White' $LogEntry = $Message } } Write-Host $LogEntry -ForegroundColor $ForegroundColor -BackgroundColor Black if ($WriteLog) { Add-content -Path $LogFile -Value $LogEntry } if ($SendReport) { Add-content -Path $ReportFile -Value $LogEntry } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T18:08:38.210", "Id": "485189", "Score": "1", "body": "[1] i would avoid the use of relative paths. that can bite you when the OS & PoSh disagree about the current dir ... and also when the current dir is not what you were expecting. take a look at `$PSScriptRoot`. [2] it looks like you ALWAYS write the two files. if so, why bother with the two $Vars? [3] you seem to ALWAYS write to the screen. i would make that an option that was off by default. your function IS named `Write-Log` ... [*grin*] [4] i would add details in the function about the structure of the CFG file. [5] i would also add Comment Base Help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T19:40:16.827", "Id": "485201", "Score": "1", "body": "If you are writing to the console and want a \"transcript\" of activity then you could just use [Start-Transcript](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-7). Dont forget to use Stop-Transcript to stop it - I would put that in a Finally block." } ]
[ { "body": "<p>I don't see anything wrong or debatable in this so far. Just a couple nitpicks:</p>\n<ul>\n<li><p>I would use parameter splatting to make the color part more compact. For example, from my own log function:</p>\n<pre><code> switch ($Severity) {\n Debug { $colors = @{ForegroundColor=&quot;DarkGray&quot; } }\n Info { $colors = @{ } }\n Warning { $colors = @{ForegroundColor=&quot;Black&quot; ; BackgroundColor=&quot;Yellow&quot; } }\n Error { $colors = @{ForegroundColor=&quot;White&quot; ; BackgroundColor=&quot;DarkRed&quot; } }\n Critical { $colors = @{ForegroundColor=&quot;DarkYellow&quot; ; BackgroundColor=&quot;DarkRed&quot; } }\n }\n\n Write-Host @colors &quot;$($Severity): $Message&quot;\n</code></pre>\n</li>\n</ul>\n<p>Maybe you could go even further with a hash of hashs and do <code>Write-Host @colors[&quot;error&quot;]</code> or something like that.</p>\n<ul>\n<li><p>To create a file only if the file doesn't already exist, you can call <code>New-Item</code> directly, it will throw an exception if the file already exists which you can just ignore with a try-catch or with <code>-ErrorAction SilentlyContinue</code>, saving a couple lines.</p>\n</li>\n<li><p>Why not make all the configuration fetched from the config file optional parameters, with the values in the file as default values ? That would help if you ever have to use the function on the fly, in a shell or as a debug tool.</p>\n</li>\n<li><p>Very personal opinion, but I would personally put the default value of <code>$OperationResult</code> to <code>Info</code>, as this is the most common case for me and I'd appreciate just whipping out a simple <code>Write-Log &quot;mymessage&quot;</code> without extra typing.</p>\n</li>\n<li><p>Last one, this one depends on your environment, but <code>Write-Log</code> is also a function in the officiel VMWare vSphere module that is quite widely used. I wouldn't change any code because of that but remember to document that if you ever have to distribute your code.</p>\n</li>\n</ul>\n<p>Overall I think your cmdlet is pretty readable and produces a log that is easy enough to parse, so it ticks all the important boxes for me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-03T14:34:42.850", "Id": "248870", "ParentId": "247769", "Score": "2" } }, { "body": "<p>I have arrived at a new solution for my log and transcript PowerShell function.</p>\n<pre><code>function Write-Log {\n [CmdletBinding()]\n param (\n [Parameter(Position = 0, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]\n [string]\n $Message,\n\n [Parameter(Mandatory = $false)]\n [switch]\n $NoTimestamp = $false\n )\n\n begin {\n if (Test-Path -Path '.\\Settings.cfg') {\n $Settings = Get-Content '.\\Settings.cfg' | ConvertFrom-StringData\n\n $LogFile = $Settings.LogFile\n $ReportFile = $Settings.ReportFile\n $WriteTranscript = $Settings.WriteTranscript -eq &quot;true&quot;\n $WriteLog = $Settings.WriteLog -eq &quot;true&quot;\n $SendReport = $Settings.SendReport -eq &quot;true&quot;\n }\n else {\n $LogFile = '.\\Log.log'\n $ReportFile = '.\\Report.log'\n $WriteTranscript = $true\n $WriteLog = $true\n $SendReport = $true\n }\n if (-not (Test-Path -Path $LogFile)) {\n New-Item -Path $LogFile -ItemType File\n }\n if ((-not (Test-Path -Path $ReportFile)) -and $SendReport) {\n New-Item -Path $ReportFile -ItemType File\n }\n }\n\n process {\n if (-not($NoTimestamp)) {\n $Timestamp = Get-Date -Format &quot;yyyy.MM.dd. HH:mm:ss:fff&quot;\n $LogEntry = $Timestamp + &quot; - &quot; + $Message\n }\n else {\n $LogEntry = $Message\n }\n\n if ($WriteTranscript) {\n Write-Verbose $LogEntry -Verbose\n }\n if ($WriteLog) {\n Add-content -Path $LogFile -Value $LogEntry\n }\n if ($SendReport) {\n Add-content -Path $ReportFile -Value $LogEntry\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T13:26:51.587", "Id": "251016", "ParentId": "247769", "Score": "0" } } ]
{ "AcceptedAnswerId": "248870", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T10:23:57.170", "Id": "247769", "Score": "4", "Tags": [ "powershell" ], "Title": "Log writing PowerShell function" }
247769
<p>I made a project, that scrapes images asynchronously and saves them in container. I have access to them through volume. Scrapy finds images on given web page.</p> <p>Any tips will be good. But first I would like to focus on docker-compose I would appreciate tips on how to improve it.</p> <h3>files tree</h3> <p>My project looks like that. <code>celery.py</code> for celery config, <code>scrap_images</code> directory for scrapy project. finals images are stored in pictures in one possible directory</p> <pre><code>. ├── celery_test.py ├── docker-compose.yaml ├── image_collector │   ├── celery.py │   ├── ENV_FILE │   ├── image_collector # overlaping │   ├── pictures │   │   ├── big │   │   ├── medium │   │   ├── small │   │   └── tiny │   ├── pipeline.log # scrapy pipeline log │   ├── scrap_images │   │   ├── custom_loger.py │   │   ├── __init__.py │   │   ├── items.py │   │   ├── middlewares.py │   │   ├── pipelines.py │   │   ├── settings.py │   │   └── spiders │   │   ├── image_spider.py │   │   └── __init__.py │   ├── scrapy.cfg │   ├── spider.log # scrapy spider log │   └── tasks.py ├── README.md ├── requirements.txt └── Worker </code></pre> <h3>docker-compose.yaml</h3> <p>I had problem with path, so in docker-compose in <code>Worker</code> I got 2 volumes that overlap to start celery and scrapy from same workdir. I start celery with docker command, and withing same workdir i start scrapy spiders when task is received</p> <pre><code>version: '3.3' services: worker: build: context: . dockerfile: Worker image: collector_worker:3.8.5 environment: - HOSTNAME=broker - PORT=5672 - DB_ACCES_NAME=postgres_db env_file: - ./image_collector/ENV_FILE volumes: - ./image_collector:/app/image_collector - ./image_collector:/app depends_on: - broker restart: always command: bash -c &quot;mkdir -p pictures &amp;&amp; chmod -R 777 pictures &amp;&amp; celery -A image_collector worker --loglevel=info --autoscale=5,1&quot; broker: image: rabbitmq:3.6.6-management hostname: broker restart: always environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=mypass ports: - &quot;5673:5672&quot; - &quot;15673:15672&quot; </code></pre> <h3>Worker</h3> <p>Container that runs celery, and starts spiders in current workdir position</p> <pre><code>FROM python:3.8.5 ENV PYTHONUNBUFFERED 1 COPY requirements.txt /app/requirements.txt WORKDIR /app RUN echo &quot;en_US.UTF-8 UTF-8&quot; &gt; /etc/locale.gen RUN pip install -r requirements.txt </code></pre> <h3>celery.py</h3> <p>Celery configuration to connect with rabbit broker</p> <pre><code>from __future__ import absolute_import, unicode_literals from celery import Celery import os user = os.getenv('LOGIN', 'admin') password = os.getenv('PASSWORD', 'mypass') hostname = os.getenv('HOSTNAME', 'localhost') port = os.getenv('PORT', '5673') broker_url = f'amqp://{user}:{password}@{hostname}:{port}' app = Celery(&quot;tasks&quot;, broker=broker_url, namespace=&quot;image_celery&quot;, include=['image_collector.tasks']) __all__ = (&quot;app&quot;,) </code></pre> <h3>Tasks.py</h3> <p>I start spiders with system command and pass url to scrap that page and process in pipeline</p> <pre><code>#from scrapy.crawler import CrawlerProcess #from .scrap_images.spiders.image_spider import ImageSpider #from scrapy.cmdline import execute from .celery import app import sys import os @app.task def start_spider(url): &quot;&quot;&quot;Task for crawling web&quot;&quot;&quot; os.system(f&quot;python -m scrapy crawl image_spider -a url={url}&quot;) if __name__ == &quot;__main__&quot;: url = r'https://www.wykop.pl/' start_spider(url) </code></pre> <h3>celery_test.py</h3> <p>i send tasks to celery manuall at this moment, nothing special</p> <pre><code>from image_collector.tasks import start_spider for pages in range(1000): url = f'https://memy.jeja.pl/nowe,0,0,3{2216 - pages:&gt;04}.html' start_spider.delay(url=url) </code></pre> <h3>image_spider.py</h3> <pre><code>import scrapy from ..items import ImageItem from ..custom_loger import define_logger class ImageSpider(scrapy.Spider): name = 'image_spider' my_logger = define_logger(&quot;spider&quot;) # allowed_domains = ['www.wikipedia.pl'] def start_requests(self): url = getattr(self, &quot;url&quot;) if url: self.my_logger.debug(f&quot;Starting image parsing at: {url}&quot;) yield scrapy.Request(url=url, callback=self.find_images) else: self.my_logger.error(f&quot;URL is empty&quot;) yield None def parse(self, response): print(f&quot;Parsing: {self.url}&quot;) def find_images(self, response): images = response.css(&quot;img::attr(src)&quot;).extract() item = ImageItem() item['image_urls'] = [] item['title'] = response.css(&quot;title::text&quot;).extract()[0] item['title'] = response.xpath(&quot;//title/text()&quot;).extract()[0] self.my_logger.info(f&quot;Found :{len(images)} images&quot;) for img in images: img = str(img) im_url = img if img.startswith(&quot;http&quot;) else &quot;http:&quot; + img item['image_urls'].append(im_url) self.my_logger.debug(f&quot;Got image: {im_url}&quot;) yield item # def save_images(self, response): # image = ImageItem() # self.my_logger.info(f&quot;Got image: {response.url}&quot;) def err_hanlder(self, failure): url = failure.request.url callback = failure.request.callback errback = failure.request.errback # should work same way as callback... ? # status = failure.value.response.status self.my_logger.error(f&quot;Fail request: @: {url}&quot;) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T10:44:42.663", "Id": "247770", "Score": "3", "Tags": [ "python", "scrapy", "docker" ], "Title": "Microservice for scraping images with celery" }
247770
<p>I have a pivot table of approximately 2 millions lines coming from a dataframe with the same structure as below:</p> <pre><code>raw = pd.DataFrame([[123456,datetime(2020,7,1),'A',10 ], [123456,datetime(2020,7,1),'B',25 ], [123456,datetime(2020,7,1),'C',0 ], [123456,datetime(2020,7,2),'A',17 ], [123456,datetime(2020,7,2),'B',23 ], [123456,datetime(2020,7,2),'C',float('NaN') ], [789012,datetime(2020,7,2),'A',11 ], [789012,datetime(2020,7,2),'B',19 ], [789012,datetime(2020,7,3),'A',8 ], [789012,datetime(2020,7,3),'B',21 ]], columns=['GROUP_ID','DATE', 'NAME', 'VALUE']) GROUP_ID DATE NAME VALUE 0 123456 2020-07-01 A 10.0 1 123456 2020-07-01 B 25.0 2 123456 2020-07-01 C 0.0 3 123456 2020-07-02 A 17.0 4 123456 2020-07-02 B 23.0 5 123456 2020-07-02 C NaN 6 789012 2020-07-02 A 11.0 7 789012 2020-07-02 B 19.0 8 789012 2020-07-03 A 8.0 9 789012 2020-07-03 B 21.0 </code></pre> <p>As you can see, the <code>VALUE</code> column can be <code>Nan</code>. The pivot table is created like this:</p> <pre><code>pt = raw.pivot_table(index=['GROUP_ID', 'DATE'], columns=['NAME'], values=['VALUE']) VALUE NAME A B C GROUP_ID DATE 123456 2020-07-01 10.0 25.0 0.0 2020-07-02 17.0 23.0 NaN 789012 2020-07-02 11.0 19.0 NaN 2020-07-03 8.0 21.0 NaN </code></pre> <p>The idea is to create a level 0 column <code>VALUE_PREV</code> where I can have the value of <code>C</code> for the day before. I first did this, and it took 10 seconds:</p> <pre><code>dfA = pt.stack().unstack(level='DATE').shift(1, axis=1).stack(level='DATE') dfA = dfA[dfA.index.get_level_values('NAME') == 'C'] dfA = dfA.unstack(level='NAME').rename(columns={'VALUE':'VALUE_PREV'}) ptA = pt.merge(dfA, how='outer', on=['GROUP_ID', 'DATE']) VALUE VALUE_PREV NAME A B C C GROUP_ID DATE 123456 2020-07-01 10.0 25.0 0.0 NaN 2020-07-02 17.0 23.0 NaN 0.0 789012 2020-07-02 11.0 19.0 NaN NaN 2020-07-03 8.0 21.0 NaN NaN </code></pre> <p>So I was wondering if there is a quicker way to do this or at least something less heavy to write / understand?</p> <p>Edit : if the <code>VALUE C</code> is <code>NaN</code> at t, <code>VALUE_PREV C</code> at t+1 MUST be <code>NaN</code> and not 0</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T15:11:40.643", "Id": "485172", "Score": "0", "body": "You might have an XY problem, why do you want the C value of the previous day? Will you also want to do the same thing for A and B values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T15:36:26.130", "Id": "485175", "Score": "0", "body": "Because at some point after i will calculate the difference between both. I don't do the same for A et B. And thanks i didn't know this XY thing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T15:44:11.193", "Id": "485176", "Score": "2", "body": "Do you mean `pt[(\"VALUE_PREV\",\"C\")] = pt[\"VALUE\"].groupby(level=0)[\"C\"].shift()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:02:42.343", "Id": "485177", "Score": "0", "body": "It works well on my example but when i do it on the big pivot table i have less line on `ptA` than after the merging with my version, it seems that the first line with `dfa` create some lines that was not there before. I have to check if those line are important for my calculations after. But it's super fast !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:49:29.310", "Id": "485401", "Score": "0", "body": "@Henry Yik I did my check and the problem with your solution is that if `VALUE C` is `NaN` then `VALUE_PREV C` will be 0 then it will create some problem because if `VALUE C` of the same line is not `NaN`, it will do `x - 0 = x` instead of `x - NaN = NaN` and it will change the final value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T13:22:29.537", "Id": "486546", "Score": "3", "body": "Please do not update the question to invalidate answers. Whilst it is unfortunate that you didn't explain the entire situation when you first posted, it's unfair to answerers to have their hard work invalidated because of a mistake that was not theirs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-25T13:34:19.270", "Id": "486552", "Score": "0", "body": "I wanted to avoid to post a very close question of this one but i'll do it, thanks" } ]
[ { "body": "<p>IIUC you can check for your conditions with <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.where.html\" rel=\"nofollow noreferrer\"><code>pd.Series.where</code></a>:</p>\n<pre><code>pt = raw.pivot_table(index=['GROUP_ID', 'DATE'], columns=['NAME'], values=['VALUE'])\n\ns = pt[&quot;VALUE&quot;].groupby(level=0)[&quot;C&quot;].shift()\n\npt[(&quot;VALUE_PREV&quot;,&quot;C&quot;)] = s.where(s.notnull(), np.NaN)\n\nprint (pt)\n\n VALUE VALUE_PREV\nNAME A B C C\nGROUP_ID DATE \n123456 2020-07-01 10.0 25.0 0.0 NaN\n 2020-07-02 17.0 23.0 NaN 0.0\n789012 2020-07-02 11.0 19.0 NaN NaN\n 2020-07-03 8.0 21.0 NaN NaN\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T18:17:11.540", "Id": "485534", "Score": "0", "body": "thanks, i have to wait one day to give you the bounty" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T15:43:27.980", "Id": "247910", "ParentId": "247777", "Score": "3" } } ]
{ "AcceptedAnswerId": "247910", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T14:26:35.380", "Id": "247777", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Get the value of the precedent day in a pivot table" }
247777
<p>This is my first ever c# script. I have played around a little and I think this is some proper c# code. Since it's my very first c# ever, I'm assuming there's a few mistakes, things that could be better, bad conventions and such. If you see any, please let me know so I can improve!</p> <pre><code>using System.Collections; using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class Mover : MonoBehaviour { [SerializeField] GameObject target; private GameObject player; // creating a variable for the player object void Update() { if (target != null) { // if the target is already destroyed, we don't have to do anything anymore player = this.gameObject; // the script is attached to the player // Here I expected I could get the NavMeshAgent component via something like player.NavMashAgant. // I do the same later for target.transform. // Is there a reason this component is not accessible via dot notation? GetComponent&lt;NavMeshAgent&gt;().destination = target.transform.position; // set the players destination as the targets potion. It starts moving automatically. if (AreClose(player, target)) { Destroy(target); } } } private static double Distance(GameObject a, GameObject b) { Vector3 aPos = a.transform.position; Vector3 bPos = b.transform.position; // A really long line.. What is the convention to make this more readable? return Math.Sqrt(Math.Pow(aPos.x - bPos.x, 2) + Math.Pow(aPos.y - bPos.y, 2) + Math.Pow(aPos.z - bPos.z, 2)); } private static bool AreClose(GameObject a, GameObject b) { double result = Distance(a, b); if (result &lt; 2.5) // random magic number for now { return true; } else { return false; } } } </code></pre>
[]
[ { "body": "<p>Unity has built in support for measuring distance. If I remember correctly it would look something like this.</p>\n<pre><code>return (a.transform.position-b.transform.position).Length\n</code></pre>\n<p>You could also save on performance by squaring the radius to check instead of <code>sqrt</code> ing the distance.</p>\n<p>Branches are uneccessary in this function.</p>\n<pre><code>private static bool AreClose(GameObject a, GameObject b)\n{\n return Distance(a, b) &lt; 2.5;\n}\n</code></pre>\n<p>The unity inspector has really good support for editing primitive variables if you make them public.</p>\n<pre><code>public class Mover : MonoBehaviour\n{\n public float destroyRadius = 2.5f;\n...\n</code></pre>\n<pre><code>GetComponent&lt;NavMeshAgent&gt;()\n</code></pre>\n<p>GetComponent is kind of slow. Assigning it in <code>Start()</code> would help performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:11:06.787", "Id": "247780", "ParentId": "247779", "Score": "0" } }, { "body": "<p>Welcome to Code Review!</p>\n<p>I'm not too familiar with Unity, so I can't really comment or offer advice on Unity-specific things.</p>\n<p>There are still a few places where I feel like your code could be improved however.</p>\n<h1>Whitespace</h1>\n<p>While I generally prefer to keep my code not too dense, I recommend never having more than one blank line in a row (except <em>maybe</em> if you want to separate a block of imports or <code>using</code>s from the rest of the code); some editors will even automatically remove any consecutive blank lines when you format your document.</p>\n<p>Similarly, that blank line at the end of your <code>Distance()</code> method doesn't serve any purpose, so I would just remove it, or maybe move it right below your <code>aPos</code> and <code>bPos</code> declarations.</p>\n<h1><code>AreClose()</code> method</h1>\n<p>Your <code>AreClose()</code> method could be rewritten in a much shorter and cleaner way, like so :</p>\n<pre><code>private static bool AreClose(GameObject a, GameObject b)\n{\n double result = Distance(a, b);\n return (result &lt; 2.5); // random magic number for now\n}\n</code></pre>\n<p>That's because the expression <code>result &lt; 2.5</code> itself evaluates to a boolean, so there's no need to check whether its value true or false, you can simply return it.</p>\n<p>You could further shorten it to...</p>\n<pre><code>private static bool AreClose(GameObject a, GameObject b)\n{\n return Distance(a, b) &lt; 2.5; // random magic number for now\n}\n</code></pre>\n<p>...since, in my opinion, the variable <code>result</code> doesn't add anything to the readability or the clarity of the code. Seeing <code>Distance(a, b) &lt; someMagicNumber</code> is clear enough on its own.</p>\n<p>You could go even further and take advantage of C#'s expression body definitions, like so</p>\n<pre><code>private static bool AreClose(GameObject a, GameObject b) =&gt; Distance(a, b) &lt; 2.5; // random magic number for now\n</code></pre>\n<p>...which doesn't look too great here because of that comment. I would recommend you put that magic number into a <code>const</code> variable, either declared inside <code>AreClose()</code> or as a class variable. This will make your code easier to modify in the future, and also allows you to give it a meaningful name like <code>MIN_DISTANCE</code>.</p>\n<pre><code>private static bool AreClose(GameObject a, GameObject b) =&gt; Distance(a, b) &lt; MIN_DISTANCE;\n</code></pre>\n<h1><code>Distance()</code> method</h1>\n<p>Like I said earlier, I'm not too familiar with Unity, but I'm pretty sure it has a built-in method for computing the distance between two vectors, like so <code>Vector3.Distance(aPos, bPos)</code>.</p>\n<p>There's nothing inherently wrong with doing it yourself if you're just trying to learn and get familiar with a new language or concept, but if you're looking for optimal performance or accuracy, I would recommend making sure there isn't already a function that does what you need before trying to reinvent the wheel -although in this specific case it's probably not too important.</p>\n<p>Additionally, I would avoid using <code>Math.Pow()</code> when you only want to square a number, as it's quite an expensive operation compared to simply doing <code>(aPos.x - bPos.x) * (aPos.x - bPos.x)</code>. This is because <code>Math.Pow()</code> needs to be able to handle non-integer exponents and (probably) uses Taylor series (<a href=\"https://en.wikipedia.org/wiki/Taylor_series\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Taylor_series</a>) to compute powers for arbitrary exponents, even if your exponent happens to be <code>2</code>. So you can just compute the square yourself, which should significantly improve performance.</p>\n<p>You could also create a <code>DistanceSquared()</code> method, and compare it with <code>MIN_DISTANCE * MIN_DISTANCE</code>, which is equivalent to comparing <code>Distance()</code> and <code>MIN_DISTANCE</code>. This allows you to avoid using <code>Math.Sqrt()</code>, which is, again, a rather slow operation. Then you can rewrite <code>Distance()</code> like this, if you still want it :</p>\n<pre><code>public static double Distance(GameObject a, GameObject b) =&gt; Math.Sqrt(DistanceSquared(a, b));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T17:07:51.487", "Id": "485185", "Score": "0", "body": "I understand everything you've said except the last part. I understand the usecase for a `DistanceSquared` and it leading to not needing to use `Math.Sqrt`. However, in the last example you use `Math.Sqrt` anyway. Am I misunderstanding after all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T17:13:24.437", "Id": "485186", "Score": "1", "body": "I simply meant that, if you still want to have a `Distance()` method in addition to `DistanceSquared()` (maybe you want to draw a circle around your `Mover` that shows its range, who knows?), you can make it so just returns the square root of `DistanceSquared()`, without having to reimplement all the calculations already done in `DistanceSquared()`. Is that clear? In short, don't rewrite code you're already written." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T16:36:53.517", "Id": "247782", "ParentId": "247779", "Score": "1" } } ]
{ "AcceptedAnswerId": "247782", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T15:38:13.943", "Id": "247779", "Score": "2", "Tags": [ "c#", "unity3d" ], "Title": "C# and unity. Moving an object to a target and destroy target once we're close" }
247779
<p>This program will ask for user to insert summoner and base from the last 20 games of said summoner, it will give avg stats and see if good or not by wins in last 20 games(a simple grading system).</p> <pre><code>import requests from getId import idcollect from games import GAME from wins import win_calc #Key for riot API Key = '**********************' #ASKING USER FOR SUMMONER NAME summonerName = input('Enter summoner name:') #Objects ids=idcollect() game=GAME() wins=win_calc() #Collecting the acc id of summoner name accId=ids.ID_collected(summonerName,Key) #Collecting game id lists game_list=[] game_list=game.find_game_ids(accId,Key) #Collecting wins list win_list=[] win_list=game.game_data(game_list,Key,summonerName) #Calcuate whether the summoner is good or not wins.is_dis_mane_good(win_list) </code></pre> <pre><code>import requests class GAME: def find_game_ids(self,accId,key): i=0 GAMEID = [] Idgame=20 url_match_list=('https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/'+(accId)+'?queue=420&amp;endIndex=20&amp;api_key='+(key)) response2=requests.get(url_match_list) #Adding 20 games into the list while Idgame&gt;0: GAMEID.append('https://na1.api.riotgames.com/lol/match/v4/matches/'+str(response2.json()['matches'][i]['gameId'])+'?api_key='+(key)) i=i+1 Idgame=Idgame-1 return GAMEID def game_data(self,game_list,key,sumName): wins=[] deaths=[] deaths= [] kills=[] assists=[] visions=[] csTotal=[] #Finding the data of said summoner in each game id for urls in game_list: response=requests.get(urls) Loop=0 index=0 while Loop&lt;=10: if response.json()['participantIdentities'][index]['player']['summonerName']!=sumName: Loop= Loop+1 index=index+1 elif response.json()['participantIdentities'][index]['player']['summonerName']==sumName: deaths.append(response.json()['participants'][index]['stats']['deaths']) kills.append(response.json()['participants'][index]['stats']['kills']) assists.append(response.json()['participants'][index]['stats']['assists']) visions.append(response.json()['participants'][index]['stats']['visionScore']) csTotal.append(response.json()['participants'][index]['stats']['totalMinionsKilled']) wins.append(response.json()['participants'][index]['stats']['win']) break #Finding avg of each stat deaths=sum(deaths)/20 kills=sum(kills)/20 assists=sum(assists)/20 visions=sum(visions)/20 csTotal=sum(csTotal)/20 print('The avg kills is '+str(kills)+'\nThe avg deaths is '+str(deaths)+'\nThe avg assists is '+str(assists)+'\nThe avg visions is '+str(visions)+'\nThe avg cs total is '+str(csTotal)) return wins </code></pre> <pre><code>import requests class idcollect: def ID_collected(self,sumName,key): #COLLECTING DATA TO BE INSERTING FOR MATCHLIST DATABASE url=('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+(sumName)+'?api_key='+(key)) response=requests.get(url) accId=(response.json()['accountId']) return accId </code></pre> <pre><code>import random class win_calc: def is_dis_mane_good(self,winlist): winlist=sum(winlist)/20 if (winlist&lt;.33): trash=['DIS MANE STINKS','run while you can','I repeat, YOU ARE NOT WINNING THIS','I predict a fat L','Have fun trying to carry this person','He is a walking trash can','He needs to find a new game','BAD LUCK!!!'] print (random.choice(trash)) elif (winlist&gt;.33 and winlist&lt;=.5): notgood=['Losing a bit','Not very good','He needs lots of help','Your back might hurt a little','Does not win much'] print (random.choice(notgood)) elif (winlist&gt;.5 and winlist&lt;=.65): ight=['He is ight','He can win a lil','You guys have a decent chance to win','Serviceable','Should be a dub'] print (random.choice(ight)) elif (winlist&gt;.65): good=['DUB!','You getting carried','His back gonna hurt a bit','winner winner chicken dinner','Dude wins TOO MUCH','You aint even gotta try','GODLIKE'] print (random.choice(good)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T05:48:55.490", "Id": "485229", "Score": "1", "body": "Welcome to Code Review. I've replaced the title with a more fitting description of your program. Feel free to [edit] your post to include your concerns into the post text; the title should simply state what your program is about, not your concerns. I hope you get some nice reviews :)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:07:03.113", "Id": "485293", "Score": "0", "body": "You forgot to mention that this is a revised version of https://codereview.stackexchange.com/questions/247554/player-data-collection-program/247598. Additionally, there are things you haven't done, like, making your code PEP8 compliant, which were refered in the other post." } ]
[ { "body": "<p><code>find_game_ids</code> is far more complicated than it needs to be. You have essentially two &quot;counters&quot;, <code>Idgame</code> and <code>i</code>. One is being used to be placed in a string, and the other is to limit how many loops happen, but they're the same value if you think about it; just opposites. You don't need <code>Idgame</code> since you can just check if <code>i &lt; 20</code>. You also don't need to manually manage <code>i</code>. <code>range</code> is for use-cases exactly like this:</p>\n<pre><code>def find_game_ids(self, accId, key):\n game_id = []\n url_match_list = f&quot;https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/{accId}?queue=420&amp;endIndex=20&amp;api_key={key}&quot;\n response2 = requests.get(url_match_list)\n for i in range(20):\n game_id.append(f&quot;https://na1.api.riotgames.com/lol/match/v4/matches/{response2.json()['matches'][i]['gameId']}?api_key={key}&quot;\n\n return game_id\n</code></pre>\n<p><code>i</code> here will be every number from <code>0</code> to <code>19</code>. I would also recommend creating a variable elsewhere to hold the <code>20</code> and call in <code>N_GAMES</code> or something. You seem to use that <code>20</code> in multiple spots. If you change it in one place and forget to change it somewhere else, you'll potentially have a nasty bug.</p>\n<p>Other things I changed:</p>\n<ul>\n<li>Variable names should be lowercase, separated by underscores according to <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP8</a>. You have names all around this file that inconsistently use Upper_case. Use lower_case unless you're naming a class name.</li>\n<li>Instead of adding string together using <code>+</code>, I changed it to use f-strings (note the <code>f</code> before the quotes). That lets you put a variable directly into a string using the <code>{variable_name}</code> syntax.</li>\n</ul>\n<p>This can be further improved though. If you're iterating to create a list like you are here, list comprehensions can sometimes be cleaner:</p>\n<pre><code>def find_game_ids(self, accId, key):\n url_match_list = f&quot;https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/{accId}?queue=420&amp;endIndex=20&amp;api_key={key}&quot;\n response2 = requests.get(url_match_list)\n \n return [f&quot;https://na1.api.riotgames.com/lol/match/v4/matches/{response2.json()['matches'][i]['gameId']}?api_key={key}&quot;\n for i in range(20)]\n</code></pre>\n<p>The major readability problem in each case stems from how long that string is. You may want to break it over multiple lines, or generate it outside of the function using another function.</p>\n<hr />\n<p>In <code>game_data</code>, you're calling <code>response.json()</code> <em>repeatedly</em>. Looking over the <a href=\"https://requests.readthedocs.io/en/master/_modules/requests/models/#Response.json\" rel=\"nofollow noreferrer\">source of that method</a>, it does <em>not</em> appear to do any caching. That means that every call to <code>.json</code> will reparse the data, which is a waste of CPU time. Save that into a variable once and use it as needed:</p>\n<pre><code>def game_data(self, game_list, key, sumName):\n . . .\n for urls in game_list:\n\n response = requests.get(urls)\n resp_json = response.json() # Save it to use it again later\n Loop = 0\n index = 0\n while Loop &lt;= 10:\n\n if resp_json['participantIdentities'][index]['player']['summonerName'] != sumName:\n Loop = Loop + 1\n index = index + 1\n elif resp_json['participantIdentities'][index]['player']['summonerName'] == sumName:\n\n deaths.append(resp_json['participants'][index]['stats']['deaths'])\n kills.append(resp_json['participants'][index]['stats']['kills'])\n assists.append(resp_json['participants'][index]['stats']['assists'])\n visions.append(resp_json['participants'][index]['stats']['visionScore'])\n csTotal.append(resp_json['participants'][index]['stats']['totalMinionsKilled'])\n wins.append(resp_json['participants'][index]['stats']['win'])\n\n . . .\n</code></pre>\n<p>Not only is that shorter, it also makes it easier to add in some preprocessing to the data later, and also has the potential to be much faster, because you aren't doing the same processing over and over again.</p>\n<hr />\n<pre><code>#Finding avg of each stat\ndeaths=sum(deaths)/20 \nkills=sum(kills)/20\nassists=sum(assists)/20\nvisions=sum(visions)/20\ncsTotal=sum(csTotal)/20\n</code></pre>\n<p>Like I said, you're using <code>20</code> in multiple places. What if you want to change this number later? It's not going to be fun to go around and find every <em>relevant</em> <code>20</code> and update it to the new value.</p>\n<p>Have that number stored once, and use that variable:</p>\n<pre><code># Top of file by imports\nN_GAMES = 20\n\n. . .\n\n# The for-loop in the updated find_game_ids\nfor i in range(N_GAMES):\n\n. . .\n\n# At the bottom of game_data\ndeaths=sum(deaths)/N_GAMES \nkills=sum(kills)/N_GAMES\nassists=sum(assists)/N_GAMES\nvisions=sum(visions)/N_GAMES\ncsTotal=sum(csTotal)/N_GAMES\n</code></pre>\n<hr />\n<p>For the classes <code>win_calc</code> and <code>id_collect</code>, there a few noteworthy things.</p>\n<p>First, they shouldn't be classes. A good indicator that you shouldn't be using a class is that you're never using <code>self</code> in any of its methods. By using a class in this case, you need to construct an empty object just to call a method on it, which you're doing here:</p>\n<pre><code>wins=win_calc()\n</code></pre>\n<p>Just to call a method on it later:</p>\n<pre><code>wins.is_dis_mane_good(win_list)\n</code></pre>\n<p>Just make those classes plain functions:</p>\n<pre><code>import random\n\ndef is_dis_mane_good(winlist):\n\n winlist = sum(winlist) / 20\n\n if (winlist &lt; .33):\n trash = ['DIS MANE STINKS', 'run while you can', 'I repeat, YOU ARE NOT WINNING THIS', 'I predict a fat L',\n 'Have fun trying to carry this person', 'He is a walking trash can', 'He needs to find a new game',\n 'BAD LUCK!!!']\n print(random.choice(trash))\n . . .\n</code></pre>\n<p>And then just use them as plain functions:</p>\n<pre><code>is_dis_mane_good(win_list)\n</code></pre>\n<p>Second, if it were appropriate to have them as classes, the names should be in CapitalCase: <code>WinCalc</code> and <code>IDCollect</code> (or maybe <code>IdCollect</code>).</p>\n<hr />\n<p>Also, I'd rename <code>is_dis_mane_good</code>. Using a slang in the output of the program is one thing, but naming your methods obscure names isn't doing yourself or other readers of your code any favors.</p>\n<p>As well in that function, I'd make some more changes:</p>\n<ul>\n<li><p>I suggest you prefix your decimal numbers with a <code>0</code>. <code>0.33</code> is much more readable than <code>.33</code>.</p>\n</li>\n<li><p>You can use operator chaining to simplify those checks too. <code>winlist &gt; 0.33 and winlist &lt;= 0.5</code> can become <code>0.33 &lt; winlist &lt;= 0.5</code>. As noted in the comments though, you can actually get rid of half of each check since, for example, if <code>winlist &lt; 0.33</code> was false, then you know <code>winlist</code> must be greater than <code>0.33</code>, so the <code>winlist &gt; 0.33</code> check is redundant.</p>\n</li>\n<li><p>There's that <code>20</code> again ;). The more places you have it, the more likely you are to forget to update at least one of them. I'd use <code>N_GAMES</code> there instead.</p>\n</li>\n<li><p>You can get rid of the duplicated <code>print(random.choice(. . .))</code> calls by assigning the list to a variable after each check, then having one <code>print</code> at the bottom.</p>\n</li>\n</ul>\n<p>After those changes, I'm left with this:</p>\n<pre><code>def competency_message(winlist):\n winlist = sum(winlist) / N_GAMES\n\n message_set = []\n if winlist &lt; 0.33: # Should be winlist &lt;= 0.33 maybe?\n message_set = ['DIS MANE STINKS', 'run while you can', 'I repeat, YOU ARE NOT WINNING THIS', 'I predict a fat L',\n 'Have fun trying to carry this person', 'He is a walking trash can', 'He needs to find a new game',\n 'BAD LUCK!!!']\n\n elif winlist &lt;= 0.5:\n message_set = ['Losing a bit', 'Not very good', 'He needs lots of help', 'Your back might hurt a little',\n 'Does not win much']\n\n elif winlist &lt;= 0.65:\n message_set = ['He is ight', 'He can win a lil', 'You guys have a decent chance to win', 'Serviceable',\n 'Should be a dub']\n\n else:\n message_set = ['DUB!', 'You getting carried', 'His back gonna hurt a bit', 'winner winner chicken dinner',\n 'Dude wins TOO MUCH', 'You aint even gotta try', 'GODLIKE']\n\n print(random.choice(message_set))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T01:36:21.173", "Id": "485213", "Score": "1", "body": "Thx all these tips are really helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:18:24.107", "Id": "485279", "Score": "0", "body": "Note that you can also remove a bit of duplication in that `if/elif` structure, by writing it as `if winlist < 0.33: ... elif winlist <= 0.5: ... elif winlist <= 0.65: ...` etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T13:37:45.877", "Id": "485286", "Score": "1", "body": "@canton7 Updated, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T13:39:39.517", "Id": "485287", "Score": "0", "body": "Ah, I meant e.g. `elif 0.5 < winlist <= 0.65` could be `elif winlist <= 0.65`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T13:44:32.513", "Id": "485289", "Score": "1", "body": "@canton7 Whoops, sorry, just woke up. Updated and added some explanation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T00:38:05.167", "Id": "247790", "ParentId": "247788", "Score": "13" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-11T22:45:36.510", "Id": "247788", "Score": "8", "Tags": [ "python", "game", "api" ], "Title": "League of Legends Summoner Analysis" }
247788
<p>I am currently practising using the SOLID principles in C#/.NET</p> <p>I have made a little example, but i am not sure if i have followed it correct. Its a simple example where i have an API controller that calls a method to get a list of users from an database and returned as DTOs.</p> <p>To use the method i need to submit an IUserReader that is mainly doing the reading operation from the database and then a IMapper object is needed that will handle the mapping from database entity to DTO.</p> <p>I made it that way to be available to switch out the IUserReader and IMapper so i can fit the query and mapping to match my requirements for a specific API call. Lets say an app is using the API to get users, the app will only need some details of the user, so we use a implementation that only selects the required information and maps it correct. We also have an backend to view the users, where we want all the user details from the database, here we use another implementation for that.</p> <p>Here is my code example, i would like to know if it is done correct.</p> <p>Data readers</p> <pre><code>public interface IDataReader&lt;T&gt; { IEnumerable&lt;T&gt; Read(); } public abstract class DataReader&lt;T&gt; : IDataReader&lt;T&gt; { private protected IDataContext _context; public abstract IEnumerable&lt;T&gt; Read(); public DataReader(IDataContext context) { _context = context; } } public interface IUserDataReader : IDataReader&lt;IUserEntity&gt; { } //First implementation of user reader public class UserDataReader : DataReader&lt;IUserEntity&gt;, IUserDataReader { public UserDataReader(IDataContext context) : base(context) { } public override IEnumerable&lt;IUserEntity&gt; Read() { return _context.Users.Where(x =&gt; x.IsActive).OrderBy(x =&gt; x.Name).ToList(); } } //Secound implementation of user reader public class UserGridDataReader : DataReader&lt;IUserEntity&gt;, IUserDataReader { public UserGridDataReader(IDataContext context) : base(context) { } public override IEnumerable&lt;IUserEntity&gt; Read() { return _context.Users.OrderBy(x =&gt; x.Name).ToList(); } } </code></pre> <p>Now the mappers:</p> <pre><code>public interface IMapper&lt;I, O&gt; { O Map(I item); } public interface IUserMapper : IMapper&lt;IUserEntity, UserDTO&gt; { } public class UserMapper : IUserMapper { public UserDTO Map(IUserEntity item) { return new FullUserDTO { Name = item.Name, Email = item.Email }; } } </code></pre> <p>The API then calls this class and method to read:</p> <pre><code>public class UserReaderService { private IUserDataReader _reader; private IUserMapper _mapper; public UserReaderService(IUserDataReader reader, IUserMapper mapper) { _reader = reader; _mapper = mapper; } public IEnumerable&lt;UserDTO&gt; Read() { IEnumerable&lt;IUserEntity&gt; userData = _reader.Read(); IEnumerable&lt;UserDTO&gt; users = userData.Select(x =&gt; _mapper.Map(x)); return users; } } </code></pre> <p>API method:</p> <pre><code> public void GetUsers() { IDataContext context = new DataContext(); IUserDataReader userDataReader = new UserDataReader(context); IUserMapper mapper = new UserMapper(); UserReaderService ur = new UserReaderService(userDataReader, mapper); ur.Read(); } </code></pre> <p>Is that correctly using SOLID principles and generally abstraction? Could i throw the IMapper dirrectly into the DataReader and make the mapping directly in the linq query instead of first returning the data result and then use mapping or would it break the SOLID principles?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:12:38.847", "Id": "485246", "Score": "0", "body": "Do not add the `IMapper` directly to the `DataReader` because you then give the `DataReader` 2 functions (*breaking S*), reading data and mapping it to the DTO. your `DataReader` is used to read the data. DTOs are created just before sending it over the wire. If your `GetUsers()` is within a controller you should inject `IDataContext`, `IUserDataReader`, `IUserMapper` using DI via the controller constructor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:26:02.897", "Id": "485248", "Score": "0", "body": "@CobyC Thanks for the comment. I was pretty sure too that it would break the SOLID, if i moved the mapper.\n\nNormally i would use dbContext.Where(...).Select(x => MAP(x)) to grap data and ensure the query only selects the needed columns, but with this example i can't control the query unless i return it as IQueryable and then make the mapper add the Select() to it, but to me that sounds like bad pratice.\n\nLets say i want to select all users like i do in UserGridDataReader but i only want the name column to be selected, do i create a new DataReader then? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:37:50.920", "Id": "485253", "Score": "1", "body": "You can create `UserGridDataReader : DataReader<IUserEntity>, IUserGridDataReader` where `IUserGridDataReader` will inherit from `IUserDataReader` where `IUserGridDataReader` has the required implementation for eg. `ReadUserNamesOnly()`. (*the O part*)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T21:33:47.917", "Id": "485318", "Score": "0", "body": "@CobyC Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:27:22.553", "Id": "485343", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>I suppose the simplest thing is to go through the principles:</p>\n<ul>\n<li>SRP - Cannot see any 'too big' things in your example</li>\n<li>OCP - The example is small enough and you are not using class\ninheritance that I cannot think of how this would apply</li>\n<li>LSP - You only have one implementation of each interface so hard to\nsay</li>\n<li>ISP - Your interfaces seem to serve a single purpose that might serve\nthe needs of several users - so no complaints there</li>\n<li>DIP - You have pushed the more variable 'decision' making out,\nkeeping the API more abstract which seems reasonable.</li>\n</ul>\n<p>Much of this, of course, depends on your specific aims and requirements. some thoughts:</p>\n<ul>\n<li>How likely is it that the mapper and reader will vary independently?</li>\n<li>Are you going to get any reuse out of all the different readers and mappers (actual not future-proofing)</li>\n<li>Will each reader have a mapper in practice, in which case your comment about combining the mapper and reader is worth more thought.</li>\n<li>Do you really need an interface for the reader, it seems like you are just wrapping what could be a function/lambda</li>\n<li>What is the motivation in restricting the outbound data?</li>\n<li>I appreciate this may just be an exercise, but it's good practice to think if you need to do this kind of restriction</li>\n</ul>\n<p>It can be difficult to have a good instinct for principles like SOLID on toy problems due to the lack of realistic constraints and compromises.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:42:45.600", "Id": "485254", "Score": "0", "body": "Thank you ! Great response, it gave me some great thoughts about how to handle things.\n\nCan you explain what you mean by: What is the motivation in restricting the outbound data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:49:15.900", "Id": "485255", "Score": "0", "body": "I agree with the reader having a function or lambda. The reader could easily have a function eg `IEnumerable<T> ReadExpression(Expression<Func<T, bool>> expression)` adding a lot more flexibility to the `DataReader`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T15:08:21.157", "Id": "485829", "Score": "0", "body": "What is the motivation in restricting the outbound data? Basically: What requirement(s) are driving this? Security, minimising payload size, etc. I try to periodically reality check is something is required at all" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:29:27.510", "Id": "247799", "ParentId": "247794", "Score": "13" } }, { "body": "<p>IMO returning <code>IEnumerable&lt;T&gt;</code> from an API is a violation of &quot;L&quot;, as running GetEnumerator() a second time (or <code>foreach</code>, or <code>Count()</code>) behaves differently for different kinds of <code>IEnumerable&lt;T&gt;</code>s. It may fail, run forever, or have expensive side-effects (like running a database query).</p>\n<p>Instead commit to returning an in-memory collection, and type the API as <code>ICollection&lt;T&gt;</code>, or <code>IList&lt;T&gt;</code>, or return <code>IQueryable&lt;T&gt;</code> and make the caller decide how to structure and when to execute the query.</p>\n<p>And given the uncertainty about the behavior of the returned <code>IEnumerable&lt;T&gt;</code>, the calling code has little choice but to immediately call <code>.ToList()</code> on the <code>IEnumerable&lt;T&gt;</code>, often creating a second copy of the collection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T21:49:19.037", "Id": "485319", "Score": "3", "body": "Great considerations about returning `IEnumerable<>`. I have often struggled with whether to go with the (IMO) least derived `IEnumerable<>` or `IList<>`/`ICollection<>`. The boundary for List vs Collection to me is if the item order matters, but this gives me some tests to perform when I'm considering `IEnumerable`. +1!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:49:15.227", "Id": "485346", "Score": "2", "body": "Returning `IEnumerable` has nothing to do with violating LSP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:58:26.273", "Id": "485418", "Score": "1", "body": "Technically it's probably IEnumerable<T> that violates LSP, as you can't substitute a infinite streaming `IEnumberable<T>` for a `List<T>`. The point is that `IEnumerable<T>` is to abstract to expose in an API as you need to know additional information about it to write correct programs. System.IO.Stream has similar problems, but comes with `CanRead`, `CanSeek`, etc methods you can use to interrogate the stream capabilities." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T06:21:50.563", "Id": "485466", "Score": "0", "body": "Why couldn't you? The `IEnumerable<T>` says nothing about the implementation detail, and without providing any further information on a method directly, should a parent method returning an infinite stream with an `IEnumerable<T>` return type be substituted for a child instead returning an instance of `List<T>`, the program will still execute just fine, you can run foreach over the collection, call the extension methods,... That is, as I have said, unless the parent method provides a distinct warning, that an infinite stream must always be returned. Then sure, you would break the LSP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T10:45:15.560", "Id": "485482", "Score": "0", "body": "If an infinite stream is substituted for a List, calling code that runs .ToList() may start failing with an OutOfMemoryException, and code that calls .Count() will never terminate." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T18:20:20.413", "Id": "247821", "ParentId": "247794", "Score": "6" } }, { "body": "<p><em>As requested, I moved my comments into an answer.</em></p>\n<p>Do not add the <code>IMapper</code> directly to the <code>DataReader</code> because you then give the <code>DataReader</code> 2 purposes (<em>breaking <strong>S</strong></em>):<em>Reading data <strong>and</strong> mapping it to the DTO</em>.</p>\n<p>Your <code>DataReader</code> is used to read the data. <em>DTOs</em> are created just before sending it over the wire.</p>\n<p>If your <code>GetUsers()</code> is within a controller you should inject <code>IDataContext</code>, <code>IUserDataReader</code>, <code>IUserMapper</code> using DI via the controller constructor.</p>\n<p>If you use DI then you can create an interface for the <code>UserReaderService</code> and only inject that into your controller constructor, the DI container will resolve the constructor for your <code>UserReaderService</code> and your controller constructor will only take 1 constructor parameter.</p>\n<p>the question in your comment:</p>\n<blockquote>\n<p><em>Lets say i want to select all users like i do in UserGridDataReader</em>\n<em>but i only want the name column to be selected, do i create a new</em>\n<em>DataReader then?</em></p>\n</blockquote>\n<p>You can create <code>UserGridDataReader : DataReader&lt;IUserEntity&gt;, IUserGridDataReader</code> where <code>IUserGridDataReader</code> will inherit from <code>IUserDataReader</code> and <code>IUserGridDataReader</code> has the required implementation, for eg. <code>ReadUserNamesOnly()</code>. (<em>the <strong>O</strong> part</em>).</p>\n<p>Keep in mind you don't want to create an interface for each additional read function, that would be stepping towards <strong>not</strong> keeping things <strong>DRY</strong>.</p>\n<p>You could add a method to the <code>DataReader</code> that has the signature of <code>IEnumerable&lt;T&gt; ReadExpression(Expression&lt;Func&lt;T, bool&gt;&gt; expression)</code> giving the <code>DataReader</code> more flexibility but still staying within the <strong>S</strong> principal.</p>\n<p>The <code>DataReader</code> still just has one purpose of just <em><strong>reading</strong></em> data.</p>\n<p>@Jamie Stevensons answer is great for determining SOLID, but like he said it is a pretty small example to really test the constraints.</p>\n<p>The only other thing I noticed is that your <code>GetUsers()</code> API call returns <code>void</code> this should probably be <code>IEnumerable&lt;UserDTO&gt;</code> or <code>List&lt;UserDTO&gt;</code> unless the code was copied from a <em>Test</em> where you should have something like an <code>Assert.</code> or some indication that it was a test.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T10:58:09.793", "Id": "248030", "ParentId": "247794", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T08:04:35.063", "Id": "247794", "Score": "7", "Tags": [ "c#", ".net", "asp.net", "asp.net-web-api" ], "Title": "C# Am I using proper SOLID principles?" }
247794
<p>so I am playing with Rawg.io 's API. U can sort their game list by their release date, however there are just too many games. In their website, there's an option called &quot;Popular only&quot;, which only shows games that are being followed by at least 1 people.</p> <p>I implemented this feature by sorting the elements I get and creating a sorted list. I wanted to make sure that I would also acces their information in a systematically way ([game's number], [name or other topic]).</p> <p>(the ##delete## parts are parts that are just for console visuals, I am planning to move this project to a Kivy app, so won't need them later)</p> <p>I really want to know what I could have done differently. What's obnoxious, stupid, ... could be better?</p> <pre><code>import requests ######Delete######### import os os.system(&quot;cls&quot;) ################### #### Functions def _Url(year1, month1, day1, year2, month2, day2, PageNumber=1): if month1 &lt; 10: month1 = &quot;0&quot; + str(month1) if day1 &lt; 10: day1 = &quot;0&quot; + str(day1) if month2 &lt; 10: month2 = &quot;0&quot; + str(month2) if day2 &lt; 10: day2 = &quot;0&quot; + str(day2) Url = ( &quot;https://api.rawg.io/api/games?dates=&quot; + str(year1) + &quot;-&quot; + str(month1) + &quot;-&quot; + str(day1) + &quot;,&quot; + str(year2) + &quot;-&quot; + str(month2) + &quot;-&quot; + str(day2) + &quot;&amp;page=&quot; + str(PageNumber) + &quot;&amp;platforms=4,187,1,18,186&amp;page_size=40&amp;ordering=released&quot; ) return Url def _GetData_Date(year1=2020, month1=8, day1=4, year2=2020, month2=8, day2=4): #just place holder values Url = _Url(year1, month1, day1, year2, month2, day2) StaticData = requests.get(Url).json() AmountOfGames = StaticData[&quot;count&quot;] AmountOfPages = AmountOfGames // 40 #1 page contains 40 so it does amount//40 to get pages if(AmountOfGames%40 != 0): AmountOfPages = AmountOfPages + 1 #does +1 if there's a leftover page PageNumber = 1 #############Delete############ Succes = 0 Fail = 0 ######################### while PageNumber &lt;= AmountOfPages: for x in range(len(StaticData[&quot;results&quot;])): if StaticData[&quot;results&quot;][x][&quot;added&quot;] &gt; 0: try: #can't start with an empty Game variable AStaticData = (StaticData[&quot;results&quot;][x],) # the &quot;,&quot;turns it to tulpe, it keeps adding tulpes to 1 giant one that contains all the filtered information Game = Game + AStaticData except: AStaticData = (StaticData[&quot;results&quot;][x],) # the &quot;,&quot;turns it to tulpe Game = AStaticData ############################Delete################# os.system(&quot;cls&quot;) Succes = Succes + 1 print(&quot;succes: &quot;, (Succes)) print(&quot;fail:&quot;, Fail) print(&quot;Total:&quot;, AmountOfGames, Succes + Fail) else: os.system(&quot;cls&quot;) Fail = Fail + 1 print(&quot;succes: &quot;, (Succes)) print(&quot;fail:&quot;, Fail) print(&quot;Total:&quot;, AmountOfGames,&quot;-&quot;, Succes + Fail) ################################################## # goes trough pages PageNumber = PageNumber + 1 if PageNumber &lt;= AmountOfPages: Url = _Url(year1, month1, day1, year2, month2, day2, PageNumber) StaticData = requests.get(Url).json() return Game #### Save it to local variables ##### StaticData =_GetData_Date() ### Main program ################### for x in range(len(StaticData)): print(StaticData[x][&quot;name&quot;]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:26:43.957", "Id": "485250", "Score": "0", "body": "Why not use the API wrapper? https://pypi.org/project/rawgpy/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:30:34.630", "Id": "485251", "Score": "0", "body": "I have more control by doing everything myself, I think. Doing it myself felt easier than understanding the full documentation of the wrapper." } ]
[ { "body": "<h2>f-strings</h2>\n<p>I recommend to use f-strings (Python version &gt;= 3.6) for string formatting. See this link for more details:\n<a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0498/</a></p>\n<p>When you use them you can replace</p>\n<pre><code>if month1 &lt; 10:\n month1 = &quot;0&quot; + str(month1)\n</code></pre>\n<p>with an expression like this:</p>\n<pre><code>month1 = f'{month1:02}'\n</code></pre>\n<p>This adds a leading zero if <code>month1</code> only has one digit.</p>\n<p>In addition, an expression like:</p>\n<pre><code> Url = (\n &quot;https://api.rawg.io/api/games?dates=&quot;\n + str(year1)\n + &quot;-&quot;\n + str(month1)\n + &quot;-&quot;\n + str(day1)\n + &quot;,&quot;\n + str(year2)\n + &quot;-&quot;\n + str(month2)\n + &quot;-&quot;\n + str(day2)\n + &quot;&amp;page=&quot;\n + str(PageNumber)\n + &quot;&amp;platforms=4,187,1,18,186&amp;page_size=40&amp;ordering=released&quot;\n )\n\n</code></pre>\n<p>can be written as</p>\n<pre><code>url_part1 = &quot;https://api.rawg.io/api/games?dates=&quot;\nurl_part2 = &quot;&amp;platforms=4,187,1,18,186&amp;page_size=40&amp;ordering=released&quot;\n\n Url = f&quot;{url_part1}{year1}-{month1}-{day1},{year2}-{month2}-{day2}&amp;page={PageNumber}{url_part2}&quot;\n</code></pre>\n<p>using f-strings. This is shorter and less error prone (less quotes you can forget), opinions might vary regarding the readability, though. Type conversions (<code>str(.)</code>) are not needed anymore.</p>\n<h2>Avoid hardcoding</h2>\n<p>It is good that you added a comment to explain where the number 40 comes from:</p>\n<pre><code>AmountOfPages = AmountOfGames // 40 #1 page contains 40 so it does amount//40 to get pages\n</code></pre>\n<p>However, it would be even better if you assigned this number to a variable with a telling name. For example</p>\n<pre><code>games_per_page = 40 # Preferably, put this on the top of your script or in a config file\n# [...]\nAmountOfPages = AmountOfGames // games_per_page\n</code></pre>\n<p>This is more flexible. Imagine the number of games per page changes.</p>\n<h2>Leftover page: ceiling division</h2>\n<p>In this part you first do a floor division (//), then you add 1 for leftover pages</p>\n<pre><code>AmountOfPages = AmountOfGames // games_per_page#1 page contains 40 so it does amount//40 to get pages\nif(AmountOfGames%games_per_page != 0):\n AmountOfPages = AmountOfPages + 1 #does +1 if there's a leftover page\n</code></pre>\n<p>This can be simplified with a ceiling division</p>\n<pre><code>import math\n\nAmountOfPages = math.ceil(AmountOfGames / games_per_page)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T18:28:27.113", "Id": "485306", "Score": "0", "body": "Thank you so much, for taking your time to check my code! You gave me different topics to learn about, which I will 100% do. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T18:38:44.703", "Id": "485308", "Score": "0", "body": "You are welcome. I forgot to mention that I did not do a complete review of your entire code, that is, I did not check every single line. I just skimmed through the code and wrote down a few things I noticed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:53:42.000", "Id": "247816", "ParentId": "247795", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T08:38:08.070", "Id": "247795", "Score": "2", "Tags": [ "python", "sorting", "api" ], "Title": "Filtering out, a list of games, based on their followers" }
247795
<p>So I came across <a href="https://stackoverflow.com/questions/63372042/how-to-convert-a-string-to-a-list-if-the-string-has-characters-for-a-group-of-ch#63372097">this question on SO</a> and I felt like it would be a cool thing to try and write a parser for since I always wanted to try it. So I present to you:</p> <p>My first time writing a parser.</p> <p>It converts strings like this:</p> <pre><code>&quot;a,s,[c,f],[f,t], [[a,c],[d3,32]]&quot; </code></pre> <p>into list objects</p> <pre><code>['a', 's', ['c', 'f'], ['f', 't'], [['a', 'c'], ['d3', '32']]] </code></pre> <p>Here is my code for now</p> <pre><code>def parseToList(string, cont=0): result = list() temp = '' i = cont while i &lt; len(string): if string[i] == ',': if len(temp) and temp != ' ': result.append(temp) temp = '' elif string[i] == '[': res = parseToList(string, i+1) i = res[1] result.append(res[0]) elif string[i] == ']': if len(temp) and temp != ' ': result.append(temp) return (result,i) else: temp += string[i] i += 1 if len(temp) and temp != ' ': result.append(temp) return (result, i) def listParse(string): return parseToList(string)[0] s = 'a,s,[c,f],[f,t], [[a,c],[d3,32]]' print(s) print(listParse(s)) </code></pre> <p>Is there anything I am doing wrong? Something I should change?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:30:59.997", "Id": "485263", "Score": "1", "body": "Do you want a review of design or only of functionality?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:37:30.150", "Id": "485265", "Score": "0", "body": "@Hawk I would prefer the design since I know there really isn't much functionality. It only handles strings" } ]
[ { "body": "<p>Here are a few things that came to my mind:</p>\n<hr />\n<h2>Bug</h2>\n<ul>\n<li><p><code>if temp != ' '</code> will not work when there are more than 1 consecutive spaces.<br />\nTo fix this, use <code>if not temp.isspace()</code> instead of comparing with a hard-coded string.<br />\nFor example, <code>s = 'a, [b]'</code> will output <code>['a', ['b'], ' ']</code> for your current code.</p>\n</li>\n<li><p>Your code outputs <code>['a', ' b']</code> for <code>a, b</code>. I'll assume that including the space is a feature and not a bug.</p>\n</li>\n</ul>\n<hr />\n<h2>Design</h2>\n<ul>\n<li><p>Wrap the test code inside <code>if __name__ == '__main__'</code>. This will prevent the code from being called when being imported from another module.</p>\n</li>\n<li><p>Function names should preferably be lowercase. Change the CamelCase names to snake_case.</p>\n</li>\n<li><p>In return statements, you need not enclose the items in a parenthesis if you are returning a tuple</p>\n</li>\n<li><p><code>result = list()</code> can be replaced with just <code>result = []</code></p>\n</li>\n<li><p><code>if len(temp)</code> can be replaced with just <code>if temp</code>. The bool of empty values are <code>False</code> in python.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>res = parse_to_list(string, i + 1)\ni = res[1]\nresult.append(res[0])\n</code></pre>\n<p>The above can be a bit simplified and can be made a bit more understandable.</p>\n<pre class=\"lang-py prettyprint-override\"><code>nested_list, i = parse_to_list(string, i + 1)\nresult.append(nested_list)\n</code></pre>\n<ul>\n<li><p>Instead of using <code>string[i]</code>, you can declare a new element <code>char</code> which is equal to <code>string[i]</code><br />\n(This is just my personal preference)</p>\n</li>\n<li><p>You can declare <code>parse_to_list</code> to inside <code>list_parse</code>. This will remove the need to pass <code>string</code> inside a recursion repeatedly, and will also make the inner function &quot;private&quot;.<br />\n(But this is also just my personal preference)</p>\n</li>\n</ul>\n<p>The final code should look something like this after applying the above:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def list_parse(string):\n def parse_to_list(cont=0):\n result = []\n temp = ''\n i = cont\n\n while i &lt; len(string):\n char = string[i]\n\n if char == ',':\n if temp and not temp.isspace():\n result.append(temp)\n temp = ''\n\n elif char == '[':\n nested_list, i = parse_to_list(i + 1)\n result.append(nested_list)\n\n elif char == ']':\n if temp and not temp.isspace():\n result.append(temp)\n return result, i\n\n else:\n temp += char\n\n i += 1\n\n if temp and not temp.isspace():\n result.append(temp)\n\n return result, i\n\n return parse_to_list()[0]\n\n\nif __name__ == '__main__':\n s = 'a,s,[c,f],[f,t], [[a,c],[d3,32]]'\n\n print(list_parse(s))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T11:05:23.650", "Id": "485269", "Score": "1", "body": "Thanks for the review! I didn't know you can declare a function inside another. This is going to be super helpful! And yeah outputting `['a', ' b']` for `a, b` is intended." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:59:09.833", "Id": "247806", "ParentId": "247798", "Score": "2" } }, { "body": "<h1>Disclaimer</h1>\n<p>I am more of a Java dev, so please excuse my non-pythonesque ideas.</p>\n<h1>Style review</h1>\n<p>Write code for someone else, not yourself (i.e. readable &amp; understandable).</p>\n<p>You have non-descriptive variable names.</p>\n<ul>\n<li><code>i</code>: usually there is a better name for it, I would consider <code>i</code> viable in something like <code>for i in range</code></li>\n<li><code>temp</code>: what does temp represent? Already processed characters, so maybe call it <code>processed_chars</code> or something</li>\n<li><code>result</code>, <code>res</code> - almost identical, very confusing. A single variable named <code>result</code> could be OK in a function, Martin Fowler uses it, although Uncle Bob despises it. You are doing parsing, so a probable alternative could be <code>parsed</code> or the like.</li>\n<li><code>res</code>: why do you have this variable in the first place? Just use a tuple deconstruction into something more meaningful:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>parsed_list, new_i = parseToList(string, i+1)\n</code></pre>\n<p>I am not sure how python work, but maybe you could even replace <code>new_i</code> directly with <code>i</code>.</p>\n<h1>Functionality review</h1>\n<p>You never fail. Weird. Are you sure you can always parse everything successfully? Even though this is a very simple and permissive language, probably not. Edge cases:</p>\n<ul>\n<li><code>[</code></li>\n<li><code>[a,]</code></li>\n<li><code>[,a]</code></li>\n</ul>\n<h1>Design review</h1>\n<p>First of all I will create a grammar. It will ease my review and it should have simplified you your implementation:</p>\n<pre><code>list = &quot;[&quot; values &quot;]&quot;\n# maybe values could be modified to accept dangling commas if you want\nvalues = value { &quot;,&quot; value }\nvalue = list | string\nstring = &lt;anything except &quot;[&quot; &quot;]&quot; &quot;,&quot; trimmed (i.e. no leadind or trailing whitespace)&gt;\n</code></pre>\n<p>Now we have a (context-free) grammar given by pseudo-EBNF. Usually lexer and parser are separate, but we don't really need special tokens, we could just use single characters as tokens. Usually a parser accepts a stream of tokens and outputs an AST. We don't need an AST, it could be directly interpreted as python values.\nAn alternative to using your whole <code>string</code> and <code>i</code> as a cursor is to use <code>string</code> as a stream of tokens, from which you take how many you want and return the rest (substring).</p>\n<p>Now to implement a grammar, I would create a function for each non-terminal symbol (rule), f.e. <code>parse_list() -&gt; []</code>, <code>parse_values() -&gt; []</code>, <code>parse_value()</code>, <code>parse_string() -&gt; str</code>. <code>parse()</code> would just call <code>parse_values()</code>. If you wrap these in a class. If you fail to match a symbol, you should raise an exception or let it known in your return value.</p>\n<p>So I would suggest signatures either:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Parser:\n def parse(input: string) -&gt; []:\n self.input = input\n parsed, unprocessed = self.parse_values(input)\n if unprocessed:\n # handle exception, maybe print\n return parsed\n\n\n def parse_list(cursor: int) -&gt; []\n # Parameter: cursor index in `input`\n # raises exception on error\n # the whole input is stored in class field\n\n def parse_list(unprocessed: str) -&gt; []\n # Parameter: the unprocessed input\n # raises exception on error\n\n def parse_list(unprocessed: str) -&gt; ([], str)\n # Parameter: the unprocessed input\n # Returns: (parsedList, new_unprocessed) on success\n # (None, unprocessed) on error\n # takes from unprocessed[0]\n</code></pre>\n<p>Example implementation draft:</p>\n<pre><code>def parse_list(unprocessed: str) -&gt; ([], str):\n matched, unprocessed = match(unprocessed, '[')\n if not matched:\n return None, unprocessed\n\n values, unprocessed = parse_values()\n if values == None:\n return None, unprocessed\n\n matched, unprocessed = match(unprocessed, ']')\n if not matched:\n return None, unprocessed\n\n return values\n\ndef match(unprocessed: str, to_match: str) -&gt; (bool, str):\n stripped = unprocessed.lstrip()\n if stripped.startswith(to_match):\n return True, stripped[to_match.len:]\n else:\n return False, unprocessed\n</code></pre>\n<p>If you keep a note of the remaining unprocessed input or the current cursor, you could report it when finding an error (f.e. in the raised exception)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:02:00.287", "Id": "247809", "ParentId": "247798", "Score": "1" } } ]
{ "AcceptedAnswerId": "247806", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:23:00.577", "Id": "247798", "Score": "7", "Tags": [ "python", "parsing" ], "Title": "Simple python string to list parser" }
247798
<p>I am fairly inexperienced when it comes to jQuery/JavaScript, so although the following code works, I am just looking to understand if my use of looping, deferred/promises etc could be optimised at all.</p> <h3>Purpose of code</h3> <p>This is just part of a larger script, which I have written to load images and its written details into a viewer. This code loads the initial image, or if an image hasn't been previously preloaded.</p> <p>The deferred part of the code specification is to allow multiple images (on the single slide of the viewer) to be loaded before the slide is shown.</p> <pre><code>$galleryImageDetails.css({ 'opacity' : '0' }); $galleryImage.css({ 'opacity' : '0' }); $('.loader').show(); if ( preloadedArray[entryId] ) { beingPreloaded = entryId; } else { $('.image-title h1').html(entryTitle); if ( entryProcess ) { $('.image-process span').html(entryProcess); $('.image-process').show(); } else { $('.image-process').hide(); } if ( entryDimensions ) { $('.image-dimensions p').html(entryDimensions); $('.image-dimensions').show(); } else { $('.image-dimensions').hide(); } $('.image-price p').html(entryPrice); preloadedArray[entryId] = []; preloadedArray[entryId].push($('&lt;img src=&quot;'+imagePath+'&quot; /&gt;')); $.each(entryVariants, function (key, val) { var variant = $('&lt;img src=&quot;'+val[0]+'&quot; /&gt;'); preloadedArray[entryId].push(variant); }); $('.image-variants .wrapper').empty(); var preloadedArrayLength = preloadedArray[entryId].length; var preloadsComplete = []; $.each( preloadedArray[entryId], function( key, value ) { var result = $.Deferred(); preloadsComplete.push(result.promise()); preloadedArray[entryId][key].on('load', function() { if ( key == 0 ) { var imageWrap = '&lt;a href=&quot;'+entryImagePopup+'&quot; data-fancybox=&quot;images&quot; data-caption=&quot;'+entryTitle+'&quot;&gt;&lt;/a&gt;'; $galleryImage.html(preloadedArray[entryId][key]); $('.gallery-image &gt; img').wrap(imageWrap); } if ( key &gt; 0 ) { variantLarge = entryVariants[key][1]; variantName = entryVariants[key][2]; var variantWrap = '&lt;div class=&quot;col-6 bp3-col-4&quot;&gt;&lt;a href=&quot;'+variantLarge+'&quot; data-fancybox=&quot;images&quot; data-caption=&quot;'+variantName+'&quot;&gt;&lt;/a&gt;&lt;/div&gt;'; $('.image-variants .wrapper').append(preloadedArray[entryId][key]) $('.image-variants .wrapper &gt; img').wrap(variantWrap); } result.resolve(); }); }); $.when.apply($, preloadsComplete).done(function () { $('#item'+entryId).attr('data-image-loaded', 'y'); imagePreload(); $('.loader').hide(); $galleryImageDetails.css({ 'opacity' : '1' }); $galleryImage.css({ 'opacity' : '1' }); prevNextLock = false; }); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:45:15.667", "Id": "247800", "Score": "3", "Tags": [ "javascript", "jquery", "promise" ], "Title": "Optimisation potential when using deferred/promises and looping" }
247800
<p>I needed to dynamically load and instantiate some classes from a generated jar and a generated .class file which depends on that jar. So I came up with this:</p> <pre class="lang-java prettyprint-override"><code>package ytm.yajco.translation.util; import org.jetbrains.annotations.NotNull; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE; public class DynamicClass { protected static final StackWalker walker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE); protected final Class&lt;?&gt; loadedClass; /** * &lt;b&gt;WARNING:&lt;/b&gt; Do not call this constructor if {@code jar} has already been loaded. * This will avoid multiple class loading. * &lt;p&gt; * Creates a new class loader which can load classes from {@code jar}. * The new classloader inherits the classpath from the class loader of the caller of this constructor. * Finally, the sought class is loaded from the given {@code jar}. * * @param classFQN fully qualified name of the class to be loaded * @param jar path to the jar or root directory where {@code classFQN} is to be found * @see StackWalker#getCallerClass() */ public DynamicClass(String classFQN, @NotNull Path jar) throws MalformedURLException, ReflectiveOperationException { this(classFQN, jar, walker.getCallerClass().getClassLoader()); } /** * &lt;b&gt;WARNING:&lt;/b&gt; Do not call this constructor if {@code jar} has already been loaded by {@code parentCL} * or its ancestors. This will avoid multiple class loading. * &lt;p&gt; * Creates a new class loader which can load classes from {@code jar}. * The new classloader inherits the classpath from {@code parentCL}. * Finally, the sought class is loaded from the given {@code jar}. * * @param classFQN fully qualified name of the class to be loaded * @param jar path to the jar or root directory where {@code classFQN} is to be found * @param parentCL classloader to use as a parent */ public DynamicClass(String classFQN, @NotNull Path jar, ClassLoader parentCL) throws MalformedURLException, ClassNotFoundException { final URL[] jarLocation = {jar.toUri().toURL()}; final URLClassLoader classLoader = URLClassLoader.newInstance(jarLocation, parentCL); loadedClass = Class.forName(classFQN, true, classLoader); } /** * Finds the sought class using the given class loader. * * @param classFQN fully qualified name of the class to be loaded * @param classLoader class loader to reuse * @throws ClassNotFoundException if the class cannot be located by the specified class loader */ public DynamicClass(String classFQN, ClassLoader classLoader) throws ClassNotFoundException { loadedClass = Class.forName(classFQN, true, classLoader); } public Class&lt;?&gt; getLoadedClass() { return loadedClass; } public ClassLoader getClassLoader() { return loadedClass.getClassLoader(); } } </code></pre> <p>In one of the cases I know the interface statically so in my <code>DynamicSupplier</code> subclass:</p> <pre class="lang-java prettyprint-override"><code>public Supplier&lt;?&gt; newSupplierInstance() throws ReflectiveOperationException { return (Supplier&lt;?&gt;) loadedClass.getDeclaredConstructor().newInstance(); } </code></pre> <p>In the other case I know the method signatures, so I have provided methods to which hide the reflective access. Also I wrap the new instance in a small class just to put an abstract layer when working with a bare <code>Object</code>.</p> <pre class="lang-java prettyprint-override"><code>package ytm.yajco.translation.language; import org.jetbrains.annotations.NotNull; import ytm.yajco.translation.util.DynamicClass; import java.io.Reader; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.nio.file.Path; public class DynamicParser extends DynamicClass { // skipped JavaDoc for brevity in this review public DynamicParser(String parserFQN, @NotNull Path parserJar) throws MalformedURLException, ReflectiveOperationException { this(parserFQN, parserJar, walker.getCallerClass().getClassLoader()); } // skipped other constructors matching super for brevity in this review public static Object parseSentence(@NotNull Object parser, String sentence) throws ReflectiveOperationException { final Method parse = parser.getClass().getMethod(&quot;parse&quot;, String.class); return parse.invoke(parser, sentence); } public static Object parseSentence(@NotNull Object parser, Reader sentence) throws ReflectiveOperationException { final Method parse = parser.getClass().getMethod(&quot;parse&quot;, Reader.class); return parse.invoke(parser, sentence); } public Parser newParserInstance() throws ReflectiveOperationException { final Object parser = loadedClass.getDeclaredConstructor().newInstance(); return new Parser(parser); } public static class Parser { private final Object parser; private Parser(Object parser) { this.parser = parser; } public Object parseSentence(String sentence) throws ReflectiveOperationException { return DynamicParser.parseSentence(parser, sentence); } public Object parseSentence(Reader sentence) throws ReflectiveOperationException { return DynamicParser.parseSentence(parser, sentence); } public Object getRealParser() { return parser; } } } </code></pre> <p>So what do you think about my creation? :) BTW, is <code>Parser</code> an adapter (as per GOF)?</p>
[]
[ { "body": "<p>First of all, the <code>DynamicClass</code> wraps a whole class loader for a single class.\nIf you need multiple classes from the same jar, you will have to create a complete\nclass loader and read the complete jar <em>for every single class</em>. This seems overkill,\nbut may well be OK in your context.</p>\n<p>Apart from that there's not much to say, as you basically create a wrapper around three\nlines of code.</p>\n<p>Regarding <code>DynamicParser</code>: here it gets ugly. So you know that you have two methods called\n<code>parse()</code> one with a string parameter and one with a reader. Why don't these classes simply\nimplement an interface which encompasses <code>parse(String</code> and <code>parse(Reader)</code>? I see reflection\nas a last resort when all else fails, and in this case, simply implementing an interface\nseems much easier and much clearer.</p>\n<p>I don't know whether you only need this for a kind of &quot;pluggable parser&quot; or if you\nhave multiple locations in your code where you need this code, but from what I see,\nI'd do the following:</p>\n<p>1 - Create an interface <code>Parser</code> which declares the methods as above</p>\n<p>2 - Create a utility class, which can load such a parser from a jar</p>\n<pre><code>public static Parser loadParser(String fqn, Path jar) {\n // basically do the same as DynamicClass,\n // but upcast to parser and return an instance\n}\n</code></pre>\n<p>3 - Use the Parser (as a strongly typed interface) in the client code</p>\n<hr />\n<p>Edit following the comment: I did not miss the third constructor, it just did not make any sense for me.</p>\n<p>So you have multiple uses like this:</p>\n<pre><code>DynamicClass dc1 = new DynamicClass(&quot;Thingy1&quot;, myJar);\n...\nDynamicClass dc2 = new DynamicClass(&quot;Thingy2&quot;, dc1.getClassLoader());\n</code></pre>\n<p>Where the locations are not necessarily related.</p>\n<p>If someone inserts another call somewhere else in the code, which coincidentally is somewhere <em>before</em> dc1, he will have to:</p>\n<pre><code>DynamicClass dc0 = new DynamicClass(&quot;Thingy0&quot;, myJar);\n</code></pre>\n<p>... and then <em>change</em> the original call to</p>\n<pre><code>DynamicClass dc1 = new DynamicClass(&quot;Thingy1&quot;, dc0.getClassLoader());\n</code></pre>\n<p>In my world this is inacceptable. If you do caching, do it in the class itself, maybe by a static map or so, but keep it out of the public interface.</p>\n<p>Regarding the interface: I feel like close-voting the question for missing review context now.</p>\n<p>Nevertheless, I cannot see any reason why you use two different classes for DynamicParser and Parser. Just have DynamicParser implement an interface Parser and be done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T14:06:24.280", "Id": "485824", "Score": "0", "body": "In your first point (load multiple classes from one jar) you missed the third ctor which allows to reuse a classloader - which you can get from a previous DynamicClass by a getter.\n...\nThe real parser is a generated class (by another tool), which has no outside dependencies currently and implements no interface. That means that even the exception it throws is generated and declared in the same package. I know the signature of it, but I cannot change it, I cannot get hold of a common interface. If I could, I would downcast in a subclass, same as with the `Supplier`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T04:23:23.310", "Id": "485887", "Score": "0", "body": "@Hawk See edit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T12:33:21.193", "Id": "248088", "ParentId": "247801", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T09:45:33.563", "Id": "247801", "Score": "4", "Tags": [ "java", "dynamic-loading" ], "Title": "DynamicClass - loads and instantiates classes at run-time" }
247801
<p>Unity scripts need access to components they will be using, my solution here guarantees that a script will have a valid reference to a component it needs, but is this solution overkill, or hard to discern intention from?</p> <p>Note: null coalescence operators would be cleaner but cannot be used for unity objects or components for terrible reasons.</p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody))] // disallows deletion of component from editor public class CubeControll : MonoBehaviour { [SerializeField, HideInInspector] private Rigidbody rigidbody; private void OnValidate() { rigidbody = GetComponent&lt;Rigidbody&gt;() != null ? // if has component attached GetComponent&lt;Rigidbody&gt;() : // assign referance gameObject.AddComponent&lt;Rigidbody&gt;(); // else add new component } // start, update etc } </code></pre> <p>This is a common situation, are there any general best practices to doing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T05:24:03.783", "Id": "485331", "Score": "0", "body": "is there any reason for not using the constructor to validate the `rigidbody` ? so this way you can make it `readonly`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:00:12.600", "Id": "485360", "Score": "0", "body": "@Heslacher, yes this is my real code... why do you say that? both branches of the `?:` operator return a `Rigidbody`... i'm not really sure what you mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:07:02.997", "Id": "485362", "Score": "0", "body": "@iSR5, are you familiar with Unity? This class inherits from monobehavior, you should never create a constructor for monobehavior derived objects" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:02:44.423", "Id": "485378", "Score": "1", "body": "@Jake unfortunately no, that's why I asked you. But it's clear now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:28:36.703", "Id": "485382", "Score": "0", "body": "Oh, you're right. sorry i don't know how that happened. I've corrected my code" } ]
[ { "body": "<p>Right now you are calling <code>GetComponent&lt;T&gt;()</code> twice if the first call return a value != null.</p>\n<p>Well, I would do this in a very simple way.</p>\n<pre><code>private void OnValidate()\n{\n rigidbody = GetComponent&lt;Rigidbody&gt;();\n if (rigidbody != null) { return; }\n \n rigidbody = gameObject.AddComponent&lt;Rigidbody&gt;();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:35:44.260", "Id": "247855", "ParentId": "247802", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:31:35.283", "Id": "247802", "Score": "2", "Tags": [ "c#", "unity3d" ], "Title": "Is my unity component validation overkill?" }
247802
<p>Now that my new compiler is capable of compiling programs such as the <a href="https://flatassembler.github.io/analogClock.html" rel="nofollow noreferrer">Analog Clock in AEC</a>, I've decided to share the code of that compiler with you, to see what you think about it.<br/><br/> File <code>compiler.cpp</code>:<br/></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;TreeNode.cpp&quot; #include &quot;bitManipulations.cpp&quot; AssemblyCode convertToInteger32(const TreeNode node, const CompilationContext context) { auto originalCode = node.compile(context); const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32, i64 = AssemblyCode::AssemblyType::i64, f32 = AssemblyCode::AssemblyType::f32, f64 = AssemblyCode::AssemblyType::f64, null = AssemblyCode::AssemblyType::null; if (originalCode.assemblyType == null) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Some part of the compiler attempted to convert \&quot;&quot; &lt;&lt; node.text &lt;&lt; &quot;\&quot; to \&quot;Integer32\&quot;, which makes no sense. This could be an &quot; &quot;internal compiler error, or there could be something semantically &quot; &quot;(though not grammatically) very wrong with your program.&quot; &lt;&lt; std::endl; exit(1); } if (originalCode.assemblyType == i32) return originalCode; if (originalCode.assemblyType == i64) return AssemblyCode( &quot;(i32.wrap_i64\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, i32); if (originalCode.assemblyType == f32) return AssemblyCode( &quot;(i32.trunc_f32_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, i32); // Makes little sense to me (that, when converting to an integer, // the decimal part of the number is simply truncated), but that's // how it is done in the vast majority of programming languages. if (originalCode.assemblyType == f64) return AssemblyCode(&quot;(i32.trunc_f64_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, i32); std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Internal compiler error, control reached the &quot; &quot;end of the \&quot;convertToInteger32\&quot; function!&quot; &lt;&lt; std::endl; exit(-1); return AssemblyCode(&quot;()&quot;); } AssemblyCode convertToInteger64(const TreeNode node, const CompilationContext context) { auto originalCode = node.compile(context); const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32, i64 = AssemblyCode::AssemblyType::i64, f32 = AssemblyCode::AssemblyType::f32, f64 = AssemblyCode::AssemblyType::f64, null = AssemblyCode::AssemblyType::null; if (originalCode.assemblyType == null) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Some part of the compiler attempted to convert \&quot;&quot; &lt;&lt; node.text &lt;&lt; &quot;\&quot; to \&quot;Integer64\&quot;, which makes no sense. This could be an &quot; &quot;internal compiler error, or there could be something semantically &quot; &quot;(though not grammatically) very wrong with your program.&quot; &lt;&lt; std::endl; exit(1); } if (originalCode.assemblyType == i32) return AssemblyCode( &quot;(i64.extend_i32_s\n&quot; + // If you don't put &quot;_s&quot;, JavaScript Virtual // Machine is going to interpret the argument as // unsigned, leading to huge positive numbers // instead of negative ones. std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, i64); if (originalCode.assemblyType == i64) return originalCode; if (originalCode.assemblyType == f32) return AssemblyCode(&quot;(i64.trunc_f32_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, i64); if (originalCode.assemblyType == f64) return AssemblyCode(&quot;(i64.trunc_f64_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, i64); std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Internal compiler error, control reached the &quot; &quot;end of the \&quot;convertToInteger64\&quot; function!&quot; &lt;&lt; std::endl; exit(-1); return AssemblyCode(&quot;()&quot;); } AssemblyCode convertToDecimal32(const TreeNode node, const CompilationContext context) { auto originalCode = node.compile(context); const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32, i64 = AssemblyCode::AssemblyType::i64, f32 = AssemblyCode::AssemblyType::f32, f64 = AssemblyCode::AssemblyType::f64, null = AssemblyCode::AssemblyType::null; if (originalCode.assemblyType == null) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Some part of the compiler attempted to convert \&quot;&quot; &lt;&lt; node.text &lt;&lt; &quot;\&quot; to \&quot;Decimal32\&quot;, which makes no sense. This could be an &quot; &quot;internal compiler error, or there could be something semantically &quot; &quot;(though not grammatically) very wrong with your program.&quot; &lt;&lt; std::endl; exit(1); } if (originalCode.assemblyType == i32) return AssemblyCode( &quot;(f32.convert_i32_s\n&quot; + // Again, those who designed JavaScript Virtual // Machine had a weird idea that integers // should be unsigned unless somebody makes // them explicitly signed via &quot;_s&quot;. std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, f32); if (originalCode.assemblyType == i64) return AssemblyCode(&quot;(f32.convert_i64_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, f32); if (originalCode.assemblyType == f32) return originalCode; if (originalCode.assemblyType == f64) return AssemblyCode(&quot;(f32.demote_f64\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, f32); std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Internal compiler error, control reached the &quot; &quot;end of the \&quot;convertToDecimal32\&quot; function!&quot; &lt;&lt; std::endl; exit(-1); return AssemblyCode(&quot;()&quot;); } AssemblyCode convertToDecimal64(const TreeNode node, const CompilationContext context) { auto originalCode = node.compile(context); const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32, i64 = AssemblyCode::AssemblyType::i64, f32 = AssemblyCode::AssemblyType::f32, f64 = AssemblyCode::AssemblyType::f64, null = AssemblyCode::AssemblyType::null; if (originalCode.assemblyType == null) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Some part of the compiler attempted to convert \&quot;&quot; &lt;&lt; node.text &lt;&lt; &quot;\&quot; to \&quot;Decimal64\&quot;, which makes no sense. This could be an &quot; &quot;internal compiler error, or there could be something semantically &quot; &quot;(though not grammatically) very wrong with your program.&quot; &lt;&lt; std::endl; exit(1); } if (originalCode.assemblyType == i32) return AssemblyCode(&quot;(f64.convert_i32_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, f64); if (originalCode.assemblyType == i64) return AssemblyCode(&quot;(f64.convert_i64_s\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, f64); if (originalCode.assemblyType == f32) return AssemblyCode(&quot;(f64.promote_f32\n&quot; + std::string(originalCode.indentBy(1)) + &quot;\n)&quot;, f64); if (originalCode.assemblyType == f64) return originalCode; std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Internal compiler error, control reached the &quot; &quot;end of the \&quot;convertToDecimal64\&quot; function!&quot; &lt;&lt; std::endl; exit(-1); return AssemblyCode(&quot;()&quot;); } AssemblyCode convertTo(const TreeNode node, const std::string type, const CompilationContext context) { if (type == &quot;Character&quot; or type == &quot;Integer16&quot; or type == &quot;Integer32&quot; or std::regex_search( type, std::regex( &quot;Pointer$&quot;))) // When, in JavaScript Virtual Machine, you can't // push types of less than 4 bytes (32 bits) onto // the system stack, you need to convert those to // Integer32 (i32). Well, makes slightly more sense // than the way it is in 64-bit x86 assembly, where // you can put 16-bit values and 64-bit values onto // the system stack, but you can't put 32-bit // values. return convertToInteger32(node, context); if (type == &quot;Integer64&quot;) return convertToInteger64(node, context); if (type == &quot;Decimal32&quot;) return convertToDecimal32(node, context); if (type == &quot;Decimal64&quot;) return convertToDecimal64(node, context); std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; node.lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; node.columnNumber &lt;&lt; &quot;, Compiler error: Some part of the compiler attempted to get &quot; &quot;the assembly code for converting \&quot;&quot; &lt;&lt; node.text &lt;&lt; &quot;\&quot; into the type \&quot;&quot; &lt;&lt; type &lt;&lt; &quot;\&quot;, which doesn't make sense. This could be an internal &quot; &quot;compiler error, or there could be something semantically &quot; &quot;(though not grammatically) very wrong with your program.&quot; &lt;&lt; std::endl; exit(-1); return AssemblyCode(&quot;()&quot;); } std::string getStrongerType(int, int, std::string, std::string); // When C++ doesn't support function // hoisting, like JavaScript does. AssemblyCode TreeNode::compile(CompilationContext context) const { std::string typeOfTheCurrentNode = getType(context); if (!mappingOfAECTypesToWebAssemblyTypes.count(typeOfTheCurrentNode)) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Internal compiler error: The function \&quot;getType\&quot; returned \&quot;&quot; &lt;&lt; typeOfTheCurrentNode &lt;&lt; &quot;\&quot;, which is an invalid name of type. Aborting the compilation!&quot; &lt;&lt; std::endl; exit(1); } AssemblyCode::AssemblyType returnType = mappingOfAECTypesToWebAssemblyTypes.at(typeOfTheCurrentNode); auto iteratorOfTheCurrentFunction = std::find_if(context.functions.begin(), context.functions.end(), [=](function someFunction) { return someFunction.name == context.currentFunctionName; }); if (iteratorOfTheCurrentFunction == context.functions.end()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Internal compiler error: The \&quot;compile(CompilationContext)\&quot; &quot; &quot;function was called without setting the current function name, &quot; &quot;aborting compilation (or else the compiler will segfault)!&quot; &lt;&lt; std::endl; exit(1); } function currentFunction = *iteratorOfTheCurrentFunction; std::string assembly; if (text == &quot;Does&quot; or text == &quot;Then&quot; or text == &quot;Loop&quot; or text == &quot;Else&quot;) // Blocks of code are stored by the parser as child nodes // of &quot;Does&quot;, &quot;Then&quot;, &quot;Else&quot; and &quot;Loop&quot;. { if (text != &quot;Does&quot;) context.stackSizeOfThisScope = 0; //&quot;TreeRootNode&quot; is supposed to set up the arguments in the scope // before passing the recursion onto the &quot;Does&quot; node. for (auto childNode : children) { if (childNode.text == &quot;Nothing&quot;) continue; else if (basicDataTypeSizes.count(childNode.text)) { // Local variables declaration. for (TreeNode variableName : childNode.children) { if (variableName.text.back() != '[') { // If it's not an array. context.localVariables[variableName.text] = 0; for (auto &amp;pair : context.localVariables) pair.second += basicDataTypeSizes.at(childNode.text); context.variableTypes[variableName.text] = childNode.text; context.stackSizeOfThisFunction += basicDataTypeSizes.at(childNode.text); context.stackSizeOfThisScope += basicDataTypeSizes.at(childNode.text); assembly += &quot;(global.set $stack_pointer\n\t(i32.add (global.get &quot; &quot;$stack_pointer) (i32.const &quot; + std::to_string(basicDataTypeSizes.at(childNode.text)) + &quot;)) ;;Allocating the space for the local variable \&quot;&quot; + variableName.text + &quot;\&quot;.\n)\n&quot;; if (variableName.children.size() and variableName.children[0].text == &quot;:=&quot;) // Initial assignment to local variables. { TreeNode assignmentNode = variableName.children[0]; assignmentNode.children.insert(assignmentNode.children.begin(), variableName); assembly += assignmentNode.compile(context) + &quot;\n&quot;; } } else { // If that's a local array declaration. int arraySizeInBytes = basicDataTypeSizes.at(childNode.text) * variableName.children[0] .interpretAsACompileTimeIntegerConstant(); context.localVariables[variableName.text] = 0; for (auto &amp;pair : context.localVariables) pair.second += arraySizeInBytes; context.variableTypes[variableName.text] = childNode.text; context.stackSizeOfThisFunction += arraySizeInBytes; context.stackSizeOfThisScope += arraySizeInBytes; assembly += &quot;(global.set $stack_pointer\n\t(i32.add (global.get &quot; &quot;$stack_pointer) (i32.const &quot; + std::to_string(arraySizeInBytes) + &quot;)) ;;Allocating the space for the local array \&quot;&quot; + variableName.text + &quot;\&quot;.\n)\n&quot;; if (variableName.children.size() == 2 and variableName.children[1].text == &quot;:=&quot; and variableName.children[1].children[0].text == &quot;{}&quot;) // Initial assignments of local arrays. { TreeNode initialisationList = variableName.children[1].children[0]; for (unsigned int i = 0; i &lt; initialisationList.children.size(); i++) { TreeNode element = initialisationList.children[i]; TreeNode assignmentNode( &quot;:=&quot;, variableName.children[1].lineNumber, variableName.children[1].columnNumber); TreeNode whereToAssignTheElement( variableName.text, variableName.lineNumber, variableName .columnNumber); // Damn, can you think up a language in // which writing stuff like this isn't // as tedious and error-prone as it is // in C++ or JavaScript? Maybe some // language in which you can switch // between a C-like syntax and a // Lisp-like syntax at will? whereToAssignTheElement.children.push_back(TreeNode( std::to_string(i), variableName.children[0].lineNumber, variableName.children[1].columnNumber)); assignmentNode.children.push_back(whereToAssignTheElement); assignmentNode.children.push_back(element); assembly += assignmentNode.compile(context) + &quot;\n&quot;; } } } } } else assembly += std::string(childNode.compile(context)) + &quot;\n&quot;; } assembly += &quot;(global.set $stack_pointer (i32.sub (global.get &quot; &quot;$stack_pointer) (i32.const &quot; + std::to_string(context.stackSizeOfThisScope) + &quot;)))&quot;; } else if (text.front() == '&quot;') assembly += &quot;(i32.const &quot; + std::to_string(context.globalVariables[text]) + &quot;) ;;Pointer to &quot; + text; else if (context.variableTypes.count(text)) { if (typeOfTheCurrentNode == &quot;Character&quot;) assembly += &quot;(i32.load8_s\n&quot; + compileAPointer(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer16&quot;) assembly += &quot;(i32.load16_s\n&quot; + compileAPointer(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer32&quot; or std::regex_search(typeOfTheCurrentNode, std::regex(&quot;Pointer$&quot;))) assembly += &quot;(i32.load\n&quot; + compileAPointer(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer64&quot;) assembly += &quot;(i64.load\n&quot; + compileAPointer(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Decimal32&quot;) assembly += &quot;(f32.load\n&quot; + compileAPointer(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Decimal64&quot;) assembly += &quot;(f64.load\n&quot; + compileAPointer(context).indentBy(1) + &quot;\n)&quot;; else { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Internal compiler error: Compiler got into a forbidden &quot; &quot;state while compiling the token \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot;, aborting the compilation!&quot; &lt;&lt; std::endl; exit(1); } } else if (text == &quot;:=&quot;) { TreeNode rightSide; if (children[1].text == &quot;:=&quot;) { // Expressions such as &quot;a:=b:=0&quot; or similar. TreeNode tmp = children[1]; // In case the &quot;compile&quot; changes the TreeNode // (which the GNU C++ compiler should forbid, // but apparently doesn't). assembly += children[1].compile(context) + &quot;\n&quot;; rightSide = tmp.children[0]; } else rightSide = children[1]; assembly += &quot;;;Assigning &quot; + rightSide.getLispExpression() + &quot; to &quot; + children[0].getLispExpression() + &quot;.\n&quot;; if (typeOfTheCurrentNode == &quot;Character&quot;) assembly += &quot;(i32.store8\n&quot; + children[0].compileAPointer(context).indentBy(1) + &quot;\n&quot; + convertToInteger32(rightSide, context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer16&quot;) assembly += &quot;(i32.store16\n&quot; + children[0].compileAPointer(context).indentBy(1) + &quot;\n&quot; + convertToInteger32(rightSide, context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer32&quot; or std::regex_search(typeOfTheCurrentNode, std::regex(&quot;Pointer$&quot;))) assembly += &quot;(i32.store\n&quot; + children[0].compileAPointer(context).indentBy(1) + &quot;\n&quot; + convertToInteger32(rightSide, context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer64&quot;) assembly += &quot;(i64.store\n&quot; + children[0].compileAPointer(context).indentBy(1) + &quot;\n&quot; + convertToInteger64(rightSide, context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Decimal32&quot;) assembly += &quot;(f32.store\n&quot; + children[0].compileAPointer(context).indentBy(1) + &quot;\n&quot; + convertToDecimal32(rightSide, context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Decimal64&quot;) assembly += &quot;(f64.store\n&quot; + children[0].compileAPointer(context).indentBy(1) + &quot;\n&quot; + convertToDecimal64(rightSide, context).indentBy(1) + &quot;\n)&quot;; else { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Internal compiler error: The compiler got into a &quot; &quot;forbidden state while compiling the token \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot;, aborting the compilation!&quot; &lt;&lt; std::endl; exit(1); } } else if (text == &quot;If&quot;) { if (children.size() &lt; 2) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Corrupt AST, the \&quot;If\&quot; node has less than 2 &quot; &quot;child nodes. Aborting the compilation (or else we will segfault)!&quot; &lt;&lt; std::endl; exit(1); } if (children[1].text != &quot;Then&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Corrupt AST, the second child of the &quot; &quot;\&quot;If\&quot; node isn't named \&quot;Then\&quot;. Aborting the compilation &quot; &quot;(or else we will probably segfault)!&quot; &lt;&lt; std::endl; exit(1); } if (children.size() &gt;= 3 and children[2].text != &quot;Else&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Corrupt AST, the third child of the &quot; &quot;\&quot;If\&quot; node is not named \&quot;Else\&quot;, aborting the &quot; &quot;compilation (or else we will probably segfault)!&quot; &lt;&lt; std::endl; exit(1); } assembly += &quot;(if\n&quot; + convertToInteger32(children[0], context).indentBy(1) + &quot;\n\t(then\n&quot; + children[1].compile(context).indentBy(2) + &quot;\n\t)&quot; + ((children.size() == 3) ? &quot;\n\t(else\n&quot; + children[2].compile(context).indentBy(2) + &quot;\n\t)\n)&quot; : AssemblyCode(&quot;\n)&quot;)); } else if (text == &quot;While&quot;) { if (children.size() &lt; 2 or children[1].text != &quot;Loop&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Corrupt AST, aborting (or else we will &quot; &quot;segfault)!&quot; &lt;&lt; std::endl; exit(1); } assembly += &quot;(block\n\t(loop\n\t\t(br_if 1\n\t\t\t(i32.eqz\n&quot; + convertToInteger32(children[0], context).indentBy(4) + &quot;\n\t\t\t)\n\t\t)&quot; + children[1].compile(context).indentBy(2) + &quot;\n\t\t(br 0)\n\t)\n)&quot;; } else if (std::regex_match(text, std::regex(&quot;(^\\d+$)|(^0x(\\d|[a-f]|[A-F])+$)&quot;))) assembly += &quot;(i64.const &quot; + text + &quot;)&quot;; else if (std::regex_match(text, std::regex(&quot;^\\d+\\.\\d*$&quot;))) assembly += &quot;(f64.const &quot; + text + &quot;)&quot;; else if (text == &quot;Return&quot;) { if (currentFunction.returnType != &quot;Nothing&quot;) { if (children.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: It's not specified what to return from &quot; &quot;a function that's supposed to return \&quot;&quot; &lt;&lt; currentFunction.returnType &lt;&lt; &quot;\&quot;, aborting the compilation (or else the compiler will &quot; &quot;segfault)!&quot; &lt;&lt; std::endl; exit(1); } TreeNode valueToBeReturned = children[0]; if (valueToBeReturned.text == &quot;:=&quot;) { TreeNode tmp = valueToBeReturned; // The C++ compiler is supposed to forbid // side-effects in the &quot;compile&quot; method, since // it's declared as &quot;const&quot;, but apparently it // doesn't. It seems to me there is some bug both // in my code and in GNU C++ compiler (which is // supposed to warn me about it). assembly += valueToBeReturned.compile(context) + &quot;\n&quot;; valueToBeReturned = tmp.children[0]; } assembly += &quot;;;Setting for returning: &quot; + valueToBeReturned.getLispExpression() + &quot;\n&quot;; assembly += &quot;(local.set $return_value\n&quot;; assembly += convertTo(valueToBeReturned, currentFunction.returnType, context) .indentBy(1) + &quot;\n)\n&quot;; } assembly += &quot;(global.set $stack_pointer (i32.sub (global.get &quot; &quot;$stack_pointer) (i32.const &quot; + std::to_string(context.stackSizeOfThisFunction) + &quot;))) ;;Cleaning up the system stack before returning.\n&quot;; assembly += &quot;(return&quot;; if (currentFunction.returnType == &quot;Nothing&quot;) assembly += &quot;)&quot;; else assembly += &quot; (local.get $return_value))&quot;; } else if (text == &quot;+&quot;) { std::vector&lt;TreeNode&gt; children = this-&gt;children; // So that compiler doesn't complain about iter_swap // being called in a constant function. if (std::regex_search(children[1].getType(context), std::regex(&quot;Pointer$&quot;))) std::iter_swap(children.begin(), children.begin() + 1); std::string firstType = children[0].getType(context); std::string secondType = children[1].getType(context); if (std::regex_search( firstType, std::regex( &quot;Pointer$&quot;))) // Multiply the second operand by the numbers of // bytes the data type that the pointer points to // takes. That is, be compatible with pointers in // C and C++, rather than with pointers in // Assembly (which allows unaligned access). assembly += &quot;(i32.add\n&quot; + std::string(children[0].compile(context).indentBy(1)) + &quot;\n\t(i32.mul (i32.const &quot; + std::to_string(basicDataTypeSizes.at(firstType.substr( 0, firstType.size() - std::string(&quot;Pointer&quot;).size()))) + &quot;)\n&quot; + convertToInteger32(children[1], context).indentBy(2) + &quot;\n\t)\n)&quot;; else assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;.add\n&quot; + convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n)&quot;; } else if (text == &quot;-&quot;) { std::string firstType = children[0].getType(context); std::string secondType = children[1].getType(context); if (!std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and std::regex_search(secondType, std::regex(&quot;Pointer$&quot;))) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: What exactly does it mean to subtract a &quot; &quot;pointer from a number? Aborting the compilation!&quot; &lt;&lt; std::endl; exit(1); } else if (std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and std::regex_search( secondType, std::regex(&quot;Pointer$&quot;))) // Subtract two pointers as if they // were two Integer32s. assembly += &quot;(i32.sub\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n&quot; + children[1].compile(context).indentBy(1) + &quot;\n)&quot;; else if (std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and !std::regex_search(secondType, std::regex(&quot;Pointer$&quot;))) assembly += &quot;(i32.sub\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n\t(i32.mul (i32.const &quot; + std::to_string(basicDataTypeSizes.at(firstType.substr( 0, firstType.size() - std::string(&quot;Pointer&quot;).size()))) + &quot;)\n&quot; + children[1].compile(context).indentBy(2) + &quot;\n\t\t)\n\t)\n)&quot;; else assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;.sub\n&quot; + convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n)&quot;; } else if (text == &quot;*&quot;) assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;.mul\n&quot; + convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n)&quot;; else if (text == &quot;/&quot;) { if (returnType == AssemblyCode::AssemblyType::i32 or returnType == AssemblyCode::AssemblyType::i64) assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;.div_s\n&quot; + convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n)&quot;; else assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;.div\n&quot; + convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n)&quot;; } else if (text == &quot;&lt;&quot; or text == &quot;&gt;&quot;) { std::string firstType = children[0].getType(context); std::string secondType = children[1].getType(context); std::string strongerType; if (std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and std::regex_search(secondType, std::regex(&quot;Pointer$&quot;))) strongerType = &quot;Integer32&quot;; // Let's allow people to shoot themselves in the foot by // comparing pointers of different types. else strongerType = getStrongerType(lineNumber, columnNumber, firstType, secondType); AssemblyCode::AssemblyType assemblyType = mappingOfAECTypesToWebAssemblyTypes.at(strongerType); if (assemblyType == AssemblyCode::AssemblyType::i32 or assemblyType == AssemblyCode::AssemblyType::i64) assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(assemblyType) + (text == &quot;&lt;&quot; ? &quot;.lt_s\n&quot; : &quot;.gt_s\n&quot;) + convertTo(children[0], strongerType, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], strongerType, context).indentBy(1) + &quot;\n)&quot;; else assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(assemblyType) + (text == &quot;&lt;&quot; ? &quot;.lt\n&quot; : &quot;.gt\n&quot;) + convertTo(children[0], strongerType, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], strongerType, context).indentBy(1) + &quot;\n)&quot;; } else if (text == &quot;=&quot;) { std::string firstType = children[0].getType(context); std::string secondType = children[1].getType(context); std::string strongerType; if (std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and std::regex_search(secondType, std::regex(&quot;Pointer$&quot;))) strongerType = &quot;Integer32&quot;; else strongerType = getStrongerType(lineNumber, columnNumber, firstType, secondType); AssemblyCode::AssemblyType assemblyType = mappingOfAECTypesToWebAssemblyTypes.at(strongerType); assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(assemblyType) + &quot;.eq\n&quot; + convertTo(children[0], strongerType, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], strongerType, context).indentBy(1) + &quot;\n)&quot;; } else if (text == &quot;?:&quot;) assembly += &quot;(if (result &quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;)\n&quot; + convertToInteger32(children[0], context).indentBy(1) + &quot;\n\t(then\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(2) + &quot;\n\t)\n\t(else\n&quot; + convertTo(children[2], typeOfTheCurrentNode, context).indentBy(2) + &quot;\n\t)\n)&quot;; else if (text == &quot;not(&quot;) assembly += &quot;(i32.eqz\n&quot; + convertToInteger32(children[0], context).indentBy(1) + &quot;\n)&quot;; else if (text == &quot;mod(&quot;) assembly += &quot;(&quot; + stringRepresentationOfWebAssemblyType.at(returnType) + &quot;.rem_s\n&quot; + convertTo(children[0], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n&quot; + convertTo(children[1], typeOfTheCurrentNode, context).indentBy(1) + &quot;\n)&quot;; else if (text == &quot;invertBits(&quot;) assembly += &quot;(i32.xor (i32.const -1)\n&quot; + convertToInteger32(children[0], context).indentBy(1) + &quot;\n)&quot;; else if (text == &quot;and&quot;) assembly += &quot;(i32.and\n&quot; + convertToInteger32(children[0], context).indentBy(1) + &quot;\n&quot; + convertToInteger32(children[1], context).indentBy(1) + &quot;\n)&quot;; else if (text == &quot;or&quot;) assembly += &quot;(i32.or\n&quot; + convertToInteger32(children[0], context).indentBy(1) + &quot;\n&quot; + convertToInteger32(children[1], context).indentBy(1) + &quot;\n)&quot;; else if (text.back() == '(' and basicDataTypeSizes.count( text.substr(0, text.size() - 1))) // The casting operator. assembly += convertTo(children[0], text.substr(0, text.size() - 1), context); else if (std::count_if(context.functions.begin(), context.functions.end(), [=](function someFunction) { return someFunction.name == text; })) { function functionToBeCalled = *find_if( context.functions.begin(), context.functions.end(), [=](function someFunction) { return someFunction.name == text; }); assembly += &quot;(call $&quot; + text.substr(0, text.size() - 1) + &quot;\n&quot;; for (unsigned int i = 0; i &lt; children.size(); i++) { if (i &gt;= functionToBeCalled.argumentTypes.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; children[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; children[i].columnNumber &lt;&lt; &quot;, Compiler error: Too many arguments passed to the function \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; (it expects &quot; &lt;&lt; functionToBeCalled.argumentTypes.size() &lt;&lt; &quot; arguments). Aborting the compilation (or else the compiler &quot; &quot;will segfault)!&quot; &lt;&lt; std::endl; exit(1); } assembly += convertTo(children[i], functionToBeCalled.argumentTypes[i], context) .indentBy(1) + &quot;\n&quot;; } for (unsigned int i = children.size(); i &lt; functionToBeCalled.defaultArgumentValues.size(); i++) { if (!functionToBeCalled.defaultArgumentValues[i]) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler warning: The argument #&quot; &lt;&lt; i + 1 &lt;&lt; &quot; (called \&quot;&quot; &lt;&lt; functionToBeCalled.argumentNames[i] &lt;&lt; &quot;\&quot;) of the function named \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; isn't being passed to that function, nor does it have some &quot; &quot;default value. Your program will very likely crash because of &quot; &quot;that!&quot; &lt;&lt; std::endl; // JavaScript doesn't even warn about such errors, // while C++ refuses to compile a program then. I // suppose I should take a middle ground here. assembly += convertTo(TreeNode(std::to_string( functionToBeCalled.defaultArgumentValues[i]), lineNumber, columnNumber), functionToBeCalled.argumentTypes[i], context) .indentBy(1); } assembly += &quot;)&quot;; } else if (text == &quot;ValueAt(&quot;) { if (typeOfTheCurrentNode == &quot;Character&quot;) assembly += &quot;(i32.load8_s\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer16&quot;) assembly += &quot;(i32.load16_s\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer32&quot; or std::regex_search(typeOfTheCurrentNode, std::regex(&quot;Pointer$&quot;))) assembly += &quot;(i32.load\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Integer64&quot;) assembly += &quot;(i64.load\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Decimal32&quot;) assembly += &quot;(f32.load\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n)&quot;; else if (typeOfTheCurrentNode == &quot;Decimal64&quot;) assembly += &quot;(f64.load\n&quot; + children[0].compile(context).indentBy(1) + &quot;\n)&quot;; else { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Internal compiler error: The compiler got into a &quot; &quot;forbidden state while compiling \&quot;ValueAt\&quot;, aborting!&quot; &lt;&lt; std::endl; exit(1); } } else if (text == &quot;AddressOf(&quot;) return children[0].compileAPointer(context); else { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: No rule to compile the token \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot;, quitting now!&quot; &lt;&lt; std::endl; exit(1); } return AssemblyCode(assembly, returnType); } AssemblyCode TreeNode::compileAPointer(CompilationContext context) const { if (text == &quot;ValueAt(&quot;) return children[0].compile(context); if (context.localVariables.count(text) and text.back() != '[') return AssemblyCode( &quot;(i32.sub\n\t(global.get $stack_pointer)\n\t(i32.const &quot; + std::to_string(context.localVariables[text]) + &quot;) ;;&quot; + text + &quot;\n)&quot;, AssemblyCode::AssemblyType::i32); if (context.localVariables.count(text) and text.back() == '[') { if (children.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The array \&quot;&quot; &lt;&lt; text.substr(0, text.size() - 1) &lt;&lt; &quot;\&quot; has no index in the AST. Aborting the compilation, or &quot; &quot;else the compiler will segfault!&quot; &lt;&lt; std::endl; exit(1); } return AssemblyCode( &quot;(i32.add\n\t(i32.sub\n\t\t(global.get &quot; &quot;$stack_pointer)\n\t\t(i32.const &quot; + std::to_string(context.localVariables[text]) + &quot;) ;;&quot; + text + &quot;\n\t)\n\t(i32.mul\n\t\t(i32.const &quot; + std::to_string(basicDataTypeSizes.at(getType(context))) + &quot;)\n&quot; + std::string(convertToInteger32(children[0], context).indentBy(2)) + &quot;\n\t)\n)&quot;, AssemblyCode::AssemblyType::i32); } if (context.globalVariables.count(text) and text.back() != '[') return AssemblyCode(&quot;(i32.const &quot; + std::to_string(context.globalVariables[text]) + &quot;) ;;&quot; + text, AssemblyCode::AssemblyType::i32); if (context.globalVariables.count(text) and text.back() == '[') { if (children.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The array \&quot;&quot; &lt;&lt; text.substr(0, text.size() - 1) &lt;&lt; &quot;\&quot; has no index in the AST. Aborting the compilation, or &quot; &quot;else the compiler will segfault!&quot; &lt;&lt; std::endl; exit(1); } return AssemblyCode( &quot;(i32.add\n\t(i32.const &quot; + std::to_string(context.globalVariables[text]) + &quot;) ;;&quot; + text + &quot;\n\t(i32.mul\n\t\t(i32.const &quot; + std::to_string(basicDataTypeSizes.at(getType(context))) + &quot;)\n&quot; + std::string(convertToInteger32(children[0], context).indentBy(3)) + &quot;\n\t)\n)&quot;, AssemblyCode::AssemblyType::i32); } std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Some part of the compiler attempted to get &quot; &quot;the assembly of the pointer to \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot;, which makes no sense. This could be an internal compiler &quot; &quot;error, or there could be something semantically (though not &quot; &quot;grammatically) very wrong with your program.&quot; &lt;&lt; std::endl; exit(1); return AssemblyCode(&quot;()&quot;); } std::string getStrongerType(int lineNumber, int columnNumber, std::string firstType, std::string secondType) { if (firstType == &quot;Nothing&quot; or secondType == &quot;Nothing&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Can't add, subtract, multiply or divide &quot; &quot;with something of the type \&quot;Nothing\&quot;!&quot;; exit(1); } if (std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and !std::regex_search(secondType, std::regex(&quot;Pointer$&quot;))) return firstType; if (std::regex_search(secondType, std::regex(&quot;Pointer$&quot;)) and !std::regex_search(firstType, std::regex(&quot;Pointer$&quot;))) return secondType; if (std::regex_search(firstType, std::regex(&quot;Pointer$&quot;)) and std::regex_search(secondType, std::regex(&quot;Pointer$&quot;))) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Can't add, multiply or divide two pointers!&quot;; } if (firstType == &quot;Decimal64&quot; or secondType == &quot;Decimal64&quot;) return &quot;Decimal64&quot;; if (firstType == &quot;Decimal32&quot; or secondType == &quot;Decimal32&quot;) return &quot;Decimal32&quot;; if (firstType == &quot;Integer64&quot; or secondType == &quot;Integer64&quot;) return &quot;Integer64&quot;; if (firstType == &quot;Integer32&quot; or secondType == &quot;Integer32&quot;) return &quot;Integer32&quot;; if (firstType == &quot;Integer16&quot; or secondType == &quot;Integer16&quot;) return &quot;Integer16&quot;; return firstType; } std::string TreeNode::getType(CompilationContext context) const { if (std::regex_match(text, std::regex(&quot;(^\\d+$)|(^0x(\\d|[a-f]|[A-F])+$)&quot;))) return &quot;Integer64&quot;; if (std::regex_match(text, std::regex(&quot;^\\d+\\.\\d*$&quot;))) return &quot;Decimal64&quot;; if (text == &quot;AddressOf(&quot;) { if (children.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: \&quot;AddressOf\&quot; is without the argument!&quot; &lt;&lt; std::endl; exit(1); } if (children.size() &gt; 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Can't take the address of multiple variables!&quot; &lt;&lt; std::endl; exit(1); } if (children[0].getType(context) == &quot;Nothing&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: \&quot;AddressOf\&quot; has an argument of type &quot; &quot;\&quot;Nothing\&quot;!&quot; &lt;&lt; std::endl; exit(1); } return children[0].getType(context) + &quot;Pointer&quot;; } if (text == &quot;ValueAt(&quot;) { if (children.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: \&quot;ValueAt\&quot; is without the argument!&quot; &lt;&lt; std::endl; exit(1); } if (children.size() &gt; 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Can't dereference multiple variables at once!&quot; &lt;&lt; std::endl; exit(1); } if (std::regex_search(children[0].getType(context), std::regex(&quot;Pointer$&quot;)) == false) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The argument to \&quot;ValueAt\&quot; is not a pointer!&quot; &lt;&lt; std::endl; exit(1); } return children[0].getType(context).substr( 0, children[0].getType(context).size() - std::string(&quot;Pointer&quot;).size()); } if (context.variableTypes.count(text)) return context.variableTypes[text]; if (text[0] == '&quot;') { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Internal compiler error: A pointer to the string &quot; &lt;&lt; text &lt;&lt; &quot; is being attempted to compile before the string itself has &quot; &quot;been compiled, aborting the compilation!&quot; &lt;&lt; std::endl; exit(1); } if (text == &quot;and&quot; or text == &quot;or&quot; or text == &quot;&lt;&quot; or text == &quot;&gt;&quot; or text == &quot;=&quot; or text == &quot;not(&quot; or text == &quot;invertBits(&quot;) { if (children.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The operator \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; has no operands. Aborting the compilation (or else we &quot; &quot;will segfault)!&quot; &lt;&lt; std::endl; exit(1); } if (children.size() &lt; 2 and text != &quot;not(&quot; and text != &quot;invertBits(&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The binary operator \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; has less than two operands. Aborting the compilation &quot; &quot;(or else we will segfault)!&quot; &lt;&lt; std::endl; exit(1); } return &quot;Integer32&quot;; // Because &quot;if&quot; and &quot;br_if&quot; in WebAssembly expect a // &quot;i32&quot;, so let's adapt to that. } if (text == &quot;mod(&quot;) { if (children.size() != 2) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: \&quot;mod(\&quot; operator requires two integer &quot; &quot;arguments!&quot; &lt;&lt; std::endl; exit(1); } if (std::regex_search(children[0].getType(context), std::regex(&quot;^Decimal&quot;)) or std::regex_search(children[1].getType(context), std::regex(&quot;^Decimal&quot;))) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Unfortunately, WebAssembly (unlike x86 &quot; &quot;assembly) doesn't support computing remaining of division &quot; &quot;of decimal numbers, so we can't support that either &quot; &quot;outside of compile-time constants.&quot; &lt;&lt; std::endl; exit(1); } return getStrongerType(lineNumber, columnNumber, children[0].getType(context), children[1].getType(context)); } if (text == &quot;If&quot; or text == &quot;Then&quot; or text == &quot;Else&quot; or text == &quot;While&quot; or text == &quot;Loop&quot; or text == &quot;Does&quot; or text == &quot;Return&quot;) // Or else the compiler will claim those // tokens are undeclared variables. return &quot;Nothing&quot;; if (std::regex_match(text, std::regex(&quot;^(_|[a-z]|[A-Z])\\w*\\[?&quot;))) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The variable name \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; is not declared!&quot; &lt;&lt; std::endl; exit(1); } if (text == &quot;+&quot; or text == &quot;*&quot; or text == &quot;/&quot;) { if (children.size() != 2) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The binary operator \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; doesn't have exactly two operands. Aborting the &quot; &quot;compilation (or else we will segfault)!&quot; &lt;&lt; std::endl; exit(1); } return getStrongerType(lineNumber, columnNumber, children[0].getType(context), children[1].getType(context)); } if (text == &quot;-&quot;) { if (children.size() != 2) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The binary operator \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; doesn't have exactly two operands. Aborting the &quot; &quot;compilation (or else we will segfault)!&quot; &lt;&lt; std::endl; exit(1); } if (std::regex_search(children[0].getType(context), std::regex(&quot;Pointer$&quot;)) and std::regex_search(children[1].getType(context), std::regex(&quot;Pointer$&quot;))) return &quot;Integer32&quot;; // Difference between pointers is an integer of the // same size as the pointers (32-bit). return getStrongerType(lineNumber, columnNumber, children[0].getType(context), children[1].getType(context)); } if (text == &quot;:=&quot;) { if (children.size() &lt; 2) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: The assignment operator \&quot;:=\&quot; has less &quot; &quot;than two operands. Aborting the compilation, or else the &quot; &quot;compiler will segfault.&quot; &lt;&lt; std::endl; exit(1); } if (children[1].getType(context) == &quot;Nothing&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Attempting to assign something of the &quot; &quot;type \&quot;Nothing\&quot; to a variable. Aborting the compilation!&quot; &lt;&lt; std::endl; } return children[0].getType(context); } auto potentialFunction = std::find_if(context.functions.begin(), context.functions.end(), [=](function fn) { return fn.name == text; }); if (potentialFunction != context.functions.end()) return potentialFunction-&gt;returnType; if (text.back() == '(' and basicDataTypeSizes.count(text.substr(0, text.size() - 1))) // Casting return text.substr(0, text.size() - 1); if (text.back() == '(') { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Compiler error: Function \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; is not declared!&quot; &lt;&lt; std::endl; exit(1); } if (text == &quot;?:&quot;) return getStrongerType(lineNumber, columnNumber, children[1].getType(context), children[2].getType(context)); return &quot;Nothing&quot;; } </code></pre> <p>The rest of the code is available <a href="https://github.com/FlatAssembler/AECforWebAssembly" rel="nofollow noreferrer">on my GitHub profile</a>, it's about 4'000 lines long, and I don't think most of it is relevant here.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T10:50:19.407", "Id": "247804", "Score": "2", "Tags": [ "c++", "c++11", "compiler", "webassembly" ], "Title": "AEC-to-WebAssembly compiler" }
247804
<ol> <li>below vbscript code took me 3hours just to complete trimming whitespaces of a 24MB file any tips to speed up the process below?</li> </ol> <blockquote> <pre><code>dim filename, path \'variables Set objFSO = CreateObject(&quot;Scripting.FileSystemObject&quot;) Set objFile = objFSO.GetFile(Wscript.ScriptFullName) strFolder = objFSO.GetParentFolderName(objFile) filename = replace(strFolder,&quot;jobs\SCRIPTS&quot;,&quot;shared\file&quot;) &amp; &quot;\DCS.txt&quot; converter(filename) objFile.Close function converter(filename) Const ForReading = 1 Const ForWriting = 2 Set objFSO = CreateObject(&quot;Scripting.FileSystemObject&quot;) PATH = filename Set objFile = objFSO.OpenTextFile(PATH, ForReading) Do Until objFile.AtEndOfStream strLine = objFile.Readline strLine = Trim(strLine) If Len(strLine) 0 Then strNewContents = strNewContents &amp; strLine &amp; vbcrlf End If Loop objFile.Close Set objFile = objFSO.OpenTextFile(PATH, ForWriting) objFile.Write strNewContents objFile.Close msgbox &quot;done trim on &quot; &amp; filename end function </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:10:37.380", "Id": "485278", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly. Please be more descriptive in the question body as well. What made you write this code? What does your input look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:28:00.613", "Id": "485281", "Score": "1", "body": "I rarely say this, but you should consider the `tr` command line tool, it should be way faster than this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T17:45:01.370", "Id": "485302", "Score": "1", "body": "Or even this single-line in PowerShell: `(gc $filename)| % {$_.trim()} | sc $filename`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T02:02:02.813", "Id": "485322", "Score": "0", "body": "i have no basic knowledge on powershell. But will try your suggestion. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T09:30:28.383", "Id": "485712", "Score": "0", "body": "@TediCarandang You can also use the powershell command into a batch file !" } ]
[ { "body": "<p>Being on Linux I can't run your code right now but here is an idea.</p>\n<p>I think the string concatenation must be <em>very</em> inefficient:</p>\n<pre><code>strNewContents = strNewContents &amp; strLine &amp; vbcrlf\n</code></pre>\n<p>What you are doing:</p>\n<ul>\n<li>read the source file line by line</li>\n<li>then concatenate to a big string</li>\n<li>write the string in one go at the end</li>\n</ul>\n<p>What I think you should be doing:</p>\n<ul>\n<li>open the source file for reading, and the target file for writing</li>\n<li>read the source file line by line</li>\n<li>at each iteration, write a trimmed line to the target file</li>\n<li>then close both files at the end</li>\n</ul>\n<p>That's it, read and write at the same time, that should solve your performance problem.</p>\n<p>A better alternative to the string concatenation would otherwise be the stringbuilder class if available in VBA (I don't think so). I agree with the suggestion that Powershell would be a better option. Many things can be done with one-liners.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T02:04:34.093", "Id": "485323", "Score": "0", "body": "will try your suggestion. Thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T19:04:14.820", "Id": "247822", "ParentId": "247807", "Score": "3" } }, { "body": "<p>If you're going to be writing VBScript or WSScript files then you should be using <a href=\"https://www.vbsedit.com/\" rel=\"nofollow noreferrer\">VBEdit</a>.</p>\n<p><img src=\"https://i.stack.imgur.com/42z8m.png\" alt=\"Intellisense Image\" /></p>\n<p><img src=\"https://i.stack.imgur.com/pn3tr.png\" alt=\"VBEdit Image\" /></p>\n<p>Allow it is not required you should still capitalize End, Function and Sub.</p>\n<p>Wrapping each tasks in it's own Sub or Function will make it easier to read, debug and modify your code.</p>\n<p>A Function that does not return a value should be a Sub.</p>\n<p>Avoid editing text files line by line. It is much more efficient to split the text into an array of lines, edit each element of the array, and then join the output.</p>\n<h2>Refactored Code</h2>\n<p>This code takes less than 1 second to trim each line of a 27 MB text file.</p>\n<pre><code>Dim FullFileName\nFullFileName = GetSharedFileName\n\nIf FileSystemObject.FileExists(FullFileName) Then\n TrimFileContents FullFileName\n MsgBox &quot;Done&quot;\nElse\n MsgBox &quot;File not found: &quot; &amp; FullFileName\nEnd If\n\n\nSub TrimFileContents(FullFileName)\n Dim Lines\n Lines = GetTextFileLines(FullFileName)\n \n Dim n\n\n For n = 0 To UBound(Lines)\n Lines(n) = Trim(Lines(n))\n Next\n \n OverWriteTextFile FullFileName, Join(Lines, vbNewLine)\nEnd Sub\n\nFunction GetSharedFileName\n GetSharedFileName = Replace(GetParentFolderName,&quot;jobs\\SCRIPTS&quot;,&quot;shared\\file&quot;) &amp; &quot;\\DCS.txt&quot;\nEnd Function\n\nFunction FileSystemObject\n Set FileSystemObject = CreateObject(&quot;Scripting.FileSystemObject&quot;)\nEnd Function\n\n\nFunction GetParentFolderName\n\n GetParentFolderName = FileSystemObject.GetFile(Wscript.ScriptFullName).ParentFolder.Path\n\nEnd Function\n\nFunction GetTextFileLines(FullFileName)\n Const ForReading = 1\n Dim Text\n With FileSystemObject.OpenTextFile(FullFileName, ForReading)\n Text = .ReadAll\n .Close\n End With\n \n If InStr(Text, vbNewLine) = 0 Then\n GetTextFileLines = Split(Text, vbLf)\n Else\n GetTextFileLines = Split(Text, vbNewLine)\n End If\n\nEnd Function\n\nSub OverWriteTextFile(FullFileName, Text)\n Const ForWriting = 2\n\n With FileSystemObject.OpenTextFile(FullFileName, ForWriting)\n .Write Text\n .Close\n End With\n \nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:50:17.877", "Id": "485413", "Score": "0", "body": "Thanks for the code tips. Really appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:58:27.517", "Id": "247845", "ParentId": "247807", "Score": "4" } }, { "body": "<p>As @HackSlash proposed to you in the comment : a single-line in Powershell</p>\n<p><code>(gc $filename)| % {$_.trim()} | sc $filename</code></p>\n<p>You can use the powershell command into a batch file :</p>\n<p>Just save this code below in your notepad or notepad++ and save it as : <code>Trim_File.bat</code> and drag and drop any file in order to trim it !</p>\n<hr />\n<pre class=\"lang-bat prettyprint-override\"><code>@echo off\nColor 0A &amp; Mode 80,4\nTitle Trimming Text files with Powershell and Batch by Hackoo 2020\nSet &quot;InputFile=%~1&quot;\nIf &quot;%InputFile%&quot; EQU &quot;&quot; Goto :Help\nSet &quot;OutPutFile=%~dpn1_Trimmed.txt&quot;\necho(\necho( Please wait a while ... Trimming this file &quot;%~nx1&quot;\nREM ----------------------------------------------------------\nPowershell ^\n(GC '&quot;%InputFile%&quot;'^) ^| %% {$_.trim()} ^| SC '&quot;%OutPutFile%&quot;' \nREM ----------------------------------------------------------\nIf Exist &quot;%OutPutFile%&quot; Start &quot;&quot; &quot;%OutPutFile%&quot; &amp; Exit\nREM ----------------------------------------------------------\n:Help\nColor 0C\necho(\necho( You should drag and drop a file over, \necho( this script &quot;%~nx0&quot; in order to trim it !\nTimeout /T 10 /NoBreak&gt;nul\nExit /B\nREM ----------------------------------------------------------\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T11:52:34.980", "Id": "248031", "ParentId": "247807", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T11:47:20.763", "Id": "247807", "Score": "5", "Tags": [ "vba", "vbscript" ], "Title": "Right-trimming text files" }
247807
<p>Here is my code for a move generator function for a chess engine. It's currently working perfectly and returning fully legal moves. How can i improve it.</p> <p>I am looking to improve this generator function and make it more efficient Any help is appreciated!</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;vector&gt; using std::cout; using std::cin; using std::endl; using std::vector; int board[8][8] = { {-5,-3,-2,-6,-10,-2,-3,-5}, {-1,-1,-1,-1,-1,-1,-1,-1}, {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}, {1,1,1,1,1,1,1,1}, {5,3,2,6,10,2,3,5}, }; bool check_w(){ int row; int col; bool found = false; for (int i = 0; i &lt; 8; i++){ for (int j = 0;j &lt; 8;j++){ if(board[i][j] == 10){ row = i; col = j; found = true; } } } if (found == false){ cout &lt;&lt; &quot;There is no white king on the board &quot; &lt;&lt; endl; return false; } if (row != 0 &amp;&amp; col != 0 &amp;&amp; board[row-1][col-1] == -1) return true; if (row != 0 &amp;&amp; col != 7 &amp;&amp; board[row-1][col+1] == -1) return true; int a; int b; a = row; if (row != 7){ for (;;){ a+=1; if(board[a][col] == -5 || board[a][col] == -6) return true; if (a == 7 || board[a][col] != 0) break; } } a = row; if (row != 0){ for (;;){ a-=1; if(board[a][col] == -5 || board[a][col] == -6) return true; if (a == 0 || board[a][col] != 0) break; } } b = col; if (col != 0){ for (;;){ b-=1; if (board[row][b] == -6 or board[row][b] == -5) return true; if(b == 0 || board[row][b] != 0) break; } } b = col; if (col != 7){ for (;;){ b+=1; if (board[row][b] == -6 or board[row][b] == -5) return true; if(b == 7 || board[row][b] != 0) break; } } a = row; b = col; if (a != 0 &amp;&amp; b != 0){ for (;;){ a-=1; b-=1; if (board[a][b] == -6 or board[a][b] == -2) return true; if(b == 0 || a == 0 || board[a][b] != 0) break; } } a = row; b = col; if (a != 0 &amp;&amp; b != 7){ for (;;){ a-=1; b+=1; if (board[a][b] == -6 or board[a][b] == -2) return true; if(b == 7 || a == 0 || board[a][b] != 0) break; } } a = row; b = col; if (a != 7 &amp;&amp; b != 0){ for (;;){ a+=1; b-=1; if (board[a][b] == -6 or board[a][b] == -2) return true; if(b == 0 || a == 7 || board[a][b] != 0) break; } } a = row; b = col; if (a != 7 &amp;&amp; b != 7){ for (;;){ a+=1; b+=1; if (board[a][b] == -6 or board[a][b] == -2) return true; if(b == 7 || a == 7 || board[a][b] != 0) break; } } if (row &gt; 0 &amp;&amp; col &lt; 6 &amp;&amp; board[row-1][col+2] == -3)return true; if (row &gt; 1 &amp;&amp; col &lt; 7 &amp;&amp; board[row-2][col+1] == -3)return true; if (row &lt; 7 &amp;&amp; col &lt; 6 &amp;&amp; board[row+1][col+2] == -3)return true; if (row &lt; 6 &amp;&amp; col &lt; 7 &amp;&amp; board[row+2][col+1] == -3)return true; if (row &lt; 6 &amp;&amp; col &gt; 0 &amp;&amp; board[row+2][col-1] == -3)return true; if (row &lt; 7 &amp;&amp; col &gt; 1 &amp;&amp; board[row+1][col-2] == -3)return true; if (row &gt; 1 &amp;&amp; col &gt; 0 &amp;&amp; board[row-2][col-1] == -3)return true; if (row &gt; 1 &amp;&amp; col &gt; 0 &amp;&amp; board[row-2][col-1] == -3)return true; if (row != 7 &amp;&amp; board[row+1][col] == 10) return true; if (row != 0 &amp;&amp; board[row-1][col] == 10) return true; if (col != 7 &amp;&amp; board[row][col+1] == 10) return true; if (col != 0 &amp;&amp; board[row][col-1] == 10) return true; if (row != 0 &amp;&amp; col != 0 &amp;&amp; board[row-1][col-1] == 10) return true; if (row != 0 &amp;&amp; col != 7 &amp;&amp; board[row-1][col+1] == 10) return true; if (row != 7 &amp;&amp; col != 0 &amp;&amp; board[row+1][col-1] == 10) return true; if (row != 7 &amp;&amp; col != 0 &amp;&amp; board[row+1][col+1] == 10) return true; return false; } vector&lt;int&gt; push(int row,int col,int desrow,int descol){ vector&lt;int&gt; move; move.push_back(row); move.push_back(col); move.push_back(desrow); move.push_back(descol); return move; } void undomove(int original,vector&lt;int&gt; Move){ board[Move[0]][Move[1]] = board[Move[2]][Move[3]]; board[Move[2]][Move[3]] = original; } int perform(vector&lt;int&gt; Move){ int original; original = board[Move[2]][Move[3]]; board[Move[2]][Move[3]] = board[Move[0]][Move[1]]; board[Move[0]][Move[1]] = 0; return original; } vector&lt;vector&lt;int&gt;&gt; generate_moves_w(){ vector&lt;vector&lt;int&gt;&gt; pseudomoves,legal_moves; vector&lt;int&gt; move; int original,a,b; for(int row = 0; row &lt; 8; row++){ for(int col = 0;col &lt; 8;col++){ if (!board[row][col]) continue; if (board[row][col] == 1 &amp;&amp; row != 0){ if (row == 6 &amp;&amp; board[row-1][col] == 0 &amp;&amp; board[row-2][col] == 0) pseudomoves.push_back(push(row,col,row-2,col)); if (board[row-1][col] == 0) pseudomoves.push_back(push(row,col,row-1,col)); if (col != 0 &amp;&amp; board[row-1][col-1] &lt; 0) pseudomoves.push_back(push(row,col,row-1,col-1)); if (col != 7 &amp;&amp; board[row-1][col+1] &lt; 0) pseudomoves.push_back(push(row,col,row-1,col+1)); } else if (board[row][col] == 5){ a = row; b = col; if (a != 0){ for (;;){ a-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a!=7){ for(;;){ a+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (b!= 0){ for(;;){ b-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || b == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } a =row; b = col; if (b != 7){ for(;;){ b+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || b == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } } else if (board[row][col] == 3){ if (row &gt; 0 &amp;&amp; col &lt; 6 &amp;&amp; board[row-1][col+2] &lt;= 0)pseudomoves.push_back(push(row,col,row-1,col+2)); if (row &gt; 1 &amp;&amp; col &lt; 7 &amp;&amp; board[row-2][col+1] &lt;= 0)pseudomoves.push_back(push(row,col,row-2,col+1)); if (row &lt; 7 &amp;&amp; col &lt; 6 &amp;&amp; board[row+1][col+2] &lt;= 0)pseudomoves.push_back(push(row,col,row+1,col+2)); if (row &lt; 6 &amp;&amp; col &lt; 7 &amp;&amp; board[row+2][col+1] &lt;= 0)pseudomoves.push_back(push(row,col,row+2,col+1)); if (row &lt; 6 &amp;&amp; col &gt; 0 &amp;&amp; board[row+2][col-1] &lt;= 0)pseudomoves.push_back(push(row,col,row+2,col-1)); if (row &lt; 7 &amp;&amp; col &gt; 1 &amp;&amp; board[row+1][col-2] &lt;= 0)pseudomoves.push_back(push(row,col,row+1,col-2)); if (row &gt; 1 &amp;&amp; col &gt; 0 &amp;&amp; board[row-2][col-1] &lt;= 0)pseudomoves.push_back(push(row,col,row-2,col-1)); if (row &gt; 0 &amp;&amp; col &gt; 1 &amp;&amp; board[row-1][col-2] &lt;= 0)pseudomoves.push_back(push(row,col,row-1,col-2)); } else if (board[row][col] == 2){ a = row; b = col; if (a != 0 &amp;&amp; b != 0){ for (;;){ a-=1; b-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 0 || b == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 0 &amp;&amp; b != 7){ for (;;){ a-=1; b+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 0 || b == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 7 &amp;&amp; b != 7){ for (;;){ a+=1; b+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 7 || b == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 7 &amp;&amp; b != 0){ for (;;){ a+=1; b-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 7 || b == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } } else if (board[row][col] == 6){ a = row; b = col; if (a != 0 &amp;&amp; b != 0){ for (;;){ a-=1; b-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 0 || b == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 0 &amp;&amp; b != 7){ for (;;){ a-=1; b+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 0 || b == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 7 &amp;&amp; b != 7){ for (;;){ a+=1; b+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 7 || b == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 7 &amp;&amp; b != 0){ for (;;){ a+=1; b-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 7 || b == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b])pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a != 0){ for (;;){ a-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (a!=7){ for(;;){ a+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || a == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } a = row; b = col; if (b!= 0){ for(;;){ b-=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || b == 0){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } a =row; b = col; if (b != 7){ for(;;){ b+=1; if (board[a][b] &gt; 0) break; if (board[a][b] &lt; 0 || b == 7){ pseudomoves.push_back(push(row,col,a,b)); break; } if(!board[a][b]) pseudomoves.push_back(push(row,col,a,b)); } } } else if (board[row][col] == 10){ if (row != 7 &amp;&amp; board[row+1][col] &lt;= 0)pseudomoves.push_back(push(row,col,row+1,col)); if (row != 0 &amp;&amp; board[row-1][col] &lt;= 0)pseudomoves.push_back(push(row,col,row-1,col)); if (col != 7 &amp;&amp; board[row][col+1] &lt;= 0)pseudomoves.push_back(push(row,col,row,col+1)); if (col != 0 &amp;&amp; board[row][col-1] &lt;= 0)pseudomoves.push_back(push(row,col,row,col-1)); if(row != 0 &amp;&amp; col!= 0 &amp;&amp; board[row-1][col-1] &lt;= 0)pseudomoves.push_back(push(row,col,row-1,col-1)); if(row != 0 &amp;&amp; col!= 7 &amp;&amp; board[row-1][col+1] &lt;= 0)pseudomoves.push_back(push(row,col,row-1,col+1)); if(row != 7 &amp;&amp; col!= 0 &amp;&amp; board[row+1][col-1] &lt;= 0)pseudomoves.push_back(push(row,col,row+1,col-1)); if(row != 7 &amp;&amp; col!= 7 &amp;&amp; board[row+1][col+1] &lt;= 0)pseudomoves.push_back(push(row,col,row+1,col+1)); } }//col loop }//row loop for (long unsigned int i = 0; i &lt; pseudomoves.size(); i++){ original = perform(pseudomoves[i]); if (check_w() == false) legal_moves.push_back(pseudomoves[i]); undomove(original,pseudomoves[i]); } return legal_moves; } int main(){ vector&lt;vector&lt;int&gt;&gt; legal_moves = generate_moves_w(); for (unsigned long int i = 0;i &lt; legal_moves.size();i++) cout &lt;&lt; legal_moves[i][0] &lt;&lt; &quot; &quot; &lt;&lt; legal_moves[i][1] &lt;&lt; &quot; &quot; &lt;&lt; legal_moves[i][2] &lt;&lt; &quot; &quot; &lt;&lt; legal_moves[i][3] &lt;&lt; endl; return 0; } </code></pre> <p>The board is represented by an 8x8 integer array and the pieces are represented with numbers. Black pieces are negative of the same values white pieces use.</p> <ul> <li>pawn - 1</li> <li>bishop - 2</li> <li>rook - 5</li> <li>knight - 3</li> <li>queen - 6</li> <li>king - 10</li> </ul> <p>A 0 in a place means that the position is empty. No piece is on it.</p> <p>I have not added pawn promotion,en passant, and castle.</p> <p>This is how the generator function works:</p> <p>There are two main loops, outer loop for iterating through each row, inner loop for iterating through each column in each row. When I start iterating, if I find a 0, I skip the iteration. Hence, <code>if(!board[row][col]) continue;</code></p> <p>If i do find piece, a set of if statements check which piece it is, and accordingly add a vector of a possible move in the format <code>[initial row, initial column, desired row,desired column</code>]</p> <p>After I generate all the moves, that means after it exits the loops, i need to iterate through all of them once again to validate them. Because if a piece was protecting a king from a <em>check</em>, it cannot be moved. I use the functions i have defined, which are <code>perform()</code> and <code>undomove()</code> to perform each move in the vector, add it to a new vector called <code>legal_moves</code> only <strong>IF</strong> the function <code>check()</code> returns <strong>false</strong>. this process returns a set of fully legal moves. However i wish to optimize it as i can perform this well over 50,000 times in a chess engine</p> <p><strong>MY LOGIC BEHIND GENERATING MOVES FOR EACH PIECE</strong></p> <ul> <li><p>Pawn: A pawn has only a few conditions, so i didn't use any loops. Just hard code. I dont generate any moves for the pawn if the <code>row</code> in the loop is 7. Because it cannot move front. If it can however. I check whether board[row+1][col] is 0. If yes then i add it to pseudomoves by performing this function <code>pseudomoves.push_back(push(row,col,row-1,col));</code>. This statement is applicable to all. The first two arguments are co-ordinates of the initial position. Second two are co-ordinates of the desired position. For pawn i also check whether an enemy piece is available diagonally.</p> </li> <li><p>Bishop: The moves of the bishop is done simply by using ** 4 loops ** Each loop for a direction it can move. Let's say i want to generate its moves top left. That means rows decreasing and col decreasing. I enter an infinite loop in which at each iteration. The increment/decrement happens(according to the direction). If at the new position i find a 0. I add it to <em>pseudomoves</em> and continue. If i find my own piece or if an edge has been reached, I break out of the loop. Lastly if I find an opponent's piece, add it to <em>pseudomoves</em> and then break , as it counts as a possible position. This same logic applies for all directions.</p> </li> <li><p>Rook:</p> </li> </ul> <p>Same logic as bishop</p> <ul> <li>Queen:</li> </ul> <p>moves of rook + moves of bishop</p> <ul> <li><p>King: total 8 directions in which the king can move. If the position is empty or has an opponents piece, add it to pseudomoves and check the next direction.</p> </li> <li><p>Knight: Easiest out of all. At max 8 possible moves of the knight. Just increments and decrements in row and column. If the position is empty or has an opponents piece, add it to pseudomoves and check the next direction.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T17:55:56.653", "Id": "485304", "Score": "0", "body": "[Edit] the question to include compilable code. At a minimum you're missing the function definition for `check_w`. Also, the title should state what your code does, not the concerns you have with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T18:28:37.993", "Id": "485307", "Score": "0", "body": "Okay i will make the changes right away, sorry for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T19:38:29.700", "Id": "485311", "Score": "0", "body": "added them both" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T20:45:13.940", "Id": "485316", "Score": "0", "body": "can you please update your question so that there is a SINGLE block of code, including the usage? as currently written, your post is very hard to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T03:14:49.267", "Id": "485328", "Score": "0", "body": "i thought it would've been like that with a single block ," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:46:54.353", "Id": "485345", "Score": "0", "body": "I have included everything now, single block of code and explained the concept next" } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Don't abuse <code>using namespace std</code></h2>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n<h2>Reconsider container choices</h2>\n<p>A <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code> is not likely to be an optimal choice for your data structure. Because a chess move, in this code is actually two pairs of coordinates (source and destination), I'd suggest that either a <code>std::array</code> or a custom type. A <code>class</code> representing a board location would be very handy for a number of things, as I'll demonstrate later. Finally rather than <code>int board[8][8]</code> a choice that would be just as efficient but would allow better use of standard algorithms would be <code>std::array&lt;int, 64&gt;</code> or better yet, make it a class.</p>\n<h2>Use more whitespace for legibility</h2>\n<p>The code contains this terribly long line:</p>\n<pre><code>if(row != 7 &amp;&amp; col!= 7 &amp;&amp; board[row+1][col+1] &lt;= 0)pseudomoves.push_back(push(row,col,row+1,col+1));\n</code></pre>\n<p>It could be made more legible by not cramming it all onto a single line:</p>\n<pre><code>if (row != 7 &amp;&amp; col!= 7 &amp;&amp; board[row+1][col+1] &lt;= 0) {\n pseudomoves.push_back(push(row,col,row+1,col+1));\n}\n</code></pre>\n<h2>Use an <code>enum</code> for clarity</h2>\n<p>Right now there are lots of <em>magic numbers</em> in the code to signify the various chess pieces. For example, the white King is represented as 10 and the black King as -10. The <code>check_w</code> routine includes this line:</p>\n<pre><code>if(board[i][j] == 10){\n</code></pre>\n<p>That's in the middle of a couple of nested loops looking for the white king.</p>\n<p>Why not make an <code>enum class</code> instead?</p>\n<pre><code>enum class Piece{k=-10, q=-6, r, n=-3, b, p, x, P, B, N, R=5, Q, K=10};\n\nif(board[i][j] == Piece::K){\n</code></pre>\n<p>Now it's a bit clearer what we're looking for without having to rely on the comment.</p>\n<h2>Rethink the code structure</h2>\n<p>Right now, it appears that you will have to duplicate the code for <code>generate_moves_w</code> to create the corresponding <code>generate_moves_b</code>, and a similar story with <code>check_w</code>. That really doesn't make much sense because the rules of chess are the same for both players. Also, all of the details of how each piece could move are in one long nested loop within <code>generate_moves_w</code>. An alternative approach would be to have one routine per type of piece, greatly simplifying the code and making it much easier to understand and test.</p>\n<h2>Don't use <code>std::endl</code> when '\\n' will do</h2>\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>.</p>\n<h2>Eliminate global variables where practical</h2>\n<p>The code declares and uses a global variable <code>board</code>. Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult. It also makes the code harder to reuse. For all of these reasons, it's generally far preferable to eliminate global variables and to instead create an object to encapsulate both the data and the relevant functions that operate on it. In this code, one obvious class would be a <code>ChessBoard</code>.</p>\n<h2>Rethink the algorithm</h2>\n<p>Right now, the code searches the entire board for pieces, recalculates all possible moves, tests each possible move for a check and then finally returns a list of valid moves. If your interest is performance, the first thing to think about is how to avoid so much recalculation. For instance, in the opening stages of the game, the possible moves for either King are unaltered by most moves. If you calculate it at the beginning of the game, you don't really need to recalculate for any move -- just certain ones. Also, there are two important and related concepts. The first concept is the possible moves each piece has available, but the other is which pieces threaten or protect others. The calculations for threaten/protect are identical -- the only difference is whether the pieces are opposite colors or not. You could use this to simplify, for example, your <code>check_w</code> code.</p>\n<h2>An example</h2>\n<p>Here's a partial refactoring of the code to show how it might look using classes.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Chess {\n class BoardLocation {\n int rank, file;\n public:\n BoardLocation(int rank, int file) :\n rank{rank}, file{file}\n { \n if (rank &lt; 0 || file &lt; 0 || rank &gt; 7 || file &gt; 7) {\n throw std::invalid_argument(&quot;rank and file must be in the range [0,7]&quot;);\n }\n }\n int Rank() const { return rank; }\n int File() const { return file; }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const BoardLocation&amp; bl) {\n return out &lt;&lt; char('a'+bl.File()) &lt;&lt; char('8'-bl.Rank());\n }\n };\npublic:\n enum class Piece{k, q, r, n, b, p, x, P, B, N, R, Q, K};\n struct ChessMove {\n BoardLocation from;\n BoardLocation to;\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const ChessMove&amp; m);\n };\n\n Chess();\n Piece operator()(int a, int b) const {\n return board[a][b];\n }\n Piece operator()(const BoardLocation&amp; bl) const {\n return board[bl.Rank()][bl.File()];\n }\n Piece &amp;operator()(const BoardLocation&amp; bl) {\n return board[bl.Rank()][bl.File()];\n }\n bool isBlack(int a, int b) const {\n auto v{board[a][b]};\n return v==Piece::k || v==Piece::q || v==Piece::r || v==Piece::n || v==Piece::b || v==Piece::p;\n }\n bool isWhite(int a, int b) const {\n auto v{board[a][b]};\n return v==Piece::K || v==Piece::Q || v==Piece::R || v==Piece::N || v==Piece::B || v==Piece::P;\n }\n Piece perform(ChessMove &amp;m);\n void undomove(Piece original, const ChessMove&amp; m);\n bool check_w() const;\n std::vector&lt;ChessMove&gt; generate_moves_w();\n static const std::unordered_map&lt;Chess::Piece, char&gt; piecename; \nprivate:\n Piece board[8][8];\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:27:22.017", "Id": "485407", "Score": "0", "body": "This is really helpful! I am just a begginner 14 year old student trying to get my feet wet. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:30:07.267", "Id": "485408", "Score": "0", "body": "Can you please give me an example so that i can better understand how to implement classes for this : )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:45:47.350", "Id": "485411", "Score": "0", "body": "I've added an example of a `Chess` class that incorporates many of these things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-23T17:04:43.257", "Id": "486369", "Score": "0", "body": "Edward I really wanted to update since you have helped me improve a lot and lot, I learnt a lot about object oriented programming and inculcated classes into the program, I made the code 1000 times cleaner. Used strings instead of vector<vector<int>> . The whole code reduced from 1000+ lines to 640. And from being about 17 seconds to generate moves 500000 times, to .. wait for it..... 4 seconds!. I really think it imrpoved a lot" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-23T18:22:18.520", "Id": "486372", "Score": "0", "body": "Well done! I’m happy that you found the review helpful." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:42:22.337", "Id": "247859", "ParentId": "247811", "Score": "2" } } ]
{ "AcceptedAnswerId": "247859", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T12:58:30.787", "Id": "247811", "Score": "4", "Tags": [ "c++", "performance", "chess" ], "Title": "C++ generator function for a Chess game" }
247811
<p>The goal here is to pull all alerts from a single iterable:</p> <pre><code>obj = Alerts(db, args) for alert in obj.alerts() pass </code></pre> <p>Now, I need to add a few more sources and I'm not sure if this is a good approach to instantiate all classes in the <code>AllAlerts</code> constructor? I also don't like the fact that I'll have to add them to the <code>self.sources</code> attribute each time there is a new one (achieving loose coupling).</p> <p>Based on the code snippet provided below could you recommend some different, perhaps a better approach?</p> <p><strong>Code:</strong></p> <pre><code>from itertools import chain from . import mappings from .utils import converter class BaseSource(object): def __init__(self, db, args): self.args = args self.db = db def alerts(self): raise NotImplementedError def _data(self, mapping, source): &quot;&quot;&quot; This method do the parsing based on data source. &quot;&quot;&quot; for entry in self._raw_data(): yield converter(source, mapping, entry) class NagiosSource(BaseSource): def __init__(self, *args, **kwargs): ... super().__init__(*args, **kwargs) def _raw_data(self): &quot;&quot;&quot; The logic to get the data from Nagios. &quot;&quot;&quot; def alerts(self): mapping = mappings.nagios return self._data(mapping, &quot;nagios&quot;) class ZabbixSource(BaseSource): def __init__(self, *args, **kwargs): ... super().__init__(*args, **kwargs) def _raw_data(self): &quot;&quot;&quot; The logic to get the data from Zabbix. &quot;&quot;&quot; def alerts(self): mapping = mappings.zabbix return self._data(mapping, &quot;zabbix&quot;) class AllAlerts(BaseSource): def __init__(self, db, args): self.sources = ( NagiosSource(db, args), ZabbixSource(db, args), ) super().__init__(db, args) def alerts(self): return chain.from_iterable(s.data() for s in self.sources) </code></pre> <p>I though about adding a class decorator that will register all sources but then again, I would have to use a global variable and not sure how I could pass args when creating objects...</p> <p><strong>test.py:</strong></p> <pre><code>sources = set() def register(cls): sources.add(cls()) return cls @register class NagiosSource: pass @register class ZabbixSource: pass </code></pre> <p><strong>Test:</strong></p> <pre><code>$ python test.py {&lt;__main__.ZabbixSource object at 0x7f1a3b1d26d0&gt;, &lt;__main__.NagiosSource object at 0x7f1a3b1d2760&gt;} </code></pre>
[]
[ { "body": "<h1>Recording Subclasses</h1>\n<p>As of Python 3.6, there is an easy way to gather all your subclasses together, without having to risk the error-prone method of manually creating an <code>AllAlerts</code> subclass and listing all of the subclasses in it. The key is <a href=\"https://docs.python.org/3/reference/datamodel.html?highlight=__init_subclass__#object.__init_subclass__\" rel=\"nofollow noreferrer\"><code>object.__init_subclass__(cls)</code></a>. It is called when a subclass is defined.</p>\n<pre><code>class BaseSource:\n subclasses = []\n\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.subclasses.append(cls)\n print(&quot;Registered&quot;, cls)\n</code></pre>\n<p>Now, whenever a subclass of <code>BaseSource</code> is defined, that subclass will be added to the <code>BaseSource.subclass</code> list.</p>\n<p>Of course, <code>AllAlerts</code> did more than this. It created one instance of each source subclass and passed the same arguments in the constructor of each. We'll have to do that in a <code>@classmethod</code> of the base class. It also used itertools to chain together all of the alerts from each of those source instances, so we'll have to record those source instances, and provide a <code>@classmethod</code> for getting that chain of alerts.</p>\n<pre><code>from itertools import chain\n\nclass BaseSource:\n subclasses = []\n\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.subclasses.append(cls)\n print(&quot;Registered&quot;, cls)\n\n @classmethod\n def init_all(cls, db, args):\n &quot;&quot;&quot;\n Create one instance for each subclass, constructed using the given\n 'db' and 'args' values.\n &quot;&quot;&quot;\n cls.sources = (subclass(db, args) for subclass in cls.subclasses)\n\n @classmethod\n def all_alerts(cls):\n &quot;&quot;&quot;\n Return an iterable of all alerts from all subclass sources\n &quot;&quot;&quot;\n return chain.from_iterable(src.alerts() for src in cls.sources)\n\n def __init__(self, db, args):\n self.db = db\n self.args = args\n\n def alerts(self):\n &quot;&quot;&quot;\n Return an iterable of alerts for this class\n &quot;&quot;&quot;\n raise NotImplementedError()\n</code></pre>\n<p>With this base class, you just need to define the source subclasses, as many as you like. There is no need to remember all of the classes; the base class does that for you:</p>\n<pre><code>class NagiosSource(BaseSource):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n print(&quot;Constructed Nagios Source&quot;)\n\n def alerts(self):\n yield &quot;Alert 1&quot;\n yield &quot;Alert 2&quot;\n\n\nclass ZabbixSource(BaseSource):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n print(&quot;Constructed Zabbix Source&quot;)\n\n def alerts(self):\n yield &quot;Alert A&quot;\n yield &quot;Alert B&quot;\n</code></pre>\n<p>After all of the subclass definitions have been read in, you will have to initialize them with the appropriate <code>db</code> and <code>args</code>, like you created an <code>AllAlerts</code> instance, which created all of the source objects. And then you can request all alerts from the base class:</p>\n<pre><code>BaseSource.init_all(&quot;mydb&quot;, (1, 2, 3))\n\nprint(list(BaseSource.all_alerts()))\n</code></pre>\n<p>Output of above:</p>\n<pre><code>Registered &lt;class '__main__.NagiosSource'&gt;\nRegistered &lt;class '__main__.ZabbixSource'&gt;\nConstructed Nagios Source\nConstructed Zabbix Source\n['Alert 1', 'Alert 2', 'Alert A', 'Alert B']\n&gt;&gt;&gt; \n</code></pre>\n<h1>Raise objects, not classes</h1>\n<p>Your <code>BaseSource</code> had the method:</p>\n<pre><code> def alerts(self):\n raise NotImplementedError\n</code></pre>\n<p>This appears to be raise a <code>class</code> instead of an <em>instance</em> of a <code>class</code>. You should write:</p>\n<pre><code> def alerts(self):\n raise NotImplementedError()\n</code></pre>\n<p>Using instances allows you to have arguments, which helps describe the error. What does &quot;Not Implemented&quot; mean? Does it mean &quot;Not Implemented Yet&quot;, as in a later version of the library is expected to provide an implementation? No! We need subclasses to provide the implementation.</p>\n<pre><code> def alerts(self):\n raise NotImplementedError(&quot;This method must be overridden in derived classes&quot;)\n</code></pre>\n<h1>Public methods need docstrings</h1>\n<p>You provide docstrings for <code>_data()</code> and <code>_raw_data()</code>, but not for <code>alerts()</code>. This is backwards.</p>\n<p>The leading underscore represents private methods. An external caller does not need to know how to call them, because they are private.</p>\n<p>On the other hand, public functions (without the leading underscore) are expected to be called by external callers. And someone writing the code which uses these Source objects may want to know how to call the methods. So they may type:</p>\n<pre><code>&gt;&gt;&gt; help(NagiosSource)\n</code></pre>\n<p>and would reasonable expect to get information about how to use the class and its public method. The docstring for <code>_data</code> and <code>_raw_data</code> would not be provided, because of the leading underscore.</p>\n<p>You may provide docstrings for private methods (the expectation is the public methods would all have been documented first), but code comments may be just as useful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T05:42:11.920", "Id": "247881", "ParentId": "247813", "Score": "3" } } ]
{ "AcceptedAnswerId": "247881", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T13:27:08.287", "Id": "247813", "Score": "5", "Tags": [ "python", "design-patterns" ], "Title": "Instantiate multiple classes in another class, invoke method from multiple classes" }
247813
<p>I need help in rewriting my code to be less repetitive. I am used to coding procedural and not object-oriented. My scala program is for Databricks.</p> <p>how would you combine cmd 3 and 5 together? Does this involve using polymorphism? My notebook first import parquet staging files in parallel. Then it run notebooks in parallel. I am repeating my parallel function, tryNotebookRun, twice, but for different scenarios.</p> <pre><code>////cmd 1 // Set Environment var client = &quot;client&quot; var storageAccount = &quot;storageaccount&quot; var container = client + &quot;-dl&quot; // Connect to Azure DataLake spark.conf.set( &quot;fs.azure.account.key.&quot; + storageAccount + &quot;.dfs.core.windows.net&quot;, dbutils.secrets.get(scope = storageAccount, key = storageAccount) ) // Set database spark.sql(&quot;USE &quot; + client) ////cmd 2 //import needed packages import scala.concurrent.duration._ import scala.concurrent.{Future, blocking, Await} import scala.concurrent.ExecutionContext import scala.language.postfixOps import scala.util.control.NonFatal import scala.util.{Try, Success, Failure} import java.util.concurrent.Executors import com.databricks.WorkflowException import collection.mutable._ import scala.collection.mutable.Map ////cmd 3 ///this part set up functions and class for importing stg parquet files as spark tables in parallel // the next two functions are for retry purpose. if running a process fail, it will retry def tryRun (path: String, schema: String, table: String): Try[Any] = { Try{ dbutils.fs.rm(s&quot;dbfs:/user/hive/warehouse/$client.db/$schema$table&quot;, true) spark.sql(s&quot;DROP TABLE IF EXISTS $schema$table&quot;) var df = sqlContext.read.parquet(s&quot;$path/$schema$table/*.parquet&quot;) df.write.saveAsTable(schema + table) } } def runWithRetry(path: String, schema: String, table: String, maxRetries: Int = 3) = { var numRetries = 0 while (numRetries &lt; maxRetries){ tryRun(path, schema, table) match { case Success(_) =&gt; numRetries = maxRetries case Failure(_) =&gt; numRetries = numRetries + 1 } } } case class tableInfo(path: String, schema: String, table: String) def parallelRuns(tableList: scala.collection.mutable.MutableList[tableInfo]): Future[Seq[Any]] = { val numRunsInParallel = 5 // If you create too many notebooks in parallel the driver may crash when you submit all of the jobs at once. // This code limits the number of parallel notebooks. implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(numRunsInParallel)) Future.sequence( tableList.map { item =&gt; Future { runWithRetry(item.path, item.schema, item.table) } .recover { case NonFatal(e) =&gt; s&quot;ERROR: ${e.getMessage}&quot; } } ) } ////cmd 4 ///Load STG data in the format of Parquet files from Data Lake to Databrick //Variables val schema = &quot;STG&quot; val dataFolder = List(schema) var tableCollection = MutableList[tableInfo]() //List of data to be added val tableList = List( &quot;AdverseEvents&quot;, &quot;Allergies&quot; ) for (table &lt;- tableList){ for (folder &lt;- dataFolder){ var path = s&quot;abfss://$container@$storageAccount.dfs.core.windows.net/$folder&quot; var a = tableInfo(path, schema, table) tableCollection += a } } val res = parallelRuns(tableCollection) Await.result(res, 3000000 seconds) // this is a blocking call. res.value ////cmd 5 ///this part set up functions and class for running cdm notebooks in parallel /// the next two functions are for retry purpose. if running a process fail, it will retry def tryNotebookRun (path: String, timeout: Int, parameters: Map[String, String] = Map.empty[String, String]): Try[Any] = { Try( if (parameters.nonEmpty){ dbutils.notebook.run(path, timeout, parameters) } else{ dbutils.notebook.run(path, timeout) } ) } def runWithRetry(path: String, timeout: Int, parameters: Map[String, String] = Map.empty[String, String], maxRetries: Int = 3) = { var numRetries = 0 while (numRetries &lt; maxRetries){ tryNotebookRun(path, timeout, parameters) match { case Success(_) =&gt; numRetries = maxRetries case Failure(_) =&gt; numRetries = numRetries + 1 } } } case class NotebookData(path: String, timeout: Int, parameters: Map[String, String] = Map.empty[String, String]) def parallelNotebooks(notebooks: Seq[NotebookData]): Future[Seq[Any]] = { val numNotebooksInParallel = 5 // If you create too many notebooks in parallel the driver may crash when you submit all of the jobs at once. // This code limits the number of parallel notebooks. implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(numNotebooksInParallel)) val ctx = dbutils.notebook.getContext() Future.sequence( notebooks.map { notebook =&gt; Future { dbutils.notebook.setContext(ctx) runWithRetry(notebook.path, notebook.timeout, notebook.parameters) } .recover { case NonFatal(e) =&gt; s&quot;ERROR: ${e.getMessage}&quot; } } ) } ////cmd 6 //run notebooks in parallel val notebooks = Seq( NotebookData(&quot;AUDAdverseEvents&quot;, 0, Map(&quot;client&quot;-&gt;client)), NotebookData(&quot;AUDAllergies&quot;, 0, Map(&quot;client&quot;-&gt;client)) ) val res = parallelNotebooks(notebooks) Await.result(res, 3000000 seconds) // this is a blocking call. res.value <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-27T08:12:28.370", "Id": "498140", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<ul>\n<li><p>in <code>tryRun()/runWithRetry()</code>:</p>\n<ul>\n<li>Naming is extremely poor. The function name should show what it does. &quot;Run&quot; what? The comment doesn't even help -- it just says &quot;a process&quot;. What does it <em>do</em>?</li>\n<li>There is no need to use a <code>Try/Success/Failure</code> construct as you are capturing neither the result of the process on success nor the exception on failure. You can just use <a href=\"https://docs.scala-lang.org/overviews/scala-book/try-catch-finally.html\" rel=\"nofollow noreferrer\">the standard <code>try/catch</code> keywords</a>.</li>\n<li>You don't specify the return type of <code>runWithRetry()</code> - what's your intention? How is the caller supposed to know if it succeeded or failed?</li>\n<li>Why don't you use the <code>case class tableInfo</code> as a parameter to these? More importantly from an OO point of view, why aren't these methods defined inside the class?</li>\n</ul>\n</li>\n<li><p>in <code>parallelRuns()</code>:</p>\n<ul>\n<li>Why are you using (explicitly, in fact) a <code>MutableList</code>? The list is not mutated, and seems to have no need to be mutated.</li>\n<li>Why are you explicitly defining the parallelism instead of just using <code>.par</code> to get a Parallel Collection?</li>\n<li>What is the comment about &quot;notebooks&quot; referring to?</li>\n<li>What is the <code>.recover {}</code> clause supposed to do? The <code>Future</code>, as written, can't fail.</li>\n</ul>\n</li>\n<li><p>in cmd 4:</p>\n<ul>\n<li>Please use <code>yield</code> inside the <code>for</code> to create a list, instead of building up the list item by item.</li>\n</ul>\n</li>\n<li><p>in cmd 5:</p>\n<ul>\n<li>Create a class that does the necessary steps, and then have two things that inherit from it, specializing as necessary.</li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-10T21:56:36.793", "Id": "507521", "Score": "0", "body": "hello, thank you for the comments. I do have an updated version that is cleaner now. These are great tips" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-27T05:19:03.533", "Id": "252739", "ParentId": "247814", "Score": "2" } } ]
{ "AcceptedAnswerId": "252739", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T14:17:44.697", "Id": "247814", "Score": "3", "Tags": [ "object-oriented", "scala", "apache-spark" ], "Title": "Rewriting scala code in object-oriented style style to reduce repetitive use of similar functions" }
247814
<p>I made a chatroom with a server and client python files, using <code>Sockets</code> and <code>Threading</code> as a project. I'm interested to acquire advice, and optimizations i could make to my program. Also please give me tips on <code>sockets</code> and <code>threading</code> in general, because I'm fairly new to the topic, and i would want to learn whatever is relevant in <code>sockets</code> in general. Thank you.</p> <p>Server.py:</p> <pre><code>import threading # constants DISCONNECT_COMMAND = '/disconnect' HEADER_LENGTH = 10 FORMAT = 'utf-8' IP = '127.0.1.1' PORT = 1234 SERVER_ADDRESS = (IP, PORT) print(&quot;[SERVER] Starting Server...&quot;) # creating and listening to socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(SERVER_ADDRESS) server_socket.listen() # clients information clients = {} # {client_socket: {'username': username, 'address': address}} messages = [] # def close_connection(client_socket): print(f&quot;[DISCONNECTION] {clients[client_socket]['username']} has disconnected!&quot;) del clients[client_socket] client_socket.close() def send_message(socket, message): try: socket.send(bytes(f&quot;{len(message):&lt;{HEADER_LENGTH}}&quot;, FORMAT)) socket.send(bytes(message, FORMAT)) except: print(f&quot;[ERROR] SENDING '{message}' to {clients[socket]['username']}&quot;) def receive_message(client_socket): while True: message_length = client_socket.recv(HEADER_LENGTH).decode(FORMAT) message = client_socket.recv(int(message_length)).decode(FORMAT) return message def send_to_all_clients(message, sender_socket): user_message = f&quot;{clients[sender_socket]['username']} &gt; {message}&quot; messages.append(user_message) print(user_message) for client_socket in clients: if sender_socket != client_socket: send_message(client_socket, user_message) def handle_client(client_socket, client_address): # user name and server prompt for new connections username = receive_message(client_socket) clients[client_socket] = {'username': username, 'address': client_address} print(f&quot;[ACTIVE CONNECTIONS] {threading.active_count() - 1}&quot;) print(f&quot;[NEW CONNECTION] {username} has connected!&quot;) # server prompt for connection, and receiving previous messages of server. send_message(client_socket, f'You have connected to the server with the username &quot;{clients[client_socket][&quot;username&quot;]}&quot;!') send_message(client_socket, str(len(messages))) # sending of previous messages to new client for i in range(len(messages)): send_message(client_socket, messages[i]) # receiving messages and sending it to other clients connected = True while connected: try: message = receive_message(client_socket) if message == DISCONNECT_COMMAND: connected = False send_to_all_clients(message, client_socket) except: connected = False close_connection(client_socket) # listening for clients print(&quot;[LISTENING] Listening for Clients&quot;) while True: client_socket, client_address = server_socket.accept() handling_thread = threading.Thread(target=handle_client, args=[client_socket, client_address]) handling_thread.start() </code></pre> <p>Client.py:</p> <pre><code>import socket import threading # Server Information SERVER_ADDRESS = ('127.0.1.1', 1234) HEADER_LENGTH = 10 FORMAT = 'utf-8' DISCONNECT_COMMAND = '/disconnect' def send_message(message): message_length = f&quot;{len(message):&lt;{HEADER_LENGTH}}&quot; client_socket.send(bytes(message_length, FORMAT)) client_socket.send(bytes(message, FORMAT)) def receive_message(): while True: message_length = client_socket.recv(HEADER_LENGTH).decode(FORMAT) if message_length: message = client_socket.recv(int(message_length)).decode(FORMAT) return message def receive_messages_in_real_time(): while True: message = receive_message() print(message) # Connecting to Server client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(SERVER_ADDRESS) # Username Prompt username = input(&quot;Enter your username:\n&quot;) send_message(username) # Server Message for successful connection, and previous messages in server print(receive_message()) number_of_messages = receive_message() for _ in range(int(number_of_messages)): print(receive_message()) # thread for receiving messages receiving_thread = threading.Thread(target=receive_messages_in_real_time) receiving_thread.daemon = True receiving_thread.start() # messaging in the server connected = True while connected: message = input() send_message(message) if message == DISCONNECT_COMMAND: connected = False </code></pre>
[]
[ { "body": "<p>Looks fine, I have no tips. You did good. In a real application, you might want to tuck things into classes or code more defensively. Make sure you deal with frequent client disconnects (they don't properly close the connection) in a way where the server doesn't eventually die.</p>\n<p>If you're looking for challenges, you could:</p>\n<ul>\n<li>Write a class which lets someone write a client bot, then write a small bot using it. I suggest event handlers or callbacks.</li>\n<li>Do the same thing again, UDP</li>\n<li>Learn how to test your TCP scaling, up to at least 100-1K clients. Then improve TCP scaling to that range.</li>\n<li>When it gets big enough, your limit will be traffic. Add individual chat rooms. in groups of 10 people per chat room. Now in theory, it should be no problem to handle 1 message per second for the whole network. Actually support 10K clients.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T22:31:40.467", "Id": "251737", "ParentId": "247815", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T14:23:56.567", "Id": "247815", "Score": "8", "Tags": [ "python", "python-3.x", "multithreading", "socket" ], "Title": "A Server and Client Chatroom Using Sockets and Threading" }
247815
<p>I created a solution for the car pooling algorithm.</p> <h3>Problem:</h3> <p>You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)</p> <p>Given a list of trips, <code>trip[i] = [num_passengers, start_location, end_location]</code> contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.</p> <p>Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.</p> <p>Example 1:</p> <pre><code>Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false </code></pre> <p>Example 2:</p> <pre><code>Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11 Output: true </code></pre> <p>My solution:</p> <pre><code>var carPooling = function(trips, capacity) { if(!trips || trips.length === 0) return true; trips.sort((a,b) =&gt; a[1]-b[1]); let dropOff = new Map(); let seated = 0; while(trips.length &gt; 0) { const trip = trips.shift(); const pickup = trip[1]; for(const [key, value] of dropOff) { if(key &lt;= pickup) { seated -= value; dropOff.delete(key); } } if(seated + trip[0] &gt; capacity) return false; seated += trip[0]; if(!dropOff.has(trip[2])) dropOff.set(trip[2], trip[0]); else dropOff.set(trip[2], dropOff.get(trip[2]) + trip[0]); } return true; }; </code></pre> <p>Is the time complexity O(N^2logN)? I sort the input array which gives me O(NlogN). Then, I have a nested loop N^2? I'm not sure about this nested loop because it is a loop inside my hash table. By the way, do you guys have any idea about how to get a better performance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T06:58:53.550", "Id": "485337", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T17:52:49.470", "Id": "485429", "Score": "0", "body": "Hey, I have yet improved my answer, as I realized that you don't need two lists, one is just enough. I have also added time and memory complexities to individual parts of the algorithm to show where the weakest point is now. So check it out :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T19:12:00.017", "Id": "485444", "Score": "0", "body": "It's awesome! Thank you" } ]
[ { "body": "<p>The sort is not in the loop, so your algorithm is &quot;just&quot; <code>O(n^2)</code> because the loop dominates, the <code>O(n * log(n))</code> of the sort is neglegable (for big n).\nYou can solve the problem in <code>O(n * log(n))</code> and without sorting or destroying the input.</p>\n<ol>\n<li><p>Walk through the trips and build a Map <code>location =&gt; {liftUps, dropOffs}</code> (<code>O(n)</code> in time, <code>O(n)</code> in memory)</p>\n</li>\n<li><p>Iterate the map and build an array of <code>{location, liftUps, dropOffs}</code> (<code>O(n)</code> in time, <code>O(n)</code> in memory)</p>\n</li>\n<li><p>sort the array by location (this is now the slowest part of the algorithm: <code>O(n * log(n))</code> in time, <code>O(1)</code> in memory)</p>\n</li>\n<li><p>iterate the array adding liftUps and subtracting dropOffs for each location to an aggregate integer that starts at zero. (<code>O(n)</code> in time, <code>O(1)</code> in memory)</p>\n</li>\n<li><p>whenever you surpass capacity return false; return true if the loop finishes</p>\n</li>\n</ol>\n<pre><code>const carPooling = (trips, capacity) =&gt; {\n let i = 0;\n const map = new Map();\n for (i = 0; i &lt; trips.length; ++i) {\n const passangers = trips[i][0];\n const start = trips[i][1];\n const end = trips[i][2];\n \n if (map.has(start)) {\n map.set(start, map.get(start) + passangers);\n } else {\n map.set(start, passangers);\n }\n \n if (map.has(end)) {\n map.set(end, map.get(end) - passangers);\n } else {\n map.set(end, -passangers);\n }\n }\n \n const list = new Array(map.size);\n i = 0;\n for (const [location, exchange] of map) {\n list[i++] = {location: location, exchange: exchange}\n }\n \n list.sort((a, b) =&gt; a.location - b.location);\n \n let occupied = 0;\n for (i = 0; i &lt; list.length; ++i) {\n occupied += list[i].exchange;\n if (occupied &gt; capacity) {\n return false;\n }\n }\n \n return true;\n}\n\nconsole.log(carPooling([[2,1,5],[3,3,7]], 4));\nconsole.log(carPooling([[3,2,7],[3,7,9],[8,3,9]], 11));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:55:11.793", "Id": "247850", "ParentId": "247817", "Score": "4" } } ]
{ "AcceptedAnswerId": "247850", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T15:58:03.947", "Id": "247817", "Score": "2", "Tags": [ "javascript", "performance", "complexity" ], "Title": "Car Pooling algorithm time complexity" }
247817
<p>Heres a code that update weekly datas from production reports</p> <p>Known flaws :</p> <ol> <li>Im copy pasting the old line and replacing the week number in it to fit it to the one we want to update. The problem is that its not taking in account if cell emplacement of the data is changing. I also tought it was simpler than re-writing all formulas in every-cell by coding every bits of formula (file emplacement, file name and cell emplacement changes every ranges)</li> <li>Should i call my action if true in another sub to make this clearer? (ex: if true, call(copy-paste-find-replace)</li> <li>I have 1 code per sheet (3 sheets) cause of the ranges are hard coded and changes depending on the sheets, with your answer to (1) i could make it a single sub with variables depending on the sheet</li> <li>I have a week and a half remaining to make this as clean as possible, i dont want to refactor it all the way .. :(</li> </ol> <p>Heres one of the 3 code :</p> <pre><code>Sub AjoutSemaineajouterperfo() ' AjoutSemaineajouterperfo Macro ' Le code permet d'ajouter une nouvelle Semaineajouteraine Dim k As Long k = 3 Do While (Cells(k, 3).Value &lt;&gt; &quot;&quot; And k &lt;= 53) ' Boucle qui trouve la première ligne Semaineajouteraine vide k = k + 1 Loop k = k - 2 ' La boucle while ajoute une Semaine de trop, on veut aussi revenir sur la dernière semaine rentrer (d'ou le -2) Dim Semaineajouter As Long Dim Destination As Long Dim Semaineavant As Long Semaineajouter = Cells(59, 3).Value ' Valeur de la semaine à ajouter(case) Destination = Semaineajouter + 1 ' Ligne ou la prochaine semaine va se coller Semaineavant = Semaineajouter - 1 ' Ligne de la dernière semaine importer Dim semaineactuelle As Long semaineactuelle = WorksheetFunction.WeekNum(Now, vbMonday) If Semaineajouter &gt; k And Semaineajouter &lt;= 52 And Semaineajouter &lt;&gt; semaineactuelle Then ' Si le numéro de Semaineajouteraine entrée est plus grand que la dernière semaine ajouté et différent de la semaine actuelle ' Aussi plus petit que 52 (préserver la mise en forme Application.EnableEvents = False Application.DisplayAlerts = False Application.ScreenUpdating = False ActiveSheet.Unprotect Dim semaineajoutertex As String Dim semaineavanttex As String semaineajoutertex = &quot;sem &quot; &amp; CStr(Semaineajouter) ' Transfert des numéros de semaine en texte (pour search and replace) semaineavanttex = &quot;sem &quot; &amp; CStr(Semaineavant) ' Range 1 Dim RangeOrigine1 As String RangeOrigine1 = &quot;C&quot; &amp; Semaineajouter &amp; &quot;:&quot; &amp; &quot;AX&quot; &amp; Semaineajouter ' Range d'origine (semaine avant) Dim RangeDestination1 As String RangeDestination1 = &quot;C&quot; &amp; Destination &amp; &quot;:&quot; &amp; &quot;AX&quot; &amp; Destination ' Range à importer (semaine ajout) Range(RangeOrigine1).Copy Range(RangeDestination1) Range(RangeDestination1).Replace What:=semaineavanttex, Replacement:=semaineajoutertex, LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False ActiveSheet.Protect Application.ScreenUpdating = True Application.DisplayAlerts = True Application.EnableEvents = True Else MsgBox &quot;Entrez un numéro de Semaineajouteraine valide&quot;, vbCritical, &quot;Ne peut exécuter&quot; End If End Sub </code></pre> <p><a href="https://i.stack.imgur.com/CbtkU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CbtkU.png" alt="In window data sample" /></a></p> <p>In this case, pressing GO would call the macro and add week 33 by copy-pasting-find-replace the line from week 32, replacing &quot;sem 32&quot; by &quot;sem 33&quot; in every newly paste entries.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T17:54:18.190", "Id": "485303", "Score": "3", "body": "Step one is to fix the formatting of your code. The VBA Rubberduck can correctly format your code for you: https://rubberduckvba.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T18:00:36.537", "Id": "485305", "Score": "0", "body": "Cant add it to my job excel without askin the IT guys, may take a week or so..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T19:46:40.447", "Id": "485312", "Score": "1", "body": "you can install in user mode without administrator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T19:55:15.677", "Id": "485313", "Score": "0", "body": "Ok so il remind myself to always try before saying it dosn't work; its done now, thx Hack!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:01:58.130", "Id": "485338", "Score": "0", "body": "Sample data would help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:38:34.880", "Id": "485384", "Score": "0", "body": "@TinMan updated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:31:02.567", "Id": "485395", "Score": "0", "body": "Does this code work for Week 4?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:39:29.060", "Id": "485396", "Score": "0", "body": "There seems to be a missing Week. Do all the cells being copied have formulas?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:39:34.020", "Id": "485397", "Score": "0", "body": "Well, since i coded this at week 29 the earlier week were all entered manualy (old vesion of the file i imported them from had different cell emplacement for datas), but yeah i've been thinking about changing \"33\" for \" sem 33\" which would be \"sem\" & semaineajoutertex. this would take off the possibility to replace things i dont want to be replace" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:41:21.673", "Id": "485398", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/111761/discussion-between-tinman-and-patates-pilees)." } ]
[ { "body": "<p>I don't see the need to find a specific row number. Simply work your way down until you reach the current week.</p>\n<p>The key to reducing repeat code is to extract it to it's own method.</p>\n<h2>Refactored Code</h2>\n<pre><code>Sub UpdateWeeklyReports()\n Application.ScreenUpdating = False\n Const WorksheetName As String = &quot;Sheet1&quot;\n Const FirstWeekNumberRow As Long = 3\n Dim LastWeek As Range\n Dim What As String, Replacement As String\n With Worksheets(WorksheetName)\n Dim Row As Long\n For Row = FirstWeekNumberRow + 1 To Format(Now, &quot;WW&quot;) - 1\n If Not .Cells(Row, 3).HasFormula Then\n ' What = &quot;sem &quot; &amp; .Cells(Row - 1, 2).Value\n ' Replacement = &quot;sem &quot; &amp; .Cells(Row, 2).Value\n AddNewRow SourceRange:=.Rows(Row - 1).Range(&quot;C1:J1&quot;), What:=What, Replacement:=Replacement\n AddNewRow SourceRange:=.Rows(Row - 1).Range(&quot;M1:T1&quot;), What:=What, Replacement:=Replacement\n AddNewRow SourceRange:=.Rows(Row - 1).Range(&quot;W1:AD1&quot;), What:=What, Replacement:=Replacement\n End If\n Next\n End With\nEnd Sub\n\nPrivate Sub AddNewRow(ByVal SourceRange As Range, ByVal What As String, ByVal Replacement As String)\n With SourceRange\n .Offset(1).Formula = .Formula\n .Offset(1).Replace What:=What, Replacement:=Replacement, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False\n End With\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:33:50.847", "Id": "247867", "ParentId": "247818", "Score": "1" } } ]
{ "AcceptedAnswerId": "247867", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T16:07:03.810", "Id": "247818", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Copy-Paste-Find-Replace (weekly update)" }
247818
<p>I am trying to create three buckets of objects. Today, yesterday and past. I am wondering can the following be done in a more concise way in pure JavaScript without any libraries?</p> <pre><code>const [todayBucket, yesterdayBucket] = [0, 1].map(offset =&gt; recordings.filter(({ createdOn }) =&gt; moment(createdOn).isSame(moment().add(-offset), 'day'), ), ); const pastBucket = recordings.filter( recording =&gt; ![...todayBucket, ...yesterdayBucket].includes(recording), ); </code></pre>
[]
[ { "body": "<p>Doing it without an additional library you could try a custom function that does the same thing</p>\n<pre><code>function isSame(a,offset) {\n const b = new Date();\n b.setDate(b.getDate() - offset); \n return a === b\n}\n\nconst [todayBucket, yesterdayBucket] = [0, 1].map(offset =&gt;\n recordings.filter(({ createdOn }) =&gt;\n isSame(createdOn,offset),\n ),\n);\nconst pastBucket = recordings.filter(\n recording =&gt; ![...todayBucket, ...yesterdayBucket].includes(recording),\n);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T19:18:49.960", "Id": "247823", "ParentId": "247820", "Score": "1" } } ]
{ "AcceptedAnswerId": "247823", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T17:30:29.987", "Id": "247820", "Score": "1", "Tags": [ "javascript" ], "Title": "JavaScript syntax: bucketing based on days (today, yesterday and past)" }
247820
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>Design a Skiplist without using any built-in libraries.</p> <p>A Skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just simple linked lists.</p> <p>For example: we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:</p> <p><a href="https://i.stack.imgur.com/jfqrj.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jfqrj.gif" alt="enter image description here" /></a></p> <p><sup>Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons</sup></p> <p>You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add , erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).</p> <p>To be specific, your design should include these functions:</p> <ul> <li><code>bool search(int target)</code>: Return whether the target exists in the Skiplist or not.</li> <li><code>void add(int num)</code>: Insert a value into the SkipList.</li> <li><code>bool erase(int num)</code>: Remove a value in the Skiplist. If <code>num</code> does not exist in the Skiplist, do nothing and return false. If there exists multiple <code>num</code> values, removing any one of them is fine.</li> </ul> <p>See more about Skiplist: <a href="https://en.wikipedia.org/wiki/Skip_list" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Skip_list</a></p> <p>Note that duplicates may exist in the Skiplist, your code needs to handle this situation.</p> <h3>Example:</h3> <pre><code>Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return false. skiplist.add(4); skiplist.search(1); // return true. skiplist.erase(0); // return false, 0 is not in skiplist. skiplist.erase(1); // return true. skiplist.search(1); // return false, 1 has already been erased. </code></pre> <h3>Constraints:</h3> <ul> <li><code>0 &lt;= num</code>, <code>target &lt;= 20000</code></li> <li>At most 50000 calls will be made to search, add, and erase.</li> </ul> </blockquote> <h3>Code</h3> <pre><code>// The following block might trivially improve the exec time; // Can be removed; static const auto __optimize__ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return 0; }(); // Most of headers are already included; // Can be removed; #include &lt;cstdint&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;vector&gt; static const struct Skiplist { using SizeType = std::int_fast16_t; struct Node { SizeType val; Node* next{nullptr}; Node* prev{nullptr}; Node* down{nullptr}; Node(SizeType val = 0) { this-&gt;val = val; } }; Node* heads{nullptr}; SizeType layers = 0; Skiplist() { std::srand(std::time(nullptr)); } const bool search(const SizeType target) { if (heads == nullptr) { return false; } auto ptr = heads; while (ptr) { while (ptr-&gt;next &amp;&amp; ptr-&gt;next-&gt;val &lt; target) { ptr = ptr-&gt;next; } if (ptr-&gt;next &amp;&amp; ptr-&gt;next-&gt;val == target) { return true; } ptr = ptr-&gt;down; } return false; } const void add(const SizeType num) { Node* ptr = heads; std::vector&lt;Node*&gt; path(layers, nullptr); for (SizeType layer = layers - 1; layer &gt;= 0; --layer) { while (ptr-&gt;next &amp;&amp; ptr-&gt;next-&gt;val &lt; num) { ptr = ptr-&gt;next; } path[layer] = ptr; ptr = ptr-&gt;down; } for (SizeType layer = 0; layer &lt;= std::size(path); ++layer) { ptr = new Node(num); if (layer == std::size(path)) { Node* last = heads; heads = new Node(); heads-&gt;down = last; heads-&gt;next = ptr; ptr-&gt;prev = heads; ++layers; } else { ptr-&gt;next = path[layer]-&gt;next; ptr-&gt;prev = path[layer]; path[layer]-&gt;next = ptr; if (ptr-&gt;next) { ptr-&gt;next-&gt;prev = ptr; } } if (layer) { ptr-&gt;down = path[layer - 1]-&gt;next; } if (std::rand() &amp; 1) { break; } } } const bool erase(const SizeType num) { auto ptr = heads; for (SizeType layer = layers - 1; layer &gt;= 0; --layer) { while (ptr-&gt;next &amp;&amp; ptr-&gt;next-&gt;val &lt; num) { ptr = ptr-&gt;next; } if (ptr-&gt;next &amp;&amp; ptr-&gt;next-&gt;val == num) { ptr = ptr-&gt;next; while (ptr) { ptr-&gt;prev-&gt;next = ptr-&gt;next; if (ptr-&gt;next) { ptr-&gt;next-&gt;prev = ptr-&gt;prev; } ptr = ptr-&gt;down; } while (heads &amp;&amp; heads-&gt;next == nullptr) { heads = heads-&gt;down; --layers; } return true; } else { ptr = ptr-&gt;down; if (ptr == nullptr) { return false; } } } return false; } }; </code></pre> <h3><a href="https://leetcode.com/problems/design-skiplist/" rel="nofollow noreferrer">LeetCode 1206 - Skip List Problem</a></h3> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/design-skiplist/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/design-skiplist/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> </ul>
[]
[ { "body": "<ul>\n<li><p><code>SizeType</code> looks like a misnomer. It feels more like <code>ValueType</code>. As a side note, consider making it a <code>template &lt;typename ValueType&gt; struct SkipList</code>.</p>\n</li>\n<li><p>Testing for <code>heads == nullptr</code> in <code>search</code> is redundant. The loop will take care of it immediately.</p>\n</li>\n<li><p>For DRY I recommend a helper method, akin to <code>std::lower_bound</code>, to be used in all interface methods (i.e. <code>search</code>, <code>add</code>, and <code>erase</code>). Yes it requires a very careful design of an iterator.</p>\n</li>\n<li><p><code>add</code> may benefit from <code>Node::Node(val, next, down)</code> constructor.</p>\n</li>\n<li><p>No naked loops, please.</p>\n<p>The <code>for (SizeType layer = 0; layer &lt;= std::size(path); ++layer)</code> loop particularly deserves to be a method on its own. Its intention is to promote a freshly inserted node, so <code>promote_added_node</code> looks like a good name.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T01:16:29.853", "Id": "247835", "ParentId": "247827", "Score": "1" } } ]
{ "AcceptedAnswerId": "247835", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T20:58:49.003", "Id": "247827", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 1206: Design Skiplist" }
247827
<p>It took me a while to solve this question and there are corner cases i missed hence the 4 unit tests. please review for performance. and if you can treat this as a review for a 45 mins programming interview.</p> <p><a href="https://leetcode.com/problems/find-and-replace-in-string/" rel="nofollow noreferrer">https://leetcode.com/problems/find-and-replace-in-string/</a></p> <blockquote> <p>To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).</p> <p>Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing.</p> <p>For example, if we have S = &quot;abcd&quot; and we have some replacement operation i = 2, x = &quot;cd&quot;, y = &quot;ffff&quot;, then because &quot;cd&quot; starts at position 2 in the original string S, we will replace it with &quot;ffff&quot;.</p> <p>Using another example on S = &quot;abcd&quot;, if we have both the replacement operation i = 0, x = &quot;ab&quot;, y = &quot;eee&quot;, as well as another replacement operation i = 2, x = &quot;ec&quot;, y = &quot;ffff&quot;, this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'.</p> <p>All these operations occur simultaneously. It's guaranteed that there won't be any overlap in replacement: for example, S = &quot;abc&quot;, indexes = [0, 1], sources = [&quot;ab&quot;,&quot;bc&quot;] is not a valid test case.</p> <p>Example 1:</p> <p>Input: S = &quot;abcd&quot;, indexes = [0,2], sources = [&quot;a&quot;,&quot;cd&quot;], targets = [&quot;eee&quot;,&quot;ffff&quot;] Output: &quot;eeebffff&quot; Explanation: &quot;a&quot; starts at index 0 in S, so it's replaced by &quot;eee&quot;. &quot;cd&quot; starts at index 2 in S, so it's replaced by &quot;ffff&quot;. Example 2:</p> <p>Input: S = &quot;abcd&quot;, indexes = [0,2], sources = [&quot;ab&quot;,&quot;ec&quot;], targets = [&quot;eee&quot;,&quot;ffff&quot;] Output: &quot;eeecd&quot; Explanation: &quot;ab&quot; starts at index 0 in S, so it's replaced by &quot;eee&quot;. &quot;ec&quot; doesn't starts at index 2 in the original S, so we do nothing. Notes:</p> <p>0 &lt;= indexes.length = sources.length = targets.length &lt;= 100 0 &lt; indexes[i] &lt; S.length &lt;= 1000 All characters in given inputs are lowercase letters.</p> </blockquote> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace StringQuestions { [TestClass] public class FindReplaceStringTest { [TestMethod] public void TestMethod1() { string S = &quot;abcd&quot;; int[] indexes = { 0, 2 }; string[] sources = { &quot;a&quot;, &quot;cd&quot; }; string[] targets = { &quot;eee&quot;, &quot;ffff&quot; }; string output = &quot;eeebffff&quot;; Assert.AreEqual(output, FindReplaceStringClass.FindReplaceString(S, indexes, sources, targets)); } [TestMethod] public void TestFailMethod1() { string S = &quot;abcd&quot;; int[] indexes = { 0, 2 }; string[] sources = { &quot;ab&quot;, &quot;ec&quot; }; string[] targets = { &quot;eee&quot;, &quot;ffff&quot; }; string output = &quot;eeecd&quot;; Assert.AreEqual(output, FindReplaceStringClass.FindReplaceString(S, indexes, sources, targets)); } [TestMethod] public void TestFailMethod2() { string S = &quot;vmokgggqzp&quot;; int[] indexes = { 3, 5, 1 }; string[] sources = { &quot;kg&quot;, &quot;ggq&quot;, &quot;mo&quot; }; string[] targets = { &quot;s&quot;, &quot;so&quot;, &quot;bfr&quot; }; string output = &quot;vbfrssozp&quot;; Assert.AreEqual(output, FindReplaceStringClass.FindReplaceString(S, indexes, sources, targets)); } [TestMethod] public void TestFailMethod3() { string S = &quot;jjievdtjfb&quot;; int[] indexes = { 4,6,1 }; string[] sources = { &quot;md&quot;, &quot;tjgb&quot;, &quot;jf&quot; }; string[] targets = { &quot;foe&quot;, &quot;oov&quot;, &quot;e&quot; }; string output = &quot;jjievdtjfb&quot;; Assert.AreEqual(output, FindReplaceStringClass.FindReplaceString(S, indexes, sources, targets)); } } } public class FindReplaceStringClass { public static string FindReplaceString(string S, int[] indexes, string[] sources, string[] targets) { var index2strings = new SortedDictionary&lt;int, Tuple&lt;string, string&gt;&gt;(); for (int i = 0; i &lt; indexes.Length; i++) { index2strings.Add(indexes[i], new Tuple&lt;string, string&gt;(sources[i], targets[i])); } StringBuilder res = new StringBuilder(); int curr = 0;//current s pointer foreach (var item in index2strings) { var index = item.Key; var source = item.Value.Item1; var target = item.Value.Item2; //check each index if source appears in s for (int k = curr; k &lt; index; k++) { res.Append(S[k]); curr++; } //check the entire prefix is found bool isFound = true; for (int sIndx = index, j = 0; sIndx &lt; index + source.Length; sIndx++, j++) { if (S[sIndx] != source[j]) { isFound = false; break; } } if (!isFound) { continue; } curr = index + source.Length; //append new string foreach (var t in target) { res.Append(t); } } //the rest of s for (int i = curr; i &lt; S.Length; i++) { res.Append(S[i]); } return res.ToString(); } } </code></pre>
[]
[ { "body": "<p>Instead of the old <code>Tuple</code> objects, you should use <code>ValueTuple</code>. They are more flexible and easier to read and maintain according to names and is further more elaborated and incorporated in C# as language. So your Dictionary could look like:</p>\n<pre><code> var index2strings = new SortedDictionary&lt;int, (string source, string target)&gt;();\n for (int i = 0; i &lt; indexes.Length; i++)\n {\n index2strings.Add(indexes[i], (sources[i], targets[i]));\n }\n</code></pre>\n<hr />\n<p>You can benefit from setting the capacity of the string builder to a large value, - maybe as:</p>\n<pre><code> StringBuilder res = new StringBuilder(S.Length * 2);\n</code></pre>\n<hr />\n<p>Because <code>KeyValuePair&lt;K,V&gt;</code> provides a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct\" rel=\"nofollow noreferrer\">&quot;decontructor&quot;</a>, you can replace this:</p>\n<blockquote>\n<pre><code> foreach (var item in index2strings)\n {\n var index = item.Key;\n var source = item.Value.Item1;\n var target = item.Value.Item2;\n</code></pre>\n</blockquote>\n<p>with this:</p>\n<pre><code> foreach ((var index, (var source, var target)) in index2strings)\n {\n</code></pre>\n<p>if you use <code>ValueTuple</code> as suggested above.</p>\n<hr />\n<p>This:</p>\n<blockquote>\n<pre><code> for (int k = curr; k &lt; index; k++)\n {\n res.Append(S[k]);\n curr++;\n }\n</code></pre>\n</blockquote>\n<p>can be replaced with:</p>\n<pre><code> int length = index - curr;\n res.Append(S.Substring(curr, length));\n curr += length;\n</code></pre>\n<p>According to my measurements it's cheaper to add one string as a whole than a sequence of its chars.</p>\n<hr />\n<p>Likewise can this:</p>\n<blockquote>\n<pre><code> //check the entire prefix is found\n bool isFound = true;\n for (int sIndx = index, j = 0; sIndx &lt; index + source.Length; sIndx++, j++)\n {\n if (S[sIndx] != source[j])\n {\n isFound = false;\n break;\n }\n }\n if (!isFound)\n {\n continue;\n }\n</code></pre>\n</blockquote>\n<p>be replaced with:</p>\n<pre><code> if (S.Substring(index, source.Length) != source)\n {\n continue;\n }\n</code></pre>\n<p>and this:</p>\n<blockquote>\n<pre><code> foreach (var t in target)\n {\n res.Append(t);\n }\n</code></pre>\n</blockquote>\n<p>with:</p>\n<pre><code> res.Append(target);\n</code></pre>\n<p>and finally this:</p>\n<blockquote>\n<pre><code> for (int i = curr; i &lt; S.Length; i++)\n {\n res.Append(S[i]);\n }\n</code></pre>\n</blockquote>\n<p>with:</p>\n<pre><code> res.Append(S.Substring(curr));\n</code></pre>\n<p>When doing so it seems that you can cut the duration to about a little lesser than half the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T07:02:15.433", "Id": "485469", "Score": "2", "body": "You can cut all the substring allocations with [`Append(String, Int32, Int32)`](https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.append?view=netcore-3.1#System_Text_StringBuilder_Append_System_String_System_Int32_System_Int32_) and `S.IndexOf(source, curr, source.Length, StringComparison.Ordinal)`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:47:04.120", "Id": "247861", "ParentId": "247828", "Score": "3" } } ]
{ "AcceptedAnswerId": "247861", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T21:52:19.633", "Id": "247828", "Score": "4", "Tags": [ "c#", "programming-challenge", "strings" ], "Title": "LeetCode: Find And Replace in String C#" }
247828
<p>I wanted to know how &quot;dark&quot; each character is when printed. I thought that this may be useful when doing ASCII-art to help with shading. I decided to write a program to objectively measure how much coverage of an area each character provides, which should roughly translate to how dark it appears when printed and zoomed out from.</p> <p>First, here are the results for pt. 100, FreeSans font, for all visible ASCII characters:</p> <pre><code>&gt;&gt;&gt; pairs = find_half_coverage_for_printable() &gt;&gt;&gt; pairs.sort(key=lambda p: p[1], reverse=True) &gt;&gt;&gt; pairs [('@', 0.3015), ('W', 0.2499), ('M', 0.241), ('B', 0.2052), ('Q', 0.1996), ('G', 0.1962), ('N', 0.1931), ('R', 0.189), ('O', 0.1816), ('D', 0.1795), ('$', 0.1782), ('S', 0.1723), ('&amp;', 0.171), ('%', 0.1677), ('E', 0.1658), ('8', 0.1653), ('g', 0.1653), ('m', 0.1624), ('H', 0.162), ('w', 0.1597), ('A', 0.1594), ('#', 0.1578), ('K', 0.1573), ('9', 0.1571), ('6', 0.1569), ('C', 0.1539), ('U', 0.153), ('Z', 0.153), ('P', 0.1513), ('X', 0.1501), ('d', 0.1482), ('q', 0.148), ('b', 0.1477), ('p', 0.1472), ('5', 0.1453), ('0', 0.1434), ('2', 0.1414), ('3', 0.1384), ('V', 0.1324), ('a', 0.1316), ('e', 0.131), ('4', 0.1277), ('F', 0.1259), ('h', 0.1228), ('o', 0.1177), ('k', 0.1171), ('Y', 0.1152), ('s', 0.1139), ('y', 0.1089), ('u', 0.1061), ('n', 0.1059), ('T', 0.1042), ('c', 0.1002), ('J', 0.0997), ('[', 0.0967), (']', 0.0967), ('z', 0.0962), ('7', 0.0947), ('L', 0.0945), ('?', 0.0903), ('x', 0.09), ('v', 0.0869), ('{', 0.0826), ('}', 0.0772), ('1', 0.0764), ('f', 0.0727), ('&gt;', 0.0711), ('j', 0.0708), ('&lt;', 0.0708), ('t', 0.0705), ('(', 0.0672), (')', 0.0672), ('=', 0.0672), ('I', 0.0657), ('|', 0.0649), ('+', 0.0624), ('l', 0.0584), ('r', 0.0572), ('!', 0.0528), ('i', 0.0504), ('^', 0.0499), ('/', 0.0411), ('\\', 0.041), ('&quot;', 0.0382), ('*', 0.0379), ('~', 0.0342), (';', 0.03), ('_', 0.0289), (&quot;'&quot;, 0.0202), (':', 0.02), (',', 0.0177), ('-', 0.0168), ('`', 0.0125), ('.', 0.01)] </code></pre> <p>So by this measure, <code>@</code> is the &quot;darkest&quot; character, and <code>.</code> is the &quot;lightest&quot; (which makes intuitive sense; although I expected <code>#</code> to rank higher).</p> <p>The program works by using <a href="https://pillow.readthedocs.io/en/stable/" rel="noreferrer">Pillow</a> to draw a (by default) 100 pt. character onto a 100x100 image in memory, then it manually checks each pixel of the image. If the color satisfies a predicate, that pixel is considered to be &quot;covered&quot;. It then calculates the percentage coverage and returns it. By default, the predicate is a check to see if the sum of the three channels exceeds <code>(255 + 255 + 255) // 2</code>. This can be easily changed though by supplying a custom predicate.</p> <p>As I note in the docstring though, this method does not produce absolute coverage measures, since the images are a little bigger than the drawn characters. The 30.15% coverage of <code>@</code> is including a lot of whitespace, and would be higher if corrected. Unfortunately, trying to get images exactly as large as the character creates its own problems, and relative coverages are fine anyways. There's also a minor issue that some characters, depending on the font, can hang down <em>slightly</em> outside of the image. I'm offsetting to the left by 5 pixels to account for that, but there's still issues of &quot;overflows&quot; near the bottom. It doesn't seem to serious though, so I left it. Underscores will be impacted the most by it.</p> <p>I know I'm not doing everything as efficiently as I could be (like only using 1 process, and accessing pixels in a naïve way). It's surprisingly fast though, so optimizations didn't seem necessary. I'd be interested though in any improvements people can see though, as I don't do image manipulation very often.</p> <pre><code>from typing import Tuple, Callable, Iterable, List import string as sg from PIL import Image as ig from PIL.Image import Image import PIL.ImageFont as ft import PIL.ImageDraw as dw Color = Tuple[int, int, int] ColorPredicate = Callable[[Color], bool] _DEFAULT_FONT = &quot;FreeSans&quot; _DEFAULT_TEST_SIZE = 100 # The size of the image and the font _DEFAULT_CHAR_SET = sg.digits + sg.ascii_letters + sg.punctuation _DEFAULT_IMG_SIZE_MULT = 1.10 _DEFAULT_CHAR_COLOR = (0, 0, 0) _DRAW_OFFSET = (5, 0) _COLOR_TUP_MAX_SUM = sum((255, 255, 255)) def _new_image(width: int, height: int) -&gt; Image: return ig.new(&quot;RGB&quot;, (width, height), (255, 255, 255)) def _draw_character(image: Image, char: str, font: ft.ImageFont, color: Color = _DEFAULT_CHAR_COLOR) -&gt; None: draw = dw.ImageDraw(image) draw.text(_DRAW_OFFSET, char, color, font) def _count_selected(image: Image, pred: ColorPredicate) -&gt; int: pix = image.load() count = 0 for y in range(image.height): for x in range(image.width): if pred(pix[x, y]): count += 1 return count def find_percent_coverage(char: str, pred: ColorPredicate, image_width: int, font: ft.ImageFont) -&gt; float: img = _new_image(image_width, image_width) _draw_character(img, char, font) count = _count_selected(img, pred) return count / (image_width * image_width) def half_color_predicate(color: Color) -&gt; bool: return sum(color) &lt;= (_COLOR_TUP_MAX_SUM &gt;&gt; 1) def find_coverage_for(chars: Iterable[str], pred: ColorPredicate, image_width: int = _DEFAULT_TEST_SIZE, font_name: str = _DEFAULT_FONT, ) -&gt; List[Tuple[str, float]]: &quot;&quot;&quot; Counts the number of pixels each character covers in an image, and return each result as a tuple of (character, percent_coverage). Unless the character is exactly as large as the image, the returned coverage percentages will not be absolute. They only have meaning relative to other results. &quot;&quot;&quot; font = ft.truetype(font_name, image_width) return [(c, find_percent_coverage(c, pred, image_width, font)) for c in chars] def find_half_coverage_for_printable(image_width: int = _DEFAULT_TEST_SIZE, font_name: str = _DEFAULT_FONT ) -&gt; List[Tuple[str, float]]: return find_coverage_for(_DEFAULT_CHAR_SET, half_color_predicate, image_width, font_name) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T02:50:03.750", "Id": "485327", "Score": "1", "body": "Interesting problem..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T06:28:36.810", "Id": "485335", "Score": "0", "body": "Rather than use a fixed 100x100 image, ImageFont has a [method](https://pillow.readthedocs.io/en/stable/reference/ImageFont.html#methods) `getsize(text)` that returns the width and height of `text` in pixels." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:01:27.117", "Id": "485388", "Score": "0", "body": "@RootTwo Yes. I didn't verify the math, but I worried that differently sized images would lead to percentages that would be harder to compare." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T22:11:04.697", "Id": "485452", "Score": "0", "body": "@Carcigenicate. I guess it depends on the font. For a fixed width font, the calculations could be off by a constant factor. For a proportional font it might make a bigger difference. A string like '|||||||' would have a lot higher density in a proportional font." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T22:41:32.713", "Id": "485456", "Score": "0", "body": "@RootTwo Ya, I realized how much of a factor the spacing of font plays when I did some tests. I had the program print out giant blocks of text to file, in the order of characters at the start of the question. There's a *general* tendency towards lighter characters at the end, but there's spikes of dark where certain characters fit together closer. I really need to use a mono spaced font for this, which I don't think OpenSans is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T03:31:54.793", "Id": "495314", "Score": "0", "body": "If you want to learn how to do this correctly, you either need to use a mono spaced font, or learn about kerning. Either way, you want the final ascii art to match (which probably means mono)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T22:19:11.300", "Id": "247830", "Score": "7", "Tags": [ "python", "python-3.x", "ascii-art" ], "Title": "A program that calculates how dense each character appears when printed" }
247830
<p>I built a simple infinite scroll using the intersection observer API, would love some feedback on ways to improve my JavaScript and make it more maintainable and reusable, and feedback according to best JavaScript practices.</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;title&gt;Infinite Scroll&lt;/title&gt; &lt;style&gt; body { font-family: sans-serif; font-size: 16px; } .container { display: flex; flex-direction: column; align-items: center; max-width: 520px; margin: 0 auto; } img { width: 100%; height: 100%; margin: 1rem 2rem; } #load-more { padding: 1rem 2rem; margin: 2; background-color: darkcyan; color: white; border-radius: 1rem; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container&quot;&gt; &lt;div id=&quot;infinite-scroll-imgs-container&quot;&gt;&lt;/div&gt; &lt;div id=&quot;load-more&quot;&gt;Loading more content...&lt;/div&gt; &lt;/div&gt; &lt;script&gt; const loadMore = document.querySelector(&quot;#load-more&quot;); const observer = new IntersectionObserver(handleIntersect, { threshold: 1 }); const imgsContainer = document.querySelector(&quot;#infinite-scroll-imgs-container&quot;); observer.observe(loadMore) function randomInteger() { return Math.floor(Math.random() * 1000000); } function imgGenerator(images) { const imgs = []; for (let i = 0; i &lt; images; i += 1) { const img = document.createElement(&quot;img&quot;); img.src = `http://api.adorable.io/avatars/${randomInteger()}`; img.classList.add('infinite-scroll-img') imgs.push(img); } return imgs; } function appendImages(container, images) { container.append(...imgGenerator(images)); } function handleIntersect(entries, observer) { entries.forEach((entry) =&gt; { if (entry.isIntersecting) { appendImages(imgsContainer, 5); } }); } appendImages(imgsContainer, 5); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I think that <code>container</code> and <code>images</code> are being repeated unecessarly.</p>\n<hr />\n<p>When you call <code>imgGenerator</code> in <code>appendImages</code>, you already know that you want an array of images.</p>\n<p>You can use <a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\">Array.from</a>:</p>\n<ul>\n<li>the first argument will be an <code>array-like</code> object, that is, an object that is accessed by index and with a length propertie(which is identified as <code>images</code> on our javascript)</li>\n<li>the second argument will be the <code>mapFunction</code>(which will\nbe <code>imgGenerator</code>), a function that will be called for every\nitem of the array</li>\n</ul>\n<p>Doing this, on <code>imgGenerator</code> you avoid to make an instance of an array(<code>imgs</code>), a push into it and a <code>for</code> loop every time you want this array, although, you will not need to pass <code>images</code> as parameter again</p>\n<hr />\n<p>the <code>container</code> is always <code>imgsContainer</code>, so, in the <code>appendImages</code> you already know where to append</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function imgGenerator() {\n const img = document.createElement(\"img\");\n img.src = `http://api.adorable.io/avatars/${randomInteger()}`;\n img.classList.add('infinite-scroll-img');\n return img;\n}\n\nfunction appendImages(images) {\n imgsContainer.append(\n ...Array.from({ length: images }, imgGenerator)\n );\n}\n\nfunction handleIntersect(entries) {\n entries.forEach(entry =&gt; {\n if (entry.isIntersecting) {\n appendImages(5);\n }\n });\n}\n\nappendImages(5);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-21T02:29:27.403", "Id": "248223", "ParentId": "247832", "Score": "1" } } ]
{ "AcceptedAnswerId": "248223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T23:13:18.780", "Id": "247832", "Score": "4", "Tags": [ "javascript", "html" ], "Title": "JavaScript infinite scroll with intersection observer" }
247832
<p>For my hashmap implementation, I'm caching hashes for each map element in an array of length <code>NBUCKETS</code>, where each element corresponds to an element in the hashmap. Assuming a hash consists of 64-bits, the first 57 bits decide the position(bucket) in the hashmap and the last 7 bits (i.e <code>H2(hash)</code>) are used as control bytes for probing the table. More concretely, while finding an element in the map using linear probing, <code>H2(hash)</code> is compared for 16 elements at a time using SIMD intrinsics before comparing actual keys. Hence, each call to <code>probe_group()</code> probes 16 elements of the map at the same time.</p> <p>Components of code where I think optimization is needed but don't know how to do so (these have TODO tags in code):</p> <ol> <li>Populating the <code>group</code> array with 16 elements from <code>hash_arr</code> is expensive. I want to avoid the usage of temporary <code>group</code> array and load the last 7 bits of 16 consecutive hash values from <code>hash_arr</code> directly into a <code>__m128i</code> (i.e <code>ctrl</code>). Is there a way to directly load the last 7 bits of 16 hash values from <code>hash_arr</code> into <code>__m128i</code> instead of using the temporary byte array <code>group</code>?</li> <li>Checking which indices have bit 1 is expensive because my current implementations applies <code>(match &gt;&gt; i) &amp; 1U</code> for each index <code>i</code>, where <code>i</code> ranges from 0 to 15 inclusive. Is there a more efficient way to do this?</li> </ol> <p>Any suggestions on improving these components as well as others parts of the code will be deeply appreciated.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;immintrin.h&gt; #include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #define NBUCKETS 100 #define GROUP_SIZE 16 typedef char h2_t; // return the lowest byte static inline h2_t H2(size_t hash) { return hash &amp; 0x7f; } // If ith element in `group` is 'hash', then ith bit in `match` will be 1, // otherwise it will be 0 static inline uint16_t probe_group(h2_t hash, h2_t *group) { __m128i ctrl = _mm_loadu_si128((__m128i*) group); __m128i match = _mm_set1_epi8(hash); return _mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl)); } int main() { // Dummy array of hashes. Each element corresponds to an element at that index in the hashmap. size_t hash_arr[NBUCKETS]; for (int i = 0; i &lt; NBUCKETS; i++) hash_arr[i] = i; // TODO Optimize this: Avoid using this array. Instead load the last 7 bits of 16 hash values directly into a `__m128i`. const int start_pos = 90; h2_t group[GROUP_SIZE]; for (int i = 0; i &lt; GROUP_SIZE; i++) group[i] = H2(hash_arr[(start_pos + i) % NBUCKETS]); // Element to be searched for in `group`. ASCII for 'c' is 99 h2_t find_ele = 'c'; uint16_t match = probe_group(find_ele, group); // TODO Optimize this: Find a better way to check which indices have bit 1 for (int i = 0; i &lt; GROUP_SIZE; i++) { if ((match &gt;&gt; i) &amp; 1U) printf(&quot;Element at index %d in group is equal to %c\n&quot;, i, find_ele); } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T02:22:45.417", "Id": "247836", "Score": "3", "Tags": [ "c", "hash-map", "simd" ], "Title": "Linear probing 16 hashmap elements in parallel using SIMD instrinsics" }
247836
<p>Please review and help me write better codes.</p> <p>Combining Pictures We can use a conditional to copy just the non-white pixels from one picture to another picture. We can take this tiny image of the women and put her by the Eiffel tower in Paris, France. I have modified the code so that the code automatically swaps the image1 and image2; hence, always using the larger image as the canvas and the smaller picture as the insert.</p> <pre class="lang-py prettyprint-override"><code>from PIL import Image image1 = Image.open(&quot;lady_tiny.jpg&quot;) image2 = Image.open(&quot;eiffel.jpg&quot;) width = min(image1.size[0], image2.size[0]) # (x) length = min(image1.size[1], image2.size[1]) # (y) # check if smaller image then use it as insert if width == image2.size[0] and length == image2.size[1]: canvas = image1.load() # larger pic insert = image2.load() # smaller pic else: insert = image1.load() canvas = image2.load() for col in range(width): for row in range(length): r, g, b = insert[col, row] # read each pixel of insert(small) # Check if the pixel isn't white if r &lt; 250 and g&lt; 250 and b&lt; 250: # Copy the color of insert (smaller) onto the canvas(larger) canvas[col, row + 130] = r, g, b if ( width == image2.size[0] and length == image2.size[1] ): # if image2 is insert then image 1 is canvas image1.show() else: image2.show() </code></pre>
[]
[ { "body": "<p>You can simplify the checks that find the smallest image. If you assume that if the image is smaller in one dimension, it will be smaller in both (which you seem to be already), you can find the smallest image using <code>min</code>'s <code>key</code> parameter:</p>\n<pre><code>small_image = min(image1, image2, key=lambda image: image.size[0])\nlarge_image = image1 if image2 == small_image else image2\n\ncanvas = large_image.load()\ninsert = small_image.load()\n</code></pre>\n<p>The <code>key</code> function is applied to each image before they're compared. In this case, I'm comparing each of the image's <code>size[0]</code> values. To get the larger image, you could get creative with sets if images are hashable, but I think a conditional expression is probably easiest.</p>\n<p>This also reduces your check at the bottom to just</p>\n<pre><code>large_image.show()\n</code></pre>\n<hr />\n<p>This part:</p>\n<pre><code>r, g, b = insert[col, row]\n\nif r &lt; 250 and g&lt; 250 and b&lt; 250:\n canvas[col, row + 130] = r, g, b\n</code></pre>\n<p>Can be simplified a bit if you use <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> with a generator expression:</p>\n<pre><code>color = insert[col, row]\n\nif all(c &lt; 250 for c in color):\n canvas[col, row + 130] = color\n</code></pre>\n<p>This frees you up from needing to create, compare, then recombine three separate variables.</p>\n<hr />\n<p>Final code:</p>\n<pre><code>from PIL import Image\n\nimage1 = Image.open(&quot;lady_tiny.jpg&quot;)\nimage2 = Image.open(&quot;eiffel.jpg&quot;)\n\nsmall_image = min(image1, image2, key=lambda image: image.size[0])\nlarge_image = image1 if image2 == small_image else image2\n\ncanvas = large_image.load()\ninsert = small_image.load()\n\nfor col in range(width):\n for row in range(length):\n color = insert[col, row]\n\n if all(c &lt; 250 for c in color):\n canvas[col, row + 130] = color\n \nlarge_image.show()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T06:01:29.987", "Id": "485703", "Score": "0", "body": "Thank you very much. Greatly appreciate your feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T23:45:34.350", "Id": "247879", "ParentId": "247838", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T04:59:11.453", "Id": "247838", "Score": "3", "Tags": [ "python" ], "Title": "Looking cleaner code of Python Combining Image with PIL" }
247838
<p>I thought it would be fun to write a simple and small bash script which randomly chooses a wallpaper from a given directory of a set of wallpaper images. The code is as follows.</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash # simple script to choose random image from # Wallpaper directory and set it as desktop background # cd into Wallpaper dir cd /home/user/Pictures/Wallpapers # using nano time mod # of imgs in Wallpapers (+1 b/c awk fields start at ind 1) # to provide a semi-random field number for the awk statement RAND=$(($(date +%N) % $(ls -h | wc -l) + 1)) IMG=$(ls -h | awk -v r=$RAND 'BEGIN{FS = &quot;\n&quot;; RS = &quot;&quot;} {print $r}') # change the desktop with the img file provided from the awk statement # (the way to set the background is system dependent but the gist is the same) gsettings set org.gnome.desktop.background picture-uri &quot;file:///home/user/Pictures/Wallpapers/$IMG&quot; </code></pre> <p>This is really just a small, fun project, but I am almost certain I am not doing this the most efficient way, so any feedback would be great.</p>
[]
[ { "body": "<p><a href=\"https://unix.stackexchange.com/questions/128985/why-not-parse-ls-and-what-to-do-instead\">Why you shouldn't parse ls.</a></p>\n<p>Let's consider <code>ls</code> bad practice, and allow me to introduce a different method to solve your issue all together. Find every <em>file</em> in the directory, /home/user/Pictures/Wallpapers, perform a random sort on it and then grab the first result.</p>\n<p><code>find /home/user/Pictures/Wallpapers -type f | sort -R | head -1</code></p>\n<p><a href=\"https://www.man7.org/linux/man-pages/man1/sort.1.html\" rel=\"nofollow noreferrer\">Sort man page</a></p>\n<pre><code> -R, --random-sort\n shuffle, but group identical keys. See shuf(1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:42:39.520", "Id": "247858", "ParentId": "247839", "Score": "0" } } ]
{ "AcceptedAnswerId": "247858", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T05:43:19.707", "Id": "247839", "Score": "2", "Tags": [ "bash", "linux", "awk" ], "Title": "Bash script wallpaper randomizer" }
247839
<p>I'm currently using a function to check if a URL has correctly escaped two different characters: <code>.</code> and <code>/</code>.</p> <p>To escape a character within a string, it requires 2 preceding <code>\</code>'s in the string (i.e.: <code>\\.</code> or <code>\\/</code>).</p> <p>Here is the code I'm currently using. As you can see I'm matching the string with some regex, and then for every element returned I check if the first character of the string is <code>\</code>.</p> <p>I feel this could be simplified, how can I make this better and avoid looping through all elements returned by <code>match</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>function isValidEscapedString(value) { return (value.match(/.?[./]/g)||[]).every((escape) =&gt; escape[0] === '\\'); } console.log(isValidEscapedString('')); // true console.log(isValidEscapedString('https://stackoverflow.com')); // false console.log(isValidEscapedString('https:\/\/stackoverflow\.com')); // false console.log(isValidEscapedString('https://stackoverflow\\.com')); // false console.log(isValidEscapedString('https:\\/\\/stackoverflow\\.com')); //true</code></pre> </div> </div> </p> <p><em>The examples in the code are working as intended.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:28:16.947", "Id": "485353", "Score": "0", "body": "Why are you specifically escaping `.` and `/`? For `RegExp` constructor or something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:35:56.120", "Id": "485354", "Score": "0", "body": "@adiga yes that's right. Somewhere in one of our other microservices it's used like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:40:53.013", "Id": "485355", "Score": "0", "body": "There are other meta characters which [can be present](https://stackoverflow.com/a/1547940) in a URL like `-?[]()*+`. You don't want to check for those?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:43:43.430", "Id": "485356", "Score": "0", "body": "@adiga you're probably right. We're currently porting a legacy RoR project into Typscript and that's how it's been done for years. And would appear those other characters haven't been used yet. lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:50:15.320", "Id": "485357", "Score": "0", "body": "Do you input the full URL or just the domain name? Because domain names only contain `-` in addition to what you have already escaped." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:52:28.067", "Id": "485358", "Score": "0", "body": "@adiga full URL without query params." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:22:45.983", "Id": "485371", "Score": "1", "body": "I have couple more questions. By, *\"without query params\"*, your url will always be in the form of `https://domain-name.com` or can it have a path after that: `https://domain-name.com/path`? Do you get the escaped string as input or do you have access to unescaped string? If you have the unescaped string, there is already [a function for escaping all the metacharacters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-21T06:39:56.947", "Id": "486109", "Score": "0", "body": "@adiga thanks I didn't know this existed, which seems to change the way it works. Currently at the company I work for, we're trying to get to user to manually escape the string being offerred as an input, however I think this could work." } ]
[ { "body": "<p>What about, instead of search for every <code>.</code> and <code>/</code> and check the predecessor character, you write a regexp that find a <code>.</code> and <code>/</code> that <em>don't</em> have <code>\\\\</code> before?</p>\n<p>This way, you can avoid the loop and the short circuit to an array</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function isValidEscaped(str) {\n const pattern = /[^\\\\]{2}[./]/g;\n return str.search(pattern) === -1; \n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-21T00:47:51.367", "Id": "248219", "ParentId": "247841", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:28:38.020", "Id": "247841", "Score": "4", "Tags": [ "javascript", "regex", "ecmascript-6" ], "Title": "Check whether '.' and '/' are escaped properly" }
247841
<p>I have a white label swift based application in which I need to change behavior depending on the customers. I would like to add that behavior in a dedicated framework in classes/struct that would be kind of plugins.</p> <p>The needs are basically always the same :</p> <ul> <li>extending C.D. data model</li> <li>synchronizing new entities with backend</li> <li>adding a new view controller between two existing...</li> </ul> <p>So this is what I have been drafting so far, and I would like some advices / external views.</p> <pre><code>enum PluginType { case navigationPlugin, synchronizationPlugin, databasePlugin } protocol BasePluginProtocol { static var type: PluginType { get } } protocol NavigationPluginProtocol : BasePluginProtocol { func handle(navigationEvent : String, from presenter: UIViewController?) } protocol SynchronizationPluginProtocol : BasePluginProtocol { // returns names of entities to be synchronized with backend in the appropriate order func orderedSynchronizableEntities([String]) -&gt; [String] } protocol DatabasePluginProtocol : BasePluginProtocol { // returns bundle containing CoreData customer model func databaseBundle(bundle : Bundle) } extension NavigationPluginProtocol { static var type: PluginType { return .navigationPlugin } } extension SynchronizationPluginProtocol { static var type: PluginType { return .synchronizationPlugin } } extension DatabasePluginProtocol { static var type: PluginType { return .databasePlugin } } class PluginManager { static var plugins = [BasePluginProtocol.Type]() static func plugin(_ pluginType : PluginType) -&gt; BasePluginProtocol.Type? { return plugins.first(where: { $0.type == pluginType }) } static public func registerPlugin(pluginType : BasePluginProtocol.Type) { plugins.append(pluginType) } } // Usage sample : let plugin = PluginManager.plugin(.synchronizationPlugin) as! SynchronizationPlugin let defaultEntitiesToSynchronize = [ ... ] SynchronizationManager.synchronize(plugin.orderedSynchronizableEntities(defaultEntitiesToSynchronize)) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T07:49:34.960", "Id": "247842", "Score": "1", "Tags": [ "swift", "plugin" ], "Title": "Plugin architecture to extend/customize behavior of white label swift based application" }
247842
<p>The code works fine for inputs that have a solution. The goal board is</p> <p>1 2 3</p> <p>4 5 6</p> <p>7 8</p> <p>I have tried to implement using the A* search algorithm. The code runs for 2 seconds or slightly more time which seems slow compared to the implementation in other languages. How do I optimize the code? I have included two sample inputs within the code one of which requires longer time to run.</p> <p><strong>Board</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; //Sample input 3 0 1 3 4 2 5 7 8 6 //Sample input 3 8 1 3 4 0 2 7 6 5 int ** goal; int N; void allocate_mem(int ** * arr) { * arr = (int ** ) malloc(N * sizeof(int * )); int i; for (i = 0; i &lt; N; i++) ( * arr)[i] = (int * ) malloc(N * sizeof(int)); } void deallocate_mem(int ** * arr) { int i, N; for (i = 0; i &lt; N; i++) free(( * arr)[i]); free( * arr); } void createTiles(int ** tiles, int ** arr) { int i, j; for (i = 0; i &lt; N; i++) for (j = 0; j &lt; N; j++) tiles[i][j] = arr[i][j]; } void createGoal(void) { int i, j; allocate_mem( &amp; goal); int filler = 1; for (i = 0; i &lt; N; i++) { for (j = 0; j &lt; N; j++) { if (i == N - 1 &amp;&amp; j == N - 1) goal[i][j] = 0; else goal[i][j] = filler++; } } } void display(int ** t) { int i, j; printf(&quot;\n%d\n&quot;, N); for (i = 0; i &lt; N; i++) { for (j = 0; j &lt; N; j++) { if (t[i][j] == 0) printf(&quot; &quot;); else printf(&quot;%d &quot;, t[i][j]); } printf(&quot;\n&quot;); } } int hamming(int ** tiles) { int count = 0, j, i; for (i = 0; i &lt; N; i++) for (j = 0; j &lt; N; j++) { if (tiles[i][j] == 0) continue; if (tiles[i][j] != goal[i][j]) count++; } return count; } bool isGoal(int ** t) { int i, j; for (i = 0; i &lt; N; i++) for (j = 0; j &lt; N; j++) if (t[i][j] != goal[i][j]) return false; return true; } bool equals(int ** p, int ** q) { int i, j; for (i = 0; i &lt; N; i++) for (j = 0; j &lt; N; j++) if (p[i][j] != q[i][j]) return false; return true; } void swap(int ** surface, int x1, int y1, int x2, int y2) { int temp = surface[x1][y1]; surface[x1][y1] = surface[x2][y2]; surface[x2][y2] = temp; } void copy(int ** toRet, int ** origin) { int i, j; for (i = 0; i &lt; N; i++) for (j = 0; j &lt; N; j++) toRet[i][j] = origin[i][j]; } //finds twin of board by exchanging any two blocks void boardTwin(int ** toRet) { int i, j; for (i = 0; i &lt; N; i++) { for (j = 0; j &lt; N - 1; j++) { if (toRet[i][j] != 0 &amp;&amp; toRet[i][j + 1] != 0) { swap(toRet, i, j, i, j + 1); } } } } typedef struct board_ { int ** data; // Lower values indicate higher priority int cost; int level; struct board_ * parent; } board; board * newBoard(int ** arr, board * parent, int level) { board * temp = (board * ) malloc(sizeof(board)); allocate_mem( &amp; (temp -&gt; data)); createTiles(temp -&gt; data, arr); temp -&gt; cost = hamming(arr); temp -&gt; level = level; temp -&gt; parent = parent; return temp; } typedef struct node { board * b; // Lower values indicate higher priority int priority; struct node * next; } Node; // Function to Create A New Node Node * newNode(board * brd) { Node * temp = (Node * ) malloc(sizeof(Node)); temp -&gt; b = brd; temp -&gt; priority = brd -&gt; cost + brd -&gt; level; temp -&gt; next = NULL; return temp; } // Return the value at head board * peek(Node ** head) { return ( * head) -&gt; b; } // Removes the element with the // highest priority form the list void pop(Node ** head) { Node * temp = * head; ( * head) = ( * head) -&gt; next; free(temp); } // Function to push according to priority void push(Node ** head, board * d) { Node * start = ( * head); // Create new Node Node * temp = newNode(d); int p = d -&gt; cost + d -&gt; level; // Special Case: The head of list has lesser // priority than new node. So insert new // node before head node and change head node. if (( * head) -&gt; priority &gt; p) { // Insert New Node before head temp -&gt; next = * head; ( * head) = temp; } else { // Traverse the list and find a // position to insert new node while (start -&gt; next != NULL &amp;&amp; start -&gt; next -&gt; priority &lt; p) { start = start -&gt; next; } // Either at the ends of the list // or at required position temp -&gt; next = start -&gt; next; start -&gt; next = temp; } } // Function to check is list is empty int isEmpty(Node ** head) { return ( * head) == NULL; } void pushNeighbors(board * brd, Node * pq) { int i, j, stop = 0; int ** temp, ** t; allocate_mem( &amp; temp); for (i = 0; i &lt; N; i++) { for (j = 0; j &lt; N; j++) if (brd -&gt; data[i][j] == 0) { stop = 1; break; } if (stop == 1) break; } if (i + 1 &lt; N) { copy(temp, brd -&gt; data); swap(temp, i + 1, j, i, j); board * dChild = newBoard(temp, brd, brd -&gt; level + 1); if (pq == NULL) { pq = newNode(dChild); } else push( &amp; pq, dChild); } if (j - 1 &gt;= 0) { copy(temp, brd -&gt; data); swap(temp, i, j - 1, i, j); board * lChild = newBoard(temp, brd, brd -&gt; level + 1); if (pq == NULL) { pq = newNode(lChild); } else push( &amp; pq, lChild); } if (i - 1 &gt;= 0) { copy(temp, brd -&gt; data); swap(temp, i - 1, j, i, j); board * uChild = newBoard(temp, brd, brd -&gt; level + 1); if (pq == NULL) { pq = newNode(uChild); } else push( &amp; pq, uChild); } if (j + 1 &lt; N) { copy(temp, brd -&gt; data); swap(temp, i, j + 1, i, j); board * rChild = newBoard(temp, brd, brd -&gt; level + 1); if (pq == NULL) { pq = newNode(rChild); } else push( &amp; pq, rChild); } } void printPath(board * root) { if (root == NULL) return; else printPath(root -&gt; parent); display(root -&gt; data); } void solve(int ** arr) { board * root = newBoard(arr, NULL, 0); Node * pq = newNode(root); int d = 0; while (!isEmpty( &amp; pq)) { d++; board * peeked = peek( &amp; pq); if (isGoal(peeked -&gt; data)) { printf(&quot;\nPath&quot;); printPath(peeked); return; } //prints a dot to mind the user that code is running if (d &gt;= 2500) { printf(&quot;. &quot;); d = 0; } pushNeighbors(peeked, pq); pop( &amp; pq); } } int main() { // Create a Priority Queue int i, j, ** arr; printf(&quot;Enter input:&quot;); scanf(&quot;%d&quot;, &amp; N); createGoal(); arr = malloc(N * sizeof(int * )); // N is the number of the rows for (i = 0; i &lt; N; i++) arr[i] = malloc(N * sizeof(int)); // N is the number of the columns for (i = 0; i &lt; N; i++) for (j = 0; j &lt; N; j++) { scanf(&quot;%d&quot;, &amp; arr[i][j]); } solve(arr); return 0; } </code></pre> <p>The code prints dots to notify that it's running.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:26:02.000", "Id": "485365", "Score": "3", "body": "One obvious major optimization is to get rid of your pointer look-up tables and use 2D arrays instead. See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). As for general code review, your coding style is both inconsistent and hard to read, to the point where I can't be bothered reading the code. Always include empty lines between function bodies, to begin with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:03:25.687", "Id": "485379", "Score": "0", "body": "There are a lot of problems with this, not just performance problems. I would say this is not A*. For example, nothing prevents the same board from being generated and visited an infinite number of times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T02:37:15.153", "Id": "485622", "Score": "0", "body": "@Lundin I had to generalise this later on for n-tile puzzle solver. So I have used 2D pointers instead of 2D arrays. I have also updated coding style and included empty lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T02:41:09.863", "Id": "485623", "Score": "0", "body": "@harold Same board might be generated but it's children will not be traversed. As the traversal takes place giving priority to lowest cost children, if same node is being generated again it's actual cost now will be higher than previous as number of moves increases and it will not be traversed. Also the code has never run infintely for any test case that has a solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T10:38:44.157", "Id": "485652", "Score": "1", "body": "A* is not supposed to run infinitely when there is no solution, it's supposed to run out of nodes to consider so it can detect that situation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-21T09:07:21.743", "Id": "486118", "Score": "0", "body": "@harold Thank you. I am able to implement it faster by not generating the same board. Also, I have added a few lines that will detect the inputs with no solution." } ]
[ { "body": "<p>I have made two major changes for the code that made it faster to run.</p>\n<ol>\n<li>I have avoided pushing parent of a particular node as its child. Code changes as follows</li>\n</ol>\n<pre><code>void pushNeighbors(board * brd, Node * pq) {\n int i, j, stop = 0;\n int ** temp, ** t;\n allocate_mem( &amp; temp);\n for (i = 0; i &lt; N; i++) {\n for (j = 0; j &lt; N; j++)\n if (brd -&gt; data[i][j] == 0) {\n stop = 1;\n break;\n }\n if (stop == 1) break;\n }\n if (i + 1 &lt; N) {\n copy(temp, brd -&gt; data);\n swap(temp, i + 1, j, i, j);\n board * dChild = newBoard(temp, brd, brd -&gt; level + 1);\n if (pq == NULL) {\n pq = newNode(dChild);\n } \n else if(brd-&gt;parent == NULL)\n push( &amp; pq, dChild);\n //Avoid pushing parent as a child again\n else if(!equals(brd-&gt;parent-&gt;data,dChild-&gt;data)) {\n push( &amp; pq, dChild); \n }\n }\n if (j - 1 &gt;= 0) {\n copy(temp, brd -&gt; data);\n swap(temp, i, j - 1, i, j);\n board * lChild = newBoard(temp, brd, brd -&gt; level + 1);\n if (pq == NULL) {\n pq = newNode(lChild);\n } \n else if(brd-&gt;parent == NULL)\n push( &amp; pq, lChild);\n //Avoid pushing parent as a child again\n else if(!equals(brd-&gt;parent-&gt;data,lChild-&gt;data)) {\n push( &amp; pq, lChild); \n } \n }\n if (i - 1 &gt;= 0) {\n copy(temp, brd -&gt; data);\n swap(temp, i - 1, j, i, j);\n board * uChild = newBoard(temp, brd, brd -&gt; level + 1);\n if (pq == NULL) {\n pq = newNode(uChild);\n } \n else if(brd-&gt;parent == NULL)\n push( &amp; pq, uChild);\n //Avoid pushing parent as a child again\n else if(!equals(brd-&gt;parent-&gt;data,uChild-&gt;data)) {\n push( &amp; pq, uChild); \n } \n }\n\n if (j + 1 &lt; N) {\n copy(temp, brd -&gt; data);\n swap(temp, i, j + 1, i, j);\n board * rChild = newBoard(temp, brd, brd -&gt; level + 1);\n if (pq == NULL) {\n pq = newNode(rChild);\n } \n else if(brd-&gt;parent == NULL)\n push( &amp; pq, rChild);\n //Avoid pushing parent as a child again\n else if(!equals(brd-&gt;parent-&gt;data,rChild-&gt;data)) {\n push( &amp; pq, rChild); \n } \n }\n}\n</code></pre>\n<ol start=\"2\">\n<li>The code solves a twin board(two numbers from the actual board will be swapped). If the twin board is solved, no solution exists for the actually entered board.</li>\n</ol>\n<pre><code>void solve(int ** arr) {\n board * root = newBoard(arr, NULL, 0);\n Node * pq = newNode(root);\n //Creating a twin array to solve\n int **twinArr;\n int i;\n twinArr = malloc(N * sizeof(int * )); // N is the number of the rows\n for (i = 0; i &lt; N; i++)\n twinArr[i] = malloc(N * sizeof(int)); // N is the number of the columns\n copy(twinArr,arr);\n boardTwin(twinArr);\n board * rootTwin = newBoard(twinArr, NULL, 0);\n Node * pqTwin = newNode(rootTwin);\n //if twin is solved,no solution for main\n while (!isEmpty( &amp; pq) || !isEmpty(&amp;pqTwin)) {\n board * peeked = peek( &amp; pq);\n board * peekedTwin = peek(&amp; pqTwin);\n if (isGoal(peeked -&gt; data)) {\n printf(&quot;\\nPath&quot;);\n printPath(peeked);\n return;\n }\n //Checks if twin is solved\n if (isGoal(peekedTwin -&gt; data)) {\n printf(&quot;\\n No solution exists for entered board.&quot;);\n return;\n }\n pushNeighbors(peeked, pq);\n pop( &amp; pq);\n //push peekedTwin neighbors\n pushNeighbors(peekedTwin, pqTwin);\n //pop minimum from twin queue\n pop( &amp; pqTwin);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-23T09:12:34.133", "Id": "248309", "ParentId": "247844", "Score": "1" } } ]
{ "AcceptedAnswerId": "248309", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T08:22:44.057", "Id": "247844", "Score": "3", "Tags": [ "performance", "c" ], "Title": "8 puzzle solver in C" }
247844
<p>I'm building a method that tries to detect whether given information about an object's property to retrieve, a constraint operator and some data to compare it against, whether the result is true or false.</p> <p>So I'm given is an object containing the type of object to read (<code>File</code>, <code>Folder</code>, <code>RegistryKey</code>, <code>RegistryValue</code>, <code>MSI</code>), the information required to retrieve that particular object type (for example a path, or an MSI product code) and the name of the property to read from that object as well as what data type that property should be. There are only four data types that can be returned: <code>string</code>, <code>int</code>, <code>DateTime</code> and <code>Version</code>.</p> <p>I'm also given a constraint operator which can be (among a couple others) <code>Equals</code>, <code>Contains</code>, <code>StartsWith</code>, <code>EndsWith</code>, <code>Between</code>, <code>GreaterThan</code>, <code>LowerThan</code>, <code>OneOf</code>. Some will only accept strings (<code>Contains</code>, <code>StartsWith</code>, <code>EndsWith</code>) others will accept the other three object types but not strings (<code>Between</code>, <code>GreaterThan</code>, <code>LowerThan</code>) and some will accept all object types (<code>Equals</code>, <code>OneOf</code>). Depending on the constraint operator itself, I may either have a single value to compare against (<code>Equals</code>, <code>StartsWith</code>, <code>EndsWith</code>, <code>GreaterThan</code>, etc), two values (<code>Between</code>) or an array of values (<code>OneOf</code>). There are also <code>And</code> and <code>Or</code> constraint operators that basically just contain an array of other constraint operator expressions.</p> <p>Lastly I also have what to compare against, which is just a value as a string and the data type that should be (so I need to cast it to the correct data type).</p> <p>My initial idea was to try to break things up and have one method responsible for a single thing. So one method to retrieve the object's property given the data that I have, one method responsible for retrieving the appropriate object to compare against (and cast it to the correct data type) and one method responsible for executing the constraint operator's logic and return a definitive <code>bool</code> value.</p> <p>My first problem is that because my method to return the object's property can actually return 4 different data types... I had to make it return <code>object</code>. I <em>could</em> make it a generic method, but then that would imply that the calling would have to know the data type of the property being returned and that feels like it's outside of the scope of the calling method, it should just go &quot;here's some data that you need to analyze to return an object's property back to me. I don't care how, I don't care what it is, just do it&quot;.</p> <p>The second problem is pretty much the same but for the data I want to compare against.</p> <p>The third problem is with the constraint operators, I thought of a way of creating an interface that fits all of them and came up with a (rather dodgy) interface implementation as follows:</p> <pre><code>public interface IConstraintOperator { public bool Check&lt;T&gt;(T valueA, params T[] valueB) } </code></pre> <p>This allows me never care for the concrete type implementing the interface and just deal with the interface, but also means I never have to care about what <code>T</code> is or what I'm passing to it (be it a single value, or two values or an array, etc).</p> <p>There are of course quite a few disadvantages to this:</p> <ul> <li><p>For each class implementing <code>IConstraintOperator</code> I need to check that <code>T</code> is a supported type and potentially handle it differently internally and throw if <code>typeof(T)</code> is not supported.</p> </li> <li><p>I receive <code>params T[]</code> as my second parameter, which means that for constraint operator that only care about one value I ignore anything other than the first value. It's not a bug at all, but it's also not pretty code when I can do <code>Equals(&quot;Hello&quot;, &quot;H&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;)</code> and only the first element of the array is used for the comparison.</p> </li> </ul> <p>How can I improve these things?</p> <p>Current working code below:</p> <pre><code>private bool DetectExpression(Expression expression, IEnumerable&lt;SimpleSetting&gt; settings) { var op = Enum.Parse&lt;ConstraintOperator&gt;(expression.Operator.OperatorName, true); if (op == ConstraintOperator.AND) return expression.Operands.Select(x =&gt; DetectExpression((Expression) x, settings)).All(x =&gt; x); if (op == ConstraintOperator.OR) return expression.Operands.Select(x =&gt; DetectExpression((Expression) x, settings)).Any(x =&gt; x); var settingReference = (SettingReference) expression.Operands.FirstOrDefault(x =&gt; x is SettingReference); var constantValue = (ConstantValue) expression.Operands.FirstOrDefault(x =&gt; x is ConstantValue); var constantValueList = (ConstantValueList) expression.Operands.FirstOrDefault(x =&gt; x is ConstantValueList); object constantValueValue = constantValue?.ValueType.Name switch { nameof(Int64) =&gt; long.Parse(constantValue.Value), nameof(Version) =&gt; Version.Parse(constantValue.Value), nameof(DateTime) =&gt; DateTime.Parse(constantValue.Value), nameof(String) =&gt; constantValue.Value, null =&gt; null, _ =&gt; throw new NotSupportedException() }; var constantValueListValue = constantValueList?.ListValueType.Name switch { &quot;Int64Array&quot; =&gt; constantValueList.Values.Select(long.Parse).Cast&lt;object&gt;(), &quot;VersionArray&quot; =&gt; constantValueList.Values.Select(Version.Parse), &quot;DateTimeArray&quot; =&gt; constantValueList.Values.Select(DateTime.Parse).Cast&lt;object&gt;(), &quot;StringArray&quot; =&gt; constantValueList.Values, null =&gt; null, _ =&gt; throw new NotSupportedException() }; var objectProperty = GetObjectProperty(settingReference, settings); return GetConstraintOperator(op).Check(objectProperty, constantValueValue ?? constantValueListValue); } private static object GetObjectProperty(SettingReferenceBase settingReference, IEnumerable&lt;SimpleSetting&gt; settings) { var obj = GetObject(settingReference, settings); if (settingReference.MethodType == ConfigurationItemSettingMethodType.Count) return obj != null ? 1 : 0; if (obj == null) return null; return settingReference.PropertyPath switch { // Registry key &quot;RegistryKeyExists&quot; =&gt; true, // Registry value &quot;RegistryValueExists&quot; =&gt; true, &quot;&quot; when settingReference.SettingSourceType == ConfigurationItemSettingSourceType.Registry =&gt; obj, // File &quot;Size&quot; =&gt; ((FileObject) obj).Size, &quot;Version&quot; when settingReference.SettingSourceType == ConfigurationItemSettingSourceType.File =&gt; ((FileObject) obj).Version, &quot;DateModified&quot; when settingReference.SettingSourceType == ConfigurationItemSettingSourceType.File =&gt; ((FileObject) obj).DateModified, &quot;DateCreated&quot; when settingReference.SettingSourceType == ConfigurationItemSettingSourceType.File =&gt; ((FileObject) obj).DateCreated, // Folder &quot;DateModified&quot; when settingReference.SettingSourceType == ConfigurationItemSettingSourceType.Folder =&gt; ((FolderObject) obj).DateModified, &quot;DateCreated&quot; when settingReference.SettingSourceType == ConfigurationItemSettingSourceType.Folder =&gt; ((FolderObject) obj).DateCreated, // Not supported _ =&gt; throw new NotSupportedException() }; } private static object GetObject(SettingReferenceBase settingReference, IEnumerable&lt;SimpleSetting&gt; settings) { var setting = settings.First(x =&gt; x.LogicalName == settingReference.SettingLogicalName); // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault switch (settingReference.SettingSourceType) { case ConfigurationItemSettingSourceType.File: return FileObject.Get(setting.Location, ((FileOrFolder) setting).Is64Bit); case ConfigurationItemSettingSourceType.Folder: return FolderObject.Get(setting.Location, ((FileOrFolder) setting).Is64Bit); case ConfigurationItemSettingSourceType.RegistryKey: var registryKey = (RegistryKey) setting; return RegistryKeyObject.Get(registryKey.RootKey, registryKey.Key, registryKey.Is64Bit); case ConfigurationItemSettingSourceType.Registry: var registrySetting = (RegistrySetting) setting; var dataType = registrySetting.SettingDataType.Name; return dataType switch { nameof(String) =&gt; RegistryValueObject&lt;string&gt;.Get(registrySetting.RootKey, registrySetting.Key, registrySetting.ValueName, registrySetting.Is64Bit)?.Value, nameof(Version) =&gt; RegistryValueObject&lt;Version&gt;.Get(registrySetting.RootKey, registrySetting.Key, registrySetting.ValueName, registrySetting.Is64Bit)?.Value, nameof(Int64) =&gt; RegistryValueObject&lt;long&gt;.Get(registrySetting.RootKey, registrySetting.Key, registrySetting.ValueName, registrySetting.Is64Bit)?.Value, _ =&gt; null }; case ConfigurationItemSettingSourceType.MSI: var msiSetting = (MSISettingInstance) setting; return WindowsInstallerObject.Get(msiSetting.ProductCode); default: throw new NotSupportedException(); } } public IConstraintOperator GetConstraintOperator(ConstraintOperator constraintOperator) { return _constraintOperators.First(x =&gt; Enum.Parse&lt;ConstraintOperator&gt;(x.GetType().Name, true) == constraintOperator); } </code></pre> <p>I actually think that the constraint operators should be extension methods/static methods with one method per each supported data type and started writing that class already, but I just can't see how to integrate it into what I already have simply because it means my <code>DetectExpression</code> method now needs to know the concrete data type being returned by <code>GetObjectProperty</code>.</p> <p>Any help with refactoring this and any other issues someone might see with it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:36:18.067", "Id": "247849", "Score": "1", "Tags": [ "c#", "parsing", ".net" ], "Title": "Code refactor - eliminate generic interface and object methods" }
247849
<p>This is my version of the Snake Game. The project is not done yet, I still want to try to implement some other game mechanics like two player mode, high score leaderboard, etc. Also I would like to implement GUI if it won't be to hard.</p> <p>At this point the game is already playable, that means that the basic game mechanics have been covered and because of that I would like to hear your opinion on the project. I would like to know how do you find my programming style, what are some areas that would need to improve, should I change or improve anything in the code or are there any better solutions for certain tasks, etc? Also I would like to hear some general advice that would be useful on future projects.</p> <pre><code>//SNAKE HEADER FILE #include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; struct coordinates{int x,y;}; enum direction{UP,DOWN,LEFT,RIGHT}; class Snake { private: vector&lt;coordinates*&gt; body; public: Snake(int bodyX,int bodyY); ~Snake(); int getX(int position); int getY(int position); void setX(int position,int x); void setY(int position,int y); int size(); void step(int x,int y,bool&amp; gameOver); void evolve(int x,int y,direction dir); }; //SNAKE SOURCE FILE #include &quot;Snake.h&quot; Snake::Snake(int bodyX, int bodyY) { cout&lt;&lt;&quot;Snake constructor is executed&quot;&lt;&lt;endl; coordinates bodyXY={bodyX,bodyY}; body.push_back(new coordinates(bodyXY)); } Snake::~Snake() { cout&lt;&lt;&quot;Snake destructor is executed&quot;&lt;&lt;endl; } int Snake::getX(int position) { return body[position]-&gt;x; } int Snake::getY(int position) { return body[position]-&gt;y; } int Snake::size() { return body.size(); } void Snake::step(int x,int y,bool&amp; gameOver) { body.erase(body.begin()); body.push_back(new coordinates({x, y})); for(int i=0;i&lt;body.size()-1;i++) { if(body[i]-&gt;x==x&amp;&amp;body[i]-&gt;y==y) { gameOver=true; cout&lt;&lt;&quot;==================================&quot;&lt;&lt;endl; cout&lt;&lt;&quot; GAME OVER!&quot;&lt;&lt;endl; cout&lt;&lt;&quot;==================================&quot;&lt;&lt;endl; } } //cout&lt;&lt;((gameOver)?&quot;True&quot;:&quot;False&quot;)&lt;&lt;endl; } void Snake::setX(int position, int x) { body[position]-&gt;x=x; } void Snake::setY(int position, int y) { body[position]-&gt;y=y; } void Snake::evolve(int x,int y,direction dir) { body.push_back(new coordinates({x,y})); for(int i=0;i&lt;body.size()-1;i++) { switch(dir) { case LEFT: body[i]-&gt;x++; break; case RIGHT: body[i]-&gt;x--; break; case UP: body[i]-&gt;y++; break; case DOWN: body[i]-&gt;y--; } } } //APPLE HEADER #include &lt;cstdlib&gt; #include &lt;iostream&gt; using namespace std; class Apple { private: int appleX,appleY; public: Apple(int width,int height); ~Apple(); int getX(); int getY(); void generate(int width,int height); }; //APPLE SOURCE #include &quot;Apple.h&quot; Apple::Apple(int width, int height) { cout&lt;&lt;&quot;Apple constructor is executed&quot;&lt;&lt;endl; generate(width,height); } Apple::~Apple() { cout&lt;&lt;&quot;Apple destructor is executed&quot;&lt;&lt;endl; } int Apple::getX() { return appleX; } int Apple::getY() { return appleY; } void Apple::generate(int width, int height) { appleX=rand()%(width-2)+1; appleY=rand()%(height-2)+1; } //GAME HEADER #include &quot;Snake.h&quot; #include &quot;Apple.h&quot; #include &lt;conio.h&gt; class Game { private: int height,width; public: Game(int height,int width); ~Game(); void render(); }; //GAME SOURCE #include &quot;Game.h&quot; Game::Game(int height, int width) :height(height),width(width){ cout&lt;&lt;&quot;Game constructor is executed&quot;&lt;&lt;endl; } Game::~Game() { cout&lt;&lt;&quot;Game destructor is executed&quot;&lt;&lt;endl; } void Game::render() { char controls; direction dir; int x,y; x=width/2; y=height/2; bool stop=false; Snake snake(x,y); Apple apple(width,height); while(!stop) { for(int i=0;i&lt;snake.size();i++) { cout&lt;&lt;snake.getX(i)&lt;&lt;&quot; &quot;&lt;&lt;snake.getY(i)&lt;&lt;endl; } for(int i=0;i&lt;height;i++) { for(int j=0;j&lt;width;j++) { /* * ============================ * GAME BOARD * ============================ * */ if(i==0||i==height-1) { if(j==0||j==width-1)cout&lt;&lt;&quot;+&quot;;//game board corners else cout&lt;&lt;&quot;-&quot;;//horizontal site } else if(j==0||j==width-1)cout&lt;&lt;&quot;|&quot;;//vertical site else { bool print=false; //IZRIS JABOLKA if(apple.getX()==j&amp;&amp;apple.getY()==i) { cout&lt;&lt;&quot;*&quot;; print=true; } /* * ================================ * SNAKE ALGORITHM * ================================ */ //if(x==j&amp;&amp;y==i)cout&lt;&lt;&quot;X&quot;; for(int k=0; k &lt; snake.size(); k++) { //SNAKE PRINT if(snake.getX(k)==j&amp;&amp;snake.getY(k)==i) { //HEAD if(k==snake.size()-1)cout&lt;&lt;&quot;X&quot;; //TAIL else cout&lt;&lt;&quot;o&quot;; print=true; } //BOUNDARY CONDITIONS if(snake.getX(k)&gt;=width-1)snake.setX(k,1); else if(snake.getX(k)&lt;=0)snake.setX(k,width-2); else if(snake.getY(k)&gt;=height-1)snake.setY(k,1); else if(snake.getY(k)&lt;=0)snake.setY(k,height-2); //SNAKE EATS THE APPLE if(snake.getX(k)==apple.getX()&amp;&amp;snake.getY(k)==apple.getY()) { apple.generate(width,height); snake.evolve(x,y,dir); } } if(!print)cout&lt;&lt;&quot; &quot;;//empty space on the board } } cout&lt;&lt;endl; } /* * ===================================== * SNAKE CONTROLS * ===================================== */ cin&gt;&gt;controls; switch (controls) { case 'a': x--; dir=LEFT; break; case 'd': x++; dir=RIGHT; break; case 'w': y--; dir=UP; break; case 's': y++; dir=DOWN; break; default: stop=true; break; } snake.step(x,y,stop); } } //AND THE MAIN SOURCE #include &lt;iostream&gt; #include &quot;Game.h&quot; const int height=10; const int width=20; int main() { Game game(height,width); game.render(); std::cout &lt;&lt; &quot;Hello, World!&quot; &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<h1>Never use <code>using namespace std</code> in header files</h1>\n<p>You should never write <code>using namespace std</code> in header files, as this can cause issues in larger projects where multiple libraries are combined. If every header file starts adding their own <code>using namespace ...</code>, it might result in hard to debug problems where it's no longer clear from what namespace a function or variable name is coming from.</p>\n<p>You can safely use it in your own <code>.cpp</code> files, but even then I would avoid this habit. See <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this question</a> for more details.</p>\n<h1>Store coordinates by value</h1>\n<p>In <code>class Snake</code>, you store pointers to coordinates in the vector <code>body</code>. But you don't need this at all, and can just store the pointers by value:</p>\n<pre><code>std::vector&lt;coordinates&gt; body;\n</code></pre>\n<p>You then no longer need to manually call <code>new</code> and <code>delete</code> to allocate memory for the coordinates. And I see you never call <code>delete</code> in your code, so this will already fix a memory leak.</p>\n<h1>Pass <code>coordinates</code> where appropriate</h1>\n<p>Since you have a nice <code>struct coordinates</code>, use it everywhere you have to pass coordinates instead of passing two <code>int</code>s, and you can also use it as a return value. For example:</p>\n<pre><code>Snake::Snake(coordinates position) {\n body.push_back(position);\n}\n\n...\n\ncoordinates Snake::getCoordinates(int position) {\n return body[position];\n}\n\n...\n\nvoid Snake::step(coordinates position, ...) {\n body.erase(body.begin());\n body.push_back(position);\n ...\n}\n</code></pre>\n<h1>Use <code>std::deque</code> for the body coordinates</h1>\n<p>The body of the snake is added to from one end, and removed from from the other end. A <code>std::vector</code> is not the best container in this case, because it can only efficiently dd and remove from the back. The <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"noreferrer\"><code>std::deque</code></a> class does provide efficient insertion and removal from both ends, and provides easy functions for that:</p>\n<pre><code>class Snake {\n std::deque&lt;coordinates&gt; body;\n ...\n};\n\nvoid Snake::step(coordinates position, ...) {\n body.pop_front();\n body.push_back(position);\n ...\n}\n</code></pre>\n<h1>Avoid using <code>std::endl</code></h1>\n<p>Prefer writing <code>&quot;\\n&quot;</code> instead of <code>std::endl</code>. The latter is equivalent to the former, but also forces a flush of the output, which can be bad for performance. For more details, see <a href=\"https://stackoverflow.com/questions/4512631/difference-between-endl-and-n\">this question</a>.</p>\n<h1>Use range-for where appropriate</h1>\n<p>Assuming you can use C++11 features, try to use range-based for-loops where possible. For example, looping over the elements of the snake's body can be done so:</p>\n<pre><code>for (auto &amp;element: body) {\n if (element.x == position.x &amp;&amp; element.y == position.y) {\n ...\n }\n}\n</code></pre>\n<h1>Separate logic from presentation</h1>\n<p>Your <code>class Snake</code> encapsulates the logic of the snake's body, but it also prints a game over message. You should try to separate logic from presentation where possible. The function <code>Snake::step()</code> should just check whether the step is valid or not, and <code>return</code> a value indicating this. The caller can then decide whether or not to print a game over message. For example:</p>\n<pre><code>bool Snake::step(coordinates position) {\n body.pop_front();\n body.push_back(position);\n\n for (auto &amp;element: body) {\n if (element.x == position.x &amp;&amp; element.y == position.y) {\n return false;\n }\n }\n\n return true;\n}\n\n...\n\nvoid Game::render() {\n ...\n while (true) {\n ...\n if (!snake.step(position)) {\n std::cout &lt;&lt; &quot;Game over!\\n&quot;;\n break;\n }\n }\n}\n</code></pre>\n<h1>Use a proper random number generator</h1>\n<p>You use the C function <code>rand()</code>, which is a poor random number generator, but it could be good enough for a game of Snake. However, you never call <code>srand()</code>, which means the random number generator will always start with the same seed value, and thus always produce the same sequence of random values.</p>\n<p>C++11 introduced much better random number generator functions. In particular, you might want to use <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"noreferrer\"><code>std::uniform_int_distribution</code></a> to generate integers in a given range. You could use it like so:</p>\n<pre><code>class Apple {\n coordinates position;\n\n std::mt19937 gen(std::random_device());\n std::uniform_int_distribution x_distrib;\n std::uniform_int_distribution y_distrib;\n\npublic:\n ...\n void generate();\n};\n\nvoid Apple::Apple(int width, int height):\n x_distrib(1, width - 1), y_distrib(1, height - 1)\n{\n generate();\n}\n\nvoid Apple::generate() {\n position = {x_distrib(), y_distrib()};\n}\n</code></pre>\n<h1>Alternative way to evolve the snake body</h1>\n<p>Your method of evolving the snake's body requires saving the last direction the snake moved in, and you also move the whole body. In a typical Snake game, what happens is that the snake's body stays in the same place, but for the next move the tail will not shrink. To do this, you can keep a variable that tracks whether the snake needs to grow:</p>\n<pre><code>class Snake {\n std::deque&lt;coordinates&gt; body;\n int grow = 0;\n ...\npublic:\n ...\n void grow(int size);\n};\n\nvoid Snake::grow(int size) {\n grow += size;\n}\n\nbool Snake::step(coordinates position) {\n if (!grow) {\n body.pop_front();\n } else {\n grow--;\n }\n\n body.push_back(position);\n ...\n};\n</code></pre>\n<p>So when the snake eats an apple, you can just call <code>snake.grow(1)</code>. And this way, you can easily make the game harder by increasing the amount of elements the snake grows for each apple it eats.</p>\n<h1>Improve handling the snake wrapping the screen</h1>\n<p>When the snake makes a move, the only part of its body that could wrap round is its head. There is no need to check all elements of its body to see if they are out of bounds. So after reading the input, you should check whether the new head position has crossed the board boundaries, and if so wrap the coordinates. Only then call <code>Snake::step()</code>.</p>\n<p>Alternatively, you could just call <code>Snake::step()</code> with the delta position, and handle the updating of the position in <code>Snake::step()</code>.</p>\n<h1>Split <code>Game::render()</code> up</h1>\n<p>The function <code>Game::render()</code> does too many things. It not only renders the current board, it also handles input and performs most of the game logic. I suggest you create a function named <code>Game::loop()</code> which just does a high level implementation of the game loop, and calls other functions that implement the various parts I just mentioned, including <code>Game::render()</code> which now should only render the board.</p>\n<p>Make a function <code>Game::handle_input()</code> that handles the player's input. It should just make the snake do one step.</p>\n<p>Make a function <code>Game::logic()</code> that implements the rest of the game logic. In particular, check if the snake's head is at the same position of the apple, or if the snake bit itself.</p>\n<p>Doing this will make these functions small and concise, making maintenance easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T07:34:35.663", "Id": "485470", "Score": "3", "body": "I didn't expect such an resourcefull answer. Thank you verry much sir. Right now I am trying to implement the things you wrote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T15:36:15.527", "Id": "485516", "Score": "0", "body": "Very nice and formatted answer. Thank you dear @G. Sliepen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T15:41:23.723", "Id": "485517", "Score": "1", "body": "@Bunny I wouldn't call them sir, at least, you sure about their gender, though." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:04:54.920", "Id": "247871", "ParentId": "247851", "Score": "19" } }, { "body": "<p>Code update:</p>\n<p><strong>Coordinates.h</strong></p>\n<pre><code>#ifndef SNAKEGAMEVOL2_COORDINATES_H\n#define SNAKEGAMEVOL2_COORDINATES_H\n\nstruct coordinates{\n int x,y;\n friend bool operator==(const coordinates&amp; l,const coordinates&amp; r)\n {\n return l.x == r.x &amp;&amp; l.y == r.y;\n }\n};\n\n#endif //SNAKEGAMEVOL2_COORDINATES_H\n</code></pre>\n<p><strong>Snake.h</strong></p>\n<pre><code>#include &lt;deque&gt;\n#include &lt;iostream&gt;\n#include &quot;Coordinates.h&quot;\n\n \n\n\nclass Snake {\nprivate:\n std::deque&lt;coordinates&gt; body;\n int nBody;\npublic:\n Snake();//default constructor\n Snake(const Snake&amp; other);//copy constructor\n Snake(coordinates init_body);//constructor\n ~Snake();\n Snake&amp; operator=(const Snake&amp; other);\n coordinates getCoordinates(int position);\n void setCoordinates(int position,coordinates xy);\n int size();\n void step(coordinates coord);\n void grow(int size);\n};\n</code></pre>\n<p><strong>Snake.cpp</strong></p>\n<pre><code>#include &quot;Snake.h&quot;\n\nSnake::Snake()\n{\n std::cout&lt;&lt;&quot;Snake default constructor is executed\\n&quot;;\n body.push_back({0,0});\n nBody=0;\n}\n\nSnake::Snake(const Snake&amp; other):body(other.body),nBody(other.nBody)\n{\n std::cout&lt;&lt;&quot;Snake copy constructor is executed\\n&quot;;\n}\n\nSnake::Snake(coordinates init_body) {\n std::cout&lt;&lt;&quot;Snake constructor is executed\\n}&quot;;\n body.emplace_back(init_body);\n nBody=0;\n}\n\nSnake::~Snake()\n{\n std::cout&lt;&lt;&quot;Snake destructor is executed\\n&quot;;\n}\n\nSnake &amp; Snake::operator=(const Snake &amp;other)= default;\n\ncoordinates Snake::getCoordinates(int position) {\n return body[position];\n}\n\nint Snake::size() {\n return body.size();\n}\n\nvoid Snake::step(coordinates coord)\n{\n if(!nBody)\n {\n body.pop_front();\n } else{\n nBody--;\n }\n body.push_back(coord);\n}\n\nvoid Snake::setCoordinates(int position, coordinates xy)\n{\n body[position]=xy;\n} \n\nvoid Snake::grow(int size)\n{\n nBody+=size;\n}\n</code></pre>\n<p><strong>Apple.h</strong></p>\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n#include &quot;Coordinates.h&quot;\n\n\n\nclass Apple {\nprivate:\n coordinates appleCoord;\npublic:\n Apple();//default constructor\n Apple(coordinates dimensions);\n ~Apple();\n coordinates getCoordinates();\n void generate(coordinates dimensions);\n\n};\n</code></pre>\n<p><strong>Apple.cpp</strong></p>\n<pre><code> #include &quot;Apple.h&quot;\n \n Apple::Apple():appleCoord({0,0})\n {\n std::cout&lt;&lt;&quot;Apple default constructor is executed\\n&quot;;\n }\n \n Apple::Apple(coordinates dimensions) {\n std::cout&lt;&lt;&quot;Apple constructor is executed\\n&quot;;\n generate(dimensions);\n }\n \n Apple::~Apple()\n {\n std::cout&lt;&lt;&quot;Apple destructor is executed\\n&quot;;\n }\n \n coordinates Apple::getCoordinates() {\n return appleCoord;\n }\n \n \n void Apple::generate(coordinates dimensiosns) {\n appleCoord.x=rand()%(dimensiosns.x-2)+1;\n appleCoord.y=rand()%(dimensiosns.y-2)+1;\n }\n</code></pre>\n<p><strong>Game.h</strong></p>\n<pre><code>#include &quot;Snake.h&quot;\n#include &quot;Apple.h&quot;\n#include &lt;conio.h&gt;\n\n\n\n\nclass Game {\nprivate:\n int height,width;\n int x,y;\n bool stop;\n Snake snake;\n Apple apple;\n\npublic:\n Game(int height, int width);\n ~Game();\n void render();\n void logic();\n void loop();\n void input();\n\n};\n</code></pre>\n<p><strong>Game.cpp</strong></p>\n<pre><code>#include &quot;Game.h&quot;\n\nGame::Game(int height, int width) : height(height), width(width) {\n std::cout&lt;&lt;&quot;Game constructor is executed\\n&quot;;\n x=width/2;\n y=height/2;\n stop=false;\n snake.setCoordinates(0,{x,y});\n apple.generate({width,height});\n}\n\nGame::~Game()\n{\n std::cout&lt;&lt;&quot;Game destructor is executed\\n&quot;;\n}\n\nvoid Game::loop()\n{\n while(!stop)\n {\n render();\n input();\n logic();\n }\n}\n\nvoid Game::render()\n{\n coordinates xy{};\n /*for(int s=0;s&lt;snake.size();s++)\n {\n std::cout&lt;&lt;snake.getCoordinates(s).x&lt;&lt;&quot; &quot;&lt;&lt;snake.getCoordinates(s).y&lt;&lt;&quot;\\n&quot;;\n }*/\n for(int i=0;i&lt;height;i++)\n {\n for (int j = 0; j &lt; width; j++)\n {\n xy={j,i};\n /*\n * ============================\n * GAME BOARD\n * ============================\n * */\n if (i == 0 || i == height - 1)\n {\n if (j == 0 || j == width - 1)std::cout &lt;&lt; &quot;+&quot;;//game board corners\n else std::cout &lt;&lt; &quot;-&quot;;//horizontal side\n }\n else if (j == 0 || j == width - 1)std::cout &lt;&lt; &quot;|&quot;;//vertical side\n //APPLE\n else if (apple.getCoordinates()==xy)std::cout &lt;&lt; &quot;*&quot;;\n else\n {\n /*\n * ============================\n * SNAKE\n * ============================\n * */\n bool print=false;\n for(int k=0;k&lt;snake.size();k++)\n {\n if(snake.getCoordinates(k)==xy)\n {\n //HEAD\n if(k==snake.size()-1) std::cout&lt;&lt;&quot;X&quot;;\n //TAIL\n else std::cout&lt;&lt;&quot;o&quot;;\n print=true;\n }\n }\n //EMPTY SPACE\n if(!print)std::cout&lt;&lt;&quot; &quot;;\n }\n }\n std::cout&lt;&lt;&quot;\\n&quot;;\n }\n}\n\nvoid Game::logic()\n{\n //BOUNDARY CONDITIONS\n if(x&gt;=width-1)x=1;\n else if(x&lt;=0)x=width-2;\n if(y&gt;=height-1)y=1;\n else if(y&lt;=0)y=height-2;\n //SNAKE EATS APPLE\n coordinates head={x,y};\n if(head==apple.getCoordinates())\n {\n apple.generate({width,height});\n snake.grow(1);\n }\n for(int i=0;i&lt;snake.size()-1;i++)\n {\n if(head==snake.getCoordinates(i)) stop=true;\n }\n snake.step({x,y});\n //std::cout&lt;&lt;(snake.step({x,y})?&quot;True&quot;:&quot;False&quot;)&lt;&lt;&quot;\\n&quot;;\n}\n\nvoid Game::input()\n{\n char controls;\n std::cin&gt;&gt;controls;\n switch(controls)\n {\n case 'a':\n x--;\n break;\n case 'd':\n x++;\n break;\n case 'w':\n y--;\n break;\n case 's':\n y++;\n break;\n default:\n stop=true;\n break;\n }\n}\n</code></pre>\n<p>I still didn't use a better random generator for the class Apple beacuse it is easier to test my code this way.</p>\n<p>I added a default constructor to the Apple and Snake class so I can initialize them without inputing arguments to the constructor inside Game class. Also I added copy constructor and operator = to the class Snake beacuse of the three rule. Don't know if it is necessary though.</p>\n<p>Next two tasks that I want to tackle are how to handle the game over output, beacuse the old one dosen't do the trick anymore. Maybe should I write an extra method that would I call inside the logic() method and the method would output some text in to the console?\nFor example:</p>\n<pre><code>void Game::logic()\n{\n...\nfor(int i=0;i&lt;snake.size()-1;i++)\n {\n if(head==snake.getCoordinates(i)) \n {\n stop=true;\n gameOver()\n }\n }\n}\n</code></pre>\n<p>And I want to implement some graphical interface. I read something about SDL library and am trying to implement it on some other project. Would it be a good idea to begin with? Or should I do something else?</p>\n<p>Also I have a non programming related question. I'm a physics student who wants to get hired as C++ (or any other language) developer. I know that my programming skills are on the beginer spectrum, so I want to learn as much as possible on my own. So I would like to know how should I do that? Am I doing it the right way, so that I tackle different kind of projects or is there another way? And what kind of project do you suggest that I should do to gain the right kind of experience?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-18T06:40:20.647", "Id": "485779", "Score": "1", "body": "Hi, if you have updated your code and want it reviewed, please create a new question on CodeReview instead of posting it as an answer. You can then also a link back to this review and mention that it is an improved version of an earlier review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-17T19:00:08.523", "Id": "248050", "ParentId": "247851", "Score": "1" } } ]
{ "AcceptedAnswerId": "247871", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T10:56:27.123", "Id": "247851", "Score": "17", "Tags": [ "c++", "snake-game" ], "Title": "OOP Snake Game C++" }
247851
<p>I saw this entertaining <a href="https://www.youtube.com/watch?v=7EmboKQH8lM&amp;t=2965s" rel="nofollow noreferrer">talk</a> by: Bob Martin on clean code and started refactoring a relatively simple class today. I am, by no means, an expert on coding and still learning a lot every day, so I want to get this right eventually as well :).</p> <p>The purpose of the code is to retrieve an xml document from a website, which contains open job vacancies, and simply counts the number of vacancies available. This number should be cached. Then either the cached value shall be returned or the xml shall be retrieved and parsed to extract the number job vacancies, which, in turn, should be put into the cache. The number is then used in another part of the app to show a &quot;we're hiring&quot; badge.</p> <p>Would you be so kind and provide me with some feedback on:</p> <ul> <li>did I go too far with the extraction method here?</li> <li>did I not go far enough with the extraction method?</li> <li>can I refactor anything else?</li> <li>any other feedback on how to improve this code :)</li> </ul> <p>Here is the before:</p> <pre><code>&lt;?php namespace mainBundle\Services; use Psr\Cache\CacheItemPoolInterface; class JobCountProvider { private $cache; public function __construct(CacheItemPoolInterface $cache) { $this-&gt;cache = $cache; } public function getJobCount() { $url = 'https://page-to-return-open-positions-xml.de/xml?language=de'; $item = $this-&gt;cache-&gt;getItem('jobs-count'); if ($item-&gt;isHit()) { $item-&gt;get(); return $item-&gt;get(); } try { $fileContents = file_get_contents($url); $fileContents = str_replace([&quot;\n&quot;, &quot;\r&quot;, &quot;\t&quot;], '', $fileContents); $fileContents = trim(str_replace('&quot;', &quot;'&quot;, $fileContents)); $jobs = simplexml_load_string($fileContents); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 300); curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000); $result = curl_exec($ch); if (!$this-&gt;isValidXml($result)) { throw new \Exception('Error getting jobs xml'); } $result = str_replace([&quot;\n&quot;, &quot;\r&quot;, &quot;\t&quot;], '', trim($result)); $result = trim(str_replace('&quot;', &quot;'&quot;, $result)); $jobs = simplexml_load_string($result); $count = $jobs-&gt;count(); } catch (Exception $e) { $this-&gt;cache-&gt;save($item-&gt;set($count)); $item-&gt;expiresAfter(432000); } catch (\Exception $e) { $count = 0; $item-&gt;expiresAfter(0); } curl_close($ch); return $count; } private function isValidXml($content) { $content = trim($content); if (empty($content)) { return false; } if (stripos($content, '&lt;!DOCTYPE html&gt;') !== false) { return false; } libxml_use_internal_errors(true); simplexml_load_string($content); $errors = libxml_get_errors(); libxml_clear_errors(); return empty($errors); } } </code></pre> <p>And here is the after:</p> <pre><code>&lt;?php namespace mainBundle\Services; use Psr\Cache\CacheItemPoolInterface; class JobCountProvider { private $cache; public function __construct(CacheItemPoolInterface $cache) { $this-&gt;cache = $cache; } public function getJobCountFromPersonio(): int { $cachedJobCount = $this-&gt;isJobCountCached(); if ($cachedJobCount !== null) { return $cachedJobCount; } $content = $this-&gt;getContentFromJobsPage(300); if (!$this-&gt;isValidXml($content)) { $this-&gt;cache-&gt;deleteItem('jobs-count'); return 0; } $jobCount = $this-&gt;getSimpleXmlObjectFromString($content)-&gt;count(); $this-&gt;saveJobCountToCache($jobCount); return $jobCount; } private function saveJobCountToCache(int $jobCount) { $item = $this-&gt;cache-&gt;getItem('jobs-count'); $this-&gt;cache-&gt;save($item-&gt;set($jobCount)); $item-&gt;expiresAfter(432000); } private function isJobCountCached() { $item = $this-&gt;cache-&gt;getItem('jobs-count'); return $item-&gt;isHit() ? $item-&gt;get() : null; } private function getSimpleXmlObjectFromString(string $string): \SimpleXMLElement { $string = str_replace([&quot;\n&quot;, &quot;\r&quot;, &quot;\t&quot;], '', trim($string)); $xml = trim(str_replace('&quot;', &quot;'&quot;, $string)); return simplexml_load_string($xml); } private function getContentFromJobsPage(int $conTimeoutInMs) { $urlToParse = 'https://page-to-return-open-positions-xml.de/xml?language=de'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $urlToParse); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $conTimeoutInMs); curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1000); return curl_exec($ch); } private function isValidXml(string $xmlString) { $content = trim($xmlString); if (empty($content)) { return false; } if (stripos($content, '&lt;!DOCTYPE html&gt;') !== false) { return false; } libxml_use_internal_errors(true); simplexml_load_string($content); $errors = libxml_get_errors(); libxml_clear_errors(); return empty($errors); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:47:53.457", "Id": "485385", "Score": "0", "body": "Thanks Mast, I added a description on the purpose of the code and tried to improve the title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:51:10.077", "Id": "485386", "Score": "0", "body": "Much better, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T12:16:38.223", "Id": "485494", "Score": "0", "body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question instead, with links back and forth." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T15:59:40.830", "Id": "485520", "Score": "0", "body": "hm okey. I posted the code for others to benefit from, but if thats not allowed, ok :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T16:08:31.853", "Id": "485521", "Score": "0", "body": "We understand the sentiment, we really do, but can you understand the mess it would create if people keep updating their question and more answers keep coming in? The first answer would no longer be applicable to the code presented. Possibly neither would the second." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T16:26:38.400", "Id": "485522", "Score": "0", "body": "Totally understand :)\nMay I post the new code as an \"answer\" to my own question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T16:28:31.273", "Id": "485523", "Score": "0", "body": "If you post it as a review and not a code-dump, yes. If that review mentions points already in the other answers, that's fine, but all answers have to be reviews. If they happen to contain the final code as well, that's totally fine. Just, note the review part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T21:40:15.017", "Id": "485544", "Score": "0", "body": "Understood. Thank you for clarifying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T02:06:01.387", "Id": "485555", "Score": "0", "body": "@Mast what is the benefit of posting a new review that repeats advice already given?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T04:28:52.453", "Id": "485626", "Score": "0", "body": "I thought some might like to see the final code with all the changes we made together for completeness sake. It is not necessary, ppl can read the great suggestions by @mickmackusa and learn from those ☺️" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T04:33:42.473", "Id": "485628", "Score": "0", "body": "@Sto I was just struck by \"_If that review mentions points already in the other answers, that's fine_\". I was under the impression that Stack Exchange sites prefer not to waste researchers' time with redundant content. I am not bothered if you post your final script. I think it only needs to be the code, and then any **new** decisions you made and the logical reasons for them." } ]
[ { "body": "<ul>\n<li><p>the <code>str_replace()</code> calls can be consolidated. (<a href=\"https://3v4l.org/jBYaK\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$string = &quot;\\ntext\\r\\ntab\\t\\ntext\\&quot;quote'\\&quot;text&quot;;\nvar_dump(\n str_replace(\n ['&quot;', &quot;\\r&quot;, &quot;\\n&quot;, &quot;\\t&quot;],\n [&quot;'&quot;, ''],\n $string\n )\n);\n</code></pre>\n</li>\n<li><p>I do like <code>return $item-&gt;isHit() ? $item-&gt;get() : null;</code> which removes a redundant call.</p>\n</li>\n<li><p>You might like to indicate the data type that a method returns. E.g.:</p>\n<pre><code>private function isValidXml(string $xmlString): bool\n</code></pre>\n</li>\n<li><p>Since your <code>trim()</code> call assumes that the incoming data <code>isset()</code>, then <code>empty()</code> is doing more &quot;work&quot; than necessary. Perhaps this:</p>\n<pre><code>$content = trim($xmlString);\nif (!$content || stripos($content, '&lt;!DOCTYPE html&gt;') !== false) {\n return false;\n}\n</code></pre>\n</li>\n<li><p>For DRYness, I would like to see <code>simplexml_load_string()</code> only called once in this class. This would demand that the validation be integrated into the <code>getSimpleXmlObjectFromString()</code> method or that the xml is passed back it after the validating method was non-false.</p>\n</li>\n</ul>\n<p>Outside of these insights, your class seems pretty tidy to me.</p>\n<hr />\n<p>After comments from the OP:</p>\n<ul>\n<li><p>I think I recommend the exception throwing technique from the original class. I am not overly confident on the best practices of writing awesome try-catch blocks, but it feels like the appropriate place for it. I don't follow why there are two catch blocks in the original class. ...Try not to get too concerned about method length -- the concern must be confined to ensuring that methods have a single responsibility.</p>\n</li>\n<li><p><code>getSimpleXmlObjectFromString()</code> is sanitizing and converting. <code>isValidXml()</code> is validating before and after loading. I think you need to decide how you want to remove the redundant loading. Do you want separate methods that:</p>\n<ol>\n<li><code>sanitizeString()</code></li>\n<li><code>validateString()</code></li>\n<li><code>validateXML()</code></li>\n</ol>\n<br>\nMaybe, maybe not; but you should never ask php to perform the same operation on the same data more than once.\n</li>\n<li><p>Since <code>$errors = libxml_get_errors();</code> will ensure that the variable will be declared if reached, then <code>empty()</code> is doing unnecessary work. Like my earlier advice, just use a falsey check.</p>\n<pre><code>return !$errors;\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T05:53:06.517", "Id": "485464", "Score": "0", "body": "Thank you for taking the time to read my post. Very helpful comments, thank you. I have implemented your comments except the last :)\n\nI am struggeling to find a good solution to only call `simplexml_load_string()` once in that class. Is it ok for the function `getSimpleXmlObjectFromString()` to either return a SimpleXml object or false? Then the function name is not suitable any more, but anything more added to it makes it too long I think. \n\nAs is, it is quite readable I think. Making this change would make it somewhat less readable and easily understandable, no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T05:54:36.757", "Id": "485465", "Score": "0", "body": "The other option to return the xml from the `isValidXml` means I need to change the function name as well, where I struggle. `returnSimpleXmlOrNull()` maybe to keep it as readable as possible?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T01:33:42.727", "Id": "247880", "ParentId": "247852", "Score": "3" } } ]
{ "AcceptedAnswerId": "247880", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T11:41:25.160", "Id": "247852", "Score": "5", "Tags": [ "php", "object-oriented", "xml", "classes", "curl" ], "Title": "Refactoring a class that counts xml dom nodes and caches the result" }
247852
<p>Below I have enum representing State of a UITableView. The states are divided into 3 categories as below.</p> <p>For all the 3 states I have different UITableViewCells which will be shown for respected cases.</p> <p>So for fetchMovies input, I am actually checking the movies count and emitting the state &amp; once again after the result.</p> <p>Can the code written in <code>transform</code> be further reduced or any suggestions.</p> <p>You can find the architecture here <a href="https://github.com/sergdort/CleanArchitectureRxSwift" rel="nofollow noreferrer">CleanArchitectureRxSwift</a></p> <pre class="lang-swift prettyprint-override"><code>import Foundation import RxSwift import RxCocoa protocol ViewModelType { associatedtype Input associatedtype Output func transform(input: Input) -&gt; Output } enum MoviesViewModelState { case loading case loaded([String]) case loadRemaining } class MoviesViewModel: ViewModelType { deinit { print(&quot;HomeViewModel deinit&quot;) } struct Input { let fetchMovies: Driver&lt;Void&gt; } struct Output { let movieSection: Driver&lt;MoviesViewModelState&gt; } var repository: SyncRepository private var names: [String] = [] private let disposeBag = DisposeBag() init(repository: SyncRepository) { self.repository = repository } func transform(input: Input) -&gt; Output { let movieSection = PublishSubject&lt;MoviesViewModelState&gt;() input.fetchMovies .asObservable() .flatMapLatest { [unowned self] _ -&gt; Observable&lt;[String]&gt; in if self.names.count &gt; 0 { movieSection.onNext(.loadRemaining) } else { movieSection.onNext(.loading) } return self.repository.fetchNames(for: self.names.count) // returns Observable&lt;[String]&gt; }.subscribe(onNext: { [unowned self] (names: [String]) in self.names.append(contentsOf: names) movieSection.onNext(.loaded(self.names)) }).disposed(by: disposeBag) return Output(movieSection: movieSection.asDriverOnErrorJustComplete()) } } extension ObservableType { func asDriverOnErrorJustComplete() -&gt; Driver&lt;Element&gt; { return asDriver { _ in return Driver.empty() } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-12T02:24:44.587", "Id": "496265", "Score": "0", "body": "I'm not a big fan of the architecture. It's a lot of boilerplate just to implement a single function." } ]
[ { "body": "<p>Well, the fact that the result of the network request is needed in the next network request means you have a cycle which mean you have to have a subject of some sort. Also, you have to maintain state which implies a <code>BahviorSubject</code> rather than a <code>PublishSubject</code>.</p>\n<p>That said, whenever you have an <code>onNext</code> inside a <code>subscribe</code>, there is likely a cleaner way.</p>\n<pre><code>class MoviesViewModel: ViewModelType {\n\n struct Input {\n let fetchMovies: Observable&lt;Void&gt;\n }\n\n struct Output {\n let movieSection: Driver&lt;MoviesViewModelState&gt;\n }\n\n private let repository: SyncRepository\n private let disposeBag = DisposeBag()\n\n init(repository: SyncRepository) {\n self.repository = repository\n }\n\n func transform(input: Input) -&gt; Output {\n let state = BehaviorSubject&lt;[String]&gt;(value: [])\n\n let movies = input.fetchMovies\n .withLatestFrom(state)\n .share(replay: 1)\n\n movies\n .map { $0.count }\n .flatMap { [repository] in repository.fetchNames(for: $0) }\n .withLatestFrom(state) { $1 + $0 }\n .bind(to: state)\n .disposed(by: disposeBag)\n\n return Output(\n movieSection: Observable.merge(\n movies.map { $0.count == 0 ? .loading : .loadRemaining },\n state.map(MoviesViewModelState.loaded)\n ).asDriverOnErrorJustComplete()\n )\n }\n}\n</code></pre>\n<p>One of the interesting things to note is that the BahviorSubject does <em>not</em> need to be a property of the class. The <code>bind</code> will capture the subject for you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-12T02:23:32.367", "Id": "251986", "ParentId": "247854", "Score": "1" } } ]
{ "AcceptedAnswerId": "251986", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T12:29:07.257", "Id": "247854", "Score": "3", "Tags": [ "rx-swift" ], "Title": "Emitting multiple States for Single Input using ViewModelType architecture" }
247854
<p>I finished a sorting algorithm visualizer (for now only uses bubble sort) and this is the code. I'd like some suggestions to improve the memory usage or time elapsed. Built with Cmake and Ninja on Windows</p> <h1>Demonstration</h1> <p><img src="https://i.stack.imgur.com/i3n7g.gif" alt="Demonstration" /></p> <h1>main.cpp</h1> <pre><code>#include &quot;Engine.h&quot; #undef main int main() { try { // if the amount is higher than the screen width it draws nothing other than a black screen :^) SortVis::Engine Visualization({ 1024, 768 }, 1024); Visualization.Run(); } catch (std::runtime_error&amp; Error) { std::cerr &lt;&lt; Error.what() &lt;&lt; &quot;\n&quot;; } } </code></pre> <h1>Engine.h</h1> <pre><code>#pragma once #include &quot;Coord.h&quot; #include &lt;SDL.h&gt; #include &lt;vector&gt; #include &lt;iostream&gt; namespace SortVis { class Engine { public: Engine() = delete; Engine(Coord pWindowSize, int pMaxNumber); Engine(Coord pWindowSize, const char* pPathToNumbersFile); Engine(Coord pWindowSize, const char* pPathToNumbersFile, const char* pWindowTitle); Engine(Coord pWindowSize, int pMaxNumber, const char* pWindowTitle); ~Engine(); void Run(); private: const Coord m_WindowSize; SDL_Window* m_Window = nullptr; SDL_Renderer* m_Renderer = nullptr; std::vector&lt;int&gt; m_Numbers = { }; int m_ColumnWidth = 0; int m_MaxValue = 0; bool m_Running = true; bool m_Sorted = false; void InitWindow(Coord pWindowSize, const char* pWindowTitle); void InitRenderer(); void CalculateNumbers(); void LoadFile(const char* pPathToNumbersFile); void HandleEvents(); void BubbleSort(); void Draw(); void DrawColumns(); void GenerateRandom(int pMaxNumber); }; } </code></pre> <h1>Engine.cpp</h1> <pre><code>#include &quot;Engine.h&quot; #include &lt;filesystem&gt; #include &lt;fstream&gt; #include &lt;random&gt; #include &lt;utility&gt; #include &lt;algorithm&gt; #include &lt;string&gt; SortVis::Engine::Engine(Coord pWindowSize, int pMaxNumber) : m_WindowSize(pWindowSize) { GenerateRandom(pMaxNumber); CalculateNumbers(); if (SDL_InitSubSystem(SDL_INIT_VIDEO) &lt; 0) { throw std::runtime_error(&quot;Could not initialize SDL&quot;); } InitWindow(pWindowSize, &quot;Sort visualizer&quot;); InitRenderer(); } SortVis::Engine::Engine(Coord pWindowSize, int pMaxNumber, const char* pWindowTitle) : m_WindowSize(pWindowSize) { GenerateRandom(pMaxNumber); CalculateNumbers(); if (SDL_InitSubSystem(SDL_INIT_VIDEO) &lt; 0) { throw std::runtime_error(&quot;Could not initialize SDL&quot;); } InitWindow(pWindowSize, &quot;Sort visualizer&quot;); InitRenderer(); } SortVis::Engine::Engine(Coord pWindowSize, const char* pPathToNumbersFile) : m_WindowSize(pWindowSize) { if (!std::filesystem::exists(pPathToNumbersFile)) { throw std::runtime_error(&quot;That file does not exist. Make sure the path is correct.&quot;); } else { LoadFile(pPathToNumbersFile); } CalculateNumbers(); if (SDL_InitSubSystem(SDL_INIT_VIDEO) &lt; 0) { throw std::runtime_error(&quot;Could not initialize SDL&quot;); } InitWindow(pWindowSize, &quot;Sort visualizer&quot;); InitRenderer(); } SortVis::Engine::Engine(Coord pWindowSize, const char* pPathToNumbersFile, const char* pWindowTitle) : m_WindowSize(pWindowSize) { if (!std::filesystem::exists(pPathToNumbersFile)) { throw std::runtime_error(&quot;That file does not exist. Make sure the path is correct.&quot;); } else { LoadFile(pPathToNumbersFile); } CalculateNumbers(); if (SDL_InitSubSystem(SDL_INIT_VIDEO) &lt; 0) { throw std::runtime_error(&quot;Could not initialize SDL&quot;); } InitWindow(pWindowSize, pWindowTitle); InitRenderer(); } SortVis::Engine::~Engine() { SDL_DestroyWindow(m_Window); SDL_DestroyRenderer(m_Renderer); SDL_Quit(); } void SortVis::Engine::Run() { // Sets render draw color to black SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 255); Draw(); while (m_Running) { HandleEvents(); if (!m_Sorted) { BubbleSort(); } } } void SortVis::Engine::BubbleSort() { for (int i = 0, Size = m_Numbers.size(); i &lt; Size - 1; ++i) { for (int j = 0; j &lt; Size - i - 1; ++j) { HandleEvents(); if (!m_Running) { return; } if (m_Numbers[j] &gt; m_Numbers[j + 1]) { std::swap(m_Numbers[j], m_Numbers[j + 1]); } } Draw(); } m_Sorted = true; } void SortVis::Engine::Draw() { SDL_RenderClear(m_Renderer); DrawColumns(); SDL_RenderPresent(m_Renderer); } void SortVis::Engine::DrawColumns() { SDL_SetRenderDrawColor(m_Renderer, 255, 255, 255, 255); SDL_Rect Column; for (int i = 0, Size = m_Numbers.size(); i &lt; Size; ++i) { Column.x = i * m_ColumnWidth; Column.w = m_ColumnWidth; Column.h = (m_Numbers[i] * m_WindowSize.Y) / m_MaxValue; Column.y = m_WindowSize.Y - Column.h; SDL_RenderFillRect(m_Renderer, &amp;Column); } SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 255); } void SortVis::Engine::HandleEvents() { SDL_Event Event; while (SDL_PollEvent(&amp;Event)) { switch (Event.type) { case SDL_QUIT: m_Running = false; break; } } } void SortVis::Engine::GenerateRandom(int pMaxNumber) { std::mt19937 Seed(std::random_device{}()); std::uniform_int_distribution&lt;int&gt; Distribution(1, pMaxNumber); for (int i = 0; i &lt; pMaxNumber; ++i) { int Number = Distribution(Seed); while (std::count(m_Numbers.begin(), m_Numbers.end(), Number) != 0) { Number = Distribution(Seed); } m_Numbers.push_back(Number); } std::cout &lt;&lt; &quot;Generated random number sequence.\n&quot;; } void SortVis::Engine::CalculateNumbers() { m_ColumnWidth = m_WindowSize.X / m_Numbers.size(); m_MaxValue = *std::max_element(m_Numbers.begin(), m_Numbers.end()); } void SortVis::Engine::LoadFile(const char* pPathToNumbersFile) { std::ifstream NumbersFile(pPathToNumbersFile); if (NumbersFile.is_open()) { std::string Number; while (std::getline(NumbersFile, Number)) { m_Numbers.push_back(std::stoi(Number)); } } else { throw std::runtime_error(&quot;Couldn't open numbers file.&quot;); } if (m_Numbers.empty()) { throw std::runtime_error(&quot;Numbers file is empty.&quot;); } std::cout &lt;&lt; &quot;Loaded numbers file.\n&quot;; } void SortVis::Engine::InitWindow(Coord pWindowSize, const char* pWindowTitle) { m_Window = SDL_CreateWindow( pWindowTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, pWindowSize.X, pWindowSize.Y, SDL_WINDOW_SHOWN ); if (m_Window == nullptr) { throw std::runtime_error(&quot;Could not initialize SDL window&quot;); } } void SortVis::Engine::InitRenderer() { m_Renderer = SDL_CreateRenderer( m_Window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED ); if (m_Renderer == nullptr) { throw std::runtime_error(&quot;Could not initialize SDL renderer&quot;); } } </code></pre> <h1>Coord.h</h1> <pre><code>#pragma once namespace SortVis { struct Coord { int X; int Y; }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:52:30.603", "Id": "485416", "Score": "4", "body": "Note on the demonstration: The actual program runs a lot faster (10s to sort on a VM), however, my screen recording in the VM was a little bit sluggish and I accidentally didn't use the correct speed-up factor to fix the issue in post-processing. That being said you should probably add how you compiled your application, given that it uses both SDL2 as well as C++17. That eases simple tests for reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:32:37.300", "Id": "485424", "Score": "0", "body": "I added the way i built the executable. If you want to know the build options i passed tell me and i'll also post my CMakeLists.txt file" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:34:38.217", "Id": "485425", "Score": "2", "body": "@Zeta No worries, the demo actually looks a lot better this way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T00:13:21.303", "Id": "485458", "Score": "2", "body": "It'd be cool to see this on GitHub with the build system in place. I'd like to try it out with any advice from the reviews implemented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T08:08:32.717", "Id": "485474", "Score": "0", "body": "https://github.com/Nadpher/SortVisualization here is the github, if you want the newer version with the improvements from the answers you'll have to clone the dev branch" } ]
[ { "body": "<p>In all, this is a nice program. In particular, it compiled and ran (almost) flawlessly on Linux, so keep up the good work on portability! Here are some things that may help you improve your program.</p>\n<h2>Fix the bug</h2>\n<p>It's a subtle bug, but there is a problem with the <code>Engine</code> class. The destructor is this:</p>\n<pre><code>SortVis::Engine::~Engine()\n{\n SDL_DestroyWindow(m_Window);\n SDL_DestroyRenderer(m_Renderer);\n\n SDL_Quit();\n}\n</code></pre>\n<p>However, <code>m_Renderer</code> contains a reference to <code>m_Window</code> as we can see from this part of <code>InitRenderer()</code>:</p>\n<pre><code>m_Renderer = SDL_CreateRenderer(\n m_Window,\n -1,\n SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED\n);\n</code></pre>\n<p>For that reason, the <code>SDL_DestroyRenderer()</code> call must come <em>first</em>.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef ENGINE_H\n#define ENGINE_H\n// file contents go here\n#endif // ENGINE_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Reconsider your naming convention</h2>\n<p>One common convention is the use uppercase for all classes and structures and lowercase for instances or individual variable names. This code seems to use uppercase for everything. Also, the partial use of &quot;Hungarian notation&quot; here is not recommended. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl5-avoid-encoding-type-information-in-names\" rel=\"nofollow noreferrer\">NL.5</a> for details.</p>\n<h2>Separate algorithm and user I/O</h2>\n<p>The question notes that only <code>BubbleSort</code> is currently implemented, but it's clear your intent is to add other algorithms. For that reason, I'd suggest refactoring the <code>Engine</code> class so that instead of having the algorithm and the display and user I/O handing all contained within a <code>BubbleSort</code> member function, I would suggest rewriting so that <code>Engine</code> would repeatedly call a <code>step</code> function that would advance one step in a sorting algorithm. That function would be solely concerned with the actual sorting mechanics, while the <code>Engine</code> would take care of all of the user I/O.</p>\n<h2>Simplify <code>for</code> loops by counting down</h2>\n<p>The code currently has this loop in <code>DrawColumns()</code>:</p>\n<pre><code>for (int i = 0, Size = m_Numbers.size(); i &lt; Size; ++i)\n{\n Column.x = i * m_ColumnWidth;\n // etc.\n}\n</code></pre>\n<p>However, this is an instance in which we don't really care whether we're counting up or down as long as all columns are displayed. With that in mind, I'd suggest writing it like this:</p>\n<pre><code>for (int i = m_Numbers.size(); i; --i)\n{\n Column.x = (i-1) * m_ColumnWidth;\n // etc.\n}\n</code></pre>\n<p>As @Useless suggested in a comment, it's not too pretty to have to subtract 1 from <code>i</code> within the loop to use it.</p>\n<p>Better would be the next suggestion.</p>\n<h2>Simplify using a range-<code>for</code></h2>\n<p>The same code loop can be simplified a bit further.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void SortVis::Engine::DrawColumns()\n{\n SDL_SetRenderDrawColor(m_Renderer, 255, 255, 255, 255);\n\n SDL_Rect Column{ 0, 0, m_ColumnWidth, 0};\n for (const auto n : m_Numbers)\n {\n Column.h = n * m_WindowSize.Y / m_MaxValue;\n // uncomment this to make the picture identical to the original\n // Column.y = m_WindowSize.Y - Column.h;\n SDL_RenderFillRect(m_Renderer, &amp;Column);\n Column.x += m_ColumnWidth;\n }\n\n SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 255);\n}\n</code></pre>\n<p>This version inverts the picture so that the bars are anchored to the bottom instead of the top of the image. If you prefer it as it was originally done, just uncomment the code line.</p>\n<h2>Simplify by better using standard algorithms</h2>\n<p>The <code>GenerateRandom</code> code is a lot more complex than it needs to be. You could write it like this:</p>\n<pre><code>void SortVis::Engine::GenerateRandom(int pMaxNumber)\n{\n static std::mt19937 rng(std::random_device{}());\n std::vector&lt;int&gt; num(pMaxNumber);\n std::iota(num.begin(), num.end(), 0);\n std::shuffle(num.begin(), num.end(), rng);\n std::swap(num, m_Numbers);\n}\n</code></pre>\n<p>An alternative approach that I like even better is this:</p>\n<pre><code>static std::vector&lt;int&gt; generateRandom(int pMaxNumber)\n{\n static std::mt19937 rng(std::random_device{}());\n std::vector&lt;int&gt; num(pMaxNumber);\n std::iota(num.begin(), num.end(), 0);\n std::shuffle(num.begin(), num.end(), rng);\n return num;\n}\n</code></pre>\n<p>Now we can simplify the constructor for <code>Engine</code>. Instead of this:</p>\n<pre><code>SortVis::Engine::Engine(Coord pWindowSize, int pMaxNumber)\n : m_WindowSize(pWindowSize)\n{\n GenerateRandom(pMaxNumber);\n // etc.\n}\n</code></pre>\n<p>Write this:</p>\n<pre><code>SortVis::Engine::Engine(Coord pWindowSize, int pMaxNumber)\n : m_WindowSize(pWindowSize),\n m_Numbers{generateRandom(pMaxNumber)}\n{\n // etc.\n}\n</code></pre>\n<h2>Don't ignore passed variables</h2>\n<p>The only difference between the two constructors for <code>Engine</code> is that one of them allows the user to passed a window title, which is then ignored! Better would be to use just the version the allows the window title and then set a default value for it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T00:44:33.457", "Id": "485459", "Score": "3", "body": "Note that looping upwards is common and quicker for many people to read and be 100% sure of the loop bounds. Also, if you're indexing any arrays, hardware prefetch may work at least slightly better when looping forwarding (increasing addresses). e.g. in Intel CPUs, the main L2 streamer can handle either direction, but one of the other prefetchers (perhaps L1d IIRC) doesn't work as well with decreasing addresses. (OTOH, if you just looped upward in one loop, the end of the array will be hot in cache so looping backwards in the next pass over the array can be good, if you don't cache-block it)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T01:17:29.223", "Id": "485460", "Score": "3", "body": "@PeterCordes I usually value clarity over performance and then find I am often pleased to find that what is clear to me also runs faster. It's good to note that which is faster is often hardware-dependent; which is clearer is often less so. Measuring is always good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T14:31:11.397", "Id": "485504", "Score": "1", "body": "I'm not a fan of using the wrong value for a loop counter and having to subtract one: it's easy to add a usage of `i` instead of `i-1` by mistake. `for (int i = m_Numbers.size(); i--; )` makes the body simpler, but the loop condition itself feels more brittle (it's easy not to notice the post-decrement). I'm not sure either is an improvement over the original." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T15:22:25.527", "Id": "485511", "Score": "0", "body": "@Useless: I agree that's a good suggestion. What I actually did in my own refactor was to initialize the `SD_Rect` outside the loop and then adjust it within the loop since `Column.w` and `Column.y` are loop invariant in my version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T15:30:11.943", "Id": "485515", "Score": "0", "body": "@Useless Why exactly would you misread i-- for --i ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T16:36:35.353", "Id": "485524", "Score": "0", "body": "I didn't suggest anyone would misread a post- as a pre-increment, but someone could easily not notice that the condition mutates the loop counter (since it's unusual). The whole thing just requires a little more effort to read correctly than a standard `for` loop." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:03:27.760", "Id": "247870", "ParentId": "247856", "Score": "14" } } ]
{ "AcceptedAnswerId": "247870", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:28:08.120", "Id": "247856", "Score": "19", "Tags": [ "c++", "sorting", "data-visualization", "sdl" ], "Title": "Sorting algorithm visualizer in C++ and SDL2" }
247856
<p>I am working with a dataframe of over 21M rows.</p> <pre><code>df.head() +---+-----------+-------+--------------+-----------+----------------+------------+ | | id | speed | acceleration | jerk | bearing_change | travelmode | +---+-----------+-------+--------------+-----------+----------------+------------+ | 0 | 533815001 | 17.63 | 0.000000 | -0.000714 | 209.028008 | 3 | | 1 | 533815001 | 17.63 | -0.092872 | 0.007090 | 56.116237 | 3 | | 2 | 533815001 | 0.17 | 1.240000 | -2.040000 | 108.494680 | 3 | | 3 | 533815001 | 1.41 | -0.800000 | 0.510000 | 11.847480 | 3 | | 4 | 533815001 | 0.61 | -0.290000 | 0.150000 | 36.7455703 | 3 | +---+-----------+-------+--------------+-----------+----------------+------------+ df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 21713545 entries, 0 to 21713544 Data columns (total 6 columns): # Column Dtype --- ------ ----- 0 id int64 1 speed float64 2 acceleration float64 3 jerk float64 4 bearing_change float64 5 travelmode int64 dtypes: float64(4), int64(2) memory usage: 994.0 MB </code></pre> <p>I would like to convert this dataframe to a multi-dimensional array. So I write this function to do it:</p> <pre><code>def transform(dataframe, chunk_size=5): grouped = dataframe.groupby('id') # initialize accumulators X, y = np.zeros([0, 1, chunk_size, 4]), np.zeros([0,]) # loop over each group (df[df.id==1] and df[df.id==2]) for _, group in grouped: inputs = group.loc[:, 'speed':'bearing_change'].values label = group.loc[:, 'travelmode'].values[0] # calculate number of splits N = (len(inputs)-1) // chunk_size if N &gt; 0: inputs = np.array_split( inputs, [chunk_size + (chunk_size*i) for i in range(N)]) else: inputs = [inputs] # loop over splits for inpt in inputs: inpt = np.pad( inpt, [(0, chunk_size-len(inpt)),(0, 0)], mode='constant') # add each inputs split to accumulators X = np.concatenate([X, inpt[np.newaxis, np.newaxis]], axis=0) y = np.concatenate([y, label[np.newaxis]], axis=0) return X, y </code></pre> <p>When I attempt converting the above <code>df</code>, the operation takes nearly 2hrs, so I cancelled it.</p> <pre><code>Input, Label = transform(df, 100) </code></pre> <p>Is the there a way I can optimize the code to speed up? I am using Ubuntu 18.04 with 16GB RAM running jupyter notebook.</p> <p><strong>EDIT</strong></p> <p>Expected output (using subset of <code>df</code>):</p> <pre><code>Input, Label = transform(df[:300], 100) Input.shape (3, 1, 100, 4) Input array([[[[ 1.76300000e+01, 0.00000000e+00, -7.14402619e-04, 2.09028008e+02], [ 1.76300000e+01, -9.28723404e-02, 7.08974649e-03, 5.61162369e+01], [ 1.70000000e-01, 1.24000000e+00, -2.04000000e+00, 1.08494680e+02], ..., [ 1.31000000e+00, -5.90000000e-01, 1.16000000e+00, 3.72171697e+01], [ 7.20000000e-01, 5.70000000e-01, -1.28000000e+00, 4.38722198e+01], [ 1.29000000e+00, -7.10000000e-01, 1.30000000e-01, 5.55044975e+01]]], [[[ 5.80000000e-01, -5.80000000e-01, 7.60000000e-01, 6.89803288e+01], [ 0.00000000e+00, 1.80000000e-01, 2.20000000e-01, 1.31199034e+02], [ 1.80000000e-01, 4.00000000e-01, -4.80000000e-01, 1.09246728e+02], ..., [ 5.80000000e-01, 1.70000000e-01, -1.30000000e-01, 2.50337736e+02], [ 7.50000000e-01, 4.00000000e-02, 2.40000000e-01, 1.94073476e+02], [ 7.90000000e-01, 2.80000000e-01, -8.10000000e-01, 1.94731287e+02]]], [[[ 1.07000000e+00, -5.30000000e-01, 6.30000000e-01, 2.02516564e+02], [ 5.40000000e-01, 1.00000000e-01, 2.80000000e-01, 3.74852074e+01], [ 6.40000000e-01, 3.80000000e-01, -7.70000000e-01, 2.56066654e+02], ..., [ 3.90000000e-01, 1.14000000e+00, -7.20000000e-01, 5.72686112e+01], [ 1.53000000e+00, 4.20000000e-01, -4.30000000e-01, 1.62305984e+01], [ 1.95000000e+00, -1.00000000e-02, 1.10000000e-01, 2.43819280e+01]]]]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:51:42.030", "Id": "485392", "Score": "2", "body": "Welcome to Code Review, to increase odds of more detailed answers you could include the `performance` tag to your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:15:12.190", "Id": "485405", "Score": "0", "body": "Welcome to Code Review! Just so we don't have to parse the code to understand the desired output, can you include a sample of your desired output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:26:18.407", "Id": "485406", "Score": "0", "body": "@Dannnno I added the expected output using subset of the dataframe (`df[:300]`) in question edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:50:48.767", "Id": "485427", "Score": "0", "body": "Did you check how much time it takes for the *groupby* operation? If that’s the bottleneck or one of the bottlenecks, you could consider using **VAEX** or **Modin** to speed it up in *pandas*. The rest of your code uses *numpy* and fills in zeroes to make the sizes of groups the same. This could potentially require a lot more memory to store the same information on disk and also on you RAM. You could consider using sparse matrices in that case to keep the memory footprint of the multidimensional array manageable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T17:54:46.367", "Id": "485430", "Score": "0", "body": "What are you trying to achieve by converting the dataframe to this ndarray? Maybe the better solution would be to skip the transformation and work with the dataframe directly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:17:19.447", "Id": "485433", "Score": "0", "body": "@mkrieger1 I want to tranform the dataset into fixed-size segments each of shape `(1,100,4)` then feed the array as input to a convolutional neural net" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T09:39:05.623", "Id": "485477", "Score": "0", "body": "For NN, CNN etc. plz use tensorflow and power of GPUs or maybe Dask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T10:26:29.760", "Id": "485478", "Score": "0", "body": "@VisheshMangla I know, but I have to preprocess the data in a way comfortable with CNN requirements first before feeding it to the network, which is what I am trying to do here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T10:27:51.887", "Id": "485479", "Score": "1", "body": "Have you heard of tensorflow image pipelines? If not try it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T13:29:27.993", "Id": "247857", "Score": "6", "Tags": [ "python", "performance", "python-3.x", "numpy", "pandas" ], "Title": "Code optimisation: Converting dataframe to numpy's ndarray" }
247857
<p>I've implemented an A* with a priority queue. I am not getting any performance issues in this little game that I am making but it would be interesting to know how to improve this.</p> <p>I am doing a few o(n) searches in getNode &amp; isSuccessorValid. I thought about using an unordered map and pointing to each node location but when erasing from the vector, that pointer might not be valid anymore.</p> <p>Thank you in advance.</p> <pre><code> struct PriorityQueueNode { PriorityQueueNode(const glm::ivec2&amp; position, const glm::ivec2&amp; parentPosition, float g, float h); float getF() const; glm::ivec2 position; glm::ivec2 parentPosition; float g; float h; }; const auto nodeCompare = [](const auto&amp; a, const auto&amp; b) -&gt; bool { return b.getF() &lt; a.getF(); }; class PriorityQueue : private std::priority_queue&lt;PriorityQueueNode, std::vector&lt;PriorityQueueNode&gt;, decltype(nodeCompare)&gt; { public: PriorityQueue(size_t maxSize) : priority_queue(nodeCompare), m_maxSize(maxSize), m_addedNodePositions() { c.reserve(maxSize); } size_t getSize() const { assert(c.size() == m_addedNodePositions.size()); return c.size(); } bool isEmpty() const { assert(c.empty() &amp;&amp; m_addedNodePositions.empty() || !c.empty() &amp;&amp; !m_addedNodePositions.empty()); return c.empty(); } bool contains(const glm::ivec2&amp; position) const { return m_addedNodePositions.find(position) != m_addedNodePositions.cend(); } const PriorityQueueNode&amp; getTop() const { assert(!isEmpty()); return top(); } const PriorityQueueNode&amp; getNode(const glm::ivec2&amp; position) const { auto node = std::find_if(c.cbegin(), c.cend(), [&amp;position](const auto&amp; node) -&gt; bool { return node.position == position; }); assert(node != c.end()); return (*node); } bool isSuccessorNodeValid(const PriorityQueueNode&amp; successorNode) const { auto matchingNode = std::find_if(c.cbegin(), c.cend(), [&amp;successorNode](const auto&amp; node) -&gt; bool { return successorNode.position == node.position; }); return matchingNode != c.cend() &amp;&amp; successorNode.getF() &lt; matchingNode-&gt;getF(); } void changeNode(const PriorityQueueNode&amp; newNode) { assert(isSuccessorNodeValid(newNode) &amp;&amp; contains(newNode.position)); eraseNode(newNode.position); add(newNode); } void add(const PriorityQueueNode&amp; node) { assert(!contains(node.position) &amp;&amp; c.size() + 1 &lt;= m_maxSize); push(node); m_addedNodePositions.insert(node.position); } void popTop() { assert(!isEmpty()); auto iter = m_addedNodePositions.find(top().position); assert(iter != m_addedNodePositions.end()); m_addedNodePositions.erase(iter); pop(); } void clear() { c.clear(); m_addedNodePositions.clear(); } private: const size_t m_maxSize; std::unordered_set&lt;glm::ivec2&gt; m_addedNodePositions; void eraseNode(const glm::ivec2&amp; position) { auto node = std::find_if(c.begin(), c.end(), [&amp;position](const auto&amp; node) { return node.position == position; }); assert(node != c.cend()); m_addedNodePositions.erase(position); c.erase(node); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-21T17:27:08.743", "Id": "489471", "Score": "2", "body": "Post your A* algorithm as well to see if there any bottlenecks there. It's not clear how do you use your priority queue. For now i can only see not really performance affecting tweaks like using `set.count` instead of `std::find`. Also it probably won't compile even if glm structs will be in scope, because i can't see any definitions of what `c` is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T13:24:09.993", "Id": "501263", "Score": "0", "body": "As noted by @Sugar the definition of `c` is not included in the question, this makes the code in the question extremely difficult to review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T14:45:27.617", "Id": "247860", "Score": "7", "Tags": [ "c++", "performance", "algorithm", "game" ], "Title": "A* using a Priority Queue" }
247860
<p>I'm trying to build a React Boilerplate Using multiple tools. They are all: React, TypeScript, ESLint, Webpack, Babel, Prettier, VSCode and with Airbnb's code style guide.</p> <p>Actually, this is my first Boilerplate. I don't know if there's a redundant dependency or unnecessary codes inside. Can you please review it? The devDependencies looks so many compared to my previous projects.</p> <p>All I want to do is create a boilerplate that uses the stacks I mentioned above, so that I can use it whenever I want to start a new project. Something like a handmade <code>create-react-app</code>. The content of the App doesn't really matter, as long as it follows the rules, just like <code>create-react-app</code>. I came here to find out the quality of my configurations, since sometimes, those tools are fighting each other and I want know when and why are they fighting again. Just like 1 hour ago, I added the Airbnb style guide and it collided with prettier's indentation. I resolved it using the last 3 eslint rules below, but I don't know if there's any hidden conflict left.</p> <p>Here's the link to my boilerplate: <a href="https://github.com/SnekNOTSnake/react-typescript-boilerplate" rel="nofollow noreferrer">https://github.com/SnekNOTSnake/react-typescript-boilerplate</a></p> <p>And here's my quick <code>.eslintrc.json</code> file:</p> <pre><code>{ &quot;parser&quot;: &quot;@typescript-eslint/parser&quot;, &quot;extends&quot;: [ &quot;plugin:@typescript-eslint/recommended&quot;, // Typescript rules &quot;plugin:prettier/recommended&quot;, // Sets the prettier/prettier rule to &quot;error&quot; &quot;plugin:react/recommended&quot;, // React rules &quot;plugin:react-hooks/recommended&quot;, // React Hooks rules &quot;airbnb-typescript&quot; // Airbnb code stylings ], &quot;parserOptions&quot;: { &quot;ecmaVersion&quot;: 2020, // ES11 New features are enabled! &quot;sourceType&quot;: &quot;module&quot;, // Tell ESLint that everything is a module &quot;project&quot;: &quot;./tsconfig.json&quot; // Location of the Parser config file }, // Runs Prettier as an ESLint rule and reports differences as individual ESLint issues. &quot;plugins&quot;: [&quot;prettier&quot;], &quot;rules&quot;: { &quot;@typescript-eslint/no-var-requires&quot;: &quot;off&quot;, // Off for webpack config files &quot;react/jsx-indent&quot;: [2, &quot;tab&quot;], // Use tabs &quot;@typescript-eslint/indent&quot;: &quot;off&quot;, // Use prettier indentation instead &quot;no-tabs&quot;: &quot;off&quot; // Use tabs } } </code></pre> <p>Another quick <code>package.json</code> file:</p> <pre><code>{ &quot;scripts&quot;: { &quot;build&quot;: &quot;NODE_ENV=production webpack --config webpack.prod.js&quot;, &quot;start&quot;: &quot;webpack-dev-server --open --config webpack.dev.js&quot;, &quot;check-types&quot;: &quot;tsc&quot; }, &quot;dependencies&quot;: { &quot;@hot-loader/react-dom&quot;: &quot;^16.13.0&quot;, &quot;react&quot;: &quot;^16.13.1&quot;, &quot;react-dom&quot;: &quot;^16.13.1&quot; }, &quot;devDependencies&quot;: { &quot;@babel/core&quot;: &quot;^7.11.1&quot;, &quot;@babel/preset-env&quot;: &quot;^7.11.0&quot;, &quot;@babel/preset-react&quot;: &quot;^7.10.4&quot;, &quot;@babel/preset-typescript&quot;: &quot;^7.10.4&quot;, &quot;@types/react&quot;: &quot;^16.9.45&quot;, &quot;@types/react-dom&quot;: &quot;^16.9.8&quot;, &quot;@types/webpack-env&quot;: &quot;^1.15.2&quot;, &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^3.8.0&quot;, &quot;@typescript-eslint/parser&quot;: &quot;^3.8.0&quot;, &quot;babel-loader&quot;: &quot;^8.1.0&quot;, &quot;clean-webpack-plugin&quot;: &quot;^3.0.0&quot;, &quot;css-loader&quot;: &quot;^4.2.1&quot;, &quot;eslint&quot;: &quot;^7.6.0&quot;, &quot;eslint-config-airbnb-typescript&quot;: &quot;^9.0.0&quot;, &quot;eslint-config-prettier&quot;: &quot;^6.11.0&quot;, &quot;eslint-plugin-import&quot;: &quot;^2.22.0&quot;, &quot;eslint-plugin-jsx-a11y&quot;: &quot;^6.3.1&quot;, &quot;eslint-plugin-prettier&quot;: &quot;^3.1.4&quot;, &quot;eslint-plugin-react&quot;: &quot;^7.20.5&quot;, &quot;eslint-plugin-react-hooks&quot;: &quot;^4.0.8&quot;, &quot;file-loader&quot;: &quot;^6.0.0&quot;, &quot;html-loader&quot;: &quot;^1.1.0&quot;, &quot;html-webpack-plugin&quot;: &quot;^4.3.0&quot;, &quot;prettier&quot;: &quot;^2.0.5&quot;, &quot;style-loader&quot;: &quot;^1.2.1&quot;, &quot;typescript&quot;: &quot;^3.9.7&quot;, &quot;webpack&quot;: &quot;^4.44.1&quot;, &quot;webpack-cli&quot;: &quot;^3.3.12&quot;, &quot;webpack-dev-server&quot;: &quot;^3.11.0&quot;, &quot;webpack-merge&quot;: &quot;^5.1.1&quot; }, &quot;engines&quot;: { &quot;node&quot;: &quot;^12.16.3&quot; } } </code></pre> <p>For the sake of completeness: <code>.babelrc.json</code></p> <pre><code>{ &quot;presets&quot;: [ [ &quot;@babel/preset-env&quot;, { &quot;targets&quot;: { &quot;edge&quot;: 17, &quot;firefox&quot;: 60, &quot;chrome&quot;: 67, &quot;safari&quot;: &quot;11.1&quot; }, &quot;corejs&quot;: &quot;3&quot;, &quot;useBuiltIns&quot;: &quot;usage&quot; } ], &quot;@babel/preset-react&quot;, &quot;@babel/preset-typescript&quot; ] } </code></pre> <p><code>tsconfig.json</code></p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;baseUrl&quot;: &quot;.&quot;, &quot;paths&quot;: { &quot;Utils/*&quot;: [&quot;src/utils/*&quot;] }, &quot;allowSyntheticDefaultImports&quot;: true, &quot;noImplicitAny&quot;: true, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;sourceMap&quot;: true, &quot;module&quot;: &quot;esnext&quot;, &quot;target&quot;: &quot;esnext&quot;, &quot;jsx&quot;: &quot;react&quot;, &quot;allowJs&quot;: true, &quot;noEmit&quot;: true, &quot;noImplicitThis&quot;: true, &quot;strictNullChecks&quot;: true, &quot;lib&quot;: [&quot;es6&quot;, &quot;dom&quot;] } } </code></pre> <p><code>.prettier.json</code></p> <pre><code>{ &quot;useTabs&quot;: true, &quot;singleQuote&quot;: true, &quot;trailingComma&quot;: &quot;all&quot;, &quot;semi&quot;: true, &quot;tabWidth&quot;: 2, &quot;endOfLine&quot;: &quot;lf&quot;, &quot;arrowParens&quot;: &quot;avoid&quot;, &quot;bracketSpacing&quot;: true } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:41:21.003", "Id": "485410", "Score": "0", "body": "Maybe you missed the text on the right side when typing your question : \"Your question *must contain code that is already working correctly*, and *the relevant code sections must be embedded in the question*.\" Questions must include the code to be reviewed. Links to code hosted on third-party sites are permissible, but the most relevant excerpts must be embedded in the question itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:46:51.557", "Id": "485412", "Score": "0", "body": "Should I put all of the files inside this question? There's like 12 of them. And I think those two are what I need the most to be reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:51:01.723", "Id": "485414", "Score": "0", "body": "I'm not sure, you're the one asking the question; only include all the files you want to be reviewed, and only those. If the two files you've put in your question are the only ones, then you're fine. You can look at some other questions to have a better idea of what is/isn't acceptable, but in general, more code is better, so don't be afraid to add more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:51:43.920", "Id": "485415", "Score": "0", "body": "Ahh, got it. I'll include all of the config files only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:56:55.263", "Id": "485417", "Score": "0", "body": "Also, I'm not sure what you mean by \"a boilerplate\"; could you expand a little bit on that in your question? Although, if the only thing you want to be reviewed is the number of dependencies and what their potential redundancies may be, it might not be relevant. But I'm not sure how we are supposed to help you modify/remove specific dependencies without actually looking at the code using those dependencies, so it might be a good idea to include said code in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:05:29.807", "Id": "485421", "Score": "1", "body": "All I want to do is create a boilerplate that uses the stacks I mentioned above, so that I can use it whenever I want to start a new project. Something like a handmade `create-react-app`. The content of the App doesn't really matter, as long as it follows the rules, just like `create-react-app`. I came here to find out the quality of my codes, since sometimes, those tools are fighting each other and I want know when and why are they fighting again. Just like 1 hour ago, I added the Airbnb style guide and it collided with prettier's indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:14:08.173", "Id": "485423", "Score": "0", "body": "Ah, I see what you mean. Something like a project template you can start from whenever you want to create a new React project, right? Could you add this info in the question itself, so that people don't need to read the comments?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:36:37.493", "Id": "247863", "Score": "8", "Tags": [ "javascript", "json", "react.js", "typescript", "eslint" ], "Title": "React Typescript Boilerplate" }
247863
<p>Below is an implementation heavily based on climberig's implementation on Leetcode for LeetCode 706. Design HashMap. Just to preface, I am doing this in preparation for an exam.</p> <p>The one below is dynamically sized, so it should increase the size of ListNode[] whenever the condition (keyCount &gt; length * 0.90) has been met.</p> <p>I was initially going to have that condition be (loadFactor &gt; 0.75), but for whatever reason, the runtime seems to increase heavily (at least on LeetCode).</p> <p>My main concern would be whether the hashing and collisions work accurately and spread evenly.</p> <p>Any and all advice to improve the code below would be helpful.</p> <pre><code>import java.lang.Math; class MyHashMap { int length = 10; int keyCount = 0; int loadFactor = keyCount / length; ListNode[] nodes = new ListNode[length]; public void put(int key, int value) { int hashKey = hashFunction(key); if (nodes[hashKey] == null) nodes[hashKey] = new ListNode(-1, -1); ListNode prev = find(nodes[hashKey], key); if (prev.next == null) { keyCount++; prev.next = new ListNode(key, value); } else prev.next.val = value; rehash(); } public int get(int key) { int hashKey = hashFunction(key); if (nodes[hashKey] == null) return -1; ListNode node = find(nodes[hashKey], key); return node.next == null ? -1 : node.next.val; } public void remove(int key) { int hashKey = hashFunction(key); if (nodes[hashKey] == null) return; ListNode prev = find(nodes[hashKey], key); // Key did not exist in the first place if (prev.next == null) return; // Removes the key by setting the previous node to the next node from the key prev.next = prev.next.next; } // Hash Function int hashFunction(int key) { return Integer.hashCode(key) % length;} ListNode find(ListNode bucket, int key) { ListNode node = bucket; ListNode prev = null; while (node != null &amp;&amp; node.key != key) { prev = node; node = node.next; } return prev; } public void rehash() { if (keyCount &gt; length * 0.90) { int oldLength = length; length = length * 2; ListNode[] newNodes = new ListNode[length]; for (int i = 0; i &lt; oldLength; i++) { if (nodes[i] == null) { continue; } ListNode next = nodes[i].next; while (next != null) { int key = next.key; int value = next.val; int hashKey = hashFunction(key); if (newNodes[hashKey] == null) newNodes[hashKey] = new ListNode(-1, -1); ListNode prev = find(newNodes[hashKey], key); if (prev.next == null) { prev.next = new ListNode(key, value); } else { prev.next.val = value; } next = next.next; } } nodes = newNodes; } printHash(); System.out.println(&quot;---------------&quot;); } public void printHash() { for (int i = 0; i &lt; length; i++) { if (nodes[i] == null) { System.out.println(&quot;Bucket Not Found&quot;); continue; } ListNode next = nodes[i].next; while (next != null) { System.out.print(&quot;Bucket Found | Key - &quot; + next.key + &quot; Value - &quot; + next.val + &quot; | &quot;); next = next.next; } System.out.println(); } } // ListNode to handle collisions class ListNode { int key, val; ListNode next; ListNode(int key, int val) { this.key = key; this.val = val; } } public static void main(String[] args) { MyHashMap ht = new MyHashMap(); for (int i = 0; i &lt; 100; i++) { int randomNumber = (int) (Math.random() * 100); ht.put(randomNumber, i); } ht.printHash(); } } </code></pre>
[]
[ { "body": "<p>The behavior seems without design flaws.</p>\n<p>However:</p>\n<ul>\n<li>Using a dummy node in front of the linked list does not really save code.\nInserting in front (LIFO, last-in-first-out) can be used for the code without\ndummy head.</li>\n<li>Rehashing does not need to do a <code>find</code> in the <code>newNodes</code>.</li>\n</ul>\n<p>(I hope you can do a diff.)</p>\n<pre><code>class MyHashMap {\n\n int length = 10;\n int keyCount = 0;\n int loadFactor = keyCount / length;\n\n ListNode[] nodes = new ListNode[length];\n\n public void put(int key, int value) {\n int hashKey = hashFunction(key);\n\n ListNode node = find(nodes[hashKey], key);\n\n if (node == null) {\n keyCount++;\n nodes[hashKey] = new ListNode(key, value, nodes[hashKey]);\n }\n else node.val = value;\n\n rehash();\n }\n\n public int get(int key) {\n int hashKey = hashFunction(key);\n\n //if (nodes[hashKey] == null)\n // return -1;\n\n ListNode node = find(nodes[hashKey], key);\n\n return node == null ? -1 : node.val;\n }\n\n public void remove(int key) {\n int hashKey = hashFunction(key);\n\n nodes[hashKey] = removeFromBucket(nodes[hashKey], key);\n// if (nodes[hashKey] == null) return;\n//\n// ListNode prev = find(nodes[hashKey], key);\n//\n// // Key did not exist in the first place\n// if (prev.next == null) return;\n//\n// // Removes the key by setting the previous node to the next node from the key\n// prev.next = prev.next.next;\n }\n\n // Hash Function\n int hashFunction(int key) { return Integer.hashCode(key) % length;}\n\n\n ListNode removeFromBucket(ListNode bucket, int key) {\n ListNode prev = null;\n ListNode node = bucket;\n while (node != null &amp;&amp; node.key != key) {\n prev = node;\n node = node.next;\n }\n if (node == null) {\n return bucket; // Not found\n }\n if (prev != null) {\n prev.next = node.next;\n return bucket; // Found after head\n }\n // Found at head\n return node.next;\n }\n\n ListNode find(ListNode bucket, int key) {\n ListNode node = bucket;\n while (node != null &amp;&amp; node.key != key) {\n node = node.next;\n }\n return node;\n }\n\n public void rehash() {\n if (keyCount &gt; length * 0.90) {\n int oldLength = length;\n length *= 2;\n ListNode[] newNodes = new ListNode[length];\n\n for (int i = 0; i &lt; oldLength; i++) {\n\n if (nodes[i] == null) {\n continue;\n }\n\n ListNode node = nodes[i];\n\n while (node != null) {\n int key = node.key;\n int value = node.val;\n\n int hashKey = hashFunction(key);\n\n newNodes[hashKey] = new ListNode(key, value, newNodes[hashKey]);\n node = node.next;\n }\n }\n nodes = newNodes;\n }\n\n\n printHash();\n System.out.println(&quot;---------------&quot;);\n }\n\n public void printHash() {\n for (int i = 0; i &lt; length; i++) {\n if (nodes[i] == null) {\n System.out.println(&quot;Bucket Not Found&quot;);\n continue;\n }\n\n ListNode next = nodes[i];\n \n while (next != null) {\n System.out.print(&quot;Bucket Found | Key - &quot; + next.key\n + &quot; Value - &quot; + next.val + &quot; | &quot;);\n next = next.next;\n }\n\n System.out.println();\n\n }\n }\n\n // ListNode to handle collisions\n class ListNode {\n int key, val;\n ListNode next;\n\n ListNode(int key, int val, ListNode next) {\n this.key = key;\n this.val = val;\n this.next = next;\n }\n }\n\n public static void main(String[] args) {\n MyHashMap ht = new MyHashMap();\n for (int i = 0; i &lt; 100; i++) {\n int randomNumber = (int) (Math.random() * 100);\n ht.put(randomNumber, i);\n }\n ht.printHash();\n }\n}\n</code></pre>\n<p>There is an issue with a new length having an integral multiple on rehashing:</p>\n<pre><code> hash keys:\nkeys length=10 length=2*10\n 7 7 7\n 17 7 17\n 27 7 7\n 37 7 17\n</code></pre>\n<p>I find this intellectually irritating, but find no drawbacks.</p>\n<p>The solution would be something like:</p>\n<pre><code> length = 2*length + 3;\n length = 3*length/2;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T08:13:38.323", "Id": "247887", "ParentId": "247864", "Score": "0" } } ]
{ "AcceptedAnswerId": "247887", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T15:45:15.720", "Id": "247864", "Score": "5", "Tags": [ "java", "linked-list", "reinventing-the-wheel", "hash-map" ], "Title": "Dynamic-sized Hash table with Linked List" }
247864
<p>I have created a working VBA script that allows the user to select a workbook and make a values only copy of it without opening it. This is useful for getting data from a workbook that is very slow to open. From here: <a href="https://stackoverflow.com/questions/63398348/how-can-i-copy-the-values-only-from-an-entire-excel-workbook-without-opening-it/">https://stackoverflow.com/questions/63398348/how-can-i-copy-the-values-only-from-an-entire-excel-workbook-without-opening-it/</a></p> <p>I can very quickly make a values only copy of an entire workbook. The result is a fast, lightweight, usable workbook that only contains values from the original workbook.</p> <p>I want to know if there are ways I can/should improve what I have done.</p> <p>I also want to know if there is a simpler way to achieve the same result.</p> <p>Main Sub</p> <pre><code>Public Sub Copy_Workbook_Values_Only() On Error GoTo ErrorHandler Dim intCount As Integer Dim firstSheet As Boolean Dim sheetname As String Dim trimmedname As String Dim db As ADODB.Connection, rs As ADODB.Recordset Set db = New ADODB.Connection Set rs = New ADODB.Recordset Set rsSheet = New ADODB.Recordset Dim wbnew As Workbook ExcelFileFullPath = PickFile() If ExcelFileFullPath = &quot;&quot; Then Exit Sub Dim strcon As String strcon = &quot;Provider=Microsoft.ACE.OLEDB.12.0;&quot; &amp; &quot;Data Source=&quot; &amp; ExcelFileFullPath &amp; &quot;;Extended Properties=&quot;&quot;Excel 12.0 Xml;HDR=NO;&quot;&quot;&quot; db.Open (strcon) Set wbnew = Workbooks.Add(xlWBATWorksheet) 'should make just one sheet in new workbook firstSheet = True Set rs = db.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, &quot;Table&quot;)) Do While Not rs.EOF sheetname = rs!TABLE_NAME 'must be a better way to get only sheets 'ADO filter does not support &quot;ends with&quot; 'I would like a way to either return only sheets (no named ranges) or filter for the same 'currently just check to see if last character is a $ If IsNotWorksheet(sheetname) Then GoTo NextIteration 'get rid of any illegal or extra characters added to worksheet name trimmedname = Sanitize_Worksheet_Name(sheetname) If firstSheet Then Set currentSheet = wbnew.Sheets(1) firstSheet = False Else If WorksheetExists(trimmedname) Then GoTo NextIteration 'skip if name somehow already exists Set currentSheet = wbnew.Sheets.Add(After:=ActiveSheet) End If currentSheet.name = trimmedname 'get data and write to worksheet SQLCompound = &quot;SELECT * FROM [&quot; &amp; sheetname &amp; &quot;]&quot; rsSheet.Open SQLCompound, db, adOpenStatic, adLockReadOnly, adCmdText currentSheet.Range(&quot;a1&quot;).CopyFromRecordset rsSheet rsSheet.Close NextIteration: rs.MoveNext Loop rs.Close db.Close Exit Sub ErrorHandler: If Not db Is Nothing Then If db.State = adStateOpen Then db.Close End If Set db = Nothing If Err &lt;&gt; 0 Then MsgBox Err.Source &amp; &quot;--&gt;&quot; &amp; Err.Description, , &quot;Error&quot; End If End Sub </code></pre> <p>Helper Functions:</p> <pre><code>Private Function PickFile() As String ' Create and set the file dialog object. Dim fd As Office.FileDialog Set fd = Application.FileDialog(msoFileDialogFilePicker) Set objSFolders = CreateObject(&quot;WScript.Shell&quot;).SpecialFolders With fd .Filters.Clear ' Clear all the filters (if applied before). ' Give the dialog box a title, word for doc or Excel for excel files. .Title = &quot;Select an Excel File&quot; ' Apply filter to show only a particular type of files. .Filters.Add &quot;Excel Files&quot;, &quot;*.xls;*.xlsx;*.xlsm&quot;, 1 .Filters.Add &quot;All Excel Files&quot;, &quot;*.xlsx;*.xlsm;*.xlsb;*.xltx;*.xltm;*.xls;*.xlt;*.xls;*.xml;*.xml;*.xlam;*.xla;*.xlw;*.xlr&quot;, 2 .Filters.Add &quot;All Files&quot;, &quot;*.*&quot;, 3 ' Do not allow users to select more than one file. .AllowMultiSelect = False .InitialFileName = objSFolders(&quot;mydocuments&quot;) ' Show the file. If .Show = True Then PickFile = .SelectedItems(1) ' Get the complete file path. End If End With End Function </code></pre> <pre><code>Private Function Sanitize_Worksheet_Name(sheetname As String) As String result = sheetname If Left(result, 1) = Chr(39) And Right(result, 1) = Chr(39) Then 'name has been wrapped in single quotes result = Mid(result, 2, Len(result) - 2) End If If Right(result, 1) = &quot;$&quot; Then 'remove trailing $ result = Left(result, Len(result) - 1) End If 'Sheet tab names cannot contain the characters /, \, [, ], *, ?, or :. Dim IllegalCharacter(1 To 7) As String, i As Integer IllegalCharacter(1) = &quot;/&quot; IllegalCharacter(2) = &quot;\&quot; IllegalCharacter(3) = &quot;[&quot; IllegalCharacter(4) = &quot;]&quot; IllegalCharacter(5) = &quot;*&quot; IllegalCharacter(7) = &quot;:&quot; For i = 1 To 7 result = Replace(result, IllegalCharacter(i), &quot;&quot;) Next i result = Left(result, 31) 'no more than 31 chars Sanitize_Worksheet_Name = result End Function </code></pre> <pre><code>Private Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean Dim sht As Worksheet If wb Is Nothing Then Set wb = ThisWorkbook On Error Resume Next Set sht = wb.Sheets(shtName) On Error GoTo 0 WorksheetExists = Not sht Is Nothing End Function </code></pre> <pre><code>'probably a better way for checking for this 'sheetnames from database end in $, but may have a trailing quote after 'tables/named ranges cannot have $ in their name in excel 'tables/named ranges will only have an interior $ -- after the sheetname, but before the range name Private Function IsNotWorksheet(sheetname As String) As Boolean i = 0 If Right(sheetname, 1) = Chr(39) Then i = 1 'ignore trailing single quote If Mid(sheetname, Len(sheetname) - i, 1) &lt;&gt; &quot;$&quot; Then 'not a sheet IsNotWorksheet = True Else IsNotWorksheet = False End If End Function </code></pre> <p>Here is a link to the pertinent post about not being able to use an &quot;ends with&quot; filter: <a href="https://stackoverflow.com/questions/55632420/vba-recordset-filter-wildcard-ending-with-not-working-error-3001">https://stackoverflow.com/questions/55632420/vba-recordset-filter-wildcard-ending-with-not-working-error-3001</a></p>
[]
[ { "body": "<p>I was able to greatly simplify the code using <code>ADOX.Catalog</code> to pull sheets instead of trying to figure out what is or is not a sheet. I also added code that will allow you to open any type of Excel file and always have the correct SQL connection string.</p>\n<p>I have some general notes here for you:</p>\n<ul>\n<li>Use RubberDuck to format your code and help you review</li>\n<li>Never use underscore &quot;_&quot; in procedure name because those are reserved for VBA events.</li>\n<li>Only one declaration per <code>Dim</code></li>\n<li>Use Late-bound objects for code portablility</li>\n<li>Use <code>Option Explicit</code> to force you to declare all your variables</li>\n<li>Don't use <code>Goto</code> when you can use <code>If</code></li>\n</ul>\n<p>Here is my version of the code:</p>\n<pre><code>Option Explicit\n\n' Set all external enums for late bound compatibility\nConst adOpenStatic As Long = 3\nConst adLockReadOnly As Long = 1\nConst adCmdText As Long = 1\nConst adStateOpen As Long = 1\n\nPublic Sub CopyWorkbookValuesOnly()\n ' Handle requirements first\n Dim excelFileFullPath As String\n excelFileFullPath = PickFile\n \n If excelFileFullPath = vbNullString Then Exit Sub\n \n On Error GoTo ErrorHandler\n\n Dim excelDB As Object\n Set excelDB = CreateObject(&quot;ADODB.Connection&quot;)\n excelDB.Open GetConnectionString(excelFileFullPath)\n \n Dim wbnew As Workbook\n Set wbnew = Workbooks.Add(xlWBATWorksheet) 'should make just one sheet in new workbook\n\n ' Get all the Sheets\n Dim sheetTabs As Object\n With CreateObject(&quot;ADOX.Catalog&quot;)\n .ActiveConnection = excelDB\n Set sheetTabs = .Tables\n End With\n \n Dim firstSheet As Boolean\n firstSheet = True\n Dim tableSheet As Object\n For Each tableSheet In sheetTabs\n Dim trimmedname As String\n If Left$(tableSheet.Name, 1) = Chr$(39) And Right$(tableSheet.Name, 1) = Chr$(39) Then ' the name has been wrapped in single quotes\n trimmedname = Mid$(tableSheet.Name, 2, Len(tableSheet.Name) - 2)\n Else ' start with just the name\n trimmedname = tableSheet.Name\n End If\n \n If Right$(trimmedname, 1) = &quot;$&quot; Then\n trimmedname = SanitizeWorksheetName(trimmedname)\n Dim currentSheet As Worksheet\n If firstSheet Then\n Set currentSheet = wbnew.Sheets(1)\n firstSheet = False\n Else\n Set currentSheet = wbnew.Sheets.Add(After:=ActiveSheet)\n End If\n \n currentSheet.Name = trimmedname\n \n 'get data and write to worksheet\n Dim sqlCompound As String\n sqlCompound = &quot;SELECT * FROM [&quot; &amp; tableSheet.Name &amp; &quot;]&quot;\n \n Dim rsSheet As Object\n Set rsSheet = CreateObject(&quot;ADODB.Recordset&quot;)\n rsSheet.Open sqlCompound, excelDB, adOpenStatic, adLockReadOnly, adCmdText\n currentSheet.Range(&quot;A1&quot;).CopyFromRecordset rsSheet\n rsSheet.Close\n Set rsSheet = Nothing\n End If\n Next tableSheet\n \nErrorHandler:\n If Not excelDB Is Nothing Then\n If excelDB.State = adStateOpen Then excelDB.Close\n Set excelDB = Nothing\n End If\n \n If Err.Number &lt;&gt; 0 Then\n MsgBox Err.Source &amp; &quot;Error number: &quot; &amp; Err.Number &amp; &quot;--&gt;&quot; &amp; Err.Description, , &quot;Error&quot;\n End If\nEnd Sub\n\nPrivate Function PickFile() As String\n ' Create and set the file dialog object.\n Dim specialFolder As Object\n Set specialFolder = CreateObject(&quot;WScript.Shell&quot;).SpecialFolders\n \n With Application.FileDialog(msoFileDialogFilePicker)\n .Filters.Clear ' Clear all the filters (if applied before).\n \n ' Give the dialog box a title, word for doc or Excel for excel files.\n .Title = &quot;Select an Excel File&quot;\n \n ' Apply filter to show only a particular type of files.\n .Filters.Add &quot;Excel Files&quot;, &quot;*.xls;*.xlsx;*.xlsm&quot;, 1\n .Filters.Add &quot;All Excel Files&quot;, &quot;*.xlsx;*.xlsm;*.xlsb;*.xltx;*.xltm;*.xls;*.xlt;*.xls;*.xml;*.xml;*.xlam;*.xla;*.xlw;*.xlr&quot;, 2\n .Filters.Add &quot;All Files&quot;, &quot;*.*&quot;, 3\n \n ' Do not allow users to select more than one file.\n .AllowMultiSelect = False\n \n .InitialFileName = specialFolder(&quot;MyDocuments&quot;)\n \n ' Show the file.\n If .Show = True Then\n PickFile = .SelectedItems.Item(1) ' Get the complete file path.\n End If\n End With\nEnd Function\n\nPrivate Function SanitizeWorksheetName(ByVal sheetName As String) As String\n Dim result As String\n result = sheetName\n\n If Right$(result, 1) = &quot;$&quot; Then 'remove trailing $\n result = Left$(result, Len(result) - 1)\n End If\n \n ' Remove illegal characters using RegEx\n Const IllegalCharacters As String = &quot;\\/\\\\\\[\\]\\*:&quot;\n With CreateObject(&quot;VBScript.RegExp&quot;)\n .Global = True\n .Pattern = IllegalCharacters\n result = .Replace(result, vbNullString)\n End With\n \n ' keep only 31 characters\n SanitizeWorksheetName = Left$(result, 31)\nEnd Function\n\nPublic Function GetConnectionString(ByVal fileName As String) As String\n Dim fileExtension As String\n fileExtension = Right$(fileName, Len(fileName) - InStrRev(fileName, &quot;.&quot;))\n Dim provider As String\n provider = &quot;Provider=Microsoft.ACE.OLEDB.12.0;Data Source=&quot;\n Dim connectionString As String\n Select Case fileExtension\n Case &quot;xls&quot;\n connectionString = provider &amp; fileName &amp; &quot;;Extended Properties=&quot;&quot;Excel 8.0;HDR=NO;IMEX=1&quot;&quot;;&quot;\n Case &quot;xlsx&quot;\n connectionString = provider &amp; fileName &amp; &quot;;Extended Properties=&quot;&quot;Excel 12.0 Xml;HDR=NO;IMEX=1&quot;&quot;;&quot;\n Case &quot;xlsb&quot;\n connectionString = provider &amp; fileName &amp; &quot;;Extended Properties=&quot;&quot;Excel 12.0;HDR=NO;IMEX=1&quot;&quot;;&quot;\n Case &quot;xlsm&quot;\n connectionString = provider &amp; fileName &amp; &quot;;Extended Properties=&quot;&quot;Excel 12.0 Macro;HDR=NO;IMEX=1&quot;&quot;;&quot;\n Case Else\n connectionString = &quot;Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=&quot; &amp; fileName &amp; &quot;;&quot;\n End Select\n \n GetConnectionString = connectionString\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:37:49.560", "Id": "485436", "Score": "0", "body": "This code chokes on my original use case - a spreadsheet with (thousands?) of named ranges. It makes a tab for each of the named ranges, not just each of the sheets. Also, if the original workbook contains a Sheet1 it errors out as the new workbook already has a sheet1 and cannot make another by the same name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:38:20.787", "Id": "485437", "Score": "0", "body": "However, I did really appreciate your feedback overall and will incorporate what I can." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:40:12.723", "Id": "485439", "Score": "0", "body": "You can only have one sheet named \"Sheet1\" and it does come with one. The name should be set on each pass so you won't ever have a collision. I've tested that much. I need to test the named ranges. I will have to make an example workbook to see what you are talking about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:44:11.003", "Id": "485440", "Score": "0", "body": "Ok, @S.Melted, please try this latest version. It should ignore named ranges as you expect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:54:57.693", "Id": "485441", "Score": "0", "body": "It now snappily goes through the original workbook with thousands of named ranges. However, I made a worksheet with two tabs named \"ab\" and \"12\". It will import \"ab\" but not \"12\" because it wraps 12$ in single quotes for the tableSheet.name making the last character a single quote, not a $." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:56:12.103", "Id": "485442", "Score": "0", "body": "To copy the sheets correctly, we still need to either set HDR=NO, or go and copy the \"header\" rows as well. As is, it chops off the first row." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:58:09.720", "Id": "485443", "Score": "0", "body": "It no longer crashes when given a workbook with an existing \"Sheet1\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T20:15:17.737", "Id": "485448", "Score": "0", "body": "Ok, I have made edits to account for numeric sheet names. I also used `HDR=NO` to avoid stripping the headers." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:18:02.413", "Id": "247872", "ParentId": "247866", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T16:32:20.490", "Id": "247866", "Score": "3", "Tags": [ "vba", "excel", "adodb" ], "Title": "Creating a values only copy of an excel workbook without opening it" }
247866
<p>I've ported the <a href="https://codereview.stackexchange.com/questions/244078/analog-clock-in-aec">Analog Clock program</a> written in AEC from Linux to WebAssembly. You can see the <a href="https://flatassembler.github.io/analogClock.html" rel="nofollow noreferrer">live version</a>.</p> <pre><code>/* * This is my attempt to port the Analog Clock in AEC, previously available * for Linux and DOS, to WebAssembly. */ //Let's import some functions useful for debugging from JavaScript... Function logString(CharacterPointer str) Which Returns Nothing Is External; Function logInteger(Integer32 int) Which Returns Nothing Is External; //Now let's define a character array that will be used both by JS and AEC. Character output[23 * 80]; Integer32 colors[23 * 80]; //Integer32 can be used as pointer to pointer, //for a lack of a more appropriate type in the //current version of AEC. &quot;colors&quot; will point //to the CSS names of the colors of the specific //characters in &quot;output&quot;. Function getAddressOfOutput() Which Returns CharacterPointer Does Return AddressOf(output[0]); //When I didn't implement the &quot;extern&quot; //keyword into my AEC compiler... EndFunction Function getAddressOfColors() Which Returns Integer32Pointer Does Return AddressOf(colors[0]); //AEC doesn't currently support //pointers to pointers, but it's //trivial to cast this to the //correct type in JavaScript. EndFunction //Now, let's implement some mathematical functions. We can't use JavaScript //&quot;Math.sin&quot; and similar because they are methods of the global &quot;Math&quot; //object, and there is, as far as I know, no way to import JavaScript //objects into WebAssembly (or some language that compiles into it). //I wonder whether this is what operating system development feels like. //In the OS development, the only code that's running on a virtual machine //is your own, and you can only use a debugger running outside of that //virtual machine. Here, quite some code runs on JavaScript Virtual Machine, //but the only code I can call is the code I've written myself in my own //programming language and some debugging functions (logString and logInteger). Decimal32 PRECISION := 512; //So that we can balance between speed and //precision. Function ln(Decimal32 x) Which Returns Decimal32 Does //Natural logarithm is the integral of 1/x from 1 to x, highschool math. Decimal32 sum := 0, epsilon := (x - 1) / (5 * PRECISION), i := 1; While (epsilon &gt; 0 and i &lt; x) or (epsilon &lt; 0 and i &gt; x) Loop sum := sum + epsilon / i; i := i + epsilon; EndWhile Return sum; EndFunction Function exp(Decimal32 x) Which Returns Decimal32 Does //Euler's Algorithm from Mathematics 2... Decimal32 i := 0, y := 1, epsilon := x / PRECISION; While (epsilon &gt; 0 and i &lt; x) or (epsilon &lt; 0 and i &gt; x) Loop y := y + epsilon * y; i := i + epsilon; EndWhile Return y; EndFunction Function sqrt(Decimal32 x) Which Returns Decimal32 Does //Binary Search Algorithm... Decimal32 max := 80 * 24, min := 0, i := (min + max) / 2; While (max - min) &gt; 1 / PRECISION Loop If i * i &gt; x Then max := i; Else min := i; EndIf i := (max + min) / 2; EndWhile Return i; EndFunction Function fmod(Decimal32 a, Decimal32 b) Which Returns Decimal32 Does Return a - b * Integer32(a / b); EndFunction //Now, let's implement trigonometric and cyclometric functions. Decimal32 oneRadianInDegrees := 180 / pi; //&quot;180/pi&quot; is a compile-time decimal //constant (since we are assigning an //initial value to a global variable), //and, as such, we can use &quot;pi&quot; to //refer to M_PI from the C library, //it's available to the compiler. Function arctan(Decimal32 x) Which Returns Decimal32 Does //Arcus tangens is equal to the integral of 1/(1+x^2), highschool math. Decimal32 sum := 0, epsilon := x / PRECISION, i := 0; While i &lt; x Loop sum := sum + epsilon / (1 + i * i); i := i + epsilon; EndWhile Return sum * oneRadianInDegrees; EndFunction Function sin(Decimal32 degrees) Which Returns Decimal32 Does If degrees&lt;0 Then Return -sin(-degrees); EndIf If degrees&gt;90 Then Decimal32 sinOfDegreesMinus90 := sin(degrees - 90); If fmod(degrees, 360) &lt; 180 Then Return sqrt(1 - sinOfDegreesMinus90 * sinOfDegreesMinus90); Else Return -sqrt(1 - sinOfDegreesMinus90 * sinOfDegreesMinus90); EndIf EndIf /* * Sine and cosine are defined in Mathematics 2 using the system of * equations (Cauchy system): * * sin(0)=0 * cos(0)=1 * sin'(x)=cos(x) * cos'(x)=-sin(x) * --------------- * * Let's translate that as literally as possible to the programming * language. */ Decimal32 radians := degrees / oneRadianInDegrees, tmpsin := 0, tmpcos := 1, epsilon := radians / PRECISION, i := 0; While (epsilon&gt;0 and i&lt;radians) or (epsilon&lt;0 and i&gt;radians) Loop tmpsin := tmpsin + epsilon * tmpcos; tmpcos := tmpcos - epsilon * tmpsin; i := i + epsilon; EndWhile Return tmpsin; EndFunction Function arcsin(Decimal32 x) Which Returns Decimal32 Does Return arctan(x / sqrt(1 - x * x)); //Highschool mathematics. EndFunction Function arccos(Decimal32 x) Which Returns Decimal32 Does Return 90 - arcsin(x); //Basic common sense to somebody who understands //what those terms mean. EndFunction Function cos(Decimal32 degrees) Which Returns Decimal32 Does Return sin(90 - degrees); //Again, basic common sense to somebody who //understands what those terms means. EndFunction Function tan(Decimal32 degrees) Which Returns Decimal32 Does Return sin(degrees) / cos(degrees); //The definition. EndFunction Function abs(Decimal32 x) Which Returns Decimal32 Does Return x &lt; 0? -x : x; EndFunction //Now, let's implement some string manipulation functions. We can't //call the methods of the JavaScript &quot;String&quot; class here. Function strlen(CharacterPointer ptr) Which Returns Integer32 Does Return ValueAt(ptr) = 0 ? 0 : 1 + strlen(ptr + 1); EndFunction Function strcat(CharacterPointer first, CharacterPointer second) Which Returns Nothing Does first := first + strlen(first); While ValueAt(second) Loop ValueAt(first) := ValueAt(second); first := first + 1; second := second + 1; EndWhile ValueAt(first) := 0; EndFunction //And, finally, we can start porting the original AEC Analog Clock, //which was targeting x86, to WebAssembly. Function updateClockToTime(Integer32 hour, Integer32 minute, Integer32 second) Which Returns Nothing Does Integer32 windowWidth := 80, windowHeight := 23, i := 0; CharacterPointer lightGrayColor := &quot;#EEEEEE&quot;; CharacterPointer lightGreenColor := &quot;#CCFFCC&quot;; While i &lt; windowWidth * windowHeight Loop //First, fill the window with //spaces and newlines. If mod(i, windowWidth) = windowWidth - 1 Then output[i] := '\n'; Else output[i] := ' '; EndIf colors[i] := lightGrayColor; i := i + 1; EndWhile Integer32 centerX := windowWidth / 2, centerY := windowHeight / 2, clockRadius := (centerX &lt; centerY)? centerX - 1 : centerY - 1; i := 0; While i &lt; windowWidth * windowHeight Loop //Next, draw the circle which //represents the clock Integer32 y := i / windowWidth, x := mod(i, windowWidth); Decimal32 distance := sqrt((x - centerX) * (x - centerX) + (y-centerY) * (y-centerY)); //Pythagorean //Theorem. If abs(distance - clockRadius) &lt; 3. / 4 Then output[i] := '*'; colors[i] := lightGreenColor; EndIf i := i + 1; EndWhile CharacterPointer redColor := &quot;#FFAAAA&quot;; //Label &quot;12&quot;... output[(centerY - clockRadius + 1) * windowWidth + centerX] := '1'; output[(centerY - clockRadius + 1) * windowWidth + centerX + 1] := '2'; colors[(centerY - clockRadius + 1) * windowWidth + centerX] := colors[(centerY - clockRadius + 1) * windowWidth + centerX + 1] := redColor; //Label &quot;6&quot;... output[(centerY + clockRadius - 1) * windowWidth + centerX] := '6'; colors[(centerY + clockRadius - 1) * windowWidth + centerX] := redColor; //Label &quot;3&quot;... output[centerY * windowWidth + centerX + clockRadius - 1] := '3'; colors[centerY * windowWidth + centerX + clockRadius - 1] := redColor; //Label &quot;9&quot;... output[centerY * windowWidth + centerX - clockRadius + 1] := '9'; colors[centerY * windowWidth + centerX - clockRadius + 1] := redColor; //Label &quot;1&quot;... Integer32 y := centerY - (clockRadius - 1) * cos(360. / 12); output[y * windowWidth + centerX + sin(360./12) * (clockRadius - 1)] := '1'; colors[y * windowWidth + centerX + sin(360./12) * (clockRadius - 1)] := redColor; //Label &quot;2&quot;... y := centerY - (clockRadius - 1.5) * cos(2 * 360. / 12); output[y * windowWidth + centerX + sin(2 * 360. / 12) * (clockRadius - 1.5)] := '2'; colors[y * windowWidth + centerX + sin(2 * 360. / 12) * (clockRadius - 1.5)] := redColor; //Label &quot;4&quot;... y := centerY - (clockRadius - 1) * cos(4 * 360. / 12); output[y * windowWidth + centerX + sin(4 * 360. / 12) * (clockRadius - 1) + 1] := '4'; colors[y * windowWidth + centerX + sin(4 * 360. / 12) * (clockRadius - 1) + 1] := redColor; //Label &quot;5&quot;... y := centerY - (clockRadius - 1) * cos(5 * 360. / 12); output[y * windowWidth + centerX + sin(5 * 360. / 12) * (clockRadius - 1) + 1] := '5'; colors[y * windowWidth + centerX + sin(5 * 360. / 12) * (clockRadius - 1) + 1] := redColor; //Label &quot;7&quot;... y := centerY - (clockRadius - 1) * cos(7 * 360. / 12); output[y * windowWidth + centerX + sin(7 * 360. / 12) * (clockRadius - 1)] := '7'; colors[y * windowWidth + centerX + sin(7 * 360. / 12) * (clockRadius - 1)] := redColor; //Label &quot;8&quot;... y := centerY - (clockRadius - 1) * cos(8 * 360. / 12); output[y * windowWidth + centerX + sin(8 * 360. / 12) * (clockRadius - 1)] := '8'; colors[y * windowWidth + centerX + sin(8 * 360. / 12) * (clockRadius - 1)] := redColor; //Label &quot;10&quot;... y := centerY - (clockRadius - 1.5) * cos(10 * 360. / 12); output[y * windowWidth + centerX + sin(10 * 360. / 12) * (clockRadius - 1.5) + 1] := '1'; output[y * windowWidth + centerX + sin(10 * 360. / 12) * (clockRadius - 1.5) + 2] := '0'; colors[y * windowWidth + centerX + sin(10 * 360. / 12) * (clockRadius - 1.5) + 1] := colors[y * windowWidth + centerX + sin(10 * 360. / 12) * (clockRadius - 1.5) + 2] := redColor; //Label &quot;11&quot;... y := centerY - (clockRadius - 1.5) * cos(11 * 360. / 12); output[y * windowWidth + centerX + sin(11 * 360. / 12) * (clockRadius - 1.5) + 1] := output[y * windowWidth + centerX + sin(11 * 360. / 12) * (clockRadius - 1.5) + 2] := '1'; colors[y * windowWidth + centerX + sin(11 * 360. / 12) * (clockRadius - 1.5) + 1] := colors[y * windowWidth + centerX + sin(11 * 360. / 12) * (clockRadius - 1.5) + 2] := redColor; Integer32 j := 0; Decimal32 angle; CharacterPointer blueColor := &quot;#AAAAFF&quot;; CharacterPointer yellowColor := &quot;#FFFFAA&quot;; While j &lt; 3 Loop CharacterPointer currentColor; If j = 0 Then angle := fmod(hour + minute / 60., 12) * (360. / 12); currentColor := redColor; ElseIf j = 1 Then angle := minute * (360. / 60); currentColor := yellowColor; Else angle := second * (360 / 60); currentColor := blueColor; EndIf Decimal32 endOfTheHandX := centerX + sin(angle) * clockRadius / (j = 0 ? 2. : j = 1 ? 3. / 2 : 4. / 3), endOfTheHandY := centerY - cos(angle) * clockRadius / (j = 0 ? 2. : j = 1 ? 3. / 2 : 4. / 3), coefficientOfTheDirection := (endOfTheHandY - centerY) / ( abs(endOfTheHandX - centerX) = 0? //Protect ourselves from //dividing by 0. 1. / 100 : endOfTheHandX - centerX ); logString(&quot;Drawing line between (&quot;); logInteger(centerX); logString(&quot;,&quot;); logInteger(centerY); logString(&quot;) and (&quot;); logInteger(endOfTheHandX); logString(&quot;,&quot;); logInteger(endOfTheHandY); logString(&quot;).\n&quot;); i := 0; While i &lt; windowWidth * windowHeight Loop Decimal32 lowerBoundX := endOfTheHandX &lt; centerX ? endOfTheHandX : Decimal32(centerX), upperBoundX := endOfTheHandX &gt; centerX ? endOfTheHandX : Decimal32(centerX), lowerBoundY := endOfTheHandY &lt; centerY ? endOfTheHandY : centerY, upperBoundY := endOfTheHandY &gt; centerY ? endOfTheHandY : centerY; y := i / windowWidth; Integer32 x := mod(i, windowWidth), isXWithinBounds; isXWithinBounds := (x &gt; lowerBoundX or x = lowerBoundX) and (x &lt; upperBoundX or x = upperBoundX); Integer32 isYWithinBounds; isYWithinBounds := (y &gt; lowerBoundY or y = lowerBoundY) and (y &lt; upperBoundY or y = upperBoundY); If isXWithinBounds and isYWithinBounds Then Decimal32 expectedX, expectedY; expectedY := (x - centerX) * coefficientOfTheDirection + centerY; expectedX := (y - centerY) * (1/coefficientOfTheDirection) + centerX; If coefficientOfTheDirection=1./0 Then expectedY := 1000; //Bigger than any possible value. EndIf If coefficientOfTheDirection=0 Then expectedX := 1000; //Again, bigger than any possible. EndIf logString(&quot;The point (&quot;); logInteger(x); logString(&quot;,&quot;); logInteger(y); logString(&quot;) is within bounds, expectedY is &quot;); logInteger(expectedY); logString(&quot; and expectedX is &quot;); logInteger(expectedX); logString(&quot;.\n&quot;); Character currentSign := j = 0 ? 'h' : j = 1 ? 'm' : 's'; If (abs(upperBoundX - lowerBoundX) &lt; 1 + 1 / PRECISION or abs(upperBoundY - lowerBoundY) &lt; 1 + 1 / PRECISION) and output[i] = ' ' Then output[i] := currentSign; colors[i] := currentColor; EndIf If (abs(expectedX - x) &lt; 3./4 or abs(expectedY - y) &lt; 3./4) and output[i] = ' ' Then output[i] := currentSign; colors[i] := currentColor; EndIf EndIf i := i + 1; EndWhile j := j + 1; EndWhile //Let's draw some ornaments. CharacterPointer darkGreenColor := &quot;#AAFFAA&quot;; i := 0; While i &lt; windowWidth * windowHeight Loop y := i / windowWidth; Integer32 x := mod(i, windowWidth); If abs(windowHeight - 2 * ln(1 + abs((x - centerX) / 2.)) - y) &lt; 1 - abs(x - centerX) / (centerX * 95./112) and x &gt; 1./2 * centerX and x &lt; 3./2 * centerX and output[i] = ' ' Then //The logarithmic curve looks somewhat //like a lemma of a flower. output[i] := 'x'; colors[i] := darkGreenColor; EndIf i := i + 1; EndWhile //Let's try to make it look like the bottom of the lemma isn't floating //in the air. j := 0; While j &lt; 3 Loop i := windowWidth * (windowHeight - 1);//So, move to the beginning of //the last line. While i &lt; windowWidth * windowHeight Loop If j &lt; 2 and (output[i - windowWidth] = 'x' and (output[i + 1] = 'x' or output[i - 1] = 'x')) Then output[i] := 'x'; colors[i] := darkGreenColor; ElseIf j=2 and (output[i + 1]=' ' and output[i - windowWidth] = 'x') Then output[i] := ' '; EndIf i := i + 1; EndWhile j := j + 1; EndWhile //The digital clock in the corner... output[windowWidth * windowHeight - 2] := '0' + mod(second, 10); output[windowWidth * windowHeight - 3] := '0' + second / 10; colors[windowWidth * windowHeight - 2] := colors[windowWidth * windowHeight - 3] := blueColor; output[windowWidth * windowHeight - 4] := ':'; output[windowWidth * windowHeight - 5] := '0' + mod(minute, 10); output[windowWidth * windowHeight - 6] := '0' + minute / 10; colors[windowWidth * windowHeight - 5] := colors[windowWidth * windowHeight - 6] := yellowColor; output[windowWidth * windowHeight - 7] := ':'; output[windowWidth * windowHeight - 8] := '0' + mod(hour,10); output[windowWidth * windowHeight - 9] := '0' + hour / 10; colors[windowWidth * windowHeight - 8] := colors[windowWidth * windowHeight - 9] := redColor; //My signature... Character signature[100] := {0}; CharacterPointer signature := AddressOf(signature[0]); //AEC, unlike C, always makes a clear distinction between //arrays and pointers. logString(&quot;Empty signature has length of: &quot;); logInteger(strlen(signature)); logString(&quot;\n&quot;); strcat(signature, &quot; Analog Clock for WebAssembly\n&quot;); logString(&quot;The first row of the signature has length of: &quot;); logInteger(strlen(signature)); logString(&quot;\n&quot;); strcat(signature, &quot; Made in AEC by\n&quot;); logString(&quot;The first two rows of signature have length: &quot;); logInteger(strlen(signature)); logString(&quot;\n&quot;); strcat(signature, &quot; Teo Samarzija&quot;); logString(&quot;Signature has length of: &quot;); logInteger(strlen(signature)); logString(&quot; \n\n&quot;); //Let's mark the last log of this function like this. i := windowWidth * (windowHeight - 3); j := 0; CharacterPointer modraColor := &quot;#AAFFFF&quot;; //Sorry, I don't know how //to say &quot;modra&quot; in English, //and I am not wasting my time //looking that up. While not(signature[j] = 0) Loop If signature[j] = '\n' Then i := (i / windowWidth + 1) * windowWidth; ElseIf not(signature[j] = 0) Then output[i] := signature[j]; colors[i] := modraColor; i := i + 1; Else output[i] := ' '; EndIf j := j + 1; EndWhile EndFunction </code></pre> <p>What do you think about it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:27:27.317", "Id": "485434", "Score": "0", "body": "what is aec? Looking at your linked program, it looks like you haven't read the comments posted which explain why your question wasn't answered" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T17:00:33.767", "Id": "247868", "Score": "2", "Tags": [ "console", "webassembly" ], "Title": "Analog Clock for WebAssembly in AEC" }
247868
<p>I have a constantly growing corpus of currently ~36,000 documents (growing daily) and I want calculate the similarity between each pair of documents. After calculating the similarity scores, I want to filter the results to only include scores above 0.9, and capture the <code>(row label, column label, metric)</code> in a list of tuples that can be written to a CSV file.</p> <p>The process that I currently have works as intended, but as my corpus of documents has continued to grow, I'm now receiving a <code>MemoryError</code> when trying to process my actual dataset.</p> <p>Error generated with my actual dataset:</p> <pre><code>2020-08-10 10:37:08,933 There are 35845 records loaded 2020-08-10 10:37:19,570 Completed pre-processing all documents 2020-08-10 10:38:05,458 Completed calculating similarity Traceback (most recent call last): File &quot;/home/curtis/project/text_similarity.py&quot;, line 97, in &lt;module&gt; scores = get_scores(pairwise_similarity, doc_keys, threshold=0.9) File &quot;/home/curtis/project/text_similarity.py&quot;, line 61, in get_scores arr[np.tril_indices(arr.shape[0], -1)] = np.nan File &quot;/home/curtis/miniconda3/envs/scraper-dev/lib/python3.7/site-packages/numpy/lib/twodim_base.py&quot;, line 868, in tril_indices return nonzero(tri(n, m, k=k, dtype=bool)) File &quot;&lt;__array_function__ internals&gt;&quot;, line 6, in nonzero File &quot;/home/curtis/miniconda3/envs/project-dev/lib/python3.7/site-packages/numpy/core/fromnumeric.py&quot;, line 1896, in nonzero return _wrapfunc(a, 'nonzero') File &quot;/home/curtis/miniconda3/envs/project-dev/lib/python3.7/site-packages/numpy/core/fromnumeric.py&quot;, line 61, in _wrapfunc return bound(*args, **kwds) MemoryError: Unable to allocate 9.57 GiB for an array with shape (642414090, 2) and data type int64 </code></pre> <p>Existing process <code>text_similarity.py</code> with sample data:</p> <pre><code>import csv import logging import os import string import numpy as np from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.datasets import fetch_20newsgroups class clean_document: &quot;&quot;&quot;Class to pre-process documents&quot;&quot;&quot; def __init__(self, input_string, stopwords): self.input_string = input_string self.string_lower = self.lower_string() self.string_no_emoji = self.drop_emoji() self.string_no_punct = self.remove_punction() self.tokens = self.tokenizer() self.tokens_no_stopwords = self.remove_stopwords(stopwords) def lower_string(self): string_lower = self.input_string.lower() return string_lower def drop_emoji(self): &quot;&quot;&quot;Thanks to https://stackoverflow.com/a/49986645&quot;&quot;&quot; no_emoji = self.string_lower.encode(&quot;ascii&quot;, &quot;ignore&quot;).decode(&quot;ascii&quot;) return no_emoji def remove_punction(self): &quot;&quot;&quot;Thanks to https://stackoverflow.com/a/266162&quot;&quot;&quot; no_punct = self.string_no_emoji.translate(str.maketrans(&quot;&quot;, &quot;&quot;, string.punctuation)) return no_punct def tokenizer(self): tokens = word_tokenize(self.string_no_punct) return tokens def remove_stopwords(self, stopwords): no_stopwords = [line for line in self.tokens if line not in stopwords] return no_stopwords def calc_pairwise_similarity(corpus): &quot;&quot;&quot;Thanks to https://stackoverflow.com/a/8897648&quot;&quot;&quot; vect = TfidfVectorizer(min_df=1) tfidf = vect.fit_transform(corpus) pairwise_similarity = tfidf * tfidf.T return pairwise_similarity def get_scores(pairwise_similarity, doc_keys, threshold=0.9): &quot;&quot;&quot;Extract scores into a list-of-tuples&quot;&quot;&quot; arr = pairwise_similarity.toarray() arr[arr &lt;= threshold] = np.nan np.fill_diagonal(arr, np.nan) arr[np.tril_indices(arr.shape[0], -1)] = np.nan idx = (~np.isnan(arr)).nonzero() vals = arr[idx].tolist() keys = list(zip(idx[0].tolist(), idx[1].tolist())) output = [(x[0][0], x[0][1], x[1]) for x in list(zip(keys, vals))] final = [(doc_keys[line[0]], doc_keys[line[1]], line[2]) for line in output] return final # MAIN PROGRAM # set up basic logging logging.basicConfig(format=&quot;%(asctime)s %(message)s&quot;, level=logging.INFO) # load the dataset newsgroups_train = fetch_20newsgroups(subset='train') documents = {i: line for i, line in enumerate(newsgroups_train['data'])} logging.info(f&quot;There are {len(documents)} records loaded&quot;) # define the stop words to use stop_words = set(stopwords.words(&quot;english&quot;)) # process the original strings and create a cleaned corpus corpus = [] for line in documents.values(): x = clean_document(line, stop_words) corpus.append(x.string_no_punct) logging.info(&quot;Completed pre-processing all documents&quot;) # calculate pairwise similaritry pairwise_similarity = calc_pairwise_similarity(corpus) logging.info(&quot;Completed calculating similarity&quot;) # get similiarity metrics doc_keys = list(documents.keys()) scores = get_scores(pairwise_similarity, doc_keys, threshold=0.9) logging.info(&quot;Extracted similarity scores&quot;) # write scores to CSV file with open(&quot;scores.csv&quot;, &quot;w&quot;) as f: writer = csv.writer(f) writer.writerows(scores) logging.info(&quot;Successfully wrote metrics to file&quot;) </code></pre>
[]
[ { "body": "<p>A quick fix to the <code>MemoryError</code> issue is to avoid expanding the sparse similarity matrix into a dense matrix for extracting indices in the <code>get_scores</code> function. Instead, the indices can be extracted by operating directly on the sparse matrix.</p>\n<pre><code>def get_scores(pairwise_similarity, doc_keys, threshold=0.9):\n sim_coo = pairwise_similarity.tocoo(copy=False)\n doc_keys = np.array(doc_keys)\n mask = (sim_coo.data &gt; threshold) &amp; (sim_coo.row &gt; sim_coo.col)\n row_doc_keys = doc_keys[sim_coo.row[mask]]\n col_doc_keys = doc_keys[sim_coo.col[mask]]\n sim_values = sim_coo.data[mask]\n return zip(row_doc_keys, col_doc_keys, sim_values)\n</code></pre>\n<p>Given the size of your data and memory limit, this fix would no longer work if your data size increases by 40%+ since the similarity matrix itself would already run out of memory. To further reduce memory usage, the similarity values need to be updated incrementally rather than computed all at once.</p>\n<p>I'll leave other code improvements to other reviews.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T20:35:15.027", "Id": "485603", "Score": "0", "body": "Thanks for the suggestion. I made that change with my actual dataset, it I encountered the same `MemoryError` with a traceback pointing to this line: `sim_coo = pairwise_similarity.tocoo()`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T21:42:24.610", "Id": "485609", "Score": "0", "body": "What is the size of data in the similarity matrix (`pairwise_similarity.data.nbytes`)? And how much memory do you have to run the program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T22:21:07.507", "Id": "485611", "Score": "0", "body": "I made an edit to the program. you could give it another try." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T00:12:53.837", "Id": "485615", "Score": "0", "body": "`pairwise_similarity.data.nbytes` = 10417218424. The machine that I'm using has 32GB of memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T00:13:51.557", "Id": "485616", "Score": "0", "body": "The changes you made enabled the calculation to successfully complete!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T01:28:35.210", "Id": "485619", "Score": "0", "body": "Thanks for your help @GZO. Do you have any thoughts on how to modify the above solution exclude the diagonal? Those are all equal to 1 and should be excluded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-16T03:36:26.943", "Id": "485625", "Score": "0", "body": "I've made another edit to the program to address the issue." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T05:40:00.350", "Id": "247935", "ParentId": "247869", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T17:46:12.760", "Id": "247869", "Score": "4", "Tags": [ "python", "python-3.x", "numpy" ], "Title": "Calculating text similarity, filtering the results, and reshaping matrix into a list-of-tuples generates MemoryError" }
247869
<p>My angular knowledge is limited, so I don't know much yet about it's garbage collection etc to make sure my component can be used without any strange side effects or memory leaks.</p> <p>I've created a stackblitz with a working version of the component here: <a href="https://stackblitz.com/edit/angular-material-messagebox?file=src/app/app.component.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-material-messagebox?file=src/app/app.component.ts</a></p> <p>So I have a button that will trigger the 'message box dialog' like this:</p> <pre class="lang-js prettyprint-override"><code> openMessageBox(buttons: Buttons) { // mb is injected in constructor let dialog = this.mb.show('Title','Message',buttons); dialog.dialogResult$.subscribe(result=&gt;{ console.log(&quot;Button pressed: &quot;, Button[result]) }); } </code></pre> <p>After clicking one of the buttons available the dialog will close and will inform what button was pressed.</p> <p>My dialog provider looks like this:</p> <pre class="lang-js prettyprint-override"><code>@Injectable() export class MessageBox { constructor(private dialog: MatDialog) { } private dialogResultSubject!: Subject&lt;Button&gt;; dialogResult$!: Observable&lt;Button&gt;; show(message: string, title?: string, buttons?: Buttons): MessageBox { let dialogRef = this.dialog.open(MessageBoxDialog, { data: { message, title, buttons: buttons ?? Buttons.Ok } } ); this.dialogResultSubject = new Subject&lt;Button&gt;(); this.dialogResult$ = this.dialogResultSubject.asObservable() dialogRef.componentInstance.dialogResult$.subscribe(pressedButton =&gt; { this.dialogResultSubject.next(pressedButton); this.dialogResultSubject.complete(); dialogRef.close(); }); return this; } } </code></pre> <p>I complete the subject in the provider because the <code>mb</code> instance (of provider) is not destroyed.</p> <p>The <code>MessageBoxDialog</code> is a simple Component that displays the Title and a Message along with the chosen buttons:</p> <pre class="lang-js prettyprint-override"><code>import { Component, Inject } from &quot;@angular/core&quot;; import { Buttons, Button } from &quot;../common&quot;; import { MAT_DIALOG_DATA } from &quot;@angular/material/dialog&quot;; import { Subject } from &quot;rxjs&quot;; @Component({ templateUrl: './message-box.component.html', styleUrls: ['./message-box.component.scss'] }) export class MessageBoxDialog { title = ''; message = ''; buttons: Buttons = Buttons.Ok; constructor( @Inject(MAT_DIALOG_DATA) public data: any ) { this.title = data.title; this.message = data.message this.buttons = data.buttons; } dialogResultSubject = new Subject&lt;Button&gt;(); dialogResult$ = this.dialogResultSubject.asObservable(); public get Buttons(): typeof Buttons { return Buttons; } public get Button(): typeof Button { return Button; } click(button: Button) { this.dialogResultSubject.next(button); } } </code></pre> <pre><code>&lt;h2 class=&quot;mat-dialog-title&quot;&gt;{{title}}&lt;/h2&gt; &lt;mat-dialog-content&gt;{{ message }}&lt;/mat-dialog-content&gt; &lt;mat-dialog-actions *ngIf=&quot;buttons === Buttons.Ok&quot;&gt; &lt;button mat-raised-button (click)=&quot;click(Button.Ok)&quot;&gt;Ok&lt;/button&gt; &lt;/mat-dialog-actions&gt; &lt;mat-dialog-actions *ngIf=&quot;buttons === Buttons.YesNo &quot;&gt; &lt;button mat-raised-button (click)=&quot;click(Button.Yes)&quot; tabindex=&quot;-1&quot;&gt;Yes&lt;/button&gt; &lt;button mat-raised-button (click)=&quot;click(Button.No)&quot; class=&quot;mat-primary&quot;&gt;No&lt;/button&gt; &lt;/mat-dialog-actions&gt; </code></pre> <p>I hope to receive feedback about whether I created this all in a good way (or not) and some tips to improve.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T20:44:18.740", "Id": "247875", "Score": "4", "Tags": [ "angular-2+" ], "Title": "Is my Angular Material MessageBox component well build?" }
247875
<p>Could you please give me some direction about how I could refactor my code? As I add functionalities to my Budget App the class is getting bigger and I'm sure I could start looking at separating concerns and maybe using some sort of abstraction.</p> <p>I've been studying OOP for a few months now but I'm not sure how to apply this knowledge to the controls on a windows form app. All I could come up with so far is to separate the calculations I want to make with the budget entries, which I'll do next.</p> <p>Here's the link to my form code:</p> <p><a href="https://github.com/pablo-the-souza/Budget1.1/blob/master/Budget1.1/Form1.cs" rel="nofollow noreferrer">https://github.com/pablo-the-souza/Budget1.1/blob/master/Budget1.1/Form1.cs</a></p> <p>And here's a snippet:</p> <pre><code> private void fillByDateAndCategoryBtn_Click(object sender, EventArgs e) { this.mainTableAdapter1.FillByDateAndCategory ( this.dataSet2.main, categoryCB.SelectedItem.ToString(), monthCalendarStart.SelectionRange.Start.ToString(), monthCalendarStart.SelectionRange.End.ToString() ); } private void FillByDateAndTypeBtn_Click(object sender, EventArgs e) { this.mainTableAdapter1.FillByDateAndType ( this.dataSet2.main, typeCB.SelectedItem.ToString(), monthCalendarStart.SelectionRange.Start.ToString(), monthCalendarStart.SelectionRange.End.ToString() ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T06:56:30.390", "Id": "485467", "Score": "0", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T06:57:27.803", "Id": "485468", "Score": "0", "body": "We require that **the code be embedded directly**. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T06:08:56.900", "Id": "247882", "Score": "2", "Tags": [ "c#", "object-oriented", ".net", "winforms" ], "Title": "Applying OOP to refactor my Windows Forms APP" }
247882
<p>Please review my program and give some tips . I am a beginner. IT is for those people who sit on computer all day and get unhealthy . This will remind them to do eye exercise , physical exercise and to drink water</p> <pre><code>import pygame import time t = time.ctime(time.time()) # noinspection SpellCheckingInspection totalbreaks2 = 17 # noinspection SpellCheckingInspection breakcount2 = 0 # noinspection SpellCheckingInspection totalbreaks = 16 # noinspection SpellCheckingInspection breakcount = 0 # noinspection SpellCheckingInspection totalbreaks1 = 10 # noinspection SpellCheckingInspection breakcount1 = 0 # noinspection SpellCheckingInspection def health(): # global keywords global breakcount2 global breakcount global breakcount1 global totalbreaks1 global totalbreaks global totalbreaks2 # water program if breakcount2 &lt; totalbreaks2: pygame.mixer.init() pygame.mixer.music.load(&quot;water.mp3.mp3&quot;) pygame.mixer.music.play(-1) query = input('Did you drink water (type drank if yes)?') if query == 'drank': with open('water.txt', 'r+') as o: o.write(f'You drank water at {t} ') pygame.mixer.music.pause() time.sleep(120) breakcount2 += 1 # eye program if breakcount &lt; totalbreaks: pygame.mixer.init() pygame.mixer.music.load(&quot;eyes.mp3.mp3&quot;) pygame.mixer.music.play(-1) query = input('Did you do eyes exercise ?(type eydone if yes)') if query == 'eydone': with open('water.txt', 'r+') as o1: o1.write(f'You drank water at {t} ') pygame.mixer.music.pause() time.sleep(1080) breakcount += 1 # exercise program if breakcount1 &lt; totalbreaks1: pygame.mixer.init() pygame.mixer.music.load(&quot;physical.mp3.mp3&quot;) pygame.mixer.music.play(-1) query = input('Did you do physical exercise (type exdone if yes) ?:') if query == 'exdone': with open('water.txt', 'r+') as o2: o2.write(f'You drank water at {t} ') pygame.mixer.music.pause() time.sleep(2400) breakcount1 += 1 health() z = input('Do you want to start the program? (y=yes , n=no):') if z == 'y': health() elif z == 'n': print('ok') else: print('type correct input') </code></pre>
[]
[ { "body": "<p><strong>Variable naming</strong></p>\n<p>Your variables should be named something more telling than <code>breakcount</code> , <code>breakcount1</code> and <code>breakcount2</code>. I suggest <code>breakcount_water</code> (and <code>_eyes</code> , <code>_physical</code>) instead.</p>\n<p><strong>Simpler logic</strong></p>\n<p>Instead of two variables for each kind of break (6 total), you can do with just one variable for each, starting at the max, and subtract <code>1</code> for each break. Then, you're done when you reach zero.\nThat lets you do the same thing with half as many (3) variables to keep track of.</p>\n<p><strong>Don't repeat yourself</strong></p>\n<pre><code>pygame.mixer.init()\npygame.mixer.music.load(&quot;water.mp3.mp3&quot;)\npygame.mixer.music.play(-1)\n</code></pre>\n<p>These three lines are identical each time you play music.\nCreate a function instead that takes the file name as input, and you can call <code>play_music(&quot;water.mp3.mp3&quot;)</code> which then executes these three lines in the function.</p>\n<pre><code>def play_music(filename):\n #the three lines from above\n</code></pre>\n<p><strong>Stack abuse</strong></p>\n<p>You're calling the <code>health()</code> function from inside itself, which means you never let it exit properly and if you did this a few thousand (maybe more) times, the program would crash due to stack overflow.\nInstead, you should use a <code>while</code> loop that checks for the condition to loop again, to start over without calling the function another time. That way, you can also initialise your variables at the start of the function (before the while-loop) and you don't need any global variables, since the function has access to them inside its own scope.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T04:53:25.633", "Id": "485890", "Score": "0", "body": "can i run 3 while loops at same time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T10:19:21.520", "Id": "485918", "Score": "0", "body": "You can with multiprocessing, but you're not doing that now so that's out of scope for the answer I think." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T18:59:31.487", "Id": "247918", "ParentId": "247883", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T06:51:12.617", "Id": "247883", "Score": "4", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Python program for healthy schedule" }
247883