body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Given a list, find the longest non-repeating (in other words I mean unique) string in the input list. Looking for code review, pointers on best practices, optimizations etc.</p> <pre><code>public final class LongestUniqueWord { /* * do not initialize this class */ private LongestUniqueWord( ) {} /** * Returns the longest non-repeating(unique) word in the list. * If each word repeats then return null. * * * @param words the list of words of a news paper. * @return the longest unique word. * @throws IllegalArgumentException if input size is 0. * @throws NPE if the input is null. */ public static String longestUniqueWord (List&lt;String&gt; words) { if (words.size() == 0) throw new IllegalArgumentException("The array should not be empty."); final Map&lt;String, Boolean&gt; uniqueWords = new HashMap&lt;String, Boolean&gt;(); for (String word : words) { if (uniqueWords.containsKey(word)) { uniqueWords.put(word, false); } else { uniqueWords.put(word, true); } } int maxLength = 0; String longestUniqueWord = null; for (Entry&lt;String, Boolean&gt; entry : uniqueWords.entrySet()) { if (entry.getValue() &amp;&amp; entry.getKey().length() &gt; maxLength) { longestUniqueWord = entry.getKey(); maxLength = longestUniqueWord.length(); } } return longestUniqueWord; } public static void main(String[] args) { List&lt;String&gt; newsPaper = new ArrayList&lt;String&gt;(); newsPaper.add("Jack"); newsPaper.add("In"); newsPaper.add("In"); newsPaper.add("The"); newsPaper.add("The"); newsPaper.add("Box"); System.out.println("Expected: Jack, Actual: " + longestUniqueWord(newsPaper)); newsPaper.add("Jack"); System.out.println("Expected: Box, Actual: " + longestUniqueWord(newsPaper)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:11:36.213", "Id": "67039", "Score": "0", "body": "What happens if the two longest unique words are the same length?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:24:59.453", "Id": "67041", "Score": "0", "body": "I should have realized it, also documented it." } ]
[ { "body": "<p>I'm on my phone so can only give pointers. </p>\n\n<ul>\n<li>In the first loop you can use <code>Map.get</code> and switch on its value:\n<ol>\n<li><code>null</code>: put <code>True</code> and add to <code>wordsByLength</code></li>\n<li><code>True</code>: put <code>False</code> and remove from <code>wordsByLength</code></li>\n<li><code>False</code>: do nothing</li>\n</ol></li>\n</ul>\n\n<p><code>Map&lt;Integer, Set&lt;String&gt;&gt; wordsByLength</code> tracks unique word sets, one per word length. It maps word length to a set of unique words. Whenever a new word appears in 1 above, add it to the set. When it is seen again for the first time in 2, remove it.</p>\n\n<p>Next sort those entries by their keys (word length) in reverse and pull the first word from the first set.</p>\n\n<p>Note that you may end up with ties of same-length words. The standard set will return an undefined \"first\" word. That may be okay. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:23:53.960", "Id": "67040", "Score": "1", "body": "Sorting would take O(n log n) time, though. The current solution is O(n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:42:00.857", "Id": "67045", "Score": "2", "body": "O(n log n) on the unique word lengths (10? 15?) is better than O(n) on the number of unique words (1,000? 1,000,000?)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:16:28.350", "Id": "39934", "ParentId": "39933", "Score": "2" } }, { "body": "<p>It looks fine, with the caveat that the answer is arbitrary if there are multiple unique words of the same maximal length. The code is easy to follow, with clear and concise naming. The algorithm is O(<em>n</em>), which cannot be improved upon significantly. Alternate approaches are possible, as pointed out by the other answers, but they aren't necessarily better than the existing code. Therefore, in my opinion, this is one of those cases where the solution is good enough to leave alone.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:22:06.047", "Id": "39935", "ParentId": "39933", "Score": "2" } }, { "body": "<p>Your solution is pretty good in general, although I'm going to outline a slightly different approach. </p>\n\n<p><strike> Firstly, as an aside, this method clearly isn't intended to modify the <code>words</code> list that is passed in, so let's make that <code>final</code>:</p>\n\n<pre><code>public static String longestUniqueWord (final List&lt;String&gt; words)\n</code></pre>\n\n<p></strike></p>\n\n<p>Secondly, we can (potentially) cut down on the work required but storing the pairs in a <code>TreeMap</code>. This will keep them in sorted order.</p>\n\n<pre><code>Map&lt;String, Boolean&gt; unique = new TreeMap&lt;String, Boolean&gt;(new Comparator&lt;String&gt;() {\n public int compare(String s1, String s2)\n {\n if(s1.length() &gt; s2.length()) return -1;\n else if(s1.length() &lt; s2.length()) return 1;\n return s2.compareTo(s1);\n }\n});\n</code></pre>\n\n<p>Here, we create a <code>TreeMap</code> which orders its elements based on the given <code>Comparator</code>. This comparator says that longer strings come earlier in the set, and if two strings have the same length, then we just go back to comparing them lexicographically. Note that this gives you flexibility to easily change how you want to deal with ties.</p>\n\n<p>Insertion is pretty much the same.</p>\n\n<pre><code>for(String word : words) {\n if(unique.containsKey(word)) {\n unique.put(word, false);\n } else {\n unique.put(word, true);\n }\n}\n</code></pre>\n\n<p>However, iteration is now (potentially) faster: if the longest string is unique, this will happen immediately, instead of having to loop through the entire <code>Map</code>.</p>\n\n<pre><code>for(Map.Entry&lt;String, Boolean&gt; entry : unique.entrySet()) {\n if(entry.getValue()) {\n return entry.getKey();\n }\n}\n</code></pre>\n\n<p>Of course, the tradeoff with this approach is that <code>TreeMap</code> is <code>O(log n)</code> instead of (amortized) <code>O(1)</code>, but this could potentially be faster depending on expected input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:36:13.580", "Id": "67043", "Score": "0", "body": "What if, if the most latest added max length word is required?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:40:38.067", "Id": "67044", "Score": "0", "body": "Change the comparator. After the first 2 checks, you'll have that `s2` must be the same length as `s1`. Check if they are equal (`s2.equals(s1)`), and if not, return -1 (which will put `s2` ahead of `s1`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:50:53.333", "Id": "67046", "Score": "0", "body": "`final` enforces no guarantees about the contents of the `List`. It just prevents this function from rebinding `words` internally. I wouldn't bother." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:58:35.847", "Id": "67047", "Score": "1", "body": "@200_success Thanks, I always have to be reminded that `final` != `const` when I come back to Java-land." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:28:48.430", "Id": "39936", "ParentId": "39933", "Score": "1" } } ]
{ "AcceptedAnswerId": "39935", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T05:47:10.437", "Id": "39933", "Score": "4", "Tags": [ "java", "strings", "hash-map" ], "Title": "Find the longest unique string in the input list" }
39933
<p>I am reading <em>Cracking the Code Interview</em> and I am getting a bit confused at the bit using 'previous'. In this problem, the method deletes duplicate nodes in a Linked List. </p> <p>My assumption is that <code>head</code> is used to scan through the linked list while previous is used to update the linked list <code>head</code> because <code>previous</code> points to the same linked list. Not sure if my assumption is correct. Could someone verify this please?</p> <p>Perhaps someone could also provide a method of increasing the efficiency or space of this program? I would love your input!</p> <pre><code>public static void deleteDups1(LinkedListNode head) { Hashtable&lt;Integer, Boolean&gt; table = new Hashtable&lt;Integer, Boolean&gt;(); LinkedListNode previous = null; while(head != null) { if (table.containsKey(head.value)) previous.next = head.next; else { table.put(head.value, true); previous = head; } head = head.next; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T09:29:10.003", "Id": "67059", "Score": "4", "body": "This question is off-topic because it contains code lifted from a book rather than [code you wrote yourself](http://meta.codereview.stackexchange.com/q/1294/9357)." } ]
[ { "body": "<p>You are right about <code>head</code>, it is used to move through the list. <code>previous</code> is a temporary pointer that is needed to perform the delete. You need it because the delete process means taking the <code>next</code> value of the Node to the left, and making it 'skip' the deleted Node and point over to the right of the deleted Node.</p>\n\n<p>The list is linked by each Node having a <code>next</code> pointer. It would look something like:</p>\n\n<pre><code>A -&gt; B -&gt; A -&gt; C -&gt; D -&gt;\n</code></pre>\n\n<p>Here the first A points to B, which points to a different A, which points to C, and so on.</p>\n\n<p>You would call your method with the pointer to the first A as the argument <code>head</code>. There is no previous ....</p>\n\n<p>So your system starts off looking like:</p>\n\n<pre><code> A -&gt; B -&gt; A -&gt; C -&gt; D -&gt;\n^ ^\nP H\n</code></pre>\n\n<p>Where <code>H</code> is the Head pointer, and <code>P</code> is the previous.</p>\n\n<p>We add the value <code>A</code> to the HashMap, and advance our pointers:</p>\n\n<pre><code> A -&gt; B -&gt; A -&gt; C -&gt; D -&gt;\n ^ ^\n P H\n</code></pre>\n\n<p>B is not in the HashMap, so move on....</p>\n\n<pre><code> A -&gt; B -&gt; A -&gt; C -&gt; D -&gt;\n ^ ^\n P H\n</code></pre>\n\n<p>A <strong>is</strong> in the HashMap, so we have a duplicate. This is where P comes in to play....</p>\n\n<p>We make the B (pointed to by <code>previous</code>) point to C....</p>\n\n<pre><code> A -&gt; B ---&gt; C -&gt; D -&gt;\n ^ /\n | A\n | ^\n P H\n</code></pre>\n\n<p>We do that by making the <code>previous</code>'s <code>next</code> point to the <code>head</code>'s <code>next</code>. We now have a kind of 'fork' in the list, with the second <code>A</code> dangling part way through....</p>\n\n<p>We have now removed the A from the main link chain, and we need to advance the head pointer to C.... Sunce Nothing is pointing to the second A now, it can be garbage collected, etc... and the final result looks like:</p>\n\n<pre><code> A -&gt; B ---&gt; C -&gt; D -&gt;\n ^ ^\n P H\n</code></pre>\n\n<p>Now, about your other questions.....</p>\n\n<p>This operation is about as fast as it can get. Not much you can do to improve performance.</p>\n\n<p>Additionally, the operation essentially uses no stoage (there is some stack amount, but this is peanuts in the scheme of things....</p>\n\n<p>If this list is able to cover your use cases, then I would say \"Great, use it\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:56:35.117", "Id": "67057", "Score": "0", "body": "The algorithm uses a `Hastable` to store all keys. So I'd say it's `O(n)` which is not exactly nothing (depends on the size of the list)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:56:09.453", "Id": "67096", "Score": "0", "body": "thank you for this thorough explanation! you reassured me and I also learn a lot!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:32:42.153", "Id": "39941", "ParentId": "39937", "Score": "6" } }, { "body": "<p>@rolfl already explained the algorithm very well, just a remark to the space consumption:</p>\n\n<p>It uses a <code>Hashtable</code> which maps keys to values. However it actually doesn't use the values - it is only interested in the keys. So it should be changed to use a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html\" rel=\"nofollow\"><code>HashSet</code></a> instead. This can be used to keep a unique collection of entities which is precisely what you want. Three advantages:</p>\n\n<ol>\n<li><p>The usage of the structure is closer to a <code>HashSet</code> than a <code>HasTable</code> so the better fitting data structure should be used. It makes the code a clearer to read.</p></li>\n<li><p>In theory it could save some memory as it does not need to store values (which are not needed anyway) associated with the key.</p></li>\n<li><p>The code can be slightly optimized (only one key lookup instead of two):</p>\n\n<pre><code>public static void deleteDups1(LinkedListNode head) {\n HashSet&lt;Integer&gt; table = new HashSet&lt;Integer&gt;();\n LinkedListNode previous = null;\n while(head != null) {\n if (!table.add(head.value)) {\n // fail to add means it is already present\n previous.next = head.next;\n }\n else {\n previous = head;\n }\n head = head.next;\n }\n}\n</code></pre></li>\n</ol>\n\n<p>As a side note (and because we are on CR): <code>deleteDups1</code> is not a really good name. I know that sometimes numbers are used to indicate newer versions of the same method but I'd suggest to rename it <code>deleteDuplicates</code> if you can.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:58:10.173", "Id": "67098", "Score": "0", "body": "Thank you for these suggestions! i thought about using HashSet would be more appropriate as well but I was just following the book! I appreciate your input thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:55:36.220", "Id": "39945", "ParentId": "39937", "Score": "2" } } ]
{ "AcceptedAnswerId": "39941", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:57:58.530", "Id": "39937", "Score": "4", "Tags": [ "java", "linked-list" ], "Title": "Delete duplicates in a linked List" }
39937
<p>I've created a simple game, in which the user needs to guess 4 digits number between 0-9, generated randomly using <code>Random()</code> Each of the 4 digits are different from each other, with no repeated digits. The user has 5 attempts to guess, and each failed (almost correct) guess will tell the user in which part they got it correct.</p> <p>Do you think this is too hard, or too easy for the user to guess? I also need some review of this code. Perhaps some of it can be simplified?</p> <pre><code>import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Game { public static void main(String[] args) { System.out.println("The computer has generate a unique 4 digit number.\n" + "You can try to guess the 4 digits number in 5 attempts.\n"); System.out.println("_______________________________________________________\n"); int[] random=numberGenerator(); int maxTry=5; int indexMatch=0; int match=0; while(maxTry&gt;0 &amp;&amp; indexMatch!=4){ int[] guess=getGuess(); indexMatch=0; match=0; for(int i=0;i&lt;guess.length;i++){ if(guess[i]==random[i]){ indexMatch++; } else if(guess[i]==random[0] || guess[i]==random[1] || guess[i]==random[2] || guess[i]==random[3]){ match++; } } if(indexMatch==4){ System.out.print("Well done! Your guess is Correct! The number is: "); for(int i=0;i&lt;guess.length;i++){ System.out.print(guess[i]); } } else{ maxTry--; if(maxTry&gt;1){ System.out.println("You have guess "+indexMatch+" correct number in correct position,"+ " and "+match+" correct number in incorrect position. \n"+maxTry+" attempt remaining."); } else if(maxTry==1){ System.out.println("You have guess "+indexMatch+" correct number in correct position,"+ " and "+match+" correct number in incorrect position. \nLast attempt!. Good luck"); } else{ System.out.println("Sorry, you failed to guess the number in 5 attempts."); System.out.print("The number is: "); for(int i=0;i&lt;random.length;i++){ System.out.print(random[i]); } } } } } public static int[] getGuess(){ Scanner keyboard = new Scanner(System.in); System.out.println("Please enter your guess: "); String input = keyboard.nextLine(); if(input.length()!=4 || input.replaceAll("\\D","").length()!=4){ System.out.println("Invalid number. You must enter 4 digits between 0-9 only."); return getGuess(); } int[] guess = new int[4]; for (int i = 0; i &lt; 4; i++) { guess[i] = Integer.parseInt(String.valueOf(input.charAt(i))); } return guess; } public static int[] numberGenerator() { Random randy = new Random(); int[] randArray = {10,10,10,10}; for(int i=0;i&lt;randArray.length;i++){ int temp = randy.nextInt(9); while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){ temp=randy.nextInt(9); } randArray[i]=temp; } return randArray; } } </code></pre>
[]
[ { "body": "<p>Just focusing on one specific point for the moment:</p>\n\n<pre><code>int temp = randy.nextInt(9);\n</code></pre>\n\n<p>This will never generate the digit <code>9</code>. </p>\n\n<p>If you want to be generating digits 0 through 9 inclusive (that is 10 different digits) you need to do:</p>\n\n<pre><code>int temp = randy.nextInt(10);\n</code></pre>\n\n<p>If you want to exclude 0 (which, in this case may make sense....):</p>\n\n<pre><code>int temp = randy.nextInt(9) + 1;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:12:42.907", "Id": "67048", "Score": "0", "body": "ouch, i really miss-look at this! thanks. `0` is included, so i'll use `nextInt(10)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:49:00.933", "Id": "67522", "Score": "2", "body": "You also don't need a loop. You can put the digits 0-9 into a list, shuffle the list, and then take the first four entries from the list." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:10:50.140", "Id": "39939", "ParentId": "39938", "Score": "14" } }, { "body": "<p>In <code>getGuess()</code>,</p>\n\n<pre><code>Integer.parseInt(String.valueOf(input.charAt(i)))\n</code></pre>\n\n<p>could be written as <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#digit(char,%20int)\" rel=\"nofollow\"><code>Character.digit(input.charAt(i), 10)</code></a>.</p>\n\n<p>In <code>getGuess()</code>, recursing on validation failure is inappropriate. (Hold down the <kbd>Enter</kbd> key to overflow the stack!) Use a loop instead:</p>\n\n<pre><code>public static int[] getGuess(){\n    Scanner keyboard = new Scanner(System.in);\n do {\n System.out.print(\"Please enter your guess: \");\n String input = keyboard.nextLine();\n if (input.matches(\"\\\\d{4}\")) break;\n System.out.println(\"Invalid number. You must enter 4 digits between 0-9 only.\");\n } while (true);\n    int[] guess = new int[4];\n    for (int i = 0; i &lt; guess.length; i++) {\n        guess[i] = Character.digit(input.charAt(i), 10);\n    }\n    return guess;\n}\n</code></pre>\n\n<p>In <code>numberGenerator()</code>, change your while-loop to a do-while.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:34:16.677", "Id": "67050", "Score": "0", "body": "cool. `Character.digit()` is a new thing for me. And about the `while`, urmm..yeah I guess you're right" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:30:51.810", "Id": "67053", "Score": "1", "body": "How to validate the user input using `do-while`? I thought recursion is the simple one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:44:19.240", "Id": "67055", "Score": "3", "body": "@RafaEl conceptually it's `do{prompt();input=getInput();while(!isValid(input));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:53:28.863", "Id": "67056", "Score": "0", "body": "okay that was really make sense. and thanks for the regex `(\"\\\\d{4}\")` much more shorter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:47:01.707", "Id": "67094", "Score": "1", "body": "@Tibos I don't know of any implementation of Java that performs tail call optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:59:46.920", "Id": "67099", "Score": "0", "body": "@200_success That was unexpected. Thanks for rectifying!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:28:26.560", "Id": "39940", "ParentId": "39938", "Score": "6" } }, { "body": "<p>Less focused on functionality and more on nomenclature: I wouldn't call your <code>new Random()</code> the name <code>randy</code>. While the name is pretty clear in what it does, the word randy also has a more immature meaning. You never know who will see your source code, so if any of your customers ever sees code with somewhat immature variable names or comments, they could think your immaturity extends to functionality, even if it doesn't.</p>\n\n<p>So instead of</p>\n\n<pre><code>Random randy = new Random();\n</code></pre>\n\n<p>write</p>\n\n<pre><code>Random rand = new Random();\n</code></pre>\n\n<p>In general, avoid using immature words, the names of coworkers, companies or products or words in foreign languages, except if the word you want to use is relevant to what the variable is intended for. <code>EPAComplianceCheck()</code> is acceptable. <code>ScrewYouGinaMcCarthy()</code> less so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:45:46.000", "Id": "67069", "Score": "0", "body": "LOL. Okay, actually I found this funny too. I just forgot to change all those variables name before posting. thanks anyway!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T13:17:55.993", "Id": "67076", "Score": "5", "body": "It's amazing how many little jokes people put in code then forget to take out...until someone who shouldn't see them does see them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T09:55:21.923", "Id": "39947", "ParentId": "39938", "Score": "12" } }, { "body": "<p>As this part of the question has been skipped so far, I'll take it:</p>\n\n<p><strong>Do you think this is too hard?</strong></p>\n\n<p>I think it is. Similarly to your game, in classic <a href=\"http://en.wikipedia.org/wiki/Mastermind_%28board_game%29\" rel=\"nofollow noreferrer\">Mastermind</a>, the player has to guess a combination of 4 non-unique coloured pegs, and each time is given a mark for the number of correct position and colour combinations.</p>\n\n<p>6<sup>4</sup> = 1,296 possible combinations</p>\n\n<p>However, with your game (to borrow the nomenclature), there are 10 possible pegs, and as they're unique the combinations are:</p>\n\n<p>10 x 9 x 8 x 7 = 5,040 possible combinations</p>\n\n<p>Which is an increase of 288.8%, furthermore you're only giving the user 5 attempts to guess, as opposed to Mastermind's 6, 8 or 12. The reason Mastermind plays with a minimum of six, is that you get to test every combination, e.g:</p>\n\n<p><img src=\"https://i.stack.imgur.com/QAApo.png\" alt=\"Mastermind guessing\"></p>\n\n<p>However, when you increase the number of possibilities to 10, and reduce the guesses to 5, you can no longer do this, and the chances of never guessing a correct number increase dramatically, e.g.:</p>\n\n<p><img src=\"https://i.stack.imgur.com/d3lQ5.png\" alt=\"Question guessing\"></p>\n\n<p>Therefore, I think you need to either increase the number of guesses to 10 (at the least), or chose a smaller set of things to guess, like A-F, 1-6, or something GUI based like Mastermind.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:51:38.743", "Id": "67070", "Score": "0", "body": "great. with 0.001 probability of winning, perhaps I should just make this as a gamble game." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:56:42.280", "Id": "67152", "Score": "10", "body": "-1 Mastermind is completely different from what you just described. In Mastermind, the player is told how many pegs are the correct color but in the wrong position, and how many are the correct color and position. Thus, in your first example `1234` would be given 3 white pegs, giving the player significantly more information than what you show here. Also, [Mastermind can always be beaten in 5 moves](http://en.wikipedia.org/wiki/Mastermind_%28board_game%29#Five-guess_algorithm)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T10:15:44.263", "Id": "39950", "ParentId": "39938", "Score": "25" } }, { "body": "<p>First off:</p>\n\n<pre><code>public class Game {\n</code></pre>\n\n<p><em>Really?</em> What game is this? Is this like, tetris or something? Make it something like <code>CodeGuessGame</code>, and add a javadoc comment to the class explaining exactly what it is, and what it does.</p>\n\n<pre><code>System.out.println(\"The computer has generate a unique 4 digit number.\\n\"\n + \"You can try to guess the 4 digits number in 5 attempts.\\n\");\n</code></pre>\n\n<p>Besides spelling errors, you shouldn't have the <code>\\n</code> at the end of that line, because you are using a <code>println</code>. Personally, I always put my <code>\\n</code>s at the <em>beginning</em> of each continuation line, but that isn't completely nessisary.</p>\n\n<pre><code> System.out.println(\"_______________________________________________________\\n\");\n</code></pre>\n\n<p>Again, extra <code>\\n</code>. Personally I would suggest using hyphens (<code>-</code>) or equals signs (<code>=</code>) instead, because those are more common for creating horizontal rules. Underscores suggest a blank that the user is supposed to type into.</p>\n\n<pre><code> int[] random = numberGenerator();\n int maxTry = 5;\n int indexMatch = 0;\n int match = 0;\n</code></pre>\n\n<p>You should combine the declarations for <code>maxTry</code>, <code>indexMatch</code>, and <code>match</code> into one statement, for conciseness.</p>\n\n<pre><code> while(maxTry&gt;0 &amp;&amp; indexMatch!=4){\n int[] guess=getGuess();\n indexMatch=0;\n match=0;\n for(int i=0;i&lt;guess.length;i++){\n if(guess[i]==random[i]){\n indexMatch++;\n }\n else if(guess[i]==random[0] || guess[i]==random[1] || guess[i]==random[2] || guess[i]==random[3]){\n match++;\n }\n }\n if(indexMatch==4){\n System.out.print(\"Well done! Your guess is Correct! The number is: \");\n for(int i=0;i&lt;guess.length;i++){\n System.out.print(guess[i]);\n }\n }\n else{\n maxTry--;\n if(maxTry&gt;1){\n System.out.println(\"You have guess \"+indexMatch+\" correct number in correct position,\"+\n \" and \"+match+\" correct number in incorrect position. \\n\"+maxTry+\" attempt remaining.\");\n }\n else if(maxTry==1){\n System.out.println(\"You have guess \"+indexMatch+\" correct number in correct position,\"+\n \" and \"+match+\" correct number in incorrect position. \\nLast attempt!. Good luck\");\n }\n else{\n System.out.println(\"Sorry, you failed to guess the number in 5 attempts.\");\n System.out.print(\"The number is: \");\n for(int i=0;i&lt;random.length;i++){\n System.out.print(random[i]);\n }\n }\n }\n } \n}\n</code></pre>\n\n<p>Whut us thish shpaghetti?? Please, learn to use <code>System.out.format</code> and ternary operations (<code>condition?valueIfTrue:valueIfFalse</code>).</p>\n\n<p>At this point, I can no longer bear to read your code any more. Please, just write a new program, and write it with configurability and reusability in mind this time.</p>\n\n<p>The game should be run as separate instances. The main method should not contain any logic having to do with the actual game. All it should do is (1) instintantiate <code>Game</code>, (2) set configurable options, and (3) call an instance method of <code>Game</code> (called something like <code>play</code>) to run the game.</p>\n\n<p>Ideally, your main method should end up looking like this:</p>\n\n<pre><code>public static void main(String [] args){\n new MastermindGame()\n .setLanes(4)\n .setColors(\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\")\n .setGuesses(5)\n .setStartFlavor(\"The computer has generated a 4 digit number.\"\n + \"\\nYou must guess this 4 digit number in 5 attempt(s).\")\n .setPrompt(\"Enter guess:\")\n .setResponse(\"Correct digit in correct position count = %1\"\n + \"\\nCorrect digit in incorrect position count = %2\"\n + \"\\nGuesses remaining = %3\")\n .setLose(\"Sorry, you failed to guess the number (%1) in 5 attempts.\");\n .setWin(\"Congratulations, you win!\");\n .play();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:34:02.353", "Id": "67140", "Score": "1", "body": "I defiantly wouldn't recommend that main method. That requires all methods returning void to return this instead. Plus debugging that will be a chore. I would consider that to be very bad practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:47:47.047", "Id": "67148", "Score": "0", "body": "Thought about this a bit more and maybe it is ok. The term seems to be a \"fluent interface\" or \"method chaining\". Dealing with stack traces from this kind of thing is going to be messy but it is somewhat interesting. See this question for a further discussion of them: http://stackoverflow.com/questions/1345001/is-it-bad-practice-to-make-a-setter-return-this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:54:47.523", "Id": "67151", "Score": "1", "body": "That won't affect stack traces, and the only thing messy about debugging it is that you need breakpoints on subexpressions (or just put them on the functions themselves instead of the call site)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:22:06.023", "Id": "39976", "ParentId": "39938", "Score": "1" } }, { "body": "<p>I will not comment on the random number generation, variable naming, or general code structure - you have enough good information in the above.</p>\n\n<p>But here is my two cents for the \"is it too hard?\" part of your question. </p>\n\n<p>The game you describe used to be known as \"<a href=\"http://en.wikipedia.org/wiki/Bulls_and_cows\">bulls and cows</a>\", and</p>\n\n<blockquote>\n <p>It's proven that any number could be solved for up to seven turns. \n Minimal average game length is 26274/5040=5.2131 turns.</p>\n</blockquote>\n\n<p>References: <a href=\"http://fourdigits.sourceforge.net\">http://fourdigits.sourceforge.net</a>, <a href=\"http://www.cs.nccu.edu.tw/~chaolin/papers/science3203.pdf\">http://www.cs.nccu.edu.tw/~chaolin/papers/science3203.pdf</a></p>\n\n<p>So yes, only four guesses is pretty hard. Five guesses gives you a less than even chance, six is better than even.</p>\n\n<p>If you are trying to solve the game with a computer, you typically want to find the guess that minimizes the maximum number of valid combinations that remain. It turns out that if you start with the guess</p>\n\n<pre><code>1234\n</code></pre>\n\n<p>the \"worst answer\" you can get back is</p>\n\n<pre><code>1 white peg (one number correct, in the wrong location)\n</code></pre>\n\n<p>which leaves you with 1440 possible combinations (any of the 4 numbers could be the one with the white peg, but it would be in the wrong position. That leaves you with 4 possible numbers in each of three positions, times 6x5x4 for the other three open positions (which must be filled by one of the numbers not yet used).</p>\n\n<p>You can actually make a list of all possible combinations, and \"cross off\" the ones that don't fit in every turn; combining this with \"if I guess abcd, and the response is [x white, y black], how many combinations are there left?\" and again picking the guess that minimizes that number. Quite easy to do in a computer.</p>\n\n<p><strong>One other bug in your code</strong></p>\n\n<p>In some situations, the best guess is one that is \"illegal\" - that is, you ask for a combination that is inconsistent with the information you have so far. It can even include a doubled-up digit - e.g.</p>\n\n<pre><code>1123\n</code></pre>\n\n<p>You have to make sure that your code deals with that input correctly. The way to do this is to change your test loop slightly - instead of</p>\n\n<pre><code>for(int i=0;i&lt;guess.length;i++){\n if(guess[i]==random[i]){\n indexMatch++;\n }\n else if(guess[i]==random[0] || guess[i]==random[1] || guess[i]==random[2] || guess[i]==random[3]){\n match++;\n }\n}\n</code></pre>\n\n<p>You need</p>\n\n<pre><code>for(int i=0;i&lt;guess.length;i++)\n if(guess[i]==random[i]){\n indexMatch++;\n }\n else if( random[i] == guess[0] || random[i] == guess[1] || random[i] == guess[2] || random[i] == guess[3]){\n match++;\n }\n }\n</code></pre>\n\n<p>Look what happens if the random code is</p>\n\n<pre><code>1234\n</code></pre>\n\n<p>and the guess is</p>\n\n<pre><code>3132\n</code></pre>\n\n<p>The correct answer would be \"one black, two white\". But your code would give \"one black, three white\" since the repeated three in the guess gets counted twice. By switching around the test, each value in the random number only gets looked at once - and that makes all the difference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T07:30:23.587", "Id": "40028", "ParentId": "39938", "Score": "8" } } ]
{ "AcceptedAnswerId": "40028", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T06:59:15.047", "Id": "39938", "Score": "26", "Tags": [ "java", "game", "random", "number-guessing-game" ], "Title": "Guessing a unique 4 random digits number" }
39938
<p>I have a <code>textarea</code> and <code>iframe</code> whose sizes should change dynamically and in reverse directions. I'd like to achive this effect without using a <code>frameset</code> or jQuery plugin. Here's the result of my attempt:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Resize&lt;/title&gt; &lt;style&gt; textarea, iframe { display: block; width: 300px; height: 200px; margin: 0; border: 0; padding: 0; } textarea { background: green; resize: none; } iframe { background: blue; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;input id="slide" oninput="resize();" onchange="resize();" type="range" min="0" max="400" value="200"&gt; &lt;textarea id="textarea"&gt;&lt;/textarea&gt; &lt;iframe id="iframe"&gt;&lt;/iframe&gt; &lt;script&gt; var slide = document.getElementById("slide"); var textarea = document.getElementById("textarea"); var iframe = document.getElementById("iframe"); function resize() { var slideValue = slide.value; textarea.style.height = slideValue + "px"; iframe.style.height = 400 - slideValue + "px"; } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><a href="http://jsfiddle.net/RainLover/EY4mR/24/" rel="nofollow">Demo</a> </p> <p>I wonder if you could review my code and let me know what you think.</p>
[]
[ { "body": "<p>Perhaps add <code>overflow:hidden;</code> to the CSS of the <code>textarea</code> and <code>iframe</code>, and add <code>scrolling=\"no\"</code> as an attribute of the HTML <code>iframe</code> element: because otherwise, a scrollbar will appear when the slider is very big or very small.</p>\n\n<p>Maybe a scrollbar is what you want (for usability); but a scrollbar makes a small visual artifact in an empty textbox or iframe, when the element is shorter than one line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:39:03.750", "Id": "67467", "Score": "0", "body": "Thanks for the answer, but this `textarea` isn't going to be empty. If I add `overflow:hidden;` to the `textarea` and remove its scrolling functionality, then how can I insert and access a long string of text?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T11:27:15.037", "Id": "67479", "Score": "0", "body": "@RainLover The scrollbar was a minor (perhaps unhelpful) answer: it was the only thing I found to comment on or criticize. Apart from that the code looks good to me: simple and easy to read. You could perhaps add a comment in the code to explain what functionality it is implementing. Do you have any specific questions/concerns about he code you posted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:07:23.317", "Id": "67548", "Score": "0", "body": "Nothing in particular. Just wanted to make sure my coding is right and if there's a better approach to achieve the same effect. Thanks anyway! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T10:27:30.360", "Id": "39952", "ParentId": "39942", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T07:49:45.217", "Id": "39942", "Score": "5", "Tags": [ "javascript", "html", "css" ], "Title": "Resize iframe & textarea in reverse directions" }
39942
<p><a href="http://projecteuler.net/problem=23" rel="nofollow">Project Euler Problem 23</a> asks:</p> <blockquote> <p>A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.</p> <p>A number <em>n</em> is called deficient if the sum of its proper divisors is less than <em>n</em> and it is called abundant if this sum exceeds <em>n</em>.</p> <p>As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.</p> <p>Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.</p> </blockquote> <p>I have been trying to optimize my solution for almost a day now but my program is not ready to get small and optimized. Can anyone please tell me how I can do that?</p> <pre><code>def isabundant(n): return sum(list(x for x in range(1, int(n/2)+1) if n % x == 0)) &gt; n abundants = list(x for x in range(1, 28123) if isabundant(x) == True) sums = 0 for i in range(12, 28123): for abundant in abundants: if abundant &gt;= i and isabundant(i+abundant) == True: sums += i print(sums) </code></pre>
[]
[ { "body": "<p>Your first problem is that you're trying to cram too much information onto one line. As a result, you loose the overview. Here is a simple refactoring:</p>\n\n<pre><code>def is_abundant(n):\n max_divisor = int(n / 2) + 1\n sum = 0\n for x in range(1, max_divisor):\n if n % x == 0:\n sum += x \n return sum &gt; n\n\nabundants = list(x for x in range(1, 28123) if is_abundant(x))\n\nsums = 0\nfor i in range(12, 28123):\n for abundant in abundants:\n if abundant &gt;= i and is_abundant(i + abundant):\n sums += i\nprint(sums)\n</code></pre>\n\n<ul>\n<li>The <code>== True</code> tests are unecessary and were removed.</li>\n<li>Naming was improved: <code>isabundant</code> → <code>is_abundant</code>.</li>\n<li>The long statement in <code>is_abundant</code> was split up.</li>\n</ul>\n\n<p>Now we can think about how this could be optimized.</p>\n\n<p>One subproblem is calculating all divisors of a number. We could put the relevant code into its own function. We can furthermore exploit that if <code>n % i == 0</code>, then there must be another integer <code>k</code> so that <code>n == i * k</code>. This means that we only have to look at a lot less numbers: only the <code>range(2, 1 + int(sqrt(n)))</code> is interesting.</p>\n\n<pre><code>def divisors(n):\n \"\"\"\n Returns all nontrivial divisors of an integer, but makes no guarantees on the order.\n \"\"\"\n # \"1\" is always a divisor (at least for our purposes)\n yield 1\n\n largest = int(math.sqrt(n))\n\n # special-case square numbers to avoid yielding the same divisor twice\n if largest * largest == n:\n yield largest\n else:\n largest += 1\n\n # all other divisors\n for i in range(2, largest):\n if n % i == 0:\n yield i\n yield n / i\n</code></pre>\n\n<p>We can now rewrite our <code>is_abundant</code> to the simpler:</p>\n\n<pre><code>def is_abundant(n):\n if n &lt; 12:\n return False\n return sum(divisors(n)) &gt; n\n</code></pre>\n\n<p>Later, in your main loop, you are doing a rather weird calculation. What were we supposed to do?</p>\n\n<blockquote>\n <p>Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.</p>\n</blockquote>\n\n<p>We furthermore know that all integers <em>above</em> 28123 can be written as such a sum. Thus we have to look at the <code>range(1, 28123 + 1)</code>! How can we decide if a number <code>n</code> can be written as a sum of abundant numbers <code>i</code> and <code>k</code>? There exists any abundant number <code>i</code> with the constraint <code>i &lt; n</code>, and another abundant number with the constraints <code>k &lt; n and n - i == k</code>. Here is one clever way to write this:</p>\n\n<pre><code>def is_abundant_sum(n):\n for i in abundants_smaller_than_n:\n if (n - i) in abundants_smaller_than_n:\n return True\n return False\n</code></pre>\n\n<p>Because we don't want to calculate the <code>abundants_smaller_than_n</code> each time, we just take all possible <code>abundants</code> and bail out if we get larger than <code>n</code>:</p>\n\n<pre><code>def is_abundant_sum(n):\n for i in abundants:\n if i &gt; n: # assume \"abundants\" is ordered\n return False\n if (n - i) in abundants:\n return True\n return False\n</code></pre>\n\n<p>where <code>abundants = [x for x in range(1, 28123 + 1) if is_abundant(x)]</code>.</p>\n\n<p>Now, all that is left to do is to sum those numbers where this condition does <em>not</em> hold true:</p>\n\n<pre><code>sum_of_non_abundants = sum(x for x in range(1, 28123 + 1) if not is_abundant_sum(x))\n</code></pre>\n\n<p>We could perform one optimization: <code>abundants</code> is a list, which is an ordered data structure. If we search for an element that is not contained in the list, all elements would have to be searched. The <code>set()</code> data structure is faster, so:</p>\n\n<pre><code>abundants_set = set(abundants)\ndef is_abundant_sum(n):\n for i in abundants:\n if i &gt; n: # assume \"abundants\" is ordered\n return False\n if (n - i) in abundants_set:\n return True\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-24T18:25:07.473", "Id": "110569", "Score": "2", "body": "Your code is not working." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-24T19:44:02.763", "Id": "110579", "Score": "0", "body": "@MohammadAreebSiddiqui Thanks for pointing that out. It seems I was too distracted by interesting number theory to write a correct `divisors()` implementation. That's kind of embarrassing. Anyway, it's fixed now and passed the projecteuler.net test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-24T19:48:41.683", "Id": "110581", "Score": "0", "body": "you could've just added a check to `yield n / i` only if `i < n / i` :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T10:42:58.017", "Id": "39954", "ParentId": "39946", "Score": "14" } }, { "body": "<p>A simple optimization would be to do this instead of iterating trough every single division:</p>\n\n<pre><code>def GetSumOfDivs(n):\n i = 2\n upper = n\n total = 1\n while i &lt; upper:\n if n%i == 0:\n upper = n/i\n total += upper\n if upper != i: total += i\n i += 1\n return total\n</code></pre>\n\n<p>then you can check if the returned value is greater than the actual number to populate your list.</p>\n\n<p>this works like this:\nlets say you want to get the sum of the divisors of 28...\ninstead of iterating through each number:\n+1, +2, +4, +7, +14 it will add 2 numbers at once like this:\n3, +4+7, +14 because you keep decreasing the upper limit for the loop for each divisor.</p>\n\n<p>keep in mind that for low numbers it will actually take more time to run through, but for big number you have a massive improvement.</p>\n\n<p>Time difference: (19.381) - (11.419) = 7.962 seconds faster while generating the abundant list</p>\n\n<p>another optimization is to search in the already generated list of abundants instead of checking if the number is abundant all over again, but you should use a dictionary instead of a list to make the search substantially faster.</p>\n\n<p>My solution to your problem:</p>\n\n<pre><code>def GetSumOfDivs(n):\n i = 2\n upper = n\n total = 1\n while i &lt; upper:\n if n%i == 0:\n upper = n/i\n total += upper\n if upper != i: total += i\n i += 1\n return total\n\n\ndef isabundant(n): return GetSumOfDivs(n) &gt; n\nlAbundants = [x for x in range(12, 28123) if isabundant(x) == True]\ndAbundants = {x:x for x in lAbundants}\n\nsums = 1\nfor i in range(2, 28123):\n boo = True\n for k in lAbundants:\n if k &lt; i:\n if (i-k) in dAbundants:\n boo = False\n break\n else : break\n if boo == True: sums += i\n\nprint(sums)\n</code></pre>\n\n<p>Why a list and a dictionary? the list is ordered and the dictionary for fast indexing.</p>\n\n<p>Total execution time: 12.08 seconds</p>\n\n<p>now try it in C++... I'm sure its under 2 seconds... XD good luck</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-20T19:42:55.807", "Id": "141958", "ParentId": "39946", "Score": "3" } } ]
{ "AcceptedAnswerId": "39954", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T09:50:40.890", "Id": "39946", "Score": "10", "Tags": [ "python", "optimization", "programming-challenge", "python-3.x" ], "Title": "Optimizing solution for Project Euler Problem #23 (non-abundant sums)" }
39946
<p>I am wondering what a better solution would be for this bit of code:</p> <pre><code>public static void main( String[] args ) { String name = "hello, ddd"; boolean[] success = new boolean[ name.length() ]; for( char character: VALID_CHARS ) { for( int index = 0; index &lt; name.length(); index ++ ) { if( name.charAt( index ) == character ) { success[ index ] = true; } } } boolean failed = false; for( boolean b: success ) { if( ! b ) { failed = true; } } System.out.println( "You" + ( failed ? " failed": " succeeded" ) + "." ); } </code></pre> <p>I have an array of valid characters that can be used for a name object, I want to check if each index of the string is valid, if each index is valid return true, otherwise return false. Any help / guidance is appreciated!</p>
[]
[ { "body": "<p>Instead of two for loops and checking the names chars with each char of VALID_CHARS i used one for..loop and check validness by checking, if the name contains the char by using the String.indexOf() method.</p>\n\n<pre><code>public static void main(String[] args) {\n String name = \"hello, ddd\";\n\n boolean failed = false;\n for (int i = 0; !failed &amp;&amp; i &lt; VALID_CHARS.length; i++) {\n failed = (name.indexOf(VALID_CHARS[i]) &lt; 0);\n }\n\n System.out.println(\"You\" + (failed ? \" failed\" : \" succeeded\") + \".\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:06:18.473", "Id": "39955", "ParentId": "39953", "Score": "2" } }, { "body": "<p>memory is surprisingly fast and efficient. If your string-to-test is even modestly large (like 1K), then you may find the following algorithm is efficient. This is especially efficient when the valid-character set is reusable....</p>\n\n<pre><code>boolean[] isvalid = new boolean[Character.MAX_VALUE + 1];\nfor (char c : VALID_CHARS) {\n isvalid[c] = true;\n}\nfor (char c : name) {\n if (!isvalid[c]) {\n System.out.println(\"You failed!.\");\n return;\n }\n}\nSystem.out.println(\"You succeeded!.\");\n</code></pre>\n\n<p>Now, in your case, there is no reason why VALID_CHARS cannot be declared as:</p>\n\n<pre><code>private static final boolean[] VALIDCHARS = buildValidChars();\nprivate static final boolean[] buildValidChars() {\n ....\n}\n</code></pre>\n\n<p>I have used, and benchmarked this sort of system to great effect when building the JDOM Character validator... <a href=\"https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/Verifier.java#L72\">you can see how I did it there....</a> but using a bit-mask representation to use less memory.... which is a bit faster. I also put together a bit of a benchmarh and writeup for the <a href=\"https://github.com/hunterhacker/jdom/wiki/Verifier-Performance\">JDOM Verifier performance</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T20:19:06.687", "Id": "80219", "Score": "0", "body": "It took me a while to figure out how your Verifier class works, but it's a very clever way of mapping the use of each character!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:33:20.063", "Id": "39957", "ParentId": "39953", "Score": "7" } } ]
{ "AcceptedAnswerId": "39957", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T10:30:35.777", "Id": "39953", "Score": "10", "Tags": [ "java", "optimization", "strings", "validation" ], "Title": "Checking if a string matches an array of valid characters" }
39953
<p>Given <em>this kind of code</em>:</p> <pre><code>public static final int DEFAULT_MASK = Mask.BASE | Mask.SECTOR | Mask.GROUP | Mask.INDUSTRY | Mask.NAME | Mask.COUNTRY; </code></pre> <p>Sonar raises a warning:</p> <blockquote> <p>Boolean expression complexity is 5 (max allowed is 3).</p> </blockquote> <p>What would be a <em>good way</em> to deal with this?</p> <p>I suppose the warning <em>might</em> go away if I rewrite like this:</p> <pre><code>public static final int DEFAULT_MASK; static { int tmp = Mask.BASE; tmp |= Mask.SECTOR; tmp |= Mask.GROUP; tmp |= Mask.INDUSTRY; tmp |= Mask.NAME; tmp |= Mask.COUNTRY; DEFAULT_MASK = tmp; } </code></pre> <p>... but this <em>smells</em> (too many mutations, ugly).</p> <p><strong>UPDATE</strong></p> <p>In addition to the default mask above, I have a few other masks as well, using different sets of bits, for different purposes. Every bitmask with more than 3 bits would raise a Sonar violation.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:23:40.547", "Id": "67066", "Score": "5", "body": "In a vacuum, I'd say that your original code is better than your workaround. However, to do a proper code review, we need more context to understand the root cause of the code smell. How will this mask be used?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:32:26.093", "Id": "67067", "Score": "5", "body": "An automated programm will weigh complexity different than a human reader. Here Sonar's mistake is to confuse the bitwise operators on constants (complexity ~ 1) with short-circuiting logical operators on general expressions (complexity ~ n). I did a [write-up on such issues over on programmers](http://programmers.stackexchange.com/a/223625/60357)." } ]
[ { "body": "<p>Without any more information than in your question, this is just a thought. I have no idea what Sonar would say about this approach:</p>\n\n<pre><code>private static final int part1 = Mask.BASE | Mask.SECTOR | Mask.GROUP;\npublic static final int DEFAULT_MASK = part1 | Mask.INDUSTRY | Mask.NAME | Mask.COUNTRY;\n</code></pre>\n\n<p>With good naming of the constants, and if the bitmasks are structured in a good way, this approach <em>might</em> actually be preferable.</p>\n\n<p>However, I really don't think this is much of an issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T12:59:33.970", "Id": "39961", "ParentId": "39956", "Score": "2" } }, { "body": "<p>The first expression in the OP is better than its alternative; and <a href=\"https://codereview.stackexchange.com/questions/39956/boolean-expression-complexity-and-bitwise-operators#comment67067_39956\">as amon said in a comment</a> this warning is IMO a mistake by Sonar.</p>\n\n<p>Therefore, I suggest, see <a href=\"https://stackoverflow.com/questions/10971968/turning-sonar-off-for-certain-code\">Turning Sonar off for certain code</a> on StackOverflow.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T13:48:05.137", "Id": "39963", "ParentId": "39956", "Score": "4" } }, { "body": "<p>You could do something like the following. It may be better or worse depending on what you want to do:</p>\n\n<pre><code>enum Mask {\n BASE(true),\n SECTOR(true),\n GROUP(true),\n ...\n OTHER(false)\n ;\n\n private final isDefault;\n\n private Mask(boolean isDefault) {\n this.isDefault = isDefault;\n }\n\n public boolean isDefault() { return isDefault; }\n\n public boolean intValue() { return 1 &lt;&lt; ordinal(); }\n}\n\npublic static final int DEFAULT_MASK = getDefaultMask();\n\nprivate static int getDefaultMask() {\n int result = 0;\n for (Mask mask : Mask.values()) {\n if (mask.isDefault()) {\n result |= mask.intValue();\n }\n }\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:18:29.797", "Id": "39972", "ParentId": "39956", "Score": "4" } }, { "body": "<p>If it’s a complex bitwise operation, like:</p>\n\n<pre><code>result = a &amp; b | c | d &amp; x &amp; y\n</code></pre>\n\n<p>then it would make perfect sense to raise a violation. On the other hand, this looks like an \"innocent\" bitmask:</p>\n\n<pre><code>mask = a | b | c | d\n</code></pre>\n\n<p>An automated tool cannot judge if this is dangerous or not, so it's understandable to raise a flag for this. But in this particular case, it's clearly a false positive.</p>\n\n<p>I put <code>// NOSONAR</code> on the offending line of code to make the warning go away, like this:</p>\n\n<pre><code>public static final int DEFAULT_MASK = Mask.BASE // NOSONAR\n | Mask.SECTOR\n | Mask.GROUP\n | Mask.INDUSTRY\n | Mask.NAME\n | Mask.COUNTRY;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T10:30:42.637", "Id": "40451", "ParentId": "39956", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T11:10:03.407", "Id": "39956", "Score": "10", "Tags": [ "java", "bitwise" ], "Title": "Boolean expression complexity and bitwise operators" }
39956
<p>When creating objects to be added to a list in Python, we can avoid the <code>if</code> statement by changing our <code>create_object</code> function to return a list.</p> <p>Is this a good idea or not? Why?</p> <p>(assume <code>create_object</code> is called in multiple places and is always added to a list)</p> <pre><code>def _create_object(self, data): if data: return Object(data) if _create_object(data): mylist.append(_create_object(data)) </code></pre> <p>or</p> <pre><code>def _create_object(self, data): if data: return [Object(data)] return [] # Now we no longer need the if mylist += _create_object(data) </code></pre> <p>or (late addition) should we be using exceptions:</p> <pre><code>def _create_object(self, data): if data: return Object(data) raise BadDataException() try: mylist.append(_create_object(data)) except BadDataException: pass </code></pre>
[]
[ { "body": "<p>Avoiding an <code>if</code> statement is not a useful goal. Occasionally it is the correct means towards a goal, such as making code easier to write or to understand. Thus I think your question is too narrowly focused, or oversimplified. The problem here is that the wrapper function <code>_create_object</code> is too simple to merit being its own function, and the complexity outside of it matches that inside.</p>\n\n<p>Let's consider some small transformations of this. First we'll take the <code>if data</code> outside of <code>_create_object</code>. I do this because I find the current implementation is close to do-what-I-mean. This may have been less true if the conditions were more intricate.</p>\n\n<pre><code>def _create_object(data):\n return Object(data)\n\nif data:\n mylist.append(_create_object(data))\n</code></pre>\n\n<p>From there it's pretty obvious that <code>_create_object</code> is another spelling of <code>Object</code>, and the final transformation is to just remove the wrapper:</p>\n\n<pre><code>if data:\n mylist.append(Object(data))\n</code></pre>\n\n<p>Let's take a step further back and assume you're pulling subsequent values of <code>data</code> from a list that I'll call <code>data_source</code>. You can avoid the kind of <code>if</code> statement you had before by writing either a list comprehension (with embedded if), or using <code>filter</code>:</p>\n\n<pre><code>mylist += [Object(data) for data in data_source if data]\n# or\nmylist += [Object(data) for data in filter(None, data_source)]\n# or, if _create_object's conditions are too complex for this transformation\nmylist += [_create_object(data) for data in data_source if _create_object(data)]\n# or, two-layers\nmylist += filter(None, [_create_object(data) for data in data_source])\n</code></pre>\n\n<p>Note that I don't particularly like the third as it calls <code>_create_object</code> twice per item, but the fourth one requires your second wrapper - the one that returns <code>None</code>.</p>\n\n<p>As for whether you should be using exceptions, the answer is two-fold. If you're dealing with a large number of false values in <code>data</code>, and this is in an inner loop, performance could be a problem. In cases like that, it can make sense to implement the look-before-you-leap semantics of your other examples. However, if <code>Object</code> cannot reasonably construct itself from a false <code>data</code> parameter, it should itself raise an exception. That way if a given caller doesn't check first, it will result in a clear fixable error.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:10:19.070", "Id": "67167", "Score": "0", "body": "Its not quite that simple. There are several parameters like data and several conditions to check. I'd like to have the conditions inside the create_object function to stop me forgetting a check when I'm in a loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T13:07:12.993", "Id": "39962", "ParentId": "39959", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T12:05:18.210", "Id": "39959", "Score": "2", "Tags": [ "python" ], "Title": "Creating objects to be added to a list" }
39959
<p>A couple of hours ago I asked a question on Stackoverflow to find out if there is <a href="https://stackoverflow.com/questions/21328328/delete-files-only-if-all-are-deletable-spare-the-innocent">a good way to delete files in a folder only if all files are indeed deletable</a> and I got some good answers that led me (I think) in the right direction</p> <p>Based on the two currently most upvoted answers I scrambled together the following code:</p> <pre><code>import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileLock; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { File directory = new File("T:\\download\\test\\1234"); if (safeDelete(directory)) { System.out.println("All deleted"); } else { System.out.println("All kept"); } } private static boolean safeDelete(File directory) { if (directory == null || !directory.isDirectory() || !directory.canWrite()) { return false; } // First get a lock on the directory itself FileLock dirLock; if ((dirLock = getLock(directory)) == null) { return false; } List&lt;File&gt; filesToDelete = new ArrayList&lt;&gt;(); List&lt;FileLock&gt; fileLocks = new ArrayList&lt;&gt;(); // Get a lock on all the files in the folder for (File file : directory.listFiles()) { FileLock lock; if (file.canWrite() &amp;&amp; ((lock = getLock(file)) != null)) { filesToDelete.add(file); fileLocks.add(lock); } else { System.out.println("Currently unable to write to " + file.getName()); releaseLocks(fileLocks); return false; } } // If we reach this line all the files are locked for us now for (File file : filesToDelete) { if (!file.delete()) { System.out.println("IMPOSSIBLE"); } } releaseLocks(fileLocks); directory.delete(); releaseLock(dirLock); return true; } private static FileLock getLock(File file) { try { return new RandomAccessFile(file, "rw").getChannel().tryLock(); } catch (IOException ex) { System.out.println(ex.toString()); return null; } } private static void releaseLocks(List&lt;FileLock&gt; locks) { for (FileLock lock : locks) { releaseLock(lock); } } private static void releaseLock(FileLock lock) { if (lock != null) { try { lock.release(); System.out.println("Released lock on " + lock.toString()); } catch (IOException ex) { System.out.println("Cant release lock on " + lock.toString()); } } } } </code></pre> <p>But it seems so... bulky to me. There are many return statements in there (I personally like it better when there is only one at the very end), a lot of if-else branching, two <code>ArrayList</code>s that manage almost the same stuff and a lot of calls to the <code>releaseLocks()</code> method.</p> <p>The core problem is in my opinion that I have to manage two sets of data on which I both have to operate: </p> <ul> <li>The Files on which I have to execute the deletion</li> <li>And the Locks which I have to release after I'm done</li> </ul> <p>So the question is:<br><strong>Can this be done more efficiently?</strong> Should I refactor the <code>safeDelete()</code> into more sub-methods?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T12:20:18.783", "Id": "67072", "Score": "0", "body": "Try to rename the whole directory, if that works, create a directory with the old name and delete the moved one. Of course assumes that the OS does not do something fishy with filelocks upon moving..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T12:24:20.063", "Id": "67073", "Score": "0", "body": "you might want to put this as an answer on SO, right now I'm intrigued by the method above and I'd really appreciate a review on this :)" } ]
[ { "body": "<p>Why not use a class to hold both the file and the lock, so you don`t need to manage two Lists like:</p>\n\n<pre><code>public class SafeDirectory {\n\n private File directory = null;\n private FileLock lock = null;\n private List&lt;SafeFile&gt; deleteableSafeFiles = new ArrayList&lt;&gt;();\n\n public SafeDirectory(String directoryPath) {\n directory = new File(directoryPath);\n }\n\n public boolean CanBeDeleted() {\n boolean canBeDeleted = false;\n if (directory != null &amp;&amp; directory.canWrite() &amp;&amp; directory.isDirectory()\n &amp;&amp; ((lock = getLock(directory)) != null)) {\n\n canBeDeleted = true;\n for (File file : directory.listFiles()) {\n SafeFile safeFile = new SafeFile(file);\n\n if (safeFile.CanBeDeleted()) {\n deleteableSafeFiles.add(safeFile);\n } else {\n canBeDeleted = false;\n System.out.println(\"Currently unable to write to \"\n + file.getName());\n RelaseLock();\n break;\n }\n }\n\n }\n return canBeDeleted;\n }\n\n public boolean Delete() {\n for (SafeFile safeFile : deleteableSafeFiles) {\n safeFile.Delete();\n }\n directory.delete();\n\n RelaseLock();\n return true;\n }\n\n private void RelaseLock() {\n for (SafeFile safeFile : deleteableSafeFiles) {\n releaseLock(safeFile.lock);\n }\n releaseLock(lock);\n }\n\n private boolean releaseLock(FileLock lock) {\n if (lock != null) {\n try {\n lock.release();\n System.out.println(\"Released lock on \" + lock.toString());\n return true;\n } catch (IOException ex) {\n System.out.println(\"Cant release lock on \" + lock.toString());\n return false;\n }\n }\n return true;\n\n }\n\n private static FileLock getLock(File file) {\n try {\n return new RandomAccessFile(file, \"rw\").getChannel().tryLock();\n\n } catch (IOException ex) {\n System.out.println(ex.toString());\n return null;\n }\n }\n\n private class SafeFile {\n\n private FileLock lock = null;\n private File file = null;\n\n SafeFile(File file) {\n this.file = file;\n }\n\n boolean CanBeDeleted() {\n return (file.canWrite() &amp;&amp; ((lock = SafeDirectory.getLock(file)) != null));\n }\n\n boolean Delete() {\n return file.delete();\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:04:40.590", "Id": "39964", "ParentId": "39960", "Score": "3" } } ]
{ "AcceptedAnswerId": "39964", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T12:05:49.100", "Id": "39960", "Score": "5", "Tags": [ "java", "optimization", "locking" ], "Title": "Operations on files and their locks - code too bulky?" }
39960
<p>See <a href="http://en.wikipedia.org/wiki/Multiton_pattern" rel="nofollow noreferrer">Wikipedia - Multiton Pattern</a> for details on the intent.</p> <p>Here's the class:</p> <pre><code>/** * Holds a thread-safe map of unique create-once items. * * Contract: * * Only one object will be made for each key presented. * * Thread safe. * * @param &lt;K&gt; * @param &lt;V&gt; */ public class Multiton&lt;K, V&gt; { // Map from the key to the futures of the items. private final ConcurrentMap&lt;K, Future&lt;V&gt;&gt; multitons = new ConcurrentHashMap&lt;K, Future&lt;V&gt;&gt;(); // A Prayer is used to construct the Callable that is attached to the FutureTask. private final Prayer prayer; public Multiton(Creator&lt;K, V&gt; creator) { // Create the prayer to the creator. this.prayer = new Prayer(creator); } /** * There can be only one. * * Use a FutureTask to do the creation to ensure only one construction. * * @param key * @return * @throws InterruptedException * @throws ExecutionException */ public V getInstance(final K key) throws InterruptedException, ExecutionException { // Already made? Future&lt;V&gt; f = multitons.get(key); if (f == null) { // Plan the future but do not create as yet. FutureTask&lt;V&gt; ft = new FutureTask&lt;V&gt;(prayer.pray(key)); // Store it. f = multitons.putIfAbsent(key, ft); if (f == null) { // It was successfully stored - it is the first (and only) f = ft; // Make it happen. ft.run(); } } // Wait for it to finish construction and return the constructed. return f.get(); } /** * Use a Prayer to pass the key to the Creator. * * @param &lt;K&gt; * @param &lt;V&gt; */ private class Prayer { private final Creator&lt;K, V&gt; creator; public Prayer(Creator&lt;K, V&gt; creator) { this.creator = creator; } public Callable&lt;V&gt; pray(final K key) { return new Callable&lt;V&gt;() { @Override public V call() throws Exception { return creator.create(key); } }; } } /** * User provides one of these to do the construction. * * @param &lt;K&gt; * @param &lt;V&gt; */ public abstract static class Creator&lt;K, V&gt; { // Return a new item under the key. abstract V create(K key) throws ExecutionException; } } </code></pre> <p>I use it to ensure I only create one <code>JAXBContex</code> for each class:</p> <pre><code>/** * Create just one JAXB context for each class. */ private static final Multiton&lt;Class, JAXBContext&gt; contexts = new Multiton&lt;Class, JAXBContext&gt;(new Creator&lt;Class, JAXBContext&gt;() { @Override JAXBContext create(Class key) throws ExecutionException { try { // Get it out of my Multiton return JAXBContext.newInstance(key); } catch (JAXBException ex) { // Pass it back as an Execution Exception. throw new ExecutionException("Failed to create JAXB Context for class "+key.getName(), ex); } } }); /** * Uses a Multiton to create a JAXB context for the object. * * @param it - The object to create the context for. * @return - the unique JAXB context. * @throws InterruptedException - Interrupted. * @throws ExecutionException - Something else went wrong (cause is wrapped) */ private static JAXBContext createJAXBContext(Object it) throws InterruptedException, ExecutionException { return contexts.getInstance(it.getClass()); } </code></pre> <h2>My Questions:</h2> <ol> <li>Is this a <code>Multiton</code> as described by the article? I.e. Will it only ever create just <strong>one</strong> instance of the object?</li> <li>Is it thread-safe?</li> <li>Am I being offensive using a <code>Prayer</code> object to request an object from the <code>Creator</code>?</li> <li>If the answer to 3 is no - should I make my <code>create</code> method of the <code>Creator</code> take a <code>Prayer</code> as a parameter rather than a <code>K key</code> - just for the belly laugh of course?</li> </ol> <p>NB: The idea of using a <code>FutureTask</code> came from a nice answer by <a href="https://stackoverflow.com/users/829571/assylias">assylias</a> on <a href="https://stackoverflow.com/a/18149547/823393">thread-safe multitons</a>. All I've really done is make it generic and plumbed in the ability to pass a <code>Creator</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:28:32.353", "Id": "67080", "Score": "0", "body": "Hmmm, a `Prayer` class with a `prey` method. Now that's not the same thing, is it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:29:16.440", "Id": "67081", "Score": "0", "body": "I'd call it a 'Factory' class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:30:38.143", "Id": "67082", "Score": "0", "body": "@ChrisW - agreed - but that wouldn't be funny any more. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:31:22.567", "Id": "67083", "Score": "0", "body": "@SimonAndréForsberg - should we then perhaps `offer` a prayer? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:33:48.843", "Id": "67084", "Score": "2", "body": "Or we could call the method `pray`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:40:36.323", "Id": "67087", "Score": "0", "body": "@SimonAndréForsberg - Ah!!! Fixed that - thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:56:26.473", "Id": "67088", "Score": "3", "body": "Hmm I thought \"multiton\" was something that weighted several tons. lol.upvoted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:14:29.217", "Id": "67089", "Score": "2", "body": "@lol.upvote - do I not get a lol.upvote for *gratuitous use of methods of communications with deities in Java*?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:24:16.847", "Id": "67091", "Score": "0", "body": "@OldCurmudgeon that went without saying :)" } ]
[ { "body": "<p>I think your use-case and the Wiki description are different. Technically, the Multiton should return the exact same intance for the exact same key, always, but, because your <code>multitons</code> Map is not a <code>static</code> instance, you can simply create multiple instances of the <code>Multiton</code> and each one will generate different instances for the same key.</p>\n\n<p>This is OK in your case, because you create a <code>private static final</code> anonymous implementation of the class.... so you handle that problem at a higher level.</p>\n\n<p>I think, otherwise, the algorithm is good.... (i.e. it will work as advertised).</p>\n\n<p>There are two changes I can recommend....</p>\n\n<ol>\n<li><p>Why is the <code>Creator&lt;K,V&gt;</code> a <code>public abstract static</code> class? This is a broken pattern, and it should simply be an interface <code>public interface Creator&lt;K,V&gt;</code></p></li>\n<li><p>This is complicated, the rest of the answer is about change 2....</p></li>\n</ol>\n\n<p>I believe you have unnecessary indirection. Your inner class:</p>\n\n<blockquote>\n<pre><code> private class Prayer {\n private final Creator&lt;K, V&gt; creator;\n\n public Prayer(Creator&lt;K, V&gt; creator) {\n this.creator = creator;\n }\n\n public Callable&lt;V&gt; pray(final K key) {\n return new Callable&lt;V&gt;() {\n\n @Override\n public V call() throws Exception {\n return creator.create(key);\n }\n\n };\n }\n\n }\n</code></pre>\n</blockquote>\n\n<p>This is overkill.... if you make the Prayer class <em>Extend</em> Callable, you win:</p>\n\n<pre><code> private class Prayer implements Callable&lt;V&gt; {\n private final K key;\n\n public Prayer(K key) {\n this.key = key;\n }\n\n @Override\n public V call() throws Exception {\n // creator is accessible as a final field on the Multiton instance.\n return creator.create(key);\n }\n\n }\n</code></pre>\n\n<p>Then, instead of keeping a final instance to <code>Prayer</code> in your main class:</p>\n\n<blockquote>\n<pre><code>private final Prayer prayer;\n</code></pre>\n</blockquote>\n\n<p>you should instead hold the simple Creator:</p>\n\n<pre><code>private final Creator&lt;K,V&gt; creator;\n</code></pre>\n\n<p>And, instead of calling <code>prayer.pray()</code>, you only need do:</p>\n\n<pre><code>FutureTask&lt;V&gt; ft = new FutureTask&lt;V&gt;(new Prayer(key));\n</code></pre>\n\n<p><strong>Note:</strong> It is much better to request a <code>new Prayer(...)</code> than it is to demand one with <code>prayer.pray()</code> !!!</p>\n\n<hr>\n\n<p>Hope this all makes sense.... I have reworked your original code as:</p>\n\n<pre><code>import java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.FutureTask;\n\npublic class Multiton&lt;K, V&gt; {\n // Map from the key to the futures of the items.\n private final ConcurrentMap&lt;K, Future&lt;V&gt;&gt; multitons = new ConcurrentHashMap&lt;K, Future&lt;V&gt;&gt;();\n // A Creator is used to construct the Callable that is attached to the FutureTask.\n private final Creator&lt;K,V&gt; creator;\n\n public Multiton(Creator&lt;K, V&gt; creator) {\n this.creator = creator;\n }\n\n /**\n * There can be only one.\n * \n * Use a FutureTask to do the creation to ensure only one construction.\n * \n * @param key\n * @return\n * @throws InterruptedException\n * @throws ExecutionException \n */\n public V getInstance(final K key) throws InterruptedException, ExecutionException {\n // Already made?\n Future&lt;V&gt; f = multitons.get(key);\n if (f == null) {\n // Plan the future but do not create as yet.\n FutureTask&lt;V&gt; ft = new FutureTask&lt;V&gt;(new Prayer(key));\n // Store it.\n f = multitons.putIfAbsent(key, ft);\n if (f == null) {\n // It was successfully stored - it is the first (and only)\n f = ft;\n // Make it happen.\n ft.run();\n }\n }\n // Wait for it to finish construction and return the constructed.\n return f.get();\n }\n\n /**\n * Use a Prayer to pass the key to the Creator.\n *\n * @param &lt;K&gt;\n * @param &lt;V&gt;\n */\n private class Prayer implements Callable&lt;V&gt; {\n private final K key;\n\n public Prayer(K key) {\n this.key = key;\n }\n\n @Override\n public V call() throws Exception {\n return creator.create(key);\n }\n\n }\n\n /**\n * User provides one of these to do the construction.\n * \n * @param &lt;K&gt;\n * @param &lt;V&gt; \n */\n public interface Creator&lt;K, V&gt; {\n // Return a new item under the key.\n abstract V create(K key) throws ExecutionException;\n\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:52:47.050", "Id": "67095", "Score": "0", "body": "On the `abstract/interface` point - you are absolutely correct. Fixed that now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:57:13.570", "Id": "67097", "Score": "0", "body": "On the `Prayer.pray/Prayer implements Callable` question - I did it this way to minimise the gratuitous construction of objects. My technique will **only** create a `Callable` **once** for each actual construction. Yours may create more than one under a thread storm. I accept that yours is neater and at a trivial cost so I suspect it is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:00:29.740", "Id": "67100", "Score": "0", "body": "@OldCurmudgeon - respectfully, I disagree with your assertion that you were only creating one Callable in a storm... every time you called `pray()` you created a Callable... This is no different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:12:06.273", "Id": "67102", "Score": "0", "body": "Agreed - but `pray` will only be called when the `FutureTask` is **run** so it won't be called if the `putIfAbsent` finds it present. You are creating a new `Prayer` for every `FutureTask`, I create a new `Prayer` for each `Multiton`. My argument is trivial because we create a new `FutureTask` every time anyway so I am not saving anything much and the gain in cleanliness with your solution outweighs that to my mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:32:47.817", "Id": "67105", "Score": "0", "body": "@OldCurmudgeon - hate to labour it... sure, in my version, Prayer **is** a Callable, in yours, it **generates** a callable. We both create a new Callable at the exact same point. In your case, `new FutureTask<V>(prayer.pray(key))`. here `prayer.pray(key)` creates an anonymous Callable instance. In my case, I do `new FutureTask<V>(new Prayer(key))`, which **is** a Callable. It is important you understand your own logic (not because I'm bashing you on this 'just because')... Perhaps join us in [the 2nd monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:30:37.100", "Id": "39973", "ParentId": "39965", "Score": "4" } } ]
{ "AcceptedAnswerId": "39973", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:11:21.437", "Id": "39965", "Score": "11", "Tags": [ "java", "thread-safety", "multiton" ], "Title": "Utilization of the Multiton pattern" }
39965
<p>See <a href="http://en.wikipedia.org/wiki/Multiton_pattern" rel="nofollow">Wikipedia - Multiton Pattern</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:14:08.137", "Id": "39966", "Score": "0", "Tags": null, "Title": null }
39966
In software engineering, the multiton pattern is a design pattern similar to the singleton, which allows only one instance of a class to be created. The multiton pattern expands on the singleton concept to manage a map of named instances as key-value pairs.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:14:08.137", "Id": "39967", "Score": "0", "Tags": null, "Title": null }
39967
<p>The first piece of code should cover the standard expected data. But as you can easily see, the data not always conveys to this standard. The code works great but I wonder if this is thought be a miss-use of the try/except clause. Better to go with if/else? </p> <pre><code>try: short_name = short_name.upper() m = (k for k,v in c.countries_dict.iteritems() if v[0] == short_name).next() m = [m] except StopIteration: if re_type == 'MAP_INFO' or re_type == 'SHAPE' or re_type == 'ARC_INFO': reg_dict = REGIONS short_name = short_name.lower() elif re_type == 'NAV_SHAPE': reg_dict = NAV_REGIONS short_name = short_name.upper() m = [] for k,v in reg_dict.iteritems(): if k == short_name: for tup in v: m.append(tup[1]) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:44:50.687", "Id": "67108", "Score": "2", "body": "Can you provide something that can be executed/tested properly and/or some information about the intended purpose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:46:09.073", "Id": "67197", "Score": "0", "body": "Is the code underneath yielding bad data? Or is it using StopIteration to signal 'I'm done'? Or to indicate that some data source has gone offline?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T04:19:28.593", "Id": "67223", "Score": "0", "body": "@theodox I think it's to indicate the value was not found." } ]
[ { "body": "<p>I would discourage this particular usage. Not exactly because it's a risk or a hack—in other circumstances it might even be the right choice for good performance—but because I find it quite obfuscatory. (This happens to echo the usual guidance to avoid using exceptions for flow control, although it's harder to apply that guidance around Python's iterators.)</p>\n\n<p>Instead I would suggest trying to make it clear what you are doing. I believe in this case you are trying to find the \"first\" key that maps to a list of values containing <code>short_name</code> in index 0. (I say \"first\" because it's in dictionary order, which isn't a particularly meaningful; it's probably more useful to say <em>an arbitrary key</em>.) If such a key does not exist, you wish to fall through to your except case. A reader is going to find that motive hard to discern. Here is an alternative way to write the first couple lines using itertools:</p>\n\n<pre><code>from itertools import islice\n\nshort_name = short_name.upper()\n# find a key of an item containing short_name, if available\nm = list(islice((k for k,v in c.countries_dict.iteritems() if v[0] == short_name), 1))\nif not m:\n # due to bad data, not all short_name values are mapped correctly; try another way\n # code from original except StopIteration\n</code></pre>\n\n<p>For bonus readability you might split that up into a named generator function that finds all matches, and then filter to the first match with <code>islice</code> or another helper. Clearly performance isn't your goal here, as you're scanning a dict by value. (If you have a lot of these to look up, you may want to create the reverse dict instead of scanning multiple times.)</p>\n\n<p>I'm far from certain that this code is what you intended. Since in the fallback case you build up a list of potentially multiple values, it seems surprising that in the primary case you explicitly exclude alternate keys. If you wanted to include all keys, you can skip <code>islice</code> and use a simple list comprehension: (Note that by slicing the list comprehension with <code>[:1]</code>, it would yield the same value for <code>m</code> as the previous approach, and is more readable, although it potentially does more work.)</p>\n\n<pre><code>short_name = short_name.upper()\nm = [k for k,v in c.countries_dict.iteritems() if v[0] == short_name]\nif not m:\n # due to bad data, not all short_name values are mapped correctly; try another way\n # code from original except StopIteration\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T07:16:16.523", "Id": "67234", "Score": "0", "body": "Rather than `islice` with 1, I'd use the default argument to `next`, and write `m = next((k for k,v in c.countries_dict.iteritems() if v[0] == short_name), None)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T14:02:17.220", "Id": "67264", "Score": "0", "body": "@DSM Thanks for bringing this up. I agree `next(iterable, default)` itself is a better way to write the operation, but it seems to communicate a subtly different intent than the \"give me at most one\" of `islice(iterable, 1)`. Since my review focused on communicating intent, I went with the `islice`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:44:46.337", "Id": "67339", "Score": "0", "body": "Thanks @MichaelUrman, very helpful answer. It is true that the generator should yield exactly one value from the dict. That is the default. But there are other data sources that won't have corresponding key/value pair in `c.countries_dict`. I agree that this is somewhat obfuscatory. I appreciate your thoughts on the matter." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T04:18:00.870", "Id": "40021", "ParentId": "39969", "Score": "6" } } ]
{ "AcceptedAnswerId": "40021", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T14:41:57.877", "Id": "39969", "Score": "4", "Tags": [ "python", "exception" ], "Title": "Generator expression in combination with StopIteration: kind of a hack?" }
39969
<p>I recently came across code that looked something like this (generates 4 random numbers in an array, this is not the actual code, I just wrote this up now, so it's untested):</p> <pre><code>var uniqueNumbers = new Array(); var count = 4; var max = 10; function main() { for (var i = 0; i &lt; count; i++) { do { var tempNum = Math.floor(Math.random() * max); //number 0-9 } while (arrayContains(uniqueNumbers, tempNum)) uniqueNumbers.push(tempNum); } } function arrayContains(a, val) { for (var i = 0; i &lt; a.length; i++) { if (a[i] == val) return true; } return false; } </code></pre> <p>Is it possible that the <code>while</code> loop could possibly be infinite (or at least take a lot of time)? In the way that it just so happens that we continuously randomly choose a number that happens to be in the array? I imagine the probability of this happening would go up as <code>count</code> increases. It's kind of reminding me of bogosort.</p> <p>I would think that this would be improved by selecting from a diminishing 'pool' of numbers, instead of selecting randomly, something like:</p> <pre><code>var uniqueNumbers = new Array(); var count = 4; var max = 10; var pool = new Array(); function main() { createPool(); for (var i = 0; i &lt; count; i++) { if (var tempNum = selectFromPool()) { uniqueNumbers.push(tempNum); } } } function createPool() { for (var i = 0; i &lt; max; i++) { pool.push(i); } } function selectFromPool() { if (pool.length &lt;= 0) return false; var selectedIndex = Math.floor(Math.random() * pool.length); var selectedValue = pool[selectedIndex]; pool = pool.slice(selectedIndex, selectedIndex+1); return selectedValue; } </code></pre> <p>Is this a better, less fragile way of doing it? Or is there some proof that the <code>while</code> loop will never be infinite because of the pseudo-random nature of computer generated random numbers?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:33:53.887", "Id": "67092", "Score": "0", "body": "In the first code, you should use a [do...while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:35:49.650", "Id": "67093", "Score": "0", "body": "@ANeves I see that, but nature of the loop in regards to the question wouldn't change, it would still have a possibility of running for a long time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:23:36.317", "Id": "67104", "Score": "0", "body": "It would make sense to add an additional debug array to your code, and store the actual random (or not random) values that you are trying to generate, and then see for yourself why the loop is failing to exit." } ]
[ { "body": "<p>Your first attempt is indeed in danger of getting into an infinite loop if a certain value never gets returned from rand (but any half decent PRNG will return all of them eventually).</p>\n\n<p>Your second attempt is very close to the (most optimal) <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow\">Fisher-Yates shuffle</a>, with the difference that you use a separate array to store the shuffled result while shrinking the original pool.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:05:09.303", "Id": "67101", "Score": "0", "body": "\"(but any half decent PRNG will return all of them eventually)\" I think this is what I'm looking for proof for, if it exists anywhere (even just in an algorithm for how prngs work)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T16:33:18.427", "Id": "67106", "Score": "1", "body": "@Esaevian keyword here is distribution, the most common PRNG the linear congruent generator will emit all possible values in a cycle the length of 2^seed_bits" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:56:54.153", "Id": "39974", "ParentId": "39970", "Score": "2" } }, { "body": "<p>It depends on the proportions of <code>count</code> and <code>max</code>, obviously, but most importantly on the behaviour of the random number generator. ECMAScript leaves the behaviour of random() to the implementation, so there's no immediate answer; it would be platform dependent. </p>\n\n<p>Expressed in Python, because it lets me have less fluff around the algorithm, your two algorithms are basically:</p>\n\n<pre><code>def algo1(count, max):\n l=[]\n while len(l)&lt;count:\n x=random.randint(1,max)\n # Might take forever to find an x that fits, particularly if n&gt;m\n if x not in l:\n l.append(x)\n return l\n\ndef algo2(count, max):\n choices=range(1,max+1)\n l=[]\n # Python also has random.sample for this operation\n while len(l)&lt;count:\n x=random.choice(choices) # Can't pick anything in l\n choices.remove(x) # because it is removed here\n l.append(x) # also will run out if count&gt;max\n return l\n</code></pre>\n\n<p>A third algorithm comes to mind which may be useful if random numbers are costly and <code>max</code> is large:</p>\n\n<pre><code>def algo3(count, max):\n assert count&lt;=max\n l=[]\n while len(l)&lt;count:\n x=random.randint(1,max-len(l))\n for y in sorted(l):\n if y&lt;=x:\n x+=1\n l.append(x)\n return l\n</code></pre>\n\n<p>This version completes in O(n²) time, with limited memory usage and only <code>count</code> random calls. If <code>count&gt;max</code> only the first <code>max</code> elements are randomly ordered; the rest are simply an incrementing series. That's unexpected behaviour, so a guard makes sense. </p>\n\n<p>As for the <a href=\"https://en.wikipedia.org/wiki/Random_number_generation\" rel=\"nofollow\">random number generation</a> itself, that's a rather complex field. The Linux man page for random(3) suggested a book (Numerical Recipes in C: The Art of Scientific Computing) with a chapter on that topic. </p>\n\n<p>A rather infamous example of failing to devise a fair algorithm for this - which also did show the browser dependency in Javascript - is the browser ballot that resulted after a judgement against Microsoft regarding anti-competitive practices in the web browser integration for Windows. Rob Weir's article <a href=\"http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html\" rel=\"nofollow\">Doing the Microsoft Shuffle: Algorithm Fail in Browser Ballot</a> covers the details, and is an interesting read. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:04:59.393", "Id": "39975", "ParentId": "39970", "Score": "2" } }, { "body": "<p>The first method can definitely go into a very long loop, but that is very unlikely to happen. Unless the numbers to pick is not very close to the available numbers, the probability that the loop would be so long that it would be noticable is very small.</p>\n\n<p>If you for example pick 5 numbers out of 10, there is still only a probability of 1 in 1267650600228229401496703205376 that it would go as far as 100 iterations when picking the fifth number.</p>\n\n<p>This is getting into the same range of probability as getting two GUID values that would happen to be the same, and that is considered so unlikely that it in practice never happens.</p>\n\n<p>Still, the second method gives a more predictable performance, so that is preferred unless you would have a huge pool of numbers to pick from. In that case creating the pool would use so much resources that the first method should be considered.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T17:32:55.587", "Id": "39977", "ParentId": "39970", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T15:08:48.977", "Id": "39970", "Score": "5", "Tags": [ "javascript", "random" ], "Title": "Could random unique selection using while cause an infinite loop?" }
39970
<p>I'm looking for suggestions on how to select properties on the child level or deeper dynamically. </p> <p>For example, here is the method that I am currently using. The method parameters is the <code>object</code> and either a <code>string</code> or <code>array</code> for the property name. If a <code>string</code> is passed used, it will just will get the property. The array is iterated through in order to select the property value.</p> <pre><code>getMappedDataProperty: function(obj, map) { var m, result, _i, _len; if (typeof map === 'string') { return obj[map]; } result = obj; for (_i = 0, _len = map.length; _i &lt; _len; _i++) { m = map[_i]; result = result[m]; } return result; } </code></pre> <p>Even though this works, I keep thinking to myself that there has to be a better way of accomplishing this. Suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:37:53.100", "Id": "67123", "Score": "0", "body": "That is a really roundabout way of doing things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:32:47.567", "Id": "67139", "Score": "0", "body": "[Here's how I've done it in the past](https://gist.github.com/megawac/6162481#file-underscore-lookup-js), however I extended it to convert `'foo.bar[0]' => ['foo', 'bar', '0']`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:14:09.070", "Id": "67155", "Score": "0", "body": "@megawac I like the idea of passing in the string 'foo.bar' then splitting it into the array. Might make better sense for the user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T10:35:53.943", "Id": "67251", "Score": "0", "body": "Looks like you're re-inventing JsonPath. I did that once for MVC-style property objects. See http://goessner.net/articles/JsonPath/" } ]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li><p><code>getMappedDataProperty</code> is a clumsy name, how about <code>getProperty</code>.</p></li>\n<li><p>receiving a string is functionally the same as an array with 1 entry, so you could <br>\n<code>map = (typeof map === 'string') ? [map] : map;</code></p></li>\n<li><p>There is no need for the underscores for <code>i</code> and <code>len</code>, also, I would rather see <code>length</code> than <code>len</code></p></li>\n<li><p>the use of the temporary variable <code>m</code> is overkill, you could go straight for<br> <code>result = result[map[i]];</code></p></li>\n</ul>\n\n<p>I would counter propose:</p>\n\n<pre><code>getProperty: function( o, map ) \n{\n map = (typeof map === 'string') ? [map] : map.slice();\n var result = o;\n while ( map.length ) {\n result = result[ map.shift() ];\n }\n return result;\n}\n</code></pre>\n\n<p>I would love to know the context in which you use this, since I cannot see a good use case for it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:07:58.950", "Id": "67154", "Score": "0", "body": "Good point on the name. Didn't think about the while loop working for just one in the array. Why do you have the `map.slice()` in the example on the third line?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:31:28.113", "Id": "67161", "Score": "0", "body": "I marked as answered, but would still like to see others opinions about this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:34:46.377", "Id": "67163", "Score": "0", "body": "To answer what I am doing: I created a generic filter that will output a flat array of a specific property value of the dataset. The issue is that some of the properties are at the child level and others at a grandchild level. Needed to handle getting for both levels." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:45:13.313", "Id": "39988", "ParentId": "39979", "Score": "2" } }, { "body": "<p>I'm going to suggest on top of @konijn's changes that:</p>\n\n<ol>\n<li>You shouldn't clone the <code>map</code> as that's just extra overhead as is using shift. I prefer your earlier attempt of just iterating the keys to be honest.</li>\n<li>You should check if <code>result[map[i]]</code> exists before you attempt to access it. So <code>getProperty({}, ['foo', 'bar'])</code> won't attempt to access <code>result['foo'] =&gt; undefined['bar']</code>. As I mentioned in a comment on the OP I've previously implemented this method and I handled this case by returning <code>undefined</code> but at the bare minimum you should acknowledge it.</li>\n<li>I would also suggest you handle numbers in your implementation.</li>\n</ol>\n\n<p>I would suggest an implementation along the lines of:</p>\n\n<pre><code>getProperty: function(result, map) {\n var type = typeof map, i = 0, len = map.length;\n if (type === 'string' || type === 'number') return result[map];\n for (; i &lt; len; i++) {\n if(map[i] in result) result = result[map[i]];\n else return undefined;\n }\n return result;\n}\n</code></pre>\n\n<p>Later if you decide to handle a map string like <code>'foo.bar'</code> it would also be easy to extend this implementation (and it'd start to look even more <a href=\"https://gist.github.com/megawac/6162481#file-underscore-lookup-js\" rel=\"nofollow\">like mine</a> lol). All it would take is adapting the string case to <code>map = map.toString().split('.')</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:32:36.083", "Id": "67182", "Score": "0", "body": "+1, I forgot about the fact that the function is very trusting!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:12:43.487", "Id": "40004", "ParentId": "39979", "Score": "2" } } ]
{ "AcceptedAnswerId": "39988", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:17:59.223", "Id": "39979", "Score": "2", "Tags": [ "javascript" ], "Title": "What is the best to select a javascript object property at any depth?" }
39979
<p>This is my program code for comparing if 2 images are the same. It basically uses the open dialog and opens 1 image at a time and puts it in 1 picture box. </p> <p>I heard that <code>GetPixel()</code> method may be slow. Is there a more efficient and faster way to compare 2 if 2 images are the same?</p> <pre><code>Bitmap image1 = null; Bitmap image2 = null; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) //first image open { OpenFileDialog openDialog = new OpenFileDialog(); if (openDialog.ShowDialog() == DialogResult.OK) { image1 = new Bitmap(openDialog.FileName); pictureBox1.Image = image1; } } private void button2_Click(object sender, EventArgs e) //second image open { OpenFileDialog openDialog = new OpenFileDialog(); if (openDialog.ShowDialog() == DialogResult.OK) { image2 = new Bitmap(openDialog.FileName); pictureBox2.Image = image2; } } private void button3_Click(object sender, EventArgs e) //compare button { if (compare(image1, image2)) { MessageBox.Show("Same Image."); } else { MessageBox.Show("Different Image."); } } private bool compare(Bitmap bmp1, Bitmap bmp2) { bool equals = true; bool flag = true; //Inner loop isn't broken //Test to see if we have the same size of image if (bmp1.Size == bmp2.Size) { for (int x = 0; x &lt; bmp1.Width; ++x) { for (int y = 0; y &lt; bmp1.Height; ++y) { if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y)) { equals = false; flag = false; break; } } if (!flag) { break; } } } else { equals = false; } return equals; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:45:09.140", "Id": "67124", "Score": "1", "body": "Note that `Bitmap` inherits from `Image`, which implements `IDisposable`. This means you very much better call `Dispose()` on those objects are you are done with them (way many paths here with UI event handlers), or put them into `using` blocks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:48:12.637", "Id": "67125", "Score": "1", "body": "Oh, and same goes for `OpenFileDialog`. I'll probably post an answer to show some of this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-02T20:06:50.547", "Id": "174483", "Score": "1", "body": "See ImageComparer.Compare method. Has overloads to specify tolerance.\nIt is available since VS2102. https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.imagecomparer.compare.aspx" } ]
[ { "body": "<p>You can use the <code>LockBits</code> method and pointers to access the image data directly.</p>\n\n<p>Example for 24 bpp images:</p>\n\n<pre><code>bool equals = true;\nRectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);\nBitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);\nBitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp2.PixelFormat);\nunsafe {\n byte* ptr1 = (byte*)bmpData1.Scan0.ToPointer();\n byte* ptr2 = (byte*)bmpData2.Scan0.ToPointer();\n int width = rect.Width * 3; // for 24bpp pixel data\n for (int y = 0; equals &amp;&amp; y &lt; rect.Height; y++) {\n for (int x = 0; x &lt; width; x++) {\n if (*ptr1 != *ptr2) {\n equals = false;\n break;\n }\n ptr1++;\n ptr2++;\n }\n ptr1 += bmpData1.Stride - width;\n ptr2 += bmpData2.Stride - width;\n }\n}\nbmp1.UnlockBits(bmpData1);\nbmp2.UnlockBits(bmpData2);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:57:49.193", "Id": "67126", "Score": "0", "body": "I assume I drag this in my `compare()` method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:13:26.340", "Id": "67131", "Score": "0", "body": "@puretppc: Yes, that is correct. After checking that the images have the same size and the correct pixel format." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:16:30.983", "Id": "67133", "Score": "0", "body": "`BitmapData` doesn't exist for me. Also `Unsafe code may only appear if compiling with /unsafe`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:24:50.980", "Id": "67135", "Score": "0", "body": "@puretppc: Add `using System.Drawing.Imaging;` at the top, or use `System.Drawing.Imaging.BitmapData`. (If you right click on `BitmapData` both options can be done automatically under `Resolve`.) To use unsafe code you need to enable it in the project properties." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:31:35.750", "Id": "67138", "Score": "0", "body": "Oh ok. But now I'm getting an error saying `'System.Drawing.Imaging.ImageLockMode' does not contain a definition for 'Read'` At the very top of the program I put `using System.Drawing.Imaging;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:35:35.613", "Id": "67141", "Score": "0", "body": "@puretppc: Sorry, that should be `ReadOnly`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:40:00.100", "Id": "67142", "Score": "0", "body": "+1 since it's working right now but my question is, is yours faster than the other 2 answers? I'm not a speed tester and I'm not at a pro level of programming. Please be honest though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:47:08.250", "Id": "67146", "Score": "0", "body": "@puretppc: Jesse C. Slicer used my code as base for his answer so that will be just as fast, and Dan Lyons tells in his answer that it's not as fast as using pointers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:53:30.360", "Id": "67150", "Score": "0", "body": "I guess yours is faster since you're using pointers right? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:14:19.073", "Id": "67156", "Score": "0", "body": "@puretppc: Well, the key is really that it accesses the data with a minimum of overhead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T13:10:15.827", "Id": "88987", "Score": "0", "body": "@Guffa: Bit of a necropost, sorry :) If I copy an image on my HDD and compare the two, this returns a match. But if I open it in Paint, then Save As (same filetype, nothing changed, just different filename), it doesn't match. Does this only check for equality in pixels (color), or does the checking of equality also include some metainformation (or similar) that is causing my matches to fail?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T13:26:17.263", "Id": "88992", "Score": "0", "body": "@Flater: This code only checks the pixel values. When you resave an image there are several way that some pixel values can become different. If the image is compressed using JPEG, then some data is interpolated when it's uncompressed, but that data is still considered when it's resaved, so some pixels may get a color that is slightly changed from the original. An image can also be converted from one color space to another, then the pixel values will differ even if they represent the same color." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T13:33:14.677", "Id": "88994", "Score": "0", "body": "@Guffa: .tif, .png, .bmp all have the same effect when saving as the same filetype. None of them still matches its original file. I didn't consider .jpg, but I assume the results there to be even wronger due to compression. Given the other filetypes (tif png bmp), is there one that has less margin for error than others? But already thanks for your reply! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-23T13:46:36.970", "Id": "88998", "Score": "0", "body": "@Flater: All the file types that you have tested are capable of storing the image without differences (as long as .tif doesn't use the JPEG compression mode), so it looks like the program is changing the colors somehow. You could use `cmd` and run `fc /b filename1 filename2` to compare the files byte by byte to see if there is just a few values that differ, or a general shift of all pixels." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:38:52.200", "Id": "39987", "ParentId": "39980", "Score": "14" } }, { "body": "<p>One thing I have done in the past is to convert the images to 64-bit encoded strings and just string compare. It won't be as fast as using pointers, naturally. However, it can be done entirely in managed code, it doesn't require you to know bits per pixel, and it works for the Image base class.</p>\n\n<pre><code>byte[] image1Bytes;\nbyte[] image2Bytes;\n\nusing(var mstream = new MemoryStream())\n{\n image1.Save(mstream, image1.RawFormat);\n image1Bytes = mstream.ToArray();\n}\n\nusing(var mstream = new MemoryStream())\n{\n image2.Save(mstream, image2.RawFormat);\n image2Bytes = mstream.ToArray();\n}\n\nvar image164 = Convert.ToBase64String(image1Bytes);\nvar image264 = Convert.ToBase64String(image2Bytes);\n\nreturn string.Equals(image164, image264);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:58:57.873", "Id": "67127", "Score": "0", "body": "Thanks this worked :) So my old code was about comparing BPP (bits per pixel)? I don't really know this since I got this off the another site" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:14:36.520", "Id": "67132", "Score": "3", "body": "Note that this will also compare any meta data in the images. If they for example are identical but with different resolution settings, this will return false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T08:30:11.140", "Id": "85967", "Score": "4", "body": "What is the purpose of converting to a base64 string? Why not simple compare the elements of both arrays (or streams)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T04:59:18.120", "Id": "426115", "Score": "0", "body": "It took a bit more work for me than I thought to get this method working; I read something about hashing the image data and thought Bitmap.GetHashCode() would suffice. I have several subimages I'm pulling from spritesheets and the last few spritesheets have blank subimages which I want to skip. It was either this or looping through each pixel of all subimages and checking to see if they were colorless (black with no alpha), which of course is processor-intensive. Thanks for sharing this!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:47:50.277", "Id": "39989", "ParentId": "39980", "Score": "12" } }, { "body": "<p>Note that Bitmap inherits from Image, which implements <code>IDisposable</code>. This means you very much better call <code>Dispose()</code> on those objects are you are done with them (way many paths here with UI event handlers), or put them into using blocks. Same goes for <code>OpenFileDialog</code>. </p>\n\n<p>As per my comments, some <code>using</code> usage (and <code>try..finally</code> usage, incorporating <a href=\"https://codereview.stackexchange.com/users/7641/guffa\">Guffa</a>'s <a href=\"https://codereview.stackexchange.com/a/39987/6172\">answer</a>):</p>\n\n<pre><code>private Bitmap image1;\n\nprivate Bitmap image2;\n\npublic Form1()\n{\n this.InitializeComponent();\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n using (var openDialog = new OpenFileDialog())\n {\n if (openDialog.ShowDialog() != DialogResult.OK)\n {\n return;\n }\n\n this.DisposeImage1();\n this.image1 = new Bitmap(openDialog.FileName);\n }\n\n this.pictureBox1.Image = this.image1;\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n using (var openDialog = new OpenFileDialog())\n {\n if (openDialog.ShowDialog() != DialogResult.OK)\n {\n return;\n }\n\n this.DisposeImage2();\n this.image2 = new Bitmap(openDialog.FileName);\n }\n\n this.pictureBox2.Image = this.image2;\n}\n\nprivate void button3_Click(object sender, EventArgs e)\n{\n MessageBox.Show(Compare(this.image1, this.image2) ? \"Same Image.\" : \"Different Image.\");\n}\n\nprivate void Form1_FormClosed(object sender, FormClosedEventArgs e)\n{\n this.DisposeImage2();\n this.DisposeImage1();\n}\n\nprivate static bool Compare(Bitmap bmp1, Bitmap bmp2)\n{\n // Test to see if we have the same size of image\n if (bmp1.Size != bmp2.Size)\n {\n return false;\n }\n\n var rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);\n var bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);\n\n try\n {\n var bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);\n\n try\n {\n unsafe\n {\n var ptr1 = (byte*)bmpData1.Scan0.ToPointer();\n var ptr2 = (byte*)bmpData2.Scan0.ToPointer();\n var width = 3 * rect.Width; // for 24bpp pixel data\n\n for (var y = 0; y &lt; rect.Height; y++)\n {\n for (var x = 0; x &lt; width; x++)\n {\n if (*ptr1 != *ptr2)\n {\n return false;\n }\n\n ptr1++;\n ptr2++;\n }\n\n ptr1 += bmpData1.Stride - width;\n ptr2 += bmpData2.Stride - width;\n }\n }\n }\n finally\n {\n bmp2.UnlockBits(bmpData2);\n }\n }\n finally\n {\n bmp1.UnlockBits(bmpData1);\n }\n\n return true;\n}\n\nprivate void DisposeImage1()\n{\n if (this.image1 == null)\n {\n return;\n }\n\n this.pictureBox1.Image = null;\n this.image1.Dispose();\n this.image1 = null;\n}\n\nprivate void DisposeImage2()\n{\n if (this.image2 == null)\n {\n return;\n }\n\n this.pictureBox2.Image = null;\n this.image2.Dispose();\n this.image2 = null;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:17:58.130", "Id": "67134", "Score": "0", "body": "`ImageLockMode` doesn't exist? Also, the unsafe I'm getting an error" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:53:45.537", "Id": "67165", "Score": "1", "body": "You'll need to check `enable unsafe code` on the Build page of your project's options. Also, add `using System.Drawing.Imaging` to your `using` directives at the top of the file to get access to `ImageLockMode`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T05:26:22.117", "Id": "108644", "Score": "0", "body": "in \"var bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat)\" last parameter bmp1.PixelFormat or bmp2.PixelFormat?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-15T05:30:41.017", "Id": "108646", "Score": "0", "body": "I got error \"Bitmap region is already locked.\" in code \"var bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat)\"" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:05:06.140", "Id": "39990", "ParentId": "39980", "Score": "6" } }, { "body": "<p>I'll focus on problems in <code>compare()</code>.</p>\n\n<p>You're using the wrong equality comparison for the bitmap size. You need to compare the contents of the <code>Size</code> objects, not whether they are the same reference.</p>\n\n<p>A variable named <code>flag</code> should be a… <em>red flag</em>! Not only is it vaguely named, its presence suggests that your code is ineffective. Avoid using variables for flow control; find more active ways to get to where you need to go.</p>\n\n<p>In this case, the solution is an early <code>return</code>. As soon as you find a single difference between the two images, you're done! You don't even need the <code>equals</code> variable.</p>\n\n<p>I would also rename <code>compare()</code> for clarity, and make it <code>static</code> because it is a pure function of its two parameters.</p>\n\n<pre><code>private static bool Equals(Bitmap bmp1, Bitmap bmp2) \n{\n if (!bmp1.Size.Equals(bmp2.Size))\n {\n return false;\n }\n for (int x = 0; x &lt; bmp1.Width; ++x)\n {\n for (int y = 0; y &lt; bmp1.Height; ++y)\n {\n if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))\n {\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T17:04:41.303", "Id": "40044", "ParentId": "39980", "Score": "9" } }, { "body": "<p>Have a look at this SO question.</p>\n\n<p><a href=\"https://stackoverflow.com/q/35151067/4062881\">https://stackoverflow.com/q/35151067/4062881</a></p>\n\n<p>It decreases the size of image, turns it B&amp;W, and then uses GetPixel() to generate hash.</p>\n\n<p>It is much faster, efficient, and works! It is able to find equal images with:</p>\n\n<ul>\n<li>different file formats (e.g. jpg, png, bmp)</li>\n<li>rotation (90, 180, 270) - by changing the iteration order of i and j</li>\n<li>different dimensions (same aspect is required)</li>\n<li>different compression (tolerance is required in case of quality loss like jpeg artifacts) - you can accept a 99% equality to be the same image and 50% to be a different one.</li>\n</ul>\n\n<p>Cheers..!! ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-30T09:43:01.253", "Id": "164510", "ParentId": "39980", "Score": "-1" } }, { "body": "<p>Why convert in base64 or compare every pixel if there's hash comparison? \nDo something like this: </p>\n\n<pre><code>byte[] fileData = File.ReadAllBytes(filePath);\nbyte[] hash = MD5.Create().ComputeHash(fileData);\n</code></pre>\n\n<p>And simply compare the hashes. </p>\n\n<p>You'll need <code>MD5CryptoServiceProvider</code> for that. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T08:38:11.477", "Id": "401867", "Score": "0", "body": "Identical images may have differences in how they are encoded (progressive or interlaced, for example, or different levels of error-correction code), so needn't be bit-identical. Also, when there's a match, you'd still have to also compare the actual data as well, given that hash collisions are possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:19:27.460", "Id": "401941", "Score": "0", "body": "First of all, if that would be the case base64 and pixel comparison wouldn't work either. Second, OP hasn't mentioned anything in that regard. If the plan is to compare slightly different images you could use the library OpenCV and a method like SIFT or SURF" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:29:50.043", "Id": "401946", "Score": "0", "body": "That makes no sense - there's no base-64 in the code that I can see, and I've just explained where pixel comparison shows identical content from different image files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T14:45:30.093", "Id": "401961", "Score": "0", "body": "Second most upvoted answer is suggesting base64 string comparison. Nice that you take the time to check before you randomly downvote others answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-21T15:16:37.520", "Id": "401975", "Score": "0", "body": "You have no idea which answers I have voted on (up or down), nor whether any of those votes were random, so please stop hurling accusations." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-20T23:53:29.883", "Id": "208096", "ParentId": "39980", "Score": "-1" } } ]
{ "AcceptedAnswerId": "39987", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:22:36.273", "Id": "39980", "Score": "23", "Tags": [ "c#", "image" ], "Title": "Determining if 2 images are the same" }
39980
<p>I am creating an API for consumption by other developers to interface with an internal framework. My goal is to be able to have the developers type something like:</p> <pre><code>profile.setPreference(new GroupPreference(id)); </code></pre> <p>or</p> <pre><code>UserPreference preference = new UserPreference(); preference.setDefaultInbox("nameOfInbox"); // set any other options, classes simplified profile.setPreference(preference); </code></pre> <p>The internal framework has all preferences persisted in the same manner. A user profile can be either a set of preferences specific to them (UserPreference) or a relation to a group preference using an ID (GroupPreference). An example of current API usage:</p> <pre><code>// Context object Profile profile = userService.getProfile("accountName"); // Preference returned here is immutable Preference preference = profile.getPreference(); preference.getDashboardOptions(); preference.getDefaultInbox(); // etc.. // To modify a users preferences UserPreference userPreference = new UserPreference(preference); userPreference.setDefaultInbox("newInbox"); // etc.. profile.setPreference(userPreference); // Or to link it to a group preference profile.setPreference(new GroupPreference(groupPreferenceId)); </code></pre> <p>I handle saving of the preference information through a PreferenceManager as a part of updating the overall profile:</p> <pre><code>preferenceManager.savePreference(preference, profileContext); </code></pre> <p>Now for the questions:</p> <ul> <li>The protected save method feels extremely cludgy but I didn't want to have any methods in the interface that potentially exposes implementation details. Is there a better way?</li> <li>How is this design overall? Something need to be reorganized?</li> </ul> <hr> <pre><code>public abstract class Preference { /** * Provides access to DashboardOptions object to manage what options are enabled * and disabled on the users dashboard. * * @return DashboardOptions object */ public abstract DashboardOptions getDashboardOptions(); /** * Gets the default inbox for the user. * * @return Default inbox */ public abstract String getDefaultInbox(); /** * Method that will be overridden to handle saving of the preference. * * @param profile ProfileContext passed in to provide information when saving preferences * @param service PreferenceService object that handles saving of preferences */ protected abstract void save(ProfileContext profile, PreferenceService service); } public class GroupPreference extends Preference { private Long groupPreferenceId; public GroupPreference(Long groupPreferenceId) { this.groupPreferenceId = groupPreferenceId; } public Long getPreferenceId() { return groupPreferenceId; } @Override public DashboardOptions getDashboardOptions() { return null; } @Override public String getDefaultInbox() { return null; } @Override protected final void save(ProfileContext profile, PreferenceService service) { service.setUserPreference(profile.getId(), groupPreferenceId); } } public class UserPreference extends Preference { private UserDashboardOptions options; private String defaultInbox = ""; public UserPreference() { this.options = new UserDashboardOptionsImpl(); } public UserPreference(Preference preference) { this.options = new UserDashboardOptionsImpl(preference.getDashboardOptions()); } @Override public UserDashboardOptions getDashboardOptions() { return options; } @Override public String getDefaultInbox() { return defaultInbox; } public void setDefaultInbox(String defaultInbox) { this.defaultInbox = defaultInbox; } @Override protected final void save(ProfileContext profile, PreferenceService service) { // The SubjectPreference is part of an internal framework I have to interface with SubjectPreference subjectPreference = service.createSubjectPreference(profile); service.saveSubjectPreference(subjectPreference); } } public class PreferenceManager { public void savePreference(Preference preference, ProfileContext profile, PreferenceService service) { preference.save(profile, service); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:31:23.587", "Id": "67160", "Score": "0", "body": "`Preference` should be an Interface instead of an Abstract class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:11:02.567", "Id": "67168", "Score": "0", "body": "Needs to be an abstract class to declare the save methods as protected vs public." } ]
[ { "body": "<p>Your design seems incredibly specific and inflexible. Any enhancement to the application is likely to require your <code>Preference</code> class to be modified. Furthermore, you will probably have to write a lot of custom code to implement persistence for the settings. Anytime you modify that code, you risk breaking compatibility with records already persisted to disk. Therefore, it would be best to stay simple and flexible.</p>\n\n<p>Consider how preferences are stored on OS X (<a href=\"http://en.wikipedia.org/wiki/Property_list\" rel=\"nofollow\">preference list</a>), Windows (<a href=\"http://en.wikipedia.org/wiki/Windows_Registry\" rel=\"nofollow\">registry</a>), and GNOME (<a href=\"https://developer.gnome.org/gconf/stable/\" rel=\"nofollow\">gconf</a>, an XML database). All of these are just key-value maps, with arbitrary strings as keys and a limited set of data types as values.</p>\n\n<p>Something generic like the following suggestiong should probably be able to accommodate most applications.</p>\n\n<pre><code>public interface Preferences {\n void setString(String key, String value);\n void setBoolean(String key, boolean value);\n void setInt(String key, int value);\n void setTuple(String, int[] value); // to store color values, for example\n void setMap(String key, Map&lt;String, String&gt;value);\n void setBytes(String key, byte[] value);\n\n boolean hasKey(String key);\n\n String getString(String key, String default);\n boolean getBoolean(String key, boolean value);\n int getInt(String key, int default);\n int[] getTuple(String key, int[] default);\n Map&lt;String, String&gt; getMap(String key, Map&lt;String, String&gt; default);\n byte[] getBytes(String key, byte[] default);\n}\n</code></pre>\n\n<p>On Java, see if you can reuse anything from <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html\" rel=\"nofollow\"><code>java.util.Properties</code></a>.</p>\n\n<hr>\n\n<p>A more advanced feature of some preference managers is the ability to specify</p>\n\n<ol>\n<li>out-of-the-box defaults</li>\n<li>site-wide mandatory settings, not overridable by users</li>\n<li>site-wide defaults</li>\n<li>user overrides</li>\n</ol>\n\n<p>You can decide whether you need such a system of cascading settings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:37:31.773", "Id": "67171", "Score": "0", "body": "The preference options are not something I have control over. I am making the public API over an internal framework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:55:27.817", "Id": "67174", "Score": "0", "body": "For now, don't think of these objects as preferences and evaluate them as just some objects doing some things." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:34:35.710", "Id": "40001", "ParentId": "39982", "Score": "3" } }, { "body": "<p>Your <code>Preference</code> class really looks like it should be an interface. And in fact it is actually two interfaces: The public one for the user and the internal one for the manager. So I'd suggest you split it up:</p>\n\n<pre><code>public interface Preference {\n /**\n * Provides access to DashboardOptions object to manage what options are enabled\n * and disabled on the users dashboard.\n * \n * @return DashboardOptions object\n */\n DashboardOptions getDashboardOptions();\n\n /**\n * Gets the default inbox for the user.\n * \n * @return Default inbox\n */\n String getDefaultInbox();\n}\n\ninterface SaveablePreference extends Preference // package private\n{\n /**\n * Method that will be overridden to handle saving of the preference.\n * \n * @param profile ProfileContext passed in to provide information when saving preferences\n * @param service PreferenceService object that handles saving of preferences\n */\n void save(ProfileContext profile, PreferenceService service);\n}\n</code></pre>\n\n<p>Your users will only ever get the <code>Preference</code> but your implementations (<code>UserPreference</code> and <code>GroupPreference</code>) will implement <code>SaveablePreference</code>.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Looking at it again it don't really see the point of the <code>PreferenceManager</code>. If the user will have to call the manager in order to save the preference then why don't make the <code>save</code> method public in the first place - so you end up with only one interface. Then the user can call <code>preference.save(context, service)</code> (the arguments he'd have to supply anyway when calling the manager).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:10:51.130", "Id": "67178", "Score": "0", "body": "In this case, how is the preference handled when it is being saved. The API user will have an instance of `Preference`, what will `PreferenceManager` be able to do with that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:21:27.877", "Id": "67180", "Score": "0", "body": "@cldfzn: Updated my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:36:41.820", "Id": "67184", "Score": "0", "body": "It was mostly a bid at removing the call from the object in the public part of the API. I'd rather have that method serviced out to a service or repository layer object. In the case of a group preference, upon save the group preference data would be loaded in to an immutable preference object and set to return from `profile.getPreference()` (at least that is my thought currently)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:38:15.440", "Id": "67185", "Score": "0", "body": "In terms of what the user would be doing `Profile profile = userService.updateProfile(profile);`. The call to save the preference wouldn't be explicit currently." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:58:40.230", "Id": "40003", "ParentId": "39982", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:25:08.833", "Id": "39982", "Score": "12", "Tags": [ "java", "object-oriented", "api" ], "Title": "Java API without exposing implementation details" }
39982
<p>I'm writing a PHP tutorial and I would like to display some forms where the users could enter values that are displayed in the same webpage, just as a demonstration. </p> <p>The forms do nothing special, they only use print instructions to display the input. </p> <p>I would like to know if these apparently innofensive forms could be a real danger for my server because of script injection.</p> <p>The code that processes the form is:</p> <pre><code>&lt;?php if (array_key_exists('user', $_POST)) { print "Hello, " . $_POST['user']; } else { print "Waiting for your input..."; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:48:51.330", "Id": "67117", "Score": "0", "body": "I think it would be helpful to include the relevant code in your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:51:07.233", "Id": "67118", "Score": "1", "body": "<?php \n if (array_key_exists('user', $_POST)) {\n print \"Hello, \" . $_POST['user']; \n } else {\n print \"Waiting for your input...\";\n }\n ?>" } ]
[ { "body": "<p>The Short answer is yes you are vulnerable to injection. XSS to be precise which you can read more about here <a href=\"https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet</a></p>\n\n<p>Explaination:</p>\n\n<p>All user input should be sanatized for example:</p>\n\n<p>if you input <code>&lt;script&gt;alert(\"This will alert\");&lt;/script&gt;</code> into your form you will notice an alert message will appear on your page</p>\n\n<p>however if you sanatize the code i.e.</p>\n\n<pre><code>print \"Hello, \" . htmlentities($_POST['user']);\n</code></pre>\n\n<p>you will no longer see the alert message</p>\n\n<p>using htmlentities() will help protect you from the script injection.</p>\n\n<p>You would also be better validating the data that will be expected from the user</p>\n\n<p>Other points which you can see here <a href=\"https://stackoverflow.com/questions/11554432/php-post-dynamic-variable-names-security-concerns\">https://stackoverflow.com/questions/11554432/php-post-dynamic-variable-names-security-concerns</a> which are based more on dynamically creating variables</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:40:30.620", "Id": "67119", "Score": "4", "body": "Also, apart from the security aspect, if you don't convert special HTML characters (in the user input) to HTML entities when you output in the _HTML_ page then the user might not even see what they have just entered and to the user your script might not appear to be working correctly - unless that is also part of the tutorial?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T22:54:20.317", "Id": "67120", "Score": "0", "body": "@w3d good point I will add that later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T08:15:19.850", "Id": "67121", "Score": "0", "body": "Yes, I understand. I have already applied htmlentities() to the input. Allowing the user to insert code is not a part of the tutorial, albeit it would be interesting that it were, but I'm too afraid to let people to put scripts in there. It would be too much risk to withstand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:56:18.177", "Id": "67280", "Score": "1", "body": "Consider updating your answer with the specific name of the vulnerability, cross site scripting. And, provide a link for more information about [xss](https://www.owasp.org/index.php/Cross-site_Scripting_(XSS))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T20:15:28.503", "Id": "67415", "Score": "0", "body": "@RobApodaca I've updated my answer" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T17:45:22.180", "Id": "39984", "ParentId": "39983", "Score": "11" } }, { "body": "<p>It's not a security risk for your server, but it may be for your users. </p>\n\n<p>Beside the fact that if the input contains <code>&lt;</code> the output might not be what you expected, the real dangers you face are XSS and CSRF. </p>\n\n<p>For example, a malicious attacker could make the user click on a link which opens your example form, and executes some malicious javascript. The big problem is not executing (on the client) attacker-controlled code, but the fact that the browser sees it as <em>coming from your website</em>, so it has access to cookies, etc...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:45:29.090", "Id": "67144", "Score": "0", "body": "This is interesting, but I don't fully understand it... Would it be necessary that the malicious script were stored in my server before being sent to the victim? Or the attacker would create a fake webpage that would ressemble one from my server?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:47:36.630", "Id": "67147", "Score": "0", "body": "A fake webpage with a form pointing to your website is enough. Also, the user may not even see this happening (e.g. Clickjacking)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:16:01.700", "Id": "39985", "ParentId": "39983", "Score": "6" } } ]
{ "AcceptedAnswerId": "39984", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-23T16:28:55.310", "Id": "39983", "Score": "8", "Tags": [ "php", "security" ], "Title": "Are my forms a danger towards code injection?" }
39983
<p>I'm showing and hiding 4 svg paths based on the value of a slider, all is working as expected, but it still feels a little cumbersome. Does anyone know a way to "<a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>" it out a little more?</p> <p><a href="http://jsfiddle.net/apaul34208/F9Wz7/18/">jsFiddle</a></p> <pre><code>$('.volumeSlider').slider({ value: 1, orientation: "vertical", range: "min", max: 1, step: 0.05, animate: true, slide: function (e, ui) { $('p').text(ui.value); var v = $('.volume1'); if (ui.value == 1) { v.show(); } if (ui.value &lt; 1) { v.slice(0).hide(); v.slice(1, 4).show(); } if (ui.value &lt;= 0.65) { v.slice(0, 2).hide(); v.slice(2, 4).show(); } if (ui.value &lt;= 0.35) { v.slice(0, 3).hide(); v.slice(4).show(); } if (ui.value === 0) { v.hide(); } } }); </code></pre>
[]
[ { "body": "<p>I am guessing that the '.volume' elements are like volume indicators, the louder the sound, the more you show.</p>\n\n<p>You can iterate over the '.volume' elements, compare the <code>index / elementCount</code> to <code>ui.value</code> and decide to <code>hide</code> or <code>show</code> per that comparison.</p>\n\n<p>So, something like : </p>\n\n<pre><code>$('.volumeSlider').slider({\n value: 1,\n orientation: \"vertical\",\n range: \"min\",\n max: 1,\n step: 0.05,\n animate: true,\n slide: function (e, ui) {\n $('p').text(ui.value);\n var v = $('.volume1');\n for( var i = 0 ; i &lt; v.length ; i++ ){\n ( 1-ui.value &gt; 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()\n }\n }\n});\n</code></pre>\n\n<p>should work. This approach will work with any number of <code>volume1</code> elements.\nI did not test this, but once you see/get this I am sure you can make this work.</p>\n\n<p>Further optimizations can be caching <code>v.length</code> and <code>1 / v.length</code>, you could probably also use <code>eq</code> instead of <code>slice()</code></p>\n\n<p>EDIT : I fixed the code to work with your HTML, the original was \n<br>\n<code>( ui.value &lt; 1 / v.length * (i + 1)) ? v.slice(i).hide() : v.slice(i).show()</code>\nwhich would work if the HTML elements were created in what I see as the correct order.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:41:33.477", "Id": "67143", "Score": "0", "body": "This looks promising, but the paths are showing/hiding in the opposite direction and the increments have changed. http://jsfiddle.net/apaul34208/F9Wz7/20/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:46:41.643", "Id": "67145", "Score": "0", "body": "Fixed, try http://jsfiddle.net/konijn_gmail_com/2aMvf/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T19:20:54.173", "Id": "39992", "ParentId": "39986", "Score": "4" } } ]
{ "AcceptedAnswerId": "39992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T18:35:27.237", "Id": "39986", "Score": "7", "Tags": [ "javascript", "jquery", "jquery-ui", "user-interface" ], "Title": "DRY multiple if statements used to show/hide elements based on slider value" }
39986
<p>I am trying to learn to create controllers for my own HTML5 audio tags, which I often have several of on the same page. The js.jQuery code below is a simple beginning to this; it works to apply a play/pause button to each corresponding audio tag with a class of my_audio. </p> <p>I'm a new coder though, so I imagine there are problems to my approach. Can anyone point out those problems, or suggest a more efficient way to do this?</p> <p>(Btw, yes I know about jPlayer, etc. Just wanting to learn to do it myself :^)</p> <pre><code>$(document).ready(function(){ $(".my_audio").each(function(index){ $( this ).attr('id', "audioId" + index); var playPauseId = "playPause" + index; $( this ).after( '&lt;div class="audio_controls_bar"&gt;\ &lt;button id="' + playPauseId + '"&gt;Pause&lt;/button&gt;\ &lt;/div&gt;' ); doAudios(index); }); }); function doAudios(index) { var audio, playbtn; function initializePlayer(){ //set object references audio = document.getElementById("audioId"+index); console.log(audio); playbtn = document.getElementById("playPause"+index); console.log(playbtn) // add event listeners playbtn.addEventListener("click", playPause, false); } initializePlayer(); function playPause(){ if(audio.paused){ audio.play(); playbtn.innerHTML = "Pause"; } else { audio.pause(); playbtn.innerHTML = "Play"; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:22:53.533", "Id": "67157", "Score": "1", "body": "Please note that JavaScript itself can't __style__ anything. This is done with CSS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:25:31.443", "Id": "67158", "Score": "0", "body": "yes. but it seems you can't style the audio element unless you make your own controllers and style them instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:56:03.407", "Id": "67166", "Score": "1", "body": "yes - take a look, I reworded the question as I see it was not clear. I know how to do the css, what I am looking for is feedback on the javascript." } ]
[ { "body": "<p>This is good code for a new coder.</p>\n\n<p>Some observations:</p>\n\n<ul>\n<li>I am not sure why you add a pause button through JavaScript, you could have this button declared simply in the HTML.</li>\n<li><code>doAudios</code> -> misnomer, since it deals with 1 audio at a time, so <code>doAudio</code> makes more sense.</li>\n<li>You go through a lot of effort to give everything an id so that you can wire everything together, it is not needed if you use your closure inside the main loop.</li>\n</ul>\n\n<p>I would counter-propose something like this to get rid of the <code>id</code> centered code:</p>\n\n<pre><code>$(document).ready(function(){\n\n $(\".my_audio\").each(function(index){\n var audio = this,\n playPause = $( '&lt;div class=\"audio_controls_bar\"&gt;&lt;button&gt;Pause&lt;/button&gt;&lt;/div&gt;' ),\n button = $( audio ).after( playPause ).children().first(); \n\n button.addEventListener(\"click\", function(){\n if(audio.paused){\n audio.play();\n this.innerHTML = \"Pause\";\n } else {\n audio.pause();\n this.innerHTML = \"Play\";\n } \n }, false); \n }); \n});\n</code></pre>\n\n<p>If you were willing to drop the <code>div</code> and put the styling on the button, it would be a bit cleaner :</p>\n\n<pre><code>$(document).ready(function(){\n\n $(\".my_audio\").each(function(index){\n var audio = this,\n button = $( '&lt;button class=\"audio_controls_bar\"&gt;Pause&lt;/button&gt;' ),\n $( audio ).after( button );\n\n button.addEventListener(\"click\", function(){\n if(audio.paused){\n audio.play();\n this.innerHTML = \"Pause\";\n } else {\n audio.pause();\n this.innerHTML = \"Play\";\n } \n }, false); \n }); \n});\n</code></pre>\n\n<p>Since here you can drop <code>playPause</code> and the <code>.children().first();</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:38:18.933", "Id": "40169", "ParentId": "39993", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T20:06:13.220", "Id": "39993", "Score": "4", "Tags": [ "javascript", "jquery", "html5" ], "Title": "javascript for controllers of multiple audio tags" }
39993
<p>I need to write a bit of code that will get a list of the RGB colours in an image and then translate them into a NumPy array of lab colours. I have managed to do this, but I would like to learn how I can do it more efficiently. </p> <pre><code>from skimage.color import rgb2lab from skimage.io import imread import numpy as np from PIL import Image # @UnresolvedImport def get_histogram (img): #histogram = plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75) w, h = img.size colours = img.getcolors(w*h) #Returns a list [(pixel_count, (R, G, B))] num, colours_rgb = zip(*colours) r,g,b = zip(*colours_rgb) num_of_colours = len(r) w2,h2 = 1,num_of_colours data = np.zeros( (w2,h2,3), dtype=np.uint8) print(data.shape) data[0,:,0] = r data[0,:,1] = g data[0,:,2] = b print(data) colours_lab = rgb2lab(data) </code></pre>
[]
[ { "body": "<ol>\n<li><p>There's no docstring for <code>get_histogram</code>. What does this function do? What kind of object should I pass for the <code>img</code> argument?</p></li>\n<li><p>You import <code>skimage.io.imread</code> and <code>PIL.Image</code> but you don't use either of them.</p></li>\n<li><p>This comment doesn't seem relevant:</p>\n\n<pre><code>#histogram = plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)\n</code></pre></li>\n<li><p>There are two useless <code>print</code> statements. I presume that these are left over from a debugging session and you forgot to remove them. You might find it useful to learn to use the <a href=\"http://docs.python.org/3/library/pdb.html\" rel=\"nofollow\">Python debugger</a> which would avoid the need to add <code>print</code> statements to the code.</p></li>\n<li><p>There are two pieces of functionality here: (i) extracting the colour data from an image into a Numpy array; (ii) converting colour data from RGB to the <a href=\"https://en.wikipedia.org/wiki/Lab_color_space\" rel=\"nofollow\">Lab colour space</a>. It would make sense to split these up (especially as piece (ii) is so simple).</p></li>\n<li><p>The function is poorly named: it does not actually get a histogram. (Because you discard the colour counts in the <code>num</code> array.) This makes me wonder what you are using this function for.</p></li>\n<li><p>You use the spelling \"colour\" but the APIs you are calling use the spelling \"color\". Even if you prefer the \"colour\" spelling, it's better to be consistent. That way there's less chance of forgetting and making a mistake.</p></li>\n<li><p>Creating a Numpy array from an a Python list is usually straightforward if you pass the list to the <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html\" rel=\"nofollow\"><code>numpy.array</code></a> function. There's no need to mess about with <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html\" rel=\"nofollow\"><code>numpy.zeros</code></a> and assigning column-wise.</p></li>\n</ol>\n\n<p>So I'd write the following:</p>\n\n<pre><code>import numpy as np\n\ndef distinct_colors(img):\n \"\"\"Return the distinct colors found in img.\n img must be an Image object (from the Python Imaging Library).\n The result is a Numpy array with three columns containing the\n red, green and blue values for each distinct color.\n\n \"\"\"\n width, height = img.size\n colors = [rgb for _, rgb in img.getcolors(width * height)]\n return np.array(colors, dtype=np.uint8)\n</code></pre>\n\n<p>The conversion to Lab colour space is so simple that I don't think it needs a function.</p>\n\n<h3>Update</h3>\n\n<p>There's one minor difficulty: the <a href=\"http://scikit-image.org/docs/dev/api/skimage.color.html\" rel=\"nofollow\"><code>skimage.color</code></a> functions all demand an array with 3 or 4 dimensions, and so only support 2- and 3- dimensional images. Your array of distinct colours is a 1-dimensional image, so it's rejected. But you can easily use <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html\" rel=\"nofollow\"><code>numpy.reshape</code></a> to turn it into a 2-dimensional image whose first dimension is 1 before passing it to <code>rgb2lab</code>, like this:</p>\n\n<pre><code>colors = distinct_colors(img)\nrgb2lab(colors.reshape((1, -1, 3)))\n</code></pre>\n\n<p>Or if you prefer the second dimension to be 1, use <code>.reshape((-1, 1, 3))</code>.</p>\n\n<p>(Personally I think the <code>skimage.color</code> behaviour is absurd. Why does it care about the number of dimensions? There doesn't seem to be any obvious reason in the code. Maybe it would be worth filing a bug report?)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T19:06:10.120", "Id": "68143", "Score": "0", "body": "The one comment that you posted wrt to coding efficiency (number 8), I have a question about. When I just do an assign of the list to a numpy array, it is not the right size, shape for the lab conversion process and throws an error (ValueError: the input array must be have a shape == (.., ..,[ ..,] 3)), got (253, 3)). Which is why I did the numpy zeroes thing. But I am hoping there is a more efficient way to do than the way I did it. I am new to python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T20:27:24.987", "Id": "68159", "Score": "0", "body": "See updated answer: it's easy to add a dimension using `numpy.reshape`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:07:07.017", "Id": "40172", "ParentId": "39997", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:00:56.563", "Id": "39997", "Score": "6", "Tags": [ "python", "beginner", "image" ], "Title": "Getting list of colours from image in lab format" }
39997
<h2>Class To Test</h2> <p>Some methods hidden for clarity</p> <pre><code>namespace RiPS.Infrastructure.UA { public class UAWorkflowManager { private readonly IContextIOAPI _api; private readonly IUAjoinedRepo _dbJoinedRepo; private readonly IRemindersSystem _remindersSystem; public UAWorkflowManager(IContextIOAPI contextIOAPI, IUAjoinedRepo uAjoinedRepo, IRemindersSystem remindersSystem) { _api = contextIOAPI; _dbJoinedRepo = uAjoinedRepo; _remindersSystem = remindersSystem; } public bool Assign(MongoUAJoinedWorkflow wf,string username, IUAWorkflowHub hub) { if (String.IsNullOrEmpty(wf.UA)) { hub.Error("Assignment Error", "Must have UA to assign"); return false; } if (wf.TaskReqs.Count &lt; 1) { hub.Error("Assignment Error", "Must have tasks"); return false; } foreach (var req in wf.TaskReqs) { if (String.IsNullOrEmpty(req.Note)) { hub.Error("Assignment Error", "All Tasks must have notes"); return false; } if (String.IsNullOrEmpty(req.Title)) { hub.Error("Assignment Error", "All Tasks must have titles. Must be an error "); return false; } } wf.Assigned = true; wf.AssignedBy = username; wf.AssignedDate = DateTime.UtcNow; var msg = GenerateMessage(wf); msg.Body = RenderViewToString(wf); var str = CreateStream(wf, hub); var fileName = str.Item1; var stream = str.Item2; AttachMessage(msg, stream, fileName); hub.Info("Assigning", "Sending Email"); RetryUtility.RetryAction(() =&gt; SendMessage(msg)); stream.Position = 0; hub.Info("Task", "adding"); foreach (var taskReq in wf.TaskReqs) { var r = _remindersSystem.AddReminder(new MongoReminder(wf.clientId, wf.policyId, wf.UA, "UAWF", taskReq.DueDate, taskReq.Title), stream, fileName); wf.ReminderGuids.Add(r.Id); stream.Position = 0; } _dbJoinedRepo.Save(wf); hub.Info("Task", "added"); hub.Info("Assigning", "Moving Email To Assigned Folder"); RetryUtility.RetryAction(() =&gt; MoveToFolder(wf.MessageId, "Assigned")); hub.Info("Assigning", "Saving Assignment to Database"); wf.Error = ""; hub.Update(wf); hub.Success("Assigned", wf.Subject); return true; } } } </code></pre> <h2>Test Class (nUnit &amp; Moq)</h2> <pre><code>namespace RiPSTests { [TestFixture] public class UAWF { private Mock&lt;IContextIOAPI&gt; mock; private Mock&lt;IUAjoinedRepo&gt; repoMock; private Mock&lt;IUAWorkflowHub&gt; hubMock; private Mock&lt;IRemindersSystem&gt; reminderMock; private const string ConstSampleUA = "FAKEUA"; private const string ConstSampleNote = "FAKENote"; private const string ConstSampleTitle = "FAKETitle"; [SetUp] public void setup() { mock = new Mock&lt;IContextIOAPI&gt;(); repoMock = new Mock&lt;IUAjoinedRepo&gt;(); hubMock = new Mock&lt;IUAWorkflowHub&gt;(); reminderMock = new Mock&lt;IRemindersSystem&gt;(); } [Test] public void CanSetup() { var man = new UAWorkflowManager(mock.Object, repoMock.Object, reminderMock.Object); Assert.NotNull(man); } [Test] public void FailMustHaveUA() { //Arrange var man = new UAWorkflowManager(mock.Object, repoMock.Object, reminderMock.Object); var wf = new MongoUAJoinedWorkflow(); //Act var res = man.Assign(wf, ConstSampleUA, hubMock.Object); //Assert Assert.IsFalse(res); hubMock.Verify(z =&gt; z.Error("Assignment Error", "Must have UA to assign"), Times.Exactly(1)); } [Test] public void FailMustHaveTasks() { //Arrange var man = new UAWorkflowManager(mock.Object, repoMock.Object, reminderMock.Object); var wf = new MongoUAJoinedWorkflow() { UA = ConstSampleUA }; //Act var res = man.Assign(wf, ConstSampleUA, hubMock.Object); //Assert Assert.IsFalse(res); hubMock.Verify(z =&gt; z.Error("Assignment Error", "Must have tasks"), Times.Exactly(1)); } [Test] public void FailTasksMustHaveNote() { //Arrange var man = new UAWorkflowManager(mock.Object, repoMock.Object, reminderMock.Objects); var wf = new MongoUAJoinedWorkflow() { UA = ConstSampleUA, TaskReqs = new List&lt;TaskReq&gt;() { new TaskReq() { DueDate = DateTime.Today, Title = ConstSampleTitle } } }; //Act var res = man.Assign(wf, ConstSampleUA, hubMock.Object); //Assert Assert.IsFalse(res); hubMock.Verify(z =&gt; z.Error("Assignment Error", "All Tasks must have notes"), Times.Exactly(1)); } } } </code></pre> <p>Test feel awfully verbose and brittle. Writing Tests Second (Need to do some overhaul and was unable to test the first time because i am not a strong tester)</p>
[]
[ { "body": "<p>Your first test, CanSetup, will never fail; a .NET constructor can never return null.</p>\n\n<p>All of your tests have the same basic setup: create a \"manager\", create a \"workflow\", invoke the Assign() method w/ the same arguments. All that changes is how the WF is constructed. Consider:</p>\n\n<ol>\n<li><p>Make the manager part of the fixture (not a local variable) and initialize it during setup. It seems to be initialized the same in all cases.</p></li>\n<li><p>Create a private helper function that encapsulates the pattern you follow, and just expose the things that vary (like the WF, or some properties of the WF) as arguments. When each test can essentially be expressed as a form of template, this is a decent way of reducing duplication.</p></li>\n<li><p>Personal preference, but I like underscores in my test names; makes it easier to read a long list of them and to spot differences. I also like fairly verbose names that describe the business case for the test: <code>Cannot_assign_a_UA_without_tasks</code> rather than <code>FailMustHaveTasks</code>. (I have no idea if I inferred the purpose of the test correctly, which is exactly the point I'm making; <code>FailMustHaveTasks</code> makes no sense to me at all)</p></li>\n<li><p>Re: tests being brittle. If you're asserting against an error message, avoid doing an Equals assert. Someone could fix a grammatical mistake and break the test. Instead, just look for one or two identifying words. I'm not sure what the syntax is w/ Moq, but in RhinoMocks it's pretty easy to say \"assert this method was called with a string argument containing the word 'Foo'\".</p></li>\n<li><p>Why else are your tests brittle? Sometimes brittle tests are caused by people asserting the wrong thing; do you really care that a specific method was called? Or do you just care that some object wasn't modified? Tests that assert against specific interactions can be more brittle than tests that assert against state.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:26:58.480", "Id": "67181", "Score": "0", "body": "To be more precise: The test `CanSetup` can fail but the `Assert` never will (the ctor could throw an exception which will make the test fail but if there is no exception then the Assert will never fail)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:42:28.333", "Id": "40002", "ParentId": "39998", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:22:56.967", "Id": "39998", "Score": "2", "Tags": [ "c#", "unit-testing", "moq", "nunit" ], "Title": "Multiple Services and Test Setup" }
39998
<p>This is how I handle this situation right now:</p> <p>For example, I have service that returns <code>UserDto</code> by user ID: <code>GetUserById</code>.</p> <ul> <li>Service never returns null or throws exceptions. </li> <li>Service always returns DTO objects derived from the base class (<code>DtoBase</code>).</li> <li>Each DTO object relates to some Entity type. Each entity has an assigned ID (In my example I used <code>long</code> for IDs, but the <code>Response</code> class can be made generic).</li> </ul> <p><code>DtoBase</code> class:</p> <pre><code>[DataContract] public abstract class DtoBase : IDtoResponseEnvelop { [DataMember] private readonly Response _responseInstance = new Response(); //This constructor should be called when there is no result protected DtoBase() {} //Each DTO object relates to some Entity (each entity has as ID). //And if there is some result this constructor should be called. protected DtoBase(long entityId) { _responseInstance = new Response(entityId); } #region IDtoResponseEnvelop Members public Response Response { get { return _responseInstance; } } #endregion } </code></pre> <p>Basically, the <code>Response</code> class aggregates operation response information such as: if there is any value, exception and warnings:</p> <pre><code>[DataContract] public class Response { #region Constructors public Response():this(0){} public Response(long entityId) { _entityIdInstance = entityId; } #endregion #region Private Serializable Members [DataMember] private BusinessExceptionDto _businessExceptionInstance; [DataMember] private readonly IList&lt;BusinessWarning&gt; _businessWarningList = new List&lt;BusinessWarning&gt;(); [DataMember] private readonly long _entityIdInstance; #endregion #region Public Methods public void AddBusinessException(BusinessException exception) { _businessExceptionInstance = new BusinessExceptionDto(exception.ExceptionType, exception.Message, exception.StackTrace); } public void AddBusinessWarnings(IEnumerable&lt;BusinessWarning&gt; warnings) { warnings.ToList().ForEach( w =&gt; _businessWarningList.Add(w)); } #endregion #region Public Getters public bool HasWarning { get { return _businessWarningList.Count &gt; 0; } } public IEnumerable&lt;BusinessWarning&gt; BusinessWarnings { get { return new ReadOnlyCollection&lt;BusinessWarning&gt;(_businessWarningList); } } public long EntityId { get { return _entityIdInstance; } } public bool HasValue { get { return EntityId != default(long); } } public bool HasException { get { return _businessExceptionInstance != null; } } public BusinessExceptionDto BusinessException { get { return _businessExceptionInstance; } } #endregion } </code></pre> <p>Now, having this in place, on server side we have:</p> <pre><code> private UserDto GetUserByIdCommand(IRepositoryLocator locator, long userId) { var item = locator.GetById&lt;User&gt;(userId); if (item != null) return Mapper.Map&lt;User, UserDto&gt;(item); //mapper calls UserDto(item.ID) constructor _businessNotifier.AddWarning(BusinessWarningEnum.Operational, string.Format("User with Id=\"{0}\" not found", userId)); return new UserDto(); //no Entity id is provided here, since no value available } </code></pre> <p>And, on client side:</p> <pre><code> var userDto = UserService.GetUserById(1); if(!userDto.Response.HasValue) { //No result is available } </code></pre> <p>Is my approach fine or is there a better way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T04:07:59.607", "Id": "67221", "Score": "7", "body": "I think it would be more natural to return a generic response object (Response<UserDTO>) that contains the DTO result as a property. It just seems more straightforward to reason about a response that has the result that you want, rather than returning a result then checking the response to see if the result actually has anything." } ]
[ { "body": "<p>I only quickly glanced at your code, so this isn't going to be a thorough review, but I think the basic idea is surprising:</p>\n<blockquote>\n<p>Service never returns null or throws exceptions.</p>\n</blockquote>\n<p>I think this approach is error-prone. When I call a method called <code>GetUserById</code>, for an <code>Id</code> that doesn't exist, I expect either an <code>ArgumentOutOfRangeException</code> (or similar), or a <code>null</code> return value - <strong>the last thing I expect</strong> is a valid object filled up with default values filling up all members.</p>\n<p>As @jlnorsworthy mentioned in his excellent comment, your approach is far from instinctive. Instead of:</p>\n<pre><code>var userDto = UserService.GetUserById(1);\nif(!userDto.Response.HasValue)\n{\n //No result is available\n}\n</code></pre>\n<p>I would perfer to have:</p>\n<pre><code>var userResult = UserService.GetUserById(1);\nif(userResult.Result == null)\n{\n //No result is available\n}\n</code></pre>\n<p>Also <code>HasValue</code> confusing because it is a well-known member of <code>Nullable&lt;T&gt;</code>, so I'd consider changing <code>EntityId</code> to be <code>Nullable&lt;long&gt;</code> or <code>Nullable&lt;Int64&gt;</code>:</p>\n<pre><code>public bool HasValue\n{\n get { return EntityId.HasValue; }\n}\n</code></pre>\n<hr />\n<p>What is <code>IRepositoryLocator</code>? If it is what I think it is, you should read up on <a href=\"http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/\" rel=\"noreferrer\">Mark Seeman's blog</a>. Shortly put:</p>\n<blockquote>\n<p>Service Locator is a well-known pattern, and since it was described by Martin Fowler, it must be good, right?</p>\n<p>No, it's actually an <strong>anti-pattern</strong> and should be avoided.</p>\n</blockquote>\n<hr />\n<p>Little nitpick, I wouldn't use <code>ForEach</code> here:</p>\n<pre><code>public void AddBusinessWarnings(IEnumerable&lt;BusinessWarning&gt; warnings)\n{\n warnings.ToList().ForEach( w =&gt; _businessWarningList.Add(w));\n}\n</code></pre>\n<p>It would be much more readable (and less <a href=\"https://stackoverflow.com/a/7816840/1188513\">semantically controversial</a>) to write it like this:</p>\n<pre><code>public void AddBusinessWarnings(IEnumerable&lt;BusinessWarning&gt; warnings)\n{\n _businessWarningList.AddRange(warnings);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T03:35:40.397", "Id": "71548", "Score": "0", "body": "+1 In Java I tend to offer two versions of any single-object finder method: `findByFoo` returns `null` when none match whereas `getByFoo` throws an exception. This gives the client programmer the freedom to handle a missing item gracefully or fail as needed. While the two methods require a little more code, they can greatly increase DRY in many cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T03:22:27.583", "Id": "41529", "ParentId": "39999", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:24:45.553", "Id": "39999", "Score": "10", "Tags": [ "c#", "design-patterns", ".net", "client" ], "Title": "Telling a client that there is no result via the DTO pattern" }
39999
<p>I wanted to try out writing an minimalistic connection pool implementation (out of curiosity and for learning). Could you all please review the code and provide feedback? </p> <p>There are two classes (class names are hyperlinked to code): </p> <ol> <li><a href="https://github.com/sharmaak/crashlabs/blob/master/MinimalConnectionPool/com/amitcodes/dbcp/ConnectionPool.java"><code>com.amitcodes.dbcp.ConnectionPool</code></a>: The connection pool implementation</li> <li><a href="https://github.com/sharmaak/crashlabs/blob/master/MinimalConnectionPool/com/amitcodes/dbcp/PooledConnection.java"><code>com.amitcodes.dbcp.PooledConnection</code></a>: The proxy for <code>java.sql.Connection</code>, written with the intent of ensuring that connections borrowed from <code>ConnectionPool</code> should be not be closed by client code, but surrendered back to the pool.</li> </ol> <hr> <p><strong>TODOs (based on review comments)</strong>:</p> <p>This is why code reviews are important. I've added the following changes so far based on the code review comments:</p> <ol> <li>maintain a count of active connections available in the pool (preferably using <code>AtomicInteger</code>)</li> <li><code>borrowConnection()</code> should ensure there are no available idle connections (using point #1 above) before opening a new pooled connection</li> <li>surrenderConnection should rollback unfinished transactions. They could leak.</li> <li>validate that surrendered connections are same as ones which were borrowed. If this check is not in place, a client can surrender connection to db 'foo' to dbcp for db 'bar'</li> <li><code>surrenderConnection()</code> should take care of rolling back any open transactions</li> <li>include a validate() method to validate constructor params</li> </ol> <hr> <p>The code: </p> <pre><code>package com.amitcodes.dbcp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; public class ConnectionPool { private static final Logger logger = Logger.getLogger(ConnectionPool.class.getCanonicalName()); private BlockingQueue&lt;Connection&gt; pool; /** * Maximum number of connections that the pool can have */ private int maxPoolSize; /** * Number of connections that should be created initially */ private int initialPoolSize; /** * Number of connections generated so far */ private int currentPoolSize; private String dbUrl; private String dbUser; private String dbPassword; public ConnectionPool(int maxPoolSize, int initialPoolSize, String url, String username, String password, String driverClassName) throws ClassNotFoundException, SQLException { if ((initialPoolSize &gt; maxPoolSize) || initialPoolSize &lt; 1 || maxPoolSize &lt; 1) { throw new IllegalArgumentException("Invalid pool size parameters"); } // default max pool size to 10 this.maxPoolSize = maxPoolSize &gt; 0 ? maxPoolSize : 10; this.initialPoolSize = initialPoolSize; this.dbUrl = url; this.dbUser = username; this.dbPassword = password; this.pool = new LinkedBlockingQueue&lt;Connection&gt;(maxPoolSize); initPooledConnections(driverClassName); if (pool.size() != initialPoolSize) { logger.log(Level.WARNING, "Initial sized pool creation failed. InitializedPoolSize={0}, initialPoolSize={1}", new Object[]{pool.size(), initialPoolSize}); } } private void initPooledConnections(String driverClassName) throws ClassNotFoundException, SQLException { // 1. Attempt to load the driver class Class.forName(driverClassName); // 2. Create and pool connections for (int i = 0; i &lt; initialPoolSize; i++) { openAndPoolConnection(); } } private synchronized void openAndPoolConnection() throws SQLException { if (currentPoolSize == maxPoolSize) { return; } Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword); pool.offer(new PooledConnection(conn, this)); currentPoolSize++; logger.log(Level.FINE, "Created connection {0}, currentPoolSize={1}, maxPoolSize={2}", new Object[]{conn, currentPoolSize, maxPoolSize}); } public Connection borrowConnection() throws InterruptedException, SQLException { if (pool.peek()==null &amp;&amp; currentPoolSize &lt; maxPoolSize) { openAndPoolConnection(); } // Borrowing thread will be blocked till connection // becomes available in the queue return pool.take(); } public void surrenderConnection(Connection conn) { if (!(conn instanceof PooledConnection)) { return; } pool.offer(conn); // offer() as we do not want to go beyond capacity } } </code></pre> <p><code>com.amitcodes.dbcp.PooledConnection</code>: Only relevant section is posted here and boiler-plate code has been removed. You can view the complete class <a href="https://github.com/sharmaak/crashlabs/tree/master/MinimalConnectionPool/com/amitcodes/dbcp">here</a> on GitHub. </p> <pre><code>package com.amitcodes.dbcp; import java.sql.*; import java.util.*; import java.util.concurrent.Executor; public class PooledConnection implements Connection { private Connection coreConnection; private ConnectionPool connectionPool; public PooledConnection(Connection coreConnection, ConnectionPool connectionPool) { this.connectionPool = connectionPool; this.coreConnection = coreConnection; } @Override public void close() throws SQLException { connectionPool.surrenderConnection(this); } /* **************************************************************** * Proxy Methods * ****************************************************************/ @Override public Statement createStatement() throws SQLException { return coreConnection.createStatement(); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return coreConnection.prepareStatement(sql); } // SOME CODE SKIPPED } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-27T07:52:29.910", "Id": "330320", "Score": "0", "body": "Lets say a client calls `surrenderConnection(connection)` but still keeps a reference to the conenction he can still go ahead and call methods like `createStatement()` and `prepareStatement()` even though the connection is returned to the poll that might me handed over to another client? How will we resolve this?" } ]
[ { "body": "<p>A few random notes:</p>\n\n<ol>\n<li><p>If I were you I'd check the source and API of <a href=\"http://commons.apache.org/proper/commons-pool/\" rel=\"noreferrer\">Apache Commons Pool</a>. You could borrow ideas about possible errors, corner cases, useful API calls, parameters etc.</p></li>\n<li><p><code>surrenderConnection</code> should rollback unfinished transactions. They could leak.</p></li>\n<li><p>SLF4J has better API than JUL. (Check Logback also, if you don't familiar with it.)</p></li>\n<li><p>A malicious (or poorly written client with multiple pools) can call <code>surrenderConnection</code> with a <code>PooledConnection</code> instance which was not created by the called <code>ConnectionPool</code>.</p></li>\n<li><p>I'd check <code>null</code>s in the constructors/methods. Does it make sense to call them with <code>null</code>? If not, check it and throw an exception. <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"noreferrer\">checkNotNull in Guava</a> is a great choice for that.</p>\n\n<pre><code>this.connectionPool = \n checkNotNull(connectionPool, \"connectionPool cannot be null\");\n</code></pre>\n\n<p>(Also see: <em>Effective Java, 2nd edition, Item 38: Check parameters for validity</em>)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T07:41:29.470", "Id": "67236", "Score": "2", "body": "Awesome :) Point #2 and #4 would have caused serious bugs. Will fix 'em and update the code soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:35:46.357", "Id": "67767", "Score": "1", "body": "I generally avoid other logging apis like SLF4J and use JUL to avoid additional library dependencies. Java EE servers also use JUL to capture and manage the logs as well. If you use a logging API then it becomes and application responsibility." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:23:00.277", "Id": "40007", "ParentId": "40005", "Score": "9" } }, { "body": "<p>It looks like the borrow connection code will create a new connection without first checking to see if there is an available connection in the pool. That's not how most connection pools work. You probably want to store a count of available connections (consider using an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html\">AtomicInteger</a> for safe concurrent access) and check against that before adding the new connection.</p>\n\n<p>Other than that it looks pretty solid. However, it looks like your test coverage is pretty thin. I suggest beefing that up. Unit tests are an excellent way to make sure your code performs as expected.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T07:33:50.097", "Id": "67235", "Score": "0", "body": "I pushed in a quick fix to peek the queue before opening a new pooled-connection (in the inline code). Will give some more thought on using `AtomicInteger` and update the code. Thanks for the review :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:25:11.357", "Id": "40009", "ParentId": "40005", "Score": "8" } }, { "body": "<p>I didn't understand the concept here. How come <code>ConnectionPool</code> is a part of <code>PooledConnection</code>?</p>\n\n<p>My understanding of a pool - you a bucket with 100 items, take one, use it and put it back into the pond.</p>\n\n<p>I would prefer writing something like:</p>\n\n<pre><code>ConnectionPool.getConnection();\nConnectionPool.releaseConnection(Connection c);\n</code></pre>\n\n<p>Where there will be only 1 instance of this pool. (I would use a private constructor and a getInstance() for pool)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-28T20:59:47.123", "Id": "418735", "Score": "0", "body": "Making ConnectionPool a singleton (private constructor & singleton) is a bad idea. What if same client wants to have 2 connection pools for connecting to 2 urls?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T05:20:11.933", "Id": "456533", "Score": "0", "body": "In that case, you should take 2 connections from the same pool. You should not create multiple pools." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T08:14:48.257", "Id": "456557", "Score": "0", "body": "If an app needs to connect to both db1 & db2, the connections cannot be in the same pool. The connections are not interchangeable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T09:08:18.283", "Id": "456666", "Score": "0", "body": "OMG. dude, you didn't get it. A pool is for one db. For a different db, there should be a different pool. In such cases, you may need a pool factory to handover pool objects to you when you pass db info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T16:53:35.977", "Id": "456691", "Score": "0", "body": "What I'm saying is - making it a true Singleton - with private constructor and all makes it impossible to make different pools per db. So the better option is to keep it non-jvm-singleton. It can be instantiated through a factory or a DI framework" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-15T04:55:38.183", "Id": "128397", "ParentId": "40005", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:27:21.597", "Id": "40005", "Score": "31", "Tags": [ "java", "jdbc", "connection-pool" ], "Title": "Connection pool implementation" }
40005
<p>I've been working on a version of Conway's Game of Life for about a week now. It has loads of features like drawing onto the screen and saving/loading images. The problem is that ever since I added mouse support, it seems to start running pretty slowly. I don't know if it is due to the mouse or if it's something else. I'm a pretty newbie coder so I'd really like some help in optimizing this.</p> <p>Just noting: I didn't include any imports due to the character limit.</p> <p>Main Class</p> <pre><code>public class MainGame extends JFrame{ static int size = 721; static JFrame frame = new JFrame("Game of Life"); static Life life = new Life(size); Random r = new Random(); JLabel lblCellCount = new JLabel("Cell Count"); JLabel lblGeneration = new JLabel("Generation"); JSlider slider = new JSlider(); JButton play = new JButton("Pause"); JLabel lblSpeed = new JLabel("Speed: (10) ups"); public SaveLoad sl = new SaveLoad(); String[] patterns = sl.loadImages(new File(".\\Patterns\\")); final JFileChooser fc = new JFileChooser(); final DefaultComboBoxModel model; final JComboBox&lt;?&gt; cmboPatterns; Point start; public void runGameLoop(){ life.running = true; Thread loop = new Thread() { public void run(){ gameLoop(); } }; loop.start(); } public void gameLoop(){ System.out.println("Started"); final int MAX_UPDATES_BEFORE_RENDER = 5; double lastUpdateTime = System.nanoTime(); double lastRenderTime = System.nanoTime(); int lastSecondTime = (int) (lastUpdateTime / 1000000000); while(life.running){ final double GAME_HERTZ = (double) slider.getValue(); final double TIME_BETWEEN_UPDATES = 1000000000 / GAME_HERTZ; final double TARGET_FPS = (int) GAME_HERTZ; final double TARGET_TIME_BETWEEN_RENDERS = 1000000000 / TARGET_FPS; double now = System.nanoTime(); int updateCount = 0; if (!life.paused){ while(now - lastUpdateTime &gt; TIME_BETWEEN_UPDATES &amp;&amp; updateCount &lt; MAX_UPDATES_BEFORE_RENDER){ // update activeCells here changeText(life.countCells()); changeText(life.generation, true); life.checkCells(); lastUpdateTime += TIME_BETWEEN_UPDATES; updateCount++; } if (now - lastUpdateTime &gt; TIME_BETWEEN_UPDATES){ lastUpdateTime = now - TIME_BETWEEN_UPDATES; } // render to screen here life.fillCells(life.activeCells); lastRenderTime = now; int thisSecond = (int) (lastUpdateTime / 1000000000); if (thisSecond &gt; lastSecondTime){ lastSecondTime = thisSecond; } while(now - lastRenderTime &lt; TARGET_TIME_BETWEEN_RENDERS &amp;&amp; now - lastUpdateTime &lt; TIME_BETWEEN_UPDATES){ Thread.yield(); try{ Thread.sleep(1); } catch(Exception e){ } now = System.nanoTime(); } } } // System.out.println("Generations " + generation); //Thread.yield(); } public static void main(String[] args){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Throwable e){ e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run(){ try{ MainGame frame = new MainGame(); frame.setVisible(true); frame.setResizable(false); } catch(Exception e){ e.printStackTrace(); } } }); } public void changeText(int cells){ lblCellCount.setText("Live Cells: " + String.valueOf(cells)); } public void changeText(int generation, boolean gen){ lblGeneration.setText("Generation: " + String.valueOf(generation)); } @SuppressWarnings({"rawtypes", "unchecked"}) public MainGame(){ pack(); setTitle("Game Of Life"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(null); addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e){ int xCell = (e.getX() - getInsets().left) / life.CELL_SIZE; int yCell = (e.getY() - getInsets().top) / life.CELL_SIZE; if (life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; xCell &gt;= 0 &amp;&amp; yCell &gt;= 0 &amp;&amp; !life.activeCells[xCell][yCell] &amp;&amp; !SwingUtilities.isRightMouseButton(e)){ //life.fillCell(xCell, yCell, 0 - r.nextInt(16777215)); life.fillLine((int) (start.getX() - getInsets().left) / life.CELL_SIZE, (int) (start.getY() - getInsets().top) / life.CELL_SIZE, (int) (e.getPoint().getX() - getInsets().left) / life.CELL_SIZE, (int) (e.getPoint().getY() - getInsets().top) / life.CELL_SIZE, 0 - r.nextInt(16777215)); start = e.getPoint(); changeText(life.countCells()); } else if (!life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; xCell &gt;= 0 &amp;&amp; yCell &gt;= 0 &amp;&amp; !life.activeCells[xCell][yCell] &amp;&amp; !SwingUtilities.isRightMouseButton(e)){ //life.fillCell(xCell, yCell, -16777215); life.fillLine((int) (start.getX() - getInsets().left) / life.CELL_SIZE, (int) (start.getY() - getInsets().top) / life.CELL_SIZE, (int) (e.getPoint().getX() - getInsets().left) / life.CELL_SIZE, (int) (e.getPoint().getY() - getInsets().top) / life.CELL_SIZE, -16777215); start = e.getPoint(); //System.out.println("main x " + (e.getPoint().getX() - getInsets().left) / life.CELL_SIZE + " main y " + (e.getPoint().getY() - getInsets().top) / life.CELL_SIZE); changeText(life.countCells()); } else if (life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; SwingUtilities.isRightMouseButton(e)){ //life.emptyCell(xCell, yCell); life.emptyLine((int) (start.getX() - getInsets().left) / life.CELL_SIZE, (int) (start.getY() - getInsets().top) / life.CELL_SIZE, (int) (e.getPoint().getX() - getInsets().left) / life.CELL_SIZE, (int) (e.getPoint().getY() - getInsets().top) / life.CELL_SIZE); start = e.getPoint(); changeText(life.countCells()); } else if (!life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; SwingUtilities.isRightMouseButton(e)){ //life.emptyCell(xCell, yCell); life.emptyLine((int) (start.getX() - getInsets().left) / life.CELL_SIZE, (int) (start.getY() - getInsets().top) / life.CELL_SIZE, (int) (e.getPoint().getX() - getInsets().left) / life.CELL_SIZE, (int) (e.getPoint().getY() - getInsets().top) / life.CELL_SIZE); start = e.getPoint(); changeText(life.countCells()); } } @Override public void mouseMoved(MouseEvent e){ } }); addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e){ } @Override public void mouseEntered(MouseEvent e){ } @Override public void mouseExited(MouseEvent e){ } @Override public void mousePressed(MouseEvent e){ int xCell = (e.getX() - getInsets().left) / life.CELL_SIZE; int yCell = (e.getY() - getInsets().top) / life.CELL_SIZE; if (life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; !SwingUtilities.isRightMouseButton(e)){ life.fillCell(xCell, yCell, 0 - r.nextInt(16777215)); start = e.getPoint(); changeText(life.countCells()); } else if (!life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; !SwingUtilities.isRightMouseButton(e)){ life.fillCell(xCell, yCell, -16777215); start = e.getPoint(); changeText(life.countCells()); } else if (life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; SwingUtilities.isRightMouseButton(e)){ life.emptyCell(xCell, yCell); start = e.getPoint(); changeText(life.countCells()); } else if (!life.colour &amp;&amp; xCell &lt; life.activeCells.length &amp;&amp; yCell &lt; life.activeCells.length &amp;&amp; SwingUtilities.isRightMouseButton(e)){ life.emptyCell(xCell, yCell); start = e.getPoint(); changeText(life.countCells()); } } @Override public void mouseReleased(MouseEvent e){ } }); life.setBounds(0, 0, size, size); getContentPane().add(life); JPanel customisePanel = new JPanel(); customisePanel.setBounds(0, size, size, 35); getContentPane().add(customisePanel); customisePanel.setLayout(null); final JButton stop = new JButton("Restart"); stop.setBounds(8, 8, 75, 23); stop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ life.reset(); //life.generation = 0; changeText(life.countCells()); changeText(0, true); } }); customisePanel.add(stop); play.setBounds(90, 8, 75, 23); play.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0){ if (life.running){ life.running = false; play.setText("Play"); changeText(life.countCells()); } else{ life.running = true; runGameLoop(); play.setText("Pause"); } } }); customisePanel.add(play); JButton clear = new JButton("Clear"); clear.setBounds(172, 8, 75, 23); clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ life.running = false; life.generation = 0; changeText(0, true); play.setText("Play"); life.cls(); life.cls(); changeText(life.countCells()); } }); customisePanel.add(clear); JButton save = new JButton("Save..."); save.setBounds(254, 8, 75, 23); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ fc.setCurrentDirectory(new File(".\\Patterns\\")); life.running = false; changeText(0, true); play.setText("Play"); changeText(life.countCells()); int returnVal = fc.showSaveDialog(MainGame.this); if (returnVal == JFileChooser.APPROVE_OPTION){ File file = fc.getSelectedFile(); fc.setCurrentDirectory(file); sl.saveImage(life.activeCells, size / life.CELL_SIZE, file); } cmboPatterns.removeAllItems(); patterns = sl.loadImages(new File(".\\Patterns\\")); orderStrings(); for (int i = 0; i &lt; patterns.length; i++){ model.addElement(patterns[i]); } } }); customisePanel.add(save); // add the colour checkbox JCheckBox colour = new JCheckBox("Colourful"); colour.setBounds(size - 74, 8, 74, 23); colour.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e){ if (e.getStateChange() == ItemEvent.SELECTED){ life.colourCells(); } else{ life.deColourCells(); } } }); customisePanel.add(colour); orderStrings(); model = new DefaultComboBoxModel(patterns); cmboPatterns = new JComboBox&lt;Object&gt;(model); cmboPatterns.setBounds(size - colour.getWidth() - 210, 9, 120, 22); cmboPatterns.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ for (int i = 0; i &lt; patterns.length; i++){ if (i == cmboPatterns.getSelectedIndex()){ life.cls(); try{ Thread.sleep(1); } catch(InterruptedException e1){ e1.printStackTrace(); } life.cls(); life.generation = 0; changeText(life.generation, true); life.fillCells(sl.loadImage(patterns[i], life.activeCells, size / life.CELL_SIZE)); } } } }); customisePanel.add(cmboPatterns); lblCellCount.setBounds(size - colour.getWidth() - 80, 12, 100, 14); customisePanel.add(lblCellCount); lblGeneration.setBounds(336, 12, 100, 14); lblGeneration.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0){ } @Override public void mouseEntered(MouseEvent arg0){ } @Override public void mouseExited(MouseEvent arg0){ } @Override public void mousePressed(MouseEvent arg0){ life.generation = 0; changeText(0, true); } @Override public void mouseReleased(MouseEvent arg0){ } }); customisePanel.add(lblGeneration); JPanel panel = new JPanel(); panel.setLayout(null); panel.setBounds(0, size + customisePanel.getHeight(), size, 46); getContentPane().add(panel); slider.setSnapToTicks(true); slider.setPaintTicks(true); slider.setValue(10); slider.setMinimum(1); slider.setMaximum(50); slider.setBounds(0, 0, size, 28); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0){ lblSpeed.setText("Speed: (" + String.valueOf(((JSlider) arg0.getSource()).getValue()) + ") ups"); slider.repaint(); } }); panel.add(slider); lblSpeed.setHorizontalAlignment(SwingConstants.CENTER); lblSpeed.setBounds(size / 2 - (80 / 2), 26, 80, 14); panel.add(lblSpeed); setBounds(0, 0, size + getInsets().left * 2 - 2, size + panel.getHeight() + customisePanel.getHeight() + 30); // start the game runGameLoop(); } /* * File.toString() returns a weird filepath so this changes that * to something i can easily understand and manipulate. */ public void orderStrings(){ for (int i = 0; i &lt; patterns.length; i++){ if (patterns[i].length() &gt; 2){ if (patterns[i].substring(patterns[i].length() - 4).equals(".png")){ patterns[i] = patterns[i].substring(0, patterns[i].length() - 4); } if (patterns[i].substring(0, 11).equals(".\\Patterns\\")) patterns[i] = patterns[i].substring(11); } } } } </code></pre> <p>Class that handles the actual game panel</p> <pre><code>public class Life extends JPanel{ //idk why this is here, eclipse puts it in automatically private static final long serialVersionUID = 1L; private BufferedImage canvas; private Random r = new Random(); private boolean[][] tempArray; boolean[][] activeCells; public final int CELL_SIZE = 8; public int generation = 0; public int cellCount = 0; public boolean colour = false; public boolean running = false; public boolean paused = false; /* * Life Constructor, creates the main image that gets put onto the JPanel */ public Life(int size){ canvas = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); fillCanvas(Color.WHITE); activeCells = new boolean[canvas.getWidth() / CELL_SIZE][canvas.getHeight() / CELL_SIZE]; tempArray = new boolean[canvas.getWidth() / CELL_SIZE][canvas.getHeight() / CELL_SIZE]; activeCells = randArray(activeCells); //drawGrid(CELL_SIZE, CELL_SIZE); fillCells(activeCells); //printArray(activeCells); } /* * Resets the game with a full set of random data */ public void reset(){ //fillCanvas(Color.WHITE); activeCells = randArray(activeCells); generation = 0; //drawGrid(CELL_SIZE, CELL_SIZE); fillCells(activeCells); } /* * Uses a temporary version of the activeCells array (tempCells) * and updates it by checking through the neighbours method. */ public void checkCells(){ int size = activeCells.length; boolean[][] tempCells = new boolean[size][size]; for (int i = 0; i &lt; size; i++){ for (int j = 0; j &lt; size; j++){ tempCells[i][j] = activeCells[i][j]; } } for (int row = 0; row &lt; activeCells.length; row++){ for (int col = 0; col &lt; activeCells[row].length; col++){ int n = neighbours(row, col); if (n &gt; 3 || n &lt; 2) tempCells[row][col] = false; else if (n == 3) tempCells[row][col] = true; else tempCells[row][col] = activeCells[row][col]; } } activeCells = tempCells; generation++; } /* * Loops through a 3x3 grid around the selected cell (row, col) * and returns the amount of true cells (no. of "neighbours") */ public int neighbours(int row, int col){ int count = 0; for (int i = row - 1; i &lt;= row + 1; i++){ for (int j = col - 1; j &lt;= col + 1; j++){ try{ if (activeCells[i][j] == true &amp;&amp; (i != row || j != col)){ count++; } } catch(ArrayIndexOutOfBoundsException f){ continue; } } } return count; } /* * Returns the number of true values in activeCells */ public int countCells(){ int count = 0; for (int i = 0; i &lt; activeCells.length; i++){ for (int j = 0; j &lt; activeCells[i].length; j++){ if (activeCells[i][j]) count++; } } cellCount = count; return count; } /* * Loops through the given array and returns it filled with random data */ public boolean[][] randArray(boolean[][] array){ for (int i = 0; i &lt; array.length; i++){ for (int j = 0; j &lt; array[i].length; j++){ if (r.nextInt(5) == 1) array[i][j] = true; else array[i][j] = false; } } return array; } /* * Fills all cells on screen with data from array. Also checks whether to * colour each cell or not. */ public void fillCells(boolean[][] array){ for (int i = 0; i &lt; array.length; i++){ for (int j = 0; j &lt; array[i].length; j++){ if (colour &amp;&amp; !tempArray[i][j] &amp;&amp; array[i][j]) fillCell(i, j, 0 - r.nextInt(16777215)); else if (array[i][j] &amp;&amp; !colour) fillCell(i, j, Color.BLACK.getRGB()); else if (!array[i][j]) emptyCell(i, j); tempArray[i][j] = array[i][j]; } } } //Interpolates between two points because just drawing onto the screen didn't update fast enough public void fillLine(int x1, int y1, int x2, int y2, int colour){ double m; if (x2 - x1 == 0){ if (y1 &lt; y2){ for (int i = y1; i &lt; y2; i++){ fillCell(x2, i, colour); } } else{ for (int i = y2; i &lt; y1; i++){ fillCell(x2, i, colour); //System.out.println("xFilling point (" + x2 + ", " + i + ")"); } } } else{ double dx = x1 - x2; double dy = y1 - y2; m = dy / dx; double c = y1 - (m * x1); if (x1 &lt; x2 &amp;&amp; m &gt;= 1){ for (int i = y1; i &lt; y2; i++){ double x = (i - c) / m; fillCell((int) x, i, colour); //System.out.println("Filling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } else if (x1 &lt; x2 &amp;&amp; m &lt;= 1 &amp;&amp; m &gt;=-1){ for (int i = x1; i &lt; x2; i++){ double y = (i * m) + c; fillCell(i, (int) y, colour); //System.out.println("Filling point (" + (i) + ", " + (int) y + "). gradient: " + m); } } else{ for (int i = y2; i &lt; y1; i++){ double x = (i - c) / m; fillCell((int) x, i, colour); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } if (y1 &lt; y2 &amp;&amp; m &lt;= -1){ for (int i = y1; i &lt; y2; i++){ double x = (i - c) / m; fillCell((int) x, i, colour); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } else if (y2 &lt; y1 &amp;&amp; m &gt;= 1){ for (int i = y2; i &lt; y1; i++){ double x = (i - c) / m; fillCell((int) x, i, colour); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } else{ for (int i = x2; i &lt; x1; i++){ double y = (i * m) + c; fillCell(i, (int) y, colour); //System.out.println("pFilling point (" + (i) + ", " + (int) y + "). gradient: " + m); } } } } /* * Colours all current active cells */ public void colourCells(){ for (int i = 0; i &lt; activeCells.length; i++){ for (int j = 0; j &lt; activeCells[i].length; j++){ if (activeCells[i][j]) fillCell(i, j, 0 - r.nextInt(16777215)); } } colour = true; } /* * Turns all current active cells black * * Could have put both colourCells and deColourCells together in one with a parameter * but it would have ended up being the same if not more code anyway. */ public void deColourCells(){ for (int i = 0; i &lt; activeCells.length; i++){ for (int j = 0; j &lt; activeCells[i].length; j++){ if (activeCells[i][j]) fillCell(i, j, -16777215); } } colour = false; } /* * Colours the cell at (x, y) white and makes the correspoding activeCells = false */ public void emptyCell(int x, int y){ int colour = Color.WHITE.getRGB(); for (int i = 0; i &lt; CELL_SIZE; i++){ //CELL_SIZE-1 for grid for (int j = 0; j &lt; CELL_SIZE; j++){ //same here canvas.setRGB(x * CELL_SIZE + 1 + i, y * CELL_SIZE + 1 + j, colour); } } activeCells[x][y] = false; repaint(); } /* * Clears the screen by calling emtpyCell and making activeCells false; * could probably remove the emptyCell part and just have it paint the * whole screen white. This was for when i had a grid in aswell. * * edit: done */ public void cls(){ for (int i = 0; i &lt; activeCells.length; i++){ for (int j = 0; j &lt; activeCells[i].length; j++){ activeCells[i][j] = false; //emptyCell(i, j); } } fillCanvas(Color.WHITE); } /* * Fills the set cell with the set colour */ public void fillCell(int x, int y, int rgb){ //System.out.println(Color.BLACK.getRGB()); //int colour = Color.BLACK.getRGB(); for (int i = 0; i &lt; CELL_SIZE; i++){ //CELL_SIZE-1 for grid for (int j = 0; j &lt; CELL_SIZE; j++){ //same here canvas.setRGB(x * CELL_SIZE + 1 + i, y * CELL_SIZE + 1 + j, rgb); } } activeCells[x][y] = true; repaint(); } /* * Draws a grid onto the screen with the given cell width and height */ public void drawGrid(int height, int width){ int colour = Color.BLACK.getRGB(); for (int i = 0; i &lt; canvas.getWidth(); i++){ for (int j = 0; j &lt; canvas.getHeight(); j++){ if (j % width == 0) canvas.setRGB(i, j, colour); if (i % height == 0) canvas.setRGB(i, j, colour); } } repaint(); } /* * Sets the size of the JPanel */ public Dimension getPreferredSize(){ return new Dimension(canvas.getWidth(), canvas.getHeight()); } /* * Handles painting to the canvas */ public void paintComponent(Graphics g){ super.paintComponents(g); Graphics2D g2 = (Graphics2D) g; g2.drawImage(canvas, null, null); } /* * Fills the entire canvas with the given colour */ public void fillCanvas(Color c){ int colour = c.getRGB(); for (int x = 0; x &lt; canvas.getWidth(); x++){ for (int y = 0; y &lt; canvas.getHeight(); y++){ canvas.setRGB(x, y, colour); } } repaint(); } /* * Prints the array to the console, for debugging. */ public void printArray(boolean[][] array){ for (int i = 0; i &lt; array.length; i++){ for (int j = 0; j &lt; array[i].length; j++){ if (array[i][j] == true) System.out.print("1 "); if (array[i][j] == false) System.out.print("0 "); } System.out.println(); } } public void emptyLine(int x1, int y1, int x2, int y2){ double m; if (x2 - x1 == 0){ if (y1 &lt; y2){ for (int i = y1; i &lt; y2; i++){ emptyCell(x2, i); } } else{ for (int i = y2; i &lt; y1; i++){ emptyCell(x2, i); //System.out.println("Filling point (" + x2 + ", " + i + ")"); } } } else{ double dx = x1 - x2; double dy = y1 - y2; m = dy / dx; double c = y1 - (m * x1); if (x1 &lt; x2 &amp;&amp; m &gt;= 1){ for (int i = y1; i &lt; y2; i++){ double x = (i - c) / m; emptyCell((int) x, i); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } else if (x1 &lt; x2 &amp;&amp; m &lt;= 1 &amp;&amp; m &gt;=-1){ for (int i = x1; i &lt; x2; i++){ double y = (i * m) + c; emptyCell(i, (int) y); //System.out.println("Filling point (" + (i) + ", " + (int) y + "). gradient: " + m); } } else{ for (int i = y2; i &lt; y1; i++){ double x = (i - c) / m; emptyCell((int) x, i); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } if (y1 &lt; y2 &amp;&amp; m &lt;= -1){ for (int i = y1; i &lt; y2; i++){ double x = (i - c) / m; emptyCell((int) x, i); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } else if (y2 &lt; y1 &amp;&amp; m &gt;= 1){ for (int i = y2; i &lt; y1; i++){ double x = (i - c) / m; emptyCell((int) x, i); //System.out.println("yFilling point (" + (i) + ", " + (int) x + "). gradient: " + m); } } else{ for (int i = x2; i &lt; x1; i++){ double y = (i * m) + c; emptyCell(i, (int) y); //System.out.println("pFilling point (" + (i) + ", " + (int) y + "). gradient: " + m); } } } } } </code></pre> <p>Class for handling Saving and loading</p> <pre><code>public class SaveLoad{ private BufferedImage canvas; private File f; /* * Saves the current activeCells array to a png by first * creating a BufferedImage of the data and then writing * it to file. */ public void saveImage(boolean[][] array, int size, File file){ canvas = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); for (int i = 0; i &lt; size; i++){ for (int j = 0; j &lt; size; j++){ if (array[i][j]) canvas.setRGB(i, j, Color.BLACK.getRGB()); else canvas.setRGB(i, j, Color.WHITE.getRGB()); } } try{ File outputFile = new File(file.toString() + ".png"); ImageIO.write(canvas, "png", outputFile); System.out.println(file.toString() + ".png Save Successfully!"); } catch(IOException e){ System.out.println("Something went wrong..."); } } /* * Returns all pngs found in the current directory in the * format of an array of Strings */ public String[] loadImages(File dir){ String[] files; File[] all = dir.listFiles(); int pngs = 0; for (int i = 0; i &lt; all.length; i++){ if (all[i].toString().indexOf(".png") != -1){ pngs++; } } files = new String[pngs]; pngs = 0; for (int i = 0; i &lt; all.length; i++){ if (all[i].toString().indexOf(".png") != -1){ files[pngs] = all[i].toString(); pngs++; } } return files; } /* * Converts a png into a 2d array of booleans which can then * be used to fill cells on the screen. */ public boolean[][] loadImage(String file, boolean[][] array, int size){ f = new File(".\\Patterns\\" + file + ".png"); try{ canvas = ImageIO.read(f); } catch(IOException e){ // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i &lt; size; i++){ for (int j = 0; j &lt; size; j++){ if (canvas.getRGB(i, j) == Color.BLACK.getRGB()) array[i][j] = true; } } return array; } } </code></pre> <p>Sorry for including all of my code, but it's because I don't really know where the problem lies, and it could be all over.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:40:51.350", "Id": "67196", "Score": "0", "body": "If you comment-out the mouse-support code, does it run quickly again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T00:46:12.663", "Id": "67198", "Score": "4", "body": "MouseMotionListener is likely eating a lot of CPU cycles. Would a simple click listener be good enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:02:45.127", "Id": "67252", "Score": "0", "body": "@TeresaCarrigan Expand a little on that and you have a nice answer to this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:03:39.287", "Id": "67253", "Score": "0", "body": "And to anyone and everyone: It wouldn't hurt to review the rest of the code here as well, there are probably a lot of things that can be cleaned up..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T23:40:35.780", "Id": "67300", "Score": "0", "body": "Commenting out the mouse code doesn't seem to affect the speed of the program. @TeresaCarrigan I don't know how i would put the complicated mouse support code into another method because it requires the use of the MouseEvent e, also I like the fact that I can draw on the screen while it is running so pausing, drawing, then running again isn't really what i want (which you can do at the moment, but you can also do it live)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:25:14.527", "Id": "67304", "Score": "0", "body": "I am surprised that commenting out the mouse code doesn't help. As for moving the mouse support code into another method, you would take values such as e.getX() and pass them as parameters in the method call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T21:46:14.893", "Id": "67430", "Score": "0", "body": "I think it may be that you are using both a MousePressed event and a MouseDragged event and doing the same thing with both events. Have you tried removing the code from the MousePressed and just using the MouseDragged code instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:26:11.423", "Id": "67597", "Score": "0", "body": "@RoddyoftheFrozenPeas Doing this probably wouldn't affect eh speed (although i will test it when i get home) because commenting out all the mouse code doesn't affect it. Also I'd like to keep in the functionality of being able to just draw one cell at a time with clicking." } ]
[ { "body": "<p>As @ChrisW mentioned: if you comment out the mouse support code, does it run quickly again? If this is the case, then changing from using a MouseMotionListener to a simple MouseListener, and check for a click instead of a drag. </p>\n\n<p>Another thing that might help is if you move complicated code out of the body of the listener method. Just making a separate method to do the task and having a call to this method will make the code easier to read, but if you are still seeing problems with the code running slowly you may want to have the listener method spawn a thread to do the updating.</p>\n\n<p>Another possibility is to have two modes of running the simulation. Add a pause button which stops the generations and enables the mouse listener. After the user makes changes, she can press a resume button which disables the mouse listener. This makes the logic easier as well, since you don't have to worry about cells changing state while you are trying to calculate the next generation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T13:29:46.883", "Id": "40037", "ParentId": "40008", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:24:10.713", "Id": "40008", "Score": "8", "Tags": [ "java", "optimization", "beginner", "game-of-life" ], "Title": "Game Of Life optimization in Java" }
40008
<p>For some reporting, I need to print a human readable date string for the week covered by the report, using just the standard python module library. So the strings should look like:</p> <blockquote> <p>Dec 29, 2013 - Jan 4, 2014</p> <p>Jan 26 - Feb 1, 2014</p> <p>Jan 19 - 25, 2014</p> </blockquote> <p>Below is a script I threw together to achieve this. But is there a simpler way to do this?</p> <pre><code>from datetime import (datetime, date, timedelta) def week_string(dt): (year, week, weekday) = dt.isocalendar() week_0 = dt - timedelta(days=weekday) week_1 = dt + timedelta(days=(6-weekday)) month_0 = week_0.strftime("%b") day_0 = week_0.strftime("%e").strip() year_0 = week_0.strftime("%Y") month_1 = week_1.strftime("%b") day_1 = week_1.strftime("%e").strip() year_1 = week_1.strftime("%Y") if year_0 != year_1: return "%s %s, %s - %s %s, %s" %( month_0, day_0, year_0, month_1, day_1, year_1) elif month_0 != month_1: return "%s %s - %s %s, %s" %( month_0, day_0, month_1, day_1, year_1) else: return "%s %s - %s, %s" %( month_0, day_0, day_1, year_1) print week_string(date(2013, 12, 30)) print week_string(date(2014, 01, 30)) print week_string(datetime.date(datetime.now())) </code></pre> <p>Since the report script is going to be shared with other people, I want to avoid adding dependencies on anything they'd need to install.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:17:17.790", "Id": "67451", "Score": "0", "body": "`datetime` is part of the standard library, so they wouldn't need to install anything aside from basic Python" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:18:27.513", "Id": "67452", "Score": "0", "body": "Right, I just mean I'm interested in answers that stick with basic Python modules, as I know there are many non-core modules that handle date formatting." } ]
[ { "body": "<p>You have a bug: if <code>dt</code> is a Sunday, then it outputs the date range starting from the previous Sunday. That is because <a href=\"http://docs.python.org/2/library/datetime.html?highlight=isocalendar#datetime.date.isocalendar\"><code>datetime.isocalendar()</code></a> represents the day of week as a number from 1 (= Monday) to 7 (= Sunday), but you want to subtract 0 to 6 days.</p>\n\n<blockquote>\n<pre><code>&gt;&gt;&gt; print week_string(date(2014, 01, 19))\nJan 12 - 18, 2014\n</code></pre>\n</blockquote>\n\n<p>My recommendation:</p>\n\n<pre><code>def week_string(dt):\n # Use underscore to indicate disinterest in the year and week\n _, _, weekday = dt.isocalendar()\n week_0 = dt - timedelta(days=weekday % 7) # Sunday\n week_1 = week_0 + timedelta(days=6) # Saturday\n</code></pre>\n\n<p>Then, I would write the following six lines more compactly:</p>\n\n<pre><code> day_0, month_0, year_0 = week_0.strftime('%e-%b-%Y').lstrip().split('-')\n day_1, month_1, year_1 = week_1.strftime('%e-%b-%Y').lstrip().split('-')\n</code></pre>\n\n<p>The rest of it seems fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:15:42.430", "Id": "67557", "Score": "0", "body": "Thanks for catching the bug, yes you're right." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T07:03:10.570", "Id": "40026", "ParentId": "40012", "Score": "7" } }, { "body": "<p><strong>Variable Names</strong>:</p>\n\n<p><code>week_0</code> and <code>week_1</code> are not helpful names. Firstly, neither contains an object that represents a week.</p>\n\n<p>More importantly, what makes <code>week_0</code> different from <code>week_1</code>? Seeing numbers used as a suffix makes me think that they are just generic values that could be stored in a list. However, in this case, they are very distinct things. <code>week_start</code> and <code>week_end</code> provide a better description for someone reading the code for the first time.</p>\n\n<p><strong>Repeated Code</strong>:</p>\n\n<p>Extracting the month, day, and year values is the same process for both date times. This should be extracted into a function that you call twice.</p>\n\n<p><strong>Building the String</strong>:\nI don't have any issues with this part of the code. But, as I was reviewing this section of the code, I decided that I would write the bulk of the function differently. I would compare the dates in order to choose a format string instead of what is done here.</p>\n\n<pre><code>if week_start.year != week_end.year:\n frmt = \"{0:%b} {0.day}, {0.year} - {1:%b} {1.day}, {1.year}\"\nelif week_start.month != week_end.month:\n frmt = \"{0:%b} {0.day} - {1:%b} {1.day}, {1.year}\"\nelse:\n frmt = \"{0:%b} {0.day} - {1.day}, {1.year}\"\n\nreturn frmt.format(week_start, week_end)\n</code></pre>\n\n<p>This way, you don't have to manually extract the date parts. It also makes the format strings easier to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:16:21.387", "Id": "67558", "Score": "0", "body": "Yes, I chose brevity over clarity on the variable names; guilty!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:17:36.063", "Id": "67559", "Score": "0", "body": "Huh, I haven't ever used that formatting approach before. Learn something new every day!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:57:54.237", "Id": "67573", "Score": "1", "body": "@Bryce: To be honest, I didn't know that curly format strings were _that_ powerful. I stumbled on to it when I was trying to figure out what `%e` did. But I'm glad I did because the end result turned out very readable." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T05:26:11.923", "Id": "40137", "ParentId": "40012", "Score": "6" } }, { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>There's no docstring. What does the <code>week_string</code> function do, and how should I call it? In particular, what is the meaning of the <code>dt</code> argument?</p></li>\n<li><p>You've put your test cases at top level in the script. This means that they get run whenever the script is loaded. It would be better to refactor the test cases into <a href=\"http://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unit tests</a> or <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctests</a>.</p></li>\n<li><p>Your code is not portable to Python 3 because the test cases use the statement form of <code>print</code>.</p></li>\n<li><p>You import <code>datetime.datetime</code> but don't use it. And you import <code>datetime.date</code> but only use it in the test cases.</p></li>\n<li><p>There's no need for parentheses in these lines:</p>\n\n<pre><code>from datetime import (datetime, date, timedelta)\n(year, week, weekday) = dt.isocalendar()\n</code></pre></li>\n<li><p>The variables are poorly named, <a href=\"https://codereview.stackexchange.com/a/40137/11728\">as explained by unholysampler</a>.</p></li>\n<li><p>You format the components (year, month, day) of the dates and then compare the formatted components:</p>\n\n<pre><code>year_0 = week_0.strftime(\"%Y\")\nyear_1 = week_1.strftime(\"%Y\")\nif year_0 != year_1:\n # ...\n</code></pre>\n\n<p>but it would make more sense to compare the <code>year</code> property of the dates directly:</p>\n\n<pre><code>if begin.year != end.year:\n # ...\n</code></pre></li>\n<li><p>The <code>%e</code> format code for <code>srtftime</code> was not defined by the C89 standard and so may not be portable to all platforms where Python runs. See the <a href=\"http://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior\" rel=\"nofollow noreferrer\"><code>strftime</code> documentation</a> where this is noted. Also, even where implemented, the <code>%e</code> format code outputs a leading space which doesn't seem appropriate in your case.</p>\n\n<p>So I would follow <a href=\"https://codereview.stackexchange.com/a/40137/11728\">unholysampler's technique</a> and use Python's string formatting operation on the <code>day</code> field of the date objects.</p></li>\n<li><p>Date-manipulating code is often tricky, and you made a mistake in the case where <code>dt</code> is on a Sunday, <a href=\"https://codereview.stackexchange.com/a/40026/11728\">as pointed out by 200_success</a>. So it would be worth putting in some assertions to check that the manipulations are correct. You can see in the revised code below that I've added assertions checking that <code>begin</code> is on a Sunday, that <code>end</code> is on a Saturday, and that <code>d</code> lies between these two dates.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>from datetime import timedelta\n\ndef week_description(d):\n \"\"\"Return a description of the calendar week (Sunday to Saturday)\n containing the date d, avoiding repetition.\n\n &gt;&gt;&gt; from datetime import date\n &gt;&gt;&gt; week_description(date(2013, 12, 30))\n 'Dec 29, 2013 - Jan 4, 2014'\n &gt;&gt;&gt; week_description(date(2014, 1, 25))\n 'Jan 19 - 25, 2014'\n &gt;&gt;&gt; week_description(date(2014, 1, 26))\n 'Jan 26 - Feb 1, 2014'\n\n \"\"\"\n begin = d - timedelta(days=d.isoweekday() % 7)\n end = begin + timedelta(days=6)\n\n assert begin.isoweekday() == 7 # Sunday\n assert end.isoweekday() == 6 # Saturday\n assert begin &lt;= d &lt;= end\n\n if begin.year != end.year:\n fmt = '{0:%b} {0.day}, {0.year} - {1:%b} {1.day}, {1.year}'\n elif begin.month != end.month:\n fmt = \"{0:%b} {0.day} - {1:%b} {1.day}, {1.year}\"\n else:\n fmt = \"{0:%b} {0.day} - {1.day}, {1.year}\"\n\n return fmt.format(begin, end)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:19:01.287", "Id": "67560", "Score": "0", "body": "Thanks, this is a very thorough review, and all good advice. Thanks for including the revised (and much improved) code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:13:08.823", "Id": "40151", "ParentId": "40012", "Score": "4" } } ]
{ "AcceptedAnswerId": "40151", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T00:24:10.703", "Id": "40012", "Score": "8", "Tags": [ "python", "strings", "datetime" ], "Title": "Printing a week range string in Python" }
40012
<p>Here is my functional approach to split a list into sub lists, each having non-decreasing numbers, so the input </p> <p>\$[1; 2; 3; 2; 4; 1; 5;]\$</p> <p>computes to</p> <p>\$[[1; 2; 3]; [2; 4]; [1; 5]]\$</p> <p>The code works, but I need a while to understand it. I would prefer a solution that is more clear. Is there a way to make this more elegant or readable? Everything is allowed, F# mutables as well. Or do I just get used more to functional code reading?</p> <p>The subsets are called "run"s in the code below.</p> <pre><code>// returns a single run and the remainder of the input let rec takerun input = match input with | [] -&gt; [], [] | [x] -&gt; [x], [] | x :: xr -&gt; if x &lt; xr.Head then let run, remainder = takerun xr x :: run, remainder else [x], xr // returns the list of all runs let rec takeruns input = match takerun input with | run, [] -&gt; [run] | run, rem -&gt; run :: takeruns rem let runs = takeruns [1; 2; 3; 2; 4; 1; 5;] &gt; val runs : int list list = [[1; 2; 3]; [2; 4]; [1; 5]] </code></pre> <p><strong>Edit:</strong></p> <p>Considering the helpful feedback I ended up with this reusable code. And got more used to functional programming, comparing imperative alternatives I meanwhile find the pure functional approach more readable. This version is good readable, although not tail recursive. For the small lists I had to deal with, readability was preferred.</p> <pre><code>// enhance List module module List = // splits list xs into 2 lists, based on f(xn, xn+1) let rec Split f xs = match xs with | [] -&gt; [], [] | [x] -&gt; [x], [] | x1 :: x2 :: xr when f x1 x2 -&gt; [x1], x2 :: xr // split on first f(xn, xn+1) | x :: xr -&gt; let xs1, xs2 = Split f xr x :: xs1, xs2 // Now takruns becomes quite simple let rec takeruns input = match List.Split (&gt;) input with | run, [] -&gt; [run] | run, rem -&gt; run :: takeruns rem let runs = takeruns [1; 2; 3; 2; 4; 1; 5;] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T02:00:54.930", "Id": "67216", "Score": "1", "body": "\"Consecutive\" would mean two integers (a, b) such that b = a + 1. It doesn't change the essence of the problem, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T10:06:25.197", "Id": "67248", "Score": "0", "body": "thx for the heads up" } ]
[ { "body": "<p>Haskell:</p>\n\n<pre><code>import Data.List.HT -- or Data.List.Grouping\n\ntakeruns xs@(x:xss) = map (map fst) pss\n where pss = segmentAfter (uncurry (&gt;)) $ zip xs xss\n</code></pre>\n\n<p><strong>EDIT</strong><br>\nExample:</p>\n\n<pre><code>xs = [1, 2, 3, 2, 4, 1, 5]\nxss = [2, 3, 2, 4, 1, 5]\nzip xs xss = [(1, 2), (2, 3), (3, 2), (2, 4), (4, 1)]\nuncurry (&gt;) (1, 2) == 1 &gt; 2 = False\nsegmentAfter ... = [\n [(1, 2) /* False */, (2, 3) /* False */, (3, 2) /* True */],\n [(2, 4) /* False */, (4, 1) /* True */],\n []\n]\nmap (map fst) (segmentAfter ...) = [[1, 2, 3], [2, 4], []]\n</code></pre>\n\n<p>And, it turns out that my function is wrong :)\nCorrect version:</p>\n\n<pre><code>takeruns xs = map (map snd) pss\n where pss = segmentAfter (uncurry (&gt;)) $ zip (minBound:xs) xs\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T08:45:21.950", "Id": "67239", "Score": "3", "body": "This is not exactly a helpful code review. At least you should try and explain the solution in haskell and in how far it could be applied to other functional language as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T08:56:18.070", "Id": "67242", "Score": "1", "body": "@ChrisWue I really don't know what to add to my answer. TS asked for \"more readable or elegant version\" -- my amost one-liner is not very readable, but probably the shortest. Initially TS mentioned Haskell" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T09:19:11.423", "Id": "67244", "Score": "0", "body": "thx for the helpful input. i realize that plain f# simply lacks some reusable functional basics, like Haskell's segmentAfter which can be found at http://hackage.haskell.org/package/utility-ht-0.0.1/docs/src/Data-List-HT-Private.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:23:20.940", "Id": "67275", "Score": "0", "body": "leventov, perhaps you could explain your code a bit more? **How** does it do what it does?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:40:07.983", "Id": "67277", "Score": "0", "body": "@SimonAndréForsberg see edit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:42:13.877", "Id": "67278", "Score": "0", "body": "Better :) Now you found that the original was incorrect as well :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T06:27:14.683", "Id": "40024", "ParentId": "40013", "Score": "4" } }, { "body": "<p>Since there is only one solution using sequences and one in Haskell, I thought that I still might post my code:</p>\n\n<pre><code>let partition list =\n let rec aux =\n function\n | trg,acc,[] -&gt; acc::trg\n | trg,a::acc,x::xs when x&lt;a \n -&gt; aux ((a::acc)::trg,[x],xs)\n | trg,acc,x::xs -&gt; aux (trg,x::acc,xs)\n aux ([],[],list)|&gt; List.map (List.rev) |&gt; List.rev\n</code></pre>\n\n<p>Of course, running through the list twice as in the last line is bad (performance wise), however this could be easily solved by a custom <code>revMap</code> function that reverses and maps at the same time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-09T19:57:37.467", "Id": "46747", "ParentId": "40013", "Score": "4" } }, { "body": "<p>Using List.foldBack</p>\n\n<pre><code>let insert e state = \n match state with\n | cur::rest -&gt;\n match cur with\n | h::_ when e &lt; h -&gt; (e::cur)::rest // add e to current list\n | _ -&gt; [e]::state // start a new list \n | _ -&gt; [[e]]\n\nList.foldBack insert [1;2;3;2;4;1;5;] []\n\nval insert : e:'a -&gt; state:'a list list -&gt; 'a list list when 'a : comparison\nval it : int list list = [[1; 2; 3]; [2; 4]; [1; 5]] \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-24T15:42:59.813", "Id": "48063", "ParentId": "40013", "Score": "4" } }, { "body": "<p>A version that uses <code>List.foldBack</code> and <code>List.pairwise</code></p>\n\n<pre><code>let split lst =\n let folder (a, b) (cur, acc) = \n match a with\n | _ when a &lt; b -&gt; a::cur, acc\n | _ -&gt; [a], cur::acc\n\n let result = List.foldBack folder (List.pairwise lst) ([List.last lst], []) \n (fst result)::(snd result)\n\nprintfn \"%A\" (split [1; 2; 3; 2; 2; 4; 1; 5;])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-18T14:53:39.753", "Id": "203933", "ParentId": "40013", "Score": "3" } } ]
{ "AcceptedAnswerId": "203933", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T00:44:25.273", "Id": "40013", "Score": "10", "Tags": [ "functional-programming", "f#" ], "Title": "Functional approach to splitting list into sub lists" }
40013
<p><em>EDIT: Here's my totally-revised PHP...</em></p> <pre><code>$text = preg_replace("~[^ a-z0-9'-]~"," ",strtolower($INPUT)); for($i=1;$i&lt;strlen($text)-1;$i++) { if(preg_match("~['-]~",$text[$i]) &amp;&amp; ( !preg_match("~[a-z0-9]~",$text[$i-1]) || !preg_match("~[a-z0-9]~",$text[$i+1])) ){ $text[$i] = " "; } } while( preg_match ("~ ~",$text) ) $text = preg_replace( "~ ~", " ", $text); if(preg_match("~[' -]~",$text[0])) $text = substr($text,1,strlen($text)-1); if(preg_match("~[' -]~",$text[strlen($text)-1])) $text = substr($text,0,strlen($text)-2); </code></pre> <p><em>Now, what I'd said still applies..</em></p> <p>This regex seems to work for me, but I'm curious if anyone can think of a breaking case, or tell me anything I did wrong.</p> <p><strike>(If it seems the code does what I say I want it do to, say so, then for fun you can help me become more neurotic about what I actually want it to do, which hinges on the question of defining an English "word".)</strike></p> <p>Desired final form of $text: replace, with spaces, all characters in $INPUT <em>except</em> for letters, digits, and any hyphens or apostrophes that are directly between two letters/digits (and hence "part of a word"). Then collapse all whitespace into single spaces, and if necessary, drop the leading and closing space.</p> <p>End result should be a lowercase series of words separated by spaces, of which some words may contain (entirely "inside" the word) one or more non-consecutive apostraphes, and/or one or more non-consecutive hyphens.</p> <p>Does this do that, with no exceptions?</p> <p>After this step, the next part will be to split (or explode, whichever is better) the string by spaces, then generate a list of words and frequencies. I'm pretty sure how to do that on my own (especially because my teacher actually told us two algorithms). In fact I'll probably hand the assignment in before choosing an answer to this; I'm mostly asking out of curiosity.</p> <p><strike>My thinking is...</p> <ul> <li>English "words" tend to be case insensitive for distinction (though there is the proper noun issue, which I'll just ignore).</li> <li>Some "words" are digits (The word <em>88</em>), or include digits, like <em>2Pac</em> or <em>se7en</em>.</li> <li>An apostrophe can also be a single quote, so it shouldn't be considered part of the word in case that's the intention, even though it sometimes might be, as with <em>What is goin' on?</em> (Fortunately, "proper" contractions don't begin or end with an apostrophe.)</li> <li>Hyphens can occur at the beginning or end of a word, but that doesn't make for a distinct word (<em>An eater asked if I was a fire-juggler or -eater</em> has two *eater*s, not one with the hyphen and one without).</li> <li>Two or more consecutive hyphens are meant as a dash of some kind, separating words</li> <li>Two consecutive apostrophes are likewise assumed to separate words, despite typos like <em>don''t</em></li> <li>In general, digits, hyphens, and apostrophes are the only relevant "non-letter letters" for word-frequency counting.</li> <li>Despite all my overthinking here, I don't actually want to be maximally thorough, just "good enough" (and "good enough" is the question I'm ovethinking!).</strike></li> </ul> <p>Old code:</p> <pre><code>$text = preg_replace( "~((?&lt;![a-z0-9])[-'](?![a-z0-9]))|([^ a-z0-9'-])~", " ", strtolower($INPUT)); while(preg_match("~ ~",$text)) $text = str_replace(" ", " ", $text); if($text[0] == " ") $text = substr($text,1,strlen($text)-2); if($text[strlen($text)-1] == " ") $text = substr($text,0,strlen($text)-2); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:02:44.683", "Id": "67200", "Score": "0", "body": "And I just found one exception: \"a--b\" should be changed to \"a b\" but is left unchanged. Hmm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:07:24.173", "Id": "67206", "Score": "0", "body": "Okay, my exceptions are piling up. Forget the complicated parts, I'll scratch those out of the original." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T02:55:50.073", "Id": "67218", "Score": "0", "body": "Can you post some example inputs and desired outputs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T17:32:22.227", "Id": "67272", "Score": "0", "body": "\"Piling up\" was an exaggeration on my part. I had found another problematic one, that \"a---b\" became \"a- -b\", not \"a b\". I think I just don't have the hang of simultaneous-lookbehind-and-lookahead, or perhaps such a thing can't generally be done with one line of regex." } ]
[ { "body": "<p>Do it in two steps. First replace all the stuff you deem to be \"junk\" with spaces, then collapse the spaces and hyphens down to a single space. You can express this with a reduce through a series of patterns that collapse to a space.</p>\n\n<p>Some output from a play in Boris.</p>\n\n<pre><code>[7] boris&gt; function clean($input) {\n[7] *&gt; $patterns = array(\n[7] *&gt; '/[^\\w\\r\\n -]/',\n[7] *&gt; '/[\\r\\n -]{2,}/'\n[7] *&gt; );\n[7] *&gt; return array_reduce(\n[7] *&gt; $patterns,\n[7] *&gt; function($text, $re) { return preg_replace($re, ' ', $text); },\n[7] *&gt; $input\n[7] *&gt; );\n[7] *&gt; }\n[8] boris&gt; clean('abc def &amp;% f');\n// 'abc def f'\n[9] boris&gt; clean('abc-def &amp;% f');\n// 'abc-def f'\n[10] boris&gt; clean('abc-def-&amp;%-f');\n// 'abc-def f\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T17:32:56.133", "Id": "67273", "Score": "0", "body": "I didn't do exactly this, but the idea of doing it programmatically is great. I'll post my new code now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T03:24:54.940", "Id": "40019", "ParentId": "40014", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T00:44:39.973", "Id": "40014", "Score": "3", "Tags": [ "php", "regex" ], "Title": "Regex to clean text in preparation for word count in PHP" }
40014
<p>Is this an OK way to handle access to database connection both inside and outside of classes?</p> <p>I used to include a PHP file -- database.detl.php -- at the very top of my index.php file containing the following code:</p> <pre><code>try{ $dbh_options = array(/*...*/); $dbh = new PDO('mysql:host=localhost;dbname='.db_name.';charset=utf8',db_user,db_user_pw,$dbh_options); } catch(PDOException $e) { /*...*/ } </code></pre> <p>Now every document that got included by index.php could use <code>$dbh</code> to access my database. This made it quite easy to work with.</p> <p>But despite including that file before any classes got loaded, this <code>$dbh</code>-variable was not available from inside the classes. This was not possible to do:</p> <pre><code>class KD_sql { public static function get_recipes(){ $qry = $dbh-&gt;query('SELECT * FROM recipes'); $get = $qry-&gt;fetchAll(); return $get; } } new KD_sql(); $recipes = sql_query::get_recipes(); </code></pre> <p>This resulted in a fatal error: <code>Call to a member function query() on a non-object...</code>.</p> <p>So I guess no variables outside of a class is ever available inside unless you somehow send it there as an additional parameter to the method.</p> <p><strong>Anyway:</strong></p> <p>This is how I rewrote the code in order to still be able to have the <code>$dbh</code>-variable available throughout the entire site - just like before, and also have the connection available inside my <code>KD_sql</code>-class - without creating the connection in multiple locations:</p> <p>First I changed database.detl.php into this:</p> <pre><code>try{ $_SITE_DATABASE_details = function(){ // &lt; added a function that holds the connection details $dbh_options = array(/*...*/); $dbh = new PDO('mysql:host=localhost;dbname='.db_name.';charset=utf8',db_user,db_user_pw,$dbh_options); return $dbh; // &lt; return connection details }; new KD_db($_SITE_DATABASE_details); // the details is sent to a new class $dbh = KD_db::con(); // &lt; a method, in this new class, returns the connection in order to still have $dbh available } catch(PDOException $e) { /*...*/ } </code></pre> <p>This might seem a bit wierd, but let me finish.<br> Here's the new <code>KD_db</code>-class:</p> <pre><code>class KD_db { protected static $con = null; # initiate and stores the connection to the $con-variable public function __construct(callable $db_details){ if (self::$con===null){ self::$con = call_user_func($db_details); } } // # the method that returns the database connection. public static function con(){ return self::$con; } // } </code></pre> <p>This class is basically just a parent class that other classes can extend to in order to have the database connection available as well.</p> <p>Here is the rewritten <code>KD_sql</code>-class:</p> <pre><code>class KD_sql extends KD_db { public static function get_recipes(){ $qry = self::$con-&gt;query('SELECT * FROM recipes'); // uses the $con -variable from parent class $get = $qry-&gt;fetchAll(); return $get; } } </code></pre> <p>I can now easily create quick-queries inside my <code>KD_sql</code>-class and just do this:</p> <pre><code>$recipes = KD_sql::get_recipes(); </code></pre> <p>which quickly returns an array of all the recipes. Or, if that doesn't cut it, I can write a more complex SQL query like this:</p> <pre><code>$recipes = $dbh-&gt;prepare(' SELECT r.columns, ot.columns FROM recipes r JOIN other_table ot ON r.fk_other_table_pk = ot.id WHERE r.some_column = :value '); </code></pre> <p>But I do have some "bugs" with the returned resultset from the class. If I only use <code>fetch()</code>, instead of <code>fetchAll()</code>, I can't do a <code>while()</code>-loop like this:</p> <pre><code>$recipes = KD_sql::get_recipes(); while($recipes){ echo $recipes['id'].' '.$recipes['name'].'&lt;br&gt;'; } </code></pre> <p>Nothing happens, beside it looks like the loop is never ending or something. That's why I'm using <code>fetchAll()</code> for now. Then uses <code>foreach()</code> because that works.</p> <p>But besides that. I would really appreciate som feedback on my way of doing this. I'm not that good with classes, oop and such. So if I'm breaking any golden rules or something - please let me know.</p>
[]
[ { "body": "<p>I think you've over-complicated this and locked yourself into using inheritance (which you should avoid until you actually need it). I'm going to suggest you use a singleton, which others will incidentally say to avoid, however database connection access is a great place to use a singleton. Since you're just passing a raw PDO object around, we'll just use a static variable for this.</p>\n\n<pre><code>class DBH {\n public static function instance() {\n static $dbh = null;\n if (!$dbh) {\n $dbh = new PDO('...');\n }\n return $dbh;\n }\n}\n</code></pre>\n\n<p>Now you can just call <code>DBH::instance()</code> from anywhere to get access to the database connection. This also has the benefit that it is a shared object and you don't create a connection for each part of the code that needs to use the database.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T10:28:13.897", "Id": "67249", "Score": "0", "body": "could you elaborate why people would say to avoid using singelton? I Don't know much about what singleton are, but I learned from a quick google search that it was a way of programming technique(?) - design pattern of some sort. I do not wish to put the details directly in the class, but rather pass them into the class.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:17:24.693", "Id": "67254", "Score": "0", "body": "@ThomasK singletons are useful when used correctly, but some people argue that they hinder automated testing, as they are not easy to override." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:18:48.357", "Id": "67255", "Score": "4", "body": "Can whoever down-voted this answer please explain why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:26:42.463", "Id": "67256", "Score": "0", "body": "Do you have any good tutorials that explains how to create and use singleton? something that is understandable for a person who's not familiar with it.. I think your answer makes sense though, so I'm about to try it out.. But just out of curiosity: I have a main class named `KD`. Is there a way to extend this `DBH` class to that, and access `instance()` like this: `KD::instance()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T11:47:53.820", "Id": "67258", "Score": "0", "body": "Since I do not wish to hard code the connection details directly in the actual class, I don't think I can use your suggestion - unless I'm not overlooking something. \nWhen I started to write the code, I first thought I could just add `call_user_func()` as I did before. But then I have to pass along the connection details every time... I think the way I already does it is better i that regard? But please tell me if there's something that I'm not aware of..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T12:04:42.923", "Id": "67259", "Score": "0", "body": "@ThomasK the singleton is one of the most common design patterns. Here's an ok write-up on it in PHP. http://www.whatsnoodle.com/creating-a-singleton-class-in-php/. If want to use `KD::instance()` (which I'd rename to `KD::dbh()`), then just define the static method there and call `DBH::instance()` from inside that (i.e. delegate the call)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T12:06:48.370", "Id": "67260", "Score": "0", "body": "@ThomasK are you passing in different connection credentials in different places, or do you just want to keep the credentials separate from the code? If the latter, you can just use regular constants (or environment variables). If the former, you might want to switch from a singleton to a registry (another, somewhat-related design pattern)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T12:27:23.173", "Id": "67261", "Score": "0", "body": "Yes - I guess. I need to keep the connection details separate from the class because this class would be located inside a framework folder which multiple sites/applications gets access to. Did that answer your question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T12:31:06.820", "Id": "67262", "Score": "1", "body": "Also. I don't think I should have the dbh instance inside my `KD`-class because I'm not always using database. I have a variable in a settings file, unique for each project, where I can activate the use of database if it is required. And only then should database related stuff, like the database.detl.php-file, KD_db and KD_sql etc. be included.." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T06:33:38.610", "Id": "40025", "ParentId": "40022", "Score": "-1" } }, { "body": "<p>Use the global keyword to make globals accessible from inside of methods and functions:</p>\n\n<pre><code>class KD_sql \n{\n public static function get_recipes()\n {\n global $dbh; // *** ADD THIS ***\n\n $qry = $dbh-&gt;query('SELECT * FROM recipes');\n $get = $qry-&gt;fetchAll();\n return $get;\n }\n}\n</code></pre>\n\n<p><a href=\"http://www.php.net/manual/en/language.variables.scope.php\" rel=\"nofollow\">http://www.php.net/manual/en/language.variables.scope.php</a></p>\n\n<p>Should you use globals for this? That is another topic completely.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:54:30.753", "Id": "40234", "ParentId": "40022", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T04:37:35.230", "Id": "40022", "Score": "4", "Tags": [ "php", "classes", "pdo" ], "Title": "Handling access to database connection both inside and outside of classes" }
40022
<p>The problem: I want to find the word in a string that has the most repeats of a single letter, each letter is independent. Does not need to be consecutive.</p> <p>Currently I am jumping each character and checking, which doesn't seem very efficient. Do you have any ideas that might improve the number of processes that are required to find which word has the most repeats?</p> <pre><code>function LetterCountI(str) { var repeatCountList = []; var wordList = str.split(/\W/); //regular expression \W for non word characters split at. var wordCount = wordList.length; // count the number of words for (var i=0; i&lt; wordCount ; i++) { var mostRepeat = 1; // set the default number of repeats to 1 var curWord = wordList[i]; // set the current word to the ith word from the list for(var ii=0; ii&lt;curWord.length ; ii++) { var repeatCount = 1; // set default repeat count to 1 var curChar = curWord[ii]; //set the current character to the iith for (var iii=0; iii&lt;curWord.length; iii++) //judge if it is the same as the iiith {var against = curWord[iii]; if (iii!=ii) // if it is Not the same referenced postion {if(curChar==against) // see if the string values match {repeatCount=repeatCount+1}}} // increase counter if match against if (repeatCount&gt;=mostRepeat) // record repeat for the highest only {mostRepeat=repeatCount} } repeatCountList = repeatCountList.concat(mostRepeat) // take the highest from each word } mostRepeat = 0; // set the repeats value to - for (j=0;j&lt;wordCount; j++) // go through the repeats count list { if(repeatCountList[j]&gt;mostRepeat) // if it has more repeats than the highest So FAR { mostRepeat = repeatCountList[j]; // record if higher than last var x = j;}} // record the index of the most repeat that is the new high var ans = []; if (mostRepeat == 1) // check if there are no repeats at all. {ans=-1} // question want to return -1 if there are no repeats else {ans=wordList[x]} // display the word from the list with the most repeat characters // code goes here return ans; } </code></pre> <p>Any help is appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T08:52:45.883", "Id": "67241", "Score": "0", "body": "I posted and answer but then I tested your code and didn't get the same output so I deleted it. What word should win between \"helllo\" and \"aabbcc\"? The first one has 2 repeated characters but the second one has 3. What's the rule? Most repeated in a row?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:57:39.737", "Id": "67307", "Score": "0", "body": "the letters only need to be repeated in the word, not consecutive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:59:12.487", "Id": "67308", "Score": "0", "body": "So `aabbcc` wins over `helllo`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T01:38:06.610", "Id": "67312", "Score": "0", "body": "no \"helllo\" wins with \"l\" repeated three (3) times. \"aabbcc\" has three letters that are repeated but only twice (2) each. Sorry I will calirfy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T07:46:23.450", "Id": "67330", "Score": "0", "body": "@Buddha The formatting of the code is an aspect that is subject to review in an answer, not to be silently fixed by editing the question. (Fixing the indentation when someone botched a copy-and-paste job into the website would be OK, but that's not the case here.) I've rolled back Rev 5 → 4." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T08:46:56.627", "Id": "67332", "Score": "0", "body": "@200_success I didn't know that, thanks for letting me know." } ]
[ { "body": "<p>I liked that you split the string into words using a regular expression. That helps a lot.</p>\n\n<p>Your code formatting (indentation and braces) is haphazard. It shouldn't be that hard to follow the standard conventions for code formatting, and it will make things easier for yourself if you do.</p>\n\n<p>I think your function tries to do too much. It would help to break down the problem. I've extracted part of the problem into a self-contained task:</p>\n\n<blockquote>\n <p>Given a word, how many times does the most frequent character appear?</p>\n</blockquote>\n\n<p>For that, you can write a function, and test it (e.g. <code>mostFrequentCount('hello')</code> should return <code>2</code>).</p>\n\n<pre><code>/**\n * Given an array (or a string), returns the number of times the most frequent\n * element (or character) appears.\n */\nfunction mostFrequentCount(elements) {\n var bins = {};\n for (var i = 0; i &lt; elements.length; i++) {\n bins[elements[i]] = (bins[elements[i]] || 0) + 1;\n }\n var max = 0;\n for (var c in bins) {\n max = Math.max(max, bins[c]);\n }\n return max;\n}\n</code></pre>\n\n<p>That should simplify the main code. Rather than commenting each line (in effect writing everything once for the computer and once for other programmers), I've tried to make the code read like English by using very human-friendly variable names.</p>\n\n<pre><code>function wordsWithMaxRepeatedCharacters(string) {\n var maxRepeatedCharacters = 0, wordsWithMaxRepeatedCharacters = [];\n\n var words = string.split(/\\W/);\n for (var w = 0; w &lt; words.length; w++) {\n var word = words[w];\n var numRepeatedCharacters = mostFrequentCount(word);\n\n if (maxRepeatedCharacters &lt; numRepeatedCharacters) {\n maxRepeatedCharacters = numRepeatedCharacters;\n wordsWithMaxRepeatedCharacters = [word];\n } else if (maxRepeatedCharacters == numRepeatedCharacters) {\n wordsWithMaxRepeatedCharacters.push(word);\n }\n }\n return wordsWithMaxRepeatedCharacters;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T01:00:48.077", "Id": "67309", "Score": "0", "body": "Thank you a lot for your help! Sorry about the format. still learning. is there an MLA style guide equivalent for code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T01:43:13.173", "Id": "67314", "Score": "0", "body": "@Reverend_Dude I liked the famous book titled [Code Complete](http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:16:31.050", "Id": "67317", "Score": "0", "body": "@Reverend_Dude And, here is a guide to indentation (whitespace) in JavaScript: http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Code_formatting#Code_formatting" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T08:35:33.833", "Id": "40031", "ParentId": "40027", "Score": "7" } }, { "body": "<p>Shorter versions of the same functions using a regular expression instead of an object for the first function and array methods for the second</p>\n\n<pre><code>var mostFrequentCount = function(s) {\nvar max = 0;\ns = s.split('').sort().join('');\ns.replace(/(.)\\1+/g,function(a){\n if (max &lt; a.length) {max = a.length;}});\nreturn max; \n};\nvar wordsWithMaxRepeatedCharacters = function(s) {\nvar n,v;\ns = s.split(/\\W/);\nn = s.map(function(n) {return mostFrequentCount(n);});\nv = Math.max.apply(null,n);\nreturn s.filter(function(a,b) {return (n[b]===v);});\n}; \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-04T07:52:30.893", "Id": "118848", "ParentId": "40027", "Score": "3" } } ]
{ "AcceptedAnswerId": "40031", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T07:15:29.270", "Id": "40027", "Score": "7", "Tags": [ "javascript", "optimization", "beginner", "strings" ], "Title": "Find the word in a string that has the most repeated characters" }
40027
<p>Please review the code quality of this JavaScript Quiz App.</p> <p>Code improvement tips and simplify are welcome.</p> <p>Demo - <a href="http://jsbin.com/eRiSUhIB/1/">http://jsbin.com/eRiSUhIB/1/</a></p> <pre><code>var quiz = [{ "question": "What is the full form of IP?", "choices": ["Internet Provider", "Internet Port", "Internet Protocol"], "correct": "Internet Protocol" }, { "question": "Who is the founder of Microsoft?", "choices": ["Bill Gates", "Steve Jobs", "Steve Wozniak"], "correct": "Bill Gates" }, { "question": "1 byte = ?", "choices": ["8 bits", "64 bits", "1024 bits"], "correct": "8 bits" }, { "question": "The C programming language was developed by?", "choices": ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"], "correct": "Dennis Ritchie" }, { "question": "What does CC mean in emails?", "choices": ["Carbon Copy", "Creative Commons", "other"], "correct": "Carbon Copy" }]; // define elements var content = $("content"), questionContainer = $("question"), choicesContainer = $("choices"), scoreContainer = $("score"), submitBtn = $("submit"); // init vars var currentQuestion = 0, score = 0, askingQuestion = true; function $(id) { // shortcut for document.getElementById return document.getElementById(id); } function askQuestion() { var choices = quiz[currentQuestion].choices, choicesHtml = ""; // loop through choices, and create radio buttons for (var i = 0; i &lt; choices.length; i++) { choicesHtml += "&lt;input type='radio' name='quiz" + currentQuestion + "' id='choice" + (i + 1) + "' value='" + choices[i] + "'&gt;" + " &lt;label for='choice" + (i + 1) + "'&gt;" + choices[i] + "&lt;/label&gt;&lt;br&gt;"; } // load the question questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " + quiz[currentQuestion].question; // load the choices choicesContainer.innerHTML = choicesHtml; // setup for the first time if (currentQuestion === 0) { scoreContainer.textContent = "Score: 0 right answers out of " + quiz.length + " possible."; submitBtn.textContent = "Submit Answer"; } } function checkAnswer() { // are we asking a question, or proceeding to next question? if (askingQuestion) { submitBtn.textContent = "Next Question"; askingQuestion = false; // determine which radio button they clicked var userpick, correctIndex, radios = document.getElementsByName("quiz" + currentQuestion); for (var i = 0; i &lt; radios.length; i++) { if (radios[i].checked) { // if this radio button is checked userpick = radios[i].value; } // get index of correct answer if (radios[i].value == quiz[currentQuestion].correct) { correctIndex = i; } } // setup if they got it right, or wrong var labelStyle = document.getElementsByTagName("label")[correctIndex].style; labelStyle.fontWeight = "bold"; if (userpick == quiz[currentQuestion].correct) { score++; labelStyle.color = "green"; } else { labelStyle.color = "red"; } scoreContainer.textContent = "Score: " + score + " right answers out of " + quiz.length + " possible."; } else { // move to next question // setting up so user can ask a question askingQuestion = true; // change button text back to "Submit Answer" submitBtn.textContent = "Submit Answer"; // if we're not on last question, increase question number if (currentQuestion &lt; quiz.length - 1) { currentQuestion++; askQuestion(); } else { showFinalResults(); } } } function showFinalResults() { content.innerHTML = "&lt;h2&gt;You've complited the quiz!&lt;/h2&gt;" + "&lt;h2&gt;Below are your results:&lt;/h2&gt;" + "&lt;h2&gt;" + score + " out of " + quiz.length + " questions, " + Math.round(score / quiz.length * 100) + "%&lt;h2&gt;"; } window.addEventListener("load", askQuestion, false); submitBtn.addEventListener("click", checkAnswer, false); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T10:03:12.450", "Id": "67247", "Score": "0", "body": "If you rightclick you can see the correct answers.some time ago i wrote a script like this that loads the questions with ajax(but without the answers)... http://stackoverflow.com/a/18337257/2450730" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T16:27:23.047", "Id": "67271", "Score": "0", "body": "lol , yeah .. your right.Anyway i just added my code cause maybe you find something there what you could need.your code looks good." } ]
[ { "body": "<p>Quite nice!</p>\n\n<p>A general thought is that you could always store the correct answer first, and then show the possible answers in a random manner to make your code more DRY.</p>\n\n<p>Furthermore:</p>\n\n<ul>\n<li>Since you do not use the <code>id</code> anywhere, you can leave this out: <code>\"' id='choice\" + (i + 1) +</code></li>\n<li>You could put <code>scoreContainer.textContent = \"Score: \" + score + \" right answers out of \" +\n quiz.length + \" possible.\";</code> into it's own function which you could call from <code>askQuestion()</code> so that you do not need to repeat this with <code>scoreContainer.textContent = \"Score: 0 right answers out of \" +\n quiz.length + \" possible.\";</code></li>\n<li>Caching the elements is good</li>\n<li>JSHint cannot complain about anything</li>\n<li>checkAnswer has too much UI state management, it ought to just check the answer.</li>\n<li><code>complited</code> -> <code>completed</code></li>\n<li>Something to think about, <code>finalResults</code> could have read the HTML from a hidden DIV and simply filled in the missing parts. Now you are maintaining HTML in JavaScript which is rarely a good idea.</li>\n</ul>\n\n<p>All in all, I like this code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:21:07.073", "Id": "40156", "ParentId": "40032", "Score": "6" } }, { "body": "<p>Just some teeny things: </p>\n\n<p>Store the lengths of the arrays in a variable when referencing inside the for loops. This way the functions will only check for the lengths once instead of on each iteration. </p>\n\n<p>For example...</p>\n\n<pre><code>function askQuestion() {\n var choices = quiz[currentQuestion].choices,\n choicesHtml = \"\",\n choicesLength = choices.length;\n\n // loop through choices, and create radio buttons\n for (var i = 0; i &lt; choicesLength; i++) {\n</code></pre>\n\n<p>And...</p>\n\n<pre><code>// determine which radio button they clicked\nvar userpick,\n correctIndex,\n radios = document.getElementsByName(\"quiz\" + currentQuestion),\n radiosLength = radios.length;\n\nfor (var i = 0; i &lt; radiosLength; i++) {\n</code></pre>\n\n<p>And along the same lines, it may be good to store <code>quiz.length</code> in a variable as well. Especially since its referenced a couple of times throughout the script.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-28T20:24:01.097", "Id": "51945", "ParentId": "40032", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T08:35:44.003", "Id": "40032", "Score": "10", "Tags": [ "javascript", "game" ], "Title": "JavaScript Quiz App" }
40032
<p>The form updates a spreadsheet with agents (employees) hours worked for a specific date. The form has 4 pages, a first page where the date and office is picked. After which the form continues to one of 3 pages which has the agent names for their particular office, and a field to enter hours.</p> <p>The form submission columns are structured as such:</p> <blockquote> <p>Timestamp Username Date Office agent1 agent2 agent3 [...] agent30</p> </blockquote> <p>On form submission, the script runs and does the following:</p> <p>It takes the information from the submission and adds them to a spreadsheet (currently received by opening the form and grabbing the last submission (rather than taking the event, I found that the event includes all agents across all offices with the rest just being blank, while the last submission only contains the fields that have values)) that has one date per row, all agents in columns and a column for summarizing the total hours for the office, as such:</p> <blockquote> <p>Date office1 agent1 agent2 [...] office2 agent14 agent15 etc.</p> </blockquote> <p>If the date doesn't exist in the sheet, it adds a new row, adds the date and copies the formulas, and fills in the agent hours. Any blank field is given a 0. Finally if the date is a date before the previous rows date, the sheet is sorted.</p> <p>If the date already exists in the sheet (as each submission only covers one office, this should be 3 submissions per date, disregarding any updates needed) all non-blank fields are updated. Blank fields are ignored.</p> <pre><code>function populateSheet() { // Matches agents to array and returns position function findMatch(agent, arr) { for (var j = 0; j &lt; arr.length; j++) { if (agent == arr[j].toLowerCase()) { return j + 1; } } return false; } // Matches dates to array and returns position function matchDate(date, dateArr) { for (var arr = 0; arr &lt; dateArr.length; arr++) { if (+date == +dateArr[arr][0]) { return arr + 1; } } return false; } // Checks if there should be a formula, else sets to 0 function matchFormulas(formulaRow, toRow) { for (var i = 0; i &lt; formulaRow.length; i++) { if (isNaN(formulaRow[i]) &amp;&amp; formulaRow[i].length &gt; 0) { toRow.getCell(1, i + 1).setFormulaR1C1(formulaRow[i]); } else { toRow.getCell(1, i + 1).setValue(0); } } } // Populates the row if there is a number function populateRow(row, values, toRow) { for (var i = 0; i &lt; row.length; i++) { // If the response is longer than 0, ie not blank if (row[i].getResponse().length &gt; 0) { var isMatch = findMatch(row[i].getItem().getTitle().toLowerCase(), values); if (isMatch) { toRow.getCell(1, isMatch + 1).setValue(row[i].getResponse()); } } } } // Open the spreadsheet, by ID, so let's hope it never ever ever changes var ss = SpreadsheetApp.openById('12345678abcdefghijklmnop'); // Get the sheet var gdSheet = ss.getSheets()[0]; // Get the last column as a number, because we'll use it, often var gdLastColumn = gdSheet.getLastColumn(); // Get the agent names from the sheet var gdAgents = gdSheet.getRange(1, 2, 1, gdLastColumn).getValues()[0]; // Grab the dates from the first column var gdDates = gdSheet.getRange(1, 1, gdSheet.getLastRow(), 1).getValues(); // And open the form, by ID, so let's hope it never ever ever changes var form = FormApp.openById('12345678abcdefghijklmnop'); // Get the responses from the form var formResponses = form.getResponses(); // Get the last repsonse var formResponse = formResponses[formResponses.length - 1]; // And itemize the response var itemResponses = formResponse.getItemResponses(); // Get the selected date and parse it into something we can work with var formDate = itemResponses[0].getResponse(); var dateSplit = formDate.split('-'); var newDate = new Date(dateSplit[0], dateSplit[1] - 1, dateSplit[2], 00, 00, 00, 00); // Check if the date exists var dateMatched = matchDate(newDate, gdDates); // If it does, update the row if (dateMatched) { var gdRow = gdSheet.getRange(dateMatched, 1, 1, gdLastColumn); populateRow(itemResponses, gdAgents, gdRow); } else { // If it doesn't exist, add a new row at the bottom var gdLastRow = gdSheet.getRange(gdSheet.getLastRow(), 1, 1, gdLastColumn); gdSheet.insertRowAfter(gdSheet.getLastRow()); var newLastRow = gdSheet.getRange(gdSheet.getLastRow() + 1, 1, 1, gdLastColumn); // Check for formulas and copy them accordingly var formulas = gdLastRow.getFormulasR1C1()[0]; matchFormulas(formulas, newLastRow); // Add the hours entered to the new row populateRow(itemResponses, gdAgents, newLastRow); // Set the date in the first cell newLastRow.getCell(1, 1).setValue(newDate); // If this date is never than the previous date, sort the sheet. if (+newDate &lt; +gdLastRow.getCell(1, 1).getValue()) { gdSheet.sort(1); } } } </code></pre> <p>As it's a fairly basic thing, I feel it's a lot of code and time (2.5 seconds with 3 date rows). Is there a way to reduce the bloat and runtime?</p>
[]
[ { "body": "<p>The only thing I can suggest is to turn your array-lookups in to object-property lookups.</p>\n\n<pre><code> function createAgentLookupTable( agents ) {\n var table = {};\n for (var i = 0 , length = agents.length; i &lt; agents.length; i++) {\n agents[i].index = i;\n table[agents[i].toLowerCase()] = agents[i]\n }\n return table;\n }\n var AgentLookupTable = createAgentLookupTable( listOfAgents );\n</code></pre>\n\n<p>You can then simply look up an agent with</p>\n\n<pre><code> function findMatch(agent) {\n var agent = AgentLookupTable[agent];\n return agent ? agent.index : false;\n } \n</code></pre>\n\n<p>This ought to increase your lookup speeds by a ton, you can use the same approach for <code>matchDate</code> and <code>matchFormulas</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:43:31.673", "Id": "67571", "Score": "1", "body": "I'm having trouble following your suggestion. What is `arr[j]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:49:25.630", "Id": "67572", "Score": "0", "body": "Gah, I was too quick. `j` -> `i`, `arr` -> `agents`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:26:11.020", "Id": "40194", "ParentId": "40034", "Score": "2" } } ]
{ "AcceptedAnswerId": "40194", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T10:32:38.017", "Id": "40034", "Score": "5", "Tags": [ "performance", "google-apps-script", "google-sheets" ], "Title": "Google Spreadsheet form script for employee work hours" }
40034
<p>I have a question about the Repository pattern:</p> <pre><code>public abstract class RepositoryBase&lt;T&gt; : IDisposable, IRepository&lt;T&gt; where T : class, IEntity { /// &lt;summary&gt; /// For iterations using LINQ extension methods on the IQueryable and IEnumerable interfaces /// it is required that the context which was used to make the query was not disposed before the iteration /// otherwise it will throw an exception /// &lt;/summary&gt; private Context _context; protected Context Context { get { return _context ?? (_context = new Context()); } } public virtual void AddOrUpdate(T entity) { var dbSet = Context.Set&lt;T&gt;(); if (dbSet.Contains(entity)) entity.ChangeDateTime = DateTime.Now; else entity.AddeDateTime = DateTime.Now; Context.Set&lt;T&gt;().AddOrUpdate(entity); Context.SaveChanges(); } public virtual void Delete(T entity) { Context.Set&lt;T&gt;().Remove(entity); Context.SaveChanges(); } public void Drop() { var dbSet = Context.Set&lt;T&gt;(); foreach (var entity in dbSet) dbSet.Remove(entity); Context.SaveChanges(); } public virtual IQueryable&lt;T&gt; Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { return Context.Set&lt;T&gt;().Where(predicate); } public IEnumerable&lt;T&gt; GetAll() { return Context.Set&lt;T&gt;(); } public void Dispose() { if (_context != null) { _context.Dispose(); _context = null; } } } </code></pre> <p>Why I am not embracing each method implementation with a <code>using</code> and disposing the <code>Context</code> as soon as the query is done?</p> <p>Some of my methods, as <code>Find</code> and <code>GetAll</code> return collections. I would want to be able to iterate through them using LINQ, only this is not possible if the Context is disposed, as it would be in the original Repository model.</p> <p>Is this the best approach to go around this issue?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T20:00:09.680", "Id": "67282", "Score": "0", "body": "Is `IEntity` just a *marker interface*?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T20:16:45.793", "Id": "67283", "Score": "0", "body": "Yes, it is just a marker interface." } ]
[ { "body": "<p>Firstly I would consider injecting the DbContext into the repository. Even though your RepositoryBase class is abstract I would have a protected constructor</p>\n\n<pre><code>protected RepositoryBase(Context dbContext) {\n _context = dbContext;\n}\n</code></pre>\n\n<p>I would then look at injecting the context into each repository and letting object that ends up creating the context be responsible for it's disposing. Perhaps you could take a look at the UnitOfWork pattern as that goes well with the repository pattern (There are plenty of articles online).</p>\n\n<p>In light of this I then probably would let another class/object be responsible for when the changes are persisted to the database. Perhaps look at it like a UI that lets you add items to a list as much as you want. Then there is a save button that will actually do the persist to the db. This save button is separate to the adding itself and means that you can bulk add items and only save when you are ready.</p>\n\n<p>One other point of doing it this way is that you never get to share Context. That means that each repositories set of changes will not be visible in another set (until the changes are persisted). This maybe what you are after but if not, it's something to consider.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:07:23.537", "Id": "40047", "ParentId": "40038", "Score": "1" } }, { "body": "<p>Reusing the same context could have some benefits if you need entities to be cached but you could also end up with contexts with a large memory sizes.</p>\n\n<p>Depending on the requirements, I have usually created a new context on every call and in the case of database contexts, played it safe by forcing a <code>ToList()</code> within the function, before returning the entities. </p>\n\n<p>This ensures that the database connection is only open for just enough time to retrieve the rows and the context is destroyed without holding on to the entities retrieved.</p>\n\n<p>The approach to take here, really depends on your requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:22:11.750", "Id": "67292", "Score": "0", "body": "But are you able to use LINQ if you use `ToList()` on the collection? Even after the `context` was disposed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:41:02.843", "Id": "67296", "Score": "0", "body": "The ToList() needs to be called before the context is disposed.\nI noticed the 'Find' returns an IQueryable instead of an IEnumerable. Are you expecting the caller to further augment the query? If not, the 'Find' could return an IEnumerable or IList, after calling ToList()." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-25T22:10:28.343", "Id": "40058", "ParentId": "40038", "Score": "2" } }, { "body": "<blockquote>\n <p>My question is about why I am not embracing each method implementation with a using and disposing the Context as soon as the query is done.\n Some of my methods, as Find and GetAll return collections. I would want to be able to iterate through them using LINQ, only this is not possible if the Context is disposed, as it would be in the original Repository model.</p>\n</blockquote>\n\n<p>A Linq enumerable isn't enumerated when it's created: it's enumerated when you try to work with it.</p>\n\n<p>If we want to dispose the context within each each method, I think you can do that by realizing the data, i.e. by reading it all into a concrete object such List or EnumerableQuery, before you dispose the context ... something like this (untested code ahead):</p>\n\n<pre><code>public IEnumerable&lt;T&gt; GetAll()\n{\n using (Context context = new Context())\n {\n IEnumerable&lt;T&gt; enumerable = context.Set&lt;T&gt;();\n // enumerate into a List before disposing the context\n List&lt;T&gt; list = new List&lt;T&gt;(enumerable);\n return list;\n }\n}\n\npublic virtual IQueryable&lt;T&gt; Find(Expression&lt;Func&lt;T, bool&gt;&gt; predicate)\n{\n using (Context context = new Context())\n {\n IEnumerable&lt;T&gt; enumerable = context.Set&lt;T&gt;().Where(predicate);\n // enumerate into a EnumerableQuery before disposing the context\n // see https://stackoverflow.com/a/6765404/49942 for further details\n EnumerableQuery&lt;T&gt; queryable = new EnumerableQuery&lt;T&gt;(enumerable);\n return queryable;\n }\n}\n</code></pre>\n\n<p>Beware that <a href=\"https://stackoverflow.com/questions/6765350/listt-to-implement-iqueryablet#comment32145235_6765404\">this is expensive if the data set is huge</a>, if you don't actually want all the data you queried.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:42:59.927", "Id": "40060", "ParentId": "40038", "Score": "2" } }, { "body": "<p>The answer is the <code>Unit Of Work</code> pattern. You are right that <code>using</code> is modern only it can not be used if you have a <code>Unit Of Work</code> in your repository that has lets say 3 write actions in it that are part of ONE transaction, but can be split in 3 writing methods. For those 3 write actions you will need the same context from the same repository. Most of those times there will be a <code>Commit</code> method in that repository to \"Commit\" that atomary transaction. You can then also Implement a \"Rollback\" method if one of those 3 write actions will fail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-09T12:48:44.020", "Id": "230423", "ParentId": "40038", "Score": "0" } } ]
{ "AcceptedAnswerId": "40060", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T13:55:35.850", "Id": "40038", "Score": "11", "Tags": [ "c#", ".net", "database", "repository" ], "Title": "Disposing the Context in the Repository pattern" }
40038
<p>I have another issue: I'm trying to handle connections made by local socket along with data from serial port. Here is my concept:</p> <ol> <li>Serial port is opened and monitored by select</li> <li>Local socket is opened and put in Listen state</li> <li>inside loop I call my function accept_connection periodically</li> <li>When new connection arrives I allocate new array of struct to handle connections data</li> <li>I'm adding socket to &amp;input with FD_SET(socket,&amp;input), and this is what select is monitoring</li> <li>I'm checking with FD_ISSET (after select returns) if there is data from some client</li> <li>If there is data I'm reading it with process_client</li> </ol> <p>It appears that it is working so far.</p> <p>My questions are: </p> <ol> <li>I'm doing this the first time. Are there some obvious mistakes? </li> <li>How do I know that client has disconnected, and socket should be cleared, and removed from clients array?</li> <li>Should I move some variables like *clients pointer <code>clients_num</code> outside the <code>main</code> function to have easier access to them from other functions, otherwise next functions can have a really long parameter list?</li> </ol> <p><strong>main.c</strong></p> <pre><code>struct client_struct { int socket; char cmd_type; }; void main { int loop_num=250; int local_socket; int serial_fd; int max_fd; int tmp_socket; fd_set input; fd_set tmp_input; char *serial_output_buffer; struct timeval timeout; struct client_struct *clients; int clients_num=0; serial_output_buffer=malloc(INPUT_BYTES_NUM * sizeof(char)); serial_fd=open_port(); local_socket=open_local_socket(); FD_ZERO(&amp;input); FD_SET(serial_fd, &amp;input); max_fd = serial_fd+1; while(TRUE) { loop_num++; if(loop_num&gt;250) { pool_from_serial(serial_fd); loop_num=0; } tmp_socket=accept_connection(); if(tmp_socket) { clients=alloc_client(clients,clients_num); clients[clients_num].socket=tmp_socket; clients_num++; FD_SET(tmp_socket, &amp;input); max_fd = getMaxFd(serial_fd,clients,clients_num); } tmp_input=input; n = select(max_fd,&amp;tmp_input,NULL,NULL,&amp;timeout); /* See if there was an error */ if (n&lt;0) perror("select failed"); else if (n == 0) ;//puts("TIMEOUT"); else { /* We have input */ if (FD_ISSET(serial_fd, &amp;input)) { if(process_serial(serial_fd,serial_output_buffer)) { process_serial_data(serial_output_buffer); } } for(i=0;i&lt;clients_num;i++) { if(FD_ISSET(clients[i].socket, &amp;input)) { process_client(clients,i); } } } fflush(stdout); usleep(10000); } return 0; } int getMaxFd(int serial_fd,struct client_struct *clients,int client_num) { int i; int res=serial_fd; for(i=0;i&lt;client_num;i++) { res=(res &gt; clients[i].socket ? res : clients[i].socket); } return (res+1); } struct client_struct* alloc_client(struct client_struct *clients,int num) { int i; if(num==0) { clients=(struct client_struct*)malloc(sizeof(struct client_struct)); } else { struct client_struct *new_array=(struct client_struct*)malloc((num+1)*sizeof(struct client_struct)); if(!new_array) { error_exit("alloc_client malloc failed"); } for(i=0;i&lt;num;i++) { new_array[i]=clients[i]; } free(clients); clients=new_array; } return clients; } </code></pre> <p><strong>local_socket.c</strong></p> <pre><code>int sck_unix; /* Listen Socket */ struct sockaddr_un adr_unix;/* AF_UNIX */ int len_unix; /* length */ void process_client(struct client_struct *clients,int num) { char buf[256]; int nread=0; int socket=clients[num].socket; int bytes=0; ioctl(socket, FIONREAD, &amp;bytes); if(!bytes) return; nread = recv(socket, buf, sizeof(buf), 0); /* If error or eof, terminate. */ if(nread &lt; 1 &amp;&amp; errno!=EAGAIN){ close(socket); error_exit("read client"); } buf[nread]='\0'; printf("client read:%s\n",buf); } int accept_connection() { int ns=0; ns = accept(sck_unix, (struct sockaddr *) &amp;adr_unix, &amp;len_unix); if(ns&lt;0) { if(errno==EAGAIN) return 0; else error_exit("accept connection failed"); } else { int flagss = fcntl(ns,F_GETFL,0); flagss |= O_NONBLOCK; fcntl(ns,F_SETFL,flagss); printf("ns:%d\n",ns); return ns; } } int open_local_socket() { int z; /* Status return code */ const char pth_unix[]="/tmp/my_sock"; /* pathname */ sck_unix = socket(AF_UNIX,SOCK_STREAM,0); if ( sck_unix == -1 ) error_exit("Creation of local socket failed"); unlink(pth_unix); memset(&amp;adr_unix,0,sizeof adr_unix); adr_unix.sun_family = AF_UNIX; strncpy(adr_unix.sun_path,pth_unix, sizeof adr_unix.sun_path-1) [sizeof adr_unix.sun_path-1] = 0; len_unix = SUN_LEN(&amp;adr_unix); z = bind(sck_unix, (struct sockaddr *)&amp;adr_unix, len_unix); if ( z == -1 ) error_exit("Bind to local socket failed"); if (listen(sck_unix, 5) == -1) { error_exit("listen error"); } int flagss = fcntl(sck_unix,F_GETFL,0); flagss |= O_NONBLOCK; fcntl(sck_unix,F_SETFL,flagss); return sck_unix; } </code></pre>
[]
[ { "body": "<p>On your questions:</p>\n\n<ol>\n<li><p>There are some oddities in your code, for example, the use of non-blocking\nsockets.</p></li>\n<li><p>Detecting disconnected clients is difficult. I'm not that familiar with\nUNIX-domain sockets, but I imagine they are much the same as Internet-domain\nsockets. You probably need either to set up periodic keep-alive messages\nwithin whatever protocol you have adopted for the client-server communication\n(ie. empty messages whose purpose is just to tell the server that the client\nis still there), or add a timeout so that a client that hasn't talked to the\nserver for some time is assumed to be dead, or both.</p></li>\n<li><p>Global variables are best avoided. Use them only as a last resort,\nwhen the alternatives are really bad. Knowing when you have reached that\npoint is difficult, so I suggest just not using globals unless there is <strong>no</strong>\nalternative.</p></li>\n</ol>\n\n<p><em>Naming:</em></p>\n\n<ul>\n<li><p><code>struct client_struct</code> tells me no more than <code>struct client</code>, so call it\nthat.</p></li>\n<li><p><code>getMaxFd</code> uses camel case, unlike all other functions. Simply <code>max_fd</code>\nwould be enough.</p></li>\n<li><p>giving your variables the suffix 'unix', as in <code>adr_unix</code> adds nothing and\nmakes it more difficult to change the code (eg if you wanted to switch to\nInternet-domain sockets) than it need be.</p></li>\n</ul>\n\n<p><em>Formatting:</em></p>\n\n<p>You need to add spaces around operators ('=', '==', '&lt;', etc) to make the code\nmore readable. I also think it is nicer to add spaces after keywords ('if',\n'while' etc).</p>\n\n<p>And you should be consistent with bracketing - sometimes you use braces on\nsingle statements and sometimes not. Many people think it is best always to\nuse braces, whether needed or not.</p>\n\n<hr>\n\n<p>In <code>getMaxFd</code>, your use of</p>\n\n<blockquote>\n<pre><code>res=(res &gt; clients[i].socket ? res : clients[i].socket);\n</code></pre>\n</blockquote>\n\n<p>is not obviously better than the more normal:</p>\n\n<pre><code>if (res &lt; clients[i].socket) {\n res = clients[i].socket;\n}\n</code></pre>\n\n<p>Also define loop variables within the loop</p>\n\n<pre><code>for(int i = 0; i &lt; client_num; i++) {\n if (res &lt; clients[i].socket) {\n res = clients[i].socket;\n }\n</code></pre>\n\n<p><hr>\nYour <code>alloc_client</code> is verbose. Perhaps you have not come across <code>realloc</code>,\nwhich is effectively what you are doing.</p>\n\n<pre><code>struct client* alloc_client(struct client *clients, size_t num)\n{\n struct client *c = realloc(clients, (num+1) * sizeof *c);\n if (!c) {\n error_exit(\"alloc_client malloc failed\");\n }\n return c;\n}\n</code></pre>\n\n<p><hr>\nYour use of globals is unnecessary. It gains nothing but costs the reader in\nbeing less understandable.</p>\n\n<blockquote>\n<pre><code>int sck_unix; /* Listen Socket */\nstruct sockaddr_un adr_unix;/* AF_UNIX */\nint len_unix; /* length */\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Your <code>process_client</code> should just take a socket not the list of structs and\nthe index. It is also unclear to me why you need to check the socket for\navailable data using <code>ioctl</code> before reading it. The function is called in\nresponse to selecting-ready so you know it can be read. And in addition you\nhave set your socket non-blocking which again means the ioctl was unnecessary.\nFor completeness, <code>EINTR</code> might also be checked as well as <code>EAGAIN</code>.</p>\n\n<hr>\n\n<p>Both your <code>accept_connection</code> and <code>open_local_socket</code> set their sockets\nnon-blocking. It is not clear to me why you need those sockets non-blocking -\nI don't think it is normal to do this, although it is clearly possible. Note\nthat you should extract the duplicated three lines of code that set\n<code>O_NONBLOCK</code> into a separate function.</p>\n\n<hr>\n\n<p>Your <code>open_local_socket</code> can be simplified significantly.</p>\n\n<blockquote>\n<pre><code>struct sockaddr_un adr_unix;/* AF_UNIX */\n...\nconst char pth_unix[]=\"/tmp/my_sock\"; /* pathname */\n...\nmemset(&amp;adr_unix,0,sizeof adr_unix);\n\nadr_unix.sun_family = AF_UNIX;\n\nstrncpy(adr_unix.sun_path,pth_unix,\n sizeof adr_unix.sun_path-1)\n [sizeof adr_unix.sun_path-1] = 0;\n</code></pre>\n</blockquote>\n\n<p>Can be replaced by a local address variable <code>adr</code> defined as follows:</p>\n\n<pre><code>#define USOCKET \"/tmp/my_sock\"\n struct sockaddr_un adr = {0, AF_UNIX, USOCKET};\n</code></pre>\n\n<p>The avoids the horrible <code>strncpy</code> and termination.</p>\n\n<p>The function also needs a <code>(void)</code> parameter list and the accepted socket\nshould be used by the caller directly instead of via a global <code>sck_unix</code>.</p>\n\n<p><hr> In <code>main</code></p>\n\n<ul>\n<li><p>define variables at their first point of use not all at the top.</p></li>\n<li><p><code>main</code> is too long - extract the contents of the loop into a function (not\nincluding the <code>loop_num</code> conditional). So <code>main</code> will have something simple,\nlike:</p>\n\n<pre><code>while (process_connections(sck, serial_fd, clients, nclients)) {\n if (++loop_num&gt;250) { ...\n }\n}\n</code></pre></li>\n<li><p>the <code>usleep</code> call should be unnecessary and should be removed.</p></li>\n<li><p>You use <code>select</code> to detect activity on accepted sockets or the serial line,\nbut not for the listening socket which you instead set non-blocking and poll\neach time round the loop. Your <code>select</code> call has an uninitialized timeout,\nwhich might allow the loop to reach the <code>accept_connection</code> call\noccasionally. That arrangement make no sense.</p>\n\n<p>You should add the listening socket to the input file descriptor set and\nhandle it when <code>select</code> returns. And there is probably no need for a\ntimeout on <code>select</code> unless there is some periodic activity that needs to\nbe serviced (eg detecting dead clients). If you use a timeout, initialize\nit appropriately.</p></li>\n<li><p>You call <code>pool_from_serial</code> every 250 cycles of the loop. That seems rather\narbitrary (could be 250 serial chars received or 250 clients connecting or a\nmixture). I don't know the purpose of this, but it might need to be more\nrobustly scheduled.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:49:28.583", "Id": "40175", "ParentId": "40039", "Score": "4" } }, { "body": "<p>So first off, global variables. Since posting this code, I made a lot of changes, signals, daemonization, logging, processing data from device, and at some point I have moved variables like:</p>\n\n<pre><code>int sigflag=0;\nchar dev_status=0x00;\nchar dev_power_status=0x00;\nint serial_fd;\nint local_socket;\nint clients_num=0;\nstruct client_struct *clients;\nstatic char const * const lock_file = \"/var/lock/device/device.lock\";\nstatic char const * const log_filename = \"/var/log/device.log\";\nFILE *logfile;\nint log_level=9;\n</code></pre>\n\n<p>to global scope, due to multi-parameter functions that otherwise I had to made.</p>\n\n<p>If I declare for example</p>\n\n<pre><code>int clients_num;\nstruct client_struct *clients;\n</code></pre>\n\n<p>inside main(), then every function called from main must have this parameters passed in arguments, which is not so bad, problem arises when next function calls next function and so on, and third function actually allocates or frees structure \"client_struct\" so it needs to return new pointer to structure and also updated variable clients_num, what it can't obviously do. So I ended up passing pointers to clients_num (among other pointers) so my alloc_clients actually returned new pointer for clients and used and modified *clients_num. </p>\n\n<p>So to sum up, is there any alternative that I don't know about except passing and returning variables throughout 3 functions, and working with pointers like *clients_num ?</p>\n\n<p>Below are some functions from approach without global variables (this is from backup, with new additions to the program some functions would have to be even longer)</p>\n\n<pre><code> struct client_struct* process_serial_data(char *buffer,struct client_struct *clients,int *clients_num,fd_set *input);\n struct client_struct* alloc_client(struct client_struct *clients,int num);\n struct client_struct* delete_clients(struct client_struct *clients,int to_delete_arr[5],int to_delete,int clients_num);\n</code></pre>\n\n<p>And this is with global variables</p>\n\n<pre><code>void process_serial_data(char *buffer,fd_set *input);\nvoid alloc_client();\nvoid delete_clients(int to_delete_arr[5],int to_delete); //array with client index to delete, number of clients to delete\n</code></pre>\n\n<p>I don't want to advocate for global variables, but... at some point my code was really complicated, although safer, due to lack of risk of global variable shadowing, right?</p>\n\n<p>Except for putting some variables into global scope I made also helper_function.h where I put client_struct definition and some variables for logging.Reason for that is that I divided my program into files main.c local_socket.h/c serial_port.h/c helper_function.h/c (and it will grow), so when I pass variable struct client_struct *clients to function in other files they need to know what this is client_struct.</p>\n\n<p>Anyway, I;m seriously thinking about rewriting this daemon in C++, so I would have nice private variables ;) and I wouldn't have to pass variables throughout many functions.</p>\n\n<p>Next thing is this NONBLOCKING sockets, I used mostly examples from the internet, but I thought about this as good idea. My program primare objective is to monitor device, and to do that it needs to query this device periodically, so I wanted to avoid situation when socket is blocked for some reason and I program doesn't pool data from device. And this is also why I used usleep in a loop, to send query over serial port in regular intervals.</p>\n\n<p>Although now I think I could setup a longer timeout in pselect and wait for this timeout to query the device, and when signal arrives, or data from client, and pselect returns prematurely I could check remaining time in timeout passed to pselect and restart pselect until this timeout reaches end, right? So this way I would get rid of usleep and query device at regular intervals.\nI'm using pselect due to signal handling and with sigmask for sigusr1 and sigterm so they can only arrive during pselect call and not during sending/receiving data or something. Signal_handler actually only changes global variable flag that is later on checked when pselect returns.</p>\n\n<p>Other issues:</p>\n\n<ul>\n<li><p>\"struct client_struct tells me no more than struct client, so call it\nthat.\" </p>\n\n<p>I have variable called clients that is pointer to actual data,\nso it can't be only \"s\" to distinguish between type and variable, I\nwill stick with that.</p></li>\n<li><p>getMaxFd uses camel case, unlike all other functions. Simply max_fd would be enough.</p>\n\n<p>Yes, will change to get_max_fd (max_fd is my variable). Also with addr_unix You are right.</p></li>\n<li><p>Also define loop variables within the loop</p>\n\n<p>I had an error saying: </p>\n\n<p>‘for’ loop initial declarations are only allowed in C99 mode </p>\n\n<p>use option -std=c99 or -std=gnu99 to compile your code</p>\n\n<p>I'm using CMake on Linux, probably some flag needs to be added to CMakeList.txt or something...</p></li>\n<li><p>realloc is good I didn't know about that, but still when I need to delete lets say second and fourth client from my *clients list in one go I still need to do it manually, and simply not include deleted clients in new copy like this</p>\n\n<pre><code>void delete_clients(int to_delete_arr[5],int to_delete) {\n int i,k;\n if(clients_num==1) {\n free(clients);\n clients=NULL;\n } else {\n struct client_struct *new_array=(struct client_struct*)malloc((clients_num-1)*sizeof(struct client_struct));\n if(!new_array) {\n error_exit(ERROR,\"delete_clients malloc failed\");\n }\n for(i=0;i&lt;clients_num;i++) {\n for(k=0;k&lt;to_delete;k++) {\n if(to_delete_arr[k]!=i)\n new_array[i]=clients[i];\n }\n }\n free(clients);\n clients=new_array;\n }\n}\n</code></pre></li>\n<li><p>process_clients takes list of structs and the index for one reason, data that arrived from serial device can be send to many clients and inside that function I'm iterating throughout list to check if any clients is waiting for that kind of response from device. In other words, when process_clients starts I don't know which client (if any) wants this data, I would have to check data type before calling process_clients</p></li>\n<li><p>ioctl is over the top in local_socket functions, and EINTR and EAGAIN will be checked</p></li>\n<li><p>open_local_socket I will simplify and it will work on local variables returning socket at the end.</p></li>\n<li><p>pselect should also monitor local_socket to check for new connections - right. Some \"code ago\" I had a problem with select returning immediately, probably due to error in local_socket creation there was no \"listen\" call. I saw examples with select listening for new connections, so pselect should also handle this.</p></li>\n<li><p>I will shorten my \"main\" and put some code to functions, however I'm not sure about defining variables in place where they are used, somehow this is clearer for me.</p></li>\n</ul>\n\n<p>I have also other questions, but I will start new thread.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T20:06:06.763", "Id": "67827", "Score": "0", "body": "If this is not specifically an answer and is asking for further review, this should be posted as a new question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T18:29:32.543", "Id": "40283", "ParentId": "40039", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T14:17:32.427", "Id": "40039", "Score": "6", "Tags": [ "c", "serial-port" ], "Title": "Handling serial port with select and local socket" }
40039
<p>I have some VB code that connects to a MySQL database to update every control on every page of a form in our database.</p> <p>I am told this is taking longer than it should to run. The 'Setup MySql connection' comment is where it starts. I am wondering if there are any obvious optimisation tricks I am missing here, or whether some things are just badly written (I wasn't sure when to open and close my <code>MySqlDataReader</code> and <code>Connection</code> objects):</p> <pre><code> Dim penPngList As New List(Of String) 'Get information on the pen docked Dim penID As String penID = _form.SessionData(0).DeviceState.PadDeviceID 'penID = "aaa" Try Dim i = 0 For Each er As ExportResult In _form.Validator.ExportResults If er.DataPathName = "xml" Then 'Load the XML Dim doc As New XmlDocument doc.Load(er.ExpandedFilePath) 'Get MySql Reader ready Dim rdr0 As MySqlDataReader Dim rdr As MySqlDataReader Dim sessionID As Int32 'Grab the Descriptor Dim document As XPathDocument = New XPathDocument(er.ExpandedFilePath) Dim navigator As XPathNavigator = document.CreateNavigator() Dim descNode As XPathNavigator = navigator.SelectSingleNode("//MIFORMS_EXPORT/SESSION/FIELD[@NAME='DESCRIPTOR']") 'Strip the Descriptor to get ID Dim descriptorString As String = descNode.InnerXml 'Const descriptorString As String = "3_cytoxdemtest_0199_999_1" 'Strip the Descriptor to get ID Dim descriptorSplitArray As String() = descriptorString.Split("_") Dim id As String = descriptorSplitArray(0) 'TASK: Get the pen image PNG name 'Get the total Session count in XML Dim penImageRaw As Int32 = doc.GetElementsByTagName("SESSION").Count If penImageRaw &gt; 0 Then 'Grab the last session element (Last one is count-1) Dim test As XmlNode = doc.GetElementsByTagName("SESSION").Item(penImageRaw - 1) Dim list As XmlNodeList = test.ChildNodes For Each node As XmlNode In list If String.Equals(node.Name, "IMAGE") Then Dim penImageExplode As String() = node.FirstChild.Value.Split("\") PenImage = penImageExplode(penImageExplode.Length - 1) penPngList.Add(PenImage) End If Next Else MsgBox("ERROR: No Session nodes found") End If 'Set-up MySql connection Const connStr As String = "server=localhost;user id=root; password=password; database=backend; pooling=false" Dim conn As New MySqlConnection(connStr) conn.Open() 'Get the information from that ID the concerned ID Dim stm As String = "SELECT Patient , Visit, Project, Centre FROM identifiers WHERE ID = '" &amp; id &amp; "'" Dim cmd As New MySqlCommand(stm, conn) rdr = cmd.ExecuteReader() If rdr.Read Then patient = rdr.GetString(0) visit = rdr.GetInt32(1) project = rdr.GetString(2) centre = rdr.GetString(3) Else Throw New Exception("Could not find the identifier") End If 'Connect to the patient using the information gathered from above Dim connStrToProject As String = "server=localhost;user id=root; password=password; database=" &amp; project &amp; "; pooling=false" Dim connToProject As New MySqlConnection(connStrToProject) connToProject.Open() 'Set-up MySql connection Const connStr0 As String = "server=localhost;user id=root; password=password; database=backend; pooling=false" Dim conn0 As New MySqlConnection(connStr0) conn0.Open() 'Get the session info Dim stm0 As String = "SELECT MAX(Session) FROM " &amp; project &amp; ".bay" Dim cmd0 As New MySqlCommand(stm0, conn0) rdr0 = cmd0.ExecuteReader() While (rdr0.Read()) If rdr0("MAX(Session)") Is DBNull.Value Then sessionID = 1 Else sessionID = rdr0.GetInt32(0) sessionID = sessionID + 1 End If End While rdr0.Close() 'For each page of the form pages For Each myPage As FormPage In _form.Pages() 'Go through each control on the page For Each myControl As FormControl In myPage.Controls() Dim nowDate As String nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") 'convert cm to DIU (device-independent units) Dim rectHeight As Int32 = (myControl.Size.Height / 2.54) * 72 Dim rectWidth As Int32 = (myControl.Size.Width / 2.54) * 72 Dim rectX As Int32 = (myControl.Position.X / 2.54) * 72 Dim rectY As Int32 = (myControl.Position.Y / 2.54) * 72 'As date variable numbers repeat, MiForm adds _x, which breaks update query. 'This is where we strip that out. Dim stringToCheck As String = myControl.Name Const stringToFind As String = "_" Dim exp As New Regex(stringToFind, RegexOptions.IgnoreCase) Dim occurrences As Integer = exp.Matches(stringToCheck).Count If occurrences = 1 And stringToCheck.Contains("_M") = False Or myControl.Name.Contains("_T") = False Then Dim singleVal = myControl.Name.Split("_") Dim sameValue = singleVal(0) Dim insertQuery1 As String = "INSERT INTO audit_pen (`Session`, `Patient`, `ValidText`, `FieldNumber`, `Marker_Height`, `Marker_Width`, `Marker_X`, `Marker_Y`, `PenPng`, `Visit`, `Page`, `EntryDate`) " &amp; _ "VALUES ('" &amp; sessionID + 1 &amp; "', '" &amp; patient &amp; "', '" &amp; myControl.Value &amp; "', '" &amp; sameValue &amp; "', '" &amp; rectHeight &amp; "', '" &amp; rectWidth &amp; "', '" &amp; rectX &amp; "', '" &amp; rectY &amp; "', '" &amp; penPngList(i) &amp; "', '" &amp; visit &amp; "', '" &amp; myPage.Name &amp; "', '" &amp; nowDate &amp; "')" Dim insertQuery1Exe As New MySqlCommand(insertQuery1, connToProject) rdr = insertQuery1Exe.ExecuteReader() rdr.Close() Dim insertQueryForRepeatVars As String = "UPDATE patient" &amp; patient &amp; " SET `Data Verified (valid)` = '1' , " &amp; _ "`Valid Text (validc)` = '" &amp; myControl.Value &amp; "' , " &amp; _ "`Verified DEC (namev)` = '" &amp; penID &amp; "' , " &amp; _ "`Base DEC (nameb)` = '[Valid Override]' , `Compare DEC (namec)` = '[Valid Override]' , " &amp; _ "`LatestPenDate` = '" &amp; nowDate &amp; "' , " &amp; _ "`Base Entry Date (mdateb)` = '" &amp; nowDate &amp; "' , " &amp; _ "`Compare Entry Date (mdatec)` = '" &amp; nowDate &amp; "' , " &amp; _ "UploadedXML = '" &amp; er.DataPathName &amp; "' , " &amp; _ "FromDigiPen = '1' , " &amp; _ "rect_height = '" &amp; rectHeight &amp; "' , " &amp; _ "rect_width = '" &amp; rectWidth &amp; "' , " &amp; _ "rect_x = '" &amp; rectX &amp; "' , " &amp; _ "rect_y = '" &amp; rectY &amp; "' , " &amp; _ "PenPngLocation = '/images/" &amp; penPngList(i) &amp; "'" &amp; _ "WHERE `Visit Number (VISIT)` = '" &amp; visit &amp; "' AND " &amp; _ "`Page Number (PAGE)` = '" &amp; myPage.Name &amp; "' AND " &amp; _ "`Variable Number (var)` = '" &amp; sameValue &amp; "'" Dim insertQueryForRepeatVarsExe As New MySqlCommand(insertQueryForRepeatVars, connToProject) rdr = insertQueryForRepeatVarsExe.ExecuteReader() rdr.Close() End If 'If underscore occured twice, that means "_x" was added in a date field "AO001DATE_M_x" If occurrences = 2 Or myControl.Name.Contains("_M") Or myControl.Name.Contains("_T") Then Dim test = myControl.Name.Split("_") Dim sameVarName = test(0) + "_" + test(1) Dim insertQuery2 As String = "INSERT INTO audit_pen (`Session`, `Patient`, `ValidText`, `FieldNumber`, `Marker_Height`, `Marker_Width`, `Marker_X`, `Marker_Y`, `PenPng`, `Visit`, `Page`, `EntryDate`) " &amp; _ "VALUES ('" &amp; sessionID + 1 &amp; "', '" &amp; patient &amp; "', '" &amp; myControl.Value &amp; "', '" &amp; sameVarName &amp; "', '" &amp; rectHeight &amp; "', '" &amp; rectWidth &amp; "', '" &amp; rectX &amp; "', '" &amp; rectY &amp; "', '" &amp; penPngList(i) &amp; "', '" &amp; visit &amp; "', '" &amp; myPage.Name &amp; "', '" &amp; nowDate &amp; "')" Dim insertQuery2Exe As New MySqlCommand(insertQuery2, connToProject) rdr = insertQuery2Exe.ExecuteReader() rdr.Close() 'Update the patient data for repeat values Dim insertQueryForRepeatValues As String = "UPDATE patient" &amp; patient &amp; " SET `Data Verified (valid)` = '1' , " &amp; _ "`Valid Text (validc)` = '" &amp; myControl.Value &amp; "' , " &amp; _ "`Verified DEC (namev)` = '" &amp; penID &amp; "' , " &amp; _ "`Base DEC (nameb)` = '[Valid Override]' , `Compare DEC (namec)` = '[Valid Override]' , " &amp; _ "`LatestPenDate` = '" &amp; nowDate &amp; "' , " &amp; _ "`Base Entry Date (mdateb)` = '" &amp; nowDate &amp; "' , " &amp; _ "`Compare Entry Date (mdatec)` = '" &amp; nowDate &amp; "' , " &amp; _ "UploadedXML = '" &amp; er.DataPathName &amp; "' , " &amp; _ "FromDigiPen = '1' , " &amp; _ "rect_height = '" &amp; rectHeight &amp; "' , " &amp; _ "rect_width = '" &amp; rectWidth &amp; "' , " &amp; _ "rect_x = '" &amp; rectX &amp; "' , " &amp; _ "rect_y = '" &amp; rectY &amp; "' , " &amp; _ "PenPngLocation = '/images/" &amp; penPngList(i) &amp; "'" &amp; _ "WHERE `Visit Number (VISIT)` = '" &amp; visit &amp; "' AND " &amp; _ "`Page Number (PAGE)` = '" &amp; myPage.Name &amp; "' AND " &amp; _ "`Variable Number (var)` = '" &amp; sameVarName &amp; "'" Dim insertQueryForRepeatValuesExe As New MySqlCommand(insertQueryForRepeatValues, connToProject) rdr = insertQueryForRepeatValuesExe.ExecuteReader() rdr.Close() End If If occurrences = 0 Then Dim insertQuery2 As String = "INSERT INTO audit_pen (`Session`, `Patient`, `ValidText`, `FieldNumber`, `Marker_Height`, `Marker_Width`, `Marker_X`, `Marker_Y`, `PenPng`, `Visit`, `Page`, `EntryDate`) " &amp; _ "VALUES ('" &amp; sessionID + 1 &amp; "', '" &amp; patient &amp; "', '" &amp; myControl.Value &amp; "', '" &amp; myControl.Name &amp; "', '" &amp; rectHeight &amp; "', '" &amp; rectWidth &amp; "', '" &amp; rectX &amp; "', '" &amp; rectY &amp; "', '" &amp; penPngList(i) &amp; "', '" &amp; visit &amp; "', '" &amp; myPage.Name &amp; "', '" &amp; nowDate &amp; "')" Dim insertQuery2Exe As New MySqlCommand(insertQuery2, connToProject) rdr = insertQuery2Exe.ExecuteReader() rdr.Close() 'Update the patient data Dim insertQuery As String = "UPDATE patient" &amp; patient &amp; " SET `Data Verified (valid)` = '1' , " &amp; _ "`Valid Text (validc)` = '" &amp; myControl.Value &amp; "' , " &amp; _ "`Verified DEC (namev)` = '" &amp; penID &amp; "' , " &amp; _ "`Base DEC (nameb)` = '[Valid Override]' , `Compare DEC (namec)` = '[Valid Override]' , " &amp; _ "`LatestPenDate` = '" &amp; nowDate &amp; "' , " &amp; _ "`Base Entry Date (mdateb)` = '" &amp; nowDate &amp; "' , " &amp; _ "`Compare Entry Date (mdatec)` = '" &amp; nowDate &amp; "' , " &amp; _ "UploadedXML = '" &amp; er.DataPathName &amp; "' , " &amp; _ "FromDigiPen = '1' , " &amp; _ "rect_height = '" &amp; rectHeight &amp; "' , " &amp; _ "rect_width = '" &amp; rectWidth &amp; "' , " &amp; _ "rect_x = '" &amp; rectX &amp; "' , " &amp; _ "rect_y = '" &amp; rectY &amp; "' , " &amp; _ "PenPngLocation = '/images/" &amp; penPngList(i) &amp; "'" &amp; _ "WHERE `Visit Number (VISIT)` = '" &amp; visit &amp; "' AND " &amp; _ "`Page Number (PAGE)` = '" &amp; myPage.Name &amp; "' AND " &amp; _ "`Variable Number (var)` = '" &amp; myControl.Name &amp; "'" Dim insertQueryExe As New MySqlCommand(insertQuery, connToProject) rdr = insertQueryExe.ExecuteReader() rdr.Close() End If Next myControl i += 1 Next myPage End If Next Catch ex As Exception Dim nowDate As String nowDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") Dim rdrError As MySqlDataReader 'Connect to the patient using the information gathered from above Const connStrToProject As String = "server=localhost;user id=root; password=password; database=backend; pooling=false" Dim connToProject As New MySqlConnection(connStrToProject) connToProject.Open() Dim insertError As String = "INSERT INTO penerror (`Pen`, `Error`, `Study`, `ErrorDate`) VALUES ('" &amp; penID &amp; "', """ &amp; ex.Message &amp; """, '" &amp; project &amp; "', '" &amp; nowDate &amp; "')" Dim insertErrorExe As New MySqlCommand(insertError, connToProject) rdrError = insertErrorExe.ExecuteReader() rdrError.Close() End Try </code></pre> <p>Again, I am trying to optimise this for speed (obviously, it should still function as above).</p>
[]
[ { "body": "<p>I'm hoping all that's missing from your code is <code>Sub DoSomething</code> at the top and <code>End Sub</code> at the bottom. That's a <strong>very</strong> lengthy procedure you have here, and aside from the length itself, one sign is the &quot;need&quot; to append numbers to your identifiers (<code>conn0</code>, <code>cmd0</code>, <code>rdr0</code>, <code>insertQuery2</code>, ...).</p>\n<h3>Naming</h3>\n<p>Getting code to work is relatively easy. Getting code to work <em>better</em> is a little harder. But naming things is one of the hardest things a programmer has to do.</p>\n<blockquote>\n<p><em>There are only two hard things in Computer Science: cache invalidation and naming things.</em></p>\n<p>-- Phil Karlton</p>\n</blockquote>\n<p>The first golden rule for good naming, is to <strong>avoid disemvoweling at all costs</strong>. An identifier called <code>rdr</code> is just a missed opportunity of calling it <code>reader</code>... and having a <em>readable</em> name for it (bad pun intended).</p>\n<p>Another golden rule, is to <strong>avoid golfed names</strong>. I don't see what's stopping <code>er</code> from being called <code>exportResult</code>. Only one of the two is really meaningful.</p>\n<h3>Single Responsibility</h3>\n<p>We don't know what that procedure is called. What we <em>do</em> know is that the only thing it doesn't do is make you a coffee... but with so many lines of code it's possible I missed a method call that actually does it. The point here, is that you have a very <em>procedural</em> procedure that reads like a <em>script</em>. This isn't what .NET and VB.NET encourages you to do. Sure, it <em>gets the job done</em>, but at one point you'll want to change it, and that's when you'll start cursing at your own code.</p>\n<p>The remedy to this headache, is <em>single responsibility</em> - try to break down what your code is doing, into several, smaller functions/procedures. Name each one after what it does, and make it do that - nothing more (and nothing less).</p>\n<h3>Dispose the Disposables</h3>\n<p>Your code instanciates many objects that implement the <code>IDisposable</code> interface, but you never call their <code>Dispose()</code> method. I don't know how/whether this can affect your code's performance, but cleaning up your resources can't be harmful. Wrap those (commands, connections, etc.) into <code>Using</code> blocks, and then you won't need to remember to <code>Close()</code> connections and <code>Dispose()</code> everything.</p>\n<h3>Throw Meaningful Exceptions</h3>\n<blockquote>\n<pre><code>Throw New Exception(&quot;Could not find the identifier&quot;)\n</code></pre>\n</blockquote>\n<p>This code throws <code>System.Exception</code> - you should be throwing an exception <em>derived</em> from that class, either an existing one or one of your own, like <code>UnknownIdentifierException</code>.</p>\n<hr />\n<p>I know this review doesn't address any performance issues. I think getting your code into a more maintainable shape is more important, and will allow you to better see where the optimisation opportunities are.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:15:24.590", "Id": "40054", "ParentId": "40042", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T15:47:19.403", "Id": "40042", "Score": "7", "Tags": [ "optimization", "performance", "mysql", "vb.net" ], "Title": "Updating every field of every page in a form" }
40042
<p>I have some Node/Express.js controllers which implement the exports.method Node module convention. This particular controller also has a few helper methods. The code works fine! </p> <p>However, I'm a stickler for conventions, best practices etc. and recently I've been going back over one of my project with jshint (Sublime Text 3) and noticed my controllers throw up lots of complaints. Well really it's the same complaint over and over again - that methods called inside a exports closure are not defined, they are in fact defined in the controller but outside of the exports closure so they can be reused.</p> <p>Example, jshint complaint</p> <ul> <li>9:14 'parseQueryString' is not defined</li> </ul> <p>So really what I'm asking, is how do you recommend I structure my controller (and also more generally node modules that use exports closures) for correctness / best practice?</p> <p>Here's the code for your reference:</p> <pre><code>/* global require, exports */ 'use strict'; var mongoose = require('mongoose'), Time = mongoose.model('Time'); exports.findAll = function (req, res) { var qs = parseQueryString(req); // Importantly we should only query times for current user. qs.query.userId = getUserVal(req, '_id'); log(req, 'Retrieving all times'); Time.find(qs.query, qs.fields, qs.options, function (err, result) { if (err) { return handleError(req, res, err); } res.send(result); }); }; exports.findById = function (req, res) { var id = req.params.id, userId = req.user.get('_id'); log(req, 'Retrieving time: ' + id); Time.findOne({'_id':id,'userId':userId}, function (err, result) { if (err) { return handleError(req, res, err); } res.send(result); }); }; exports.addTime = function (req, res) { var time = new Time(req.body); // Enforce user association time.userId = req.user.get('_id'); time.user = req.user.get('name'); log(req, 'Adding time: ' + time); time.save(function (err) { if (err) { return handleError(req, res, err); } Time.findById(time._id, function (err, found) { time = found; }); res.send(time); }); }; exports.updateTime = function (req, res) { var id = req.params.id, userId = req.user.get('_id'), time = req.body; delete time._id; log(req, 'Updating time: ' + id); Time.update({'_id':id,'userId':userId}, time, function (err, rowsAffected, raw) { if (err) { return handleError(req, res, err); } console.log('The number of updated documents was %d', rowsAffected); console.log('The raw response from Mongo was ', raw); }); }; exports.deleteTime = function (req, res) { var id = req.params.id, userId = req.user.get('_id'); log(req, 'Deleting time: ' + id); Time.remove({'_id':id,'userId':userId}, function (err) { if (err) { return handleError(req, res, err); } res.send(req.body); }); }; // Helpers handleError = function(req, res, err) { log(req, 'error : ' + err); res.send({'error' : err}); }; log = function(req, msg) { console.log(msg + ' | u:' + getUserVal(req, '_id')); }; getUserVal = function(req, val) { return req.user ? req.user.get(val) : ''; }; // Extract options from query string // and format for mongoose query as follows: // query = {'client':'ABK','category':'Email'} // fields = 'client category' // options = {limit:10,skip:0} parseQueryString = function(req) { var result = { query: JSON.parse(JSON.stringify(req.query)), fields: '', options: {} }, tmp = result.query; for (var key in tmp) { if (tmp.hasOwnProperty(key)) { var val = tmp[key]; // console.log(' + key + ' = ' + val); if (key === ':show') { result.fields = val.replace(',', ' '); delete result.query[key]; } else if (key === ':limit') { result.options.limit = parseInt(val); delete result.query[key]; } else if (key === ':skip') { result.options.skip = parseInt(val); delete result.query[key]; } } } // console.log('result = ' + JSON.stringify(result)); return result; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T08:33:46.927", "Id": "69990", "Score": "0", "body": "What's your jshint configuration? You can set `\"node\": true`.\nSee the full list of options here: http://www.jshint.com/docs/options/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T21:13:45.133", "Id": "70263", "Score": "0", "body": "You can find your answer here. http://stackoverflow.com/a/336868/327004." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T18:15:47.730", "Id": "70654", "Score": "0", "body": "...They don't have `var` statements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-07T21:32:03.560", "Id": "70687", "Score": "0", "body": "Thanks Jivings, great spot I hadn't noticed that, so used to declaring functions as part of an object / module" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T15:46:23.547", "Id": "71640", "Score": "0", "body": "@Jivings in this situation, adding `var` will probably not solve the problem. From my understanding, the `parseQueryString` function is defined later in the file. So when jshint is analysing the file, the function is not defined. There is 2 options. First, you declare your function like this `function parseQueryString() {...}` or you move it at the top of the file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T17:55:58.353", "Id": "71664", "Score": "0", "body": "@jackdbernier Yes, you are correct." } ]
[ { "body": "<p>Like I mentioned in my comment, adding var will probably not solve the problem. The <code>parseQueryString</code> function is declared as a variable. Therefor it should be placed earlier in the file than the call to that function. Like explained here <a href=\"https://stackoverflow.com/a/336868/327004\">https://stackoverflow.com/a/336868/327004</a>. There is 2 options. First, you declare your function like this <code>function parseQueryString() {...}</code> or you move it at the top of the file.</p>\n\n<p>Also, it's a code review platform and the title starts with \"How to improve...\".</p>\n\n<p>Here's some comments.</p>\n\n<p><code>parseQueryString</code> by its name I think it will return an object containing all supported parameters present in the querystring. Though, by the comments I know it does way more. It also create a mongoose query. \"Extract options from query <strong>AND</strong> format for mongoose query\". Second, this function does more then one thing. Therefor, you should split it in 2. I would have 2 or 3 functions (the second one is optional) <code>extractParametersFromQueryString</code>, <code>applyDefaultValues</code> and <code>createMongooseQuery</code>.</p>\n\n<p>Finally has mentioned by @Jivings, add the <code>var</code>keyword.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-14T15:56:28.073", "Id": "41659", "ParentId": "40043", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T16:26:45.137", "Id": "40043", "Score": "6", "Tags": [ "javascript", "node.js", "express.js" ], "Title": "Express.js controller with Node.js style exports.methods" }
40043
<p>Below is code that will compile when <code>INT_MAX</code> is equal to 2<sup>32</sup>. It will generate a compiler error when <code>INT_MAX</code> is not equal to 2<sup>32</sup>.</p> <pre><code>#include &lt;iostream&gt; #include &lt;climits&gt; namespace NBitCheck { template&lt;bool&gt; struct CTAssert; template&lt;&gt; struct CTAssert&lt;true&gt; {}; constexpr bool intbitwidthcheck=INT_MAX-(2^32)+1; CTAssert&lt;intbitwidthcheck&gt; a; } int main(void) { return 0; } </code></pre>
[]
[ { "body": "<p>In C++, <code>sizeof</code> returns the size of a number relative to the size of char.</p>\n\n<p>So, <code>sizeof(int)</code> should give you how many chars each int takes.</p>\n\n<p>Next, we need to know how many bits each char has. <code>CHAR_BIT</code> has that information.</p>\n\n<p>So try this:</p>\n\n<pre><code>constexpr size_t bits_per_int = sizeof(int) * CHAR_BIT;\nconstexpr bool intbitwidthcheck = (bits_per_int == 32);\n</code></pre>\n\n<p>Frankly, I believe this way is more readable.</p>\n\n<p>Not to mention, can one reasonably expect a 32-bits <strong>signed</strong> int to contain values up to <code>2^32 - 1</code>? Shouldn't that be the <code>UINT_MAX</code>? <code>INT_MAX</code> should be up to <code>2^31 - 1</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:26:29.830", "Id": "67347", "Score": "0", "body": "One may expect (even though I never saw such architecture) that `INT_MAX == UINT_MAX` as a border case. What the standard ensures is that `The range of non-negative values of a signed integer type is a\nsubrange of the corresponding unsigned integer type, and the value representation of each corresponding\nsigned/unsigned type shall be the same.`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T21:11:55.720", "Id": "68169", "Score": "0", "body": "horrible C-style hack. Why not use the C++ features explicitly provided for such purposes? (`std::numeric_limits<>`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T02:17:55.763", "Id": "68227", "Score": "0", "body": "@Walter numeric_limits doesn't tell how many bits an int has. If instead of checking how many bits there are you really want the actual representable limits, use Massimiliano's approach instead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:55:49.407", "Id": "40049", "ParentId": "40046", "Score": "7" } }, { "body": "<p>To check if the fundamental type <code>int</code> is 32 bits wide I would do the following:</p>\n\n<pre><code>#include&lt;limits&gt;\n#include&lt;cstdint&gt;\n\nstatic_assert( std::numeric_limits&lt;int&gt;::max() == std::numeric_limits&lt;int32_t&gt;::max() , \"int is not 32 bits wide\");\n</code></pre>\n\n<p>which should be (to the best of my understanding) safer than what is proposed by @luiscubal.</p>\n\n<p>The point I would raise with the accepted answer is that <em>not all the bits in the object representation of an <code>int</code> may be used to represent a numeric value</em>.</p>\n\n<p>In fact, even though in the C++ standard (section 3.9) the issue is not clearly stated as in the C standard (section 6.2.6.2), I think the possibility of having padding bits in an integer type representation is allowed for compatibility reasons. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:22:25.253", "Id": "40086", "ParentId": "40046", "Score": "6" } } ]
{ "AcceptedAnswerId": "40049", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T18:48:20.800", "Id": "40046", "Score": "5", "Tags": [ "c++", "c++11", "template", "integer", "assertions" ], "Title": "What might be another way to test if int is 32 bits wide at compile time?" }
40046
<p>I've started learning F# and functional programming in general, but the code I wrote doesn't seems to be really <em>functional</em>. Could you take a look and say how to make it more as it should be in functional programming?</p> <pre><code>type internal CsvReader(source : Stream) = // input stream let stream = source // reader let mutable reader : StreamReader = new StreamReader(source) [&lt;Literal&gt;] let bufferSize = 1000 // currently processed line let mutable buffer : char[] = Array.zeroCreate bufferSize // current position let mutable currentPosition : int = bufferSize // end of file let mutable EndOfFile : bool = false // loads new chunk of data from file to buffer let UpdateBuffer() : bool = match reader.ReadBlock(buffer, 0, buffer.Length) with | 0 -&gt; false | _ -&gt; true // initialization method let Initialize() = let pos = source.Seek(0L, SeekOrigin.Begin) if not (pos = 0L) then raise(Exception("sdf")) () // read one char from stream let rec GetChar(eat : bool) : (bool * char) = let position = currentPosition match position with | 1000 -&gt; match UpdateBuffer() with | false -&gt; EndOfFile &lt;- true (false, Char.MinValue) | true -&gt; currentPosition &lt;- 0; GetChar(eat) | _ -&gt; let item = System.Convert.ToInt32(buffer.[position]) match item with | 0 -&gt; (false, Char.MinValue) | _ -&gt; match eat with | true -&gt; currentPosition &lt;- currentPosition + 1; (true, buffer.[position]) | false -&gt; (true, buffer.[position]) // default constructor logic do if Utils.IsNull source then raise(ArgumentNullException("source")) if not source.CanRead then raise(ArgumentException("source")) if not source.CanSeek then raise(ArgumentException("source")) Initialize() () // parameterless constructor // always throws ArgumentNullException private new() = CsvReader(null) // just for testing member x.PublicGetChar = GetChar </code></pre> <p>Right now the only think it does it stream content of <code>Stream</code> char by char by <code>PublicGetChar</code> method. I wrote UT to make sure it works:</p> <pre><code>[&lt;TestClass&gt;] type CsvReaderTests() = let GetStringStream(input : string) : Stream = let stream = new MemoryStream() let writer = new StreamWriter(stream) ignore(writer.Write(input)) writer.Flush() stream.Position &lt;- 0L stream :&gt; Stream [&lt;TestMethod&gt;] member this.TestMethod1 () = let input = "test" let reader = new CsvReader(GetStringStream(input)) let chars = seq { while fst(reader.PublicGetChar(false)) do yield snd(reader.PublicGetChar(true)) } let output = (new System.String(chars |&gt; Array.ofSeq)) input |&gt; should equal output </code></pre> <p>Main concerns I have about the code:</p> <ul> <li>usage of <code>match</code>/<code>with</code></li> <li>a lot of <code>mutable</code> stuff within <code>CsvReader</code> type</li> <li>if I had to write it in C# it would look really similar :D</li> </ul> <p>That's the very first F# code I've ever written, so be polite, please :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:38:12.227", "Id": "67294", "Score": "0", "body": "What's the point of all this code, why won't you just use `StreamReader.Read()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:40:25.390", "Id": "67295", "Score": "0", "body": "@svick Calling `Read` would require file access every time you call it. With this code you read from file in chunks, which should be faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:50:34.877", "Id": "67298", "Score": "1", "body": "No, it wouldn't. `StreamReader` already has an internal buffer. Anyway, whenever you do something that “should be faster”, you should really measure that it actually is faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:53:03.890", "Id": "67299", "Score": "1", "body": "Yes, I would definitely measure that if it was production code. It's not :) I'm trying to learn f# and that's the only reason I wrote this code." } ]
[ { "body": "<p>Your first F# code isn't too bad. I've made some small simplifications to streamline your code a bit and take advantage of some built-in F# functions:</p>\n\n<pre><code>type internal CsvReader(source : Stream) = \n\n // input stream\n let stream = source\n\n // reader\n let mutable reader : StreamReader = new StreamReader(source)\n\n [&lt;Literal&gt;]\n let bufferSize = 1000\n\n // currently processed line\n let mutable buffer : char[] = Array.zeroCreate bufferSize\n\n // current position\n let mutable currentPosition = bufferSize\n\n // end of file\n let mutable EndOfFile = false\n\n // loads new chunk of data from file to buffer\n let UpdateBuffer() : bool =\n reader.ReadBlock(buffer, 0, buffer.Length) &lt;&gt; 0\n\n // initialization method\n let Initialize() =\n let pos = source.Seek(0L, SeekOrigin.Begin)\n if not (pos = 0L) then\n invalidOp \"sdf\"\n\n // read one char from stream\n let rec GetChar(eat : bool) : (bool * char) = \n let position = currentPosition\n match position with\n | 1000 -&gt;\n match UpdateBuffer() with\n | false -&gt;\n EndOfFile &lt;- true\n false, Char.MinValue\n | true -&gt;\n currentPosition &lt;- 0\n GetChar eat\n | _ -&gt; \n match int buffer.[position] with\n | 0 -&gt;\n false, Char.MinValue\n | _ -&gt;\n match eat with\n | true -&gt;\n currentPosition &lt;- currentPosition + 1\n true, buffer.[position]\n | false -&gt; \n true, buffer.[position]\n\n // default constructor logic\n do\n if Utils.IsNull source then\n nullArg \"source\"\n if not source.CanRead then\n invalidArg \"source\" \"The source stream cannot be read from.\"\n if not source.CanSeek then\n invalidArg \"source\" \"The source stream does not support seeking.\"\n\n Initialize()\n\n // parameterless constructor\n // always throws ArgumentNullException\n private new() = CsvReader(null)\n\n // just for testing\n member x.PublicGetChar = GetChar\n</code></pre>\n\n<p>One thing you'd definitely want to add (if this were production code) -- this class would ideally implement the <code>IDisposable</code> interface so you can properly close and release the resources associated with the <code>StreamReader</code> you use internally.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T19:04:27.240", "Id": "40115", "ParentId": "40048", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T19:52:01.593", "Id": "40048", "Score": "5", "Tags": [ "beginner", "functional-programming", "f#", "stream" ], "Title": "Read text from stream char by char" }
40048
<p>This is a chat using Node.js, socket.io and MongoDB for storage.</p> <p>I'd appreciate any feedback on what can be improved. I understand that this allows for non-unique usernames to be used, and it's currently a JavaScript prompt, however this is simply a demonstration for entering a username to test the functionality.</p> <p><strong>index.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Chat&lt;/title&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="chat"&gt; &lt;div class="chat-messages"&gt;&lt;/div&gt; &lt;textarea placeholder="Type your message"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"&gt;&lt;/script&gt; &lt;script&gt; (function() { var socket = io.connect('http://127.0.0.1:8080'), name = prompt('Enter your name'); // Listen for output from server socket.on('output', function(data) { var messages = document.querySelector('.chat .chat-messages'); if(data.length) { // Loop results for(var x = 0; x &lt; data.length; x = x + 1) { var message = document.createElement('div'); message.setAttribute('class', 'chat-message'); message.innerText = data[x].name + ': ' + data[x].message; // Prepend messages.appendChild(message); messages.insertBefore(message, messages.firstChild); } } }); // Listen for keydown document.querySelector('.chat textarea').addEventListener('keydown', function(event) { var self = this; // Is enter down (without shift being held)? if(event.which === 13 &amp;&amp; event.shiftKey === false) { if(name) { // Send message socket.emit('input', { name: name, message: self.value }); self.value = ''; } event.preventDefault(); } }); })(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>server.js</strong></p> <pre><code>var mongo = require('mongodb').MongoClient, client = require('socket.io').listen(8080).sockets; client.on('connection', function(socket) { // Connect to MongoDB mongo.connect('mongodb://127.0.0.1/chat', function(err, db) { if(err) throw err; var col = db.collection('messages'); // Emit all messages col.find().limit(100).sort({_id: 1}).toArray(function(err, res) { if(err) throw err; socket.emit('output', res); }); // Wait for input socket.on('input', function(data) { col.insert({name: data.name, message: data.message}, function(err, docs) { // Emit latest message to all clients client.emit('output', [data]); }); }); }); }); </code></pre> <p><strong>main.css</strong> (not as important here)</p> <pre><code>body, textarea { font: 13px "Trebuchet MS", sans-serif; } .chat { max-width:300px; } .chat-messages, .chat textarea { border:1px solid #bbb; } .chat-messages { width:100%; height:300px; overflow-y:scroll; padding:10px; } .chat-message { margin-bottom:10px; } .chat textarea { border-top:0; margin:0; max-width:100%; width:100%; padding:10px; } .chat textarea:focus { outline:none; } </code></pre>
[]
[ { "body": "<p>You should only open one connection to mongodb. Otherwise if you have 10 users connected on your chat, you'll have 10 opened connections to mongodb.</p>\n\n<pre><code>var mongo = require('mongodb').MongoClient;\nvar sio = require('socket.io');\n\nmongo.connect('mongodb://127.0.0.1/chat', function(err, db) {\n if(err) throw err;\n\n var messages = db.collection('messages');\n\n client = sio.listen(8080).sockets;\n client.on('connection', function(socket) {\n messages.find().limit(100).sort({_id: 1}).toArray(function(err, res) {\n if(err) throw err;\n\n socket.emit('output', res);\n });\n\n socket.on('input', function(data) {\n messages.insert({name: data.name, message: data.message}, function(err, docs) {\n client.emit('output', [data]);\n });\n });\n });\n});\n</code></pre>\n\n<p>From there, I would split the code into small functions. One could be call <code>onInputMessage</code> and looks something like.</p>\n\n<pre><code>var onInputMessage = function(data) {\n message.insert({name: data.name, message: data.message}, function(err, docs) {\n client.emit('output', [data]);\n};\n</code></pre>\n\n<p>So that you can call it like this <code>socket.on('input', onInputMessage);</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-16T23:22:52.990", "Id": "44536", "ParentId": "40050", "Score": "3" } } ]
{ "AcceptedAnswerId": "44536", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T20:20:51.080", "Id": "40050", "Score": "4", "Tags": [ "javascript", "node.js", "mongodb", "chat", "socket.io" ], "Title": "Node.js chat client" }
40050
<p>I have this function:</p> <pre><code>int sort(book *data, int books, char mode, char sortBy) { int i, j; book aux; aux.cat = malloc(sizeof *(aux.cat)); if(sortBy == 'n') { for(i = 0; i &lt; books; i++) { for(j = i; j &lt; books; j++) { if(mode == 'a') { if(strcmp((data + i)-&gt;fname, (data + j)-&gt;fname) &gt; 0) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } else { if(strcmp((data + i)-&gt;fname, (data + j)-&gt;fname) &lt; 0) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } } } } else { for(i = 0; i &lt; books; i++) { for(j = i; j &lt; books; j++) { if(mode == 'a') { if(strcmp((data + i)-&gt;categ, "Fictiune") == 0) { if(((data + i)-&gt;cat)-&gt;price &gt; ((data + j)-&gt;cat)-&gt;price) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } } else { if(strcmp((data + i)-&gt;categ, "Fictiune") == 0) { if(((data + i)-&gt;cat)-&gt;price &lt; ((data + j)-&gt;cat)-&gt;price) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } } } } } free(aux.cat); return 0; } </code></pre> <p>I need to sort the <code>data</code> array in two modes: ascending and descending, and by two criteria: name and price.</p> <p>The question is: is there a way to write another, more compact function that will do the same thing?</p> <p>And, what do you think about line 5 (<code>aux.cat = malloc(sizeof *(aux.cat));</code>)? Is it a right way to initialize the <code>cat</code> pointer?</p> <p>These are the structures:</p> <pre><code>typedef struct { int price, edition; char favCharacter[SMAX]; } category; typedef struct { char title[SMAX], fname[SMAX], lname[SMAX], categ[SMAX]; category *cat; } book; </code></pre>
[]
[ { "body": "<p>The code for the two cases (sorting by name and sorting by price) have nearly nothing in common. You may be better off writing two functions. Even if you really like this interface, it might make sense to have the master function to call a sort-by-name function or a sort-by-price function to do the work.</p>\n\n<p>I have no idea what <code>aux.cat = malloc(sizeof *(aux.cat))</code> is for. You never really store anything in the <code>.cat</code> member. Furthermore, after all the swapping done in the sorting process, the <code>aux.cat</code> at the end of the function is not the same <code>aux.cat</code> that you started out with. That's a memory leak.</p>\n\n<p>Your sort algorithm is <a href=\"http://en.wikipedia.org/wiki/Selection_sort\" rel=\"nofollow\">selection sort</a>, which takes O(<em>n</em><sup>2</sup>) time. There are more efficient algorithms that work in O(<em>n</em> log <em>n</em>) time.</p>\n\n<p>Your <code>sort()</code> function always returns <code>0</code>. You might as well make it a <code>void</code> function and not return any value.</p>\n\n<p>For efficiency and brevity, you would be better off using sorting routines built into the C library. All you have to do to use those routines is to define a comparator function, which tells the sorting function how to order any pair of books.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nstatic int compare_books_by_name_asc(const void *a, const void *b) {\n const book *book_a = (const book *)a,\n *book_b = (const book *)b;\n return strcmp(book_a-&gt;fname, book_b-&gt;fname);\n}\n\nstatic int compare_books_by_name_desc(const void *a, const void *b) {\n return compare_books_by_name_asc(b, a);\n}\n\nstatic int compare_books_by_price_asc(const void *a, const void *b) {\n int price_a = ((const book *)a)-&gt;cat-&gt;price,\n price_b = ((const book *)b)-&gt;cat-&gt;price;\n return price_a &lt; price_b ? -1 :\n price_a &gt; price_b ? +1 : 0;\n}\n\nstatic int compare_books_by_price_desc(const void *a, const void *b) {\n return compare_books_by_price_asc(b, a);\n}\n\nvoid sort(book *books, int num_books, char mode, char sortBy) {\n int (*comparator)(const void *, const void *);\n if (sortBy == 'n') { /* Sort by name */\n comparator = (mode == 'a') ? compare_books_by_name_asc\n : compare_books_by_name_desc;\n } else { /* Sort by price */\n comparator = (mode == 'a') ? compare_books_by_price_asc\n : compare_books_by_price_desc;\n }\n qsort(books, num_books, sizeof(*books), comparator);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:42:47.267", "Id": "40056", "ParentId": "40051", "Score": "4" } } ]
{ "AcceptedAnswerId": "40056", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T20:55:14.367", "Id": "40051", "Score": "5", "Tags": [ "c", "sorting", "memory-management", "pointers" ], "Title": "Shorten a sorting function" }
40051
<ul> <li>Website: <a href="http://www.pubnub.com/" rel="nofollow">http://www.pubnub.com/</a></li> <li>Stack Overflow tag wiki: <a href="http://stackoverflow.com/tags/pubnub/info">http://stackoverflow.com/tags/pubnub/info</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:03:20.483", "Id": "40052", "Score": "0", "Tags": null, "Title": null }
40052
PubNub offers a publish/subscribe API for real-time messaging in the cloud.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:03:20.483", "Id": "40053", "Score": "0", "Tags": null, "Title": null }
40053
<p>I'm wondering if anyone would like to give me some solid advice on how to better organize my main.js file. I have a hunch that I should probably break the file into multiple files and decrease the amount of global variables. Maybe my naming is not so great either? I'm using codekit so I can prepend if that won't screw up my scopes.</p> <p><a href="https://github.com/adamgedney/AGedneySMS/blob/master/js/main.js" rel="nofollow">GitHub</a></p> <pre><code>//@codekit-prepend "jquery-1.10.2.min.js" //@codekit-prepend "jquery.event.special.js" //@codekit-prepend "jquery.easing.min.js" //@codekit-prepend "lightbox-2.6.min.js" //@codekit-prepend "handlebars-v1.1.2.js" //Globals var duration; var seek_time; var seek_bar_left; var seek_bar_right; var seek_scrub; var seek_bar_width; var xPos; var name; var cam_toggle; var mic_toggle; var rec_toggle; var fav_toggle; var mic_index = 0;//0 default mic var cam_index = 0;//0 default cam var drag = false; var play_toggle = false; var playing = false; var recording = false; var connection_open = false; var current_video; var current_user; var user_avatar; var user_avatar_array = []; var comments_array = []; var user_array = []; var created_array = []; var new_video = false; //firebase globals var db = new Firebase('https://adamgedney.firebaseio.com/'); var video_obj = db.child('/videos'); var comments_obj = db.child('/comments'); // var globalError = function(message){ // console.log(message, "error mess"); // } //==========================================callbacks=================================// var connected = function(success, error){ console.log(success, error); if(success){ connection_open = true; if(recording){ flash.startRecording(name,cam_index,mic_index); }else{ flash.startPlaying(current_video); }; }else{ connection_open = false; } }; var getDuration = function(dur){ duration = dur; }; var seekTime = function(time){ seek_time = time; xPos = (seek_time / duration) * seek_bar_right; // scrub position update only when not dragging if(!drag){ $('#seek_bar_scrub').offset({left: seek_bar_left + xPos}); } };// seekTime() //auth callback var auth = new FirebaseSimpleLogin(db, function(error, user){ if(!error){ if(user.provider == "github"){ current_user = user.displayName; user_avatar = user.avatar_url; login(); }else if(user.provider == "twitter"){ current_user = user.displayName; user_avatar = user.profile_image_url; login(); } } }); // //end callbacks // //========================Seek Bar drag/drop functionality=========================// //mousedown to start drag $(document).on('mousedown', '#seek_bar_scrub', function(e){ drag = true; //required to prevent text selection on mouseout of seek_bar e.preventDefault(); moving(); }); //mouseup to stop drag $(document).on('mouseup', function(e){ drag = false; }); //drag and setTime function moving(){ $(document).on('mousemove', function(e){ var set_time = ((e.pageX - seek_bar_left) / seek_bar_width) * duration; if(drag){ $('#seek_bar_scrub').offset({left: e.pageX}); //sets scrub time flash.setTime(set_time); //creates a border if(seek_scrub &lt; seek_bar_left){ $('#seek_bar_scrub').offset({left: seek_bar_left}); }else if(seek_scrub &gt; (seek_bar_right - $('#seek_bar_scrub').width())){ $('#seek_bar_scrub').offset({left: (seek_bar_right - $('#seek_bar_scrub').width())}); }; }; }); }; //flash ready serves as document ready var flashReady = function(){ //sets init volume to 70 $('#vol_bar').val(100); $(document).on('click', '#play_btn', function(e){ play_video(); }); };// flashReady() //set volume init $(document).on('change', function(e){ var vol = $('#vol_bar').val() / 100; vol = vol.toFixed(1); flash.setVolume(vol); }); function play_video(){ //handles connect or play/pause toggle if(!playing){ flash.stopRecording(); flash.connect('rtmp://localhost/SMSServer/'); playing = true; recording = false; new_video = false; }else if(playing &amp;&amp; !recording &amp;&amp; new_video){ flash.stopPlaying(); flash.connect('rtmp://localhost/SMSServer/'); new_video = false; }else if(playing &amp;&amp; !new_video){ flash.playPause(); } //handles image toggle if (!play_toggle){ $('#play_btn').attr('src', 'images/pause.png'); play_toggle = true; }else{ $('#play_btn').attr('src', 'images/play.png'); play_toggle = false; } }; //---------------------------Templating--------------------------// init(); function init(){ $.get('templates/templates.html', function(htmlArg){ var source = $(htmlArg).find('#logged_out').html(); var template = Handlebars.compile(source); // var context = {id: posts._id, title:posts.title, created: posts.created, author: posts.author, category: posts.category, text: posts.text} // var html = template(context); $('#content').append(template); //defaults to hide upon program load $('.transport_popup').hide(); $('.rec_select').hide(); $('.mic_select').hide(); $('.cam_select').hide(); $('.login_popup').hide(); $('.sub_list').hide(); });//get() };//init() //--------------------On login, $.get logged in state----------------// $(document).on('click', '#login_gh', function(e){ //github authentication auth.login('github'); }); $(document).on('click', '#login_tw', function(e){ //github authentication auth.login('twitter'); }); function login(){ $.get('templates/templates.html', function(htmlArg){ var source = $(htmlArg).find('#logged_in').html(); var template = Handlebars.compile(source); // var context = {id: posts._id, title:posts.title, created: posts.created, author: posts.author, category: posts.category, text: posts.text} // var html = template(context); $('#content').empty(); $('#content').append(template); //defaults to hide upon program load $('.transport_popup').hide(); $('.rec_select').hide(); $('.mic_select').hide(); $('.cam_select').hide(); $('.stop_rec_modal').hide(); $('.login_popup').hide(); $('.sub_list').hide(); seek_bar_width = $('#seek_bar_inner').width(); seek_bar_left = Math.floor($('#seek_bar_inner').offset().left); seek_bar_right = seek_bar_left + seek_bar_width; seek_scrub = $('#seek_bar_scrub').offset().left; swfobject.embedSWF( "swf/higley_wigley.swf", "flashContent", "100%", "100%", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes); // JavaScript enabled so display the flashContent div in case it is not replaced with a swf object. swfobject.createCSS("#flashContent", "display:block;text-align:left;"); //populates comments &amp; video fields get_comments(); get_videos(); });//get() };//login() //Controls logout $(document).on('click', '#login_state', function(e){ if($('#login_state').html() == "Logout"){ //logs out facebook or twitter auth.logout(); $.get('templates/templates.html', function(htmlArg){ var source = $(htmlArg).find('#logged_out').html(); var template = Handlebars.compile(source); // var context = {id: posts._id, title:posts.title, created: posts.created, author: posts.author, category: posts.category, text: posts.text} // var html = template(context); $('#content').empty(); $('#content').append(template); //defaults to hide upon program load $('.transport_popup').hide(); $('.rec_select').hide(); $('.mic_select').hide(); $('.cam_select').hide(); $('.login_popup').hide(); $('.sub_list').hide(); });//get() };// if }); //-------------Show/hide login dropdown----------------// var log_toggle = false; $(document).on('click', '#login_state', function(e){ if(!log_toggle){ $('.login_popup').fadeIn(); log_toggle = true; }else{ $('.login_popup').fadeOut(); log_toggle = false; } }); //====================Show/Hide mic/cam/rec options=====================// //camera select popup $(document).on('click', '#camera_btn', function(e){ if (!cam_toggle){ //hides other popups $('.mic_select').hide(); $('.rec_select').hide(); $('#mic_btn').css('opacity', '1'); rec_toggle = false; mic_toggle = false; $('#camera_btn').css('opacity', '.5'); $('.transport_popup').fadeIn(); $('.cam_select').fadeIn(); cam_toggle = true; //get and loop through attached cameras var cam_list = flash.getCameras(); $('.cameras').empty(); for(var i=0; i&lt;cam_list.length; i++){ var li = '&lt;li&gt;&lt;a id="' + i + '" href="#"&gt;' + cam_list[i].substr(0, 18) + '&lt;/a&gt;&lt;/li&gt;'; $('.cameras').append(li); } }else{ $('#camera_btn').css('opacity', '1'); $('.transport_popup').fadeOut(); $('.cam_select').fadeOut(); cam_toggle = false; } }); //select and store camera choice $(document).on('click', '.cameras a', function(e){ e.preventDefault(); cam_index = $(this).attr("id"); }); //mic select popup $(document).on('click', '#mic_btn', function(e){ if (!mic_toggle){ //hides other popups $('.cam_select').hide(); $('.rec_select').hide(); $('#camera_btn').css('opacity', '1'); cam_toggle = false; rec_toggle = false; $('#mic_btn').css('opacity', '.5'); $('.transport_popup').fadeIn(); $('.mic_select').fadeIn(); mic_toggle = true; //get and loop through attached cameras var mic_list = flash.getMicrophones(); $('.mics').empty(); for(var j=0; j&lt;mic_list.length; j++){ var li = '&lt;li&gt;&lt;a id="' + j + '" href="#"&gt;' + mic_list[j].substr(0, 20) + '&lt;/a&gt;&lt;/li&gt;'; $('.mics').append(li); } }else{ $('#mic_btn').css('opacity', '1'); $('.transport_popup').fadeOut(); $('.mic_select').fadeOut(); mic_toggle = false; } }); //select and store microphone choice $(document).on('click', '.mics a', function(e){ e.preventDefault(); mic_index = $(this).attr("id"); }); //record popup $(document).on('click', '#rec_btn', function(e){ if (!rec_toggle){ //hides other popups $('.mic_select').hide(); $('.cam_select').hide(); $('#rec_btn').attr('src', 'images/cancel_rec.png'); $('#rec_btn').attr('title', 'Cancel Recording'); $('#mic_btn').css('opacity', '1'); $('#cam_btn').css('opacity', '1'); cam_toggle = false; mic_toggle = false; $('.transport_popup').fadeIn(); $('.rec_select').fadeIn(); rec_toggle = true; }else{ $('#rec_btn').attr('src', 'images/rec.png'); $('#rec_btn').attr('title', 'Record A Video'); $('.transport_popup').fadeOut(); $('.rec_select').fadeOut(); rec_toggle = false; } }); //start recording $(document).on('click', '#start_recording', function(e){ e.preventDefault(); name = $('#name').val(); var cat = $('#category').val(); var desc = $('#file_desc').val(); //opens connection flash.stopPlaying(); flash.connect('rtmp://localhost/SMSServer/'); recording = true; playing = false; // $('.poster').fadeOut(); $('.stop_rec_modal').fadeIn(); //resets the record modal $('#rec_btn').attr('src', 'images/rec.png'); $('#rec_btn').attr('title', 'Record A Video'); $('.transport_popup').fadeOut(); $('.rec_select').fadeOut(); rec_toggle = false; //adds video to database video_obj.push({video: name, category: cat, description: desc, author: current_user, created_date: get_datetime()}); }); //stop recording button $(document).on('click', '#stop_rec', function(e){ flash.stopRecording(); $('.stop_rec_modal').hide(); // $('.poster').fadeIn(); }); //-------------Favorites button------------// $(document).on('click', '#fav_btn', function(e){ if (!fav_toggle){ $('#fav_btn').attr('src', 'images/star_y.png'); fav_toggle = true; }else{ $('#fav_btn').attr('src', 'images/star.png'); fav_toggle = false; } }); //------------Category Dropdown----------------// var cat_toggle; var v_toggle; var f_toggle; $(document).on('click', '.drop_down', function(e){ e.preventDefault(); if($(this).html() == 'My Videos'){ if(!v_toggle){ $('.vid_cats').fadeOut(); $('.favorited_vids').fadeOut(); f_toggle = false; cat_toggle = false; $('.my_vids').fadeIn(); v_toggle = true; }else{ $('.my_vids').fadeOut(); v_toggle = false; } }else if($(this).html() == 'Favorites'){ if(!f_toggle){ $('.my_vids').fadeOut(); $('.vid_cats').fadeOut(); cat_toggle = false; v_toggle = false; $('.favorited_vids').fadeIn(); f_toggle = true; }else{ $('.favorited_vids').fadeOut(); f_toggle = false; } }else if($(this).html() == 'Categories'){ if(!cat_toggle){ $('.favorited_vids').fadeOut(); $('.my_vids').fadeOut(); f_toggle = false; v_toggle = false; $('.vid_cats').fadeIn(); cat_toggle = true; }else{ $('.vid_cats').fadeOut(); cat_toggle = false; } }; }); $(document).on('click', '.sub_list a', function(e){ e.preventDefault(); $('.sub_list').fadeOut(); cat_toggle = false; v_toggle = false; f_toggle = false; }); //============================Click Handlers==============================// //set comments $(document).on('click', '#submit_comment', function(e){ e.preventDefault(); set_comment(); }); //select lesson from list &amp; set current video to this value $(document).on('click', '.lesson', function(e){ var this_title = $(this).find('h2').html(); var this_time = $(this).find('h3').html(); var this_desc = $(this).find('p').html(); current_video = this_title + ".flv"; new_video = true; // flash.stopPlaying(); play_video(); get_comments(); render_info(this_title, this_time, this_desc); }); //============================Getters/Setters==============================// function set_comment(){ var com = $('#new_comment').val(); var usr = current_user; var d = get_datetime(); var t = current_video; //pushes comment into messages object comments_obj.push({user: usr, avatar: user_avatar, comment: com, created: d, title: t}); //resets comment form $('#new_comment').val(''); //gets comments and appends to comment list get_comments(); }; //retrieve comments when there is a new one //store in the comments_array function get_comments(){ $('.comments_wrapper').empty(); comments_obj.on('child_added', function (snapshot) { console.log(snapshot.val().title, "comment in db"); var comments = snapshot.val().comment; var users = snapshot.val().user; var created = snapshot.val().created; var avatar = snapshot.val().avatar; //empties arrays comments_array = []; user_array = []; created_array = []; user_avatar_array = []; if(snapshot.val().title == current_video){ //pushes result strings into arrays comments_array.push(comments); user_array.push(users); created_array.push(created); user_avatar_array.push(avatar); render_comments(); }; }); }; //get_comments() function get_videos(){ video_obj.on('child_added', function (snapshot) { var video_array = []; video_array.push(snapshot.val()); render_videos(video_array); }); }; //get_comments() function get_datetime(){ // datetime on 12 hr clock var d = new Date(); var day = d.getDay(); var month = d.getMonth() + 1; var year = d.getFullYear(); var hour = d.getHours(); var minutes = d.getMinutes(); var time; if(hour &gt; 12){ hour = hour - 12; time = hour + ":" + minutes; time += "pm"; } return month + "/" + day + "/" + year + " " + time; }; //============================Renderers==============================// function render_videos(video_array){ for (var l=0;l&lt;video_array.length;l++){ var s = '&lt;div class="lesson"&gt;'; s += '&lt;img src="images/thumb.jpg" alt="video thumbnail"/&gt;'; s += '&lt;h2&gt;' + video_array[l].video + '&lt;/h2&gt;'; s += '&lt;h3&gt;' + video_array[l].created_date + '&lt;/h3&gt;'; s += '&lt;p&gt;' + video_array[l].description + '&lt;/p&gt;'; s += '&lt;/div&gt;&lt;!-- ./lesson--&gt;'; $('.lessons_container').append(s); };// for }; function render_comments(){ for (var k=0;k&lt;comments_array.length;k++){ var s = '&lt;div class="comment"&gt;'; s += '&lt;a href="' + user_avatar_array[k] + '" data-lightbox="avatar id" &gt;&lt;img src="' + user_avatar_array[k] + '" alt="user avatar" /&gt;&lt;/a&gt;'; s += '&lt;h2&gt;' + user_array[k] + '&lt;/h2&gt;'; s += '&lt;h3&gt;' + created_array[k] + '&lt;/h3&gt;'; s += '&lt;p&gt;' + comments_array[k] + '&lt;/p&gt;'; s += '&lt;/div&gt;&lt;!-- /.comment--&gt;'; $('.comments_wrapper').append(s); };// for }; function render_info(title, time, desc){ $('.desc').empty(); var s = '&lt;div class="title_wrapper"&gt;'; s += '&lt;h1&gt;' + title + '&lt;/h1&gt;'; s += '&lt;p class="time"&gt;' + time + '&lt;/p&gt;'; s += '&lt;/div&gt;&lt;!-- /.title_wrapper--&gt;'; s += '&lt;p class="desc_copy"&gt;' + desc + '&lt;/p&gt;'; s += '&lt;div class="desc_gallery"&gt;'; s += '&lt;a href="images/poster.jpg" data-lightbox="movie screenshots"&gt;&lt;img src="images/shot.jpg" alt="movie screenshot 1"/&gt;&lt;/a&gt;'; s += '&lt;a href="images/poster.jpg" data-lightbox="movie screenshots"&gt;&lt;img src="images/shot.jpg" alt="movie screenshot 2"/&gt;&lt;/a&gt;'; s += '&lt;/div&gt;&lt;!-- /.desc_gallery--&gt;'; $('.desc').append(s); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:25:06.430", "Id": "67293", "Score": "3", "body": "please fix your indentation, it's horrific and makes reading it difficult especially in Post formatting. I already removed the white space. I would get rid of it if it is in your code. if you did it to separate the blocks in this post you should use `---` with a new line before and after, this will give you a separator line in the post" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:32:13.640", "Id": "67305", "Score": "1", "body": "Things like `$('#rec_btn').attr('src', 'images/cancel_rec.png');\n $('#rec_btn').attr('title', 'Cancel Recording');` should usually be chained and written `$('#rec_btn').attr('src', 'images/cancel_rec.png').attr('title', 'Cancel Recording');`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:27:35.853", "Id": "67321", "Score": "1", "body": "Also I'd recommend creating a namespace and putting all those globals in your namespace object" } ]
[ { "body": "<p>Two random thoughts:</p>\n\n<ol>\n<li><p>In the <em>Category Dropdown</em> part the <code>$(this).html()</code> could be extracted out to a named local variable.</p></li>\n<li><p>The following code is duplicated, it could be extracted out a separate function:</p>\n\n<pre><code>$('.transport_popup').hide();\n$('.rec_select').hide();\n$('.mic_select').hide();\n$('.cam_select').hide();\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:20:27.017", "Id": "67319", "Score": "1", "body": "you could also write it `$('.transport_popup, .rec_select, .mic_select, .cam_select').hide()` and underscores in css names is poor style" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:54:35.433", "Id": "40070", "ParentId": "40055", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T21:30:30.393", "Id": "40055", "Score": "5", "Tags": [ "javascript", "video" ], "Title": "Streaming media server" }
40055
<p>I'm basically redoing a piece of reactive C# code <a href="https://stackoverflow.com/questions/19499469/how-to-extend-throttle-timespan-in-middle-of-a-long-running-query">posted in SO</a> code in F#, please, see below. The translation is fairly literal, I've just written the infinite loop as a recursive function and rearranged the conditions for breaking the recursion. Any notes regarding style and so forth, even the most subjective ones, are a fair game, but I would like to present two explicit questions: </p> <p>As reading <a href="https://codereview.stackexchange.com/users/2041/svick">svick's</a> comment I realised I'm actually asking advice on how could I refactor the <code>throttleDuration</code> part of code to be actually be inside the <code>throttleFactory</code>, which in turn then would produce the desired doubles. It looks like I'm feeling the effect of trying to think more functionally and in terms of function composition as it feels more natural than in F# than in C#.</p> <p>In any event, two points of note here:</p> <ul> <li>Would this refactoring question be a better fit for Stackoverflow question?</li> <li>Currently in my intended sequence of doubles from <code>throttleFactory</code> to <code>Throttle</code> there is an added twist in form of the <em>q for quitting variable</em>. I believe this could be safely ignored and just assume there would be only valid doubles produced somehow by some kind of a generator. This would also drop out the question about <code>if conditional</code> on context my particular piece of code (of course, not in general sense) unless there's some slick way of doing the generating and checking with active patterns or something.</li> </ul> <p>As writing this now, it also looks like I wouldn't need the whole <code>inputLoop</code> variable in case I'd use just some arbitrary generator, which in turn negates some the ideas I had with regarding rehearsing this (I haven't tried to write actual code as of yet). The thing is, I'm rookie enough with this so as not to know if going this "<em>plain generator</em> or <em>q for quitting also</em>" route would bear fruit and I'm afraid I run out of time trying if I try for too long by myself.</p> <p>The above mentioned sequence generation (excluding the issue of quitting) is the vague reason I'm suspiciously eying at the <code>ref cell</code>. I leave the rest of my original post as is for reference.</p> <p>Ignoring the magic numbers, would there be a more idiomatic (or cleaner) way to write the generator or equivalent function?</p> <pre><code>open System open FSharp.Reactive open System.Reactive open System.Reactive.Linq [&lt;EntryPoint&gt;] let main argv = let throttleValueGenerator(minInclusiveMillisecondsLowerBound, maxExlusivemillisecondsUpperBound, countOfValues) = let rnd = new System.Random() Observable.Generate(0, (fun value -&gt; value &lt; countOfValues), (fun value -&gt; value + 1), (fun value -&gt; rnd.Next(minInclusiveMillisecondsLowerBound, maxExlusivemillisecondsUpperBound)), (fun value -&gt; TimeSpan.FromSeconds(float 1))) //The idea here is to produce events on one second intervals and whenever throttle is more than one second, no value will be output. let throttleFactory = fun _ -&gt; throttleValueGenerator(100, 2000, 30) let sequence = Observable.Interval(TimeSpan.FromSeconds(1.0)).Throttle(throttleFactory) printfn "Sequence starts on %A..." DateTime.Now let subscription = sequence.Subscribe(fun a -&gt; printfn "%i on %A" a DateTime.Now) Console.ReadKey() |&gt; ignore printfn "Sequence end on %A." DateTime.Now subscription.Dispose() 0 </code></pre> <ul> <li><p>I became to think if it'd be possible to leave out the intermediary feeling <code>ref throttleDuration</code> and perhaps construct the <code>throttleFactory</code> in some slick way by parsing the Console.ReadLine and in case it's double, parse piping/creating an infinite sequence or something from <code>Console.ReadLine()</code> and feeding the values directly into the <code>Throttle</code> function (or to <code>throttleFactory</code>). There mightn't be, but I would like to avoid banging my head too hard when thinking of that, albeit it might be educational.</p></li> <li><p>Do those <em>if conditionals</em> look all right from functional style perspective or could active patterns fit here? I read about them in <a href="http://fsharpforfunandprofit.com/posts/convenience-active-patterns/" rel="nofollow">F# for Fun and profit article</a> by <strong>Scott Wlaschin</strong> (a good site, slick looking code) and they could be usable in situations like this at least in larger code bases.</p></li> </ul> <p>For the code below, I installed both <a href="https://www.nuget.org/packages/Rx-Main" rel="nofollow">Rx-Main</a> and <a href="https://www.nuget.org/packages/FSharp.Reactive/" rel="nofollow">FSharp.Reactive</a>.</p> <pre><code>open System open FSharp.Reactive open System.Reactive open System.Reactive.Linq [&lt;EntryPoint&gt;] let main argv = let throttleDuration = ref (TimeSpan.FromSeconds(0.5)); let throttleFactory = fun _ -&gt; Observable.Timer(!throttleDuration) let sequence = Observable.Interval(TimeSpan.FromSeconds(1.0)).Throttle(throttleFactory); let subscription = sequence.Subscribe(fun a -&gt; printfn "%i" a) let rec inputLoop() = printfn "Enter throttle duration in seconds or 'q' to quit" let input = Console.ReadLine().Trim() if not(String.Equals(input, "q", StringComparison.InvariantCultureIgnoreCase)) then let success, value = System.Double.TryParse input if success then throttleDuration := TimeSpan.FromSeconds(value); inputLoop() inputLoop() |&gt; ignore subscription.Dispose() 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:47:57.240", "Id": "67297", "Score": "1", "body": "So you want `throttleDuration` to mutate, but not be mutable? That doesn't make much sense to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T08:45:59.513", "Id": "67331", "Score": "0", "body": "That was a good question, it made me clarify my thoughts (in addition of sleeping over it). I updated my post to hopefully convey better what I was really thinking (I think) when I wrote it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:02:58.593", "Id": "40057", "Score": "4", "Tags": [ "f#", "system.reactive" ], "Title": "F# and Rx code that throttles; can it be done without ref cells (and possibly with active patterns)?" }
40057
<p>I want to learn how to write clean code from the start. This is my first project, a 'Minimum Viable Product' implementation of Conway's Game of Life in C#. Mostly I want to know if my code is readable, clean, understandable, etc.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; //The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur: //Any live cell with fewer than two live neighbours dies, as if caused by under-population. //Any live cell with two or three live neighbours lives on to the next generation. //Any live cell with more than three live neighbours dies, as if by overcrowding. //Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. //The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations. namespace Life { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // Some parameters to use throughout the program // I'll basically use an array to store data and buttons to represent the cells static int columns = 30; // Columns the Grid will have static int rows = 20; // Rows the Grid will have static int depth = 3; // Depth of the Grid int cellWidth = 20; // With of the cells which will also be used to determine positions int cellHeight = 20; // Height of the cells which will also be used to determine position string[, ,] cellGrid = new string[columns, rows, depth]; // This is the array that will hold the cell's information Panel Panel1 = new Panel(); // A panel where the cells will be laid out // Upon Loading the Form //Add the Panel and Populate with the cells public void Form1_Load(object sender, EventArgs e) { this.Controls.Add(Panel1); Panel1.Location = new Point(0, 0); Panel1.Size = new Size(cellWidth * columns, cellHeight * rows); Panel1.Visible = true; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { Button cell = new Button(); cellGrid[j, i, 0] = "dead"; // All cells start dead cell.Location = new Point((j * cellWidth), (i * cellHeight)); // Possition is assigned to cell cell.Size = new Size(cellWidth, cellHeight);// Size is Assigned to cell cell.Click += button_Click; cell.FlatStyle = FlatStyle.Flat; // Style cell.Margin.All.Equals(0); // Margins cell.BackColor = Color.White; // Color Panel1.Controls.Add(cell); // Add to Panel } } } // When clicking on a cell it will switch between being alive and dead private void button_Click(object sender, EventArgs e) { Button thisButton = ((Button)sender); // Get the index in cellGrid using the cell's position int xIndex = thisButton.Location.X / cellWidth; int yIndex = thisButton.Location.Y / cellHeight; if (thisButton.BackColor == Color.White) // If the BackColor is white, it means it's dead so { thisButton.BackColor = Color.Black; // Change the color to Black cellGrid[xIndex, yIndex, 0] = "Alive"; // Change the cell to "Alive" in the Array } else // Otherwise it's alive so: { thisButton.BackColor = Color.White; // Change color to White cellGrid[xIndex, yIndex, 0] = "Dead"; // Change to Dead in the array } } // This will determine how many Neighbours or live cells each space has void Neighbours() { for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { int neighbours = 0; for (int k = i - 1; k &lt; i + 2; k++) { for (int l = j - 1; l &lt; j + 2; l++) { try { if (k == i &amp;&amp; l == j) { neighbours += 0; } else if (cellGrid[l, k, 0] == "Alive") { neighbours += 1; } } catch (Exception e) { neighbours += 0; } } } cellGrid[j, i, 1] = neighbours.ToString(); } } } // Switches the grid to the next generation killing and reviving cells following the rules. public void UpdateGrid() { foreach (Control cell in Panel1.Controls) { int xIndex = cell.Left / cellWidth; int yIndex = cell.Top / cellHeight; int neighbours = Convert.ToInt32(cellGrid[xIndex, yIndex, 1]); if (neighbours &lt; 2 | neighbours &gt; 3) { cellGrid[xIndex, yIndex, 0] = "Dead"; cell.BackColor = Color.White; } else if (neighbours == 3) { cellGrid[xIndex, yIndex, 0] = "Alive"; cell.BackColor = Color.Black; } } } // Each generation that passes updates the grid following the rules public void NextGen() { Neighbours(); UpdateGrid(); } // Each tick of the timer will be a generation private void timer1_Tick(object sender, EventArgs e) { timer1.Stop(); NextGen(); timer1.Start(); } // When pressing the Start button, generations will start passing automatically private void StartBtn_Click(object sender, EventArgs e) { if (StartBtn.Text == "Start" | StartBtn.Text == "Resume") { timer1.Start(); StartBtn.Text = "Pause"; } else { timer1.Stop(); StartBtn.Text = "Resume"; } } // Pressing Reset, resets the grid private void ResetBttn_Click(object sender, EventArgs e) { timer1.Stop(); StartBtn.Text = "Start"; for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; columns; j++) { cellGrid[j, i, 0] = "dead"; // Kill all cells } } NextGen(); //Makes one generation go by } // You can pass generations manually by pressing Next Gen Button private void NextGenBttn_Click(object sender, EventArgs e) { NextGen(); //Hace que transcurra una generación } // Control how many generations in each second by changing the value private void GenXSec_ValueChanged(object sender, EventArgs e) { timer1.Interval = Convert.ToInt32(1000 / GenXSec.Value); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:28:23.937", "Id": "67322", "Score": "3", "body": "MVP? Wait, what? What does that stand for in this context? I don't think you're trying to figure out who was the most valuable player in the Game of Life..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T03:17:52.240", "Id": "67324", "Score": "0", "body": "@user2357112 I don't understand the use of MVP either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T04:55:15.940", "Id": "67327", "Score": "0", "body": "Thanks for all the feedback. MVP stands for Minimum Viable Product. It's lean startup talk meaning. Something that works with the bare minimum of features and design" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T05:21:04.773", "Id": "67328", "Score": "6", "body": "@user2900210 You might want to define such non-standard acronyms in your question body in the future, not everybody speaks lean-startup :)" } ]
[ { "body": "<p>Just a few random notes:</p>\n\n<ol>\n<li><p>Instead of <code>i</code> and <code>j</code> the variables could be called as <code>rowNumber</code> and <code>columnNumber</code>.</p>\n\n<p>Update for Thomas's comment: Reading (and understanding) code usually takes time but it's usually not because of long variable or method names. I'd not optimize for character number. There are debates about <a href=\"https://softwareengineering.stackexchange.com/q/71710/36726\">this topic on Programmer.SE</a> too. <a href=\"https://softwareengineering.stackexchange.com/a/71723/36726\">My favorite answer is nikie's one</a>, beacuse of mentioning the short 7-slot (+-2) term memory.</p></li>\n<li>\n\n<pre><code>cellGrid[j, i, 0]\n</code></pre>\n\n<p><code>0</code> here is a magic number. A named constant would be better.</p></li>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code>cell.BackColor = Color.White; // Color\n</code></pre>\n\n<p>It says nothing more than the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>Shorter lines, without horizontal scrolling would be easier to read.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:34:07.070", "Id": "67338", "Score": "0", "body": "Imho your first advice is a bit too verbose. `i` and `j` are fairly standard index variable names, as long as you define them properly. `row` and `col` maybe, but `rowNumber` and `columnNumber` is just way too long." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:13:02.853", "Id": "67341", "Score": "0", "body": "@Thomas: I'v updated the answer a little bit about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T12:30:23.320", "Id": "67481", "Score": "1", "body": "Typos like `for (int j = 0; i < columns; j++)` are easy to make, and hard to spot. If you mistype `column` it's a bright red line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T09:00:56.777", "Id": "74418", "Score": "0", "body": "@palacsint Sure, but the type (int) already indicates that they are numbers. So in that respect `rowNumber` and `columnNumber` are rather redundant names, so `row` and `column` are more appropriate IMHO. Being explicit doesn't mean being redundant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T11:37:44.723", "Id": "74423", "Score": "1", "body": "@Thomas: When I wrote them I thought of them as `rowIndex` and `coluumnIndex` I guess it would have been better, thanks for pointing that out! (An integer also could be a counter, a minimal value etc., so the `index` postfix does not seem redundant to me.)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T23:03:21.410", "Id": "40062", "ParentId": "40059", "Score": "3" } }, { "body": "<p>You defined depth as 3, but, you're only using 2 strings (one for the alive-or-dead, and the second for the neighbours-count).</p>\n\n<p>Instead of storing cell-state as an array of strings, define a class (or perhaps a struct):</p>\n\n<pre><code>enum State\n{\n Alive,\n Dead\n}\nclass CellState\n{\n internal State State { get; set; }\n internal int Neighbours { get; set; }\n internal CellState() { this.State = State.StateDead; Neighbours = 0; }\n}\n</code></pre>\n\n<p>... also ...</p>\n\n<pre><code>CellState[,] cellGrid = new CellState[columns, rows];\n\ncellGrid[j, i] = new CellState(); // All cells start dead\n\ncellGrid[xIndex, yIndex].State = State.Alive; // Change the cell to \"Alive\" in the Array\n</code></pre>\n\n<p>Or (if there are only two states) use a boolean instead of an enum:</p>\n\n<pre><code>class CellState\n{\n internal bool IsAlive { get; set; }\n internal int Neighbours { get; set; }\n internal CellState() { this.IsAlive = false; Neighbours = 0; }\n}\n</code></pre>\n\n<hr>\n\n<p>Creating 400 Button controls becomes expensive. If you had a much larger grid (e.g. 1000x1000) then you (i.e. your machine) couldn't manage it. Instead of Button controls, you could create a Custom Control on which you Paint the cells yourself, and handle its mouse events for hit-tests.</p>\n\n<hr>\n\n<p>This was confusing at first sight:</p>\n\n<pre><code> for (int i = 0; i &lt; rows; i++)\n {\n for (int j = 0; j &lt; columns; j++)\n {\n int neighbours = 0;\n\n for (int k = i - 1; k &lt; i + 2; k++)\n {\n for (int l = j - 1; l &lt; j + 2; l++)\n</code></pre>\n\n<p>You could name variables:</p>\n\n<ul>\n<li>i to row</li>\n<li>j to col</li>\n<li>k to i</li>\n<li>l to j</li>\n</ul>\n\n<hr>\n\n<p>You <strike>shouldn't</strike> <strong>mustn't</strong> use exceptions for normal events, for example reaching the edge of the screen.</p>\n\n<pre><code>catch (Exception e) { neighbours += 0; }\n</code></pre>\n\n<p>Instead don't cause an exception, for example:</p>\n\n<pre><code>for (int k = i - 1; k &lt; i + 2; k++)\n{\n if ((k &lt; 0) || (k == rows))\n {\n // beyond edge of screen: not a neighbour\n continue;\n }\n</code></pre>\n\n<hr>\n\n<p>Apart from that it's clean, neat, understandable.</p>\n\n<p>There are vertical empty/whitespace lines you should remove.</p>\n\n<p>The string value \"Start\" exists in more than one method (could be defined as a constant or variable in one place, e.g. in case you want to load it from a multi-lingual resource file).</p>\n\n<p>I was surprised to see you call Stop and Start in your timer1_Tick method: normally a method like that will leave the timer ticking. Perhaps you do it because NexGen takes a long time, so you want to reset the timer in order to see the change before the next tick.</p>\n\n<p>A comment which describes the algorithm being implemented (e.g. a modified version of <a href=\"http://en.wikipedia.org/wiki/Conway&#39;s_Game_of_Life#Rules\" rel=\"nofollow noreferrer\">Conway's Game of Life Rules</a>) could help someone else in the future who needed to maintain your software. They can read the software to see what it does; comments help them know what it's supposed to do (for example in case it's not doing what it's supposed to be doing).</p>\n\n<hr>\n\n<p>It might be a an idea call <a href=\"https://codereview.stackexchange.com/questions/39579/testing-whether-characters-of-a-string-are-unique\">Refresh</a> together with <a href=\"https://stackoverflow.com/a/487757/49942\">SuspendDrawing and ResumeDrawing</a> in your UpdateGrid method. Changing Button instances (causing them to repaint) might (I don't know) be expensive).</p>\n\n<hr>\n\n<p>You mentioned \"MVP\": does that mean <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"nofollow noreferrer\">Model–view–presenter</a>?</p>\n\n<p>If so I'm not seeing the MVP pattern in your code: instead you have one class, with UI events tied to data-state events.</p>\n\n<p>For example, how would you change this (and how much would you need to change) if you wanted to implement Console and WPF versions of this program, as well as the Windows Forms version?</p>\n\n<hr>\n\n<blockquote>\n <p>MVP stands for Minimum Viable Product. It's lean startup talk meaning. Something that works with the bare minimum of features and design.</p>\n</blockquote>\n\n<p>In that case, I suggest the following Minimum changes.</p>\n\n<p>Replace this statement ...</p>\n\n<pre><code>string[, ,] cellGrid = new string[columns, rows, depth]\n</code></pre>\n\n<p>... with ...</p>\n\n<pre><code>Tuple&lt;bool,int&gt;[,] cellGrid = new Tuple&lt;bool,int&gt;[columns, rows];\n</code></pre>\n\n<p>That gives you type-safety: use a bool instead of \"Alive\" and \"Dead\", and integer expessions instead of expressions like <code>neighbours.ToString()</code> and <code>Convert.ToInt32(cellGrid[xIndex, yIndex, 1])</code>.</p>\n\n<p>Replace this statement ...</p>\n\n<pre><code>for (int k = i - 1; k &lt; i + 2; k++)\n</code></pre>\n\n<p>... with ...</p>\n\n<pre><code>for (int k = Math.Max(i - 1, 0); k &lt; Math.Min(i + 2, rows); k++)\n</code></pre>\n\n<p>... and a corresponding change to your <code>l</code> range. Throwing 50 exceptions per calculation is horrendous in my opinion; however I must admit that <a href=\"https://stackoverflow.com/a/161965/49942\">they're not as bad as I thought they were</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T04:54:36.857", "Id": "67326", "Score": "0", "body": "Thanks for all the feedback. MVP stands for Minimum Viable Product. It's lean startup talk meaning. Something that works with the bare minimum of features and design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:16:19.653", "Id": "67343", "Score": "1", "body": "Why did you mark the members of `CellState` as `internal`? If the whole class is already `internal` (which is the default), I think it makes sense to make the members `public`. That way, if you decide to make the class `public` later on, you don't need to change all the members." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:27:17.890", "Id": "67348", "Score": "0", "body": "@svick I think the default accessibility for classes (i.e. for the name of the class) is internal, but the default accessibility for the class's members (methods, properties, and fields) is private. I made CellState properties and constructor internal so that they would be visible to the Form1 class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:29:48.310", "Id": "67349", "Score": "0", "body": "@ChrisW Yes, what I was trying to say is that you should have made the members `public` instead. It would still behave the same now, and it would be more future-proof." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:49:34.853", "Id": "67350", "Score": "0", "body": "@svick You are right. I'm in the habit of defining everything, where they're not private or protected, as internal. So usually, for me, public is a signal that it's a method which implements some underlying `interface`. If I needed to justify that, I'd say it's to communicate (to other programmers) the programmer's intent: a public method in an internal class looks strange (\"why did he declare it public when the class is internal?\")." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:09:43.230", "Id": "40069", "ParentId": "40059", "Score": "11" } }, { "body": "<p>I am known for a bit of the ole' over engineering but in the interest of separation of concerns I would be inclined to distill the project into it's core elements.</p>\n\n<p>e.g</p>\n\n<pre><code>internal interface GameOfLifeRenderer\n{\n GameOfLife GameOfLife { set; }\n\n int CellWidth { get; }\n int CellHeight { get; }\n\n void HighlightCell(int x, int y);\n void DeHighlightCell(int x, int y);\n\n void Initialize();\n void Update();\n\n}\n\ninternal interface GameOfLife\n{\n int Columns { get; }\n int Rows { get; }\n\n void Initialize();\n void Update();\n GridCell GetCell(int x, int y);\n}\n\ninternal interface GridCell\n{\n Boolean Alive { get; set; }\n GridCell[] GetNeighbours();\n\n}\n</code></pre>\n\n<p>With that in mind, you could easily have the Form be your View/Renderer and create a presenter to hold it and the GameOfLife object. </p>\n\n<p>Then you would have a nice clean number of decoupled calls, if you then decide down the line to build a non-winform renderer or even just a different render such as a custom graphics object. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:52:59.637", "Id": "67487", "Score": "0", "body": "Why interfaces instead of classes? Why is HighlightCell a method of Renderer not of Game? Why GetNeighbours instead of CountLiveNeighbours? Where do you store the 'temporary' neighbour count or the pending Alive value, and implement the game rules?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:56:18.890", "Id": "67488", "Score": "0", "body": "@ChrisW I just did I high level overview, not the full implementation. There would of course be a backing class file behind each of these.\n\nThe point of the interfaces is to show only the information that should be public. The actual implementation such as temporary values and calculations should not be exposed in case they change" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:59:58.117", "Id": "67489", "Score": "0", "body": "So GameOfLife is more like GridCellArray, containing GridCell instances but no rules? What do Initialize and Update do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:04:17.093", "Id": "67490", "Score": "0", "body": "@ChrisW\n\nHighlightCell is a rendering task. So it goes in the renderer. Game on the other hand probably should have a SelectCell function.\n\nIf you are interesed, When I get home from work I could put together a full implementation, although I'll post it as a secondary question so the other fine fellows here can correct my implementation as the question is slightly different from yours. \n\nYours was in respect to a minimalist solution while what I outlined above is a more over-engineered extensible solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:09:48.947", "Id": "67491", "Score": "0", "body": "@ChrisW the idea is to think of what is the simplest thing each part needs to know? renderer doesn't need to know rules, rules and gridSquare don't need to know how it will be displayed.\n\nOnce you have separated out each section you can theoretically swap them out. for example you could have a GameOfLifeStandardRuleSet,GameOfLifeZombieRuleSet etc and it will still be able to display the same regardless, or have a \n\nGameOfLifeWinformRenderer,GameOfLifeWPFRenderer,GameOfLifeConsoleRenderer etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:21:49.437", "Id": "67494", "Score": "0", "body": "*I am not the author of the question.* Given the terms of the question (i.e. \"MVP\"), it would be neat to see a better-engineered version of the code in the OP, which wraps/rearranges the existing lines of code in a minimum of new lines of code (ideally no new lines of code, just new class and method declarations/signatures). My worry/query about this answer was that you might have posted an answer which only said, \"I like to over-engineer by defining interfaces\", AND more worryingly that the interfaces which you posted weren't well thought-out / practicable." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T12:39:47.100", "Id": "40148", "ParentId": "40059", "Score": "3" } }, { "body": "<p>Here's a take on it, that merely does some cleanup of the existing code.</p>\n\n<p>Beyond the changes shown below, I would also highly recommend separating the UI logic from the game logic.</p>\n\n<p>One error I found:</p>\n\n<pre><code>cell.Margin.All.Equals(0); // Margins\n</code></pre>\n\n<p>doesn't do anything at all. What I think you mean is:</p>\n\n<pre><code>var margin = cell.Margin;\nmargin.All = 0;\ncell.Margin = margin;\n</code></pre>\n\n<p>So, without further ado:</p>\n\n<pre><code>namespace Life\n{\n using System;\n using System.Drawing;\n using System.Globalization;\n using System.Windows.Forms;\n\n /// &lt;summary&gt;\n /// The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:\n /// Any live cell with fewer than two live neighbours dies, as if caused by under-population.\n /// Any live cell with two or three live neighbours lives on to the next generation.\n /// Any live cell with more than three live neighbours dies, as if by overcrowding.\n /// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n /// The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations.\n /// &lt;/summary&gt;\n public partial class Form1 : Form\n {\n //// Some parameters to use throughout the program\n //// I'll basically use an array to store data and buttons to represent the cells\n\n private const string Dead = \"Dead\";\n\n private const string Alive = \"Alive\";\n\n /// &lt;summary&gt;\n /// Columns the Grid will have\n /// &lt;/summary&gt;\n private const int Columns = 30;\n\n /// &lt;summary&gt;\n /// Rows the Grid will have\n /// &lt;/summary&gt;\n private const int Rows = 20;\n\n /// &lt;summary&gt;\n /// Depth of the Grid\n /// &lt;/summary&gt;\n private const int Depth = 2;\n\n private const int DeadOrAliveIndex = 0;\n\n private const int NeighborCountIndex = 1;\n\n /// &lt;summary&gt;\n /// With of the cells which will also be used to determine positions\n /// &lt;/summary&gt;\n private const int CellWidth = 20;\n\n /// &lt;summary&gt;\n /// Height of the cells which will also be used to determine position\n /// &lt;/summary&gt;\n private const int CellHeight = 20;\n\n /// &lt;summary&gt;\n /// This is the array that will hold the cell's information\n /// &lt;/summary&gt;\n private readonly string[,,] cellGrid = new string[Columns, Rows, Depth];\n\n /// &lt;summary&gt;\n /// A panel where the cells will be laid out\n /// &lt;/summary&gt;\n private readonly Panel panel1 = new Panel();\n\n public Form1()\n {\n this.InitializeComponent();\n }\n\n // Upon Loading the Form\n // Add the Panel and Populate with the cells\n public void Form1_Load(object sender, EventArgs e)\n {\n this.Controls.Add(this.panel1);\n this.panel1.Location = new Point(0, 0);\n this.panel1.Size = new Size(CellWidth * Columns, CellHeight * Rows);\n this.panel1.Visible = true;\n\n for (var row = 0; row &lt; Rows; row++)\n {\n for (var column = 0; column &lt; Columns; column++)\n {\n var cell = new Button();\n\n this.cellGrid[column, row, DeadOrAliveIndex] = Dead;\n cell.Location = new Point(CellWidth * column, CellHeight * row);\n cell.Size = new Size(CellWidth, CellHeight);\n cell.Click += this.ButtonClick;\n cell.FlatStyle = FlatStyle.Flat;\n var margin = cell.Margin;\n margin.All = 0;\n cell.Margin = margin;\n cell.BackColor = Color.White;\n this.panel1.Controls.Add(cell);\n }\n }\n }\n\n // When clicking on a cell it will switch between being alive and dead\n private void ButtonClick(object sender, EventArgs e)\n {\n var thisButton = sender as Button;\n\n if (thisButton == null)\n {\n return;\n }\n\n // Get the index in cellGrid using the cell's position\n var row = thisButton.Location.Y / CellHeight;\n var column = thisButton.Location.X / CellWidth;\n\n\n // If the BackColor is white, it means it's dead so\n var isDead = thisButton.BackColor == Color.White;\n\n thisButton.BackColor = isDead ? Color.Black : Color.White;\n this.cellGrid[column, row, DeadOrAliveIndex] = isDead ? Alive : Dead;\n }\n\n // This will determine how many Neighbours or live cells each space has\n private void Neighbours()\n {\n for (var row = 0; row &lt; Rows; row++)\n {\n for (var column = 0; column &lt; Columns; column++)\n {\n var neighbours = 0;\n\n for (var i = row - 1; i &lt; row + 2; i++)\n {\n if (i &lt; 0 || i &gt;= Rows)\n {\n continue;\n }\n\n for (var j = column - 1; j &lt; column + 2; j++)\n {\n if (j &lt; 0 || j &gt;= Columns)\n {\n continue;\n }\n\n if (this.cellGrid[j, i, DeadOrAliveIndex] == Alive)\n {\n neighbours++;\n }\n }\n }\n\n this.cellGrid[column, row, NeighborCountIndex] = neighbours.ToString(CultureInfo.InvariantCulture);\n }\n }\n }\n\n\n // Switches the grid to the next generation killing and reviving cells following the rules.\n public void UpdateGrid()\n {\n foreach (Control cell in this.panel1.Controls)\n {\n var row = cell.Top / CellHeight;\n var column = cell.Left / CellWidth;\n var neighbours = Convert.ToInt32(this.cellGrid[column, row, NeighborCountIndex]);\n\n if (neighbours &lt; 2 || neighbours &gt; 3)\n {\n this.cellGrid[column, row, DeadOrAliveIndex] = Dead;\n cell.BackColor = Color.White;\n }\n else if (neighbours == 3)\n {\n this.cellGrid[column, row, DeadOrAliveIndex] = Alive;\n cell.BackColor = Color.Black;\n }\n }\n }\n\n // Each generation that passes updates the grid following the rules\n public void NextGen()\n {\n this.Neighbours();\n this.UpdateGrid();\n }\n\n // Each tick of the timer will be a generation\n private void timer1_Tick(object sender, EventArgs e)\n {\n this.timer1.Stop();\n this.NextGen();\n this.timer1.Start();\n }\n\n // When pressing the Start button, generations will start passing automatically\n private void StartBtn_Click(object sender, EventArgs e)\n {\n if (this.StartBtn.Text == \"Start\" || this.StartBtn.Text == \"Resume\")\n {\n this.timer1.Start();\n this.StartBtn.Text = \"Pause\";\n }\n else\n {\n this.timer1.Stop();\n this.StartBtn.Text = \"Resume\";\n }\n }\n\n // Pressing Reset, resets the grid\n private void ResetBttn_Click(object sender, EventArgs e)\n {\n this.timer1.Stop();\n this.StartBtn.Text = \"Start\";\n\n // Kill all cells\n for (var row = 0; row &lt; Rows; row++)\n {\n for (var column = 0; column &lt; Columns; column++)\n {\n this.cellGrid[column, row, DeadOrAliveIndex] = Dead;\n }\n }\n\n this.NextGen(); // Makes one generation go by\n }\n\n // You can pass generations manually by pressing Next Gen Button\n private void NextGenBttn_Click(object sender, EventArgs e)\n {\n this.NextGen(); // Hace que transcurra una generación\n }\n\n // Control how many generations in each second by changing the value\n private void GenXSec_ValueChanged(object sender, EventArgs e)\n {\n this.timer1.Interval = Convert.ToInt32(1000 / this.GenXSec.Value);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:05:48.380", "Id": "40217", "ParentId": "40059", "Score": "3" } }, { "body": "<p>Going for short'n'sweet, below is my effort (it absolutely won't win any prizes for performance!). <code>syb0rg</code> has suggested I add a few words regarding how I think this is an improvement. Here goes:</p>\n\n<ul>\n<li><p>Just using 2D integer arrays is representationally lighter.</p></li>\n<li><p>I use abstraction (<code>Rg</code>, <code>Sum</code>, <code>Do</code> over actions, etc.) to factor\nout common patterns.</p></li>\n<li><p>I use collections of short functions to do what I want; each function\nshould be easy to understand by itself.</p></li>\n<li><p>By going for brevity, I think I have improved the clarity of the code.</p></li>\n</ul>\n\n<p>-</p>\n\n<pre><code>void Main()\n{\n var rows = 10; // Including a 1-cell border o'death.\n var cols = 10;\n var rnd = new Random();\n var cell = new int[rows, cols];\n Do(cell, rows, cols, (r, c) =&gt; { cell[r, c] = (int)Math.Round(rnd.NextDouble()); });\n while (true) {\n WriteCells(cell, rows, cols);\n Console.WriteLine(\"--------\");\n Console.ReadLine();\n cell = Gen(cell, rows, cols);\n }\n}\n\nstatic IEnumerable&lt;int&gt; Rg = Enumerable.Range(-1, 3);\n\nstatic int Nbrs(int[,] cell, int r, int c) {\n return Rg.Sum(dr =&gt; Rg.Sum(dc =&gt; cell[r + dr, c + dc]));\n}\n\nstatic int Next(int[,] cell, int r, int c) {\n var nbrs = Nbrs(cell, r, c) - cell[r, c];\n return (cell[r, c] == 0 &amp;&amp; nbrs == 3 || cell[r, c] == 1 &amp;&amp; (nbrs == 2 || nbrs == 3)) ? 1 : 0;\n}\n\nstatic void Do(int[,] cell, int rows, int cols, Action&lt;int, int&gt; a) {\n for (var r = 1; r &lt; rows - 1; r++) {\n for (var c = 1; c &lt; cols - 1; c++) {\n a(r, c);\n }\n }\n}\n\nstatic int[,] Gen(int[,] cell, int rows, int cols) {\n var nxt = new int[rows, cols];\n Do(cell, rows, cols, (r, c) =&gt; { nxt[r, c] = Next(cell, r, c); });\n return nxt;\n}\n\nstatic void WriteCells(int[,] cell, int rows, int cols) {\n Do(cell, rows, cols, (r, c) =&gt; {\n Console.Write(cell[r, c] == 0 ? ' ' : '*');\n if (c == cols - 2) Console.WriteLine();\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T02:40:23.207", "Id": "68856", "Score": "0", "body": "@syb0rg, fair enough. Sometimes short code can speak for itself; here I have tried to demonstrate clarity and brevity by omitting unnecessary fluff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:18:20.847", "Id": "68866", "Score": "0", "body": "@syb0rg, Righto: my representation is lighter and, through abstraction (`Rg`, `Sum`, `Do` over actions), my code is shorter, more regular, and hence more comprehensible. I've completely skipped the usual OO chaff (classes, interfaces, inheritance, design patterns...) because it really doesn't help solve the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T03:45:37.397", "Id": "68879", "Score": "0", "body": "Here ya go! Vote reversed! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T02:24:17.000", "Id": "40817", "ParentId": "40059", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T22:13:46.953", "Id": "40059", "Score": "11", "Tags": [ "c#", "beginner", "game-of-life" ], "Title": "Minimal Game of Life in C#" }
40059
<p>As part of a fun project to help build my knowledge of PHP. I've written a Data Access Class here to bridge the site to the database. I know there are a lot of posts and articles out there explaining this type of thing, but I needed some individual feedback from people.</p> <p>It does work, but I'm open to all sorts of responses! I'm torn between which format to work with, but I've been following Zend's code formatting documents. If you're familiar with that, I'd love to hear where my code is wrong there.</p> <p>Any speed issues I'd gladly hear. I'm also open to code recycling tips.</p> <pre><code>class DataBase { /** * @var null|\PDO */ private $_connection = NULL; /** * @var string */ private $_databaseHost = 'localhost'; /** * @var string */ private $_databaseUser = 'root'; /** * @var string */ private $_databasePassword = ''; /** * @var string */ private $_returnMethod = 0; const DECIDE_RETURN_METHOD = 0; const ASSOC_ARRAY_RETURN_METHOD = 1; const LAST_ID_RETURN_METHOD = 2; const BOOLEAN_RETURN_METHOD = 3; /** * Construct a Database object. Use this to query the database(s). * * @param string $database The database to start a MySQL connection with. * @param string $host The host the connection will be with. * @param string $username The username the connection will be with. * @param string $password The password the connection will be with. * * @throws Exception If the database could not be connected to. */ public function __construct($database, $host = 'localhost', $username = 'root', $password = '') { $this-&gt;_databaseHost = $host; $this-&gt;_databaseUser = $username; $this-&gt;_databasePassword = $password; try { $dsn = 'mysql:dbname=' .$database. ';host=' .$this-&gt;_databaseHost; $this-&gt;_connection = new PDO($dsn, $this-&gt;_databaseUser, $this-&gt;_databasePassword,array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION)); } catch (PDOException $error) { throw new Exception('Could not connect to ' .$database. '.&lt;br&gt;' .$error-&gt;getMessage()); } } /** * Execute a string of SQL to the database. * * @param string $sql The SQL to be executed. * @param array|null $data Optional data to be prepared for the SQL staement. * @param int $return Use DECIDE_RETURN_METHOD if you're using a common sql statement, and it will choose what it thinks is the * best return method. Or choose ASSOC_ARRAY_RETURN_METHOD for an associative array to be returned, BOOLEAN_RETURN_METHOD for a boolean, * or LAST_ID_RETURN_METHOD for the last inserted ID. If the last method is used, you may specify $data['lastInsertId'] to give * a value for lastInsertId(). * * @return mixed Corresponds to the parameter: $return. */ public function PerformDBQuery($sql, array $data = NULL, $return=self::DECIDE_RETURN_METHOD) { if ($return == 0) { if (stripos($sql, 'select') &gt; -1) { $this-&gt;_returnMethod = self::ASSOC_ARRAY_RETURN_METHOD; } elseif (stripos($sql, 'insert') &gt; -1 || stripos($sql, 'update') &gt; -1 || stripos($sql, 'delete') &gt; -1) { $this-&gt;_returnMethod = self::BOOLEAN_RETURN_METHOD; } } elseif ($return &gt; 0 &amp;&amp; $return &lt; 4) { $this-&gt;_returnMethod = $return; } return $this-&gt;query_db($sql, $data); } /** * Execute a string of SQL to the database. * * @param string $sql The SQL to be executed. * @param array|null $data Optional data to be prepared for the SQL staement. * * @throws Exception If the sql statement is not a minimum 10 character string. * @throws Exception If the database is not connected. * * @return mixed Corresponds to $this-&gt;_returnMethod. */ private function query_db($sql, array $data) { if (is_string($sql) &amp;&amp; isset($sql[9])) { if (!is_null($this-&gt;_connection)) { try { if (is_null($data)) { $statement = $this-&gt;_connection-&gt;query($sql); } else { $statement = $this-&gt;_connection-&gt;prepare($sql); $statement-&gt;execute($data); } if ($this-&gt;_returnMethod == 1) { return $statement-&gt;fetchAll(PDO::FETCH_ASSOC); } elseif ($this-&gt;_returnMethod == 2) { if (isset($data['lastInsertId'])) { $column = $data['lastInsertId']; } else { $column = NULL; } return $this-&gt;_connection-&gt;lastInsertId($column); } elseif ($this-&gt;_returnMethod == 3) { return TRUE; } } catch (PDOException $error) { if ($this-&gt;_returnMethod == 1 || $this-&gt;_returnMethod == 2) { return NULL; } elseif ($this-&gt;_returnMethod == 3) { return FALSE; } } } else { throw new Exception('Database connection not available.'); return FALSE; } } else { throw new Exception('Invalid SQL string.'); return FALSE; } } } </code></pre> <p>If it's possible, I'd like an opinion on how to organize errors and exceptions! </p> <ul> <li>Do I throw errors in this class? </li> <li>Should I use Exceptions, or should I <code>return</code> the error message from the class? </li> </ul> <p>I have yet to find an article explaining standards for error handling in this situation. I've been researching when to use <code>self::</code> and <code>$this-&gt;</code> and I'd like to know if I'm using those right.</p>
[]
[ { "body": "<p>Just a few random notes:</p>\n\n<ol>\n<li><p>Correct me if I'm wrong but if you throw an exception the statements after the <code>throw</code> statements won't be run. So here <code>return FALSE</code> never runs, therefore it's unnecessary:</p>\n\n<pre><code>throw new Exception('Database connection not available.');\nreturn FALSE;\n</code></pre></li>\n<li><p>The <code>query_db</code> function could use guard clauses to make the code flatten:</p>\n\n<pre><code>private function query_db($sql, array $data) {\n if (!is_string($sql) || !isset($sql[9])) {\n throw new Exception('Invalid SQL string.');\n }\n if (is_null($this-&gt;_connection)) {\n throw new Exception('Database connection not available.');\n }\n try {\n ...\n}\n</code></pre>\n\n<p>References: </p>\n\n<ul>\n<li><em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; </li>\n<li><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">Flattening Arrow Code</a></li>\n</ul></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:14:12.530", "Id": "67303", "Score": "1", "body": "Thank you for both of those. I didn't realize `throw`s would do that! I originally had this class with guard clauses, but when I re-coded to update it, I took them out for some reason. Thanks for putting me back on track!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T23:48:00.367", "Id": "40066", "ParentId": "40061", "Score": "5" } }, { "body": "<blockquote>\n <p>I've been researching when to use self:: and $this-> and I'd like to\n know if I'm using those right.</p>\n</blockquote>\n\n<p>self:: is for referencing static variables, etc\n$this-> is for dynamic variables</p>\n\n<p>Eg your constants are static so</p>\n\n<pre><code>self::ASSOC_ARRAY_RETURN_METHOD is correct\n</code></pre>\n\n<p>Whereas calling a method from within the object itself (once it has been instantiated)</p>\n\n<pre><code>$this-&gt;PerformDBQuery(...\n</code></pre>\n\n<p>I have made some changes to your code, see inline comments</p>\n\n<pre><code>&lt;?php\n\nclass DataBase\n{\n /**\n * @var null|\\PDO\n */\n// private $_connection = NULL;\n// /**\n// * @var string\n// */\n// private $_databaseHost = 'localhost';\n// /**\n// * @var string\n// */\n// private $_databaseUser = 'root';\n// /**\n// * @var string\n// */\n// private $_databasePassword = '';\n\n\n // why is this declared as a string in the php docs ???\n /**\n * @var string\n */\n private $_returnMethod = 0;\n\n\n // maybe a better name would be AUTO_DETECT_RETURN_METHOD\n const DECIDE_RETURN_METHOD = 0;\n\n const ASSOC_ARRAY_RETURN_METHOD = 1;\n const LAST_ID_RETURN_METHOD = 2;\n const BOOLEAN_RETURN_METHOD = 3;\n\n /**\n * Construct a Database object. Use this to query the database(s).\n *\n * @param string $database The database to start a MySQL connection with.\n * @param string $host The host the connection will be with.\n * @param string $username The username the connection will be with.\n * @param string $password The password the connection will be with.\n *\n * @throws Exception If the database could not be connected to.\n */\n\n // Use of default username of root and password of blank should be discouraged\n// public function __construct($database, $host = 'localhost', $username = 'root', $password = '')\n public function __construct($database, $host = 'localhost', $username, $password)\n {\n\n // you have no re-connect function, so why store host/user/pass, storing the connection is sufficient\n // unless you have more advanced plans in mind for this class\n // $this-&gt;_databaseHost = $host;\n // $this-&gt;_databaseUser = $username;\n // $this-&gt;_databasePassword = $password;\n\n try {\n // use local use\n // $dsn = 'mysql:dbname=' . $database . ';host=' . $this-&gt;_databaseHost;\n $dsn = 'mysql:dbname=' . $database . ';host=' . $host;\n\n // $this-&gt;_connection = new PDO($dsn, $this-&gt;_databaseUser, $this-&gt;_databasePassword, array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION));\n $this-&gt;_connection = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION));\n\n } catch (PDOException $error) {\n throw new Exception('Could not connect to ' . $database . '.&lt;br&gt;' . $error-&gt;getMessage());\n }\n }\n\n /**\n * Execute a string of SQL to the database.\n *\n * @param string $sql The SQL to be executed.\n * @param array|null $data Optional data to be prepared for the SQL staement.\n * @param int $return Use DECIDE_RETURN_METHOD if you're using a common sql statement, and it will choose what it thinks is the\n * best return method. Or choose ASSOC_ARRAY_RETURN_METHOD for an associative array to be returned, BOOLEAN_RETURN_METHOD for a boolean,\n * or LAST_ID_RETURN_METHOD for the last inserted ID. If the last method is used, you may specify $data['lastInsertId'] to give\n * a value for lastInsertId().\n *\n * @return mixed Corresponds to the parameter: $return.\n */\n public function PerformDBQuery($sql, array $data = NULL, $return = self::DECIDE_RETURN_METHOD)\n {\n\n // you have declared constants, might as well use them it makes your code a lot more readable\n //if ($return == 0) {\n if ($return == self::DECIDE_RETURN_METHOD) {\n\n // according to php docs, recommended way of testing stripos matches is !== FALSE\n // if (stripos($sql, 'select') &gt; -1) {\n if (stripos($sql, 'select') !== FALSE) {\n $this-&gt;_returnMethod = self::ASSOC_ARRAY_RETURN_METHOD;\n } elseif (stripos($sql, 'insert') &gt; -1 || stripos($sql, 'update') &gt; -1 || stripos($sql, 'delete') &gt; -1) {\n $this-&gt;_returnMethod = self::BOOLEAN_RETURN_METHOD;\n }\n\n // here is another way of checking the statement type, that is a little easier to read (in my opinion)\n $stmt_type = strtolower(substr($sql, 0, 6));\n\n if ($stmt_type == 'select') {\n $this-&gt;_returnMethod = self::ASSOC_ARRAY_RETURN_METHOD;\n } elseif ($stmt_type == 'insert' || $stmt_type == 'update' || $stmt_type == 'delete') {\n $this-&gt;_returnMethod = self::BOOLEAN_RETURN_METHOD;\n } else {\n // hang on, what if the statement isn't select/update/delete/insert\n // what returnMethod will you use\n // eg COMMIT and ROLLBACK are valid sql\n }\n\n // use your constants here too\n //} elseif ($return &gt; 0 &amp;&amp; $return &lt; 4) {\n } elseif (in_array($return, array(self::ASSOC_ARRAY_RETURN_METHOD, self::LAST_ID_RETURN_METHOD, self::BOOLEAN_RETURN_METHOD ))) {\n $this-&gt;_returnMethod = $return;\n } else {\n // else??? what is the default\n // or should we throw an exception here?\n }\n\n // not sure why we are storing the return method as a property, it is a single use field (unless you have other plans in mind for this class)\n // why not just pass it as a parameter to the query_db method?\n\n return $this-&gt;query_db($sql, $data);\n }\n\n /**\n * Execute a string of SQL to the database.\n *\n * @param string $sql The SQL to be executed.\n * @param array|null $data Optional data to be prepared for the SQL staement.\n *\n * @throws Exception If the sql statement is not a minimum 10 character string.\n * @throws Exception If the database is not connected.\n *\n * @return mixed Corresponds to $this-&gt;_returnMethod.\n */\n private function query_db($sql, array $data)\n {\n\n // I am just implementing @palacsint recommendations here, as I am in agreement with them\n\n if (is_string($sql) &amp;&amp; isset($sql[9])) {\n throw new Exception('Invalid SQL string.');\n }\n\n if (!is_null($this-&gt;_connection)) {\n throw new Exception('Database connection not available.');\n }\n\n // i prefer to have 1 return statement per function if possible, for easier reading\n $ret = NULL;\n\n try {\n if (is_null($data)) {\n $statement = $this-&gt;_connection-&gt;query($sql);\n } else {\n $statement = $this-&gt;_connection-&gt;prepare($sql);\n $statement-&gt;execute($data);\n }\n\n // use the constants to help us understand your code\n // if ($this-&gt;_returnMethod == 1) {\n if ($this-&gt;_returnMethod == self::ASSOC_ARRAY_RETURN_METHOD) {\n $ret = $statement-&gt;fetchAll(PDO::FETCH_ASSOC);\n\n // use of constants again\n // } elseif ($this-&gt;_returnMethod == 2) {\n } elseif ($this-&gt;_returnMethod == self::LAST_ID_RETURN_METHOD) {\n if (isset($data['lastInsertId'])) {\n $column = $data['lastInsertId'];\n } else {\n $column = NULL;\n }\n $ret = $this-&gt;_connection-&gt;lastInsertId($column);\n// } elseif ($this-&gt;_returnMethod == 3) {\n } elseif ($this-&gt;_returnMethod == self::BOOLEAN_RETURN_METHOD) {\n $ret = TRUE;\n }\n\n\n\n } catch (PDOException $error) {\n\n // Is this the best way to handle pdo exceptions?\n // We are effectively masking the error and returning null\n // how will that be useful to the end user.\n // Perhaps we could store the error in a property call last_error_message or something like that\n // then the user could do\n //\n // if (!$dal-&gt;db_query($sql, $data)) {\n // echo $dal-&gt;last_error_message();\n // }\n\n // if ($this-&gt;_returnMethod == 1 || $this-&gt;_returnMethod == 2) {\n if ($this-&gt;_returnMethod == self::ASSOC_ARRAY_RETURN_METHOD || $this-&gt;_returnMethod == self::LAST_ID_RETURN_METHOD) {\n\n $ret = NULL;\n // } elseif ($this-&gt;_returnMethod == 3) {\n } elseif ($this-&gt;_returnMethod == self::BOOLEAN_RETURN_METHOD) {\n\n $ret = FALSE;\n }\n }\n\n return $ret;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:56:46.867", "Id": "40085", "ParentId": "40061", "Score": "2" } } ]
{ "AcceptedAnswerId": "40085", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T23:00:34.117", "Id": "40061", "Score": "7", "Tags": [ "php", "classes", "pdo", "formatting" ], "Title": "Specific PHP Data Access Class" }
40061
<p>I'm trying to come up with an alternative to the <code>gmean</code> implementation in <code>scipy</code>, because it is awkwardly slow. To that end I've been looking into alternate calculation methods and implementing them in <code>numpy</code>. My only issue is that a method that in the two methods I'm implementing, the one that I feel ought to be faster is in fact much slower. I feel like this is an issue with my implementation and would love advice on improving it.</p> <pre><code>def fast_gmean(vector, chunk_size=1000): base, exponent = np.frexp(vector) exponent_sum = float(np.sum(exponent)) while len(base) &gt; 1: base = np.array_split(base, math.ceil(float(base.size)/chunk_size)) intermediates = np.array([np.prod(split) for split in base]) base, current_exponent = np.frexp(intermediates) exponent_sum += np.sum(current_exponent) return (base[0]**(1.0/vector.size)) * (2**(exponent_sum/vector.size)) def actually_fast_gmean(vector): return np.exp(np.mean(np.log(vector))) </code></pre> <p>While these both outperform <code>scipy</code>'s gmean implementation, the second method is about 33% faster than the first.</p> <p>Note: I'm testing this on arrays of approximately 5000 entries.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T01:40:03.310", "Id": "67313", "Score": "2", "body": "Let's start with: why did you think the first method would be faster?" } ]
[ { "body": "<h3>1. Checking your claim</h3>\n\n<p>You claim that \"these both outperform <code>scipy</code>'s <code>gmean</code> implementation\", but I can't substantiate this. For example:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; import numpy\n&gt;&gt;&gt; data = numpy.random.exponential(size=5000)\n&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:fast_gmean(data), number=10000)\n5.540040018968284\n&gt;&gt;&gt; timeit(lambda:actually_fast_gmean(data), number=10000)\n1.4999530320055783\n&gt;&gt;&gt; from scipy.stats import gmean\n&gt;&gt;&gt; timeit(lambda:gmean(data), number=10000)\n1.4939542019274086\n</code></pre>\n\n<p>So as far as I can tell, there's no significant difference in runtime between your <code>actually_fast_gmean</code> and <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gmean.html\" rel=\"noreferrer\"><code>scipy.stats.gmean</code></a>, and your <code>fast_gmean</code> is more than 3 times slower.</p>\n\n<p>So I think you need to give us more information. What's the basis for your claim about performance? What kind of test data are you using?</p>\n\n<p>(Update: in comments it turned out that you were using <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.mstats.gmean.html\" rel=\"noreferrer\"><code>scipy.stats.mstats.gmean</code></a>, which is a version of <code>gmean</code> specialized for <em>masked arrays</em>.)</p>\n\n<h3>2. Read the source!</h3>\n\n<p>If you look at the <a href=\"https://github.com/scipy/scipy/blob/v0.13.0/scipy/stats/stats.py#L495\" rel=\"noreferrer\">source code for <code>scipy.stats.gmean</code></a>, you'll see that it's almost exactly the same as your <code>actually_fast_gmean</code>, except that it's more general (it takes <code>dtype</code> and <code>axis</code> arguments):</p>\n\n<pre><code>def gmean(a, axis=0, dtype=None):\n if not isinstance(a, np.ndarray): # if not an ndarray object attempt to convert it\n log_a = np.log(np.array(a, dtype=dtype))\n elif dtype: # Must change the default dtype allowing array type\n if isinstance(a,np.ma.MaskedArray):\n log_a = np.log(np.ma.asarray(a, dtype=dtype))\n else:\n log_a = np.log(np.asarray(a, dtype=dtype))\n else:\n log_a = np.log(a)\n return np.exp(log_a.mean(axis=axis))\n</code></pre>\n\n<p>So it's not surprising that these two functions have almost identical runtimes.</p>\n\n<h3>3. Why <code>fast_gmean</code> is slow</h3>\n\n<p>Your strategy is to avoid calls to <code>log</code> by performing arithmetic on the exponent and mantissa parts of the floating-point numbers.</p>\n\n<p>Very roughly speaking, for each element of the input, you avoid one call to each of <code>log</code> and <code>mean</code>, and gain one call to each of <code>frexp</code>, <code>sum</code>, <code>array_split</code> and <code>prod</code>.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; from numpy import log, mean, frexp, sum, array_split, prod\n&gt;&gt;&gt; for f in log, mean, frexp, sum, prod:\n... print(f.__name__, timeit(lambda:f(data), number=10000))\nlog 1.0724926821421832\nmean 0.3662677980028093\nfrexp 0.34479621006175876\nsum 0.21649421006441116\nprod 0.280590218026191\n&gt;&gt;&gt; timeit(lambda:array_split(data, 5), number=10000)\n2.1635821380186826\n</code></pre>\n\n<p>So it's the call to <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html#numpy.array_split\" rel=\"noreferrer\"><code>numpy.array_split</code></a> that's costly. You could avoid this call and split the array yourself, like this:</p>\n\n<pre><code>def fast_gmean2(vector, chunk_size=1000):\n base, exponent = np.frexp(vector)\n exponent_sum = np.sum(exponent)\n while base.size &gt; 1:\n intermediates = []\n for i in range(0, base.size, chunk_size):\n intermediates.append(np.prod(base[i:i + chunk_size]))\n base, current_exponent = np.frexp(np.array(intermediates))\n exponent_sum += np.sum(current_exponent)\n return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)\n</code></pre>\n\n<p>and this is roughly twice as fast as your version:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; timeit(lambda:fast_gmean2(data), number=10000)\n2.585187505930662\n</code></pre>\n\n<p>but still about twice as slow as <code>scipy.stats.gmean</code>, and that's because of the Python interpreter overhead. Numpy has a speed advantage whenever you can vectorize your operations so that they run on fixed-size datatypes in the Numpy core (which is implemented in C for speed). If you can't vectorize your operations, but have to loop over them in Python, then you pay a penalty.</p>\n\n<p>So let's vectorize that:</p>\n\n<pre><code>def fast_gmean3(vector, chunk_size=1000):\n base, exponent = np.frexp(vector)\n exponent_sum = np.sum(exponent)\n while len(base) &gt; chunk_size:\n base = np.r_[base, np.ones(-len(base) % chunk_size)]\n intermediates = base.reshape(chunk_size, -1).prod(axis=0)\n base, current_exponent = np.frexp(intermediates)\n exponent_sum += np.sum(current_exponent)\n if len(base) &gt; 1:\n base, current_exponent = np.frexp([base.prod()])\n exponent_sum += np.sum(current_exponent)\n return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)\n</code></pre>\n\n<p>For arrays of the size we've been testing (about 5000), this is a little slower than <code>fast_gmean2</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; timeit(lambda:fast_gmean3(data), number=10000)\n2.8020136120030656\n</code></pre>\n\n<p>But for larger arrays it beats <code>gmean</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; bigdata = np.random.exponential(size=1234567)\n&gt;&gt;&gt; timeit(lambda:gmean(bigdata), number=100)\n3.192410137009574\n&gt;&gt;&gt; timeit(lambda:fast_gmean3(bigdata), number=100)\n2.3945167789934203\n</code></pre>\n\n<p>So the fastest implementation depends on the length of the array.</p>\n\n<h3>4. Other comments on <code>fast_gmean</code></h3>\n\n<ol>\n<li><p>There's no docstring. What does this function do and how do I call it? What value should I pass in for the <code>chunk_size</code> argument?</p></li>\n<li><p>It's critical that <code>chunk_size</code> is not too large, otherwise the call to <code>prod</code> could underflow and the result will be incorrect. So there needs to be a check that the value is safe, and a comment explaining how you computed the safe range of values.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:03:48.827", "Id": "67545", "Score": "0", "body": "Fascinating, it looks like there are two different gmean functions in `scipy`. I was using the one at `scipy.stats.mstats.gmean`, which appears to be much slower than the other version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:06:00.903", "Id": "67547", "Score": "0", "body": "That's the version for use with [masked arrays](http://docs.scipy.org/doc/numpy/reference/maskedarray.html), that is, \"arrays that may have missing or invalid entries\". Naturally functions that operate on masked arrays are slower because they have to check each entry to see whether it is valid." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:11:56.910", "Id": "40163", "ParentId": "40067", "Score": "7" } } ]
{ "AcceptedAnswerId": "40163", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:06:02.613", "Id": "40067", "Score": "4", "Tags": [ "python", "numpy" ], "Title": "Optimizing numpy gmean calculation" }
40067
<p>I have a local database in <code>Windows Phone 8</code> app. The app includes a lot of queries to the database and I don't want bad effect on the responsiveness of UI.</p> <p>For example I have a table of users and method to get a user from database by id. </p> <p><strong>Current variant</strong></p> <pre><code>public class CacheDataContext : DataContext { public static string DBConnectionString = "Data Source=isostore:/Cache.sdf"; public CacheDataContext(string connectionString) : base(connectionString) { } public static AutoResetEvent OperationOnDatabaseUser = new AutoResetEvent(true); public Table&lt;User&gt; UserItems; } public class CacheDataContextUser : CacheDataContext { public CacheDataContextUser(string connectionString) : base(connectionString) { } public User GetUser(string id) { try { OperationOnDatabaseUser.WaitOne(); using (CacheDataContext context = new CacheDataContext(DBConnectionString)) { //find user in the data base and return } } finally { OperationOnDatabaseUser.Set(); } } } </code></pre> <p>I need ensure safety of the data if at the same time on database wallow different requests to add, modify, delete data. For this I use <code>AutoResetEvent</code>. Not sure what I'm doing it right, but so far no problems.</p> <p>I can get user from the database:</p> <pre><code>using (DataBaseUser = new CacheDataContextFriends(ConnectionString)) { var user = DataBaseUser.GetUser(id); } </code></pre> <p><strong>Async/await</strong></p> <p>But I want work with the database using keywords async/await.</p> <pre><code>public class CacheDataContextUser : CacheDataContext { public CacheDataContextUser(string connectionString) : base(connectionString) { } private object threadLock = new object(); public Task&lt;User&gt; GetUser(string id) { using (CacheDataContext context = new CacheDataContext(DBConnectionString)) { var result = await Task&lt;User&gt;.Factory.StartNew(() =&gt; { lock (threadLock) { //find user in the data base and return } }); return result; } } } </code></pre> <p>I'm afraid to rewrite the method as described above, because I'm not sure it's right. Please tell me what the problem may be. My main goal is to improve the responsiveness of the app.</p>
[]
[ { "body": "<p>Before even addressing the actual question, have you actually proven that database queries are harming your responsiveness? Since the queries are to local storage it's possible that they are fast enough to not require using asynchrony, particularly if they are simple queries or the database is small.</p>\n\n<p>Next, I notice you've assumed that the database itself is not threadsafe, i.e. that you must only allow access from one thread at a time. Are you sure that's actually true? Many (most?) database handle concurrency themselves, so you may be adding an unnecessary layer of synchronization. I looked around a bit, but could not find anything specifically documenting concurrent access to isolated storage databases. I would start by researching that, or possibly asking a question on StackOverflow. If the database does allow concurrent access then you just need to worry about update conflicts, which you could hopefully avoid in a single-user phone application. </p>\n\n<p>What I'm getting at here is that multi-threading and locking is <em>hard</em>. Don't do it unless you're sure you have a good reason to do it.</p>\n\n<p>If you really must to multi-threading, then the C# <code>lock</code> keyword is a good place to start. Unfortunately, your example probably will not work properly because each <code>CacheDataUserContext</code> instance will have it's own lock object - so if you create more than one instance they could conflict with each other. </p>\n\n<p>You \"Current Variant\" actually gets this more right, because your <code>AutoResetEvent</code> is a static variable, so there is only a single instance of it across the system. However, as I understand <code>DataContext</code> it lets you use Linq statements against the database, which will not know anything about your lock and hence will not be synchronized. </p>\n\n<p>I think you'd have to create a separate application layer to wrap the <code>DataContext</code> and expose just the certain operations that your application needs. This is generally called the \"Repository Pattern\". Inside the repository you could create a single lock object, wrap a <code>lock</code> around all accesses to a <code>DataContext</code>, and use <code>Task.Factory.StartNew</code> inside each of the repository methods to make them asynchronous. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T21:26:23.177", "Id": "70783", "Score": "0", "body": "Thank you for your answer! My database is not very big, but sometimes happens bad responsiveness. For example on the map when you need to select the users with the right coordinates. If very often scale the map, it may slow down. In general, I understand your ideas, thank you. By the way, why lock better than AutoResetEvent? I can use static lock object in CacheDataContext: protected static readonly object threadLock = new object();" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T14:58:06.700", "Id": "70957", "Score": "0", "body": "`lock` is simpler. It's also the language's default choice for mutual exclusion, so anyone reading the code will be able to tell what you're trying to do more easily." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T22:54:53.357", "Id": "40793", "ParentId": "40068", "Score": "3" } }, { "body": "<p>I faced similar issues, please have a try of my implementation: <a href=\"https://codereview.stackexchange.com/questions/49536/threadsafe-isostoragemanager/49853\">ThreadSafe IsoStorageManager</a></p>\n\n<p>I'm doing heavy testing right now, and current version seems to be quite stable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-17T16:33:33.527", "Id": "51007", "ParentId": "40068", "Score": "0" } } ]
{ "AcceptedAnswerId": "40793", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:06:14.343", "Id": "40068", "Score": "8", "Tags": [ "c#", "database", "thread-safety", "async-await", "windows-phone" ], "Title": "Using keywords async/await in database queries (Windows Phone 8)" }
40068
<p>Having so many loops running concurrently obviously can't be good, and the code seems overly complicated. There has to be a simpler, more efficient way to</p> <ol> <li>Turn the designMode of all iFrames on</li> <li>Find the three "buttons" ('a' link elements) - that when clicked affect its corresponding iFrame - depending on its className</li> <li>Put those "buttons" into a multidimensional array/object - i.e target.rtfID.x - for easy relationship - i.e "<em>this</em> bold button affects <em>this</em> iFrame</li> <li>Whenever a "button" is clicked, find its corresponding iFrame through the object and send the iFrame's id as an argument for another function.</li> </ol> <p></p> <pre><code> function richText(var1, var2) { document.getElementById(var1).addEventListener('click', function() { bold(var2); }, false); } function bold(target) { if (target != 0) { document.getElementById(target).contentDocument.execCommand('bold', false, null); document.getElementById(target).contentWindow.focus(); } else { document.getElementById('richTextField').contentDocument.execCommand('bold', false, null); document.getElementById('richTextField').contentWindow.focus(); } } function iFrameOn() { var rtfContainer, rtContainer, richTxt, richTxtId, rtf = document.querySelectorAll('div &gt; form &gt; iframe'), //Rich Text Field newPost = document.getElementById('richTextField').contentDocument.body, target = {}, rtfIndex = 0; //Turn iFrames On while (rtfIndex &lt; rtf.length) { rtfID = rtf[rtfIndex].id; if (rtf[rtfIndex].contentDocument.designMode != 'On') {rtf[rtfIndex].contentDocument.designMode = 'On';} newPost.innerHTML = "&lt;i style=\"color:#DDDDDD;\"&gt;What's up?&lt;/i&gt;"; newPost.addEventListener('blur', function() { if (newPost.innerHTML == '') {newPost.innerHTML = "&lt;i style=\"color:#DDDDDD;\"&gt;What's up?&lt;/i&gt;";} }, false); document.getElementById('richTextField').contentWindow.addEventListener('focus', function() { if (newPost.innerHTML == "&lt;i style=\"color:#DDDDDD;\"&gt;What's up?&lt;/i&gt;") {newPost.innerHTML = '';} }, false); rtContainer = rtf[rtfIndex].nextElementSibling; //Next Element Sibling should be a div console.log('rtContainer is: '+rtContainer); richTxt = rtContainer.childNodes; console.log('richTxt is: '+richTxt); for (var i = 0; i &lt; richTxt.length; i++) { if (richTxt[i].nodeType != 1 || (richTxt[i].nodeType == 1 &amp;&amp; (richTxt[i].className == 'submit_button sbmtPost' || richTxt[i].className == ""))) {continue;} richTxtId = richTxt[i].id; target.rtfID = {}; switch (richTxt[i].className) { case 'richText bold': if (target.rtfID.bold != richTxtId) { target.rtfID.bold = richTxtId; console.log(target.rtfID.bold+' is associated with: '+rtfID); richText(richTxtId, rtfID); } break; case 'richText underline': if (target.rtfID.underline != richTxtId) { target.rtfID.underline = richTxtId; console.log(target.rtfID.underline+' is associated with: '+rtfID); } break; case 'richText italic': if (target.rtfID.italic != richTxtId) { target.rtfID.italic = richTxtId; console.log(target.rtfID.italic+' is associated with: '+rtfID); document.getElementById(target.rtfID.italic).addEventListener('click', function() { richText(rtfID); }, false); } break; default: console.log('Error with commenting system!'); } } /*var obj = target.rtfID; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { console.log("prop: " + prop + " value: " + obj[prop]); switch(prop) { case 'bold': document.getElementById(obj[prop]).addEventListener('click', function() { richText(obj, prop); }, false); break; case 'underline': document.getElementById(obj[prop]).addEventListener('click', function() { Underline(obj[prop]); }, false); break; case 'italic': document.getElementById(obj[prop]).addEventListener('click', function() { richText(obj, prop); }, false); break; default: console.log('Error in for...in loop'); } } else {console.log('error');} }*/ rtfIndex++; } } </code></pre>
[]
[ { "body": "<p>There is a quite bit wrong with this code, the loops are possibly the least of it.</p>\n\n<ul>\n<li>A ton of commented out code and <code>console.log</code> statements, please clean this up</li>\n<li>Inconsistent indenting, you indent with 1, 4 or 0 spaces, pick one ( I suggest 2 )</li>\n<li>The underline button, it does not work</li>\n<li>The italics button, it does not work either</li>\n<li><code>if (rtf[rtfIndex].contentDocument.designMode != 'On') \n {rtf[rtfIndex].contentDocument.designMode = 'On';}</code><br>\ncan be replaced with<br>\n<code>rtf[rtfIndex].contentDocument.designMode = 'On';</code></li>\n<li><code>\"&lt;i style=\\\"color:#DDDDDD;\\\"&gt;What's up?&lt;/i&gt;\"</code> should be a constant</li>\n<li>This: <code>document.querySelectorAll('div &gt; form &gt; iframe')</code> seems awfully optimistic, are you sure that you will never use iframes for anything else? I would suggest you find a more reliable means to find the richtext iframes.</li>\n<li>I am not sure why you would want to put the buttons in an array, once you wire them you should no longer care about them</li>\n<li>You can link buttons and their corresponding iFrame through a closure: <a href=\"http://javascript-reference.info/javascript-closures-for-dummies.htm\" rel=\"nofollow\">http://javascript-reference.info/javascript-closures-for-dummies.htm</a>, which seems pretty much what the commented-outcode did.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T21:28:40.343", "Id": "67588", "Score": "0", "body": "The array was just to link the button to its iFrame. I saw no other way of doing this. The commented out code and console.log statements were for debugging purposes. The richtext iFrames will **always** be within a form element, which will always be within a div. I did it this way specifically so iFrames used in the usual manner would not be affected. As for the indents, that's how I do in my editor so my apologies for that. Thanks for your help, and I hope this all explains my reasoning for doing things certain ways." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:55:27.347", "Id": "40161", "ParentId": "40072", "Score": "2" } } ]
{ "AcceptedAnswerId": "40161", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T01:21:03.650", "Id": "40072", "Score": "6", "Tags": [ "javascript", "optimization", "performance", "html" ], "Title": "Rich Text on multiple iFrames" }
40072
<p>Can someone look over this? This is the entire authentication file. It's referenced at the beginning of all my catalog editing files to make sure only the specified user is logged in. I want to make sure it's secure.</p> <pre><code>&lt;?php // pageauth.php // Asks for a username and a password and checks it. if($_SESSION['logged_in'] != 1){ if(!isset($_SERVER['PHP_AUTH_USER'])){ header('WWW-Authenticate: Basic realm="Catalog Administration"'); header('HTTP/1.0 401 Unauthorized'); echo '&lt;h1&gt;Hey! You can\'t be here!&lt;/h1&gt; &lt;p&gt;Try logging in first!&lt;/p&gt;'; exit; }elseif(md5($_SERVER['PHP_AUTH_USER']) != "04b2f0a4ad7772ca864aa569917b2d2d"){ echo '&lt;h1&gt;Wrong Username!&lt;/h1&gt; &lt;p&gt;Only the admin username and password are accepted.&lt;/p&gt;'; exit; }elseif(md5($_SERVER['PHP_AUTH_PW']) != "ed972411dfcca5313ab151694af01da8"){ echo '&lt;h1&gt;Wrong Password!&lt;/h1&gt; &lt;p&gt;For obvious reasons, we need a correct password!&lt;/p&gt;'; exit; }else{ session_start(); $_SESSION['logged_in'] = 1; } } ?&gt; </code></pre> <p>I just need to authenticate for one user. I don't need to go into databases or anything, so I thought PHP_AUTH would be a good solution.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:17:55.287", "Id": "67318", "Score": "0", "body": "If you're using Basic authentication, you shouldn't need to deal with sessions; the browser will re-send whatever credentials it last used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:21:02.010", "Id": "67320", "Score": "0", "body": "Thanks! Other than that, anything else?" } ]
[ { "body": "<p>md5 usage may be okay on small projects, but it's generally considered weak and shouldn't be used. As of the MD5 wikipedia page:</p>\n\n<blockquote>\n <p>The security of the MD5 hash function is severely compromised.</p>\n</blockquote>\n\n<p>and <a href=\"http://us1.php.net/md5\" rel=\"nofollow noreferrer\">http://us1.php.net/md5</a></p>\n\n<blockquote>\n <p>It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm.</p>\n</blockquote>\n\n<p><strike>So perhaps you should look into PHP's other hashing methods, say <code>hash()</code> itself. You can read more here: <a href=\"http://us1.php.net/manual/en/function.hash.php\" rel=\"nofollow noreferrer\">http://us1.php.net/manual/en/function.hash.php</a></strike></p>\n\n<h3>Important Edit:</h3>\n\n<p>I read a little bit more and I am incorrect! The hash method is <em>okay</em>. It's not great like <strong>bcrypt</strong>! I highly suggest you read both of these and understand them, I'm sure it will come in handy later on! <a href=\"https://security.stackexchange.com/questions/17421/how-to-store-salt\">https://security.stackexchange.com/questions/17421/how-to-store-salt</a> and <a href=\"https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords\">https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords</a>. And directly relating to PHP, <a href=\"http://us1.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">http://us1.php.net/manual/en/function.password-hash.php</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T03:50:09.427", "Id": "67325", "Score": "0", "body": "Thanks for the feedback! I'll use `hash()` instead!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T06:26:48.703", "Id": "67895", "Score": "0", "body": "I have updated my answer, please read the edit!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T23:55:49.653", "Id": "68204", "Score": "0", "body": "Thanks for the update! I feel comfortable using `hash(SHA256,$password)`, but if I think I need more security (for something like an entire user system in a database) I'll look into bcrypt!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:44:17.107", "Id": "40074", "ParentId": "40073", "Score": "5" } }, { "body": "<p>Basic authentication is very basic. It is not really designed to allow responses, such as Wrong Username/Wrong Password.</p>\n\n<p>If a login attempt fails it will prompt you for the username/password again and again, (usually the browsers allow 3 attempts before failing)\nOnce the login fails you get 1 error message. This could be caused by wrong username/password from cancel option.</p>\n\n<p>If you want to show bad username/password messages I suggest you implement your own authentication form (which is not difficult).</p>\n\n<p>It is also not a good idea to show wrong username, and wrong password explicitly as once I guess the correct username, I will be able to tell from your response saying bad password only. Then i can work on cracking your password knowing I have the username correct.</p>\n\n<p>I have altered your code substantially and tried to explain why in the comments</p>\n\n<p>If you are using apache websserver, all of what you have done can also be achieved using a a simple .htaccess and .htpasswd file\nHere is a website that can generate those files for you\n<a href=\"http://www.htaccesstools.com/htpasswd-generator/\" rel=\"nofollow\">http://www.htaccesstools.com/htpasswd-generator/</a></p>\n\n<pre><code>&lt;?php\n// pageauth.php\n// Asks for a username and a password and checks it.\n\n// lets define username/password first, so it is easier to change later without digging through the code.\n$auth_hash_algorithm = \"sha256\";\n$user_hash = '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'; // admin\n$pass_hash = '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'; // password\n\n// If i run your code up under E_STRICT then i get a warning\n// Notice: Undefined variable: _SESSION in test.php\n// We should really start the session before we use it, not in the conditional logic below\n\nsession_start();\n\n// Next I get\n// Notice: Undefined index: logged_in in test.php\n// the first time through we should test the index logged_in exists before referencing it.\n// Assuming logged_in could only ever be set to 1, then we could just test to see if logged_in is not set, rather then != 1\n\n// if($_SESSION['logged_in'] != 1){\nif(!isset($_SESSION['logged_in'])){\n\n // First time through it prompts me for a user/name password\n // if i leave the username/password blank it says Wrong Username!\n // $_SERVER['PHP_AUTH_USER'] is now set to blank and i can't even attempt to login again unless i restart the browser\n // I am assuming it was not the intention to only allow 1 login attempt?\n\n $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;\n $pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;\n\n if (hash($auth_hash_algorithm, $user) == $user_hash &amp;&amp; hash($auth_hash_algorithm, $pass) == $pass_hash) {\n $_SESSION['logged_in'] = 1;\n } else {\n header('WWW-Authenticate: Basic realm=\"Catalog Administration\"');\n header('HTTP/1.0 401 Unauthorized');\n echo '&lt;h1&gt;Hey! You can\\'t be here!&lt;/h1&gt;\n &lt;p&gt;Try logging in first!&lt;/p&gt;';\n exit;\n }\n}\n\necho \"Success You must be logged in\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T20:29:58.697", "Id": "67419", "Score": "0", "body": "Thank you so much! This is an amazing improvement over my code!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T08:34:02.580", "Id": "40081", "ParentId": "40073", "Score": "3" } } ]
{ "AcceptedAnswerId": "40081", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T02:15:18.247", "Id": "40073", "Score": "5", "Tags": [ "php", "security", "authentication" ], "Title": "PHP Authentication Security" }
40073
<p>I am working on a project in which I need to have synchronous and asynchronous methods of my Java client. Some customer will call synchronously and some customer will call asynchronously, depending on their requirement.</p> <p>Here is my Java client which has <code>synchronous</code> and <code>asynchronous</code> methods:</p> <pre><code>public class TestingClient implements IClient { private ExecutorService service = Executors.newFixedThreadPool(10); private RestTemplate restTemplate = new RestTemplate(); // for synchronous @Override public String executeSync(ClientKey keys) { String response = null; try { Future&lt;String&gt; handle = executeAsync(keys); response = handle.get(keys.getTimeout(), TimeUnit.MILLISECONDS); } catch (TimeoutException e) { } catch (Exception e) { } return response; } // for asynchronous @Override public Future&lt;String&gt; executeAsync(ClientKey keys) { Future&lt;String&gt; future = null; try { ClientTask ClientTask = new ClientTask(keys, restTemplate); future = service.submit(ClientTask); } catch (Exception ex) { } return future; } } </code></pre> <p>Here is my <code>ClientTask</code> class, which implements the <code>Callable</code> interface. I am passing around the dependency using DI pattern in the <code>ClientTask class</code>. In the call method, I am just making a URL basis on <code>machineIPAddress</code> and using the <code>ClientKeys</code> which is passed to <code>ClientTask</code> class and then hit the server using <code>RestTemplate</code> and get the response back.</p> <pre><code>class ClientTask implements Callable&lt;String&gt; { private ClientKey cKeys; private RestTemplate restTemplate; public ClientTask(ClientKey cKeys, RestTemplate restTemplate) { this.restTemplate = restTemplate; this.cKeys = cKeys; } @Override public String call() throws Exception { // .. some code here String url = generateURL("machineIPAddress"); String response = restTemplate.getForObject(url, String.class); return response; } // is this method thread safe and the way I am using `cKeys` variable here is also thread safe? private String generateURL(final String hostIPAdress) throws Exception { StringBuffer url = new StringBuffer(); url.append("http://" + hostIPAdress + ":8087/user?user_id=" + cKeys.getUserId() + "&amp;client_id=" + cKeys.getClientId()); final Map&lt;String, String&gt; paramMap = cKeys.getParameterMap(); Set&lt;Entry&lt;String, String&gt;&gt; params = paramMap.entrySet(); for (Entry&lt;String, String&gt; e : params) { url.append("&amp;" + e.getKey()); url.append("=" + e.getValue()); } return url.toString(); } } </code></pre> <p>Here is my <code>ClientKey</code> class using the builder patter, which the customer will use to make the input parameters to pass to the <code>TestingClient</code>: </p> <pre><code>public final class ClientKey { private final long userId; private final int clientId; private final long timeout; private final boolean testFlag; private final Map&lt;String, String&gt; parameterMap; private ClientKey(Builder builder) { this.userId = builder.userId; this.clientId = builder.clientId; this.remoteFlag = builder.remoteFlag; this.testFlag = builder.testFlag; this.parameterMap = builder.parameterMap; this.timeout = builder.timeout; } public static class Builder { protected final long userId; protected final int clientId; protected long timeout = 200L; protected boolean remoteFlag = false; protected boolean testFlag = true; protected Map&lt;String, String&gt; parameterMap; public Builder(long userId, int clientId) { this.userId = userId; this.clientId = clientId; } public Builder parameterMap(Map&lt;String, String&gt; parameterMap) { this.parameterMap = parameterMap; return this; } public Builder remoteFlag(boolean remoteFlag) { this.remoteFlag = remoteFlag; return this; } public Builder testFlag(boolean testFlag) { this.testFlag = testFlag; return this; } public Builder addTimeout(long timeout) { this.timeout = timeout; return this; } public ClientKey build() { return new ClientKey(this); } } public long getUserId() { return userId; } public int getClientId() { return clientId; } public long getTimeout() { return timeout; } public Map&lt;String, String&gt; getParameterMap() { return parameterMap; } public boolean istestFlag() { return testFlag; } } </code></pre> <p>Is this thread-safe, as I am using <code>ClientKey</code> variables in <code>ClientTask</code> class in multithreaded environment so not sure what will happen if another thread tries to make <code>ClientKey</code> variable while making a call to <code>TestingClient</code> synchronous method? The customer will be making a call to us with the use of this code, and they can call us from their multithreaded application as well.</p> <pre><code>IClient testClient = ClientFactory.getInstance(); Map&lt;String, String&gt; testMap = new LinkedHashMap&lt;String, String&gt;(); testMap.put("hello", "world"); ClientKey keys = new ClientKey.Builder(12345L, 200).addTimeout(2000L).parameterMap(testMap).build(); String response = testClient.executeSync(keys); </code></pre> <p>I'm just trying to understand whether my above code will be thread-safe or not, as they can pass multiple values to my <code>TestingClient</code> class from multiple threads. I have a feeling that my <code>ClientKey</code> class is not thread-safe because of <code>parameterMap</code>, but I'm not sure.</p> <p>Also, do I need <code>StringBuffer</code> here, or will <code>StringBuilder</code> be fine as <code>StringBuilder</code> is faster than <code>StringBuffer</code>, and because it's not synchronized?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T11:42:07.353", "Id": "67691", "Score": "0", "body": "Although you found already a thread-safe solution, there are other ways to achieve thread-safty. A couple of days ago an [interesting question was asked at stackoverflow](http://stackoverflow.com/questions/21210870/in-java-can-you-use-the-builder-pattern-with-required-and-reassignable-fields/21211472) which basically returns a new Builder instance for each argument to set atomically and further provides compile-time checking of arguments. This approach should be thread-safe too." } ]
[ { "body": "<p>If I haven't missed anything then <code>ClientKey</code> should be thread safe. Once you have build the <code>ClientKey</code> object, the <code>parameterMap</code> is only ever read and never modified. </p>\n\n<p>However it relies on the fact that no malicious or buggy client isn't trying to modify in the meantime. Therefor I would consider changing the <code>ClientKey</code> object to protect against changes. Several options come to mind</p>\n\n<ol>\n<li><p>Change your <code>ClientKey</code> constructor so it creates a readonly map:</p>\n\n<pre><code>private ClientKey(Builder builder) {\n this.userId = builder.userId;\n this.clientId = builder.clientId;\n this.remoteFlag = builder.remoteFlag;\n this.testFlag = builder.testFlag;\n this.parameterMap = Collections.unmodifiableMap(builder.parameterMap);\n this.timeout = builder.timeout;\n} \n</code></pre>\n\n<p>This will prevent anyone from changing the map obtained via <code>getParameterMap</code>.</p></li>\n<li><p>Make your <code>ClientKey</code> class implement <code>Iterable&lt;Entry&lt;string, string&gt;&gt;</code> which allows iteration over the internal map rather than exposing the map through a get function.</p></li>\n<li><p>Return an <code>Iterable&lt;Entry&lt;string, string&gt;&gt;</code> from <code>getParameterMap</code> (and probably call it <code>getParameters</code> instead).</p></li>\n</ol>\n\n<p>I'd prefer 2 or 3 because it enforces the readonly-ness in a much stronger way.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Number 3 could be simply implemented as </p>\n\n<pre><code>Iterable&lt;Entry&lt;string, string&gt;&gt; getParameters() {\n return parameterMap.entrySet();\n}\n</code></pre>\n\n<p>or if you want to be really paranoid (to protect against someone trying to cast the return value back to a <code>Set</code> in order to try adding elements):</p>\n\n<pre><code>Iterable&lt;Entry&lt;string, string&gt;&gt; getParameters() {\n return Collections.unmodifiableSet(parameterMap.entrySet());\n}\n</code></pre>\n\n<p>Usage would be to replace this:</p>\n\n<blockquote>\n<pre><code> final Map&lt;String, String&gt; paramMap = cKeys.getParameterMap();\n Set&lt;Entry&lt;String, String&gt;&gt; params = paramMap.entrySet();\n for (Entry&lt;String, String&gt; e : params) {\n url.append(\"&amp;\" + e.getKey());\n url.append(\"=\" + e.getValue());\n }\n</code></pre>\n</blockquote>\n\n<p>with:</p>\n\n<pre><code> for (Entry&lt;String, String&gt; e : cKeys.getParameters()) {\n url.append(\"&amp;\" + e.getKey());\n url.append(\"=\" + e.getValue());\n }\n</code></pre>\n\n<p>The slight downside to that is that a user cannot perform fast lookups anymore on it to get the value for a specific parameter. If you want to support that then you'd need to add a <code>getParameter(string parameterName)</code> method to <code>ClientKey</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T08:49:13.787", "Id": "67334", "Score": "0", "body": "Thanks Chris for the suggestion. Appreciated your help. Can you provide an example for option 2 and 3 corresponding to my example so that I can understand how things will look like and how I am supposed to use it. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:19:49.807", "Id": "67336", "Score": "0", "body": "@user2809564: See updated answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:33:54.683", "Id": "67337", "Score": "0", "body": "Thanks a lot Chris. I also have similar question [here](http://codereview.stackexchange.com/questions/40079/how-to-avoid-gson-deserialization-if-i-am-aware-of-error-response-from-the-serve). See if you can help me out there as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T07:38:31.880", "Id": "40078", "ParentId": "40076", "Score": "2" } } ]
{ "AcceptedAnswerId": "40078", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T04:39:19.783", "Id": "40076", "Score": "3", "Tags": [ "java", "performance", "multithreading", "thread-safety" ], "Title": "Synchronous and asynchronous client methods" }
40076
<p>I am working on a project in which I am making a call to one of my servers using <code>RestTemplate</code> which is running a RESTful service and getting the response back from them. </p> <p>The response that I will be getting from my server can be either of these error responses (that's all I have for error response) if something has gone wrong:</p> <pre><code>{"warning": "user_id not found", "user_id": some_user_id} {"error": "user_id for wrong partition", "user_id": some_user_id, "partition": some_partition} {"error": "missing client id", "client_id":2000} </code></pre> <p>or below successful response if there is no failures (it can be any random json string, key can be different as well) - </p> <pre><code>{"@data": {"oo":"1205000384","p":"2047935"}} </code></pre> <ol> <li>If I am getting any error response as mentioned above, then I am deserializing it so that I can log them as an error with a specific <code>error</code> or <code>warning</code> I got front the server which can be for example - <code>user_id not found</code> or <code>missing client id</code>.</li> <li>If it is a successful response, then I am also deserializing it, which I don't need for my use case as we don't have any POJO. I just need to return the response as is which I receive from the server.</li> </ol> <p>In my use case, I don't need to deserialize my response string if it is a successful response as we don't have any POJO for that and we are returning the response string as it is which we have got from the server. But just for logging specific error messages (if I am getting error response from the server) I am deserializing it which I am thinking is unnecessary. There might be better solution for my use case.</p> <p>Here is my Java client which is calling a <code>Callable</code> task using <code>future.get</code>:</p> <pre><code>public class TestingClient implements IClient { private ExecutorService service = Executors.newFixedThreadPool(10); private RestTemplate restTemplate = new RestTemplate(); @Override public String executeSync(ClientKey keys) { String response = null; try { ClientTask ClientTask = new ClientTask(keys, restTemplate); Future&lt;String&gt; future = service.submit(ClientTask); response = handle.get(keys.getTimeout(), TimeUnit.MILLISECONDS); } catch (TimeoutException e) { } catch (Exception e) { } return response; } } </code></pre> <p>And here is my <code>ClientTask</code> class, which implements the <code>Callable</code> interface. In the call method, I am generating a URL and then hit the server using <code>RestTemplate</code> and get the response back:</p> <pre><code>class ClientTask implements Callable&lt;String&gt; { private ClientKey cKeys; private RestTemplate restTemplate; public ClientTask(ClientKey cKeys, RestTemplate restTemplate) { this.restTemplate = restTemplate; this.cKeys = cKeys; } @Override public String call() throws Exception { // .. some code here String url = "some_url"; String response = restTemplate.getForObject(url, String.class); String test = checkJSONResponse(response); return test; } private String checkJSONResponse(final String response) throws Exception { // may be there are some better way of doing it for my scenario instead of using GSON Gson gson = new Gson(); String str = null; JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse it, may be performance issues here/ if (jsonObject.has("error") || jsonObject.has("warning")) { final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject .get("warning").getAsString(); // log specific `error` here using log4j str = response; } else { str = response; } return str; } } </code></pre> <p>As you can see, we are deserializing the JSON string only to log specific error messages if we are getting any error response back. But for successful response we don't need any deserialization but still we are doing it.</p> <p>Is there any better way of solving this problem? I am currently seeing some performance issues with the GSON deserialization. The only way I can identify successful response is error response will have <code>error</code> or <code>warning</code> in the response. I guess there might be some better way of solving this problem without paying the cost for deserialization.</p>
[]
[ { "body": "<p>If you have indeed identified the json deserialization to be a performance problem (by profiling it) then you can </p>\n\n<ol>\n<li>Try using a different json serializer (GSon was reported at least in the past to be a fair bit slower than for example <a href=\"https://github.com/FasterXML/jackson\" rel=\"nofollow\">Jackson</a>)</li>\n<li>Don't deserialize and check the string manually.</li>\n</ol>\n\n<p>From \"one of my servers\" I conclude that you control exactly what responses the server can send and how they are composed. In which case a simple:</p>\n\n<pre><code>if (response.contains(\"error\") || response.contains(\"warning\")) {\n ...\n}\n</code></pre>\n\n<p>might suffice and be robust enough. When handling the error case you could then either still deserialize the message or just use some string splitting or regular expressions in order to extract the data for logging. Or you could simply log the entire json - it's human readable and a log parser could easily extract the relevant data for analysis afterwards.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T16:57:01.160", "Id": "67375", "Score": "0", "body": "Thanks Chris. For your second option, it might be possible for some of my successful response string, it has error or warning in it, I don't know when and it is very unlikely to happen but to be on the safer side, I am not trying that option. I might want to try regular expression option which can check whether my response string has error or warning as the first key, if it is there then extract the specific error message and log it. If possible can you provide an example on that. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:27:42.177", "Id": "40087", "ParentId": "40079", "Score": "2" } } ]
{ "AcceptedAnswerId": "40087", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T07:46:36.300", "Id": "40079", "Score": "3", "Tags": [ "java", "performance", "multithreading", "thread-safety", "rest" ], "Title": "Making a call to a server running a RESTful service" }
40079
<p>I'm trying to get started with network and parallel programming in C#. I'm almost a complete novice in programming, so I'm looking for feedback on a small script I'm writing.</p> <p>The goal of the programming is to:</p> <ol> <li>Accept incoming connections and store them as users which are sent into <code>Room</code>s. Users are expected to provide occasional input, maybe once every second.</li> <li>After a certain time, the input from all users in a room is collected and then sent back to all users in that room.</li> </ol> <p>In total there are 3 classes:</p> <ol> <li>Server</li> <li>Room</li> <li>User</li> </ol> <p>The below code is far from complete and, and I haven't decided on startup and close down mechanisms yet. As of now, I just want the connections and asynchronous to work.</p> <pre><code>class Server { private bool ServerIsRunning; private const int port = 12321; private TcpListener _listener; private List&lt;Room&gt; _rooms; private const int speed = 100; public Server() { _rooms = new List&lt;Room&gt;(); startServer(); } // Start the server private void startServer() { try { _listener = new TcpListener(IPAddress.Any, port); _listener.Start(); ServerIsRunning = true; listenForClients(); } catch (SocketException e) { Console.Write(e.Message); } } // Listen for clients while server is on, if found, send them to a room async private void listenForClients() { while (ServerIsRunning) { TcpClient client = await _listener.AcceptTcpClientAsync(); new User(client, getARoom()); } } // Get a room thats not full(less then 10 users) private Room getARoom() { int index = _rooms.Count - 1; if ((index &lt; 0) || (_rooms[index].NumberOfUsers &gt; 9)){ _rooms.Add(new Room(speed)); index++; } return _rooms[index]; } } class Room { private Task _sending; private static Timer timer; private List&lt;User&gt; _users; private List&lt;Task&gt; _readers; public Task Sending { get { return _sending; } } public int NumberOfUsers { get { return _users.Count; } } public Room(int time) { this._users = new List&lt;User&gt;(); this._readers = new List&lt;Task&gt;(); this._sending = new Task(); setupTimer(time); } public void start() { timer.Start(); } public void stop() { timer.Stop(); } // set up timer private void setupTimer(int time) { timer = new Timer(time); timer.Elapsed += new ElapsedEventHandler(sendNewOutput); } // Add user to room and start if full public void registerUser(User newUser) { _users.Add(newUser); _readers.Add(newUser.Reading); if (_users.Count &gt; 0) { start(); } } // remove user from room public void deRegisterUser(User user) { _users.Remove(user); _readers.Remove(user.Reading); } // waits for all users to finish recieving and then send the total input back to all async private void sendNewOutput(object s, ElapsedEventArgs a) { await Task.WhenAll(_readers); // Waits for all clients to read try { _sending = Task.Run(() =&gt; { sendOutput(interpretInput()); }); } catch (Exception e) { Console.WriteLine(e.Message); } } // gathers all input private List&lt;byte[]&gt; interpretInput() { List&lt;byte[]&gt; input = new List&lt;byte[]&gt;(); _users.ForEach((user) =&gt; { input.AddRange(user.Input); }) return input; } // Sends out output private void sendOutput(List&lt;byte[]&gt; output) { _users.ForEach((user) =&gt; { user.send(output); }); } } class User { private TcpClient _connection; private NetworkStream _stream; private Room _room; private Task _reading; private List&lt;byte[]&gt; _input; public Task Reading { get { return _reading; } } // So that others can see if the task is complete public List&lt;byte[]&gt; Input { get { return _input; } } // making the input available public User(TcpClient connection, Room room) { this._connection = connection; this._stream = connection.GetStream(); this._room = room; this._reading = new Task(); this._room.registerUser(this); listen(); } // Listen for data private void listen() { Task.Run(async () =&gt; { while (_connection.Connected) { if (_stream.CanRead &amp;&amp; _stream.DataAvailable) { _reading = read(); await _reading; // finish reading before starting again } Thread.Sleep(50); // i dont want to read all the time } cleanUp(); }); } // wait for the room to finish sending out data and then read the new thats waiting async private Task read() { await _room.Sending; // Waits for the server to finish sending out info to all clients before reading in new int length; byte[] input = new byte[1024]; while ((length = await _stream.ReadAsync(input, 0, 1024)) != 0) { byte[] data = new byte[length]; Array.Copy(input, data, length); _input.Add(data); } } // sends output to client public void send(List&lt;byte[]&gt; output) { output.ForEach((message) =&gt; { _stream.Write(message, 0, message.Length); }); } // dergisters the user from the room and closes stream and connection private void cleanUp() { _room.deRegisterUser(this); try { _stream.Close(); _connection.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:25:45.727", "Id": "67346", "Score": "0", "body": "“I just want the connections and asynchronous to work.” Does that mean it doesn't work now? If that's the case, your question is not appropriate here, Core Review is for reviewing working code only." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T14:55:44.243", "Id": "67364", "Score": "0", "body": "Apologies, I didnt know." } ]
[ { "body": "<p>A few things I noticed:</p>\n\n<ol>\n<li><p>Traditionally methods in C# follow <code>CamelCase</code> naming convention (as you can see everwhere in the .NET framework).</p></li>\n<li><p>You probably want to pass the <code>port</code> and <code>speed</code> as parameters to the server rather than hard coding them.</p></li>\n<li><p><code>speed</code> - what is that? You have to actually go down and read the code and see that it's passed to a timer and you have to know that the timer expects the timeout in milliseconds in order to know what it means. Something like <code>roomUpdateIntervalMs</code> would be more descriptive and take the guesswork out of what unit the value is. Also consider making it a <code>TimeSpan</code> instead (in which case you can drop the <code>Ms</code> suffix).</p></li>\n<li><p>Use the power of Linq. This:</p>\n\n<blockquote>\n<pre><code>List&lt;byte[]&gt; input = new List&lt;byte[]&gt;();\n_users.ForEach((user) =&gt; { input.AddRange(user.Input); })\nreturn input;\n</code></pre>\n</blockquote>\n\n<p>can be rewritten as</p>\n\n<pre><code>return _users.SelectMany(u =&gt; u.Input).ToList();\n</code></pre></li>\n<li><p>This:</p>\n\n<blockquote>\n<pre><code>byte[] input = new byte[1024];\n while ((length = await _stream.ReadAsync(input, 0, 1024)) != 0) {\n</code></pre>\n</blockquote>\n\n<p>should be</p>\n\n<pre><code>byte[] input = new byte[1024];\nwhile ((length = await _stream.ReadAsync(input, 0, input.Length)) != 0) {\n</code></pre>\n\n<p>otherwise you have to change a constant in two places if you want to make the buffer larger.</p></li>\n<li><p>The comment here is misleading:</p>\n\n<pre><code>// Add user to room and start if full\npublic void registerUser(User newUser)\n</code></pre>\n\n<p>It does start it if at least one user is in there (not empty rather than full). In fact it will call <code>start()</code> every time you add a user as the condition checks for <code>count &gt; 0</code>.</p></li>\n<li><p>This <code>new User(client, getARoom());</code> reads a bit strange. In a garbage collected language on first glance this reads like \"nothing holds the reference so it will be garbage collected immediately\". Only after digging into the code one will see that it's internally added to the room collection. I would suggest to remove the registration form the <code>User</code> constructor and make it an external call instead.</p>\n\n<pre><code>var room = getARoom();\nvar user = new User(client, room);\nroom.registerUser(user);\n</code></pre>\n\n<p>This makes it more explicit what if happening.</p></li>\n<li><p><code>AcceptTcpClientAsync</code> can accept a client any time. In which case you can add a new user while a send operation is in progress which happens to iterate over the user list. You are bound to get a <code>InvalidOperationException</code> stating <code>Collection was modified; enumeration operation may not execute.</code></p></li>\n<li><p>Last but not least probably the biggest issue:</p>\n\n<p>I admit that I'm not having a great deal of experience with the async framework however: Tasks are not synchronization primitives. They are an abstraction aimed to make asynchronous and parallel programming a bit easier and less painful.</p>\n\n<p>You are using them to synchronize read and send operations and I'm pretty sure this will be a source of pain. A <a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx\" rel=\"nofollow\"><code>ReaderWriterLock</code></a> owned by the room would seem a better tool (<code>n</code> readers, <code>1</code> writer, don't write while reading, don't read while writing). Don't expose the lock though - this should be encapsulated. Each user should call something like <code>_room.ObtainReadPermission()</code> or so which internally enters the lock.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:48:32.613", "Id": "67354", "Score": "0", "body": "Thank You! Lots of good tips here and ill take a look at all of them. The last one in particular, way better solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T15:11:39.633", "Id": "67367", "Score": "0", "body": "Ad. 4: I think you need SelectMany there, Select would be the equivalent of Add, not AddRange." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:23:06.313", "Id": "40089", "ParentId": "40080", "Score": "4" } } ]
{ "AcceptedAnswerId": "40089", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T08:25:54.700", "Id": "40080", "Score": "5", "Tags": [ "c#", "tcp", "async-await" ], "Title": "Basic TCP server application in C# using async / await" }
40080
<p>Problem: Concat all sub-arrays of a given array. </p> <p>Example input: <code>[[0, 1], [2, 3], [4, 5]]</code></p> <p>Example output: <code>[0, 1, 2, 3, 4, 5]</code></p> <p><strong>Solution A: Use a loop</strong></p> <pre><code>var flattened=[]; for (var i=0; i&lt;input.length; ++i) { var current = input[i]; for (var j=0; j&lt;current.length; ++j) flattened.push(current[j]); } </code></pre> <p><strong>Solution B: Use reduce</strong></p> <pre><code>var flattened = input.reduce(function(a, b) { return a.concat(b); }, []); </code></pre> <p>Solution B looks much shorter and easier to understand, but, it seems to be much more resource-wasteful - for each element of the input, a new array is created - the concatenation of a and b. On the contrary, solution A uses a single array 'flattened', which is updated during the loop.</p> <p>So, my question is: which solution is better? Is there a solution that combines the best of both worlds?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T10:08:30.687", "Id": "67340", "Score": "5", "body": "Typical solution is `Array.prototype.concat.apply([],input)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-20T04:21:17.187", "Id": "128663", "Score": "0", "body": "@elclanrs this should be an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-14T15:54:11.213", "Id": "151259", "Score": "1", "body": "@elclanrs - This solution fails if there are a large number of arrays in input because it overflows the call stack. Otherwise, you are correct." } ]
[ { "body": "<p><a href=\"http://jsperf.com/flatten-an-array-loop-vs-reduce\">Here</a> is the performance test for these two and couple more approaches (one suggested by @elclanrs in the comments).</p>\n\n<p>The performance differences will vary significantly across different browsers, and even different version on same browser, as browser these days try to optimize javascript very aggressively. </p>\n\n<p>Unless you are dealing with very large arrays or this operation is performed repeatedly in quick succession, I would suggest you to use simplest and clearest approach. But, that being said the loop solution is also not that complex or big anyway (and it performs better than others especially on firefox)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:04:38.650", "Id": "67376", "Score": "1", "body": "Thanks a lot! It seems that a loop is indeed the most efficient approach, as I thought." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-23T14:49:56.123", "Id": "148169", "Score": "0", "body": "forEach+push is actually doing nothing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T13:04:56.127", "Id": "40093", "ParentId": "40083", "Score": "10" } }, { "body": "<p>Taking @elclanrs solution in the comments above and modifying slightly to overcome the limitations with ultra long arrays and argument expansion, you could use something like this:</p>\n\n<pre><code>function flattenLongArray(input) {\n var LIMIT = 32768;\n var end, result = [];\n\n\n for(var i = 0; i &lt; input.length; i+=LIMIT) {\n end = Math.min(i+LIMIT, input.length) - 1;\n Array.prototype.concat.apply(result, input.slice(i, end));\n }\n\n return result;\n}\n</code></pre>\n\n<p>This is admittedly verbose, but it works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-29T19:38:18.240", "Id": "376218", "Score": "0", "body": "Sorry my friend, can you explain a little bit more this code? I can't understand why the use of `LIMIT = 32768`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-30T15:31:41.790", "Id": "376343", "Score": "0", "body": "The limit is there to overcome the stack limitation. For arrays larger than 32768, applying the `concat` function like this will result in the JS engine throwing an error because the call stack will exceed the 32k limit as it recurses. See my comment to elclanrs regarding his solution using `concat` in the discussion at the top. If you are never going to encounter arrays that large, the limit checking code isn't needed and you can just use `concat` directly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-30T15:35:59.337", "Id": "376344", "Score": "0", "body": "I want to add that the limit may vary depending on the JavaScript engine implementation. My chosen limit of 32768 is probably quite generous and should be lower. Here is [an SE link which lists JavaScript stack limits in various browser versions](https://stackoverflow.com/questions/7826992/browser-javascript-stack-size-limit)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-15T04:07:09.790", "Id": "84117", "ParentId": "40083", "Score": "6" } } ]
{ "AcceptedAnswerId": "40093", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:38:17.007", "Id": "40083", "Score": "14", "Tags": [ "javascript", "comparative-review" ], "Title": "Flatten an array - loop or reduce?" }
40083
<p>This is my first attempt a for git command I can use to push the latest commit and email the diff. Story behind how it came up: <a href="http://goo.gl/3NEHvn" rel="nofollow">http://goo.gl/3NEHvn</a></p> <p><strong>Revision 1</strong> (Scroll down for 2nd Revision)</p> <pre><code>import argparse import subprocess import os import re import send import sys class INVALIDEMAIL(Exception): pass def main(): parser = argparse.ArgumentParser(prog='ipush', description='Utility to push the last commit and email the color diff') parser.add_argument('-v', '--verbose', action='store_true', help='if enabled will spit every command and its resulting data.') parser.add_argument('-c', '--compose', help='text message to be sent with diff') parser.add_argument('-to', type=str, help='enter a valid email you want to send to.') parser.add_argument('-ver', '--version', action='version', version='%(prog)s 1.0') parser.add_argument('-d', '--diff', required=False, help='if present pass arguments to it as you will do to git diff in inverted commas') args = parser.parse_args() VERBOSE = args.verbose optArgs = vars(args) if optArgs['to']: sendTo = optArgs['to'] pattern = "^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$" if not re.match(pattern, sendTo) != None: raise INVALIDEMAIL("You have entered an invalid email to send to.") else: sendto = "removed@myemail.com" diffCmd = 'git diff HEAD^ HEAD' if not optArgs['diff'] else "git diff %s" % optArgs['diff'] branchName, _ = execGitCommand('git rev-parse --abbrev-ref HEAD') # stripping newline character which got appended when pulling branch name branchName = branchName.split("\n")[0] commitComment, _ = execGitCommand('git log -1 --pretty=%B') subject = "%s: %s" % (branchName, commitComment) # check for fatal error when executing git command diffData, error = execGitCommand(diffCmd, VERBOSE) if 'fatal' not in error.split(":"): modifiedData, error = execGitCommand('git status', VERBOSE) if any([re.search(word, modifiedData) for word in ['modified', 'untracked']]): print "\x1b[31m You have uncommited changes, Commit and try again:\x1b[m" return # only push that is displayed if diffCmd in ['git diff HEAD^ HEAD', 'git diff HEAD~ HEAD']: pushBranch(VERBOSE) if diffData: htmlDiff = getHtml(diffData.split("\n")) message = htmlDiff if not optArgs['compose'] else "%s&lt;br&gt;&lt;br&gt;%s" % ( optArgs['compose'], htmlDiff) emailDiff(subject, sendto, message) else: print error.capitalize() def getHtml(diffData): """ This method convertes git diff data to html color code """ lines = "" openTag = "&lt;span style='font-size: .80em; color: " openTagEnd = ";font-family: courier, arial, helvetica, sans-serif;'&gt;" nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;' for eachLine in diffData: if eachLine.startswith('-'): tabs = eachLine.count('\t') lines += "%s#ff0000%s%s%s&lt;/span&gt;&lt;br&gt;" % (openTag, openTagEnd, nbsp*tabs ,eachLine) elif eachLine.startswith('+'): tabs = eachLine.count('\t') lines += "%s#007900%s%s%s&lt;/span&gt;&lt;br&gt;" % (openTag, openTagEnd, nbsp*tabs, eachLine) else: tabs = eachLine.count('\t') lines += "%s#000000%s%s%s&lt;/span&gt;&lt;br&gt;" % (openTag, openTagEnd, nbsp*tabs, eachLine) return lines def execGitCommand(command=None, verbose=False): """ Function used to get data out of git commads and errors in case of failure. Args: command(string): string of a git command verbose(bool): whether to display every command and its resulting data. Return: (tuple): string of Data and error if present """ if command: pr = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) msg = pr.stdout.read() err = pr.stderr.read() txt = "\x1b[32mResult:\x1b[m\n"+msg if msg else "\x1b[31mError:\x1b[m\n"+err if verbose: print "Executing '%s'\n%s" % (command, txt) return msg, err def emailDiff(subject, emailTo, htmlDiff): """ This function send color diff via email Args: subject(string): name of the branch with commit message htmlDiff(string): html formatted string """ mail = send.EMail( mailFrom=os.getenv('myemail'), server='smtp.gmail.com', usrname=os.getenv('myemail').split('@')[0], password=os.getenv('PASS'), files=None, debug=False ) mail.sendMessage(subject, htmlDiff, None, emailTo) print "\x1b[31m Diff of branch, %s sent to email: %s .\x1b[m" % (subject, emailTo) def pushBranch(VERBOSE): """ Pushes the branch to remote repository Args: VERBOSE(bool): defines whether to spit out which command is being executed and result of command. Return: (bool) True if push Succesfull else False """ _, err = execGitCommand('git push') if re.search(r'rejected', err): print '%s\n\x1b[31mDo you want to try force push?\x1b[m\n\x1b[31mEnter yes to force Push else any key to cancel\x1b[m' % err # default value yes and hit enter without entering anything answer = raw_input('[YES]') if answer and answer.lower() not in ['yes', 'y', 'f', 'git push -f']: print "Cancelled !!!" else: execGitCommand('git push -f', VERBOSE) print "\x1b[33mPush Succesfull !\x1b[m" if VERBOSE else "" return True else: print "\x1b[33mPush Succesfull !\x1b[m" if VERBOSE else "" return True return False if __name__ == '__main__': sys.exit(main()) </code></pre> <p>It has dependency file that sends the email [send.py]</p> <pre><code>from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import smtplib class EMail(object): """ Class defines method to send email """ def __init__(self, mailFrom, server, usrname, password, files, debug=False): self.debug = debug self.mailFrom = mailFrom self.smtpserver = server self.EMAIL_PORT = 587 self.usrname = usrname self.password = password def sendMessage(self, subject, msgContent, files, mailto): """ Send the email message Args: subject(string): subject for the email msgContent(string): email message Content files(List): list of files to be attached mailto(string): email address to be sent to """ msg = self.prepareMail(subject, msgContent, files, mailto) # connect to server and send email server=smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT) server.ehlo() # use encrypted SSL mode server.starttls() # to make starttls work server.ehlo() server.login(self.usrname, self.password) server.set_debuglevel(self.debug) try: failed = server.sendmail(self.mailFrom, mailto, msg.as_string()) except Exception as er: print er finally: server.quit() def prepareMail(self, subject, msgHTML, attachments, mailto): """ Prepare the email to send Args: subject(string): subject of the email. msgHTML(string): HTML formatted email message Content. attachments(List): list of file paths to be attached with email. """ msg = MIMEMultipart() msg['From'] = self.mailFrom msg['To'] = mailto msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject #the Body message msg.attach(MIMEText(msgHTML, 'html')) msg.attach(MIMEText("Sent using git ipush\n git clone https://sanfx@bitbucket.org/sanfx/git-ipush.git")) if attachments: for phile in attachments: # we could check for MIMETypes here part = MIMEBase('application',"octet-stream") part.set_payload(open(phile, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(phile)) msg.attach(part) return msg </code></pre> <p>I would really appreciate if you can help me make it more better. How neat is this first attempt?</p> <p><strong>Revision 2</strong>: I have updated the following methods:</p> <pre><code>def getHtml(diffData): """ This method convertes git diff data to html color code Args: diffData(sting): diff between commits in simple text """ openTag = "&lt;span style='font-size: .80em; color: " openTagEnd = "00;font-family: courier, arial, helvetica, sans-serif;'&gt;" nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;' lines = [] for line in diffData: color = "#ff00" if line.startswith('-') else ('#0079' if line.startswith('+') else '#0000') tabs = line.count('\t') lines.append("%s%s%s%s%s&lt;/span&gt;&lt;br&gt;" % ((openTag, color, openTagEnd, nbsp*tabs ,line))) return ''.join(lines) </code></pre> <p>and this too:</p> <pre><code>def validate_address(address): """ If address looks like a valid e-mail address, return it. Otherwise raise ArgumentTypeError. Args: address(string): email address to send to """ if re.match('^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$', address): return address raise argparse.ArgumentTypeError('Invalid e-mail address: %s' % address) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:42:53.203", "Id": "67353", "Score": "0", "body": "OOps I forgot to run pylint before posting, I'll do that next." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:50:49.827", "Id": "67355", "Score": "2", "body": "What's the point of checking for the valid email address? You exclude a fair amount of valid ones." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:52:16.233", "Id": "67773", "Score": "0", "body": "@ChrisWue: Like what ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T18:53:49.397", "Id": "67816", "Score": "0", "body": "like `user@domain` or `\"Jon Doe\"@example.com`. Admittedly not extremely likely (except maybe for the first one). It's much more likely the user has a typo in the address - in which case it's still valid just the wrong address." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-21T22:07:12.720", "Id": "103100", "Score": "0", "body": "Don't forget address extensions! (`user+service@example.com`)" } ]
[ { "body": "<p>Here's my review on the Python code :</p>\n\n<p>As a general comment, your code does not follow <a href=\"http://www.python.org/dev/peps/pep-0008/\">this</a>. I'll try to hilight the different points as I see them but for the most obvious one, the namming convention is not respected. You can find tools to check automatically that everything is fine. For instance, <a href=\"http://pep8online.com/\">http://pep8online.com/</a> .</p>\n\n<p><a href=\"http://docs.python.org/dev/library/argparse.html#argparse.ArgumentParser.add_argument\">This</a> can take a default value as an argument. I guess you could use this to remove the <code>if optArgs['to']</code> logic.</p>\n\n<p>Comparisons to singletons like None should always be done with is or is not, never the equality operators.</p>\n\n<pre><code>if not re.match(pattern, sendTo) != None:\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if re.match(pattern, sendTo) is None:\n</code></pre>\n\n<p>You could remove duplication from</p>\n\n<pre><code>diffCmd = 'git diff HEAD^ HEAD' if not optArgs['diff'] else \"git diff %s\" % optArgs['diff']\n</code></pre>\n\n<p>by writing it</p>\n\n<pre><code>diffCmd = \"git diff %s\" % (optArgs['diff'] if optArgs['diff'] else \"HEAD^ HEAD\")\n</code></pre>\n\n<p>Purely personal but I find</p>\n\n<pre><code>message = htmlDiff if not optArgs['compose'] else \"%s&lt;br&gt;&lt;br&gt;%s\" % (optArgs['compose'], htmlDiff)\n</code></pre>\n\n<p>easier to read when conditions are not inverted:</p>\n\n<pre><code>message = \"%s&lt;br&gt;&lt;br&gt;%s\" % (optArgs['compose'], htmlDiff) if optArgs['compose'] else htmlDiff\n</code></pre>\n\n<p>I do not think <code>eachLine</code> is a very good variable name. <code>line</code> seems to be simple enough (and it does follow the naming conventions).</p>\n\n<pre><code>def getHtml(diffData):\n \"\"\" This method convertes git diff data to html color code\n \"\"\"\n lines = \"\"\n openTag = \"&lt;span style='font-size: .80em; color: \"\n openTagEnd = \";font-family: courier, arial, helvetica, sans-serif;'&gt;\"\n nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'\n for eachLine in diffData:\n if eachLine.startswith('-'):\n tabs = eachLine.count('\\t')\n lines += \"%s#ff0000%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, openTagEnd, nbsp*tabs ,eachLine)\n elif eachLine.startswith('+'):\n tabs = eachLine.count('\\t')\n lines += \"%s#007900%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, openTagEnd, nbsp*tabs, eachLine)\n else:\n tabs = eachLine.count('\\t')\n lines += \"%s#000000%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, openTagEnd, nbsp*tabs, eachLine)\n return lines\n</code></pre>\n\n<p>can be enhanced by removing duplicated code :</p>\n\n<pre><code>def getHtml(diffData):\n \"\"\" This method convertes git diff data to html color code\n \"\"\"\n lines = \"\"\n openTag = \"&lt;span style='font-size: .80em; color: \"\n openTagEnd = \";font-family: courier, arial, helvetica, sans-serif;'&gt;\"\n nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'\n for line in diffData:\n if line.startswith('-'):\n value = '#ff0000'\n elif line.startswith('+'):\n value = '#007900'\n else:\n value = '#000000'\n tabs = line.count('\\t')\n lines += \"%s%s%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, value, openTagEnd, nbsp*tabs ,line)\n return lines\n</code></pre>\n\n<p>Then, PEP 8 advices to use <code>''.join()</code> instead of multiple concatenation which can become a bit expensive. Here's how you could do.</p>\n\n<pre><code>def getHtml(diffData):\n \"\"\" This method convertes git diff data to html color code\n \"\"\"\n lines = []\n openTag = \"&lt;span style='font-size: .80em; color: \"\n openTagEnd = \";font-family: courier, arial, helvetica, sans-serif;'&gt;\"\n nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'\n for line in diffData:\n if line.startswith('-'):\n value = '#ff0000'\n elif line.startswith('+'):\n value = '#007900'\n else:\n value = '#000000'\n tabs = line.count('\\t')\n lines.append(\"%s%s%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, value, openTagEnd, nbsp*tabs ,line))\n return ''.join(lines)\n</code></pre>\n\n<p>Now, if we want to go further, one can notice that the pattern <code>l=[]. for x in X: l.append(f(x))</code> looks like it could be some kind of list comprehension/generator expression.\nThus :</p>\n\n<pre><code>def getHtml(diffData):\n \"\"\" This method convertes git diff data to html color code\n \"\"\"\n openTag = \"&lt;span style='font-size: .80em; color: \"\n openTagEnd = \";font-family: courier, arial, helvetica, sans-serif;'&gt;\"\n nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'\n lines = []\n for line in diffData:\n value = '#ff0000' if line.startswith('-') else ('#007900' if line.startswith('+') else '#000000')\n tabs = line.count('\\t')\n lines.append(\"%s%s%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, value, openTagEnd, nbsp*tabs ,line))\n return ''.join(lines)\n</code></pre>\n\n<p>becomes (but it might be a bit too excessive):</p>\n\n<pre><code>def getHtml(diffData):\n \"\"\" This method convertes git diff data to html color code\n \"\"\"\n openTag = \"&lt;span style='font-size: .80em; color: \"\n openTagEnd = \";font-family: courier, arial, helvetica, sans-serif;'&gt;\"\n nbsp = '&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'\n return ''.join([(\"%s%s%s%s%s&lt;/span&gt;&lt;br&gt;\" % (openTag, '#ff0000' if line.startswith('-') else ('#007900' if line.startswith('+') else '#000000'), openTagEnd, nbsp*line.count('\\t') ,line)) for line in diffData])\n</code></pre>\n\n<p>You do not need to check <code>if attachments:</code> before doing <code>for phile in attachments:</code>.</p>\n\n<p>That's pretty much all I have to say about the code itself for the time being.</p>\n\n<p>Now for the functional side of it, I am not quite sure what was intended but you might want to have a look at git hooks as they would be a nice way to send the email automatically as you commit/push.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:39:29.613", "Id": "67352", "Score": "0", "body": "Does git hook push allow's colour diff in email ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T16:11:23.253", "Id": "67372", "Score": "0", "body": "thanks for the review, I preferred not to use list comprehension though just to leave code more readable for anyone who looks although list comprehension are my personal favourites." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T19:12:56.833", "Id": "67403", "Score": "1", "body": "If you pull the line-formatting out into a function, the list comprehension becomes much cleaner: `return ''.join([format_color_html(line) for line in diffData])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:20:06.027", "Id": "67552", "Score": "2", "body": "`''.join(map(format_color_html, diffData))` is a shorter way to compute the same result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T01:58:09.560", "Id": "67629", "Score": "1", "body": "@DavidHarkness : I think this way I can come up with whole module of colour and styling for HTML formatting !!! something like pygmentize is doing." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T11:30:51.180", "Id": "40090", "ParentId": "40084", "Score": "10" } }, { "body": "<h3>1. Introduction</h3>\n\n<p>I'm just going to comment on the part of your program (the first few lines of the <code>main</code> function) where you parse the command-line arguments. You'll see that there's plenty here for one answer.</p>\n\n<h3>2. Comments on your code</h3>\n\n<ol>\n<li><p>I don't like the specification of this program. It does two things: (i) push all commits on the current branch to the remote origin; (ii) e-mail the diff from the last commit (only) on the current branch to a specified e-mail address.</p>\n\n<p>The problem is that these two things do not match. You push <em>all the commits</em> but then e-mail the diff for the <em>last commit only</em>. This more or less ensures that at some point a user will be confused or misled because they had made multiple commits locally but when they ran your script they only saw the diff for the last commit they made.</p>\n\n<p>My proposal is that you separate these two pieces of functionality. Piece number (i) is so simple (just run <code>git push</code>, and if that fails, ask the user if they want to try <code>git push -f</code>) that it doesn't deserve a special script. So I would revise the script so that it just e-mail a diff.</p></li>\n<li><p>I don't like the casual way you run <code>git push -f</code>. It says in the manual that the <code>-f</code> option \"can cause the remote repository to lose commits; use it with care.\" Running it if the user presses return in response to the prompt \"Enter yes to force Push else any key to cancel\" does not seem like an appropriate level of care.</p></li>\n<li><p>In Unix, users expect options that start with a single hyphen to be single characters, and for options without arguments to be combinable. In particular, <code>-ver</code> would normally mean the same thing as <code>-v -e -r</code>. So I would recommend replacing <code>-ver</code> with <code>-V</code> and getting rid of the <code>-to</code> option (you can make this a positional argument, as in the <code>sendmail</code> command).</p></li>\n<li><p>There's no need to write \"in inverted commas\" in the help text. It's reasonable to assume that the user knows how to use the shell.</p></li>\n<li><p>There's no need to pass <code>type=str</code> or <code>required=False</code> to <a href=\"http://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument\"><code>add_argument</code></a>: these are the defaults.</p></li>\n<li><p>If you had kept your code to 79 columns (as recommended by the <a href=\"http://www.python.org/dev/peps/pep-0008/\">Python style guide, PEP8</a>) then we could read your code here without having to scroll it horizontally.</p></li>\n<li><p>It's conventional to use <code>CamelCase</code> for classes, so I would name the exception class <code>InvalidEmail</code>.</p></li>\n<li><p>There's no need to call <code>vars(args)</code>: instead of <code>optArgs['to']</code> you could just write <code>args.to</code> and so on.</p></li>\n<li><p>By specifying a default value for the <code>--diff</code> argument, you can avoid the need to check whether this argument was supplied when assembling the <code>diffCmd</code>.</p></li>\n<li><p>The default e-mail address should come from the environment, not be hard-coded into the script.</p></li>\n<li><p>The validation of the e-mail address is too restrictive: many e-mail addresses will be rejected. It's good practive just to check for the presence of an <code>@</code> (to avoid typos) and let your mail server reject bad addresses.</p></li>\n<li><p>Since you are using <a href=\"http://docs.python.org/3/library/re.html#re.match\"><code>re.match</code></a>, which only matches at the start of the string, there's no need to anchor the pattern with <code>^</code>.</p></li>\n<li><p>It's not a good idea to raise exceptions for user errors (reserve them for programming errors). For user errors, it's best to print a usage message instead. This is most easily done by passing a function to the <code>type=</code> parameter for the e-mail address argument.</p></li>\n<li><p>For testing purposes, it's a good idea for <code>main</code> to take one parameter <code>argv</code>, and to pass this to <code>parser.parse_args</code>. This allows you to test the program from the interactive interpreter. In the <code>__name__ == '__main__'</code> clause, write <code>main(sys.argv)</code>.</p></li>\n<li><p>You write <code>sys.exit(main())</code> but the function <code>main</code> doesn't return an exit code.</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>import argparse\nimport os\nimport re\nimport sys\n\ndef validate_address(address):\n \"\"\"If address looks like a valid e-mail address, return it. Otherwise\n raise ArgumentTypeError.\n\n \"\"\"\n if re.match('[^@]+@[^@]+$', address):\n return address\n raise argparse.ArgumentTypeError('Invalid e-mail address: {}'.format(address))\n\ndef main(argv=()):\n parser = argparse.ArgumentParser(prog='git-mail-diff',\n description='E-mail a git diff')\n parser.add_argument(dest='address', nargs='?',\n type=validate_address,\n default=os.getenv('myemail'),\n help='E-mail address to send the diff to')\n parser.add_argument('-d', '--diff',\n default='HEAD^ HEAD',\n help='arguments to pass to git diff '\n '(default: HEAD^ HEAD)')\n parser.add_argument('-c', '--compose',\n help='message to be sent along with the diff')\n parser.add_argument('-v', '--verbose', action='store_true',\n help='print commands and responses to standard output')\n parser.add_argument('-V', '--version', action='version',\n version='%(prog)s 1.0')\n args = parser.parse_args(argv)\n # ... etc ...\n\nif __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:33:30.743", "Id": "67766", "Score": "0", "body": "no it pushes the last commit only which is why I have a check for if `git diff HEAD^ HEAD` then do `pushBranch()` and email the same only. But if the diff is of something else it will just diff and display in verbose mode and email but not push." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:45:07.497", "Id": "67770", "Score": "0", "body": "also your regex for validating email address is wrong" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:55:34.553", "Id": "67774", "Score": "0", "body": "(1) Suppose that a user has multiple local commits that have not yet been pushed to the remote repository, and they run your script (without passing any options). The check on `diffCmd` passes, so you call `pushBranch`, which runs `git push`, which pushes all commits. But then you e-mail only the output of `git diff HEAD^ HEAD` (that is, the last commit only). (2) See my point #11." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:00:33.603", "Id": "67776", "Score": "0", "body": "for that there is a check `if any([re.search(word, modifiedData) for word in ['modified', 'untracked']]):print \"You have uncommited changes, Commit and try again\"\n return`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:01:12.733", "Id": "67777", "Score": "0", "body": "I'm not talking about uncommitted changes. I'm talking about committed changes that have not been pushed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:03:16.210", "Id": "67781", "Score": "0", "body": "to push the committed change is exactly i made it to push, that is always the last committed push." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:03:55.073", "Id": "67782", "Score": "0", "body": "But what if you have multiple committed changes that have not yet been pushed? (The difficulty in communicating this point seems like evidence for my point #1.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:24:58.240", "Id": "67791", "Score": "0", "body": "point, added check for that too: `re.search('ahead', modifiedData):` or is it better to just do `if 'ahead' in modifiedData` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:53:00.217", "Id": "67801", "Score": "0", "body": "`# Your branch is ahead of 'upstream' by 1 commit` would be fine, so you can't just search for the string `ahead`, you have to count the number of commits you are ahead by. (Also, `ahead` might legitimately appear elsewhere in the output of `git status`, for example in a filename.) It would be more reliable to use something like `git rev-list --left-only --count BRANCH...BRANCH@{upstream}`. (Where `BRANCH` is the local branch name, which you can determine using `git rev-parse --abbrev-ref HEAD`.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T18:21:30.013", "Id": "67808", "Score": "0", "body": "Just thought of it, suppose I have 3 unpushed commits then git push will obviously push all unpushed ones or just the last commit only?" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:48:19.780", "Id": "40183", "ParentId": "40084", "Score": "8" } } ]
{ "AcceptedAnswerId": "40090", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T09:46:21.533", "Id": "40084", "Score": "8", "Tags": [ "python", "git" ], "Title": "Git command: push the latest commit and email the diff in colour" }
40084
<p>I am writing a method to synchronize the local Core Data entities with a remote web service (in this case, Parse.com).</p> <p>To update changed or created objects, I fetch all where the <code>updatedAt</code> date property is larger than the last local sync date. So far, so good.</p> <p>But I am struggling with the deletion of local objects that have been removed on the server. My current approach is the following. This however seems quite expensive to me (\$O(r*l)\$ in the worst case, if I recall correctly). Is there any way to reduce the two loops?</p> <pre><code>PFQuery *idQuery = [PFQuery queryWithClassName:@"Product"]; [idQuery selectKeys:@[]]; NSArray *allRemote = [idQuery findObjects]; NSArray *allRemoteIds = [allRemote valueForKey:@"objectId"]; NSArray *allLocal = [Product all]; for(Product *p in allLocal) { BOOL shouldDelete = YES; for(NSString *remoteId in allRemoteIds) { if([remoteId isEqualToString:p.productId]) { shouldDelete = NO; break; } } if(shouldDelete) { [p delete]; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T08:43:28.220", "Id": "67470", "Score": "0", "body": "For what it's worth, two nested `for`-loops are not the end of the world, are they?" } ]
[ { "body": "<p>You can use <code>NSPredicate</code>:</p>\n\n<pre><code>NSArray* productsToDelete = [allLocal filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@\"NOT (productId IN %@)\", allRemoteIds]];\nfor(Product* product in productsToDelete) {\n [product delete];\n}\n</code></pre>\n\n<p>This will for sure improve readability of your code. I'm not sure about performance, but I would assume that Apple's implementation of <code>filteredArrayUsingPredicate</code> should be fast enough. If you really want to know it, do some profiling. </p>\n\n<p>You can also read great article about performance of collections in Objective-C:</p>\n\n<p><a href=\"http://www.objc.io/issue-7/collections.html\" rel=\"nofollow\">http://www.objc.io/issue-7/collections.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T00:28:12.660", "Id": "94977", "Score": "0", "body": "As a note of interest, from a performance stand point, `forin` loops do tend to be faster than `filteredArrayUsingPredicate:`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T12:09:33.010", "Id": "40259", "ParentId": "40095", "Score": "1" } }, { "body": "<p>That inner for-loop is basically equal to</p>\n\n<pre><code>shouldDelete = !([allRemoteIds containsObject:p.productId]);\n</code></pre>\n\n<p>i.e. if the product id exists in <code>allRemoteIds</code> then it should be deleted. The implementation of <code>containsObject</code> may have to go through the array of ids but it should in most cases quickly discard an object based on its hash which should make it faster. I also find it more readable than an explicit loop.</p>\n\n<p>I'm not sure what the <code>delete</code> method does in your case but it's not safe to add or remove objects from an array while enumerating it. If that isn't the case for you then your code could can be simplified like this:</p>\n\n<pre><code>for (Product *product in allLocal) {\n BOOL shouldDelete = !([allRemoteIds containsObject:p.productId]);\n if(shouldDelete) {\n [p delete];\n }\n}\n</code></pre>\n\n<p>Don't worry about the temporary variable. The compiler is going to remove that and it helps with readability.</p>\n\n<p>If your delete operation is safe to run concurrently on many objects then it may be slightly faster to run it like this:</p>\n\n<pre><code>[allLocal enumerateObjectsWithOptions:NSEnumerationConcurrent\n usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n Product *p = obj;\n BOOL shouldDelete = !([allRemoteIds containsObject:p.productId]);\n if(shouldDelete) {\n [p delete];\n }\n}];\n</code></pre>\n\n<p>You should measure and see if that makes a difference for you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T18:58:54.053", "Id": "43879", "ParentId": "40095", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T14:05:12.477", "Id": "40095", "Score": "5", "Tags": [ "objective-c", "web-services", "sync" ], "Title": "Synchronization with remote web service" }
40095
<p>I have a (control engineering) controller. These controllers usually need several parameters to do their thing, and in my application it is desirable that these parameters can be changed while the controller is running - in a thread safe and well defined manner.</p> <p>I came up with this design (extremely simplified):</p> <pre><code>// This is the class that the user instanciates. public class Controller { public ControllerInfo Info { get; set; } public void Start() { ... } public void Stop() { ... } private ControllerBody body = new ControllerBody(); private void ControllerThreadProc() { while (true) { var elapsedTime_ms = ...; var currentInfo = this.Info; // the actual calculation is done in another class this.body.SingleStep(currentInfo, elapsedTime_ms); Thread.Sleep(currentInfo.SampleTime_ms); } } } // This exists as a separate class so it is possible to test the // mathematical model without having to do it in real-time. public class ControllerBody { public void SingleStep(ControllerInfo info, long elapsedTime_ms) { var referenceValue = info.ReferenceValueGetter(); var calculationResult = math; info.ControlValueSetter(calculationResult); } } // Immutable class that contains all the info necessary to do stuff. public class ControllerInfo { public Func&lt;double&gt; ReferenceValueGetter { get; private set; } public Action&lt;double&gt; ControlValueSetter { get; private set; } public int SampleTime_ms { get; private set; } public double SomeConstant { get; private set; } public double OtherConstant { get; private set; } ... public ControllerInfo(/* 1 argument per property :( */) { /* many assignments */ } } </code></pre> <p>Usage example:</p> <pre><code>var controller = new Controller(); controller.Info = new ControllerInfo(/* values */); controller.Start(); // later: controller.Info = new ControllerInfo(/* new values */); // Application is done: controller.Stop(); </code></pre> <p>Again, it should be possible to change the controller while it is running. Therefore I gave <code>Controller</code> a publicly settable <code>ControllerInfo</code>.</p> <p>However, if the user decides to change the values of <code>SomeConstant</code> <strong>and</strong> <code>OtherConstant</code> in this example, it must be guaranteed that no calculation step is executed where only <em>one</em> of these are changed. In other words, changing a bunch of parameters must be an atomic operation. That's why <code>ControllerInfo</code> is not mutable.</p> <p>I have identified 2 downsides to this architecture:</p> <ol> <li><p>If I add another mathematical constant to <code>ControllerInfo</code>, I have to add (1) a property, (2) a parameter to the constructor (can be forgotten even if (1) has been done!), and (3) an assigment inside the constructor (can be forgotten even if (1) and (2) have been done!).</p></li> <li><p>If the user wants to change a parameter while the controller is running, they must make another tedious constructor call, passing in values that have changed, as well as values that haven't changed.</p></li> </ol> <p>To get around the usability problem, I considered introducing a <code>ControllerInfoFactory</code> class, which is basically a mutable copy of <code>ControllerInfo</code>:</p> <pre><code>public class ControllerInfoFactory { public (SamePropertiesAsControllerInfo) { get; set; } public ControllerInfo CreateControllerInfo() { return new ControllerInfo(/* pass all parameters from this */); } } </code></pre> <p>However, that makes the first problem even worse: For each property, I now also have to add the property to <code>ControllerInfoFactory</code>. Luckily, this time it's not possible to forget updating the <code>CreateControllerInfo</code> method as long as the <code>ControllerInfo</code> constructor has already been updated.</p> <p>Now to code review:</p> <ol> <li>Does this design make sense? Is the usability OK?</li> <li>Can the large amount of repetitive code per property be reduced?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T21:39:14.190", "Id": "67429", "Score": "0", "body": "Why is this tagged 'Java'? It appears to be exclusively C# code. From what I understand, the threading mechanisms and classes in the two languages are rather different." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T22:50:58.687", "Id": "67431", "Score": "0", "body": "@RoddyoftheFrozenPeas Because I could think of no difference between the languages that is relevant to this question. I chose to settle for the C# syntax for the code samples simply because the property notation seemed more concise. I could have just used a UML class diagram instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T01:42:22.037", "Id": "67444", "Score": "0", "body": "Removed Java tag, because a logical answer for a Java question of this sort would be to use java.util.concurrent.* - and there's no Java code to review" } ]
[ { "body": "<p>Another option is to create ControllerInfo with mutable properties and a Clone method which would return a copy of the instance.</p>\n\n<p>Then on the ControllerInfo Info set, simply call the Clone method and set _info to the clone of the object passed in.</p>\n\n<pre><code>private ControllerInfo _info;\n\npublic Info\n{\n get { return _info; }\n set { _info = value.Clone(); }\n}\n</code></pre>\n\n<p>To be clearer you can do away with Info as a property and instead code a method</p>\n\n<pre><code>public Controller SetInfo(ControllerInfo info)\n{\n _info = info.Clone(); \n return this;\n}\n</code></pre>\n\n<p>Doing away with \"get\" semantics for Info, is a good idea, as you do not want the interface to suggest that a get followed by mutating the Info object would reflect the changes in the Controller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T20:52:58.810", "Id": "70776", "Score": "1", "body": "BTW, you can implement `Clone()` using [`MemberwiseClone()`](http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone), which would avoid any repetition." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T08:28:05.080", "Id": "40144", "ParentId": "40096", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T14:26:19.787", "Id": "40096", "Score": "6", "Tags": [ "c#", "thread-safety", "immutability" ], "Title": "Allow changing the properties of a mutable controller in a thread safe way" }
40096
<p>What's the best way to format a number?</p> <ul> <li>If decimal is less than <code>2</code> digits, add zero to make it <code>2</code> decimals</li> <li>If more than <code>4</code>, truncate to <code>4</code> decimals</li> <li><p>If <code>3</code> decimals, keep it to <code>3</code> decimals</p> <pre><code>14 =&gt; 14.00 14.1 =&gt; 14.10 14.123 =&gt; 14.123 14.12347 =&gt; 14.1234 </code></pre></li> </ul> <p><strong>I don't want rounding to happen</strong></p> <pre><code>if (number !== 0) { nParts = number.toString().split('.'); if (nParts[1]) { if (nParts[1].length &gt; 4) { nParts = 4; } else if (nParts[1].length &lt; 3) { nParts = 2; } else { nParts = 3; } } else { nParts = 2; } } number = number.toFixed(nParts); </code></pre> <p>Help me improve on this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:53:01.553", "Id": "67380", "Score": "2", "body": "As I interpret it, 14.99999 → '14.9999'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T01:39:41.203", "Id": "67443", "Score": "2", "body": "toString().split('.') isn't going to work reliably. Consider that some cultures write their numbers using a comma for a decimal `987,24`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:04:43.330", "Id": "67482", "Score": "0", "body": "@kleinfreund Right" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:05:10.377", "Id": "67483", "Score": "0", "body": "@200_success Correct" } ]
[ { "body": "<p>since you don't want rounding, treat as string rather than number... </p>\n\n<pre><code>function strange(number){\n var n=0;\n if (number !== 0) {\n nParts = number.toString().split(/\\.|,/);\n if (nParts[1]){\n n=nParts[1].length;\n n = n &lt;=2 ? 2 : n==3 ? 3 : 4;\n nParts[1] = nParts[1] + '0'\n }else{\n n=2;\n nParts[1]='00';\n }\n } \n return nParts[0] + '.' + nParts[1].slice(0,n);\n}\n\n;strange(14);\n;strange(14.1);\n;strange(14.123);\n;strange(14.12347);\n\n/*\n14 =&gt; 14.00\n14.1 =&gt; 14.10\n14.123 =&gt; 14.123\n14.12347 =&gt; 14.1234\n*/\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T05:55:00.823", "Id": "40139", "ParentId": "40097", "Score": "2" } } ]
{ "AcceptedAnswerId": "40139", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T14:46:09.753", "Id": "40097", "Score": "8", "Tags": [ "javascript", "formatting", "floating-point" ], "Title": "Number format in JavaScript" }
40097
<p>I keep running into the same pattern with code using promises in javascript.</p> <p>When writing a function which takes a promise and returns a promise, obviously I want to reject the promise I'm returning when the promise I received is rejected (and usually I want to pass the error down the chain verbatim). This results in a fair amount of boilerplate:</p> <pre><code>var fs = require ('fs'); var when = require ('when'); var nodefn = require ("when/node/function"); var get_some_data = function (filename) { return nodefn.call (fs.readFile, filename); }; var parse_some_data = function (filename) { var deferred = when.defer (); var input = get_some_data (filename); input.then (function (data) { // imagine some complicated but synchronous process here which // may also call deferred.reject() if something goes wrong. deferred.resolve (JSON.parse (data)); }, function (error) { deferred.reject (error); }); return deferred.promise; }; var do_something = function (filename) { var deferred = when.defer (); var input = parse_some_data (filename); input.then (function (data) { // imagine some complicated but synchronous process here which // may also call deferred.reject() if something goes wrong. data['foo'] = 'bar'; deferred.resolve (data); }, function (error) { deferred.reject (error); }); return deferred.promise; }; </code></pre> <p>Is there a better way to structure this code? Do promise libraries have features which I'm not using, which would reduce the boilerplate? (The above code uses when from cujo.js, but if other promise libraries have better solutions I'm interested in hearing about them).</p>
[]
[ { "body": "<p>You're making more work for yourself than necessary. </p>\n\n<p>Check this out:</p>\n\n<pre><code>var fs = require('fs');\nvar nodefn = require(\"when/node/function\");\n\nvar get_some_data = function(filename) {\n return nodefn.call(fs.readFile, filename);\n};\n\nvar parse_some_data = function(filename, throwError) {\n return get_some_data(filename).then(function(data) {\n // Mimic a synchronous error\n if (throwError) {\n throw new Error('Error parsing data')\n }\n\n return JSON.parse(data);\n });\n};\n\nvar stringify_some_data = function(filename, throwParseError, throwLogError) {\n return parse_some_data(filename, throwParseError).then(function(parsedData) {\n // Mimic a synchronous error\n if (throwLogError) {\n throw new Error('Error stringifying data.');\n }\n\n return JSON.stringify(parsedData);\n });\n};\n\nvar onSuccess = function(dataString) {\n console.log('Success! ' + dataString);\n};\nvar onError = function(err) {\n console.log('Error! ' + err.message);\n};\n\n// \"Success! { \"data\": \"obj\" }\"\nstringify_some_data('./data.json').then(onSuccess, onError);\n\n// \"Error! ENOENT, open './not_a_file.json'\"\nstringify_some_data('./not_a_file.json').then(onSuccess, onError);\n\n// \"Error! Error parsing data\"\nstringify_some_data('./data.json', true).then(onSuccess, onError);\n\n// \"Error! Error stringifying data.\"\nstringify_some_data('./data.json', false, true).then(onSuccess, onError);\n</code></pre>\n\n<p>A couple of things to note:</p>\n\n<ul>\n<li>An error thrown anywhere in the promise chain (synchronous or not) will bubble down to your <code>onError</code> handler</li>\n<li>Return values of <code>Promise</code> objects are passed as arguments to the next <code>onSuccess</code> handler</li>\n</ul>\n\n<p>I'm still working on grokking how the <a href=\"http://promises-aplus.github.io/promises-spec/\" rel=\"nofollow\">Promise/A+</a> spec works. If you've used <code>jQuery.Deferred</code>, you should know that it does not follow the spec (which made using When.js a big learning curve for me). <a href=\"http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/\" rel=\"nofollow\">Here's a pretty decent article</a> explaining the Promise/A+ spec. Brian Cavalier (a When.js author) has <a href=\"http://blog.briancavalier.com/async-programming-part-1-it-s-messy/\" rel=\"nofollow\">some blog posts on asynchronous programming</a> which are worth reading, as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T16:05:20.950", "Id": "42965", "ParentId": "40100", "Score": "3" } } ]
{ "AcceptedAnswerId": "42965", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T14:55:30.383", "Id": "40100", "Score": "6", "Tags": [ "javascript", "error-handling", "promise" ], "Title": "Structuring functions receiving and returning promises?" }
40100
<p>In his <em><a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin#Bibliography" rel="noreferrer">Clean Code</a></em> book, <a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin" rel="noreferrer">Robert C. Martin</a> states that functions should do only one thing and one should not mix different levels of abstraction. So I started wondering whether the code below meets these requirements (I assume the answer is negative). Which one of the following code snippets is better?</p> <h3>Snippet 1</h3> <pre><code>public void run() { isRunning = true; try { serverSocket = new ServerSocket(port); } catch (IOException | IllegalArgumentException e) { System.out.println("Could not bind socket to given port number."); System.out.println(e); System.exit(1); } while(isRunning) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { logEvent("Could not accept incoming connection."); } Client client = new Client(clientSocket, this); connectedClients.put(client.getID(), client); Thread clientThread = new Thread(client); clientThread.start(); logEvent("Accepted new connection from " + clientSocket.getRemoteSocketAddress().toString()); client.send("@SERVER:HELLO"); } } </code></pre> <h3>Snippet 2</h3> <pre><code>public void run() { isRunning = true; createServerSocket(); while(isRunning) { Socket clientSocket = null; clientSocket = acceptConnection(); addClient(clientSocket); } } private void createServerSocket() { try { serverSocket = new ServerSocket(port); } catch (IOException | IllegalArgumentException e) { System.out.println("Could not bind socket to given port number."); System.out.println(e); System.exit(1); } } private Socket acceptConnection() { try { Socket clientSocket = serverSocket.accept(); } catch (IOException e) { logEvent("Could not accept incoming connection."); } return clientSocket; } private void addClient(Socket clientSocket) { Client client = new Client(clientSocket, this); connectedClients.put(client.getID(), client); Thread clientThread = new Thread(client); clientThread.start(); logEvent("Accepted new connection from " + clientSocket.getRemoteSocketAddress().toString()); client.send("@SERVER:HELLO"); } </code></pre> <p>However, splitting such simple code into multiple fragments seems like an overkill (although it's more readable - is it?). Besides, <code>createServerSockets</code> has side effects (<code>Sys.exit</code>) and <code>addClient</code> does too many things at once. Any advice?</p>
[]
[ { "body": "<p>The second one is much easier to read, it expresses the developers intent. At first sight I (as a maintainer or another developer in the same team, for example) just want a quick overview about the code and don't care about the details. (How the code creates a server socket, for example.) The second one exactly gives that.</p>\n\n<p>The <code>System.exit</code> side effect could be eliminated: throw an exception with a proper message (and don't forget to set the cause). Then handle the exception in the <code>run</code> method. I often see wrappings like the following:</p>\n\n<pre><code>public void run() {\n try {\n doRun();\n } catch (SomeException e) {\n // exception handling here\n }\n}\n</code></pre>\n\n<p>This often makes the <code>doRun()</code> simpler and easier to read.</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li>\n\n<pre><code>Socket clientSocket = null;\nclientSocket = acceptConnection();\n</code></pre>\n\n<p>Could be written as </p>\n\n<pre><code>Socket clientSocket = acceptConnection();\n</code></pre></li>\n<li><p>I'd modify the <code>createServerSocket()</code> method to return the server socket and the <code>acceptConnection()</code> method to have a <code>ServerSocket</code> parameter. It would remove the temporal coupling between the two methods. It would be impossible to call them in the wrong order.</p></li>\n<li><p>I've not written any threading code recently but I don't think that creating a separate thread for every client scale well. You might want to use an executor/thread pool there.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:13:56.363", "Id": "67377", "Score": "1", "body": "Thanks - I like the code you've proposed. Now it seems quite obvious, but I didn't come up with this idea earlier. I suppose I should also split addClient into more methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:20:39.113", "Id": "67378", "Score": "0", "body": "@prometh07: Yes, good point. I'd start with a `registerNewClient()` and a `sendInitialMessage()` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T00:01:55.083", "Id": "67437", "Score": "1", "body": "Since `clientSocket` can't be used anywhere else (i.e., the scope of the variable is so short), I wouldn't even bother with it. Why not just `addClient(acceptConnection())` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T00:07:42.550", "Id": "67438", "Score": "0", "body": "1) Yes. 2) Hmm... the serverSocket is a member variable. It is not used outside the run() method, so you (and rolfl) are right here. 3) The code is for educational purpose only, so I doubt there would be more than 5 users at once (it's a chat application - I will describe it more precisely in main post later)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T08:53:41.290", "Id": "67471", "Score": "1", "body": "@JoshuaTaylor: I think that's also fine. Two possible disadvantages: readers don't know the return type of `acceptConnection()`; using *step into* while debugging is a little bit harder." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:05:12.880", "Id": "40103", "ParentId": "40101", "Score": "19" } }, { "body": "<p>Your exception handling for <code>new ServerSocket(port)</code> could be better. I don't like the way <code>System.exit(1)</code> is buried in a helper function. The exception should be caught in such a way that it bypasses the <code>clientSocket</code>-accepting loop.</p>\n\n<p>Similarly, if <code>serverSocket.accept()</code> throws an exception, you log it, but blithely proceed to try to create a client thread anyway. Instead, the client-thread-creating code should be inside the <code>try</code> block, so that the exception would cause it to be skipped.</p>\n\n<p>Here is a preliminary rearrangement to fix the exception handling.</p>\n\n<pre><code>public void run() { \n try {\n serverSocket = new ServerSocket(port);\n\n isRunning = true;\n while (isRunning) {\n try {\n Socket clientSocket = serverSocket.accept();\n Client client = new Client(clientSocket, this);\n connectedClients.put(client.getID(), client);\n Thread clientThread = new Thread(client);\n clientThread.start();\n logEvent(\"Accepted new connection from \" + clientSocket.getRemoteSocketAddress().toString());\n // The \"hello\" should be sent by the clientThread code instead\n // client.send(\"@SERVER:HELLO\");\n } catch (IOException e) {\n logEvent(\"Could not accept incoming connection.\");\n }\n }\n } catch (IOException | IllegalArgumentException e) {\n System.out.println(\"Could not bind socket to given port number.\");\n System.out.println(e);\n System.exit(1);\n }\n}\n</code></pre>\n\n<p>If you would like to offload some responsibility from this method, you could create <a href=\"https://stackoverflow.com/a/15541866/1157100\">\"client tasks\" to be put into a \"client processing pool\"</a>. Then this <code>run()</code> method could be wonderfully generic.</p>\n\n<p>As noted above, <code>client.send(\"@SERVER:HELLO\")</code> belongs in the <code>clientThread</code> code, not in this loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:20:22.993", "Id": "40104", "ParentId": "40101", "Score": "13" } }, { "body": "<p>I don't like either solution (or the currently suggested answers). In any application where you run a ServerSocket, I believe that the socket management should be done on the Main thread. This would avoid the exact situation where you have a <code>System.exit(1)</code>. The basic pattern for a server application is:</p>\n\n<pre><code>public static void main(String[] args) {\n // sort out the arguments, if any.\n int port = 12345; // default, args can override\n\n // open the ServerSocket to ensure you can reserve the port befor you do expensive setup.\n try (ServerSocket serverSocket = createServerSocket(port)) {\n // Initialize the system\n setup();\n\n listenForClients(serverSocket);\n\n } catch (IOException ioe) {\n // deal with exception\n // can do System.exit(1) in the main thread to set exit codes...\n // but my personal preference is to throw an exception from the main method.\n // whihc exits with 1, and still does a clean shutdown.\n } \n}\n</code></pre>\n\n<p>There are some things you are doing wrong with your ClientThread setup. If you want the client threads to die when the main thread stops then you should set them to be <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon%28boolean%29\">Daemon threads</a>:</p>\n\n<pre><code>Thread clientThread = new Thread(client);\nclientThread.setDaemon(true);\n</code></pre>\n\n<p>The Java system will terminate when all non-Daemon threads stop. If your only non-Daemon thread is the Main thread (it is always non-Daemon), then the system will exit cleanly when the main thread ends.</p>\n\n<p>You can use this to your advantage in a number of ways... including having a terminating variable like <code>AtomicBoolean isRunning = new AtomicBoolean(true)</code> which any thread can set to false, and the main thread will periodically check... (using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/channels/Selector.html\">Selector and a ServerSocketChannel</a> - an advanced concept)</p>\n\n<p>The bottom line is that you are not setting Daemon threads appropriately, and as a consequence, you need heavy-weight <code>System.exit(1)</code>. Your ServerSocket management should be on the main thread too (or, it is possible, to make it on the only non-Daemon thread by spawning it from the Main thread, and letting the main thread exit normally).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T19:34:22.860", "Id": "67405", "Score": "1", "body": "I'm going to add GUI later, so I think I need this separate thread." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:58:30.960", "Id": "40108", "ParentId": "40101", "Score": "9" } } ]
{ "AcceptedAnswerId": "40103", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T16:33:42.677", "Id": "40101", "Score": "29", "Tags": [ "java", "multithreading", "exception-handling", "socket", "comparative-review" ], "Title": "Java method - levels of abstraction" }
40101
<p>I have a repository class that impliments a repository Interface. In my Controllers I want a way to access the repository without creating constructors each time in the controller. So now all my Controllers have to do is inherit from Base. Any pitfalls to this, or how I can write it differently.</p> <pre><code>public class BaseController : Controller { public IRepository Repo {get;set;} public IStudentRepositroy StudentRepo {get;set;}; public BaseController() : this(new Repository(),new StudentRepository()) { } public BaseController(IRepository repo,IStudentRepository studentRepo) { Repo = repo; StudentRepo = studentRepo; } } </code></pre>
[]
[ { "body": "<p>This sounds exactly like a desire for Dependency Injection (using an <a href=\"https://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code\">IoC container</a>). ASP.NET MVC is perfectly setup for this already with plenty of containers out there for you to use!</p>\n\n<p>You can still have a base constructor take arguments if you wish but I would try and limit how many.</p>\n\n<p>So your controllers would look like:</p>\n\n<pre><code>public StudentController(IRepository repo,IStudentRepository studentRepo)\n : base(repo)\n{\n StudentRepo = studentRepo;\n}\n</code></pre>\n\n<p>So by using the IoC framework these will be automatically resolved to your desired class. By doing this, it opens up the opportunity to more easily inject mock classes into your controllers and further separates them conceptually from implementation detail of the repositories. Although I typically do not Unit test my controllers (as I try to keep them as skinny as possible), it would also make unit testing easier.</p>\n\n<p>Typically you might do this in the Global.ascx or in the App_Start folder. You can get most DI frameworks by using <a href=\"http://www.nuget.org/%E2%80%8E\" rel=\"noreferrer\">Nuget</a> packages (which I would recommend). There are many out there but here are a couple of examples from ones I have dealt with in the past.</p>\n\n<h2>Autofaq</h2>\n\n<pre><code>public class AutofaqConfig\n{\n public static void Configure()\n {\n var builder = new ContainerBuilder();\n builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();\n\n RegisterRepositories(builder);\n\n var container = builder.Build();\n DependencyResolver.SetResolver(new AutofacDependencyResolver(container));\n }\n\n private static void RegisterRepositories(ContainerBuilder builder)\n { \n builder.RegisterType&lt;StudentRepository&gt;().As&lt;IStudentRepository&gt;();\n // And any other repositories here\n }\n}\n\nAnd in your global ascx\n\npublic class MvcApplication : System.Web.HttpApplication\n{\n protected void Application_Start()\n {\n AreaRegistration.RegisterAllAreas(); \n FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);\n RouteConfig.RegisterRoutes(RouteTable.Routes);\n BundleConfig.RegisterBundles(BundleTable.Bundles);\n\n AutofaqConfig.Configure();\n }\n}\n</code></pre>\n\n<h2>Ninject (Using the MVC3 ninject module)</h2>\n\n<pre><code>public static class NinjectWebCommon \n{\n private static readonly Bootstrapper bootstrapper = new Bootstrapper();\n\n /// &lt;summary&gt;\n /// Starts the application\n /// &lt;/summary&gt;\n public static void Start() \n {\n DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));\n DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));\n bootstrapper.Initialize(CreateKernel);\n }\n\n /// &lt;summary&gt;\n /// Stops the application.\n /// &lt;/summary&gt;\n public static void Stop()\n {\n bootstrapper.ShutDown();\n }\n\n /// &lt;summary&gt;\n /// Creates the kernel that will manage your application.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;The created kernel.&lt;/returns&gt;\n private static IKernel CreateKernel()\n {\n var kernel = new StandardKernel();\n kernel.Bind&lt;Func&lt;IKernel&gt;&gt;().ToMethod(ctx =&gt; () =&gt; new Bootstrapper().Kernel);\n kernel.Bind&lt;IHttpModule&gt;().To&lt;HttpApplicationInitializationHttpModule&gt;();\n\n RegisterServices(kernel);\n\n // Install our Ninject-based IDependencyResolver into the Web API config\n GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);\n\n return kernel;\n }\n\n /// &lt;summary&gt;\n /// Load your modules or register your services here!\n /// &lt;/summary&gt;\n /// &lt;param name=\"kernel\"&gt;The kernel.&lt;/param&gt;\n private static void RegisterServices(IKernel kernel)\n {\n kernel.Bind&lt;StudentRepository&gt;().To&lt;IStudentRepository&gt;();\n } \n}\n</code></pre>\n\n<h2>Using Unity (Using Unit.MVC4)</h2>\n\n<pre><code>public class UnityConfig\n{\n #region Unity Container\n private static Lazy&lt;IUnityContainer&gt; container = new Lazy&lt;IUnityContainer&gt;(() =&gt;\n {\n var container = new UnityContainer();\n RegisterTypes(container);\n return container;\n });\n\n /// &lt;summary&gt;\n /// Gets the configured Unity container.\n /// &lt;/summary&gt;\n public static IUnityContainer GetConfiguredContainer()\n {\n return container.Value;\n }\n #endregion\n\n /// &lt;summary&gt;Registers the type mappings with the Unity container.&lt;/summary&gt;\n /// &lt;param name=\"container\"&gt;The unity container to configure.&lt;/param&gt;\n /// &lt;remarks&gt;There is no need to register concrete types such as controllers or API controllers (unless you want to \n /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.&lt;/remarks&gt;\n public static void RegisterTypes(IUnityContainer container)\n {\n // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.\n // container.LoadConfiguration();\n\n // Repositories\n container.RegisterType&lt;IStudentRepository, StudentRepository&gt;();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T09:18:17.450", "Id": "67472", "Score": "1", "body": "The thing to remember is any extra param in your base class needs to be mirrored in all your controllers constructors. We've done this in the past, where we have had a basecontroller with say 20 controllers , and then we add a parm on the base constructor. now you need to update all 20 controllers and chain it through. To stop this we created a wrapper class, called \"ControllerPayload\" and only pass that through. Anything we need to add, like your repo or whatever, we add as properties on this object. Now you can maintain it a lot easier, as you only need to updated the object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:39:15.750", "Id": "67570", "Score": "0", "body": "Nice idea spaceman. One reason why I like keeping parameters in controllers however is it allows me to help identify perhaps design issues. If I find my controller requiring more than 3-4 parameters I start to ask myself what's going on and is there a better way. Your idea is sound though as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-01T00:35:22.153", "Id": "130252", "Score": "0", "body": "I'm trying to figure this out myself. [This article](http://www.davepaquette.com/archive/2013/03/27/managing-entity-framework-dbcontext-lifetime-in-asp-net-mvc.aspx) recommends using dependency injection and also adding the repository item (DBContext, in this case) as a constructor to the controller. I have a base controller that accepts this and saves it in an instance variable. However, now I must add this same constructor to every controller that derives from the base controller. I wish there was a way that I didn't need to do that for the reasons given above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-01T07:01:15.363", "Id": "130268", "Score": "0", "body": "@JonathanWood Most DI frameworks accept property injection as far as I'm aware, however from reading it's better practice to have constructor injection to be more explicit about the controllers required dependencies. If a dbContext is not needed in every controller is not inheriting it an option?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-04T22:06:34.920", "Id": "463938", "Score": "0", "body": "Note that-for anyone new to this-if using *Unity*: You still have to put `UnityConfig.RegisterContainer();` in the *Global.ascx.cs* `App_Start`, & need a function in the *UnityConfig* class (put in App_Start folder): `public static void RegisterContainer()\n {\n var container = new UnityContainer();\n\n container.RegisterType<IDataRepository, DataRepository>(new HierarchicalLifetimeManager());\n\n DependencyResolver.SetResolver(new UnityDependencyResolver(container));\n\n }` and references: `Microsoft.Practices.Unity` and `Unity.Mvc3` (or 4 or 5)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T18:48:28.297", "Id": "40112", "ParentId": "40102", "Score": "11" } }, { "body": "<p>Create a service locator concept, so the object creation part will be handled by it. There is no need to always create objects. Use unit of works logic in the web config file. Here all the mappings (<code>iClass int = new Class()</code>), so everything will be on track.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-10T13:05:06.030", "Id": "81926", "Score": "5", "body": "I don't have enough knowledge in C#, but your answer seems to me like it would be better with more explanation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-10T12:36:23.940", "Id": "46808", "ParentId": "40102", "Score": "0" } } ]
{ "AcceptedAnswerId": "40112", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T17:02:14.777", "Id": "40102", "Score": "14", "Tags": [ "c#", "asp.net", "mvc", "controller" ], "Title": "Using a BaseController in MVC asp.net to reuse the repository" }
40102
<p>I've made an attempt at writing class wrappers around basic OpenGL objects to make managing them easier and more intuitive. Writing a generic one for program uniforms proved to require a little bit more effort than the other objects, due to there being different OpenGL functions for manipulating uniforms of different types. So, I came upon this solution, using templates and inheritance:</p> <pre><code>/* An attempt at type-safe OpenGL shader uniform manipulation _UniformBase forms the base class that the implementation for each data type derives from */ template &lt;class T&gt; class _UniformBase { protected: // Each program-uniform pair is stored in a forward_list std::forward_list&lt;std::pair&lt;GLuint,GLint&gt;&gt; Uniforms; virtual void SetUniform(const T&amp;, const GLint&amp;) const = 0; // Must be implemented in child classes virtual void SetUniform_DSA(const T&amp;, const GLuint&amp;, const GLint&amp;) const = 0; public: // I don't see the necessity of a copy constructor with the way that I use this class _UniformBase() {} virtual ~_UniformBase() {} // Gets a handle to the OpenGL uniform, given the program and the uniform name int Register(_Program Program_in, const char *Name_in) { GLint Location; GLuint Program = Program_in.GetHandle(); if((Location = glGetUniformLocation(Program, Name_in)) == -1) return 1; Uniforms.push_front(std::pair&lt;GLuint, GLint&gt;(Program, Location)); return 0; } // Clears out the uniform handle list...haven't used it at all void ClearUniforms() { Uniforms.clear(); } // Sets all stored uniforms to Data_in void SetData(const T &amp;Data_in) { // Can use GL_EXT_direct_state_access extension or plain OpenGL // Guess which one I like better #ifdef DIRECT_STATE_ACCESS for(auto &amp;i : Uniforms) { SetUniform_DSA(Data_in, i.first, i.second); } #else Data = Data_in; GLuint Initial; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)(&amp;Initial)); GLuint Previous = Initial; for(auto &amp;i : Uniforms) { if(i.first != Previous) { glUseProgram(i.first); Previous = i.first; } SetUniform(&amp;Data_in, i.second); } if(Initial != Previous) glUseProgram(Initial); #endif } }; /* Just a "dummy" class that allows me to make the specializations for each datatype. Attempting to instantiate an unimplemented datatype will result in a compile-time error due to SetUniform and SetUniform_DSA being pure virtual (which is what I want) */ template &lt;class T&gt; class _Uniform : public _UniformBase&lt;T&gt; { }; /* Here are the implementations of the SetUniform and SetUniform_DSA methods Each uses an OpenGL function to set the program uniform */ template &lt;&gt; class _Uniform&lt;glm::mat4&gt; : public _UniformBase&lt;glm::mat4&gt; { protected: void SetUniform(const glm::mat4&amp; Data, const GLint &amp;Uniform_in) const { glUniformMatrix4fv(Uniform_in, 1, GL_FALSE, glm::value_ptr(Data)); } void SetUniform_DSA(const glm::mat4&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const { glProgramUniformMatrix4fvEXT(Program_in, Uniform_in, 1, GL_FALSE, glm::value_ptr(Data)); } }; template &lt;&gt; class _Uniform&lt;glm::vec4&gt; : public _UniformBase&lt;glm::vec4&gt; { protected: void SetUniform(const glm::vec4&amp; Data, const GLint &amp;Uniform_in) const { glUniform4fv(Uniform_in, 1, glm::value_ptr(Data)); } void SetUniform_DSA(const glm::vec4&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const { glProgramUniform4fvEXT(Program_in, Uniform_in, 1, glm::value_ptr(Data)); } }; template &lt;&gt; class _Uniform&lt;glm::vec3&gt; : public _UniformBase&lt;glm::vec3&gt; { protected: void SetUniform(const glm::vec3&amp; Data, const GLint &amp;Uniform_in) const { glUniform3fv(Uniform_in, 1, glm::value_ptr(Data)); } void SetUniform_DSA(const glm::vec3&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const { glProgramUniform3fvEXT(Program_in, Uniform_in, 1, glm::value_ptr(Data)); } }; template &lt;&gt; class _Uniform&lt;glm::vec2&gt; : public _UniformBase&lt;glm::vec2&gt; { protected: void SetUniform(const glm::vec2&amp; Data, const GLint &amp;Uniform_in) const { glUniform2fv(Uniform_in, 1, glm::value_ptr(Data)); } void SetUniform_DSA(const glm::vec2&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const { glProgramUniform2fvEXT(Program_in, Uniform_in, 1, glm::value_ptr(Data)); } }; template &lt;&gt; class _Uniform&lt;float&gt; : public _UniformBase&lt;float&gt; { protected: void SetUniform(const float&amp; Data, const GLint &amp;Uniform_in) const { glUniform1fv(Uniform_in, 1, &amp;Data); } void SetUniform_DSA(const float&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const { glProgramUniform1fvEXT(Program_in, Uniform_in, 1, &amp;Data); } }; template &lt;&gt; class _Uniform&lt;int&gt; : public _UniformBase&lt;int&gt; { protected: void SetUniform(const int&amp; Data, const GLint &amp;Uniform_in) const { glUniform1iv(Uniform_in, 1, &amp;Data); } void SetUniform_DSA(const int&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const { glProgramUniform1ivEXT(Program_in, Uniform_in, 1, &amp;Data); } }; </code></pre> <p>This allows me to use a pretty simple interface for manipulating these:</p> <pre><code>_Uniform&lt;glm::vec4&gt; Test; Test.Register(TheProgram, "SomeVec4"); Test.SetData(glm::vec4(1.0f, 2.0f, 3.0f, 4.0f); </code></pre> <p>maintaining a degree of type safety.</p> <p>I like the interface as it stands, as it does what I want it to do. However, I am looking for suggestions for improvement in the implementation, as it is kinda messy.</p>
[]
[ { "body": "<p>I decided to invert the class scheme: instead of having a <code>_UniformBase</code> class and having each specialization derive from it, I now have a single <code>_Uniform</code> class which owns a copy of a <code>_UniformHandler</code> class that provides the specialized uniform-setting functions. This way, I have static polymorphism without too much complication, and with the same external interface.</p>\n\n<pre><code>template &lt;class T&gt;\nclass _UniformHandler;\n\ntemplate&lt;&gt;\nclass _UniformHandler&lt;glm::mat4&gt;\n{\npublic:\n inline void SetUniform(const glm::mat4&amp; Data, const GLint &amp;Uniform_in) const\n {\n glUniformMatrix4fv(Uniform_in, 1, GL_FALSE, glm::value_ptr(Data));\n }\n inline void SetUniform_DSA(const glm::mat4&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const\n {\n glProgramUniformMatrix4fvEXT(Program_in, Uniform_in, 1, GL_FALSE, glm::value_ptr(Data));\n }\n};\ntemplate &lt;&gt;\nclass _UniformHandler&lt;glm::vec4&gt;\n{\npublic:\n inline void SetUniform(const glm::vec4&amp; Data, const GLint &amp;Uniform_in) const\n {\n glUniform4fv(Uniform_in, 1, glm::value_ptr(Data));\n }\n inline void SetUniform_DSA(const glm::vec4&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const\n {\n glProgramUniform4fvEXT(Program_in, Uniform_in, 1, glm::value_ptr(Data));\n }\n};\n\ntemplate &lt;&gt;\nclass _UniformHandler&lt;glm::vec3&gt;\n{\npublic:\n inline void SetUniform(const glm::vec3&amp; Data, const GLint &amp;Uniform_in) const\n {\n glUniform3fv(Uniform_in, 1, glm::value_ptr(Data));\n }\n inline void SetUniform_DSA(const glm::vec3&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const\n {\n glProgramUniform3fvEXT(Program_in, Uniform_in, 1, glm::value_ptr(Data));\n }\n};\n\ntemplate &lt;&gt;\nclass _UniformHandler&lt;glm::vec2&gt;\n{\npublic:\n inline void SetUniform(const glm::vec2&amp; Data, const GLint &amp;Uniform_in) const\n {\n glUniform2fv(Uniform_in, 1, glm::value_ptr(Data));\n }\n inline void SetUniform_DSA(const glm::vec2&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const\n {\n glProgramUniform2fvEXT(Program_in, Uniform_in, 1, glm::value_ptr(Data));\n }\n};\n\ntemplate &lt;&gt;\nclass _UniformHandler&lt;float&gt;\n{\npublic:\n inline void SetUniform(const float&amp; Data, const GLint &amp;Uniform_in) const\n {\n glUniform1fv(Uniform_in, 1, &amp;Data);\n }\n inline void SetUniform_DSA(const float&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const\n {\n glProgramUniform1fvEXT(Program_in, Uniform_in, 1, &amp;Data);\n }\n};\n\ntemplate &lt;&gt;\nclass _UniformHandler&lt;int&gt;\n{\npublic:\n inline void SetUniform(const int&amp; Data, const GLint &amp;Uniform_in) const\n {\n glUniform1iv(Uniform_in, 1, &amp;Data);\n }\n inline void SetUniform_DSA(const int&amp; Data, const GLuint &amp;Program_in, const GLint &amp;Uniform_in) const\n {\n glProgramUniform1ivEXT(Program_in, Uniform_in, 1, &amp;Data);\n }\n};\n\ntemplate &lt;class T&gt;\nclass _Uniform\n{\nprotected:\n // Each program-uniform pair is stored in a forward_list\n std::forward_list&lt;std::pair&lt;GLuint,GLint&gt;&gt; Uniforms;\n _UniformHandler&lt;T&gt; UniformHandler;\n\npublic:\n _Uniform() {}\n _Uniform(const _Uniform&amp; cp): Uniforms(cp.Uniforms) {}\n _Uniform(_Uniform&amp;&amp; mv): Uniforms(std::move(mv.Uniforms)) {}\n _Uniform&amp; operator=(const _Uniform&amp; cp)\n {\n Uniforms = cp.Uniforms;\n return *this;\n }\n _Uniform&amp; operator=(_Uniform&amp;&amp; mv)\n {\n std::swap(Uniforms, mv.Uniforms);\n return *this;\n }\n ~_Uniform() {}\n\n // Gets a handle to the OpenGL uniform, given the program and the uniform name\n int Register(_Program Program_in, const char *Name_in)\n {\n GLint Location;\n GLuint Program = Program_in.GetHandle();\n if((Location = glGetUniformLocation(Program, Name_in)) == -1) return 1;\n Uniforms.push_front(std::pair&lt;GLuint, GLint&gt;(Program, Location));\n return 0;\n }\n\n // Clears out the uniform handle list...haven't used it at all\n void ClearUniforms()\n {\n Uniforms.clear();\n }\n\n // Sets all stored uniforms to Data_in\n void SetData(const T &amp;Data_in)\n {\n // Can use GL_EXT_direct_state_access extension or plain OpenGL\n // Guess which one I like better\n #ifdef DIRECT_STATE_ACCESS\n for(auto &amp;i : Uniforms)\n {\n UniformHandler.SetUniform_DSA(Data_in, i.first, i.second);\n }\n #else\n Data = Data_in;\n GLuint Initial;\n glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)(&amp;Initial));\n GLuint Previous = Initial;\n for(auto &amp;i : Uniforms)\n {\n if(i.first != Previous)\n {\n glUseProgram(i.first);\n Previous = i.first;\n }\n UniformHandler.SetUniform(&amp;Data_in, i.second);\n }\n if(Initial != Previous) glUseProgram(Initial);\n #endif\n }\n\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-02T18:18:19.637", "Id": "40685", "ParentId": "40117", "Score": "3" } }, { "body": "<p>Just came across your question, and since you never got any replies from other users, I'll give you a few comments:</p>\n\n<p>The first thing that bothers me with your code is the naming you've chosen. Why appending every class name with <code>_</code>? Did you know that a name beginning with an underscore and an uppercase letter is reserved in <strong>any scope</strong> for use by the C++ implementation? Read <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">this thread</a> for a full discussion.</p>\n\n<hr>\n\n<p>Empty constructors/virtual destructor:</p>\n\n<pre><code>_UniformBase() {}\nvirtual ~_UniformBase() {}\n</code></pre>\n\n<p>Can be defaulted in C++11, which is now preferred:</p>\n\n<pre><code>_UniformBase() = default;\nvirtual ~_UniformBase() = default;\n</code></pre>\n\n<p>But I don't think you need to define a default constructor at all. Don't declared it if it is not needed.</p>\n\n<hr>\n\n<p>The logic of the return value of <code>_Uniform::Register()</code> is the opposite of what most people would expect. It return 0 on success and 1 on error. This is not a good idea, as most programmers would call it like this: <code>if (unif.Register( ... ))</code>, thinking it returns a bool, and then wonder why it always fails. It should return a <code>bool</code> and <code>true</code> on success, <code>false</code> on failure.</p>\n\n<hr>\n\n<p>You might want to run some tests an profiling and see if there isn't a gain in switching to an <code>std::vector</code> instead of an <code>std::forward_list</code> for storage. The forward list will incur a lot of memory allocations, plus data will be scattered through the memory. Lists make very good containers when you need to insert and remove frequently from arbitrary positions. For a storage that changes <em>infrequently</em>, a <code>vector</code> is usually better. In a shader program/uniform-var list, you only set up the set of variables once, when the the program is created, so I'm almost certain a vector would be better in this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-22T01:28:28.993", "Id": "123086", "Score": "1", "body": "This was unexpected! Thanks for your input, makes me want to get back into OpenGL programming. You're right about all that, I made really odd decisions for some reason. But, I definitely wasn't aware of the underscore-followed-by-capital rule, only the double-underscore rule; good to know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-22T01:33:10.413", "Id": "123087", "Score": "1", "body": "@mebob - Glad I could help `;)`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-22T01:19:38.967", "Id": "67500", "ParentId": "40117", "Score": "2" } } ]
{ "AcceptedAnswerId": "67500", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T19:21:45.473", "Id": "40117", "Score": "6", "Tags": [ "c++", "c++11", "template", "opengl", "type-safety" ], "Title": "Type safe program uniform manipulation in OpenGL" }
40117
<p>I'm looking for bugs, ways to make it more portable or standardized, improvements of any kind. Seems to do what it is supposed to on my Ubuntu 12.04 PC.</p> <pre><code>/* VLC-Watchdog v2 * * A fix for stopped VLC Media Player inhibiting the power management * daemon and preventing screen saver and/or monitor power off. * * Takes start | stop as command line argument. * * Checks if VLC Media Player is running using pgrep. If VLC is found * to be running, queries the playback status through the DBus low level * API. If the playback status is found to be stopped, calls the Quit() * method via DBus. If VLC is found not to be running VLC-Watchdog sleeps * for 10 seconds then repeats all of the above. When VLC-Watchdog receives * the stop signal ("VLC-Watchdog stop" from the command line) it exits. */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;dbus/dbus.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;signal.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; static void skeleton_daemon(); int vlc_running(); void kill_vlc_if_stopped(int pid); void usage(char *pname); void sig_handler(int signo); extern int running = 1; int main(int argc, char *argv[]) { FILE *fp; int pid; //check command line arguments for validity if ((argc != 2) || ( (strcmp(argv[1], "start") != 0) &amp;&amp; (strcmp(argv[1], "stop") != 0))) usage(argv[0]); //start / run actions if (strcmp(argv[1], "start") == 0) { skeleton_daemon(); //daemonize //write the PID to a file for future reference fp = fopen("/tmp/vlcwatchdog.pid", "w"); fprintf(fp, "%d\n", getpid()); fclose(fp); //register signal handler if (signal(SIGUSR1, sig_handler) == SIG_ERR) { fprintf(stderr, "error while setting signal handler\n"); exit(1); } /* when first started and every 10 seconds thereafter, check if * VLC is running, check if it is stopped, ask it to Quit() if it * is stopped. Stop and exit when SIGUSR1 is received */ while (running) { if ((pid = vlc_running())) { kill_vlc_if_stopped(pid); } sleep(10); } //remove temporary file if (remove("/tmp/vlcwatchdog.pid") == -1) { fprintf(stderr, "error removing temporary file \ /tmp/vlcwatchdog.pid"); exit(1); } } //stop actions if (strcmp(argv[1], "stop") == 0) { //retrieve PID from file fp = fopen("/tmp/vlcwatchdog.pid", "r"); if (fscanf(fp, "%d", &amp;pid) != 1) fprintf(stderr, "fscanf failed\n"); fclose(fp); //issue stop signal to VLC-Watchdog daemon kill(pid, SIGUSR1); } exit(0); } /* deamonize the process */ static void skeleton_daemon() { pid_t pid; /* Fork off the parent process */ pid = fork(); /* An error occurred */ if (pid &lt; 0) exit(EXIT_FAILURE); /* Success: Let the parent terminate */ if (pid &gt; 0) exit(EXIT_SUCCESS); /* On success: The child process becomes session leader */ if (setsid() &lt; 0) exit(EXIT_FAILURE); /* Fork off for the second time*/ pid = fork(); /* An error occurred */ if (pid &lt; 0) exit(EXIT_FAILURE); /* Success: Let the parent terminate */ if (pid &gt; 0) exit(EXIT_SUCCESS); /* Set new file permissions */ umask(0); /* Change the working directory to the root directory */ /* or another appropriated directory */ if (chdir("/") != 0) { fprintf(stderr, "chdir failed\n"); exit(1); } /* Close all open file descriptors */ int x; for (x = sysconf(_SC_OPEN_MAX); x&gt;0; x--) { close (x); } } /* check if it is stopped, if so, tell it to Quit() */ void kill_vlc_if_stopped(int pid) { DBusConnection *conn; DBusError err; DBusMessage *method_call, *reply; DBusMessageIter iter, sub_iter; int arg_type = 0; const char *prop_iface = "org.mpris.MediaPlayer2.Player"; const char *prop_iface_method_name = "PlaybackStatus"; const char *pb_stat; char name[80], buf[80]; //append the pid to the name of the destination strcpy (name, "org.mpris.MediaPlayer2.vlc-"); sprintf (buf, "%d", pid); strcat (name, buf); dbus_error_init(&amp;err); // init error conn = dbus_bus_get(DBUS_BUS_SESSION, &amp;err); //connect to session bus //create the method call to be used to get playback status of VLC method_call = dbus_message_new_method_call(name, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties", "Get"); //put the method arguments on the message dbus_message_append_args(method_call, DBUS_TYPE_STRING, &amp;prop_iface, DBUS_TYPE_STRING, &amp;prop_iface_method_name, DBUS_TYPE_INVALID); //call the method, get the reply, check for error reply = dbus_connection_send_with_reply_and_block (conn, method_call, -1, &amp;err); if (reply == NULL) { fprintf(stderr, "Null Reply \n %s \n", err.message); dbus_error_free(&amp;err); exit(1); } //initialize an iterator pointing to arguments in reply message dbus_message_iter_init (reply, &amp;iter); //check the type of the first argument (should be variant) arg_type = dbus_message_iter_get_arg_type(&amp;iter); if (arg_type != DBUS_TYPE_VARIANT) { fprintf(stderr, "Expected variant, got %d\n", arg_type); exit(1); } //recurse into the variant container to get an iter to the string dbus_message_iter_recurse(&amp;iter, &amp;sub_iter); //check the type of the value in the variant (should be string) arg_type = dbus_message_iter_get_arg_type(&amp;sub_iter); if (arg_type != DBUS_TYPE_STRING) { fprintf(stderr, "Expected string, got %d\n", arg_type); exit(1); } //extract the value of the string from sub_iter dbus_message_iter_get_basic(&amp;sub_iter, &amp;pb_stat); //if VLC is stopped, tell it to close by calling Quit() if (strcmp("Stopped", pb_stat) == 0) { //initialize the Quit() method call message method_call = dbus_message_new_method_call(name, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2", "Quit"); //send the Quit() message, report error if any if (!dbus_connection_send(conn, method_call, NULL)) { fprintf (stderr, "Send of Quit() call message failed\n"); exit(1); } } return; } /* return PID of VLC if it is running, 0 otherwise */ int vlc_running() { FILE *fp; char s[64]; int pid; fp = popen("pgrep vlc", "r"); if (fp == NULL) { printf("NULL fp error\n"); fclose(fp); exit(1); } if (fgets(s, 9, fp) != NULL) { sscanf(s, "%d", &amp;pid); fclose(fp); return pid; } else { fclose(fp); return 0; } } /* Print the usage help then exit */ void usage(char *pname) { fprintf(stderr, "usage: %s start | stop\n", pname); exit(1); } /* Signal handler function */ void sig_handler(int signo) { if (signo == SIGUSR1) running = 0; return; } </code></pre> <p>This is the makefile</p> <pre><code>#-----------------------------------------------# # # VLC-Wathcdog Makefile # # using GCC C compiler # #-----------------------------------------------# # Variable Definitions ( *** denotes a required entry ) EXECUTABLE=VLC-Watchdog # *** name of finished program executable SOURCES=vlcwd.c # *** .c files separated by a space CC=gcc # which compiler to use CFLAGS= -g -Wall -O3 --std=gnu1x# compiler options LIBS=dbus-1 # libraries that need pkg-config OBJECTS=$(SOURCES:.c=.o) # Compiler flags: # -g -- Enable debugging # -Wall -- Turn on all warnings # -O3 -- make the maximum effort to optimize the code ifeq ($(strip $(LIBS)),) # or ifneq (... LIBFLAGS=#command-if-LIBS-empty else #command-if-LIBS-not-empty CFLAGS += `pkg-config --cflags $(LIBS)` LIBFLAGS= `pkg-config --libs $(LIBS)` endif all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(OBJECTS) -o $@ $(LIBFLAGS) .o: $(CC) $(CFLAGS) $&lt; -o $@ clean: rm $(OBJECTS) $(EXECUTABLE) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T23:47:54.410", "Id": "67435", "Score": "0", "body": "I'm adding error logging and testing if the .pid file exists before trying to open it during a stop." } ]
[ { "body": "<p>Just a few simple things:</p>\n\n<ol>\n<li><p>This:</p>\n\n<blockquote>\n<pre><code>strcpy (name, \"org.mpris.MediaPlayer2.vlc-\");\nsprintf (buf, \"%d\", pid);\nstrcat (name, buf);\n</code></pre>\n</blockquote>\n\n<p>can be written as</p>\n\n<pre><code>sprintf(name, \"%s%d\", \"org.mpris.MediaPlayer2.vlc-\", pid);\n</code></pre>\n\n<p>removes the need for <code>buf</code> and makes it a bit cleaner.</p></li>\n<li><p>In general your error logging is a bit adventurous. Sometimes you obtain the file pointer to the error log in which case you usually close it (but it's kinda ugly having to remember this) and sometimes you just log a string in which case you don't close the file pointer. You should be able to just do it with one function:</p>\n\n<pre><code>void log_error(const char* format, ...)\n{\n va_list args;\n FILE *errlog;\n\n errlog = fopen(\"/tmp/vlcwderr.log\", \"a\");\n\n va_start(args, format);\n vfprintf(errlog, format, args);\n va_end(args);\n\n fclose(errlog);\n return;\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:44:58.120", "Id": "67506", "Score": "0", "body": "Thank you. That va_ family is pretty handy. Never seen that before but then I'm self taught so that doesn't mean much lol" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:49:52.360", "Id": "40143", "ParentId": "40119", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T21:09:46.377", "Id": "40119", "Score": "8", "Tags": [ "c", "linux", "portability" ], "Title": "VLC media player watchdog daemon" }
40119
<p>I am currently working on a small website for my scuba diving club, and it needs a "simple" login system to allow members-only features etc.</p> <p>I've been using the php-login-minimal as the base for the PHP login: <a href="https://github.com/panique/php-login-minimal" rel="nofollow">https://github.com/panique/php-login-minimal</a> It works by creating a session cookie if a user is logged in. This works just perfectly well on my local XAMPP server, but when uploaded to my external domain (one.com), logging in does not always work. It is as if no session cookie is being set. Eventually, after a bunch of tries, it'll work. These troubles do not occur on localhost, however, so I might just have to contact the domain support about that.</p> <p>What I would also like to get feedback on, is if everything is done reasonably or if I should work on improving/changing various parts of my website system.</p> <p>Any feedback in general is greatly appreciated. Have never done much PHP/HTML, so would love to improve.</p> <p>Here's what a member-only page currently looks like:</p> <p><strong>members.php</strong> (shows the members in the diveclub, fetched from the MySQL db)</p> <pre><code>&lt;?php require_once('authorize.php'); ?&gt; &lt;!DOCTYPE html&gt; &lt;?php require_once('includes/load.php'); GLOBAL $db; require_once('includes/functions.php'); ?&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;link rel="stylesheet" type="text/css" href="css/stylesheet.css"&gt; &lt;title&gt;Medlemsliste - &lt;?php echo SITE_TITLE ?&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="header"&gt; &lt;div id="header-menu"&gt; &lt;img id="logo" src="img/nsdk_logo_header.png"&gt; &lt;ul id="main-menu"&gt; &lt;li&gt;&lt;a href="index.php"&gt;Forsiden&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="omklubben.php"&gt;Om klubben&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="kontakt.php"&gt;Kontakt&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;img id="top-image" src="img/header/foto.jpg"&gt; &lt;?php include("sidebar.php"); ?&gt; &lt;div id="content-container"&gt; &lt;span class="content-header"&gt;Medlemsliste&lt;/span&gt; &lt;div class="content"&gt; &lt;h1&gt;Medlemmer af NSDK&lt;/h1&gt; &lt;p&gt;Du kan sende mail til et medlem ved at sende en mail til &lt;code&gt;fornavn.efternavn@nsdk.dk&lt;/code&gt;, f.eks. &lt;a href="mailto:anders.and@nsdk.dk"&gt;anders.and@nsdk.dk&lt;/a&gt;. &lt;?php $is_moderator = (get_access_from_username($_SESSION['username']) &gt; 0); if ($is_moderator) echo '&lt;p&gt;&lt;b&gt;NB: Du er logget ind som et bestyrelsesmedlem og bliver derfor også oplyst adresse på medlemmer!&lt;/b&gt;&lt;/p&gt;'; ?&gt; &lt;!-- LIST BEGIN --&gt; &lt;table id="table-members" width="100%"&gt; &lt;tr&gt; &lt;th&gt;&lt;a href="members.php?order=firstname"&gt;Fornavn&lt;/a&gt;&lt;/th&gt; &lt;th&gt;&lt;a href="members.php?order=lastname"&gt;Efternavn&lt;/a&gt;&lt;/th&gt; &lt;th&gt;Tlf. nr.&lt;/th&gt; &lt;th&gt;&lt;a href="members.php?order=certificate"&gt;Certifikat&lt;/a&gt;&lt;/th&gt; &lt;?php if ($is_moderator) { ?&gt; &lt;th&gt;Adresse&lt;/th&gt; &lt;?php } ?&gt; &lt;/tr&gt; &lt;?php if (!empty($_GET['order'])) { if ($_GET['order'] == 'certificate') $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY certificate, lastname, firstname;'); else if ($_GET['order'] == 'lastname') $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY lastname, firstname;'); else if ($_GET['order'] == 'firstname') $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY firstname, lastname;'); else $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY lastname, firstname;'); } else $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY lastname, firstname;'); $members_amount = 0; while ($row = mysqli_fetch_array($queryResult)) { echo '&lt;tr&gt;'; echo '&lt;td&gt;'.$row['firstname'].'&lt;/td&gt;'; echo '&lt;td&gt;'.$row['lastname'].'&lt;/td&gt;'; echo '&lt;td&gt;'.$row['phone'].'&lt;/td&gt;'; echo '&lt;td&gt;'.$row['certificate'].'&lt;/td&gt;'; if ($is_moderator) { echo '&lt;td&gt;'.$row['address'].'&lt;/td&gt;'; } echo '&lt;/tr&gt;'; $members_amount++; } ?&gt; &lt;/table&gt; &lt;!-- LIST END --&gt; &lt;br&gt; &lt;p&gt;Antal medlemmer: &lt;?php echo '&lt;b&gt;'.$members_amount.'&lt;/b&gt;' ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>authorize.php</strong></p> <pre><code>&lt;?php require_once('includes/load.php'); require_once('includes/login.php'); $login = new Login(); if (!$login-&gt;isUserLoggedIn()) { // not logged in, redirect to login header('Location: http://www.nsdk.dk/ny/login.php'); echo "FEJL: Denne side kræver login!"; die(); } ?&gt; </code></pre> <p><strong>includes/load.php</strong></p> <pre><code>&lt;?php if (!file_exists('configuration.php')) { require_once('configuration_default.php'); } else { require_once('configuration.php'); } // initialize mysql db $db = new database(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); // https://github.com/panique/php-login-minimal // check for minimum php version if (version_compare(PHP_VERSION, '5.3.7', '&lt;')) { exit("Sorry, Simple PHP Login does not run on a PHP version smaller than 5.3.7 !"); } else if (version_compare(PHP_VERSION, '5.5.0', '&lt;')) { // if you are using PHP 5.3 or PHP 5.4 you have to include the password_api_compatibility_library.php // (this library adds the PHP 5.5 password hashing functions to older versions of PHP) require_once("libraries/password_compatibility_library.php"); } ?&gt; </code></pre> <p><strong>includes/login.php</strong> (only differs slightly from the original php-login-minimal)</p> <p><a href="https://github.com/panique/php-login-minimal/blob/master/classes/Login.php" rel="nofollow">https://github.com/panique/php-login-minimal/blob/master/classes/Login.php</a></p> <p><strong>includes/database.php</strong> (loaded from configuration.php)</p> <pre><code>&lt;?php class database { protected $dblink; protected $dbuser; protected $dbpassword; protected $dbname; protected $dbhost; // query result protected $result; function __construct($dbuser, $dbpassword, $dbname, $dbhost){ $this-&gt;dbuser = $dbuser; $this-&gt;dbpassword = $dbpassword; $this-&gt;dbname = $dbname; $this-&gt;dbhost = $dbhost; $this-&gt;connect(); } function connect(){ $this-&gt;dblink = mysqli_connect($this-&gt;dbhost, $this-&gt;dbuser, $this-&gt;dbpassword, $this-&gt;dbname) or die('Could not connect: ' . mysqli_error($link )); } function query($query){ $this-&gt;result = mysqli_query($this-&gt;dblink, $query) or die('Query failed: ' . mysqli_error($this-&gt;dblink)); return $this-&gt;result; } function get_row($query = null) { if ($query) { $this-&gt;query($query); } else { return null; } } } ?&gt; </code></pre>
[]
[ { "body": "<p>Overall your code looks fine</p>\n\n<p>If you are having trouble with sessions, check the live server configuration, especially the cookie domain and path.</p>\n\n<p>I have put some inline comments in the code, the changes I have done will make it a bit easier to maintain (in my opinion) but are not essential.</p>\n\n<pre><code>&lt;?php\nrequire_once('authorize.php');\n?&gt;\n\n&lt;!DOCTYPE html&gt;\n\n&lt;?php\nrequire_once('includes/load.php');\nGLOBAL $db;\n\nrequire_once('includes/functions.php');\n\n\n$is_moderator = (get_access_from_username($_SESSION['username']) &gt; 0);\n\n// move database access to top of code\n// if an error occurs you can show an error message before you render the page, rather then have a mess in the middle of the page\nif (!empty($_GET['order']))\n{\n if ($_GET['order'] == 'certificate')\n $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY certificate, lastname, firstname;');\n else if ($_GET['order'] == 'lastname')\n $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY lastname, firstname;');\n else if ($_GET['order'] == 'firstname')\n $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY firstname, lastname;');\n else\n $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY lastname, firstname;');\n\n} else {\n $queryResult = $db-&gt;query('SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY lastname, firstname;');\n}\n\n\n// i have re-written this part, there is nothing wrong with your code\n// this is personal preference for readability, see what you think\n$sql = 'SELECT id, firstname, lastname, phone, certificate, address FROM dc_members ORDER BY ';\n\n$param_order = (!empty($_GET['order'])) ? $_GET['order'] : null;\n\nswitch($param_order) {\n case 'certificate':\n $order_by = 'certificate, lastname, firstname';\n break;\n\n case 'firstname':\n $order_by = 'firstname, lastname';\n break;\n\n case 'lastname':\n default:\n $order_by = 'lastname, firstname';\n break;\n}\n\n// only do query in one place, simpler if you want to handle errors\n$queryResult = $db-&gt;query($sql.$order_by);\n\n\n// mysqli_fetch_array returns a number indexed array and a associative array combined, mysqli_fetch_assoc is all you need\n// while ($row = mysqli_fetch_array($queryResult)) {\n\n$members = array();\n\nwhile ($row = mysqli_fetch_assoc($queryResult)) {\n $members[] = $row;\n}\n\n// $members_amount = 0; $members_amount++;\n$members_amount = count($members);\n\n// only put code for presentation logic below here\n\n?&gt;\n\n&lt;html&gt;\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"css/stylesheet.css\"&gt;\n\n &lt;title&gt;Medlemsliste - &lt;?php echo SITE_TITLE ?&gt;&lt;/title&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n&lt;div id=\"container\"&gt;\n &lt;div id=\"header\"&gt;\n &lt;div id=\"header-menu\"&gt;\n &lt;img id=\"logo\" src=\"img/nsdk_logo_header.png\"&gt;\n &lt;ul id=\"main-menu\"&gt;\n &lt;li&gt;&lt;a href=\"index.php\"&gt;Forsiden&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"omklubben.php\"&gt;Om klubben&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"kontakt.php\"&gt;Kontakt&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;img id=\"top-image\" src=\"img/header/foto.jpg\"&gt;\n\n &lt;?php include(\"sidebar.php\"); ?&gt;\n\n &lt;div id=\"content-container\"&gt;\n &lt;span class=\"content-header\"&gt;Medlemsliste&lt;/span&gt;\n &lt;div class=\"content\"&gt;\n &lt;h1&gt;Medlemmer af NSDK&lt;/h1&gt;\n &lt;p&gt;Du kan sende mail til et medlem ved at sende en mail til &lt;code&gt;fornavn.efternavn@nsdk.dk&lt;/code&gt;, f.eks. &lt;a href=\"mailto:anders.and@nsdk.dk\"&gt;anders.and@nsdk.dk&lt;/a&gt;.\n\n\n &lt;?php\n // move non-presentation code to top\n // $is_moderator = (get_access_from_username($_SESSION['username']) &gt; 0);\n\n if ($is_moderator)\n echo '&lt;p&gt;&lt;b&gt;NB: Du er logget ind som et bestyrelsesmedlem og bliver derfor også oplyst adresse på medlemmer!&lt;/b&gt;&lt;/p&gt;';\n ?&gt;\n\n &lt;!-- LIST BEGIN --&gt;\n &lt;table id=\"table-members\" width=\"100%\"&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;a href=\"members.php?order=firstname\"&gt;Fornavn&lt;/a&gt;&lt;/th&gt;\n &lt;th&gt;&lt;a href=\"members.php?order=lastname\"&gt;Efternavn&lt;/a&gt;&lt;/th&gt;\n &lt;th&gt;Tlf. nr.&lt;/th&gt;\n &lt;th&gt;&lt;a href=\"members.php?order=certificate\"&gt;Certifikat&lt;/a&gt;&lt;/th&gt;\n &lt;?php if ($is_moderator) { ?&gt;\n &lt;th&gt;Adresse&lt;/th&gt;\n &lt;?php } ?&gt;\n &lt;/tr&gt;\n\n &lt;?php\n // member info could contain html characters, make sure we escape them with htmlspecialchars or htmlentities\n foreach ($members as $member):\n ?&gt;\n &lt;tr&gt;\n &lt;td&gt;&gt;&lt;?php echo htmlspecialchars($member['firstname']) ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo htmlspecialchars($member['lastname']) ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo htmlspecialchars($member['phone']) ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo htmlspecialchars($member['certificate']) ?&gt;&lt;/td&gt;\n\n &lt;?php if ($is_moderator): ?&gt;\n &lt;td&gt;&lt;?php echo htmlspecialchars($member['address']) ?&gt;&lt;/td&gt;\n &lt;?php endif ?&gt;\n\n &lt;/tr&gt;\n &lt;?php endforeach ?&gt;\n &lt;/table&gt;\n &lt;!-- LIST END --&gt;\n\n &lt;br&gt;\n &lt;?php\n // why do we echo &lt;b&gt; tag?\n // &lt;p&gt;Antal medlemmer i Nakskov Sportsdykkerklub: &lt;?php echo '&lt;b&gt;'.$members_amount.'&lt;/b&gt;' ?&gt; &lt;/p&gt;\n ?&gt;\n &lt;p&gt;Antal medlemmer i Nakskov Sportsdykkerklub: &lt;b&gt;&lt;?php echo $members_amount ?&gt;&lt;/b&gt; &lt;/p&gt;\n\n &lt;/div&gt;\n &lt;/div&gt;\n\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:17:09.780", "Id": "67466", "Score": "0", "body": "Thanks for your feedback! I will run through your comments and most certainly try to get in contact with the domain support, to see if I can get the session cookies fixed! Cheers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T22:43:33.980", "Id": "40121", "ParentId": "40120", "Score": "2" } } ]
{ "AcceptedAnswerId": "40121", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T21:15:47.780", "Id": "40120", "Score": "6", "Tags": [ "php", "html", "security", "authentication" ], "Title": "Review on a PHP login/authentication system" }
40120
<p>This algorithm is supposed to organize and visually duplicate images. I compare 2 images at a time; 1 is the first index image of the directory and another for comparing every other image in the directory. If there are duplicates of the first index image, all of the duplicates will be moved to a new folder that is named after the original folder.</p> <p>It is working fine but the performance time is approximately 5 minutes and 29 seconds. I am dealing with 1090 images.</p> <p>For example, if 2.png had 5 visually duplicated images, they would be moved to the path file called:</p> <blockquote> <p>C:\Users\user\Downloads\CaptchaCollection\Large\Duplicates\2</p> </blockquote> <p>What this code is supposed to do:</p> <ol> <li><p>Copy all the images from another directory to:</p> <blockquote> <p>C:\Users\user\Downloads\CaptchaCollection\Large\</p> </blockquote> <p>This is because I want to back up my raw images just in case I lose them</p></li> <li><p>Collects the amount of images there are in the directory.</p></li> <li><p>Selects the first index and then compares it with all other images in the directory.</p></li> <li><p>If they are equal they are moved to a new folder.</p></li> <li><p>When this is done the original is moved to the <code>Sorted</code> folder.</p></li> <li><p>Then a new first index will be selected and the loop goes on until everything is finished. At the end of the inner loop, it will recalculate the amount files in the directory.</p></li> <li><p>Move the last file into the <code>Sorted</code> folder.</p></li> <li><p>Check for any empty folders.</p></li> <li><p>Recursively deletes them.</p></li> <li><p>(Not involved in sorting) Pretty much logs everything into a text file.</p></li> </ol> <p></p> <pre><code>private bool compare(Bitmap bmp1, Bitmap bmp2) { bool equals = true; // sets it to true first Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height); BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat); BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp2.PixelFormat); unsafe { byte* ptr1 = (byte*)bmpData1.Scan0.ToPointer(); byte* ptr2 = (byte*)bmpData2.Scan0.ToPointer(); int width = rect.Width * 3; // for 24bpp pixel data for (int y = 0; equals &amp;&amp; y &lt; rect.Height; y++) { for (int x = 0; x &lt; width; x++) { if (*ptr1 != *ptr2) { equals = false; break; } ptr1++; ptr2++; } ptr1 += bmpData1.Stride - width; ptr2 += bmpData2.Stride - width; } } // unlocks the bits bmp1.UnlockBits(bmpData1); bmp2.UnlockBits(bmpData2); // disposes the image bmp1.Dispose(); bmp2.Dispose(); return equals; // returns if they're same or not } private void sort(object sender, EventArgs e) { // testing time Stopwatch w = new Stopwatch(); w.Start(); // file paths string sourceDir = @"C:\Users\user\Documents\Original"; string copiedOriginal = @"C:\Users\user\Downloads\CaptchaCollection\Large\"; string duplicatePath = copiedOriginal + "Duplicates\\"; string movedOriginal = copiedOriginal + "Sorted\\"; // creates a log FileStream outputFileStream = new FileStream(copiedOriginal + "log.txt", FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(outputFileStream); // Copy picture files. foreach (string f in Directory.GetFiles(sourceDir, "*.png")) { // Remove path from the file name. string fName = f.Substring(sourceDir.Length + 1); // Use the Path.Combine method to safely append the file name to the path. // Will overwrite if the destination file already exists. File.Copy(Path.Combine(sourceDir, fName), Path.Combine(copiedOriginal, fName), true); } // creates the folders for the sorting Directory.CreateDirectory(duplicatePath); Directory.CreateDirectory(movedOriginal); // makes sure only n.png is counted var files = Directory.GetFiles(copiedOriginal) .Select(nameWithExtension =&gt; Path.GetFileNameWithoutExtension(nameWithExtension)) .Where(name =&gt; { int number; return int.TryParse(name, out number); }) .Select(name =&gt; int.Parse(name)) .OrderBy(number =&gt; number).ToArray(); // will move if there is more than 1 file. while (files.Length &gt; 1) { // creates an individual folder based on the original image's name assosiated with the duplicated images string duplicateOfFolder = Directory.CreateDirectory(duplicatePath + files[0].ToString()).FullName; // sorting inner loop for (int j = 1; j &lt; files.Length; j++) { // creates 2 images objects for it to run Bitmap im1 = new Bitmap(copiedOriginal + files[0].ToString() + ".png"); Bitmap im2 = new Bitmap(copiedOriginal + files[j].ToString() + ".png"); // if they are the same if (compare(im1, im2)) { // moves the duplicates to the file that was linked to the them File.Move(copiedOriginal + files[j].ToString() + ".png", duplicateOfFolder + "\\" + files[j].ToString() + ".png"); // logs the moves writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png"); } } // logs that it has finished all duplicates associated writer.WriteLine(files[0].ToString() + ".png " + "has had its duplicates removed."); // moves the non-duplicated file to the sorted folder File.Move(copiedOriginal + files[0].ToString() + ".png", movedOriginal + files[0].ToString() + ".png"); // recalculates the length of the directory files = Directory.GetFiles(copiedOriginal) .Select(nameWithExtension =&gt; Path.GetFileNameWithoutExtension(nameWithExtension)) .Where(name =&gt; { int number; return int.TryParse(name, out number); }) .Select(name =&gt; int.Parse(name)) .OrderBy(number =&gt; number).ToArray(); } // moves the non-duplicated file to the sorted folder File.Move(copiedOriginal + files[0].ToString() + ".png", movedOriginal + files[0].ToString() + ".png"); // deletes and logs any empty folders that were created in this process processDirectory(duplicatePath); writer.WriteLine(deletedDirectories); // finished the timing w.Stop(); writer.WriteLine(w.Elapsed); // closes the log.txt file writer.Close(); outputFileStream.Close(); } private static void processDirectory(string startLocation) { foreach (var directory in Directory.GetDirectories(startLocation)) { // recursively calls itself processDirectory(directory); // if it is empty it will delete if (Directory.GetFiles(directory).Length == 0 &amp;&amp; Directory.GetDirectories(directory).Length == 0) { Directory.Delete(directory, false); // deletes deletedDirectories += Path.GetFileName(directory) + " , "; // logs the deleted directories } } } </code></pre> <p><strong>Results after every test (2nd test and later):</strong></p> <blockquote> <ul> <li>00:05:33.5252512</li> <li>00:05:27.4010562</li> </ul> </blockquote>
[]
[ { "body": "<p>The algorithm as described is <code>O(n^2)</code> worst case. Assuming that there are <code>n</code> images and no two images are equal then the first one gets compared against <code>n-1</code>, the second one against <code>n-2</code>, ... etc. so you have <code>1/2 * n * (n + 1)</code> comparisons.</p>\n<p>A way around this is by calculating a checksum with low enough collision probability on each image - <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">SHA256</a> comes to mind but there are a whole heap of others in the <a href=\"http://msdn.microsoft.com/en-us/library/System.Security.Cryptography%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">.NET framework</a> which will fit the bill.</p>\n<p>Then the algorithm becomes (pseudo LINQ):</p>\n<pre><code>var equivalentImages = allImages.Select(i =&gt; Tuple.Create(HashImage(i), FullPath(i)))\n .GroupBy(t =&gt; t.Item1);\n</code></pre>\n<p>This way you only need to process the data of each image once and then group them by the hash.</p>\n<p>A few remarks to your code:</p>\n<ol>\n<li><p>Instead of disposing <code>bmp1</code> and <code>bmp2</code> manually you should use a <code>using</code> block. This means they will get disposed even if any of the code in between throws an exception.</p>\n</li>\n<li><p>Similar <code>Stream</code>s are <code>IDisposable</code> so again you should wrap them in a <code>using</code> block.</p>\n</li>\n<li><p>It is not overly clear that the <code>writer</code> is used for logging purposes until you read the code. I would abstract it behind an <code>ILogger</code> interface which I would pass in. It makes it much clearer that the messages are used for logging and removes the responsibility of managing the log file out of the function (Single Responsibility Principle). In fact you should have a look at <a href=\"http://logging.apache.org/log4net/\" rel=\"nofollow noreferrer\">log4net</a> which provides a whole heap more flexibility in terms of logging targets and filtering. In case your project should grow this will make things a bit easier.</p>\n</li>\n</ol>\n<p><strong>Update</strong></p>\n<p>A very simple example use (loosely based on <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">the MSDN example</a> for copying the bitmap data):</p>\n<pre><code>public byte[] HashImage(string fileName)\n{\n using (var image = new Bitmap(fileName))\n {\n var sha256 = SHA256.Create();\n\n var rect = new Rectangle(0, 0, image.Width, image.Height);\n var data = image.LockBits(rect, ImageLockMode.ReadOnly, image.PixelFormat);\n\n var dataPtr = data.Scan0;\n\n var totalBytes = (int)Math.Abs(data.Stride) * data.Height;\n var rawData = new byte[totalBytes];\n System.Runtime.InteropServices.Marshal.Copy(dataPtr, rawData, 0, totalBytes);\n\n image.UnlockBits(data);\n\n return sha256.ComputeHash(rawData);\n }\n}\n</code></pre>\n<p><strong>Update 2</strong>: To complete the example (based on your pastebin, note I changed the method above to accept a filename rather than a <code>Bitmap</code> directly)</p>\n<pre><code>private Tuple&lt;int, string&gt; GetIndexedImage(string fileName)\n{\n var baseFileName = Path.GetFileNameWithoutExtension(fileName);\n int index;\n if (int.TryParse(baseFileName, out index))\n {\n return Tuple.Create(index, fileName);\n }\n return null;\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n string original = @&quot;C:\\Users\\user\\Documents\\CaptchaCollection\\&quot;;\n\n var equivalentImages = Directory.GetFiles(original)\n .Select(f =&gt; GetIndexedImage(f)) // build tuples (index, fileName) or null if parsing failed\n .Where(t =&gt; t != null) // ignore all invalid ones\n .OrderBy(t =&gt; t.Item1) // order by index\n .Select(t =&gt; Tuple.Create(HashImage(t.Item2), t.Item2)) // create new tuple (hash, fileName)\n .GroupBy(t =&gt; t.Item1); // group by Hash\n\n // print groups\n foreach (var group in equivalentImages)\n {\n Console.WriteLine(&quot;All images with hash: {0}&quot;, HashToString(group.Key));\n foreach (var t in group)\n {\n Console.WriteLine(&quot;\\t{0}&quot;, t.Item2);\n }\n }\n \n}\n\nprivate string HashToString(byte[] hash)\n{\n var builder = new StringBuilder();\n foreach (var b in hash)\n {\n builder.AppendFormat(&quot;{0:x2}&quot;, b);\n }\n return builder.ToString();\n}\n</code></pre>\n<p>Note:</p>\n<ul>\n<li>Unless the hashes collided (very unlikely) or there is a subtle bug I've missed (possible) all image within each group should have the same content and you can do your file moving.</li>\n<li>You probably don't want to hard-code the directory and rather pass it in from external.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T03:05:30.303", "Id": "67449", "Score": "0", "body": "Oh I'm not sure how to use those things. Yeah I know my algorithm is slow but what other search/sort algorithms are better to use than this for images lets say? I'm not really good at this because I only code what I know so yeah. Do you have code to show to fix maybe? This could help me understand instead of reading all the documentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:25:23.970", "Id": "67519", "Score": "0", "body": "I'd suggest you read the documentation so that when you continue to 'only code what I know so yeah', you know more. Nothing will help you understand it better than reading the documentation and trying it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:23:58.293", "Id": "67563", "Score": "0", "body": "@puretppc: I added a simple example on how to possibly compute a hash for the image. I leave it to you to implement the rest, use a different hashing algorithm and optimize it in any other way" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T02:05:04.757", "Id": "67871", "Score": "0", "body": "@ChrisWue Oh I see yeah it worked to compare when I used `if (HashImage(im1).SequenceEqual(HashImage(im2)))`. That's really the only change I made in the code. Is that actually a better and faster way to search and sort maybe? I'm testing it now but it still seems slow" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T02:38:51.603", "Id": "67874", "Score": "1", "body": "@puretppc: No, what you should do is: Create the hashes for all images and store them with a reference to the image - this is the `equivalentImages` from the pseudo linq algorithm. This will be the slow part because it needs to create the hash for each image which will take some time. However once you got the hashes you can simply group them - all entries in one group are images which should be the same and then you can do you file moving." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T04:21:21.220", "Id": "67888", "Score": "0", "body": "@ChrisWue Like this I guess? http://pastebin.com/6FSntr46 Also, the LINQ line isn't working (last one)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T08:07:31.967", "Id": "67910", "Score": "0", "body": "@puretppc: See my updated answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T03:46:44.060", "Id": "68030", "Score": "0", "body": "@ChrisWue So this was what I got from your code (without my code): http://pastebin.com/w0ZbDNee How do I group items based on the Hash group? I'm very unfamiliar with LINQ. The items didn't seem to print as a duplicated group. They were still spread all over the place (duplicates in Hash Value)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-27T00:22:23.593", "Id": "40123", "ParentId": "40122", "Score": "12" } } ]
{ "AcceptedAnswerId": "40123", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T23:15:31.457", "Id": "40122", "Score": "8", "Tags": [ "c#", "algorithm", "performance", "sorting", "image" ], "Title": "Organizing and visually duplicating images" }
40122
<p>This function is intended to remove leading and trailing whitespace from a string. How can it be made more efficient? For example, can the two <code>for</code> loops be combined into one?</p> <pre><code>string trim(string str) { int i = 0; for (char c : str) { if (!isspace(c)) break; i++; } string trimmed = str.substr(i, (str.length()-i)); i = 0; for (char c : str) { if (isspace(c)) break; i++; } trimmed = trimmed.substr(0, i); return trimmed; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T02:05:30.503", "Id": "67445", "Score": "1", "body": "For starters, you should pass `str` by `const&` since it's not being modified." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T02:57:17.487", "Id": "67447", "Score": "0", "body": "@Jamal Good advice in general, but I'm on the fence here. I think it may be reasonable to take a non-const non-reference, then modify it (use `.erase` instead of `.substr`). Maybe that's because I would have expected the name `trim` to mean in-place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T03:00:08.447", "Id": "67448", "Score": "0", "body": "@MichaelUrman: That too. I was adapting that to what was already here. I've noted in my review that it doesn't work, but I've deleted it as my own code snippet removes *all* whitespace instead of just leading and trailing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T21:54:04.407", "Id": "67841", "Score": "0", "body": "You are assuming that the string contains 1 word. If your string contains multiple words then you will loose all but the first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T05:11:37.220", "Id": "136222", "Score": "0", "body": "Any particular reason why there isn't a `trim()` method available as part of the string library? [C# and Java](http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28string_functions%29#trim) have it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-06T06:07:28.830", "Id": "137861", "Score": "1", "body": "@lifebalance C++ isn't a very good language." } ]
[ { "body": "<p>To make this more efficient, you have to consider what's inefficient about it. I see two main contenders:</p>\n\n<ol>\n<li>Data copies</li>\n<li>Data scans</li>\n</ol>\n\n<p>You copy data in up to three places. First when <code>str</code> is passed into the function it may be copied or it may be moved. Second when you take <code>trimmed = str.substr(..)</code> you copy a presumably large portion of the string. Third when you take <code>trimmed = trimmed.substr(..)</code> you do so again. In the worst case (when no whitespace is removed) this is two or three full copies of your string.</p>\n\n<p>You scan data in two places. First when you scan <code>str</code> forward, looking for non-whitespace. Second when you scan <code>str</code> forward, looking for whitespace. The latter appears to be a mistake, as you use the index this calculates against <code>trimmed</code>, and, as Jamal found, strings with leading whitespace result in empty strings being returned. It seems to me that instead of finding the first whitespace character, you need to find the last non-whitespace.</p>\n\n<p>My recommendations are as follows. If <em>run-time efficiency</em> is your ultimate concern (as opposed to programmer efficiency or other concerns), consider changing your function signature to pass a string by reference. This avoids the initial possible copy. Then avoid the other two copies by modifying the passed string in place with <code>std::string::erase</code> instead of <code>std::string::substr</code>. If you stick to <code>std::string::substr</code>, definitely find both ends and only call <code>substr</code> once. Second, unless you mean something unusual by \"leading and trailing whitespace\" (such as returning the first whitespace delimited substring) scan for trailing whitespace from the end of your string.</p>\n\n<p>If <em>run-time efficiency</em> is your ultimate concern, you can't optimize properly without knowing more about your data. Do you typically see large amounts of whitespace at one or both ends of your string, or is it typically a relatively small amount? If possible, profile a few approaches against a representative data set. If you typically extract small desired strings from within large amounts of whitespace, it's possible that a passing a <code>const string&amp;</code> and returning the results of a single call to <code>std::string::substr(pos, len)</code> will be faster. But if you typically remove no whitespace, it's hard to beat in-place even with C++11's move semantics.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T03:39:35.887", "Id": "40131", "ParentId": "40124", "Score": "2" } }, { "body": "<p>If readability and maintenance is a concern something like this might help:</p>\n\n<pre><code>const string whitespace = \" \\t\\f\\v\\n\\r\";\nstring test = \" test1 test2 test3 \\n\\n\";\nint start = test.find_first_not_of(whitespace);\nint end = test.find_last_not_of(whitespace);\ntest.erase(0,start);\ntest.erase((end - start) + 1);\n</code></pre>\n\n<p>This still iterates over the string twice but is much more concise.</p>\n\n<p>One way to only iterate once would be like this:</p>\n\n<pre><code>string test2 = \" test1 test2 test3 \\n\\n\";\nint start2 = 0, end2 = test2.length() - 1;\nwhile(isspace(test2[start2]) || isspace(test2[end2]))\n{\n if(isspace(test2[start2]))\n start2++;\n if(isspace(test2[end2]))\n end2--;\n}\ntest2.erase(0,start2);\ntest2.erase((end2 - start2) + 1);\n</code></pre>\n\n<p>This iterates up to the maximum number of whitespace characters on either end.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:28:28.147", "Id": "40158", "ParentId": "40124", "Score": "2" } }, { "body": "<p>Your current implementation you will lose all but the first word:</p>\n\n<pre><code>std::string str(\"this is a sentence\");\nstd::string t = trim(str);\n\nstd::cout &lt;&lt; t &lt;&lt; \"\\n\" \n\n// Output\nthis\n</code></pre>\n\n<p>If that is your intention then there is an easier way of doing that:</p>\n\n<pre><code>std::string trim(std::string const&amp; str)\n{\n std::string word;\n std::stringstream stream(str)\n stream &gt;&gt; word;\n\n return word;\n}\n</code></pre>\n\n<p>If you want to trim space of the ends on the string, then I would use the string search functions<a href=\"http://coliru.stacked-crooked.com/a/3ac708f29bf72d91\" rel=\"nofollow\"> [coliru demo]</a>:</p>\n\n<pre><code>std::string trim(std::string const&amp; str)\n{\n if(str.empty())\n return str;\n\n std::size_t firstScan = str.find_first_not_of(' ');\n std::size_t first = firstScan == std::string::npos ? str.length() : firstScan;\n std::size_t last = str.find_last_not_of(' ');\n return str.substr(first, last-first+1);\n}\n</code></pre>\n\n<p><a href=\"http://www.sgi.com/tech/stl/basic_string.html\" rel=\"nofollow\">Here</a> is the string documentation. Boost also has some <a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/string_algo.html\" rel=\"nofollow\">extra libraries</a> on the subject.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T22:03:31.127", "Id": "40302", "ParentId": "40124", "Score": "10" } }, { "body": "<p>What about <a href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/string_algo.html\" rel=\"nofollow\">boost</a>?</p>\n\n<pre><code>std::string untrimmed( \" This is an untrimmed string! \" );\nstd::string trimmed( boost::algorithm::trim( s ) );\n</code></pre>\n\n<p>It doesn't get much terser than that, and I trust the boost libs to be more efficient than what I could hack together on a whim...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T20:02:26.380", "Id": "86812", "Score": "0", "body": "Would be my way to go. boost is always a good idea." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T09:41:49.233", "Id": "40344", "ParentId": "40124", "Score": "4" } }, { "body": "<p>Loki Astari's ideas <em>will</em> work (for the most part) except for the last one, in one special (but certainly no less important) case: If the string being split is all spaces.</p>\n\n<p>This can be fixed with a simple conditional statement:</p>\n\n<pre><code>std::string trim(std::string const&amp; str)\n{\n std::size_t first = str.find_first_not_of(' ');\n\n // If there is no non-whitespace character, both first and last will be std::string::npos (-1)\n // There is no point in checking both, since if either doesn't work, the\n // other won't work, either.\n if(first == std::string::npos)\n return \"\";\n\n std::size_t last = str.find_last_not_of(' ');\n\n return str.substr(first, last-first+1);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T18:31:47.277", "Id": "86800", "Score": "0", "body": "It would be more clear and maintainable if you changed the -1 to `std::string::npos`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T19:43:37.227", "Id": "86811", "Score": "0", "body": "This is a good point. I'll edit it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T15:36:49.410", "Id": "49349", "ParentId": "40124", "Score": "1" } }, { "body": "<p>From various source and after a lot experiments, the code below can be used in the following manner: </p>\n\n<pre><code>RemoveLTWhiteSp(Inpu_strng, &amp;res_strng);\n</code></pre>\n\n<p>I always use this code and it works fine as a trim function. It removes leading and trailing white spaces.</p>\n\n<pre><code>void RemoveLTWhiteSp(std::string &amp;InStr_Token, std::string *OutStr)\n{\n if( 0 != InStr_Token.size() ) //if the size is 0\n {\n std::string wspc (\" \\t\\f\\v\\n\\r\");// These are the whitespaces\n //finding the last valid character \n std::string::size_type posafter = InStr_Token.find_last_not_of(wspc);\n //finding the first valid character\n std::string::size_type posbefore=InStr_Token.find_first_not_of(wspc);\n\n if((-1 &lt; (int)posafter) &amp;&amp; (-1 &lt; (int)posbefore)) //Just Wsp\n {\n std::string NoSpaceToken;\n // Cut off the outside parts of found positions\n NoSpaceToken = InStr_Token.substr(posbefore,((posafter+1)-posbefore));\n *OutStr = NoSpaceToken;\n }\n }\n}\n</code></pre>\n\n<p>Here is a usage example with a very efficient tokenizer using a vector. The tokens argument is just a \"vector string\":</p>\n\n<pre><code>template&lt;class ContainerT&gt;\n\nvoid tokenize(const std::string&amp; str, ContainerT&amp; tokens, const std::string&amp; delimiters , bool trimEmpty = false )\n{\n std::string::size_type pos, lastPos = 0;\n std::string Instr;\n std::string OutStr;\n\n while(true)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n {\n pos = str.length();\n\n if(pos != lastPos || !trimEmpty)\n {\n Instr = std::string(ContainerT::value_type(str.data()+lastPos, (ContainerT::value_type::size_type)pos-lastPos ));\n RemoveLTWhiteSp(Instr, &amp;OutStr);\n tokens.push_back(OutStr);\n }\n break;\n }\n else\n {\n if(pos != lastPos || !trimEmpty)\n {\n Instr = std::string(ContainerT::value_type(str.data()+lastPos, (ContainerT::value_type::size_type)pos-lastPos ));\n RemoveLTWhiteSp(Instr, &amp;OutStr);\n tokens.push_back(OutStr);\n }\n }\n lastPos = pos + 1;\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-31T13:46:32.447", "Id": "179265", "ParentId": "40124", "Score": "0" } } ]
{ "AcceptedAnswerId": "40302", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T01:57:57.697", "Id": "40124", "Score": "7", "Tags": [ "c++", "optimization", "strings", "c++11" ], "Title": "Trim white space from string" }
40124
<p>I'm working on an algorithm to determine if a <code>std::string</code> has all of the same character. Here is what I have:</p> <pre><code>bool string_has_all_of_the_same_chars(const std::string&amp; s) { return std::all_of(s.begin(), s.end(), [&amp;s](char ch) { return ch == s[0]; }); } </code></pre> <p>Are there any improvements that can be made to this? I am guaranteed by another function that <code>s</code> is not empty.</p>
[]
[ { "body": "<p>You could simply use <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/find_first_not_of\" rel=\"noreferrer\"><code>find_first_not_of</code></a> </p>\n\n<pre><code>bool string_has_all_of_the_same_chars(const std::string&amp; s) {\n return s.find_first_not_of(s[0]) == std::string::npos;\n}\n</code></pre>\n\n<p><em>Update:</em></p>\n\n<p>This works only, when the string is not empty. A complete version would also test <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/empty\" rel=\"noreferrer\"><code>empty</code></a> </p>\n\n<pre><code>bool string_has_all_of_the_same_chars(const std::string&amp; s) {\n return s.empty() || s.find_first_not_of(s[0]) == std::string::npos;\n}\n</code></pre>\n\n<p>Instead of <code>s[0]</code>, one could also use <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/front\" rel=\"noreferrer\"><code>s.front()</code></a> or <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/begin\" rel=\"noreferrer\"><code>*s.begin()</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T03:44:47.683", "Id": "67450", "Score": "0", "body": "You could use `s.front()` instead of `s[0]`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T02:50:52.957", "Id": "40128", "ParentId": "40126", "Score": "9" } } ]
{ "AcceptedAnswerId": "40128", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T02:45:49.117", "Id": "40126", "Score": "1", "Tags": [ "c++", "algorithm", "strings" ], "Title": "Determine if a std::string has all of the same character" }
40126
<p>Working on an exercise from <a href="http://www.manning.com/bjarnason/" rel="nofollow">Functional Programming in Scala</a>, I implemented a <code>Traverse</code> instance for <code>Option</code>:</p> <pre><code>override def traverse[G[_],A,B](oa: Option[A])(f: A =&gt; G[B])(implicit G: Applicative[G]): G[Option[B]] = oa match { case None =&gt; G.unit(None) case _ =&gt; { val a: A = oa.get val x: G[B] = f(a) G.map(x)(Some(_)) } } </code></pre> <p>Is this idiomatic? Besides condensing the <code>case _</code>'s 3 lines to 1, perhaps there's a more concise way to write this method?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T22:16:54.633", "Id": "67843", "Score": "0", "body": "Can't you just use `G.unit(oa map f)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T22:20:42.297", "Id": "67845", "Score": "0", "body": "`oa map f` produces a type of `Option[G[B]]`. Applying `G.unit` would give `G[Option[G[B]]`." } ]
[ { "body": "<ol>\n<li>Never use <code>get</code> method on option. In this case you could use <code>case Some(a)</code> instead.</li>\n<li>You don't need curly braces in <code>case</code> branches</li>\n</ol>\n\n<pre><code>oa match {\n case None =&gt; G.unit(None)\n case Some(a) =&gt;\n val x: G[B] = f(a)\n G.map(x)(Some(_))\n}\n</code></pre>\n\n<p>I don't know if variable <code>x</code> makes any sense in this case. I'd just use this:</p>\n\n<pre><code>case Some(a) =&gt; G.map(f(a))(Some(_))\n</code></pre>\n\n<p>You could also use methods of <code>Option</code> like <code>fold</code> of <code>map</code> + <code>getOrElse</code>, but I guess pattern matching is the best solution in this case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T22:11:03.970", "Id": "40303", "ParentId": "40127", "Score": "2" } } ]
{ "AcceptedAnswerId": "40303", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T02:49:30.890", "Id": "40127", "Score": "3", "Tags": [ "scala" ], "Title": "Writing Traverse Instance for Option" }
40127
<p>Working on an example from <a href="http://www.manning.com/bjarnason/" rel="nofollow">Functional Programming in Scala</a>, I'm working on <code>Option#map2</code>:</p> <pre><code>override def map2[A, B, C](fa: Option[A],fb: Option[B])(f: (A, B) =&gt; C): Option[C] = { (fa, fb) match { case (None, _) =&gt; None case (_, None) =&gt; None case (_, _) =&gt; Some(f(fa.get, fb.get)) // runtime-safe get calls } } </code></pre> <p>Is the above implementation reasonable? I presumed that, if either <code>fa</code> or <code>fb</code> were <code>None</code>, then so should be the returned value. Pattern matching seemed the most clean to me, but perhaps there's a cleaner or more concise way to write this method?</p>
[]
[ { "body": "<p>Your code is correct - it should work nicely.</p>\n\n<p>The first thing that I would improve on is the <code>// runtime-safe get calls</code>. This is an anti-pattern in Scala and is generally discouraged. In this case you can use pattern matchings powerful extractors to get the value the <code>Option</code> is storing:</p>\n\n<pre><code>case (Some(a), Some(b)) =&gt; Some(f(a, b))\n</code></pre>\n\n<p>But instead of pattern matching the most elegant way to solve this problem is to use <a href=\"http://daily-scala.blogspot.fr/2009/08/for-comprehensions.html\" rel=\"noreferrer\">for comprehensions</a>. It is functionally the same as your code:</p>\n\n<pre><code>override def map2[A, B, C](fa: Option[A], fb: Option[B])(f: (A, B) =&gt; C): Option[C] = {\n for {\n a &lt;- fa\n b &lt;- fb\n } yield f(a, b)\n}\n</code></pre>\n\n<p>Since <code>Option</code> is essentially a collection with either zero or one element it can be used in for-comprehensions. The variable <code>a</code> will only be populated if <code>fa</code> is a <code>Some</code>. If either is <code>None</code> then nothing will be yielded and the result is <code>None</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T15:59:59.093", "Id": "80161", "Score": "0", "body": "Thanks, Akos. Could you please provide a reference for `.get` being an anti-pattern? It makes sense to me, but I'd appreciate a reference for further reading" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T18:12:46.943", "Id": "80189", "Score": "1", "body": "Sorry, I may have overused the word \"anti-pattern\" as it is not explicitly stated anywhere. The issue is that `.get` will throw a `NoSuchElementException` if the `Option` is empty. In this case you *know* that it won't be empty, but what happens when you or someone refactors it? Will they make sure that the `.get` will be called on a code path that is safe? It is generally encouraged (not only in Scala) to avoid this, because you're just setting yourself up for bugs. I would recommend a talk on this topic, it covers the issue and Scala's solution to it quite well: http://youtu.be/gVXt1RG_yN0" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-01T20:31:46.407", "Id": "80221", "Score": "0", "body": "Thanks! I went to NeScala 2014 and was thinking of that video right as I clicked your link!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-27T17:36:40.633", "Id": "186890", "Score": "0", "body": "When I use it like this `Option.map2(Some(3), None)(_+_)` it fails why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-27T21:49:50.637", "Id": "186952", "Score": "1", "body": "@eguneys The issue is that `None` is essentially `Option[Nothing]` and the `_ + _` then translates to `Int + Nothing`. This can't compile as `Nothing` can't be added with `Int`, to fix this use `Option.empty[Int]` instead of `None`!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:52:30.857", "Id": "40278", "ParentId": "40130", "Score": "5" } } ]
{ "AcceptedAnswerId": "40278", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T02:58:31.207", "Id": "40130", "Score": "2", "Tags": [ "scala" ], "Title": "Implementing Option#map2" }
40130
<p>Given the following piece of code, can it be done better:</p> <pre><code>public object DistanceFrom( IEnumerable&lt;Coordinate&gt; coordinates) { IEnumerable&lt;DbGeography&gt; addresses = coordinates.Select( c =&gt; DbGeography.FromText(String.Format("POINT ({0} {1})", c.Longitude, c.Latitude))); IEnumerable&lt;VehicleGeography&gt; vehicles = this.GPSInsightProvider.Query().Document.Placemarks.Select( p =&gt; new VehicleGeography { DriverName = p.DriverName, Point = DbGeography.FromText(String.Format("POINT ({0} {1})", p.Point.Longitude, p.Point.Latitude)) }); ICollection&lt;object&gt; technicians = new List&lt;object&gt;(); foreach (DbGeography address in addresses) { technicians.Add(vehicles.Select( v =&gt; new { DriverName = v.DriverName, Distance = v.Point.Distance(address) / 1609.344 }).Where( v =&gt; v.Distance.HasValue).OrderBy( v =&gt; v.Distance).Take(3).Select( v =&gt; new { DriverName = v.DriverName, Distance = String.Format("{0:#.#}", v.Distance) })); } return technicians; } </code></pre> <p><code>GPSInsightProvider</code> parses a KML and returns its object representation. I then take that and convert it temporarily into a <code>VehicleGeography</code> so I can create a <code>DbGeography</code> property for it. I then loop through the addresses I'm checking against and the do a dirty-looking calculation to see which are the closest three vehicles to the address. At most I will be doing this for a maximum of three addresses at a time. I take the resulting object and return it as JSON to my web application.</p> <p>I'm curious if there's a better way to perform that whole lookup/calculation/whatever-this-is?</p>
[]
[ { "body": "<p>Firstly, I really don't like your indentation, particularly with the method header, so I've pasted into Visual Studio and will be working from the code as it appears below:</p>\n\n<pre><code> public object DistanceFrom(IEnumerable&lt;Coordinate&gt; coordinates)\n {\n IEnumerable&lt;DbGeography&gt; addresses = coordinates.Select(c =&gt;\n DbGeography.FromText(String.Format(\"POINT ({0} {1})\", c.Longitude, c.Latitude)));\n IEnumerable&lt;VehicleGeography&gt; vehicles = this.GPSInsightProvider.Query().Document.Placemarks.Select(p =&gt;\n new VehicleGeography\n {\n DriverName = p.DriverName,\n Point = DbGeography.FromText(String.Format(\"POINT ({0} {1})\", p.Point.Longitude, p.Point.Latitude))\n });\n ICollection&lt;object&gt; technicians = new List&lt;object&gt;();\n\n foreach (DbGeography address in addresses)\n {\n technicians.Add(\n vehicles\n .Select(v =&gt;\n new\n {\n DriverName = v.DriverName,\n Distance = v.Point.Distance(address) / 1609.344\n })\n .Where(v =&gt;v.Distance.HasValue)\n .OrderBy(v =&gt;v.Distance)\n .Take(3)\n .Select(v =&gt;\n new\n {\n DriverName = v.DriverName,\n Distance = String.Format(\"{0:#.#}\", v.Distance)\n }));\n }\n\n return technicians;\n }\n</code></pre>\n\n<p>My first question: Why does this return an object? I'm strongly against returning anonymous types, you really should be creating a class or struct for this data combination. Secondly, you know that at the bare minimum, it returns a List of these anonymous types, so at the least your should return a <code>List&lt;object&gt;</code></p>\n\n<p>Secondly:</p>\n\n<p><code>ICollection&lt;object&gt; technicians = new List&lt;object&gt;();</code></p>\n\n<p>Why are you specifically reducing the functionality that you're returning? Require least on parameters, return most.</p>\n\n<p>Use <code>var</code> on variable declarations where the right-hand-side makes the type obvious. This saves you extra typing when you want to change that variable's type later.</p>\n\n<p>e.g.</p>\n\n<p><code>ICollection&lt;object&gt; technicians = new List&lt;object&gt;();</code></p>\n\n<p>becomes</p>\n\n<p><code>var technicians = new List&lt;object&gt;();</code></p>\n\n<p>Is there a special reason you return only the top 3 results from your query? If so, that magic number should be a const somewhere with a reasonable name. If not, it should be a variable somewhere, again with a reasonable name.</p>\n\n<p>The same goes for <code>1609.344</code>. I'm guessing that's a conversion from meters to miles, but it doesn't make a ton of sense on its own.</p>\n\n<p>I think your LINQ is doing a little bit too much. I'd recommend splitting it up a bit so it's clearer what it's doing. Afterall, you're already looping through addresses, so split it up a little.</p>\n\n<pre><code> technicians.Add(\n vehicles\n .Select(v =&gt;\n new\n {\n DriverName = v.DriverName,\n Distance = v.Point.Distance(address) / 1609.344\n })\n .Where(v =&gt;v.Distance.HasValue)\n .OrderBy(v =&gt;v.Distance)\n .Take(3)\n .Select(v =&gt;\n new\n {\n DriverName = v.DriverName,\n Distance = String.Format(\"{0:#.#}\", v.Distance)\n }));\n</code></pre>\n\n<p>maybe becomes</p>\n\n<pre><code> var vehiclesByDistance = \n vehicles\n .Select(v =&gt;\n new\n {\n DriverName = v.DriverName,\n Distance = v.Point.Distance(address) / 1609.344\n })\n .Where(v =&gt;v.Distance.HasValue)\n .OrderBy(v =&gt;v.Distance);\n\n technicians.Add(\n vehiclesByDistance\n .Take(3)\n .Select(v =&gt;\n new\n {\n DriverName = v.DriverName,\n Distance = String.Format(\"{0:#.#}\", v.Distance)\n }));\n</code></pre>\n\n<p>Finally, I'm pretty sure your LINQ is breaking the Single Responsibility Principle. It appears to be performing distance unit conversion, sorting and formatting. It might be wise to split this up a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T11:29:20.530", "Id": "68380", "ParentId": "40133", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T04:13:36.860", "Id": "40133", "Score": "2", "Tags": [ "c#", "linq", "entity-framework", "geospatial" ], "Title": "DbGeography calculation" }
40133
<p>I have the following questions for the below code:</p> <ol> <li>Is there a simpler implementation of an on-screen counter?</li> <li>I made <code>CountTimer</code> inner class since it's tightly coupled with the GUI part anyway. What would be the best way to uncouple them?</li> </ol> <p></p> <pre><code>package count_timer; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CountTimerGUI implements ActionListener { private JFrame frame; private JPanel panel; private JLabel timeLabel = new JLabel(); private JButton startBtn = new JButton("Start"); private JButton pauseBtn = new JButton("Pause"); private JButton resumeBtn = new JButton("Resume"); private JButton stopBtn = new JButton("Stop"); private JButton resetBtn = new JButton("Reset"); private JButton greenBtn = new JButton("Green"); private JButton redBtn = new JButton("Red"); private CountTimer cntd; public CountTimerGUI() { setTimerText(" "); GUI(); } private void GUI() { frame = new JFrame(); panel = new JPanel(); panel.setLayout(new BorderLayout()); timeLabel.setBorder(BorderFactory.createRaisedBevelBorder()); panel.add(timeLabel, BorderLayout.NORTH); startBtn.addActionListener(this); pauseBtn.addActionListener(this); resumeBtn.addActionListener(this); stopBtn.addActionListener(this); resetBtn.addActionListener(this); greenBtn.addActionListener(this); redBtn.addActionListener(this); JPanel cmdPanel = new JPanel(); cmdPanel.setLayout(new GridLayout()); cmdPanel.add(startBtn); cmdPanel.add(pauseBtn); cmdPanel.add(resumeBtn); cmdPanel.add(stopBtn); cmdPanel.add(resetBtn); panel.add(cmdPanel, BorderLayout.SOUTH); JPanel clrPanel = new JPanel(); clrPanel.setLayout(new GridLayout(0,1)); clrPanel.add(greenBtn); clrPanel.add(redBtn); panel.add(clrPanel, BorderLayout.EAST); frame.setContentPane(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.pack(); cntd = new CountTimer(); } private void setTimerText(String sTime) { timeLabel.setText(sTime); } private void setTimerColor(Color sColor) { timeLabel.setForeground(sColor); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub JButton btn = (JButton) e.getSource(); if (btn.equals(greenBtn)) { setTimerColor(Color.GREEN.darker()); } else if (btn.equals(redBtn)) { setTimerColor(Color.RED); } else if (btn.equals(startBtn)) { cntd.start(); } else if (btn.equals(pauseBtn)) { cntd.pause(); } else if (btn.equals(resumeBtn)) { cntd.resume(); } else if (btn.equals(stopBtn)) { cntd.stop(); } else if (btn.equals(resetBtn)) { cntd.reset(); } } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CountTimerGUI(); } }); } private class CountTimer implements ActionListener { private static final int ONE_SECOND = 1000; private int count = 0; private boolean isTimerActive = false; private Timer tmr = new Timer(ONE_SECOND, this); public CountTimer() { count=0; setTimerText(TimeFormat(count)); } @Override public void actionPerformed(ActionEvent e) { if (isTimerActive) { count++; setTimerText(TimeFormat(count)); } } public void start() { count = 0; isTimerActive = true; tmr.start(); } public void resume() { isTimerActive = true; tmr.restart(); } public void stop() { tmr.stop(); } public void pause() { isTimerActive = false; } public void reset() { count = 0; isTimerActive = true; tmr.restart(); } } private String TimeFormat(int count) { int hours = count / 3600; int minutes = (count-hours*3600)/60; int seconds = count-minutes*60; return String.format("%02d", hours) + " : " + String.format("%02d", minutes) + " : " + String.format("%02d", seconds); } } </code></pre>
[]
[ { "body": "<p><strong>GUI</strong>:</p>\n\n<p>My preference is to have one <code>ActionListener</code> per button. This way you won't have to deal with checking the source before performing an action.</p>\n\n<hr>\n\n<p>Naming the method <code>GUI()</code> doesn't follow naming conventions. Methods should start with a lower case letter. <code>initGUI()</code> would be a better name as it also describes what is happening in the method.</p>\n\n<hr>\n\n<p>The <code>CountTimer</code> is not a GUI component, it should not be in the GUI initialization method.</p>\n\n<hr>\n\n<p><strong>CountTimer</strong>:</p>\n\n<p>AS you noted, <code>CountTimer</code> is tightly coupled with your GUI. This means you will have to do work in order to reuse it in any way. It would be better as a stand-alone class that you just happen to use in a GUI.</p>\n\n<p>I believe the following would be a good interface. It provides that same kind of control and allows the user of the counter to decide what to do when an event occurs.</p>\n\n<pre><code>class `CountTimer` {\n CountTimer(TickListener listener);\n void start();\n void stop();\n void pause();\n void resume();\n void reset();\n interface TickListener {\n tick(int count);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You don't set <code>isTimerActive</code> to <code>false</code> when you stop the timer. In general, this field does not give you anything because stopping the timer will stop events from being fired.</p>\n\n<p><strong>TimeFormat</strong>:</p>\n\n<p>Again, this function does not follow naming conventions.</p>\n\n<hr>\n\n<p>This should be code that is coupled with the GUI as it deals with the presentation of a number you are tracking, not the actual number value. </p>\n\n<hr>\n\n<p>You can pass multiple arguments to <code>String.format()</code>, so you don't need to call it three times. Just create one format sting that accepts all the values you want.</p>\n\n<p><strong>General</strong>:</p>\n\n<p>Star imports can pollute your namespace and make it hard to track down where a class is coming from.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T00:19:00.433", "Id": "67617", "Score": "0", "body": "A bit confused by the interface you posted. Why did you use `class` (and not `interface`) in the outer one? Or is it an `abstract class`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:49:23.670", "Id": "67645", "Score": "1", "body": "@PM 77-1 I started out writing a real class, but then decided only the interface was important. So Judy think of it as pseudo-code since you can't specify a constructor in an interface." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T05:54:48.357", "Id": "40138", "ParentId": "40136", "Score": "5" } }, { "body": "<p>+1 to <em>@unholysampler</em> and some other notes:</p>\n\n<ol>\n<li><p>I'd avoid abbreviations like <code>redBtn</code> and <code>cntd</code>. They make the code harder to read and could undermine autocomplete. For example, if you type <code>redBu</code> autocomplete won't find anything. It's often annoying. (See also: <a href=\"https://softwareengineering.stackexchange.com/a/71723/36726\">nikie's answer on Using single characters for variable names in loops/exceptions</a>)</p></li>\n<li>\n\n<pre><code>// TODO Auto-generated method stub\n</code></pre>\n\n<p>This comment only noise. Remove it. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>I think this kind of formatting is really hard to maintain:</p>\n\n<pre><code>if (btn.equals(greenBtn)) { setTimerColor(Color.GREEN.darker()); } \nelse if (btn.equals(redBtn)) { setTimerColor(Color.RED); }\nelse if (btn.equals(startBtn)) { cntd.start(); }\nelse if (btn.equals(pauseBtn)) { cntd.pause(); }\nelse if (btn.equals(resumeBtn)) { cntd.resume(); }\nelse if (btn.equals(stopBtn)) { cntd.stop(); }\nelse if (btn.equals(resetBtn)) { cntd.reset(); }\n</code></pre>\n\n<p>If you have a new variable with a longer name you have to modify seven other lines too to keep it nice. It also looks badly on revison control diff and could cause unnecessary merge conflicts.</p>\n\n<p>From <em>Code Complete, 2nd Edition</em> by <em>Steve McConnell</em>, p758:</p>\n\n<blockquote>\n <p><strong>Do not align right sides of assignment statements</strong></p>\n \n <p>[...]</p>\n \n <p>With the benefit of 10 years’ hindsight, I have found that, \n while this indentation style might look attractive, it becomes\n a headache to maintain the alignment of the equals signs as variable \n names change and code is run through tools that substitute tabs\n for spaces and spaces for tabs. It is also hard to maintain as\n lines are moved among different parts of the program that have \n different levels of indentation.</p>\n</blockquote></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:35:45.867", "Id": "67568", "Score": "0", "body": "What do you recommend for `VeryLongNameOfType` variable declaration? `VeryLongNameOfType veryLongNameOfType;`, `VeryLongNameOfType vlnot;`, or something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:45:34.990", "Id": "67582", "Score": "1", "body": "@PM77-1: I often use `notSoLongNameOfType` or just the last word (or last few words) of the name of the type but I don't think that there is an universal rule here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:22:23.010", "Id": "40193", "ParentId": "40136", "Score": "4" } } ]
{ "AcceptedAnswerId": "40138", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T05:25:47.467", "Id": "40136", "Score": "6", "Tags": [ "java", "swing", "timer" ], "Title": "Java GUI code with Swing Timer" }
40136
<p>My program is a fraction calculator that is supposed to calculate the basic operations (+, -, *, /) and is supposed to exit when I enter % as my sentinel value. This is what I have so far; any feedback is highly appreciated. </p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; enum MenuSelection{ NONE =0, ADD =1, SUBTRACT =2, MULTIPLY =3, DIVIDE =4, QUIT =5, END =6, }; int menu() { int MenuSelection=0; do { cout&lt;&lt;"\n1) Add"&lt;&lt;endl; cout&lt;&lt;"2) Subtract"&lt;&lt;endl; cout&lt;&lt;"3) Multiply"&lt;&lt;endl; cout&lt;&lt;"4) Divide"&lt;&lt;endl; cout&lt;&lt;"5) %"&lt;&lt;endl; cin&gt;&gt; MenuSelection; // if(MenuSelection&lt;= NONE || MenuSelection &gt;= END) cout&lt;&lt;"Please pick a number from 1-5 as shown in the menu selection."&lt;&lt;endl; if(MenuSelection==QUIT) {cout&lt;&lt;"You have chosen to exit the program"&lt;&lt;endl; cout&lt;&lt;"You have answered \n"; exit(1); } } while(MenuSelection&lt;= NONE || MenuSelection &gt;= END); // return MenuSelection; } void addFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result) { // NUM_result= (num1* den2) +(num2*den1); // DEN_result= den1*den2; } void subFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result) { NUM_result = (num1*den2) - (num2*den1); // DEN_result= den1*den2; // } void multiplyFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result) { NUM_result = num1*num2; // DEN_result= den1* den2; } void divideFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result) { // NUM_result = num1*den2; // DEN_result = den1*num2; } void input_values_FROM_USER(int &amp;num1, int &amp;num2, int &amp;den1, int &amp;den2) { cout&lt;&lt;endl; cout&lt;&lt;"Enter the numerator for first fraction--&gt;"; cin&gt;&gt;num1; cout&lt;&lt;"Enter denominator for first fraction--&gt; "; cin&gt;&gt;den1; cout&lt;&lt;"Enter numerator for second fraction--&gt; "; cin&gt;&gt;num2; cout&lt;&lt;"Enter denominator for second fraction--&gt; "; cin&gt;&gt;den2; cout&lt;&lt;"-------------------------------------------\n\n\n"; } void outputResults(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result, int operation) { if(operation == ADD) { cout&lt;&lt;"The sum of the two is--&gt; "&lt;&lt;num1&lt;&lt;'/'&lt;&lt;den1&lt;&lt;'+'&lt;&lt;num2&lt;&lt;'/'&lt;&lt;den2&lt;&lt;'='&lt;&lt;NUM_result&lt;&lt;'/'&lt;&lt;DEN_result&lt;&lt;endl; } if(operation== SUBTRACT) { cout&lt;&lt;"The difference of the two is--&gt; "&lt;&lt;num1&lt;&lt;'/'&lt;&lt;den1&lt;&lt;'- '&lt;&lt;num2&lt;&lt;'/'&lt;&lt;den2&lt;&lt;'='&lt;&lt;NUM_result&lt;&lt;'/'&lt;&lt;DEN_result&lt;&lt;endl; } if(operation== MULTIPLY) { cout&lt;&lt;"The product of the two is--&gt; " &lt;&lt;num1&lt;&lt;'/'&lt;&lt;den1&lt;&lt;'*'&lt;&lt;num2&lt;&lt;'/'&lt;&lt;den2&lt;&lt;'='&lt;&lt;NUM_result&lt;&lt;'/'&lt;&lt;DEN_result&lt;&lt;endl; } if(operation== DIVIDE) { cout&lt;&lt;"The quotient of the two is--&gt; " &lt;&lt;num1&lt;&lt;'/'&lt;&lt;den1&lt;&lt;'/'&lt;&lt;num2&lt;&lt;'/'&lt;&lt;den2&lt;&lt;'='&lt;&lt;NUM_result&lt;&lt;'/'&lt;&lt;DEN_result&lt;&lt;endl; } } void main() { int MenuSelection = NONE; int num1=0, num2=0, den1=0, den2=0; int NUM_result=0, DEN_result=0; cout&lt;&lt;"Author: Jose Soto."&lt;&lt;endl; cout&lt;&lt;"CSCI 110-- Jose Soto's Project 2 (Basic Fraction Arithmetic)\n\n"&lt;&lt;endl; do { MenuSelection= menu(); input_values_FROM_USER(num1,num2,den1,den2); if(MenuSelection==ADD) { addFractions(num1,num2,den1,den2,NUM_result, DEN_result); } if(MenuSelection==SUBTRACT) { subFractions(num1,num2,den1,den2,NUM_result, DEN_result); } if(MenuSelection==MULTIPLY) { multiplyFractions(num1,num2,den1,den2,NUM_result,DEN_result); } if(MenuSelection==DIVIDE) { divideFractions(num1,num2,den1,den2,NUM_result,DEN_result); } outputResults(num1,num2,den1,den2,NUM_result,DEN_result,MenuSelection); } while(MenuSelection != QUIT); cin.get(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T06:43:15.607", "Id": "67457", "Score": "2", "body": "Welcome! Please consider using proper, consistent indentation and avoiding excess whitespace. It's all over the place here and is hard to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T06:58:05.560", "Id": "67458", "Score": "1", "body": "Your original question didn't match the code you presented. We can't really review code that you intend to write, only code that you have already written, so I've edited the question accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:02:42.377", "Id": "67459", "Score": "0", "body": "I am supposed to have the number of correct out of the total answered. For example when I enter %, it is supposed to display something like \"You answered 8 out of 10 questions correctly, you have 80.5% which is a letter grade of B.\" Then it's supposed to exit the program. I'm not too sure what to write in terms of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:11:38.600", "Id": "67462", "Score": "2", "body": "In Code Review, our minimum standard is that we review code that already works. (See [help/on-topic].) Would you like a critique of the working features of your code, or would you prefer to withdraw the question until you have completed the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T08:04:53.827", "Id": "67469", "Score": "0", "body": "A critique would suffice." } ]
[ { "body": "<p>Had a few thoughts on your code. </p>\n\n<p>Your code doesn't accept a '%' to quit. Changing the menu to accept a '%' makes the rest of it inconsistent. so making all the input match the operation and changing the enum to reflect the character values instead of arbitrary ones helps with this.</p>\n\n<p>You're parsing the menu input in 2 places. It's easier to maintain if you use the menu routine just to read the input and keep any parsing of the input in the calling routine.</p>\n\n<p>A <code>switch</code> block improves the readability when you have to parse the user's input.</p>\n\n<p>When parsing user input through a menu putting the input into a <code>char</code> instead of an <code>int</code> makes it harder for user input to break your code.</p>\n\n<p>When you're sending literal strings to the console it's usually more efficient to to add a '\\n' to the end of it rather than sending <code>endl</code> separately.</p>\n\n<p>Here's some revised code which cleans up a number of issues:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstdlib&gt;\n\nusing namespace std;\n\n\nenum MenuSelection\n{\n ADD = 43,\n SUBTRACT = 45,\n MULTIPLY = 42,\n DIVIDE = 47,\n QUIT = 37,\n};\nvoid input_values_FROM_USER(int &amp;num1, int &amp;num2, int &amp;den1, int &amp;den2)\n\n{ \n cout&lt;&lt;endl;\n cout&lt;&lt;\"Enter the numerator for first fraction--&gt;\";\n cin&gt;&gt;num1;\n cout&lt;&lt;\"Enter denominator for first fraction--&gt; \";\n cin&gt;&gt;den1;\n cout&lt;&lt;\"Enter numerator for second fraction--&gt; \";\n cin&gt;&gt;num2;\n cout&lt;&lt;\"Enter denominator for second fraction--&gt; \";\n cin&gt;&gt;den2;\n cout&lt;&lt;\"-------------------------------------------\\n\\n\\n\";\n}\nchar menu()\n{ \n char MenuSelection = 0;\n\n cout&lt;&lt;\"\\n+) Add\\n\";\n cout&lt;&lt;\"-) Subtract\\n\";\n cout&lt;&lt;\"*) Multiply\\n\";\n cout&lt;&lt;\"/) Divide\\n\";\n cout&lt;&lt;\"%) Quit\\n\";\n cin&gt;&gt; MenuSelection;\n return MenuSelection;\n}\nvoid addFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result)\n{ \n NUM_result= (num1* den2) +(num2*den1);\n DEN_result= den1*den2;\n}\n\nvoid subFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result)\n{ \n NUM_result = (num1*den2) - (num2*den1);\n DEN_result= den1*den2;\n}\n\nvoid multiplyFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result)\n{ \n NUM_result = num1*num2;\n DEN_result= den1* den2;\n}\nvoid divideFractions(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result)\n{\n NUM_result = num1*den2;\n DEN_result = den1*num2;\n}\nvoid outputResults(int num1, int num2, int den1, int den2, int &amp;NUM_result, int &amp;DEN_result, int operation)\n{\n cout&lt;&lt;\"The result of the operation is--&gt; \"&lt;&lt;num1&lt;&lt;'/'&lt;&lt;den1&lt;&lt;(char)operation&lt;&lt;num2&lt;&lt;'/'&lt;&lt;den2&lt;&lt;'='&lt;&lt;NUM_result&lt;&lt;'/'&lt;&lt;DEN_result&lt;&lt;endl;\n}\nvoid main()\n{ \n char MenuSelection = '0';\n int num1=0, num2=0, den1=0, den2=0;\n int NUM_result=0, DEN_result=0;\n bool bad = false;\n cout&lt;&lt;\"Author: Jose Soto.\"&lt;&lt;endl;\n cout&lt;&lt;\"CSCI 110-- Jose Soto's Project 2 (Basic Fraction Arithmetic)\\n\\n\\n\";\n do\n {\n bad = false;\n MenuSelection = menu();\n switch(MenuSelection)\n {\n case ADD:\n input_values_FROM_USER(num1,num2,den1,den2);\n addFractions(num1,num2,den1,den2,NUM_result, DEN_result);\n break;\n case SUBTRACT:\n input_values_FROM_USER(num1,num2,den1,den2);\n subFractions(num1,num2,den1,den2,NUM_result, DEN_result);\n break;\n case MULTIPLY:\n input_values_FROM_USER(num1,num2,den1,den2);\n multiplyFractions(num1,num2,den1,den2,NUM_result,DEN_result);\n break;\n case DIVIDE:\n input_values_FROM_USER(num1,num2,den1,den2);\n divideFractions(num1,num2,den1,den2,NUM_result,DEN_result);\n break;\n case QUIT:\n cout&lt;&lt;\"\\nYou have chosen to exit the program\\n\"; \n bad = true;\n default:\n cout&lt;&lt;\"Please pick an option as shown in the menu.\\n\";\n bad = true;\n break;\n }\n if(!bad)\n outputResults(num1,num2,den1,den2,NUM_result,DEN_result,MenuSelection);\n }\n while(MenuSelection != QUIT);\n cin.get();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:10:25.673", "Id": "40150", "ParentId": "40140", "Score": "6" } }, { "body": "<p>Since you have a C++ tag on this question, I assume this is eventually meant as a C++ program. If that is the case, you should have </p>\n\n<pre><code>class Fraction {\n int denominator;\n int numerator;\n Fraction(int d, int n) : denominator(d), numerator(n) {}\n // define operators for +, -, etc.\n}\n</code></pre>\n\n<p>If you are still writing just in C—combine parsing the user input with dispatching the appropriate message to an object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T23:57:21.147", "Id": "40312", "ParentId": "40140", "Score": "5" } }, { "body": "<p>Some things not mentioned: </p>\n\n<ol>\n<li>Please do not use <code>using namespace std</code>. Read\n<a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this</a></li>\n<li><code>void main()</code> is <a href=\"http://www.stroustrup.com/bs_faq2.html#void-main\" rel=\"nofollow noreferrer\">not a part of the C++ standard</a>.</li>\n<li><p>Consider creating a class for representing fractions.\n The arithmetic functions should be implemented in operator overloads. Combining advice from the previous answers, your code\nwould become easier to read and maintain. </p>\n\n<p>Note: In general, operators that return a new value should be\nreturned by value.</p>\n\n<pre><code> class Fraction\n {\n\n public:\n Fraction(int a,int b) : numerator(a), denominator(b){}\n Fraction operator+(const Fraction&amp;, const Fraction&amp;); //Return a Fraction by value\n Fraction operator-(const Fraction&amp;, const Fraction&amp;);\n Fraction operator*(const Fraction&amp;, const Fraction&amp;);\n Fraction operator/(const Fraction&amp;, const Fraction&amp;);\n\n private:\n\n int denominator;\n int numerator;\n\n };\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-18T00:37:10.663", "Id": "67071", "ParentId": "40140", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T06:36:13.187", "Id": "40140", "Score": "5", "Tags": [ "c++", "beginner", "homework", "calculator", "rational-numbers" ], "Title": "Rational arithmetic calculator" }
40140
<p>While trying to learn more about arrays in C, I tried to write some code that did the following:</p> <ul> <li><p>Read a stream of numbers from the <code>stdin</code> and store them in an array</p></li> <li><p>Print the array in the order the numbers have been stored (i.e. print the original array)</p></li> <li><p>Print the array in reversed order</p></li> <li><p>Sort and print the array</p></li> <li><p>Given an array, search whether an entered value is present in an array. If it is present, print the index otherwise print that the value doesn't exist.</p></li> </ul> <p>It will be great if somebody could review it and let me know how to improve it.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; static void printArray(int array[],int startIndex,int endIndex){ if(startIndex &lt; endIndex){ while(startIndex &lt;= endIndex){ printf(" %i ",array[startIndex++]); } }else{ while(startIndex &gt;= endIndex){ printf(" %i ",array[startIndex--]); } } printf("\n"); } static int cmpfunc(const void * a,const void * b) { if(*(int*)a &gt; *(int*)b) return 1; else return -1; } static void sortedArray(int* originalArray){ qsort((void*)originalArray,(sizeof(originalArray)/sizeof(originalArray[0])),sizeof(originalArray[0]),cmpfunc); return; } static int getIndex(int value,int array[],int size){ int i; for(i = 0;i &lt; size;i++){ if(array[i] == value){ return i; } } return -1; } static void identifyTheIndices(int *arbitraryArray,int size){ char buf[10]; printf("Enter the value to search for..enter q to exit\n"); while(fgets(buf,sizeof buf,stdin) != NULL){ if(buf[0] == 'q'){ break; } char *end; int value = (int) strtol(buf,&amp;end,0); if(end != buf){ int currentIndex = getIndex(value,arbitraryArray,size); if(currentIndex &gt; -1){ printf("Found the entered value %i at index %i\n",value,currentIndex); }else{ printf("Entered value %i doesn't exist\n",value); } } printf("Enter the value to search for..enter q to exit\n"); } } int main(int argc,char **argv) { int counter = 0; if(argc &gt; 1){ int originalArray[argc-1]; while(counter &lt; (argc - 1)){ int currentValue = atoi(argv[counter+1]); printf("Reading input value %i into array \n",currentValue); originalArray[counter] = currentValue; counter++; } int size = sizeof(originalArray)/sizeof(originalArray[0]); printf("Printing out the original array\n"); printArray(originalArray,0,size - 1); printf("Printing out the array in reverse\n"); printArray(originalArray,size - 1,0); printf("Sorting the array in ascending order\n"); qsort((void*)originalArray,size,sizeof(originalArray[0]),cmpfunc); printf("Printing out the sorted array\n"); printArray(originalArray,0,size-1); int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 }; identifyTheIndices(arr,sizeof(arr)/sizeof(arr[0])); } return 0; } </code></pre>
[]
[ { "body": "<p>@sc_ray pretty good effort if you are new to C programming.</p>\n\n<p>A few points in your code which you can improve:</p>\n\n<ol>\n<li><p>Taking array values from command-line is not good. Its better you use scanf and proper data-type. Below are logs when I pass a very long int value as cmd-line argument. It fails to store the value and gives garbage.</p>\n\n<pre><code>./a.out 7 999999999999 0 123\nReading input value 7 into array\nReading input value 2147483647 into array\nReading input value 0 into array\nReading input value 123 into array\nPrinting out the original array\n7 2147483647 0 123\n.....\n</code></pre></li>\n<li><p>Hope this is a code pasting mistake. Remove this <code>arr</code> array not needed.</p>\n\n<pre><code>int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 };\nidentifyTheIndices(arr,sizeof(arr)/sizeof(arr[0]));\n</code></pre></li>\n<li><p>The searching of elements in array can be improved using <a href=\"https://stackoverflow.com/questions/249392/binary-search-in-array\">Binary Search Algo</a> rather than sequential search.</p></li>\n</ol>\n\n<p>Rest all looks good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T06:18:22.080", "Id": "67668", "Score": "0", "body": "Thanks. I will modify the array search to be binary search. It is definitely more computationally efficient." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T13:15:44.943", "Id": "40152", "ParentId": "40141", "Score": "4" } }, { "body": "<p>I disagree with @vishram0709 about taking values from the command line. There\nis nothing wrong with this. It is often useful to have the option of taking\nvalues from the command line; you can also prompt for input values if none are\ngiven on the command line.</p>\n\n<p>The fault he pointed out is caused by not <strong>validating</strong> the input values. The\nsame error could occur if the value was input using <code>scanf</code> - and you saw in\none of your earlier questions that <code>scanf</code> has its own issues. To check the\ninput values you can use</p>\n\n<pre><code>errno = 0;\nchar *end;\nlong value = strtol(string, &amp;end, 0);\nif (errno == ERANGE) {\n perror(string);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>The input values above are now <code>long</code> not <code>int</code> because <code>strtol</code> converts to\n<code>long</code> and detects <code>ERANGE</code> based upon the size of the maximum possible <code>long</code>.\nIf you wanted to detect over-range <code>int</code> values you could use:</p>\n\n<pre><code>char *end;\nlong value = strtol(string, &amp;end, 0);\nif ((int) value != value) {\n fprintf(stderr, \"%s: Result too large\\n\", string);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>Some other observations:</p>\n\n<ul>\n<li><p><code>printArray</code> would be more normal taking a <code>const</code> start point and a length.</p>\n\n<pre><code>static void printArray(const int array[], size_t n);\n</code></pre>\n\n<p>and have another <code>printReverseArray</code> to print the reversed array.</p></li>\n<li><p><code>cmpfunc</code> should return 0 if the items match.</p></li>\n<li><p><code>sortedArray</code> is unused. It is also wrong in that</p>\n\n<pre><code>(sizeof(originalArray)/sizeof(originalArray[0])),\n</code></pre>\n\n<p>gives something meaningless when <code>originalArray</code> is a pointer.\n<code>sizeof(originalArray)</code> gives the size of the pointer, not the array that\nit points to.</p>\n\n<p>Later on in <code>main</code>, you do it right, with</p>\n\n<pre><code>int size = sizeof(originalArray)/sizeof(originalArray[0]);\n</code></pre>\n\n<p>because here <code>originalArray</code> is a real array, not a pointer. But you\nalready had the array size (<code>argc - 1</code>), so this was unnecessary.</p></li>\n<li><p>the <code>array</code> parameter to <code>getIndex</code> should be <code>const</code>. But the function is\nunreliable, as it fails for negative numbers. To make it work you need\nto separate the return value from the success/failure.</p>\n\n<pre><code>static int getIndex(int value, int array[], int size, int *index);\n</code></pre></li>\n<li><p>add some spaces, eg after <code>if</code>, <code>while</code>, <code>for</code>, <code>;</code> and <code>,</code> etc.</p></li>\n<li><p>you use the variable names <code>array</code>, <code>originalArray</code> and <code>arbitraryArray</code> to\nidentify essentially the same thing - an array. Don't use multiple names\nfor equivalent things without good reason.</p></li>\n<li><p>Your reading loop</p>\n\n<pre><code>int counter = 0;\n...\nint originalArray[argc-1];\nwhile(counter &lt; (argc - 1)){\n int currentValue = atoi(argv[counter+1]);\n printf(\"Reading input value %i into array \\n\",currentValue);\n originalArray[counter] = currentValue;\n counter++; \n}\n</code></pre>\n\n<p>would be neater as:</p>\n\n<pre><code>--argc;\nint array[argc];\nfor (int i = 0; i &lt; argc; ++i) {\n int v = atoi(argv[i + 1]);\n printf(\"Reading input value %i into array \\n\", v);\n array[i] = v;\n}\n</code></pre>\n\n<p>shorter variable names are ok, and indeed preferable, where their scope is\nrestricted. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T06:15:40.960", "Id": "67667", "Score": "0", "body": "I am learning a lot from your reviews. I had a question, why would I be passing the array parameter as a const? I can probably look this up but is const essentially making the reference to the array immutable, so that the array cannot be modified by the function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:18:38.800", "Id": "67704", "Score": "0", "body": "Thanks @William Morris for pointing that out. I meant to say that taking care of error senarios was needed in the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:18:30.590", "Id": "67717", "Score": "1", "body": "Yes that is right. The function cannot modify the array values if the array is passed `const`. Neither can any function called by that function with the array as a parameter. That allows the compiler to optimise more and tells users of the function that their data will not be changed. It is good practice to add `const` to pointer parameters where possible." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:54:51.873", "Id": "40184", "ParentId": "40141", "Score": "4" } } ]
{ "AcceptedAnswerId": "40184", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:03:19.190", "Id": "40141", "Score": "3", "Tags": [ "c", "array" ], "Title": "Array manipulation exercise" }
40141
<p>Currently building my personal site using Jekyll, inuitcss and GitHub Pages. I'd like to hear your thoughts on the markup of my blog page and its post pages.</p> <p>What do you think about handling logo's like this? Also I'm not sure about the headings. The page-title probably should be part of the main section.</p> <p><strong>blog markup:</strong></p> <pre><code>&lt;body&gt; &lt;header class=site-head role=banner&gt; &lt;a href="/" class=site-logo&gt; &lt;!-- base64 encoded transparent gif; logo is applied through background-image --&gt; &lt;img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="site-title"&gt; &lt;/a&gt; &lt;nav class=site-nav role=navigation&gt; &lt;a href="/" class=nav__item--blog rel=home&gt;Blog&lt;/a&gt;&lt;!-- --&gt;&lt;a href="/portfolio" class=nav__item--portfolio&gt;Portfolio&lt;/a&gt;&lt;!-- --&gt;&lt;a href="/profil" class=nav__item--profil&gt;Profil&lt;/a&gt;&lt;!-- --&gt;&lt;a href="/impressum" class=nav__item--impressum&gt;Impressum&lt;/a&gt; &lt;/nav&gt; &lt;h1 class=page-title&gt;Freundliche Artikel&lt;/h1&gt; &lt;/header&gt; &lt;main class="page-content wrapper" role=main&gt; &lt;ul class=post-list&gt; &lt;li&gt; &lt;a href="/2014/01/one-nice-little-article" class=post-list__link&gt; &lt;span class=post-list__time&gt;26. Januar 2014&lt;/span&gt; &lt;h2 class=post-list__title&gt;We can't stop here&lt;/h2&gt; &lt;/a&gt; &lt;p&gt;This is a post excerpt from the actual article. Usually the first paragraph.&lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="/2014/01/sweet-introduction" class=post-list__link&gt; &lt;span class=post-list__time&gt;15. Januar 2014&lt;/span&gt; &lt;h2 class=post-list__title&gt;Introduction anyone?&lt;/h2&gt; &lt;/a&gt; &lt;p&gt;This is a post excerpt from the actual article. Usually the first paragraph.&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/main&gt; &lt;footer class=site-foot role=contentinfo&gt; &lt;p&gt;Author. Hosting. Used tools.&lt;/p&gt; &lt;/footer&gt; &lt;/body&gt; </code></pre> <p><strong>post markup:</strong></p> <pre><code>&lt;body&gt; &lt;header class=site-head role=banner&gt; &lt;a href="/" class=site-logo&gt; &lt;!-- base64 encoded transparent gif; logo is applied through background-image --&gt; &lt;img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="site-title"&gt; &lt;/a&gt; &lt;nav class=site-nav role=navigation&gt; &lt;a href="/" class=nav__item--blog rel=home&gt;Blog&lt;/a&gt;&lt;!-- --&gt;&lt;a href="/portfolio" class=nav__item--portfolio&gt;Portfolio&lt;/a&gt;&lt;!-- --&gt;&lt;a href="/profil" class=nav__item--profil&gt;Profil&lt;/a&gt;&lt;!-- --&gt;&lt;a href="/impressum" class=nav__item--impressum&gt;Impressum&lt;/a&gt; &lt;/nav&gt; &lt;/header&gt; &lt;main class="page-content wrapper" role=main&gt; &lt;article class=entry&gt; &lt;span class=entry__meta&gt;26. Januar 2014&lt;/span&gt; &lt;h1&gt;We can't stop here&amp;hellip;&lt;/h1&gt; &lt;p&gt;How're you doing? Eveything alright?&lt;/p&gt; &lt;p&gt;Another paragraph. Might be a conclusion.&lt;/p&gt; &lt;/article&gt; &lt;/main&gt; &lt;footer class=site-foot role=contentinfo&gt; &lt;p&gt;Author. Hosting. Used tools.&lt;/p&gt; &lt;/footer&gt; &lt;/body&gt; </code></pre>
[]
[ { "body": "<h3>Blog markup</h3>\n\n<p>The site title should be a <code>h1</code>.</p>\n\n<p>Use an <code>ul</code> for the navigation links. Or, if you don’t want that, use at least a <code>div</code> element for each link, or a textual separator between each link.</p>\n\n<p>The page title (+ the content under its scope) needs be enclosed in a sectioning element (probably <code>section</code> in this case). Also, don’t include the page title in the site’s <code>header</code>.</p>\n\n<p>The <code>main</code> element should also contain the page title.</p>\n\n<p>Each post excerpt should get its own <code>article</code> (as a general rule: don’t use headings in list items (e.g. <code>li</code>) unless they have a sectioning content parent).</p>\n\n<p>You may use the <code>time</code> element for the dates.</p>\n\n<p>Which leads to (excluding anything not related to the outline):</p>\n\n<pre><code>&lt;body&gt;\n\n &lt;header&gt;\n\n &lt;h1&gt;&lt;img src=\"\" alt=\"…\"&gt;&lt;/h1&gt;\n\n &lt;nav&gt;&lt;/nav&gt;\n\n &lt;/header&gt;\n\n &lt;main&gt;\n &lt;section&gt;\n\n &lt;h1&gt;Freundliche Artikel&lt;/h1&gt;\n\n &lt;ul&gt;\n &lt;li&gt;\n &lt;article&gt;\n &lt;h2&gt;We can't stop here&lt;/h2&gt;\n &lt;/article&gt;\n &lt;/li&gt;\n &lt;li&gt;\n &lt;article&gt;\n &lt;h2&gt;Introduction anyone?&lt;/h2&gt;\n &lt;/article&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n\n &lt;/section&gt;\n &lt;/main&gt;\n\n &lt;footer&gt;&lt;/footer&gt;\n\n&lt;/body&gt;\n</code></pre>\n\n<h3>Post markup</h3>\n\n<p>Again, use the site heading as <code>h1</code> (as a child of body, without any sectioning content element parents).</p>\n\n<p>Again, use <code>ul</code> for the navigation links etc.</p>\n\n<p>You may use the <code>time</code> element for the dates.</p>\n\n<p>Your <code>footer</code> contains information about the whole page (<code>body</code>). So if one of the articles is written by a different author, the <code>article</code> should get its own <code>footer</code>.</p>\n\n<hr>\n\n<p>Some further explanations from the comments:</p>\n\n<h3>(a) Why the site name should be <code>body</code>s <code>h1</code></h3>\n\n<p>Please see <a href=\"https://stackoverflow.com/a/14920215/1591669\">my answer</a> to a different question. The last example (HTML + the corresponding outline) applies to your case. </p>\n\n<p>In short: When you don’t use a heading for the site name, your main content heading will be used as the heading for the whole <code>body</code>. Everything else on this page will be in scope of this heading. But there are things on your page which shouldn’t be in its scope, for example your navigation. </p>\n\n<p>In your current HTML, the <code>nav</code> (which clearly represents navigation for the whole <em>site</em>) would be in the scope of \"Freundliche Artikel\" (while your <code>nav</code> might be friendly, it’s clearly not an article ;-)).</p>\n\n<h3>(b) Why the logo can be used for (a)</h3>\n\n<p>(You need to agree with (a) first.)</p>\n\n<p>Headings are not for text only. A logo typically represents the site name (blog name, company name, whatever). It doesn’t matter if the logo includes a textual representation or if it’s graphics only. In both cases, the <code>alt</code> text would be the textual site name, as this is what the logo stands for.</p>\n\n<h3>(c) Why you can’t use sectioning elements (for your main content) when your main content is not included in a sectioning element and you have a site heading</h3>\n\n<p>Let’s take this (wrong) example:</p>\n\n<pre><code>&lt;h1&gt;Artikelschmiede &lt;!-- site name --&gt;&lt;/h1&gt;\n\n&lt;h2&gt;Freundliche Artikel &lt;!-- main content heading --&gt;&lt;/h2&gt;\n\n&lt;article&gt;\n &lt;h3&gt;We can't stop here&lt;/h3&gt;\n&lt;/article&gt;\n\n&lt;article&gt;\n &lt;h3&gt;Introduction anyone?&lt;/h3&gt;\n&lt;/article&gt;\n</code></pre>\n\n<p>The outline is:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>1. Artikelschmiede\n 1.1 Freundliche Artikel\n 1.2 We can't stop here\n 1.3 Introduction anyone?\n</code></pre>\n\n<p>But the outline should be:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>1. Artikelschmiede\n 1.1 Freundliche Artikel\n 2.1 We can't stop here\n 2.2 Introduction anyone?\n</code></pre>\n\n<p>So to get the correct outline, use a sectioning element for the whole main content (typically <code>section</code> or <code>article</code>):</p>\n\n<pre><code>&lt;h1&gt;Artikelschmiede &lt;!-- site name --&gt;&lt;/h1&gt;\n\n&lt;section&gt;\n &lt;h2&gt;Freundliche Artikel &lt;!-- main content heading --&gt;&lt;/h2&gt;\n\n &lt;article&gt;\n &lt;h3&gt;We can't stop here&lt;/h3&gt;\n &lt;/article&gt;\n\n &lt;article&gt;\n &lt;h3&gt;Introduction anyone?&lt;/h3&gt;\n &lt;/article&gt;\n&lt;/section&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:15:31.340", "Id": "67716", "Score": "0", "body": "1. I disagree on using `h1` only for site-titles. I have a logo and no present site-title on the page. This makes the page-title on pages and the article titles in post-pages the highest heading in the hierarchy. 2. Isn't the whole page itself the scope for my page-title? The section element seperates sections of content (like of articles). I agree on moving it to the main element, tho. 3. Also using `article` for the post excerpts makes sense. (to be continued...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:25:24.130", "Id": "67719", "Score": "0", "body": "4. Using the `time` element there is a good idea. 5. Good point for the `footer` inside articles. However this is my personal site. There won't be other authors (for the time now. ;). 6. I'd like to hear a reason for using a list for my navigation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:32:28.453", "Id": "67724", "Score": "0", "body": "@kleinfreund: 1. Headings don’t need to consist of text. And that aside, your `img` has `alt` content, which will get used as heading content for consumers not capable of parsing images (i.e., search engines). Without using the site name in the top-level heading, your document outline will be wrong!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:34:10.507", "Id": "67727", "Score": "0", "body": "@kleinfreund: 2. Yes, currently. But when you use the site name as top-level heading (or in other words: as heading for the `body` sectioning root element) [→ 1], then you’ll have to use a sectioning element for the main content (or you may use corresponding heading levels `h2`-`h6` but (!) then you can’t use sectioning content elements anymore on that page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:38:38.920", "Id": "67731", "Score": "0", "body": "@kleinfreund: 6. -- a) First, why you should use block level elements (like `div` or `li`): in text browsers (i.e., browsers without CSS support), your links would be displayed all in one line, without any separators. So either use block level elements (then each link will be displayed on its own line) or use a textual separator (e.g., `·` or something like that). -- b) Why `ul`? Because your navigation consists of a *set* of links, e.g., it represents the sections of your site (you are communicating: \"My site is divided into four sections\", which gives a start/end for screenreaders)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T18:28:43.980", "Id": "67811", "Score": "0", "body": "1. A logo is not a heading. I don't see how not using an actual site-title as the `h1` makes your document outline wrong. Sources? 2. Why can't I use sectioning elements on that page anymore when I use `h2`-`h6`? Maybe we should discuss this in a chat?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T19:58:26.473", "Id": "67826", "Score": "1", "body": "@kleinfreund: I added explanations to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T18:12:44.310", "Id": "67979", "Score": "0", "body": "In my opinion, using a heading for a logo is wrong and I keep it this way. I moved my page title to the `main` element, which makes my outline correct for now. You're right though, if I use a h1 as a site title, I will need to rework the outline. I also considered deliting the navigational elements with line-breaks (whitespace), but I switched to using an `ul` now. Btw I had no votes left yesterday and didn't remember today. I will upvote and accept tomorrow. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T20:20:55.857", "Id": "67989", "Score": "0", "body": "@kleinfreund: Note that if you agree with (a), you could still get the correct ouline by using a sectioning element for the main content and omitting a heading for the `body`. My point is not (primarily) that the logo needs to be used as site heading, but that there needs to be a top-level entry in the outline. This can be achieved by using a heading (containing text, a graphic, an audio file …) or by using sectioning elements explicitly everywhere, so that no heading belongs to `body`." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:59:56.510", "Id": "40262", "ParentId": "40142", "Score": "2" } } ]
{ "AcceptedAnswerId": "40262", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T07:37:31.657", "Id": "40142", "Score": "5", "Tags": [ "html", "html5" ], "Title": "Markup of a blog page and its posts" }
40142
<p>I just started trying out SVG the other day. Eventually I hope to be able to know how to do what SE does with their reputation graphs.</p> <p>For now, I've just been trying to set up an easier way to make lines. I think my below code is decent, but please let me know what I can improve on or what I'm doing poorly.</p> <p>Would like your thoughts before I start adding like animations, creativity, data to it.</p> <p>Demo <a href="http://jsfiddle.net/ECKNh/">http://jsfiddle.net/ECKNh/</a></p> <pre><code>var Line = {}; Line.LINES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; var SVGline = function (l) { this.l = l; } for (var i = Line.LINES.length; i &gt; -1; i -= 1) { Line[Line.LINES[i]] = new SVGline(Line.LINES[i]); } SVGline.prototype.createline = function (x1, y1, x2, y2, color, w) { var aLine = document.createElementNS('http://www.w3.org/2000/svg', 'line'); aLine.setAttribute('x1', x1); aLine.setAttribute('y1', y1); aLine.setAttribute('x2', x2); aLine.setAttribute('y2', y2); aLine.setAttribute('stroke', color); aLine.setAttribute('stroke-width', w); return aLine; } function start() { var aSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); aSvg.setAttribute('width', 1000); aSvg.setAttribute('height', 400); var w = document.getElementById('container'); for (var i = 1; i &lt; 11; i += 1) { var x1 = Math.floor(Math.random() * 500 / 2); var xx = Line[i].createline(x1, 0, 200, 300, 'rgb(0,0,' + x1 + ')', i); aSvg.appendChild(xx); } w.appendChild(aSvg); } start(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-19T05:19:14.103", "Id": "212113", "Score": "1", "body": "Just to help you out to see how other people are creating _SVG_ renderers you might want to check out [TWO.js](https://jonobr1.github.io/two.js/). That library has a very nice way of handling __2D__ rendering. Hope that helps:)" } ]
[ { "body": "<p><em>Let me know what I can improve on or what I'm doing poorly.</em></p>\n\n<p>If you are going to do animations with those lines, you will want to keep track of them. I am assuming that is why you have an array of <code>LINES</code>. However, in <code>createLine</code> you create the SVG element and just return it, you do not keep a reference to it. So it will be hard to animate those lines, you would have to query the DOM to find them back.</p>\n\n<p>I suggest you have an object that creates SVG elements, a factory so to speak. And then another object that tracks lines you have created so far, mostly to do animations and other fun stuff.</p>\n\n<p>The factory object could be something like</p>\n\n<pre><code>SVG = {\n createCanvas : function( width, height, containerId ){\n var container = document.getElementById( containerId );\n var canvas = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n canvas.setAttribute('width', width);\n canvas.setAttribute('height', height);\n container.appendChild( canvas ); \n return canvas;\n },\n createLine : function (x1, y1, x2, y2, color, w) {\n var aLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');\n aLine.setAttribute('x1', x1);\n aLine.setAttribute('y1', y1);\n aLine.setAttribute('x2', x2);\n aLine.setAttribute('y2', y2);\n aLine.setAttribute('stroke', color);\n aLine.setAttribute('stroke-width', w);\n return aLine;\n }\n}\n</code></pre>\n\n<p>Initially the <code>lines</code> object could be as simple as</p>\n\n<pre><code>var lines = [];\nlines.addLine = function( line ){\n this.push( line );\n return line;\n}\n</code></pre>\n\n<p>Your start function would then be something like</p>\n\n<pre><code>function start() {\n var canvas = SVG.createCanvas( 1000 , 400 , 'container' ),\n lineElement, i, x1;\n\n for (i = 1; i &lt; 11; i += 1) {\n x1 = Math.floor(Math.random() * 500 / 2),\n lineElement = lines.addLine( SVG.createLine(x1, 0, 200, 300, 'rgb(0,0,' + x1 + ')', i) );\n canvas.appendChild( lineElement );\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-18T05:33:34.920", "Id": "211940", "Score": "0", "body": "Being new to SVG , I am just starting to learn ways to create a line with JavaScript and @konjin's code looks great. But there is a typo error in the `for` loop: `createline` should be `createLine`. I noticed it when running your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-18T07:49:32.120", "Id": "276969", "Score": "0", "body": "`lines.addLine = …` looks weird. This makes it difficult to iterate over the array. The code can be made clearer without that function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-18T07:51:43.057", "Id": "276970", "Score": "0", "body": "What are your reasons for sometimes having a space inside parentheses and sometimes not?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T03:12:51.443", "Id": "40324", "ParentId": "40145", "Score": "8" } } ]
{ "AcceptedAnswerId": "40324", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T09:05:28.250", "Id": "40145", "Score": "12", "Tags": [ "javascript", "svg" ], "Title": "Making lines with SVG and JavaScript" }
40145
<p>I have this stored procedure that I'd like improved. I have changed the DB name and the procedure name. I am working on SQL Server 2000.</p> <pre><code> USE [DBName] ALTER PROCEDURE [dbo].[Table_GetSomething] @name nvarchar(50), @Cooltree nvarchar(10), @aID int, @bID int = 0 AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; declare @bCE bit = 0 declare @aCE bit = 0 declare @bCE2 bit = 0 declare @aCE2 bit = 0 declare @tableName varchar(60) declare @table table ( FA nvarchar(255), FN nvarchar(255), [Seeboj] nvarchar(1024), Brotty nvarchar(4000), CD nvarchar(4000) ) if( select count(*) from ECCB where aID = @aID and bID = @bID and [Name] = @name) = 1 set @bCE = 1 else if( select count(*) from ECCA where aID = @aID and [Name] = @name) &gt; 0 set @aCE = 1 if( select count(*) from ECCDB where aID = @aID and bID = @bID) &gt; 0 set @bCE2 = 1 else if( select count(*) from ECCDA where aID = @aID) &gt; 0 set @aCE2 = 1 if @bCE = 1 insert into @table (FA, FN, [Seeboj], Brotty) select FA, FN, [Seeboj], Brotty from ECCB where aID = @aID and bID = @bID and [Name] = @name else if(@aCE = 1) insert into @table (FA, FN, [Seeboj], Brotty) select FA, FN, [Seeboj], Brotty from ECCA where aID = @aID and [Name] = @name else insert into @table (FA, FN, [Seeboj], Brotty) select FA, FN, [Seeboj], Brotty from EDC where Cooltree = @Cooltree and [Name] = @name if(@bCE2 = 1) update @table set CD = (select CD from ECCDB where aID = @aID and bID = @bID) else if(@aCE2 = 1) update @table set CD = (select CD from ECCDA where aID = @aID) else update @table set CD = (select CD from EDCCD where Cooltree = @Cooltree) select * from @table END </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T11:19:01.507", "Id": "67478", "Score": "7", "body": "The picture is missing and an explanation what this does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:34:13.543", "Id": "67531", "Score": "12", "body": "I agree with @Bobby. Please provide sufficient [context](http://codereview.stackexchange.com/tags/sql/info); it's really hard to review SQL not knowing what the schema looks like and what you are trying to accomplish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:41:12.697", "Id": "67534", "Score": "3", "body": "Or in different words: With no schema, people may assume you did everything there on purpose and therefor won't answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:46:23.753", "Id": "67583", "Score": "3", "body": "More to the point: reading this code gives the distinct impression that any real problems here are not with the code, but with the underlying schema. \"Normalization nightmare\" is the alliterative phrase I might use. It is hard to tell when you have so thoroughly obfuscated any explanatory value in the variable names, but that's my gut reaction to this sequence of operations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T14:30:41.593", "Id": "67950", "Score": "7", "body": "Even more to the point, without a description of what the code is supposed to do, then the only reference is what the code actually does, as a result, the code is doing exactly what it does, thus it is perfect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-16T15:36:14.160", "Id": "102141", "Score": "1", "body": "@SharePointer, Let me know what you think of my revised answer, maybe post a follow up question let's see if we can counter those Down Votes. We all love reviewing code and would love to help you out if you give us a chance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-07T16:59:22.753", "Id": "332184", "Score": "1", "body": "The current question title, which states what your code *is*, rather than what it's *for*, applies to too many questions on this site to be useful. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-08T10:15:58.920", "Id": "332313", "Score": "0", "body": "@TobySpeight Did you looked at edits ? if you didn't please do so :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-08T10:19:33.180", "Id": "332314", "Score": "0", "body": "Yes, I have looked through the edits - at no time has the title ever included the *purpose* of this stored procedure. The site standard is for the title to simply state *the task accomplished by the code*." } ]
[ { "body": "<p>You have a lot of <code>if</code> statements in your SQL. This screams at me that you are doing something in your SQL that should be done in the application, and that this SQL should be separated into two distinct stored procedures. </p>\n\n<p>The benefits of doing this:</p>\n\n<ol>\n<li>Faster stored procedures</li>\n<li>Use a coding language instead of a query language to do the logic where it was meant to be done, it will be way easier to do logic in something like C# or VB.</li>\n</ol>\n\n<p>You need to look at what you are trying to do as a whole here, because this doesn't look like much fun.</p>\n\n<hr>\n\n<p>You can get rid of all of these variables</p>\n\n<pre><code>declare @bCE bit = 0\ndeclare @aCE bit = 0\ndeclare @bCE2 bit = 0\ndeclare @aCE2 bit = 0\ndeclare @tableName varchar(60)\n</code></pre>\n\n<p>The <code>@tableName</code> variable I didn't see being used anywhere.</p>\n\n<p>Instead of having two sets of if then statements you can merge the actions with the checks, something like this</p>\n\n<pre><code>IF(SELECT COUNT(*)\n FROM ECCB\n WHERE aID = @aID\n AND bID = @bID\n AND [Name] = @name) = 1\nBEGIN\n INSERT INTO @table (FA, FN, [Seeboj], Brotty)\n SELECT FA, FN, [Seeboj], Brotty\n FROM ECCB\n WHERE aID = @aID\n AND bID = @bID\n AND [Name] = @name\nEND\nELSE\nBEGIN\n IF(SELECT COUNT(*)\n FROM ECCA\n WHERE aID = @aID\n AND [Name] = @name) &gt; 0\n BEGIN\n INSERT INTO @table (FA, FN, [Seeboj], Brotty)\n SELECT FA, FN, [Seeboj], Brotty\n FROM ECCA\n WHERE aID = @aID\n AND [Name] = @name\n END\n ELSE\n BEGIN\n INSERT INTO @table (FA, FN, [Seeboj], Brotty)\n SELECT FA, FN, [Seeboj], Brotty\n FROM EDC\n WHERE Cooltree = @Cooltree\n AND [Name] = @name\n END\nEND\n\n\nIF(SELECT COUNT(*)\n FROM ECCDB\n WHERE aID = @aID\n AND bID = @bID) &gt; 0\nBEGIN\n UPDATE @table\n SET CD =\n (SELECT CD\n FROM ECCDB\n WHERE aID = @aID\n AND bID = @bID)\nEND\nELSE\nBEGIN\n IF(SELECT COUNT(*)\n FROM ECCDA\n WHERE aID = @aID) &gt; 0\n BEGIN\n UPDATE @table\n SET CD =\n (SELECT CD\n FROM ECCDA\n WHERE aID = @aID)\n END\n ELSE\n BEGIN\n UPDATE @table\n SET CD =\n (SELECT CD\n FROM EDCCD\n WHERE Cooltree = @Cooltree)\n END\nEND\n</code></pre>\n\n<p>You might have noticed that I also added <code>BEGIN</code> and <code>END</code> statements for the different blocks, I think this adds to the readability of the code, it might even be necessary, I am not sure in SQL SERVER 2000 though, I normally code in 2008. </p>\n\n<p>I also capitalized all the fun SQL SERVER keywords, it doesn't really matter except for readability, but I believe that it is standard practice to capitalize these words even though SQL SERVER is case insensitive when it comes to keywords.</p>\n\n<hr>\n\n<p>With all the changes that I made it looks like this:</p>\n\n<pre><code>USE [DBName]\n\nALTER PROCEDURE [dbo].[Table_GetSomething] \n @name NVARCHAR(50), \n @Cooltree NVARCHAR(10),\n @aID INT,\n @bID INT = 0\nAS\nBEGIN\n -- SET NOCOUNT ON added to prevent extra result sets from\n -- interfering with SELECT statements.\n SET NOCOUNT ON;\n\n DECLARE @table TABLE\n (\n FA NVARCHAR(255),\n FN NVARCHAR(255),\n [Seeboj] NVARCHAR(1024),\n Brotty NVARCHAR(4000),\n CD NVARCHAR(4000)\n )\n\n IF(SELECT COUNT(*)\n FROM ECCB\n WHERE aID = @aID\n AND bID = @bID\n AND [Name] = @name) = 1\n BEGIN\n INSERT INTO @table (FA, FN, [Seeboj], Brotty)\n SELECT FA, FN, [Seeboj], Brotty\n FROM ECCB\n WHERE aID = @aID\n AND bID = @bID\n AND [Name] = @name\n END\n ELSE\n BEGIN\n IF(SELECT COUNT(*)\n FROM ECCA\n WHERE aID = @aID\n AND [Name] = @name) &gt; 0\n BEGIN\n INSERT INTO @table (FA, FN, [Seeboj], Brotty)\n SELECT FA, FN, [Seeboj], Brotty\n FROM ECCA\n WHERE aID = @aID\n AND [Name] = @name\n END\n ELSE\n BEGIN\n INSERT INTO @table (FA, FN, [Seeboj], Brotty)\n SELECT FA, FN, [Seeboj], Brotty\n FROM EDC\n WHERE Cooltree = @Cooltree\n AND [Name] = @name\n END\n END\n\n\n IF(SELECT COUNT(*)\n FROM ECCDB\n WHERE aID = @aID\n AND bID = @bID) &gt; 0\n BEGIN\n UPDATE @table\n SET CD =\n (SELECT CD\n FROM ECCDB\n WHERE aID = @aID\n AND bID = @bID)\n END\n ELSE\n BEGIN\n IF(SELECT COUNT(*)\n FROM ECCDA\n WHERE aID = @aID) &gt; 0\n BEGIN\n UPDATE @table\n SET CD =\n (SELECT CD\n FROM ECCDA\n WHERE aID = @aID)\n END\n ELSE\n BEGIN\n UPDATE @table\n SET CD =\n (SELECT CD\n FROM EDCCD\n WHERE Cooltree = @Cooltree)\n END\n END\nSELECT * FROM @table\nEND\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:50:16.813", "Id": "40280", "ParentId": "40146", "Score": "33" } } ]
{ "AcceptedAnswerId": "40280", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T09:58:32.323", "Id": "40146", "Score": "-5", "Tags": [ "sql", "sql-server" ], "Title": "Stored procedure" }
40146
<p>First attempt was done <a href="https://codereview.stackexchange.com/questions/36938/node-js-passport-wrapper">here</a>:</p> <p>My second attempt (now using jslint to make sure the spacing is correct and have incorporate the majority of the feedback from previous attempt).</p> <pre><code>/* * Export single function that creates the passportControl object * The function has two parameters: * app: The nodejs/express service object. * This is used to register the end points * this authentication object listens too. * register: See https://codereview.stackexchange.com/questions/36940/local-user-registration * For an example implementation. This is still being worked on. * * It also uses an external module for configuration (ie holding all the secrets) * This file is not in source control (but in a key repository nice and safe). * config: Expected fields: * config.app The URL of the site. * config.passport An object containing the secrets for each service * The values will depend on the service and the * implementation of passport-&lt;service&gt; module * See the passport code for more detail * Example: * passport: { * facebook: { * clientID: 'FACEBOOK_CLIENT_ID', * clientSecret: 'FACEBOOK_CLIENT_SECRET', * }, * twitter: { * consumerKey: 'TWITTER_CONSUMER_KEY', * consumerSecret: 'TWITTER_CONSUMER_SECRET', * } * } * * The passport control object is supposed to be a wrapper for * nodejs/express/passport authentication. * * When the object is created it adds three end points to the server for authentication * /api/auth?type=&lt;AuthenticationType&gt; * /api/auth/callback?type=&lt;AuthenticationType&gt; * /api/authexit * * Where AuthenticationType is the service doing the authentication. * Eg Facebook/Twitter/Amazon etc * * A fourth end point is added to get display info about the user: * And information about supported authentication services. This allows the * front-end to display the appropriate controls without needing code changes. * /api/userInfo * * This end point returns the following json object: * { * logedin: true if the user is currently logged in; false otherwise. * displayName: The users display name if logged in, '' otherwise * loginMethods: A list of services that can be used to login if not logged in. * } * * This object has two public methods: * checkPassport(req, res) * registerUser(req, res) * * req: http request received from node. * res: response object we use to reply to the request. * * These are automatically hooked up to the exposed endpoints. * To extend this for any particular service just add the appropriate * objects to the array built with buildData() * */ // Global object for correctly escaping URL var querystring = require('querystring'); var config = require('../config.js'); // Private Method function addStandardStratergy(passport, register, result, name, prittyName, type, app, config) { config.callbackURL = 'http://' + app + '/api/auth/callback?type=' + name; console.log('Callback: ' + config.callbackURL); var Strategy = require(type).Strategy; /*jslint unparam: true*/ passport.use(new Strategy(config, function(accessToken, refreshToken, profile, done) { register.updateUser({ provider: profile.provider, providerId: profile.id, displayName: profile.displayName }, function(err, localUser) { if (err) {done(err); return; } done(null, localUser); }); })); result.auth[name] = passport.authenticate(name); result.callback[name] = function(req, res, page) {passport.authenticate(name, { successRedirect: page, failureRedirect: '/login'})(req, res); }; result.services.push({type: name, display: prittyName}); /*jslint unparam: false*/ } /* * This builds the data object central to 'passportControl' * The Key: Is the name of the 'AuthenticationType' the value is the passport object that does the authentication. * auth: Handles the initial authentication request. * callback: Handles the callback from the authentication service * services: A list of social services that can be used for logging in */ function buildData(passport, register) { // Add more strategies as required here. /*jslint unparam: true*/ var result = { auth: { default: function(req, res) {res.redirect('/login?' + querystring.stringify({reg_error: 'Invalid Authentication Type (attempt)'})); } }, callback: { default: function(req, res) {res.redirect('/login?' + querystring.stringify({reg_error: 'Invalid Authentication Type (callback)'})); } }, services: [] }; /*jslint unparam: false*/ /* * Add a call for each social network you want to use for registration */ addStandardStratergy(passport, register, result, 'facebook', 'Facebook', 'passport-facebook', config.app, config.passport.facebook); addStandardStratergy(passport, register, result, 'twitter', 'Twitter', 'passport-twitter', config.app, config.passport.twitter); return result; } module.exports = function(app, register) { // App: Application object // register: The user registration service // This has been abstracted from the passport authentication code. // I will document this interface separately. // Get the passport object we reap // Correctly initialize and turn on sessions. var passport, passportControl; passport = require('passport'); app.use(passport.initialize()); app.use(passport.session()); // Set passport to only save the user ID to the session passport.serializeUser(function(localUser, done) { done(null, localUser.id); }); // Set passport to retrieve the user object using the // saved id (see serializeUser). passport.deserializeUser(function(localUserId, done) { register.getSavedUser(localUserId, function(err, localUser) { if (err) { done(err); return; } done(null, localUser); }); }); // Create the passport control object passportControl = { data: buildData(passport, register), checkPassport: function(req, res) { req.session.page = req.query.page || '/'; return this.performAction(this.data.auth, req, res); }, registerUser: function(req, res) { req.query.page = req.session.page; return this.performAction(this.data.callback, req, res); }, deAuthorize: function(req, res) { var page = req.query.page || '/'; req.logout(); res.redirect(page); }, performAction: function (dataItem, req, res) { var action, page; action = dataItem[req.query.type]; page = req.query.page || '/'; if (action === null) { action = dataItem['default']; } return action(req, res, page); }, authTypes: function() { return this.data.services; } }; // The service endpoints // This will control all authentication. app.get('/api/authexit', function(req, res) { passportControl.deAuthorize(req, res); }); app.get('/api/auth', function(req, res) { passportControl.checkPassport(req, res); }); app.get('/api/auth/callback', function(req, res) { passportControl.registerUser(req, res); }); app.get('/api/userInfo', function(req, res) { res.json({ logedin: req.user ? true : false, displayName: req.user ? req.user.displayName : '', loginMethods: req.user ? [] : passportControl.authTypes() }); }); return passportControl; }; </code></pre> <h2>Usage in a node.js application:</h2> <h3>Edit <code>buildData()</code></h3> <p>Add appropriate calls to <code>addStandardStratergy()</code> (see examples provided)</p> <h3>Call In your code like this.</h3> <pre><code>var express = require('express'); var ppControl = require('./PassportControl.js'); var app = express(); var register = /* Your object for persisting user info */; var customsAgent = ppControl(app, register); </code></pre> <h3>Done.</h3> <h2>HTML on the client end to display login controls</h2> <p>Note: using Angular to do the work:</p> <pre><code>&lt;script type="text/javascript"&gt; /*&lt;![[CDATA[*/ function LoginController($scope) { $scope.logins = []; $scope.doLogin = function(type) { window.location.href = '/api/auth?type=' + type + '&amp;page=' + encodeURIComponent(document.URL); }; /*jslint unparam: true*/ /* Notice the call here to get the button info */ $.get( '/api/userInfo', '', function(data, textStatus, request) { if (request.status === 200) { $scope.logins = data.loginMethods; $scope.$apply(); } }, "json" ); /*jslint unparam: false*/ } /*]]&gt;*/ &lt;/script&gt; &lt;!-- fa Generic button using icon fa-facebook places facebook icon on button fa-twitter places twitter con on button fa- ... etc --&gt; &lt;div ng-controller="LoginController"&gt; &lt;!-- Other parts of control removed --&gt; &lt;form method="post" accept-charset="UTF-8"&gt; &lt;button ng-repeat="login in logins" ng-click="doLogin(login.type)"&gt; &lt;i class="fa fa-{{login.type}}"&gt;&lt;/i&gt; | Login with {{login.display}} &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T01:30:51.357", "Id": "67866", "Score": "0", "body": "`addStandardStratergy` ;) In all seriousness, this code looks very nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-18T18:28:29.140", "Id": "88138", "Score": "0", "body": "Somehow ended up checking your resume. There is a spelling mistake. Javascrip" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-18T19:03:23.000", "Id": "88140", "Score": "0", "body": "@AseemBansal: Which resume (can you provide a link)? I don't think there is javascript on my resume since I don't do it much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-19T02:40:32.627", "Id": "88189", "Score": "0", "body": "http://careers.stackoverflow.com/lokiastar" } ]
[ { "body": "<p>I really like this code, I only have a few minor observations:</p>\n\n<ul>\n<li><code>'http://'</code> &lt;- https should be an option without modifying your wrapper ?</li>\n<li><code>(request.status === 200)</code> &lt;- You should provide support for when things go wrong ? Also I think <code>success</code> is only called when <code>request.status</code> is <code>200</code></li>\n<li>The fact that <code>result.auth.default</code> and <code>result.auth.callback</code> are so similar bugs me (DRY), but I could not find a neater way to do it</li>\n<li>Spelling: <code>logedin</code> -> <code>loggedIn</code></li>\n</ul>\n\n<p>Other than that, very cool, something I would consider using for my own Node projects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T17:50:27.453", "Id": "83001", "Score": "2", "body": "Watch out this weekend. I have an update to this code that supports 12 popular sites out of the box. Facebook/Twitter/Google+/FourSquare/LinkedIn/GitHub/Meetup/AOL/Yahoo/Vimeo/Instagram/Tumbler. (Note I did not write any of the actual code I just add glue to plug the already written code (which seems to be this guy https://github.com/jaredhanson?tab=repositories)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T20:31:15.843", "Id": "83028", "Score": "0", "body": "http://codereview.stackexchange.com/q/47392/507" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-16T13:19:38.167", "Id": "47351", "ParentId": "40159", "Score": "4" } } ]
{ "AcceptedAnswerId": "47351", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:29:35.787", "Id": "40159", "Score": "11", "Tags": [ "javascript", "node.js", "authentication", "passport" ], "Title": "node.js Passport Wrapper 2" }
40159
<p>My <code>app</code> module bootstraps a Backbone.js application.<br> <strong>I need <code>app</code> to be available in every other view</strong> for easy access to router, triggering navigation, etc.</p> <p>I never ported an app to RequireJS before, and I got stuck on circular dependency problem, and <a href="https://stackoverflow.com/a/17148715/458193">this answer</a> isn't quite clear to me, so I'm not sure if I applied the solution correctly.</p> <p>I'm using <a href="http://requirejs.org/docs/whyamd.html#sugar" rel="nofollow noreferrer">AMD sugar style</a> throughout the app, so here's what I came up with:</p> <h3>app.js</h3> <pre><code>define(function (require, exports) { 'use strict'; var _ = require('underscore'), Backbone = require('backbone'), Router = require('Router'), AppView = require('common/views/app_view'), // ... return _.extend(exports, { start: function () { this.router = new Router(); Backbone.history.start(); this.appView = new AppView(); this.appView.render(); }, // ... }); }); </code></pre> <p>Extending <code>exports</code> instead of directly returning an object allows me to do <code>app = require('app')</code> in any view of the app without worrying about circular dependencies.</p> <p>All other modules in the app return value normally (i.e. I'm not using <code>exports</code> anywhere else).</p> <p>Is this an OK strategy for a Require.js Backbone app?<br> Are there better solutions (that will also work with <a href="http://requirejs.org/docs/optimization.html" rel="nofollow noreferrer">optimizer</a> or <a href="https://github.com/jrburke/almond" rel="nofollow noreferrer">Almond</a>)?</p> <p>An example of how I'm using <code>app</code> in a (rather deeply nested) view:</p> <h3>zine_item_view.js</h3> <pre><code>define(function (require) { 'use strict'; var View = require('common/views/view'), Misc = require('common/helpers/misc'), app = require('app'); var ZineItemView = View.extend({ template: 'templates/social/items/zine_item.html', events: { 'click': 'showZine' }, showZine: function (e) { if (!Misc.shouldHandleClick(e)) { return; } app.presenter.showZine({ zine: this.model, route: app.router.routeToZineTrending(this.model.id) }); } }); return ZineItemView; }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:38:31.830", "Id": "67730", "Score": "0", "body": "From an MVC perspective, your views should not have access to router or be able to trigger navigation. Don't get me wrong, I employ a similar scheme, but I think this is wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:50:15.593", "Id": "67736", "Score": "0", "body": "Can you also post one of your views that would use `app` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T04:21:35.113", "Id": "67889", "Score": "0", "body": "Sorry if I am dense, but what is `app.presenter.showZine` supposed to do here ? Are you setting a route inside of a `View` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T10:23:14.770", "Id": "67924", "Score": "0", "body": "@konijn: `presenter` is not a view, it's a separate object that has methods like `showZine`, `showUser`, `showHome`, etc. Think of it as of a simple “controller” (although there are no controllers in Backbone per se). It manages the root view. It often needs to load a model asynchronously, and, when it is ready, updates both root view and the current route." } ]
[ { "body": "<p>There are few ways to solve your problem with Backbone.js + Require.js and executing functions or changing routes from view.</p>\n\n<h2>1. Using Backbone.Router</h2>\n\n<p>Here is approach I've used multiple times:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>'use strict';\n\n// Your view --------------\ndefine([\n 'jquery'\n 'backbone'\n 'common/views/view',\n 'common/helpers/misc'\n], function ($, Backbone, View, Misc) {\n\n var ZineItemView = View.extend({\n ...\n showZine: function (e) {\n if (!Misc.shouldHandleClick(e)) {\n return;\n }\n // Pass all control from view to the router,\n // see http://stackoverflow.com/a/20311253/1363799\n Backbone.history.navigate('yourUrl_to_zine');\n }\n });\n\n return ZineItemView;\n});\n\n// Main block --------------\nrequire([\n 'jquery'\n 'backbone',\n 'app',\n 'ZineItemView'\n], function($, Backbone, App, ZineItemView) {\n ...\n\n var app = new App();\n\n var zineItemView = new ZineItemView({...});\n\n // Router way \n var router = Backbone.Router.extend({\n routes: {\n \"yourUrl_to_zine\": \"showZine\"\n },\n showZine: function() {\n // Here you gave access to zineItemView.model and zineItemView.model.id\n app.presenter.showZine({\n zine: zineItemView.model,\n // I think next row becames obsolete\n route: app.router.routeToZineTrending(zineItemView.model.id)\n });\n }\n });\n});\n</code></pre>\n\n<h2>2. Event-driven approach</h2>\n\n<pre><code>'use strict';\n\n// Your view --------------\ndefine([\n 'jquery',\n 'backbone',\n 'common/views/view',\n 'common/helpers/misc'\n], function ($, Backbone, View, Misc) {\n\n var ZineItemView = View.extend({\n ...\n showZine: function (e) {\n if (!Misc.shouldHandleClick(e)) {\n return;\n }\n\n var view = this;\n\n // Trigger global event with desired parameters\n $(window).trigger('showZine.App', {\n zine: view.model,\n modelId: view.model.id // probably it's obsolete, because you can get it from zine property\n });\n }\n });\n\n return ZineItemView;\n});\n\n// Somewhere in app block --------------\n// lodash is a dependency, because we use bind method\nvar App = {\n initialize: function() {\n $(window).on('showZine.App', _.bind(this.presenter.showZine, this) );\n },\n presenter: {\n showZine: function(event, paramsObj) {\n // Here you have paramsObj,\n // with paramsObj.zine = zineItemView.model\n // and paramsObj.modelId = zineItemView.model.id\n\n // Call app.router.routeToZineTrending from here, but be aware about value of `this` and `app` variables\n }\n }\n};\n</code></pre>\n\n<h2>3. Syntax of module defining (optional)</h2>\n\n<p>It preferentual, but seems to be a standart (it's easier to see dependencies):\n</p>\n\n<pre><code>'use strict';\n\ndefine([\n 'common/views/view',\n 'common/helpers/misc',\n 'app'\n], function (View, Misc, app) {\n\n var ZineItemView = View.extend({\n ...\n });\n\n return ZineItemView;\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T12:19:21.987", "Id": "81299", "Score": "0", "body": "You are welcome :). I'm also looking for more robust solution which somebody could propose." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-07T11:55:57.627", "Id": "46541", "ParentId": "40160", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T14:48:50.490", "Id": "40160", "Score": "6", "Tags": [ "javascript", "backbone.js", "modules", "require.js" ], "Title": "Avoiding RequireJS circular dependencies" }
40160
<p>In Java they're not really known as <code>GOTO</code> statements and are rather referred to as <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html" rel="noreferrer">Branching Statements</a>, but I find that the former term is a bit more indicative of what they actually do.</p> <p>Regardless, I've been designing some code recently which has me in a bind. On the one hand, I've been taught to avoid avid use of such statements because <a href="https://softwareengineering.stackexchange.com/questions/58237/are-break-and-continue-bad-programming-practices">they make code both non-linear and more difficult to follow</a>. They of course have excellent uses, and I'm not one of those puritans who says that they should be discarded at any cost.</p> <p>On the other hand, there's also a <a href="https://stackoverflow.com/questions/2928556/programming-style-should-you-return-early-if-a-guard-condition-is-not-satisfied">common tenet</a> that says I <a href="https://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement">ought to avoid</a> deep <a href="http://vocamus.net/dave/?p=1421" rel="noreferrer">nesting of conditions and loops</a> if it's <a href="http://debuggable.com/posts/programming-psychology-return-home-early:4811de9f-ae28-49c2-a7dc-2f154834cda3" rel="noreferrer">possible and reasonable to do so</a>.</p> <p>So here's my conundrum. I'm hoping someone can guide me and give me some solid reasoning and best practices advice, because apparently my brain can't handle the conflicting signals.</p> <p>Several times through my code, I have a <code>for()</code> loop which is something like the following (where <code>lines</code> is a <code>List&lt;String&gt;</code> and <code>values</code> is a <code>Map&lt;String, String&gt;</code>):</p> <pre><code>for(String line : lines) { if(line.charAt(0) == '#') { LOGGER.debug("Skipping commented line in file."); continue; } line = line.trim().toLowerCase(); String[] pair = line.split("="); if(pair.length != 2) { LOGGER.error("Skipping malformed line in file: " + line); continue; } pair[0] = pair[0].trim(); pair[1] = pair[1].trim(); if(values.containsKey(pair[0])) { LOGGER.debug("Value is already assigned."); continue; } values.put(pair[0], pair[1]); //...and so on with still more processing } </code></pre> <p>The reason I gave a little bit more in this code snippet than is strictly required to understand the use case is because I think the fact that the <code>for</code> loop isn't really "tight" and that it performs a lot of processing is relevant to the style choice. To me, it makes the code feel somewhat sloppy and messy to have multiple areas scattered throughout it which bump the reader back to the beginning of the loop. In other words, it feels a lot like <a href="https://stackoverflow.com/questions/46586/goto-still-considered-harmful">the good old <code>GOTO</code></a> that everyone <a href="http://xkcd.com/292/" rel="noreferrer">loves to hate on</a>.</p> <p>So my other design option is to write it with the following style:</p> <pre><code>for(String line : lines) { if(!line.charAt(0) == '#') { line = line.trim().toLowerCase(); String[] pair = line.split("="); if(pair.length == 2) { pair[0] = pair[0].trim(); pair[1] = pair[1].trim(); if(!values.containsKey(pair[0])) { values.put(pair[0], pair[1]); //...and so on with still more processing } else { LOGGER.debug("Value is already assigned."); } } else { LOGGER.error("Skipping malformed line in file: " + line); } } else { LOGGER.debug("Skipping commented line in file."); } } </code></pre> <p>Both of these techniques/styles makes my eye twitch spastically for various reasons, and I keep rewriting my code to fit whichever rationalization wins out in the current moment. I also think that if you definitively choose one as "The Style" to always go with, it's trivial to extend the above code snippets to the point where it makes more sense to go with the other.</p> <p>Does anyone have a more definitive statement of when to use one style over the other? Or even just some good reasoning to apply to a situation to make sure you are following the best rule and coding practice? Any general tips, tricks, and advice for dealing with these sorts of situations?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:22:12.330", "Id": "67503", "Score": "12", "body": "In either approach, it is worth considering [Extract-Till-You-Drop](https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop) (with well thought of names for your extracted methods) for the code inside your if-blocks. It is certainly a best practice and makes the final top-level function clean and readable either with early-returns (which are easier to spot in a clean + small top-level function) or even with nested-ifs. I've rarely squirmed at either of the two approaches when the thankfully SMALL function's intent is crystal clear and reads like prose." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:22:41.750", "Id": "67504", "Score": "2", "body": "One way would be to create a class holding these pair values with a static factory method that does all this checking and returns `null` on failure. That would cut the checking to `for { Pair pair = Pair.fromString(line); if (pair != null) {`. Within that static factory method you can use `return`...it's basically the same, but better wrapped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:21:32.347", "Id": "67529", "Score": "1", "body": "@JeffGohlke In that case, you should be using [`java.util.Properties`](http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html) to accomplish the task, rather than rolling your own. It does exactly what you are trying to do here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:45:25.107", "Id": "67536", "Score": "0", "body": "@AJMansfield Meh. No thank you. I've seen it used in my production environment and I'm not a huge fan of it. Writing my own allows me to handle values as something other than `String` if I want to, for example. The `Properties` API simply doesn't seem terribly powerful or useful to me. If others find it sufficient, though, that's great." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:51:00.463", "Id": "67539", "Score": "1", "body": "In any case, the question is more about how to handle issues of this *style* rather than addressing alternate ways to achieve the goal of the particular use case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:30:41.287", "Id": "67566", "Score": "10", "body": "[GOTO causes velociraptors](http://xkcd.com/292/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:56:37.983", "Id": "67585", "Score": "14", "body": "I misread this as **Nietzsche** vs GOTO... I was genuinely excited to find out what that meant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:21:47.307", "Id": "67614", "Score": "11", "body": "I agree; both of these make me twitchy. The solution I would recommend is: take a step back and ask yourself what you are really doing. **You are writing a parser without writing a lexer first**. I would be inclined to structure this code much more like a traditional compiler. Define a lexical grammer. Decompose the text into a sequence of tokens. Then run a parser over the tokens to produce a data structure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T00:21:52.310", "Id": "67618", "Score": "0", "body": "You could split the different tests into small boolean-methods and use these in you nesting. It looks a little smaller and is (depending on the programmer you're talking too) even a better (OO) programming practice" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T04:56:50.443", "Id": "67658", "Score": "1", "body": "@user1167442 I really wish that was an XKCD or something now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T05:11:13.567", "Id": "67660", "Score": "6", "body": "All control structures are just GOTO in disguises, so you should write all your methods without any control structures, no for-loops, no while-loops, no if-conditionals, and no functions. They're all just GOTO and we all know that GOTO is the vilest of all evil." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T09:31:37.000", "Id": "67681", "Score": "1", "body": "Don't use GOTO (well you can't in Java anyway). Don't use extra flags to terminate loops. **Do use break with labels**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T10:07:29.857", "Id": "67685", "Score": "1", "body": "Where is the `GOTO`? `continue` (at least without a label) is not a `GOTO` in any way. It's like saying `return` is a `GOTO` and should be avoided..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T11:08:20.000", "Id": "67690", "Score": "4", "body": "Control structures are not GOTOs; they are jumps, secured behind the language. The problem with GOTOs is not the jump—that happens all the time in assembly and you really can’t avoid it—but the way they (real GOTOs) influence your code and make it vulnerable. Using control structures is more than just fine and you definitely shouldn’t see the jumps in the background—you will never be able to avoid those anyway. Instead, make sure that your code is well written and easy to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T12:47:59.357", "Id": "67699", "Score": "2", "body": "I'll join the camp that says: whenever you use `break` or `continue`, you should *probably* extract and use `return` instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:01:22.053", "Id": "67702", "Score": "1", "body": "\"return\" and \"continue\" are no different from each other. What's going on is you have a series of criteria which must be met before you can get to the goal (extracting a key-value pair) and you have to do an increasing amount of work to verify each criterion. If it fails at any point, then you give up on that input and proceed to the next. Look up \"Arrow Antipattern\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:34:45.140", "Id": "67741", "Score": "0", "body": "Structured programming with go to statements (1974) by Donald E. Knuth\nhttp://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.6084\n\nWhy Functional Programming Matters, by John Hughes\nhttp://www.cse.chalmers.se/~rjmh/Papers/whyfp.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:45:26.297", "Id": "67747", "Score": "0", "body": "Edsger Dijkstra Considered Harmful http://se-according-to-futhork.blogspot.com.au/2013/03/edsger-dijkstra-considered-harmful.html\n\nYou should rewrite your program in Haskell, and in assembly language, and as a flow diagram.\n\nTo answer your question, it's better to avoid Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:46:19.017", "Id": "67799", "Score": "1", "body": "@poke: When an algorithm fits structured programming constructs, one should use those. When it doesn't, a `goto` or equivalent may sometimes yield clearer code than alternatives. One advantage of such instructions is that the target labels very concisely shout *EXECUTION MAY TRANSFER DIRECTLY HERE* and are less likely to escape notice than comments or `continue` statements within a loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T21:47:42.793", "Id": "67840", "Score": "1", "body": "I am surprised no-one suggested to use Exceptions as a way of exiting the handling of a line. It does look a lot like the continue, except they can all go to the same place to be logged, and you really have to do something about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T03:00:59.113", "Id": "67878", "Score": "0", "body": "This is a case of misunderstanding why some people consider GOTOs harmful. GOTOs are considered harmful when they obfuscate what the code is doing (i.e. the user is jumping around all over the place). Continues are a logical form of jump as they always point back to the same area - the beginning of a loop. Personally I would say the continues are far more readable than the nesting; the nesting requires the user to mentally unpick the nests first, whereas the continues are easily understandable - 'ignore the rest of the code and continue as you were'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T03:43:43.377", "Id": "67883", "Score": "0", "body": "Of course, lambda is the ultimate GOTO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T03:45:36.107", "Id": "67884", "Score": "0", "body": "@Pseudonym Haha, alas, I have yet to master the arcane art of lambda." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T21:37:19.313", "Id": "67996", "Score": "0", "body": "@njzk2, you're joking, of course..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T21:45:31.040", "Id": "67998", "Score": "0", "body": "@Craig : Not really. I think it is worth considering. A big try ... catch around the whole treatment, no tests at all, http://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain style. It accounts for case of `line == null` for instance, or any other issue in the handling of the line, without adding more tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T18:46:46.597", "Id": "68496", "Score": "0", "body": "@njzk2, I typically try not to be hard-line dogmatic about things, but using exceptions for flow control might be one of those things. What is wrong with using tests? If you rely on exceptions for flow control, you're just putting the tests off on someone else, then relying for normal flow control on a mechanism designed and intended for handling EXCEPTIONAL conditions. In other words, intended for handling things you can't test for. Using exceptions unavoidably harms performance of the code, as well. There are **many** reasons to avoid using exceptions in normal code paths." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T18:54:44.940", "Id": "68497", "Score": "1", "body": "This is a good article. Particularly relevant in this context, I think, is the \"Bonehead\" exception description: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx" } ]
[ { "body": "<p>Your first excerpt is fine, and it is better than your second. Your second excerpt is worse because of the deeper nesting. (Also, if you were to choose nesting anyway, I'd invert the conditions to put the shorter code branch first to reduce mental workload when reading the code.)</p>\n\n<p>Consider <em>why</em> the <a href=\"http://www.cs.utexas.edu/~EWD/ewd02xx/EWD215.PDF\"><code>goto</code> statement is considered harmful</a>. Since it has the potential to jump to arbitrary places in the code, it could turn your program into a pile of spaghetti.</p>\n\n<p>The use of <code>continue</code> is not a problem. You still have a structured loop, and the only thing it can do is proceed to the top of the loop to process the next element (if there is one). No chance of spaghetti there.</p>\n\n<p>If you don't care about logging, you could use a capturing regular expression, which takes care of your first two conditions as well as trimming whitespace. You would only have to worry about whether the key already exists.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:49:56.340", "Id": "67507", "Score": "0", "body": "To be fair, `continue` can be used to jump somewhat arbitrarily around if the [labeled version](http://www.java2s.com/Code/Java/Language-Basics/ContinueWithLabelDemo.htm) is used. It's not always quite as straightforward." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:23:55.650", "Id": "67530", "Score": "8", "body": "I'm not sure why you object so strongly to `continue`. I'd be curious to see what arguments you come up with for a \"`continue` statement considered harmful\" essay." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:40:33.333", "Id": "67533", "Score": "1", "body": "I don't object so strongly to it, and I don't think it's horribly harmful. I just think that unless the `continue` conditions are all listed nicely and neatly at the top of a method (rather than scattered throughout as demonstrated) that is really damages someone's ability to follow through code intuitively. That's all. Basically what I said in the question. The question isn't about whether one is more harmful to a program than the other (since both work just fine), just what's a better practice for readability/maintainability and so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:23:38.810", "Id": "67562", "Score": "5", "body": "@JeffGohlke - Everything I've ever seen about `continue`/`break` has only said that the labeled version should be avoided. Avoiding the unlabeled form inside a loop is like avoiding `return` statements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:31:11.383", "Id": "67567", "Score": "3", "body": "@Bobson I agree with the analogy completely. The question could be restructured to ask about having lots of `return` statements (\"return early, return often\") or having lots of nested conditions and fewer `return`s. Same idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T09:28:23.893", "Id": "67680", "Score": "1", "body": "@Bobson: Wow. I religiously avoid the unlabelled version, because the only way to know where it goes it by poking through layers of code, and as people we're pretty bad about that. An explicit label on the construct of interest avoids that completely. It also avoids the \"inserting a loop inside another shuts down the electric grid of the entire East coast\", a rather famous software bug involving a break... without a label." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T12:36:38.033", "Id": "67697", "Score": "2", "body": "@IraBaxter - If your code is complex enough that you can't tell you're in a loop, then you really need to refactor it. And since the unlabeled versions only apply to the current loop, it *should* be trivial to tell where they go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:32:41.780", "Id": "67708", "Score": "0", "body": "@Bobson: say what you like; the east coast disaster was real and traceable directly to \"don't use labels\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:05:13.200", "Id": "67739", "Score": "2", "body": "@IraBaxter - Got a link to source that? I can't find anything on google, but I'm not sure what terms to use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T23:24:54.790", "Id": "67856", "Score": "0", "body": "@IraBaxter - I would be interested to see that too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T01:37:11.003", "Id": "68021", "Score": "0", "body": "_Expert C Programming_ by Peter van der Linden mentions it; apparently the AT&T programmer wanted to exit an if block, and the break exited the surrounding block, meaning a struct didn't get initialized. A watchdog program detected this and restarted the system; the system when restarted sent out a packet to the other systems ... that triggered this bug and crashed them. It was the phone system, not the electric grid. http://www.mit.edu/hacker/part1.html calls it the Martin Luther King Day Crash, though it doesn't go into detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T19:08:29.803", "Id": "73566", "Score": "0", "body": "Electric grid disaster of east coast sounds like [the 2003 incident](http://en.wikipedia.org/wiki/Northeast_blackout_of_2003) to me, where [a race condition caused problems](http://www.theregister.co.uk/2004/04/08/blackout_bug_report/). \"There was a couple of processes that were in contention for a common data structure, and through a software coding error in one of the application processes, they were both able to get write access to a data structure at the same time,\" \"And that corruption lead to the alarm event application getting into an infinite loop and spinning.\"\" Maybe a mixup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T17:56:09.693", "Id": "75295", "Score": "0", "body": "I think @prosifaes has identified the one I was thinking of. Yes, phone system not electrical grid for that specific case but it doesn't surprise that there were other massive failures cause by similar coding glitches. If you want to read about more disasters caused by stupid code errors (some of this type), go read the Peter Nuemann's Risks summary in \"Software Engineering News\" going back for decades. My original comment stands: if a loop break uses explicit labels, nobody has to guess where they go, and they won't suddenly surprise you when a new layer of goo gets inserted into the code." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:21:19.113", "Id": "40164", "ParentId": "40162", "Score": "51" } }, { "body": "<p>I agree with @200_sucess that the first version is better.</p>\n\n<p>An alternative may be a subroutine:</p>\n\n<pre><code>for(String line : lines) {\n AddLine(line, values);\n //...and so on with still more processing\n}\n\nvoid AddLine(String line, Map&lt;String, String&gt; values)\n{\n if(line.charAt(0) == '#') {\n LOGGER.debug(\"Skipping commented line in file.\");\n return;\n }\n\n line = line.trim().toLowerCase();\n String[] pair = line.split(\"=\");\n\n if(pair.length != 2) {\n LOGGER.error(\"Skipping malformed line in file: \" + line);\n return;\n }\n\n pair[0] = pair[0].trim();\n pair[1] = pair[1].trim();\n\n if(values.containsKey(pair[0])) {\n LOGGER.debug(\"Value is already assigned.\");\n return;\n }\n\n values.put(pair[0], pair[1]);\n}\n</code></pre>\n\n<p>Do you mind the \"early return\" in a subroutine? Would you goto the end of the subroutine in order to return, or build a deeply-nested if?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:29:47.277", "Id": "40166", "ParentId": "40162", "Score": "10" } }, { "body": "<p>A different way is to let these pairs be represented by a class, which itself has a static factory method that will return <code>null</code> on failure.</p>\n\n<pre><code>public final class Pair {\n private String key;\n private String value;\n\n public Pair(key, value) {\n // TODO: Add proper argument checking/throw exceptions.\n\n this.key = key;\n this.value = value;\n }\n\n public String getKey() {\n return key;\n }\n\n public String getValue() [\n return value;\n }\n\n /**\n * Returns the string representation which looks like @{code key=value}.\n */\n @Override\n public String toString() {\n return key + \"=\" + value;\n }\n}\n</code></pre>\n\n<p>And the static factory method:</p>\n\n<pre><code>/**\n * Constructs a Pair from the given string,\n * returns null if the string is misformed or\n * the string was null.\n * \n * A well formed input looks like {@code key=value} and\n * does not start with a {@code #} as that indicates comments.\n */\npublic static Pair fromString(String str) {\n // We do not accept nulls and empty strings.\n if (str == null || str.empty()) {\n return null;\n }\n\n // TODO: Figure out if trimming of str would be a good idea.\n\n // Skip comments.\n if (str.startsWith(\"#\")) {\n return null;\n }\n\n String[] splitted = str.split(\"=\");\n\n // We also do not accept anything else.\n if (splitted.length != 2) {\n return null;\n }\n\n // TODO: Are you accepting zero-length keys/values?\n\n return new Pair(splitted[0], splitted[1]);\n}\n</code></pre>\n\n<p>It basically looks the same as your loop, with two important differences:</p>\n\n<ol>\n<li>It's a method of its own, easily reusable, easily testable.</li>\n<li>It has documentation what the input should look like.</li>\n</ol>\n\n<p>Now to your loop:</p>\n\n<pre><code>for (String line : lines) {\n Pair pair = Pair.fromString(line);\n if (pair != null &amp;&amp; !values.containsKey(pair.getKey())) {\n // TODO\n }\n}\n</code></pre>\n\n<p>That does not only shorten the code inside the loop, but will in the end make it more readable because you're now using <code>pair.getValue()</code> instead of <code>pair[1]</code>.</p>\n\n<p>Based on the context of this I would suggest other names, though, like <code>StringPair</code>, <code>Setting</code>, <code>SettingsPair</code> or <code>ConfigEntry</code>.</p>\n\n<p>Here is your loop with the log statements (assuming that the LOGGER has an overload that works similar to <code>Logger.log(...)</code>):</p>\n\n<pre><code>for (String line : lines) {\n Pair pair = Pair.fromString(line);\n if (pair != null) {\n if (!values.containsKey(pair.getKey()) {\n // TODO\n } else {\n LOGGER.debug(\"Pair is already assigned: {0}\", pair);\n }\n } else {\n LOGGER.error(\"Skipping line: {0}\", line);\n }\n}\n</code></pre>\n\n<p>There are no fine-grained error messages there because it should be obvious from the input why the <code>fromString</code> function could not create the <code>Pair</code>.</p>\n\n<p>Though we're back at two <code>if</code>-statemens with <code>else</code> branches, readability is a lot better.</p>\n\n<hr>\n\n<p>This does violate Item 43 from Effective Java (2nd Edition) which goes like this:</p>\n\n<blockquote>\n <p>Return empty arrays or collections, not nulls</p>\n</blockquote>\n\n<p>But why did I than suggest this approach? Effective Java states that it is better to throw fine grained exceptions rather then return <code>null</code> to ease dealing with the method. This is true for any sort of method, but it is not what this approach is supposed to do. We <em>don't care</em> what kind of problem there is, we just want an object that is usable for our program logic or move on, discarding fine grained errors in the process.</p>\n\n<p>If you use this approach you need to keep some things in mind:</p>\n\n<ul>\n<li>Don't use a constructor for this purpose but a static factory method.</li>\n<li>Document the behavior and purpose of the static factory method thoroughly.</li>\n<li>It should be obvious when seeing the input what the function returns.</li>\n<li>Know when to use this and when to use exception handling (be aware why this is not a generic all-in-one solution to everything).</li>\n<li>If this is inside a library/public API, always provide a way that does throw fine grained exceptions.</li>\n</ul>\n\n<hr>\n\n<p>In case you're parsing ini or settings file with this which do not require \"special\" treatment, <a href=\"https://codereview.stackexchange.com/a/40179/2612\">the answer from AJMansfield is correct</a>.</p>\n\n<blockquote>\n <p>Do not roll your own version if <code>java.util.Properties</code> works for it.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:19:08.977", "Id": "67528", "Score": "9", "body": "I would either call it `StringPair` or `Pair<String,String>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:19:01.193", "Id": "67592", "Score": "3", "body": "The fromString method won't look quite as clean if the LOGGER statements are re-inserted. There's a loss of functionality here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:40:42.770", "Id": "67603", "Score": "0", "body": "@AndrewLazarus: I do not consider Logger statements \"functionality\", I also fail to see the need to reinsert *all* of these statements. In my opinion it should be obvious why the function returned what it returned by looking at the input. If it is not-obvious from looking at the input, then there's something wrong with the function. You could achieve something along these lines by splitting the `if` condition and utilizing the `else` parts. That way you get logging but without the need for finer grained messages (it's either: \"Yo, this is malformed\" or \"Already exists\")." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:51:57.523", "Id": "67605", "Score": "0", "body": "@Bobby I guess just as a matter of lines, if you want to log the message, now you have to test after getting the `NULL`—it doesn’t come out as short." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:53:29.997", "Id": "67615", "Score": "0", "body": "Great answer. Perhaps you could even replace the static factory method by a Parser class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T12:13:02.123", "Id": "67694", "Score": "2", "body": "Please, please don't use `null` to signify invalid lines. Either throw `IllegalArgumentException` or use Guava's / SE8's [Optional<T>](http://download.java.net/jdk8/docs/api/java/util/Optional.html) . The OP doesn't specify what the file looks like, but `null` is really not the thing for this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:57:07.590", "Id": "67712", "Score": "0", "body": "@TC1: Normally I'd agree with you, but I consider this one of the \"edge\" cases where this is quite valid. You're right that the constructor should have proper argument checking and should throw exceptions, but the `fromString` method is explicitly designed for this and, most importantly, it's documented that it does return `null`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T08:28:53.307", "Id": "67914", "Score": "1", "body": "There are however some issues with this code: 1. As other's mentioned, `null` is a bad way to signal validation errors. 2. `Pair.fromString` does both parsing and validation. By returning `null` you lose the information about the validation error (i.e. the `\"malformed line\"` message). So the code is functionally different, regardless of whether you think that this information is unimportant. 3. You didn't actually answer OP's question. Well, implicitly you did, because you chose nested `if`, but guard statements are IMHO more readable (i.e. simply writing `if (pair == null) continue;`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T09:49:28.583", "Id": "67918", "Score": "0", "body": "@Groo: 200_success and rolfl did answer the question, I provided a different way, so did AJMansField (most likely even a better one). I don't necessarily see a problem with that, as I said before, I consider showing (sometimes completely) different ways an important part of reviewing code." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:49:59.230", "Id": "40170", "ParentId": "40162", "Score": "62" } }, { "body": "<p>Here is a far and away superior solution: use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html\"><code>java.util.Properties</code></a> to handle your configuration file. <code>Properties</code> supports a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#load(java.io.Reader)\"><code>key=value</code> syntax</a> that is very similar to the one you are trying to parse. It's up to you to decide whether that syntax is close enough to handle any existing configuration files you might have, and whether the validation and logging in your current code are essential.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T21:00:41.477", "Id": "67587", "Score": "5", "body": "Even though the question is more about code style, this is a case of where the question can be \"X or Y?\" and the answer is \"Z!\". A reminder to always think outside the box. +1 for the edited version of this answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:27:15.717", "Id": "40179", "ParentId": "40162", "Score": "19" } }, { "body": "<p>I agree with others that the first one is better because it's easier to read but <em>@AJMansfield</em> also has a really good point. It's worth mentioning that you can also use Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Splitter.html\" rel=\"nofollow\"><code>Splitter</code></a> and <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Splitter.MapSplitter.html\" rel=\"nofollow\"><code>MapSplitter</code></a> classes or write something similar.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T21:33:57.013", "Id": "40206", "ParentId": "40162", "Score": "4" } }, { "body": "<p>Let me echo @AJMasfield that for this particular example <strong>Don't Reinvent the Wheel.</strong> However, this question comes up in contexts other than Properties. In the second version, the LOGGER messages are further and further away from the relevant <code>if</code> clauses. The first version uses an idiom we should be familiar with, checking preconditions and error exits up at the top. I find it quite readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:23:56.003", "Id": "40213", "ParentId": "40162", "Score": "7" } }, { "body": "<p>Your problem is not with the loop construct - nor is it with GOTOs. Your problem is you are avoiding some tools that can make your code better.</p>\n\n<p>Here's an example.</p>\n\n<pre><code>enum Validator {\n IsNotComment(\"Skipping commented line in file.\") {\n\n @Override\n boolean isValid(String s) {\n return !s.startsWith(\"#\");\n }\n\n },\n IsAPair(\"Not a pair\") {\n\n @Override\n boolean isValid(String s) {\n return s.trim().split(\"=\").length == 2;\n }\n\n };\n\n abstract boolean isValid(String s);\n\n public final String failMsg;\n\n Validator(String failMsg) {\n this.failMsg = failMsg;\n }\n}\n\npublic void test() {\n String[] lines = {\"Hello\"};\n Map&lt;String,String&gt; values = new HashMap&lt;&gt;();\n for (String line : lines) {\n boolean valid = true;\n String failMsg = \"\";\n for ( Validator v : Validator.values() ) {\n valid &amp;= v.isValid(line);\n if ( !valid ) {\n failMsg = v.failMsg;\n }\n }\n if ( valid ) {\n // Do stuff with valid lines.\n String [] parts = line.trim().split(\"=\");\n values.add(parts[0],parts[1]);\n } else {\n System.out.println(\"Failed validation: \"+failMsg);\n }\n }\n}\n</code></pre>\n\n<p>See that by refactoring properly you can now add more validations steps without affecting the main code, each one will only add to the quality. You have now transformed brittle code that is comparably difficult to understand and enhance into something clear and flexible.</p>\n\n<p>This encourages you to focus on the fact that you are trying to mix validation with parsing. </p>\n\n<p>If you let your worries guide you properly you will see that the validation is a separate process and your attempt to mix the validation into the parsing process is making your code smell.</p>\n\n<p>Validate first - then parse. Do <strong>not</strong> pre-optimise and merge them into one until you have a good <em>measured</em> reason to do so - and even then measure again.</p>\n\n<h2>Added</h2>\n\n<p>Just for the joy of it - here's what it might look like in Java 8</p>\n\n<pre><code>List&lt;String&gt; lines = Arrays.asList(\n \"# Comment\",\n \"\",\n \"A=B\",\n \"A=C\",\n \"X=Y \",\n \"P = Q\");\n\npublic void test() {\n Map&lt;String,String&gt; values = new HashMap&lt;&gt;();\n lines.stream()\n // Trim it and lowercase.\n .map(s -&gt; s.trim().toLowerCase())\n // Discard empty lines - good call @rolfl\n .filter(s -&gt; !s.isEmpty())\n // Discard comments.\n .filter(s -&gt; s.charAt(0) != '#')\n // Split the trimmed form\n .map(s -&gt; s.split(\"=\"))\n // Must be two parts.\n .filter(a -&gt; a.length == 2)\n // Trim each one.\n .map(a -&gt; new String[]{a[0].trim(), a[1].trim()})\n // Not seen already.\n .filter(a -&gt; !values.containsKey(a[0]))\n // Install in values.\n .forEach (a -&gt; values.put(a[0], a[1]));\n System.out.println(values);\n}\n</code></pre>\n\n<p>This really actually prints:</p>\n\n<pre><code>{p=q, a=b, x=y}\n</code></pre>\n\n<p>Now is that cool or what?</p>\n\n<p>Sorry but it doesn't do all your helpful printing and stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T04:39:52.937", "Id": "67656", "Score": "0", "body": "Thank you for this post. This really gave me an epiphany moment concerning the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T08:40:03.737", "Id": "67677", "Score": "1", "body": "@OldCurmudgeon The problem with this approach is you separate validation and processing. Which would lead to code duplication. e.g. `// Do stuff with valid lines.` would also contain a `String.split(\"=\")`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T09:00:29.340", "Id": "67678", "Score": "1", "body": "@abuzittingillifirca - That miniscule loss is balanced by a significant gain in code quality. It also suggests that you should use a new class to handle the String so you can retain the parts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T00:53:36.223", "Id": "68212", "Score": "1", "body": "Good call on the Java8 streams .... looks interesting. And thanks for the 'good call' as well. You will probably find that this `.filter(s -> s.length() > 0)` is better written as `.filter(s -> !s.isEmpty())`... Nice Answer! (good thing you edited. I have votes now!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T10:11:25.673", "Id": "68286", "Score": "0", "body": "@rolfl - Thanks (again) for the useful feedback. `isEmpty` deployed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T05:27:09.110", "Id": "71059", "Score": "1", "body": "Perhaps you meant `failMsg += v.failMsg`, since the code as written overwrites an existing `failMsg` in case of multiple errors. If only the first message should be printed, why not break out of the validation loop immediately? I like the enum setup—one way of addressing @abuzittingillifirca comment on efficiency is you can split the validators (two implementations of an interface) into pre-parse and post-parse. In this example, the inefficiency is probably trivial, but not if the simple `split` were something expensive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T07:11:50.780", "Id": "71069", "Score": "0", "body": "@AndrewLazarus Least of my problems with **code duplication** is efficiency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T07:47:51.877", "Id": "71072", "Score": "0", "body": "@abuzittingillifirca Yes, I don't like the duplicated parsing, either. I do like the Validator class, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-11T14:17:42.850", "Id": "101109", "Score": "0", "body": "Couldn't you actually reimplement the Logger-Messages inside the filter conditions? like ( a == 2 || LogAndReturnFalse(...)) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-24T22:12:34.933", "Id": "103901", "Score": "0", "body": "@Falco - Forgive the delay in responding. No, that would force all users of the Validator to suffer log entries. I would much rather make the error message available for use than force the user to deal with logging side effects. Maybe the error message should be a `List<String>` but no more. Good intent but wrong approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-25T07:34:44.923", "Id": "103984", "Score": "1", "body": "Of course I wouldn't write directly to the system logger, but collecting all errors in a list and logging them afterwards would provide all functionality of the original question!" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:46:38.383", "Id": "40220", "ParentId": "40162", "Score": "24" } }, { "body": "<p>I find it strange that the zero-length line problem has not yet been pointed out:</p>\n\n<pre><code>for(String line : lines) {\n\n if(line.charAt(0) == '#') {\n ....\n</code></pre>\n\n<p>The code above assumes a non-empty line in all cases, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29\">otherwise you get IndexOutOfBoundsException</a>.</p>\n\n<p>This is the sort of issue that should be identified and covered with Unit testing.</p>\n\n<p>This also leads on to the fact that you appear to be <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged &#39;reinventing-the-wheel&#39;\" rel=\"tag\">reinventing-the-wheel</a>, and should consider the suggestion for using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html\">java.util.Properties</a>.</p>\n\n<p>Despite that suggestion, I have to weigh in on the <code>continue</code>/<code>break</code> theoretical discussion as well. Loop entry and exit points are already the targets of branch instructions in the compiled (JIT or Byte) code that Java produces. These branch points are well managed, and have clean, and well documented entry/exit conditions. They are nothing like the concept of a GOTO. I have, over time, become very comfortable with using them, and they are no more distrustful than an early-return from a method call. In fact, conceptually, that is what they are, simply an early-termination of a block of code that happens to be in a loop, and the termination may allow (<code>continue</code>) or disallow (<code>break</code>) further iteration.</p>\n\n<p>I would not recommend using these statements with impunity, but, the fact that <code>break</code> is the natural syntax in the <code>switch</code> statement gives some hint that it's OK to use. It is the right tool for some jobs. Use it when appropriate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T00:51:59.750", "Id": "40224", "ParentId": "40162", "Score": "25" } }, { "body": "<p><strong>The solution to your problem (given in the example):</strong></p>\n\n<ol>\n<li>Select the contents of your <code>for</code> block</li>\n<li>Refactor -> Extract method</li>\n<li>Inspect program to make sure nothing broke</li>\n<li>Inspect the new generated method to see if it's ugly</li>\n<li>If ugly, select ugly parts, go to #2</li>\n<li>If you can't select them because they are too scattered in the body, rearrange until you can</li>\n<li>If you can't rearrange because code would break, reconsider your algorithm design - does it really have to be this convoluted?</li>\n<li>If yes, accept it and move on. Not all code can be beautiful, and sometimes perfectionism isn't worth it.</li>\n</ol>\n\n<hr>\n\n<p><strong>The answer to your question (example aside):</strong></p>\n\n<p><code>goto</code> is very rarely needed in modern languages. Part of the reason is that things like <code>return</code>, <code>break</code>, <code>continue</code> and <code>throw</code> exist. These are basically very limited versions of <code>goto</code> that are incapable of causing anywhere near as much chaos, but can still satisfy a popular <code>goto</code> use case. It is unlikely that you will encounter <code>goto</code> worthy code which cannot be tamed using these tools and applying some intelligent refactoring.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T05:42:04.890", "Id": "40239", "ParentId": "40162", "Score": "6" } }, { "body": "<p>Here's an answer out of left-field, but it may give you some inspiration. If I were doing this in Haskell I would write it as a pipeline of maps and folds on a list. I don't know much about Java, but could you rewrite your function as several smaller functions each of which acts on an iterator and produces a new iterator to feed into the next function?</p>\n\n<pre><code>processLines = insertInto dict\n . map trimPairs\n . filter notMalformed\n . map splitLine\n . filter notComment\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T09:47:51.333", "Id": "67683", "Score": "0", "body": "I was just about to suggest a functional approach too. The problem is basically passing some input through a series of filters, which is modeled perfectly in a functional way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:34:32.263", "Id": "67740", "Score": "1", "body": "This is also a very good idea. Thank you. I might actually end up going with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T08:55:39.000", "Id": "67916", "Score": "2", "body": "Java 8 can help here :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T21:39:07.787", "Id": "67997", "Score": "0", "body": "@SilviuBurcea Can you explain? My production environment is just getting Java 7 this year, so I'm still busy trying to master things like lambda and try-with-resources blocks. Haha" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T07:57:41.880", "Id": "68048", "Score": "0", "body": "@JeffGohlke Java 8 introduced Streams and some other utilities, like Files.lines(path) that returns a Stream. Map and filter are applied on streams. You can then map every line to something(even a bean), then you can filter them on the fly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T00:04:54.477", "Id": "68206", "Score": "0", "body": "See my Java 8 implementation [here](http://codereview.stackexchange.com/a/40220/11913)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T08:27:04.063", "Id": "40251", "ParentId": "40162", "Score": "9" } }, { "body": "<p>Base on the notion \"ask forgiveness rather than permission\", I would put the line handling in a try-catch block, like so :</p>\n\n<pre><code>for(String line : lines) {\n\n try {\n if(line.charAt(0) == '#') {\n throw new Exception(\"Skipping commented line in file.\");\n }\n\n line = line.trim().toLowerCase();\n String[] pair = line.split(\"=\");\n\n pair[0] = pair[0].trim();\n pair[1] = pair[1].trim();\n\n if(values.containsKey(pair[0])) {\n throw new Exception(\"Value is already assigned.\");\n }\n\n values.put(pair[0], pair[1]);\n\n //...and so on with still more processing\n } catch (Exception e) {\n LOGGER.error(\"Skipping line in file: \" + line + \" \" + e.getMessage());\n }\n}\n</code></pre>\n\n<p>This can catch any other case you may not have considered, such as the line being null or empty, or any thing else in the line processing.</p>\n\n<p>I would probably extract a method to include the <code>values.put</code> with the <code>containsKey</code> test that would throw the exception. Any kind of test you need to perform can be extracted to a method that throws an exception if the condition is not met, such as </p>\n\n<pre><code>public void testComment(String line) throws Exception {\n if (line.charAt(0)) {\n throw new Exception(\"Skipping commented line in file.\");\n }\n}\n</code></pre>\n\n<p>To conclude, I think exceptions work in this case because you expect a specific input, and anything that does not match it (any exception to it) it to be discarded.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T00:13:55.773", "Id": "68208", "Score": "2", "body": "A comment is too routine to justify the use of an exception. The variable-already-assigned situation might be handled that way. Still, catching _all_ `Exception`s makes me uneasy. To trace the intended flow, I have to examine _every single function call_ in the `try` block and brainstorm ideas about what kinds of exceptions might be thrown. It reminds me of [this code](http://codereview.stackexchange.com/a/37244/9357)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T14:08:06.977", "Id": "40459", "ParentId": "40162", "Score": "1" } } ]
{ "AcceptedAnswerId": "40170", "CommentCount": "27", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:03:59.253", "Id": "40162", "Score": "82", "Tags": [ "java", "parsing" ], "Title": "Nesting versus GOTO: which is better to avoid?" }
40162
<p>Provides 3 types of normal ajax - get, post, and post for form data.</p> <p>Also provides serialized ajax (get style) using a queue.</p> <p>Please review the correctness of this code.</p> <pre><code>/************************************************************************************************** AJAX */ // ... snip Pub.ajax = function (config_ajax) { var xhr; // get if (config_ajax.type === 'get') { xhr = new win.XMLHttpRequest(); xhr.open('GET', config_ajax.url, true); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(null); } // post if (config_ajax.type === 'post') { xhr = new win.XMLHttpRequest(); xhr.open("POST", config_ajax.url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(config_ajax.data); } // post for form_data if (config_ajax.type === 'multi') { xhr = new win.XMLHttpRequest(); xhr.open("POST", config_ajax.url, true); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(config_ajax.data); } }; // queue used for serial ajax Priv.Queue = (function () { var queue = [], publik = {}; function getIndexFromToken(callback) { var hold; $A.someIndex(queue, function (val, index) { if (val.callback === callback) { hold = index; return index; } }); return hold; } function getBlockedProperty(item) { var blocked; if (item) { blocked = item.blocked; } else { blocked = false; } return blocked; } publik.addItem = function (callback) { var temp = {}; temp.blocked = false; temp.callback = callback; temp.response_text = null; queue.push(temp); }; publik.itemCompleted = function (response_text, callback) { var index, item, blocked; index = getIndexFromToken(callback); if (index !== 0) { queue[index].blocked = true; queue[index].response_text = response_text; } else { item = queue.shift(); item.callback(response_text); blocked = getBlockedProperty(queue[0]); while (blocked) { item = queue.shift(); item.callback(item.response_text); blocked = getBlockedProperty(queue[0]); } } }; return publik; }()); // serial ajax // unlike normal ajax the ordering is guaranteed Pub.serialAjax = function (source, callback) { Priv.Queue.addItem(callback); Pub.ajax({ type: 'get', url: source, callback: function (response_text) { Priv.Queue.itemCompleted(response_text, callback); } }); }; // ... snip </code></pre>
[]
[ { "body": "<p>From a once-over:</p>\n\n<ul>\n<li><p>You keep creating the same function in <code>Pub.ajax</code>:<br></p>\n\n<pre><code> xhr.onload = function () {\n if (this.status === 200) {\n config_ajax.callback(xhr.responseText);\n }\n };\n</code></pre>\n\n<p>You could consider assigning this function once to a <code>var onloadFunction</code> which you then assign like this : <code>xhr.onload = onloadFunction</code>. On the whole, <code>Pub.ajax</code> needs to be reviewed by you with DRY in mind.</p></li>\n<li><p><code>getBlockedProperty</code> could be written in a much shorter fashion:<br></p>\n\n<pre><code>function getBlockedProperty(item) {\n return item ? item.blocked : false;\n}\n</code></pre></li>\n<li><p><code>getIndexFromToken</code> is odd, I have no idea what it really does, not a single variable or parameter is called <code>token</code> and there is not a single line of comment.</p></li>\n<li><p><code>publik.addItem</code> could use Object Literal Notation to make it more succint:<br></p>\n\n<pre><code>publik.addItem = function (callback) {\n var temp = {\n blocked : false;\n callback : callback;\n response_text : null;\n };\n queue.push(temp);\n};\n</code></pre></li>\n<li><p>lowerCamelCasing -> You are not using it everywhere</p></li>\n<li><p>A minor observation, would it not be much easier to just send synchronous requests instead of building a custom queue ?</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T04:17:16.830", "Id": "40329", "ParentId": "40167", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:33:58.333", "Id": "40167", "Score": "0", "Tags": [ "javascript" ], "Title": "A package for the DOM - Ajax" }
40167
<p>Please provide feedback on the correctness of this code. It should handle older versions of IE but how far back it goes I have not determined yet.</p> <pre><code>/************************************************************************************************** EVENTS */ // ... snip Priv.functionNull = function () { return undefined; }; // createEvent Priv.createEvent = function () { if (doc.createEvent) { return function (type) { var event = doc.createEvent("HTMLEvents"); event.initEvent(type, true, false); $A.someKey(this, function (val) { val.dispatchEvent(event); }); }; } if (doc.createEventObject) { return function (type) { var event = doc.createEventObject(); event.eventType = type; $A.someKey(this, function (val) { val.fireEvent('on' + type, event); }); }; } return Priv.functionNull; }; Priv.proto.createEvent = function (type) { return Priv.createEvent.call(this, type); }; Pub.createEvent = (function () { return function (element, type) { var temp = []; temp[0] = element; Priv.createEvent.call(temp, type); }; }()); // addEvent Priv.addEvent = (function () { if (win.addEventListener) { return function (type, callback) { $A.someKey(this, function (val) { val.addEventListener(type, callback); }); }; } if (win.attachEvent) { return function (type, callback) { $A.someKey(this, function (val) { val.attachEvent('on' + type, callback); }); }; } return Priv.functionNull; }()); Priv.proto.addEvent = function (type, callback) { return Priv.addEvent.call(this, type, callback); }; Pub.addEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; Priv.addEvent.call(temp, type, callback); }; }()); //remove event Priv.proto.removeEvent = (function () { if (win.removeEventListener) { return function (type, callback) { $A.someKey(this, function (val) { val.removeEventListener(type, callback); }); }; } if (win.detachEvent) { return function (type, callback) { $A.someKey(this, function (val) { val.detachEvent('on' + type, callback); }); }; } return Priv.functionNull; }()); Priv.proto.removeEvent = function (type, callback) { return Priv.removeEvent.call(this, type, callback); }; Pub.removeEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; Priv.removeEvent.call(temp, type, callback); }; }()); </code></pre>
[]
[ { "body": "<p><strong>The good</strong></p>\n\n<p>Your code will handle any type of browser, is pretty easy to follow.</p>\n\n<p><strong>The bad</strong></p>\n\n<p><code>Pub.removeEvent</code> will not work. That's because you define <code>Priv.proto.removeEvent</code> twice, whereas you probably want to define <code>Priv.proto.removeEvent</code> and <code>Priv.removeEvent</code>.</p>\n\n<p><strong>The ugly</strong></p>\n\n<p>You are using <code>doc.createEvent</code> which is deprecated, you should look into <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\" rel=\"nofollow\">event constructors</a>.</p>\n\n<p><strong>Furthermore</strong></p>\n\n<p>Because IE decided to do things differently for many event related things, a lot of people check as you do for the existence of a function and go from there, however your approach could be a little DRYer.</p>\n\n<pre><code>Priv.addEvent = (function () {\n if (win.addEventListener) {\n return function (type, callback) {\n $A.someKey(this, function (val) {\n val.addEventListener(type, callback);\n });\n };\n }\n if (win.attachEvent) {\n return function (type, callback) {\n $A.someKey(this, function (val) {\n val.attachEvent('on' + type, callback);\n });\n };\n }\n return Priv.functionNull;\n}());\n</code></pre>\n\n<p>can be done as </p>\n\n<pre><code>Priv.addEvent = (function () {\n var addFunction = win.addEventListener ? 'addEventListener' : 'attachEvent',\n prefix = win.addEventListener ? '' : 'on';\n\n return function (type, callback) {\n $A.someKey(this, function (val) {\n val[addFunction]( prefix + type, callback);\n });\n };\n return Priv.functionNull;\n}());\n</code></pre>\n\n<p>This approach can be applied to <code>addEvent</code>, <code>removeEvent</code> and perhaps to 'createEvent'.</p>\n\n<p>Finally, as always, you should steer away from <code>someKey</code>, just stick to the standard <code>Array</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T05:14:29.613", "Id": "67891", "Score": "0", "body": "\"The good, The Bad, The Ugly and IE.\" Definately the right order." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T03:44:31.390", "Id": "40326", "ParentId": "40168", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:37:45.003", "Id": "40168", "Score": "1", "Tags": [ "javascript" ], "Title": "A package for the DOM - Events" }
40168
<p>I can't quite figure out the best way to approach this. I have two jQuery objects that both are used to set cookies. I then parse the JSON and set a cookie that is either the users height or the users weight.</p> <p>This works fine, but I feel like there is an extreme amount of redundant code here that could be cleaned up but for the life of me I'm blanking on how to best do this. Ideally I'd like to be able to somehow condense this and have a function that I can pass in parameters if I want to receive the height cookie or the weight cookie.</p> <p>Possibly something along the lines of: <code>userInfo(heightCookie)</code> or <code>userInfo(weightCookie)</code>.</p> <p>I'm a bit of a newbie, so code examples are ideal, please.</p> <pre><code>var height_cookie = { name: 'user-height', options: { path: '/', expires: 365 } }; var weight_cookie = { name: 'user-weight', options: { path: '/', expires: 365 } }; function userHeightCookie() { var userData = $.parseJSON($.cookie(height_cookie.name)); return(userData); }; function userWeightCookie() { var userData = $.parseJSON($.cookie(weight_cookie.name)); return(userData); }; function readHeightCookie(userInfo) { $.cookie(height_cookie.name, JSON.stringify(userInfo), height_cookie.options); }; function readWeightCookie(userInfo) { $.cookie(weight_cookie.name, JSON.stringify(userInfo), weight_cookie.options); }; var userInfo = readHeightCookie(); var userInfo2 = readWeightCookie(); </code></pre>
[]
[ { "body": "<p>I'd put the cookies into an object so they can be named.</p>\n\n<pre><code>var userCookies = {\n height: {\n name: 'user-height',\n options: {\n path: '/',\n expires: 365\n }\n },\n weight: {\n name: 'user-weight',\n options: {\n path: '/',\n expires: 365\n }\n }\n};\n</code></pre>\n\n<p>Then you only need read/write cookie methods: <em>(I've not used <code>$.cookie</code> so I'm only guessing I haven't broken it.)</em></p>\n\n<pre><code>function readCookie(cookieName) {\n var userData = $.parseJSON($.cookie(userCookies[cookieName].name));\n return(userData);\n};\n\nfunction writeCookie(userInfo, cookieName) {\n $.cookie(weight_cookie.name, JSON.stringify(userInfo),userCookies[cookieName].options);\n};\n</code></pre>\n\n<p>If you want to be really modular (like all the cool kids) you might do something like:</p>\n\n<pre><code>var CookieMonster =(function ($) {\n var userCookies = {\n height: {\n name: 'user-height',\n options: {\n path: '/',\n expires: 365\n }\n },\n weight: {\n name: 'user-weight',\n options: {\n path: '/',\n expires: 365\n }\n }\n };\n return {\n readCookie: function readCookie(cookieName) {\n var userData = $.parseJSON($.cookie(userCookies[cookieName].name));\n return(userData);\n },\n writeCookie: function writeCookie(userInfo, cookieName) {\n $.cookie(weight_cookie.name, JSON.stringify(userInfo),userCookies[cookieName].options);\n }\n };\n})(jQuery);\n\nvar userInfo = CookieMonster.readCookie('height');\nvar userInfo2 = CookieMonster.readCookie('weight');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T00:36:19.033", "Id": "40315", "ParentId": "40171", "Score": "5" } } ]
{ "AcceptedAnswerId": "40315", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T15:58:58.373", "Id": "40171", "Score": "7", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "Pass in parameters instead of multiple functions" }
40171
<p>I've noticed some discrepancies in timings in our system, and I'm trying to narrow down what could be causing them.</p> <p>I'm reviewing out time abstraction, and as far as I can determine it's fine.</p> <p>Am I missing anything, and is it portable (besides being constrained to POSIX)?</p> <pre><code>typedef struct timespec Time; static inline Time getTime() { static struct timespec time; clock_gettime(CLOCK_MONOTONIC, &amp;time); return time; } static inline __constant Time timeAdd(Time oldTime, Time time) { if (time.tv_nsec + oldTime.tv_nsec &gt;= 1E9) return (Time){ tv_sec: time.tv_sec + oldTime.tv_sec + 1, tv_nsec: time.tv_nsec + oldTime.tv_nsec - 1E9 }; else return (Time){ tv_sec: time.tv_sec + oldTime.tv_sec, tv_nsec: time.tv_nsec + oldTime.tv_nsec }; } static inline __constant Time timeDiff(Time oldTime, Time time) { if (time.tv_nsec &lt; oldTime.tv_nsec) return (Time){ tv_sec: time.tv_sec - 1 - oldTime.tv_sec, tv_nsec: 1E9 + time.tv_nsec - oldTime.tv_nsec }; else return (Time){ tv_sec: time.tv_sec - oldTime.tv_sec, tv_nsec: time.tv_nsec - oldTime.tv_nsec }; } static __always_inline __constant double timeSeconds(Time time) { return time.tv_sec + time.tv_nsec/1E9; } static inline double timeSince(Time oldTime) { struct timespec time; clock_gettime(CLOCK_MONOTONIC, &amp;time); return timeSeconds(timeDiff(oldTime, time)); } </code></pre>
[]
[ { "body": "<p>I can see nothing wrong, but I think it is not optimal. My compiler warns me\nabout floating point conversions of those '1E9' constants. If I rewrite your\n<code>timeAdd</code> as follows, the code is easier to read and the generated code is\nsignificantly smaller:</p>\n\n<pre><code>#define BILLION 1000000000\nTime timeAdd(Time t1, Time t2)\n{\n long sec = t2.tv_sec + t1.tv_sec;\n long nsec = t2.tv_nsec + t1.tv_nsec;\n if (nsec &gt;= BILLION) {\n nsec -= BILLION;\n sec++;\n }\n return (Time){ .tv_sec = sec, .tv_nsec = nsec };\n}\n</code></pre>\n\n<p>The same goes for the other functions, I think.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:58:31.303", "Id": "67586", "Score": "2", "body": "If you're using integer BILLION then the timeSeconds expression should include a cast to double, i.e. `time.tv_sec + (double)time.tv_nsec/BILLION;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T01:20:02.400", "Id": "74007", "Score": "0", "body": "I haven't seen you answer any questions in a while. I sure hope we haven't seen the last of William Morris." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T13:37:12.807", "Id": "74053", "Score": "1", "body": "@syb0rg not intentionally, but I only really review C and there are some great reviewers (yourself included) who seem always to beat me to it recently :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T15:17:41.143", "Id": "74068", "Score": "0", "body": "@WilliamMorris That's usually because I hang out in our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor), and there is a constantly updating feed of new questions so I can see when they are posted. :P" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:47:12.043", "Id": "40196", "ParentId": "40176", "Score": "11" } }, { "body": "<p>Just be careful with your <code>double timeSeconds(Time time)</code> function, since a double does not have enough bits to fully express a large number of seconds and a small number of fractional seconds. For example, using a timestamp in the year of 2014, resolution for fractions of a second starts breaking down somewhere around 10us.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-06T16:19:19.923", "Id": "69094", "ParentId": "40176", "Score": "3" } }, { "body": "<p>You may also want an implementation for <code>timeCmp</code> in order to complete your library:</p>\n\n<pre><code>// Return 1 if a &gt; b, -1 if a &lt; b, 0 if a == b\nstatic inline __constant int timeCmp(Time a, Time b) {\n if (a.tv_sec != b.tv_sec) {\n if (a.tv_sec &gt; b.tv_sec)\n return 1;\n else \n return -1;\n } else {\n if (a.tv_nsec &gt; b.tv_nsec)\n return 1;\n else if (a.tv_nsec &lt; b.tv_nsec)\n return -1;\n else\n return 0;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-03T11:00:08.353", "Id": "79451", "ParentId": "40176", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T16:59:58.583", "Id": "40176", "Score": "8", "Tags": [ "c", "datetime", "linux" ], "Title": "Correctness of calculations with struct timespec" }
40176
<p>I just want to make sure that my Rolling (Moving) Average class is understandable and reasonably <a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/what-is-this-thing-you-call-thread-safe" rel="nofollow noreferrer">thread safe</a>.</p> <p>My main questions are:</p> <ol> <li><p>Is having totalCounts as a long just for a potential edge case overkill?</p> </li> <li><p>Is checking to see if the number of observed counts is 1 (and thus, just return the observed total), also edge case overkill?</p> </li> <li><p>Is there any way to minimize the locking in Add Method? (It's not a bottle neck or anything, but I'm just wondering if I might be locking that part more than needed)</p> </li> </ol> <p>--</p> <pre><code>public sealed class RollingAverage { public RollingAverage() : this(defaultMaxRememberedNumbers) { // } public RollingAverage(int maxRememberedNumbers) { if (maxRememberedNumbers &lt;= 0) { throw new ArgumentException(&quot;maxRememberedNumbersmust be greater than 0.&quot;, &quot;maxRememberedNumbers&quot;); } this.counts = new Queue&lt;int&gt;(maxRememberedNumbers); this.maxSize = maxRememberedNumbers; this.currentTotal = 0L; this.padLock = new Object(); } private const int defaultMaxRememberedNumbers = 10; private readonly Queue&lt;int&gt; counts; private readonly int maxSize; private long currentTotal; private object padLock; public void Add(int value) { lock (this.padLock) { if (this.counts.Count == this.maxSize) { this.currentTotal -= (long)this.counts.Dequeue(); } this.counts.Enqueue(value); this.currentTotal += (long)this.value; } } public int CurrentAverage { get { long lenCounts; long observedTotal; lock (this.padLock) { lenCounts = (long)this.counts.Count; observedTotal = this.currentTotal; } if (lenCounts == 0) { throw new InvalidOperationException(&quot;No counts to average.&quot;); } else if (lenCounts == 1) { return (int)observedTotal; } else { return (int)(observedTotal / lenCounts); } } } public void Clear() { lock (this.padLock) { this.currentTotal = 0L; this.counts.Clear(); } } } </code></pre> <p>-Edit- Fixed inconsistent use of &quot;this.&quot;.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:31:10.977", "Id": "67599", "Score": "0", "body": "With `int` it does not matter, but for floating-point computations, the naive formula for a rolling average is prone to unnecessary round-off errors. And this has been known for 50 years. See [this](http://www.johndcook.com/standard_deviation.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-10T12:01:59.757", "Id": "501952", "Score": "0", "body": "Take look at https://docs.microsoft.com/en-us/dotnet/standard/collections/thread-safe/ if you haven’t considered it" } ]
[ { "body": "<p>To answer your questions:</p>\n\n<ol>\n<li>It's hard to say. If you expect a large number of values or moderate number of large values, you could potentially overflow an int. Otherwise, you may be fine using int instead of long.</li>\n<li>Yes, it's overkill, since dividing the total by the count would yield the correct answer anyways.</li>\n<li>Unfortunately, no. You need to lock anything which can be mutated by other threads, and you're doing precisely that.</li>\n</ol>\n\n<p>I would do a few things:</p>\n\n<ul>\n<li><p>Use a different naming format for fields than you do for local variables. The most common format I have seen with .NET code is an underscore prefix, though the naming guidelines do not have any particular rule for private fields. Once that is done, you can drop all the <code>this</code> references.</p></li>\n<li><p>Constants should use different casing from fields. SCREAMING CASE is the one I follow and see most often, but the framework isn't really consistent. There appears to be a mix of PascalCase and SCREAMING_CASE, depending on which class you look at in ILDASM, even just within mscorlib.dll.</p></li>\n<li><p>Avoid unnecessary casting. .NET performs implicit casting in many cases, so there is no need to use most of the casts. The only exception is casting the calculated average to int (from long).</p></li>\n<li><p>Use proper exceptions. The exception in the constructor should instead be <code>ArgumentOutOfRangeException</code>, as it more clearly states what the problem was.</p></li>\n<li><p>Returning from within a lock works, so there is no need to define local variables for the total in the CurrentAverage property</p>\n\n<pre><code>public sealed class RollingAverage\n{\n public RollingAverage()\n : this(DEFAULT_MAX_CAPACITY)\n {\n }\n\n public RollingAverage(int maxCapacity)\n {\n if (maxCapacity &lt;= 0)\n {\n throw new ArgumentOutOfRangeException(\"maxRememberedNumbersmust be greater than 0.\",\n \"maxRememberedNumbers\");\n }\n\n _counts = new Queue&lt;int&gt;(maxCapacity);\n _maxSize = maxCapacity;\n _currentTotal = 0L;\n _padLock = new Object();\n }\n\n private const int DEFAULT_MAX_CAPACITY = 10;\n\n private readonly Queue&lt;int&gt; _counts;\n private readonly int _maxSize;\n\n private long _currentTotal;\n private object _padLock;\n\n public void Add(int value)\n {\n lock (_padLock)\n {\n if (_counts.Count == _maxSize)\n {\n _currentTotal -= _counts.Dequeue();\n }\n\n _counts.Enqueue(value);\n _currentTotal += value;\n }\n }\n\n public int CurrentAverage\n {\n get\n {\n lock (_padLock)\n {\n var lenCounts = _counts.Count;\n if (lenCounts == 0)\n {\n throw new InvalidOperationException(\"No counts to average.\");\n }\n\n return (int)(_currentTotal / lenCounts);\n }\n }\n }\n\n public void Clear()\n {\n lock (_padLock)\n {\n _currentTotal = 0L;\n _counts.Clear();\n }\n }\n}\n</code></pre></li>\n</ul>\n\n<h2>Other things to consider</h2>\n\n<ul>\n<li><p>Consider using a <code>float</code> or <code>double</code> type for the CurrentAverage property. It is better to preserve the correct decimal answer in case you need a more exact average. You can always truncate the answer back down to an int or float in the caller if you really want.</p></li>\n<li><p>If the ratio of reads/writes heavily favors reads, consider using a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim%28v=vs.110%29.aspx\">ReaderWriterLockSlim</a>. This will allow multiple readers to retrieve the average without blocking one another. Just remember to differentiate between obtaining the lock in reader mode versus writer or upgrade mode.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:23:06.853", "Id": "67561", "Score": "0", "body": "I'll agree with most of your assessments (especially returning double rather than int for CurrentAverage - let the calling code decide how to deal with the fractional part). But I'm keeping the structure of CurrentAverage, due to the fact that I'm only needing to look at those two values (`this.counts.Count` and `this.currentTotal`), so why lock for longer than I need? And I also prefer explicit conversion as a nice way of showing two variables aren't the same type without resorting to Systems Hungarian Notation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:45:00.613", "Id": "40182", "ParentId": "40177", "Score": "6" } }, { "body": "<p>Couple of small bits:</p>\n\n<ul>\n<li>The arguments to your <code>ArgumentOutOfRangeException</code> exception are in the wrong order.</li>\n<li>I eliminated the <code>padLock</code> member variable, because the <code>counts</code> member variable is perfectly convenient to use as a <code>lock</code> argument for the usage under consideration.</li>\n</ul>\n\n<p>I agree with what <a href=\"https://codereview.stackexchange.com/users/7983/dan-lyons\">Dan Lyons</a> <a href=\"https://codereview.stackexchange.com/a/40182/6172\">has to say</a>, but I take a somewhat different tack on naming conventions and <code>this</code> usage. A lot of this comes from <a href=\"https://stylecop.codeplex.com/\" rel=\"nofollow noreferrer\">StyleCop</a> and <a href=\"https://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">ReSharper</a>. Just as a comparison, here's my version:</p>\n\n<pre><code>public sealed class RollingAverage\n{\n private const int DefaultMaxCapacity = 10;\n\n private readonly Queue&lt;int&gt; counts;\n\n private readonly int maxSize;\n\n private long currentTotal;\n\n public RollingAverage() : this(DefaultMaxCapacity)\n {\n }\n\n public RollingAverage(int maxCapacity)\n {\n if (maxCapacity &lt; 1)\n {\n throw new ArgumentOutOfRangeException(\n \"maxCapacity\",\n \"maxCapacity must be greater than 0.\");\n }\n\n this.counts = new Queue&lt;int&gt;(maxCapacity);\n this.maxSize = maxCapacity;\n this.currentTotal = 0L;\n }\n\n public double CurrentAverage\n {\n get\n {\n lock (this.counts)\n {\n var lenCounts = this.counts.Count;\n\n if (lenCounts == 0)\n {\n throw new InvalidOperationException(\"No counts to average.\");\n }\n\n return this.currentTotal / (double)lenCounts;\n }\n }\n }\n\n public void Add(int value)\n {\n lock (this.counts)\n {\n if (this.counts.Count == this.maxSize)\n {\n this.currentTotal -= this.counts.Dequeue();\n }\n\n this.counts.Enqueue(value);\n this.currentTotal += value;\n }\n }\n\n public void Clear()\n {\n lock (this.counts)\n {\n this.counts.Clear();\n this.currentTotal = 0L;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:19:17.653", "Id": "67593", "Score": "0", "body": "Sorry to be nit-picky, but I used `ArgumentException`, not `ArgumentOutOfRangeException`, which the arguments ARE in the correct order. And if it weren't for `currentTotal`, I might agree with you about using `counts` as a lock - though I'd have to think about how that might impact maintenance. It seems useful though, so I think I'll use it in a future project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:26:59.433", "Id": "67598", "Score": "0", "body": "Whups, that's what I get for looking at both the original code and the one in one of the answers at the same time. Sorry about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-08T06:34:39.167", "Id": "501792", "Score": "0", "body": "Any reason not to use Interlocked.Increment instead of the second lock on the incrementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-08T13:24:27.067", "Id": "501816", "Score": "1", "body": "@Alenros Yes, the reason not to is because there is more than just the increment happening within the lock." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T21:59:34.150", "Id": "40210", "ParentId": "40177", "Score": "2" } } ]
{ "AcceptedAnswerId": "40182", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-01-27T17:02:42.643", "Id": "40177", "Score": "6", "Tags": [ "c#" ], "Title": "Rolling Average class sanity check" }
40177
<p>I have below code in one function:</p> <pre><code>public void func() { if (!string.IsNullOrEmpty(customerpay) &amp;&amp; !string.IsNullOrEmpty(warrantypay) &amp;&amp; !string.IsNullOrEmpty(maintanceplan)) { if (customerpay == "Include" &amp;&amp; warrantypay == "Include" &amp;&amp; maintanceplan == "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[C^W^I]"; } else if (customerpay == "Include" &amp;&amp; warrantypay == "Include" &amp;&amp; maintanceplan != "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[C^W]"; } else if (customerpay == "Include" &amp;&amp; warrantypay != "Include" &amp;&amp; maintanceplan != "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[C]"; } else if (customerpay != "Include" &amp;&amp; warrantypay == "Include" &amp;&amp; maintanceplan == "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[W^I]"; } else if (customerpay != "Include" &amp;&amp; warrantypay != "Include" &amp;&amp; maintanceplan == "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[I]"; } else if (customerpay != "Include" &amp;&amp; warrantypay == "Include" &amp;&amp; maintanceplan != "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[W]"; } else if (customerpay == "Include" &amp;&amp; warrantypay != "Include" &amp;&amp; maintanceplan == "Include") { transactiontype = "," + "[Population].[Transaction Type Code].&amp;[C^I]"; } } } </code></pre> <p>I need to simplify the above <code>if</code>-<code>else</code> C# code. Is there a way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:46:01.797", "Id": "67537", "Score": "0", "body": "One thing you could do is have those `(stringVar) == \"Include\"` as boolean checks at the start of the if statement, like so: `if(/*none are null*/) { bool hasCustomerPay = customerpay == \"Include\"; bool hasWarrentPay = warrentpay == \"Include\"; bool hasMaintancePlan = maintanceplan == \"Include\"; /*long if-else here*/ }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T14:54:12.917", "Id": "67955", "Score": "0", "body": "What is logic behind this code? A bet you have some rules to decide whether you add one or more 'lines' to transactiontype, and rule which you use for generation C^WI combinations" } ]
[ { "body": "<p>You could do it like this:</p>\n\n<pre><code>public void func()\n{\n if (string.IsNullOrEmpty(customerpay) || string.IsNullOrEmpty(warrantypay) || string.IsNullOrEmpty(maintanceplan))\n return;\n\n if (customerpay != \"Include\" &amp;&amp; warrantypay != \"Include\" &amp;&amp; maintanceplan != \"Include\")\n return;\n\n List&lt;char&gt; parts = new List&lt;char&gt;();\n if (customerpay == \"Include\")\n parts.Add(\"C\");\n if (warrantypay == \"Include\")\n parts.Add(\"W\");\n if (maintanceplan == \"Include\")\n parts.Add(\"I\");\n\n transactiontype = \",[Population].[Transaction Type Code].&amp;[\" + string.Join(\"^\", parts) + \"]\";\n}\n</code></pre>\n\n<p>First, we simply return if any of the strings is empty; by inverting the logic, we can reduce one indentation level that makes the code unecessarily complicated. We also return for the single case that isn’t handled in your original code: If all three strings are not <code>\"Include\"</code>.</p>\n\n<p>After that, it’s easy once you find out the pattern of your string. The only changing part of your result string is in the brackets at the end. There are three possible characters: <code>C</code>, <code>W</code>, and <code>I</code>. They appear if the corresponding string equals to <code>\"Include\"</code>. The characters are separated by a <code>^</code>. So we just check each condition alone, and collect the characters in a list. Then we join with the separation character and build the final result string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:56:45.083", "Id": "67540", "Score": "0", "body": "+1 beat me to it :) Though, you could probably omit the IsNullOrEmpty checks since the inequality check takes care of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:00:48.230", "Id": "67542", "Score": "0", "body": "+1 for beating me to it also :) ... *and* for handling the unlikely case where none of the strings say \"Include\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:00:34.883", "Id": "67556", "Score": "0", "body": "@DanLyons Good idea, but that is actually only half-true. When just one of the strings equals `\"Include\"`, then the inequality check is skipped, but the two other variables could still be null ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:42:56.280", "Id": "67709", "Score": "0", "body": "@poke thanks for your solution.i have modified question by added some more conditions. could you please check once again and please let me know how can i use this solution for that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:27:34.610", "Id": "67721", "Score": "0", "body": "@SivaRajini Does the order of the resulting things matter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T14:51:10.683", "Id": "67954", "Score": "0", "body": "@SivaRajini do not modify question in the way which invalidates answers. If these answers cannot help in your real problem, then ask another question" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:55:09.883", "Id": "40185", "ParentId": "40178", "Score": "11" } }, { "body": "<p>Well the first condition could be reversed, immediately reducing the nesting level:</p>\n\n<pre><code>if (string.IsNullOrEmpty(customerpay) || string.IsNullOrEmpty(warrantypay) || string.IsNullOrEmpty(maintanceplan))\n{\n return;\n}\n\n// rest of conditions\n</code></pre>\n\n<p>This code <em>looks</em> like sample code, but I'll say it anyway: <code>func</code> is a bad name for any function, especially one that returns <code>void</code>. And to follow naming C# conventions it should be named <code>Func</code> - but that clashes with the framework's <code>Func&lt;T&gt;</code>, making it even more confusing. Give meaningful names!!</p>\n\n<p>Back to the <code>else if</code> blocks..</p>\n\n<p>This code builds a <code>string</code>. I think <code>transactionType</code> should be <code>transactionTypeBuilder</code> and be of type <code>StringBuilder</code> - don't concatenate strings like that; <strong>build</strong> them instead!</p>\n\n<p>Moreover, each branch is really coming up with <em>the very last part</em> to be added to the string, so it would be easier to understand what the code does at a glance if you introduced a variable and changed the <code>transactionType</code> assignment to this:</p>\n\n<pre><code>transactionType = string.Format(\",[Population].[Transaction Type Code].&amp;[{0}]\", code);\n</code></pre>\n\n<p>Where <code>code</code> is what each branch is trying to solve. This leaves you with this:</p>\n\n<pre><code>var code = string.Empty;\nif (customerpay == \"Include\" &amp;&amp; warrantypay == \"Include\" &amp;&amp; maintanceplan == \"Include\")\n{\n code = \"C^W^I\";\n}\nelse if (customerpay == \"Include\" &amp;&amp; warrantypay == \"Include\" &amp;&amp; maintanceplan != \"Include\")\n{\n code = \"C^W\";\n}\nelse if (customerpay == \"Include\" &amp;&amp; warrantypay != \"Include\" &amp;&amp; maintanceplan != \"Include\")\n{\n code = \"C\";\n}\nelse if (customerpay != \"Include\" &amp;&amp; warrantypay == \"Include\" &amp;&amp; maintanceplan == \"Include\")\n{\n code = \"W^I\";\n}\nelse if (customerpay != \"Include\" &amp;&amp; warrantypay != \"Include\" &amp;&amp; maintanceplan == \"Include\")\n{\n code = \"I\";\n}\nelse if (customerpay != \"Include\" &amp;&amp; warrantypay == \"Include\" &amp;&amp; maintanceplan != \"Include\")\n{\n code = W\";\n}\nelse if (customerpay == \"Include\" &amp;&amp; warrantypay != \"Include\" &amp;&amp; maintanceplan == \"Include\")\n{\n code = \"C^I\";\n}\n</code></pre>\n\n<p>Now each test seems to be crying for a <code>bool</code>. Consider this:</p>\n\n<pre><code>var code = string.Empty;\nvar includeCustomerPay = (customerPay == \"Include\");\nvar includeWarrantyPay = (warrantyPay == \"Include\");\nvar includeMaintenancePlan = (maintenancePlan == \"Include\");\n\nif (includeCustomerPay &amp;&amp; includeWarrantyPay &amp;&amp; includeMaintancePlan)\n{\n code = \"C^W^I\";\n}\nelse if (includeCustomerPay &amp;&amp; includeWarrantyPay &amp;&amp; !includeMaintancePlan\n{\n code = \"C^W\";\n}\nelse if (includeCustomerPay &amp;&amp; !includeWarrantyPay &amp;&amp; !includeMaintancePlan)\n{\n code = \"C\";\n}\nelse if (!includeCustomerPay &amp;&amp; includeWarrantyPay &amp;&amp; includeMaintancePlan)\n{\n code = \"W^I\";\n}\nelse if (!includeCustomerPay &amp;&amp; !includeWarrantyPay &amp;&amp; includeMaintancePlan)\n{\n code = \"I\";\n}\nelse if (!includeCustomerPay &amp;&amp; includeWarrantyPay &amp;&amp; !includeMaintancePlan)\n{\n code = \"W\";\n}\nelse if (includeCustomerPay &amp;&amp; !includeWarrantyPay &amp;&amp; includeMaintancePlan)\n{\n code = \"C^I\";\n}\n</code></pre>\n\n<p>Isn't something starting to emerge? The \"code\" for each <code>bool</code> is always in the same order, and separated by a <code>\"^\"</code>.</p>\n\n<p>Therefore, the whole condition can be dropped, with the help of a bit of <a href=\"/questions/tagged/linq\" class=\"post-tag\" title=\"show questions tagged &#39;linq&#39;\" rel=\"tag\">linq</a>:</p>\n\n<pre><code>var codes = new[] \n { \n includeCustomerPay ? \"C\" : string.Empty,\n includeWarrantyPay ? \"W\" : string.Empty,\n includeMaintenancePlan ? \"I\" : string.Empty\n };\n\nvar code = string.Join(\"^\", codes.Where(c =&gt; !string.IsNullOrEmpty));\ntransactionType = string.Format(\",[Population].[Transaction Type Code].&amp;[{0}]\", code);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:43:42.967", "Id": "67710", "Score": "0", "body": "thanks for your solution.i have modified question by added some more conditions. could you please check once again and please let me know how can i use this solution for that updated question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:19:58.610", "Id": "67718", "Score": "3", "body": "@SivaRajini you realize you've just invalidated both answers with that edit? I suggest you rollback that edit, rework your code per our answers (and accept either), and post another CR question with your updated code. More work, but more votes for everyone :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:40:00.677", "Id": "67733", "Score": "0", "body": "Agreed; just starting a new answer with the full code would be fine too (i.e. without reworking it), as the situation changed quite a bit, and our solutions don’t really apply easily to the new thing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:56:47.693", "Id": "40186", "ParentId": "40178", "Score": "10" } } ]
{ "AcceptedAnswerId": "40185", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:20:21.167", "Id": "40178", "Score": "8", "Tags": [ "c#" ], "Title": "Simplifying conditional statements for transaction code" }
40178
<blockquote> <p>Define a macro <code>swap(t, x, y)</code> that interchanges two arguments of type <code>t</code>.(Block structure will help.)</p> </blockquote> <p>The ideea is that a variable defined in a block structure exists only inside the block structure. So, I can create a temporary variable without affecting the code.</p> <p>Here is my solution:</p> <pre><code>#include &lt;stdio.h&gt; #define swap(t, x, y) {t tmp = x; x = y; y = tmp;} int main() { int x = 10, y = 2; swap(int, x, y); printf("%d %d", x, y); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:19:11.617", "Id": "67551", "Score": "5", "body": "I see that you have made a recent edit that invalidates some advice in the answers. It is often not recommended to make changes to your code once it has been reviewed (or even posted). Therefore, I have rolled back your edit so that all the answers can still be considered valid." } ]
[ { "body": "<p>If you are using GCC, we can use the <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Typeof.html\" rel=\"nofollow noreferrer\"><code>typeof()</code></a><sup>(C99)</sup> keyword to get rid of one of the arguments. Also, <a href=\"https://stackoverflow.com/q/154136/1937270\">add a <code>do-while</code> so the macro to be used in contexts where it would otherwise be problematic</a>.</p>\n\n<pre><code>#define SWAP(a, b) do { typeof(a) t; t = a; a = b; b = t; } while(0)\n</code></pre>\n\n<hr>\n\n<p>You could also use an exclusive-or (<code>^=</code>) to get rid of that temporary variable, but that only works for integers.</p>\n\n<pre><code>#define SWAP(a, b) do { a ^= b; b ^= a; a ^= b; } while(0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:37:18.267", "Id": "67532", "Score": "2", "body": "But that doesn't support other arguments than ints (or other ordinal types), does it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:49:40.740", "Id": "67538", "Score": "0", "body": "@SimonAndréForsberg You are correct. I have added in another solution that works with more types than just `int`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T10:34:56.990", "Id": "79138", "Score": "1", "body": "Note that is you are using GCC 4.9, a somewhat better solution would be to use the `__auto_type` extension whose behaviour is similar to the C++11 keyword `auto`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:33:43.613", "Id": "40181", "ParentId": "40180", "Score": "12" } }, { "body": "<p>First, macros should have <code>ALL_CAPS</code> names to distinguish them from functions. Users need to be able to distinguish macros from functions because they behave slightly differently. For example, with your definition of <code>swap()</code> as a macro, this code (for illustration purposes — not that it's good code) fails to compile:</p>\n\n<pre><code>if (swap(int, x, y), x) {\n /* Do something */\n}\n</code></pre>\n\n<p>Also, I'd put a <a href=\"https://stackoverflow.com/q/154136/1157100\">defensive <code>do { ... } while (0)</code></a> around your definition. Otherwise, this would cause an unexpected compilation error:</p>\n\n<pre><code>int main() {\n int x = 10, y = 0;\n if (x != 0)\n SWAP(int, x, y);\n else\n x = 0;\n printf(\"%d %d\\n\", x, y);\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:58:32.717", "Id": "40187", "ParentId": "40180", "Score": "10" } } ]
{ "AcceptedAnswerId": "40181", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T17:27:30.230", "Id": "40180", "Score": "9", "Tags": [ "c", "macros" ], "Title": "Macro that interchanges 2 arguments" }
40180
<p>Today I started to tackle the 99 Haskell problems (<a href="http://www.haskell.org/haskellwiki/99_questions">http://www.haskell.org/haskellwiki/99_questions</a>). I had to struggle with problem 9 which requires to <em>Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.</em>.</p> <p>For example the input:</p> <pre><code>pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'] ["aaaa","b","cc","aa","d","eeee"] </code></pre> <p>I managed to create a <code>pack</code> function. However, my solution feels kind of overcomplicated:</p> <pre><code>pack :: [[Char]] -&gt; [[Char]] pack xs = foldl (\acc x -&gt; if not(null acc) &amp;&amp; x `Data.List.isPrefixOf` (last acc) then (init acc) ++ [(last acc) ++ x] else acc ++ [x]) [] xs </code></pre> <p>A <strong>test</strong> of my <code>pack</code> function:</p> <pre><code>pack ["a", "a", "b", "b", "b", "c", "a", "a", "c"] ["aa","bbb","c","aa","c"] </code></pre> <ul> <li>Can you give me a code review?</li> <li>How can I simplify it? What could I improve to make this function more idiomatic?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:54:03.300", "Id": "67737", "Score": "0", "body": "For the record, that is the same as the `group` function of `Data.List`. You could also inspect its [source code](http://hackage.haskell.org/package/base-4.6.0.1/docs/src/Data-List.html#group)." } ]
[ { "body": "<p>Let's improve the function step by step, focusin on readability as well as on the algorithm itself.</p>\n\n<ol>\n<li><p>I believe the type of the function is not what it should be. We get a list of characters, and we should produce a list of lists:</p>\n\n<pre><code>pack1 :: [Char] -&gt; [[Char]]\npack1 xs = foldl (\\acc x -&gt; if not(null acc) &amp;&amp; [x] `isPrefixOf` (last acc) \n then (init acc) ++ [(last acc) ++ [x]] \n else acc ++ [[x]]) [] xs\n</code></pre></li>\n<li><p>The function doesn't require that we compare <code>Char</code>s. In such a case, it's better to make its type as generic as possible. Not only it makes it usage more generic, it also helps us ensure that we restrict to the specific problem of packing, not introducing anything particular about <code>Char</code>s. So the generalized type would be <code>(Eq a) =&gt; [a] -&gt; [[a]]</code>.</p></li>\n<li><p>The <strong>major problem</strong> is that the function has <em>O(n^2)</em> time complexity. This is because calling <code>last</code> on a list, or appending someting to its end using <code>++</code> is <em>O(n)</em>, and doing it <em>n</em>-times gets us to <em>O(n^2)</em>. This is definitely something we'd like to avoid. The solution is easy: Instead of appending to the list, let's just prepend, and reverse it at the end. Since <code>reverse</code> is <em>O(n)</em>, the result will be <em>O(n)</em> as well. Let's apply this idea to both the \"big\" list as well as its sublists:</p>\n\n<pre><code>pack2 :: (Eq a) =&gt; [a] -&gt; [[a]]\npack2 xs = reverse . map reverse $\n foldl (\\acc x -&gt; if not (null acc) &amp;&amp; [x] `isPrefixOf` (head acc)\n then (x : (head acc)) : (tail acc)\n else [x] : acc) [] xs\n</code></pre>\n\n<p>Most likely we could also omit <code>map reverse</code>, as the sublists always contain equal elements. This assumes that if two elements are equal, they're indistinguishable, which is usually a reasonable assumption. But I kept it there for completeness, and it doesn't affect the asymptotic complexity.</p></li>\n<li><p>In Haskell it's customary to avoid <code>if/then/else</code> in favor of pattern matching. Not only it's often shorter, but it provides stronger guarantees and/or less required reasoning about the code. In the <code>if</code> condition, the reader needs to infer that using <code>last</code> or <code>head</code> on <code>acc</code> is allowed because we checked it's non-empty. If we instead factor out the inner function and use patternmatching,</p>\n\n<pre><code>pack3 :: (Eq a) =&gt; [a] -&gt; [[a]]\npack3 = reverse . map reverse . foldl f []\n where f acc@(as@(a:_):ass) x | a == x = (x : as) : ass\n f acc x = [x] : acc\n</code></pre>\n\n<p>we don't need to use any potentially dangerous functions such as <code>head/tail</code> and do any checking.</p>\n\n<p>Here we also introduced another small improvement called η-conversion (eta). The idea is that <code>\\x -&gt; g x</code> is equivalent to <code>g</code>.</p></li>\n<li><p>We'd like to avoid calling <code>reverse</code>.</p>\n\n<p>The problem is that we're using <code>foldl</code> to produce the final list. By its nature, if we use <code>foldl</code> for converting lists, it reverses the order of the elements (or causes <em>O(n^2)</em> time complexity). Although we want to consume the list from left to right, it's more appropriate to use <code>foldr</code> here. (I'd say that the only reason to use <code>foldl</code> is if the result needs the whole list - for example when summing a list.)</p>\n\n<p>Let's start with implementing <code>map</code> using <code>foldr</code>. (I'll hide the example, if you want to try it yourself. If you don't, just hover the mouse over it.)</p>\n\n<blockquote class=\"spoiler\">\n <p> <code>map' f = foldr (\\x r -&gt; f x : r) []</code>\n \n The idea is to express how to process a single element, knowing how the rest of the list is processed.</p>\n</blockquote>\n\n<p>Let's apply the same principle to <code>pack</code>:</p>\n\n<pre><code>pack4 :: (Eq a) =&gt; [a] -&gt; [[a]]\npack4 = foldr f []\n where f x acc@(as@(a:_):ass) | a == x = (x : as) : ass\n f x acc = [x] : acc\n</code></pre>\n\n<p>This isn't very different from the previous example. The main difference is that we (seemingly!) consume elements from the right, so we have no problem with reversing the order.</p></li>\n<li><p>And still ... we can ask for more. The problem is that the function isn't lazy enough (even though we're using <code>foldr</code>). We'd like for example that </p>\n\n<pre><code>head $ pack4 ('a' : 'c' : repeat 'b')\n</code></pre>\n\n<p>produced \"a\", instead of looping forever - the required information is available. The reason for this is that we inspect the accumulator (by matching it with the pattern <code>acc@(as@(a:_):ass)</code> which is not <em>irrefutable</em>) at each iteration, which means that in order to produce a single element we first force the processing of the rest of the list. </p>\n\n<p>Instead, we can create the result structure first to hold the current element without forcing the results of processing the rest of input list, so that this structure will be filled with more values only when/if it is so demanded:</p>\n\n<pre><code>pack5 :: (Eq a) =&gt; [a] -&gt; [[a]]\npack5 = foldr f []\n where \n f x r = (x:u):w \n where \n (u,w) = case r of \n [] -&gt; ([],[]) \n (g:gs) | head g==x -&gt; (g ,gs) \n gs -&gt; ([],gs)\n</code></pre></li>\n</ol>\n\n<p>See also the source code for <a href=\"http://hackage.haskell.org/package/base-4.6.0.1/docs/src/Data-List.html#group\" rel=\"nofollow\">group</a>, which is also implemented with the lazy behavior. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T16:40:48.293", "Id": "68115", "Score": "1", "body": "lazy code: `... where { f x r = (x:u):w where (u,w) = case r of { [] -> ([],[]) ; (g:gs) | head g==x -> (g,gs) ; gs -> ([],gs) }}`. Separation of structure creation and filling. Saw it first in some answer by Daniel Fischer, but it's very similar to what is normally done, in Prolog." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T15:05:34.863", "Id": "68480", "Score": "0", "body": "@WillNess I don't think it'd be fair to add it to my answer, as it was your idea. Better add it as your own answer. (Or feel free to edit my answer yourself.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T15:35:55.787", "Id": "68482", "Score": "0", "body": "Done editing. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:19:01.253", "Id": "40211", "ParentId": "40188", "Score": "10" } } ]
{ "AcceptedAnswerId": "40211", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:03:09.000", "Id": "40188", "Score": "7", "Tags": [ "haskell" ], "Title": "99 Haskell problems, problem 9: Pack function" }
40188
<p><strong>PigLatin Kata</strong></p> <pre><code>PigLatin Kata Create a PigLatin class that is initialized with a string - detail: The string is a list of words seperated by spaces: 'hello world' - detail: The string is accessed by a method named phrase - detail: The string can be reset at any time without re-initializing - example: PigLatin.new('hello world') completed (Y|n): Translate Method Create a translate method that translates the phrase from english to pig-latin. - detail: The method will return a string. - detail: The empty string will return nil. - example: "" translates to nil completed (Y|n): Translate words that start with vowels. - detail: Append "ay" to the word if it ends in a consonant. - example: "ask" translates to "askay" - detail: Append "yay" to the word if it ends with a vowel. - example: "apple" translates to "appleyay" - detail: Append "nay" to the word if it ends with "y". - example: "any" translates to "anynay" completed (Y|n): Translate a word that starts with a single consonant. - detail: Removing the consonant from the front of the word. - detail: Add the consonant to the end of the word. - detail: Append 'ay' to the resulting word. - example: "hello" translates to "ellohay" - example: "world" translates to "orldway" completed (Y|n): Translate words that start with multiple consonants. - detail: Remove all leading consonants from the front of the word. - detail: Add the consonants to the end of the word. - detail: Append 'ay' to the resulting word. - example: "known" translates to "ownknay" - example: "special" translates to "ecialspay" completed (Y|n): Support any number of words in the phrase. - example: "hello world" translates to "ellohay orldway" - detail: Each component of a hyphenated word is translated seperately. - example: "well-being" translates to "ellway-eingbay" completed (Y|n): Support capital letters. - detail: If a word is captalized, the translated word should be capitalized. - example: "Bill" translates to "Illbay" - example: "Andrew" translates to "Andreway" completed (Y|n): Retain punctuation. - detail: Punctuation marks should be retained from the source to the translated string - example: "fantastic!" tranlates to "anfasticfay!" - example: "Three things: one, two, three." translates to "Eethray ingsthay: oneyay, otway, eethray." completed (Y|n): Congratulations! - Create a PigLatin class that is initialized with a string 00:03:51 - Create a translate method that translates the phrase from english to p 00:02:09 - Translate words that start with vowels. 00:09:24 - Translate a word that starts with a single consonant. 00:05:13 - Translate words that start with multiple consonants. 00:01:26 - Support any number of words in the phrase. 02:48:13 - Support capital letters. 00:10:46 - Retain punctuation. 00:40:26 ---------------------------------------------------------------------- -------- Total Time taking PigLatin kata: 04:01:27 </code></pre> <p><strong>Specs:</strong></p> <pre><code> 1 require 'spec_helper' 2 require 'piglatin' 3 4 describe PigLatin do 5 subject(:piglatin) { PigLatin.new phrase } 6 let(:phrase) { "hello world" } 7 8 describe "new" do 9 specify { expect { piglatin }.to_not raise_error } 10 end 11 12 describe ".translate" do 13 let(:phrase) { "" } 14 its(:translate) { should eq("") } 15 16 context "for words that start with vowels" do 17 context "and end with consonants" do 18 let(:phrase) { "ask" } 19 subject(:translate) { piglatin.translate } 20 it 'appends ay' do 21 should eq("askay") 22 end 23 end 24 context "and end with vowels" do 25 let(:phrase) { "apple" } 26 its(:translate) do should eq("appleyay") end 27 end 28 context "and ends with y" do 29 let(:phrase) { "any" } 30 its(:translate) { should eq(phrase + "nay") } 31 end 32 end 33 34 context "words that start with consonants" do 35 let(:phrase) { "hello" } 36 its(:translate) { should eq("ellohay") } 37 end 38 context "words that start with multiple consonants" do 39 let(:phrase) { "known" } 40 its(:translate) { should eq("ownknay") } 41 end 42 context "multiple words" do 43 let(:phrase) { "hello world" } 44 its(:translate) { should eq("ellohay orldway") } 45 end 46 context 'hyphenated words' do 47 let(:phrase) { "well-being" } 48 its(:translate) { should eq("ellway-eingbay") } 49 end 50 context 'capatalized words' do 51 let(:phrase) { "Bill" } 52 its(:translate) { should eq("Illbay") } 53 end 54 context 'capatalized words' do 55 let(:phrase) { "Andrew" } 56 its(:translate) { should eq("Andreway") } 57 end 58 context 'punctuation marks' do 59 let(:phrase) { "fantastic!" } 60 its(:translate) { should eq("antasticfay!") } 61 end 62 context 'complex phrase' do 63 let(:phrase) { 'Three things: one, two, three.' } 64 its(:translate) { should eq('Eethray ingsthay: oneyay, otway, eethray.') } 65 end 66 end 67 end </code></pre> <p><strong>PigLatin class:</strong></p> <pre><code> 1 class PigLatin 2 attr_accessor :phrase 3 alias :initialize :phrase= 4 5 def translate 6 return "" if @phrase.empty? 7 @phrase.gsub!(/\w+/) { |word| translate_word(word) } 8 end 9 10 private 11 12 def translate_word(word) 13 # Consonants 14 word.concat(word.slice!(/^[^aeiou]*/i || "")) 15 # Vowels 16 word.gsub!(/y$/, "yn") or word.gsub!(/([aeiou])$/, '\1y') 17 # Capitalized Words 18 word.capitalize! if word.downcase! 19 # Ending 20 word += 'ay' 21 end 22 end </code></pre>
[]
[ { "body": "<p>The code clearly works, and is very concise. I think that to make it more readable, instead of using comments, you could have expressive method names:</p>\n\n<pre><code>def translate_word(word)\n replace_consonants_to_end_of_word(word)\n\n append_n_to_last_letter_y(word) or append_y_to_last_letter_vowel(word)\n\n recapitalize(word)\n\n word += 'ay'\nend\n\ndef replace_consonants_to_end_of_word(word)\n word.concat(word.slice!(/^[^aeiou]*/i || \"\"))\nend\n\ndef append_n_to_last_letter_y(word)\n word.gsub!(/y$/, \"yn\")\nend\n\ndef append_y_to_last_letter_vowel(word)\n word.gsub!(/([aeiou])$/, '\\1y')\nend\n\ndef recapitalize(word)\n word.capitalize! if word.downcase!\nend\n</code></pre>\n\n<p>Sure, it's a little longer, but I believe it is more readable, and one can appreciate more how you tackled each of the requirements.</p>\n\n<p>Nice code, anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T07:29:15.773", "Id": "40829", "ParentId": "40189", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:27:45.713", "Id": "40189", "Score": "3", "Tags": [ "ruby", "rspec", "pig-latin" ], "Title": "Pig Latin Translator in Ruby and Rspec" }
40189
<p>I am learning about object oriented programming in Python using classes. I have attached an image of what I had in mind when structuring my classes. This is supposed script model cars. I want to know if the way that I set up my code it the ideal way of modeling cars.</p> <p>A few things:</p> <ul> <li><p>There are no syntax errors. I can create instances without errors.</p></li> <li><p>The subclasses uses <code>*args</code> to get the attributes of the parent class. Is this the correct way of doing that?</p></li> <li><p>I am using Python 2.7.5</p></li> <li><p>I have included a few example instances of the class</p></li> <li><p>Each class only has an <code>__init__</code> method and a <code>vehicle_print</code> method. I have not yet added any other methods.</p></li> </ul> <p><img src="https://i.stack.imgur.com/nUncP.jpg" alt="enter image description here"></p> <pre><code>class Vehicle(object): # no instance of this class should be created def __init__(self, typ, make, model, color, year, miles): self.typ = typ self.make = make self.model = model self.color = color.lower() self.year = year self.miles = miles def vehicle_print(self): print('Vehicle Type: ' + str(self.typ)) print('Make: ' + str(self.make)) print('Model: ' + str(self.model)) print('Color: ' + str(self.color)) print('Year: ' + str(self.year)) print('Miles driven: ' + str(self.miles)) class GasVehicle(Vehicle): def __init__(self, fuel_tank, *args): self.fuel_tank = fuel_tank Vehicle.__init__(self, *args) def vehicle_print(self): Vehicle.vehicle_print(self) print('Fuel capacity (gallons): ' + str(self.fuel_tank)) class ElectricVehicle(Vehicle): def __init__(self, energy_storage, *args): self.energy_storage = energy_storage Vehicle.__init__(self, *args) def vehicle_print(self): Vehicle.vehicle_print(self) print('Energy Storage (Kwh): ' + str(self.energy_storage)) class HeavyVehicle(GasVehicle): # no instance of this class should be created def __init__(self, max_weight, wheels, length, *args): self.max_weight = max_weight self.wheels = wheels self.length = length GasVehicle.__init__(self, *args) def vehicle_print(self): GasVehicle.vehicle_print(self) print('Maximum load (tons): ' + str(self.max_weight)) print('Wheels: ' + str(self.wheels)) print('Length (m): ' + str(self.length)) class ConstructionTruck(HeavyVehicle): def __init__(self, cargo, *args): self.cargo = cargo HeavyVehicle.__init__(self, *args) def vehicle_print(self): HeavyVehicle.vehicle_print(self) print('Cargo: ' + str(self.cargo)) class Bus(HeavyVehicle): def __init__(self, seats, * args): self.seats = seats HeavyVehicle.__init__(self, *args) def vehicle_print(self): HeavyVehicle.vehicle_print(self) print('Number of seats: ' + str(self.seats)) class HighPerformance(GasVehicle): # no instance of this class should be created def __init__(self, hp, top_speed, *args): self.hp = hp self.top_speed = top_speed GasVehicle.__init__(self, *args) def vehicle_print(self): GasVehicle.vehicle_print(self) print('Horse power: ' + str(self.hp)) print('Top speed: ' + str(self.top_speed)) class SportCar(HighPerformance): def __init__(self, gear_box, drive_system, *args): self.gearbox = gear_box self.drive_system = drive_system HighPerformance.__init__(self, *args) def vehicle_print(self): HighPerformance.vehicle_print(self) print('Gear box: ' + self.gearbox) print('Drive system: ' + self.drive_system) bmw = GasVehicle(30, 'SUV', 'BMW', 'X5', 'silver', 2003, 120300) # regular car bmw.vehicle_print() print tesla = ElectricVehicle(85, 'Sport', 'Tesla', 'Model S', 'red', 2014, 1243) # electric car tesla.vehicle_print() print lambo = SportCar('manual', 'rear wheel', 650, 160, 23, 'race car', 'Lamborgini', 'Enzo', 'dark silver', 2014, 3500) # sportscar lambo.vehicle_print() print truck = ConstructionTruck('cement', 4, 12, 21, 190, 'transport', 'Dirt Inc.', 'Dirt Blaster 100', 'blue', 1992, 120030) # Construction truck truck.vehicle_print() </code></pre> <ul> <li><a href="http://dpaste.com/hold/1572525/" rel="noreferrer">dpaste</a></li> <li><a href="http://pastebin.com/eQiT4F49" rel="noreferrer">pastebin</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:25:28.030", "Id": "67707", "Score": "1", "body": "Your class hierarchy makes no sense. There are electric buses, trucks, and sports cars." } ]
[ { "body": "<p>When chaining constructors, it's customary to call the parent class constructor first, then perform the subclass-specific initialization. Here, it makes little difference since you're just setting a bunch of variables, but in more complex situations you could run into problems doing things in this order.</p>\n\n<p>Use the <a href=\"https://stackoverflow.com/q/576169/1157100\"><code>super</code></a> keyword to avoid hard-coding the class hierarchy more than necessary.</p>\n\n<p>Instead of defining <code>vehicle_print()</code>, it would be more customary to define <code>__str__()</code>. It would also give the caller the flexibility to do something other than printing to <code>sys.stdout</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:20:04.530", "Id": "67576", "Score": "0", "body": "I disagree with the suggestion to use `super` here, at least for `__init__`. While `super` is designed to solve the diamond inheritance problem, it requires the multiple inheritance call chain's function parameters to remain compatible. Vader's `__init__` parameters are incompatible. But it would work fine in `vehicle_print` / `__str__`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T19:53:10.910", "Id": "40197", "ParentId": "40190", "Score": "6" } }, { "body": "<p>This is a fine place to start learning about OOP class hierarchies. It helps you understand how methods and data are shared amongst various members of the hierarchy. However I would never model a data-hierarchy in this fashion. In fact, especially in python, I would probably make just one class with a bunch of optional attributes. The one implementation of <code>vehicle_print</code> would conditionally print each of the attributes, depending on whether they had a real value. But first let's look more at what you built.</p>\n\n<p>Your use of calling the base class's implementation of <code>vehicle_print</code> is spot on for the hierarchy you've built. This lets you effectively share the implementation of your print function for the data that is shared. The interface of the function, however, is a little limiting, as you do not expose other functionality of the <code>print</code> statement. If you wanted to expose this, there are two main approaches:</p>\n\n<ul>\n<li>Add parameters to your function for other capabilities of the <code>print</code> statement, such as a <code>file=sys.stdout</code> parameter like is done in Python 3's <code>print</code> function. You could then use this in your <code>print</code> statement.</li>\n<li>Instead of implementing a printing function, implement a string-making function such as <code>__str__</code>. This allows the consumer to make those decisions explicitly. If you want to offer a <code>vehicle_print</code> function as well, it can become effectively <code>print str(self)</code>.</li>\n</ul>\n\n<p>Your use of <code>*args</code> in <code>__init__</code> feels a little unusual to me. This is because I'm used to the combined arguments growing in the other order. Instead of having the arguments to <code>SportsCar</code> be <code>(&lt;SportsCar&gt;, &lt;HighPerformance&gt;, &lt;GasVehicle&gt;, &lt;Vehicle&gt;)</code>, I typically expect <code>(&lt;Vehicle&gt;, &lt;GasVehicle&gt;, &lt;HighPerformance&gt;, &lt;SportsCar&gt;)</code>. This way when looking at initializations of different types, the first arguments are the same across types; your way it's the last arguments. Unfortunately for that order to work, you end up having to name all arguments:</p>\n\n<pre><code>class GasVehicle(Vehicle):\n def __init__(self, typ, make, model, color, year, miles, fuel_tank):\n self.fuel_tank = fuel_tank\n Vehicle.__init__(self, typ, make, model, color, year, miles)\n</code></pre>\n\n<p>or go with something unhelpful in your function signature:</p>\n\n<pre><code>class GasVehicle(Vehicle):\n def __init__(self, *args):\n if len(args) != 7: # optionally verify length...\n raise ValueError(\"...\")\n args = list(args)\n self.fuel_tank = args.pop()\n Vehicle.__init__(self, *args) # ...or let the base catch it\n</code></pre>\n\n<p>Finally, here's the approach I would actually take for the problem at hand. The downside is it doesn't actually leverage OOP, so if you're in a class studying it, you would likely be graded poorly for going this way. (By the way, in Python 3 I might make all the helper function's arguments keyword only, so they do not accept positional parameters, as positional become nearly unreadable in the lengths required below.)</p>\n\n<pre><code>class Vehicle(object):\n \"\"\"Represent a vehicle.\"\"\"\n def __init__(self, **kwargs):\n self.info = kwargs\n\n def __str__(self):\n strs = []\n # base Vehicle info is always known\n strs.append('Vehicle Type: ' + str(self.info['typ']))\n strs.append('Make: ' + str(self.info['make']))\n # ...\n # specialized info is not always known\n if 'fuel_tank' in self.info:\n strs.append('Fuel capacity (gallons): ' + str(self.info['fuel_tank'])\n if 'energy_storage' in self.info:\n strs.append('Energy Storage (Kwh): ' + str(self.info['energy_storage'])\n # ...\n return \"\\n\".join(strs)\n\n# helper functions to create concrete kinds of cars\ndef ElectricVehicle(typ, make, model, color, year, miles, energy_storage):\n # trick; equivalent to passing each element of the locals() dict by keyword\n return Vehicle(**locals())\ndef GasVehicle(typ, make, model, color, year, miles, fuel_tank):\n return Vehicle(**locals())\ndef SportsCar(typ, make, model, color, year, miles, fuel_tank, hp, top_speed, gear_box, drive_system):\n return Vehicle(**locals())\ndef ConstructionTruck(typ, make, model, color, year, miles, fuel_tank, max_weight, wheels, length, cargo):\n return Vehicle(**locals())\ndef Bus(typ, make, model, color, year, miles, fuel_tank, max_weight, wheels, length, seats):\n return Vehicle(**locals())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:34:48.220", "Id": "67580", "Score": "0", "body": "Your way of doing it in one class look intriguing but I wonder how do i create an instance of lets say sports car or bus? There is only one class for all cars." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:51:16.837", "Id": "67584", "Score": "0", "body": "@Vader Right, that question doesn't make sense for this implementation. My general assertion here is it's not of practical use to differentiate by type of vehicle. So first we'd have to figure out why you want to differentiate, and then we can consider a means to do so. (Perhaps something like checking `'gear_box' in vehicle.info`.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:16:15.423", "Id": "40200", "ParentId": "40190", "Score": "6" } }, { "body": "<p>A couple of things to consider</p>\n\n<p>1) As a style thing, I'd prefer **kwargs to *args in your constructors. This makes things clearer since there's no chance that a change to a base class initializer will invalidate other code in subclasses. Something like @MichaelUrman's example:</p>\n\n<pre><code>class Vehicle(object):\n \"\"\"Represent a vehicle.\"\"\"\n def __init__(self, **kwargs):\n self.info = kwargs\n</code></pre>\n\n<p>Allows you to flexibly specify values while providing class level defaults that vary on application. Super (as mentioned in other answers) is great for avoiding repetition here. For example</p>\n\n<pre><code>class FourByFour (Vehicle):\n def __init__(self, **kwargs):\n # provide a default transmissions\n if not 'transmission' in kwargs: kwarg['transmission'] = 'Generic 4x4'\n super (FourByFour, self).__init__(**kwargs)\n</code></pre>\n\n<p>In the comments to @MichaelUrman's example, OP asks how to create a specific class of car. A common python idiom (which is less common in other languages) is to create 'thin' subclasses that vary primarily by default content and then occasionally override default methods. This is common in cases where you want a lot of classes which are mostly the same but differ in details and you don't expect to manage lots of subtle hierarchical changes. From the 10,000 ft level this is the same using helper classes, since you're just populating a set of variables in a structured way; I prefer it to using helper functions because it allows you to add custom methods as necessary while keeping things data driven.</p>\n\n<p>For example:</p>\n\n<pre><code>class Vehicle(object): \n\"\"\"Represent a vehicle.\"\"\"\n DEFAULTS = {'wheels':4, 'doors':2, 'fuel':'gasoline', 'passengers':2}\n\n def __init__(self, **kwargs):\n kwargs.update(self.DEFAULTS)\n self.info = kwargs \n\n def drive(self):\n print \"Vroom\"\n\n\nclass Sedan(Vehicle):\n DEFAULTS = {'wheels':4, 'doors':4, 'fuel':'gasoline', 'passengers':5}\n\ndef Hybrid(Sedan):\n DEFAULTS = {'wheels':4, 'doors':4, 'fuel':'smug', 'passengers':4}\n\n def drive(self):\n print \"purrrrrr...\"\n\nclass Van(Vehicle):\n DEFAULTS = {'wheels':4, 'doors':3, 'fuel':'gasoline', 'passengers':2, 'cargo':[]}\n\n def unload(self):\n if not self.cargo:\n print \"no cargo loaded\"\n else:\n print \"unloading\"\n return self.cargo\n</code></pre>\n\n<p>Conceptually this is halfway between 'traditional' inheritance heavy OOP and @MichaelUrman's data customization approach. All three have their applications, and the neat thing about python is that it's very good at both @MichaelUrman's method and mine -- which is not true for languages obsessed with type-checking and signature maintenance.</p>\n\n<p>2) On the strategy level, in the long term you'll benefit from a finer grained approach. Engines, transmissions, and tires for example might be their own classes instead of aspects of vehicle (a station wagon and a sedan, for example, might share everything but body styles). The class hierarchy becomes less of an issue as you do more mix-and-match customization by creating collections of components. The usual pretentious programmer way to say this is '<a href=\"http://en.wikipedia.org/wiki/Composition_over_inheritance\">prefer composition over inheritance</a>'</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:29:04.967", "Id": "40214", "ParentId": "40190", "Score": "8" } } ]
{ "AcceptedAnswerId": "40214", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T18:45:25.220", "Id": "40190", "Score": "9", "Tags": [ "python", "object-oriented", "classes", "python-2.x" ], "Title": "Model cars as classes" }
40190
<p>I've developed a simple CSS transition solution for a slide out menu with a single toggle, and would love some feedback on if anything could be simplified or improved.</p> <p><strong>Markup</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Slide out menu&lt;/title&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;meta name="viewport" content="initial-scale=1"&gt; &lt;/head&gt; &lt;body class="menu menu-open"&gt; &lt;header&gt; &lt;a href="#" class="menu-toggle"&gt;Toggle&lt;/a&gt; &lt;/header&gt; &lt;nav class="menu-side"&gt; This is a side menu &lt;/nav&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; (function() { var body = $('body'); $('.menu-toggle').bind('click', function() { body.toggleClass('menu-open'); return false; }); })(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Styles</strong></p> <pre><code>body { padding-right:50px; } .menu { overflow-x:hidden; position:relative; left:0; } .menu-open { margin-left:241px; } .menu-open .menu-side { left:0; } .menu-side, .menu { -webkit-transition: all 0.2s ease-in; -moz-transition: all 0.2s ease-in; transition: all 0.2s ease-in; } .menu-side { position:fixed; left:-231px; top:0; width:210px; border-right:1px solid #000; height:100%; background-color:#333; color:#fff; padding:10px; } </code></pre>
[]
[ { "body": "<p><strong>HTML:</strong></p>\n\n<ul>\n<li><p>In addition to your existing viewport meta tag, I suggest adding the width value:<br></p>\n\n<pre><code>&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n</code></pre>\n\n<p>Also moving the tag before you load your stylesheets and the title code help your performance. <a href=\"https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag\">MDN on using the viewport meta tag.</a></p></li>\n<li><p>A <code>header</code> element typically contains headings and other introductory content. The Toggle-link should be part of your navigation as well, because that's what it is. <a href=\"http://html5doctor.com/the-header-element/\">HTML5 Doctor</a> is a great ressource, if you want to know more about this.</p></li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li>Generally one should avoid using <code>all</code> in transitions. Using the actual properties you're going to animate is more performant</li>\n</ul>\n\n<p>It would be a help to have a <a href=\"http://jsfiddle.net\">jsfiddle demo</a> of this to test around.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:48:30.943", "Id": "67748", "Score": "0", "body": "Thanks for the feedback.\n\nThe only thing I'd have to pick up on is that in my opinion the header could house the navigational toggle. w3c says \"a group of introductory or navigational aids\". Is the toggle not a navigational aid? HTML5 Doctor also mentions that \"a recent change to the spec you can now include the <nav> element within the <header>\", so do you think the navigation could just sit within the header all together?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:51:33.253", "Id": "67751", "Score": "0", "body": "@AlexGarrett Yes, it is. But it's a part of your actual navigation and shouldn't be seperated from it. You can move the whole navigation to the header, but the toggle alone there is misplaced. That's what I've meant. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:01:54.853", "Id": "67757", "Score": "0", "body": "Sorry, misunderstood you. Makes a lot of sense now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:36:27.787", "Id": "40203", "ParentId": "40201", "Score": "5" } } ]
{ "AcceptedAnswerId": "40203", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:24:19.410", "Id": "40201", "Score": "6", "Tags": [ "html", "css" ], "Title": "Slide out CSS menu" }
40201
<p>I wrote a CppUnit test suite to unit-test the code that I posted <a href="https://codereview.stackexchange.com/questions/39887/lua-c-api-how-can-i-improve-this-runtime-expression-autocompletion">here</a> which is a single routine that proposes how a Lua expression could be auto-completed.</p> <p>What do you think? I appreciate all the comments.</p> <pre><code>#include &lt;boost/format.hpp&gt; #include &lt;cppunit/extensions/HelperMacros.h&gt; class Tests : public CppUnit::TestFixture { private: lua_State* L; protected: void execute (const std::string&amp; script) { luaL_dostring(L, script.c_str()); } void assertSize (const std::vector&lt;std::string&gt;&amp; candidates, size_t size) { CPPUNIT_ASSERT_EQUAL_MESSAGE( boost::str(boost::format("The candidate list size is %d, but should be %d.") % candidates.size() % size), size, candidates.size() ); } void assertContains (const std::vector&lt;std::string&gt;&amp; candidates, const std::string&amp; value) { CPPUNIT_ASSERT_MESSAGE( boost::str(boost::format("Candidate list doesn't contain '%s'.") % value), std::find(candidates.begin(), candidates.end(), value) != candidates.end() ); } public: void setUp() { L = luaL_newstate(); luaL_openlibs(L); } void tearDown() { CPPUNIT_ASSERT_EQUAL_MESSAGE("The stack is not empty.", 0, lua_gettop(L)); lua_close(L); } void globalNamesAreAutocompleted() { execute("resources = { textures = { 'texture1', 'texture2', 'texture3' } }"); execute("resolution = { sizeX = 2560, sizeY = 1440 }"); auto candidates = buildAutoCompleteCandidates(L, "reso"); assertSize(candidates, 2); assertContains(candidates, "resources"); assertContains(candidates, "resolution"); } void valuesWithinTablesAreAutocompleted() { execute("europe = { countries = { France = { cities = { Paris = { LeMarais = {}, LesHalls = {}, Montparnasse = {}, Montmartre = {} }}}}}"); auto candidates = buildAutoCompleteCandidates(L, "europe.countries['France'].cities['Paris'].Mont"); assertSize(candidates, 2); assertContains(candidates, "europe.countries['France'].cities['Paris'].Montparnasse"); assertContains(candidates, "europe.countries['France'].cities['Paris'].Montmartre"); } void metatableIndexTableIsFollowed() { execute("metaValues = { metaValue = 'AAA' }"); execute("values = setmetatable({ value = 'aaa' }, { __index = metaValues })"); auto candidates = buildAutoCompleteCandidates(L, "values."); assertSize(candidates, 2); assertContains(candidates, "values.metaValue"); assertContains(candidates, "values.value"); } void metatableIndexTableChainIsFollowed() { execute("metaValues1 = { valueA = 'alpha' }"); execute("metaValues2 = { valueB = 'beta' }"); execute("metaValues3 = { valueC = 'kappa' }"); execute("setmetatable(metaValues3, { __index = metaValues2 })"); execute("setmetatable(metaValues2, { __index = metaValues1 })"); execute("values = { value = 'theta' }"); execute("setmetatable(values, { __index = metaValues3 })"); auto candidates = buildAutoCompleteCandidates(L, "values."); assertSize(candidates, 4); assertContains(candidates, "values.value"); assertContains(candidates, "values.valueA"); assertContains(candidates, "values.valueB"); assertContains(candidates, "values.valueC"); } void metatableLoopBreaks() { execute("loopTable1 = { valueA = 'alpha' }"); execute("loopTable2 = { valueB = 'beta' }"); execute("loopTable3 = { valueC = 'kappa' }"); execute("setmetatable(loopTable1, { __index = loopTable2 })"); execute("setmetatable(loopTable2, { __index = loopTable3 })"); execute("setmetatable(loopTable3, { __index = loopTable1 })"); auto candidates = buildAutoCompleteCandidates(L, "loopTable1."); assertSize(candidates, 3); assertContains(candidates, "loopTable1.valueA"); assertContains(candidates, "loopTable1.valueB"); assertContains(candidates, "loopTable1.valueC"); } void blankExpressionAutocompletsWithAllGlobals() { execute("star = 'Alpha Centauri'"); execute("spaceship = 'Millenium Falcon'"); execute("planets = 'Tarsonis'"); auto candidates = buildAutoCompleteCandidates(L, ""); CPPUNIT_ASSERT(candidates.size() &gt; 25); assertContains(candidates, "star"); assertContains(candidates, "spaceship"); assertContains(candidates, "planets"); assertContains(candidates, "io"); assertContains(candidates, "table"); assertContains(candidates, "print"); } void colonReturnsFunctionValues() { execute("calculator = { sin = math.sin, cos = math.cos, pi = 3.14, e = 2.7182 }"); auto candidates = buildAutoCompleteCandidates(L, "calculator:"); assertSize(candidates, 2); assertContains(candidates, "calculator:sin"); assertContains(candidates, "calculator:cos"); } static CppUnit::Test* suite() { CppUnit::TestSuite* suite = new CppUnit::TestSuite("AutocompleteSuite"); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Global names are autocompleted", &amp;Tests::globalNamesAreAutocompleted)); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Values within tables are autocompleted", &amp;Tests::valuesWithinTablesAreAutocompleted)); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Metatable index table is followed", &amp;Tests::metatableIndexTableIsFollowed)); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Metatable index table chain is followed", &amp;Tests::metatableIndexTableChainIsFollowed)); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Metatable loop breaks", &amp;Tests::metatableLoopBreaks)); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Blank expression autocompletes with all globals", &amp;Tests::blankExpressionAutocompletsWithAllGlobals)); suite-&gt;addTest(new CppUnit::TestCaller&lt;Tests&gt;("Colon returns function values", &amp;Tests::colonReturnsFunctionValues)); return suite; } }; </code></pre>
[]
[ { "body": "<h2>Coverage</h2>\n\n<p>Your tests don't cover</p>\n\n<ul>\n<li><p>the case where there is no completion because the last separator is called on an entry that is not a table</p></li>\n<li><p>the case where <code>__index</code> is not a table</p></li>\n</ul>\n\n<p>This hints at a general problem: It seems that you are doing sunny day tests only.</p>\n\n<h2>Non selfcontained source</h2>\n\n<p>It seems you did not post the whole code because this does not work as is. (Even after \"including\" the code from the other question.) This opens the door for problems that occur because the answerers did not create the same environment as you have there.</p>\n\n<h2>Missing includes</h2>\n\n<p>Your test code does not include </p>\n\n<ul>\n<li>the necessary lua libraries for functions (or macros) like <code>luaL_dostring</code>.</li>\n<li>the test runner needed for actually running the test (I used <code>cppunit/ui/text/TestRunner.h</code>)</li>\n</ul>\n\n<h2>Naming</h2>\n\n<ul>\n<li><code>L</code> (looks like a macro, too generic (although probably idiomatic in Lua context))-> <code>luaState</code></li>\n<li><code>script</code> -> <code>expression</code> (at least you did never pass a script but only expression to <code>execute</code>)</li>\n<li><code>blankExpressionAutocompletsWithAllGlobals</code> (typo) -> <code>blankExpressionAutocompletesWithAllGlobals</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-30T12:52:41.480", "Id": "61552", "ParentId": "40202", "Score": "7" } } ]
{ "AcceptedAnswerId": "61552", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:26:07.040", "Id": "40202", "Score": "7", "Tags": [ "c++", "c++11", "unit-testing" ], "Title": "CppUnit test suite for testing a routine" }
40202
<p>I feel like using this many partial views where a view renders a partial that renders a partial is just digging a hole of poor design, so I'm looking for any suggestions or guidance as to if this is best/worst practice. One of the reasons I don't like it is because it seems too easy to duplicate code across the different views to handle styling. Here they are in order of nesting.</p> <p><strong>The index view:</strong></p> <pre><code>@model IEnumerable&lt;RESTDemo.Models.StockQuote&gt; @{ ViewBag.Title = "Index"; } &lt;h2&gt;Demo Stock Watch List&lt;/h2&gt; &lt;fieldset&gt; &lt;legend&gt;StockQuote&lt;/legend&gt; &lt;div id="controls"&gt; &lt;input type="submit" name="Refresh" id="Refresh" value="Refresh" data-submit-action="refresh" data-submit-method="get" data-submit-url="@Url.Action("Refresh")" data-stock-target="#stockTable" /&gt; &lt;input type="submit" name="Reset" id="Reset" value="Clear List" data-submit-action="reset" data-submit-method="delete" data-submit-url="@Url.Action("Reset")" data-stock-target="#stockList" /&gt; &lt;form id="addStock" method="post" action="@Url.Action("Add")" data-add-ajax="true" data-stock-target="#stockTable"&gt; &lt;input type="search" name="symbol" /&gt; &lt;input type="submit" value="Add" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;/fieldset&gt; @Html.Partial("_stocks", Model) </code></pre> <p><strong>The _stocks view:</strong> </p> <pre><code>@model IEnumerable&lt;RESTDemo.Models.StockQuote&gt; &lt;div id="stockList"&gt; &lt;table id="stockTable"&gt; &lt;tr&gt; &lt;td&gt;Symbol&lt;/td&gt; &lt;td&gt;Last Price&lt;/td&gt; &lt;td class="change"&gt;Change&lt;/td&gt; &lt;td class="change"&gt;Change Percent&lt;/td&gt; &lt;td&gt;Volume&lt;/td&gt; &lt;td class="last-column"&gt;&lt;/td&gt; &lt;/tr&gt; @Html.Partial("stockList", Model) &lt;/table&gt; &lt;/div&gt; </code></pre> <p><strong>The stockList view:</strong></p> <pre><code>@model IEnumerable&lt;RESTDemo.Models.StockQuote&gt; @foreach (var item in Model) { string cssClass; if (item.Change &gt; 0) { cssClass = "num-pos"; } else if (item.Change &lt; 0) { cssClass = "num-neg"; } else { cssClass = "num-zero"; } &lt;tr class="data-row"&gt; &lt;td class="stock-symbol"&gt;@item.Symbol&lt;/td&gt; &lt;td&gt;@item.LastPrice&lt;/td&gt; &lt;td class="@cssClass"&gt;@Html.DisplayFor(modelItem =&gt; item.Change)&lt;/td&gt; &lt;td class="@cssClass"&gt;@Html.DisplayFor(modelItem =&gt; item.ChangePercent)&lt;/td&gt; &lt;td&gt;@item.Volume&lt;/td&gt; &lt;td class="last-column"&gt; &lt;span class="delete-me" data-action="@Url.Action("Remove")" data-stock-method="delete"&gt; &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; } </code></pre> <p>And finally the stock partial which is used as the response to an Ajax call to insert a single row into the table:</p> <pre><code>@model RESTDemo.Models.StockQuote @{ string cssClass; if (Model.Change &gt; 0) { cssClass = "num-pos"; } else if (Model.Change &lt; 0) { cssClass = "num-neg"; } else { cssClass = "num-zero"; } } &lt;tr class="data-row"&gt; &lt;td class="stock-symbol"&gt;@Model.Symbol&lt;/td&gt; &lt;td&gt;@Model.LastPrice&lt;/td&gt; &lt;td class="@cssClass"&gt;@Html.DisplayFor(modelItem =&gt; Model.Change)&lt;/td&gt; &lt;td class="@cssClass"&gt;@Html.DisplayFor(modelItem =&gt; Model.ChangePercent)&lt;/td&gt; &lt;td&gt;@Model.Volume&lt;/td&gt; &lt;td class="last-column"&gt; &lt;span class="delete-me" data-action="@Url.Action("Remove")" data-stock-method="delete"&gt; &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre>
[]
[ { "body": "<p>First of all, I don't see anything you have done here as bad practice or poor design, that being said, I would probably not opt to nest as deeply. In my thinking, breaking up the the view into sub views should be done for 2 possible reasons.</p>\n\n<ul>\n<li>Organization</li>\n<li>Reusibility</li>\n</ul>\n\n<p>I am assuming that you don't intend to reuse these views elsewhere in the application, if that is the case, you are only gaining organization. When that is the case, I would probably not put the list body into a separate view, but only the list elements. In other words, break into a subview only when your bound context changes, IE, you are binding to a item instead of the collection. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:04:17.227", "Id": "67607", "Score": "0", "body": "Thanks for the suggestions, it definitely makes sense to consider what the model is bound to. I am doing this more for learning, so this is a very limited scope application. I think I initially split the list body off so an Ajax call to refresh the data wouldn't have to write the whole table, just the contents, but it really isn't that much data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:53:29.650", "Id": "40215", "ParentId": "40204", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:47:38.363", "Id": "40204", "Score": "8", "Tags": [ "c#", "html", "asp.net-mvc-4" ], "Title": "Stock list view" }
40204
<p>Here is an attempt to code a specific kind of Singleton - the one geared for our configuration needs. It needs to be initialized with a configuration location, do not allow copies or other instances, and provide feedback or fail in case of problems. Prefer graceful feedback from violated workflows. While not performance-critical (especially initialization), the correct behavior and thread safety are needed.</p> <p>Configuration location differs in production/testing/development scenarios - or may be acquired via a network broadcast in the future. Getting location is outside of this class scope.</p> <p>So, here is the <code>Config.h</code> header:</p> <pre><code>class Config { public: typedef std::function&lt;void(std::string)&gt; DupInitCB; static void init(std::string loc, DupInitCB err_cb); static Config&amp; instance(); private: static std::unique_ptr&lt;Config&gt; cfg; static std::mutex init_mutex; std::string url; Config(std::string loc); Config(const Config&amp; src); // not implemented Config&amp; operator=(const Config&amp; right); // not implemented public: std::string val(std::string key); }; </code></pre> <p>The implementation <code>Config.cpp</code>:</p> <pre><code>#include "Config.h" std::unique_ptr&lt;Config&gt; Config::cfg; std::mutex Config::init_mutex; void Config::init(std::string loc, DupInitCB err_cb) { std::lock_guard&lt;std::mutex&gt; lock(init_mutex); if (cfg != nullptr) { err_cb(loc); } else { cfg.reset(new Config(loc)); }; }; Config&amp; Config::instance() { if (cfg == nullptr) throw std::logic_error("Requested uninitialized Config"); return *cfg.get(); } Config::Config(std::string loc) : url(loc) {}; std::string Config::val(std::string key) { return key + " key requested at the location " + url; } </code></pre> <p>Finally, a usage example:</p> <pre><code>#include "Config.h" int _tmain(int argc, _TCHAR* argv[]) { try { std::cout &lt;&lt; Config::instance().val("Upstream") &lt;&lt; std::endl; std::cerr &lt;&lt; "Did not trow an exception when called an uninitialized Config." &lt;&lt; std::endl; return 1; } catch (std::logic_error e) { std::cout &lt;&lt; "Properly thrown an error when called an uninitialized Config." &lt;&lt; std::endl; } catch (...) { std::cerr &lt;&lt; "Thrown an unexpected exception when called an uninitialized Config." &lt;&lt; std::endl; return 1; } Config::init( "http://cnf.local/dev", [](std::string loc){ std::cout &lt;&lt; "Duplicate Config init (" &lt;&lt; loc &lt;&lt; ")" &lt;&lt; std::endl; } ); Config::init( "http://cnf.local/prod", [](std::string loc){ std::cout &lt;&lt; "Duplicate Config init (" &lt;&lt; loc &lt;&lt; ")" &lt;&lt; std::endl; } ); std::cout &lt;&lt; Config::instance().val("Upstream") &lt;&lt; std::endl; return 0; } </code></pre> <p>A buildable VC++ 2012 solution is posted at <a href="https://github.com/didenko/parametrized_config_singleton" rel="nofollow">the GitHub repo</a>.</p> <p>The specific questions I have are:</p> <ol> <li>Does the <code>instance()</code> method need to be synchronized?</li> <li>Is there a better way to handle violated workflow from the <code>instance()</code> method than throwing an exception?</li> <li>What are the dangers of call-back from under the lock?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:07:03.913", "Id": "67761", "Score": "0", "body": "Doesn't relate to your questions, so I'll post it as a comment: `static std::unique_ptr<Config> cfg` should be a static member of `Config::init` to avoid issues with the initialization order of class static variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:17:57.957", "Id": "67787", "Score": "0", "body": "@Massimiliano, I thought initialization order is a problem when one has dependencies between static members and they are in different compilation units. Am I missing something? I am not sure in what sense it can be a member of `Config::init()` and be accessible by the `Config::instance()` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T19:24:15.060", "Id": "67818", "Score": "1", "body": "You didn't miss anything :-) I just wanted to point out (in case it was of interest) that you can't call safely `Config::init()` or `Config::instance()` in code that initializes non-local variables. With a [few modifications](http://coliru.stacked-crooked.com/a/457b7d73832206df) you may remove this restriction. Of course the solution is not without drawbacks, as the helper function now merges two responsibilities." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T20:59:44.953", "Id": "67836", "Score": "0", "body": "Makes sense. Not my case but good to know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T21:30:54.957", "Id": "67839", "Score": "0", "body": "@Massimiliano If cfg were static inside Config::init then when would its constructor be called: would its constructor be called as soon as Config::init is called? If you define cfg inside Config::init **after** the lock_guard statement, then would cfg's constructor be delayed until after the lock is acquired?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T08:08:40.240", "Id": "67911", "Score": "0", "body": "@ChrisW First question: if I don't misinterpret the standard (6.7.4) it depends on the initialization being static or dynamic. In both cases you should be granted that the variable will be correctly initialized after the first time control passes through its declaration. Second question: I assume it may be delayed, but is not always required to be delayed. Anyhow I don't understand what are the points you are trying to make here: could you be more explicit? (disclaimer: I am not being sarcastic)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T09:50:20.353", "Id": "67919", "Score": "0", "body": "@Massimiliano \"... after the first time control passes through its declaration\" sounds OK: provided that it's declared inside the scope of the lock_guard. My fear was that the compiler-emitted code which decides whether or not it has already been constructed (or, needs to be constructed for the first time) isn't thread-safe. If it's defined outside the lock_guard then it may be constructed twice: one thread starts to construct it; another thread starts to construct it; the first thread finishes construction and enters the lock guard, while the other thread is still reconstructing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T22:34:11.860", "Id": "68009", "Score": "0", "body": "This is how to create a singelton in C++: http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289" } ]
[ { "body": "<blockquote>\n <p>Does the instance() method need to be synchronized?</p>\n</blockquote>\n\n<p>Theoretically, yes: because unique_ptr isn't thread-safe: therefore you should not call get while another thread is calling reset.</p>\n\n<p>It may be safe in practice.</p>\n\n<p>Alternatively you don't need all the functionality of a unique_ptr.\nInstead you could implement its functionality using a dumb pointer, which you can reason about and/or access using the STL <code>atomic</code> functions.</p>\n\n<blockquote>\n <p>Is there a better way to handle violated workflow from the instance() method than throwing an exception?</p>\n</blockquote>\n\n<p>You could return a pointer instead of a reference, and return a null pointer instead of throwing an exception: and expect the caller to check for null before dereferencing the pointer.</p>\n\n<p>Another possibility may be the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow\">Null Object pattern</a>: if there's no Config instance then return a reference to an empty Config instance, or a Config instance initialized with suitable default values.</p>\n\n<blockquote>\n <p>What are the dangers of call-back from under the lock?</p>\n</blockquote>\n\n<p>In general the danger of callback from under a lock is 'deadly embrace' a.k.a. 'deadlock'; for example:</p>\n\n<pre><code>Thread 1:\n\n// get the lock\nlock_guard&lt;mutex&gt; lock(foo_mutex);\n// get the config\nconfig.init(\"foo\", [](string loc){ cout &lt;&lt; \"I don't care\"; });\n\nThread 2:\n\nconfig.init(\"foo\", [](string loc){\n lock_guard&lt;mutex&gt; lock(foo_mutex);\n cout &lt;&lt; \"I don't care\";\n});\n</code></pre>\n\n<p>Imagine the following sequence:</p>\n\n<ul>\n<li>Thread 2 enters config and acquires config's lock</li>\n<li>Thread 1 acquires the the foo_mutex</li>\n<li>Thread 1 blocks on the config mutex (owned by thread 2)</li>\n<li>Thread 2 enters the callback</li>\n<li>Thread 2 callback blocks on the foo_mutex (owned by thread 1)</li>\n</ul>\n\n<p>It's safe to acquire multiple locks if you always acquire them in the same sequence.\nWith a callback it's difficult for the author of the Config class to predict what locks might be held before and/or during the callback.\nThis is a hidden problem for low-level library classes: for example if Logger uses Config in its implementation, Logger and Config each have their own mutex, and a callback from Config tries to invoke a Logger method.</p>\n\n<hr>\n\n<p>Another problem with callback from under a lock is that you don't know how long the callback is going to take. If the callback takes a long time to execute, then the lock will be held for a long time.</p>\n\n<hr>\n\n<blockquote>\n <p>OK, so callback is now gone.</p>\n</blockquote>\n\n<p>Perhaps you can keep the callback provided you unlock before calling it:</p>\n\n<pre><code>void Config::init(std::string loc, DupInitCB err_cb) {\n bool succeeded;\n\n { // scope of lock_guard\n std::lock_guard&lt;std::mutex&gt; lock(init_mutex);\n if (cfg != nullptr) {\n succeeded = false;\n } else {\n cfg.reset(new Config(loc));\n succeeded = true;\n };\n } // lock_guard is released here\n\n // error callback after releasing the lock`enter code here`\n if (!succeeded)\n err_cb(loc);\n};\n</code></pre>\n\n<p>Or the code within the artificial <code>{ ... }</code> scope above could be a private method which returns bool, called from init, and named something like locked_init.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:48:44.710", "Id": "67749", "Score": "0", "body": "OK, so callback is now gone. I did two versions - with all flow errors as exceptions and as return values. I like the return values version more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T15:57:02.287", "Id": "67753", "Score": "0", "body": "I edited the answer to show how to keep the callback if you want it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:01:24.210", "Id": "67756", "Score": "0", "body": "Makes sense, good pattern - will note. Generally I use callbacks if a \"detour\" of logic is needed. In this case it only complicates things as control returns to the caller anyway very directly. The new code looks much simpler too. Why did I go with the callback I do not understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T16:03:46.610", "Id": "67758", "Score": "0", "body": "@VladDidenko Your using shared_ptr looks like an improvement over unique_ptr." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-10T05:51:59.170", "Id": "190592", "Score": "0", "body": "The shared pointer version is at the https://github.com/didenko/parametrized_config_singleton/tree/fb46de commit. Now Config::init() returns bool for consumer to inspect. Instance is now stored privately in a shared pointer, which makes the Config::instance() a very simply accessor - and the consumer can inspect if it is still nullptr or not." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:07:06.833", "Id": "40218", "ParentId": "40205", "Score": "4" } } ]
{ "AcceptedAnswerId": "40218", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T20:58:38.820", "Id": "40205", "Score": "6", "Tags": [ "c++", "c++11", "singleton" ], "Title": "A parametrized Config singleton" }
40205
<p>This function converts a list to an array when list has quotes and embedded comma:</p> <pre><code>array function convertRow(required string lstRow) { var arResult = []; var arTemp = ListToArray(arguments.lstRow, ',', true); var quoteMode = false; var startQuote = false; for (var i in arTemp) { if (i CONTAINS '"' &amp;&amp; not quoteMode) { startQuote = true; } if (startQuote) { ArrayAppend(arResult, replace(i, '"', '')); startQuote = false; quoteMode = true; } else if (quoteMode) { arResult[ArrayLen(arResult)] &amp;= "," &amp; replace(i, '"', ''); if (i CONTAINS '"') quoteMode = false; } else ArrayAppend(arResult, i); } writedump(lstRow); writedump(arResult); return arResult; } </code></pre>
[]
[ { "body": "<p>I could get rid of your startQuote variable, I reduced the number of <code>i CONTAINS '\"'</code> comparasions by 1.</p>\n\n<pre><code>array function convertRow(required string lstRow) {\n var arResult = [];\n var arTemp = ListToArray(arguments.lstRow, ',', true);\n var quoteMode = false;\n\n for (var i in arTemp) {\n var containsQuote = i CONTAINS '\"';\n if (containsQuote &amp;&amp; not quoteMode) {\n ArrayAppend(arResult, replace(i, '\"', ''));\n quoteMode = true;\n }\n else if (quoteMode){\n arResult[ArrayLen(arResult)] &amp;= \",\" &amp; replace(i, '\"', '');\n quoteMode = not containsQuote;\n }\n else{\n ArrayAppend(arResult, i);\n }\n }\n\n\n writedump(lstRow);\n writedump(arResult);\n\n return arResult;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:02:42.810", "Id": "40216", "ParentId": "40209", "Score": "2" } } ]
{ "AcceptedAnswerId": "40216", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T21:58:31.247", "Id": "40209", "Score": "1", "Tags": [ "javascript", "array", "coldfusion" ], "Title": "Converting a list to an array when list has quotes and embedded comma" }
40209
<p>Here is the original C++ class I converted to Lisp at the very bottom of this post.</p> <pre><code>class TrainingData { public: TrainingData(const string filename); bool isEof(void) { return m_trainingDataFile.eof(); } void getTopology(vector&lt;unsigned&gt; &amp;topology); // Returns the number of input values read from the file: unsigned getNextInputs(vector&lt;double&gt; &amp;inputVals); unsigned getTargetOutputs(vector&lt;double&gt; &amp;targetOutputVals); private: ifstream m_trainingDataFile; }; </code></pre> <p>It is a class from a C++ Neural Network I am converting to Common Lisp. The entire 400 line Neural Net is <a href="http://inkdrop.net/dave/docs/neural-net-tutorial.cpp" rel="nofollow">here</a>.</p> <p>Below is the conversion I came up with. Based on the Neural Network I linked above, can anyone tell me if I converted the C+ class, above, correctly with the following Lisp code? I'd rather have a little assurance before I start converting the entire 400 lines.</p> <pre><code>(defclass training-data () ((training-data-stream :reader training-data-stream :writer |set training data stream (using a funky name)| :initarg :training-data-stream)) ) ;;; initialize-instance :after -- This is your 'constructor' code. (defmethod initialize-instance :after ((td training-data) &amp;key training-data-stream &amp;allow-other-keys) ;; Initialize the slot. ;; Note that 'opening' a stream, as it is implied by the C++ class ;; definiton and leaking the open stream handle is very impolite. (let ((is (etypecase training-data-stream ((string pathname) (open training-data-stream :direction :input)) (stream (if (input-stream-p training-data-stream) training-data-stream (error "Not an input stream."))))) ) (|set training data stream (using a funky name)| is td) )) (defgeneric is-eof (td) (:method ((td training-data)) ;; Are you sure you want this method? )) </code></pre> <p><strong>EDIT:</strong> As far as tests go, please let me explain:</p> <p>Due to the fact I'm just a intermediate at Linear Algebra I had a wee bit of a time understanding Neural Networks. This conversion into Lisp is the way I figured out how to figure out what Neural Networks do. I'm best at Lisp, pretty good at C, and sort of good at C++, so I'm trying to learn Neural Networks by converting a C++ nn to Lisp.</p> <p>I don't have enough info to test any specific piece of the code I posted here or at the link yet. I'm still in the process of learning <code>std::stringstream</code> and I've just learned what bitwise XOR was. I can post the instructions that tell how to run the C++ nn at the link in its entirety, and the code to create the data file for it, so you can see how it runs or explain how the incomplete snippet I posted ties in with the rest of the code. The incomplete member functions I added in this post have completed counterparts within the rest of the code at the link I just added.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:15:17.393", "Id": "67640", "Score": "0", "body": "The link to the Neural Network code seems to be missing - can you please edit your question to have it please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:17:52.730", "Id": "67641", "Score": "0", "body": "Perhaps you can edit your question to be a bit more focused. It will be hard for someone to understand 400+ lines of C++ code to help you determine if your Lisp implementation is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:18:59.593", "Id": "67642", "Score": "0", "body": "And a further comment/question: do you have any tests for this code? If you ported those *first* then you would be greatly assisted to make sure your implementation is at least ok." } ]
[ { "body": "<h2>Code review - mostly style</h2>\n\n<p>You did a litteral translation from C++ to CL that seems good. I have some stylistic issues with it:</p>\n\n<pre><code>(defclass training-data ()\n ((training-data-stream :reader training-data-stream\n :writer |set training data stream (using a funky name)|\n :initarg :training-data-stream)))\n</code></pre>\n\n<ol>\n<li><p>I guess <code>|set training data stream (using a funky name)|</code> is an attempt at obfuscating the writer method, so that you can have a kind of \"private\" setter. Don't do that.</p>\n\n<ol>\n<li><code>:writer</code> is optional: if you don't specify it, you won't generate a specific setter for your slot. You can always use <code>slot-value</code> to alter a slot. <em>However, I don't recommend this appropach</em>.</li>\n<li><p>You can define a <code>:accessor</code> method, which acts as both a reader and a writer method (resp. <code>(my-accessor instance)</code> and <code>(setf (my-accessor instance) value)</code>). Since your C++ field is <code>private</code> and has no public getter/setter, this is an appropriate approach:</p>\n\n<ul>\n<li>Define only an accessor, say <code>training-data-stream</code>, and </li>\n<li>Do <strong>not</strong> export the <code>training-data-stream</code> symbol from your package.\nVisibility is handled at package level in CL.</li>\n</ul></li>\n</ol></li>\n<li><p>Your <code>initarg</code> could be made shorter: it is used when making an instance of a <code>training-data</code> class, so <code>:training-data-stream</code> is redundant, just use <code>:input-stream</code> (<code>:stream</code> would be too vague).</p></li>\n</ol>\n\n<p>Then...</p>\n\n<pre><code>;;; initialize-instance :after -- This is your 'constructor' code.\n\n(defmethod initialize-instance :after ((td training-data)\n &amp;key\n training-data-stream\n &amp;allow-other-keys)\n ;; Initialize the slot.\n</code></pre>\n\n<p>So far, so good; just rename <code>training-data-stream</code> as <code>input-stream</code>.</p>\n\n<pre><code> ;; Note that 'opening' a stream, as it is implied by the C++ class\n ;; definiton and leaking the open stream handle is very impolite.\n</code></pre>\n\n<p>Your own comment highlights that </p>\n\n<ul>\n<li>the original C++ class might not be good at following C++ best practices (RAII, for example), and</li>\n<li>you are doing a verbatim clone of the C++ class instead of having a more idiomatic CL approach. Since you are just copying an existing codebase in order to understand it, it is not so bad. Maybe you could try to refactor it later, as an exercise.</li>\n</ul>\n\n<p>Besides, \"impolite\" is not the word I would have used, because it is not accurate (it sounds as-if you ignore, or side-step, the real problems behind leaking resources).</p>\n\n<p>Hereafter, your <code>let</code> binding is useless:</p>\n\n<pre><code> (let ((is (etypecase training-data-stream\n ((string pathname) (open training-data-stream :direction :input))\n (stream (if (input-stream-p training-data-stream)\n training-data-stream\n (error \"Not an input stream.\")))))\n )\n (|set training data stream (using a funky name)| is td)\n ))\n</code></pre>\n\n<p>In other word, <code>(let ((x (something))) (use x))</code> could simply be <code>(use (something))</code>.\nMoreover, you changed the original behavior by allowing the constructor to be initialized with streams, and not only strings (was it necessary?).</p>\n\n<p>Note that instead of <code>etypecase</code>, which is good, you could also let <code>initialize-instance</code> call a new generic method, say <code>initialize</code>, that dispatches on the type of the stream, either <code>string</code> or <code>stream</code> (we can't dispatch on <code>&amp;key</code> arguments, otherwise <code>initialize-instance</code> would suffice).</p>\n\n<pre><code> (setf (training-data-stream td)\n (etypecase input-stream\n ((string pathname) (open input-stream :direction :input))\n (stream (if (input-stream-p training-data-stream)\n training-data-stream\n (error \"Not an input stream.\"))))))\n</code></pre>\n\n<h2>Your objective</h2>\n\n<blockquote>\n <p>I'm trying to learn Neural Networks by converting a C++ nn to Lisp</p>\n</blockquote>\n\n<p>Learning high-level concepts like neural networks using an implementation like the one you linked is not very effective, in my opinion.</p>\n\n<p>Even though you have difficulties with C++, this is not the language that prevents you from understanding neural networks; for example:</p>\n\n<pre><code> Layer &amp;outputLayer = m_layers.back();\n m_error = 0.0;\n\n for (unsigned n = 0; n &lt; outputLayer.size() - 1; ++n) {\n double delta = targetVals[n] - outputLayer[n].getOutputVal();\n m_error += delta * delta;\n }\n m_error /= outputLayer.size() - 1; // get average error squared\n m_error = sqrt(m_error); // RMS\n</code></pre>\n\n<p>Those are just math operations, and the fact that they are written in C++ is not what makes them difficult to grasp. In fact, I never really studied neural networks and all the above code is cryptic, even though I am familiar with the language.</p>\n\n<p>I doubt that rewriting it in CL will help you.</p>\n\n<p>What you need first is a book and tutorials for high-level concepts.\nExperiment with a easy-to-use library, like for example <a href=\"http://pybrain.org/docs/\" rel=\"nofollow\">PyBrain</a>, which has a good documentation.</p>\n\n<p>Maybe when you have a good understanding of neural networks, you can go back to the linked code and inspect the implementation to see how it was designed, and why.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-15T13:39:32.050", "Id": "47238", "ParentId": "40212", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T22:21:36.190", "Id": "40212", "Score": "5", "Tags": [ "c++", "classes", "common-lisp" ], "Title": "Did I convert this C++ class to Common Lisp correctly?" }
40212
<p>I am kind of new to object orientation in PHP and I need some experts feedback.</p> <p>This class fetches the weather from <a href="http://api.met.no/weatherapi/locationforecast/1.8/?lat=59.32893000000001;lon=18.06491" rel="nofollow">this URL</a>.</p> <p>It grabs the weather, temperature and an icon from the current hour.</p> <ol> <li>Is this proper OOP?</li> <li>Or what can I do to improve this class?</li> <li>Do I need to make it more abstract?</li> <li>What can I do to make the _parse_weather_xml method less ugly?</li> </ol> <p>Concrete examples are very much appreciated!</p> <pre><code>&lt;?php /** * Weather class */ class Weather { private $_weather; private $_temperature; private $_symbol_url; public function __construct($latitude, $longitude) { $this-&gt;_check_weather($latitude, $longitude); } private function _check_weather($latitude, $longitude) { $weather_xml = $this-&gt;_get_weather_xml($latitude, $longitude); $weather_xml = $this-&gt;_parse_weather_xml($weather_xml); } public function get_weather($property) { return $this-&gt;$property; } public function __get($property) { if(!property_exists($this, $property)){ echo "The property {$property} doesn't exist."; } } private function _get_weather_xml($_latitude, $_longitude) { $weather_xml = simplexml_load_file("http://api.met.no/weatherapi/locationforecast/1.8/?lat={$_latitude};lon={$_longitude}"); return $weather_xml; } private function _parse_weather_xml($weather_xml) { define('TZ_OFFSET', 60*60*1); $now = time(); $current_hour = $now - ($now % (60*60)); $current_weather = array(); foreach ($weather_xml-&gt;product-&gt;time as $time){ $from_hour = strtotime($time['from']) - TZ_OFFSET; $from_hour = $from_hour - ($from_hour % (60*60)); if($time['datatype'] == "forecast"){ if($from_hour == $current_hour){ if($time-&gt;location-&gt;symbol){ if(!isset($current_weather['symbol'])){ $current_weather['symbol'] = $time-&gt;location-&gt;symbol; } } else { if(!isset($current_weather['temperature'])){ $current_weather['temperature'] = $time-&gt;location-&gt;temperature['value']; } } } } } $this-&gt;_weather = $current_weather['symbol']['id']; $this-&gt;_temperature = $current_weather['temperature']; $this-&gt;_symbol_url = "http://api.met.no/weatherapi/weathericon/1.0/?symbol=".$current_weather['symbol']['number'].";content_type=image/png"; } } // Instantiate Weather object, parameters: latitude, longitude $weather = new Weather(59.32893000000001, 18.06491); echo $weather-&gt;get_weather("_weather")."&lt;br /&gt;"; echo $weather-&gt;get_weather("_temperature")."&lt;br /&gt;"; echo "&lt;img src=".$weather-&gt;get_weather("_symbol_url")." /&gt;"; ?&gt; </code></pre>
[]
[ { "body": "<p>The bulk of your code looks fine, I have made what are (In my opinion) a few usability enhancements, but take it or leave it as you see fit.</p>\n\n<p>I don't think you can really make the xml processing any less ugly.</p>\n\n<p>Comments are inline</p>\n\n<pre><code>&lt;?php\n\n/**\n * Weather class\n */\n\nclass Weather\n{\n // lets define our constants here, so if it ever change we don't have to scan the code to find it\n const TZ_OFFSET_SECONDS = 3600;\n const URL_API = \"http://api.met.no/weatherapi/locationforecast/1.8/\";\n const URL_IMG = \"http://api.met.no/weatherapi/weathericon/1.0/\";\n\n\n private $_current_weather = null;\n// private $_temperature;\n// private $_symbol_url;\n private $_latitude;\n private $_longitude;\n\n\n public function __construct($latitude, $longitude)\n {\n // Nothing wrong with what you have done, but personally i am not a big fan of doing work in the constructor\n // $this-&gt;_check_weather($latitude, $longitude);\n $this-&gt;_latitude = $latitude;\n $this-&gt;_longitude = $longitude;\n }\n\n// private function _check_weather($latitude, $longitude)\n private function _check_weather()\n {\n // check and store the current weather, then ignore any further requests\n if (!$this-&gt;_current_weather) {\n $weather_xml = $this-&gt;_get_weather_xml();\n\n// $weather_xml = $this-&gt;_parse_weather_xml($weather_xml);\n $this-&gt;_current_weather = $this-&gt;_parse_weather_xml($weather_xml);\n }\n }\n\n // I am not a big fan of passing through properties and getting them dynamically,\n // unless you are expecting dynamic data back from the service you are calling\n // the user has to know the parameters _temperature, _symbol_url and type them correctly\n // if you use clearly defined functions then auto-complete on ide's will work and it makes life easier\n // the less the user needs to know about the inner workings the better\n\n// public function get_weather($property)\n// {\n// return $this-&gt;$property;\n// }\n//\n// public function __get($property)\n// {\n// if(!property_exists($this, $property)){\n// echo \"The property {$property} doesn't exist.\";\n// }\n// }\n\n public function get_weather() {\n $this-&gt;_check_weather();\n\n return isset($this-&gt;_current_weather['symbol']['id']) ? $this-&gt;_current_weather['symbol']['id'] : 'Unknown';\n }\n\n public function get_temperature() {\n $this-&gt;_check_weather();\n\n return isset($this-&gt;_current_weather['temperature']) ? $this-&gt;_current_weather['temperature'] : 'Unknown';\n }\n\n public function get_symbol_url() {\n $this-&gt;_check_weather();\n\n return isset($this-&gt;_current_weather['symbol']['number']) ? self::URL_IMG.\"?symbol=\".$this-&gt;_current_weather['symbol']['number'].\";content_type=image/png\" : NULL;\n }\n\n// private function _get_weather_xml($_latitude, $_longitude)\n private function _get_weather_xml()\n {\n $weather_xml = simplexml_load_file(self::URL_API.\"?lat={$this-&gt;_latitude};lon={$this-&gt;_longitude}\");\n return $weather_xml;\n }\n\n private function _parse_weather_xml($weather_xml)\n {\n // it good how you have kept parse weather a separate function to get weather xml\n // this way you can write a unittest and pass in dummy xml and inspect the response\n\n // don't use define() in a function, what if we call that function twice, will if define it twice and wipe out previous values?\n // you would be better off with a const that is referenced in this class's namespace only (moved code to top of class)\n\n //define('TZ_OFFSET', 60*60*1);\n\n\n $now = time();\n $current_hour = $now - ($now % (60*60));\n\n $current_weather = array();\n\n foreach ($weather_xml-&gt;product-&gt;time as $time){\n $from_hour = strtotime($time['from']) - self::TZ_OFFSET_SECONDS;\n $from_hour = $from_hour - ($from_hour % (60*60));\n\n if($time['datatype'] == \"forecast\"){\n\n if($from_hour == $current_hour){\n if($time-&gt;location-&gt;symbol){\n if(!isset($current_weather['symbol'])){\n $current_weather['symbol'] = $time-&gt;location-&gt;symbol;\n }\n }\n else {\n if(!isset($current_weather['temperature'])){\n $current_weather['temperature'] = $time-&gt;location-&gt;temperature['value'];\n }\n }\n }\n }\n }\n // $this-&gt;_weather = $current_weather['symbol']['id'];\n // $this-&gt;_temperature = $current_weather['temperature'];\n // $this-&gt;_symbol_url = self::URL_IMG.\"?symbol=\".$current_weather['symbol']['number'].\";content_type=image/png\";\n return $current_weather;\n }\n}\n\n// Instantiate Weather object, parameters: latitude, longitude\n$weather = new Weather(59.32893000000001, 18.06491);\n\n//echo $weather-&gt;get_weather(\"_weather\").\"&lt;br /&gt;\";\n//echo $weather-&gt;get_weather(\"_temperature\").\"&lt;br /&gt;\";\n//echo \"&lt;img src=\".$weather-&gt;get_weather(\"_symbol_url\").\" /&gt;\";\n\n\necho $weather-&gt;get_weather().\"&lt;br /&gt;\";\necho $weather-&gt;get_temperature().\"&lt;br /&gt;\";\necho \"&lt;img src=\".$weather-&gt;get_symbol_url().\" /&gt;\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T04:29:25.983", "Id": "40238", "ParentId": "40219", "Score": "1" } }, { "body": "<p>Right, first: short answers to your 4 questions:</p>\n\n<ol>\n<li>Is this proper OOP?<br>\nNo, there are several issues</li>\n<li>Or what can I do to improve this class?<br>\nA few things, we'll get to that in a moment.</li>\n<li>Do I need to make it more abstract?<br>\nYou may want to look into that</li>\n<li>What can I do to make the <code>_parse_weather_xml</code> method less ugly?\nDitch it, or better yet, inject a dependency that <em>just</em> parses XML</li>\n</ol>\n\n<p>I'm at work now, so I'll be updating this answer every once in a while.<br>\nBut first off: <strong><em>is this proper OOP?</em></strong></p>\n\n<p>No, for two main reasons: OOP works best if each class (object) has only 1 single task, and is given all it needs to do this one task. Your class does several things: it parses XML, it echoes, and it serves as an API/wrapper thing for a parsed XML file. Take this for example:</p>\n\n<pre><code>public function get_weather($property)\n{\n return $this-&gt;$property;\n}\npublic function __get($property)\n{\n if(!property_exists($this, $property)){\n echo \"The property {$property} doesn't exist.\";\n }\n}\n</code></pre>\n\n<p>What is quite likely is for me to do either:</p>\n\n<pre><code>$foo = $instance-&gt;get_weather('foobar');\n//or even\n$foo = $instance-&gt;foobar;\n</code></pre>\n\n<p>Both will do the same thing. Not only does your <strong><em>slow</em></strong> magic method <code>__get</code> expose all properties (both public and private) to the user, it also, as in the case I gave here results in unwanted behaviour. Assume, if you will, an MVC pattern. if I were to paste the code <code>$foo = ...</code> in the Model layer, or the controller, the <code>echo</code> would cause the headers to be sent, and I am no longer able to set the headers.<br>\nBut that's nothing compared to the bugs I might be getting: <strong>I don't know which usage of <code>$instance</code> is causing the problem</strong> I'll have to debug all of the code. An object shouldn't <code>echo</code>. Especially not if its goal is to notify the user of abuse: <em>throw an exception!</em></p>\n\n<pre><code>public function get_weather($property)\n{\n if (property_exists($this, $property))\n return $this-&gt;$property;\n throw new InvalidArgumentException($property. ' does not exist!');\n}\n</code></pre>\n\n<p>Think about these for a kickoff... I'll be back for more, though :)</p>\n\n<hr>\n\n<p>Back for more:<br>\nAnd let's get right into the nitty-gritty, and question your design. Now this may seem harsh, but <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">IMO, that's what code-review has to do</a>.</p>\n\n<p>You've defined a constructor to accept coordinates. Right, so that, to me, looks like a data class (an object that carries data, and just has getters and setters to allow for easy data access). But in reality, the data I pass to the constructor is never stored, it is, in stead, passed on directly to an API call, and results in your class parsing an XML DOM. From this, you set the actual properties of the object.<br>\nNow, in itself, this is perfectly valid: I don't <em>need</em> to know how and whence the data is coming from, but I may want to be offered, in the very least, a <em>choice</em> of when the API call is actually made. Personally, I'd lazy-load it, for example.</p>\n\n<p>I may also find myself in the position where I have only 1 of the coordinates you need, and I may choose to create the instance of the class ahead of time, and set the second coordinate later on.<br>\nThe main reason why I'd want to do this is because that allows me to use type-hints in my code:</p>\n\n<pre><code>class Weather\n{\n private $long = null;\n private $lat = null;\n public function __construct(array $coords)\n {\n if (isset($coords['long'])) $this-&gt;long = $coords['long'];\n if (isset($coords['lat'])) $this-&gt;lat = $coords['lat'];\n }\n public function setLong($long)\n {\n $this-&gt;long = $long;\n return $this;//enables chainable interface\n }\n public function setLat($lat)\n {\n $this-&gt;lat = $lat;\n return $this;\n }\n public function getLong()\n {\n return $this-&gt;long;\n }\n public function getLat()\n {\n return $this-&gt;lat;\n }\n}\n</code></pre>\n\n<p>Now this way, I can pass the instance along god knows how many times, but to methods that all look like this:</p>\n\n<pre><code>public function doStuff(Weather $weatherInstance)\n{\n $this-&gt;checkCoordinates($weatherInstance);//this once may set missing coordinates\n}\n</code></pre>\n\n<p>Back for more in a moment...</p>\n\n<hr>\n\n<p>On the reason why I'm not using underscores in the property names: I try to follow the PHP FIG coding style guidelines as much as possible, and like <a href=\"http://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a> clearly states:</p>\n\n<blockquote>\n <p>Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.</p>\n</blockquote>\n\n<p>The standards also specify that methods should be camelCased. I did not change your methods <code>get_weather</code> to the more preferable <code>getWeather</code> for clarity purposes only, but you may have noticed that I <em>did</em> use camelCased method names for example methods and my getters and setters.</p>\n\n<p>As for those getter and setter methods: Yes, I most certainly do use those whenever I can. Instead of relying on <code>__get</code> and <code>__set</code> magic methods. There are several issues I have with these magic methods, to name a few:</p>\n\n<ul>\n<li>Exposing private and protected properties.</li>\n<li>Slow (at least 2 additional lookups required)</li>\n<li>bad for code-hinting IDE's</li>\n<li>No control over the types being assigned to the actual properties, thus no control over the data your object contains => risk of memory leaks is quite real.</li>\n</ul>\n\n<p>Now, let's examine these 5 issues:</p>\n\n<pre><code>class PrivateOnly\n{\n private $email = null;\n private $db = null;\n public function __set($name, $val)\n {\n $this-&gt;{$name} = $val;\n }\n public function setEmail($email)\n {\n if (!filter_var($email, FILTER_VALIDATE_EMAIL))\n {\n throw new InvalidArgumentException(__METHOD__.' was not passed a valid email address, instead saw: '. $email);\n }\n $this-&gt;email = $email;\n return $this;\n }\n public function setDb(PDO $connection)\n {\n $this-&gt;db = $connection;\n return $this;\n }\n}\n</code></pre>\n\n<p>Now here you can clearly see that a setter allows me to <em>validate</em> the input more clearly, and allows me to throw exceptions that actually <em>explain</em> what is wrong with my code at any give time.<br>\nI can also use type-hinting, to restrict any value <em>except</em> for those types I actually need, in the case of the <code>db</code> property, it is clear that I'm expecting to receive an instance of <code>PDO</code> to be assigned to that property.<br>\nThis makes my API more self-documenting, less error prone, faster to learn and (as I will show) faster in terms of performance, too.</p>\n\n<p><strong><em>performance</em></strong>: I've already covered the internals of PHP objects <a href=\"https://stackoverflow.com/questions/17696289/pre-declare-all-private-local-variables/17696356#17696356\">here</a>. The bottom line, and I was backed up by hakre (a PHP core contributor), is that pre-declared properties are faster, simply because a lookup of a pre-declared (aka property known at compile time) is an <em>O(1)</em> operation, as opposed to <em>O(n)</em>.<br>\nThe same applies to methods, too, and so a pre-defined setter will outperform a magic method. End of. Compare what PHP has to do in the following cases:</p>\n\n<pre><code>$instance-&gt;newProperty = 'new Value';\n//1. loopup for public newProperty ==&gt; not found\n//2. lookup for __set ==&gt; found\n//3. invoke __set, pass newProperty zval, and newValue\n//4. set flag on instance that PHP uses to check if it's already in the __set method\n//5. execute __set \n// 5a=&gt; scan properties_table (HashTable) for property (fast one)\n// 5b=&gt; if property is private or protected, change value, else:\n// add new pointer to properies table (the slow table)\n//6. return\n</code></pre>\n\n<p>The same operations will be required for the <code>__get</code> method, give or take. Compare that to a pre-defined property (which only required step 1), and compare that to a custom (safer) setter:</p>\n\n<pre><code>$myObject-&gt;setEmail('foo@bar.com');\n//1. Lookup for setEmail method\n//2. invoke\n//3. execute, throw exception on failure\n//4. Lookup email property (fast table)\n//5. assign\n//6. Return\n</code></pre>\n\n<p>Yes, you may say, this is the same number of steps as the slow approach (magic set), but I think you'll agree that the outcome of this approach is much, much more predictable, it only uses the fast HashTable lookups and performs additional validations that the first approach simply <em>can't do</em>.</p>\n\n<p><strong><em>code-hinting</em></strong>: simple - most decent IDE's will use the doc-blocks in your class for code-completion and code hinting. If you use a magic setter, then there are no doc-blocks in place to help you out. If you use a getter and setter per property, then your IDE will tell you what each method expects, in terms of arguments and, perhaps more importantly, what a getter returns.<br>\nIf a getter returns an instance of a class, the IDE will know what class you're using here:</p>\n\n<pre><code>$pdo = $myInstance-&gt;getDb();//assume doc-block @return \\PDO\n$pdo-&gt;p[auto-complete:prepare]();\n</code></pre>\n\n<p>This makes your code easier to learn and use for others. <strong>Use doc-blocks and type-hints whenever you can</strong>.</p>\n\n<p><strong><em>Control</em></strong>: Well, most of this is covered already, but take the <code>PrivateOnly</code> class example again: I hint <code>PDO</code> in the <code>setDb</code> method. That means that if I pass an invalid argument at some point, the method won't ever get called, and the app will crash, on the plus side, you'll have an easy time identifying the <em>exact line</em> in your code that caused this problem, and might see that that line of code is attempting to pass an instance of <code>Mysqli</code> to the <code>setDb</code> method, and you can set about fixing the code.<Br>\nUsing a setter, the line that looks like this:</p>\n\n<pre><code>$instance-&gt;db = new Mysqli();\n</code></pre>\n\n<p>Goes by unnoticed... it's perfectly valid, but then, when you attempt to call a method of the instance that actually <em>uses</em> the <code>db</code> property, thinking it's a <code>PDO</code> instance, you're in trouble:</p>\n\n<pre><code>$stmt = $this-&gt;db('SELECT * FROM userData WHERE email = :email');//all good\n//stmt is mysqli_stmt instance, though you think it's a PDOStatement\n$stmt-&gt;execute(\n array(\n ':email' =&gt; $this-&gt;getEmail()\n )\n);//ERROR mysqli_stmt::execute expects void!\n</code></pre>\n\n<p>This is where you'll find yourself stepping through a lot of code, in search of that one statement <code>$this-&gt;db = $mysqliInstance;</code>, which you are likely to overlook, simply because it's a perfectly valid and simple statement. Don't torture yourself with stuff like this: use the tools you have at your disposal: methods + typehints save lives, or at least: working hours.</p>\n\n<p><strong><em>Memory leaks</em></strong>: PHP manages memory using reference counts, if an object, or value has no references (no var left that point to a given object), then the memory associated with that value is freed. This works fine in simple cases, but leaks like a b**** when you introduce it to some circular references: </p>\n\n<pre><code>$instance-&gt;itself = $instance; \n</code></pre>\n\n<p>The ref-count of <code>$instance</code> is increased by 1, because <code>$instance</code> has been given a new property, and that property references <code>$instance</code>, so this is a circular reference, because we have an object that points to itself. The reference count, then will always be >= 1, never 0, because within the scope of <code>$instance</code>, a reference to itself is still accessible.<br>\nEven if PHP has addressed this specific issue (and I think it has), stuff like this is still prone to leak:</p>\n\n<pre><code>$instance-&gt;brother = $instance2;\n$instance2-&gt;sister = $instance;\n</code></pre>\n\n<p>2 separate objects reference each-other, if I would then reassign <code>$instance</code> and <code>$instance2</code>, it wouldn't matter, because the ref-count will be >= 1 for both objects:</p>\n\n<pre><code>[scope instance] -&gt; instance2 ==&gt; refcount instance2 =&gt; 1\n[scope instance2] -&gt; instance ==&gt; refcount instance =&gt; 1\n</code></pre>\n\n<p>Because both instances are referenced in a scope, that they supposedly can still access, they can't be GC'ed, yet neither of these scopes is accessible to you. Hence <code>__set</code> can easily lead to memory leaks:</p>\n\n<pre><code>$instance-&gt;typ0 = $someObj;\n//comment: avoid memory leak, remove reference to $someObj\n$instance-&gt;typo = null;\n</code></pre>\n\n<p>Because of the typo, you're actually not unsetting the reference to <code>$someObj</code>. Don't use PHP's object overloading, that's the bottom line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T09:45:38.773", "Id": "67682", "Score": "0", "body": "Thank you so much for your feedback! I'm looking forward to hear more!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T14:39:40.010", "Id": "67732", "Score": "0", "body": "@DoubleRainbow: Added a little side-note on constructor" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T19:37:25.370", "Id": "67821", "Score": "0", "body": "Wow thanks! I didn't expect to receive this much help! It's very appreciated!\n\nSorry for being a noob, but do you usually write one separate getter and setter for each property in a class? And do you prefer not to have an underscore as the first character in a private or protected property or method?\n\nI'd love to hear more feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T08:27:36.547", "Id": "67913", "Score": "0", "body": "@DoubleRainbow: Added reasons for my omitting the underscore, and some more details on setters and getters and why to use them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T15:32:12.137", "Id": "67957", "Score": "0", "body": "Again, thank you so much for your help! It is really very helpful! You've already helped me too much, but if you're in the mood, could you explain more about what you mean by \"Ditch it, or better yet, inject a dependency that just parses XML\" regarding the _parse_weather_xml method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T15:48:22.620", "Id": "67962", "Score": "0", "body": "@DoubleRainbow: I will, I'm thinking about how to best tackle that (which is bound to be the most substantial part of my review). It's just that I can't find the time ATM, owing to quite a hefty schedule both at work and at home :). In the mean time, [you may find this older CR post of mine interesting](http://codereview.stackexchange.com/questions/37731/structure-of-api-wrapper/37741#37741), since you are effectively trying to write an API wrapper of sorts, or you are basically writing something that may grow into one" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T08:23:50.323", "Id": "40250", "ParentId": "40219", "Score": "5" } } ]
{ "AcceptedAnswerId": "40250", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T23:16:09.280", "Id": "40219", "Score": "3", "Tags": [ "php", "object-oriented", "xml" ], "Title": "PHP Weather class" }
40219
<p>I am creating an app in Unity3D and it is my first time coding in C#. I use the following code to parse a JSON file hosted on my server and use the information to render prefabs within my scene:</p> <pre><code> // Parses the json Object JSONParser parser = new JSONParser(); AssetData assetData = parser.ParseString(mJsonAssetInfo.text); mAssetData = assetData; // Updates state variables mIsLoadingAssetData = false; for(var i = 0; i &lt; assetData.Assets.Count; i++){ GameObject newAsset = null; if(((Assets)assetData.Assets[i]).AssetType == "Text"){ newAsset = (GameObject)Instantiate(asset, new Vector3(15*i, 0, 0), Quaternion.identity); newAsset.GetComponent&lt;TextMesh&gt;().text = ((Assets)assetData.Assets[i]).AssetContent; newAsset.transform.rotation = Quaternion.Euler(90, -180, 0); string[] rgba = Regex.Split(((Assets)assetData.Assets[i]).AssetBgcolor, ", "); float red = float.Parse(rgba[0]); float green = float.Parse(rgba[1]); float blue = float.Parse(rgba[2]); float alpha = float.Parse(rgba[3]); var child = newAsset.renderer.transform.transform.Find("background"); child.renderer.material.color = new Color(red/255, green/255, blue/255, alpha); float posXtag; posXtag = (((((Assets)assetData.Assets[i]).AssetLeft * 100f / 1024f) + (((Assets)bookData.Assets[i]).AssetWidth * 100f / 1024f) / 2f))-50f; float posYtag; posYtag = -1*((Assets)assetData.Assets[i]).AssetTop * 50f / 512f - ((Assets)assetData.Assets[i]).AssetHeight * 50f / 512f / 2f +25f; newAsset.transform.localPosition = new Vector3(posXtag,0,posYtag); child.renderer.transform.localScale = new Vector3(((Assets)assetData.Assets[i]).AssetWidth/102.4f,0.2f,((Assets)assetData.Assets[i]).AssetHeight/102.4f); } else if (((Assets)assetData.Assets[i]).AssetType == "Image"){ newAsset = (GameObject)Instantiate(iasset, new Vector3(15*i, 0, 0), Quaternion.identity); newAsset.transform.parent = AugmentationObject.transform; Color color = newAsset.renderer.material.color; color.a = 0f; newAsset.renderer.material.color = color; string url = ((Assets)bookData.Assets[i]).AssetContent; StartCoroutine(DownloadImage(url, newAsset, ((Assets)assetData.Assets[i]).AssetFilename, "IMAGE")); newBrick.transform.rotation = Quaternion.Euler(0, 0, 0); float posXtag; posXtag = (((((Assets)assetData.Assets[i]).AssetLeft * 100f / 1024f) + (((Assets)assetData.Assets[i]).AssetWidth * 100f / 1024f) / 2f))-50f; float posYtag; posYtag = -1*((Assets)assetData.Assets[i]).AssetTop * 50f / 512f - ((Assets)assetData.Assets[i]).AssetHeight * 50f / 512f / 2f +25f; newAsset.transform.localPosition = new Vector3(posXtag,0,posYtag); newAsset.transform.localScale = new Vector3(((Assets)assetData.Assets[i]).AssetWidth/102.4f,0.2f,((Assets)assetData.Assets[i]).AssetHeight/102.4f); } else if (((Assets)assetData.Assets[i]).AssetType == "Video"){ newAsset = (GameObject)Instantiate(video, new Vector3(15*i, 0, 0), Quaternion.identity); newAsset.GetComponent&lt;Playback&gt;().m_path = ((Assets)assetData.Assets[i]).AssetContent; string url = ((Assets)newAssetData.Assets[i]).AssetThumbnail; StartCoroutine(DownloadImage(url, newAsset, ((Assets)assetData.Assets[i]).AssetFilename, "VIDEO")); newAsset.transform.rotation = Quaternion.Euler(0, -180, 0); float posXtag; posXtag = (((((Assets)assetData.Assets[i]).AssetLeft * 100f / 1024f) + (((Assets)assetData.Assets[i]).AssetWidth * 100f / 1024f) / 2f))-50f; float posYtag; posYtag = -1*((Assets)assetData.Assets[i]).AssetTop * 50f / 512f - ((Assets)assetData.Assets[i]).AssetHeight * 50f / 512f / 2f +25f; newAsset.transform.localPosition = new Vector3(posXtag,0,posYtag); newAsset.transform.localScale = new Vector3(((Assets)assetData.Assets[i]).AssetWidth/102.4f,0.2f,((Assets)assetData.Assets[i]).AssetHeight/102.4f); } newAsset.transform.tag = "Asset"; // IF ASSET IS SET TO FADEIN DO THAT HERE: if(((Assets)assetData.Assets[i]).AssetFadein == "true"){ iTween.FadeTo(newBrick, 1f, 1); } else { Color color = newAsset.renderer.material.color; color.a = 1f; newAsset.renderer.material.color = color; } // EOF ASSET FADEIN if(((Assets)assetData.Assets[i]).AssetAction != ""){ newAsset.AddComponent("TouchListener"); newAsset.GetComponent&lt;TouchListener&gt;().actionUrl = ((Assets)assetData.Assets[i]).AssetAction; } } </code></pre> <p>My JSON file can contain information of 3 "asset" types (text, image or video), each asset type renders a different prefab (<code>Text</code> = asset, <code>Image</code> = iasset, <code>Video</code> = video). I then set the different parameters for the prefab:</p> <ul> <li>Hieght</li> <li>Width </li> <li>position x-axis </li> <li>position y-axis </li> <li>background color (text only) </li> <li>texture (image and video) </li> <li>fadein animation (if set) </li> <li>touch action (if set)</li> </ul> <p>My code works fine, but as it is my first time coding in C# I am sure there is a cleaner way of getting the job done. Any suggestion would be greatly appreciated!</p>
[]
[ { "body": "<p>I would split the asset loading into 3 different classes: <code>TextAsssetLoader</code>, <code>ImageAssetLoader</code>, and <code>VideoAssetLoader</code>. This will allow you to separate the loading of each type. Additionally, I would create an interface so you can eliminate the <code>if</code> statement in your current code.</p>\n\n<pre><code>public interface IAssetLoader\n{\n GameObject Create(AssetData assetData, int index);\n}\n</code></pre>\n\n<p>Then each class would be:</p>\n\n<pre><code>public class TextAssetLoader : IAssetLoader\n{\n public GameObject Create(AssetData assetData, int index)\n {\n var newAsset = (GameObject)Instantiate(asset, new Vector3(15*index, 0, 0), Quaternion.identity);\n newAsset.GetComponent&lt;TextMesh&gt;().text = assetData.AssetContent;\n newAsset.transform.rotation = Quaternion.Euler(90, -180, 0);\n\n string[] rgba = Regex.Split(assetData.AssetBgcolor, \", \");\n float red = float.Parse(rgba[0]);\n float green = float.Parse(rgba[1]);\n float blue = float.Parse(rgba[2]);\n float alpha = float.Parse(rgba[3]);\n\n var child = newAsset.renderer.transform.transform.Find(\"background\");\n child.renderer.material.color = new Color(red/255, green/255, blue/255, alpha);\n\n float posXtag;\n posXtag = (((((Assets)assetData.Assets[i]).AssetLeft * 100f / 1024f) + assetData.AssetWidth * 100f / 1024f) / 2f))-50f;\n\n float posYtag;\n posYtag = -1*assetData.AssetTop * 50f / 512f - (assetData.AssetHeight * 50f / 512f / 2f +25f;\n\n newAsset.transform.localPosition = new Vector3(posXtag,0,posYtag);\n child.renderer.transform.localScale = new Vector3(assetData.AssetWidth/102.4f,0.2f,assetData.AssetHeight/102.4f);\n }\n}\n\n// Next two clases are pretty much the same.\n</code></pre>\n\n<p>Your main loader then looks like:</p>\n\n<pre><code>public class AssetLoader\n{\n private static readonly IDictionary&lt;string IAssetLoader&gt; Loaders = new Dictionary&lt;string, IAssetLoader&gt;\n {\n { \"Text\", new TextAssetLoader() },\n { \"Image\", new ImageAssetLoader() },\n { \"Video\", new VideoAssetLoader() },\n };\n\n public void LoadAssets()\n {\n\n for(var i = 0; i &lt; assetData.Assets.Count; i++)\n {\n var asset = assetData.Assets[i];\n\n GameObject gameObject = Loaders[asset..AssetType].Create(asset, i);\n\n // Rest of the code to deal with gameObject\n }\n\n }\n}\n</code></pre>\n\n<p>On top of this change, I would suggest getting rid of all the casts in your code; <code>((Assets)assetData.Assets[i])</code> gets a little confusing. If you have to cast it do it once as in my code, a better alternative is to have an <code>AssetData</code> class, and have the <code>Asset</code>s and <code>IEnumerable&lt;AssetData&gt;</code>. This way you don't have to ever cast it in your code; it is done on deserialization.</p>\n\n<p>Standard C# guidelines suggest having opening and closing braces on separate lines:</p>\n\n<pre><code>if (something)\n{\n}\n</code></pre>\n\n<p>Other than making it easier to read, I don't see too much else that needs attention.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T11:48:13.153", "Id": "67693", "Score": "0", "body": "Thanks for the detailed response @Jeff, I am going to integrate it and test and will post back" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T00:36:00.157", "Id": "40222", "ParentId": "40221", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T00:09:04.480", "Id": "40221", "Score": "8", "Tags": [ "c#", "parsing", "json", "unity3d" ], "Title": "Loop through JSON and create prefab in Unity3D" }
40221
<p>A puzzle I was given:</p> <blockquote> <p><strong>Description:</strong></p> <p>Write a method that returns the "pivot" index of a list of integers. We define the pivot index as the index where the sum of the numbers on the left is equal to the sum of the numbers on the right. Given [1, 4, 6, 3, 2], the method should return 2, since the sum of the numbers to the left of index 2 is equal to the sum of numbers to the right of index 2 (1 + 4 = 3 + 2). If no such index exists, it should return -1. If there are multiple pivots, you can return the left-most pivot.<br> You can write the method in any language.</p> <p>Make sure that the method:</p> <ul> <li>runs successfully</li> <li>handles all edge cases</li> <li>is as efficient as you can make it!</li> </ul> </blockquote> <p>Apparently my solution is not efficient enough:</p> <pre><code>def pivot(arr) results = [] arr.each_with_index do |n,index| last = arr.size - 1 sum_left = arr[0..index].inject(:+) sum_right = arr[index..last].inject(:+) results &lt;&lt; index if sum_left == sum_right end results.any? ? results.first : -1 end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T03:23:24.167", "Id": "67649", "Score": "1", "body": "Steven, your code is quite inefficient. For example, you calculate `last` each time through the loop, even though it doesn't change and you add up all the elements each time through the loop. (You include `arr[index]` in both the left and right sums, which is OK, but not necessary.) Consider calculating an array `t` such that `t[i]` is the sum of all elements with indices between `0` and `t`, inclusive, for `i` from `0` to `arr.size-1`. How can you do that efficiently? That reduces your problem to finding `n` such that `t[n-1] == t[arr.size-1] - t[n]`, or showing that no such `n` exists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T03:55:20.400", "Id": "67650", "Score": "0", "body": "Thank you for the prompt review Cary. Boy is my face red on that last variable running through the loop. That was clumsy! I like your solution of summing between indices - very elegant and clever. Cheers!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T05:05:31.587", "Id": "67659", "Score": "1", "body": "Steven, if you wish to edit your question to include a revised solution, I suggest you write \"Edit: ....\", and leave your current solution at the bottom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:40:54.280", "Id": "67795", "Score": "1", "body": "http://stackoverflow.com/questions/5898104/how-to-optimally-divide-an-array-into-two-subarrays-so-that-sum-of-elements-in-b" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T17:41:49.190", "Id": "67796", "Score": "0", "body": "http://en.wikipedia.org/wiki/Partition_problem" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T19:35:38.257", "Id": "67820", "Score": "0", "body": "@Nakilon, I think your SO link should be quite helpful to Steven, but the wiki discussion of the general partition problem (dividing the elements into two sets having equal sums, as opposed to just slicing the array) may be confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T20:52:38.900", "Id": "67835", "Score": "0", "body": "@CarySwoveland Your first comment here seems like an answer to me. If you post it as an answer, you'll probably get an up-vote or two." } ]
[ { "body": "<p>Ruby allows -1 as an index that means last, so you don't have to calculate it at all.</p>\n\n<p>Calculating the whole left_sum every time is repeating work since it is always the previous left_sum + arr[index-1] (except for when index = 0). Similarly the right_sum is always the previous right_sum - arr[index].</p>\n\n<p>You don't have to gather all results, so you can terminate early on finding the leftmost solution, or as soon as sum_left > sum_right (assuming there are no negative numbers in arr?) you know there is no solution, so can return -1.</p>\n\n<p>For example (untested)</p>\n\n<pre><code>def find_pivot(arr)\n sum_left = -arr[-1]\n sum_right = arr.inject(:+)\n arr.each_index do |i|\n sum_left += arr[i-1]\n sum_right -= arr[i]\n if sum_left == sum_right\n return i\n elsif sum_right &lt; sum_left\n # assuming there are no negative numbers we already know there's no solution\n return -1\n end\n end\n return -1 # in case we somehow reach the end without a solution or early termination\nend\n</code></pre>\n\n<p>Initialising sum_left to <code>-arr[-1]</code> is a trick to save on having to add an if statement to detect and handle the first iteration of the loop differently, since it cancels out the effect of <code>sum_left += arr[0-1]</code> which would make sum_left jump to the value of the last value in the array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-29T02:24:16.043", "Id": "67872", "Score": "0", "body": "Nat your example worked perfectly. Thanks for schooling me on the negative index. VERY handy trick!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T20:04:48.883", "Id": "40292", "ParentId": "40226", "Score": "8" } }, { "body": "<p>Here's another way:</p>\n\n<pre><code>def pivot(arr)\n n = arr.size\n raise ArgumentError \"arr.size = #{arr.size} &lt; 3\" if n &lt; 3\n ct = 0\n cum = arr.each_with_object([]) { |e,c| c &lt;&lt; (ct += e) }\n tot = cum.last\n (1...n-1).each do |i|\n return i if cum[i-1] == tot - cum[i]\n end\n return -1\nend\n\npivot([1, 4, 6, 3, 2]) #=&gt; 2\npivot([1, 4, 6, 3, 2, 8, 1]) #=&gt; 3\npivot([1, 3, 1, -1, 3, -5, 8, 1]) #=&gt; 4\npivot([1, 4, 6, 3, 1, 8]) #=&gt; -1\npivot([1.0, 4.5, 6.0, 3.0, 2.5]) #=&gt; 2\n</code></pre>\n\n<p>For <code>arr = [1, 4, 6, 3, 2]</code>, <code>cum = [1, 5, 11, 14, 16]</code>. Beginning with <code>i = 1</code>\nwe attempt to find <code>i, 1 &lt;= i &lt;= n-2</code>, such that <code>cum[i-1] == 16 - cum[i]</code>. </p>\n\n<p>If the elements of <code>arr</code> are all non-negative,</p>\n\n<pre><code>return i if cum[i-1] == tot - cum[i]\n</code></pre>\n\n<p>can be replaced with:</p>\n\n<pre><code>return i if (d = tot - cum[i] - cum[i-1]) == 0\nreturn -1 if d &lt; 0\n</code></pre>\n\n<p>In this case, <code>cum</code> is non-decreasing, so if</p>\n\n<pre><code>cum[i-1] &gt; tot - cum[i]\n</code></pre>\n\n<p>no <code>j &gt; i</code> can be the pivot index.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T04:03:06.170", "Id": "41266", "ParentId": "40226", "Score": "1" } }, { "body": "<p>Here another solution with no if's and no sum_right, you could skip the first iteration but then you need to check the length of the array first.</p>\n\n<pre><code>def pivot(arr)\n i, sum_left, total = 0, 0, arr.inject(:+)\n sum_left, i = sum_left+arr[i], i+1 until sum_left &gt;= (total-arr[i])/2\n return ((sum_left == (total-arr[i])/2) and (arr.length &gt; 2)) ? i:-1\nend \n\nputs pivot([1, 4, 6, 3, 2]) #=&gt; 2\nputs pivot([1, 4, 6, 3, 2, 8, 1]) #=&gt; 3\nputs pivot([1, 3, 1, -1, 3, -5, 8, 1]) #=&gt; 4\nputs pivot([1, 4, 6, 3, 1, 8]) #=&gt; -1\nputs pivot([1.0, 4.5, 6.0, 3.0, 2.5]) #=&gt; 2\nputs pivot([3, 4, 6, 3, 4]) #=&gt; 2\nputs pivot([3]) #=&gt; -1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T17:54:57.110", "Id": "43533", "ParentId": "40226", "Score": "0" } } ]
{ "AcceptedAnswerId": "40292", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T01:13:22.877", "Id": "40226", "Score": "7", "Tags": [ "ruby" ], "Title": "Make this Ruby array pivot more efficient?" }
40226
<p>I have two functions to count the number of set '1' bits in the first <code>offset</code> bits of either a 64 bit number, or a bitmap struct.</p> <p>After some profiling, particularly the latter is quite a bottleneck in our system.</p> <p>What can we do to make it faster?</p> <pre><code>#define POPCOUNT16(x) __builtin_popcount(x) #define POPCOUNT64(x) __builtin_popcountl(x) static __always_inline __constant int32 count64(int64 const bitmap, int32 const offset) { return offset == 0 ? 0 : POPCOUNT64(bitmap &amp; (0xffffffffffffffffUL &lt;&lt; (64 - offset))); } typedef struct { int64 hi; int16 lo; } __packed int80; static __always_inline __constant int32 countBitmap(int80 const bitmap, int32 const offset) { int32 count = 0; if (offset &gt; 0) { count += POPCOUNT64(bitmap.hi &amp; (0xffffffffffffffffUL &lt;&lt; (sizeof (bitmap.hi)*8 - MIN(offset, sizeof (bitmap.hi)*8)))); if (offset &gt; sizeof (bitmap.hi)*8) count += POPCOUNT16(bitmap.lo &amp; ((int16)0xffff &lt;&lt; (sizeof (bitmap.hi)*8+sizeof (bitmap.lo)*8 - offset))); } return count; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T03:05:32.143", "Id": "67646", "Score": "1", "body": "Either I'm confused, or you are. `count64()` takes an `int64 bitmap` — how can there be a `bitmap.hi`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T10:26:57.093", "Id": "67687", "Score": "0", "body": "can you guarantee that offset is larger than 0? if so you can eliminate the first branch" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T12:54:10.743", "Id": "67701", "Score": "0", "body": "@ratchetfreak Either I have the branch at the call site, or in the function. As it's marked with `inline __attribute__((always_inline))`, I figured it would make no difference which, so I put it in the function for simplicity." } ]
[ { "body": "<p>first issue: you hardcode <code>8</code> as the number of bits per <code>sizeof</code> unit: portability says it should be <code>CHAR_BIT</code> which may be something else on some architectures</p>\n\n<p>second issue: both members of int80 are signed, only <code>hi</code> should be while <code>lo</code> can be unsigned</p>\n\n<p>if you can guarantee that offset is between 0 and 80 then you don't need to test for 0, and just document that exceeding the bounds is undefined behavior</p>\n\n<pre><code>static __always_inline __constant int32 countBitmap(int80 const bitmap, uint32 const offset) {\n int32 count = 0;\n if (offset &lt;= sizeof (bitmap.hi)*CHAR_BIT) {\n count = POPCOUNT64(bitmap.hi &gt;&gt;&gt; (sizeof (bitmap.hi)*CHAR_BIT - offset));\n // logical right shift to do away with the AND\n }else{\n count = POPCOUNT64(bitmap.hi)+\n POPCOUNT16(bitmap.lo &gt;&gt;&gt; (sizeof (bitmap)*CHAR_BIT - offset));\n }\n return count;\n}\n</code></pre>\n\n<p>here there is only 1 branch compared to the 2 you had before (possibly 3 depending on how <code>MIN</code> was implemented)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T10:50:05.730", "Id": "40255", "ParentId": "40230", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:29:45.093", "Id": "40230", "Score": "4", "Tags": [ "optimization", "c", "performance", "bitwise" ], "Title": "Efficiently counting '1' bits in the first n bits" }
40230
<p>Is there any better way of printing it?</p> <pre><code>public class PercentPrinter { /** * @param args */ public static void main(String[] args) { for (int i = 0; i &lt; 100; i++) { if (i == 0) System.out.print("percent completed: " + i + " %"); try { Thread.sleep(500); } catch (Exception e) { System.out.println(e); } if (i &gt; 9 &amp;&amp; i &lt;= 99) { System.out.print('\b'); System.out.print('\b'); System.out.print('\b'); System.out.print('\b'); System.out.print(i + " %"); } else { System.out.print('\b'); System.out.print('\b'); System.out.print('\b'); System.out.print(i + " %"); } } } } </code></pre>
[]
[ { "body": "<p>this sounds like a good candidate for a <code>printf</code>:</p>\n\n<ul>\n<li>always print a fixed amount of backspaces.</li>\n<li>always print a fixed-size % value.</li>\n</ul>\n\n<p>Finally, when monitoring things this way you always have <a href=\"http://en.wikipedia.org/wiki/Off-by-one_error#Fencepost_error\" rel=\"nofollow\">a fencepost problem</a>. Your work is the space between the fenceposts, and the fenceposts are the messages you write. You always have one more fencepost than space between them. You will need to have some message outside the loop. In your case, you do 100 items of work, so you will need 101 messages. I tend to chose to print the progress message after the work, so I tend to pre-print the first message before the loop.</p>\n\n<p>Also, you should have a simpler system for mixing the work (the <code>sleep(500)</code>) and the messages(<code>prints</code>).</p>\n\n<p>Consider the setup:</p>\n\n<pre><code>System.out.print(\"percent completed: 0 %\")\nfor (int i = 0; i &lt; 100; i++) {\n try {\n Thread.sleep(500);\n } catch (Exception e) {\n System.out.println(e);\n }\n System.out.printf(\"\\b\\b\\b\\b\\b%3d %%\", (i+1) );\n}\n</code></pre>\n\n<p>The above code will pre-print the message, and then each loop iteration it will erase 5 spaces, print a 3-wide integer value (padded with spaces), followed by \" %\". It requires the appropriate escaping <a href=\"http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#printf%28java.lang.String,%20java.lang.Object...%29\" rel=\"nofollow\">for <code>printf</code></a>.</p>\n\n<p><strong>Update:</strong> A few additional things:</p>\n\n<p><strong>%3d</strong> -> You request details on what the <code>%3d</code> does. It prints a minimum 3-character wide string representing an integral amount. if supplied with the integer <code>0</code> it will print <code>' 0'</code> (two spaces and a 0). If supplied with <code>99</code> it will print <code>' 99'</code>. If supplied with more than 3 digits, or more than 2-digit negative numbers, it will use as many characters as it needs. So, for <code>-100</code> it will print <code>'-100'</code>, and for <code>12345</code> it will print <code>'12345'</code>. You can read up on the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#dnint\" rel=\"nofollow\">documentation for the Formatter class</a> to see how this works. <a href=\"http://www.homeandlearn.co.uk/java/java_formatted_strings.html\" rel=\"nofollow\">Examples</a> and <a href=\"http://docs.oracle.com/javase/tutorial/java/data/numberformat.html\" rel=\"nofollow\">tutorials</a> are available online which will help too.</p>\n\n<p><strong>Error Handling</strong> - you should do more than just <code>System.out.println(e)</code>. There are degrees of error handling, and depending on the conditions there may be reasons to ignore, log, wrap, dump, throw, record, combine, or just count exceptions. But, never should you do a System.out.println(e). This just prints the toString of the exception, and that's not very useful. You should probably at least use <code>e.printStackTrace()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T11:47:43.047", "Id": "67692", "Score": "0", "body": "what is %3d here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T12:16:10.270", "Id": "67696", "Score": "0", "body": "As I say, it will `will erase 5 spaces, print a 3-wide integer value (padded with spaces), followed by \" %\"`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T11:39:21.487", "Id": "40257", "ParentId": "40242", "Score": "5" } }, { "body": "<p>Standing on the shoulders of @rolfl…</p>\n\n<p>I would prefer to use a carriage return to return the cursor to the beginning of the line, as it's a bit less fragile than backspacing.</p>\n\n<pre><code>public static void main(String[] args) {\n // Java's Printwriter.format() doesn't tell you how many characters\n // it produced; 30 characters is an overestimate to ensure that\n // the entire \"Percent completed: ***%\" string gets overwritten.\n final String CLEARLINE_FMT = \"\\r%30s\\r\";\n\n try {\n for (int i = 0; i &lt; 100; i++) {\n System.out.printf(\"\\rPercent completed: %3d%%\", i);\n Thread.sleep(500);\n }\n System.out.printf(CLEARLINE_FMT + \"Done!\\n\", \"\");\n } catch (InterruptedException e) {\n System.out.printf(CLEARLINE_FMT + \"Interrupted!\\n\", \"\");\n }\n}\n</code></pre>\n\n<p>Or, if you want to print \"100%\" instead of \"Done!\":</p>\n\n<pre><code>public static void main(String[] args) {\n // Java's Printwriter.format() doesn't tell you how many characters\n // it produced; 30 characters is an overestimate to ensure that\n // the entire \"Percent completed: ***%\" string gets overwritten.\n final String CLEARLINE_FMT = \"\\r%30s\\r\";\n\n try {\n for (int i = 0; ; i++) {\n System.out.printf(\"\\rPercent completed: %3d%%\", i);\n if (i &gt;= 100) {\n System.out.println();\n break;\n }\n Thread.sleep(500);\n }\n } catch (InterruptedException e) {\n System.out.printf(CLEARLINE_FMT + \"Interrupted!\\n\", \"\");\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:54:02.873", "Id": "40261", "ParentId": "40242", "Score": "6" } }, { "body": "<p>Here's a solution that doesn't require you to have a fixed length string, and also doesn't require much setup/cleanup.</p>\n\n<p>The holder parameter remembers the length of the previous message and clears that many characters the next time something is printed.</p>\n\n<pre><code>public static void printDynamic(AtomicInteger holder, String str) {\n String reset = \"\";\n if (holder.get() &gt; 0) {\n reset = String.format(\"%0\" + holder.get() + \"d\", 0).replace('0', '\\r');\n }\n System.out.print(reset + str);\n holder.set(str.length());\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>public static void main(String[] args) {\n AtomicInteger holder = new AtomicInteger();\n try {\n for (int i = 0; i &lt;= 100; i++) {\n printDynamic(holder, String.format(\"%02d%% complete\", i));\n Thread.sleep(500);\n }\n printDynamic(holder, \"Done\\n\");\n } catch (InterruptedException e) {\n printDynamic(holder, \"Interrupted\\n\");\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-14T09:35:31.913", "Id": "172951", "ParentId": "40242", "Score": "1" } } ]
{ "AcceptedAnswerId": "40257", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T06:32:57.333", "Id": "40242", "Score": "5", "Tags": [ "java", "formatting", "console" ], "Title": "Is this the best way to print dynamic percent value?" }
40242