body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm trying to write a piece of code that will mimic ASCII keyboard output. It uses the keyboard library from <a href="http://www.pjrc.com/teensy/usb_keyboard.html" rel="nofollow">pjrc</a>, but the application I'm working on requires outputting string sequences rather than individual keys (the <a href="http://www.pjrc.com/teensy/td_keyboard.html" rel="nofollow">C++ interface</a> exposes <code>Keyboard.print</code>, which does exactly what I want, except that I'm trying to stick to C for learning purposes).</p> <p>Here's a kick at it;</p> <pre><code>[snip] #include &lt;string.h&gt; #include "usb_keyboard.h" // definitions for the /KEY_\w+/ symbols int key_from_char(char c){ if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') return c + KEY_A - 'a'; if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') return c + KEY_A - 'A'; if (c &gt;= '1' &amp;&amp; c &lt;= '9') return c + KEY_A - '1'; if (c == '0') return 39; // 0 is low in ASCII, high in the USB key definition // there's no easy mapping between the other ASCII characters and // USB keyboard keys, so these are all manually represented switch (c) { case ' ': return KEY_SPACE; break; case '!': return KEY_1; break; case '"': return KEY_QUOTE; break; case '#': return KEY_NUMBER; break; case '$': return KEY_4; break; case '%': return KEY_5; break; case '&amp;': return KEY_7; break; case '\'': return KEY_QUOTE; break; case '(': return KEY_9; break; case ')': return KEY_0; break; case '*': return KEYPAD_ASTERIX; break; case '+': return KEYPAD_PLUS; break; case ',': return KEY_COMMA; break; case '-': return KEYPAD_MINUS; break; case '.': return KEY_PERIOD; break; case '/': return KEYPAD_SLASH; break; case ':': return KEY_SEMICOLON; break; case ';': return KEY_SEMICOLON; break; case '&lt;': return KEY_COMMA; break; case '=': return KEY_EQUAL; break; case '&gt;': return KEY_PERIOD; break; case '?': return KEY_SLASH; break; case '@': return KEY_2; break; case '[': return KEY_LEFT_BRACE; break; case '\\': return KEY_BACKSLASH; break; case ']': return KEY_RIGHT_BRACE; break; case '^': return KEY_6; break; case '_': return KEY_MINUS; break; case '`': return KEY_TILDE; break; case '{': return KEY_LEFT_BRACE; break; case '|': return KEY_BACKSLASH; break; case '}': return KEY_RIGHT_BRACE; break; case '~': return KEY_TILDE; break; default: return 0; } } int modifier_from_char(char c){ if ((c &gt;= 'A' &amp;&amp; c &lt;= 'Z') || // not sure how useful it is to put chars instead of ints for the rest of these c == '!' || c == '"' || (c &gt;= '$' &amp;&amp; c &lt;= '&amp;') || c == '(' || c == ')' || c == ':' || c == '&lt;' || (c &gt;= '&gt;' &amp;&amp; c &lt;= '@') || c == '^' || c == '_' || (c &gt;= '{' &amp;&amp; c &lt;= '~')) return KEY_SHIFT; return 0; } int8_t usb_keyboard_print(char *s){ int s_len = strlen(s); int i; for(i = 0; i &lt; s_len; i++){ usb_keyboard_press(key_from_char(s[i]), modifier_from_char(s[i])); } } </code></pre> <p>It seems to work, when I do </p> <pre><code>int main(void) { ... usb_keyboard_print("abcdABCD1234!@#$%^&amp;*()_+|~{}:\"&gt;?&lt;-=\\`[];',./"); ... } </code></pre> <p>the character sequence</p> <pre><code>abcdABCD1234!@\$%^&amp;*()_+|~{}:"&gt;?&lt;-=\`[];',./ </code></pre> <p>is output as if by keyboard.</p> <p>All comments welcome, but I also have specific points/questions</p> <ul> <li>It seems like there should be an easier way to do this. I mention above that the C++ version of the <code>usb_keyboard</code> library provides a <code>Keyboard.print</code> which does essentially the same thing, but I haven't found anything similar for plain C.</li> <li>Are there any issues I'm missing about USB key codes that would make this code wonk out based on nationality settings? How would you go about internationalizing it?</li> <li>This is basically the first C code I've written since getting out of high-school, so please point out style errors and inefficiencies with extreme prejudice.</li> </ul>
[]
[ { "body": "<p>Don't subtract absolute values:</p>\n\n<pre><code> if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') return c - 93;\n</code></pre>\n\n<p>It makes it hard to understand what you are doing when you subtract integer literals from character codes. I would normally expect some form of value that conveys some meaning. For example lets assume ASCII (You probably want your keyboard thing but I don't know the appropriate macro).</p>\n\n<pre><code> if (c &gt;= 'a' &amp;&amp; c &lt;= 'z') return c + 3 - 'a'; // For some reason you want 'a' to map to 3\n // If we assume ASCII 'a' =&gt; 96 \n\n\n if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') return c + 4 - 'A'; // For some reason you want 'A' to map to 4\n // If we assume ASCII 'A' =&gt; 65\n</code></pre>\n\n<p>Either you have some other requirement that is not ASCII (very possible), you want 'a'/'A' to map to some non zero number or you have a bug. But it is hard to tell with the way you have written your code as the literal values 93 and 61 have no real meaning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T20:48:30.497", "Id": "10670", "Score": "0", "body": "Lowercase a is [97, not 96](http://www.asciitable.com/) in ASCII. The values being returned are part of the header file included with the [Teensy C code](http://www.pjrc.com/teensy/usb_keyboard.zip)(zip file). You more or less got it, that header has the \"A\" key mapped to `4` (which I assume is some sort of keyboard standard; I don't know enough to dispute it). While ASCII has a different code for \"a\" than \"A\", the USB keyboard protocol seems to use the same code for both, but expects a modifier key for the uppercase. They're represented as `#define`s, so I could do `return c + KEY_A - 'a'`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T20:09:48.683", "Id": "6805", "ParentId": "6796", "Score": "2" } }, { "body": "<p>You could take a bit of a different approach if you wanted to get rid of the switch ( as they get a bit inefficient with lots of conditions)</p>\n\n<p>you can make an array of 256 ints, and use the current function to populate the array, then to get the int for the char. </p>\n\n<pre><code>int key_from_char(char c){\n return my_char_mapping_array[(unsigned int)c];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T03:38:32.440", "Id": "10677", "Score": "0", "body": "I agree with the usage of the array (that's a good idea). But I not sure I agree with the statement that switch statements get inefficient. I find they are implemented as a jump table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T08:53:44.220", "Id": "10683", "Score": "0", "body": "+1: the solution for this should really be data-driven rather than logic-driven" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T22:56:43.443", "Id": "6811", "ParentId": "6796", "Score": "1" } } ]
{ "AcceptedAnswerId": "6805", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:34:14.433", "Id": "6796", "Score": "3", "Tags": [ "c", "strings" ], "Title": "Keyboard Printing with Teensy" }
6796
<p>I really need some help removing some duplicated code. I've linked the methods causing me issues. <a href="http://pastebin.com/cZJihM4J" rel="nofollow">http://pastebin.com/cZJihM4J</a></p> <p>As you can see each method does similar things but retrieve different values. i.e one method to insert a string at a certain line. Another to get the the lines index and another to get the contents at a particular line</p> <p>There are things like:</p> <pre><code>String text = textArea.getText(); int start = 0; int count = 0; String buildNewTextArea = ""; </code></pre> <p>I could make these values global but not sure if this is the best way to approach this. My brain can't find away around this :(</p> <p>Thanks in advance</p> <pre><code> public String insertCodeBlock(String newBlock) { String text = textArea.getText(); int start = 0; int count = 0; String buildNewTextArea = ""; while (start &gt;= 0) { int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length()); if (nextLineStart == -1) { nextLineStart = text.length(); } String[] temp = diffBlocks.get(indexOfLine).split(","); int startLine = Integer.valueOf(temp[0]); int endLine = (Integer.valueOf(temp[1]) - 1) + startLine; if (count == startLine) { buildNewTextArea += newBlock; } else if (count &lt; startLine || count &gt; (startLine + (endLine - startLine))) { buildNewTextArea += text.substring(start, nextLineStart); } count++; start = text.indexOf(NEW_LINE, nextLineStart); } return buildNewTextArea; } private int getLineIndex(int line) { String text = textArea.getText(); int start = 0; int count = 0; String buildNewTextArea = ""; int index = 0; while (start &gt;= 0) { int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length()); if (nextLineStart == -1) { nextLineStart = text.length(); } if (count == line) { return index; } buildNewTextArea = text.substring(start, nextLineStart); index += buildNewTextArea.length(); count++; start = text.indexOf(NEW_LINE, nextLineStart); } return text.length(); } public String getLineContent(int startLine, int endLine) { String text = textArea.getText(); int start = 0; int count = 0; String buildNewTextArea = ""; while (start &gt;= 0) { int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length()); if (nextLineStart == -1) { nextLineStart = text.length(); } if (count &gt;= startLine &amp;&amp; count &lt;= endLine) { buildNewTextArea += text.substring(start, nextLineStart); } count++; start = text.indexOf(NEW_LINE, nextLineStart); } return buildNewTextArea; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T16:53:09.967", "Id": "10646", "Score": "2", "body": "Globals are never the best way to approach anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:23:20.280", "Id": "10647", "Score": "1", "body": "Don't do this with Strings: *buildNewTextArea += newBlock* in a loop. You should use a *StringBuilder* instead: it's more verbose but also much more efficient (you'll be generating way less garbage)." } ]
[ { "body": "<p>In the spirit of 'clean code', you should strive to make your methods as short as possible, and they should do only one thing.</p>\n\n<p>To start with, the following is a candidate for extracting into its own method</p>\n\n<pre><code> int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length());\n if (nextLineStart == -1) {\n nextLineStart = text.length();\n }\n</code></pre>\n\n<p>I would also be tempted to make the following class instance variables</p>\n\n<pre><code>String text = textArea.getText();\nint start = 0;\nint count = 0;\n</code></pre>\n\n<p>That should reduce a lot of the duplicated code you have, and the rest looks to be specific to each method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:10:47.960", "Id": "10648", "Score": "1", "body": "Disagree on the instance variable, you could run into thread-safety issues. Variables should be at the lowest possible scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:11:25.243", "Id": "10649", "Score": "0", "body": "Agree on the clean code. Anything that is duplicate could be moved to a method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:12:52.993", "Id": "10650", "Score": "0", "body": "Agreed, but the OP didn't mention anything about multi-threading. I don't think there's anything bad about using private class instance variables, after all they are limited in scope to the enclosing class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:15:39.437", "Id": "10651", "Score": "1", "body": "I will still stay with the rule that if a variable is never used outside a method (or its value does not need to be retained between method calls) it should be method-scope (the lowest possible scope). IMHO" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:19:27.010", "Id": "10652", "Score": "0", "body": "Fair comment. If the variable is very localised and only used in one place, then would be better as a method local." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:06:58.787", "Id": "6798", "ParentId": "6797", "Score": "1" } }, { "body": "<p>It seems like each method is iterating over the list of lines and doing something. It is the \"doing something\" that is unique. Consider having a single method that iterates over the lines and takes an interface to do the \"something\". For each method, an appropriate interface instance would be passed (possible anonymous inner class) that takes the appropriate action.</p>\n\n<p>Something like this:</p>\n\n<pre><code>private interface ProcessLine{\n void processLine(String line, int index, int charIndex);\n void complete();\n}\n\nprivate ProcessLine process(ProcessLine processor){\n String text = textArea.getText();\n int start = 0;\n int count = 0;\n String buildNewTextArea = \"\";\n int index = 0;\n while (start &gt;= 0) {\n int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length());\n if (nextLineStart == -1) {\n nextLineStart = text.length();\n }\n\n processor.processLine(line, count);\n index += buildNewTextArea.length();\n count++;\n start = text.indexOf(NEW_LINE, nextLineStart);\n }\n return processor;\n}\n\nprivate int getLineIndex(final int line) {\n int result = -1;\n return process(new ProcessLine(){\n public void processLine(String line, int index, int charIndex){\n if (index == line)\n result = charIndex;\n }\n });\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T17:12:59.783", "Id": "6799", "ParentId": "6797", "Score": "2" } }, { "body": "<p>Maybe this can help?</p>\n\n<pre><code>private static int getLineLength(String str, int line){\n return str.split(\"\\n\")[line].length(); //line start 0\n }\n private static String getLineContent(String str, int startLine, int endLine){\n String s = \"\";for(int i=startLine;i&lt;=endLine;i++){s +=str.split(\"\\n\")[i] ;}return s;\n }\n private static String insertBlock(String sourceStr, String insertStr, int startLine, int endLine){\n return getLineContent(sourceStr, 0, startLine).concat(insertStr).concat(getLineContent(sourceStr, endLine, sourceStr.split(\"\\n\").length-1)); \n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T18:44:35.610", "Id": "6801", "ParentId": "6797", "Score": "2" } } ]
{ "AcceptedAnswerId": "6801", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T16:50:13.820", "Id": "6797", "Score": "4", "Tags": [ "java" ], "Title": "Struggling to refactor code to remove duplication" }
6797
<p>I was wondering if someone could give some tips as to how improve long strings of if-else statements and redundant if statements. For example, how should I optimize this if statement so it would be more re-usable for maintenance purposes:</p> <pre><code> if (($game == 'DS' &amp;&amp; $eventId == 185) || ($game == 'MT' &amp;&amp; $eventId == 333) || ($game == 'HK' &amp;&amp; $eventId == 51) || ($game == 'main' &amp;&amp; $eventId == 1166) || ($game == 'WT' &amp;&amp; $eventId == 97)) { /* some code */ } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:23:07.533", "Id": "10654", "Score": "3", "body": "You could pair the `$game` and `$eventId` variables together as array members and then do a `if (in_array($game.$eventId, $matches)) blah...`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:24:36.577", "Id": "10655", "Score": "1", "body": "I tend to shove the data in an array and iterate over that. It's usually a little easier to read/edit/maintain, although it's probably a little slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:26:00.300", "Id": "10656", "Score": "1", "body": "Could you please be more specific in the use of the in_array function. Should I declare all of values of the the $game and $eventId variables into an array and then use the in_array function to match them up>" } ]
[ { "body": "<p>I would use the most laziest option possible. Use some string concatenation and a comparison list, as you only need to compare pairs anyway:</p>\n\n<pre><code>if (in_array(\"$game,$eventId\", array(\"DS,185\", \"MT,333\", \"HK,51\", \"main,1166\", \"WT,97\"))) {\n</code></pre>\n\n<p>See <a href=\"http://php.net/in_array\" rel=\"nofollow\"><code>in_array</code></a>. You could actually use real array pairs to compare against. But in this instance there's no need.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:33:11.033", "Id": "10657", "Score": "0", "body": "I type too slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:38:58.407", "Id": "10658", "Score": "0", "body": "Ha! I beats you! :} Yes, you put too much effort into the testcase. But I see now my `,` delimiter is redundant, in this case anyway, no ambiguity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:40:59.977", "Id": "10659", "Score": "0", "body": "Well, technically my comment under the question beat you by five minutes, but who's counting? `;)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:42:31.707", "Id": "10660", "Score": "1", "body": "It also occurred to me that an associative array could work just as well and possibly easier, `$matches = array('DS'=>185, ...);`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:43:38.837", "Id": "10661", "Score": "1", "body": "I just pretend I didn't notice that. Actually my first idea was `strstr(\"-DS,185-MT,333-HK,52-\", \"-$a,$b-\")`, but was afraid of the downvotes, so stole yours." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:45:47.850", "Id": "10662", "Score": "0", "body": "Add a jQuery version and you'll be a lock for that \"special\" badge." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:47:03.860", "Id": "10663", "Score": "0", "body": "Could I create $game and $eventId arrays as well once I create an associative array like Jared mentioned, then use the in_array function this way: `if (in_array($game.$eventId, $matches))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:51:22.873", "Id": "10664", "Score": "0", "body": "You would use `in_array(ARRAY($game, $eventId), ARRAY( array(1,2), array(3,4), array(5,6) ))` then. Note that the $matches list would be an array of two-element-array-pairs, and the needle would itself be an array pair, not just the concatenated string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:51:57.077", "Id": "10665", "Score": "0", "body": "@user1094886 - [This is how you could use an associative array](http://codepad.org/oCdFLDLo) to perform the check." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:52:53.010", "Id": "10666", "Score": "0", "body": "@user1094886: The associative array Jarred mentioned would be testable with simply `if ($matches[$game] == $eventId)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:53:13.370", "Id": "10667", "Score": "0", "body": "I think I'm starting to get it. Thanks a lot. You guys are good at this stuff!" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:27:43.423", "Id": "6803", "ParentId": "6802", "Score": "2" } }, { "body": "<p>This is one way you could do it:</p>\n\n<pre><code>&lt;?php\n\n$matches = array(\n 'DS' . 185,\n 'MT' . 333,\n 'HK' . 51,\n 'main' . 1166,\n 'WT' . 97\n);\n\nprint_r($matches);\n\n$game = 'DS';\n$eventId = '185';\n\nif (in_array($game.$eventId, $matches)) {\n echo \"You found a match: $game$eventId\\n\";\n} else {\n echo \"No match on: $game$eventId\\n\";\n}\n\n$game = 'MT';\n$eventId = '185';\n\nif (in_array($game.$eventId, $matches)) {\n echo \"You found a match: $game$eventId\\n\";\n} else {\n echo \"No match on: $game$eventId\\n\";\n}\n\n$game = 'main';\n$eventId = '1166';\n\nif (in_array($game.$eventId, $matches)) {\n echo \"You found a match: $game$eventId\\n\";\n} else {\n echo \"No match on: $game$eventId\\n\";\n}\n\n?&gt;\n</code></pre>\n\n<p><a href=\"http://codepad.org/jYGvuJxx\" rel=\"nofollow\">http://codepad.org/jYGvuJxx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T03:02:41.237", "Id": "10668", "Score": "0", "body": "Jared, isn't there another way to avoid declaring each $game and $eventId before an if-statement? Or does that mean I would have to create a `$game = array('MT', 'HK', etc)` and `$eventId = array(185, 333, etc)` and then use these two arrays for comparison purposes using an if-statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T03:06:02.567", "Id": "10669", "Score": "0", "body": "That was a demonstration; how you determine it in your actual script is up to you. You keep coming back to this idea that you need two different `array()`s, one for `$games` and one for `$eventId`, and at least in the context of the usage in the `if()` statement, I can't see it's necessary. If you use an associative array, you can always extract the keys and values to get a list, as well, if you need it for some *other* reason." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:32:15.167", "Id": "6804", "ParentId": "6802", "Score": "1" } }, { "body": "<p>Another way would be:</p>\n\n<pre><code>$eventId = $form_values['eventId'];\n$game = $form_values['game'];\n\n$games = array(\n 'DS' =&gt; 185), \n 'MT' =&gt; 333), \n 'HK' =&gt; 51), \n 'main' =&gt; 1166), \n 'WT' =&gt; 97)\n);\n\nif(isset($games[$game]) &amp;&amp; $games[$game] === $eventId) {\n /* some code */\n}\n</code></pre>\n\n<p>It is hard to tell without knowing where else you might be using the data. If your solution structure can match the real data for the problem then you will get the best result.</p>\n\n<p>I am guessing that games is more complex than just a link to an eventId. If it were more complex then it might look like this:</p>\n\n<pre><code>$games = array(\n 'DS' =&gt; array('eventId' =&gt; 185,\n 'otherData' =&gt; 'blah'),\n 'MT' =&gt; array('eventId' =&gt; 333,\n 'otherData' =&gt; 'nah')\n);\n\nif (isset($games[$game]['eventId']) &amp;&amp; $games[$game]['eventId'] === $eventId) {\n /* some code */\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-01T04:41:45.013", "Id": "335593", "Score": "0", "body": "This answer recommends the best data structure for the \"lookup\" array. An associative array is a logical choice to preserve the paired data in the simplest form. Concatenating the associated values to serve `in_array()` not only looks/feels hacky, in some fringe cases it can lead to inaccuracies. Paul's method is easy to read/comprehend and will be more welcome in a professional team setting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-01T04:43:23.117", "Id": "335594", "Score": "0", "body": "Alternatively, the conditional statement could be: `!!array_intersect_assoc($games,[$game=>$eventId])` or `!empty(array_intersect_assoc($games,[$game=>$eventId]))` if you wanted to make a single expression, but these would be less efficient than Paul's method and allow php to \"type juggle\" (which probably isn't an issue for this case). If this were my project, I'd be using Paul's method." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T01:52:11.410", "Id": "6815", "ParentId": "6802", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T02:20:20.727", "Id": "6802", "Score": "-2", "Tags": [ "php" ], "Title": "Matching pairs of game and event ID" }
6802
<p>Looking for the best way to do this. Currently in 4 different classes I have:</p> <pre><code>textArea = new JTextArea(10, 55) { { setOpaque(false); } @Override protected void paintComponent(Graphics g) { for (int i = 0; i &lt; list.size(); i++) { if(i == lineIndex) g.setColor(Color.black); g.drawRect(0, 20, 750, 20); } super.paintComponent(g); } }; </code></pre> <p>I've simplified down what I actually have. As you can see there is duplication. The only data that is different is what is in the <code>list</code>. A list is passed into each of these classes There are some other stuff in the class which depends on the textarea and the <code>lineIndex</code> variable changes in the class depending on what the user does. I call the repaint() method of the textarea when I need the textarea to draw something else. The paintcomponent does a simple draw.</p> <p>I'm not sure of the best way for each of the classes to contain the textarea so I dont have duplication. In each of the classes I have an addList(List list) method which the textareas need to use.</p> <p>Hope I explained this ok.</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T00:37:32.467", "Id": "10672", "Score": "0", "body": "Might help to have a little bit more of the code, but at the moment I don't see any reason you need to pass the list in (unless it changes size... with is problematic). Why not pass in the _size_ - immediate code reuse..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:19:38.003", "Id": "10687", "Score": "0", "body": "The content of each list is slightly different. I'm not sure what other code to put in. Maybe I could have a method in each class. Something like addTextAreaAndList(TextArea ta, List l)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T16:47:23.387", "Id": "10706", "Score": "0", "body": "I'm assuming the contents of the list were different. You haven't included any code where that's relevant or referenced, though. Yes, you reference the size, but unless I see something different, there's no reason you can't pass in the integer index, and avoid the whole loop anyways. Also, you probably want to move that call to `super.paintComponent()` to _before_ you paint the rectangle, as otherwise your painting will be 'behind' whatever the `super` call draws." } ]
[ { "body": "<p>Write your own class:</p>\n\n<pre><code>class MyTextArea extends JTextArea{\n\n private final List&lt;Foo&gt; list;\n\n MyTextArea(int row, int col, List&lt;Foo&gt; list) {\n super(row, col); \n this.list = list;\n setOpaque(false);\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n for (int i = 0; i &lt; list.size(); i++) {\n if(i == lineIndex) \n g.setColor(Color.black); \n g.drawRect(0, 20, 750, 20);\n //use list...\n }\n super.paintComponent(g);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T13:57:49.700", "Id": "6836", "ParentId": "6806", "Score": "6" } } ]
{ "AcceptedAnswerId": "6836", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T20:37:24.817", "Id": "6806", "Score": "7", "Tags": [ "java", "swing" ], "Title": "Refactoring code duplication so the same textArea is not used in 4 different classes" }
6806
<p>I have a function that moves circles out of the way of an expanding circle. It moves them along a ray from the center of the expanding circle through the center of the circle to move. This allows all surrounding circles to move without overlapping.</p> <p>Here's a diagram to better explain this:</p> <p><img src="https://i.stack.imgur.com/9Ixav.png" alt="circles"></p> <p>I expand the size of the red circle from 100px to 200px. I want to move all the blue circles out of the way by half the difference ( (200-100)/2 = 50px, in this example ) along the gray line (with the gray line being different for each blue circle).</p> <p><a href="http://jsfiddle.net/ThinkingStiff/uLu7v/" rel="nofollow noreferrer">jsFiddle</a></p> <pre><code>$this.siblings( ".circle" ).each( function() { var $this = $( this ), circle = $this.data(), circleX = circle.left + circle.radius, circleY = circle.top + circle.radius, a = Math.abs( hoveredY - circleY ), b = Math.abs( hoveredX - circleX ), c = Math.sqrt( ( a*a ) + ( b*b ) ), A = Math.acos( b / c ), C = 90 * ( Math.PI / 180 ), B = C - A, sinA = Math.sin( A ), sinB = Math.sin( B ), sinC = Math.sin( C ), newc = c + ( expand / 2 ), newa = ( newc * sinA ) / sinC, newb = ( newc * sinB ) / sinC, newX = hoveredX + ( hoveredX &gt; circleX ? -newb : newb ), newY = hoveredY + ( hoveredY &gt; circleY ? -newa : newa ), left = newX - circle.radius, top = newY - circle.radius; $this.animate( { "left": left, "top": top }, 75 ); }); </code></pre> <p><code>hoveredX</code> and <code>hoveredY</code> are the left and top coordinates of the red circle and <code>expand</code> is how much the red circle is expanding in pixels.</p> <p>Mathematically, I'm sure there is a better way to do this, but I got this way working, and it's fine (although I'm not opposed hearing better solutions). But the one part I don't like about this function are the two lines:</p> <pre><code>newX = hoveredX + ( hoveredX &gt; circleX ? -newb : newb ), newY = hoveredY + ( hoveredY &gt; circleY ? -newa : newa ), </code></pre> <p>What bugs me is that I'm having to do the check at all. Those two lines are basically saying, "If the circle is on the left/top do it one way, and if it's on the right/bottom do it another way". I feel like I'm missing something earlier in the function that could be solved by switching the sides of operators, adding instead of subtracting, or getting the absolute value.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T00:56:12.763", "Id": "10674", "Score": "0", "body": "`a = Math.abs(` is why you have to check. Are you sure you need absolute values?" } ]
[ { "body": "<p>I had two thoughts. One was ... You really only need an angle and a distance. The distance is the amount you expand and the angle can be derived from the x/y coordinates.</p>\n\n<p><a href=\"http://jsfiddle.net/uLu7v/38/\" rel=\"nofollow\">http://jsfiddle.net/uLu7v/38/</a></p>\n\n<p>first you calculate the angle:</p>\n\n<pre><code>var angle = Math.atan2(hoveredY - circleY, hoveredX - circleX);\n</code></pre>\n\n<p>Then you calculate the distance they move: </p>\n\n<pre><code>var topMove = ((expand /2 ) * Math.sin(angle)); // sin for Y\nvar leftMove = ((expand /2 ) * Math.cos(angle)); // cos for X\n</code></pre>\n\n<p>then use jQuery's built in animate <code>+=</code>:</p>\n\n<pre><code>$this.animate( { \n \"left\": \"-=\" + leftMove + \"px\",\n \"top\": \"-=\" + topMove + \"px\"\n}, 75 );\n</code></pre>\n\n<p>Tada!</p>\n\n<p><strong>Edit:-</strong> A couple of improvements in the code not supplied in the question:</p>\n\n<p>In <code>function inCircle()</code> change the return statement to <code>return (mouseDistance &lt;= radius);</code> Using the ternary operator to return a boolean? ... I'm sure it used to return some other values right?</p>\n\n<p>In <code>$( \".circle\" ).click(</code> :</p>\n\n<pre><code>if(!$( this ).data( \"clicked\" ) &amp;&amp; inCircle( $( this ), event.pageX, event.pageY ) ) {\n\n $( this ).data( \"clicked\", true );\n setLocations( this, 200, event );\n\n} else {\n\n resetLocations();\n $( this ).data( \"clicked\", false );\n\n};\n</code></pre>\n\n<p>Makes it cleaner but not a real improvement otherwise, more of a preference.</p>\n\n<p>In <code>function setLocations()</code> your circle parameter conflicts with the local circle variable. I would change the parameter to <code>circleElement</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T04:12:03.213", "Id": "10678", "Score": "0", "body": "WOW. I'm not worthy. 20 lines to 3. Up-vote this, people. My demo page gets a lot of hits. I put a link to your SO profile in there with credit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T04:37:51.970", "Id": "10679", "Score": "0", "body": "@ThinkingStiff thanks. Don't worry we all do this. It took me a couple of goes till i really sat back and thought about it. It happens that I was recently working on some angle/circle/distance stuff myself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T05:07:30.937", "Id": "10680", "Score": "0", "body": "@ThinkingStiff I just added some other suggestions for the rest of the code which don't really change a great deal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:13:05.610", "Id": "10715", "Score": "0", "body": "Both good changes, updated. Thanks. Who knows how I ended up at a ternary boolean. :) The `circle` in `setLocations()` was a last minute change I made to get ready for this post. It was called `hovered` or something nonintuitive before. Good catch." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T03:29:54.577", "Id": "6817", "ParentId": "6807", "Score": "3" } } ]
{ "AcceptedAnswerId": "6817", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T21:25:47.683", "Id": "6807", "Score": "3", "Tags": [ "javascript", "jquery", "computational-geometry" ], "Title": "Moving circles along a ray to eliminate location check" }
6807
<p>As of now, I am using this code to open a file and read it into a list and parse that list into a <code>string[]</code>:</p> <pre><code>string CP4DataBase = "C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt"; CP4DataBaseRTB.LoadFile(CP4DataBase, RichTextBoxStreamType.PlainText); string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\n'); List&lt;string&gt; tempCP4List = new List&lt;string&gt;(); string[] line1CP4Components; foreach (var line in splitCP4DataBaseLines) tempCP4List.Add(line + Environment.NewLine); string concattedUnitPart = ""; foreach (var line in tempCP4List) { concattedUnitPart = concattedUnitPart + line; line1CP4PartLines++; } line1CP4Components = new Regex("\"UNIT\",\"PARTS\"", RegexOptions.Multiline) .Split(concattedUnitPart) .Where(c =&gt; !string.IsNullOrEmpty(c)).ToArray(); </code></pre> <p>I am wondering if there is a quicker way to do this. This is just one of the files I am opening, so this is repeated a minimum of 5 times to open and properly load the lists.</p> <p>The minimum file size being imported right now is 257 KB. The largest file is 1,803 KB. These files will only get larger as time goes on as they are being used to simulate a database and the user will continually add to them.</p> <p>So my question is: is there a quicker way to do all of the above code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T14:31:27.063", "Id": "13410", "Score": "0", "body": "What are you trying to accomplish? Perhaps you are trying to replace one type of newlines with another? Or perhaps you want to read a text file into some more useful format (like objects?). Please give some sample input text also." } ]
[ { "body": "<p>If i read this correctly you are reading in some text with newline characters, Splitting on new line characters, adding new line characters back in and then concatenation the lines back together?</p>\n\n<p>why not instead:</p>\n\n<pre><code>CP4DataBaseRTB.Text.Replace('\\n', Environment.NewLine);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T02:08:00.930", "Id": "6816", "ParentId": "6808", "Score": "2" } }, { "body": "<p>The part of the code that makes it really slow is this:</p>\n\n<pre><code>string concattedUnitPart = \"\";\nforeach (var line in tempCP4List)\n{\n concattedUnitPart = concattedUnitPart + line;\n line1CP4PartLines++;\n}\n</code></pre>\n\n<p>You should not concatenate large strings like that. The string gets longer and longer for each iteration, and it's copied into a new string each time.</p>\n\n<p>If you Read a file that is 1.8 MB, that consists of lines which varies between 50 and 100 characters, you will have been copying about 10 000 MB of data before you have the result.</p>\n\n<p>Also, it scales very badly, so when the files grow it will grow slower at an exponential rate. To handle a file that is 5 MB you will be copying about 80 000 MB of data.</p>\n\n<p>James suggestion to do a replace seems to be a good option. If you want to split and join, you can use the <code>String.Join</code> method:</p>\n\n<pre><code>string[] splitCP4DataBaseLines = CP4DataBaseRTB.Text.Split('\\n');\nstring concattedUnitPart = String.Join(Environment.NewLine, splitCP4DataBaseLines) + Environment.NewLine;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T06:08:52.190", "Id": "10681", "Score": "5", "body": "Another option is to use a `StringBuilder` to build up `concattedUnitPart`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T04:57:44.257", "Id": "10727", "Score": "0", "body": "Why would you split a string and the next line stick it all back together again? isn't that like my niece who cuts paper so she can sticky tape it together again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T06:20:53.257", "Id": "10730", "Score": "1", "body": "@JamesKhoury: I don't know, possibly if you want the option to do something to each line in between. I just wanted to show that there is a short and efficient way of doing that too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T04:45:19.520", "Id": "6819", "ParentId": "6808", "Score": "5" } }, { "body": "<p>There are a few points I would make on this - some with regards to performance and some simply regarding better coding practices.</p>\n\n<p>First off, when hard coding a file path and when you don't require any escape characters, it is easier to simply declare the string with a prefixed '@'. This means you don't need to escape your backslash characters.</p>\n\n<pre><code>string CP4DataBase = @\"C:\\Program\\Line Balancer\\FUJI DB\\KTS\\KTS - CP4 - Part Data Base.txt\";\n</code></pre>\n\n<p>Next, where you have constructed <code>tempCP4List</code>, you could have taken two alternate approaches. The first makes use of the <a href=\"http://msdn.microsoft.com/en-us/library/dw8e0z9z.aspx\" rel=\"nofollow\"><code>capacity</code> constructor parameter</a> or the <a href=\"http://msdn.microsoft.com/en-us/library/y52x03h2.aspx\" rel=\"nofollow\"><code>List&lt;string&gt;.Capacity</code> property</a>, which explicitly specifies the initial size of the <code>List</code>. This is useful as when building a list using <code>Add()</code>, if the contents of the list exceeds the capacity, a new array will be created within the <code>List</code> to accommodate the new element. When working with large collections of data, this could cause an issue with performance. So here, I would use:</p>\n\n<pre><code>List&lt;string&gt; tempCP4List = new List&lt;string&gt;(splitCP4DataBaseLines.Length);\n</code></pre>\n\n<p><strong>- or -</strong></p>\n\n<pre><code>List&lt;string&gt; tempCP4List = new List&lt;string&gt;();\ntempCP4List.Capacity = splitCP4DataBaseLines.Length;\n</code></pre>\n\n<p>Alternately, you could use LINQ to build the list straight away, using:</p>\n\n<pre><code>List&lt;string&gt; tempCP4List = new List&lt;string&gt;(splitCP4DataBaseLines.Select(line =&gt; line + Environment.NewLine));\n</code></pre>\n\n<p>Another point, which has already been mentioned by Guffa is concatenating strings in the way you have with <code>concattedUnitPart = concattedUnitPart + line;</code> is a very memory-hungry process. In this case, both Guffa and Anna Lear have made good points with regards to using <a href=\"http://msdn.microsoft.com/en-us/library/57a79xd0.aspx\" rel=\"nofollow\"><code>string.Join(...)</code></a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx\" rel=\"nofollow\"><code>StringBuilder</code></a>. If you run a small test program with large amounts of string data, you will see just how drastic a performance improvement this can deliver.</p>\n\n<p>Finally, where you have performed your final string split, you have also used the LINQ extension method to check for empty strings. There is no need to do this, as it is an option that you can specify in the <a href=\"http://msdn.microsoft.com/en-us/library/tabh47cf.aspx\" rel=\"nofollow\"><code>string.Split(...)</code></a> method. So you would instead write the final line as:</p>\n\n<pre><code>line1CP4Components = new Regex(\"\\\"UNIT\\\",\\\"PARTS\\\"\", RegexOptions.Multiline)\n .Split(new string[1] { concattedUnitPart }, StringSplitOptions.RemoveEmptyEntries);\n</code></pre>\n\n<p>Notice the use of the <a href=\"http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx\" rel=\"nofollow\"><code>StringSplitOptions.RemoveEmptyEntries</code> option</a>. This tells the <code>string.Split(...)</code> method to do exactly what your <code>Where(...)</code> clause does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T08:39:27.220", "Id": "6822", "ParentId": "6808", "Score": "2" } }, { "body": "<p>Here my 5 cents to all answers. When you use regular expression more than once it always helps to declare your regular expression as a field with Compiled option:</p>\n\n<pre><code>private static readonly Regex splitRegex = new Regex(\"\\\"UNIT\\\",\\\"PARTS\\\"\", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:34:13.630", "Id": "6827", "ParentId": "6808", "Score": "1" } } ]
{ "AcceptedAnswerId": "6819", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T21:29:11.037", "Id": "6808", "Score": "2", "Tags": [ "c#", "parsing" ], "Title": "Speedily Read and Parse Data" }
6808
<p>I've not written many shell scripts and cobbled this together from examples. The 'if' condition should check if this is already running and quite if so. The 'wget' call should trigger the php page and write any output to a txt file. The script will be launched by cron. Is this a reasonable approach?</p> <pre><code>#!/bin/sh if ps -ef | grep -v grep | grep "dev.mydomain.biz/system_processdata.php" ; then exit 0 else wget -q -O /tmp/system_processimport.txt http://dev.mydomain.biz/system_processdata.php?a=37&amp;b=61 exit 0 fi </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:29:28.870", "Id": "10717", "Score": "1", "body": "You might do better to look into `pidof` or `psgrep` rather than parsing the output of `ps`, to avoid potential false positives … ?" } ]
[ { "body": "<p>You should protect the URL with quotation marks since <code>&amp;</code> is a control operator:</p>\n\n<pre><code>wget -q -O /tmp/out.txt \"http://dev.mydomain.biz/system_processdata.php?a=37&amp;b=61\"\n</code></pre>\n\n<p>Furthermore, prevent concurrent calls on the server (PHP) side, it should be the server's responisibility.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:23:32.583", "Id": "6853", "ParentId": "6810", "Score": "0" } }, { "body": "<p>You should protect the URL with double quotes to prevent the shell from parsing the <code>=</code>, <code>?</code>, and <code>&amp;</code> as being special instead of just plain old characters.</p>\n\n<p>Also, as a minor nitpick, you should use <code>fgrep</code> because <code>grep</code> will treat the <code>.</code> characters as being 'match any character' and not as a literal <code>.</code>. <code>fgrep</code> treats the whole string it's searching for (except for <code>\\n</code>) as literal. But this is unlikely to cause you problems in practice.</p>\n\n<p>The programmer in me shudders at this approach because so many things <em>could</em> potentially go wrong. In practice, they almost certainly won't. But I've learned to never, ever write programs as if the things I think should never happen never will. Because, in practice, they almost all do eventually.</p>\n\n<p>For example, if you ever try to do two different fetches with different parameters at the same time, one will mysteriously not happen.</p>\n\n<p>Also, if some random person happens to have put that URL on the command line for something, that will cause the script to not do anything until whatever command it is finishes.</p>\n\n<p>As I said, these may or may not be serious problems. But I would be aware of them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T01:29:50.760", "Id": "6857", "ParentId": "6810", "Score": "1" } } ]
{ "AcceptedAnswerId": "6857", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T22:37:29.367", "Id": "6810", "Score": "2", "Tags": [ "php", "bash", "shell" ], "Title": "Shell script: is it doing what I think it's doing" }
6810
<p>Having been through hundreds of often-conflicting posts on testing with <em>RSpec</em>, <em>Capybara</em>, <em>FactoryGirl</em>, <em>Spork</em>, <em>Guard</em> and <em>Devise</em> without Cucumber, this is the spec_helper which "seems to" work.</p> <p>I'm bracing for it to blow up or not work like the previous attempts.</p> <p>Here's my <a href="https://gist.github.com/1472169" rel="nofollow"><strong>spec_helper.rb</strong></a></p> <p>Questions:</p> <ol> <li>Is there something in it likely to cause trouble?</li> <li>Are there inefficiencies? Anything which ought to be done better?</li> </ol> <p></p> <pre><code>require 'rubygems' require 'spork' def start_simplecov require 'simplecov' SimpleCov.start 'rails' unless ENV["SKIP_COV"] end def spork? defined?(Spork) &amp;&amp; Spork.using_spork? end def simplecov? defined?(SimpleCov) &amp;&amp; SimpleCov.using_simplecov? end def setup_environment # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' start_simplecov unless (spork? || !simplecov?) if spork? ENV['DRB'] = 'true' # require "rails/mongoid" # Spork.trap_class_method(Rails::Mongoid, :load_models) require "rails/application" Spork.trap_method(Rails::Application::RoutesReloader, :reload!) end require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' # require 'rspec/autorun' require 'capybara/rails' require 'capybara/rspec' Capybara.default_host = 'http://localhost' Capybara.server_port = 3000 include Capybara::DSL require 'factory_girl_rails' # FactoryGirl.factories.clear # FactoryGirl.find_definitions Rails.backtrace_cleaner.remove_silencers! require 'database_cleaner' # DatabaseCleaner.orm = "mongoid" DatabaseCleaner.strategy = :truncation Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| config.mock_with :rspec # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures # config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.clean end # config.include Mongoid::Matchers config.include Devise::TestHelpers, :type =&gt; :controller config.extend ControllerMacros, :type =&gt; :controller config.include FactoryGirl::Syntax::Methods Capybara.javascript_driver = :rack_test # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false end end def each_run if spork? # FactoryGirl.definition_file_paths = [File.join(Rails.root, 'spec', 'factories')] # FactoryGirl.find_definitions # FactoryGirl.reload Pollsrv::Application.reload_routes! FactoryGirl.factories.clear Dir.glob("#{::Rails.root}/spec/factories/*.rb").each { |file| load "#{file}" } end # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. end # If spork is available in the Gemfile it'll be used but we don't force it. unless (begin; require 'spork'; rescue LoadError; nil end).nil? Spork.prefork do # Loading more in this block will cause your tests to run faster. However, # if you change any configuration or code from libraries loaded here, you'll # need to restart spork for it take effect. setup_environment ActiveSupport::Dependencies.clear # Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} end Spork.each_run do # This code will be run each time you run your specs. each_run end else # Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} setup_environment each_run end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T20:44:53.243", "Id": "225743", "Score": "1", "body": "A lot of this seems unnecessary. Many portions of this are done in the background, by the various libraries. Here's what mine looks like: https://gist.github.com/1409074#file_spec_helper.rb" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T13:53:48.643", "Id": "6812", "Score": "7", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "spec_helper.rb for RSpec, Capybara, FactoryGirl, Spork and Devise" }
6812
<p>Here is a small script I wrote to get the HNews ask section and display them without using a web browser. I'm just looking for feedback on how to improve my style/coding logic/overall code.</p> <pre><code>#!/usr/bin/python '''This script gets the headlines from hacker news ask section''' import urllib2 import HTMLParser import re class HNParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.data=[] self.recording=0 def handle_starttag(self, tag, attribute): if tag!='a': return elif self.recording: self.recording +=1 return for name, value in attribute: if name=='href' and value[0]=='i': break else: return self.recording=1 def handle_endtag(self, tag): if tag=='a' and self.recording: self.recording-=1 def handle_data(self, data): if self.recording: self.data.append(data) HOST='http://news.ycombinator.com/ask' parser=HNParser() f=urllib2.urlopen(HOST) rawHTML=f.read() parser.feed(rawHTML) i=0 for items in parser.data: try: print parser.data[2*i] i+=1 except IndexError: break parser.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T00:53:22.533", "Id": "10673", "Score": "0", "body": "You'll almost definitely get someone who points out that your indenting is incorrect ... wait that was me! Just check the preview before you submit it so that the code section looks the same as your file." } ]
[ { "body": "<p>This is how I would modify your script. Comments are inline. This version is PEP8-PyLint-PyFlakes approved. ;-)</p>\n\n<pre><code>#!/usr/bin/python\n\n'''This script gets the headlines from hacker news ask section'''\n\nimport urllib2\nimport HTMLParser\n# remove unused imports\n\n\nclass HNParser(HTMLParser.HTMLParser):\n\n # use class-level attribute instead of \"magic\" strings.\n tag_name = 'a'\n\n def __init__(self):\n HTMLParser.HTMLParser.__init__(self)\n self.data = []\n self.recording = 0\n\n def handle_starttag(self, tag, attribute):\n\n if tag != self.tag_name:\n return\n\n # clearer implicit loop, with no \"break\"\n if not any(name == 'href' and value.startswith('item')\n for name, value in attribute):\n return\n\n # no need to check if self.recording == 0, because in that case setting\n # self.recording = 1 is equivalent to incrementing self.recording!\n self.recording += 1\n\n def handle_endtag(self, tag):\n if tag == self.tag_name and self.recording:\n self.recording -= 1\n\n def handle_data(self, data):\n if self.recording:\n self.data.append(data)\n\n\ndef main():\n HOST = 'http://news.ycombinator.com/ask'\n parser = HNParser()\n f = urllib2.urlopen(HOST)\n rawHTML = f.read()\n parser.feed(rawHTML)\n try:\n # use fancy list indexing and omit last \"Feature Request\" link\n for item in parser.data[:-1:2]:\n print item\n finally:\n # close the parser even if exception is raised\n parser.close()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-14T20:22:46.440", "Id": "22115", "Score": "0", "body": "I’m not convinced that the generic `tag_name` is more readable than `'a'`, on the contrary. I’m all for using an attribute here, but give it a proper name. The context suggets that it should be called `starttag` – or maybe `linktag`. Also, the `try … finally: parser.close()` should be replaced with a `with` block." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:31:04.650", "Id": "7085", "ParentId": "6813", "Score": "1" } }, { "body": "<p>Instead of <code>HTMLParser.HTMLParser.__init__(self)</code> you should write <code>super(HTMLParser.HTMLParser, self).__init__()</code></p>\n\n<p><code>urllib2</code> and <code>HTMLParser</code>, though included with Python, are very limited. <a href=\"http://docs.python-requests.org/en/latest/\" rel=\"nofollow\">requests</a> and <a href=\"http://lxml.de/cssselect.html\" rel=\"nofollow\">lxml + cssselect</a> are more powerful. With them, your script can be written as</p>\n\n<pre><code>import requests\nfrom lxml.html import fromstring\ncontent = requests.get('https://news.ycombinator.com/ask').content\nhtml_doc = fromstring(content)\n# Select all title links &amp; ignore \nlinks = html_doc.cssselect('.title &gt; a[href^=item]')\nprint '\\n'.join(link.text for link in links)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T11:17:14.293", "Id": "47054", "ParentId": "6813", "Score": "0" } } ]
{ "AcceptedAnswerId": "7085", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T23:41:06.660", "Id": "6813", "Score": "2", "Tags": [ "python", "web-scraping" ], "Title": "HNews \"ask section\" page scraping Python script" }
6813
<p>I have a piece of code that get errors from form and display to view:</p> <pre><code>$errors = $form-&gt;getMessages(); $msg = ''; foreach ($errors as $error) { foreach ($error as $err) { $msg .= $err . '&lt;br/&gt;'; } } $this-&gt;view-&gt;error_message = $msg; </code></pre> <p>It look so ugly, but now I don't have any ideas to improve it. Thank for help.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T17:32:53.840", "Id": "10709", "Score": "1", "body": "No way to use less foreach loop and get it cleaner." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T00:56:00.303", "Id": "10725", "Score": "1", "body": "It is impossible to tell without knowing the exact structure of $errors." } ]
[ { "body": "<p>Im assuming your $errors array looks like this:</p>\n\n<pre><code>$errors = array(array('message 1'), array('message 2'), array('message 3'));\n</code></pre>\n\n<p>Then you could use something like this:</p>\n\n<pre><code>$msg = '';\nforeach($errors as $inner) {\n $msg .= current($inner) . '&lt;br /&gt;';\n}\necho $msg;\n// message 1&lt;br /&gt;message 2&lt;br /&gt;message 3&lt;br /&gt;\n</code></pre>\n\n<p>I dont know if its more efficient than the 2 foreach loops though.</p>\n\n<p>On the other hand I personally would look into modifying the getMessages() mehtod so that it returns a single array and not a multidimensional one. With a single array you just need to implode it with a 'br' :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T15:43:04.390", "Id": "10703", "Score": "0", "body": "by using current() it not get all $error in $errors :(" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T15:38:21.550", "Id": "6840", "ParentId": "6818", "Score": "2" } }, { "body": "<p>Given errors like this:</p>\n\n<pre><code>$errors = array(array('message 1a','message 1b'), array('message 2'), array('message 3'));\n</code></pre>\n\n<p>I you could make a function that can call itself to account for the nested arrays.</p>\n\n<pre><code>function showErrors($errors) {\n foreach ($errors as $error) {\n $msg .= (is_array($error))? showErrors($error) : $error.'&lt;br/&gt;';\n }\n return($msg);\n}\n$msg = showErrors($errors);\n</code></pre>\n\n<p>Not sure it's cleaner, but it may be more versatile. This will accommodate deeper nested arrays should the need arise. If possible, I like Pratt's suggestion of supplying a single array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T16:52:49.300", "Id": "6843", "ParentId": "6818", "Score": "1" } }, { "body": "<p>You can use array_merge to reduce the array from 2-dim to 1-dim, then implode the array.</p>\n\n<pre><code>$this-&gt;view-&gt;error_message = \n implode(array_reduce($form-&gt;getMessages(),\n \"array_merge\", \n array()),\n \"&lt;br/&gt;\");\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.array-merge.php\">http://php.net/manual/en/function.array-merge.php</a></p>\n\n<p><a href=\"http://www.php.net/manual/en/function.array-reduce.php\">http://www.php.net/manual/en/function.array-reduce.php</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T19:11:23.423", "Id": "6846", "ParentId": "6818", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T03:30:37.367", "Id": "6818", "Score": "2", "Tags": [ "php", "error-handling", "form", "zend-framework" ], "Title": "Collecting form errors to be displayed" }
6818
<p>This code will be used to map a set of unique keys to a container of objects that are unique to that key. I would like to be able to reuse this code in future projects hence the template, and not hard coding the types into the class. You can also access the code <a href="http://matthewh.me/scripts/browser/c++/c++_io/stl_file_io" rel="nofollow">here</a>.</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;set&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include "file_to_map.h" int main(int argc, char *argv[]) { file_to_map&lt;std::string, std::multiset&lt;std::string&gt; &gt; ftm("opengl_functions"); std::ifstream ifs; ifs &lt;&lt; ftm; std::cout &gt;&gt; ftm; return 0; } </code></pre> <p><strong>file_to_map.h</strong></p> <pre><code>#ifndef FILE_TO_MAP_H_ #define FILE_TO_MAP_H_ #include &lt;map&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; template &lt;class T&gt; struct print { print(std::ostream &amp;out) : os(out) {} void operator() (T x) { os &lt;&lt; x &lt;&lt; ' ' &lt;&lt; std::endl; } std::ostream &amp; os; }; template &lt;class key, class container&gt; class file_to_map { public: file_to_map() { m_file = ""; } file_to_map(std::string file) { m_file = file; } ~file_to_map() { } std::map&lt;key, container&gt;&amp; getMap() { return m_map; } friend std::ostream&amp; operator&gt;&gt; (std::ostream &amp;out, file_to_map&lt;key, container&gt; &amp;obj) { typedef typename std::map&lt;key, container&gt;::const_iterator mapItr; mapItr mbi = obj.m_map.begin(); mapItr emi = obj.m_map.end(); while (mbi != emi) { out &lt;&lt; " -- " &lt;&lt; mbi-&gt;first &lt;&lt; " -- " &lt;&lt; std::endl; ++mbi; } return out; } friend std::istream&amp; operator&lt;&lt; (std::ifstream &amp;in, file_to_map&lt;key, container&gt; &amp;obj) { if (in.is_open()) in.close(); if (obj.m_file == "") return in; in.open(obj.m_file.c_str(), std::ios::in); if (in.fail() || in.bad()) { in.close(); return in; } std::vector&lt;key&gt; tmp; typedef std::istream_iterator&lt;key&gt; string_input; copy(string_input(in), string_input(), back_inserter(tmp)); typename std::vector&lt;key&gt;::iterator bvi = tmp.begin(); typename std::vector&lt;key&gt;::iterator evi = tmp.end(); while (bvi != evi) { obj.m_map[*(bvi)] = container(); ++bvi; } in.close(); return in; } private: std::map&lt;key, container&gt; m_map; std::string m_file; }; #endif//FILE_TO_MAP_H_ </code></pre> <p><strong>Makefile</strong></p> <pre><code>file_to_map : file_to_map.h main.cpp g++ -o file_to_map -Wall ./file_to_map.h ./main.cpp </code></pre>
[]
[ { "body": "<p>For one thing, you have operators <code>&lt;&lt;</code> and <code>&gt;&gt;</code> reversed for the streams.</p>\n\n<p>I wouldn't recommend overloading ifstream operator, at least not like this. <code>operator&gt;&gt;</code> does not normally open and close files, it reads a value from an already open stream. Basically your class is just asking the caller to provide what the class could create itself. Neither would chaining this operator use do any good, because the returned stream is not good anyway.</p>\n\n<p>Personally I think that <code>operator&gt;&gt;</code> should either be able to parse what <code>operator&lt;&lt;</code> outputs, or it shouldn't be implemented at all.</p>\n\n<p>The constructor itself should load the file and/or the class should provide a named method for loading a file.</p>\n\n<hr>\n\n<p>As to populating the map keys, is it really necessary to put the keys in a vector first?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T17:33:28.643", "Id": "6844", "ParentId": "6821", "Score": "2" } }, { "body": "<p>The main issue I see here is that you are loading in a map from a file and I see you load in the keys but cannot see anywhere where you load in the values.</p>\n\n<p>Loading in all the keys first isn't necessarily a bad idea, and if you do it that way then you do need to use a vector or similar container as a temporary container (so you retain the order when you read in the values).</p>\n\n<p>Unless you already have files in your file system that you need to load into a map, and you can't change these files, then I would take a somewhat different approach for a \"generic\" map read (and write). For example if you have a function to read a vector then you can use that also to read the map (by reading all the keys) then again to read the values. Note that these cannot read until \"end of stream\" (well particularly the key-reader cannot) so there must be a special marker to determine where these end, or a header section so you know how far to read.</p>\n\n<p>Once you have determined how the layout is going to be, then write the code for it. I would suggest you make this section use a generic \"stream\" rather than a file as such.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-18T18:04:32.210", "Id": "7933", "ParentId": "6821", "Score": "0" } } ]
{ "AcceptedAnswerId": "6844", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T07:35:57.297", "Id": "6821", "Score": "2", "Tags": [ "c++", "hash-map" ], "Title": "File to map class" }
6821
<p>This is a follow-on from a previous question I posted <a href="https://stackoverflow.com/questions/8403069/looking-to-select-an-undetermined-number-of-rows-in-excel-as-part-of-larger-vba">here</a>.</p> <p>I've got code here that works for what I want, but the problem is the loop takes ages to perform. I was wondering if anyone could follow this and tidy it up a bit for me.</p> <pre><code>Sub Refresh_Data() Application.CutCopyMode = False 'Turns screen updating off to increase speed Application.ScreenUpdating = False 'Get 'G/L Account numbers Sheet1 = "BW TB" Sheets(Sheet1).Activate Range("A1").Activate 'Find last row - always named "Overall Result" in ColA Cells.Find(What:="Overall Result", After:=ActiveCell, LookIn:=xlFormulas, LookAt _ :=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _ True, SearchFormat:=False).Activate 'This looks up to row 25 (title row), but adjusts to only copy data from row 26 down to the penultimate row (the subtotal is not required) lastrow = Selection.Row - 1 colno = Selection.Column firstrow = Selection.End(xlUp).Row + 1 'CopyPaste loop 'First sheet is titled "4020" i = Sheets("4020").Index 'Due to all the sheet names being numeric. This is a slight workaround. 'It basically runs the macro starting at the 4020 sheet and ending at the last sheet with a numeric sheets. 'i.e. pastes values for all numbered tabs. Do While IsNumeric(Sheets(i).Name) = True 'clear all formulae except first formulaic row (Row5) Sheets(i).Activate Range("A6").EntireRow.Select Range(Selection, Selection.Offset(1000, 0)).ClearContents 'Copy G/L Account numbers from BW TB sheet to current sheet Sheets(BWTB).Activate Range(Cells(firstrow, colno), Cells(lastrow, colno)).Copy Sheets(i).Activate Range("a5").PasteSpecial xlPasteValues 'Copy down formulae Range("B5:L5").Copy Range("B5:L5", Range("B5:L5").Offset(lastrow - firstrow, 0)).PasteSpecial xlPasteFormulas ActiveSheet.Calculate 'Paste As Values Range("B6:L6", Range("B6:L6").Offset(lastrow - firstrow, 0)).Copy Range("B6").PasteSpecial xlPasteValues i = i + 1 Loop End Sub </code></pre> <p>The scenario is about 25 'numericlly named' sheets (eg 4020) for which I need to first clear (this is for a rolling document updated periodically with a differing number of rows required, the determine the number of rows, then copy-pastespecial data from an unformatted mastersheet (BW TB).</p> <p>Apologies for the mess it's in. I'm in the process of breaking up the code into more sub functions for easier reading.</p>
[]
[ { "body": "<p>You should <strong>clean up every <code>Select</code> and <code>Activate</code></strong> and use <strong>objects</strong> instead</p>\n\n<p>You'd better use the <strong>object model</strong> of VBA.<br>\nFor instance, if you only want to copy the <em>value</em> of a cell:</p>\n\n<p><strong>Don't do</strong></p>\n\n<pre><code>Range(\"A1\").Select\nSelection.Copy\nRange(\"A2\").Select\nSelection.Paste\n</code></pre>\n\n<p><strong>Do</strong></p>\n\n<pre><code>Range(\"A2\").Value = Range(\"A1\").Value\n</code></pre>\n\n<p>Another example:</p>\n\n<p><strong>Don't do</strong></p>\n\n<pre><code>Cells.Find(...).Activate\nlastrow = Selection.Row - 1\ncolno = Selection.Column\nfirstrow = Selection.End(xlUp).Row + 1\n</code></pre>\n\n<p><strong>Do</strong></p>\n\n<pre><code>Dim mycell as Range\nSet cell = Cells.Find(...)\nlastrow = mycell .Row - 1\ncolno = mycell .Column\nfirstrow = mycell .End(xlUp).Row + 1\n</code></pre>\n\n<p>And so on, especially on your <code>Sheet</code> objects.</p>\n\n<h3>Example to copy-paste between sheets</h3>\n\n<p>You only have to adapt this kind of statement to your specific case:</p>\n\n<pre><code>Worksheets(\"Sheet1\").Range(\"A1\").Copy\nWorksheets(\"Sheet2\").Range(\"A2\").PasteSpecial xlPasteFormulas\n</code></pre>\n\n<h3>Other tips</h3>\n\n<p>You can also have a look at the very good website of <a href=\"http://www.cpearson.com/excel/optimize.htm\" rel=\"nofollow\">Chip Pearson</a></p>\n\n<h3>Edit</h3>\n\n<p>Instead of:</p>\n\n<pre><code>Sheets(i).Activate\nRange(\"A6\").EntireRow.Select\nRange(Selection, Selection.Offset(1000, 0)).ClearContents\n</code></pre>\n\n<p>You can try:</p>\n\n<pre><code>Dim lastCol as Long\nWith Sheets(i)\n lastCol = .Cells(6, .Columns.Count).End(xlToLeft).Column\n .Range(\"A6\", .Cells(1000, lastCol)).ClearContents\nEnd With\n</code></pre>\n\n<p>This will find the last column where you have data (so that you don't have to clear contents of the entire row) on the 6th row and then it will clear the content of the Range between A6 and the last column and the 1000th row.</p>\n\n<h3>Another edit</h3>\n\n<p>You also have a <em>minor</em> issue in your declaration part.</p>\n\n<p>This:</p>\n\n<pre><code>Dim mycell As Range, LastRow, ColNo, FirstRow, i As Integer\n</code></pre>\n\n<p>doesn't work, you have to do:</p>\n\n<pre><code>Dim mycell As Range, LastRow As Integer, ColNo As Integer, FirstRow As Integer, i As Integer\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:07:27.207", "Id": "10695", "Score": "1", "body": "+1. Very good advice. I think you meant `Set mycell = Cells.Find(...) ` which can then be tested for a valid result before proceeding, ie `If Not mycell is Nothing Then` etc" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T11:55:49.920", "Id": "10746", "Score": "0", "body": "Thanks for the tips! re: the edit, that code clears the \"BW TB\" masterdata tab also, which is odd :S" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T12:32:23.523", "Id": "10747", "Score": "0", "body": "Then, you'd better check this statement: `IsNumeric(Sheets(i).Name)` in debug to see what is wrong. If the name of your master tab is \"BW TB\", the code shouldn't get executed. Unless the `Do While` execute the first loop before testing (maybe you should try with a `for loop`?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:08:03.917", "Id": "10751", "Score": "0", "body": "Tried it with a for loop and get the same issue. Will report back if I find a solution :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:22:38.993", "Id": "10756", "Score": "0", "body": "Have a look in debug about the `Sheets(i).Name` and see why `IsNumeric(Sheets(i).Name)` is True, this is probably part of your issue. Btw, you could now ask a new question on SO with your issue (and the new code) - don't forget to tell us the sheets' name" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:40:35.180", "Id": "10760", "Score": "0", "body": "Done :) link is here: http://stackoverflow.com/questions/8522646/need-help-correcting-a-with-statement-inside-a-subroutine-nested-within-a-loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-18T19:59:40.833", "Id": "17477", "Score": "1", "body": "@JMax While the last line about `Dim`ing should be fixed, it's not correct to say `Dim mycell As Range, LastRow, ColNo, FirstRow, i As Integer` \"**doesn't work**\". It does, it's just that those unspecified variables will default to the Variant type." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T09:49:41.067", "Id": "6833", "ParentId": "6823", "Score": "7" } }, { "body": "<p>This may be solved by disabling Screen Update while the code is running.</p>\n\n<ol>\n<li><p>Add the following line of code just after Sub Refresh_Data()</p>\n\n<pre><code>Application.ScreenUpdating = False\n</code></pre></li>\n<li><p>Add the following code just before End Sub (Add just before End Sub not in loop)</p>\n\n<pre><code>Application.ScreenUpdating = True\n</code></pre></li>\n<li><p>Remove the line ActiveSheet.Calculate</p></li>\n</ol>\n\n<p>This may help. Have a try.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:03:03.873", "Id": "10696", "Score": "0", "body": "That is already in the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:12:18.867", "Id": "10697", "Score": "0", "body": "@brettdj: Yes he has included Application.Screenupdating = False and he uses ActiveSheet.Calculate in the end instead of enabling Screen updating. I am not sure but recalculating the entire sheet in a loop may be making the code slow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T10:49:46.787", "Id": "6834", "ParentId": "6823", "Score": "6" } }, { "body": "<p><strong>First</strong>, since you have a <code>ActiveSheet.Calculate</code>, did you turn calculation Off before running the macro ? This <em>might</em> be the easiest and biggest improvement. </p>\n\n<p><strong>Second</strong> you can replace: </p>\n\n<pre><code>'clear all formulae except first formulaic row (Row5)\nSheets(i).Activate\nRange(\"A6\").EntireRow.Select\nRange(Selection, Selection.Offset(1000, 0)).ClearContents\n</code></pre>\n\n<p>by:</p>\n\n<pre><code>sheets(i).range(6:1006).clearcontents\n</code></pre>\n\n<p><strong>Third</strong>, you could replace:</p>\n\n<pre><code>'Copy G/L Account numbers from BW TB sheet to current sheet\nSheets(BWTB).Activate\nRange(Cells(firstrow, colno), Cells(lastrow, colno)).Copy\n\nSheets(i).Activate\nRange(\"a5\").PasteSpecial xlPasteValues\n</code></pre>\n\n<p>by:</p>\n\n<pre><code>'Copy G/L Account numbers from BW TB sheet to current sheet\nwith Sheets(BWTB)\n Range(.Cells(firstrow, colno), .Cells(lastrow, colno)).Copy\nend with\nSheets(i).Range(\"a5\").PasteSpecial xlPasteValues\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T12:24:29.387", "Id": "10699", "Score": "0", "body": "The first point does make a big difference, thanks! I'm just debugging points 2 and 3 as VBA isnt happy with either of them right now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:04:10.033", "Id": "6835", "ParentId": "6823", "Score": "7" } }, { "body": "<p><strong>Introduction</strong></p>\n\n<p>The other answers have merit but perhaps not as much merit as the posters think.</p>\n\n<p>I have had the problem of a routine taking much, much longer than expected for no obvious reason on a number of occasions. I would change things around and the problem would disappear but it was never clear what I had done to fix the problem. My best theory was it was something to do with moving rows from one worksheet to another. I promised myself that one day I would investigate this systematically. Chris's problem seemed relatively clean so perhaps this was the opportunity I was seeking.</p>\n\n<p><strong>Summary</strong></p>\n\n<p>With one exception, bad practice in the way worksheets are accessed adds little to the duration of a macro.</p>\n\n<p>Compilation (top option on Debug) has no obvious effect on duration.</p>\n\n<p>Closing and reopening a workbook may reduce the duration of a macro if the workbook has been subject to significant modification since it was last opened.</p>\n\n<p>Even if there are no formulae, having calculation off decreases the duration of a worksheet-accessing macro but not by as much as you would think.</p>\n\n<p>The one bad practice I found that makes a real difference is to switch worksheets and then activate the new worksheet while screen updating is on. By making every other mistake I was able to get the duration of a macro up from 15 to 199 seconds. Adding activate for every access of a new worksheet increased the duration to 9,838 seconds (2:43:58). Adding ScreenUpdating=False brought it down to 466 seconds (7:46)</p>\n\n<p>I suspect that there is a bug in Excel 2003. I have little experience with other versions so it may or may not apply to them. The bug seems to be associated with moving lots of data around and lengthy macro developments with lots of repeated runs to test corrections. I hit this bug once during the experimentation for this answer but as soon as I tried to pin it down it disappeared.</p>\n\n<p><strong>Experiments</strong></p>\n\n<p>I created a workbook with 26 worksheets. One I named \"Alpha\" while the rest had numeric names. I coded a macro to fill these sheets with between 900 and 1000 rows each of 25 columns with every cell containing a six character string. Other routines cleared rows with either EntireRow.ClearContents and EntireRow.Delete and used Copy and Paste to move data from the worksheet Alpha to the other worksheets.</p>\n\n<p>I could discover no difference in duration between EntireRow.ClearContents and EntireRow.Delete. However clearing or deleting a selected range as opposed to the entire worksheet increased the total duration of processing the 26 worksheets from .07 seconds to .13 seconds.</p>\n\n<p>By including every bad practice I could think of, I could bring the duration of a copy and paste from worksheet Alpha to each of the other 25 worksheets up to 1.3 seconds.</p>\n\n<p>Copying a row 5 containing formulae down from rows 6 to 905 for each of 25 sheets with both Calculate and ScreenUpdating On took 2.5 seconds.</p>\n\n<p>The above are not exact matches for Chris’s routine but they are broadly similar. </p>\n\n<p>The only routine I could get to take more than a second or two was the fill routine. This routine serves to prepare the worksheets for the real tests but it was the only routine that could be made to exhibit extended durations.</p>\n\n<p>The basic function of the fill routine is to fill 26 worksheets with 6 character strings. Every worksheet had 25 columns but the number of rows varies from 900 to 1000. A total of 613,600 cells are filled. For each cell I take the first six characters of a 62-character string and then moved the first character of the 62-character string to the end. To give a crude indication of progress I display the worksheet number to the immediate window. It took two or three seconds per sheet but I did not care enough to improve it.</p>\n\n<p>Using the fill routine to prepare the workbook, I was able to get timings for moving static data about. It was when I updated the fill routine to output formulae to row 5 that I hit a problem. Previously, as the routine ran the numbers 1 to 26 scrolled quickly up the immediate windows. After the update, 1 was displayed and then nothing. I paused the macro after a while and found it had only reached row 177 of the first sheet. </p>\n\n<p>I added a timer to the fill routine and tried to pin down the cause of the slow running but I was never able get it to repeat. This matches my earlier experience of this problem. My macro would suddenly speed up but I was never able to identify anything I had done that caused it to speed up.</p>\n\n<p>As I created routines that took longer to run, I found timings inconsistent. The second run of a macro would take less time than the first. After saving and reopening, the macro would be even quicker. Normally; sometimes it was the other way round. It is possible that background tasks (for example, software checking for updates or virus checker) were a factor but this seems unlikely. The difference in run times was only 10 to 20 seconds but there was no pattern I could detect. Compilation had no noticable effect. I have no difficulty in believing that I was piling up work for the garbage collector; was this a factor? Was Excel losing memory so the heap was getting smaller and smaller? If this was the cause, how come my recollection is that sometimes the slow running would last for a day or two. I usually hibernate Windows but I close Excel down at least once a day during an extended development. I am sorry if this is a brain dump but I am hoping something will click with someone familiar with Excel's internal workings.</p>\n\n<p>I recoded by fill routine to maximise its sensitivity to poor programming. I changed the sequence of the For-loops to: Row, Column, Worksheet. I prefilled the sheet with 562,224 formulae most of which I overwrote one by one. I alternated between activating or not activating the worksheet over 600,000 times, having calculation on or off and having screen updating on or off. The timings I got were:</p>\n\n<pre><code>Activate Calculation Screen updating Total duration\n No Off Off 0:00:20\n No On Off 0:01:57\n No On On 0:03:19\n Yes Off Off 0:05:42\n Yes On Off 0:07:46\n Yes On On 2:43:58 \n</code></pre>\n\n<p>I ran these tests in background because I could not handle the screen flashing from one sheet to another. I am very impressed at how quickly the fill took without activation, calculation and screen updating since I am generating 613,000 strings and placing them in individual cells. There is clearly an advantage in not activating worksheets and having calculation off if possible but nothing like the advantage I have always assumed. </p>\n\n<p>I should perhaps report that the formulae I used were of the form ‘=Mid($Ax,y,1)’. That is column A contained a string and all the other columns extracted a character from it. I originally set row 4 to numbers and all the other cells to the cell above plus one. I found Mid was noticeable slower. No doubt there are other formulae are even slower.</p>\n\n<p><strong>Conclusions</strong></p>\n\n<p>It is not easy to get extended run times through poor programming; you must make a lot of mistakes at the same time.</p>\n\n<p>Does anyone else recall macros with unexpectedly had extended run times? Can anyone suggest an alternative to my theory that Excel 2003 has a bug that might apply to later versions? I have access to a laptop with Excel 2007 and I with rerun the tests on the laptop when I get the opportunity. However, this is unlikely to reveal the bug, if it exists, because there will be no development which seems to be a requirement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T23:52:33.267", "Id": "6931", "ParentId": "6823", "Score": "4" } }, { "body": "<p>You will know from my last answer that I have created a workbook that has the same structure as yours. This means that with some modification I can run your macro. For me it takes .75 seconds for the loops to complete. In this answer, I explain what I have done and why.</p>\n\n<p>I recall that at one stage you were reporting that Sheet(\"BW TB\") was being updated when it should not have been. I cannot find that report so perhaps it has been sorted. No matter, it is an excuse to tell you something.</p>\n\n<p>Programs always seem to go wrong in the middle. You want the program to run for 5 minutes and then stop at the problem area so you can investigate statement by statement. The tool for this task is the Assert statement. Most languages have assert statements. The VBA one is of the form:</p>\n\n<pre><code>Debug.Assert Sheets(i).Name &lt;&gt; BWTB\n</code></pre>\n\n<p>That is <code>Debug.Assert</code> followed by a boolean expression. Here I assert that the current sheet name is not BWTB. It this assertion is true, execution does not pause. But if it is false, execution stops on the assert statement. Place the assert statement at the top of the suspect code. When it pauses, use F8 (execute single statement) or use F9 (set/unset breakpoint) and F5 (execute until breakpoint) to step through the code until you have isolated the problem.</p>\n\n<p>I assume you have made all the improvements people have suggested although my experiments reveal these improvements will not make the difference we all believed.</p>\n\n<p>You start with Sheets(\"4020\"). I seem to recall that you said it was important to start with this sheet. Is this because the other sheets depend on Sheets(\"4020\") or because Sheets(\"4020\") is Sheets(1)? I do not like the way you step through the sheets. Your code depends on Sheets(\"4020\") being Sheets(1) and Sheets(\"BW TB\") being Sheets(26).</p>\n\n<p>If Sheets(\"4020\") is special you should make the body a subroutine with sheet name or index as a parameter. You then (1) call the subroutine for Sheets(\"4020\") and (2) amend the loop to:</p>\n\n<pre><code>For i = 1 to Worksheets.Count\n If (Sheets(i).Name = \"4020\" or Sheets(i).Name = \"BW TB\") Then\n ' Do not action this sheet\n Else\n ' Action this sheet\n End if\nNext\n</code></pre>\n\n<p>You could rearrange the boolean expression so the then-block is executed rather than the else-block but that sort of boolean expression hurts my head. If having a boolean expression I can understand means using the else-block then so be it.</p>\n\n<p>When I set up my workbook, my equivalent of Sheets(\"BW TB\") ended up in the middle so I have had to change your code in this way. I have had to do the same to the code I am about to show you.</p>\n\n<p>You need to isolate the portion of your routine that is taking a long time. The secret to this is the Timer statement which returns seconds since midnight as a single.</p>\n\n<p>I have declared some new variables:</p>\n\n<pre><code> Dim Duration As Single\n Dim InxTVCol As Integer\n Dim InxTVRow As Integer\n Dim TimerVal(1 To 6, 0 To 27) As Single\n Const LastTimeRow As Integer = 26\n Const TotalRow As Integer = 27\n Const LastTimeCol As Integer = 5\n Const TotalCol As Integer = 6\n</code></pre>\n\n<p>I store timer values in TimerVal(1 To 5, 1 To 26). That is 5 times per loop for each of 26 worksheets. I use column 6 for worksheet totals. I use row 27 for loop portion totals. I used TimerVal(0,5) for the start time so TimerVal(N-1,5) is always the end time of the last loop. I use constants so if you decide you need 4 or 6 times per loop or you add more worksheets, you can change the constants rather than my code </p>\n\n<p>I placed <code>TimerVal(LastTimeCol, 0) = Timer</code> before the Do statment.</p>\n\n<p>I placed <code>TimerVal(1, i) = Timer</code> immediately after the Do statment, with four other such statements placed throughout the loop.</p>\n\n<p>The effect of this is for the loop to record 125 times. The following code displays those times to the immediate window as durations:</p>\n\n<pre><code> For InxTVRow = 1 To LastTimeRow\n If TimerVal(1, InxTVRow) = 0# Then\n ' This sheet not actioned\n Else\n Duration = TimerVal(1, InxTVRow) - TimerVal(LastTimeCol, InxTVRow - 1)\n Debug.Print Right(\" \" &amp; InxTVRow, 2) &amp; \" \" &amp; Format(Duration, \"00000.00\");\n TimerVal(TotalCol, InxTVRow) = Duration\n TimerVal(1, TotalRow) = TimerVal(1, TotalRow) + Duration\n For InxTVCol = 2 To LastTimeCol\n Duration = TimerVal(InxTVCol, InxTVRow) - TimerVal(InxTVCol - 1, InxTVRow)\n Debug.Print \" \" &amp; Format(Duration, \"00000.00\");\n TimerVal(TotalCol, InxTVRow) = TimerVal(TotalCol, InxTVRow) + Duration\n TimerVal(InxTVCol, TotalRow) = TimerVal(InxTVCol, TotalRow) + Duration\n Next\n Debug.Print \" | \" &amp; Format(TimerVal(TotalCol, InxTVRow), \"00000.00\")\n End If\n Next\n Debug.Print \" \";\n For InxTVCol = 1 To 5\n Debug.Print \" --------\";\n Next\n Debug.Print \" | ---------\"\n Debug.Print \" \";\n Duration = 0#\n For InxTVCol = 1 To 5\n Duration = Duration + TimerVal(InxTVCol, TotalRow)\n Debug.Print \" \" &amp; Format(TimerVal(InxTVCol, TotalRow), \"00000.00\");\n Next\n Debug.Print \" | \" &amp; Format(Duration, \"00000.00\")\n</code></pre>\n\n<p>On my system the result is:</p>\n\n<pre><code> 1 00000.00 00000.01 00000.04 00000.01 00000.02 | 00000.07\n 2 00000.00 00000.01 00000.03 00000.00 00000.01 | 00000.05\n 3 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n 4 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n 5 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n 6 00000.00 00000.00 00000.01 00000.01 00000.00 | 00000.03\n 7 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n 8 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n 9 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n10 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n11 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n12 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n13 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n14 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n15 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n16 00000.00 00000.00 00000.01 00000.00 00000.00 | 00000.02\n17 00000.00 00000.00 00000.02 00000.00 00000.00 | 00000.03\n18 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n19 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n20 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n21 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n22 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n23 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n24 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n25 00000.00 00000.00 00000.01 00000.00 00000.01 | 00000.03\n -------- -------- -------- -------- -------- | ---------\n 00000.00 00000.11 00000.34 00000.11 00000.20 | 00000.75\n</code></pre>\n\n<p>I have an anomaly in portion 3 of sheets 1 and 2 that might bear investigation. I should have displayed sheet name rather than sheet index. I leave that for you. </p>\n\n<p>If the fault is in your code, this should you enable to isolate the cause.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T00:09:48.897", "Id": "10957", "Score": "0", "body": "One point I noticed. Your search for \"Overall Result\" is in the wrong direction. xlPrevious will get you to the bottom row more quickly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T12:23:24.933", "Id": "6945", "ParentId": "6823", "Score": "2" } } ]
{ "AcceptedAnswerId": "6833", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T09:59:35.497", "Id": "6823", "Score": "8", "Tags": [ "vba", "excel" ], "Title": "Managing book of Excel sheets" }
6823
<p>Because I needed to execute some actions one by one in seperate thread (not to block GUI) and I couldn't use <code>Task.ContinueWith</code> from .NET 4.0 I decided to write it by myself.</p> <p>Here is how it evolved thanks to your suggestions.</p> <pre><code>public class ActionQueue { private Thread _thread; private bool _isProcessed = false; private object _queueSync = new object(); private readonly Queue&lt;Action&gt; _actions = new Queue&lt;Action&gt;(); private SynchronizationContext _context; /// &lt;summary&gt; /// Occurs when one of executed action throws unhandled exception. /// &lt;/summary&gt; public event CrossThreadExceptionEventHandler ExceptionOccured; /// &lt;summary&gt; /// Occurs when all actions in queue are finished. /// &lt;/summary&gt; public event EventHandler ProcessingFinished; /// &lt;summary&gt; /// Gets enqueued actions. /// &lt;/summary&gt; public IEnumerable&lt;Action&gt; Actions { get { lock (_queueSync) { return new ReadOnlyCollection&lt;Action&gt;(_actions.ToList()); } } } protected virtual void Execute() { _isProcessed = true; try { while (true) { Action action = null; lock (_queueSync) { if (_actions.Count == 0) break; else action = _actions.Dequeue(); } action.Invoke(); } if (ProcessingFinished != null) { _context.Send(s =&gt; ProcessingFinished(this, EventArgs.Empty), null); } } catch (ThreadAbortException) { // Execution aborted } catch (Exception ex) { if (ExceptionOccured != null) { _context.Send(s =&gt; ExceptionOccured(this, new CrossThreadExceptionEventArgs(ex)), null); } } finally { _isProcessed = false; } } /// &lt;summary&gt; /// Starts processing current queue. /// &lt;/summary&gt; /// &lt;returns&gt;Returns true if execution was started.&lt;/returns&gt; public virtual bool Process() { if (!_isProcessed) { _context = SynchronizationContext.Current; _thread = new Thread(Execute); _thread.Start(); return true; } else { return false; } } /// &lt;summary&gt; /// Enqueues action to process. /// &lt;/summary&gt; /// &lt;param name="action"&gt;Action to enqueue.&lt;/param&gt; public void Enqueue(Action action) { lock (_queueSync) { _actions.Enqueue(action); } } /// &lt;summary&gt; /// Clears queue. /// &lt;/summary&gt; public void Clear() { lock (_queueSync) { _actions.Clear(); } } /// &lt;summary&gt; /// Aborts execution of current queue. /// &lt;/summary&gt; /// &lt;returns&gt;Returns true if execution was aborted.&lt;/returns&gt; public bool Abort() { if (_isProcessed) { _thread.Abort(); return true; } else { return false; } } } public delegate void CrossThreadExceptionEventHandler(object sender, CrossThreadExceptionEventArgs e); public class CrossThreadExceptionEventArgs : EventArgs { public CrossThreadExceptionEventArgs(Exception exception) { this.Exception = exception; } public Exception Exception { get; set; } } </code></pre> <p>Here is some usage example:</p> <pre><code>ActionQueue queue = new ActionQueue(); queue.Enqueue(SomeMethod); queue.Process(); foreach(var item in collection) { var itemToProcess = item; queue.Enqueue(() =&gt; SomeMethod(itemToProcess)); } queue.Process(); </code></pre> <p><br /> Edits:</p> <ul> <li>Implemented observable pattern</li> <li>Synchronization context added</li> <li><code>IsProcessed</code> property removed</li> </ul>
[]
[ { "body": "<p>Since the class itself does very little (runs a bunch of methods on a separate thread), there is little justification in using it, IMHO.</p>\n\n<p>This statement would basically do the same thing (on a <code>ThreadPool</code>, that is):</p>\n\n<pre><code>ThreadPool.QueueUserWorkItem(s =&gt;\n{\n SomeMethod();\n DoSomething();\n AndSomeMore();\n});\n</code></pre>\n\n<p>If it included stuff like progress updating, exception handling and finalization events, then it could make more sense to use it:</p>\n\n<pre><code>interface IActionQueue\n{\n void Start();\n\n // if you know the list count, you can provide some progress info\n event Action&lt;Double&gt; ProgressChanged;\n\n // there is no way to catch an exception on a separate thread, so \n // this would be neat\n event Action&lt;Exception&gt; ExceptionHappened;\n\n // this can be useful also\n event Action Finished;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T13:26:23.133", "Id": "10688", "Score": "0", "body": "I think that justification in using it is the possibility to reuse it and expand in the future. You think that isn't enough? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T13:30:13.500", "Id": "10689", "Score": "0", "body": "And I thought that `ThreadPool` is used rather to do some work in parallel. Am I wrong? Does it execute actions one by one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T13:39:53.077", "Id": "10690", "Score": "0", "body": "Oh, sorry - now I see that you put it in a single lambda :) You are right then. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T13:46:27.167", "Id": "10691", "Score": "0", "body": "But wait... I need to enqueue some actions from different places and in different moments and then start them from another so the code you provided is not enough. Of course, I can build a queue and process it using `ThreadPool` but don't you think that using `ActionQueue` is better idea?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T13:04:32.353", "Id": "10749", "Score": "0", "body": "@rotman: ok, my answer was based on your first example. If you do need to create this list from several places, using a separate class might make it more explicit. But you should then consider suggestions made by Slade and Jesse: I would not expose the mutable list to the outside world, if there is a chance that it may be iterated on a separate thread. The simplest way would be to change the list into a `Queue`, make it private, and expose a public `Add` method which should *lock* while enqueuing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:21:41.633", "Id": "10755", "Score": "0", "body": "New version above." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:52:02.417", "Id": "6828", "ParentId": "6826", "Score": "4" } }, { "body": "<p>If you are using the <code>ActionQueue</code> simply for invoking a collection of actions one-by-one one another thread, then there isn't really much you can say over the implementation (other than the point already made by Groo).</p>\n\n<p>However, if you wish to have this <code>ActionQueue</code> running on another thread, while accepting requests to queue another action to execute (so you can execute actions asynchronously), then you may wish to look into using a combination of <a href=\"http://msdn.microsoft.com/en-us/library/7977ey2c.aspx\" rel=\"nofollow\"><code>Queue&lt;Action&gt;</code></a>, a background worker thread and <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx\" rel=\"nofollow\"><code>AutoResetEvent</code></a>. I won't write the full implementation of that here, as I don't know if that is what you want, but if you do then I would be happy to edit this answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T13:12:44.850", "Id": "6829", "ParentId": "6826", "Score": "1" } }, { "body": "<p>Don't expose your concrete lists:</p>\n\n<pre><code>public class ActionQueue\n{\n private readonly IList&lt;Action&gt; actions = new List&lt;Action&gt;();\n\n public IEnumerable&lt;Action&gt; Actions\n {\n get\n {\n return new ReadOnlyCollection&lt;Action&gt;(actions);\n }\n }\n\n public void Add(Action action)\n {\n this.actions.Add(action);\n }\n\n protected virtual void Execute()\n {\n foreach (var action in this.actions)\n {\n action.Invoke();\n }\n }\n\n public virtual void Start()\n {\n var thread = new Thread(Execute);\n\n thread.Start();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T15:08:31.790", "Id": "10700", "Score": "2", "body": "I wouldn't use the `IList` interface in this case if you are wanting to restrict access to the `Actions` property. Instead, I'd maintain it as `List` inside of the `class` and change the return type of the `Actions` property to `IEnumerable<Action>`. Then still use the `ReadOnlyCollection<Action>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T15:29:32.227", "Id": "10702", "Score": "0", "body": "I'll buy that.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:22:46.450", "Id": "10757", "Score": "0", "body": "I took into account your suggestions. New version above." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T14:51:46.473", "Id": "6839", "ParentId": "6826", "Score": "1" } }, { "body": "<p>Your approach is not ThreadSafe, replace the Queue with ConcurrentQueue or add locking around all the Enqueue, Dequeue, and Count members. Also, I would avoid throwing an exception if the Queue is still processing. This condition is something that is largely a private concern of your class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T13:45:18.550", "Id": "10812", "Score": "0", "body": "I can't use `ConcurrentQueue` because it's .NET 3.5 so I introduced locks. Thanks for that.\n\nMaybe throwing exception it's the best solution (do you have any suggestions?) but I rather disagree that state of being processed is a private concern of the class. What if some other object wants to check if queue has ended the work? I can imagine such situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T19:59:47.387", "Id": "10819", "Score": "1", "body": "In both cases where your throwing an exception I would just exit silently. Although I don't have the full context, it just seems like the caller shouldn't need to the know about the inner workings of this class; at least not at that level. Having said that, if the caller needs to be aware of whether or not their invokation led to the initiation of any real action, you could simply return with a bool or enum indicating what they triggered; if anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T20:09:56.087", "Id": "10820", "Score": "1", "body": "Sorry, I forgot to answer one of your questions. If callers need to be notified when a queued item is processed, there are more efficient ways of achieving this. For example, you could use an Observer Pattern and let callers subscribe to the working state of the Queue (Ex. OnProcessingQueuedItems, OnQueuedItemProcessed, OnProcessingQueueCompleted, etc...). Alternatively, each caller could register a callback with the request and be notified when their instance is processed. In any case, using exceptions such as I saw above just isn't a great way to communicate what you've indicated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T13:14:28.997", "Id": "10901", "Score": "0", "body": "I totally agreed with your suggestions. I can find updated version above. Thanks." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:38:13.117", "Id": "6892", "ParentId": "6826", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T11:19:43.390", "Id": "6826", "Score": "4", "Tags": [ "c#", ".net", "multithreading" ], "Title": "Action queue in .NET 3.5" }
6826
<p>Is there a cleaner way of checking a dataset for tables/rows before attempting to read them?</p> <pre><code>If ds.Tables.Count &gt; 0 Then If ds.Tables(0).Rows.Count &gt; 0 Then 'do something with the the rows at this point End If End If </code></pre> <p>Edit to clarify - I am talking specifically about the two bool checks to see if the dataset acutally contains any data in table(0).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T10:12:47.210", "Id": "10744", "Score": "1", "body": "Please define: `Check`? Do you want to check for the existence of columns or that a value was returned?" } ]
[ { "body": "<p>I'm doing a couple of assumptions here, but I hope I'm on target.</p>\n\n<p>If you just want the first column of the first row, you should use SqlCommand.ExecuteScalar instead of reading it into a dataset.</p>\n\n<p>For instance:</p>\n\n<pre><code>using (var cn = new SqlConnection(\"...\"))\n{\n using (var cmd = new SqlCommand(\"SELECT statusCode FROM table WHERE whatever\", cn)\n {\n cn.Open();\n return (string)cmd.ExecuteScalar();\n }\n}\n</code></pre>\n\n<p>(Notice the using statement if you don't know it. It automatically disposes the connection and command)</p>\n\n<p>You could also look into using SqlCommand.ExecuteReader which returns an SqlDataReader. The latter is cleaner and has better performance than the dataset method too. </p>\n\n<pre><code>using (var reader = cmd.ExecuteReader())\n{\n while(reader.Read()) \n { \n var value = reader.GetString(0); \n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T10:12:11.937", "Id": "10743", "Score": "1", "body": "The reader needs to be disposed, too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T09:08:54.643", "Id": "6862", "ParentId": "6841", "Score": "5" } }, { "body": "<p>Assuming that you are using a version of .NET that supports extension methods you could write an extension which does the basic check. </p>\n\n<p>VB.NET</p>\n\n<pre><code>Public NotInheritable Class DataSetExtensions\n Private Sub New()\n End Sub\n &lt;System.Runtime.CompilerServices.Extension&gt; _\n Public Shared Function IsTableDataPopulated(dataSet As DataSet) As Boolean\n Return dataSet IsNot Nothing AndAlso dataSet.Tables.Count &gt; 0 AndAlso dataSet.Tables(0).Rows.Count &gt; 0\n End Function\nEnd Class\n</code></pre>\n\n<p>c#</p>\n\n<pre><code>public static class DataSetExtensions\n{\n public static bool IsTableDataPopulated(this DataSet dataSet)\n {\n return dataSet != null &amp;&amp; dataSet.Tables.Count &gt; 0 &amp;&amp; dataSet.Tables[0].Rows.Count &gt; 0;\n }\n}\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>if (ds.IsTableDataPopulated()) \n{\n // do stuff\n}\n</code></pre>\n\n<p>Note: I am not 100% sure if the VB code works as I used a translator for converting c# to VB.NET, call me lazy :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-01T02:00:12.970", "Id": "7348", "ParentId": "6841", "Score": "5" } }, { "body": "<p>This looks like a good opportunity to use <code>AndAlso</code>.</p>\n\n<p>From the MSDN documentation (<a href=\"http://msdn.microsoft.com/en-us/library/cb8x3kfz%28v=vs.80%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/cb8x3kfz(v=vs.80).aspx</a>):</p>\n\n<blockquote>\n <p>One use of the AndAlso operator is to test for the existence of an\n object instance before attempting to access one of its members.</p>\n</blockquote>\n\n<p>In your case:</p>\n\n<p><code>If ds.Tables.Count &gt; 0 AndAlso ds.Tables(0).Rows.Count &gt; 0 Then</code></p>\n\n<p>(Which is basically what Kane said, without the funky extension methoding - now that I re-read his answer)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T13:29:49.630", "Id": "15479", "ParentId": "6841", "Score": "5" } }, { "body": "<pre><code> Dim ds As New DataSet\n Dim bExists As Boolean\n Try\n bExists = ds.Tables(0).Rows.Count &gt; 0\n Catch\n 'There is no rows or either the Dataset or DataTable are nothing/null\n End Try\n\n If bExists Then\n '... Do your task\n End If\n</code></pre>\n\n<p><code>bExists</code> will be <code>True</code> if the DataSet and DataTable are not nothing and the DataTable has rows. If one of them is nothing an <code>Object reference exception</code> will occur and the <code>bExists</code> remains <code>False</code>, also if they are <em>not</em> nothing but the table has no rows then the <code>bExists</code> will be false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T14:34:30.550", "Id": "82307", "Score": "0", "body": "could you explain this answer a little bit please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T14:45:21.783", "Id": "82309", "Score": "0", "body": "\"bExists\" will be True if the DataSet and DataTable are not nothing and the DataTable has rows.\nIf one of them is nothing an Object reference exception will occure and the bExists remains False, also if they are not nothing but the table has no rows then the bExists will be false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T19:39:58.053", "Id": "82330", "Score": "0", "body": "Or something else caused an exception in the try block and you just ate an exception. Note that whether this matters, depends upon what else is done in your try block. But for just that reason, you shouldn't use try/catch as a substitute for appropriate validation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T19:49:32.200", "Id": "82331", "Score": "0", "body": "How come that! Could you provide me an exception will occure except the object reference? and this solution is especially made for this case, the try block just validate the expression.\nIt's valid way to check and it's used inside the .NET Framework if tried to refactor some of it's code!\nfor example: \"TryCast\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T23:07:28.967", "Id": "82359", "Score": "0", "body": "Generally, this type of thing should be avoided unless there is no other way to do it. It is much cheaper, and less error prone to simply check for the conditions you know can go wrong, rather than to rely on exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T17:16:15.890", "Id": "82433", "Score": "0", "body": "@DejaVu: in your example, it works, but it provides no benefit over explicitly checking the conditions. It works by doing something that should be avoided where possible, and since it is trivially possibly to avoid it in this case...." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T14:14:50.410", "Id": "47002", "ParentId": "6841", "Score": "0" } } ]
{ "AcceptedAnswerId": "7348", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T15:57:00.387", "Id": "6841", "Score": "3", "Tags": [ ".net", "vb.net" ], "Title": "Checking datasets for tables and rows" }
6841
<p>This is related to <a href="https://stackoverflow.com/questions/8476346/java-reading-xml-configuration-and-applying-to-an-object-whats-a-lightweight">a question I posted on Stack Overflow</a>. The consensus was to use JAXB, which is what I did.</p> <p>One of the requirements was that it needed to work with legacy XML configuration files. The code needed to be able to start reading new configuration settings from XML files already used to configure pre-existing applications.</p> <p>In trying to make the code reusable, I added the generic type parameter. However, this causes some yuckiness for the user, as it requires user to pass in the class type. (It shouldn't be necessary - but due to Java implementation of generics, there's no easy way around that).</p> <p>I had to throw this together very quickly, so I would welcome any suggestions on improvement (or finding errors). I wasn't very skilled with JAXB, so perhaps there is a better solution I overlooked.</p> <pre><code>package com.eztech.config; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.w3c.dom.Document; import org.w3c.dom.Node; import com.eztech.xml.XmlUtils; public class JAXBConfigurator&lt;T&gt; { private String filePath; private Class&lt;T&gt; clazz; public JAXBConfigurator(Class&lt;T&gt; toConfigure, String xmlFilePath) { this.clazz = toConfigure; this.filePath = xmlFilePath; } /** * Parses Xml and reads configuration from Document element. Using this method * assumes that the configuration xml starts at the top of the xml document. * @return * @throws Exception */ public T createAndConfigure() throws Exception { return createAndConfigure(null); } /** * Selects specified element from the parsed Xml document to use as the base * for reading the configuration. * * @param tagName * @return */ public T createAndConfigure(String tagName) throws Exception { Document doc = XmlUtils.parse(filePath); Node startNode; if (tagName == null) { startNode = doc; } else { startNode = XmlUtils.findFirstElement(doc, tagName); } return readConfigFromNode(startNode); } private T readConfigFromNode(Node startNode) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); JAXBElement&lt;T&gt; configElement = unmarshaller.unmarshal(startNode, clazz); return configElement.getValue(); } } </code></pre> <p>How to use it:</p> <pre><code>JAXBConfigurator&lt;MyConfig&gt; configurator = new JAXBConfigurator&lt;Config&gt;(MyConfig.class, xmlfilePath); instance = configurator.createAndConfigure("MyXmlStartTag"); </code></pre>
[]
[ { "body": "<p>Two things which are good to know about JAXB:</p>\n\n<ul>\n<li>You can annotate private methods and fields, JAXB can call/modify them. It could help hiding internal data structure from clients.</li>\n<li><a href=\"http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Marshaller.html#marshalEventCallback\" rel=\"nofollow\"><code>Marshaller</code></a> as well as <a href=\"http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html#unmarshalEventCallback\" rel=\"nofollow\"><code>Unmarshaller</code></a> has event callbacks. They can help handing deprecated or compound fields.</li>\n</ul>\n\n<p>Just two small notes about the code:</p>\n\n<ol>\n<li><p>I would call the class <code>JaxbConfigurator</code>. Lowercase letters are easier to read. (Effective Java, Second Edition, Item 56: Adhere to generally accepted naming conventions)</p></li>\n<li><p>It would be worth checking input parameters in the constructor to avoid latter mysterious <code>NullPonterExceptions</code>:</p>\n\n<pre><code>import static com.google.common.base.Preconditions.*;\n\n...\n\npublic JaxbConfigurator(final Class&lt;T&gt; toConfigure, final String xmlFilePath) {\n this.clazz = checkNotNull(toConfigure, \"toConfigure cannot be null\");\n this.filePath = checkNotNull(xmlFilePath, \"xmlFilePath cannot be null\");\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:42:40.427", "Id": "10906", "Score": "0", "body": "Thanks for the comment. The null check is definitely critical. I didn't understand one thing you wrote: \"You can annotate private methods and fields, JAXB can call/modify them. It could help hiding internal data structure from clients.\" Does this somehow affect the code above? (I was thinking that the annotations are entirely internal to the client class and JAXB, but this utility doesn't need any knowledge of that.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T21:45:04.157", "Id": "10933", "Score": "0", "body": "*\"Does this somehow affect the code above?\"* - No, it doesn't but it could help if your client (config) classes have to handle more than one XML schema (because of XML schema backward compatibility reasons)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T13:40:11.337", "Id": "6918", "ParentId": "6845", "Score": "4" } }, { "body": "<h3>Finals and Validation</h3>\n\n<p>The fields </p>\n\n<pre><code>private String filePath;\nprivate Class&lt;T&gt; clazz;\n</code></pre>\n\n<p>seem to be constant references, why not transforming them to <code>final</code>s: <code>private final String</code> etc?</p>\n\n<p>To validate them, a very short way is</p>\n\n<pre><code>import java.util.Objects;\n...\n// in the constructor:\nObjects.requireNonNull(toConfigure);\n</code></pre>\n\n<h3>Avoid Throwing Exception</h3>\n\n<p>Throwing <code>Exception</code> in any of the methods forces the user of your class to <code>catch (Exception)</code>, which is not very comfortable and brings some doubts about the API. Please try to replace <code>Exception</code> with a more concrete type, which specifies the kind of exceptional condition that the user should be aware of. E.g. <code>throws JAXBException</code> is OK.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-08T12:21:36.257", "Id": "190282", "Score": "0", "body": "I agree with both you points. Actually, I configured Eclipse to automatically convert `private` variables to `final private`, so I don't have to think about this anymore. Throwing a more specific Exception is also better design to give users the option to handle it specifically or not." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-07T06:41:43.460", "Id": "104002", "ParentId": "6845", "Score": "2" } } ]
{ "AcceptedAnswerId": "6918", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T18:11:29.293", "Id": "6845", "Score": "4", "Tags": [ "java", "xml", "jaxb", "configuration" ], "Title": "Reusable configuration reader for Java" }
6845
<p>I'm using the Amazon S3 Java SDK to fetch a list of files in a (simulated) sub-folder. This code is rather standard (<code>AWSConfiguration</code> is a class that contains a bunch of account specific values):</p> <pre><code>String prefix = "/images/cars/"; int prefix_size = prefix.length(); AmazonS3 s3 = new AmazonS3Client(new AWSConfiguration()); ObjectListing objectListing = s3.listObjects(new ListObjectsRequest(). withBucketName(AWSConfiguration.BUCKET). withPrefix(prefix)); </code></pre> <p>Now this list will include objects like <code>/images/cars/default.png</code> as well as <code>/images/cars/ford/Default.png</code> (because they both contain the same prefix). To list only the objects that are directly inside the <code>/images/cars/</code> "folder" I have the following function (in a class called S3Asset)</p> <pre><code>public static boolean isInsideFolder(int root_size, String key) { return (key.substring(root_size).indexOf("/") == -1); } </code></pre> <p>This looks at the full key for any <code>/</code> after the prefix as a clue that it is inside a sub-folder. This lets me iterate over the objects with the following code (I'm trimming the prefix for clarity):</p> <pre><code>for(S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { if(S3Asset.isInsideFolder(prefix_size, objectSummary.getKey())) { System.out.println(objectSummary.getKey().substring(prefix_size)); } } </code></pre> <p>As near as I can tell this is the cleanest way to do this but it has one characteristic that I don't like. If I'm looking a root level folder I'm requesting the names of all files in all sub-folders only to iterate over them and learn that there is only one object in the actual root level folder. I've considered associating a key with the value being the full path of the folder, which would allow me to request objects with a predictable key instead of the prefix, but the major downside to this is that the key would have to be generated in code and therefor assets uploaded directly in to the S3 Bucket (through the management console) would not have this key. Anyone have a better idea?</p>
[]
[ { "body": "<p>In the <a href=\"http://docs.amazonwebservices.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/ListObjectsRequest.html\"><code>ListObjectsRequest</code> javadoc</a> there is a method called <code>withDelimiter(String delimiter)</code>. Adding <code>.withDelimiter(\"/\")</code> after the <code>.withPrefix(prefix)</code> call then you will receive only a list of objects at the same folder level as the prefix (avoiding the need to filter the returned <code>ObjectListing</code> after the list was sent over the wire).</p>\n\n<p>Some notes about the code:</p>\n\n<p>1, I'd extract out to a local variable for the <code>ListObjectsRequest</code> instance:</p>\n\n<pre><code>final ListObjectsRequest listObjectRequest = new ListObjectsRequest().\n withBucketName(AWSConfiguration.BUCKET).\n withPrefix(prefix);\nfinal ObjectListing objectListing = s3.listObjects(listObjectRequest);\n</code></pre>\n\n<p>It's easier to read.</p>\n\n<p>2, <code>root_size</code> should be <code>rootSize</code>. (Regarding to the Java Coding Conventions.)</p>\n\n<p>3, I would use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#contains%28java.lang.CharSequence%29\">String.contains</a> instead of <code>indexOf</code>. It's more meaningful, easier to read since you don't have to use the <code>-1</code> magic number.</p>\n\n<p>4, In the last snippet I'd create a local variable for the <code>key</code>:</p>\n\n<pre><code>for (final S3ObjectSummary objectSummary: objectListing.getObjectSummaries()) {\n final String key = objectSummary.getKey();\n if (S3Asset.isImmediateDescendant(prefix, key)) {\n final String relativePath = getRelativePath(prefix, key);\n System.out.println(relativePath);\n }\n}\n</code></pre>\n\n<p>5, Furthermore, I'd move the <code>length</code> call inside the helper method:</p>\n\n<pre><code>public String getRelativePath(final String parent, final String child) {\n if (!child.startsWith(parent)) {\n throw new IllegalArgumentException(\"Invalid child '\" + child \n + \"' for parent '\" + parent + \"'\");\n }\n // a String.replace() also would be fine here\n final int parentLen = parent.length();\n return child.substring(parentLen);\n}\n\npublic boolean isImmediateDescendant(final String parent, final String child) {\n if (!child.startsWith(parent)) {\n // maybe we just should return false\n throw new IllegalArgumentException(\"Invalid child '\" + child \n + \"' for parent '\" + parent + \"'\");\n }\n final int parentLen = parent.length();\n final String childWithoutParent = child.substring(parentLen);\n if (childWithoutParent.contains(\"/\")) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Note the input check. (Effective Java, Second Edition, Item 38: Check parameters for validity)</p>\n\n<p>The multiple calls of <code>length</code> could look redundant and slow but premature optimization is not a good thing (see Effective Java, Second Edition, Item 55: Optimize judiciously). If you check the <a href=\"http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Core/lang/java/lang/String.java.htm\">source of <code>java.lang.String</code></a>, you will find this:</p>\n\n<pre><code>/** The count is the number of characters in the String. */\nprivate final int count;\n\n...\n\npublic int length() {\n return count;\n}\n</code></pre>\n\n<p><code>String</code> is immutable, so it's easy to cache its length and JDK does it for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:11:06.763", "Id": "10720", "Score": "4", "body": "If this is the kind of input that you can expect from this community then I am 100% behind supporting it's promotion to a full fledged site! Thank you for such a complete answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:19:17.453", "Id": "10722", "Score": "1", "body": "Point 4 is very close to how this code actually looks in my actual app, and for point 5, in my S3Asset class I have 2 methods (one that takes 2 strings and does the length check on the parent, and one that I referenced in my question). It's a premature optimization, but calling a string length function on each iteration when the value will always be the same just makes me feel bad. Now what will I do with all the extra nanoseconds I'm saving?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:32:44.733", "Id": "10723", "Score": "1", "body": "Check the update, there is no extra nanosecond :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T00:05:31.630", "Id": "10830", "Score": "1", "body": "It looks like the missing API call is \"withDelimiter\" which is clearly described on this page http://aws.amazon.com/releasenotes/213, if you update your answer I'll mark it as correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T10:25:20.910", "Id": "21352", "Score": "0", "body": "Please give the KeyObjectType jar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:25:21.503", "Id": "21353", "Score": "0", "body": "It was just pseudo-code, the concrete type is `String`. I've updated my answer. Sorry for the inconvenience and thanks for the feedback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-01T19:29:36.867", "Id": "398839", "Score": "1", "body": "Great answer, I think it also can be improved by mentioned that at the ObjectListing level, the resulting list is truncated for more than 1000 acording to API Doc this https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html, The ObjectListing has a method objectListing.isTruncated() to indicate if there are more results, objectListing.getNextMarker() and objectListing.setNextMarker() are used to control the paging. A do-while() is suggested for the iteration, it would contain the \"for (final S3ObjectSummary objectSummary: objectListing.getObjectSummaries())\" loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-01T23:37:24.513", "Id": "398850", "Score": "0", "body": "@le0diaz: Thanks! Could you write your comment as a separate answer? I'd upvote that too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-02T14:35:13.110", "Id": "398928", "Score": "0", "body": "@palacsint I think, as this is the best answer, just to edit and include the changes I'm suggesting, it would only add some lines of code to the point 4, you can consider this as reference: https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html . A new answer would not add any more significant to the existing," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T08:31:45.880", "Id": "399256", "Score": "0", "body": "@le0diaz: I think we can have multiple good answers here, even from the same person: https://codereview.meta.stackexchange.com/questions/20/should-one-person-have-multiple-answers" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:36:17.453", "Id": "6850", "ParentId": "6847", "Score": "22" } }, { "body": "<p>That's an old question, but I just've find out that with a new version of amazonaws \"1.9.22\" you can call \"getCommonPrefixes\" to get a list of all available prefixes. You need to use delimiter either.</p>\n\n<pre><code>val listObjectRequest = new ListObjectsRequest().\n withBucketName(\"bucket\").\n withPrefix(\"prefix\").\n withDelimiter(\"/\")\n\ns3Client.listObjects(listObjectRequest).getCommonPrefixes\n</code></pre>\n\n<p>So, for a structure like \"prefix/aaa/111\" it will return \"prefix/aaa\" level items.</p>\n\n<p>UPDATE:</p>\n\n<p>And a java version (original one uses scala)</p>\n\n<pre><code>AmazonS3 s3 = new AmazonS3Client(new AWSConfiguration());\nListObjectsRequest listObjectRequest = new ListObjectsRequest().\n withBucketName(AWSConfiguration.BUCKET).\n withPrefix(prefix).\n withDelimiter(\"/\");\nObjectListing objectListing = s3.listObjects(listObjectRequest).getCommonPrefixes();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-03T17:09:41.430", "Id": "149453", "Score": "0", "body": "Welcome to CR! That's great, but good answers on this site directly relate to the OP's code. Perhaps you could edit and add a bit of context to say where this snippet fits in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-03T18:02:36.847", "Id": "149458", "Score": "0", "body": "Thanks @cyrillk! This community continues to pleaantly surprise me :) The original answer has become a deep part of a lot of my projects, I'm going to revisit the video see if your answer can make the intent cleaner :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-03T17:01:40.383", "Id": "83121", "ParentId": "6847", "Score": "5" } }, { "body": "<p>I got nothing returned when I used <code>withDelimiter(\"/\")</code>. It turned out that in order to use delimiter, I also needs to end my prefix with <code>/</code>. In other words, <code>withPrefix(\"prefix/abc\")</code> will get all objects under <code>prefix/abc</code>, but for delimiter to work, use <code>withPrefix(\"prefix/abc/\")</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-28T00:04:38.013", "Id": "171365", "ParentId": "6847", "Score": "4" } } ]
{ "AcceptedAnswerId": "6850", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T19:14:05.353", "Id": "6847", "Score": "21", "Tags": [ "java", "amazon-s3" ], "Title": "List objects in a Amazon S3 folder without also listing objects in sub folders" }
6847
<p>I didn't know this site existed before now... awesome!</p> <p>I just made a thread here: <a href="https://stackoverflow.com/questions/8511620/c-palindrome-finder-optimization">https://stackoverflow.com/questions/8511620/c-palindrome-finder-optimization</a> </p> <pre><code>#include &lt;iostream&gt; #include &lt;ostream&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;algorithm&gt; using namespace std; bool isPal(string); int main() { vector&lt;string&gt; sVec; vector&lt;string&gt; sWords; vector&lt;string&gt; sTwoWords1; vector&lt;string&gt; sTwoWords2; char myfile[256]="/home/Damien/Test.txt"; ifstream fin; string str; fin.open(myfile); if(!fin){ cout &lt;&lt; "fin failed"; return 0; } while(fin){ fin &gt;&gt; str; sWords.push_back(str); if(!fin){ break; } if(isPal(str)){ sVec.push_back(str); } else{ getline(fin, str); } } reverse(sVec.begin(), sVec.end()); for(int i =0; i &lt; sVec.size(); i++){ cout &lt;&lt; sVec[i] &lt;&lt; " is a Palindrome " &lt;&lt;endl; } // Test 2 for(int i=0; i&lt;sWords.size(); i++) { for(int j=(i+1); j&lt;sWords.size(); j++){ str = sWords[i]+sWords[j]; if(isPal(str)){ sTwoWords1.push_back(sWords[i]); sTwoWords2.push_back(sWords[j]); } } } fin.close(); for(int i=0; i&lt;sTwoWords1.size();i++){ cout &lt;&lt; sTwoWords1[i] &lt;&lt; " and " &lt;&lt; sTwoWords2[i] &lt;&lt; " are palindromic. \n"; } return 0; } bool isPal(string&amp; testing) { return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin()); } </code></pre> <p>About optimizing some code, assuming that I take the revision to my isPal function, what else can I do to optimize the hell out of my code?</p> <p>Thanks a lot for any / all recommendations!</p> <p>Wordfile: <a href="http://www.filedropper.com/ospd3" rel="nofollow noreferrer">http://www.filedropper.com/ospd3</a></p>
[]
[ { "body": "<h3>Reading a file:</h3>\n\n<pre><code>while(fin){ \n\n fin &gt;&gt; str; \n sWords.push_back(str); \n if(!fin){ \n break; \n } \n</code></pre>\n\n<p>You push the value str before checking it worked. It should be:</p>\n\n<pre><code>while(fin)\n{ \n fin &gt;&gt; str; \n if(!fin){ \n break; \n } \n sWords.push_back(str); \n</code></pre>\n\n<p>Or even better would be:</p>\n\n<pre><code>while(fin &gt;&gt; str)\n{ \n sWords.push_back(str); \n</code></pre>\n\n<h3>Why are you doing this:</h3>\n\n<pre><code> else{\n getline(fin, str);\n }\n</code></pre>\n\n<p>Mixing operator >> and getline() makes the code hard to read.<br>\nEither use all operator >> or use getline() to get a line at a time then parse the line internally.</p>\n\n<p>Note:: operator>> will ignore the '\\n' at the end of the line and work. So if your file is a list of words one per line there is no need to use getline(). If on the other hand your file is a lot of text and you only want the first word on each line then you need to use getline().</p>\n\n<h3>Method 1: Use operator>></h3>\n\n<pre><code> // If your input file has one word per line (or you want to use all words)\n while(file &gt;&gt; word)\n {\n // Do stuff\n }\n</code></pre>\n\n<h3>Method 1: Use getline()</h3>\n\n<pre><code> // If your input file contains lots of words\n // But you only want to use the first word on each line\n while(std::getline(file, line))\n {\n std::stringstream linestream(line);\n linestream &gt;&gt; word;\n\n // Do stuff\n }\n</code></pre>\n\n<h3>You seem to reversing the line just to print it:</h3>\n\n<pre><code>reverse(sVec.begin(), sVec.end()); \nfor(int i =0; i &lt; sVec.size(); i++){ \n cout &lt;&lt; sVec[i] &lt;&lt; \" is a Palindrome \" &lt;&lt;endl; \n} \n</code></pre>\n\n<p>Rather than reversing the array, just iterate it in reverse order:</p>\n\n<pre><code>for(std::vector&lt;std::string&gt;::const_iterator&amp; loop = sVec.rbegin(); loop != sVec.rend(); ++ loop)\n{ \n cout &lt;&lt; (*loop) &lt;&lt; \" is a Palindrome \" &lt;&lt;endl; \n} \n</code></pre>\n\n<h3>Note on efficiency:</h3>\n\n<p>Using push_back() on an vector can be in-effecient if you are pushing a lot of data. As evertime the vector runs out of space it must allocate more memory and copy the string to the new buffer. You help by pre-allocting space.</p>\n\n<pre><code>sVec.reserve(1000); // Guess at the size\n // Note when the vector runs out of space it will approximately\n // double its internal buffer.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:49:22.980", "Id": "10718", "Score": "0", "body": "Whoops, I actually parsed two different revisions of my code, thank you very much for bringing this to my attention. I was actually using getline(fin, str) as my while statement but then I changed it to fin >> for a different test I was running. Thank you so much for pointing those errors out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:39:44.090", "Id": "6851", "ParentId": "6849", "Score": "4" } }, { "body": "<pre><code>#include &lt;iostream&gt;\n#include &lt;ostream&gt;\n#include &lt;vector&gt;\n#include &lt;fstream&gt;\n#include &lt;algorithm&gt; \n</code></pre>\n\n<p>You forgot to <code>#include &lt;string&gt;</code>.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Although this might be acceptable in books and on this site to shorten lines, <strong>don't use <em>using namespace std</em> in real code</strong>.</p>\n\n<pre><code> vector&lt;string&gt; sVec;\n vector&lt;string&gt; sWords;\n vector&lt;string&gt; sTwoWords1;\n vector&lt;string&gt; sTwoWords2;\n char myfile[256]=\"/home/Damien/Test.txt\";\n ifstream fin;\n string str;\n</code></pre>\n\n<p>This is an outdated style. Even in C, your variabled don't have to be declared at the top anymore. <strong>Declare each variable on the line it's initialized.</strong></p>\n\n<pre><code> char myfile[256]=\"/home/Damien/Test.txt\";\n</code></pre>\n\n<p>Don't use char arrays, <strong>use <code>std::string</code></strong> (or in rare cases: <code>std::vector&lt;char&gt;</code>).</p>\n\n<pre><code> ifstream fin;\n fin.open(myfile);\n</code></pre>\n\n<p>Why two lines where one would be enough, and why using <code>open()</code>? Replace it with:</p>\n\n<pre><code> std::ifstream fin(myfile.c_str());\n</code></pre>\n\n<p>As myfile should be a std::string.</p>\n\n<pre><code> while(fin){\n fin &gt;&gt; str;\n sWords.push_back(str);\n</code></pre>\n\n<p>The other answer has already corrected the bug in this statement.</p>\n\n<pre><code> reverse(sVec.begin(), sVec.end());\n for(int i =0; i &lt; sVec.size(); i++){ \n</code></pre>\n\n<p><strong>Use iterators</strong> to loop over a container. In this case, use reverse iterators and you won't even need to call <code>reverse()</code>.</p>\n\n<pre><code> fin.close();\n</code></pre>\n\n<p><strong>The destructor will close it anyway</strong>. Is there any reason to explicitly close it at this point? If there was any, just make sure that the life-time of <code>fin</code> ends at this point, e.g. by making a separate function of reading all input. Your <code>main()</code> is way too long anyway.</p>\n\n<pre><code> str = sWords[i]+sWords[j];\n if(isPal(str)){\n</code></pre>\n\n<p>Bug! \"aab\" and \"aa\" will turn out to be a palindrome pair, as \"aabaa\" is a palindrome.</p>\n\n<pre><code>bool isPal(string&amp; testing) {\n</code></pre>\n\n<p>That should be a const reference.</p>\n\n<pre><code>bool isPal(string);\n....\nbool isPal(string&amp; testing) {\n</code></pre>\n\n<p>Those don't match.</p>\n\n<pre><code> return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin());\n</code></pre>\n\n<p>Cool! Finally some real C++ code! Even the <code>std::</code> is present!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T10:22:27.983", "Id": "10745", "Score": "0", "body": "Ouch, brutal answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T00:35:50.647", "Id": "6855", "ParentId": "6849", "Score": "3" } } ]
{ "AcceptedAnswerId": "6851", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:29:38.887", "Id": "6849", "Score": "4", "Tags": [ "c++" ], "Title": "Cross-post from SO- Palindrome finding function" }
6849
<p><strong>Magnus Lie Hetland</strong> in his <strong>Beginning python</strong> wrote a code to replicate the range() built-in.</p> <pre><code>def interval(start, stop=None, step=1): if stop is None: start, stop = 0, start result = [] i = start while i &lt; stop: result.append(i) i += step return result </code></pre> <p>I re-wrote it like this.</p> <pre><code>def interval(*args): if len(args)&lt;1: raise TypeError('range expected at least 1 arguments, got 0') elif len(args)&gt;3 : raise TypeError('range expected at most 3 arguments, got %d' % len(args)) else: if len(args)==1: start = 0 stop = args[0] step = 1 elif len(args)==2: start=args[0] stop=args[1] step=1 elif len(args)==3: start=args[0] stop=args[1] step=args[2] result = [] while start &lt; stop: result.append(start) start+=step return result </code></pre> <p>I know my code is lengthier but don't you people think its easier to grasp/understand than Hetland's code? Different peoples' minds work differently. In my mind the code felt easier to understand cos I come from a <strong>C</strong> background. My emphasis is on code comprehension.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T08:55:33.557", "Id": "10740", "Score": "0", "body": "You got **Magnus Lie Hetland**'s version slightly wrong. The line that reads `i = start` is indented one level too far." } ]
[ { "body": "<p>I think your code is more straightforward, but its size is a bit daunting. I actually like the original better. The only real 'trick' it uses is multiple assignment. And while it requires you to think through the different cases of <code>range</code> a bit to realize it works, this isn't something I mind. In fact, with yours, if I were to verify its correctness I'd have to spend just as much time because it has so much more code.</p>\n\n<p>I tend to prefer code that's a bit terse, but elegantly handles all the cases to code that laboriously checks each case and handles that case with case-specific code. And this is in any programming language.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T08:24:23.420", "Id": "10737", "Score": "0", "body": "Thanks I get the point.less code if not complicated even if complex." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T06:28:15.500", "Id": "6860", "ParentId": "6858", "Score": "3" } }, { "body": "<p>This is bad</p>\n\n<pre><code> while start &lt; stop:\n result.append(start)\n start+=step\n</code></pre>\n\n<p>Don't reuse <code>start</code> to be the index of the loop. It's confusing. It violates the <em>meaning</em> of start. </p>\n\n<p>The lengthy parameter parsing is good, but can be made more clear. Don't waste time on checking for <code>&lt;1</code> or <code>&gt;3</code>. Just use the <code>if</code> statement.</p>\n\n<pre><code>if len(args)==1:...\nelif len(args)==2:...\nelif len(args)==3:...\nelse:\n raise TypeError( \"Wrong number of arguments\" )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T04:04:45.407", "Id": "11409", "Score": "0", "body": "Well,the range() built-in shows the argument No in exception message like **range expected at least 1 arguments, got 0**.I wanted to emulate it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T13:29:22.843", "Id": "11437", "Score": "0", "body": "@Jibin: \"built-in shows the argument number\". That doesn't mean it's **good** design. It should also be part of the `else` clause if it's so important to provide that kind of message." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T04:32:19.820", "Id": "11584", "Score": "0", "body": ":got that.I think there is a psychological reason to 'why error/exception should be in else case'.Suppose a programmer is reading the code, for first few moments his mind is fresh so main logic should come first,error/exceptions can come last.What do you think?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T23:06:05.583", "Id": "11669", "Score": "0", "body": "\"logic should come first,error/exceptions can come last.\" I'm unclear on how it can be otherwise. What's the alternative?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T06:57:35.190", "Id": "12048", "Score": "0", "body": "As in my code - the exception comes first in the `if` clause and actual the calculation of `range` comes last in the `else` clause." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T13:07:34.513", "Id": "12067", "Score": "0", "body": "@Jibin: I'm confused. First you say \"logic should come first,error/exceptions can come last\". I agree with you. Then you say \"the exception comes first in the if clause\". I thought you agreed that the exception should come first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T11:43:25.263", "Id": "12447", "Score": "0", "body": "Never mind.Thank you for putting up with me this far" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T12:01:12.643", "Id": "6916", "ParentId": "6858", "Score": "3" } }, { "body": "<p>You've replaced three named arguments with a variable-length list of anonymous arguments and three seperate ways of mapping list positions onto named variables ... I'd question why that seems clearer to you.</p>\n\n<p>You're then manually enforcing constraints on the variable-length argument list which the interpreter handled for you in the original code.</p>\n\n<p>And, finally, where you <code>raise</code> an exception, you don't need to put the following code in an <code>else</code> block: if you're coming from <strong>C</strong>, think of the <code>raise</code> more like an early return.</p>\n\n<p>eg.</p>\n\n<pre><code>def interval(*args): \n if len(args)&lt;1:\n raise TypeError('range expected at least 1 arguments, got 0')\n if len(args)&gt;3 :\n raise TypeError('range expected at most 3 arguments, got %d' % len(args))\n if len(args)==1:\n ...\n</code></pre>\n\n<p>(although S.Lott's formulation is better still).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:38:12.620", "Id": "10825", "Score": "0", "body": "The problem with the version that has three named arguments is that those names aren't necessarily indicative of what the argument does, i.e. if you call `interval(3)` the name of the first argument is `start` even though its semantics are `stop`. So for that reason alone I think the `*args` version is actually clearer - at least the user won't make any assumptions about what the arguments to without consulting the documentation first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:31:32.420", "Id": "10917", "Score": "0", "body": "OK, good point: the code itself still looks more readable to me, but might also be misleading." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T04:23:57.970", "Id": "11410", "Score": "0", "body": "Ok,I agree that **else & elif** is not required,but they make sure that only one block gets executed for sure,though logically there is no possibility for multiple **if** blocks getting executed in your code cos exception is **raised** .Is there any performance penalty if I use **elif or else** than **if**" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T14:53:29.490", "Id": "6921", "ParentId": "6858", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T05:59:50.693", "Id": "6858", "Score": "3", "Tags": [ "python", "c" ], "Title": "Thinking in python" }
6858
<p>The script takes a string such as this: <code>(15, 176) (65, 97) (72, 43) (102, 6) (191, 189) (90, 163) (44, 168) (39, 47) (123, 37)</code> and breaks it into an array of arrays. It then computes the largest possible number of choices, with the guideline that each selected array has to have both numbers smaller than the previous selection. For the above string, the right output would be <code>4</code>.</p> <pre><code>people = File.read(ARGV[0]) people = people.sub("\(", '').sub(/\)$/, '').split("\) \(") people.map! { |p| p.split(', ') } count = 0 test = people.permutation.to_a test.each do |perm| test_count = 0 perm.each_with_index do |item, i| test_case = perm[i+1] unless test_case == nil test_count += 1 if item[0] &gt; test_case[0] &amp;&amp; item[1] &gt; test_case[1] end count = [count, test_count].max end end p count </code></pre> <p>Anyways, it works but is sloooow, especially with longer strings. How can I speed this up? I know the nested loops can be problematic and as the string grows the number of permutations grows. Any advice would be much appreciated. </p> <p>Edit: I am running this on Ruby 1.8.7.</p> <hr> <p>Edit: New attempt at the problem/script:</p> <pre><code>people = '(15, 176) (65, 97) (72, 43) (102, 6) (191, 189) (90, 163) (44, 168) (39, 47) (123, 37)' #people = File.read(ARGV[0]).chomp people = people.sub("\(", '').sub(/\)$/, '').split("\) \(") people.map! { |p| p.split(', ').map {|a| a.to_i } } ht = people.sort_by { |h| h[0] } wt = people.sort_by { |w| w[1] } a_i = [] ht.each do |item| a_i &lt;&lt; wt.index(item) end def subgen( array, count=1, t=(array.length+1) ) if array.length == 1 return count end without = subgen(array[0..-2], count, t) if array[0] &gt; array[-1] || array[-1] &gt; t return without else with = subgen(array[0..-2], count+=1, t = array[-1]) return [with, without].max end end current = 0 a_i.each_with_index do |item, j| test = a_i[j..-1] current = [current, subgen(test)].max end p current </code></pre> <p>This has been thoroughly tested and works, but there has to be a way to make it faster. Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T22:01:06.880", "Id": "10888", "Score": "0", "body": "On my machine, the first code takes 10.776s while the second one takes 0.005s. That's 2000x faster !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T03:31:26.330", "Id": "10896", "Score": "0", "body": "@barjak It is incredibly faster! but I think it can still be made faster. For long lists subgen gets called a lot and I wonder if there is a way to reduce that some how. I've been reading about [memoization](http://en.wikipedia.org/wiki/Memoization) but I can't figure out how to apply it to my new script." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-17T10:49:10.623", "Id": "14251", "Score": "0", "body": "I realized that your problem seems to be somewhat similar to the [longest common subsequence problem](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem)." } ]
[ { "body": "<p>So, you are generating every possible permutations of the array, which is a O(n!) operation. This is huge.</p>\n\n<p>I think this can be done with an O(n²) algorithm. I would do :</p>\n\n<ul>\n<li>create an array containing the pairs, ordered by the first value</li>\n<li>create another one containing the pairs, ordered by the second value</li>\n<li>create a third array containing, for each index of the first array, the index in the second array where we can find the corresponding value.</li>\n<li>find every subset of this third array whose values are in ascending order.</li>\n</ul>\n\n<p>The result is the length of the biggest subset.</p>\n\n<h3>Example</h3>\n\n<pre><code>first array | second array | third array\n------------+--------------+------------\n15,176 | 102,6 | 7\n39,47 | 123,37 | 3\n44,168 | 72,43 | 6\n65,97 | 39,47 | 4\n72,43 | 65,97 | 2\n90,163 | 90,163 | 5\n102,6 | 44,168 | 0\n123,37 | 15,176 | 1\n191,189 | 191,189 | 8\n</code></pre>\n\n<p>The ascending subsets are :</p>\n\n<ul>\n<li>7 8</li>\n<li>3 6 8</li>\n<li>3 4 5 8</li>\n<li>6 8</li>\n<li>4 5 8</li>\n<li>2 5 8</li>\n<li>5 8</li>\n<li>0 1 8</li>\n<li>1 8</li>\n<li>8</li>\n</ul>\n\n<p>The biggest subset is (3 4 5 8), and its size is 4.</p>\n\n<h3>Complexity</h3>\n\n<p>The sorts can be done with O(n log n)\nThe creation of the third array is O(n²)\nTo find the subset, I think we can do that with O(n²) (I'm not sure about that)</p>\n\n<p>So, the whole thing should be O(n²).</p>\n\n<p>The algorithm for finding the ascending subsets is not trivial. I'm sure it will be fun to implement !</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T13:58:27.413", "Id": "6867", "ParentId": "6861", "Score": "5" } }, { "body": "<p>The code below follows the known rule: use the simplest possible algorithm, unless some code-probing bottleneck analysis (with your particular data) proves it insufficiently fast.</p>\n\n<p>So, it basically uses the algorithm you first gave, plus @barjak's indices, and his insights both into what you are doing, and into the fact that combinations are as good as permutations, after they are both sorted. Also:</p>\n\n<ul>\n<li>Since finding the largest is the goal, it starts with the largest and works smaller so it can stop as soon as it finds the first one.</li>\n<li>It converts the numbers so it can work with the faster binary instead of strings.</li>\n<li>It doesn't convert the huge enumerable (of combinations or even permutations) into an array, which stores everything in memory and could cause a paging slowdown, but individually checks its entries.</li>\n<li>Using Ruby library methods when possible (mostly written in C), rather than our own Ruby code, speeds up execution.</li>\n</ul>\n\n<p>The Ruby <a href=\"http://ruby-doc.org/core-1.9.3/Array.html#method-i-combination\" rel=\"nofollow\">library</a> 'makes no guarantees about the order in which the combinations are yielded', so at first I didn't trust it to keep the order of the indices when giving combinations of them, but I put in such a further algorithmic optimization to avoid sorting by height for every combination.</p>\n\n<p>Also, I bail out as soon as I find the weights out of order, rather than sort the entire combination's worth. But still it will be O(n!) because, almost n times, it checks almost n!/(n-k)!k! combinations, each of length k. And, it still takes a long time: 16 seconds at just 22 pairs (with my setup). 19 pairs takes 2 seconds.</p>\n\n<p>I found your description, 'the largest possible number of choices with the guidelines that each selected array has to have both numbers smaller than the previous selection' somewhat hard to interpret. So, I read your code instead, and came up with:</p>\n\n<p>Problem: drawing from a set of integer 2-tuples, find the length of the longest subset which can strictly increase in both variables.</p>\n\n<p>For your test data, I got 4 also.</p>\n\n<pre><code>def print_time\n p Time.new.sec\nend\n\ndef increasing?(array, indices)\n f = array.at indices.first\n skip_first = 1\n# Compare adjacent pairs.\n (skip_first...indices.length).reduce(f) do |memo,i|\n each = array.at indices.at i\n return false unless memo &lt; each # Bail out quickly.\n each # Slide the pair.\n end\n true\nend\n\ndef search\n# Get filename.\n ##fn = ARGV.at 0\n\n# Read string containing parenthesized pairs of numbers.\n ##paren = File.read fn\n# Or, use test string.\n ##paren = '(15, 176) (65, 97) (72, 43) (102, 6) (191, 189) (90, 163) (44, 168) (39, 47) (123, 37)'\n# Or, generate repeatable random numbers.\n srand 0\n n, max = 22, 100000\n paren=(0...n).map{(0..1).map{rand max}}.map{|a,b| \"(#{a}, #{b})\"}.join ' '\n print_time\n\n# Translate to array syntax.\n# Add commas.\n commas = paren.gsub ') (', '),('\n\n# Convert parentheses to brackets.\n brack = commas.tr '()', '[]'\n s = \"[ #{brack} ]\"\n\n# Convert into pairs of numbers in binary.\n people = eval s\n\n# Pre-sort people by height then weight, which may speed sorting the combinations.\n people = people.sort\n\n# Remove duplicates, which could reduce the length considerably, depending on the data.\n people = people.uniq\n\n# Get single numbers in binary.\n ht = people.map{|e| e.first} # Height.\n wt = people.map{|e| e.last } # Weight.\n\n# Set up indices.\n pl = people.length\n p \"N after removing duplicates is #{pl}.\"\n indices = (0...pl).to_a\n\n result = 0 # Preserve the result after the block.\n\n# Start from the largest size of subset and go downward.\n decreasing_sizes = (1..pl).to_a.reverse\n decreasing_sizes.each do |size|\n\n# Use combinations instead of permutations.\n# Don't produce a big array of combinations, because\n# it could be causing slow virtual-memory paging.\n# Instead, check each combination when it is supplied.\n\n indices.combination(size).each do |comb|\n\n# Each combination is sorted already in increasing order by height.\n ## comb = comb.sort{|i,k| (ht.at i) &lt;=&gt; (ht.at k)}\n\n# Check whether the weights are also in increasing order.\n next unless increasing? wt, comb\n w = wt.values_at *comb # Double check.\n next unless w.sort==w\n\n# We have found our first subset, which is increasing in both\n# height and weight.\n# Therefore, its size is the largest good subset size.\n# Report this size and stop.\n result = [size, comb.map{|i| people.at i}]\n throw :result, result\n end\n end\nend\n\nlength, pairs = catch(:result){ search}\np \"One of the longest subsets has length #{length}: #{pairs.inspect}, length #{length}.\"\nprint_time\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-23T23:19:18.470", "Id": "8231", "ParentId": "6861", "Score": "1" } }, { "body": "<p>Best for this is an algorithm similar to <a href=\"http://en.wikipedia.org/wiki/Patience_sorting\" rel=\"nofollow\">Patience sorting</a>. I wrote some Ruby code that processes tens of thousands of pairs in something like a few seconds. You're welcome to write me if you're still interested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-20T20:47:51.700", "Id": "10199", "ParentId": "6861", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T06:45:04.980", "Id": "6861", "Score": "5", "Tags": [ "optimization", "ruby" ], "Title": "This script works but keeps timing out with longer inputs. How can I improve its speed? [Ruby]" }
6861
<p>I took the Python class at Google code today, and this is what I made for the problem about building a word counter.</p> <p>Please take a look and suggest any improvements that can be done. Please do point out the bad practices if I have used any.</p> <pre><code>import sys def make_dict(filename): """returns a word/count dictionary for the given input file""" myFile=open(filename,'rU') text=myFile.read() words=text.lower().split() wordcount_dict={} #map each word to its count for word in words: wordcount_dict[word]=0 for word in words: wordcount_dict[word]=wordcount_dict[word]+1 myFile.close() return wordcount_dict def print_words(filename): """prints each word in the file followed by its count""" wordcount_dict=make_dict(filename) for word in wordcount_dict.keys(): print word, " " , wordcount_dict[word] def print_top(filename): """prints the words with the top 20 counts""" wordcount_dict=make_dict(filename) keys = wordcount_dict.keys() values = sorted(wordcount_dict.values()) for x in xrange (1,21): #for the top 20 values for word in keys : if wordcount_dict[word]==values[-x]: print word, " ",wordcount_dict[word] def main(): if len(sys.argv) != 3: print 'usage: ./wordcount.py {--count | --topcount} file' sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_words(filename) elif option == '--topcount': print_top(filename) else: print 'unknown option: ' + option sys.exit(1) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>I like the way you've broken down the code into functions, I think it makes sense and avoids repetition or duplication of code and functionality.</p>\n\n<p>One slight improvement to consider here is to have <code>print_words</code> and <code>print_top</code> take the dictionary returned from <code>make_dict</code> rather than calling it as their first step. In addition to avoiding a tiny amount of duplicated code, this sort of \"function composition\" when used effectively can be a very powerful design pattern, allowing very expressive and readable code for more complicated problems than this one.</p>\n\n<p>A few other specific thoughts:</p>\n\n<p>In <code>make_dict</code>, you're reading the entire file contents into memory, and then processing each word twice. This works well enough for small files, but imagine that you had a 500 gigabyte text file? In this case, reading the file into memory (\"buffering\" it) will lead to a program crash, or at the very least, very bad performance.</p>\n\n<p>Instead, you can actually iterate the file in a <code>for</code> loop, which will only read small portions of the file into memory at once. This requires a slight change to your logic in <code>make_dict</code>:</p>\n\n<pre><code>myFile=open(filename,'rU')\nwordcount_dict={} #map each word to its count\nfor line in myFile:\n # .strip() removes the newline character from the\n # end of the line, as well as any leading or trailing\n # white-space characters (spaces, tabs, etc)\n words = line.strip().lower().split()\n for word in words:\n if word not in wordcount_dict:\n wordcount_dict[word] = 0\n wordcount_dict[word] += 1\n</code></pre>\n\n<p>In <code>print_words</code>, you're using <code>.keys()</code> to get the words from the <code>wordcount_dict</code>, then accessing those keys from the dictionary. This works fine, but Python dictionaries allow you to get <em>items</em> (that is, key-value pairs) directly when iterating a dictionary, using <code>.items()</code> instead of <code>.keys()</code>:</p>\n\n<pre><code>for word, count in wordcount_dict.items():\n print word, \" \" , count\n</code></pre>\n\n<p><code>items()</code> returns a list of length-2 tuples, and the <code>for word, count in ...</code> syntax \"unpacks\" those tuples into the variables <code>word</code> and <code>count</code>.</p>\n\n<p>Building on this technique, we can simplify <code>print_top</code> as well. Once we have in hand a list of each (word, count) pair (the length-2 tuples), we can sort that list, and then print only the top 20 words (ranked by their count):</p>\n\n<pre><code>wordcount_dict=make_dict(filename)\nword_count_pairs = wordcount_dict.items()\nword_count_pairs.sort(\n # use a \"key\" function to return the sort key\n # for each item in the list we are sorting; here\n # we return index 1 -- that is, the count -- to\n # sort by that\n key=lambda pair: pair[1],\n\n # reverse the sort so that the words with the\n # highest counts come first in the sorted list\n reverse=True\n)\n\n# make a copy of the first 20 elements of the\n# list, using slice notation\ntop_word_count_pairs = word_count_pairs[:20]\n\nfor word, count in top_word_count_pairs:\n print word, \" \",wordcount_dict[word]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T13:15:47.277", "Id": "6865", "ParentId": "6863", "Score": "2" } }, { "body": "<p>I'd write <code>make_dict</code> function this way: </p>\n\n<pre><code>def make_dict(filename):\n wordcount_dict={}\n with open(filename,'rU') as myFile:\n for line in myFile:\n words = line.strip().lower().split()\n for word in words:\n wordcount_dict.setdefault(word, 0) \n wordcount_dict[word] += 1\n return wordcount_dict\n</code></pre>\n\n<p><code>With</code> keyword closes file automatically if exception happens. \n{}.setdefault() is more pythonic than the condition which @dcrosta suggested.</p>\n\n<p>What about <code>main</code> function, there is an excellent python library <a href=\"http://docs.python.org/library/optparse.html\" rel=\"nofollow\">optparse</a>, which helps parsing command line options. Check it if you need more complex user interface. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T10:08:58.340", "Id": "10809", "Score": "0", "body": "i was not aware of the setdefault() method of dictionary .with..as thing is new to me too..and about optparse , i am just starting out .So I guess i'll check that out later..thanks for the tip though :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T05:45:12.320", "Id": "6911", "ParentId": "6863", "Score": "3" } }, { "body": "<p>If you have to prepare a word counter, then the more adequate container is <code>collections.defaultdict</code></p>\n\n<p>Then your <code>make_dict</code> function could be written much more simply:</p>\n\n<pre><code>def make_dict(filename):\n \"\"\"returns a word/count dictionary for the given input file\"\"\"\n wordcount_dict = defaultdict(int)\n with open(filename, 'rU') as myFile:\n for line in myFile:\n words = line.strip().lower().split()\n for word in words: \n wordcount_dict[word] += 1\n return wordcount_dict\n</code></pre>\n\n<p>Note that you don't need to care about initialization of dictionary entries for new keys for word counting, as <code>defaultdict</code> takes care of it.</p>\n\n<p><strong>Another different approach is to use OOP</strong>. That is, to create a word counter object with state initialization, methods and all the stuff. The code gets simplified, encapsulated and ready to be extended.</p>\n\n<p>Below, there is a working OOP proposal. There are some improvements that can be implemented also in your functional version if you don't like OOP:</p>\n\n<p>1) I simplified your methods. Now there is only one method <code>print_words(self, number=None)</code>. If you want the best 20 then just indicate the number of words.</p>\n\n<p>2) I included some optimizations to clean words that are splitted with punctuation characters (otherwise <code>house</code>, <code>house.</code> and <code>house'</code> would be counted as different), using constants from the <code>string</code> module.</p>\n\n<pre><code>non_chars = string.punctuation + string.whitespace\nwords = [item.strip(non_chars).lower() for item in line.split()]\n</code></pre>\n\n<p>3) I used <code>operator.itemgetter</code> for the sorting key (instead of lambdas. More readable, imho)</p>\n\n<p>4) I used formatting for the print for a better look. Used classical <code>%</code>.</p>\n\n<pre><code>import operator\nimport string\nfrom collections import defaultdict\n\nclass WordCounter(defaultdict):\n def __init__(self, filename):\n defaultdict.__init__(self, int)\n self.file = filename\n self._fill_it()\n\n def _fill_it(self):\n \"fill dictionary\"\n non_chars = string.punctuation + string.whitespace\n with open(self.file, 'rU') as myFile:\n for line in myFile:\n words = [item.strip(non_chars).lower() for item in line.split()]\n for word in words: \n self[word] += 1\n\n def print_words(self, number=None):\n \"\"\"prints the words with the top &lt;number&gt; counts\"\"\"\n wc_pairs = self.items()\n wc_pairs.sort(key=operator.itemgetter(1), reverse=True)\n number = number or len(wc_pairs)\n for word, count in wc_pairs[:number]:\n print \"%-20s%5s\" % (word, count)\n\n\nmy_wc = WordCounter('testme.txt')\n\nprint my_wc['aword'] # print 'aword' counts\nmy_wc.print_words() # print all (sorted by counts)\nmy_wc.print_words(3) # print top 3\n</code></pre>\n\n<p>And a final note: leaving a blank space before and after an operator and after commas in lists, increases readability of the text and is considered good practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T21:15:13.553", "Id": "6951", "ParentId": "6863", "Score": "5" } } ]
{ "AcceptedAnswerId": "6865", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T12:41:18.810", "Id": "6863", "Score": "6", "Tags": [ "python", "optimization", "programming-challenge" ], "Title": "Optimizing word counter" }
6863
<p>I am writing some code to turn a multi level UL into an accordion:</p> <pre><code>$(document).ready(function () { $('.s4-ql li ul').each(function (index) { $(this).hide(); }); $('.s4-ql ul li ul').each(function (index) { var length = 0; length = $(this).children().length; var CurrentItem = $(this).parent().find('a:first'); CurrentItem.find('.menu-item-text').append('&lt;span style=\'float:right;font-size:0.8em;\'&gt;(' + length + ')&lt;/span&gt;'); }); $('.s4-ql ul li').hover( function () { $(this).find('a:first').next().slideToggle('normal'); }, function () { $(this).find('a:first').next().slideToggle('normal'); } ); }); </code></pre> <p>Can anyone tell me whether I am being relatively efficient or whether there is anywhere that I can "trim the fat", so to speak? The code also counts the number of children and displays that number on the main parent.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:13:58.033", "Id": "10752", "Score": "1", "body": "Also, speaking of \"trimming the fat\", please don't write tags in titles and signatures in questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:18:56.460", "Id": "10753", "Score": "0", "body": "What do you mean Tom? sorry? - As for code review..thx for that link, was not aware of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:23:54.003", "Id": "10758", "Score": "0", "body": "@user257503: I mean, please don't write tags in titles (like \"jQuery: \"), and signatures/thanks are not required (and will be edited out) as you're writing a question not an email! ta [not the same for comments :P]" } ]
[ { "body": "<p>All jQuery mutation methods operate on every element in the set.<br>\nYou can just write <code>$('.s4-ql li ul').hide()</code>; you don't need <code>.each</code>.</p>\n\n<p>Also, you should just write <code>var length = $(this).children().length;</code> in one line.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:13:31.130", "Id": "6870", "ParentId": "6869", "Score": "1" } }, { "body": "<p>It'll be good if you can provide your HTML markup. Without it I can do this:</p>\n\n<pre><code>jQuery(function($) {\n $('.s4-ql li ul').hide();\n $('.s4-ql ul li').hover(function() {\n $(this).find('a:first').next().slideToggle();\n }, function() {\n $(this).find('a:first').next().slideToggle();\n }).find('ul').each(function(index) {\n var $this = $(this);\n $this.parent().find('a:first .menu-item-text').append(['&lt;span style=\\'float:right;font-size:0.8em;\\'&gt;(', $this.children().length, ')&lt;/span&gt;'].join(''));\n });;\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:24:10.800", "Id": "6871", "ParentId": "6869", "Score": "3" } } ]
{ "AcceptedAnswerId": "6871", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T15:10:27.593", "Id": "6869", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Making an accordion from a multi-level HTML list" }
6869
<p>How I can change this multi-loop to reduce the computation time?</p> <p><code>A</code> is a matrix (5 × 10000) where the fifth line contains values between 1 and 50 corresponding to different events of an experiment. My goal is to find the columns of the matrix which are the same for all possible combinations of 7 different events.</p> <pre><code>data = A(1:4,:); exptEvents = A(5,:); % Find repeats [b,i,j] = unique(data', 'rows'); % Organize the indices of the repeated columns into a cell array reps = arrayfun(@(x) find(j==x), 1:length(i), 'UniformOutput', false); % Find events corresponding to these repeats reps_Events = cellfun(@(x) exptEvents(x), reps, 'UniformOutput', false); U = cellfun(@unique, reps_Events, 'UniformOutput', false); repeat_counts = cellfun(@length, U); kk=1; for i1=1:50 for i2=1:50 for i3=1:50 for i4=1:50 for i5=1:50 for i6=1:50 for i7=1:50 if i1~=i2 &amp;&amp; i2~=i3 &amp;&amp; i3~=i4 &amp;&amp; i4~=i5 &amp;&amp; i5~=i6 &amp;&amp; i6~=i7 myEvents = [i1 i2 i3 i4 i5 i6 i7]; v= b(cellfun(@(x)all(ismember(myEvents,x)),U),:); intersection(1,kk)=v(1); intersection(2,kk)=v(2); intersection(3,kk)=v(3); intersection(4,kk)=v(4); intersection(5,kk)=i1; intersection(6,kk)=i2; intersection(7,kk)=i3; intersection(8,kk)=i4; intersection(9,kk)=i5; intersection(10,kk)=i6; intersection(11,kk)=i7; kk=kk+1; end end end end end end end end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:19:27.847", "Id": "10776", "Score": "0", "body": "I'm not sure I understand your problem clearly - does the 5th row of `A` contain a cell for each column, each with 7 values (1-50) in it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:34:08.987", "Id": "10777", "Score": "0", "body": "I think the problem is the need to avoid 'for' loops. otherwise you can see my last question (Intersection of several sets of results corresponding to different events in matlab) for an example (5x20) of the matrix A." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:49:29.397", "Id": "10778", "Score": "0", "body": "So does the code you pasted here give the desired output, it just takes too long?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T23:16:13.567", "Id": "10779", "Score": "0", "body": "yes this is the case for code" } ]
[ { "body": "<p>There's quite a few things that you can do to reduce computation time.</p>\n\n<p>First of all, if you know that an outcome has to be the combination of seven events, you can throw out whatever has fewer of them.</p>\n\n<p>Then, you can preassign the output array (growing in a loop is usually not very fast).</p>\n\n<p>Finally, you want to generate all possible subsets if there are, say, 9 events from which you can choose 7. </p>\n\n<p>So you'd start</p>\n\n<pre><code>%# throw out useless stuff\ntooFewIdx = repeat_counts &lt; 7;\n\nb(tooFewIdx,:) = [];\nU(tooFewIdx) = [];\nrepeat_counts(tooFewIdx) = [];\n\n%# estimate how many combinations you will get\nnPerms = arrayfun(@(x)nchoosek(x,7),repeat_counts);\n\nintIdx = [0;cumsum(nPerms(:))];\n\n%# pre-assign output\n%# If this runs out of memory, try using integer formats\n%# instead, e.g. zeros(...,'uint8') if no value is above 255\nintersection = zeros(intIdx(end),11);\n\n%# loop to fill intersection\nfor i=1:length(U)\n\n%# fill in the experiment information\nintersection((intIdx(i)+1):intIdx(i+1),1:4) = repmat(b(i,:),nPerms(i),1);\n\n%# add all combinations of events\nintersection((intIdx(i)+1):intIdx(i+1),5:11) = combnk(U{i},7);\n\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T23:58:20.973", "Id": "10781", "Score": "0", "body": "??? Maximum variable size allowed by the program is exceeded.\n\nError in ==> intersection = zeros(intIdx(end),11); I have values ​​that are above 1000" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T05:09:22.427", "Id": "10782", "Score": "0", "body": "@bzak: If you are trying to choose 7 out of 50, then you're going to do a lot of combinations, which means that you will not have enough memory to create the variable. Maybe you may have to rethink your approach to whatever problem it is you're trying to solve." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T12:27:56.803", "Id": "10783", "Score": "0", "body": "I reduced the matrix to a size of (5x2000) and tried to see the results for all 3 possible combinations.\nI found the first error:\n??? Subscript indices must either be real positive integers or logicals.\nError in ==> intersection((intIdx(i-1)+1):intIdx(i),1:4) = repmat(b(i,:),nPerms(i),1);\nSo I replaced (for i = 1: length (U)) by (for i = 2: length (U))\nbut I got the second error:\n??? Subscripted assignment dimension mismatch.\nError in ==> intersection((intIdx(i-1)+1):intIdx(i),1:4) = repmat(b(i,:),nPerms(i),1);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T19:34:02.557", "Id": "10785", "Score": "0", "body": "@user319336: turns out that I made an error with the indices. This should hopefully work." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:43:10.193", "Id": "6879", "ParentId": "6878", "Score": "1" } } ]
{ "AcceptedAnswerId": "6879", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T21:46:35.777", "Id": "6878", "Score": "0", "Tags": [ "performance", "algorithm", "matrix", "combinatorics", "matlab" ], "Title": "Finding columns of a matrix that are the same for combinations of events" }
6878
<p>I have a pan control that look like this:</p> <p><img src="https://i.stack.imgur.com/n8lif.png" alt="pan control"></p> <p>Pretty standard Google Mapsish controls, IMO.</p> <p>When the user clicks in the top 3rd of the control, it should pan up (deltaY = +1); right third means it should pan east (deltaX = -1); Down is deltaY = -1, and West is deltaX = +1. The control is 50px, square. I have working code, but I believe it can be written much more elegantly than this using a single (if discontinuous) mathematical function.</p> <pre><code>$(control).click(function (evt) { var clickPointX = (evt.layerX || evt.offsetX), clickPointY = (evt.layerY || evt.offsetY), deltaX, deltaY; // control is 50x50 px. // Click in the top third, get a positive 'Y' value. // Click in the left third, get a positive 'X' value. // Click in the middle, get zero. if (clickPointX &lt; 16) { deltaX = +1; } else if (clickPointX &gt; 34) { deltaX = -1; } else { deltaX = 0; } if (clickPointY &lt; 16) { deltaY = +1; } else if (clickPointY &gt; 34) { deltaY = -1; } else { deltaY = 0; } map.panDirection(deltaX, deltaY); }); </code></pre>
[]
[ { "body": "<p>Well, if you want less repetition, you can do this.\nBut I don't think there's anything wrong with your\napproach (which is more efficient incidentally).</p>\n\n<pre><code>var pan = function(clickx, clicky){\n var delta = function(val){\n return val &lt; 16 ? 1 :\n val &gt; 34 ? -1 :\n 0;\n };\n return {dx: delta(clickx), dy: delta(clicky)};\n};\n</code></pre>\n\n<p>I do think you should separate out the click handling\nand the panning algorithm into separate functions unless efficiency\nthen becomes an issue.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T04:38:31.380", "Id": "10803", "Score": "0", "body": "You're right. I will probably do that, I just wanted to see if this could be made into a simple discontinuous mathematical function first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T02:35:07.533", "Id": "10939", "Score": "1", "body": "What I've written is a simple discontinuous mathematical function :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T20:11:12.997", "Id": "6884", "ParentId": "6883", "Score": "1" } }, { "body": "<p>A few improvements:</p>\n\n<ul>\n<li>replace magic numbers</li>\n<li>extract repetition into a function</li>\n<li>dynamically calculate dimensions</li>\n</ul>\n\n<p>Example code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getDelta(clickPoint, controlDimension, threshold){\n var delta;\n if (clickPoint &lt; threshold) {\n delta = +1;\n } else if (clickPoint &gt; controlDimension- threshold) {\n delta = -1;\n } else {\n delta = 0;\n }\n return delta;\n}\n\n$(document).ready(function () {\n var control = $('#example');\n var controlHeight = control.height();\n var controlWidth = control.width();\n var widthThreshold = controlHeight/3;\n var heightThreshold = controlWidth/3;\n \n $(control).click(function (evt) {\n var clickPointX = (evt.layerX || evt.offsetX);\n var clickPointY = (evt.layerY || evt.offsetY);\n var deltaX = getDelta(clickPointX, controlWidth, widthThreshold);\n var deltaY = getDelta(clickPointY, controlHeight, heightThreshold);\n alert('delta x: ' + deltaX + '\\n' + 'delta y: ' + deltaY);\n //map.panDirection(deltaX, deltaY);\n });\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;html&gt;\n &lt;div id='example' style='background-color: red; height: 50px; width: 50px;' /&gt;\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T04:16:04.160", "Id": "6908", "ParentId": "6883", "Score": "3" } }, { "body": "<p>Probably more of a personal preference but i find three sections to an <code>if</code> hard to read.</p>\n\n<p>I would set your Delta values to 0 initially</p>\n\n<pre><code>var deltaX = 0;\n</code></pre>\n\n<p>then you can remove:</p>\n\n<pre><code>} else {\n deltaX = 0;\n}\n</code></pre>\n\n<p>and you have three less lines to read. Not a real performance improvement or anything though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T04:46:16.233", "Id": "6909", "ParentId": "6883", "Score": "0" } } ]
{ "AcceptedAnswerId": "6908", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T19:47:07.767", "Id": "6883", "Score": "3", "Tags": [ "javascript", "functional-programming", "user-interface" ], "Title": "Handler for a control to pan a map in four directions" }
6883
<p>Are there issues of any kind with this extension method?</p> <pre><code>using System; using System.Web; namespace AccountingBackupWeb.CacheExtensions { public static class Extensions { public static T Get&lt;T&gt;(this System.Web.Caching.Cache cache, string key, Func&lt;T&gt; f) where T : class { T results = HttpContext.Current.Cache[key] as T; if (results == null) { results = f(); HttpContext.Current.Cache[key] = results; } return results; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:25:03.920", "Id": "10788", "Score": "3", "body": "Why do you have `cache` as the first parameter when you don't use it in the method at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T22:07:21.857", "Id": "10789", "Score": "0", "body": "the only reason is so that it is an extension method as opposed to a static utility function.. good point though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T08:59:00.880", "Id": "10808", "Score": "3", "body": "but if you are not actually doing anything with \"cache\" why should this be an extension method on that type?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T16:01:36.313", "Id": "10814", "Score": "0", "body": "ah, it took me a minute, but your saying make the first line of the implementation T results = cache[key] as T, right?" } ]
[ { "body": "<p>Without some more context on what your goals and/or concerns are its hard to say. This seem ok, although passing delegate functions is relatively expensive so if hyper-performance is required, you should refactor that. Aside from that, the only issue may be <code>HttpContext.Current</code> being null which would cause a NullReferenceException, although I assume this is not possible given your hosting scenario.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:29:23.587", "Id": "6891", "ParentId": "6885", "Score": "3" } }, { "body": "<p>Logically, it makes sense to me that you would want to tie a key to a Func. This method could then just take the string and then delegate the responsibility to decide how to fetch the value to another class. Also, a few nitpicky points about what is actually there. I consider using letters as variables poor practice since it gives no context as to how it will be used. I would rename \"f\" to something like \"retrieve\" or \"fetch\". Also, there is no guarantee that running \"f\" will actually give you a non null value. In that case, I doubt you would want to store null in your cache.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T02:42:19.243", "Id": "6907", "ParentId": "6885", "Score": "4" } }, { "body": "<p>As JoeGeeky said <code>HttpContext.Current</code> might be null and it is better to ckeck it. But I also want to point out that from architectural point of view it is always better to incapsulate your cache host (<code>HttpContext.Current</code> in your case), so your framework cache getter method won't depend on Web classes.</p>\n\n<p>You can introduce an abstract class (or interface) <code>CacheHost</code> and on runtime configure which actual subclass will be used as cache host. In most of your cases it could be <code>HttpContext.Current</code>, but if you run a separate thread and there you will use methods that relies on your cache, then you will be able to leverage your cache mechanism even if there is no <code>HttpContext.Current</code> in that thread.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T05:50:43.327", "Id": "6912", "ParentId": "6885", "Score": "1" } }, { "body": "<p>I just have a little issue with the method name itself. It's not given by the name of a method called \"Get\" that it actually sets the cache value to the result of f if not already set, and then returns it.\nHow 'bout GetOrInitializeTo, and then having a Get method that just gets?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T20:56:09.700", "Id": "6971", "ParentId": "6885", "Score": "1" } }, { "body": "<p>In addition to what's already been said:</p>\n\n<ul>\n<li>the <code>key</code> parameter might be null</li>\n<li>the <code>f</code> parameter might be null</li>\n<li>The mechanism is highly inefficient if you actually want to cache <code>null</code> for a specific key </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T13:23:03.883", "Id": "7019", "ParentId": "6885", "Score": "1" } }, { "body": "<p>Since the <code>as T</code> operation will result in <code>null</code> if the value is actually not null but is not of type T, you might consider doing an extra check when <code>results</code> is null to determine whether the value in cache at that key is actually null. Example implementation shown below:</p>\n\n<pre><code> public static T Get&lt;T&gt;(this System.Web.Caching.Cache cache, string key, Func&lt;T&gt; f) where T : class\n {\n object value = cache[key];\n\n T results = value as T;\n\n if (results == null)\n {\n if (value != null)\n {\n // log a warning, because there is a non-null value in cache with this key, but it is not of the specified type.\n }\n\n results = f();\n cache[key] = results;\n }\n\n return results;\n }\n</code></pre>\n\n<p>Essentially, if <code>results</code> is null but <code>value</code> is not null, then that means that there is already some value in cache with the specified key that is not of type T. I would consider that situation a potential coding error, so I would most likely want to log a warning or an error if that were to happen.</p>\n\n<p>Alternatively, you could throw an exception. That would allow you to keep the details of your logging mechanism out of this utility method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T14:58:09.600", "Id": "7082", "ParentId": "6885", "Score": "1" } }, { "body": "<p>Use <code>var</code> when the right-hand side of a declaration makes its type obvious:</p>\n\n<pre><code>T results = HttpContext.Current.Cache[key] as T;\n</code></pre>\n\n<p>Should be</p>\n\n<pre><code>var results = HttpContext.Current.Cache[key] as T;\n</code></pre>\n\n<p>Here, the <code>as T</code> clause makes it very obvious that results is of type <code>T</code>. Using <code>var</code> means that changing <code>T</code> becomes a single operation, as opposed to changing it in two places.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T10:27:49.797", "Id": "87411", "ParentId": "6885", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T20:36:15.490", "Id": "6885", "Score": "6", "Tags": [ "c#" ], "Title": "Extension method to get results of type T from a cache" }
6885
<p><strong>Background information</strong></p> <p>I am building a web application that consumes 3 different WCF services that are hosted internally.</p> <p>Each response object from the service inherits from a base class <code>ResponseBase</code>. This class contains properties <code>int ErrorCode</code> and <code>string ErrorMessage</code>.</p> <p>When I am consuming these services in my web application I want to implement some general error handling that verifies if the response object contains an <code>errorcode &lt; 0</code>.</p> <p>What I've come up with is a static class <code>ServiceHelper</code> with several overloads of the following method:</p> <pre><code>public static void VerifyResponse(dynamic response) { if (response == null) throw new ArgumentNullException("response"); if (response.ErrorCode &lt; 0) throw new InvalidServiceResponseException(response.ErrorCode, response.ErrorMessage); } </code></pre> <p>Now as you can see the type of the parameter is dynamic. The reason for this, and this is basically why I'm asking this question, is that I don't have a general base object to define all response objects. Because each WCF service will creat its own contracts there can't be a shared base object between services. Well... <a href="http://www.freddes.se/2010/05/02/sharing-datacontracts-between-wcf-services/" rel="nofollow">it can be done</a> but we prefer to keep it simple for now.</p> <p><strong>Question</strong> </p> <p>Do you of some magic way to validate 3 different types of response objects but with a properly typed parameter and without creating a different method for each service. Because each service has a different <code>ResponseBase</code> type even though it is actually the same. </p> <p>Or do you think it is permitted to use a dynamic parameter in this context?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T05:42:36.303", "Id": "96131", "Score": "0", "body": "Well, some things cannot be done right and easy at the same time :)\nI recommend you reading [that article](http://code-magazine.com/Article.aspx?quickid=0809101). It won't make your implementation easier, but I am sure it will shed some light on how to organize work with WCF services better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T07:37:24.700", "Id": "96132", "Score": "0", "body": "Thanks for the article, It provides some alternatives. But keeping maintainability and KISS in mind, I think my current solution isn't so bad." } ]
[ { "body": "<p>Peter - a couple of observations:</p>\n\n<ol>\n<li>Since you say \"Each response object from the service inherits from a base class ResponseBase\" the gut reaction is to just use ResponseBase and let the inheritance model in C# handle everything. As you go on to explain, however, ResponseBase is not really the same base class across services, as they vary from service to service with generated code. In this case, you know exactly what the shape of the object is, but don't know its type. This is an example of '<a href=\"http://en.wikipedia.org/wiki/Duck_typing\" rel=\"nofollow\">duck typing</a>' - if it looks like a duck, walks like a duck, and quacks like a duck, then we might as well treat it like a duck. This is exactly what dynamic typing is good for and seems to me an excellent use of this feature of C# 4.0.</li>\n<li>The two exception conditions in your code are not created equal. The first seems to flag an incorrect use of the method, while the second is the method doing its job. So consider replacing the first one with a Code Contract if you are on .NET 4. (See Dino Esposito's articles in MSDN Magazine - 3 months in a row - for a good overview, starting <a href=\"http://msdn.microsoft.com/en-us/magazine/gg983479.aspx\" rel=\"nofollow\">here</a>. Note especially that Code Contracts can be turned off for runtime, and they may be off already in your project. See Dino's articles for an explanation.)</li>\n</ol>\n\n<p>Here is pseudocode:</p>\n\n<pre><code>public static void VerifyResponse(dynamic response) \n{\n Contract.Requires(response != null);\n // or perhaps: Contract.Requires&lt;ArgumentNullException&gt;(response != null, \"response\");\n // or: if (response == null) throw new ArgumentNullException(\"response\"); \n\n if (response.ErrorCode &lt; 0) \n throw new InvalidServiceResponseException(response.ErrorCode, response.ErrorMessage); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T11:28:38.463", "Id": "12446", "Score": "0", "body": "please reread the text below my code example in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-05T00:05:02.423", "Id": "13549", "Score": "0", "body": "@Peter - good point! I rewrote bullet 1. of my answer after re-reading the text below your code example. Bullet 2. still applies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-06T09:17:26.137", "Id": "13608", "Score": "0", "body": "Thanks for teaching me about the `Contract` class and pointing me to Code Contracts in general! Really helpful. And for approving my use of dynamic types in this case :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-13T14:14:57.877", "Id": "7768", "ParentId": "6886", "Score": "2" } } ]
{ "AcceptedAnswerId": "7768", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-01T08:49:20.357", "Id": "6886", "Score": "2", "Tags": [ "c#", "wcf" ], "Title": "WCF general response validation for multiple services" }
6886
<p>I'm writing a custom JavaScript converter to deserialize some JSON. Here's a few lines I'm writing:</p> <pre><code>public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer) { int NoteID; NotesModel TheObject = new NotesModel(); if (dictionary.ContainsKey("NoteID")) { if (int.TryParse(serializer.ConvertToType&lt;string&gt;(dictionary["NoteID"]), out NoteID)) { TheObject.NoteID = serializer.ConvertToType&lt;int&gt;(dictionary["NoteID"]); } } </code></pre> <p>How can this be improved?</p>
[]
[ { "body": "<p>you can do </p>\n\n<pre><code>TheObject.NoteID = NoteID;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:06:27.727", "Id": "6888", "ParentId": "6887", "Score": "7" } }, { "body": "<p>It would be like this, you are already converting it to int with the tryParse</p>\n\n<pre><code>public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer)\n {\n int noteID;\n NotesModel TheObject = new NotesModel();\n\n if (dictionary.ContainsKey(\"NoteID\"))\n {\n if (int.TryParse(serializer.ConvertToType&lt;string&gt;(dictionary[\"NoteID\"]), out noteID))\n {\n TheObject.NoteID = noteId;\n }\n }\n}\n</code></pre>\n\n<p>or even shorter</p>\n\n<pre><code>public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer)\n {\n int noteID;\n NotesModel TheObject = new NotesModel();\n\n if (dictionary.ContainsKey(\"NoteID\") &amp;&amp; int.TryParse(serializer.ConvertToType&lt;string&gt;(dictionary[\"NoteID\"]), out NoteID))\n {\n TheObject.NoteID = noteId;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-02T07:11:14.723", "Id": "11570", "Score": "1", "body": "You might want to have noteID in out parameter instead of NoteID. Sorry couldn't edit it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:07:32.983", "Id": "6889", "ParentId": "6887", "Score": "3" } }, { "body": "<p>I would recommend the following...</p>\n\n<pre><code>public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type, JavaScriptSerializer serializer) \n { \n int noteID; \n NotesModel TheObject = new NotesModel(); \n\n object value;\n\n if (dictionary.TryGetValue(\"NoteID\", out value)) \n { \n if (int.TryParse(serializer.ConvertToType&lt;string&gt;(value), out NoteID)) \n { \n TheObject.NoteID = noteId; \n } \n } \n}\n</code></pre>\n\n<p>This should cut your dictionary query by half.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:21:14.663", "Id": "6890", "ParentId": "6887", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T21:03:05.490", "Id": "6887", "Score": "4", "Tags": [ "c#", "converting", "serialization" ], "Title": "Converter for deserializing JSON" }
6887
<p>I'm working on a function that extracts information from an XML document and compares to what the user has typed in. Can you suggest any ways in which I can improve it? The variables in the XML file are compared against txtSearch.</p> <pre><code>function checkXML() { var s = ""; var albumPages = []; for (var i = 0; i &lt; xmlalbums.length; i++) { var xmlalbum = xmlalbums[i]; var album_title = dataFromTag(xmlalbum, 'title'); var artist = dataFromTag(xmlalbum, 'artist'); var xmltracks = xmlalbum.getElementsByTagName('track'); for (var t = 0; t &lt; xmltracks.length; t++) { var track = xmltracks[t]; song_title = dataFromTag(track, 'title') albumPages[albumPages.length] = artist.toUpperCase() + ':' + album_title.toUpperCase() + ':' + song_title.toUpperCase(); } } var resultList = ''; var resultCount = []; for (var i = 0; i &lt; albumPages.length; i++) { var searchArtist = albumPages[i].substring(0, albumPages[i].indexOf(":")); var searchAlbum = albumPages[i].substring(albumPages[i].indexOf(":") + 1, albumPages[i].lastIndexOf(":")); var searchSong = albumPages[i].substring(albumPages[i].lastIndexOf(":") + 1, albumPages[i].length); if (searchArtist.indexOf(txtSearch) != -1 || searchAlbum.indexOf(txtSearch) != -1 || searchSong.indexOf(txtSearch) != -1) { resultList += "&lt;option&gt;" + searchSong + "&lt;/option&gt;" resultCount[resultCount.length] = i; } } if (resultList.length == 0) { s += "&lt;span style='font-size: 2em;color: #fff;font-family: Arial;'&gt;No result found!&lt;/span&gt;" } else if (resultList.length &gt; 0) { s += '&lt;select size="' + (resultCount.length + 1) + '" onclick="parent.col3(value);"&gt;'; s += resultList; s += '&lt;/select&gt;'; } else { s += "&lt;span style='font-size: 2em;color: #fff;font-family: Arial;'&gt;Awaiting search query...&lt;/span&gt;" } with(document.getElementById('col2').contentDocument) { open(); write(s); close(); } } </code></pre>
[]
[ { "body": "<p>I'd create a local variable for <code>albumPages[i]</code> in the second for loop:</p>\n\n<pre><code>for (var i = 0; i &lt; albumPages.length; i++) {\n var albumPage = albumPages[i];\n var searchArtist = albumPage.substring(0, albumPage.indexOf(\":\"));\n ...\n}\n</code></pre>\n\n<p>It would remove a lot of unnecessary indexing and make the code easier to read.</p>\n\n<p>But... in the first <code>for</code> the code concatenates the artist, album title and song title strings and in the second loop it parses it with string functions. You should not do that, it looks completely unnecessary. Use a better data structure (class, struct, array etc. - I don't know JavaScript so well), store your data into it in the first loop and iterate over it in the second loop without parsing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T00:05:56.050", "Id": "6896", "ParentId": "6894", "Score": "1" } }, { "body": "<p>I have not benchmarked the different processes, but it is my belief that using XPath to traverse/parse your XML would be a much better option than using string methods.</p>\n\n<p>It's a big subject, but you might want to start <a href=\"https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript\" rel=\"nofollow\">here</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T23:19:40.933", "Id": "6898", "ParentId": "6894", "Score": "-1" } }, { "body": "<p>A few general things from a quick scan:</p>\n\n<ul>\n<li>declare all your variables at the top in one <code>var</code> statement rather than using it throughout the script</li>\n<li>use <code>somearray.push(x)</code> rather than <code>somearray[somearray.length]=x</code>, as its shorter and means you don't have to look up the <code>.length</code> property every time in your loop</li>\n<li>in general, avoid <code>with</code>; there are many reasons why e.g. <a href=\"http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/\" rel=\"nofollow\">http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/</a></li>\n<li>string concatenation is slow; instead of many <code>+=</code> operators, create an array, use <code>.push()</code> as above to add strings to the array, then use <code>.join('')</code> to merge them together.</li>\n</ul>\n\n<p>And yes, XPath would be a better approach to extract data from XML.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T23:23:26.823", "Id": "6899", "ParentId": "6894", "Score": "2" } }, { "body": "<p>How exactly do you want it improved? </p>\n\n<ul>\n<li><p>better performance?</p></li>\n<li><p>better relevance and recall of the search results?</p></li>\n<li><p>better code maintainability?</p></li>\n<li><p>better robustness / security?</p></li>\n</ul>\n\n<p>One obvious criticism is that generating XML/HTML output using string concatenation is both (a) inefficient, and (b) error-prone (for example, there is no attempt to escape special characters or detect special sequences like \"]]>\")</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T00:17:45.213", "Id": "6900", "ParentId": "6894", "Score": "1" } } ]
{ "AcceptedAnswerId": "6899", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T23:17:54.850", "Id": "6894", "Score": "3", "Tags": [ "javascript", "xml" ], "Title": "Improving search through XML file" }
6894
<p>I am building a web app that needs to access various tables in a given MySQL db. To do that, I have created a generic class, see <code>DAO_DBRecord.php</code> below, and I create children classes for each table I want to access, e.g., <code>DAO_User.php</code> is used to access the <code>users</code> table. The only difference in the children classes is that I change the value of the variable which contains the name of the table I wish to access.</p> <p>My questions are:<br> 1 - Should I make the <code>DAO_DBRecord.php</code> class abstract? I'm not planning to instantiate it, and in fact as it is written I cannot access any table with it.<br> 2 - Should I use constants in the <code>DAO_DBRecord.php</code> class (e.g., <code>const USER_TABLENAME = 'users'; const ARTICLE_TABLENAME = 'articles';</code>) and reference them in the children classes (e.g., <code>private Stable = USER_TABLENAME;</code>)?<br> 3 - Anything else I should do?</p> <p><strong>Class_DB.php:</strong> </p> <pre><code>&lt;?php class DB { private $dbHost; private $dbName; private $dbUser; private $dbPassword; function __construct($dbHost, $dbName, $dbUser, $dbPassword) { $this-&gt;dbHost=$dbHost; $this-&gt;dbName=$dbName; $this-&gt;dbUser=$dbUser; $this-&gt;dbPassword=$dbPassword; } function createConnexion() { return new PDO("mysql:host=$this-&gt;dbHost;dbname=$this-&gt;dbName", $this-&gt;dbUser, $this-&gt;dbPassword); } } ?&gt; </code></pre> <p><strong>DAO_DBRecord.php</strong> </p> <pre><code>&lt;?php require_once('Class_DB.php'); class DAO_DBrecord { private $dbh; // This is an instance of Class_DB to be injected in the functions. private $table=NULL; function __construct($dbh){ $this-&gt;dbh=$dbh; } function dbConnect(){ $dbConnection=$this-&gt;dbh-&gt;createConnexion(); return $dbConnection; } function checkRecordExists($recordIdentifier, $tableColName){ $dbConnection=$this-&gt;dbConnect(); $query=$dbConnection-&gt;prepare("SELECT COUNT(*) FROM $table " . "WHERE $tableColName = :recordIdentifier"); $query-&gt;bindParam(":recordIdentifier", $recordIdentifier); $query-&gt;execute(); $result=$query-&gt;fetch(PDO::FETCH_ASSOC); if ($result["COUNT(*)"]&gt;0){ return true; } else return false; } } ?&gt; </code></pre> <p><strong>DAO_Users.php</strong> </p> <pre><code>&lt;?php class DAO_User extends DAO_DBRecord { private $table='users'; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T02:18:29.593", "Id": "10799", "Score": "0", "body": "Why not something like http://stackoverflow.com/a/368990/567663 ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T22:12:20.443", "Id": "11660", "Score": "0", "body": "Sorry Paul - I don't understand your link." } ]
[ { "body": "<p><del>If the only difference between subclasses of <code>DAO_DBRecord</code> is the table name I wouldn't use subclasses. I'd just pass the table name to to the constructor of <code>DAO_DBRecord</code> and use different instances for different tables.</del></p>\n\n<p>If the only difference between subclasses of <code>DAO_DBRecord</code> is the table name I would pass the name of the table to the constructor of the parent class:</p>\n\n<pre><code>class UserDao extends DAO_DBRecord {\n\n public function __construct($db) {\n parent::__construct($db, 'users');\n }\n}\n</code></pre>\n\n<p>Having different classes improves type safety. In Java you can't pass a <code>UserDao</code> to a method with an <code>ArticleDao</code> parameter(1), it does not compile. I don't know whether this kind of type safety exists in PHP or not, but it could be a good practice and could results more readable code.</p>\n\n<p>(1) Of course except if <code>UserDao</code> is a subclass of <code>ArticleDao</code></p>\n\n<hr>\n\n<p>I don't feel that making <code>DAO_DBRecord</code> class abstract would make a big difference. If your clients wants to misuse the class they can create a dummy (non-abstract) subclass for that:</p>\n\n<pre><code>class AnyDao extends DAO_DBRecord {\n\n public function __construct($db, $tableName) {\n parent::__construct($db, $tableName);\n }\n}\n</code></pre>\n\n<p>If you want to protect <code>DAO_DBRecord</code> from instantiation with unknown table names make its constructor <code>private</code> and create static factory functions for your tables inside the <code>DAO_DBRecord</code>:</p>\n\n<pre><code>class DAO_DBrecord {\n private $db;\n private $tableName;\n\n private function __construct($db, $tableName) {\n $this-&gt;db = $db;\n $this-&gt;tableName = $tableName;\n }\n\n public static function createUserDao($db) {\n return new DAO_DBrecord($db, 'users');\n }\n\n public static function createArticleDao($db) {\n return new DAO_DBrecord($db, 'articles');\n }\n ...\n}\n</code></pre>\n\n<p>So, <code>DAO_DBrecord</code> cannot be used with other tables.</p>\n\n<hr>\n\n<p>If you use your table names only once creating constants for them looks unnecessary in this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T00:21:32.357", "Id": "10792", "Score": "0", "body": "That's the way I had it before, then I thought it would be better programming to separate it, just in case I end up having different needs for different tables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T00:35:36.970", "Id": "10793", "Score": "0", "body": "Sorry, you are right, I've forgotten type safety for a moment. I've updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T04:30:23.857", "Id": "10801", "Score": "0", "body": "Thanks. Do you think the parent class should be abstract?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T11:16:44.720", "Id": "10811", "Score": "0", "body": "Check the update, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T23:08:40.307", "Id": "11670", "Score": "0", "body": "Why do you make the static functions `createUserDao` and `createArticleDao` private?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T23:12:23.037", "Id": "11671", "Score": "0", "body": "That's the default :), it was a typo, I've fixed it. Thanks for pointing this out." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T00:18:36.147", "Id": "6901", "ParentId": "6895", "Score": "2" } } ]
{ "AcceptedAnswerId": "6901", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T23:51:30.800", "Id": "6895", "Score": "2", "Tags": [ "php", "object-oriented", "pdo" ], "Title": "PHP DAO classes inherit from a generic DAO classes and only change the table name" }
6895
<p>I am quite new to JavaScript and I wonder if you experts can see any obvious mistakes in this working code, and if any, suggest good improvements.</p> <pre><code>// add iframes to page var normal_sortables = document.getElementById('normal-sortables'); normal_sortables.innerHTML = normal_sortables.innerHTML + '&lt;div class="postbox"&gt;&lt;iframe style="width:100%;height:300px;" id="iframe_upload" src="upload.php"&gt;&lt;/iframe&gt;&lt;iframe style="width:100%;height:300px;" id="iframe_images" src="images.php"&gt;&lt;/iframe&gt;&lt;iframe style="width:100%;height:300px;" id="iframe_pdf_documents" src="pdf.php"&gt;&lt;/iframe&gt;&lt;/div&gt;'; // declaring all variables var code_to_be_inserted = '', textarea_content = document.getElementById('content'), iframe_upload = document.getElementById('iframe_upload'), iframe_images = document.getElementById('iframe_images'), iframe_pdf_documents = document.getElementById('iframe_pdf_documents'); // upload iframes of images and pdf documents when file is uploaded iframe_upload.onload = function () { iframe_images.src = 'images.php'; iframe_pdf_documents.src = 'pdf.php'; } // add image to content editor iframe_images.onload = function () { var images = iframe_images.contentWindow.document.getElementsByTagName('img'); for (var i = 0; i &lt; images.length; i++) { images[i].onclick = function () { code_to_be_inserted = '&lt;img alt="" src="'+this.src+'" /&gt;\n\n'; textarea_content.value = code_to_be_inserted + textarea_content.value; } } } // add pdf documents to content editor iframe_pdf_documents.onload = function () { var pdf_documents = iframe_pdf_documents.contentWindow.document.getElementsByTagName('a'); for (var i = 0; i &lt; pdf_documents.length; i++) { pdf_documents[i].onclick = function () { code_to_be_inserted = '\n\n&lt;a href="' + this.href+'" target="_blank"&gt;Click here to open ' + this.innerHTML + '&lt;/a&gt;'; textarea_content.value = textarea_content.value + code_to_be_inserted; alert ('testar'); return false; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T10:20:23.183", "Id": "10810", "Score": "0", "body": "Hope you are also aware of jslint site which is good for syntactical checking." } ]
[ { "body": "<p>If you wanted to retain any event handlers that were already attached to your elements, you could change the first piece of code like this an avoid one of the dangers of setting innerHTML on an element that already has a bunch of HTML in it:</p>\n\n<pre><code>// add iframes to page\nvar normal_sortables = document.getElementById('normal-sortables');\n// create container div\nvar newDiv = document.createElement(\"div\");\nnewDiv.className = \"postbox\";\n// put content into container div\nnewDiv.innerHTML = '&lt;iframe style=\"width:100%;height:300px;\" id=\"iframe_upload\" src=\"upload.php\"&gt;&lt;/iframe&gt;&lt;iframe style=\"width:100%;height:300px;\" id=\"iframe_images\" src=\"images.php\"&gt;&lt;/iframe&gt;&lt;iframe style=\"width:100%;height:300px;\" id=\"iframe_pdf_documents\" src=\"pdf.php\"&gt;&lt;/iframe&gt;';\n// add container div to the sortables\nnormal_sortables.appendChild(newDiv);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T02:05:31.703", "Id": "10796", "Score": "0", "body": "I see, that seams to be good practice :) Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T02:16:22.183", "Id": "10797", "Score": "0", "body": "Shouldn't it be: newDiv.className =\"postbox\";" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T02:18:17.607", "Id": "10798", "Score": "0", "body": "@Hakan - Yes, that was a copy/paste error. Fixed." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T02:00:41.667", "Id": "6904", "ParentId": "6903", "Score": "5" } } ]
{ "AcceptedAnswerId": "6904", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T01:52:32.090", "Id": "6903", "Score": "5", "Tags": [ "javascript", "beginner", "event-handling", "dom" ], "Title": "Altering contents when loading iframes" }
6903
<p>I have tried using jQuery to create an alternative of marquee, and got no success. It flickers and does not stop on hover. I edited and edited again and it finally came out with a jQuery + JavaScript mess.</p> <p>JavaScript:</p> <pre><code>$(document).ready(function(){ marquee(); var timeout=1; function marquee(){ var margin= -($('#mydiv &gt; div:eq(0)').outerHeight()+ 20); $('#mydiv &gt; div:eq(0)').animate({'margin-top': margin+'px'},4000,function(){ $('#mydiv &gt; div:eq(2)').html($(this).html()); $(this).html('').css({'margin-top':'0px'}).appendTo($('#mydiv')); loop(); }); } function loop(){ if(timeout) setTimeout(marquee,0); } $('#mydiv').hover(function(){ timeout = 0; $('#mydiv &gt; div:eq(0)').stop(true); },function(){ timeout = 1; marquee(); }); }); </code></pre> <p>Markup:</p> <pre><code> &lt;div id='mydiv' style='width:300px;height:300px;overflow:hidden'&gt; &lt;div id='div1'&gt; &lt;h4&gt; Advantages:&lt;/h4&gt;&lt;br&gt; &lt;ul&gt; &lt;li&gt;blah 1&lt;/li&gt; &lt;li&gt;blah 2&lt;/li&gt; &lt;li&gt;blah 3&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id='div2'&gt; &lt;h4&gt;Applications:&lt;/h4&gt;&lt;br&gt; &lt;ul&gt; &lt;li&gt;blah 1&lt;/li&gt; &lt;li&gt;blah 2&lt;/li&gt; &lt;li&gt;blah 3&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id='div3'&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T17:57:27.740", "Id": "11219", "Score": "1", "body": "I wouldn't recommend to put a marquee on a page unless you want to make harder for the user to notice your whole page and not just the marquee, also some users find marquees annoying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T15:07:57.140", "Id": "32737", "Score": "0", "body": "I just created a jQuery plugin. Try this. https://github.com/aamirafridi/jQuery.Marquee" } ]
[ { "body": "<p>A few points:</p>\n\n<ul>\n<li><code>$(this).html('')</code> will throw away the contents of <code>#div1</code> (on the first iteration) and <code>#div2</code> (on the second iteration). If you want the marquee to loop, that's not going to work.</li>\n<li>This is a perfect use case for a simple jQuery plugin (see <a href=\"http://docs.jquery.com/Plugins/Authoring\" rel=\"nofollow\">the documentation</a>).</li>\n<li>You should probably use <a href=\"http://api.jquery.com/next/\" rel=\"nofollow\"><code>next()</code></a> instead of the <code>eq</code> selector, to make your code work with any number of children (or at least any number above 1).</li>\n<li>To stop the animations on hover, you'll have to call <a href=\"http://api.jquery.com/stop/\" rel=\"nofollow\"><code>stop()</code></a> on any elements that may be half-way into an animation. Pausing and continuing the marquee would be good use cases for <a href=\"http://docs.jquery.com/Plugins/Authoring#Plugin_Methods\" rel=\"nofollow\">plugin methods</a>.</li>\n<li>You could consider using the <code>position</code> and <code>top</code> attributes to position the children; this is exactly what <code>position: absolute</code> is for.</li>\n</ul>\n\n<p>Given below is an example of a simple plugin that does roughly what you want. To keep in theme with this site, I've stuck with your approach -- animation is done on <code>margin-top</code> and, as you can see, only the first child is animated.</p>\n\n<p>Because of this, the marquee won't loop until all children are outside the parent <code>div</code>. To make it wrap sooner, I would advise rewriting the plugin to use <code>position: absolute</code> and the <code>top</code> attribute on each child. That way, each child can be idependently animated and the marquee can be looped earlier.</p>\n\n<p>Finally, keep in mind that this example is far from perfect. For example, the total height of the children is re-calculated on each run. The plugin could be made more efficient simply by <a href=\"http://docs.jquery.com/Plugins/Authoring#Data\" rel=\"nofollow\">maintaining state</a>.</p>\n\n<h2>Plugin:</h2>\n\n<pre><code>(function($) {\n\n var methods = {\n init: function(options) {\n this.children(':first').stop();\n this.marquee('play');\n },\n play: function() {\n var marquee = this,\n pixelsPerSecond = 100,\n firstChild = this.children(':first'),\n totalHeight = 0,\n difference,\n duration;\n\n // Find the total height of the children by adding each child's height:\n this.children().each(function(index, element) {\n totalHeight += $(element).innerHeight();\n });\n\n // The distance the divs have to travel to reach -1 * totalHeight:\n difference = totalHeight + parseInt(firstChild.css('margin-top'), 10);\n\n // The duration of the animation needed to get the correct speed:\n duration = (difference/pixelsPerSecond) * 1000;\n\n // Animate the first child's margin-top to -1 * totalHeight:\n firstChild.animate(\n { 'margin-top': -1 * totalHeight },\n duration,\n 'linear',\n function() {\n // Move the first child back down (below the container):\n firstChild.css('margin-top', marquee.innerHeight());\n // Restart whole process... :)\n marquee.marquee('play');\n }\n );\n },\n pause: function() {\n this.children(':first').stop();\n }\n };\n\n $.fn.marquee = function(method) {\n\n // Method calling logic\n if (methods[method]) {\n return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));\n } else if (typeof method === 'object' || !method) {\n return methods.init.apply(this, arguments);\n } else {\n $.error('Method ' + method + ' does not exist on jQuery.marquee');\n }\n\n };\n\n})(jQuery);\n</code></pre>\n\n<h2>Usage:</h2>\n\n<pre><code>var marquee = $('#mydiv');\n\nmarquee.marquee();\n\nmarquee.hover(function() {\n marquee.marquee('pause');\n}, function() {\n marquee.marquee('play'); \n});\n</code></pre>\n\n<p>This example can also be found on jsfiddle: <a href=\"http://jsfiddle.net/PPvG/LgsrU/\" rel=\"nofollow\">http://jsfiddle.net/PPvG/LgsrU/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-02T09:44:41.080", "Id": "11553", "Score": "0", "body": "superb work. No flickering at all. Thanks for giving time. But this plugin is working exactly like marquee. When all divs finished sliding up. It shows blank for some time and then shows the first div again. I wanted a continuous loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T15:34:32.407", "Id": "7183", "ParentId": "6905", "Score": "3" } }, { "body": "<p>I've been researching the best possible implementations for marquee myself. I indeed was looking for element marquee, rather than text marquee. I finally implemented the code using CSS3 transitions with graceful degradation to scroll animation for the older browsers. The CSS3 transitions, and indeed scroll implementation, is by far more efficient that offsetting elements using margin or any similar implementation.</p>\n\n<p>Even with 4 simultaneous marquee elements on the page, the implementation has virtually no performance impact.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NRf5K.png\" alt=\"enter image description here\"></p>\n\n<p>The demo can be seen at <a href=\"https://dev.anuary.com/60244f3a-b8b2-5678-bce5-f7e8742f0c69/\" rel=\"nofollow noreferrer\">https://dev.anuary.com/60244f3a-b8b2-5678-bce5-f7e8742f0c69/</a>. The code is available at <a href=\"https://github.com/gajus/marquee\" rel=\"nofollow noreferrer\">https://github.com/gajus/marquee</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-11T01:49:50.297", "Id": "20406", "ParentId": "6905", "Score": "1" } } ]
{ "AcceptedAnswerId": "7183", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-15T06:08:04.763", "Id": "6905", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jQuery marquee, without flickering, less memory consumption, and no plugin" }
6905
<p>I have this method for searching a DB based on filters I was wondering if anyone thought as I do that this code is excessive, and secondly if you have any suggestions to shorten the code.</p> <pre><code>private const string NO_FILTER = "No filter"; [DataObjectMethod(DataObjectMethodType.Select)] public static List&lt;Part&gt; GetPartsSearch(string partNumber, string modelNumber, string slotNumber, string yardNumber, int commodityId, string description) { using (var context = new EntitiesModel()) { IQueryable&lt;Part&gt; parts; if (slotNumber != NO_FILTER) { if (modelNumber != "0") { if (yardNumber != NO_FILTER) { if (commodityId &gt; 0) { // Have slot, model, yard and commodity parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partSlot.SlotNumber == slotNumber &amp;&amp; partModel.ModelNumber == modelNumber &amp;&amp; partYard.YardNumber == yardNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { //Have slot, model and yard parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber where partSlot.SlotNumber == slotNumber &amp;&amp; partModel.ModelNumber == modelNumber &amp;&amp; partYard.YardNumber == yardNumber select part; } } else { //have slot, model and commodity if (commodityId &gt; 0) { parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partSlot.SlotNumber == slotNumber &amp;&amp; partModel.ModelNumber == modelNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { //Have slot and model parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber where partSlot.SlotNumber == slotNumber &amp;&amp; partModel.ModelNumber == modelNumber select part; } } } else if (yardNumber != NO_FILTER) { if (commodityId &gt; 0) { //Have slot yard and commodity parts = from part in context.Parts join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partSlot.SlotNumber == slotNumber &amp;&amp; partYard.YardNumber == yardNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { //Have slot and yard parts = from part in context.Parts join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber where partSlot.SlotNumber == slotNumber &amp;&amp; partYard.YardNumber == yardNumber select part; } } else { if (commodityId &gt; 0) { parts = from part in context.Parts join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partSlot.SlotNumber == slotNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { parts = from part in context.Parts join partSlot in context.PartsBySlots on part.PartNumber equals partSlot.PartNumber where partSlot.SlotNumber == slotNumber select part; } } } else if (modelNumber != "0") { if (yardNumber != NO_FILTER) { // Have model, yard and commodity if (commodityId &gt; 0) { parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partModel.ModelNumber == modelNumber &amp;&amp; partYard.YardNumber == yardNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { // Have model and yard parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber where partModel.ModelNumber == modelNumber &amp;&amp; partYard.YardNumber == yardNumber select part; } } else { if (commodityId &gt; 0) { // Have model and commodity parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partModel.ModelNumber == modelNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { // Have model parts = from part in context.Parts join partModel in context.PartsByModels on part.PartNumber equals partModel.PartNumber where partModel.ModelNumber == modelNumber select part; } } } else if (yardNumber != NO_FILTER) { if (commodityId &gt; 0) { //have yard and commodity parts = from part in context.Parts join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where partYard.YardNumber == yardNumber &amp;&amp; commodity.CommodityID == commodityId select part; } else { // Have yard parts = from part in context.Parts join partYard in context.PartsByYards on part.PartNumber equals partYard.PartNumber where partYard.YardNumber == yardNumber select part; } } else if (commodityId &gt; 0) { // Have commodity parts = from part in context.Parts join commodity in context.Commodities on part.CommodityId equals commodity.CommodityID where commodity.CommodityID == commodityId select part; } else { parts = from part in context.Parts select part; } if (partNumber != "0") { parts = parts.Where(p =&gt; p.PartNumber.ToLower().Contains(partNumber.ToLower())); } if(!string.IsNullOrEmpty(description)) { parts = parts.Where(p =&gt; p.Description.ToLower().Contains(description.ToLower())); } parts = parts.OrderBy(p =&gt; p.PartNumber); return parts.ToList(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T09:55:18.660", "Id": "10840", "Score": "0", "body": "Although I've not tried this with these specific constructs, you may want to look into Compilable Linq Expressions. These would be defined, build, and compiled in your constructor and reused throughout. This is a pattern I've used with similarly complex linq queries and acheived big performanace advantages. Also, as a *micro-optimization*, `ToUpper()` is faster then `ToLower()`. And lets not forget that offloading this to the database in a SPROC or View would be much-much faster and a better use of resources overall." } ]
[ { "body": "<p>I'd try creating a query builder class which stores the join statements and where conditions and later build the whole query from the stored statements. A sample pseudocode:</p>\n\n<pre><code>public class QueryBuilder {\n List&lt;String&gt; joins;\n List&lt;String&gt; whereConditions;\n\n ...\n\n public void addJoin(final String join) {\n joins.add(join);\n }\n\n public void addWhereCondition(final String condition) {\n whereConditions.add(condition);\n }\n\n public String buildQuery() {\n final StringBuilder result = new StringBuilder();\n result.append(\"...\");\n for (final String join: joins) {\n result.append(join);\n }\n result.append(\"WHERE \");\n for (final String condition: whereConditions) {\n result.append(condition);\n // TODO: handle &amp;&amp;s here\n }\n\n return result.toString();\n }\n}\n</code></pre>\n\n<p>I suppose something like this is possible in C# too. Then, the ifs could be rewritten like this:</p>\n\n<pre><code>if (commodityId &gt; 0) {\n queryBuilder.addJoin(\"join commodity in context.Commodities on part.CommodityId \n equals commodity.CommodityID\");\n queryBuilder.addWhere(\"commodity.CommodityID == commodityId\");\n}\n\nif (yardNumber != NO_FILTER) {\n queryBuilder.addJoin(\"join partYard in context.PartsByYards on part.PartNumber \n equals partYard.PartNumber\");\n queryBuilder.addWhere(\"partYard.YardNumber == yardNumber\");\n}\n</code></pre>\n\n<p>It would reduce cyclomatic complexity and make the code easier to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T12:43:09.067", "Id": "6917", "ParentId": "6913", "Score": "0" } }, { "body": "<p>It's definitely excessive. :)</p>\n\n<p>I'd start by looking into whether there should be one method for getting the data without a commodity filter, and one method for the ones with commodity.</p>\n\n<p>I'd also put each query into its own method anyway. That will give you quite a bit more readable main function(s).</p>\n\n<p>But to be frank, I wonder why you don't have navigation properties on your entities, and just eagerload them by .Include (if EF) or use a DataLoadOptions set (if L2S).\nThat way you could ditch all the joins from all the queries.</p>\n\n<p>Also, if you change to the extension syntax, you can add where statements to the queryable.</p>\n\n<p>For instance (EntityFramework eagerloading):</p>\n\n<pre><code>var queryable = context.Parts;\nif (shouldIncludeModel)\n queryable = queryable.Include(\"Model\");\nif (model &gt; 0)\n queryable = queryable.Where(p =&gt; p.Model.Id == model);\nif (shouldIncludeYard)\n queryable = queryable.Include(\"Yard\");\nif (yard &gt; 0)\n queryable = queryable.Where(p =&gt; p.Yard.Id == yard);\n\nreturn queryable.ToList();\n</code></pre>\n\n<p>etc.</p>\n\n<p>This should of course also be further refactored in many a better way, at least separated in methods responsible for each of the related entities.\nAnyway, I think you'll get quite a bit shorter methods by doing this.</p>\n\n<p>Building on palacsints suggestion, you could also check out how to build Linq expressions manually, but that is quite advanced and cumbersome.\nThere's some info here: <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb397951.aspx</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T09:48:00.953", "Id": "10839", "Score": "0", "body": "I agree with the seperation, as it stands the JIT will not optimize this method because its just too large." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T14:45:20.937", "Id": "6919", "ParentId": "6913", "Score": "2" } } ]
{ "AcceptedAnswerId": "6919", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T11:15:58.327", "Id": "6913", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Search with filters code" }
6913
<p>We're storing the xml communications with an external service in a text in the db and in a <code>before_create</code> I've got the following:</p> <pre><code> # filter opera password def remove_password! self.request.gsub! /UserPassword\&gt;[^\&lt;]*\&lt;\//, 'UserPassword&gt;[FILTERED]&lt;/' end </code></pre> <p>Is there a better, safer way of doing it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T23:04:59.343", "Id": "10854", "Score": "0", "body": "Is the XML always the same schema? Can it be validated with a Schema or DTD?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T17:05:42.907", "Id": "10878", "Score": "0", "body": "yes the schema in the header stills but for several reasons at this point I've got only the string, and I'd avoid to re-convert it into xml" } ]
[ { "body": "<p>That depends on how confident you are that neither of these cases will be true:</p>\n\n<ul>\n<li>Another tag like will be introduced that you will want to leave unfiltered</li>\n<li>No nested tags will appear within the tag</li>\n</ul>\n\n<p>An example of the last would be:</p>\n\n<pre><code>&lt;UserPassword&gt;&lt;for name=\"boy\"&gt;Sue&lt;/for&gt;&lt;/UserPassword&gt;\n</code></pre>\n\n<p>It seems your assumptions are safe, but if you want to be certain, go with</p>\n\n<pre><code>self.request.gsub! /\\&lt;UserPassword\\&gt;.+?\\&lt;/UserPassword\\&gt;/gm, '&lt;UserPassword&gt;[FILTERED]&lt;/UserPassword&gt;'\n</code></pre>\n\n<p>By eliminating the greediness of the regex, you can match the exact tag you mean and reduce the assumptions that will come back and bite you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T17:09:50.013", "Id": "10879", "Score": "0", "body": "there are no sub-tags in userPassword, the reason why I hadn't included the complete close tag is because some servers respond with a tag-prefix e.g.: `<n3:UserPassword>` though I understand that including the close tag is definitely a must" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T21:55:47.800", "Id": "10887", "Score": "0", "body": "If you know the form of the tag-prefix, then specify it as optional. E.g.: `\\<(?:[a-zA-Z]+\\d+:)?UserPassword\\>/gm` The non-capturing group ensures you will not get it in your password (if that matters) but if you specify the form, you can be sure you aren't getting garbage from the server." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T02:14:25.230", "Id": "6935", "ParentId": "6914", "Score": "3" } } ]
{ "AcceptedAnswerId": "6935", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T11:19:01.370", "Id": "6914", "Score": "4", "Tags": [ "ruby", "regex", "xml" ], "Title": "filter out password in xml string" }
6914
<p>I have written some JavaScript code with jQuery to create collapsible webparts in SharePoint 2010. </p> <p>Can someone suggest some improvements? As I think that the methods I am using for selectors are not ideal. The solution works perfectly as it is, I just want to ensure that I am being as efficient as possible.</p> <p>Below is a snippet of the HTML that I am doing the processing on.</p> <p>UPDATE: Just a note, I am starting from <code>s4-wpTopTable</code> because it is the best way for me to ensure I am dealing with a SharePoint webpart. </p> <pre><code>&lt;table width="100%" cellpadding="0" cellspacing="0" border="0"&gt; &lt;tr&gt; &lt;td id="MSOZoneCell_WebPartWPQ4" valign="top" class="s4-wpcell" onkeyup="WpKeyUp(event)" onmouseup="WpClick(event)"&gt; &lt;table class="s4-wpTopTable" border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tr&gt; &lt;td&gt; &lt;table border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tr class="ms-WPHeader"&gt; &lt;td align="left" class="ms-wpTdSpace"&gt;&amp;#160;&lt;/td&gt; &lt;td title="Links - Use the Links list for links to Web pages that your team members will find interesting or useful." id="WebPartTitleWPQ4" class="ms-WPHeaderTd"&gt; &lt;h3 style="text-align:justify;" class="ms-standardheader ms-WPTitle"&gt; &lt;a accesskey="W" href="/sites/test/Lists/Links"&gt;&lt;nobr&gt;&lt;span&gt;Links&lt;/span&gt;&lt;span id="WebPartCaptionWPQ4"&gt;&lt;/span&gt;&lt;/nobr&gt;&lt;/a&gt; &lt;/h3&gt; &lt;/td&gt; &lt;td align="right" class="ms-WPHeaderTdMenu" onclick="OpenWebPartMenu(&amp;#39;MSOMenu_WebPartMenu&amp;#39;, this, &amp;#39;WebPartWPQ4&amp;#39;,&amp;#39;False&amp;#39;); TrapMenuClick(event); return false;"&gt;&lt;span style="display:none;"&gt;&lt;/span&gt;&lt;div class="ms-WPMenuDiv" onmouseout="this.className='ms-WPMenuDiv'" onmouseover="this.className='ms-WPMenuDivHover'"&gt;&lt;a onclick="OpenWebPartMenuFromLink(&amp;#39;MSOMenu_WebPartMenu&amp;#39;, this, &amp;#39;WebPartWPQ4&amp;#39;,&amp;#39;False&amp;#39;); return false;" id="WebPartWPQ4_MenuLink" onkeydown="WebPartMenuKeyboardClick(document.getElementById('WebPartWPQ4_MenuLink'), 13, 40, event)" href="#" title="Links Web Part Menu" class="ms-wpselectlink" onblur="UpdateWebPartMenuFocus(this, 'ms-wpselectlink', 'ms-WPEditText');" onfocus="UpdateWebPartMenuFocus(this, 'ms-wpselectlinkfocus', 'ms-WPEditTextVisible');" menuid="MSOMenu_WebPartMenu"&gt;&lt;img class="ms-WPHeaderMenuImg" src="/_layouts/images/wpmenuarrow.png" alt="Links Web Part Menu" style="border-width:0px;" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;/td&gt;&lt;td class="ms-WPHeaderTdSelection"&gt;&lt;span class="ms-WPHeaderTdSelSpan"&gt;&lt;input type="checkbox" id="SelectionCbxWebPartWPQ4" class="ms-WPHeaderCbxHidden" title="Select or deselect Links Web Part" onblur="this.className='ms-WPHeaderCbxHidden'" onfocus="this.className='ms-WPHeaderCbxVisible'" onkeyup="WpCbxKeyHandler(event);" onmouseup="WpCbxSelect(event); return false;" onclick="TrapMenuClick(event); return false;" /&gt;&lt;/span&gt;&lt;/td&gt;&lt;td align="left" class="ms-wpTdSpace"&gt;&amp;#160;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="" valign="top"&gt; //CONTENT WILL BE IN HERE &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>And this is the jQuery that I am using:</p> <pre><code>&lt;script type="text/javascript" src="http://ajax.Microsoft.com/ajax/jQuery/jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; jQuery(function($) { $('.s4-wpTopTable').find('tr:first h3').append('&lt;a class=\'min\' style=\'float:right\'&gt;&lt;img src=\'/_layouts/images/collapse.gif\'/&gt;&lt;/a&gt;'); var Collapse = "/_layouts/images/collapse.gif"; var Expand = "/_layouts/images/expand.gif"; $('.min').click(function(){ var img = $(this).children(); $(this).closest('.s4-wpTopTable').find('tr:first').next().toggle().is(":visible") ? img.attr('src',Collapse) : img.attr('src',Expand ); }); }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<pre><code>$('.s4-wpTopTable').find('tr:first h3')...\n</code></pre>\n\n<p>is the same as </p>\n\n<pre><code>$('.s4-wpTopTable tr:first h3')...\n</code></pre>\n\n<p>Only one hit for jQueury goodness instead of two.<br>\nalso you're attaching the click handler after putting it into the DOM. You can do it the other way:</p>\n\n<pre><code>// ...\n.append(\n $('&lt;a class=\\'min\\' style=\\'float:right\\'&gt;&lt;img src=\\'/_layouts/images/collapse.gif\\'/&gt;&lt;/a&gt;')\n .click(function(){ \n var img = $(this).children();\n $(this)\n .closest('.s4-wpTopTable')\n .find('tr:first')\n .next()\n .toggle().is(\":visible\") ? img.attr('src',Collapse) : img.attr('src', Expand);\n })\n);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-28T21:47:42.763", "Id": "142957", "Score": "0", "body": "Its better to use the jquery `on` method for reasons mentioned here http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click \n\nso `$('.min').click(function()`... \nwould be \n`$('.min').on('click',function()`..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T02:04:29.537", "Id": "36173", "ParentId": "6920", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T14:52:43.547", "Id": "6920", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Can this code be improved? jQuery with SharePoint" }
6920
<p>I was hoping I might get some of the brains in Stack Overflow to take a look at my Python static blogger application. I've been using it a few years in a pretty hacked up form. Lately I decided to clean it up and put it up on Github. I'd love some smarter Python programmers to give me advice and wisdom into ways to improve, optimize, and simplify the code.</p> <p>The program is here: <a href="https://github.com/mshea/Pueblo" rel="nofollow">https://github.com/mshea/Pueblo</a></p> <p>Some philosophies:</p> <ol> <li><p>I don't want more features. I want it as simple as it can be.</p></li> <li><p>I always prefer native modules. My ISP doesn't let me install new modules so the Markdown one is the only one I use outside of the defaults.</p></li> <li><p>I'd like to keep it to a single script unless splitting it up makes things much easier or simple.</p></li> <li><p>I'm particularly interested in any potential security concerns. Right now I don't see any.</p></li> <li><p>I'm not big into flexibility. I'd prefer it to do it one way really well rather than many ways poorly. If people want a flexible blogging platform, go with WordPress.</p></li> </ol> <pre><code>#!/usr/local/bin/python # # Pueblo: Python Markdown Static Blogger # # 17 December 2011 # # A single Python script to build a simple blog from a directory full of markdown files. # # This script requires the Markdown python implementation available at: # http://pypi.python.org/pypi/Markdown/2.1.0 # # This script requires markdown files using the following multimarkdown metadata as the first three lines # of the processed .txt markdown files as follows: # # Title: the Title of your Document # Author: Joe Blow # Date: 15 December 2011 # # The program will generate an index.html homepage file, an archive.html archive file, # and an index.xml RSS file. # # Header and footer data can be edited in the variables throughout the program. # # This script expects the following additional files: # style.css: The main site's stylesheet. # iphone.css: The mobile version of the site's stylesheet. # sidebar.html: A secondary set of data usually displayed as a sidebar. # # Instructions # Install the Markdown python module. # Configure this script by changing the configuration variables below. # Put your static markdown .txt files in the configured directory # Run the script either manually, with a regular cronjob, or as a CGI script. # View the output at index.html config = { "directory": ".", # No trailing slash. "site_url": "http://yoursite.net/", # Must have a trailing slash. "site_title": "Your Website", "site_description": "Your blog tagline.", "google_analytics_tag": "UA-111111-1", "author_name": "Your Name", "author_bio_link": "about.html", "amazon_tag": "mikesheanet-20", "twitter_tag": "twitterid", "author_email": "your@emailaddress.com", "header_image_url": "", "header_image_width": "", "header_image_height": "", "sidebar_on_article_pages": False, "minify_html": False, } nonentryfiles = [] # Main Program import glob, re, rfc822, time, cgi, datetime, markdown from time import gmtime, strftime, localtime, strptime def rebuildsite (): textfiles = glob.glob(config["directory"]+"//*.txt") for nonfile in nonentryfiles: textfiles.remove(config["directory"]+"/"+nonfile) indexdata = [] # Rip through the stack of .txt markdown files and build HTML pages from it. for eachfile in textfiles: eachfile = eachfile.replace(config["directory"]+"\\", "") content = open(eachfile).read() lines = re.split("\n", content) title = re.sub("(Title: )|( )", "", lines[0]) title = cgi.escape(title) urltitle = title.replace("&amp;", "%26") author = lines[1].replace("Author: ","") date = re.sub("( )|(\n)|(Date: )","",lines[2]) numdate = strftime("%Y-%m-%d", strptime(date, "%d %B %Y")) content = markdown.markdown(re.sub("(Title:.*\n)|(Author:.*\n)|(Date:.*\n\n)| ", "", content)) summary = re.sub("&lt;[^&lt;]+?&gt;","", content) summary = summary.replace("\n", " ")[0:200] htmlfilenamefull = htmlfilename = eachfile.replace(".txt", ".html") htmlfilename = htmlfilename.replace(config["directory"]+"/", "") postname = htmlfilename.replace(".html", "") # Build the HTML file, add a bit of footer text. htmlcontent = [buildhtmlheader("article", title, date)] htmlcontent.append(content) htmlcontent.append(buildhtmlfooter("article", urltitle)) htmlfile = open(htmlfilenamefull, "w") htmlfile.write(minify("".join(htmlcontent))) htmlfile.close() if numdate &lt;= datetime.datetime.now().strftime("%Y-%m-%d"): indexdata.append([[numdate],[title],[summary],[htmlfilename],[content]]) # The following section builds index.html, archive.html and index.xml. indexdata.sort() indexdata.reverse() indexbody=archivebody=rssbody="" count=0 for indexrow in indexdata: dateobject = strptime(indexrow[0][0], "%Y-%m-%d") rssdate = strftime("%a, %d %b %Y 06:%M:%S +0000", dateobject) nicedate = strftime("%d %B %Y", dateobject) articleitem = ''' &lt;h2&gt;&lt;a href="%(article_link)s"&gt;%(article_title)s&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;%(date)s - %(summary)s...&lt;/p&gt; ''' % { 'article_link': indexrow[3][0], 'article_title': indexrow[1][0], 'date': nicedate, 'summary': indexrow[2][0], } rssitem = ''' &lt;item&gt; &lt;title&gt;%(title)s&lt;/title&gt; &lt;link&gt;%(link)s&lt;/link&gt; &lt;guid&gt;%(link)s&lt;/guid&gt; &lt;pubDate&gt;%(pubdate)s&lt;/pubDate&gt; &lt;description&gt;%(description)s&lt;/description&gt; &lt;content:encoded&gt; &lt;![CDATA[%(cdata)s]]&gt; &lt;/content:encoded&gt; &lt;/item&gt; ''' % { 'title': indexrow[1][0], 'link': config["site_url"]+indexrow[3][0], 'pubdate': rssdate, 'description': indexrow[2][0], 'cdata': indexrow[4][0], } count = count + 1 if count &lt; 15: rssbody = rssbody + rssitem if count &lt; 30: indexbody = indexbody+articleitem archivebody = archivebody + articleitem sidebardata = open(config["directory"]+"/sidebar.html").read() rssdatenow = rfc822.formatdate() indexdata = [buildhtmlheader("index", config["site_title"], "none")] indexdata.append(indexbody) indexdata.append("&lt;h2&gt;&lt;a href=\"archive.html\"&gt;View All %(article_count)s Articles&lt;/a&gt;&lt;/h2&gt;\n&lt;/div&gt;\n" % { 'article_count': str(count) }) indexdata.append(buildhtmlfooter("index", "")) indexfile = open(config["directory"]+"/index.html", "w").write(minify("".join(indexdata))) archivedata = [buildhtmlheader("archive", config["site_title"]+" Article Archive", "none")] archivedata.append(archivebody) archivedata.append("\n&lt;/div&gt;\n") archivedata.append(buildhtmlfooter("archive", "")) archivefile = open (config["directory"]+"/archive.html", "w").write(minify("".join(archivedata))) rsscontent = '''&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/\" &gt; &lt;channel&gt; &lt;title&gt;%(site_title)s&lt;/title&gt; &lt;link&gt;%(site_url)s&lt;/link&gt; &lt;description&gt;%(site_description)s&lt;/description&gt; &lt;pubDate&gt;%(rssdatenow)s&lt;/pubDate&gt; &lt;language&gt;en&lt;/language&gt; &lt;atom:link href="%(site_url)sindex.xml" rel="self" type="application/rss+xml" /&gt; %(rssbody)s &lt;/channel&gt; &lt;/rss&gt; ''' % { 'site_url': config["site_url"], 'site_title': config["site_title"], 'site_description': config["site_description"], 'rssdatenow': rssdatenow, 'rssbody': rssbody, } rssfile = open(config["directory"]+"/index.xml", "w").write(minify(rsscontent)) # Subroutine to build out the page's HTML header def buildhtmlheader(type, title, date): if config["header_image_url"] != "": headerimage = ''' &lt;img class="headerimg" src="%(header_image_url)s" alt="%(site_title)s: %(site_description)s" height="%(header_image_height)s" width="%(header_image_width)s" /&gt; ''' % { 'header_image_url': config["header_image_url"], 'site_title': config["site_title"], 'site_description': config["site_description"], 'header_image_height': config["header_image_height"], 'header_image_width': config["header_image_width"], } htmlheader = [''' &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;%(title)s&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" media="screen and (min-width: 481px)" href="style.css"&gt; &lt;link rel="stylesheet" type="text/css" media="only screen and (max-width: 480px)" href="iphone.css"&gt; &lt;link rel="alternate" type="application/rss+xml" title="%(title)s" href="index.xml"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;meta name="viewport" content="user-scalable=no, width=device-width" /&gt; &lt;meta name="apple-mobile-web-app-capable" content="yes" /&gt; &lt;meta name="apple-mobile-web-app-status-bar-style" content="black" /&gt; &lt;script type="text/javascript"&gt; var _gaq = _gaq || []; _gaq.push(['_setAccount', '%(google_analytics_tag)s']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; ''' % { 'title': title, 'google_analytics_tag': config["google_analytics_tag"], } ] # Tons of conditional checks lay ahead. Does it use a header image # and do you want the sidebar on article pages? if config["sidebar_on_article_pages"] != True and type == "article": htmlheader.append("\n&lt;div class=\"article_container\"&gt;\n") else: htmlheader.append("\n&lt;div class=\"container\"&gt;\n") if config["header_image_url"] != "" and type == "index": htmlheader.append(headerimage) elif config["header_image_url"] != "" and type != "index": htmlheader.append("&lt;a href=\"/\"&gt;\n" + headerimage + "&lt;/a&gt;\n") elif config["header_image_url"] == "" and type == "index": htmlheader.append(''' &lt;div class="header"&gt; &lt;h1&gt;%(site_title)s&lt;/h1&gt; &lt;p&gt;%(site_description)s&lt;/p&gt; &lt;/div&gt; ''' % { 'site_title': config["site_title"], 'site_description': config["site_description"], } ) elif config["header_image_url"] == "" and type != "index": htmlheader.append(''' &lt;p class="return_link"&gt; &lt;a href="index.html"&gt;%(site_title)s&lt;/a&gt; &lt;/p&gt; ''' % { 'site_title': config["site_title"] } ) if type == "index": htmlheader.append("\n&lt;div class=\"article_list\"&gt;\n") elif type == "archive": htmlheader.append("\n&lt;div class=\"article_list\"&gt;\n&lt;h1&gt;Article Archive&lt;/h1&gt;\n") elif type == "article": htmlheader.append(''' &lt;div class="article"&gt; &lt;h1&gt;%(title)s&lt;/h1&gt; &lt;p&gt;by &lt;a href="%(author_bio_link)s"&gt;%(author_name)s&lt;/a&gt; on %(date)s&lt;/p&gt; ''' % { 'author_bio_link': config["author_bio_link"], 'title': title, 'author_name': config["author_name"], 'date': date, } ) return "".join(htmlheader) # Subroutine to remove all line breaks to make for some packed fast HTML def minify(content): if config["minify_html"]: content = re.sub("\n","",content) return content # Subroutine to build out the footer. def buildhtmlfooter (type, urltitle): footer_parts = [] sidebardata = open(config["directory"]+"/sidebar.html").read() if type == "index" or type == "archive" or config["sidebar_on_article_pages"]: footer_parts.append(sidebardata) if type == "article": footer_parts.append( ''' &lt;p&gt;Send feedback to &lt;a href="mailto:%(email)s"&gt;%(email)s&lt;/a&gt; or &lt;a href="http://twitter.com/share?via=%(twitter_tag)s&amp;text=%(urltitle)s"&gt;share on twitter&lt;/a&gt;.&lt;/p&gt; ''' % { 'email': config['author_email'], 'twitter_tag': config['twitter_tag'], 'urltitle': urltitle, }) footer_parts.append("\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;") return "".join(footer_parts) # This program is designed to run as a CGI script so you can rebuild your site by hitting a URL. print "Content-type: text/html\n\n" rebuildsite() print "&lt;html&gt;&lt;head&gt;&lt;title&gt;Site Rebuilt&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Site Rebuilt&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;" </code></pre>
[]
[ { "body": "<p>Here are a few suggestions:</p>\n\n<p>String comparisons should be done with <code>==</code> (and <code>!=</code>) instead of <code>is</code> (and <code>is not</code>). <code>is</code> works, but implies you are comparing identity (which is usually a memory address), whereas <code>==</code> is comparing value. See <a href=\"https://stackoverflow.com/a/2988117/331473\">https://stackoverflow.com/a/2988117/331473</a> for more information.</p>\n\n<hr>\n\n<p>Your boolean configs (eg: <code>minify_html</code>) should be actual boolean values <code>True</code>/<code>False</code> instead of 1/0. Also, when you are checking for these, you should drop the comparison. Example:</p>\n\n<pre><code>if minify_html == 1: # or minify_html == True \n ... # (if you've converted these to booleans)\n</code></pre>\n\n<p>can be written as:</p>\n\n<pre><code>if minify_html:\n ...\n</code></pre>\n\n<hr>\n\n<p>Using module level vars as configs is generally ok for a few things, but once you've got a whole catalog of things, it can be a bit much to keep track of. Several times while reviewing your code I found myself saying \"Where did that var come from?\".</p>\n\n<p>If you want to address this, you could put these in a dictionary so it's \"namespaced\" so to speak. Example:</p>\n\n<pre><code>config = {\n \"site_url\": \"...\",\n \"site_name\": \"...\"\n}\n</code></pre>\n\n<p>then in your code, you can more easily spot config bits:</p>\n\n<pre><code>if config['minify_html']:\n ....\n</code></pre>\n\n<hr>\n\n<p>There's more cleanup that can be done, but these are just the first few things that popped out at me. One more thing... I don't have time address it now, but the long chain of <code>if</code>/<code>else</code>s in <code>buildhtmlheader</code> could be refactored a bit to make things a little less redundant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T02:09:25.497", "Id": "6934", "ParentId": "6923", "Score": "8" } }, { "body": "<ol>\n<li>I prefer emphasize constants in UPPERCASE.</li>\n<li><p>Imports should usually be on separate lines, e.g.:</p>\n\n<pre><code>Yes: import os\n import sys\n\nNo: import sys, os\n</code></pre></li>\n<li><p>Use spaces instead of tabs.</p></li>\n<li>Avoid to name variables as built-in functions/objects. I mean <code>file</code>. If you need this function later, it will take time to figure out why it doesn't work. </li>\n<li><p><code>With</code> keyword closes file automatically if exception happens. it's preferable for opening files.</p>\n\n<pre><code>with open(filename, 'r') as f:\n content = f.read()\n</code></pre></li>\n<li><p>If you need to import your module or part of it, your code will execute <code>rebuildsite</code> each time. To prevent this, use condition</p>\n\n<pre><code>if __name__ == '__main__':\n print \"Content-type: text/html\\n\\n\"\n rebuildsite()\n print \"Site Rebuilt&lt;/body&gt;&lt;/html&gt;\"\n</code></pre></li>\n<li><p>To join path is better with <code>os.path.join</code> </p>\n\n<pre><code>os.path.join(DIRECTORY, 'sidebar.html')\n</code></pre></li>\n<li><p>More efficient way to concatenate strings in python is to join a lists, use triple quotes for new-line and % for formatting:</p>\n\n<pre><code>parts = [\n '''\n&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;%(title)s&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;''' % {'title' : title}\n]\n\nif not SIDEBAR_ON_ARTICLE_PAGES and type == \"article\":\n parts.append('''\n&lt;div class=\"article_container\"&gt;\n''')\n\nreturn ''.join(patrs)\n</code></pre></li>\n</ol>\n\n<p>Follow other <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a> recommendations </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T09:34:29.110", "Id": "6955", "ParentId": "6923", "Score": "7" } }, { "body": "<p>I like the other two answers so far and I see you've already added some of the advice in. </p>\n\n<p>I have two small additions:</p>\n\n<ol>\n<li><p>this might be shorter but it is harder to read:</p>\n\n<pre><code>for nonfile in nonentryfiles: textfiles.remove(config[\"directory\"]+\"/\"+nonfile) # Except for non-entry files\n</code></pre>\n\n<p>I'm guessing you've come from a language that emphasizes being consise but instead in python prefer to do things that make it easier to understand in siz months when you want to tweak something</p>\n\n<pre><code>for nonfile in nonentryfiles:\n textfiles.remove(config[\"directory\"] + \"/\" + nonfile)\n</code></pre>\n\n<p>new line whitespace can make it that much easier to read. <em>(also I put spaces in your string concatination. Makes it easier to read too.)</em></p>\n\n<p>Another whitespace would be all those if's else's elif's .... its too hard to find where one starts and another finishes.</p>\n\n<p>try instead:</p>\n\n<pre><code>if test:\n ...\nelse:\n ...\n\n\nif test:\n ...\nelif something else:\n ...\n</code></pre>\n\n<p>Makes it easier to find each if statement.</p></li>\n<li><p>Commenting every line like: <code># Open up the file</code> isn't really going to help. It just makes the useful comments harder to find in all the noise.</p>\n\n<p>Instead try to find the comments that generalize the section of code and remove the rest. Or if you had to do something unusual leave them in too. Think \"if I had no idea what this code does which lines would I need explaining.\"</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T00:56:25.543", "Id": "10893", "Score": "1", "body": "Thank you. I guess I was falling for the old \"keep the lines fewer\" idea. I get that clarity in code is most important. I'm refactoring now. Thank you for the excellent feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T03:18:01.100", "Id": "10895", "Score": "1", "body": "I updated the code above based on the feedback you guys sent. I'd always appreciate more tips and tricks. Thank you for the style guide! I'll check that out right now. Learning a lot from you guys. Thank you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T23:10:24.860", "Id": "6974", "ParentId": "6923", "Score": "5" } }, { "body": "<p>I'd strongly suggest moving the HTML content out of the code and into separate files; I know you want to keep this simple and single-file but in this case there some real benefits to treating the HTML as a resource rather than as code:</p>\n\n<ol>\n<li>HTML is a finicky format. It's easy to screw up an escape or lose a bracket and mess up the output. With separate files it's trivial to preview them and verify them independent of possible code bugs.</li>\n<li>Since HMTL is so finicky, keeping it inline with code also means you'll have to worry about an extra quote character somewhere causing code parsing errors.</li>\n<li>It's easier to iterate on tweaky stuff like changes to CSS using an HTML specific editing tool than by messing with tags in a Python IDE or a plain text editor</li>\n</ol>\n\n<p>I'd also use <a href=\"http://docs.python.org/2/library/string.html#template-strings\" rel=\"nofollow\">string.Template</a> for any complex string formatting opertations. The % operator is great for single substitutions but Template is better for keeping the code clean:</p>\n\n<pre><code> example = Template('''\n &lt;span font =\"${font}\"&gt; Good ${timeofday}, ${salute} ${name}&lt;spam&gt; \n ''')\n\n print example.substitute(font='sanserif', timeofday='evening', salute='Mr.', name='Bond')\n</code></pre>\n\n<p>Plus you can use safe_substitute to allow more error-tolerant display so you don't bork your server.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-20T03:32:29.220", "Id": "37799", "ParentId": "6923", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T16:39:17.887", "Id": "6923", "Score": "11", "Tags": [ "python", "security", "markdown" ], "Title": "Markdown static blogger program" }
6923
<p>Which version of this code is better?</p> <p>Ver 1.</p> <pre><code>a = 0 for i in xrange( 1000 ): if i % 3 == 0 or i % 5 == 0: a += i print a </code></pre> <p>Ver 2.</p> <pre><code>from operator import add print reduce( add, ( i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0 ) ) </code></pre> <p>Things I like about version one is that it is more readable, but it creates requires a variable. If you had to choose, which one would you argue is better?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:26:40.117", "Id": "10824", "Score": "1", "body": "Version 3: Use the `sum()` function with the generator used in version 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T01:11:49.140", "Id": "10856", "Score": "1", "body": "is `list descriptor` a correct name for that ? Should not be `for-loops` vs `generator comprehensions` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T01:30:30.953", "Id": "10857", "Score": "0", "body": "@joaquin Yes, it should (and is now). Descriptors are [something entirely different](http://users.rcn.com/python/download/Descriptor.htm)." } ]
[ { "body": "<p>The second version can (and should) be written using <code>sum</code> instead of <code>reduce(add,...)</code>, which is somewhat more readable:</p>\n\n<pre><code>sum(i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0)\n</code></pre>\n\n<p>That is the version that I'd prefer as far as implementations of this particular algorithm go because it's more declarative than a loop and just reads nicer in my opinion. (It's also faster though that's less of a concern).</p>\n\n<p>However it should be noted that for summing all numbers up to n that divisible by 3 or 5, <a href=\"https://codereview.stackexchange.com/a/280/128\">there's actually a better algorithm than going over all those numbers and summing them</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-01T01:01:55.780", "Id": "360280", "Score": "0", "body": "On testing, the generator version is not faster than a simple `for` loop. Do you have a reference / benchmarking to support your claim?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:30:11.403", "Id": "6928", "ParentId": "6927", "Score": "8" } }, { "body": "<p>Don't use <code>reduce</code>, it is removed python 3. </p>\n\n<pre><code>kracekumar@python-lover:~$ python -m timeit 'sum(i for i in xrange(1000) if i%3 ==0 or i%5==0) '\n1000 loops, best of 3: 232 usec per loop\n\nkracekumar@python-lover:~$ python -m timeit 'sum([i for i in xrange(1000) if i%3 ==0 or i%5==0]) '\n\n10000 loops, best of 3: 177 usec per loop\n</code></pre>\n\n<p>First method uses <code>generators</code> second one uses <code>list comprehensions</code>.</p>\n\n<p>You can use both but <code>generators</code> will occupy less memory. </p>\n\n<pre><code>In [28]: g = (i for i in xrange(1000) if i%3 ==0 or i%5==0)\n\nIn [29]: l = [i for i in xrange(1000) if i%3 ==0 or i%5==0]\n\nIn [30]: import sys\n\nIn [31]: sys.getsizeof(l)\nOut[31]: 2136\n\nIn [32]: sys.getsizeof(g)\nOut[32]: 36\n</code></pre>\n\n<p>It is advised to use generators, here is a beautiful tutorial about <a href=\"http://www.dabeaz.com/generators/\" rel=\"nofollow\">generators</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T20:23:49.927", "Id": "10852", "Score": "3", "body": "`reduce` isn't removed in Python 3, just moved (into the functools module)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T05:56:58.710", "Id": "6942", "ParentId": "6927", "Score": "0" } } ]
{ "AcceptedAnswerId": "6928", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:19:33.193", "Id": "6927", "Score": "7", "Tags": [ "python" ], "Title": "What is better? For-loops or generator expressions (in cases like this)" }
6927
<p>From <a href="http://perldoc.perl.org/perl.html" rel="nofollow">the Perl documentation</a>:</p> <blockquote> <p><a href="http://www.perl.org" rel="nofollow">Perl</a> is a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It's also a good language for many system management tasks. The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal).</p> </blockquote> <p>The <a href="http://search.cpan.org/" rel="nofollow">CPAN</a> is Perl's module repository and is where users should turn first for code that implements solutions to already-solved problems.</p> <p><a href="https://metacpan.org/module/perldelta" rel="nofollow">Changes in the latest stable release </a></p> <p><a href="http://www.perl.org/get.html" rel="nofollow">Get it now</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T00:04:50.900", "Id": "6932", "Score": "0", "Tags": null, "Title": null }
6932
Perl is a language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T00:04:50.900", "Id": "6933", "Score": "0", "Tags": null, "Title": null }
6933
<p>So today I jumbled together a script that would get data from a database, from different tables and such. I had wanted to just use simple ifs without the whiles, but I couldn't make it possible. The code I posted is useable but randomly times out when testing, and i'm afraid of how it would perform under stress. Is there any way to improve this code to stop the timing out?</p> <pre><code>&lt;?php $getConference = sprintf("SELECT DISTINCT confName, tableName FROM conferences WHERE enabled='1' ORDER BY id DESC"); $catConference = mysql_query($getConference); while($conference = mysql_fetch_array($catConference)) { echo "&lt;h2 class=\"expand\"&gt;".$conference['confName']."&lt;/h2&gt; &lt;ul class=\"collapse\"&gt;"; $getExistingEvent = sprintf("SELECT DISTINCT event FROM " . $conference['tableName']); $catExistingEvent = mysql_query($getExistingEvent); while($existingevent = mysql_fetch_array($catExistingEvent)) { $getCat = sprintf("SELECT * FROM event WHERE id='".$existingevent['event']."'"); $catResult = mysql_query($getCat); while($row = mysql_fetch_array($catResult)) { $getWinner = sprintf("SELECT place, name, event FROM 2012rlc WHERE event='".$row['id']."' ORDER BY place"); $catWinner = mysql_query($getWinner); echo " &lt;li&gt; &lt;h2 class=\"expand\"&gt;".$row['eventName']."&lt;/h2&gt; &lt;ul class=\"collapse\"&gt; "; while($winner = mysql_fetch_array($catWinner)) { echo "&lt;li&gt;".$winner['place']. " ".$winner['name']."&lt;/li&gt;"; } echo "&lt;/ul&gt;&lt;/li&gt;"; } } echo "&lt;/ul&gt;"; } mysql_free_result($catResult); mysql_free_result($catWinner); mysql_free_result($catExistingEvent); mysql_free_result($catConference); ?&gt; </code></pre> <p>Some have asked for the database schema, which I have included below: </p> <pre><code>CREATE TABLE `2012rlc` ( `id` int(11) unsigned NOT NULL auto_increment, `place` varchar(4) default '', `name` varchar(255) default NULL, `event` int(5) default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=52 DEFAULT CHARSET=latin1; CREATE TABLE `conferences` ( `id` int(11) unsigned NOT NULL auto_increment, `confName` varchar(255) default NULL, `tableName` varchar(50) default NULL, `enabled` tinyint(1) default '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; CREATE TABLE `event` ( `id` int(11) unsigned NOT NULL auto_increment, `eventName` varchar(255) default NULL, `teamEvent` tinyint(1) default '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=47 DEFAULT CHARSET=latin1; </code></pre> <p>Output to EXPLAIN MySQL command:</p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE conferences ALL NULL NULL NULL NULL 4 Using where; Using temporary; Using filesort </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T22:21:44.660", "Id": "10934", "Score": "0", "body": "What is the difference between `conferences.confName` and `2012rlc.name`? Is the schema in [3NF](http://en.wikipedia.org/wiki/Third_normal_form)?" } ]
[ { "body": "<p>First of all, does you tables have indexes? If you run the queries with <a href=\"http://dev.mysql.com/doc/refman/5.0/en/explain.html\" rel=\"nofollow\"><code>EXPLAIN</code></a> on MySql console (for example <code>EXPLAIN SELECT DISTINCT confName, tableName FROM conferences WHERE enabled='1' ORDER BY id DESC</code>), does it show that it uses indexes?</p>\n\n<hr>\n\n<p>I'm not sure that it's a real performance issue or not but the current <code>mysql_free_result</code> calls doesn't free all resources, just the last one because the code runs lots of queries in loops. You should put these calls immediately after the last use of the resource, for example:</p>\n\n<pre><code>while (...) {\n ...\n while($winner = mysql_fetch_array($catWinner)) {\n echo \"&lt;li&gt;\".$winner['place']. \" \".$winner['name'].\"&lt;/li&gt;\";\n }\n // free $catWinner at the end of every iteration\n mysql_free_result($catWinner);\n}\n</code></pre>\n\n<hr>\n\n<p>I don't think that (generally) a good design to create separate tables for (probably) the same type of records. Instead of creating separate tables for every conference, consider creating only one table. It should have a <code>conferenceId</code> attribute as well as the <code>conferences</code> table should have a <code>conferenceId</code> too (instead of the <code>tableName</code> attribute). (Don't forget the <a href=\"http://en.wikipedia.org/wiki/Foreign_key#Example\" rel=\"nofollow\">foregin keys</a>.)</p>\n\n<p>If I'm right, this <code>conferenceId</code> could be in the <code>event</code> table and you don't need separate conference tables at all. (Feel free to post your database schema too. It could be worth a new question.)</p>\n\n<hr>\n\n<p>Using <code>sprintf</code> does not make any sense here and in the similar calls:</p>\n\n<pre><code>$getExistingEvent = sprintf(\"SELECT DISTINCT event FROM \" . $conference['tableName']);\n</code></pre>\n\n<p>It's the same as</p>\n\n<pre><code>$getExistingEvent = \"SELECT DISTINCT event FROM \" . $conference['tableName'];\n</code></pre>\n\n<p>Or it could be</p>\n\n<pre><code>$getExistingEvent = sprintf(\"SELECT DISTINCT event FROM %s\", $conference['tableName']);\n</code></pre>\n\n<p>where <code>sprintf</code> does the including/formatting.</p>\n\n<hr>\n\n<p><strong>Edit:</strong></p>\n\n<p>I'd create the following indexes:</p>\n\n<pre><code>ALTER TABLE `conferences` ADD INDEX `enabled`(`enabled`);\nALTER TABLE `2012rlc` ADD INDEX `event_id`(`event`);\n</code></pre>\n\n<p>I hope it helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T18:05:16.690", "Id": "10848", "Score": "0", "body": "Alrighty, I posted my database schema in the original post. If I were to have all the data in one table, would organization be harder? Also, I have also put the output to the command you had me run in the original post as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T22:24:14.093", "Id": "10935", "Score": "0", "body": "I've updated the answer, check it, please. The schema usally should be in 3NF which removes lots of redundancy. It makes modifications easier to do." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T03:33:01.067", "Id": "6938", "ParentId": "6937", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T03:03:34.943", "Id": "6937", "Score": "3", "Tags": [ "php", "optimization", "mysql" ], "Title": "Nested while loop for getting db data. Timing out at random times because of the PHP. Any way to make this more efficient?" }
6937
<p>I have written the below code for quick sort in Java:</p> <pre><code>void quicksort (int[] a, int lo, int hi) { // lo is the lower index, hi is the upper index // of the region of array a that is to be sorted int i=lo, j=hi, h; // comparison element x int x=a[(lo+hi)/2]; // partition do { while (a[i]&lt;x) i++; while (a[j]&gt;x) j--; if (i&lt;=j) { h=a[i]; a[i]=a[j]; a[j]=h; i++; j--; } } while (i&lt;=j); // recursion if (lo&lt;j) quicksort(a, lo, j); if (i&lt;hi) quicksort(a, i, hi); } </code></pre> <p>Please review and possibly offer a better solution.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T16:19:20.123", "Id": "10844", "Score": "3", "body": "If this is homework, it should be tagged as 'homework'. If it is not homework, then it should be tagged as 'reinventing-the-wheel'." } ]
[ { "body": "<p>Some small notes:</p>\n\n<ol>\n<li><p>Instead of commenting here:</p>\n\n<pre><code>void quicksort (int[] a, int lo, int hi) {\n // lo is the lower index, hi is the upper index\n // of the region of array a that is to be sorted\n int i=lo, j=hi, h;\n</code></pre>\n\n<p>rename the variables:</p>\n\n<pre><code>void quicksort (final int[] a, final int lowerIndex, final int upperIndex)\n</code></pre>\n\n<p>It's easier to read.</p>\n\n<p>(Check <em>Clean Code</em> by Robert C. Martin, page 53-54 also.)</p></li>\n<li><p>Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method.</p>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>. (Google for \"minimize the scope of local variables\", it's on Google Books too.))</p></li>\n<li><p>This:</p>\n\n<pre><code>h=a[i]; \na[i]=a[j]; \na[j]=h;\n</code></pre>\n\n<p>can be extracted out to a <code>swap</code> method:</p>\n\n<pre><code>public void swap(final int[] arr, final int pos1, final int pos2) {\n final int temp = arr[pos1];\n arr[pos1] = arr[pos2];\n arr[pos2] = temp;\n}\n</code></pre></li>\n<li><p>Maybe you should provide an easier to use helper method too for the clients:</p>\n\n<pre><code>public void quicksort(final int[] data) {\n if (data == null) {\n throw new NullPointerException(\"data cannot be null\");\n }\n if (data.length == 0) {\n return;\n }\n quicksort(data, 0, data.length - 1);\n}\n</code></pre>\n\n<p>Note the input validation.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T05:37:04.763", "Id": "6940", "ParentId": "6939", "Score": "7" } }, { "body": "<p>You shorten the code a little bit, but it might hurt readability:</p>\n\n<pre><code> a[i]=a[j]; \n a[j]=h;\n i++; \n j--;\n\n //can be written as:\n\n a[i++]=a[j]; \n a[j--]=h;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T10:13:33.537", "Id": "10841", "Score": "0", "body": "I agree, this does make things harder to follow, although I'm curious... what performance advantage might this have at runtime. I suspect this will result in fewer instructions to execute, is that right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T16:17:49.297", "Id": "10843", "Score": "4", "body": "I doubt it will have any effect on the runtime. Both the java-to-bytecode compiler and the bytecode-to-machine-code jit of the vm know very well how to optimize simple things like that as best as possible, no matter how you code them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T09:54:07.800", "Id": "6944", "ParentId": "6939", "Score": "1" } }, { "body": "<p><strong>Extract smaller methods</strong></p>\n\n<p>Methods should only do one thing. In other answers it was already pointed out that for example the swapping mechanism can be extracted into its own method. This couldn't be more true, the <code>quicksort</code> method has no business knowing about how to swap two variables in an array. </p>\n\n<p><strong>Variable declaration</strong></p>\n\n<p>Refrain from declaring multiple variables on a single line. It's less readable and you're making one line do multiple things. Declare each variable on its own line.</p>\n\n<p>Give your variables more meaningful names and declare them in the innermost scope possible, as demonstrated by palacsint. Variable names that are only one or two characters long are bad as a rule.</p>\n\n<p><strong>Comments</strong></p>\n\n<p>Do document your code, particularly public or package-restricted methods. See the following example:</p>\n\n<pre><code>/**\n *\n * @param array An array of integers that is to be sorted.\n * @param lowerBound The lower index of the region of the array that is to\n * be sorted.\n * @param upperBound The upper index of the region of the array that is to\n * be sorted.\n */\nvoid quicksort(int[] array, int lowerBound, int upperBound) {\n</code></pre>\n\n<p>Don't rely on comments to make it clear what your code does. Methods should be short, simple and only do one thing. With the help of meaningful variable and method names and good documentation, it shouldn't be hard to figure out what the method does. You will not need comments.</p>\n\n<p><strong>Brackets</strong></p>\n\n<p>With if-statements or loops that have only one line in their body, it's sometimes tempting to omit brackets. Do use them anyway. It will make your code a few lines longer, but it will help readability. Also, it'll be easier to add more lines to the body afterwards.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-15T01:42:53.140", "Id": "54280", "ParentId": "6939", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T04:34:31.693", "Id": "6939", "Score": "8", "Tags": [ "java", "sorting", "quick-sort" ], "Title": "Quick Sort Implementation" }
6939
<p>I need a way to build up a sort of stack of places to search for an item.</p> <p>What I would like to do is to have each layer searched for an item, and if it is found at that level, then it should be loaded by each higher level (successively). </p> <p>What I have so far is just a basic framework, but I was wondering if I was missing some more apt abstraction here in terms of command flow. Does anyone have any suggestions?</p> <pre><code>type Result = String type Query = String type Search = Query -&gt; Maybe Result type Load = Result -&gt; Maybe Result data LoadFunc = LoadFunc { search :: Search, load :: Load } data RunFunc = RunFunc { runner :: [RunFunc] -&gt; Maybe Result } mkRunFunc :: Query -&gt; LoadFunc -&gt; RunFunc mkRunFunc q lf = RunFunc r where r (x:xs) = case search lf q of Nothing -&gt; runner x xs &gt;&gt;= load lf a -&gt; a r [] = search lf q inMem :: LoadFunc inMem = LoadFunc { search = search, load = load } where search q = if q == "hi" then return $ "Found in mem." else Nothing load = addToLog "Loaded to mem." renDisk :: LoadFunc renDisk = LoadFunc { search = search, load = load } where search q = if q == "foo" then return $ "Found rendered." else Nothing load = addToLog "Added rendered." onDisk :: LoadFunc onDisk = LoadFunc { search = search, load = load } where search q = if q == "bar" then return $ "Found on disk." else Nothing load = addToLog "Now on disk." addToLog :: Result -&gt; Result -&gt; Maybe Result addToLog next str = return $ str ++ (' ':next) tester :: [LoadFunc] -&gt; Query -&gt; Maybe Result tester caches q = runner first rem where caches' = mk `fmap` caches first = head caches' rem = tail caches' mk = mkRunFunc q </code></pre> <p>To see this in action, it should be sufficient to load up ghci and enter:</p> <pre><code>tester "bar" [inMem,renDisk,onDisk] </code></pre>
[]
[ { "body": "<p>How about making <code>inMem</code> &amp; co \"bracket\" functions? Like follows:</p>\n\n<pre><code>import Control.Monad.Writer\n\ntype M a = Writer String a\ntype LoadFunc a b = (a -&gt; M b) -&gt; a -&gt; M b\n\ntype Query = String\ntype Result = ()\n\ninMem :: LoadFunc Query Result\ninMem _ \"hi\" = tell \"Found in mem. \"\ninMem f q = f q &gt;&gt; tell \"Added to mem. \"\n\nrenDisk :: LoadFunc Query Result\nrenDisk _ \"foo\" = tell \"Found rendered. \"\nrenDisk f q = f q &gt;&gt; tell \"Added rendered. \"\n\nonDisk :: LoadFunc Query Result\nonDisk _ \"bar\" = tell \"Found on disk. \"\nonDisk f q = f q &gt;&gt; tell \"Now on disk. \"\n\ntester :: [LoadFunc Query Result] -&gt; Query -&gt; M Result\ntester = foldr ($) notFound\n where notFound q = tell \"Not found!\"\n</code></pre>\n\n<p>Run using <code>runWriter $ tester [inMem,renDisk,onDisk] \"bar\"</code></p>\n\n<p>This should give you the control flow you seek - as well as enough room for extension by replacing the monad as required. You could for example have <code>notFound</code> throw an exception using an <code>Error</code> monad instead (which would probably make sense).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T20:56:11.430", "Id": "10954", "Score": "0", "body": "That's an interesting idea, I like the idea of using the pattern matcher to determine a match, although I'd need more than just a writer, as I'd need to be doing some IO in there. At any rate, +1 @Peter :)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T15:57:22.490", "Id": "6949", "ParentId": "6947", "Score": "4" } } ]
{ "AcceptedAnswerId": "6949", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T14:16:16.497", "Id": "6947", "Score": "6", "Tags": [ "haskell", "functional-programming" ], "Title": "Chaining method calls and \"bubbling\" the results" }
6947
<p>I'm interested in implementing role based code in C++. I'm also interested in what side effects or barriers (from static strong typing perhaps?) have been added that I am unaware of and if there is a better way.</p> <pre><code>#include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;numeric&gt; using namespace std; // Interfaces to the roles. class IsourceAccount { public: virtual int availableBalance() = 0; virtual void withdraw(int amount) = 0; }; class IdestAccount { public: virtual int availableBalance() = 0; virtual void deposit(int amount) = 0; }; // MODEL Classes. class Account: public IsourceAccount, public IdestAccount { private: int balance; public: Account(): balance(0) { } int availableBalance() { return balance; } void deposit(int amount) { balance += amount; } void withdraw(int amount) { balance -= amount; } }; class Account2: public IsourceAccount, public IdestAccount { private: vector&lt;int&gt; audit; public: Account2() { } int availableBalance() { return accumulate( audit.begin(), audit.end(), 0 ); } void deposit(int amount) { audit.push_back(amount); } void withdraw(int amount) { audit.push_back(-amount); } }; // How the Model objects interact class moneyTransferCTX { // Role methods (from context and from roleplayers). class /*role*/ sourceAccount: public IsourceAccount { public: void transferTo(moneyTransferCTX *ctx, int amount); } *sourceAccount; class /*role*/ destAccount: public IdestAccount { public: void receive(moneyTransferCTX *ctx, int amount); } *destAccount; public: moneyTransferCTX(IsourceAccount *src, IdestAccount *dst): // Cast the objects (src,dst) to their roles (sourceAccount, destAccount). sourceAccount(static_cast&lt;decltype(sourceAccount)&gt;(src)), destAccount(static_cast&lt;decltype(destAccount)&gt;(dst)) { } void execute(int amount) { this-&gt;sourceAccount-&gt;transferTo(this, amount); } }; void moneyTransferCTX::sourceAccount::transferTo(moneyTransferCTX *ctx, int amount) { if (this-&gt;availableBalance() &lt; amount) throw -1; this-&gt;withdraw(amount); ctx-&gt;destAccount-&gt;receive(ctx, amount); } void moneyTransferCTX::destAccount::receive(moneyTransferCTX *ctx, int amount) { this-&gt;deposit(amount); } // Testing... int main() { Account2 *savings = new Account2(); Account *checking = new Account(); //Changing the class type shouldn't hurt the code. moneyTransferCTX *ctx[2]; savings-&gt;deposit(10); checking-&gt;deposit(100); ctx[0] = new moneyTransferCTX(savings, checking); ctx[1] = new moneyTransferCTX(checking, savings); printf("Opening Status- Savings: %d, Checking: %d\n", savings-&gt;availableBalance(), checking-&gt;availableBalance()); try { printf("Transfer Savings to Checking 50\n"); ctx[0]-&gt;execute(50); } catch(int n) { printf("Error: not enough funds\n"); } printf("Savings: %d, Checking %d\n", savings-&gt;availableBalance(), checking-&gt;availableBalance()); try { printf("Transfer Checking to Savings 30\n"); ctx[1]-&gt;execute(30); } catch(int n) { printf("Error: not enough funds\n"); } printf("Closing Status- Savings: %d, Checking %d\n", savings-&gt;availableBalance(), checking-&gt;availableBalance()); delete ctx[0]; delete ctx[1]; delete savings; delete checking; return 0; } </code></pre>
[]
[ { "body": "<p>In moneyTransferCTX:</p>\n\n<p>You are using pointers. As you never expect these to be NULL (and they can't be changed) you should be using references.</p>\n\n<p>The constructor is casting objects to things that are not necessarily valid.</p>\n\n<pre><code>moneyTransferCTX(IsourceAccount *src, IdestAccount *dst):\n // Cast the objects (src,dst) to their roles (sourceAccount, destAccount).\n sourceAccount(static_cast&lt;decltype(sourceAccount)&gt;(src)),\n destAccount(static_cast&lt;decltype(destAccount)&gt;(dst))\n{}\n</code></pre>\n\n<p>Just because a src is an IsourceAccount does not mean it is also sourceAccount so casting it may not be valid. But it looks like what you are trying was to create a wrapper class (like this):</p>\n\n<pre><code>class sourceAccount\n{\n IsourceAccount&amp; account;\n public:\n sourceAccount(IsourceAccount &amp;acc): account(acc) {}\n void transferTo(moneyTransferCTX&amp; ctx, int amount)\n {\n if (account.availableBalance() &lt; amount) throw -1;\n account.withdraw(amount);\n\n ctx.destAccount-&gt;receive(ctx, amount);\n }\n} sourceAccount;\n</code></pre>\n\n<p>Personally I think this is overkill and you should just put the work you were putting in these classes into the execute method.</p>\n\n<p>I would do this:</p>\n\n<pre><code>// How the Model objects interact\nclass moneyTransferCTX \n{\n IsourceAccount&amp; sourceAccount;\n IdestAccount&amp; destAccount;\n\npublic:\n moneyTransferCTX(IsourceAccount&amp; src, IdestAccount&amp; dst)\n : sourceAccount(src)\n , destAccount(dst)\n {}\n\n void execute(int amount)\n {\n if (sourceAccount.availableBalance() &lt; amount) throw -1;\n sourceAccount.withdraw(amount);\n destAccount.deposit(amount);\n } \n};\n</code></pre>\n\n<p>Creating dynamic objects should not be done if not required.</p>\n\n<pre><code>Account2 *savings = new Account2();\nAccount *checking = new Account(); //Changing the class type shouldn't hurt the code.\n</code></pre>\n\n<p>It is easier to create normal objects (then you don't have to delete them). If you must create them then you should wrap their usage in a shared pointer.</p>\n\n<pre><code>Account2 savings;\nAccount checking; //Changing the class type shouldn't hurt the code.\n</code></pre>\n\n<p>Learn to use the C++ streams (It provides type safety):</p>\n\n<pre><code>printf(\"Opening Status- Savings: %d, Checking: %d\\n\",\n savings-&gt;availableBalance(),\n checking-&gt;availableBalance()); \n\n//\n\nstd::cout &lt;&lt; \"Opening Status- Savings: \" &lt;&lt; savings-&gt;availableBalance()\n &lt;&lt; \", Checking: \" &lt;&lt; checking-&gt;availableBalance()\n &lt;&lt; \"\\n\"; \n</code></pre>\n\n<p>Your use of exceptions is on the edge of being acceptable. Some people will say it is OK others will say it is in-appropriate. Personally I could go either way depending on what the application is doing. What you should keep in mind that exceptions are used to transfer control when an error occurs but should not normally by used for control flow. Error codes/status can be good internally, but <strong>don't leak them outside your interface</strong>.</p>\n\n<p>The other thing I would point out is that you should probably not use int (though I suspect you were just doing that as a demonstration) as an exception. Either pick one of the standard exceptions or build your own (derived from std::runtime_error).</p>\n\n<pre><code> try {\n printf(\"Transfer Savings to Checking 50\\n\");\n ctx[0]-&gt;execute(50);\n } catch(int n) {\n printf(\"Error: not enough funds\\n\");\n }\n</code></pre>\n\n<p>More pointer comments. Normal (modern C++) contains very few pointers. And even less explicit calls to delete. Any dynamically allocated object should be wrapped inside a smart pointer (or container like object boost::ptr_container springs to mind here). This makes there usage exception safe.</p>\n\n<pre><code>std::auto_ptr&lt;moneyTransferCTX&gt; tr(new moneyTransferCTX(checking, savings));\n// Note I am using auto_ptr as this is the only smart pointe in C++03\n// But it is not considered a good one (as it is easy to misuse)\n// Look up the boost::shared_ptr or if you have C++11 compiler it is part of the standard.\n\n// Note there are several good smart pointers and you should learn when to use\n// each one appropriately. \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T07:27:26.367", "Id": "6954", "ParentId": "6952", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T23:11:14.343", "Id": "6952", "Score": "7", "Tags": [ "c++", "finance" ], "Title": "Bank transaction implementation - side-effects of barriers" }
6952
<p>I have a requirement to capture a string in a specific format of <code>* [Numeric Digits] *</code>. This is how I have done right now but I think it would be faster with Regular Expressions. I don't have a lot of experience with RegEx, so please help me optimize this code using RegEx.</p> <pre><code>if (string.IsNullOrEmpty(BarcodeScan) &amp;&amp; e.KeyChar.ToString() == "*") BarcodeScan = e.KeyChar.ToString(); else { if (BarcodeScan.StartsWith("*")) { if (int.TryParse(e.KeyChar.ToString(), out i)) BarcodeScan += i.ToString(); else if (e.KeyChar.ToString() == "*") { BarcodeScan += "*"; ArticleID = BarcodeScan.Substring(1, BarcodeScan.Length - 2); } else BarcodeScan = string.Empty; } } </code></pre> <p>The above code is written in KeyPress event so I have to capture the string as the user is doing the input. Basically the first <code>*</code> means that the user has started entering Article ID and I keep on capturing numeric digits till he enters another <code>*</code>. </p> <p>This means that </p> <ul> <li><code>*2323</code> is valid but incomplete</li> <li><code>*34h</code> is invalid</li> <li><code>*343f33</code> is invalid </li> <li><code>*3434hsds3 *</code> is invalid</li> <li><strong><code>*3412 *</code> is valid and complete</strong></li> </ul> <p>How do I check for <code>*2323</code> in regex? I tried <code>^\*\d+</code> but it allows <code>*22f</code> as well.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T10:57:53.320", "Id": "10860", "Score": "1", "body": "This free tool is great for testing your expressions http://www.radsoftware.com.au/regexdesigner. I'm not associated with the company, just a grateful user :)" } ]
[ { "body": "<p>Could you possibly provide more samples of your data? In any case, try this </p>\n\n<pre><code>Regex regex = new Regex(@\"^[*]\\d+[*]$\");\n</code></pre>\n\n<p>If you actually expect the brackets (e.g. []) using the following:</p>\n\n<pre><code>Regex regex = new Regex(@\"^[*][\\[]\\d+[]][*]$\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T11:29:07.713", "Id": "10861", "Score": "0", "body": "thanks for your reply. Could you please check out my question again as I have given more details of what I want to do. What would be the regex to check *NumericDigits but disallow anything else" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T11:51:08.153", "Id": "10862", "Score": "0", "body": "To check for `*2323` use `^[*][\\[]\\d+$`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T11:59:55.587", "Id": "10863", "Score": "0", "body": "it didnt work. What is the purpose of [\\\\[] ? \\d+$ means that there should be on or more numerics at the end?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T12:31:34.403", "Id": "10864", "Score": "0", "body": "The `[*]` checks to ensure it starts with a '*'. The `[\\[]` checks to ensure the next character is '['. The `\\d+` checks to ensure it has a series of digits. I ran a test for `*[123` on http://www.regexplanet.com/advanced/dotnet/index.html and a match was found. Wait... Sorry, I misread your sample data you wanted to test `*123`. My bad... use `^[*]\\d+$`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T19:49:08.450", "Id": "10882", "Score": "0", "body": "thanks for your help! Sorry I could not vote up as I do not have reputation of 15." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T20:00:06.270", "Id": "10884", "Score": "0", "body": "No problem, just glad to help" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T10:43:22.113", "Id": "6958", "ParentId": "6956", "Score": "4" } } ]
{ "AcceptedAnswerId": "6958", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T09:41:04.387", "Id": "6956", "Score": "3", "Tags": [ "c#", ".net", "asp.net", "regex", "winforms" ], "Title": "Capturing a string in a specific format" }
6956
<p>Reading Jeff Atwood's <a href="http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html" rel="noreferrer">"Why Can't Programmers.. Program?"</a> led me to think that almost all of the solutions would not be something I would want in my own code-base. The Fizz Buzz program specification from Imran is <a href="http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/" rel="noreferrer">here</a> which says:</p> <blockquote> <p>Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.</p> </blockquote> <p>Implementing my solution differently than almost everyone else - I would like to put my solution up for review (as everyone doing it differently must think that my solution is not the best).</p> <p>Could you please review my approach. Is it overkill to suggest such a solution? Under what conditions would you split it into a Model and Views? Are there any issues with the code?</p> <p>For a start, I don't think a language agnostic definition of the problem can fully describe the best solution. In an interview I would find out by asking questions what was expected of the Fizz Bang code. Probable questions and my assumed answers are:</p> <ol> <li><p>Whether any changes were likely to be made in the future? (such as new words, different rules other than 'Fizz' on multiples of 3 and 'Bang' on 5). &nbsp;&nbsp;&nbsp;<strong>Yes</strong></p></li> <li><p>Whether the existing code-base was procedural or OO? &nbsp;&nbsp;&nbsp;<strong>OO</strong></p></li> </ol> <p>I have decided to split the model and view components so that different output formats could be easily implemented.</p> <p>Model:</p> <pre><code>class Model_Fizz_Buzz { private $fizzBuzz; /** Construct the Fizz Buzz game model. * @param fizzBuzz \Array The list of period =&gt; text for the game. If the * number is a multiple of the period then the text should be used. */ public function __construct(Array $fizzBuzz=array()) { $this-&gt;fizzBuzz = $fizzBuzz; } /** Get the Fizz_Buzz game numbers. * @param start \int The number to start from (defaults to 1). * @param end \int The number to finish with (defaults to 100). */ public function get($start=1, $end=100) { $data = array(); for ($num = $start; $num &lt;= $end; $num++) { $data[$num] = ''; foreach ($this-&gt;fizzBuzz as $period =&gt; $text) { if ($num % $period === 0) { $data[$num] .= $text; } } if (empty($data[$num])) { $data[$num] = $num; } } return $data; } } </code></pre> <p>View:</p> <pre><code>class View_Text_Lines { /** Write the data values separated by newlines. * @param data \array The data to be written. */ public function write(Array $data) { foreach ($data as $val) { echo $val . PHP_EOL; } } } </code></pre> <p>Usage would be:</p> <pre><code>$fizzView = new View_Text_Lines(); echo PHP_EOL . '-- Standard Fizz Buzz' . PHP_EOL; $fizzBuzz = new Model_Fizz_Buzz(array(3 =&gt; 'Fizz', 5 =&gt; 'Buzz')); $fizzView-&gt;write($fizzBuzz-&gt;get()); echo PHP_EOL . '-- Three Buzz Bang' . PHP_EOL; $threeBuzz = new Model_Fizz_Buzz(array(3 =&gt; 'Three', 4 =&gt; 'Buzz', 5 =&gt; 'Bang')); $fizzView-&gt;write($threeBuzz-&gt;get(30, 61)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T16:59:06.717", "Id": "32262", "Score": "4", "body": "An important part of writing good code is choosing which code *not to write*. The above is an *insanely* over-engineered solution, and it would not hire somebody who produced it. I want you to do one days work per day. I do not want you to do one days work per month, which is how this code suggests you will work. I would be worried that you're the sort of person who produces a mini-framework to solve even the simplest of problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T17:12:22.750", "Id": "32265", "Score": "3", "body": "I have worked with people who write code this way. They are the *worst people to work with*. They move at a glacial pace and spend most of their time writing code that they will *throw out* when they realize they've produced a bloated, unmaintainable monster that is in desperate need of refactoring. The worst thing you can do to a codebase is introduce unneeded complexity. You're introducing tremendous space for maintenance headaches and potential bugs for *no gain*." } ]
[ { "body": "<blockquote>\n <p>Is it overkill to suggest such a solution? </p>\n</blockquote>\n\n<p>Yes, I think so :-)</p>\n\n<blockquote>\n <p>Under what conditions would you split it into a Model and Views? </p>\n</blockquote>\n\n<p>If you need more than one view. For example, if the specification says that the program should be able to write the results to the screen, a CSV/PDF file, a network socket, a web service etc.</p>\n\n<blockquote>\n <p>Are there any issues with the code?</p>\n</blockquote>\n\n<p>It's fine, just three issues:</p>\n\n<ul>\n<li>Naming: I'd rename <code>$data</code> to <code>$result</code>.</li>\n<li>Input checks: \n\n<ul>\n<li>What should happen when <code>$start &gt; $end</code>? (Check and throw an exception.)</li>\n<li>What should happen when <code>$period</code> is not a number? (Throw an exception in the constructor.)</li>\n</ul></li>\n<li>Unit tests are missing.</li>\n</ul>\n\n<blockquote>\n <p>Whether any changes were likely to be made in the future?</p>\n</blockquote>\n\n<p>I would not try predicting it. If there are some change requests refactor it. The tests will show whether there is a regression or not. On Programmers.SE there are same questions about it:</p>\n\n<ul>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/59810/design-for-future-changes-or-solve-the-problem-at-hand\">Design for future changes or solve the problem at hand</a></li>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/79586/future-proofing-code\">Future proofing code</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T15:07:42.873", "Id": "6967", "ParentId": "6957", "Score": "13" } }, { "body": "<p>I agree that your solution is proper and any reviewer would understand that you're experienced.</p>\n\n<p>My suggestion, beyond palacsint's, is that you slim your code down a bit to make it more readable. I cut 11 lines from <code>get</code>, decreasing it's length by 46%, without compromising on readability one bit.</p>\n\n<pre><code>public function get($start=1, $end=100) {\n $data = array();\n\n for($num = $start; $num &lt;= $end; $num++) {\n foreach($this-&gt;fizzBuzz as $period =&gt; $text)\n if($num % $period === 0)\n $data[$num] = $text;\n else\n $data[$num] = $num;\n }\n\n return $data;\n}\n</code></pre>\n\n<p>Of course this is personal preference, but I hope to inspire thought regardless of whether that would cause an actual change of mind or not.</p>\n\n<p>PS. Sorry to comment on such an old question. I simply wanted to post my thoughts for anyone who might dig this up as I did.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T04:45:00.523", "Id": "32241", "Score": "1", "body": "`$data[$num] .= $text;` will issue a warning if `$data[$num]` doesn't already exist. (In other words, this code is going to spit out a ton of warnings.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T13:48:24.523", "Id": "32252", "Score": "0", "body": "Thanks Corbin, I didn't notice the dot. Fixed now!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T17:06:34.680", "Id": "32264", "Score": "0", "body": "I can not disagree more with your first line. This code does not speak of experience to me; it speaks of crippling inexperience. Only somebody who had never written code professionally could produce something so overwrought for such a simple task. I have worked with people like this. They take ten times longer than anybody else to solve the same problems. Given a half-day problem, they'll spend a full day writing *most* of a solution and then throw it out because they thought of a better architecture." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-21T12:34:14.330", "Id": "33275", "Score": "0", "body": "The dot was there for a reason, because multiple periods may be present for a given number." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-05T02:01:27.483", "Id": "20168", "ParentId": "6957", "Score": "5" } } ]
{ "AcceptedAnswerId": "6967", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T10:33:55.023", "Id": "6957", "Score": "11", "Tags": [ "php", "interview-questions", "fizzbuzz" ], "Title": "Fizz Buzz interview question code" }
6957
<p>This code is still very naive. I am trying to convert an existing XSD to JSONSchema. Firstly, pardon the variable names (I know some are really just stupid but I will fix them once I get all the functionality to work.) </p> <pre><code>using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Schema; using Newtonsoft.Json; namespace XSDToJson { public class ReadXsd { private static string GetTargetSchema(string filepath) { var doc = new XmlDocument(); doc.Load(filepath); return doc.OfType&lt;XmlElement&gt;().First().Attributes["targetNamespace"].Value; } public static void ValidationCallback(object sender, ValidationEventArgs args) { switch (args.Severity) { case XmlSeverityType.Warning: Console.Write("WARNING: "); break; case XmlSeverityType.Error: Console.Write("ERROR: "); break; } Console.WriteLine(args.Message); } private static Dictionary&lt;String, Object&gt; HandleSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction restriction) { var res = new Dictionary&lt;String, Object&gt;(); foreach (var t in restriction.Facets.OfType&lt;XmlSchemaEnumerationFacet&gt;()) { var d = new Dictionary&lt;String, Object&gt;{{"fixed", t.IsFixed}}; var annotation = HandleAnnotation(t.Annotation); if (annotation != "") d.Add("description", annotation); res.Add(t.Value,d); } foreach (var t in restriction.Facets.OfType&lt;XmlSchemaMaxExclusiveFacet&gt;()) { var d = new Dictionary&lt;String, Object&gt; { { "fixed", t.IsFixed } }; var annotation = HandleAnnotation(t.Annotation); if (annotation != "") d.Add("description", annotation); res.Add(t.Value, d); } foreach (var t in restriction.Facets.OfType&lt;XmlSchemaMinExclusiveFacet&gt;()) { var d = new Dictionary&lt;String, Object&gt; { { "fixed", t.IsFixed } }; var annotation = HandleAnnotation(t.Annotation); if (annotation != "") d.Add("description", annotation); res.Add(t.Value, d); } return res; } private static dynamic HandleSimpleType(XmlSchemaSimpleType simpleType) { var temp = HandleAnnotation(simpleType.Annotation); var simple = new Dictionary&lt;String, Object&gt; { {"type", simpleType.TypeCode.ToString()}, {"description", temp}, {"final", simpleType.Final.ToString()}, {"datatype", simpleType.Datatype.TypeCode.ToString()}, {"derivedby", simpleType.DerivedBy.ToString()} }; if (simpleType.Content != null) { if (simpleType.Content is XmlSchemaSimpleTypeRestriction) { var res = HandleSimpleTypeRestriction(simpleType.Content as XmlSchemaSimpleTypeRestriction); if (res.Count &gt; 0) simple.Add("enum", res); } else if (simpleType.Content is XmlSchemaSimpleTypeList) { var list = simpleType.Content as XmlSchemaSimpleTypeList; simple["type"] = "array"; simple.Add("items", new Dictionary&lt;String,Object&gt;{{"type",list.ItemTypeName.Name}}); } } return simple ; } private static dynamic HandleComplexType(XmlSchemaComplexType complexType) { dynamic properties = new ExpandoObject(); properties.type = complexType.BaseXmlSchemaType.QualifiedName.Name; properties.extends = new ExpandoObject(); ((IDictionary&lt;String, Object&gt;) properties.extends).Add("$ref", complexType.BaseXmlSchemaType.QualifiedName.Namespace + "/" + complexType.BaseXmlSchemaType.QualifiedName.Name + "#"); properties.description = HandleAnnotation(complexType.Annotation); if (complexType.AttributeUses.Count &gt; 0) { var enumerator = complexType.AttributeUses.GetEnumerator(); while (enumerator.MoveNext()) { var attribute = (XmlSchemaAttribute) enumerator.Value; if (attribute == null) continue; if (((IDictionary&lt;String, Object&gt;) properties).ContainsKey(attribute.QualifiedName.Name)) ((IDictionary&lt;String, Object&gt;) properties).Add(attribute.QualifiedName.Name + "Hello", HandleAttribute(attribute)); else ((IDictionary&lt;String, Object&gt;) properties).Add(attribute.QualifiedName.Name, HandleAttribute(attribute)); } } if (complexType.AnyAttribute != null) ((IDictionary&lt;String, Object&gt;)properties).Add("additionalItems",new Dictionary&lt;String,Object&gt;{{"$ref",complexType.AnyAttribute.Namespace}}); var sequence = complexType.ContentTypeParticle as XmlSchemaSequence; if (sequence != null) { foreach (XmlSchemaParticle childParticle in sequence.Items) { dynamic d2 = new ExpandoObject(); var element = (childParticle as XmlSchemaElement); if (element == null) continue; d2.type = element.QualifiedName.Name; d2.extends = new ExpandoObject(); ((IDictionary&lt;String, Object&gt;) d2.extends).Add("$ref", element.QualifiedName.Namespace + "/" + element.QualifiedName.Name + "#"); if (element.DefaultValue != null) ((IDictionary&lt;String, Object&gt;) d2).Add("default", element.DefaultValue); if (element.IsAbstract) ((IDictionary&lt;String, Object&gt;) d2).Add("abstract", element.IsAbstract); d2.minItems = childParticle.MinOccursString; d2.maxItems = childParticle.MaxOccursString; if (((IDictionary&lt;String, Object&gt;) properties).ContainsKey(element.QualifiedName.Name)) ((IDictionary&lt;String, Object&gt;) properties).Add(element.QualifiedName.Name + "Hello", d2); else ((IDictionary&lt;String, Object&gt;) properties).Add(element.QualifiedName.Name, d2); } } var choice = complexType.ContentTypeParticle as XmlSchemaChoice; if (choice != null) { if (((IDictionary&lt;String, Object&gt;)properties).ContainsKey("enum")) ((IDictionary&lt;String, Object&gt;)properties).Add("enum"+ "Hello", HandleChoice(choice)); else ((IDictionary&lt;String, Object&gt;)properties).Add("enum", HandleChoice(choice)); } return properties; } private static dynamic HandleChoice(XmlSchemaChoice choice) { dynamic d2 = new ExpandoObject(); d2.description = HandleAnnotation(choice.Annotation); foreach (var item in choice.Items) ((IDictionary&lt;String, Object&gt;)d2).Add(((XmlSchemaElement)item).QualifiedName.Name, FixElement(item as XmlSchemaElement)); d2.minItems = choice.MinOccursString; d2.maxitems = choice.MaxOccursString; return d2; } private static dynamic HandleXmlSchemaParticle(XmlSchemaParticle childParticle) { dynamic d2 = new ExpandoObject(); var element = (childParticle as XmlSchemaElement); if (element == null) return null; d2.type = element.QualifiedName.Name; d2.extends = new ExpandoObject(); ((IDictionary&lt;String, Object&gt;)d2.extends).Add("$ref", element.QualifiedName.Namespace + "/" + element.QualifiedName.Name + "#"); if (element.IsAbstract) ((IDictionary&lt;String, Object&gt;)d2).Add("abstract", element.IsAbstract); if (element.DefaultValue != null) ((IDictionary&lt;String, Object&gt;)d2).Add("default", element.DefaultValue); d2.minItems = childParticle.MinOccursString; d2.maxItems = childParticle.MaxOccursString; d2.description = HandleAnnotation(element.Annotation); if (element.ElementSchemaType is XmlSchemaComplexType) { var c = element.ElementSchemaType as XmlSchemaComplexType; var complex = HandleComplexType(c); ((IDictionary&lt;String, Object&gt;)d2).Add(c.BaseXmlSchemaType.QualifiedName.Name, complex); } else if (element.ElementSchemaType is XmlSchemaSimpleType) { var simple = HandleSimpleType(element.ElementSchemaType as XmlSchemaSimpleType); ((IDictionary&lt;String, Object&gt;)d2).Add(element.ElementSchemaType.QualifiedName.Name, simple); } return d2; } private static dynamic HandleComplexTypeFromElement(XmlSchemaComplexType complexType) { dynamic d = new ExpandoObject(); if (complexType.AttributeUses.Count &gt; 0){ var enumerator = complexType.AttributeUses.GetEnumerator(); while (enumerator.MoveNext()){ var attribute = (XmlSchemaAttribute)enumerator.Value; var d2 = HandleAttribute(attribute); ((IDictionary&lt;string, Object&gt;)d).Add(attribute.QualifiedName.Name, d2); } } var sequence = complexType.ContentTypeParticle as XmlSchemaSequence; if (sequence != null){ foreach (XmlSchemaParticle childParticle in sequence.Items){ var element = (childParticle as XmlSchemaElement); if (element == null) continue; if (((IDictionary&lt;string, Object&gt;)d).ContainsKey(element.QualifiedName.Name)) ((IDictionary&lt;string, Object&gt;)d).Add(element.QualifiedName.Name + "Hello", HandleXmlSchemaParticle(childParticle)); else ((IDictionary&lt;string, Object&gt;)d).Add(element.QualifiedName.Name, HandleXmlSchemaParticle(childParticle)); } } return d; } private static dynamic IterateOverElement(XmlSchemaElement element) { var complexType = element.ElementSchemaType as XmlSchemaComplexType; if (complexType == null) { var simpleType = element.ElementSchemaType as XmlSchemaSimpleType; return simpleType == null ? new ExpandoObject() : HandleSimpleType(simpleType); } return HandleComplexTypeFromElement(complexType); } private static string GetSchemaDescription(XmlSchemaAnnotation annotation) { //Get the count of the elements in Items , then chekc if it appinfo or documentation and then act accordingly if (annotation == null || annotation.Items == null) return "N/A"; var count = annotation.Items.Count; for (var i = 0; i &lt; count; i++) { if (!(annotation.Items[i] is XmlSchemaDocumentation)) continue; var d = annotation.Items[i] as XmlSchemaDocumentation; if (d == null) continue; // Console.WriteLine("Annotation" + d.Markup[i].InnerText); var temp = ""; for (var j = 0; j &lt; d.Markup.Count(); j ++ ) temp += "\n"+ d.Markup[j].InnerText; return temp; } return "N/A"; } private static string HandleAnnotation(XmlSchemaAnnotation annotation) { //Get the count of the elements in Items , then chekc if it appinfo or documentation and then act accordingly if (annotation == null || annotation.Items == null) return ""; var count = annotation.Items.Count; for (var i = 0; i &lt; count; i++) { if (annotation.Items[i] is XmlSchemaDocumentation) { var d = annotation.Items[i] as XmlSchemaDocumentation; if (d != null){ return d.Markup[i].InnerText; } } else if (annotation.Items[i] is XmlSchemaAppInfo) { var appinfo = annotation.Items[i] as XmlSchemaAppInfo; if (appinfo != null){ if (appinfo.Markup == null) return ""; var markupcount = appinfo.Markup.Count(); for (var k = 0; k &lt; markupcount; k++){ var ns = appinfo.Markup[k].NamespaceURI + "/" + appinfo.Markup[k].LocalName; var attributeCount = appinfo.Markup[0].Attributes.Count; for (var j = 0; j &lt; attributeCount; j++){ Console.WriteLine(appinfo.Markup[k].Attributes[j].Value); } } } } } return ""; } private static dynamic HandleAttributeGroup(XmlSchemaAttributeGroup attributegroup) { dynamic d = new ExpandoObject(); d.description = HandleAnnotation(attributegroup.Annotation); foreach (var attr in attributegroup.Attributes.OfType&lt;XmlSchemaAttribute&gt;()) { var a = HandleAttribute(attr); ((IDictionary&lt;String, Object&gt;) d).Add(attr.QualifiedName.Name,a); } foreach (var attr in attributegroup.Attributes.OfType&lt;XmlSchemaAttributeGroupRef&gt;()) { d.extends = new ExpandoObject(); ((IDictionary&lt;String, Object&gt;)d.extends).Add("$ref",attr.RefName.Namespace+"/"+attr.RefName.Name+"#"); } return d; } private static dynamic HandleAttribute(XmlSchemaAttribute attribute) { dynamic attr = new ExpandoObject(); attr.type = attribute.AttributeSchemaType.QualifiedName.Name; attr.extends = new ExpandoObject(); ((IDictionary&lt;String, Object&gt;)attr.extends).Add("$ref", attribute.AttributeSchemaType.QualifiedName.Namespace + "/" + attribute.AttributeSchemaType.QualifiedName.Name + "#"); if (HandleAnnotation(attribute.Annotation) != "") attr.description = HandleAnnotation(attribute.Annotation) ; if(attribute.DefaultValue != null) ((IDictionary&lt;String, Object&gt;)attr).Add("default", attribute.DefaultValue); if (attribute.Use == XmlSchemaUse.Required) attr.required = true; return attr; } private static dynamic FixElement(XmlSchemaElement element) { var delement = IterateOverElement(element); if (((element.ElementSchemaType is XmlSchemaSimpleType))) { ((IDictionary&lt;string, Object&gt;)delement).Remove("description"); ((IDictionary&lt;string, Object&gt;)delement).Add("description", HandleAnnotation(element.Annotation)); } else { ((IDictionary&lt;string, Object&gt;)delement).Add("description", HandleAnnotation(element.Annotation)); if (!element.SchemaTypeName.IsEmpty) { ((IDictionary&lt;string, Object&gt;)delement).Remove("type"); ((IDictionary&lt;string, Object&gt;)delement).Add("type", element.SchemaTypeName.Name); ((IDictionary&lt;string, Object&gt;)delement).Add("extends", new ExpandoObject()); ((IDictionary&lt;string, Object&gt;)delement.extends).Add("$ref", element.SchemaTypeName.Namespace + "/" + element.SchemaTypeName.Name + "#"); } else { if (element.ElementSchemaType.BaseXmlSchemaType == null) { ((IDictionary&lt;string, Object&gt;)delement).Add("type", element.ElementSchemaType.QualifiedName.Name); ((IDictionary&lt;string, Object&gt;)delement).Add("extends", new ExpandoObject()); ((IDictionary&lt;string, Object&gt;)delement.extends).Add("$ref", element.ElementSchemaType.QualifiedName.Namespace + "/" + element.ElementSchemaType.QualifiedName.Name + "#"); } else { ((IDictionary&lt;string, Object&gt;)delement).Add("type", element.ElementSchemaType.BaseXmlSchemaType.QualifiedName.Name); ((IDictionary&lt;string, Object&gt;)delement).Add("extends", new ExpandoObject()); ((IDictionary&lt;string, Object&gt;)delement.extends).Add("$ref", element.ElementSchemaType.BaseXmlSchemaType.QualifiedName.Namespace + "/" + element.ElementSchemaType.BaseXmlSchemaType.QualifiedName.Name + "#"); } } } if (!element.SubstitutionGroup.IsEmpty) ((IDictionary&lt;string, Object&gt;)delement).Add("substitutiongroup", element.SubstitutionGroup.Namespace + "/" + element.SubstitutionGroup.Name + "#"); if (element.IsAbstract) ((IDictionary&lt;string, Object&gt;)delement).Add("abstract", element.IsAbstract); if (element.IsNillable) ((IDictionary&lt;string, Object&gt;)delement).Add("nillable", element.IsNillable); ((IDictionary&lt;string, Object&gt;)delement).Add("maxItems", element.MaxOccurs); ((IDictionary&lt;string, Object&gt;)delement).Add("minItems", element.MinOccurs); return delement; } public static void PopulateJsonSchema(string filename , string filepath) { Console.WriteLine("------"+filename); var targetNamespace = GetTargetSchema(filepath); dynamic jsonschema = new ExpandoObject(); var schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += ValidationCallback; schemaSet.Add(targetNamespace, filepath); schemaSet.Compile(); //Populate Header Here var baseschema = schemaSet.Schemas(targetNamespace).Cast&lt;XmlSchema&gt;().First(); ((IDictionary&lt;string, Object&gt;)jsonschema).Add("$schema", baseschema.TargetNamespace); jsonschema.version = baseschema.Version; jsonschema.name = filename.Substring(0, filename.Length - 4); //Populate description of the JsonSchemaObject foreach (var obj in schemaSet.Schemas(targetNamespace).Cast&lt;XmlSchema&gt;().SelectMany(s =&gt; s.Items.OfType&lt;XmlSchemaAnnotation&gt;())){ jsonschema.description = GetSchemaDescription(obj); } jsonschema.properties = new Dictionary&lt;String, Object&gt;(); foreach (var element in schemaSet.Schemas(targetNamespace).Cast&lt;XmlSchema&gt;().SelectMany(s =&gt; s.Elements.Values.Cast&lt;XmlSchemaElement&gt;())) { Console.WriteLine(element.Name); jsonschema.properties.Add(element.Name, FixElement(element)); } //Get all the complextypes foreach (var obj in schemaSet.Schemas(targetNamespace).Cast&lt;XmlSchema&gt;().SelectMany(s =&gt; s.Items.OfType&lt;XmlSchemaComplexType&gt;())) { //.Where(obj =&gt; obj.ContentModel != null) Console.WriteLine(obj.Name); var d = HandleComplexType(obj); jsonschema.properties.Add(obj.QualifiedName.Name, d); } //get all the Simple Types foreach (var obj in schemaSet.Schemas(targetNamespace).Cast&lt;XmlSchema&gt;().SelectMany(s =&gt; s.Items.OfType&lt;XmlSchemaSimpleType&gt;().Where(c =&gt; c.Content != null))) { Console.WriteLine(obj.Name); var d = HandleSimpleType(obj); jsonschema.properties.Add(obj.QualifiedName.Name, d); } //get all the attributeGroups foreach (var obj in schemaSet.Schemas(targetNamespace).Cast&lt;XmlSchema&gt;().SelectMany(s =&gt; s.Items.OfType&lt;XmlSchemaAttributeGroup&gt;())) { Console.WriteLine(obj.Name); jsonschema.properties.Add(obj.QualifiedName.Name,HandleAttributeGroup(obj)); } //get all the attributes foreach (var attr in from XmlSchema schema in schemaSet.Schemas(targetNamespace) let temp = schema.Attributes let schema1 = schema from attr in temp.Names.Cast&lt;XmlQualifiedName&gt;().Select(name =&gt; name) .Select(t =&gt; schema1.Attributes[t] as XmlSchemaAttribute). Where(attr =&gt; attr.AttributeSchemaType != null) select attr) { jsonschema.properties.Add(attr.Name, HandleAttribute(attr)); } String json = JsonConvert.SerializeObject(jsonschema, Newtonsoft.Json.Formatting.Indented); File.WriteAllText( filepath.Replace(filename, jsonschema.name + ".js"), json.Replace("Hello", "").Replace(@"\n","").Replace(@"\r","").Replace(@"\t","")); } } } static void Main(string[] args) { const string path = @"C:\Users\ashutosh\documents\visual studio 2010\Projects\XSDToJson\XSDToJson"; var files = NavigateDirectories(path); foreach (var file in files) { ReadXsd.PopulateJsonSchema(file.Name, file.FullName); } Console.WriteLine("Press any key to exit"); } </code></pre> <ol> <li><p>As you would notice I am using an <code>IDictionary</code> to add the properties to JSON Schema. So, when I have a situation where there are two properties with the same name even though they come from two different target schema, I am stuck. The "Hello" written there is just to let me finish emitting out jsonschema. I would like to handle this schema, without making some serious breaking changes to this code.</p></li> <li><p>What design pattern could I use and is this also a case where I can refactor some set of methods into extension methods?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-05T16:08:36.230", "Id": "202431", "Score": "0", "body": "Kind of late, but why not use Json.NET? Just use xsd2code and then JSchemaGenerator generator = new JSchemaGenerator();\n \n JSchema schema = generator.Generate(typeof(...));" } ]
[ { "body": "<p>I have not tried or scrutinized your code much, but my immediate impression is that you can clean this up quite a bit.</p>\n\n<p>I recommend getting this book about clean code:\n<a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882</a></p>\n\n<p>If you look at your HandleSimpleTypeRestriction method, you repeat the same 5 lines for each foreach statement. By extracting those five lines to a method, you'll shorten the HandleSimpleTypeRestriction method by 12 lines. The code will end up like this:</p>\n\n<pre><code> private static Dictionary&lt;String, Object&gt; HandleSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction restriction) \n { \n var res = new Dictionary&lt;String, Object&gt;(); \n foreach (var t in restriction.Facets.OfType&lt;XmlSchemaEnumerationFacet&gt;()) \n AddRes(res, t);\n\n foreach (var t in restriction.Facets.OfType&lt;XmlSchemaMaxExclusiveFacet&gt;()) \n AddRes(res, t);\n\n foreach (var t in restriction.Facets.OfType&lt;XmlSchemaMinExclusiveFacet&gt;()) \n AddRes(res, t);\n\n return res; \n } \n\n private static void AddRes&lt;T&gt;(Dictionary&lt;string, object&gt; res, T t)\n // you're gonna need a where T : somebaseclass here.\n {\n var d = new Dictionary&lt;String, Object&gt;{{\"fixed\", t.IsFixed}}; \n var annotation = HandleAnnotation(t.Annotation); \n if (annotation != \"\") \n d.Add(\"description\", annotation); \n res.Add(t.Value,d); \n }\n</code></pre>\n\n<p>You could even put the for in a method so you end up with an even shorter method.</p>\n\n<p>Rinse and repeat for all your code, and I bet you've got a much more readable class.</p>\n\n<p>Then you can see if some of the methods share parameters that others don't use, and separate those into smaller utility classes with one responsibility.\nSee <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Single_responsibility_principle</a>\n(a very good practice)</p>\n\n<p>All this gives you code that is easier to understand and maintain.\nShould be done with care though, if you don't do unit testing, look into it! :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T05:43:57.277", "Id": "11138", "Score": "0", "body": "thanks for the input...this seems like the way to go ..i know about SOLID ...i am just wondering if re-factoring before i have all the functionality going is a great idea ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T22:17:09.340", "Id": "11237", "Score": "3", "body": "I believe you should work test-driven and refactor more or less all the time. The day consists of\n1. Write some test code\n2. Write some prod code\n3. Repeat from step 1 until something messy starts to work\n4. Refactor\n5. Repeat steps 1-5" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T12:23:47.330", "Id": "11345", "Score": "0", "body": "i have taken your suggestions into account and then used some of my own searching to make it slightly more readable and extensible. The core class(ReadXsd) has reduced by more than a 100 lines . The code has been updated with v 0.3." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T12:53:03.473", "Id": "11432", "Score": "3", "body": "+1 for a very solid answer. In addition to Robert C. Martin's **Clean Code** that you've already suggested, I'd like to also recommend [Growing Object-Oriented Software, Guided by Tests](http://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627) by Steve Freeman and Nat Pryce." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T19:01:09.680", "Id": "11449", "Score": "0", "body": "@codesparkle my updated question should make it a little easier for the adventurous souls :) Give it a shot" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T13:43:23.250", "Id": "7111", "ParentId": "6959", "Score": "4" } } ]
{ "AcceptedAnswerId": "7111", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T14:18:07.970", "Id": "6959", "Score": "5", "Tags": [ "c#", "converting", "json", "xsd" ], "Title": "Convert XSD to JSONSchema" }
6959
<p>This code works to copy named capture groups of a Regex to the same named properties of a strongly typed object. However, it's not pretty. Someone mentioned I should use polymorphism to at least remove the five if statements.</p> <p>What should I consider when improving this code? Suggested reading?</p> <pre><code>// Copies named capture groups in a REGEX to the properties of an object // if the names match static public void CopyProperties(Regex regex, Match source, object target) { if (target != null &amp;&amp; source != null &amp;&amp; source.Success) { var targetType = target.GetType(); // only step through non numeric capture names foreach (var sourceProp in regex.GetGroupNames() .Where(p =&gt; !Regex.IsMatch(p, @"^\d+$") &amp;&amp; !String.IsNullOrWhiteSpace(p))) { // does the target property the same as source exist? var targetPropName = targetType.GetProperty(sourceProp); // if the source and target exist if (targetPropName != null &amp;&amp; !String.IsNullOrWhiteSpace(source.Groups[sourceProp].Value) ) { var targetPropSetter = targetPropName.GetSetMethod(); // created a variable for each possible type // because I couldn't inline the Convert.ToInt32, etc. string sourceValue = source.Groups[sourceProp].Value; int? intValue = !Regex.IsMatch(sourceValue, @"^\d{1,10}$") ? (int?) null : Convert.ToInt64(sourceValue) &lt;= Int32.MaxValue ? Convert.ToInt32(sourceValue) : (int?) null; long? longValue = Regex.IsMatch(sourceValue, @"^\d{1,19}$") ? Convert.ToInt64( sourceValue) : (long?) null; bool? boolValue = Regex.IsMatch(sourceValue, @"^(?i)true$|^(?i)false$") ? Convert.ToBoolean(sourceValue) : (bool?) null; decimal? decimalValue = Regex.IsMatch(sourceValue, @"^\d+\.?\d*$") ? Convert.ToDecimal(sourceValue) : (decimal?) null; // multiple if because it didn't like a switch statement // I didn't think five micro functions would improve this if (targetPropName.PropertyType == typeof(string)) targetPropSetter.Invoke(target, new[] { (object) sourceValue }); if (targetPropName.PropertyType == typeof(Nullable&lt;Int32&gt;)) targetPropSetter.Invoke(target, new[] { (object) intValue }); if (targetPropName.PropertyType == typeof(Nullable&lt;Int64&gt;)) targetPropSetter.Invoke(target, new[] { (object) longValue }); if (targetPropName.PropertyType == typeof(Nullable&lt;Boolean&gt;)) targetPropSetter.Invoke(target, new[] { (object) boolValue }); if (targetPropName.PropertyType == typeof(Nullable&lt;Decimal&gt;)) targetPropSetter.Invoke(target, new[] { (object) decimalValue }); } } } } </code></pre>
[]
[ { "body": "<p>By seeing the structure of your code structure i assume that all those if staements can easily be changed by a 'switch case' - which obviuosly is a <a href=\"http://c2.com/xp/CodeSmell.html\" rel=\"nofollow\">code smell</a>. I think you need to refactor your code. For further details please visit this <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\" rel=\"nofollow\">link</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T09:07:12.953", "Id": "6961", "ParentId": "6960", "Score": "2" } }, { "body": "<p>I would consider using <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx\" rel=\"nofollow\">TypeDescriptor</a> to help simplify the code. That will allow you to get all the properties and associated <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx\" rel=\"nofollow\">TypeConverters</a> without ugly reflection calls. Here is an example:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> public static void CopyProperties(Regex regex, Match match, object target)\n {\n if (regex == null || match == null || target == null)\n {\n throw new ArgumentNullException();\n }\n\n if (match.Success)\n {\n var properties = TypeDescriptor\n .GetProperties(target)\n .Cast&lt;PropertyDescriptor&gt;()\n .Where(prop =&gt; !prop.IsReadOnly);\n\n foreach (string groupName in regex.GetGroupNames())\n {\n var property = properties\n .FirstOrDefault(prop =&gt; prop.Name == groupName);\n\n if (property != null &amp;&amp; \n property.Converter.CanConvertFrom(typeof(string)))\n {\n try\n {\n property.SetValue(\n target,\n property.Converter.ConvertFrom(\n match.Groups[groupName].Value));\n }\n catch\n {\n // Probably couldn't convert string to type\n }\n }\n }\n }\n }\n</code></pre>\n\n<p>The only caveats with the code above is I don't think it will get properties in base classes and the try/catch is a little clunky but it's probably OK if your regex to parse out the groups were specific enough.</p>\n\n<p>Scott Hanselman has a good article about TypeConverters <a href=\"http://www.hanselman.com/blog/TypeConvertersTheresNotEnoughTypeDescripterGetConverterInTheWorld.aspx\" rel=\"nofollow\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T11:19:16.047", "Id": "6962", "ParentId": "6960", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T08:57:27.790", "Id": "6960", "Score": "3", "Tags": [ "c#", "regex" ], "Title": "Code Improvement: Copy Regex named capture groups to strongly typed object" }
6960
<p>Basically I just wrote this calculator as a sort of JavaScript test for myself. It's a simple calculator with addition, subtraction, and multiplication. I've made some improvements to it before posting this. </p> <p>At this point I was hoping anyone could just point out some ways I could have cleaned this code up more, basically as an exercise in learning. I've included the JavaScript, followed by the HTML.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> displayNum = ""; storedNum = ""; operation = 0; queuedOperation = 0; calculationFinished = false; function clearDisplay() { // Select the calculator's display var display = document.getElementById("display"); // Clear the global variables and the display displayNum = ""; storedNum = ""; operation = 0; queuedOperation = 0; display.value = displayNum; } function numInput(num) { // Select the calculator's display var display = document.getElementById("display"); // Check if the display is empty and the number being pressed is 0 // This is to make sure the first number isn't 0 because then javascript thinks we are using OCTAL (Base eight) if ((display.value == "") &amp;&amp; num == "0") { // If it is, do nothing return; } // Check if a calculation has finished // If it has replace the number in the display (the answer to the calculation with the number // that was just pressed and change calculation finished back to false else if (calculationFinished == true) { display.value = num; calculationFinished = false; } // if neither of these is the case input the numbers as usual else { display.value += num; } } function insertDecimal(dec) { // Select the calculator's display var display = document.getElementById("display"); // Loop through the current number to make sure there isn't already a decimal for (i = 0; i &lt; display.value.length; i++) if (display.value.charAt(i) == '.') { // If there is, do nothing return; } // If there isn't add a decimal to the end of the displayed number display.value += dec; } function setOperation(command) { // Select the calculator's display var display = document.getElementById("display"), displayNum = display.value; // eval both the numbers to remove quotes // otherwise 4 + 5 will be "4" + "5" which in JS will equal 45 evalDisplay = eval(displayNum), evalStored = eval(storedNum); // Check if there is a queued operation // If there is a queued operation calculate it // Then set the stored number to total of the calculation if (queuedOperation == 0) { storedNum = display.value; } else if (queuedOperation == 1) { storedNum = evalStored + evalDisplay; } else if (queuedOperation == 2) { storedNum = evalStored - evalDisplay; } else if (queuedOperation == 3) { storedNum = evalStored * evalDisplay; } // Check what command was put into the calculator // Then set the operation to the correct number if (command == 'add') { operation = 1; } else if (command == 'subtract') { operation = 2; } if (command == 'multiply') { operation = 3; } // Queue up an operation for enterint multiple commands without hitting equals // i.e. 10x4+8-9+3= queuedOperation = operation; // Clear the display in order to receive a new number display.value = ''; } function calculate() { // Select the calculator's display var display = document.getElementById("display"); displayNum = display.value; var evalDisplay = eval(displayNum), evalStored = eval(storedNum); // Do the math if (operation == 1) { displayNum = evalStored + evalDisplay; } else if (operation == 2) { displayNum = evalStored - evalDisplay; } else if (operation == 3) { displayNum = evalStored * evalDisplay; } // Change display to the answer display.value = displayNum; if (operation != 0) calculationFinished = true; // Clear all the global variables // Necessary in case the user wants to make a calculation using the answer operation = 0; queuedOperation = 0; displayNum = ""; storedNum = ""; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="calculator.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;form class="calcForm" name="calculator"&gt; &lt;input type="text" class="calcDisplay" id="display" /&gt; &lt;div class="calcRow"&gt; &lt;input type="button" class="calcButton" value="7" onclick="numInput('7')" /&gt; &lt;input type="button" class="calcButton" value="8" onclick="numInput('8')" /&gt; &lt;input type="button" class="calcButton" value="9" onclick="numInput('9')" /&gt; &lt;input type="button" class="calcButton" value="+" onclick="setOperation('add')" /&gt; &lt;/div&gt; &lt;div class="calcRow"&gt; &lt;input type="button" class="calcButton" value="4" onclick="numInput('4')" /&gt; &lt;input type="button" class="calcButton" value="5" onclick="numInput('5')" /&gt; &lt;input type="button" class="calcButton" value="6" onclick="numInput('6')" /&gt; &lt;input type="button" class="calcButton" value="-" onclick="setOperation('subtract')" /&gt; &lt;/div&gt; &lt;div class="calcRow"&gt; &lt;input type="button" class="calcButton" value="1" onclick="numInput('1')" /&gt; &lt;input type="button" class="calcButton" value="2" onclick="numInput('2')" /&gt; &lt;input type="button" class="calcButton" value="3" onclick="numInput('3')" /&gt; &lt;input type="button" class="calcButton" value="x" onclick="setOperation('multiply')" /&gt; &lt;/div&gt; &lt;div class="calcRow"&gt; &lt;input type="button" class="calcButton" value="0" onclick="numInput('0')" /&gt; &lt;input type="button" class="calcButton" value="." onclick="insertDecimal('.')" /&gt; &lt;input type="button" class="calcButton" value="C" onclick="clearDisplay()" /&gt; &lt;input type="button" class="calcButton" value="=" onclick="calculate()" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-22T14:49:27.600", "Id": "334443", "Score": "0", "body": "Your four function calculator only implements three functions." } ]
[ { "body": "<p>Replace <code>eval(displayNum)</code> with <code>+displayNum</code> - eval executes the value which not only slower it's vulnerable to XSS.</p>\n\n<p>Other than that you would start to look into making you code Object Oriented (OO) to combine code into logical groups and to take the functions and variables out of the window scope. Good Posts:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/907225/object-oriented-javascript-best-practices\">https://stackoverflow.com/questions/907225/object-oriented-javascript-best-practices</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1908443/what-are-good-javascript-oop-resources\">https://stackoverflow.com/questions/1908443/what-are-good-javascript-oop-resources</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T13:13:25.267", "Id": "6964", "ParentId": "6963", "Score": "3" } }, { "body": "<ul>\n<li><p>All those globals give me the willies. Same with the <code>eval</code>s.</p></li>\n<li><p>You're doing math in two places -- in <code>calculate</code> and in <code>setOperation</code>. Consider that <code>display.value = x; storedNum = display.value; display.value = ''</code> has the same effect as <code>storedNum = x; display.value = ''</code>. Translation: you can call <code>calculate()</code> from <code>setOperation</code>, and avoid repeating yourself. It also removes the need for <code>queuedOperation</code>.</p></li>\n<li><p><code>insertDecimal</code> loops over the whole string, checking each char for equality with <code>'.'</code>. Better would be <code>if (display.value.indexOf('.') != -1) return;</code>. Or even better than that, <code>if (display.value.indexOf('.') === -1) { /* add the dot */ }</code>.</p></li>\n<li><p><code>insertDecimal</code> also takes the decimal point as an argument. This doesn't make sense, since you're not using it to add anything but decimal points. Lose the arg.</p></li>\n<li><p>The value of <code>operation</code> isn't obvious. 0, 1, 2, or 3? Those numbers don't mean anything to me. You're not limited to numbers; you could use operator symbols, function names, or even functions themselves. At which point you could get rid of the if/else statements for your math.</p></li>\n<li><p>The global <code>displayNum</code> is never used. In fact, <code>displayNum</code> can be eliminated altogether, as its only purpose is to hold the parsed number. Consider that with the refactoring of <code>operation</code>, you only ever need the value in one place -- and you can convert it right there and avoid having another variable.</p></li>\n<li><p>The display doesn't work quite right when i calculate 125 + 0 or 125 * 0. I get the right result, by happy accident. (An empty string converts to 0.) But the 0 i entered never shows up in the text box.</p></li>\n<li><p>You're repeating yourself by setting the globals at the beginning of the script, and then doing the same thing within <code>clearDisplay</code>. Have an event listener call <code>clearDisplay</code> when the page is ready, and you'll only have one place to change stuff.</p></li>\n<li><p>Stylewise, having the display clear itself the instant you hit an operator button is kinda jarring. Calculators typically don't work that way, and if you're going to make one, you should make it work the way people are used to. Also, the cleared-out box is kinda odd anyway. When you clear, a calculator typically shows '0'.</p></li>\n<li><p>Stylewise, i have a personal hatred of comments that say the obvious. They just add noise.</p></li>\n</ul>\n\n<p>With that stuff fixed:</p>\n\n<pre><code>function clearDisplay() {\n var display = document.getElementById('display');\n display.value = '0';\n storedNum = '0';\n calculationFinished = true;\n operation = operations.none;\n}\n\nfunction clearPreviousResult() {\n var display = document.getElementById('display');\n if (calculationFinished) {\n display.value = '0';\n calculationFinished = false;\n }\n}\n\nfunction numInput(digit) {\n var display = document.getElementById('display');\n clearPreviousResult();\n // Get rid of a 0 if it's the only thing in there.\n // This particular way of doing it lets you enter a 0 and have it show up,\n // as well as leaving a 0 for the decimal point to snuggle up to.\n if (display.value === '0') display.value = '';\n display.value += digit;\n}\n\nfunction insertDecimal() {\n var display = document.getElementById('display');\n clearPreviousResult();\n if (display.value.indexOf('.') === -1) display.value += '.';\n}\n\noperations = {\n // no-op. Takes the right side, and just returns it. Since the right side is the\n // display value, and calculate() sets display.value, this effectively makes\n // calculate() say \"display.value = +display.value\".\n none: function(left, right) { return right; },\n\n // Math ops.\n add: function(left, right) { return left + right; },\n subtract: function(left, right) { return left - right; },\n multiply: function(left, right) { return left * right; }\n};\n\nfunction setOperation(command) {\n var display = document.getElementById('display');\n calculate();\n storedNum = display.value;\n if (operations.hasOwnProperty(command))\n operation = operations[command];\n}\n\nfunction calculate() {\n var display = document.getElementById('display');\n display.value = operation(+storedNum, +display.value);\n calculationFinished = true;\n operation = operations.none;\n}\n\nif ('addEventListener' in window)\n window.addEventListener('load', clearDisplay);\nelse\n window.attachEvent('onload', clearDisplay);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T22:58:33.680", "Id": "7007", "ParentId": "6963", "Score": "4" } }, { "body": "<p>Some extra items that have not been raised and are so important.</p>\n<h3>Declare vars</h3>\n<p>Every variable must have a declaration. If you dont define the variable it is automatically defined and placed in the global scope. This becomes a major source of bugs, headaches, frustration and madness.</p>\n<pre><code>var myVar = 0;\n</code></pre>\n<p>Not</p>\n<pre><code>myVar = 0;\n</code></pre>\n<p>Event if you want it in global scope.</p>\n<h3>Use strict mode</h3>\n<p>All beginners should have as the very first line of any javascript</p>\n<pre><code>&quot;use strict&quot;;\n</code></pre>\n<p>It will prevent you from doing what what I mentioned above.</p>\n<h3>Strict equality and inequality</h3>\n<p>Javascript has two types of equals and not equals. They are <code>==</code> <code>!=</code> and <code>===</code>\n<code>!==</code>. The first two are lazy and will return true if the values are somewhat equal (to hard to explain in a paragraph)</p>\n<p>The latter two <code>===</code> and <code>!==</code> are what you should use always, unless you know why you should use the other. Forget you ever saw ==, and != and never use them again.</p>\n<h3>Blockless blocks.</h3>\n<p>Blocks after statements can be omitted if you have only one line of code to execute.</p>\n<pre><code> if (something) doFoo();\n \n</code></pre>\n<p>As opposed to</p>\n<pre><code> if (something) { \n doFoo();\n }\n // or\n if (something) { doFoo() }\n</code></pre>\n<p>The first without the curlys was introduced some time way back and is the dumbest thing to have ever been allowed in any language. We can not remove it from the languages that allow it, too much source already written.</p>\n<p>But you risk your coding sanity if you feel you do not need { } for single lines. Because if you make a change adding another line and forget the curls, you have a bug that is so hard to find, hours and days will be burnt for no good reason but lazy fingers. Just use the rule, all blocks are delimited with {} even if you don't have to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-19T12:26:40.907", "Id": "176053", "ParentId": "6963", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T13:02:10.903", "Id": "6963", "Score": "5", "Tags": [ "javascript", "html", "calculator" ], "Title": "Simple four-function calculator" }
6963
<p>I'm looking for a review of my current code. It is supposed to capture a paste in the browser window, regardless of the element with focus. This is not the final form as I will be converting it into a jQuery plugin but I'm looking for a review of the logic behind the code.</p> <p>jfiddle: <a href="http://jsfiddle.net/JgU37/44/" rel="nofollow">http://jsfiddle.net/JgU37/44/</a></p> <pre><code>$(document).ready(function() { // Fake paste var doFakePaste = false; $(document).on('keydown', function(e) { $('#status').html('metaKey: ' + e.metaKey + ' ctrlKey: ' + e.ctrlKey + ' which: ' + e.which); // These browser work with the real paste event if ($.client.browser === "Chrome") return; if ($.client.os === "Windows" &amp;&amp; $.client.browser === "Safari") return; // Check for patse keydown event if (!doFakePaste &amp;&amp; ($.client.os === "Mac" &amp;&amp; e.which == 86 &amp;&amp; e.metaKey) || ($.client.os !== "Mac" &amp;&amp; e.which == 86 &amp;&amp; e.ctrlKey)) { doFakePaste = true; // got a paste if (!$("*:focus").is("input") &amp;&amp; !$("*:focus").is("textarea")) { $('#status').html('fake paste'); // Focus the offscreen editable $('#TribblePaste').focus(); // Opera doesn't support onPaste events so we have // to use a timeout to get the paste if ($.client.browser === "Opera") { setTimeout(function() { doFakePaste = false; var html = $('#TribblePaste').html(); var text = $('#TribblePaste').text(); if (text == '') text = $('#TribblePaste').val(); $('#resultA').text('[o] '+html); $('#resultB').text('[o] '+text); $('#TribblePaste').val(''); $('#TribblePaste').text(''); $('#TribblePaste').blur(); }, 1); } } } }).on('paste', function (e) { // Firefox is not supported - they don't // expose the real clipboard if ($.client.browser === 'Firefox') return; $('#status').html('paste event'); // real pasteing var html = ''; var text = ''; if (window.clipboardData) // IE { text = window.clipboardData.getData("Text"); } if (e.clipboardData &amp;&amp; e.clipboardData.getData) // Standard { text = e.clipboardData.getData('text/plain'); text = e.clipboardData.getData('text/html'); } if (e.originalEvent.clipboardData &amp;&amp; e.originalEvent.clipboardData.getData) // jQuery { text = e.originalEvent.clipboardData.getData('text/plain'); html = e.originalEvent.clipboardData.getData('text/html'); } $('#resultA').text(html); $('#resultB').text(text); }); // Setup the offscreen paste capture area $('&lt;div contenteditable id="TribblePaste"&gt;&lt;/div&gt;').css({ 'position': 'absolute', 'top': '-100000px', 'width': '100px', 'height': '100px' }).on('paste', function(e) { setTimeout(function() { doFakePaste = false; var html = $('#TribblePaste').html(); var text = $('#TribblePaste').text(); if (text == '') text = $('#TribblePaste').val(); $('#resultA').text(html); $('#resultB').text(text); $('#TribblePaste').val(''); $('#TribblePaste').text(''); $('#TribblePaste').blur(); }, 1); }).appendTo('body'); $('#data').html('os: ' + $.client.os + ' browser: ' + $.client.browser); }); </code></pre> <p>On a side note, if you try it in a browser thats not listed (in the fiddle), or in one that is listed and get a different result, please post a comment :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T19:48:01.500", "Id": "10881", "Score": "0", "body": "Maybe some words about what the code supposed to do would be useful :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T19:50:37.873", "Id": "10883", "Score": "4", "body": "Pro tip: named functions or objects for code organization. All you have now is a single function that does everything. It's like putting all your code in `main`" } ]
[ { "body": "<p>You need to detect the browser only once, not on each keypress.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T22:37:31.603", "Id": "10889", "Score": "0", "body": "I agree ... its not like it will change between key-presses ... unless something is seriously wrong." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T21:55:23.627", "Id": "6972", "ParentId": "6970", "Score": "3" } }, { "body": "<p>You're overwriting in the paste handlers, you should chain the <code>if</code>s with <code>else</code>s:</p>\n\n<pre><code> // Reverted order to ensure we get the same result as with the previous code version.\n if (e.originalEvent.clipboardData &amp;&amp;\n e.originalEvent.clipboardData.getData) // jQuery\n {\n text = e.originalEvent.clipboardData.getData('text/plain');\n html = e.originalEvent.clipboardData.getData('text/html');\n }\n else if (e.clipboardData &amp;&amp; e.clipboardData.getData) // Standard\n {\n text = e.clipboardData.getData('text/plain');\n text = e.clipboardData.getData('text/html');\n }\n else if (window.clipboardData) // IE\n { \n text = window.clipboardData.getData(\"Text\");\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T11:49:00.067", "Id": "6981", "ParentId": "6970", "Score": "0" } } ]
{ "AcceptedAnswerId": "6972", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T19:33:05.630", "Id": "6970", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "review of work-in-progress javascript - Capture pastes in browser" }
6970
<p>The code below is a good representation of my coding skills. I've been at it for about 6 months. What I am interested in is ways to make the following program faster. I currently have the urlrequests threaded to pull information for 500 stocks, but it is still too slow (around 30 seconds). What python techniques can I use to make this program more efficient?</p> <p>Thanks! </p> <pre><code>from urllib.request import urlopen from csv import reader from threading import Thread class StockQuote(): """gets stock data from Yahoo Finance""" def __init__(self, quote): self.quote = quote def lastPrice(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=l1'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def volume(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=v0'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def yearrange(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=w0'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def PEratio(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=r0'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def bookValue(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=b4'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def EBITDA(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=j4'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def PEGRatio(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=r5'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) def ticker(self): url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f=s0'.format(ticker=self.quote) return bytes.decode((urlopen(url).read().strip())) class StockData(Thread): def __init__(self, stk, fileobj): Thread.__init__(self) self.stk = stk self.fileobj = fileobj def run(self): try: stkObj = StockQuote(self.stk) stkdata= {} stkdata['Ticker'] = stkObj.ticker() stkdata['Price'] = stkObj.lastPrice() stkdata['PE Ratio'] = stkObj.PEratio() stkdata['Volume'] = stkObj.volume() stkdata['Year Range'] = stkObj.yearrange() stkdata['Book Value per Share'] = stkObj.bookValue() stkdata['EBITDA'] = stkObj.EBITDA() stkdata['PEG Ratio'] = stkObj.PEGRatio() except Exception: pass self.fileobj.write(str(stkdata)) def openSP500file(): SP500 = reader(open(r'C:\Users\test\Desktop\SP500.csv', 'r'), delimiter=',') printlist = open(r'C:\Users\test\Desktop\SP500prices.txt', 'w') for x in SP500: indStk = x[0] t1 = StockData(indStk, printlist) t1.start() def main(): openSP500file() if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>It is difficult to make the program faster because time is mostly expended in IO and url connections. It would help for checking changes if you could provide the csv stock files.</p>\n\n<p>On the other hand the code could be greatly simplified. The following code has not been tested (no csv files available) but gives you the idea:</p>\n\n<pre><code>from urllib.request import urlopen\nfrom csv import reader\nfrom threading import Thread\n\n\nclass StockQuote():\n \"\"\"gets stock data from Yahoo Finance\"\"\"\n\n names = dict(lastPrice='l1', volume='v0', yearrange='w0', PEratio='r0',\n bookValue='b4', EBITDA='j4', PEGRatio='r5', ticker='s0')\n\n def __init__(self, quote):\n self.quote = quote\n self.url = 'http://finance.yahoo.com/d/quotes.csv?s={ticker}&amp;f={par}'\n\n def __getattr__(self, name):\n url = self.url.format(ticker=self.quote, par=StockQuote.names[name])\n return bytes.decode((urlopen(url).read().strip()))\n\n\nclass StockData(Thread):\n\n def __init__(self, stk, fileobj):\n Thread.__init__(self)\n self.stk = stk\n self.fileobj = fileobj\n\n def run(self):\n stkdata = {}\n stkObj = StockQuote(self.stk)\n for prprty in StockQuote.names:\n try:\n func = getattr(stkObj, prprty)\n stkdata[prprty] = func()\n except Exception:\n pass\n\n self.fileobj.write(str(stkdata))\n\n\ndef openSP500file():\n SP500 = reader(open(r'C:\\Users\\test\\Desktop\\SP500.csv', 'r'), delimiter=',')\n printlist = open(r'C:\\Users\\test\\Desktop\\SP500prices.txt', 'w')\n for x in SP500:\n indStk = x[0]\n t1 = StockData(indStk, printlist)\n t1.start()\n\n\ndef main():\n openSP500file()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T02:56:42.483", "Id": "10894", "Score": "0", "body": "Thank you very much. I'll have to study up on the getattr and the .names method that you added to the for prprty loop. I haven't seen those before. But this is really helpful and I love how compact you made the code. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T01:34:00.683", "Id": "6976", "ParentId": "6973", "Score": "1" } } ]
{ "AcceptedAnswerId": "6976", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-18T22:14:35.603", "Id": "6973", "Score": "2", "Tags": [ "python", "performance", "multithreading" ], "Title": "threading objects and urlrequests" }
6973
<p>Just wondering if this basic performance test between an untyped array of arrays and a vector (typed array) of arrays in Actionscript 3... is fair and balanced? It's simple, designed to test random access on the collections as well as pushing new items, etc. Here goes:</p> <pre><code>import flash.events.Event; import flash.utils.getTimer; //Performance timer related var startTime:Number; //ms // //Our two container types we're testing IO on var arrayOfArrays:Array = new Array(); var vectorOfArrays:Vector.&lt;Array&gt; = new Vector.&lt;Array&gt;(); // //Used to store a bunch of arrays we're going to use to test var testArrays:Array = new Array(); // var randomIndex:uint = 0; var i:uint = 0; var arr:Array; //Generate a bunch of arrays of mixed typed content for(i = 0; i &lt; 100000; ++i) { generateTestArray(); } /*====================================================================================================== *********************************** Array Tests ********************************************* *=====================================================================================================*/ //Test push on array of arrays trace("Testing Array of Arrays push performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { arrayOfArrays.push(testArrays[i]); } trace("Total time for 100000 push calls on Array of Arrays: " + (getTimer() - startTime)); trace(" "); // //Test random write on array of arrays trace("Testing Array of Arrays random assignment performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { randomIndex = Math.round(Math.random() * 99999) as uint; arrayOfArrays[randomIndex] = testArrays[randomIndex]; } trace("Total time for 100000 random assignment calls on Array of Arrays: " + (getTimer() - startTime)); trace(" "); // //Test sequential read on array of arrays trace("Testing Array of Arrays sequential read performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { arr = arrayOfArrays[i]; } trace("Total time for 100000 sequential read calls on Array of Arrays: " + (getTimer() - startTime)); trace(" "); // //Test random read on array of arrays trace("Testing Array of Arrays sequential read performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { randomIndex = Math.round(Math.random() * 99999) as uint; arr = arrayOfArrays[randomIndex]; } trace("Total time for 100000 random read calls on Array of Arrays: " + (getTimer() - startTime)); trace(" "); // /*====================================================================================================*/ /*====================================================================================================== *********************************** Vector Tests ********************************************* *=====================================================================================================*/ //Test push on vector of arrays trace("Testing Vector of Arrays push performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { vectorOfArrays.push(testArrays[i]); } trace("Total time for 100000 push calls on Vector of Arrays: " + (getTimer() - startTime)); trace(" "); // //Test random write on vector of arrays trace("Testing Vector of Arrays random assignment performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { randomIndex = Math.round(Math.random() * 99999) as uint; vectorOfArrays[randomIndex] = testArrays[randomIndex]; } trace("Total time for 100000 random assignment calls on Vector of Arrays: " + (getTimer() - startTime)); trace(" "); // //Test sequential read on vector of arrays trace("Testing Vector of Arrays sequential read performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { arr = vectorOfArrays[i]; } trace("Total time for 100000 sequential read calls on Vector of Arrays: " + (getTimer() - startTime)); trace(" "); // //Test random read on vector of arrays trace("Testing Vector of Arrays sequential read performance:"); startTime = getTimer(); for(i = 0; i &lt; 100000; ++i) { randomIndex = Math.round(Math.random() * 99999) as uint; arr = vectorOfArrays[randomIndex]; } trace("Total time for 100000 random read calls on Vector of Arrays: " + (getTimer() - startTime)); trace(" "); // /*====================================================================================================*/ function generateTestArray():void { var newArray:Array = new Array(); var totalItems:uint = Math.round(Math.random() * 50 + 1); var i:uint = 0; var dice:uint = 0; for(i; i &lt; totalItems; ++i) { dice = Math.round(Math.random() * 5); switch(dice) { case 0: newArray.push(new int(Math.random())); break; case 1: newArray.push(new String(Math.random())); break; case 2: newArray.push(new Array()); break; case 3: newArray.push(new MovieClip()); break; case 4: newArray.push(new Date()); break; case 5: newArray.push(new Event(Event.COMPLETE, false, false)); break; } } testArrays.push(newArray); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T00:23:29.537", "Id": "10890", "Score": "0", "body": "Note that I tagged as javascript because the two languages are nearly identical anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T00:33:41.747", "Id": "10891", "Score": "2", "body": "But it has nothing to do with javascript. Because your testing the performance difference between two features not implemented in javascript" } ]
[ { "body": "<p><strong>Some thoughts</strong></p>\n\n<p>You don't need to use <code>new int</code> (it's very uncommon in actionscript), just cast it to that:</p>\n\n<pre><code>newArray.push(int(Math.random()));\n</code></pre>\n\n<p>You don't need to use <code>new String</code> (it's very uncommon in actionscript), just use the toString() function</p>\n\n<pre><code> newArray.push(Math.random().toString());\n</code></pre>\n\n<p>You could also directly cast to uint, to have it rounded.</p>\n\n<pre><code> randomIndex = uint(Math.random() * 99999);\n</code></pre>\n\n<p>You <em>could</em> also benchmark fixed length array/vectors.</p>\n\n<p>In the end results of the benchmark you should add a note that creating/assigning the random value takes some time too. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-14T15:13:37.357", "Id": "12580", "ParentId": "6975", "Score": "1" } }, { "body": "<pre><code>Math.random()\n</code></pre>\n\n<p>is a quite slow operator compared to Array access. In this case: </p>\n\n<pre><code>for(i = 0; i &lt; 100000; ++i) {\n randomIndex = Math.round(Math.random() * 99999) as uint;\n arrayOfArrays[randomIndex] = testArrays[randomIndex];\n}\n</code></pre>\n\n<p>i think you'll measure the speed to the Math class, not array assignment speed. (same holds for other examples, where you use do lots of Math calls.) To test random assignment speed, i'd first populate an array with random elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-23T18:08:19.720", "Id": "18945", "ParentId": "6975", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T00:20:29.370", "Id": "6975", "Score": "2", "Tags": [ "performance", "actionscript-3" ], "Title": "Is there anything biased in this performance test?" }
6975
<p>I'm coding a small web app with no real functionality. It's like a pilot program for something bigger. What I want is construct a program that works as a clock on/off for a restaurant. Actually I'm just trying to simulate one. What I'v done is working but I would like to know whether there is any java class that I can use in a session to calculate the difference between the clock on and off.</p> <p>Index.jsp</p> <pre><code>&lt;%@page import="javax.media.jai.operator.EncodeDescriptor"%&gt; &lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Project&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Employees&lt;/h1&gt; &lt;form action=&lt;%= response.encodeURL("CheckUser") %&gt; method="get"&gt; &lt;input type="hidden" name="userId" value="1"&gt; &lt;input type="submit" value="Diogo"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CheckUser</p> <pre><code>public class CheckUser extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId = request.getParameter("userId"); User user1 = new User(); user1.setUserId(userId); HttpSession session = request.getSession(); session.setAttribute("userId", userId); Hours h1 = (Hours) session.getAttribute("hours"); if (h1 == null){ h1 = new Hours(user1); } Calendar cal = new GregorianCalendar(); h1.setMinutes(cal.get(Calendar.MINUTE)); request.setAttribute("hours", h1); String url = "/show.jsp"; session.setAttribute("hours", h1); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); } </code></pre> <p>show.jsp</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;JSP Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;%@ page import="Business.*, process.*" %&gt; &lt;% String userId = (String) session.getAttribute("userId"); Hours h = (Hours) session.getAttribute("hours"); String actualMinute = h.getMinutes(); String calcMinute = h.getCalMinutes(); %&gt; &lt;h1&gt;&lt;%= userId %&gt;&lt;/h1&gt; &lt;h1&gt;&lt;%= h.getMinutes() %&gt; minuto atual&lt;/h1&gt; &lt;% if(!actualMinute.equalsIgnoreCase(calcMinute) || calcMinute == "0") { %&gt; &lt;h1&gt;&lt;%= h.getCalMinutes() %&gt; minutes&lt;/h1&gt; &lt;% }else { %&gt; &lt;h1&gt;It is working&lt;/h1&gt; &lt;h1&gt;&lt;%= h.getCalMinutes() %&gt;&lt;/h1&gt; &lt;% } %&gt; &lt;form action="&lt;%= response.encodeURL("index.jsp") %&gt;" method="get"&gt; &lt;input type="submit" value="return"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I assume that <code>Hours</code> is a custom class of yours. </p>\n\n<ul>\n<li><p>If you are asking if there is an existing Java class that will automagically calculate the \"difference\" between two instances of your custom class, the the answer is \"No\".</p></li>\n<li><p>If you are asking (more generally) what is the best class for handling temporal quantities so that you can compare them, calculate differences and so on, then the answer is to look at the JodaTime libraries.</p></li>\n</ul>\n\n<hr>\n\n<p>I also note that you are STILL using \"Business\" as a package name. You should stop it before The Protectors of Java Purity find a way to hack your PC and fill the disc drive with zeros!!!</p>\n\n<p>Seriously, it is <strong>bad practice</strong>. Don't do it. Follow the standard Java naming conventions, like professional developers do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T04:31:27.230", "Id": "10943", "Score": "0", "body": "Hi,thanks for the advise. I'm gonna use the Joda library. I can grab the minutes of a day and then do the math. Relating to the name convention, I was following a book. So, should I name packages? Cheers" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T03:19:32.533", "Id": "6978", "ParentId": "6977", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T02:45:52.230", "Id": "6977", "Score": "2", "Tags": [ "java" ], "Title": "Improvement of this method" }
6977
<p>I use this piece of code to compute a short-time Fourier transform:</p> <pre><code>// Output pre-allocation std::vector&lt;std::vector&lt;std::complex&lt;T&gt; &gt; &gt; y(nFft, std::vector&lt;std::complex&lt;T&gt; &gt;(nFrames, 0.0)); std::vector&lt;T&gt; xt; std::vector&lt;std::complex&lt;T&gt; &gt; yt; xt.reserve(nFft); yt.reserve(nFft); #pragma omp parallel for private(xt,yt) for (unsigned int t = 0; t &lt; nFrames; ++t) { const int offset = -((int) wSize/2) + t*nHop; // Extract frame of input data if (offset &lt; 0) { xt.assign(x.begin(), x.begin() + offset + wSize); xt.resize(wSize, 0.0); } else if (offset + wSize &gt; n) { xt.assign(x.begin() + offset, x.end()); xt.resize(wSize, 0.0); } else xt.assign(x.begin() + offset, x.begin() + offset + wSize); // Apply window to current frame std::transform(xt.begin(), xt.end(), w.begin(), xt.begin(), std::multiplies&lt;T&gt;()); // Zero padding std::rotate(xt.begin(), xt.begin() + wSize/2, xt.end()); xt.insert(xt.begin() + wSize/2, nFft - wSize, 0.0); yt = fft(xt); // Perform the FFT! #pragma omp critical { for (unsigned int f = 0; f &lt; nFft; ++f) y[f][t] = yt[f]; } } </code></pre> <p>Is there something that I can improve, either in design style or performances, without sacrificing readability? Of course the point is to improve my coding skills without using any external library! </p> <p>Regarding the xt and yt vectors, I put them outside the loop to improve the performances in mono-threaded (when OpenMP is disabled). In multi-threaded, there are copied for each thread anyway (hence the use of the private close).</p>
[]
[ { "body": "<p>The only thing worth commenting on is the identifier names could be more meaningful.</p>\n\n<ul>\n<li>Short identifiers are harder to find when maintaining the code (more false positives).</li>\n<li>Short identifiers make it hard to put meaning to the identifier.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:34:43.490", "Id": "6996", "ParentId": "6980", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T10:54:41.853", "Id": "6980", "Score": "4", "Tags": [ "c++", "vectors", "openmp" ], "Title": "Vectors assignations and operations in a loop and parallelization with OpenMP" }
6980
<pre><code> private static void OnSundayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e) { BinaryDataGrid c = sender as BinaryDataGrid; if (c != null) { if (_shouldCallBack) { if (c.Sunday.Length == 4) return; Days day = (Days)c.dataGrid.Items[0]; byte[] newArray = new byte[c.Sunday.Length + 1]; newArray[0] = Convert.ToByte(0); c.Sunday.CopyTo(newArray, 1); day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0); _sun = day.Value; } else { _shouldCallBack = true; c.Sunday = BitConverter.GetBytes(_sun).Reverse().ToArray().Skip(1).ToArray(); } } } private static void OnMondayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e) { BinaryDataGrid c = sender as BinaryDataGrid; if (c != null) { if (_shouldCallBack) { if (c.Monday.Length == 4) return; Days day = (Days)c.dataGrid.Items[1]; byte[] newArray = new byte[c.Monday.Length + 1]; newArray[0] = Convert.ToByte(0); c.Monday.CopyTo(newArray, 1); day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0); _mon = day.Value; } else { _shouldCallBack = true; c.Monday = BitConverter.GetBytes(_mon).Reverse().ToArray().Skip(1).ToArray(); } } } </code></pre> <p>I've got the same code for every week day, how can I generalize this so I don't have 6 duplicates of the code above?</p>
[]
[ { "body": "<p>What you need to do is:</p>\n\n<ol>\n<li><p>Add a parameter of type <code>System.DayOfWeek</code> called, say, <code>day_of_week</code>.</p></li>\n<li><p>Replace the fields <code>BinaryDataGrid.Sunday</code>, <code>.Monday</code>, etc. with a <code>Dictionary&lt;K,V&gt;</code> that has a key of type <code>System.DayOfWeek</code> and use <code>day_of_week</code> to access values within that dictionary.</p></li>\n<li><p>Do the same for your <code>_sun</code>, <code>_mon</code> etc. global variables. (For which you will burn in hell, incidentally.)</p></li>\n</ol>\n\n<p>If you cannot modify <code>BinaryDataGrid</code>, then write two helper methods, one for getting and one for setting the value of the day member of <code>BinaryDataGrid</code>: Each method has a <code>switch( day_of_week )</code> and modifies the appropriate member of <code>BinaryDataGrid</code>.</p>\n\n<p>Good luck and have fun.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:43:20.863", "Id": "10907", "Score": "0", "body": "Hi thanks for your suggestion, i'll definately improve that, but kindly enlighten me on 3rd point, (For which you will burn in hell, incidentally.) If this is that bad, guide me towards something that will help me fix that and also why this is so bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:56:20.183", "Id": "10909", "Score": "0", "body": "From wikipedia (http://en.wikipedia.org/wiki/Global_variable): \"They are usually considered bad practice precisely because of their non-locality: a global variable can potentially be modified from anywhere (unless they reside in protected memory or are otherwise rendered read-only), and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity.\"\n\nIf you want to read more, here: \"Global Variables are Bad\" http://c2.com/cgi/wiki?GlobalVariablesAreBad" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:57:02.207", "Id": "10910", "Score": "0", "body": "I do not know why you had to use them, and what you are trying to achieve with them, so I cannot help you get rid of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:10:48.857", "Id": "10912", "Score": "0", "body": "Actually i believe i could replace them with private properties, Thanks anyways" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:27:07.023", "Id": "10916", "Score": "0", "body": "Thanks for the accept. In order to replace them with private properties you will first need to make your methods non-static, instead of static which they are now. And that will probably open up another can of worms. So if you can just get away by leaving them as they are, just swipe them under the carpet and move on." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:11:42.633", "Id": "6990", "ParentId": "6982", "Score": "2" } }, { "body": "<p>Mike Nakis has covered most of the design issues, so I'm going to cover some of the smaller points.</p>\n\n<p><strong>Var</strong></p>\n\n<p>Use the <code>var</code> keyword when defining method-scope variables for which the right hand side of the definition makes the type obvious. This saves you time when you come to refactor, and is neater.</p>\n\n<p>e.g.</p>\n\n<pre><code>BinaryDataGrid c = sender as BinaryDataGrid;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>var c = sender as BinaryDataGrid;\n</code></pre>\n\n<p><strong>Naming</strong></p>\n\n<p>Don't use single-character variable names. These do nothing but make the code more difficult to comprehend. Extra characters are free, so be descriptive.</p>\n\n<pre><code>var dateGrid = sender as BinaryDataGrid;\n</code></pre>\n\n<p><strong>Braces</strong></p>\n\n<p>Always prefer to use braces for your if statements, it's cleaner, spaces things out better, and it's a StyleCop violation not to. Additionally, prefer to surround any statement involving braces with empty lines, this improves readability. Additionally, try to give your statements some space. Group together related statements, but leave a gap between unrelated ones.</p>\n\n<p>So</p>\n\n<pre><code>if (_shouldCallBack)\n{\n if (c.Sunday.Length == 4)\n return;\n Days day = (Days)c.dataGrid.Items[0];\n byte[] newArray = new byte[c.Sunday.Length + 1];\n newArray[0] = Convert.ToByte(0);\n c.Sunday.CopyTo(newArray, 1);\n day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0);\n _sun = day.Value;\n}\nelse\n{\n _shouldCallBack = true;\n c.Sunday = BitConverter.GetBytes(_sun).Reverse().ToArray().Skip(1).ToArray();\n}\n</code></pre>\n\n<p>Looks better as</p>\n\n<pre><code>if (_shouldCallBack)\n{\n if (c.Sunday.Length == 4)\n {\n return;\n }\n\n Days day = (Days)c.dataGrid.Items[0];\n\n byte[] newArray = new byte[c.Sunday.Length + 1];\n newArray[0] = Convert.ToByte(0);\n\n c.Sunday.CopyTo(newArray, 1);\n\n day.Value = BitConverter.ToInt32(newArray.Reverse().ToArray(), 0);\n\n _sun = day.Value;\n}\nelse\n{\n _shouldCallBack = true;\n\n c.Sunday = BitConverter.GetBytes(_sun).Reverse().ToArray().Skip(1).ToArray();\n}\n</code></pre>\n\n<p><strong>ToArray</strong></p>\n\n<p>You have a duplicate call to ToArray that is wasted execution time here:</p>\n\n<pre><code>c.Sunday = BitConverter.GetBytes(_sun).Reverse().ToArray().Skip(1).ToArray();\n</code></pre>\n\n<p>Instead simply call:</p>\n\n<pre><code>c.Sunday = BitConverter.GetBytes(_sun).Reverse().Skip(1).ToArray();\n</code></pre>\n\n<p><strong>Design</strong></p>\n\n<p>This is quite a lot of logic for what looks to be code-behind. I would recommend looking into some more well-structured patterns such as MVVM to keep your code separate from your view.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-18T10:37:27.950", "Id": "74038", "ParentId": "6982", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T12:49:36.190", "Id": "6982", "Score": "2", "Tags": [ "c#" ], "Title": "Duplicate code in day of the week event handlers" }
6982
<p>I have two very similar functions that exist mainly for syntactic sugar.</p> <pre><code>deactivate = (el, seek) -&gt; el.find(seek).removeClass("active") activate = (el, seek) -&gt; el.find(seek).addClass("active") </code></pre> <p>This allows me to write, for example:</p> <pre><code>activate $("#something"), ".child" </code></pre> <p>Using the above purely as an example, ignoring any logical errors with the JavaScript itself… how could this be refactored to be more dry?</p>
[]
[ { "body": "<p>You can use js' bracket notation for this task</p>\n\n<pre><code>alter = (el, seek, method) -&gt; el.find(seek)[method + \"Class\"](\"active\")\n#use like this:\nalter $(\"#something\"), \".child\", \"add\"\n</code></pre>\n\n<p>However, your situation doesn't really call for DRYness. Your method names make more sense than <code>alter</code>, or whichever name you may choose.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T13:56:52.597", "Id": "10902", "Score": "0", "body": "You could just use your `alter` function as a stepping stone for the definitions of `activate`/`deactivate` become more DRY: `deactivate = (el, seek) -> alter el, seek, \"remove\"` `activate = (el, seek) -> alter el, seek, \"add\"` (Disclamer: I don't use CoffeScript)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T14:05:17.383", "Id": "10903", "Score": "0", "body": "@RoToRa Correct, and you can also do it the other way around: Store `activate` and `deactivate` on an object, and pass which one you want as an argument to `alter`: `containingObject[method](\"active\")`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T20:43:29.367", "Id": "10931", "Score": "0", "body": "Thank you. I think the syntactic benefit of my initial functions outweigh the benefit of making the code more DRY. I was just wondering if there was something I was missing here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T13:40:15.143", "Id": "6984", "ParentId": "6983", "Score": "2" } }, { "body": "<p>I think your code is fine. I would only suggest a more complex solution only if this pattern happens more often.</p>\n\n<p>For example, if you want to refactor to allow for other class names you can do something like this:</p>\n\n<pre><code>adder = clsName -&gt; (el, seek) -&gt; el.find(seek).removeClass(clsName)\nremover = clsName -&gt; (el, seek) -&gt; el.find(seek).addClass(clsName)\n\nactivate = adder 'active'\ndeactivate = remover 'active'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:10:24.987", "Id": "6989", "ParentId": "6983", "Score": "0" } } ]
{ "AcceptedAnswerId": "6984", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T13:27:43.063", "Id": "6983", "Score": "1", "Tags": [ "javascript", "jquery", "coffeescript" ], "Title": "Similar but slightly different JavaScript functions" }
6983
<p>I am an eighth grader with a school project of creating and application in Java that returns the total permutations of two given numbers. It needs to be light and efficient, for later deployment on a website. I was wondering if there was any way I could improve the code so it would be more efficient.</p> <pre><code>class Factorials { public static void main(String[] args){ int n = 8; long factorialN = n; for (int ForN = n; ForN &lt;= n &amp;&amp; ForN &gt; 1; ForN--) { factorialN = factorialN * ForN; } factorialN = factorialN / n; System.out.println(factorialN); int r = 6; int rMinus1 = r - 1; long factorialR = rMinus1; for (int ForR = rMinus1; ForR &lt;= rMinus1 &amp;&amp; ForR &gt; 1; ForR--) { factorialR = factorialR * ForR; } factorialR = factorialR / rMinus1; System.out.println(factorialR); int nMr = n - r; System.out.println(nMr); long factorialNmR = nMr; if (nMr == 2) { factorialNmR = 2; } else if (nMr &lt;= 1){ factorialNmR = 1; } else if (nMr &gt; 2) { for (int FornMr = nMr; FornMr &lt;= nMr &amp;&amp; FornMr &gt; 1; FornMr--) { factorialNmR = factorialNmR * FornMr; } factorialNmR = factorialNmR / nMr; System.out.println(factorialNmR); } long permutations = factorialN; System.out.println(permutations); permutations = permutations / factorialNmR; System.out.println(permutations); } } </code></pre>
[]
[ { "body": "<p>First of all, please write a single function instead of expanding what is essentially the same code three times!</p>\n\n<pre><code>long factorialN = n;\nfor (int ForN = n; ForN &lt;= n &amp;&amp; ForN &gt; 1; ForN--) {\n factorialN = factorialN * ForN;\n}\nfactorialN = factorialN / n;\n</code></pre>\n\n<p>Also, if your <code>for</code>-loop counter will start at <code>N</code> and only decrement, you do not need to check in every iteration whether it is less than or equal to N; it is guaranteed to be. You only need to check if it is greater than 1. But that incurs no performance penalty, since the Java compiler is clever enough to disregard your superfluous check.</p>\n\n<p>Now, if you want a faster factorial implementation, you can use a recursive one, like the one described in <a href=\"http://www.luschny.de/math/factorial/csharp/FactorialSplit.cs.html\" rel=\"nofollow\">this page</a>. It is in C#, but you should have no problem converting it to Java. The only thing is, you need to gain knowledge of what recursion really is before trying to pass this as a piece of code you understand.</p>\n\n<p>Or, you could use something far more advanced, like the asymptotic prime factorization algorithm described on <a href=\"http://www.luschny.de/math/factorial/csharp/FactorialPrimeSwing.cs.html\" rel=\"nofollow\">this page</a>, though you will have a very hard time convincing your teacher that you, an 8th grader, have the slightest clue as to how this algorithm works, and why, so better stay away from it!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:49:42.193", "Id": "10908", "Score": "0", "body": "My only question is, how would I create only one function? And also, my school requires that for each project, I need a live resource. Basically, I need someone to help me that isn't a website. Could I consider you my live resource for this project?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:24:48.143", "Id": "10915", "Score": "0", "body": "Possibly, (if it does not involve anything more than communicating via email,) but first I want to know if you are any good. Because it is one thing to help someone do their work and another to do their work for them. So, I edited my answer to show you the piece of code which is triplicate. Can you not extract that code into a separate function and call that function three times from within your main function? I mean, if not, then you need to learn the very basics of programming, instead of worrying about factorials, let alone of efficient means of computing factorials." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T17:30:12.997", "Id": "10921", "Score": "0", "body": "Communicating via email is fine, and for the programming sufficiency, I believe I could probably do it, but I would need some help, not a lot, but some nonetheless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T19:38:31.353", "Id": "10923", "Score": "1", "body": "The first part of my email address is 'michael'. The last part (the part after the 'at' sign) is listed in my profile as my website. I will need you to do what I asked in my previous comment before I become your live resource. It has nothing to do with efficiency, so it is not answering your question. It just tells me that you know a bit of what you are doing so you are not just trying to find someone to do your homework for you. Also I would like you to send me whatever information you can explaining to me what your school considers a live resource." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T01:02:57.797", "Id": "10938", "Score": "3", "body": "don't forget, stackexchange has a chatroom too for another medium of communication." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:34:06.350", "Id": "6991", "ParentId": "6988", "Score": "6" } } ]
{ "AcceptedAnswerId": "6991", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:10:19.107", "Id": "6988", "Score": "8", "Tags": [ "java", "performance", "homework", "combinatorics" ], "Title": "Java application for finding permutations efficiently" }
6988
<p>I'm <em>trying</em> to learn Haskell and the mindset of programming functionally. I have started off by trying to understand the basics by writing code without any <code>Monads</code> in it. </p> <p>So far, I think I'm getting used to the type system and how the basics works. </p> <p>I thought to myself, why not try to get some feedback on what I have written to learn even more. So hopefully I will get some valuable information! </p> <p>I have written a function which iterates a <code>String</code> and splits it into <code>[String]</code> by using given <code>Char</code> as a delimiter. Similar to what PHP's <code>explode</code> and Python's <code>split</code> does. </p> <p>Here's what I have got so far: </p> <pre><code>main :: IO() main = do print $ groupBy "/hejsan/asdas" '/' [] print $ groupBy "/hejsan/asdas/hoho" '/' [] print $ groupBy "/hejsan/asdas/hahsdhashdas" '/' [] print $ groupBy "/hejsan/99/hahsdhashdas" '/' [] print $ groupBy "/123/asdas/hahsdhashdas///" '/' [] print $ groupBy "/123/asdas/hahsdhashdas//20////hej" '/' [] groupBy :: String -&gt; Char -&gt; [String] -&gt; [String] groupBy "" _ [] = [] groupBy (x:xs) c [] | x == c = groupBy xs c [] | otherwise = groupBy xs c [[x]] groupBy "" _ (r:rs) = reverse result where result = if r == "" then rs else [r] ++ rs groupBy (x:xs) c (r:rs) | x == c = groupBy xs c $ nextGroup ++ rs | otherwise = groupBy xs c $ [r ++ [x]] ++ rs where nextGroup = if r == "" then [r] else [""] ++ [r] </code></pre> <p>With output: </p> <pre><code>["hejsan","asdas"] ["hejsan","asdas","hoho"] ["hejsan","asdas","hahsdhashdas"] ["hejsan","99","hahsdhashdas"] ["123","asdas","hahsdhashdas"] ["123","asdas","hahsdhashdas","20","hej"] </code></pre> <p>So the main idea is to only show groups which have values in them. I bet there is:</p> <ul> <li>Some library function which can simplify the functions internals</li> <li>Some way to eliminate the 3rd argument so that it will be transparent to the user (Currying?) </li> </ul> <p><strong>I welcome all types of feedback except for feedback like "there is a library function which does all that for you". I'd like feedback on the internals and this particular problem is just an example</strong> </p>
[]
[ { "body": "<p>Well, sorry, but it is <strong>really</strong> tempting to note that there is in fact a library routine that can do that, and it is even called the same as your function:</p>\n\n<pre><code>groupBy (\\a b -&gt; b /= '/') \"/hejsan/asdas\"\n</code></pre>\n\n<p>This code with <code>groupBy</code> from <code>Data.List</code> will give you <code>[\"/hejsan\",\"/asdas\"]</code>. Even though it should probably be noted that this is taking advantage of how <code>groupBy</code> is implemented internally, which might not be the best idea.</p>\n\n<p>But let's look at your implementation - two things jump out:</p>\n\n<ul>\n<li><p>You are clearly using the first element in the <code>rs</code> list differently from the rest. Why not make it an additional parameter so you can skip de- and recomposing the list all the time? </p></li>\n<li><p>Why do you even need an accumulation parameter for your groups? Once you append something to <code>rs</code>, you already know that it will be reversed in the end and end up at the start of the return value. So you can simply prepend the group to the result of the recursive function call.</p></li>\n</ul>\n\n<p>With the two changes and a bit of refactoring (replacing your <code>if</code> by pattern matches), we get the following version:</p>\n\n<pre><code>groupBy :: String -&gt; Char -&gt; String -&gt; [String]\ngroupBy \"\" _ \"\" = []\ngroupBy \"\" _ r = [r]\ngroupBy (x:xs) c \"\"\n | x == c = groupBy xs c \"\"\n | otherwise = groupBy xs c [x]\ngroupBy (x:xs) c r\n | x == c = r : groupBy xs c \"\"\n | otherwise = groupBy xs c (r ++ [x])\n</code></pre>\n\n<p>This can be improved further:</p>\n\n<ul>\n<li><p>This has clearly two modes of operation depending on <code>r == \"\"</code>. When calling you always know whether that is the case, so you could easily split it into two functions. One of them can get rid of the <code>r</code> parameter completely, so you end up with a nice function to call from outside.</p></li>\n<li><p>Building a list using <code>++</code> is inefficient, as it creates a copy of the list each time you append an element, leading O(n²) complexity. It's better to use <code>x:r</code> and then <code>reverse</code> once in the end, which is a more efficient O(n). A bit more involved refactoring enables you to construct the string in the right form right away (see <code>span</code>).</p></li>\n</ul>\n\n<p>That's really all the difference to the \"perfect\" library-level implementation (see <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/Data-List.html#groupBy\">the library code</a>). Note that generally, initialization of accumulation parameters is simply done by defining a wrapper function, even though we can easily put this function without even needing it.</p>\n\n<p>Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T12:01:16.023", "Id": "10946", "Score": "0", "body": "Great, this was exactly what I was looking for! Getting feedback on the actual algorithm and not just that I can do it with the library function. You have given me a lot to think about and analyze! Thank you for a really good answer! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T07:11:42.657", "Id": "11680", "Score": "2", "body": "@Wortmann: from Data.List \"The group function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument.\" This is actually a very useful property that I take advantage of from time to time, and I don't believe it's in any danger of making code non-portable. If you would like to group non-contiguous elements, simply compose with sortBy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T00:33:27.423", "Id": "7009", "ParentId": "6992", "Score": "9" } }, { "body": "<p>Another version, using the Prelude function <code>break</code>.</p>\n\n<pre><code>groupBy :: String -&gt; Char -&gt; [String]\ngroupBy str delim = let (start, end) = break (== delim) str\n in start : if null end then [] else groupBy (tail end) delim \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T22:38:22.240", "Id": "11149", "Score": "0", "body": "Interesting! Thanks for submitting :) I haven't even seen `let` been used with the `in` keyword before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T22:43:59.360", "Id": "11150", "Score": "0", "body": "Btw, any idea how this measures up performance wise? Spontaneously I believe this would be slower since it has to iterate the remaining list each time it divides it with break, or am I wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T23:16:11.110", "Id": "11190", "Score": "0", "body": "I don't think so: Why should `break` evaluate the second list to the end? Once the split point is found, it has everything it needs." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T13:18:01.223", "Id": "7153", "ParentId": "6992", "Score": "6" } }, { "body": "<p>OP asked specifically about eliminating the third argument \nso that it will be transparent to the user.\nIn general, the easy way to do this is to have one\nfunction that fronts for another. There is no rule that says that\nthe starting call of a recursive function has to have all the options\nthat the nested calls have. Similarly, there's no rule that says that\nthe recursion has to produce the result in its final form. So, a shell\nfunction to do pre- and post- processing around a recursion seems reasonable.</p>\n\n<p>So even the original function implementation could be hidden inside\na simple wrapper:</p>\n\n<pre><code>simpleGroupBy :: String -&gt; Char -&gt; [String]\nsimpleGroupBy s c = groupBy s c []\n</code></pre>\n\n<p>For cleanliness, you could probably rename simpleGroupBy to groupBy,\nrename groupBy to groupBy' and hide this groupBy' in a where clause\nunder the new groupBy. This nesting allows the constant c to be \npulled out of the recursive argument list, to be referenced in \nplace at the outer function's scope.</p>\n\n<p>Here's an alternative implementation that does all that\nand also uses foldr to shift the focus from the recursion to\nwhat happens at each step of the recursion.\nThe implementation borrows from the cleanup suggested by @Peter</p>\n\n<pre><code>groupBy :: String -&gt; Char -&gt; [String]\n-- Work backards through the string, starting with an empty result list \n-- and no pending element.\ngroupBy s c = let (res,elem) = foldr step ([],[]) s\n -- The final result should include the leading chars, \n -- if any.\n in if elem == [] \n then res\n else elem:res\n where \n step x accum@(result,[]) - No element is in progress.\n -- With no element in progress, x is the end of a new\n -- one, or ignored if it's c.\n | x == c = accum -- final or repeated c has no effect\n | otherwise = (result,[x]) -- x ends the element\n step x (result,element) -- An element is in progress.\n -- x is the head (so far) of an element in progress,\n -- except if c, in which case the element is the head\n -- (so far) of the result list and the element is \n -- considered empty.\n | x == c = (element:result,[]) -- include the element in the result\n | otherwise = ( result,x:element) -- include x in the element\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T09:01:51.187", "Id": "11683", "Score": "0", "body": "Thank you, Paul! I have always done the hiding this way, so it feels good to know that it was a good way to do this. I also appreciate you showing me another way to do this. I have a lot to think about and research! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T03:49:37.093", "Id": "7436", "ParentId": "6992", "Score": "3" } }, { "body": "<p>If someone tells you not to write such a function because it already exists, then you should ignore it and go ahead and write it. It's a great exercise.</p>\n\n<p>That said, after you've written your version, it's a good idea to look up the libraries and see its source code for comparison. You'll probably find very good code there, since it has been reviewed and tested by many people. </p>\n\n<p>In fact you can learn stuff from the documentation alone. For instance, you mention Python's split. I don't know Python well, but I checked its documentation and it defines the function in a different way. Splitting \"/abc/def//g\" with '/' would give <em>[\"\", \"abc\", \"def\", \"\", g]</em>. That's different from your examples, but it makes more sense for CSV files, for instance, where 2 consecutive delimiters indicate an empty field. Maybe you want Python's split's definition, or maybe you really want a function that produces your examples, but in this case you'd need a more precise specification. </p>\n\n<p>Another example: in Haskell, you'll see that a function like yours would likely have the arguments reversed:</p>\n\n<pre><code>groupBy' delim str = foo\n</code></pre>\n\n<p>because this allows you to easily write (groupBy' '/'), which is often more useful than (groupBy' \"my string\").</p>\n\n<p>I don't know of any function in the standard libraries that does exactly what you want. In your specification, Data.List.groupBy doesn't work. But even if you don't mind not discarding the delimiters, using groupBy for that is just wrong (groupBy expects a function that's like equality: transitive and reflexive).</p>\n\n<p>However, your function looks very similar to <em>words</em> from the Prelude. So you could write a <em>wordsBy</em> function that is like <em>words</em> that, instead of using spaces as delimiters, takes a function argument that determines the delimiters.</p>\n\n<p>I got this by modifying the library code:</p>\n\n<pre><code>wordsBy :: (Char -&gt; Bool) -&gt; String -&gt; [String]\nwordsBy isDelim xs = \n case dropWhile isDelim xs of\n \"\" -&gt; []\n xs' -&gt; w : wordsBy isDelim rest\n where (w, rest) = break isDelim xs'\n-- note that xs' starts with a non-delimiter, and w is completely\n-- non-delimiters.\n\nyourGroupBy c = wordsByDelim (== c)\n</code></pre>\n\n<p>It's similar to Landei's version. I believe Landei's version is like Python's split. This one is a bit longer but gives the results you want.</p>\n\n<p>So, maybe not what you expected, but I hope it helps. ;-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T18:39:51.047", "Id": "21401", "Score": "0", "body": "Thanks for the input! It's been a while since I checked new answers here on `codereview`. So it was a nice surprise to have gotten even more input :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-12T17:32:32.840", "Id": "7720", "ParentId": "6992", "Score": "3" } } ]
{ "AcceptedAnswerId": "7009", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:46:34.457", "Id": "6992", "Score": "11", "Tags": [ "strings", "haskell" ], "Title": "Approach to string split by character in Haskell" }
6992
<p>The following code is very slow. I was wondering if you can help me speed it up.</p> <pre><code>private void filter(List&lt;CheckBox&gt; boxList) { // refLanguageTabs is a TabControl the Tabcount is 9 for (int i = 0; i &lt; refLanguageTabs.TabCount; i++) { Control[] ctrls = refLanguageTabs.TabPages[i].Controls.Find(refLanguageTabs.TabPages[i].Name + "Grid", true); DataGridView dgv = ctrls[0] as DataGridView; // average row count is 3000 for (int j = 0; j &lt; dgv.RowCount; j++) { for (int k = 0; k &lt; boxList.Count; k++) { if (dgv.Rows[j].Cells[1].Value.ToString() != boxList[k].Name.ToString()) { dgv.Rows[j].Visible = false; } } } dgv.Refresh(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-04T19:01:20.557", "Id": "161811", "Score": "0", "body": "Only state the code purpose in the title, what does it do specifically?" } ]
[ { "body": "<p>Some few thoughts without testing or anything else:</p>\n\n<ul>\n<li>Cache the value of the cell in a local variable.</li>\n<li><a href=\"https://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c-sharp\">Replace for-loops if possible with foreach-loops</a>.</li>\n<li>The call of <code>boxList[x].Name.ToString()</code> is unnecessary, it is already a String.</li>\n<li><code>break</code> after setting the visibility to avoid unnecessary checks.</li>\n</ul>\n\n\n\n<pre><code>foreach(DataGridViewRow row in dgv.Rows)\n{\n String cellValue = row.Cells[1].Value.ToString();\n foreach(CheckBox boxItem in boxList)\n {\n if(cellValue == boxItem.Name)\n {\n row.Visible = false;\n break;\n }\n }\n}\n</code></pre>\n\n<p>On another sidenote, please use meaningful variable names, even in such stupid iterating loops.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:09:55.847", "Id": "10911", "Score": "0", "body": "Is there a speed difference between for and foreach?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:38:54.060", "Id": "10918", "Score": "1", "body": "Yes, there can be. With for() you have to use indexed arrays, and when you use indexed arrays the compiler has to emit code to check that your indexes are within the bounds of your array all the time. With foreach() you do not use indexed arrays, so you save those checks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T08:09:42.647", "Id": "10944", "Score": "0", "body": "So I gather its like using iterators in c++ . . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T08:17:18.857", "Id": "10945", "Score": "1", "body": "@PoiXen: [The main reason is readability](http://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c-sharp)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:46:22.703", "Id": "11055", "Score": "0", "body": "Caching the value of the cell in a local variable and using `break` are indeed optimizations which could produce a perceptible difference. But I still bet that the optimization that I proposed (just 2 passes instead of N*M passes) should provide the greatest performance improvement. Did you try it, @PoiXen?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:37:16.100", "Id": "11068", "Score": "0", "body": "Sorry, that should read 'just 2 passes instead of N passes'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T06:02:57.517", "Id": "48122", "Score": "2", "body": "@MikeNakis - my understanding is that for() is faster than foreach() despite the index bound checking. If you perform a Google search \"for vs foreach performance\" you would find that a lot of people would disagree with your statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T09:32:44.473", "Id": "48135", "Score": "1", "body": "@Marko I did the Google search that you suggested, and what I saw is that the answer to the question is still highly debatable, though most indications appear to suggest that for() will usually be somewhat faster, indeed. So, I stand corrected. But in any case, whatever performance difference there is, it will be negligible as far as the question at hand is concerned. The better readability of the foreach() loop is almost always worth the few extra clock cycles." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:59:31.727", "Id": "6994", "ParentId": "6993", "Score": "5" } }, { "body": "<p>My recommendation would be to first make one pass through your cells and populate a dictionary in which the key is the name and the value is the cell itself. Then make a single pass through the checkboxes, and for each checkbox use its name to lookup the cell in the dictionary and there you have it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T20:47:46.683", "Id": "10953", "Score": "0", "body": "Whoever upvoted this, thank you. It is a pity how the best answer is some times overlooked! C-:=" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:15:28.163", "Id": "11058", "Score": "0", "body": "What name do you mean to use for the key?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:23:59.880", "Id": "11059", "Score": "0", "body": "Hmmmm, I meant the value of the cell. As in `MyDictionary[row.Cells[1].Value] = row.Cells[1]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:25:06.243", "Id": "11060", "Score": "0", "body": "And what if there are multiple cells with the same value?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:29:29.340", "Id": "11061", "Score": "0", "body": "I did not know that was a possibility, but I suppose I should have thought of it. So, in that case, you can reverse it, assuming that you do not have two checkboxes with the same name. (Which sounds like a reasonable assumption to make.) First enumerate the checkboxes and populate a dictionary mapping checkbox names to checkboxes. Then, enumerate your rows, and look up the corresponding checkbox using the value of the cell. This actually makes more sense, because I assume you have fewer checkboxes than rows, so the dictionary will take up less memory." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:31:26.607", "Id": "11067", "Score": "0", "body": "I had that thought already, you can go one step further and make a `List<String>` only containing the names, sort it and use a binary search against it...but if there are so many checkboxes that a binary search is needed, something is grossly wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:38:40.947", "Id": "11070", "Score": "0", "body": "If you have more than a dozen checkboxes then a dictionary will probably perform better. But that's not the issue. The issue is this: if you are having performance problems with the sample code you showed, then obviously, something which is otherwise inconspicuous takes an awful long time. And the only things that can take a long time are 'dgv.Rows[j].Cells[1].Value.ToString()' and 'boxList[k].Name'. So, reducing the number of times these get executed should solve the performance problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:39:28.403", "Id": "11071", "Score": "0", "body": "In your code, these get executed roughly (NumberOfRows * NumberOfCheckboxes) times. In my proposal, they get executed roughly (NumberOfRows + NumberOfCheckboxes) times. That's a huge difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:41:46.090", "Id": "11072", "Score": "0", "body": "(I now notice you are not the OP, so I should not be saying \"your code\".)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:45:29.533", "Id": "11074", "Score": "0", "body": "You're aware that a Dictionary will need to look up that stuff, too, right? Even if it does that with a binary search, it still is `Rows*8` in the worst case. But if that's needed then there's something wrong with the overall design of the application." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:48:55.377", "Id": "11075", "Score": "0", "body": "The dictionary does not work with a binary search, it works in an even more efficient way, and it is said to achieve O(1) instead of O(log(N)), which is what binary search achieves. (This is not exactly so in practice, because there is a large constant factor, that's why we say that you see the improvement for N > a dozen.) But forget about that, the issue here is not dictionary vs. list." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:41:15.513", "Id": "6997", "ParentId": "6993", "Score": "1" } }, { "body": "<p>If you can stand a little LINQ and Task Parallel library, this might give it a little boost:</p>\n\n<pre><code> private void filter(IEnumerable&lt;CheckBox&gt; boxList)\n {\n // refLanguageTabs is a TabControl the Tabcount is 9\n for (var i = 0; i &lt; refLanguageTabs.TabCount; i++)\n {\n var ctrls = refLanguageTabs.TabPages[i].Controls.Find(refLanguageTabs.TabPages[i].Name + \"Grid\", true);\n var dgv = ctrls.Any() ? ctrls[0] as DataGridView : null;\n\n if (dgv == null)\n {\n continue;\n }\n\n // average row count is 3000\n Parallel.For(0, dgv.RowCount, j =&gt;\n {\n foreach (var t in boxList.Where(t =&gt; dgv.Rows[j].Cells[1].Value.ToString() != t.Name.ToString()))\n {\n dgv.BeginInvoke(new MethodInvoker(() =&gt; { dgv.Rows[j].Visible = false; }));\n }\n });\n\n dgv.Refresh();\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T16:50:36.123", "Id": "6998", "ParentId": "6993", "Score": "1" } } ]
{ "AcceptedAnswerId": "6994", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T15:49:30.753", "Id": "6993", "Score": "2", "Tags": [ "c#" ], "Title": "Help reducing loops with filter code" }
6993
<p>I'm generating all combinations of an array, so for instance, <code>["a", "b", "c", "d"]</code> will generate:</p> <pre><code>[ "a", "b", "ab", "c", "ac", "bc", "abc", "d", "ad", "bd", "abd", "cd", "acd", "bcd", "abcd" ] </code></pre> <p><a href="http://jsfiddle.net/BDG/e7sSX/5/">Here's the code I've written that does complete this task.</a></p> <p>What I'd like to know is if there is a better way, as iterating over the array <strong>twice</strong> feels like I'm cheating, or the complexity of the code is much more computationally expensive than it needs to be.</p> <p>Also, the name for a function that takes an array and returns the combinations, what might that be called? Combinator seems inappropriate.</p> <pre><code>var letters = ["a", "b", "c", "d"]; var combi = []; var temp= ""; var letLen = Math.pow(2, letters.length); for (var i = 0; i &lt; letLen ; i++){ temp= ""; for (var j=0;j&lt;letters.length;j++) { if ((i &amp; Math.pow(2,j))){ temp += letters[j] } } if (temp !== "") { combi.push(temp); } } console.log(combi.join("\n")); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T01:34:14.460", "Id": "501308", "Score": "0", "body": "I have answered another question like this. I hope it will help you also. Please check: stackoverflow.com/a/65535210/2184182" } ]
[ { "body": "<p>A much faster way to do <code>Math.pow( 2, x )</code> if x is an integer is <code>1 &lt;&lt; x</code>.</p>\n\n<p>A good name for the function might also be 'array_permutator'.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T20:33:01.663", "Id": "10928", "Score": "0", "body": "My main issue is this double-looping with the `if`-checking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T20:39:54.217", "Id": "10930", "Score": "0", "body": "Yes, I understand that. I cannot come up with an idea for eliminating the nested loop. So, wait and see if someone thinks of something." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T20:04:43.677", "Id": "7005", "ParentId": "7001", "Score": "6" } }, { "body": "<p>An alternative is to build a trie and then walk the trie to generate\nthe combinations. There are two recursive functions and I've timed\nit as roughly an order of magnitude slower than your iterative version,\nbut I thought you might find it interesting nonetheless. (Once JS gets\ntail-call optimisation, some recursive approaches will run faster.)</p>\n\n<pre><code>var follows, combinations;\n\nfollows = function(a){\n return a.map(function(item, i){\n return [item, follows(a.slice(i+1))];\n });\n};\n\ncombinations = function(a){\n var combs = function(prefix, trie, result){\n trie.forEach(function(node, i){\n result.push(prefix + node[0]);\n combs(prefix + node[0], node[1], result);\n });\n return result;\n };\n return combs('', follows(a), []);\n};\n\ncombinations(['a','b','c','d']);\n</code></pre>\n\n<p>P.S. Your <code>permutations</code> function outputs an array of arrays, not an array of strings like your example at the top of your question. I've output an array of strings with my <code>combinations</code> function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T01:26:25.293", "Id": "7010", "ParentId": "7001", "Score": "11" } }, { "body": "<p>A recursive solution, originally <a href=\"https://stackoverflow.com/a/8171776/592746\">seen here</a>, but modified to fit your requirements (and look a little more JavaScript-y):</p>\n\n<pre><code>function combinations(str) {\n var fn = function(active, rest, a) {\n if (!active &amp;&amp; !rest)\n return;\n if (!rest) {\n a.push(active);\n } else {\n fn(active + rest[0], rest.slice(1), a);\n fn(active, rest.slice(1), a);\n }\n return a;\n }\n return fn(\"\", str, []);\n}\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>combinations(\"abcd\")\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[\"abcd\", \"abc\", \"abd\", \"ab\", \"acd\", \"ac\", \"ad\", \"a\", \"bcd\", \"bc\", \"bd\", \"b\", \"cd\", \"c\", \"d\"]\n</code></pre>\n\n<p><strong>Regarding the name</strong>: Don't name it <code>permutations</code>; a permutation is an arrangement of all the original elements (of which there should be <code>n!</code> total). In other words, it already has a precise meaning; don't unnecessarily overload it. Why not simply name it <code>combinations</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T06:41:54.883", "Id": "56838", "Score": "1", "body": "Stumbled back here and have no idea why I didn't originally point out that \"combination\" also has an existing mathematical definition http://en.wikipedia.org/wiki/Combination" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T17:28:47.340", "Id": "64038", "Score": "10", "body": "\"All possible combinations\" can also be called a \"power set\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:24:33.597", "Id": "66678", "Score": "4", "body": "On closer inspection… a [power set](http://en.wikipedia.org/wiki/Power_set) should include the empty string. I'm not sure what to call a power set minus the empty string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-01T11:36:30.023", "Id": "194663", "Score": "1", "body": "I'm trying to create my library of babel and this came in handy xD" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-31T23:24:16.703", "Id": "255816", "Score": "1", "body": "Instead of \"power set\" (which is about sets, without caring for order), an even better name would be [`subsequences`](https://en.wikipedia.org/wiki/Subsequence) (although technically that includes the empty sequence as well)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-30T08:02:08.677", "Id": "513565", "Score": "0", "body": "This function causes stack overflow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T05:37:45.273", "Id": "513857", "Score": "0", "body": "@Werlious in what case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-04T06:22:11.513", "Id": "513861", "Score": "0", "body": "@Wayne combinations of lowercase alpha chars eg `combinations(\"abcdef...uvwxyz\")`. Copied the code to the repl, tried that (is what I needed) and get either a stack overflow or heap OOM. Recursive solution by @Guffa did not have this issue for me for some reason" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T16:46:09.007", "Id": "7025", "ParentId": "7001", "Score": "57" } }, { "body": "<p>You can do it recursively:</p>\n\n<pre><code>function getCombinations(chars) {\n var result = [];\n var f = function(prefix, chars) {\n for (var i = 0; i &lt; chars.length; i++) {\n result.push(prefix + chars[i]);\n f(prefix + chars[i], chars.slice(i + 1));\n }\n }\n f('', chars);\n return result;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var combinations = getCombinations([\"a\", \"b\", \"c\", \"d\"]);\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[\"a\",\"ab\",\"abc\",\"abcd\",\"abd\",\"ac\",\"acd\",\"ad\",\"b\",\"bc\",\"bcd\",\"bd\",\"c\",\"cd\",\"d\"]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T21:01:43.780", "Id": "428613", "Score": "0", "body": "thanks... slight tweak to return set of arrays \n\n```function getCombinations(array) {\n var result = [];\n var f = function(prefix=[], array) {\n for (var i = 0; i < array.length; i++) {\n result.push([...prefix,array[i]]);\n f([...prefix,array[i]], array.slice(i + 1));\n }\n }\n f('', array);\n return result;\n}```javascript" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:59:50.353", "Id": "439720", "Score": "0", "body": "The best and most readable solution!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T12:38:51.780", "Id": "7042", "ParentId": "7001", "Score": "28" } }, { "body": "<p>I prefer your approach much better than a recursive approach, especially when larger lists are being processed.</p>\n\n<p>Some notes:</p>\n\n<ul>\n<li>I like the name <code>powerSet</code> as per @200_success</li>\n<li>You do not need to check for <code>combination.length !== 0</code> if you start with <code>i=1</code></li>\n<li>If you call the function <code>permutations</code>, then you should not call the list you build <code>combinations</code>, that is confusing</li>\n<li>You could cache <code>list.length</code>, that is a common optimization</li>\n</ul>\n\n<p>With curly braces you can then have:</p>\n\n<pre><code>function powerSet( list ){\n var set = [],\n listSize = list.length,\n combinationsCount = (1 &lt;&lt; listSize),\n combination;\n\n for (var i = 1; i &lt; combinationsCount ; i++ ){\n var combination = [];\n for (var j=0;j&lt;listSize;j++){\n if ((i &amp; (1 &lt;&lt; j))){\n combination.push(list[j]);\n }\n }\n set.push(combination);\n }\n return set;\n}\n</code></pre>\n\n<p>without them it could look like this:</p>\n\n<pre><code>function powerSet( list ){\n var set = [],\n listSize = list.length,\n combinationsCount = (1 &lt;&lt; listSize);\n\n for (var i = 1; i &lt; combinationsCount ; i++ , set.push(combination) )\n for (var j=0, combination = [];j&lt;listSize;j++)\n if ((i &amp; (1 &lt;&lt; j)))\n combination.push(list[j]);\n return set;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:21:44.280", "Id": "66677", "Score": "2", "body": "The first version is excellent. The second one is not nearly as good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T17:39:22.210", "Id": "66680", "Score": "3", "body": "The 2nd version is too Golfic, but I am addicted to dropping curlies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-10T23:30:50.093", "Id": "368090", "Score": "1", "body": "I like this answer. If I were to try to improve (which is not needed), I would say, 1. I would use `powerSet`, instead of `set`, or at least something with less overloaded meaning. 2. I would avoid 2nd nested loop as most of the inner loops are unused. I think memoization would be good for that (https://jsfiddle.net/ynotravid/kkwfnpu7/20/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-03T12:33:03.517", "Id": "432965", "Score": "0", "body": "upvoted the problem is, this generates abcd only once it should generate abcd, acbd, adbc...and so on till all 16 permutations are exhausted and do the same for 3 letter and 2 letter and single letter ones" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T10:10:17.647", "Id": "514904", "Score": "1", "body": "@PirateApp From OP's example, order doesn't matter, he only wants one 4-character output, i.e. either one of abcd, adbc, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-19T11:00:49.353", "Id": "514913", "Score": "0", "body": "@Ynot Nice algorithm! It's impressive. I notice that the `iterations` number for the \"Without memoization\" one is misleading. It should be 60 instead of 22 (which is the result of running `powerSet(list)` twice before declaring the `powerSetDoubleLoop` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-24T00:44:53.710", "Id": "515274", "Score": "1", "body": "@blackr1234, yes you are right thanks. https://jsfiddle.net/ynotravid/0qp6ctzn/4/" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-21T16:00:08.480", "Id": "39747", "ParentId": "7001", "Score": "17" } }, { "body": "<p>Try this simple one.</p>\n\n<pre><code>var input=\"abcde\";\nvar len=input.length;\nvar str = \"\";\nvar p=Math.pow(2,len);\nvar twoPower;\nfor(i = 0; i &lt; p; i++) \n{\n twoPower=p;\n for(j=0;j&lt;len;j++)\n {\n twoPower=twoPower/2;\n str+= (i &amp; twoPower ? input.charAt(j) : \"\");\n }\n str+=\"\\n\";\n}\nalert(str);\n</code></pre>\n\n<p>It's working method is so simple. \nWhat would you do if you have to find all binary numbers for a given a bit length?\nYes the 8 4 2 1 method.\nif bit length is 3 then possible numbers are</p>\n\n<h2>4 2 1</h2>\n\n<p>0 0 0<br>\n0 0 1<br>\n0 1 0<br>\n0 1 1<br>\n1 0 0<br>\n1 0 1<br>\n1 1 0<br>\n1 1 1 </p>\n\n<p>These are the 8 possible values.\nThe same method is used here but for 1's here is a character and for 0's nothing. So, number of possible combinations is (2^n)-1.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T17:21:03.117", "Id": "154273", "Score": "3", "body": "Welcome to CodeReview. As it is your code is little more than a code dump, please provide context towards why the OP should take your suggestion /what would differentiate it from what he's already doing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-01T17:14:05.890", "Id": "85611", "ParentId": "7001", "Score": "0" } }, { "body": "<p>I have two solutions for this, one being binary and one being recursive;</p>\n\n<p>The binary would be as follows;</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getSubArrays(arr){\n var len = arr.length,\n subs = Array(Math.pow(2,len)).fill();\n return subs.map((_,i) =&gt; { var j = -1,\n k = i,\n res = [];\n while (++j &lt; len ) {\n k &amp; 1 &amp;&amp; res.push(arr[j]);\n k = k &gt;&gt; 1;\n }\n return res;\n }).slice(1);\n}\n\nconsole.log(JSON.stringify(getSubArrays([\"a\",\"b\",\"c\",\"d\"])));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>And the recursive one is as follows;</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getSubArrays(arr){\n if (arr.length === 1) return [arr];\n else {\n subarr = getSubArrays(arr.slice(1));\n return subarr.concat(subarr.map(e =&gt; e.concat(arr[0])), [[arr[0]]]);\n }\n}\n\nconsole.log(JSON.stringify(getSubArrays([\"a\",\"b\",\"c\",\"d\"])));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-25T17:41:38.093", "Id": "142431", "ParentId": "7001", "Score": "4" } }, { "body": "<p>In this case, a non-recursive solution is easier to understand, IMHO:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const powerset = (array) =&gt; { // O(2^n)\n const results = [[]];\n for (const value of array) {\n const copy = [...results]; // See note below.\n for (const prefix of copy) {\n results.push(prefix.concat(value));\n }\n }\n return results;\n};\n\nconsole.log(\n powerset(['A', 'B', 'C'])\n);\n\n// [ [],\n// [ 'A' ],\n// [ 'B' ],\n// [ 'A', 'B' ],\n// [ 'C' ],\n// [ 'A', 'C' ],\n// [ 'B', 'C' ],\n// [ 'A', 'B', 'C' ] ]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Because <code>results</code> is extended within the loop body, we cannot iterate over it using <code>for-of</code> — doing so would iterate over the newly added elements as well, resulting in an infinite loop. We only want to iterate over the elements that are in <code>results</code> when the loop starts, i.e. indices <code>0</code> until <code>results.length - 1</code>. So we either cache the original <code>length</code> in a variable and use that, i.e.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>for (let index = 0, length = results.length; index &lt; length; index++) {\n const prefix = results[index];\n // …\n}\n</code></pre>\n\n<p>…or we just create a static copy of results and iterate over that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-09T07:52:09.760", "Id": "154883", "ParentId": "7001", "Score": "10" } }, { "body": "<p>In this collection of answers, I think we're missing the traditional recursive solution, which highlights the elegance of a recursive algorithm:</p>\n\n<pre><code>const subSeq = (s) =&gt; {\n if (s.length == 1) return ['', s] \n\n // All the subSeq without the first char:\n const ss = subSeq(s.slice(1))\n\n // Return both those with and those without the first char\n return [...ss.map(ch =&gt; s[0] + ch), ...ss]\n}\n</code></pre>\n\n<p>or more concisely stated, but perhaps harder to follow:</p>\n\n<pre><code>const subSeq = (s) =&gt; s.length == 1 \n ? ['', s] \n : (ss=subSeq(s.slice(1)), \n [...ss.map(ch =&gt; s[0] + ch), ...ss])\n</code></pre>\n\n<p>includes the empty string in the answer:</p>\n\n<pre><code>subSeq('abcd')\n=&gt; [\"abc\", \"abcd\", \"ab\", \"abd\", \"ac\", \"acd\", \"a\", \"ad\", \"bc\", \"bcd\", \"b\", \"bd\", \"c\", \"cd\", \"\", \"d\"]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T05:37:08.977", "Id": "204749", "ParentId": "7001", "Score": "1" } } ]
{ "AcceptedAnswerId": "7025", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T17:34:08.417", "Id": "7001", "Score": "91", "Tags": [ "javascript", "combinatorics" ], "Title": "Generating all combinations of an array" }
7001
<pre><code>public class BQueue&lt;T&gt; { private Queue&lt;T&gt; q = new LinkedList&lt;T&gt;(); private int limit; public BQueue(int limit) { this.limit = limit; } public synchronized void put (T t) throws InterruptedException { while (isFull()) { wait(); } boolean e = isEmpty(); q.add(t); if (e) notifyAll(); } public synchronized T get () throws InterruptedException { while (isEmpty()) { wait(); } boolean f = isFull(); T t = q.poll(); if (f) notifyAll(); return t; } private boolean isEmpty() { return q.size() == 0; } private boolean isFull() { return q.size() == limit; } } </code></pre> <p>Is this implementation thread-safe?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T19:44:57.327", "Id": "10924", "Score": "3", "body": "I _think_ it probably is, although I occasionally get tripped up by some threading stuff. Is there a reason you're not implementing any of the interfaces (`Queue`, etc.)? Or even just using an existing [Blocking Queue](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html)?" } ]
[ { "body": "<p>It looks to me like it is thread-safe. But don't take my word for it; you better consider each answer as a vote, and go with what the majority says. (Multi-threading is tricky!) Note: comments should not be considered as answers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T19:46:07.540", "Id": "7003", "ParentId": "7002", "Score": "1" } }, { "body": "<p>Yes, it's thread-safe. (Or at least I haven't found any issue.) Please note, that the Java Collections Framework already has a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html\" rel=\"nofollow\">BlockingQueue</a> interface which has some implementations, for example a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html\" rel=\"nofollow\">LinkedBlockingQueue</a> (<a href=\"http://www.docjar.com/html/api/java/util/concurrent/LinkedBlockingQueue.java.html\" rel=\"nofollow\">source</a>). It's probably well tested add has better performance, so try not to reinvent the wheel if it's not necessary.</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p>Try using longer variable names:</p>\n\n<blockquote>\n<pre><code>boolean f = isFull();\n</code></pre>\n</blockquote>\n\n<p>It could be <code>isFull</code> which results more readable code. The same is true for <code>q</code> and <code>t</code>. (I'd rename it to <code>queue</code> and <code>item</code>.)</p></li>\n<li><p>Check your input: What happens when <code>limit</code> is <code>0</code> or less than zero? (You should throw an <code>IllegalArgumentException</code>.)</p></li>\n<li><p>The <code>limit</code> and <code>q</code> fields could be marked <code>final</code>. It would improve code readability since readers don't have to check whether their values have changed somewhere in the class or not. It also would prevent accidental value modifications.</p></li>\n<li><p>The used <code>Queue</code> has an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#isEmpty%28%29\" rel=\"nofollow\"><code>isEmpty</code></a> method (by implementing <code>Collection.isEmpty()</code>), you could use that instead of your own.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-30T03:19:11.190", "Id": "13207", "Score": "2", "body": "Thread-safety is a bona fide Hard Problem. Whenever possible, use someone else's tested code, especially code from the JDK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-16T00:13:03.020", "Id": "177538", "Score": "0", "body": "1. Should'nt isEmpty() and isFull() need to be synchronized too ?\n2. Should'nt limit be volatile ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-16T06:04:42.473", "Id": "177580", "Score": "1", "body": "@sreeprasad: 1. `isEmpty()` and `isFull()` are `private` methods and are called from only `synchronized` methods, so they're safe now. (As far as there isn't any public non-synchronized method which calls them, for example.) Anyway, `synchronization` keywords on them would not hurt, I would use that. (Write it as an answer, I would upvote it.) I usually use the `@GuardedBy` annotation too in my code for better clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-16T06:04:49.313", "Id": "177581", "Score": "1", "body": "@sreeprasad: 2. Since `limit` is read and written in only `synchronized` methods it's safe without `volatile`, the `synchronized` block guarantees that changes are visible to other threads too." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T21:38:19.927", "Id": "7006", "ParentId": "7002", "Score": "8" } }, { "body": "<p>This looks thread-safe to me. However, I'm puzzled by the logic driving the notifications.</p>\n\n<p>In <code>put()</code>, you wait until the queue is non-full (i.e., at least one slot open), then you add element <code>t</code> to the end of the queue. Cool, but then you only notify other threads if the queue was empty prior to adding <code>t</code>. Similarly, in <code>get()</code>, you wait until the queue is non-empty (i.e., has at least one item), then you fetch element <code>t</code> from the head of the queue. Again, cool, but then you only notify other threads if the queue was full prior to fetching <code>t</code>. This will have the effect of requiring the queue to be completely filled before it can be emptied, and conversely for it to be completely emptied before it can be refilled.</p>\n\n<p>Maybe this was your intention, but this is not documented in the behavior, nor is it typical for a blocking queue.</p>\n\n<p>I think what you might want is this instead:</p>\n\n<pre><code>public synchronized void put (T t) throws InterruptedException {\n while (isFull())\n wait();\n q.add(t);\n notifyAll();\n}\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>public synchronized T get () throws InterruptedException {\n while (isEmpty())\n wait();\n T t = q.poll();\n notifyAll();\n return t;\n}\n</code></pre>\n\n<p>This version of <code>put()</code> will notify waiting threads immediately after a new element is added. This will wake up any waiting <code>get()</code> calls and immediately fetch the value you just added. This is usually what you want. If any other waiting <code>put()</code> call wakes up and finds that the queue is full (since you just added an element after possibly having waited for it to be non-full), it will simply cycle around the <code>while</code> loop and begin waiting again; no harm done.</p>\n\n<p>Similarly, this version of <code>get()</code> will notify waiting threads immediately after an element is removed. This will wake up any waiting <code>put()</code> calls immediately and allow them to store a new value. This is also usually what you want. And if any other waiting <code>get()</code> call wakes up and finds that the queue is empty (since you may have just removed the last element), it will simply cycle around the <code>while</code> loop and begin waiting again until someone else adds another element.</p>\n\n<p>Other than that, it looks good to me!</p>\n\n<p>p.s. — Since <code>get()</code> and <code>put()</code> are synchronized, there's no harm in calling <code>notifyAll()</code> before you actually remove the item from the queue, because other waiting threads can't actually run again until you exit from <code>get()</code> (because you're not waiting). So, it can be simplified even further:</p>\n\n<pre><code>public synchronized T get () throws InterruptedException {\n while (isEmpty())\n wait();\n notifyAll();\n return q.poll();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T00:22:41.827", "Id": "82367", "Score": "0", "body": "I'm not sure that I understand the first part completely. If the queue is not empty `get` won't call `wait()`, sou don't have to fill it completely to `get` something. (A small example code might help.) Anyway, the second points is a good catch, +1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-30T06:08:26.187", "Id": "394624", "Score": "0", "body": "I don't really understand what you meant by \"In put(), you wait until the queue is non-full (i.e., at least one slot open)\".\nIn the code it the put() method it only went to wait() if the queue was full. otherwise, it put the element in the queue right away." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-26T16:54:51.880", "Id": "8334", "ParentId": "7002", "Score": "3" } }, { "body": "<p>This is thread safe if there are only one producer and one consumer. The get() may return null or throw exceptions if there are two consumers. For instance if queue is empty and 2 consumers calling get(), then both consumers will be suspended at the wait(). When the producer pushes an object into queue and notify both consumers, both consumers will break the while loop and call get(). Unfortunately one consumer will get the object but the other consumer will receive null object. The fix should extend the while loop to cover this case</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T11:14:48.793", "Id": "80299", "Score": "0", "body": "I believe you are mistaken in this case. With the entire methods being synchronized, only one of the waiting threads will exit the `while()` loop" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-02T09:12:51.707", "Id": "46023", "ParentId": "7002", "Score": "-1" } }, { "body": "<p>I think its thread safe.. Also there can be multiple consumers as the method get is synchronized so only 1 consumer would be able to acquire lock on get.</p>\n\n<p>When the first consumer releases the lock, then the second consumer would check the while loop that if its empty and would again enter the wait state.</p>\n\n<p>So it seems fine to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-07T08:20:06.483", "Id": "69139", "ParentId": "7002", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T18:43:08.510", "Id": "7002", "Score": "15", "Tags": [ "java", "multithreading", "queue", "collections", "synchronization" ], "Title": "Java blocking queue" }
7002
<p>I have a <code>xxs</code> list:</p> <pre><code>xxs:: [(([Char], [Char]),([Char], [Char]),[(Double, [Char], [Char])])] xxs = [(("a11","b11"),("a12","b12"), [(0,"a1","b1"),(1.2,"a2","b2"),(2.3,"a3","b3"),(4.2,"a4","b4")]), (("c11","d11"),("a12","b12"),[(1,"a5","b5"),(1.4,"a6","b6"),(1.9,"a7","b7"),(4.4,"a8","b8")])] </code></pre> <p>And I need something like:</p> <pre><code>foo 1 -- 1 is the index output: [(0.0,0.0,"a1","b1"),(1.2,1.2,"a2","b2"),(2.3,3.5,"a3","b3"),(4.2,7.7,"a4","b4")] </code></pre> <p>or</p> <pre><code>foo 2 -- 2 is the index output: [(1.0,1.0,"a5","b5"),(1.4,2.4,"a6","b6"),(1.9,4.3,"a6","b6"),(4.4,8.7,"a6","b6")] </code></pre> <p>Where the <code>second element</code> of each tuple is the summation of all the Doubles from the <code>xxs</code> inner list.</p> <p>I solve it this way:</p> <pre><code>auxA :: Int -&gt; [(Double, [Char], [Char])] auxA indexP = aux1 xxs!!(indexP-1) where aux1 [] = [] aux1 ((_,_,c):xs) = c:aux1 xs auxB :: Int -&gt; [Double] auxB indexP = aux2 (auxA indexP) where aux2 [] = [] aux2 ((x,_,_):xs) = x:aux2 xs integer1 :: Int -&gt; [Double] integer1 indexP = [ i | (i,_,_) &lt;- auxA indexP] intSummation :: Int -&gt; [Double] intSummation indexP = scanl (+) (head (auxB indexP)) (drop 1 (auxB indexP)) string1 :: Int -&gt; [[Char]] string1 indexP = [ st1 | (_,st1,_) &lt;- auxA indexP] string2 :: Int -&gt; [[Char]] string2 indexP = [ st2 | (_,_,st2) &lt;- auxA indexP] foo :: Int -&gt; [(Double, Double, [Char], [Char])] foo indexP = zip4 (integer1 indexP) (intSummation indexP) (string1 indexP) (string2 indexP) --or fob :: Int -&gt; [(Double, Double, [Char], [Char])] fob indexP = [(i,intSum,st1,st2) | (((i,intSum),st1),st2) &lt;- zip (zip(zip (integer1 indexP) (intSummation indexP)) (string1 indexP)) (string2 indexP)] </code></pre> <p>For <code>fob</code>, I've found a similar code here: <a href="https://stackoverflow.com/questions/2468226/how-to-zip-multiple-lists-in-haskell">https://stackoverflow.com/questions/2468226/how-to-zip-multiple-lists-in-haskell</a></p> <p>Finally, one question: any suggestion to solve this problem with a different approach/code?</p> <p>Thanks.</p> <p>edit: type signatures added.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T01:01:47.443", "Id": "10940", "Score": "0", "body": "@ehird For me, this is not exactly a \"Code Review\"... is more like: I'm a beginner in Haskell, I solved my homework, but I'm curious about other solutions/approaches to solve it. But maybe your right." } ]
[ { "body": "<p>Wow! What an ugly data structure. I suggest making small transformations until you arrive at the form you desire; this is in contrast to your current solution that extracts the exact element you desire (performing all needed computations) without building a new representation.</p>\n\n<p><strong>1) Eliminate unused fields</strong></p>\n\n<pre><code>map (\\(_,_,lst) -&gt; lst) -- This is like 'auxA' with the lookup\n</code></pre>\n\n<p>This gets rid of the first two elements of the tuple, which your transformation didn't seem to use.</p>\n\n<p>The first line simply drops your first two tuples, so instead of:</p>\n\n<pre><code>xxs:: [(([Char], [Char]),([Char], [Char]),[(Double, [Char], [Char])])]\n</code></pre>\n\n<p>Which didn't seem needed for your computations (you didn't really explain what you want in words, so it's possible I missed the point by skipping your code). Now you have:</p>\n\n<pre><code>xxs:: [[(Double, [Char], [Char])]]\n</code></pre>\n\n<p><strong>2) Compute the running sum</strong></p>\n\n<pre><code>-- This is similar to your interger1, intSummation, string1, and string2 all rolled in one\ndrop 1 . scanl (\\(_,s,_,_) (n,x,y) -&gt; (n,n+s,x,y)) (0,0,\"\",\"\")\n</code></pre>\n\n<p>The \"scan\" just transforms a list using a binomial and a starting element. In this case, you see the <code>n+s</code> is the second element while the original value, <code>n</code>, is the first element of the output tuples. I call <code>drop 1</code> to get rid of my initial 4-tuple that starts the scan.</p>\n\n<p>The final code looks like:</p>\n\n<pre><code>import Data.List\n\ntmd i =\n let xxs' = map (\\(_,_,lst) -&gt; lst) xxs -- This is like 'auxA' with the lookup\n xxsFinal = map (drop 1 . scanl (\\(_,s,_,_) (n,x,y) -&gt; (n,n+s,x,y)) (undefined,0,undefined,undefined)) $ xxs'\n in lookup i (zip [1..] xxsFinal)\n</code></pre>\n\n<p>With correct results (afaict):</p>\n\n<pre><code>&gt; Just (foo 2) == tmd 2\nTrue\n&gt; Just (foo 1) == tmd 1\nTrue\n</code></pre>\n\n<p><strong>If #2 is too much in one step</strong></p>\n\n<ol>\n<li>Extract the values: <code>let vals = map (\\(n,_,_) -&gt; n) input</code></li>\n<li>Compute the sums: <code>let sums = drop 1 . scanl (+) 0 $ vals</code></li>\n<li>Combine the info: <code>zipWith3 (\\v s (_,a,b) -&gt; (v,s,a,b)) vals sums input</code></li>\n</ol>\n\n<p><strong>Comparing to your code (learning to use standard functions)</strong></p>\n\n<p>Mostly, you seem to be of a mind to looking data on demand when it's easier and cleaner to build a list of all results and pull out the desired values. Some specific observations:</p>\n\n<ol>\n<li>Your <code>aux1</code> and <code>aux2</code> functions are just maps, for example <code>aux1 = map (\\(_,_,c) -&gt; c)</code>.</li>\n<li><code>!!</code> is a partial function. I suggest you use <code>lookup index . zip [1..]</code>.</li>\n<li>Most of your list comprehensions are easier to read as a <code>map</code> function and simple lambda. They really don't deserve to be separate functions.</li>\n<li>Way to go, using <code>scanl</code> as a beginner - nice work. However, instead of using 'head' and 'drop' perhaps you could just use your own zero element (like I did with <code>0</code> and <code>\"\"</code> - or I could have used <code>undefined</code>) or use <code>scanl1 (+) . auxB</code>.</li>\n</ol>\n\n<p>P.S. Good work coming in with a complete solution!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T02:51:37.637", "Id": "10941", "Score": "1", "body": "Excellent post. It sure did help me to understand some functions usage. And, of course, thanks for you advises. For sure that I’ll try to follow yours advises in the future! I really learn a nice couple of things with your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T02:14:48.633", "Id": "7012", "ParentId": "7011", "Score": "7" } } ]
{ "AcceptedAnswerId": "7012", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T00:49:19.693", "Id": "7011", "Score": "11", "Tags": [ "haskell" ], "Title": "A different code?" }
7011
<p>I think I'm finished writing a multithreaded reader-writer implementation for my Operating Systems course. I would like to verify that my multithreading is correct and that I'm using good C++0x style.</p> <p>PalindromeDatabase.h</p> <pre><code>class PalindromeDatabase : public Utility::Uncopyable { friend void *read(void *classHandle); friend void *write(void *classHandle); public: PalindromeDatabase(std::vector&lt;int&gt; const&amp; arguments); void process(); private: void createReaderThreads(); void createWriterThreads(); void joinReaderThreads(); void joinWriterThreads(); void *read(); void readPalindromes(); void *write(); void processPalindromes(); void formatPalindrome(std::string&amp; palindrome); void removeNonAlphabeticCharacters(std::string&amp; palindrome); void toLowerCase(std::string&amp; palindrome); private: const std::string PalindromeFilename_; const int ThreadWorkTime_; const int NumberOfReaders_; const int NumberOfWriters_; std::vector&lt;pthread_t&gt; readerThreads_; std::vector&lt;pthread_t&gt; writerThreads_; sem_t semaphore_; pthread_mutex_t writerMutex_; Timer timer_; }; </code></pre> <p>PalindromeDatabase.cpp</p> <pre><code>PalindromeDatabase::PalindromeDatabase(std::vector&lt;int&gt; const&amp; arguments) : PalindromeFilename_("palindromes"), ThreadWorkTime_(arguments[1]), NumberOfReaders_(arguments[2]), NumberOfWriters_(arguments[3]), readerThreads_(NumberOfReaders_), writerThreads_(NumberOfWriters_) { sem_init(&amp;semaphore_, 0, NumberOfReaders_); pthread_mutex_init(&amp;writerMutex_, nullptr); } void PalindromeDatabase::process() { Logger().log() &lt;&lt; "Starting session..."; timer_.start(); createReaderThreads(); createWriterThreads(); joinReaderThreads(); joinWriterThreads(); timer_.stop(); Logger().log() &lt;&lt; "Ending session..."; Logger().log() &lt;&lt; "Elapsed time: " &lt;&lt; timer_.seconds() &lt;&lt; "s:" &lt;&lt; timer_.milliseconds() % 1000 &lt;&lt; "ms."; pthread_exit(nullptr); } void PalindromeDatabase::createReaderThreads() { for (auto&amp; thread : readerThreads_) pthread_create(&amp;thread, nullptr, ::read, static_cast&lt;void*&gt;(this)); } void PalindromeDatabase::joinReaderThreads() { for (auto&amp; thread : readerThreads_) { int garbage = 0; pthread_join(thread, reinterpret_cast&lt;void**&gt;(&amp;garbage)); } } void *PalindromeDatabase::read() { timeval startTime; gettimeofday(&amp;startTime, nullptr); while (Utility::elapsedTime(startTime) &lt; ThreadWorkTime_) { sem_wait(&amp;semaphore_); auto threadID = pthread_self(); Logger().log() &lt;&lt; "Reader " &lt;&lt; threadID &lt;&lt; " is reading the file..."; readPalindromes(); Logger().log() &lt;&lt; "Reader " &lt;&lt; threadID &lt;&lt; " has finished reading the file..."; sem_post(&amp;semaphore_); sleep(1); // Simulate work } return nullptr; } void *PalindromeDatabase::write() { timeval startTime; gettimeofday(&amp;startTime, nullptr); while (Utility::elapsedTime(startTime) &lt; ThreadWorkTime_) { pthread_mutex_lock(&amp;writerMutex_); for (int i = 0; i &lt; NumberOfReaders_; ++i) sem_wait(&amp;semaphore_); pthread_mutex_unlock(&amp;writerMutex_); auto threadID = pthread_self(); Logger().log() &lt;&lt; "Writer " &lt;&lt; threadID &lt;&lt; " is working on the file..."; processPalindromes(); Logger().log() &lt;&lt; "Writer " &lt;&lt; threadID &lt;&lt; " finished working on the file..."; for (int i = 0; i &lt; NumberOfReaders_; ++i) sem_post(&amp;semaphore_); sleep(1); // Simulate work. } return nullptr; } </code></pre> <p>I've kept the code minimal, showing only the multithreaded parts and not the implementation, which is a little nonsensical since we simply had to do "busy work". I've omitted the Logger because I think it's safe and outside of any critical sections. </p>
[]
[ { "body": "<p>It is very hard to determine if multi threaded code is correct just by looking at it. You should create special tests that simulate concurrent operations and validate shared state for corruption. The test(s) should be run for considerable amount of time and preferably on multi CPU (core) environment to be sure that code is working correctly.</p>\n\n<p>Here's what I consider suspicious in the code sample you've provided:\nIn PalindromeDatabase::write() you're releasing write mutex soon after you've waited for all readers to complete. If I understand correctly, if there are multiple writers it is possible that they will call processPalindromes() simultaneously.</p>\n\n<p>I propose placing pthread_mutex_unlock(&amp;writerMutex_); after the processPalindromes is called thus write will be thread-safe.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T09:52:32.177", "Id": "10968", "Score": "1", "body": "Testing and verifying my results is very confusing. My current test-harness creates six logs with a 1:1, 1:10, 1:100, 1:1000 ratio of readers to writers and vice-versa. I specify a thread runtime of 15seconds. However, the results are usually so close together that I'm just clueless as to whether or not this is correct. Can you give me an example of proper test values? More than 1000 threads each? Longer than a minute?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T10:17:30.360", "Id": "10969", "Score": "3", "body": "Thousands of threads is a bad approach (the more threads the more CPU scheduling). I would use ratios where there is no single reader or writer (like 2:2). Increase thread running time to at least several minutes (the more the better). Ideally your test should validate constantly if there was any state corruption. Run the test for at least couple of hours to be sure that everything is fine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T09:48:13.900", "Id": "7039", "ParentId": "7014", "Score": "2" } } ]
{ "AcceptedAnswerId": "7039", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T08:48:01.323", "Id": "7014", "Score": "4", "Tags": [ "c++", "multithreading", "c++11", "palindrome" ], "Title": "Correct multithreaded reader-writer implementation" }
7014
<p>I have been working on Custom TextBox control, which only allows alphanumeric characters. Note that I have not restricted characters from KeyPress, KeyUp event as I don't want to restrict copy/paste or any other operation that should be allowed generally. I have only trimmed non-alphanumeric character on paste operation. However, I am not sure whether the code I wrote is good or bad as I have very little experience of desktop application.</p> <pre><code>using System; using System.Windows.Forms; using System.Text.RegularExpressions; namespace SaintThomas.UserControls { class TextBoxForUserName : TextBox { protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); this.SuspendLayout(); int startPos = this.SelectionStart; if (Regex.IsMatch(this.Text, "[^0-9_A-Z]", RegexOptions.IgnoreCase)) { int reduceStartPos = this.Text.Length; this.Text = Regex.Replace(this.Text, "[^0-9_A-Z]", "", RegexOptions.IgnoreCase); startPos = (startPos &lt;= 0) ? 0 : startPos - (reduceStartPos - this.Text.Length); if (this.Text.Length &lt; startPos) { startPos = this.Text.Length; } this.SelectionStart = startPos; } this.ResumeLayout(); } } } </code></pre>
[]
[ { "body": "<p>Are you reinventing the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx\" rel=\"nofollow\">MaskedTextBox</a>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T12:51:42.757", "Id": "10972", "Score": "0", "body": "Of course not! If the functionality I tried to implement through above code is possible using MaskedTextBox then please let me. Also note that the length of text can be vary and I don't want PromtChar appear in textbox." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T16:53:23.843", "Id": "10985", "Score": "0", "body": "It seems to be, but I guess one needs to try it (I haven't). I knew that these masked controls existed so figured it would be useful to post it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T13:49:46.300", "Id": "7021", "ParentId": "7016", "Score": "1" } }, { "body": "<p>Aside from the indentation issues...</p>\n\n<ul>\n<li>You could simply use <code>@\"\\W\"</code> for your regular expression (with <code>RegexOptions.None</code>).</li>\n<li>A simpler way to deal with the cursor is to measure the distance from the end of the string, since you can know that will remain constant.</li>\n<li>Using <code>Regex.Match</code> followed by <code>Regex.Replace</code> seems pointless to me. If the string doesn't need to be changed, <code>Regex.Replace</code> should be able to determine that quickly.</li>\n<li><p>Calls to <code>SuspendLayout</code> also seem unnecessary, since the layout of your control (i.e., its bounds, position) is not changing.</p>\n\n<pre><code>protected override void OnTextChanged(EventArgs e) {\n base.OnTextChanged(e);\n int charsFromEnd = this.Text.Length - this.SelectionStart;\n this.Text = Regex.Replace(this.Text, @\"\\W\", \"\", RegexOptions.None);\n this.SelectionStart = this.Text.Length - charsFromEnd;\n}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T00:10:43.147", "Id": "7129", "ParentId": "7016", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T10:29:00.357", "Id": "7016", "Score": "2", "Tags": [ "c#", "winforms" ], "Title": "C# Winforms: Is there any way to improve this simple custom Textbox code?" }
7016
<p>Below is my code which I use to read data from a remote URL (which is GZipped), convert it to a <code>Map</code>, process the map (remove various unwanted fields, etc), the write it back to a file in JSON format.</p> <p>Unfortunately, it's ugly. I'm doing multiple things in the same method, but can't think of a good way to break them apart, as the input files can have hundreds of thousands of lines, so they will cause me to run out of memory quickly if I try to read in the whole thing, then process it, then output it.</p> <p>Can anyone offer any assistance/suggestions?</p> <pre><code>private void importTdatFile(String fileURL) { String filename = getFilename(fileURL) + ".gz"; try { URL url = new URL(fileURL); // set up input GZIPInputStream gzis; if (new File(filename).isFile()) { InputStream is = ClassLoader.getSystemResourceAsStream(fileURL); gzis = new GZIPInputStream(is); System.out.println("Using tdat header from classes directory"); } else { gzis = new GZIPInputStream(url.openStream()); } BufferedReader reader = new BufferedReader(new InputStreamReader(gzis)); // set up output BufferedWriter writer = new BufferedWriter(new FileWriter(catalog.getName() + ".json")); // create a template so I only have to create a map once Map&lt;String, String&gt; template = new LinkedHashMap&lt;String, String&gt;(catalog.getFieldData().size()); for (String fieldName : catalog.getFieldData().keySet()) { template.put(fieldName, null); } // start processing while (reader.ready()) { String line = reader.readLine(); if (line.matches("^(.*?\\|)*$")) { Map&lt;String, String&gt; result = new HashMap&lt;String, String&gt;(); String[] fieldNames = catalog.getFieldData().keySet().toArray(new String[]{}); String[] fieldValues = line.split("\\|"); for (int i = 0; i &lt; fieldValues.length; i++) { FieldData fd = catalog.getFieldData().get(fieldNames[i]); if (catalog.getFieldDataSet().contains(fd)) { result.put(fieldNames[i], fieldValues[i]); } } result = removeNulls(result); result = removeUnwantedFields(result, catalog); result = fixFieldPrefixes(result, catalog); result = fixFieldNames(result, catalog); writer.write(getJsonLine(result)); } } writer.close(); reader.close(); gzis.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } </code></pre>
[]
[ { "body": "<p>An idea:</p>\n\n<pre><code>private BufferedReader getReader(final String fileUrl) throws IOException {\n final String filename = getFilename(fileUrl) + \".gz\";\n final URL url = new URL(fileUrl);\n final InputStream stream;\n if (new File(filename).isFile()) {\n stream = ClassLoader.getSystemResourceAsStream(fileUrl);\n System.out.println(\"Using tdat header from classes directory\");\n } else {\n stream = url.openStream();\n }\n final GZIPInputStream gzipStream = new GZIPInputStream(stream);\n final InputStreamReader gzipStreamReader = \n new InputStreamReader(gzipStream, \"UTF-8\");\n final BufferedReader reader = new BufferedReader(gzipStreamReader);\n return reader;\n}\n</code></pre>\n\n<p>You don't have to <code>close</code> the <code>GZIPInputStream</code>, <a href=\"https://stackoverflow.com/questions/3628899/do-i-need-to-close-inputstream-after-i-close-the-reader\"><code>Reader.close()</code> does it</a>.</p>\n\n<hr>\n\n<p>I'd invert the condition inside the <code>while</code> loop:</p>\n\n<pre><code>// start processing\nwhile (reader.ready()) {\n final String line = reader.readLine();\n if (!line.matches(\"^(.*?\\\\|)*$\")) {\n continue;\n }\n Map&lt;String, String&gt; result = new HashMap&lt;String, String&gt;();\n ...\n}\n</code></pre>\n\n<p>It makes the code <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">flatten</a> which is easier to read.</p>\n\n<hr>\n\n<p>This code maybe unnecessary, since no one uses the <code>template</code>˛object:</p>\n\n<pre><code>// create a template so I only have to create a map once\nfinal Map&lt;String, String&gt; template = \n new LinkedHashMap&lt;String, String&gt;(catalog.getFieldData().size());\nfor (final String fieldName : catalog.getFieldData().keySet()) {\n template.put(fieldName, null);\n}\n</code></pre>\n\n<hr>\n\n<p>You should specify the charset when you call the constructor of the <code>InputStreamReader</code>.</p>\n\n<pre><code>final InputStreamReader gzipStreamReader = \n new InputStreamReader(gzipStream, \"UTF-8\");\n</code></pre>\n\n<p>Omitting it could lead to 'interesting' surprises, since it will use the default charset which varies from system to system.</p>\n\n<hr>\n\n<p>Here is the code after a few more method extractions. Check the comments please and feel free to ask if something isn't clear.</p>\n\n<pre><code>public void importTdatFile(final String fileUrl) throws MyAppException {\n try {\n doImport(fileUrl);\n } catch (final IOException e) {\n // MalformedURLException is a subclass of IOException\n throw new MyAppException(\"Cannot import\", e);\n }\n}\n\nprivate void doImport(final String fileUrl) throws IOException {\n BufferedReader reader = null;\n BufferedWriter writer = null;\n try {\n reader = getReader(fileUrl);\n writer = getWriter();\n\n while (reader.ready()) {\n final String line = reader.readLine();\n final Map&lt;String, String&gt; results = processLine(line);\n filterResults(results);\n final String jsonLine = getJsonLine(results);\n writer.write(jsonLine);\n }\n } finally {\n closeQuietly(reader);\n writer.close(); // do NOT ignore output errors\n }\n}\n\nprivate BufferedReader getReader(final String fileUrl) throws IOException {\n final InputStream stream = getStream(fileUrl);\n final BufferedReader reader = createGzipReader(stream);\n return reader;\n}\n\nprivate InputStream getStream(final String fileUrl) \n throws MalformedURLException, IOException {\n final InputStream stream;\n // I don't really like this 'if' here\n if (isGzipFile(fileUrl)) {\n // I'm not sure that the condition is correct for classpath loading\n // or not\n stream = ClassLoader.getSystemResourceAsStream(fileUrl);\n // I would put this println to somewhere else (after refactoring the 'if')\n System.out.println(\"Using tdat header from classes directory\");\n } else {\n final URL url = new URL(fileUrl);\n stream = url.openStream();\n }\n return stream;\n}\n\nprivate BufferedReader createGzipReader(final InputStream stream) \n throws IOException, UnsupportedEncodingException {\n final GZIPInputStream gzipStream = new GZIPInputStream(stream);\n final InputStreamReader gzipStreamReader = \n new InputStreamReader(gzipStream, \"UTF-8\");\n final BufferedReader reader = new BufferedReader(gzipStreamReader);\n return reader;\n}\n\nprivate boolean isGzipFile(final String fileUrl) {\n final String filename = getFilename(fileUrl) + \".gz\";\n return new File(filename).isFile();\n}\n\nprivate BufferedWriter getWriter() throws IOException {\n // TODO: FileWriter use the default character encoding (see javadoc),\n // maybe you should use a FileOutputStream with a specified encoding.\n final String outputFilename = getOutputFilename();\n final FileWriter fileWriter = new FileWriter(outputFilename);\n return new BufferedWriter(fileWriter);\n}\n\nprivate String getOutputFilename() {\n return catalog.getName() + \".json\";\n}\n\nprivate Map&lt;String, String&gt; processLine(final String line) {\n final Map&lt;String, String&gt; result = new HashMap&lt;String, String&gt;();\n if (!isProcessableLine(line)) {\n return result;\n }\n // It's hard to refactor without the internals of catalog.\n final String[] fieldValues = line.split(\"\\\\|\");\n\n for (int i = 0; i &lt; fieldValues.length; i++) {\n // TODO: possible ArrayIndexOutOfBoundsException here?\n final String fieldName = catalog.getFieldName(i);\n final FieldData fieldData = catalog.getFieldData(fieldName);\n if (catalog.fieldDataSetContains(fieldData)) {\n final String fieldValue = fieldValues[i];\n result.put(fieldName, fieldValue);\n }\n }\n\n return result;\n}\n\nprivate void filterResults(final Map&lt;String, String&gt; results) {\n removeNulls(results);\n // TODO: catalog probably a field, so it should be visible inside these\n // methods without passing them as a parameter\n removeUnwantedFields(results, catalog);\n fixFieldPrefixes(results, catalog);\n fixFieldNames(results, catalog);\n}\n\nprivate boolean isProcessableLine(final String line) {\n // TODO: A precompiled regexp maybe faster but it would be premature\n // optimization, so don't do that without profiling\n return line.matches(\"^(.*?\\\\|)*$\");\n}\n\nprivate void closeQuietly(final Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (final IOException e) {\n // TODO: log the exception with a logger instead of the\n // printStackTrace();\n e.printStackTrace();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Anyway, your streaming approach is fine, you shouldn't read the whole file into the memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T20:57:28.477", "Id": "10955", "Score": "0", "body": "I like your ideas and incorporated them, but I still don't like that I'm doing three separate things in one method: import from file, convert, and export to JSON. I've got an EventBus implemented for the application, but I'm reluctant to fire events from importer to converter to exporter, which seems to be overkill (and use alot of resources for large input files)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:12:41.587", "Id": "10960", "Score": "0", "body": "What do you think about the update? Now almost every method has single responsibility. For example, `doImport` controls the conversion while the called methods do the low-level work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:00:03.877", "Id": "10993", "Score": "0", "body": "Nice. I didn't quite do everything you suggested, but did the majority. I had also not mentioned that importTdatFile() was one of a couple of import methods for file types. I ended up implementing a strategy pattern for processLine(). The current version of the file is at https://github.com/dartmanx/HEASARC-Utilities/blob/0.2.0/catalogparser/src/main/java/org/jason/heasarcutils/catalogparser/util/io/DataManager.java. Thanks for the help." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T19:44:54.307", "Id": "7030", "ParentId": "7027", "Score": "1" } } ]
{ "AcceptedAnswerId": "7030", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T18:17:49.283", "Id": "7027", "Score": "2", "Tags": [ "java" ], "Title": "Converting input from a FileReader to JSON and outputting it again" }
7027
<p>I have a data structure that looks like this:</p> <pre><code>a = { 'red': ['yellow', 'green', 'purple'], 'orange': ['fuschia'] } </code></pre> <p>This is the code I write to add new elements:</p> <pre><code>if a.has_key(color): a[color].append(path) else: a[color] = [path] </code></pre> <p>Is there a shorter way to write this?</p>
[]
[ { "body": "<p>You can use <a href=\"http://docs.python.org/library/collections.html\">collections.defaultdict</a>:</p>\n\n<pre><code>from collections import defaultdict\n\nmydict = defaultdict(list)\n</code></pre>\n\n<p>Now you just need:</p>\n\n<pre><code>mydict[color].append(path)\n</code></pre>\n\n<p><code>defaultdict</code> is a subclass of <code>dict</code> that can be initialized to a list, integer... </p>\n\n<hr>\n\n<p>btw, the use of <code>has_key</code> is discouraged, and in fact <code>has_key</code> has been removed from python 3.2.<br>\nWhen needed, use this by far more pythonic idiom instead:</p>\n\n<pre><code>if color in a:\n ........\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:58:16.137", "Id": "10965", "Score": "0", "body": "even better is\ntry:\n a[color].append(path)\nexcept KeyError:\n a[color] = [path]\n\n... and this comment formatting is broken :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T21:24:35.880", "Id": "11131", "Score": "1", "body": "@blaze try/except is better? I'd say not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T13:11:16.023", "Id": "11160", "Score": "0", "body": "if try is usually successful and exception isn't raised - it's effective. one less \"if\" to check." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T15:39:10.923", "Id": "11169", "Score": "0", "body": "lots of stuff happening around checking whether operation goes right and whether exception is thrown. besides the semantics of \"exception\" should be that something, well, exceptional is taking place. I'd avoid using exceptions for regular code flow if a convenient alternative exists" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T19:22:25.153", "Id": "7029", "ParentId": "7028", "Score": "7" } } ]
{ "AcceptedAnswerId": "7029", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T19:15:31.217", "Id": "7028", "Score": "1", "Tags": [ "python" ], "Title": "Shorter way to write list-as-dict-value in Python?" }
7028
<p>On my webform, there are two kinds of address-fields a user can give. But since it's a complex webform (Drupal) it's kind of hard to achieve. Every time a user adds an extra address, the form is regenerated and there will be a new item added to the <code>$address_afl</code> and <code>$address_bev</code>-array. Is it possible to compress this code so the foreach-loop starts looping with the highest value (either <code>$address_afl</code> or<code>$address_bev</code> ) </p> <pre><code>$address_afl = $form['field_afl_dienst_adressen']['und']; $i = 0; foreach($address_afl as $value) { if (is_array($value)) { $test = array_keys($value); if(is_array($test)) { foreach ($test as $z) { if (strpos($z, '#') === 0) continue; if (isset($form['field_afl_dienst_adressen']['und'][$i][$z])) { $form['field_afl_dienst_adressen']['und'][$i][$z]['#prefix'] = "&lt;div class='address-publicatie-$z'&gt;"; $form['field_afl_dienst_adressen']['und'][$i][$z]['#suffix'] = "&lt;/div&gt;"; } } } } $i++; } $address_bev = $form['field_bevoegde_adressen']['und']; $i = 0; foreach($address_bev as $value) { if (is_array($value)) { $test = array_keys($value); if(is_array($test)) { foreach ($test as $z) { if (strpos($z, '#') === 0) continue; if (isset($form['field_afl_dienst_adressen']['und'][$i][$z])) { $form['field_bevoegde_adressen']['und'][$i][$z]['#prefix'] = "&lt;div class='address-publicatie-$z'&gt;"; $form['field_bevoegde_adressen']['und'][$i][$z]['#suffix'] = "&lt;/div&gt;"; } } } } $i++; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T01:12:19.763", "Id": "10958", "Score": "2", "body": "Can you merge your two $address_ arrays into a single array? Maybe generalize this code into a function that takes the form name as a parameter, this way your loop is programed once and called twice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T11:48:10.470", "Id": "10971", "Score": "1", "body": "Your indentation is confusing, Your second `if` is should not be at the same level as the first. However, array_keys always returns an array so you don't need the second `if` and they should be deleted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T07:46:36.430", "Id": "11011", "Score": "0", "body": "@Paul, I needed to check if they variable is an array for avoiding some NOTICE-messages..." } ]
[ { "body": "<p>I don't quite exactly understand the logic, but you could extract out at least one method which removes lots of code duplication. I've inverted some conditions (which improves code readability) and placed some comments into the code too.</p>\n\n<pre><code>function processValue(&amp;$form, $value, $i, &amp;$form_sub) {\n if (!is_array($value)) {\n return;\n }\n\n // TODO: rename test to $keys or something more meaningful\n $test = array_keys($value);\n if (!is_array($test)) {\n // TODO: is it possible? according to the documentation \n // array_keys() always returns array \n return;\n }\n foreach ($test as $z) {\n if (strpos($z, '#') === 0) {\n continue;\n }\n if (!isset($form['field_afl_dienst_adressen']['und'][$i][$z])) {\n continue;\n }\n $form_sub[$i][$z]['#prefix'] = \"&lt;div class='address-publicatie-$z'&gt;\";\n $form_sub[$i][$z]['#suffix'] = \"&lt;/div&gt;\";\n }\n}\n\n\n$address_afl = $form['field_afl_dienst_adressen']['und'];\n$i = 0;\nforeach($address_afl as $value) {\n processValue($form, $value, $i, $form['field_afl_dienst_adressen']['und']);\n $i++;\n}\n\n$address_bev = $form['field_bevoegde_adressen']['und'];\n$i = 0;\nforeach($address_bev as $value) {\n processValue($form, $value, $i, $form['field_bevoegde_adressen']);\n $i++;\n}\n</code></pre>\n\n<hr>\n\n<p>A possible bug: both <code>foreach</code> has the following condition with the same <code>$form</code> index:</p>\n\n<pre><code>if (isset($form['field_afl_dienst_adressen']['und'][$i][$z])) ...\n</code></pre>\n\n<p>Maybe you want to change the second one to</p>\n\n<pre><code>if (isset($form['field_bevoegde_adressen']['und'][$i][$z])) ...\n</code></pre>\n\n<p>It would make possible some other refactorings (fewer parameters etc.), as <em>Victor T.</em> suggested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T21:40:08.263", "Id": "7056", "ParentId": "7031", "Score": "2" } }, { "body": "<p>You should be able to factor all those duplicates down into 2 function calls. </p>\n\n<p>I think palacsint's observation is correct that <code>$test</code> is always an array here. In fact, I'm not sure I see why you don't just use the keys in <code>$value</code> directly. It doesn't appear the keys get changed in the loop.</p>\n\n<pre><code>if (is_array($value)) {\n $test = array_keys($value);\nif(is_array($test)) {\n foreach ($test as $z) {\n</code></pre>\n\n<p>This refactor is similar to palacsint's suggestion but taken further.</p>\n\n<pre><code>function name_needed(&amp;$addr_src)\n{\n $i = -1;\n foreach($addr_src as $next) \n {\n ++$i;\n if (!is_array($next)) continue;\n\n foreach($next as $z =&gt; $_) \n {\n if (strpos($z, '#') === 0 || !isset($addr_src[$i][$z])) continue;\n\n $addr_src[$i][$z]['#prefix'] = \"&lt;div class='address-publicatie-$z'&gt;\";\n $addr_src[$i][$z]['#suffix'] = \"&lt;/div&gt;\";\n }\n }\n}\n\nname_needed($form['field_afl_adressen']['und']);\nname_needed($form['field_bevoegde_adressen']['und']);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T10:47:01.460", "Id": "11015", "Score": "0", "body": "I've also thought of moving a little bit further, but in both `foreach` the if condition uses the *same* key. Check my update for the details." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T02:29:41.160", "Id": "7058", "ParentId": "7031", "Score": "1" } } ]
{ "AcceptedAnswerId": "7056", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T19:59:47.317", "Id": "7031", "Score": "4", "Tags": [ "php" ], "Title": "If statement with 2 conditions" }
7031
<p>I often end up working with systems where the data is delivered with some <code>Id</code> property and possibly a <code>parentId</code> prop, but never do anyone tempt to actually give me a nice recursive object to play with.</p> <p>Now, the code below is merely a suggestion in how to solve these kind of "problems", I've created the <code>FlatObject</code> to simulate an incoming with data.</p> <pre><code>class Program { static void Main(string[] args) { // Fill list with sample data List&lt;FlatObject&gt; flatObjects = new List&lt;FlatObject&gt; { new FlatObject(1,0), new FlatObject(2,0), new FlatObject(3,0), new FlatObject(4,0), new FlatObject(5,1), new FlatObject(6,2), new FlatObject(7,6), new FlatObject(8,6) }; // call the recursive method var recursiveObjects = FillRecursive(flatObjects, 0); } private static List&lt;RecursiveObject&gt; FillRecursive(List&lt;FlatObject&gt; flatObjects, int parentId) { List&lt;RecursiveObject&gt; recursiveObjects = new List&lt;RecursiveObject&gt;(); foreach (var item in flatObjects.Where(x =&gt; x.ParentId.Equals(parentId))) { recursiveObjects.Add(new RecursiveObject { Id = item.Id, ParentId = item.ParentId, Children = FillRecursive(flatObjects, item.Id) }); } return recursiveObjects; } } public class FlatObject { public int Id { get; set; } public int ParentId { get; set; } public FlatObject(int id, int parentId) { Id = id; ParentId = parentId; } } public class RecursiveObject { public int Id { get; set; } public int ParentId { get; set; } public List&lt;RecursiveObject&gt; Children { get; set; } } </code></pre> <p>I am aware of some Linq alternatives to solve the <code>foreach</code> loop but that does hardly not change the approach of this.</p> <pre><code>private static List&lt;RecursiveObject&gt; FillRecursive(List&lt;FlatObject&gt; flatObjects, int parentId) { return flatObjects.Where(x =&gt; x.ParentId.Equals(parentId)).Select(item =&gt; new RecursiveObject { Id = item.Id, ParentId = item.ParentId, Children = FillRecursive(flatObjects, item.Id) }).ToList(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T23:39:26.780", "Id": "10956", "Score": "4", "body": "Looks beautiful. I would have used the term 'hierarchical' rather than 'recursive' in many places, however. Including the title." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:40:32.417", "Id": "11004", "Score": "0", "body": "Don't mean to nit-pick, but just trying to point out some potential issues. This approach works when your data has a single root (ParentId: 0). If your data happens to have multiple distinct roots (a disconnected graph), though, then I think you'll miss some of the data. It looks like circular references would probably cause infinite recursion (stack overflow exception)." } ]
[ { "body": "<p>You could, perhaps, derive RecursiveObject from FlatObject.</p>\n\n<p>In the degenerate case in which all objects belong to a single lineage (every object has one and only one child, except the last one) and you have <strong>lots</strong> of objects, then your recursive method will try to use an awful lot of stack space, possibly failing with a stack overflow exception. The way to correct this is by avoiding recursion and adding a stack data structure within your function, which then works in a loop. But of course you would not want to do that unless there is a very clear possibility of such a degenerate case ever occurring. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T23:46:32.977", "Id": "7033", "ParentId": "7032", "Score": "1" } }, { "body": "<p>I'm a fan of <a href=\"http://blogs.msdn.com/b/ericlippert/archive/tags/immutability/\" rel=\"nofollow\">immutable objects</a> and <a href=\"http://msdn.microsoft.com/en-us/library/bb384062.aspx\" rel=\"nofollow\">collection initializer</a> syntax, myself:</p>\n\n<pre><code> private static void Main()\n {\n // Fill list with sample data\n FlatObjectList flatObjects = new FlatObjectList\n {\n { 1, 0 }, { 2, 0 }, { 3, 0 }, { 4, 0 }, { 5, 1 }, { 6, 2 }, { 7, 6 }, { 8, 6 }\n };\n\n // call the recursive method\n RecursiveObjectList recursiveObjects = FillRecursive(flatObjects, 0);\n }\n\n private static RecursiveObjectList FillRecursive(IEnumerable&lt;FlatObject&gt; flatObjects, int parentId)\n {\n return new RecursiveObjectList(flatObjects\n .Where(x =&gt; x.ParentId.Equals(parentId))\n .Select(item =&gt; new RecursiveObject(item.Id, item.ParentId, FillRecursive(flatObjects, item.Id))));\n }\n}\n\npublic sealed class FlatObjectList : List&lt;FlatObject&gt;\n{\n public void Add(int id, int parentId)\n {\n this.Add(new FlatObject(id, parentId));\n }\n}\n\npublic sealed class RecursiveObjectList : List&lt;RecursiveObject&gt;\n{\n public RecursiveObjectList(IEnumerable&lt;RecursiveObject&gt; list)\n {\n this.AddRange(list);\n }\n\n public void Add(int id, int parentId, RecursiveObjectList children)\n {\n this.Add(new RecursiveObject(id, parentId, children));\n }\n}\n\npublic sealed class FlatObject\n{\n private readonly int id;\n\n private readonly int parentId;\n\n public int Id { get { return this.id; } }\n\n public int ParentId { get { return this.parentId; } }\n\n public FlatObject(int id, int parentId)\n {\n this.id = id;\n this.parentId = parentId;\n }\n}\n\npublic sealed class RecursiveObject\n{\n private readonly int id;\n\n private readonly int parentId;\n\n private readonly ReadOnlyCollection&lt;RecursiveObject&gt; children;\n\n public RecursiveObject(int id, int parentId, IList&lt;RecursiveObject&gt; children)\n {\n this.id = id;\n this.parentId = parentId;\n this.children = new ReadOnlyCollection&lt;RecursiveObject&gt;(children);\n }\n\n public int Id { get { return this.id; } }\n\n public int ParentId { get { return this.parentId; } }\n\n public ReadOnlyCollection&lt;RecursiveObject&gt; Children { get { return this.children; } }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T09:44:04.250", "Id": "10967", "Score": "1", "body": "I am also a big fan of immutable objects and readonly members, but what is the point in adding accessor properties for readonly members?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T13:56:49.627", "Id": "10974", "Score": "0", "body": "So anyone who uses those objects can read them, yes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:15:04.400", "Id": "10975", "Score": "1", "body": "Sorry, my mistake, I did not word the question properly. Let me put it another way: Given that the members are readonly, why make them private? Make them public and you do not have to provide accessor properties for them! The \"All thy members shall be private\" clause sounds like a religious doctrine to me, superstitiously followed by people for no good reason: if it is readonly, it does not have to be private!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:24:29.620", "Id": "10976", "Score": "1", "body": "The best practice is to have all external access be through property accessors in the case the internals of your object need to change in the future. In one example, I can change the internal type of `id` to a `string`, but as long as the accessor can convert it to an `int`, the contract is intact. If I expose the field directly, I a) don't have that luxury and b) cannot ensure binary compatibility any more with my callers without a recompile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:32:33.420", "Id": "10977", "Score": "0", "body": "I will buy the binary compatibility part. The other part about the luxury does not apply because at any moment you wish you can turn the field into a property and nobody outside your class will notice. And since binary compatibility is a rather rarely occurring practical consideration, I would rather make that the special case, and consider the norm to be the simpler case: \"if readonly, then public is fine\". I think this ought to be the subject of a separate question. I am looking right now to see if it has been asked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:38:28.143", "Id": "10978", "Score": "0", "body": "Don't take my word for it, let's ask noted C# guru Jon Skeet: http://stackoverflow.com/a/1272535/3312 and http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:45:45.190", "Id": "10980", "Score": "1", "body": "I see, the question has already been Skeeted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:52:00.413", "Id": "10992", "Score": "0", "body": "Hmm, will this be faster?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:48:25.157", "Id": "10997", "Score": "0", "body": "I would say this falls under one of those \"it doesn't matter unless you're doing millions of operations\" scenarios. Measure both approaches and see what you get." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:27:29.693", "Id": "10998", "Score": "0", "body": "@MikeNakis - The readonly keyword restricts your code from modifying the fields outside of the constructor. This would be a problem if, for instance, you wanted to put an AddChild or RemoveChild method on the RecursiveObject class, assuming that the AddChild and RemoveChild method would be responsible for ensuring that the child's ParentId property is properly assigned after being added/removed. You could also lazily initialize the Children property so that you only create a list object if there are actually children." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T23:58:13.253", "Id": "7034", "ParentId": "7032", "Score": "1" } }, { "body": "<p>Below is the code for my approach. A benefit is that the heirarchy goes both ways; up and down. While the parent object contains a list of child objects, each child has a reference to the parent object.</p>\n\n<p>Some differences from your original setup:</p>\n\n<ul>\n<li>The ParentId property on FlatObject is nullable, so objects that have no parent will have null.</li>\n<li>The Children property on RecursiveObject is IEnumerable instead of List. This prevents consumers from modifying the contents of the list. If you want to allow consumers to add/remove items from the list, then RecursiveObject should expose methods to perform those actions so that you can make sure that the Parent property is properly assigned when a child is added/removed.</li>\n<li>I've made the Id, Parent, and Children properties on RecursiveObject read-only. This certainly isn't necessary, but you can do that if desired. This is the reason why I made the FlatObjectsToRecursiveObjects method as a static method of the RecursiveObjects class; so that it can have access to the private property setters.</li>\n</ul>\n\n<p>The gist of this approach is that we first convert the FlatObjects to RecursiveObjects and store them in a dictionary keyed by the Id. Then, we do another pass over the FlatObjects in order to assign the Parent and Children properties of each RecursiveObject, using the dictionary to perform the necessary look-ups with the FlatObject's Id and ParentId properties.</p>\n\n<pre><code>class FlatObject\n{\n public int Id { get; set; }\n public int? ParentId { get; set; }\n}\n\nclass RecursiveObject\n{\n public int Id { get; private set; }\n public RecursiveObject Parent { get; private set; }\n public IEnumerable&lt;RecursiveObject&gt; Children { get; private set; }\n\n public static IEnumerable&lt;RecursiveObject&gt; FlatObjectsToRecursiveObjects(IEnumerable&lt;FlatObject&gt; flatObjects)\n {\n // convert flat objects into heirarchial objects and store them in a dictionary keyed with the object's Id\n var recursiveObjectsById = flatObjects.Select(item =&gt; new RecursiveObject { Id = item.Id }).ToDictionary(item =&gt; item.Id);\n\n // group flat objects by their ParentId\n var flatObjectsGroupedByParentId = flatObjects.Where(item =&gt; item.ParentId.HasValue).GroupBy(item =&gt; item.ParentId.Value);\n foreach (var group in flatObjectsGroupedByParentId)\n {\n // find each group's parent object\n RecursiveObject parent;\n if (recursiveObjectsById.TryGetValue(group.Key, out parent))\n {\n // convert the group of flat objects to a list of heirarchial objects by looking up the correct heirarchial object from the dictionary\n parent.Children = group.Select(item =&gt; recursiveObjectsById[item.Id]).ToList();\n\n // assign the parent object to each child object\n foreach (var child in parent.Children)\n {\n child.Parent = parent;\n }\n }\n else\n {\n // something's wrong!!! ParentId refers to a non-existant object.\n }\n }\n\n return recursiveObjectsById.Values;\n }\n}\n</code></pre>\n\n<p>EDIT: Added an \"improved\" version of my original approach, shown below. The following implementation provides the following benefits:</p>\n\n<ul>\n<li>The Children property on RecursiveObject never returns a null, but it still retains the \"benefit\" of lazy initialization. The Children property getter checks if the _Children field is null, and if so it returns the default instance of the <code>EmptyEnumerable&lt;RecursiveObject&gt;</code> class (code included).</li>\n<li>Children can now be added/removed using the new AddChild, RemoveChild, and AddChildren methods on RecursiveObject.</li>\n<li>The FlatObjectsToRecursiveObjects method is slightly simpler now because it utilizes the new AddChildren method.</li>\n<li>The FlatObjectsToRecursiveObjects method no longer has to be a member of the RecursiveObject class, since it does not access any private details of the class.</li>\n<li><p>My setup code includes a second root (<code>new FlatObject(9,-1)</code>) and circular references (<code>new FlatObject(10,10)</code> and <code>new FlatObject(0,2)</code>), just to verify that the implementation can handle these special cases.</p>\n\n<pre><code>class FlatObject\n{\n public int Id { get; set; }\n public int? ParentId { get; set; }\n\n public FlatObject(int id)\n {\n this.Id = id;\n }\n\n public FlatObject(int id, int parentId)\n : this(id)\n {\n this.ParentId = parentId;\n }\n}\n\nclass RecursiveObject\n{\n public int Id { get; private set; }\n public RecursiveObject Parent { get; private set; }\n private List&lt;RecursiveObject&gt; _Children;\n\n public IEnumerable&lt;RecursiveObject&gt; Children\n {\n get\n {\n IEnumerable&lt;RecursiveObject&gt; value = _Children;\n if (value == null)\n value = EmptyEnumerable&lt;RecursiveObject&gt;.Default;\n return value;\n }\n }\n\n public RecursiveObject(int id)\n {\n this.Id = id;\n }\n\n public void AddChild(RecursiveObject child)\n {\n if (_Children == null)\n _Children = new List&lt;RecursiveObject&gt;();\n _Children.Add(child);\n child.Parent = this;\n }\n\n public bool RemoveChild(RecursiveObject child)\n {\n if (_Children != null)\n {\n bool removed = _Children.Remove(child);\n if (removed)\n child.Parent = null;\n return removed;\n }\n else\n {\n return false;\n }\n }\n\n public void AddChildren(IEnumerable&lt;RecursiveObject&gt; children)\n {\n if (children == null)\n throw new ArgumentNullException(\"children\");\n\n if (_Children == null)\n _Children = new List&lt;RecursiveObject&gt;(children);\n else\n _Children.AddRange(children);\n\n foreach (var child in children)\n {\n child.Parent = this;\n }\n }\n}\n\nclass Program\n{\n public static IEnumerable&lt;RecursiveObject&gt; FlatObjectsToRecursiveObjects(IEnumerable&lt;FlatObject&gt; flatObjects)\n {\n // convert flat objects into heirarchial objects and store them in a dictionary keyed with the object's Id\n var recursiveObjectsById = flatObjects.Select(item =&gt; new RecursiveObject(item.Id)).ToDictionary(item =&gt; item.Id);\n\n // group flat objects by their ParentId\n var flatObjectsGroupedByParentId = flatObjects.Where(item =&gt; item.ParentId.HasValue).GroupBy(item =&gt; item.ParentId.Value);\n foreach (var group in flatObjectsGroupedByParentId)\n {\n // find each group's parent object\n RecursiveObject parent;\n if (recursiveObjectsById.TryGetValue(group.Key, out parent))\n {\n // convert the group of flat objects to a list of heirarchial objects by looking up the correct heirarchial object from the dictionary\n parent.AddChildren(group.Select(item =&gt; recursiveObjectsById[item.Id]));\n }\n else\n {\n // something's wrong!!! ParentId refers to a non-existant object.\n }\n }\n\n return recursiveObjectsById.Values;\n }\n\n static void Main(string[] args)\n {\n List&lt;FlatObject&gt; flatObjects = new List&lt;FlatObject&gt;()\n {\n new FlatObject(1,0),\n new FlatObject(2,0),\n new FlatObject(3,0),\n new FlatObject(4,0),\n new FlatObject(5,1),\n new FlatObject(6,2),\n new FlatObject(7,6),\n new FlatObject(8,6),\n new FlatObject(9,-1),\n new FlatObject(10,10),\n new FlatObject(0,2),\n };\n\n var recursiveObjects = FlatObjectsToRecursiveObjects(flatObjects).ToList();\n }\n}\n\n#region Universal Code\n\nclass EmptyEnumerator&lt;T&gt; : IEnumerator&lt;T&gt;\n{\n public static readonly EmptyEnumerator&lt;T&gt; Default = new EmptyEnumerator&lt;T&gt;();\n\n public T Current\n {\n get { throw new InvalidOperationException(); }\n }\n\n public void Dispose()\n {\n }\n\n object System.Collections.IEnumerator.Current\n {\n get { throw new InvalidOperationException(); }\n }\n\n public bool MoveNext()\n {\n return false;\n }\n\n public void Reset()\n {\n }\n}\n\nclass EmptyEnumerable&lt;T&gt; : IEnumerable&lt;T&gt;\n{\n public static readonly EmptyEnumerable&lt;T&gt; Default = new EmptyEnumerable&lt;T&gt;();\n\n public IEnumerator&lt;T&gt; GetEnumerator()\n {\n return EmptyEnumerator&lt;T&gt;.Default;\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n}\n\n#endregion\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:52:37.177", "Id": "7054", "ParentId": "7032", "Score": "5" } } ]
{ "AcceptedAnswerId": "7054", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T23:09:07.797", "Id": "7032", "Score": "5", "Tags": [ "c#", "linq", "recursion" ], "Title": "Recursive method turning flat structure to recursive" }
7032
<p>First time I'm using stackexchange. I'm in 8th standard. I tried to implement Queue in Java. I wrote something like this> Right now I'm not able to test it because I don't have JVM in my machine. So I just wanted to know Is this correct implementation? Am I going in the right direction? </p> <pre><code> import java.lang.*; import java.util.*; public class Queue { public static void main(string[] args) { LinkedList l1=new LinkedList(); InputstreamReaderir=new InputstreamReader(System.in); BufferReader bf=new BufferReader(ir); System.out.println("Enter the number of elements to be inserted into queue"); string str; str=bf.readline(); System.out.println("Enter your Choice: "); System.out.println("1-&gt;Insert 2-&gt;Delete 3-&gt;Display 3-&gt;Exit"); string choice; choice.readline(); for(;;) { switch { case 1:l1.insertrear(); break; case 2:l1.deletefront(); break; case 3: system.out("Contents of Queue are:" +l1); break; default: exit; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T11:01:10.533", "Id": "10970", "Score": "2", "body": "you might find http://ideone.com helpful if you don't have a proper dev environment setup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T15:45:08.007", "Id": "10983", "Score": "1", "body": "I don't really see a \"queue\" implementation here. You initialize a regular `LinkedList` and then attempt to call methods on it that don't exist." } ]
[ { "body": "<p>It needs some improvement but you're definitely in the right direction. There are some typos (<code>string</code> should be <code>String</code>, for example) but I'm sure that you will be able to fix them.</p>\n\n<p>Just two notes:</p>\n\n<p>1, Here maybe you want to read some initial elements:</p>\n\n<pre><code>System.out.println(\"Enter the number of elements to be inserted into queue\");\nstring str;\nstr=bf.readline();\n</code></pre>\n\n<p>2, The menu printing, input reading logic currently runs only once.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:40:09.887", "Id": "7037", "ParentId": "7035", "Score": "1" } }, { "body": "<p>you're on the right track with using a <code>LinkedList</code>, this is one of the easiest ways to implement your own <code>Queue</code> - <strong>I hope this is an exercise, since you should otherwise use Java's built-in <code>Queue</code>.</strong></p>\n\n<p>I must confess I found your question interesting and decided to write a Queue so as to demonstrate. Note that you <strong>should create a class</strong> for your custom <code>Queue</code>. If you implement the whole thing in <code>main</code>, there'll be no way to <em>reuse</em> the code.</p>\n\n<p>So you'd create a new file, let's call it <code>Queue.java</code>. It would look something like this:</p>\n\n<pre><code>import java.util.*;\n\npublic class Queue&lt;T&gt; implements Iterable&lt;T&gt; {\n\n private LinkedList&lt;T&gt; elements = new LinkedList&lt;T&gt;();\n\n public void enqueue(T element) {\n elements.add(element);\n }\n\n public T dequeue() {\n return elements.removeFirst();\n }\n\n public T peek() {\n return elements.getFirst();\n }\n\n public void clear() {\n elements.clear();\n }\n\n public int size() {\n return elements.size();\n }\n\n public boolean isEmpty() {\n return elements.isEmpty();\n }\n\n @Override\n public Iterator&lt;T&gt; iterator() {\n return elements.iterator();\n }\n}\n</code></pre>\n\n<p>Notice that that the code is <em>extremely</em> simple - no method's implementation is longer than one line. However, I don't know your level of experience so there might be two weird things in here: the use of <a href=\"http://www.java2s.com/Tutorial/Java/0200__Generics/Catalog0200__Generics.htm\" rel=\"nofollow\">Generics</a> and the <code>implements Iterable&lt;T&gt;</code>.</p>\n\n<h3><a href=\"http://docs.oracle.com/javase/tutorial/java/generics/index.html\" rel=\"nofollow\">Generics</a></h3>\n\n<p>The <code>&lt;T&gt;</code> means you can put any Java object into the <code>Queue</code><em>keeping Type safety</em>.\nThis means, when you call <code>Queue.Dequeue()</code>, the result will still have the same type that it had when you <code>Enqueued</code>\nit.</p>\n\n<h3><a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Iterable.html\" rel=\"nofollow\"><code>Iterable&lt;T&gt;</code></a></h3>\n\n<p>Oracle says:</p>\n\n<blockquote>\n <p>Implementing this interface allows an object to be the target of the <code>foreach</code> statement.</p>\n</blockquote>\n\n<p>Note that you don't need to know more, because we simply delegate this responsibility to <code>LinkedList.iterator()</code> which does the work for us.</p>\n\n<p>Below is some code to test your new Queue. Play around with it. You can add other queue tests to <code>main</code>, for instance: </p>\n\n<pre><code>testQueue(true, false, true, true);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>testQueue(0.5, 3.6, -5.4, 0.0);\n</code></pre>\n\n<p>to test putting different types of data into your <code>Queue</code>.<br>\nIf anything remains unclear, feel free to leave a comment, and I'll update my answer.</p>\n\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n testQueue(1, 2, 3, 4, 5);\n testQueue(\"first\", \"second\", \"third\");\n }\n\n private static &lt;T&gt; void testQueue(T... elements) {\n outputLine(\"testing a Queue&lt;%s&gt;\", getClassOf(elements));\n Queue&lt;T&gt; queue = new Queue&lt;T&gt;();\n outputSize(queue);\n enqueueElementsInto(queue, elements);\n outputSize(queue);\n loopOverAllElementsOf(queue);\n dequeueAllFrom(queue);\n outputSize(queue);\n outputLine(\"---\");\n }\n\n private static &lt;T&gt; void outputSize(Queue&lt;T&gt; queue) {\n outputLine(\"empty: %s, size: %s elements\", queue.isEmpty(), queue.size());\n }\n\n private static &lt;T&gt; void enqueueElementsInto(Queue&lt;T&gt; queue, T... elements) {\n outputLine(\"enqueueing: \");\n for (T element : elements) {\n queue.enqueue(element);\n output(element + \" \");\n }\n }\n\n private static &lt;T&gt; void loopOverAllElementsOf(Queue&lt;T&gt; queue) {\n outputLine(\"Queue contains: \");\n for (T element : queue) {\n output(element + \" \");\n }\n }\n\n private static &lt;T&gt; void dequeueAllFrom(Queue&lt;T&gt; queue) {\n outputLine(\"dequeueing: \");\n while (!queue.isEmpty()) {\n T next = queue.peek();\n T dequeued = queue.dequeue();\n outputLine(\"expected: %s \", next);\n output(\"dequeued: %s \", dequeued);\n }\n }\n\n private static void outputLine(String format, Object... params) {\n output('\\n' + format, params);\n }\n\n private static void output(String format, Object... params) {\n System.out.print(String.format(format, params));\n }\n\n private static &lt;T&gt; String getClassOf(T... elements) {\n String nameOfArray = elements.getClass().getSimpleName();\n return nameOfArray.substring(0, nameOfArray.length() - 2);\n }\n}\n</code></pre>\n\n<p>output:</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>testing a Queue&lt;Integer&gt;\nempty: true, size: 0 elements\nenqueueing: 1 2 3 4 5 \nempty: false, size: 5 elements\nQueue contains: 1 2 3 4 5 \ndequeueing: \nexpected: 1 dequeued: 1 \nexpected: 2 dequeued: 2 \nexpected: 3 dequeued: 3 \nexpected: 4 dequeued: 4 \nexpected: 5 dequeued: 5 \nempty: true, size: 0 elements\n---\ntesting a Queue&lt;String&gt;\nempty: true, size: 0 elements\nenqueueing: first second third \nempty: false, size: 3 elements\nQueue contains: first second third \ndequeueing: \nexpected: first dequeued: first \nexpected: second dequeued: second \nexpected: third dequeued: third \nempty: true, size: 0 elements\n---\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T17:48:04.473", "Id": "11299", "Score": "1", "body": "Very nice, but I would have liked to let student do a bit more of his homework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T17:55:33.623", "Id": "11300", "Score": "1", "body": "@Chris thank you. Well, I just couldn't resist, I hadn't created a generic type in Java yet nor had I tried a simple Queue... curiosity got the better of me. Anyway, he'll have a hard time explaining this to his teacher if he doesn't understand it ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T15:05:09.857", "Id": "7223", "ParentId": "7035", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T07:22:02.017", "Id": "7035", "Score": "3", "Tags": [ "java", "queue" ], "Title": "Queue Implementation" }
7035
<p>I am interested in seeing how people would refactor this code to make it more readable, remove local variables, etc. The code checks a string against a number of arrays. The first (0) field of each array is the root word and the rest of the words are its synonyms. The idea is to replace any word in the user-provided string with the root word or provide the user-supplied word if none were found.</p> <pre><code>import java.util.Arrays; public class Synonymiser { private final static int ROOT_WORD = 0; private String[][] mSynonyms; public Synonymiser(String[]... synonyms) { super(); this.mSynonyms = synonyms; } public String normaliseString(String inStr){ String[] inArr = inStr.split(" "); boolean matchFound; for (int i = 0; i &lt; inArr.length; i++){ matchFound=false; for (String[] synonymArr : mSynonyms){ for(int j = 0 ; j &lt; synonymArr.length; j++){ if (inArr[i].equalsIgnoreCase(synonymArr[j])){ inArr[i] = synonymArr[ROOT_WORD]; matchFound = true; } if (matchFound) break; } if (matchFound) break; } } return Arrays.toString(inArr); } public static void main(String [] args){ String[] ar1 = new String[] {"one", "two", "three", "four", "five"}; String[] ar2 = new String[] {"six", "seven", "eight"}; Synonymiser s = new Synonymiser(ar1, ar2); System.out.println(s.normaliseString("one two seven bulb")); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:27:36.477", "Id": "10961", "Score": "0", "body": "I'd start with _consistent_ indentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:31:18.393", "Id": "10962", "Score": "0", "body": "sorry that's more to do with me making it display as code on this site, it's got standard eclipse indentation in my project" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T08:47:11.310", "Id": "10964", "Score": "0", "body": "Part of the problem as it seems is that you have mixed spaces and tabs for your indentation. Choose one or the other. Once you do that, you'll make a lot of people happy. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T09:23:52.703", "Id": "10966", "Score": "0", "body": "The `for (int j = 0;` loop can be replaced with a `for (String possibleSynonym : synonymArr)`" } ]
[ { "body": "<p>1, You could eliminate the <code>matchFound</code> flag if you create a label for your outer <code>for</code> loop and call <code>break</code> with this label:</p>\n\n<pre><code>matchLoop: for (final String[] synonymArr : mSynonyms) {\n for (int j = 0; j &lt; synonymArr.length; j++) {\n if (inArr[i].equalsIgnoreCase(synonymArr[j])) {\n inArr[i] = synonymArr[ROOT_WORD];\n break matchLoop;\n }\n }\n}\n</code></pre>\n\n<p>Anyway, I think using labels is more or less bad smell, so try to extract out the loops to separate methods.</p>\n\n<p>2, I'd create at least a <code>Word</code> class which stores the (root)word and its synonyms. I should result more readable the code in the <code>Synonymiser</code> class too:</p>\n\n<pre><code>public class Word {\n\n private final String rootWord;\n\n private final Set&lt;String&gt; synomins;\n\n public Word(final String rootWord, final Collection&lt;String&gt; synomins) {\n super();\n // TODO: empty String/null check\n this.rootWord = rootWord;\n // TODO: convert the input to lowercase (it helps contains())\n this.synomins = new HashSet&lt;String&gt;(synomins);\n this.synomins.add(rootWord);\n }\n\n public static Word createWord(final String rootWord, final String... synonims) {\n final List&lt;String&gt; synonimList = Arrays.asList(synonims);\n return new Word(rootWord, synonimList);\n }\n\n public boolean contains(final String word) {\n // TODO: convert word to lowercase for proper comparison\n if (synomins.contains(word)) {\n return true;\n }\n return false;\n }\n\n public String getRootWord() {\n return rootWord;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T09:20:43.737", "Id": "7038", "ParentId": "7036", "Score": "1" } }, { "body": "<p>I would like to go beyond just making the code prettier, and change the method that you are using. Instead of looping through the arrays looking for matches, you can put the synonyms in a hashed list. That will give you a performance close to O(1) for each lookup, instead of O(n).</p>\n\n<p>Example in C#:</p>\n\n<pre><code>public class Synonymiser {\n\n private Dictionary&lt;string, string&gt; _synonyms = new Dictionary&lt;string, string&gt;();\n\n public Synonymiser AddWord(string word, params string[] synonyms) {\n foreach (string synonym in synonyms) {\n _synonyms.Add(synonym.ToUpper(), word);\n }\n return this;\n }\n\n public string NormaliseString(string inStr){\n string replacement;\n return String.Join(\n \" \",\n inStr.Split(' ')\n .Select(w =&gt; _synonyms.TryGetValue(w.ToUpper(), out replacement) ? replacement : w)\n );\n }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Synonymiser s =\n new Synonymiser()\n .AddWord(\"one\", \"two\", \"three\", \"four\", \"five\")\n .AddWord(\"six\", \"seven\", \"eight\");\n\nConsole.WriteLine(s.NormaliseString(\"one two seven bulb\"));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>one one six bulb\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:45:37.410", "Id": "10991", "Score": "0", "body": "I think you mean HashMap/Dictionary, not HashSet..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:20:59.113", "Id": "10996", "Score": "0", "body": "@ChrisMarasti-Georg: Yes, you are right. A set would be only keys, so I changed it to read \"a hashed list\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T10:49:13.037", "Id": "7041", "ParentId": "7036", "Score": "5" } }, { "body": "<p>This implementation will end up having poor performance for large dictionaries - you will have O(n) performance for n root words. I would recommend converting the synonym array into a HashMap, mapping a key word to its root word value. This will give you a slightly more expensive initialization (essentially, the cost that you pay for each call to normalizeString will be paid once, on construction). The memory footprint will be slightly larger as well - one extra pointer per synonym.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.HashMap;\n\npublic class Synonymiser {\n\n private final static int ROOT_WORD = 0;\n\n private HashMap&lt;String, String&gt; mSynonyms;\n\n public Synonymiser(String[]... synonyms) {\n super();\n mSynonyms = new HashMap&lt;String, String&gt;(synonyms.length*5); //Enough initial storage for 5 synonyms per root\n for(String[] root: synonyms) {\n for(int i = 0; i&lt;root.length; ++i) {\n if(i == ROOT_WORD) {\n continue;\n }\n mSynonyms.put(root[i], root[ROOT_WORD]);\n }\n }\n }\n\n\n public String normaliseString(String inStr){\n String[] inArr = inStr.split(\" \");\n\n for (int i = 0; i &lt; inArr.length; i++){\n String synonym = mSynonyms.get(inArr[i]);\n if(synonym != null) {\n inArr[i] = synonym;\n }\n }\n return Arrays.toString(inArr);\n }\n\n public static void main(String [] args){\n String[] ar1 = new String[] {\"one\", \"two\", \"three\", \"four\", \"five\"};\n String[] ar2 = new String[] {\"six\", \"seven\", \"eight\"};\n Synonymiser s = new Synonymiser(ar1, ar2);\n\n System.out.println(s.normaliseString(\"one two seven bulb\"));\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:45:05.817", "Id": "7045", "ParentId": "7036", "Score": "2" } }, { "body": "<p>I'd start by extracting the body of the outermost loop. For any given candidate string, find the synonym.</p>\n\n<pre><code>public class Synonymiser {\n\n ...\n\n public String normaliseString(String inStr){\n String[] inArr = inStr.split(\" \");\n for (int i = 0; i &lt; inArr.length; i++) {\n inArr[i] = synonym(inArr[i]);\n }\n return Arrays.toString(inArr);\n }\n\n private String synonym(String candidate) {\n for (String[] array : mSynonyms) {\n for (String s : array) {\n if (candidate.equalsIgnoreCase(s) {\n return array[ROOT_WORD];\n }\n }\n }\n return candidate;\n }\n\n ...\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:55:49.397", "Id": "7046", "ParentId": "7036", "Score": "1" } }, { "body": "<p>Here's my take; it's basically the same as the others. Notes and caveats, in no order:</p>\n\n<ul>\n<li>I keep two maps, one of primary => synonyms, one of synonym => word.</li>\n<li>Added error condition if a synonym is registered to two different primaries.</li>\n<li>Ignore if a synonym is added to single primary, multiple times.</li>\n<li>Does not ensure a synonym is never registered as a primary, or vice-versa--in reality there would need to be a decision regarding how to handle that situation.</li>\n<li>Code unit-tested but not used outside of tests has been stripped.</li>\n<li>Comments and parameter validation stripped.</li>\n<li>I return a string (joined with Commons Lang), not an array.</li>\n<li>One bug left in intentionally, for fun. Any others, probably not intentional.</li>\n</ul>\n\n<hr>\n\n<pre><code>public class Synonymizer {\n\n private Map&lt;String, Set&lt;String&gt;&gt; wordSynonymsMap;\n\n private Map&lt;String, String&gt; synonymWordMap;\n\n public Synonymizer() {\n wordSynonymsMap = new HashMap&lt;String, Set&lt;String&gt;&gt;();\n synonymWordMap = new HashMap&lt;String, String&gt;();\n }\n\n public void addSynonyms(String word, String... synonyms) {\n Set&lt;String&gt; wordSynonyms = getSynonyms(word);\n for (String synonym : synonyms) {\n wordSynonyms.add(synonym);\n if (synonymWordMap.containsKey(synonym) &amp;&amp; !synonymWordMap.get(synonym).equals(word)) {\n throw new RuntimeException(String.format(\"'%s' already used as synonym for '%s'\", synonym, synonymWordMap.get(synonym)));\n }\n synonymWordMap.put(synonym, word);\n }\n }\n\n public Set&lt;String&gt; getSynonyms(String word) {\n if (!wordSynonymsMap.containsKey(word)) {\n wordSynonymsMap.put(word, new HashSet&lt;String&gt;());\n }\n\n return wordSynonymsMap.get(word);\n }\n\n public String normalizeString(String s) {\n List&lt;String&gt; l = new ArrayList&lt;String&gt;();\n for (String word : s.split(\" \")) {\n l.add(synonymize(word));\n }\n\n return StringUtils.join(l, \" \");\n }\n\n public String synonymize(String word) {\n if (wordSynonymsMap.containsKey(word)) {\n return word;\n }\n\n String primary = synonymWordMap.get(word);\n if (primary != null) {\n return primary;\n }\n\n return word;\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T04:49:49.960", "Id": "7059", "ParentId": "7036", "Score": "1" } } ]
{ "AcceptedAnswerId": "7038", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T07:50:10.560", "Id": "7036", "Score": "4", "Tags": [ "java" ], "Title": "Synonymiser refactoring" }
7036
<p>The aim of this code is to return an object which contains all of the movies. Where attributes are not found, they need to return <code>None</code> rather than be undefined and raise an exception.</p> <p><code>attrs</code> is a list of all possible properties for that class. Each class loops through and tries to get the attribute. If the attribute is not there, <code>setattr(self,attr,video.attrib.get(attr))</code> will return <code>None</code>.</p> <p>The end result is an object which can be referenced like so:</p> <p><code>Movielist.movies[0].Video.title</code> would return <em>"30 Minutes Or Less".</em></p> <p>The XML structure is as follows:</p> <ul> <li>Each movie is returned as an XML <code>&lt;Video&gt;</code></li> <li>Each movie has a <code>&lt;Media&gt;</code> subsection which may contain multiple elements</li> <li>Within each <code>&lt;Media&gt;</code> subsection are <code>&lt;Part&gt;</code> subsections. There may also be multiple entries here.</li> </ul> <p>I'm sure there must be a better / simpler way of doing this.</p> <p>A sample of the Python source code follows, along with a sample of XML code returned / scanned by the <code>Movielist</code> class after that:</p> <pre class="lang-python prettyprint-override"><code>import httplib import xml.etree.ElementTree as ElementTree def getUrl(server,url): c=httplib.HTTPConnection(server.ip,server.port) c.request("GET",url) r=c.getresponse() return r.read() def getxml(server,serverPath,tag): responseData=getUrl(server,serverPath) e=ElementTree.XML(responseData) if not tag: return e else: return e.findall(tag) class Video(): class Media(): class Part(): def __init__(self,part): attrs=['key', 'duration', 'file', 'size', ] for attr in attrs: setattr(self,attr,part.attrib.get(attr)) def __init__(self,media): attrs=['id', 'duration', 'bitrate', 'width', 'height', 'aspectRatio', 'audioChannels', 'audioCodec', 'videoCodec', 'videoResolution', 'container', 'videoFrameRate', 'optimizedForStreaming', ] for attr in attrs: setattr(self,attr,media.attrib.get(attr)) xmlParts=media.findall("Part") self.parts=[] for part in xmlParts: p=self.Part(part) self.parts.append(p) def __init__(self,server,video): # Get the detail self.key=video.attrib.get('key') x=getxml(server,self.key,"Video") video=x[0] self.video=video attrs=['ratingKey', 'key', 'studio', 'type', 'title', 'contentRating', 'summary', 'rating', 'year', 'tagline', 'thumb', 'art', 'duration', 'originallyAvailableAt', 'addedAt', 'updatedAt', 'titleSort', 'viewCount', 'viewOffset', 'guid', 'lastViewedAt', 'index', ] for attr in attrs: setattr(self,attr,video.attrib.get(attr)) self.media=None for subitem in self.video: if subitem.tag=="Media": self.media=self.Media(subitem) class Server: def __init__(self,ip,port): self.ip=ip self.port=port def movielisturl(self,key): return "/library/sections/%s/all" % key class Movielist: def __init__(self,server,key): x=getxml(server,server.movielisturl(key),"Video") print x self.movies=[] for item in x: m=Video(server,item) self.movies.append(m) def main(): s=Server("localhost",32400) l=Movielist(s,4) for video in l.movies: print video.title if __name__ == "__main__": main() </code></pre> <p><strong>XML Sample</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" ?&gt; &lt;MediaContainer art="/:/resources/movie-fanart.jpg" identifier="com.plexapp.plugins.library" mediaTagPrefix="/system/bundle/media/flags/" mediaTagVersion="1323514612" size="260" title1="Movies" viewGroup="movie" viewMode="65592"&gt; &lt;Video addedAt="1323265351" art="/library/metadata/242/art?t=1324432778" contentRating="R" duration="4980000" key="/library/metadata/242" originallyAvailableAt="2011-08-12" ratingKey="242" studio="Media Rights Capital" summary="30 Minutes or Less is a 2011 American action comedy crime film directed by Ruben Fleischer starring Jesse Eisenberg, Aziz Ansari, Danny McBride and Nick Swardson. It is produced by Columbia Pictures and funded by Media Rights Capital." thumb="/library/metadata/242/thumb?t=1324432778" title="30 Minutes or Less" type="movie" updatedAt="1324432778" year="2011"&gt; &lt;Media aspectRatio="2.35" audioChannels="6" audioCodec="dca" bitrate="1500" container="mkv" duration="4983000" height="534" id="242" optimizedForStreaming="0" videoCodec="h264" videoFrameRate="24p" videoResolution="720" width="1280"&gt; &lt;Part duration="4983000" file="/mnt/raid/Entertainment/Movies/30 Minutes Or Less (2011).mkv" key="/library/parts/249/file.mkv" size="3521040154"/&gt; &lt;/Media&gt; &lt;Genre tag="Comedy"/&gt; &lt;Genre tag="Action"/&gt; &lt;Writer tag="Michael Diliberti"/&gt; &lt;Director tag="Ruben Fleischer"/&gt; &lt;Country tag="USA"/&gt; &lt;Role tag="Jesse Eisenberg"/&gt; &lt;Role tag="Danny McBride"/&gt; &lt;Role tag="Nick Swardson"/&gt; &lt;/Video&gt; &lt;Video addedAt="1323265356" art="/library/metadata/375/art?t=1324432778" contentRating="PG-13" duration="7140000" key="/library/metadata/375" originallyAvailableAt="2010-06-11" rating="7.8" ratingKey="375" studio="Dune Entertainment" summary="The A-Team is an American action film based on the television series of the same name. It was released in cinemas in the United States on June 11, 2010, by 20th Century Fox. The film was directed by Joe Carnahan and produced by Stephen J. Cannell and the Scott brothers Ridley and Tony. The film has been in development since the mid 1990s, having gone through a number of writers and story ideas, and being put on hold a number of times. Producer Stephen J. Cannell wished to update the setting, perhaps using the first Gulf War as part of the backstory. The film stars Liam Neeson, Bradley Cooper, Quinton Jackson, and Sharlto Copley as The A-Team, former U.S. Army Rangers, imprisoned for a crime they did not commit. They escape and set out to clear their names. Jessica Biel, Patrick Wilson, and Brian Bloom fill supporting roles. The film received mixed reviews from critics and performed slightly below expectations at the box office. The reception from the cast of the original television series was also mixed." tagline="There Is No Plan B" thumb="/library/metadata/375/thumb?t=1324432778" title="The A-Team" titleSort="A-Team" type="movie" updatedAt="1324432778" year="2010"&gt; &lt;Media aspectRatio="2.35" audioChannels="6" audioCodec="dca" bitrate="1500" container="mkv" duration="8013000" height="544" id="375" optimizedForStreaming="0" videoCodec="h264" videoFrameRate="24p" videoResolution="720" width="1280"&gt; &lt;Part duration="8013000" file="/mnt/raid/Entertainment/Movies/The A-Team Extended 720P Bluray X264-Zmg.mkv" key="/library/parts/382/file.mkv" size="8531243656"/&gt; &lt;/Media&gt; &lt;Genre tag="Thriller"/&gt; &lt;Genre tag="Action"/&gt; &lt;Writer tag="Skip Woods"/&gt; &lt;Writer tag="Joe Carnahan"/&gt; &lt;Director tag="Joe Carnahan"/&gt; &lt;Country tag="USA"/&gt; &lt;Role tag="Patrick Wilson"/&gt; &lt;Role tag="Liam Neeson"/&gt; &lt;Role tag="Sharlto Copley"/&gt; &lt;/Video&gt; &lt;/MediaContainer&gt; </code></pre>
[]
[ { "body": "<pre><code>import httplib\nimport xml.etree.ElementTree as ElementTree\n\ndef getUrl(server,url):\n c=httplib.HTTPConnection(server.ip,server.port)\n c.request(\"GET\",url)\n r=c.getresponse()\n return r.read()\n</code></pre>\n\n<p>Firstly, the function doesn't really match its name. getUrl makes me think it should return a URL, not take my url and download it. Secondly, there is function urllib.urlopen which does everything this function does minus the last line. And it takes a url as an argument, so you can combine the two parameters here.</p>\n\n<pre><code>def getxml(server,serverPath,tag):\n responseData=getUrl(server,serverPath)\n e=ElementTree.XML(responseData)\n</code></pre>\n\n<p>But some spaces around those =. I also think you shouldn't use single letter variables name (usually).</p>\n\n<pre><code> if not tag:\n</code></pre>\n\n<p>When checking for None I recommend <code>tag is not None</code> just to be explicit. </p>\n\n<pre><code> return e\n else:\n return e.findall(tag)\n\nclass Video():\n</code></pre>\n\n<p>Either drop the parens here, or put <code>object</code> in them. </p>\n\n<pre><code> class Media():\n class Part():\n</code></pre>\n\n<p>I'm not a fan of nesting classes (usually). I'd separate them out.</p>\n\n<pre><code> def __init__(self,part):\n attrs=['key',\n 'duration',\n 'file',\n 'size',\n ]\n for attr in attrs:\n setattr(self,attr,part.attrib.get(attr))\n</code></pre>\n\n<p>I would recommend against loading from XML in your classes' constructor. It ties your internal objects too much into the structure of the xml file. I'd suggest having external function which extract the data from the XML and then pass it into the constructor. </p>\n\n<pre><code> def __init__(self,media):\n</code></pre>\n\n<p>Here's the reason why nesting classes is problematic. Its hard to tell what class I'm in now.</p>\n\n<pre><code> attrs=['id',\n 'duration',\n 'bitrate',\n 'width',\n 'height',\n 'aspectRatio',\n 'audioChannels',\n 'audioCodec',\n 'videoCodec',\n 'videoResolution',\n 'container',\n 'videoFrameRate',\n 'optimizedForStreaming',\n ]\n for attr in attrs:\n setattr(self,attr,media.attrib.get(attr))\n</code></pre>\n\n<p>We see this piece of code exactly in the previous constructor. You should move it into a function.</p>\n\n<pre><code> xmlParts=media.findall(\"Part\")\n self.parts=[]\n for part in xmlParts:\n p=self.Part(part)\n self.parts.append(p)\n</code></pre>\n\n<p>Instead you can do <code>self.parts = map(self.Part, media.findall(\"Part\"))</code>. That will make this less complicated here.</p>\n\n<pre><code> def __init__(self,server,video):\n # Get the detail\n self.key=video.attrib.get('key')\n</code></pre>\n\n<p>Do you really want to get None here if the key is missing?</p>\n\n<pre><code> x=getxml(server,self.key,\"Video\")\n video=x[0]\n</code></pre>\n\n<p>Any reason not to combine those two lines? Your constructor fetches the data from the server. As with the xml parsing I think this is best done outside of the constructor. </p>\n\n<pre><code> self.video=video\n</code></pre>\n\n<p>Why do you want to keep a reference the xml node? Shouldn't you just toss it once you've finished reading from it?</p>\n\n<pre><code> attrs=['ratingKey',\n 'key',\n 'studio',\n 'type',\n 'title',\n 'contentRating',\n 'summary',\n 'rating',\n 'year',\n 'tagline',\n 'thumb',\n 'art',\n 'duration',\n 'originallyAvailableAt',\n 'addedAt',\n 'updatedAt',\n 'titleSort',\n 'viewCount',\n 'viewOffset',\n 'guid',\n 'lastViewedAt',\n 'index',\n ]\n for attr in attrs:\n setattr(self,attr,video.attrib.get(attr))\n\n\n self.media=None\n for subitem in self.video:\n if subitem.tag==\"Media\":\n self.media=self.Media(subitem)\n</code></pre>\n\n<p>Is there a find function or something to make this simpler?</p>\n\n<pre><code>class Server:\n</code></pre>\n\n<p>The class name should probably be more specific then just <code>Server</code></p>\n\n<pre><code> def __init__(self,ip,port):\n self.ip=ip\n self.port=port\n\n def movielisturl(self,key):\n return \"/library/sections/%s/all\" % key\n</code></pre>\n\n<p>I'd probably have the server class define a method that returns the XML rather then just providing the URL. That the way the server can actually fetch the XML anyway it likes not just a http connection.</p>\n\n<pre><code>class Movielist:\n\n def __init__(self,server,key):\n x=getxml(server,server.movielisturl(key),\"Video\")\n print x\n self.movies=[]\n for item in x:\n m=Video(server,item)\n self.movies.append(m)\n</code></pre>\n\n<p>I wouldn't have a MovieList class. I'd just have a list of movies. I'd have a function that returns a list of movies from a particular server.</p>\n\n<pre><code>def main():\n s=Server(\"localhost\",32400)\n l=Movielist(s,4)\n for video in l.movies:\n</code></pre>\n\n<p>You are mixing video and movie, I recommend picking a terminology and sticking with it.</p>\n\n<pre><code> print video.title\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T20:56:11.200", "Id": "7055", "ParentId": "7044", "Score": "4" } }, { "body": "<p>You may use <a href=\"http://lxml.de/\" rel=\"nofollow\">lxml lib</a></p>\n\n<pre><code>from cStringIO import StringIO\nfrom lxml import etree\n\nxml = StringIO(''' YOUR XML ''')\n\ndef main(): \n tree = etree.parse(xml)\n print tree.xpath(\"//Video/@title\")\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>['30 Minutes or Less', 'The A-Team']\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T06:08:49.057", "Id": "7063", "ParentId": "7044", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T13:06:21.517", "Id": "7044", "Score": "5", "Tags": [ "python", "xml", "parsing" ], "Title": "Parsing XML in Python" }
7044
<p>I am using class "active" to keep track on which child to fade in and fade out in my gallery. Are there any other, better options for doing this?</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;style type="text/css"&gt; #div_with_children{margin:0 auto;width:960px;height:499px;overflow:hidden} .child{width:960px;height:500px} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="div_with_children"&gt; &lt;div class="child" style="background:#0C3"&gt;1&lt;/div&gt; &lt;div class="child" style="background:#993"&gt;2&lt;/div&gt; &lt;div class="child" style="background:#F63"&gt;3&lt;/div&gt; &lt;div class="child" style="background:#FC0"&gt;4&lt;/div&gt; &lt;/div&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; (function ($) { $.fn.bildspel_fade = function () { var $t = this, $c = $t.children(), $c0 = $c.eq(0), $c1 = $c.eq(-1), n = function () { var i = $t.children('.active').index(), i1 = i + 1; $c.css('position', 'absolute'); if ($c1.hasClass("active")) { // om man ÄR på sista $c1.fadeOut(1000).removeClass('active'); $c0.addClass('active').fadeIn(1000); } else { // om man INTE ÄR på sista $t.find('.active').fadeOut(1000).removeClass('active').next().addClass('active').fadeIn(1000); } }; setInterval(n, 6000); $c.hide(); $c0.addClass('active').fadeIn(1000); }; })(jQuery); $(window).load(function () { $('#div_with_children').bildspel_fade(); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Maybe using jQuery's <a href=\"http://api.jquery.com/jQuery.data/\" rel=\"nofollow\"><code>$.data()</code></a> to store a bool variable or something like that. </p>\n\n<p>Also you could store a global variable with the active position (e.g. \"3\" for the 3rd item in the gallery), and then change it, using it along with the :eq() selector.</p>\n\n<p>Either way, I think that the .active class approach is very useful because it gives you the chance to alter the CSS properties for that specific item on your gallery.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:23:36.040", "Id": "7053", "ParentId": "7047", "Score": "1" } } ]
{ "AcceptedAnswerId": "7053", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T14:46:59.630", "Id": "7047", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Keep track on active slide" }
7047
<p>Previous question:</p> <p><a href="https://codereview.stackexchange.com/questions/6988/java-application-for-finding-permutations-efficiently">Java application for finding permutations efficiently</a>></p> <p>I have changed quite a bit of code, and need some more reviews.</p> <pre><code>class Permutations { static long factorial(int num){ long factorial = num; for (int forBlockvar = num; forBlockvar &gt; 1; forBlockvar--) { factorial = factorial * forBlockvar; } return factorial / num; } public static void main(String[] args){ long FactNmR; int n = 8; int num = n; int r = 6; int nMr = n - r; long FactN = factorial(num); if (nMr == 2) { FactNmR = 2; } else if (nMr &lt;= 1){ FactNmR = 1; } else if (nMr &gt;= 2) { num = nMr; FactNmR = factorial(num); } long permutations = FactN; permutations = permutations / FactNmR; System.out.println(permutations); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:17:13.037", "Id": "10989", "Score": "1", "body": "Are you sure that you pasted it well? It's not compiling, I think the `return` statement of the `factorial` method is in a wrong place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:19:47.103", "Id": "10990", "Score": "0", "body": "Yeah, I figured out that the return statement has to be outside of the brackets of the factorial method. Thank you anyways." } ]
[ { "body": "<h2>Code comment:</h2>\n\n<pre><code>static long factorial(int num){\n long factorial = num;\n for (int forBlockvar = num; forBlockvar &gt; 1; forBlockvar--) {\n factorial = factorial * forBlockvar;\n }\n return factorial / num;\n}\n</code></pre>\n\n<p>You are starting your <code>factorial = num</code>, then multiplying it by <code>num</code> in the first iteration of the loop, then dividing by <code>num</code> at the end. Starting with <code>factorial = 1</code>, or starting <code>forBlockvar = num - 1</code> (I prefer the second) will remove the need to divide at the end. You can also return 1 if the input is less than 2.</p>\n\n<pre><code>static long factorial(int num){\n if(num &lt; 2) {\n return 1;\n }\n long factorial = num;\n for (int forBlockvar = num - 1; forBlockvar &gt; 1; forBlockvar--) {\n factorial = factorial * forBlockvar;\n }\n return factorial;\n}\n</code></pre>\n\n<p>You could also implement this function recursively.</p>\n\n<pre><code>static long factorial(int num){\n if(num &lt; 2) {\n return 1;\n }\n return num * factorial(num - 1);\n}\n</code></pre>\n\n<h2>General:</h2>\n\n<p>What do you mean by finding the permutations of 2 numbers? There are 2 permutations of 2 numbers [x, y]: [x, y] and [y, x].</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I think I know what you are trying to do now... You want to know how many permutations are available by selecting <code>r</code> objects out of a total of <code>n</code>.</p>\n\n<p>The basic formula for that is <code>n! / (n-r)!</code>. However, this means calculating the factorial of <code>(n-r)</code> twice (in our example, we have <code>8*7*6*5*4*3*2*1 / 2*1</code>, but with a lower <code>r</code> the overlap will be greater).</p>\n\n<p>Instead of calculating the complete factorial for both numerator and denominator, there is a way to calculate the value of the numerator such that the denominator is always going to be 1. That means we eliminate one factorial calculation, and reduce the other. I'm going to let you think about it a bit before just giving the answer.</p>\n\n<p><strong>EDIT 2</strong></p>\n\n<p>Since you have figured out what I was hinting at, I'll explain it further.</p>\n\n<p><code>n!</code> can be represented as <code>n*(n-1)*(n-2)*(n-3)...(2)*(1)</code>. When <code>r</code> is less than <code>n</code> and greater than <code>0</code>, <code>n!</code> can be then be represented as <code>n*(n-1)*(n-2)...(n-r+1)*(n-r)*(n-r-1)*(n-r-2)...(2)*(1)</code>.</p>\n\n<p><code>(n-r)!</code> is <code>(n-r)*(n-r-1)*(n-r-2)...(2)*(1)</code>.</p>\n\n<p>Therefore, our numerator is <code>n*(n-1)*(n-2)...(n-r+1)*(n-r)*(n-r-1)*(n-r-2)...(2)*(1)</code>, and our denominator is <code>(n-r)*(n-r-1)*(n-r-2)...(2)*(1)</code>. Cancelling like terms, we have <code>n!/(n-r)! = n*(n-1)*(n-2)...(n-r+1)</code>.</p>\n\n<pre><code>static long permute(int totalItems, int numToPick) {\n long permutations = totalItems;\n while (--numToPick &gt; 0) {\n permutations *= --totalItems;\n }\n return permutations;\n}\n</code></pre>\n\n<p>You should ensure that <code>0 &lt; numToPick &lt;= totalItems</code>, and <code>totalItems &gt; 0</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:05:45.280", "Id": "10994", "Score": "1", "body": "+1. Please note that the second (`forBlockvar = num - 1`) gives result `0` for input `0` (instead of `1`, `0! = 1`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:08:46.107", "Id": "10995", "Score": "0", "body": "@palacsint good point. Updated answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:29:42.433", "Id": "10999", "Score": "0", "body": "So, @ChrisMarasti-Georg, what you are meaning is canceling similar terms, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:36:40.037", "Id": "11001", "Score": "0", "body": "@CodeAdmiral Yes, exactly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:38:00.783", "Id": "11002", "Score": "0", "body": "Otay, that helps a bunch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:38:12.640", "Id": "11003", "Score": "0", "body": "Problem is, I still get an error: Main.java:48: variable FactNmR might not have been initialized\n?????" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:48:18.957", "Id": "11005", "Score": "0", "body": "That error is because the compiler is not allowed to determine that all code paths assign a value to FactNmR before it is read. You can initialize it `long FactNmR = 0`, or have an `else` with no `if` at the end of the branch that assigns a value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:54:53.627", "Id": "11006", "Score": "0", "body": "Otay, thank you again, @ChrisMarasti-Georg" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:53:36.600", "Id": "7051", "ParentId": "7048", "Score": "2" } }, { "body": "<p>It looks much better and it's more easier to read than the previous post. Some small notes below.</p>\n\n<p>In the <code>factorial</code> method you should assign <code>1</code> to the <code>factorial</code> variable in the first line, so you don't have to divide it with <code>num</code> in the last line.</p>\n\n<pre><code> static long factorial(int num) {\n long factorial = 1;\n ...\n return factorial;\n }\n</code></pre>\n\n<p>It would result more simple and easier to read code and it gives proper result for <code>0</code>.</p>\n\n<p>After that you should reduce the <code>if-else if-else-if</code> structure since the <code>factorial</code> method now gives proper result for \n<code>2</code>, <code>1</code> and <code>0</code>.</p>\n\n<hr>\n\n<p>You could call the <code>factorial</code> method with <code>nMr</code> in this part:</p>\n\n<pre><code>num = nMr;\nFactNmR = factorial(num);\n</code></pre>\n\n<hr>\n\n<p>Based on the classic</p>\n\n<pre><code>P(n, k) = n! / ((n - k)!)\n</code></pre>\n\n<p>formula, I'd create one variable for only one thing with these names:</p>\n\n<ul>\n<li><code>n</code>, <code>k</code> for the input values,</li>\n<li><code>diff</code> would be the result of <code>n - k</code>,</li>\n<li><code>dividend</code> would be the result of <code>n!</code>,</li>\n<li><code>divisor</code> would be the result of <code>dividend!</code>.</li>\n</ul>\n\n<p>The <code>n</code> and <code>k</code> are the most important. Anyway, put the formula in a comment with the used variable names. It would help the readers a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:31:08.777", "Id": "11000", "Score": "0", "body": "Yes, I have since fixed this, thank you so much. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:02:48.530", "Id": "7052", "ParentId": "7048", "Score": "1" } }, { "body": "<p>CodeAdmiral,</p>\n\n<p>I think I would find the program most readable like this:</p>\n\n<p><strong>The straightforward way:</strong></p>\n\n<pre><code>class Permutations {\n\n static long factorial(int n) {\n long f = 1;\n while (n &gt; 0) f *= n--;\n return f;\n }\n\n public static void main(String[] args){\n int n = 8, k = 6;\n long permutations = factorial(n) / factorial(n-k);\n System.out.println(permutations);\n }\n}\n</code></pre>\n\n<p>Of course, this method is less efficient -- and also more prone to overflow -- than the more direct method of computing the result without wasted operations. So, a cleaner way would be like this:</p>\n\n<p><strong>The more efficient way:</strong></p>\n\n<pre><code>class Permutations {\n\n static long permutations(int n, int k) {\n long p = 1;\n while (k-- &gt; 0) p *= n--;\n return p;\n }\n\n public static void main(String[] args){\n int n = 8, k = 6;\n System.out.println(permutations(n, k));\n }\n}\n</code></pre>\n\n<p>Tying it all together with a version that also computes n choose k (combinations) gives the following:</p>\n\n<p><strong>Computing both permutations and combinations:</strong></p>\n\n<pre><code>class Permutations {\n\n static long factorial(int n) {\n long f = 1;\n while (n &gt; 0) f *= n--;\n return f;\n }\n\n static long permutations(int n, int k) {\n long p = 1;\n while (k-- &gt; 0) p *= n--;\n return p;\n }\n\n static long combinations(int n, int k) {\n long a = 1, b = 1;\n while (k &gt; 0) { a *= n--; b *= k--; }\n return a / b;\n }\n\n public static void main(String[] args){\n int n = 8, k = 6;\n System.out.println(\n \"Permutations: \" + permutations(n, k) + \" = \" +\n factorial(n) / factorial(n-k));\n System.out.println(\n \"Combinations: \" + combinations(n, k) + \" = \" +\n factorial(n) / factorial(k) / factorial(n-k));\n }\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:12:16.710", "Id": "11033", "Score": "0", "body": "Thank you! Not meaning to be a hater or anything, but for the math, I want to fully understand how to reach the solution. Your answer was amazing. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T00:01:28.567", "Id": "7057", "ParentId": "7048", "Score": "2" } } ]
{ "AcceptedAnswerId": "7051", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T16:16:43.510", "Id": "7048", "Score": "2", "Tags": [ "java", "homework", "combinatorics" ], "Title": "Permutations Finder Help Number 2" }
7048
<p>Please have a look at the following 2 snippets:</p> <pre><code>var query = _ctx.Notes.Where(...); var searchLower = searchTerms.ToLower(); query = query.Where(a =&gt; a.Comment.ToLower().Contains(searchLower)) </code></pre> <p>vs</p> <pre><code>var query = _ctx.Notes.Where(...); query = query.Where(a =&gt; a.Comment.ToLower().Contains(searchTerms.ToLower())) </code></pre> <p>Is there any peformance increase by converting the search terms before carrying out the LINQ query?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T15:43:19.943", "Id": "11350", "Score": "1", "body": "Note that according to \"Best Practices for Using Strings in the .NET Framework\" you should be converting `ToUpper()`, not `ToLower()`. Link: http://msdn.microsoft.com/en-us/library/dd465121.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-02T12:10:46.603", "Id": "11556", "Score": "2", "body": "You should also have a look at Jon Skeet's answer to thus question around case sensitivity: http://stackoverflow.com/questions/234591/upper-vs-lower-case" } ]
[ { "body": "<p>Instead of <code>Contains()</code>, use <code>IndexOf()</code> which takes a comparer:</p>\n\n<pre><code>var query = _ctx.Notes.Where(...); \nquery = query.Where(a =&gt; a.Comment.IndexOf(searchTerms, StringComparison.OrdinalIgnoreCase) &gt;= 0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T16:47:40.993", "Id": "10984", "Score": "0", "body": "I think it should be `>= 0`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:07:35.033", "Id": "10986", "Score": "0", "body": "Is this actually quicker against an SQL database?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T17:16:24.897", "Id": "10988", "Score": "0", "body": "@jaffa: your best bet for speed against the database is to have a case-insensitive column with `Latin1_General_CS_AS` (or appropriate) and run that contains in a stored proc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T16:39:03.560", "Id": "7050", "ParentId": "7049", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T16:26:57.127", "Id": "7049", "Score": "1", "Tags": [ "c#", "linq" ], "Title": "Is there any performance increase converting search term to lower case before LINQ" }
7049
<p>My query is this:</p> <pre><code>UPDATE `phrases` SET `phrases`.`count`=(SELECT COUNT(*) FROM `strings` WHERE `string` LIKE CONCAT('%', `phrases`.`phrase`, '%')) </code></pre> <p>My tables look like this:</p> <pre><code>CREATE TABLE `phrases` ( `hash` varchar(32) NOT NULL, `count` int DEFAULT 0, `phrase` text NOT NULL, PRIMARY KEY (`hash`), KEY(`count`) ) </code></pre> <p>And</p> <pre><code>CREATE TABLE `strings` ( `string` text NOT NULL, ) </code></pre> <p><code>phrases</code> has 18,000 rows and <code>strings</code> has 1500 rows.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T22:09:27.617", "Id": "11009", "Score": "0", "body": "It might be more efficient to have a separate table where you would store the counts per phrase, and then only update this table once a new string is added. Since the number of strings is low in comparison to the phrases, I figure this wont happen that often. So you would not perform the whole count again, just add 1 if the new string matches that phrase." } ]
[ { "body": "<p>Since you're using a <code>LIKE</code> with wildcards, you're going to do a table-scan against both tables, running a total of 18000*1500 = 27000000 substring comparisons.</p>\n\n<p>To optimize this, you need to use some fulltext index technology. I suggest <a href=\"http://sphinxsearch.com/\" rel=\"nofollow\">Sphinx Search</a> or <a href=\"http://lucene.apache.org/solr/\" rel=\"nofollow\">Apache Solr</a>. If you do this, you don't need to keep a count of how many matches there are, because the search index makes it a lot less expensive to get a count on demand.</p>\n\n<p>MySQL also implements a <a href=\"http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html\" rel=\"nofollow\">FULLTEXT index</a> type, but it is only supported in the MyISAM storage engine in current versions (up to 5.5). I don't recommend using MyISAM for important data. </p>\n\n<p>MySQL 5.6 is developing a fulltext index for InnoDB.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T22:04:52.703", "Id": "7061", "ParentId": "7060", "Score": "4" } }, { "body": "<p>You should drop the index and collect the counts.</p>\n\n<p>This will speed up the updating of the <code>count</code> column.</p>\n\n<p>When done, put the index back.</p>\n\n<pre><code>ALTER TABLE phrase DROP INDEX `count`;\nUPDATE phrase SET COUNT=0;\nUPDATE phrases INNER JOIN string\nON ( LOCATE(strings.string,phrases.phrase) &gt; 0 )\nSET phrase.`count`=phrase.`count`+1;\nALTER TABLE phrase ADD INDEX `count` (`count`);\n</code></pre>\n\n<p>This INNER JOIN is nothing more than a Cartesian Product (pointed out by Bill Karwin's answer as 27,000,000 rows being examined in a temp table).</p>\n\n<p>If the time to process is something can live with, all well and good.</p>\n\n<p>If the time to process is disastrously slow, <em>you must try Bill Karwin's answer</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T22:07:34.153", "Id": "7062", "ParentId": "7060", "Score": "0" } } ]
{ "AcceptedAnswerId": "7061", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T21:57:04.717", "Id": "7060", "Score": "3", "Tags": [ "strings", "sql", "mysql" ], "Title": "Phrases update query" }
7060
<p>I have made a simple scorecard form which uses jQuery to automatically calculate the score of submissions depending on field values. Some fields are "critical" which means if they are a fail they automatically fail. </p> <p>You can see a <a href="http://jsfiddle.net/westieuk/WtDMk/288/" rel="nofollow">jsFiddle example</a> to get a better understanding. I have tried to make the code as efficient as possible but would welcome peoples opinions on what improvements can be made.</p> <pre><code>//disable individual radios by# $("#edit-submitted-calc-verification-completed-idv-correctly-1, #edit-submitted-calc-summary--action-2-notes-1").attr('disabled',true); $("#webform-component-calc select, #webform-component-calc :radio").change(function(){ var $score = 0; var $fails = 0; var $critFails = 0; $('select option:selected, :radio:checked').each(function(){ var $thisVal = $(this).val(); var $split = $thisVal.split('_'); var $string = $split[0]; var $points = parseInt($split[1],10); $(this).parents('tr').find('.webform-grid-option').removeClass('pass fail'); if ($string == 'fail' || $string == 'critical') { $(this).parents('.webform-grid-option').addClass('fail'); if($string == 'fail') { $fails += 1; } if($string == 'critical') { $critFails += 1; } } else { $(this).parents('.webform-grid-option').addClass('pass'); if($string == 'pass' || $string == 'na') { $score += $points; } } }); var $finalScore = $score; if($critFails &gt; 0){ var $finalScore = 0; } var $summary = 'Final Call score: '+$finalScore+'% with '+$fails+' Fails / '+$critFails+' Critical Fails'; //alert($summary); $('#edit-submitted-calc-number-of-fails').val($fails); $('#edit-submitted-calc-call-score').val($score); $('#edit-submitted-calc-critical-failures-number-of-critial-fails').val($critFails); $('#edit-submitted-calc-critical-failures-final-score').val($finalScore); $('#edit-submitted-calc-summary').val($summary); }); </code></pre>
[]
[ { "body": "<p>Personally I wouldn't change anything about the calculation itself. It all quite reasonable the way it is. </p>\n\n<p>There are just two things could be optimized concerning jQuery:</p>\n\n<ul>\n<li>You should be using <code>.closet()</code> instead of <code>.parents()</code> since you only need the first (closest) matching parent and not all ancestors.</li>\n<li>Also you can optimize assigning the event handler to the radio buttons by using <code>.delegate()</code> (or <code>.on</code> with jQUery 1.7) instead.</li>\n</ul>\n\n<p>There are also a few things which personally I'd do differently:</p>\n\n<ul>\n<li>In the HTML I'd use <code>th</code> elements for the question cells and <code>td</code> just for the options, allowing you to get rid of the classes <code>webform-grid-question</code> and <code>webform-grid-option</code>.</li>\n<li>I'm not a big fan of using <code>$</code> in variable names, especially if they don't point to a jQuery object.</li>\n<li>I don't like using <code>input</code> elements for output. I'd use a \"normal\" element such as <code>span</code> or <code>div</code> (or if HTML5 is a option the new <code>output</code> element).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:57:08.197", "Id": "7086", "ParentId": "7065", "Score": "1" } } ]
{ "AcceptedAnswerId": "7086", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:08:03.897", "Id": "7065", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "jQuery score card form to determine pass or fail" }
7065
<p>This is a view as part of a RESTful image handler module, written for Flask, I am sure there is a better/more pythonic way of doing parts of this, maybe using List Comprehensions or Generator Functions. But I am a bit of a Python newbie and cannot spot it. Can any experienced pythonistas take a look?</p> <pre><code>@__mod__.route('/', methods=['GET']) @__mod__.route('/&lt;filename&gt;', methods=['GET']) def get(filename=None): """ Get a list of all Images or a single Image """ couchdb.init_app(current_app) image = Image() if filename is None: results = image.view('images/all') filenames = [] for result in results.all(): if result._attachments: for attachment in result._attachments.keys(): filenames.append(url_for('.get', filename=attachment)) response = make_response(simplejson.dumps(filenames), 200) response.headers['Content-Type'] = 'application/json' return response else: results = image.view('images/all', key=filename) if results.first() is not None: try: image_file = image.get_db().fetch_attachment(results.first(), filename) image_doc = results.first()._attachments[filename] response = make_response(image_file, 200) response.headers['Content-Type'] = image_doc['content_type'] return response except ResourceNotFound: abort(404) else: abort(404) </code></pre> <p>I've managed this on my own, using a list comprehension instead of the ugly for-if structures:</p> <pre><code>if filename is None: results = image.view('images/all') filenames = [url_for('.get', filename=attachment) for result in results if result._attachments for attachment in result._attachments] response = make_response(simplejson.dumps(filenames), 200) response.headers['Content-Type'] = 'application/json' return response else: results = image.view('images/all', key=filename) if results.first(): try: image_file = image.get_db().fetch_attachment(results.first(), filename) image_doc = results.first()._attachments[filename] response = make_response(image_file, 200) response.headers['Content-Type'] = image_doc['content_type'] return response except ResourceNotFound: abort(404) else: abort(404) </code></pre>
[]
[ { "body": "<pre><code>@__mod__.route('/', methods=['GET'])\n@__mod__.route('/&lt;filename&gt;', methods=['GET'])\n</code></pre>\n\n<p>Seeing as you end up handling these two routes in completely different ways, why don't you just implement two functions?</p>\n\n<pre><code>def get(filename=None):\n \"\"\" Get a list of all Images or a single Image \"\"\"\n\n couchdb.init_app(current_app)\n image = Image()\n</code></pre>\n\n<p>I don't know what these class does, but I suspect its not really an Image given the methods called on it. It seems more like an image library or something.</p>\n\n<pre><code> if filename is None:\n results = image.view('images/all')\n filenames = []\n for result in results.all():\n\n if result._attachments:\n</code></pre>\n\n<p>Attributes starting with underscores are usually intended to be private. You usually shouldn't be accessing them.</p>\n\n<pre><code> for attachment in result._attachments.keys():\n</code></pre>\n\n<p>If you are checking for an empty _attachments above (as opposed to None), you don't need to. The loop will execute zero times for an empty dictionary. Also, you don't need keys() because the default iteration for a dictionary is keys</p>\n\n<pre><code> filenames.append(url_for('.get', filename=attachment))\n</code></pre>\n\n<p>You did post an edit with a comprehensionified version. </p>\n\n<pre><code>filenames = [url_for('.get', filename=attachment) \n for result in results \n if result._attachments\n for attachment in result._attachments]\n</code></pre>\n\n<p>The same issues exist here as with the explicit for loop. Its also a bit long and complex I might do the following</p>\n\n<pre><code>attachments = [result._attachments for result in results if result._attachments]\nattachments = [attachment for attachment for attachments in attachments]\nattachments = [url_for('.get', filename = attachment) for attachment in attachments]\n</code></pre>\n\n<p>Better? maybe. maybe not.</p>\n\n<pre><code> response = make_response(simplejson.dumps(filenames), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n else:\n results = image.view('images/all', key=filename)\n\n if results.first() is not None: \n try:\n image_file = image.get_db().fetch_attachment(results.first(), filename)\n image_doc = results.first()._attachments[filename]\n response = make_response(image_file, 200)\n response.headers['Content-Type'] = image_doc['content_type']\n return response\n</code></pre>\n\n<p>I'd consider a utility function that calls make_response and sets a content_type.</p>\n\n<pre><code> except ResourceNotFound:\n abort(404)\n</code></pre>\n\n<p>It is recommended that you put as little as possible in your try blocks. You only want to catch exceptions from where it is expected to be thrown. I'm not sure where you it is coming from in your code.</p>\n\n<pre><code> else:\n abort(404)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T17:54:43.283", "Id": "7091", "ParentId": "7067", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T13:28:28.000", "Id": "7067", "Score": "3", "Tags": [ "python", "image", "flask" ], "Title": "Python RESTful image handler" }
7067
<p>I'm working through an introduction to computer science book, this is not homework for me but me trying to learn in my spare time, I'm not asking for homework help!</p> <p>The output is below, and this is all ok, but I'm just certain there is a more efficient way of doing this. I have been trying for many hours now and this is still the best solution I can come up with, if anyone can improve upon this and possibly explain how, I would highly appreciate it.</p> <p>The code:</p> <pre><code>naught = 0 one = 0 two = 0 three = 0 four = 0 five = 0 six = 0 seven = 0 eight = 0 nine = 0 for i in range (0, 10): print("") for i in range (0,1): print(naught, end = " ") for i in range (0,1): print(one, end = " ") one += 1 for i in range (0,1): print(two, end = " ") two += 2 for i in range (0,1): print(three, end = " ") three += 3 for i in range (0,1): print(four, end = " ") four += 4 for i in range (0,1): print(five, end = " ") five += 5 for i in range (0,1): print(six, end = " ") six += 6 for i in range (0,1): print(seven, end = " ") seven += 7 for i in range (0,1): print(eight, end = " ") eight += 8 for i in range (0,1): print(nine, end = " ") nine += 9 </code></pre> <p>The output is below and that is all correct, that's no problem.</p> <pre><code>0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36 0 5 10 15 20 25 30 35 40 45 0 6 12 18 24 30 36 42 48 54 0 7 14 21 28 35 42 49 56 63 0 8 16 24 32 40 48 56 64 72 0 9 18 27 36 45 54 63 72 81 </code></pre> <p>As I said I'm getting the right answer, just I'm not satisfied that it's in the best way. Many thanks, Matt.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:35:51.073", "Id": "11018", "Score": "1", "body": "Is this literally a multiplication table generator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T20:54:06.717", "Id": "11019", "Score": "2", "body": "`range(0,1)` = `range(1)` = `[0]` = one iteration? I don't get the point of doing a single iteration for-loop" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T21:02:13.293", "Id": "11020", "Score": "2", "body": "@julio.alegria this has got to be the first time I have seen anyone do that deliberately and not as a joke." } ]
[ { "body": "<pre><code>for i in range(10):\n for j in range(10):\n print i*j,\n print \"\"</code></pre>\n\n<p>Something like this, perhaps?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:37:25.313", "Id": "7069", "ParentId": "7068", "Score": "10" } }, { "body": "<p>If you are just looking to generate that same output, simplify your problem a little:</p>\n\n<pre><code>for x in range(10):\n temp = ''\n\n for y in range(10):\n temp += str(x * y) + ' '\n\n print temp\n</code></pre>\n\n<p>Or if you want to get fancy:</p>\n\n<pre><code>for x in range(10):\n print ' '.join(str(x * y) for y in range(10))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:38:03.773", "Id": "7070", "ParentId": "7068", "Score": "4" } }, { "body": "<pre><code>naught = 0\none = 0\ntwo = 0\nthree = 0\nfour = 0\nfive = 0\nsix = 0\nseven = 0\neight = 0\nnine = 0\n</code></pre>\n\n<p>Whenever you find yourself creating a number of variables that differ by a number, it means you really wanted a list. Instead, try doing something like:</p>\n\n<pre><code>numbers = [0, 0, 0, 0, 0, 0, 0, 0] # there are better ways, but I'm keeping it simple for now\n</code></pre>\n\n<p>Now you can use numbers[0], numbers[1], etc instead of the named variables.</p>\n\n<pre><code>for i in range (0, 10):\n</code></pre>\n\n<p>Odd space between range and (</p>\n\n<pre><code> print(\"\")\n for i in range (0,1):\n</code></pre>\n\n<p>You shouldn't use the same name for your loop index for loops inside each other. You also really shouldn't write a loop that only execute once.</p>\n\n<pre><code> print(naught, end = \" \")\n\n for i in range (0,1):\n print(one, end = \" \")\n one += 1\n</code></pre>\n\n<p>If we get rid of the pointless loop once, and use the list we get something like</p>\n\n<pre><code>print(numbers[1], end = \" \")\nnumbers[1] += 1\n\n for i in range (0,1):\n print(two, end = \" \")\n two += 2\n</code></pre>\n\n<p>Let's do the same here</p>\n\n<pre><code>print(numbers[2], end = \" \")\nnumbers[2] += 2\n</code></pre>\n\n<p>Hey! those are almost exactly the same! All that differs is the two. In fact, we are going to do that many more times. So we can use a loop</p>\n\n<pre><code>for j in range(1, 10):\n print(numbers[j]. end = \" \")\n numbers[j] += j\n</code></pre>\n\n<p>See how every place that had the number now uses j. We put the code in a loop and we don't need to repeat it 9 times.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T18:10:17.763", "Id": "7092", "ParentId": "7068", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:32:28.160", "Id": "7068", "Score": "4", "Tags": [ "python" ], "Title": "Improving many for loops, any more efficient alternative?" }
7068
<p>Is there a better way to do this without using <code>if</code> or <code>case</code> statements?</p> <pre><code>var val = ui.value, $box = $('#message'); switch(true) { case (val &gt; 50): $box.hide(); animations.animateBox($box.html('you have chosen XN')); break; case (val &lt; 50): $box.hide().delay(300); animations.animateBox($box.html('you have chosen VN')); break; default: $box.hide(); animations.animateBox($box.html('you have chosen PN')); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:32:24.793", "Id": "11021", "Score": "0", "body": "Although `switch` can be used with expressions, you should better only use literal/constant values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:33:24.383", "Id": "11023", "Score": "10", "body": "That's a very wrong use of a switch statement" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:34:55.010", "Id": "11024", "Score": "0", "body": "Would it be simpler to go with a if..else if..else construct. I don't understand your use of switch here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:07:55.607", "Id": "11048", "Score": "0", "body": "Conditional logic. Better way to do this without using if or case. ಠ_ಠ" } ]
[ { "body": "<p>You <strong>must not</strong> use conditional statements in combination with <code>switch</code>... that is THE DEVIL... because <code>switch/case</code> only interpretates <strong>values</strong> !</p>\n\n<p>Infact, what you did there equals</p>\n\n<pre><code>switch( true ) {\n case true/false:\n break;\n case true/false:\n break;\n etc.\n}\n</code></pre>\n\n<p>That is ohhh-so-wrong! Only use <code>switch</code> if you have well defined states/values which you want to check for. You totally should go with a <code>if/else</code> statement there.</p>\n\n<pre><code>if( val &gt; 50 ) {\n}\nelse if( val &lt; 50 ) {\n}\nelse { // val equals 50\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:09:03.237", "Id": "11032", "Score": "1", "body": "You are writing this as if it's technically wrong use `switch` the way Amit did, however technically it's not wrong at all. It is of course wrong, because it's a bad code style and affects readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:22:25.180", "Id": "11042", "Score": "1", "body": "I agree with @RoToRa. Switch statement like that works. If it was wrong it wouldn't work. Whether it's safe to do it this way or whether it aids readability it's a different question and an argumentative one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:23:19.813", "Id": "11043", "Score": "0", "body": "@jAndy: when you say `case true/false` it's actually the same with every case statement. The variable in switch is either of some value or it's not. The same with these expressions... So technically switch statement with case expressions is argumentative in its nature at best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:09:42.637", "Id": "11054", "Score": "0", "body": "@RobertKoritnik: Well, a `switch` statement is intended to check a variable for multiple values/states. The usage in the OPs code is totally confusing and potentially dangerous. Since his expressions can only end up beeing `true` or `false` you will never be able to have more than 2 `cases`. So again, this is pure evil." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T19:36:14.030", "Id": "11099", "Score": "1", "body": "You could quite easily have as many true/false cases as you want. The `switch` statement in JS is much more flexible than Java's or C's; it has no requirement that case values be unique, and doesn't require a constant/literal for the case expression. It'll just start at the first case that evaluates equal to the `switch` expression. The `switch (true)` thing is ugly, and an abuse of `switch`, and not optimizable into a jump table, but it's quite valid JS -- and any interpreter that can't deal with it is broken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T20:18:50.890", "Id": "11130", "Score": "0", "body": "@jAndy: I must totally agree with cHao... You can have many `case`-es as you need. They could be: **case (val < 50)** and next **case (val < 100)** and next **case (val < 150)** and so on and so forth. Javascript will go checking from one to the next to the next etc... Until it gets to one that returns `true`. Basically. Javascript will evaluate each when it runs not in front. But even though if it was evaluating before execution it would be important that **only one be `true` and all the rest would be `false` so it would know exactly which one to execute..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T21:45:05.813", "Id": "11133", "Score": "0", "body": "its a complete missuse of the statement and I'm still absolutely convinced it will always be trouble and confusion. Even if its not \"technically wrong\", its still wrong (imo)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:32:56.210", "Id": "7077", "ParentId": "7076", "Score": "14" } }, { "body": "<p>This <strong>completely replaces</strong> your <code>switch</code> statement by using <strike>inline if statements</strike> <strong>conditional</strong> operator:</p>\n\n<pre><code>$box.hide().delay(val &lt; 50 ? 300 : 0);\nvar s = val &gt; 50 ? 'XN' : (val &lt; 50 ? 'VN' : 'PN');\nanimations.animateBox($box.html('you have chosen ' + s));\n</code></pre>\n\n<p>the first line could be replaced by these two arguably more readable lines that omit the call to <code>delay()</code> function when not applicable:</p>\n\n<pre><code>$box.hide();\nval &lt; 50 &amp;&amp; $box.delay(300);\n</code></pre>\n\n<p>Since @GregGuida pointed out that this code is less readable I suppose I can make it more readable by better formatting it. And I'll use the suggestion of replacing the first line with two of them:</p>\n\n<pre><code>$box.hide();\n\n// only delay animation when value &lt; 50\nval &lt; 50 &amp;&amp; $box.delay(300);\n\nvar s = val &gt; 50 ? 'XN' :\n (val &lt; 50 ? 'VN' :\n 'PN');\n// set HTML\nanimations.animateBox($box.html('you have chosen ' + s));\n</code></pre>\n\n<p>Same code but visually less chaotic (even without comments it would look less chaotic) and much much more readable. At least much more readable than OP's original code. <strong>That I'm sure of.</strong> Readability is of course an argumentative disposition. But I'll leave that to others.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:45:49.630", "Id": "11027", "Score": "2", "body": "The only thing I would change us abstracting out the conditions into variables. Like `var isXN=val>50;` but that's just me. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T18:46:34.983", "Id": "11039", "Score": "5", "body": "The problem with this solution is that it is 100 times harder to read. this is code review not [code golf](http://codegolf.stackexchange.com/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:20:32.590", "Id": "11041", "Score": "0", "body": "@GregGuida: That may be, hence the two line replacement suggestion for the first line. But for the rest it does remove the excessive if statement and switch statement that OP was after. Quote: *Is there a better way to do this without using if or case statements* Unquote. My answer is **exactly that**. No `switch` nor `if` statement if we say that inline `if` is not an `if`... At least it doesn't seem like one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:39:50.883", "Id": "11046", "Score": "0", "body": "Your cleanup makes it much more readable, I guess I just disagree with the \"no if\" part of the question. If ever there was a place to use `if ... if else ... else` this is it. Also not to be a JS snob, but its called a [conditional operator](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Conditional_Operator)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:09:56.087", "Id": "11049", "Score": "0", "body": "Ternary's still technically an if. You're just not actually writing \"if\" in the code. The \"without if\" bit of the question is kind of absurd though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:29:24.293", "Id": "11051", "Score": "0", "body": "@BenBrocka: It would be absurd if it said _without code branching_. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:30:02.297", "Id": "11052", "Score": "0", "body": "@GregGuida: You're right. Inline if isn't the correct term. You're right it's called **conditional operator**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:43:12.570", "Id": "11053", "Score": "0", "body": "@RobertKoritnik between no case and no if (and the ternary operator really is an if IMO) you've pretty much run out of conditional operators in any standard coding style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T23:34:10.890", "Id": "11101", "Score": "0", "body": "@BenBrocka: jump tables can take the place of conditional operators, and in really large cases that's what you probably want to use. Of course, three isn't really large..." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:35:30.767", "Id": "7078", "ParentId": "7076", "Score": "18" } }, { "body": "<p>You can try something like:</p>\n\n<pre><code>var val = ui.value,\n $box = $('#message');\n var choice = (val &gt; 50) ? 'XN' : ((val &lt; 50) ? 'VN' : 'PN');\n\n if(val &lt; 50) {\n $box.hide().delay(300);\n } else {\n $box.hide();\n };\n\n animations.animateBox($box.html('you have chosen ' + choice));\n</code></pre>\n\n<p>You could remove the IF statement altogether if it weren't for the delay().</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:38:58.370", "Id": "11028", "Score": "0", "body": "What does .delay(0) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:40:57.267", "Id": "11029", "Score": "0", "body": "var delayAmount=(val<50)?300:0;\n$box.hide().delay(delayAmount);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:42:09.777", "Id": "11030", "Score": "0", "body": "delay stops execution for the number of milliseconds indicated. http://api.jquery.com/delay/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:50:04.253", "Id": "11031", "Score": "0", "body": "Here's a simple example. http://jsfiddle.net/Ccugd/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:37:57.170", "Id": "7079", "ParentId": "7076", "Score": "2" } }, { "body": "<p>You can use the conditional operator of you want to avoid <code>if</code> and <code>switch</code>. You can reduce some repetiton in the code using a variable for the chosen product:</p>\n\n<pre><code>var val = ui.value,\nvar box = $('#message');\nbox.hide().delay(val &lt; 50 ? 300 : 0);\nvar product =\n val &gt; 50 ? 'XN' :\n val &lt; 50 ? 'VN' :\n 'PN';\nanimations.animateBox(box.html('you have chosen ' + product));\n</code></pre>\n\n<p>You should still consider if the code is more readable using <code>if</code> statements:</p>\n\n<pre><code>var val = ui.value,\nvar box = $('#message');\nbox.hide();\nif (val &lt; 50) {\n box.delay(300);\n}\nvar product;\nif (val &gt; 50) {\n product = 'XN';\n} else if (val &lt; 50) {\n product = 'VN';\n} else {\n product = 'PN';\n}\nanimations.animateBox(box.html('you have chosen ' + product));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T17:21:21.230", "Id": "7088", "ParentId": "7076", "Score": "1" } }, { "body": "<p>My suggestions:</p>\n\n<ol>\n<li>use ternary operators;</li>\n<li>use single char;</li>\n<li>for prevent type casting, compare defined values with undefined;</li>\n<li>use logical \"and\" (<code>&amp;&amp;</code>) instead of <code>if</code>.</li>\n</ol>\n\n<p>Code snippet:</p>\n\n<pre><code>var val = ui.value,\n box = $('#message'),\n chr = 50 &gt; val ? 'V' : (50 &lt; val ? 'X' : 'P');\nbox.hide();\n50 &gt; val &amp;&amp; box.delay(300);\nanimations.animateBox(box.html('You have chosen ' + chr + 'N'));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-15T12:37:52.003", "Id": "107663", "ParentId": "7076", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T12:28:56.137", "Id": "7076", "Score": "14", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Animating one of three boxes based on a form value" }
7076
<p>Any suggestions on how I could improve it? </p> <p><a href="http://jsfiddle.net/sambenson/RmkEN/" rel="nofollow">jsFiddle</a></p> <pre><code>(function($){ $.extend({ notify: function(options, duration) { var // Default options object defaults = { inline: false, href: '', html: '', onStart: function(){}, onShow: function(){}, onComplete: function(){}, onCleanup: function(){}, onClosed: function(){} }, options = $.extend(defaults, options), // Elements &amp; Clones notifications_active = ($('ul#notification_area').length ? true : false), container = (notifications_active ? $('ul#notification_area') : $('&lt;ul&gt; &lt;/ul&gt;').attr('id', 'notification_area')), wrapper = $('&lt;li&gt;&lt;/li&gt;').addClass('notification'), // Useful variables clone, get_clone, close, start_countdown, element, north, south, east, west, content, add_notification; options.onStart.call(this); if(!notifications_active){ $('body').append(container); } get_clone = function(){ if(options.href){ if(options.inline){ return $(options.href).clone(); } else { return $('&lt;iframe&gt;&lt;/iframe&gt;').attr('src', options.href).css({width: '100%', height: '100%'}); } } else if(options.html){ return $(options.html); } } close = function(){ options.onCleanup.call(this); wrapper.fadeOut('fast', function(){ $(this).remove(); options.onClosed(); }) } start_countdown = function(){ setTimeout(function(){ close(); }, duration); } element = function(tag, cl, id){ var el = document.createElement(tag); if(cl){ el.className = cl; } if(id){ el.id = id; } return $(el); } add_notification = function(){ wrapper.append( element('div', 'notify_top').append( element('div', "notify_nw"), north = element('div', "notify_n"), element('div', "notify_ne") ), element('div', 'notify_center').append( east = element('div', "notify_w"), content = element('div', 'notify_content').append(clone), west = element('div', "notify_e") ), element('div', 'notify_bottom').append( element('div', "notify_se"), south = element('div', "notify_s"), element('div', "notify_sw") ) ); wrapper.css("visibility", "hidden").appendTo(container); if(options.close){ var close_elem = $('&lt;span&gt;&lt;/span&gt;').addClass('cl').html(options.close); content.append(close_elem); } var anim_length = 0 - parseInt(wrapper.outerHeight()); wrapper.css('marginBottom', anim_length); wrapper_height = wrapper.height(); north.width(parseInt(wrapper.width())-40); south.width(parseInt(wrapper.width())-40); east.height(parseInt(content.height())); west.height(parseInt(content.height())); options.onShow.call(this); wrapper.animate({marginBottom: 0}, 'fast', function(){ wrapper.hide().css('visibility', 'visible').fadeIn('fast'); if(duration){ start_countdown(); } if(!options.close){ wrapper.bind('click', function(){ close(); }) } else { close_elem.bind('click', function(){ close(); }) } options.onComplete.call(this); }); } clone = get_clone(); add_notification(); } }); })(jQuery); </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li><p>rename onClosed to onClose</p></li>\n<li><p>don't declare that group of useful variables at once, declare them as you go. Or, declare once but use a var statement. Some of them are used only in add_notification function, so move them there.</p></li>\n<li><p>break these lines</p>\n\n<pre><code>container = (notifications_active ? $('ul#notification_area') : $('&lt;ul&gt;&lt;/ul&gt;').attr('id', 'notification_area'));\n...\nif(!notifications_active){\n $('body').append(container);\n}\n</code></pre></li>\n</ul>\n\n<p>into these (you remove one conditional statement and it's easier to follow):</p>\n\n<pre><code>if (notifications_active) {\n container = $('ul#notification_area');\n} else {\n container = $('&lt;ul&gt;&lt;/ul&gt;').attr('id', 'notification_area'));\n $('body').append(container);\n}\n</code></pre>\n\n<ul>\n<li><p>rename the function element to something more explicit and simplify it. You never use the id argument. It could be something like:</p>\n\n<pre><code>createElement = function(tag, cl){\n return $(document.createElement(tag)).addClass(cl);\n}\n</code></pre></li>\n</ul>\n\n<p>you can use this helper in other places where you create elements, for example in this block:</p>\n\n<pre><code>if(options.close){\n var close_elem = $('&lt;span&gt;&lt;/span&gt;').addClass('cl').html(options.close);\n content.append(close_elem);\n}\n</code></pre>\n\n<ul>\n<li><p>parseInt should always be used with the radix, parseInt(999, 10) for decimal numbers</p></li>\n<li><p>remove this useless line</p>\n\n<pre><code>wrapper_height = wrapper.height();\n</code></pre></li>\n<li><p>it seems you don't pass a close option, so all lines that check options.close are useless or don't do what you expect. If users can provide this value (for instance, if you mention in the documentation, they could try), then set a default value.</p></li>\n<li><p>these last lines are obscure</p>\n\n<pre><code>clone = get_clone();\nadd_notification(); \n</code></pre></li>\n</ul>\n\n<p>it turns out that add_notification uses clone, so it would be better to pass it as a parameter to make it explicit. As a general rule, it's better to pass parameters than putting everything in the same scope and rely on them having the expected value all the time. You could have passed parameters to start_countdown, get_clone and they would be more generic functions.</p>\n\n<ul>\n<li>a more subjective topic, you use underscore to separate words in variables, but the options you accept are in camel case, I would prefer using the same convention for both (and would prefer camel case).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T10:26:33.533", "Id": "7135", "ParentId": "7080", "Score": "2" } } ]
{ "AcceptedAnswerId": "7135", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T14:12:34.157", "Id": "7080", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "jQuery notifications plugin" }
7080
<p>Requirements:<br /> When the page (or in the case of the example Frame) expands, the only column to expand with the table should be 'unfrozen' columns (without the 'freeze' class). </p> <p><a href="http://jsfiddle.net/BZDyr/4/" rel="nofollow">here is the live demo</a> <em>The jQuery is there to show dynamic content, it is not the code under review</em></p> <p>What I really don't like is that is seems to hacky to just set the width of the column to 1px... I can forsee this causing issues with older/junkier browsers. </p> <p><strong>HTML</strong></p> <pre><code>&lt;!-- snippet --&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="freeze"&gt;id&lt;/th&gt; &lt;th class="freeze"&gt;name&lt;/th&gt; &lt;th&gt;description&lt;/th&gt; &lt;th class="freeze"&gt;something else&lt;/th&gt; &lt;th class="freeze"&gt;actions&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.data-table { width: 100%; font-size: 90%; background-color: #fff; border: 1px solid #666; } .data-table th { white-space: nowrap; text-align: center; } .data-table td { font-size: 90%; color: #222; } .data-table td:last-child { white-space: nowrap; } .data-table td, .data-table th { padding: 6px; border-right: 1px solid #999; } .data-table td:last-child, .data-table th:last-child { border: none; } .data-table tbody tr { border: 1px solid #666; } .data-table tbody tr:nth-child(odd) td { background-color: #efefef; } .freeze { width: 1px; } </code></pre> <p>This works in at least IE8, Chrome 16, and FF8</p>
[]
[ { "body": "<p>IMHO it's completely fine to set the width like this. Table cell widths have always be defined to be a \"minimum width\". </p>\n\n<p>As long the table doesn't have <code>table-layout: fixed</code> or the cells don't have <code>overflow</code> set to anything else than <code>visible</code>, I don't believe any browser (old or new) would have any problems width this.</p>\n\n<p>The only nitpick I would have, it that the size of <code>1px</code> feels wrong to me, mostly because this forces the column to wrap as much as possible and depending on the content this may not look very good. I would suggest <code>1em</code> (purely because it \"feels\" better :-) and maybe a larger minimal width such as <code>10em</code> would be suitable for some columns.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:23:57.580", "Id": "11034", "Score": "0", "body": "Good suggestions, thankyou!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T15:21:51.843", "Id": "7083", "ParentId": "7081", "Score": "4" } } ]
{ "AcceptedAnswerId": "7083", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T14:54:09.663", "Id": "7081", "Score": "4", "Tags": [ "html", "css" ], "Title": "Is this the best way to collapse a column width?" }
7081
<p>I just rewrote this:</p> <pre><code>if (budgetRemaining != 0 || totalOpenInvoices != 0) { } </code></pre> <p>Like this:</p> <pre><code>if (new[] { budgetRemaining, totalOpenInvoices }.Any(c =&gt; c != 0)) { } </code></pre> <p>If I had seen that before I ramped up on Linq, it would have confused me. Now that I've been learning functional programming and using Linq, it seems natural, but is it sacrificing simplicity?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:13:05.657", "Id": "11040", "Score": "0", "body": "Does totalOpenInvoices represent the sum of the monetary amount of the open invoices, or is it just the number of invoices that are open?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:30:12.170", "Id": "11044", "Score": "0", "body": "it's the sum of the amounts from every open invoice" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:13:03.323", "Id": "11050", "Score": "37", "body": "Your rewrite is a lot harder to read, IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:51:04.317", "Id": "11056", "Score": "16", "body": "this is a case of \"I've just learned some really cool stuff, let me try it out on the first thing that comes my way\". Been there. Done it. Not worth it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:45:01.107", "Id": "11073", "Score": "2", "body": "this syntax is odd to people who are not familiar with functional programming. However, it might be worth it when you have more than 2 terms to check. also extracting the lambda expression into a named property might make it more readable and please people who prefer a fluent style.\nprivate Func<int, bool> IsNotZero\n{\n get { return c => c != 0; }\n}\n...\nif (new[] { budgetRemaining, totalOpenInvoices, otherThings, moreStuff, etc, ... }.Any(IsNotZero))\n{\n}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:49:12.130", "Id": "11076", "Score": "0", "body": "I read the second version and pretty much just took an extra second to JIT compile it into version 1 in my head. It's not horrible or anything, but that second is wasted for no real gain. At run time, the best case is the compiler would do the same, but I **highly** doubt it. Though in practical terms the efficiency difference is probably irrelevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:49:59.093", "Id": "11077", "Score": "0", "body": "@Tion, I had the same thought as you - i suppose the converse is that if even one of the items in the array needs to be evaluated by a slightly different condition, it breaks down whereas in the un-factored version one could change just one of the comparison operators without impacting the whole thing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T23:33:04.660", "Id": "11079", "Score": "0", "body": "@psr, part of the reason I originally rewrote it was based on the idea that functional style results in code that expresses the intention of the author - in other words I was thinking \"if any of these are not zero\" and without the wierdness of the array allocation, the code would pretty much echo that. Ultimately I reverted what I personally prefer bec. its impractical to go against the grain for minimal return." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T06:32:36.143", "Id": "11087", "Score": "0", "body": "readability fail. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T19:54:02.247", "Id": "11102", "Score": "0", "body": "You can grab your nose using either hand or by moving your hand around the back of your neck. I'd say keep it simple." } ]
[ { "body": "<p>Seems to be swatting a fly with a Buick to me. The first form seems pretty concise and the variable names are quite descriptive. The second form creates a new object (the array) which will eventually have to be GC'd and introduces a new lambda variable, <code>c</code> which doesn't seem descriptive any more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T17:47:15.127", "Id": "11037", "Score": "0", "body": "http://www.simple-talk.com/dotnet/performance/the-top-5-.net-memory-management-misconceptions/ The object would not be \"garbage collected\" unless it was still in use at time of collection. That is, if it wasn't in use, it would not get moved to Gen1, it would just be wiped." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T18:05:00.477", "Id": "11038", "Score": "4", "body": "Other way around: it would be collected if NOT still in use. If it WAS still in use, it would move to Gen1. But the point is, there's an array created and not referenced anywhere else but the condition if the `if` statement so it would be instantly eligible for collection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:40:54.060", "Id": "11047", "Score": "2", "body": "Using the `Any()` method here is overkill in this case. It should be reserved for the longer cases where there are maybe 4 or more separate conditions or if you just happen to have the collection lying around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:55:35.557", "Id": "11057", "Score": "6", "body": "GM called, and they don't like you calling their Buicks fly swatters. :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T17:39:12.857", "Id": "7089", "ParentId": "7087", "Score": "48" } }, { "body": "<p>As a Java developer, the first is much easier to read. It could be confusing too: why the author use LINQ instead of a simple <code>||</code>? It reminds me the <a href=\"http://en.wikipedia.org/wiki/Law_of_the_instrument\">law of the instrument</a>: \"if all you have is a hammer, everything looks like a nail\".</p>\n\n<p>Anyway, maybe it's worth creating a well-named local variable for the condition which could help the readers:</p>\n\n<pre><code>boolean needName = budgetRemaining != 0 || totalOpenInvoices != 0\nif (needName) {\n ...\n}\n</code></pre>\n\n<p>Creating a named local variable would improve the readability of the second version too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T13:08:48.263", "Id": "11141", "Score": "1", "body": "I would prefer to replace the local variable needName with a private function needName()" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T17:43:56.213", "Id": "7090", "ParentId": "7087", "Score": "22" } }, { "body": "<p>If possible, I might prefer to do something like this:</p>\n\n<pre><code>IEnumerable&lt;decimal&gt; GetBalances()\n{\n decimal budgetRemaining = 0M;\n\n // calculate budget remaining\n\n yield return budgetRemaining;\n\n decimal totalOpenInvoices = 0M;\n\n // calculate the total of the open invoices\n\n yield return totalOpenInvoices;\n\n // ... calculate and yield any other balances that require consideration\n}\n</code></pre>\n\n<p>and then I could write the if statement like this:</p>\n\n<pre><code> if (this.GetBalances().Any(balance =&gt; balance != 0M))\n {\n }\n</code></pre>\n\n<p>Note: I doubt that I would use this approach if I only needed to check 2 balances, but I might do this if I had very many different balances that needed to be checked.</p>\n\n<h3>Original Answer</h3>\n\n<p>EDIT: The comment on the question indicates that the totalOpenInvoices variable represents the total monetary amount of the open invoices, therefore this answer doesn't really apply to the question. I'll leave it here, though, as I feel that the argument would still be valid for the situation described in this answer.</p>\n\n<p>Does totalOpenInvoices represent the sum of the monetary amount of the open invoices, or is it just the number of invoices that are open?</p>\n\n<p>If the latter, then one reason why I don't like this approach is because you're sort of comparing apples and oranges. You're saying that the check <code>budgetRemaining != 0</code> is similar in nature to the check <code>totalOpenInvoices != 0</code>, and the only difference is the input variable (either budgetRemaining or totalOpenInvoices).</p>\n\n<p>I'll try illustrate why this doesn't make sense to me by breaking the if statement down in a different way. I'll move the <code>!= 0</code> code out into a delegate called stillHasMoney:</p>\n\n<pre><code>Func&lt;decimal, bool&gt; stillHasMoney = (amount) =&gt; amount != 0;\n\nif (stillHasMoney(budgetRemaining) || stillHasMoney(totalOpenInvoices))\n{\n}\n</code></pre>\n\n<p>Now, does this code still make sense? If totalOpenInvoices represents the number of open invoices, not the sum of the monetary amount of the open invoices, then this code doesn't seem correct to me. It's like saying \"I had 5 turtles and gave away 2. How much money is left?\" Similarly, this code is saying \"I had 5 open invoices and closed 2. How much money is left?\" Granted, invoices translate to money more easily than turtles, but the point is, do you care about the number of open invoices or the sum of their monetary value?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:34:39.343", "Id": "7094", "ParentId": "7087", "Score": "5" } }, { "body": "<p>Fancy is not the word for it. This is insane. Ever heard of the KISS principle? Keep-it-simple-stupid. Unless of course you are intentionally looking for ways to make your code look obfuscated, and your executable file bloated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T11:56:00.640", "Id": "11091", "Score": "3", "body": "True. Solutions should be as simple as possible (but no simpler)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:58:35.400", "Id": "7095", "ParentId": "7087", "Score": "29" } }, { "body": "<p>In C# you have some syntactic noise, which makes this code even less readable, overweighing the benefits of such a low-yielding abstraction by a large margin. Even in a language like Haskell, famous for its abstraction power, the best you can do is this:</p>\n\n<pre><code>any (/= 0) [budgetRemaining, totalOpenInvoices]\n</code></pre>\n\n<p>Which is, although usable, still longer than</p>\n\n<pre><code>budgetRemaining /= 0 || totalOpenInvoices /= 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T23:24:18.037", "Id": "7102", "ParentId": "7087", "Score": "8" } }, { "body": "<p>Sometimes it's just handier to have a function like </p>\n\n<pre><code>bool IsAlive(..)\n{\n return (budgetRemaining != 0 || totalOpenInvoices != 0);\n}\n</code></pre>\n\n<p>it doesn't directly apply to your question, just a side note:)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T16:59:37.200", "Id": "7455", "ParentId": "7087", "Score": "1" } }, { "body": "<p>Assuming both <code>budgetRemaining</code> and <code>totalOpenInvoices</code> are guaranteed to be non-negative, you could write:</p>\n\n<pre><code>if (budgetRemaining + totalOpenInvoices &gt; 0)\n{\n}\n</code></pre>\n\n<p>Of course, while that simplifies the code, it sacrifices clarity and maintainability. So don't do that. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T23:44:03.937", "Id": "7474", "ParentId": "7087", "Score": "3" } } ]
{ "AcceptedAnswerId": "7089", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T17:10:46.653", "Id": "7087", "Score": "30", "Tags": [ "c#", "linq" ], "Title": "Are these if-statements too fancy?" }
7087
<p>I wrote a query to run the same query across multiple databases and combine the results. While it seems plenty quick I was wondering if there is a better way to do this.</p> <pre><code>create table #serverlist( ID smallint IDENTITY(1,1), dbName varchar(50) ) create table #browsercounts( ID smallint IDENTITY(1,1), --Email varchar(50), Browser varchar(50), Counts int) insert into #serverlist select name from sys.databases where name like '%Test2Portal%' and name not like '%_Test%' Declare @counter int, @rows int set @counter = 1 set @rows = (select COUNT(dbName) from #serverlist) while (@counter &lt;= (@rows)) Begin Declare @SQL varchar(1000) Declare @database varchar(50) = (select dbName from #serverlist where ID = @counter) Select @SQL = 'select Browser, COUNT(Browser) as Counts from ' + @database+ '.dbo.Session where Browser is not null group by Browser' insert into #browsercounts Exec (@SQL) set @counter += 1 End Select * From #browsercounts drop table #serverlist drop table #browsercounts </code></pre>
[]
[ { "body": "<p>You could skip the while clause and execute it as one statement - something like</p>\n\n<pre><code>select @SQL = @SQL + ' select Browser, COUNT(Browser) as Counts from ' + \n @database+ '.dbo.Session where Browser is not null group by Browser UNION ALL' from #serverlist\n\n--you should get rid of the last union all statement in the string \nset @sql = left(@sql, len(@sql) - 10)\n\ninsert into #browsercounts\n Exec (@SQL)\n</code></pre>\n\n<p>--but just an idea ....</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:45:12.703", "Id": "11062", "Score": "0", "body": "Seems all right, only there should be a space before `select` (which I've added now)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:57:51.623", "Id": "11063", "Score": "0", "body": "So with this setup how do I actually get the database name for the @database variable? I had a select that incremented in the loop that pulled it for each one. I am not clear how that value is getting set in this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T19:53:14.797", "Id": "7097", "ParentId": "7096", "Score": "1" } }, { "body": "<p>You probably don't need any temp tables unless you need access to these temp tables across different stored procedures, here is how I would write it.</p>\n\n<pre><code>DECLARE @sql VARCHAR(MAX)\n\nSELECT @Sql = COALESCE(@sql + ' UNION ALL ', '') + 'SELECT [' + name + '].dbo.Session.Browser, COUNT(['+name+'].dbo.Session.Browser) AS Counts FROM [' + name + '].dbo.Session WHERE [' + name + '].dbo.Session.Browser IS NOT NULL GROUP BY ['+name+']dbo.Session.Browser'\nfrom sys.databases\nwhere name like '%Test2Portal%' and name not like '%_Test%'\n\nEXEC @sql --this will perform the select for you\n</code></pre>\n\n<p>hope this is helpful</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T20:55:26.927", "Id": "11064", "Score": "1", "body": "The OP seems satisfied with non-delimited names, judging by their query, but generally it is a good idea to delimit them in such cases, like you did. Only it would be safer to use `QUOTENAME()` rather than hardcoded `[...]` around the name. For, if there was a `]` in the name, `QUOTENAME()` would escape it correctly, while with hardcoded brackets the name would remain unchanged and the query would then fail to execute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:07:21.110", "Id": "11065", "Score": "0", "body": "@AndriyM sounds like a good idea, never used QUOTENAME() before, didn't know you can use [ or ] in a database name but I just validated it and you are right" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T20:35:13.770", "Id": "7098", "ParentId": "7096", "Score": "4" } }, { "body": "<p>I had this same issue today. I already had a table of the databases, so I wrote a program. It could be done with dynamic sql in the same way.</p>\n\n<p>That said, I have huge regrets that my original design used multiple databases in the first place and maybe the reality is that the reason its not something readily doable is related to the fact that its not something that ideally needs to be done (just a thought).</p>\n\n<pre><code>void Main()\n{\n string sql = @\"\n print '@Name';\n print '[Lumos Labs ]-&gt;[Lumos Labs, Inc.]'; update Advertiser set Name='Lumos Labs, Inc.' where Name='Lumos Labs '\n print '[Emma Stein]-&gt;[Emma Stine]'; update Advertiser set Name='Emma Stine' where Name='Emma Stein'\n print '[Lieferheld GmbH]-&gt;[Lieferheld]'; update Advertiser set Name='Lieferheld' where Name='Lieferheld GmbH'\n print '[Monster]-&gt;[Monster Worldwide]'; update Advertiser set Name='Monster Worldwide' where Name='Monster'\n print '[Quinstreet / Surehits]-&gt;[QuinStreet LLC]'; update Advertiser set Name='QuinStreet LLC' where Name='Quinstreet / Surehits'\n print '[Eye Buy Now]-&gt;[T33ZE/Specs Optics/EyeBuyNow]'; update Advertiser set Name='T33ZE/Specs Optics/EyeBuyNow' where Name='Eye Buy Now'\n print '[T33ZE/Specs Optics/]-&gt;[T33ZE/Specs Optics/EyeBuyNow]'; update Advertiser set Name='T33ZE/Specs Optics/EyeBuyNow' where Name='T33ZE/Specs Optics/'\n print '[T33ZE]-&gt;[T33ZE/Specs Optics/EyeBuyNow]'; update Advertiser set Name='T33ZE/Specs Optics/EyeBuyNow' where Name='T33ZE'\n print '[SmartDate USD]-&gt;[Smartdate]'; update Advertiser set Name='Smartdate' where Name='SmartDate USD'\n print '[Vistaprint US]-&gt;[Vistaprint]'; update Advertiser set Name='Vistaprint' where Name='Vistaprint US'\n print '[Ultradiamond]-&gt;[UltraDiamonds.com]'; update Advertiser set Name='UltraDiamonds.com' where Name='Ultradiamond'\n print '[Tranzact Media]-&gt;[Remedy Health Media/MediZine]'; update Advertiser set Name='Remedy Health Media/MediZine' where Name='Tranzact Media'\n print '[MyCityDeal EUR]-&gt;[MyCityDeal]'; update Advertiser set Name='MyCityDeal' where Name='MyCityDeal EUR'\n \";\n\n foreach (var item in DADatabases.Skip(1))\n {\n string query = sql.Replace(\"@Name\", item.Name);\n\n foreach (var line in query.Split('\\n').Where(s =&gt; !string.IsNullOrWhiteSpace(s)))\n {\n try \n {\n Console.WriteLine (\"&gt;&gt;\" + line);\n\n using(var con = new SqlConnection(item.Connection_string))\n using(var cmd = new SqlCommand(line, con))\n {\n con.InfoMessage += (s, e) =&gt;\n {\n Console.WriteLine (\"&gt;\" + e.Message);\n };\n con.Open();\n int i = cmd.ExecuteNonQuery();\n\n Console.WriteLine (\"Rows Affected: \" + i);\n }\n }\n catch(Exception e) \n { \n Console.WriteLine (\"Exception: \" + e.Message); \n }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:46:31.277", "Id": "7100", "ParentId": "7096", "Score": "1" } } ]
{ "AcceptedAnswerId": "7098", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-21T18:42:02.547", "Id": "7096", "Score": "2", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Query for combining results of same query running across multiple databases" }
7096
<p>Here is my attempt at a floaty Bar module, used in a mobile application. There are several "bars", which stick to the top of the browser window once they are passed. When the next bar is reached, it takes over that sticky position... Based on: <a href="http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-css.html" rel="nofollow">http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-css.html</a></p> <pre><code>CMBi.floatyBar = (function(){ var dayGroups = []; function getPositions() { var that = this; $.each( $('.day-group'), function(i, day) { if ($(this).length &gt;= 1) { // Add the initial starting Y position to the object this.initialYPosition = $(this).offset().top; that.dayGroups[i] = this; } }); } function setPositionsOnScroll() { var _daygroups = dayGroups, that = this; if ( window.scrollY &lt; _daygroups[0].initialYPosition) { this.restoreInitialPosition(_daygroups[0]); } for ( var i = 0; i &lt; _daygroups.length; i++ ) { // Get the next floaty bar position var _nextYposition = _daygroups[i+1] ? _daygroups[i+1].initialYPosition : config.vars.docHeight; // Between two bars, or betweem the last bar and the end of the doc if ( window.scrollY &gt; _daygroups[i].initialYPosition &amp;&amp; window.scrollY &lt; _nextYposition) { // Stick the bar to the top that.setTop(_daygroups[i]); // Restore initial positions of the other bars $.each(_daygroups, function(index, day) { if (index !== i) { that.restoreInitialPosition(day); } }); } } } function setTop(element) { // Called when it's time for the floaty bar to move var _yPos = window.scrollY - element.initialYPosition; element.style['-webkit-transform'] = 'translateY(' + _yPos + 'px)'; } function restoreInitialPosition(element) { // Called when the floaty bar is dismissed var _yPos = 0; element.style['-webkit-transform'] = 'translateY(' + _yPos + 'px)'; } return { init : getPositions, setPositions : setPositionsOnScroll }; }()); </code></pre>
[]
[ { "body": "<p>What I tend to do in these situations is have two states for the floaty thing:</p>\n\n<ol>\n<li>When it's not in \"stay on the page\" mode, it has <code>position:relative</code>.</li>\n<li>When the page is scrolled down enough, it gets <code>position:fixed</code> and stays on the page.</li>\n</ol>\n\n<p>It is not animation intensive at all, it's more like the way gmail used to be before the recent changes. You only change the element's style when the page scrolls up or down past a certain point, but most scroll events you just ignore.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T19:41:37.347", "Id": "11391", "Score": "1", "body": "Position fixed is not available in mobile safari on iOS < 5 (same for the Android browser). That's why it's implemented like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T13:11:02.503", "Id": "18058", "Score": "1", "body": "Thus you should support `position: fixed` on browsers that support it and fallback to something else on those that don't. See: https://github.com/filamentgroup/jQuery-Mobile-FixedToolbar-Legacy-Polyfill" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T04:22:16.010", "Id": "7249", "ParentId": "7099", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T22:41:52.633", "Id": "7099", "Score": "3", "Tags": [ "javascript" ], "Title": "Floaty bars module, need improvement?" }
7099
<p>I'm somewhat new to SQL (using it in the past but only being exposed to it heavily in my current role). Unfortunately nobody at my current company has really given me any advice on formatting. How can I format this better / what should I avoid doing that I may have done below? Any feedback on re-factoring would be greatly appreciated also.</p> <pre><code>/* Uncomment when testing this SQL */ declare @period_id as int = 252 -- ### Potentially redundant ### declare @building_id as varchar(10) = '20500' declare @section_name as varchar(20) = 'ALL' declare @lease_expiry_period as int = 1; /* SQL for Section_Name parameter on report */ select 'ALL', 1 as order_by union all select distinct upper(isnull(section_name, '')) as section_name, 2 as order_by from property.lease_period where section_name &lt;&gt; '' order by 2; declare @truncateddate as date = dateadd(d,0,datediff(d,0,getdate())); /* SQL for Report (dsDetail) */ select lp.period_id , lp.building_id , lp.suite_id , lp.lease_id , lp.tenant_trading_name, lp.suite_status , lp.suite_name , lp.suite_area, lp.lease_status , lp.lease_current_start_date , lp.lease_current_stop_date , lp.lease_current_term , lp.lease_occupancy_date , lp.lease_vacated_date from property.lease_period lp where lp.lease_current_stop_date &lt; @truncateddate and (upper(lp.lease_status) = 'ACTIVE' or upper(lp.lease_status) = 'OVERHOLDING') --and lp.period_id = @period_id -- ##Potentially redundant (query now running into the future) and lp.building_id = @building_id and not exists ( select 1 from lease_deal.lease l where lp.building_id = l.building_id and lp.lease_id = l.lease_id ) and (@section_name = 'ALL' or (@section_name &lt;&gt; 'ALL' and upper(section_name) = upper(@section_name))) and lp.lease_current_stop_date between @truncateddate and dateadd(MONTH, @lease_expiry_period, @truncateddate) order by period_id desc </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T15:44:49.230", "Id": "11441", "Score": "0", "body": "FYI, Unless you have a persisted calculated column for upper(lp.lease_status) and upper(lp.section_name), you may want to research the impact of using a function within your where clause. Check out the following SO article for more details: http://stackoverflow.com/q/799584/5685" } ]
[ { "body": "<p>What you've got is pretty readable, but there are a few points to make:</p>\n\n<ol>\n<li>Your sub-query is written with a different indentation style from the main query.</li>\n<li>I prefer to see the keywords in upper-case.</li>\n<li><p>Personally, I dislike spaces before commas intensely (and you aren't 100% consistent about adding them). However, I loathe even more the style where the comma is put at the start of the next line:</p>\n\n<pre><code> item1\n , item2\n , item3\n</code></pre></li>\n<li><p>I'd use explicit AS to introduce table aliases. At least on the DBMS I use mainly, using AS gives a degree of future-proofing against aliases that become keywords in a later version of the product. That is, writing <code>FROM SomeTable st</code> runs into a problem later if <code>st</code> becomes a keyword, but writing <code>FROM SomeTable AS st</code> avoids that problem. Whether this helps in other DBMS is open to debate.</p></li>\n</ol>\n\n<p>For your query, I'd probably write:</p>\n\n<pre><code>SELECT lp.period_id,\n lp.building_id,\n lp.suite_id,\n lp.lease_id,\n lp.tenant_trading_name,\n lp.suite_status,\n lp.suite_name,\n lp.suite_area,\n lp.lease_status,\n lp.lease_current_start_date,\n lp.lease_current_stop_date,\n lp.lease_current_term,\n lp.lease_occupancy_date,\n lp.lease_vacated_date\n FROM property.lease_period AS lp\n WHERE lp.lease_current_stop_date &lt; @truncateddate \n AND (UPPER(lp.lease_status) = 'ACTIVE' OR UPPER(lp.lease_status) = 'OVERHOLDING')\n AND lp.building_id = @building_id\n AND NOT EXISTS\n (SELECT *\n FROM lease_deal.lease AS l\n WHERE lp.building_id = l.building_id\n AND lp.lease_id = l.lease_id\n )\n AND (@section_name = 'ALL' \n OR (@section_name &lt;&gt; 'ALL' AND UPPER(section_name) = UPPER(@section_name)))\n AND lp.lease_current_stop_date BETWEEN @truncateddate AND\n DATEADD(MONTH, @lease_expiry_period, @truncateddate)\n ORDER BY period_id DESC;\n</code></pre>\n\n<p>Sometimes, I'd indent the sub-query more than I did here, occasionally even placing it after the EXISTS:</p>\n\n<pre><code> AND NOT EXISTS (SELECT *\n FROM lease_deal.lease AS l\n WHERE lp.building_id = l.building_id\n AND lp.lease_id = l.lease_id\n )\n</code></pre>\n\n<p>That has a tendency to run off the right-hand edge of the screen, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T07:55:10.153", "Id": "11088", "Score": "1", "body": "Just wondering what DBMS you're using (in relation to declaring 'as' explicitly)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T15:41:28.117", "Id": "11093", "Score": "0", "body": "See my profile :) Informix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T15:42:07.153", "Id": "11094", "Score": "3", "body": "You will find the style with the comma at the start of the next line very useful if you do a lot of copying/cutting and pasting column names around. I am so tired of SQL parsers bitchslapping me just because I forgot an extra comma right before the 'FROM' keyword." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T15:45:32.977", "Id": "11095", "Score": "0", "body": "Very valid point - also good when commenting lines out. Might adopt that - appreciated. Would upvote you but not enough karma yet :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T15:52:56.100", "Id": "11096", "Score": "1", "body": "I know that people use the leading comma because it makes it easier to move code around without fogettting to to remove unwanted trailing commas; it can also reduce the number of lines changed when you add a new column at the end of the select-list (because you don't change what was the last line; you only add a new one). Neither is, IMNSHO (but it is only _opinion_) sufficient excuse to justify the violence to the normal use of comma after words. It is an ugly and unwarranted abuse of the syntax. But I'm an old fuddy-duddy, and you aren't on my team, so you can do as you see fit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T15:47:53.937", "Id": "11442", "Score": "0", "body": "One of the nice features of RedGate's SQL Prompt is that it can quickly convert your SQL to a more consistent format and has options to have leading or trailing commas. :D" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T07:32:50.157", "Id": "7106", "ParentId": "7101", "Score": "11" } } ]
{ "AcceptedAnswerId": "7106", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T23:00:01.350", "Id": "7101", "Score": "5", "Tags": [ "mysql", "sql", "sql-server", "t-sql" ], "Title": "SQL - How's my formatting?" }
7101
<p>I'm building a web application in Java. I'm new to Java, so before I get too far into this... I'm hoping to take advantage of all the experience here and learn the problems with this setup.</p> <p><strong>My Servlet</strong></p> <pre><code>package cms.content; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ben */ @WebServlet(name = "EditServlet", urlPatterns = {"/content/edit"}) public class EditServlet extends library.Controller { @Override public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.loadView(request, response, "/content/edit"); response.getWriter().write("Hi"); System.out.println("EditServlet loaded"); } } </code></pre> <p><strong>My Controller</strong></p> <pre><code>package library; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Ben */ public class Controller extends HttpServlet { public final library.MySQL db; public Controller() { this.db = new MySQL(); } public void loadView (HttpServletRequest request, HttpServletResponse response, String view) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher(view+".jsp"); response.setContentType("text/html;charset=UTF-8"); System.out.println("MyServlet::LoadView() success"); dispatcher.forward(request, response); } } </code></pre> <p><strong>My View</strong></p> <pre><code>&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;JSP Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;This is edit.jsp&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I haven't tried to pass any parameters to this view or anything like that. But are there any obvious problems or improvements that need to be made?</p>
[]
[ { "body": "<p>First off, its not clear what you're trying to achieve, so its hard to evaluate. </p>\n\n<p>But, looking a the code there comes after you forward to the view, that could be confusing, because it will still execute. </p>\n\n<p>At a higher level, I also don't really see the need for this complicated of a setup to get to your edit page when you can just link straight to the edit jsp all nice an RESTful like. If you're just experimenting and trying to learn that's cool, but if you're really trying to get something done then you should look at just using an existing framework.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T03:43:41.300", "Id": "7105", "ParentId": "7104", "Score": "1" } }, { "body": "<ol>\n<li><p>Instead of printing messages with <code>System.out</code> you should use a logger framework (for example, SLF4J and Logback). See: <a href=\"https://stackoverflow.com/questions/2727500/log4j-vs-system-out-println-logger-advantages\">log4j vs. System.out.println - logger advantages?</a></p></li>\n<li><p>The package in the <code>public final library.MySQL db;</code> is unnecessary, since the file is in the <code>library</code> package.</p></li>\n<li><p><code>library</code> is not a good package name. See: <a href=\"http://c2.com/ppr/wiki/JavaIdioms/JavaPackageNames.html\" rel=\"nofollow noreferrer\">Java Package Names on c2.com</a></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-09T15:51:31.903", "Id": "12419", "ParentId": "7104", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T03:19:38.113", "Id": "7104", "Score": "1", "Tags": [ "java", "html", "mvc", "jsp", "servlets" ], "Title": "Is there a more efficient way of loading views within my java app?" }
7104
<p>I have a <code>TreeView</code> called <code>myTreeView</code>. I want to be able to write a single statement after which <code>myTreeView.SelectedNode</code> is <code>null</code>, but <code>TreeView.SelectedNode</code> doesn't have a setter. I've looked at the decompiled source of <code>TreeView</code>, and there <em>is</em> a <code>SetSelectedNode</code> method (that can accept <code>null</code>), but it's <code>internal</code>.</p> <p>So I made this extension method:</p> <pre><code>public static void ClearSelection(this TreeView treeView) { var currentSelection = treeView.SelectedNode; if (currentSelection != null) { currentSelection.Selected = false; } } </code></pre> <p>and now I can just say</p> <pre><code>myTreeView.ClearSelection(); </code></pre> <p>But this seems insane. Am I missing something?</p>
[]
[ { "body": "<p>If you havent already figured it out:</p>\n\n<pre><code>currentSelection.SelectedNode.Checked = false;\n</code></pre>\n\n<p>Hope that helps :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T22:47:36.313", "Id": "11403", "Score": "2", "body": "I think you're confusing the `Checked` and `Selected` properties. If the `TreeView` has `ShowTextBoxes = true` then it will show a checkbox next to each node. These can be checked and unchecked, and you can retrieve checked nodes with the `CheckedNodes` property. However, when a node is clicked it becomes selected (provided it is not a navigation node). This is then the `SelectedNode` - irrespective of whether it has been checked." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T22:00:54.443", "Id": "7124", "ParentId": "7112", "Score": "0" } }, { "body": "<p>There's no in-built method to do this. Your extension method looks great.</p>\n\n<p>Even if <code>TreeView</code> did have an obscurely-named method to clear its selected node, I can only imagine it doing exactly the same as what you've written anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T22:43:47.927", "Id": "7289", "ParentId": "7112", "Score": "2" } } ]
{ "AcceptedAnswerId": "7289", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T14:12:50.637", "Id": "7112", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Is this really what has to be done to clear the selection of an ASP.NET TreeView?" }
7112
<p>I am writing a script that takes one CSV file searches for a value in another CSV file then writes an output depending on the result it finds.</p> <p>I have been using Python's CSV Distreader and writer. I have it working, but it is very inefficient because it is looping through the 2 sets of data until it finds a result.</p> <p>There are a few bits in the code which are specific to my setup (file locations etc), but I'm sure people can see around this.</p> <pre><code># Set all csv attributes cache = {} in_file = open(sript_path + '/cp_updates/' + update_file, 'r') reader = csv.DictReader(in_file, delimiter= ',') out_file = open(sript_path + '/cp_updates/' + update_file + '.new', 'w') out_file.write("StockNumber,SKU,ChannelProfileID\n") writer = csv.DictWriter(out_file, fieldnames=('StockNumber', 'SKU', 'ChannelProfileID'), delimiter=',') check_file = open(sript_path + '/feeds/' + feed_file, 'r') ch_file_reader = csv.DictReader(check_file, delimiter=',') #loop through the csv's, find stock levels and update file for row in reader: #print row check_file.seek(0) found = False for ch_row in ch_file_reader: #if row['SKU'] not in cache: if ch_row['ProductCode'] == row[' Stock']: Stk_Lvl = int(ch_row[stk_lvl_header]) if Stk_Lvl &gt; 0: res = 3746 elif Stk_Lvl == 0: res = 3745 else: res = " " found = True print ch_row print res cache[row['SKU']] = res if not found: res = " " #print ch_row #print res cache[row['SKU']] = res row['ChannelProfileID'] = cache[row['SKU']] writer.writerow(row) </code></pre> <p>This is a few lines from my <code>in_file</code> and also the outfile is the same structure. It just updates the <code>ChannelProfileID</code> depending on the results found.</p> <blockquote> <pre class="lang-none prettyprint-override"><code>"StockNumber","SKU","ChannelProfileID" "10m_s-vid#APTIIAMZ","2VV-10",3746 "10m_s-vid#CSE","2VV-10",3746 "1RR-01#CSE","1RR-01",3746 "1RR-01#PCAWS","1RR-01",3746 "1m_s-vid_ext#APTIIAMZ","2VV-101",3746 </code></pre> </blockquote> <p>This is a few line from the <code>check_file</code>:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>ProductCode, Description, Supplier, CostPrice, RRPPrice, Stock, Manufacturer, SupplierProductCode, ManuCode, LeadTime 2VV-03,3MTR BLACK SVHS M - M GOLD CABLE - B/Q 100,Cables Direct Ltd,0.43,,930,CDL,2VV-03,2VV-03,1 2VV-05,5MTR BLACK SVHS M - M GOLD CABLE - B/Q 100,Cables Direct Ltd,0.54,,1935,CDL,2VV-05,2VV-05,1 2VV-10,10MTR BLACK SVHS M - M GOLD CABLE - B/Q 50,Cables Direct Ltd,0.86,,1991,CDL,2VV-10,2VV-10,1 </code></pre> </blockquote> <p>You can see it selects the first line from the <code>in_file</code>, looks up the SKU in the check_file then writes the <code>out_file</code> in the same format as the in_file changing the <code>ChannelProfileID</code> depending what it finds in the Stock field of the <code>check_file</code>, it then goes back to the first line in the <code>check_file</code> and performs the same on the next line on the <code>in_file</code>.</p> <p>As I say this script is working and outputs exactly what I want, but I believe it is slow and inefficient due to having to keep loop through the <code>check_file</code> until it finds a result.</p> <p>What I'm after is suggestions on how to improve the efficiency. I'm guessing there's a better way to find the data than to keep looping through the <code>check_file</code>.</p>
[]
[ { "body": "<p>One thing that you should avoid is reading the same file multiple times. There isn't any detail about how big are your files in the question, so I guess that they can fit in memory. In that case, I'd recommend to read the files once, work on the data in memory and write the result file.</p>\n\n<p>Aside from that, as you read the data, there should be some way to improve the search time later. It looks like the columns in which you're interested are the ones related to the <code>ProductCode</code>. So maybe you could create a dictionary of lists that can be accessed using the <code>ProductCode</code> as key. As I said, this should speed up the search.</p>\n\n<p>If there's some reason why using a dictionary isn't appropriate. You can try to use a database like <code>sqlite3</code>, which is part of the standard library, and store your data in memory in such a way that you can run SQL queries to get the data that you need in a faster way.</p>\n\n<p>I hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T23:58:23.810", "Id": "7114", "ParentId": "7113", "Score": "1" } }, { "body": "<p>I think I have come up with something along the lines of what you want using dicts</p>\n\n<pre><code>import csv\nin_file = open(\"in.csv\", 'r')\nreader = csv.DictReader(in_file, delimiter= ',')\nout_file = open(\"out.txt\", 'w')\nout_file.write(\"StockNumber,SKU,ChannelProfileID\\n\")\ncheck_file = open(\"check.csv\", 'r')\ncheck = csv.DictReader(check_file, delimiter=',')\n\nprodid = set()\nprod_sn = dict()\nfor row in reader:\n prodid.add(row[\"SKU\"])\n prod_sn[row[\"SKU\"]] = row[\"StockNumber\"]\n print(row[\"SKU\"])\n\nstocknums = dict()\nfor row in check:\n stocknums[row[\"ProductCode\"]] = row[\" Stock\"]\n print(row[\"ProductCode\"])\n\n\nfor product in prodid:\n ref = 0\n if product in stocknums:\n if(stocknums[product] &gt; 0):\n ref = 1\n\n\n out_file.write(str(prod_sn[product]) + ',' + str(product) + ','+ str(ref)+ \"\\n\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T00:06:49.580", "Id": "7115", "ParentId": "7113", "Score": "1" } }, { "body": "<p>What you want is a mapping from the product code (the <em>key</em>) to a stock level/result code (the <em>value</em>). In Python this is known as a <a href=\"http://docs.python.org/tutorial/datastructures.html#dictionaries\" rel=\"nofollow\">dictionary</a>. The way to do it is to go through your check file at the start, and use the information in it to create a dictionary containing all the stock level details. You then go through your input file, read in the product code, and retrieve the stock code from the dictionary you created earlier.</p>\n\n<p>I've rewritten your code to do this, and it works for the example files you gave. I have commented it fairly thoroughly, but if there is anything unclear in it just post a comment and I'll try to clarify.</p>\n\n<pre><code>import csv\n\n# Open the check file in a context manager. This ensures the file will be closed\n# correctly if an error occurs.\nwith open('checkfile.csv', 'rb') as checkfile:\n checkreader = csv.DictReader(checkfile)\n\n # Create a function which maps the stock level to the result code.\n def result_code(stock_level):\n if stock_level &gt; 0:\n return 3746\n if stock_level == 0:\n return 3745\n return \" \"\n\n # This does the real work. The middle line is a generator expression which\n # iterates over each line in the check file. The product code and stock\n # level are extracted from each line, the stock level converted into the\n # result, and the two values put together in a tuple. This is then converted\n # into a dictionary. This dictionary has the product codes as its keys and\n # their result code as its values.\n product_result = dict(\n (v['ProductCode'], result_code(int(v[' Stock']))) for v in checkreader\n )\n\n# Open the input and output files.\nwith open('infile.csv', 'rb') as infile:\n with open('outfile.csv', 'wb') as outfile:\n reader = csv.DictReader(infile)\n\n # Use the same field names for the output file.\n writer = csv.DictWriter(outfile, reader.fieldnames)\n writer.writeheader()\n\n # Iterate over the products in the input.\n for product in reader:\n # Find the stock level from the dictionary we created earlier. Using\n # the get() method allows us to specify a default value if the SKU\n # does not exist in the dictionary.\n result = product_result.get(product['SKU'], \" \")\n\n # Update the product info.\n product['ChannelProfileID'] = result\n\n # Write it to the output file.\n writer.writerow(product)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T17:46:02.397", "Id": "11187", "Score": "0", "body": "Great Thanks, really clear and simple with excellent comments!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T17:52:17.517", "Id": "11188", "Score": "0", "body": "Great Thanks, really clear and simple with excellent comments, has really helped my learning. It's also taken a script that took about 30 mins to complete with a full dataset to a matter of seconds!\n\nOne slight change I made is;\n` def result_code(stock_level):\n try :\n stock_level = int(stock_level)\n except :\n stock_level = 0\n if stock_level > 0:\n return 3746\n if stock_level == 0:\n return 3745\n return \" \"\n product_result = dict(\n (v['item code'], result_code(v['stock'])) for v in checkreader\n )`\nBecause now and again a blank space is used instead of 0 for a stock level of 0." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T00:30:15.510", "Id": "7116", "ParentId": "7113", "Score": "2" } }, { "body": "<p>This I hope, meets all your needs. It allows you to hold on to your csv in a dict form, do lookups and modifications, and also write it in a perserved order. You can also change which column you want to be your lookup column (making sure that there is a unique id for every row of that column. In my example of usage, it assumes that both classes are contained withing the same file named 'CustomDictReader.py'. So in the end, what you can do with this is create two CSVRW objects, set your lookup column for each one and do your swapping/compare/lookup, then do the final write, when you are done going through what you need</p>\n\n<p>-- File 'CustomDictReader.py' --</p>\n\n<pre><code>import csv, collections, copy\n\n'''\n# CSV TEST FILE 'test.csv'\n\nTBLID,DATETIME,VAL\nC1,01:01:2011:00:01:23,5\nC2,01:01:2012:00:01:23,8\nC3,01:01:2013:00:01:23,4\nC4,01:01:2011:01:01:23,9\nC5,01:01:2011:02:01:23,1\nC6,01:01:2011:03:01:23,5\nC7,01:01:2011:00:01:23,6\nC8,01:01:2011:00:21:23,8\nC9,01:01:2011:12:01:23,1\n\n\n#usage\n\n&gt;&gt;&gt; import CustomDictReader\n&gt;&gt;&gt; import pprint\n&gt;&gt;&gt; test = CustomDictReader.CSVRW()\n&gt;&gt;&gt; success, thedict = test.createCsvDict('TBLID',',',None,'test.csv')\n&gt;&gt;&gt; pprint.pprint(dict(d))\n{'C1': OrderedDict([('TBLID', 'C1'), ('DATETIME', '01:01:2011:00:01:23'), ('VAL', '5')]),\n 'C2': OrderedDict([('TBLID', 'C2'), ('DATETIME', '01:01:2012:00:01:23'), ('VAL', '8')]),\n 'C3': OrderedDict([('TBLID', 'C3'), ('DATETIME', '01:01:2013:00:01:23'), ('VAL', '4')]),\n 'C4': OrderedDict([('TBLID', 'C4'), ('DATETIME', '01:01:2011:01:01:23'), ('VAL', '9')]),\n 'C5': OrderedDict([('TBLID', 'C5'), ('DATETIME', '01:01:2011:02:01:23'), ('VAL', '1')]),\n 'C6': OrderedDict([('TBLID', 'C6'), ('DATETIME', '01:01:2011:03:01:23'), ('VAL', '5')]),\n 'C7': OrderedDict([('TBLID', 'C7'), ('DATETIME', '01:01:2011:00:01:23'), ('VAL', '6')]),\n 'C8': OrderedDict([('TBLID', 'C8'), ('DATETIME', '01:01:2011:00:21:23'), ('VAL', '8')]),\n 'C9': OrderedDict([('TBLID', 'C9'), ('DATETIME', '01:01:2011:12:01:23'), ('VAL', '1')])}\n\n'''\n\nclass CustomDictReader(csv.DictReader):\n '''\n override the next() function and use an\n ordered dict in order to preserve writing back\n into the file\n '''\n\n def __init__(self, f, fieldnames = None, restkey = None, restval = None, dialect =\"excel\", *args, **kwds):\n csv.DictReader.__init__(self, f, fieldnames = None, restkey = None, restval = None, dialect = \"excel\", *args, **kwds)\n\n def next(self):\n if self.line_num == 0:\n # Used only for its side effect.\n self.fieldnames\n row = self.reader.next()\n self.line_num = self.reader.line_num\n\n # unlike the basic reader, we prefer not to return blanks,\n # because we will typically wind up with a dict full of None\n # values\n while row == []:\n row = self.reader.next()\n d = collections.OrderedDict(zip(self.fieldnames, row))\n\n lf = len(self.fieldnames)\n lr = len(row)\n if lf &lt; lr:\n d[self.restkey] = row[lf:]\n elif lf &gt; lr:\n for key in self.fieldnames[lr:]:\n d[key] = self.restval\n return d\n\nclass CSVRW(object):\n\n def __init__(self):\n self.file_name = \"\"\n self.csv_delim = \"\"\n self.csv_dict = collections.OrderedDict()\n\n def setCsvFileName(self, name):\n '''\n @brief stores csv file name\n @param name- the file name\n '''\n self.file_name = name\n\n def getCsvFileName():\n '''\n @brief getter\n @return returns the file name\n '''\n return self.file_name\n\n def getCsvDict(self):\n '''\n @brief getter\n @return returns a deep copy of the csv as a dictionary\n '''\n return copy.deepcopy(self.csv_dict)\n\n def clearCsvDict(self):\n '''\n @brief resets the dictionary\n '''\n self.csv_dict = collections.OrderedDict()\n\n def updateCsvDict(self, newCsvDict):\n '''\n creates a deep copy of the dict passed in and\n sets it to the member one\n '''\n self.csv_dict = copy.deepcopy(newCsvDict)\n\n def createCsvDict(self,dictKey, delim, handle = None, name = None, readMode = 'rb', **kwargs):\n '''\n @brief create a dict from a csv file where:\n the top level keys are the first line in the dict, overrideable w/ **kwargs\n each row is a dict\n each row can be accessed by the value stored in the column associated w/ dictKey\n\n that is to say, if you want to index into your csv file based on the contents of the\n third column, pass the name of that col in as 'dictKey'\n\n @param dictKey - row key whose value will act as an index\n @param delim - csv file deliminator\n @param handle - file handle (leave as None if you wish to pass in a file name)\n @param name - file name (leave as None if you wish to pass in a file handle)\n @param readMode - 'r' || 'rb'\n @param **kwargs - additional args allowed by the csv module\n @return bool - SUCCESS|FAIL\n '''\n retVal = (False, None)\n self.csv_delim = delim\n\n try:\n reader = None\n if isinstance(handle, file):\n self.setCsvFileName(handle.name)\n reader = CustomDictReader(handle, delim, **kwargs)\n else:\n if None == name:\n name = self.getCsvFileName()\n else:\n self.setCsvFileName(name)\n reader = CustomDictReader(open(name, readMode), delim, **kwargs)\n\n for row in reader:\n self.csv_dict[row[dictKey]] = row\n\n retVal = (True, self.getCsvDict())\n\n except IOError:\n retVal = (False, 'Error opening file')\n\n return retVal\n\n def createCsv(writeMode, outFileName = None, delim = None):\n '''\n @brief create a csv from self.csv_dict\n @param writeMode - 'w' || 'wb'\n @param outFileName - file name || file handle\n @param delim - csv deliminator\n @return none\n '''\n if None == outFileName:\n outFileName = self.file_name\n if None == delim:\n delim = self.csv_delim\n\n with open(outFileName, writeMode) as fout:\n for key in self.csv_dict.values():\n fout.write(delim.join(key.keys()) + '\\n')\n break\n\n for key in self.csv_dict.values():\n fout.write(delim.join(key.values()) + '\\n')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T19:31:48.280", "Id": "7143", "ParentId": "7113", "Score": "1" } } ]
{ "AcceptedAnswerId": "7116", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T21:19:37.930", "Id": "7113", "Score": "6", "Tags": [ "python", "beginner", "search", "csv" ], "Title": "Searching for a value from one CSV file in another CSV file" }
7113
<p>I am learning Scala, coming from Java background. Here I have written a small prototype proof of concept program that is a part of concept base for a simple upcoming tutorial game. There are two game objects: a Cell and a Breed of cells (a 1d row). The operations are simple. One can create a breed with a number of cells. Each cell can mutate with a custom function chosen randomly from the available set. If the breed mutates, all of it's cells mutate. My question is the one common today - how Scala-ish is my code? How to improve? Coming from OOP, I have witnessed a very strange feeling while writing this code: it feels just like the internals of objects leak out from their ripped bodies just like in a real OOP thriller movie. But everyone suggests breaking the code into functions... so where is the balance?</p> <pre><code>package main import scala.util.Random object Breed extends App{ val rand:Random = new Random //mutations def mutF(f:Int =&gt; Int)(v:Int) : Int = {f(v)} def mutFA(v:Int) : Int = mutF(x =&gt; x)(v) def mutFB(v:Int) : Int = mutF(x =&gt; x + x)(v) def mutFC(v:Int) : Int = mutF(x =&gt; x * x)(v) val mutations : List[Int=&gt;Int] = List(mutFA, mutFB, mutFC) //constants (sources) val emptyCellList : List[Cell] = List[Cell]() //mutations manipulations def nextMutation(f:Int=&gt;Int) : Int=&gt;Int = { val i = mutations.indexOf(f) if(i == mutations.length - 1) mutations(0) else mutations(i + 1) } def randomMutation : Int=&gt;Int = { mutations(rand.nextInt(mutations.length)) } //---CELL--- class Cell(f:Int=&gt;Int, value:Int) { def mutate() = new Cell(nextMutation(f), f(value)) override def toString = "[" + value + "]" } def cellsToString(l:List[Cell]) : String = { l match { case Nil =&gt; "" case y :: ys =&gt; y.toString + cellsToString(ys) } } //breeder def createBreed(num:Int) : Breed = { def makeCell() : Cell = new Cell(randomMutation, rand.nextInt(10)) def makeCells(acc:Int, cells:List[Cell]) : List[Cell] = { if(acc == 0) cells else makeCells(acc - 1, makeCell :: cells) } new Breed(0, makeCells(num, List[Cell]())) } def mutateBreed(gens:Int, breed:Breed) : Breed = { def mutate(acc:Int, b:Breed) : Breed = { if(acc == 0) b else { val mutated : Breed = b.mutate(); println(b.output() + " ---&gt; " + mutated.output()) mutate(acc - 1, mutated) } } mutate(gens, breed) } //---BREED--- class Breed(generation:Int, cells:List[Cell]) { def mutateCells() : List[Cell] = { def f(l:List[Cell]) : List[Cell] = { l match { case Nil =&gt; Nil case x :: xs =&gt; x.mutate() :: f(xs) } } println("BREED: size=" + cells.length) f(cells) } def mutate() : Breed = new Breed(generation + 1, mutateCells) def output() : String = { "BREED: [" + generation + "] = " + cellsToString(cells) } } // /\/\/\/\/test/\/\/\/\ def test() { val breed = createBreed(10) mutateBreed(10, breed) } test } </code></pre>
[]
[ { "body": "<p>Some improvements:</p>\n\n<ul>\n<li>Try to minimize all mutable state and side effecting methods to single places. Don't divide them through the whole program.</li>\n<li>Scala is object oriented. Therefore use methods of the objects you want to work with instead of global functions.</li>\n<li>use methods with an empty parameter list only if these methods has side effects.</li>\n<li>search the API for methods you can work with.</li>\n</ul>\n\n<p>That's what I came up with:</p>\n\n<pre><code>object Game {\n\n import util.Random\n\n val rand: Random = new Random\n val mutations: Seq[Int =&gt; Int] = Seq(x =&gt; x, x =&gt; x + x, x =&gt; x * x)\n\n case class Cell(f: Int =&gt; Int, value: Int) {\n def mutate = {\n def nextMutation: Int =&gt; Int =\n mutations(((mutations indexOf f) + 1) % mutations.size)\n Cell(nextMutation, f(value))\n }\n\n override def toString = \"[\"+value+\"]\"\n }\n\n case class Breed(generation: Int, cells: Seq[Cell]) {\n def mutate: Breed =\n Breed(generation + 1, cells map { _.mutate })\n\n override def toString: String =\n \"BREED: [\"+generation+\"] = \"+cells.mkString\n }\n\n def makeCells(num: Int) = {\n def randomMutation =\n mutations(rand nextInt mutations.size)\n\n def makeCell =\n Cell(randomMutation, (rand nextInt 10))\n\n (Seq fill num) { makeCell }\n }\n\n def test() {\n val firstBreed = Breed(0, makeCells(10))\n val breeds = ((1 to 10).iterator scanLeft firstBreed) {\n (b, _) =&gt; b.mutate\n }\n printBreeds(breeds)\n }\n\n def printBreeds(breeds: Iterator[Breed]) {\n (breeds sliding 2) foreach {\n case Seq(b, mutated) =&gt;\n println(\"BREED: size=\"+b.cells.size)\n println(b+\" ---&gt; \"+mutated)\n }\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T10:47:51.323", "Id": "11120", "Score": "0", "body": "Wow! Thanks, Antoras, your code clearly gave me a whole bunch of insights! There are numerous places that I see now, can be improved. I see you are making a heavy use of Seq that results in numerous cool usecases like pattern matching, mapping, iterating, currying and so on. That is what it is for functional programming. I feel like printing both source codes and posting them on the wall so I could meditate on comparing them from time to time) I also remember that I was reading JavaDocs just for fun when beginning with Java. So I guess the same would be true for Scala too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T11:18:26.657", "Id": "11121", "Score": "0", "body": "I have noticed that you are using case classes here. That allows the corresponding functions to return Cell and Breed objects without the 'new' keyword. Why is this a preference here? Is it something aiming the future where I could use the both classes as case classes for say pattern matching, or is there some other benefit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T11:37:46.420", "Id": "11122", "Score": "0", "body": "btw, sorry, not enough reputation to rate you up yet" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T18:15:03.010", "Id": "11303", "Score": "0", "body": "I use case classes whenever there are a lot of object instantiations. I think it is easier to read and it is more obvious that the object stands for an immutable state. case classes have some advantages compared to normal classes. You mentioned already pattern matching, but there also some useful methods like `copy` or `productIterator`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T23:02:46.197", "Id": "7127", "ParentId": "7117", "Score": "2" } } ]
{ "AcceptedAnswerId": "7127", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T15:32:15.307", "Id": "7117", "Score": "2", "Tags": [ "object-oriented", "functional-programming", "scala" ], "Title": "Scala object-function balance" }
7117
<p>I had to do a small application using a menu system and Turtle. I have finished it and worked perfect. Just to make sure, can you please check it if it has done properly?</p> <pre><code>#!/usr/bin/python ## draw_shape.py import turtle as t def how_many(): while True: print " How many of then do you want to draw?" print " -Range is from 1 to 5-" global shape_no shape_no = raw_input(' Enter your choice: ') try: shape_no = int(shape_no) if (1 &lt;= shape_no &lt;= 5): print "Your number is ok" break else: print print "from 1 to 5 only" except: print "Only numbers allowed - Please try again" return True #=========#=========#=========#=========#=========#=========#=========# def start_point(): t.penup() t.setpos(-240,0) t.pendown() def draw_square(howmanyof): start_point() for a in range(howmanyof): for a in range(4): t.forward(80) t.left(90) t.penup() t.forward(100) t.pendown() def draw_triangle(howmanyof): start_point() for a in range(howmanyof): for a in range(3): t.forward(80) t.left(120) t.penup() t.forward(100) t.pendown() def draw_rectangle(howmanyof): start_point() for a in range(howmanyof): for a in range(2): t.forward(80) t.left(90) t.forward(40) t.left(90) t.penup() t.forward(100) t.pendown() def draw_hexagon(howmanyof): start_point() for a in range(howmanyof): for a in range(6): t.forward(50) t.left(60) t.penup() t.forward(110) t.pendown() def draw_octagon(howmanyof): start_point() for a in range(howmanyof): for a in range(8): t.forward(40) t.left(45) t.penup() t.forward(110) t.pendown() def draw_circle(howmanyof): start_point() for a in range(howmanyof): t . circle(50) t.penup() t.forward(120) t.pendown() #=========#=========#=========#=========#=========#=========#=========# def main(): while True: print print " Draw a Shape" print " ============" print print " 1 - Draw a square" print " 2 - Draw a triangle" print " 3 - Draw a rectangle" print " 4 - Draw a hexagon" print " 5 - Draw an octagon" print " 6 - Draw a circle" print print " X - Exit" print choice = raw_input(' Enter your choice: ') if (choice == 'x') or (choice == 'X'): break elif choice == '1': how_many() draw_square(shape_no) elif choice == '2': how_many() draw_triangle(shape_no) elif choice == '3': how_many() draw_rectangle(shape_no) elif choice == '4': how_many() draw_hexagon(shape_no) elif choice == '5': how_many() draw_octagon(shape_no) elif choice == '6': how_many() draw_circle(shape_no) else: print print ' Try again' print #=========#=========#=========#=========#=========#=========#=========# if __name__ == "__main__": main() #=========#=========#=========#=========#=========#=========#=========# </code></pre>
[]
[ { "body": "<ol>\n<li><p>Why are you using a global? There seems to be no need for it, and in general it's something to avoid.</p></li>\n<li><p>Why not factor out the common stuff? In your main loop you have a bunch of if cases which all start in the same way and then all call methods which are very similar. If you start by checking that it's a valid input you could pull out the calls to <code>how_many()</code> and <code>start_point()</code> and even the loop <code>for a in range(howmanyof):</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T17:20:49.067", "Id": "11097", "Score": "0", "body": "1- when i take off `global shape_no` i can not get the user input. It draws 4 times regardless of user input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T19:29:00.197", "Id": "11098", "Score": "0", "body": "@baris22 As mentioned in the SO answers, return `shape_no` from `how_many()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T21:23:07.483", "Id": "11100", "Score": "0", "body": "Thanks alot. I got it working and i kind of understood what you meant" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T16:57:37.123", "Id": "7119", "ParentId": "7118", "Score": "1" } }, { "body": "<p>(You haven't updated the question based on Peter's answer, so I can't really comment on <code>how_many()</code>, and will primarily focus on the rest.)</p>\n\n<p>First of all, your function names are misleading: <code>draw_triangle</code> should draw a triangle, while yours draws a certain number of triangles. I suggest pulling the triangle-drawing logic into a separate function called <code>draw_triangle</code> and then renaming the current <code>draw_triangle</code> to <code>draw_n_triangles</code>. You might even be able to make a <code>draw_n_shapes</code> function which takes a function for drawing one shape -- I haven't looked too closely, but it seems like this could work:</p>\n\n<pre><code>def draw_n_shapes(n, draw_func):\n start_point()\n for a in range(n): \n draw_func()\n t.penup() \n t.forward(120)\n t.pendown()\n</code></pre>\n\n<p>Note that the spacing may be off (you use 100, 110, and 120 in the different functions -- either pass it as a parameter, or choose one).</p>\n\n<p>Secondly, instead of the long if..else chain, you could use a dictionary. For example:</p>\n\n<pre><code>def main():\n draw_functions = {\n 1: draw_square,\n 2: draw_triangle,\n 3: draw_rectangle,\n 4: draw_hexagon,\n 5: draw_octagon,\n 6: draw_circle\n }\n while True:\n # stuff that shows the message, takes input, etc.\n if choice.lower() == 'x':\n break\n if int(choice) in draw_functions:\n draw_functions[int(choice)](shape_no)\n else:\n print \"Try again\"\n</code></pre>\n\n<p>You instead could use a list, but then the indices would start at 0, which I don't think you want.</p>\n\n<p>Thirdly, although your functions are all short and fairly self-documenting, I would suggest adding docstrings to your functions, as well as comments whenever you feel like you have to make an important decision. Even if you don't expect the code to be read by anyone at all, spotting similarities may be simpler in text than in code. You may also want to name your constants -- the aforementioned 100 is a good example, as well as the <code>-240, 0</code> point you use in <code>start_point</code> (why did you choose that point?).</p>\n\n<p>Speaking of which, <code>start_point</code> may be better-named <code>jump_to_start_point</code>, if I understood the purpose correctly. In general, you may want to have function names start with a verb.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T04:47:39.360", "Id": "7404", "ParentId": "7118", "Score": "1" } }, { "body": "<p>Fix your prints.</p>\n<p>Proper syntax is:</p>\n<pre><code> print(&quot;Hi&quot;)\n</code></pre>\n<p>and this will print Hi.</p>\n<p>Also, you didn't <code>import raw_input</code>.\nInstead of using <code>raw_input</code>, use <code>input()</code>, I'm pretty sure that it does the same thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T19:17:35.440", "Id": "486956", "Score": "0", "body": "On Python 2, the shown syntax works just fine. There's also a difference in how input should be handled between Python 2 and 3. Having said that, I think your answer may be misinformed due to those differences. Can you please verify for yourself that your answer is still relevant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-26T18:37:48.807", "Id": "490045", "Score": "0", "body": "oh your using python 2, I I'm using python 3, and my editor is bothering me about it, and I'm not used to printing in python 2, sorry." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T17:34:53.390", "Id": "248557", "ParentId": "7118", "Score": "-2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T15:34:42.467", "Id": "7118", "Score": "4", "Tags": [ "python", "homework", "turtle-graphics" ], "Title": "Menu system and Turtle" }
7118
<p>I'm trying to print the top 5 most queried strings from a text file. I can't use other third-party libraries to make it easier w.r.t hashmap implementations.</p> <p>I need to improve on these if possible:</p> <ol> <li>cyclomatic complexity</li> <li>Memory usage</li> <li>Execution time </li> <li>Page faults</li> </ol> <p></p> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; class Topfive { private HashMap&lt;String, Integer&gt; hashmap = new HashMap&lt;String, Integer&gt;(); public HashMap&lt;String, Integer&gt; getHashmap() { return hashmap; } public void putWord(String main) { Integer frequency = getHashmap().get(main); if (frequency == null) { frequency = 0; } hashmap.put(main, frequency + 1); } public TreeMap&lt;String, Integer&gt; process(File fFile) throws FileNotFoundException { Scanner scanner = new Scanner(new FileReader(fFile)); while (scanner.hasNextLine()) { String wordp = scanner.nextLine(); int j = wordp.indexOf("query=") + 6; int k = wordp.length() - 1; String fut = wordp.substring(j, k).trim(); this.putWord(fut); } scanner.close(); ValueComparator bvc = new ValueComparator(getHashmap()); TreeMap&lt;String, Integer&gt; sorted_map = new TreeMap&lt;String, Integer&gt;(bvc); sorted_map.putAll(getHashmap()); return sorted_map; } public static void main(String[] args) { if (args.length &gt; 0) { File fFile = new File(args[0]); Topfive topfive = new Topfive(); try { TreeMap&lt;String, Integer&gt; sorted_map = topfive.process(fFile); int count = 0; for (String key : sorted_map.keySet()) { System.out.println(key); count++; if (count &gt;= 5) { break; } } } catch (FileNotFoundException e) { e.printStackTrace(); } } } } </code></pre> <pre><code>class ValueComparator implements Comparator&lt;Object&gt; { private Map&lt;String, Integer&gt; base; public ValueComparator(Map&lt;String, Integer&gt; base) { this.base = base; } @Override public int compare(Object first_obj, Object second_obj) { int ret = -1; if (base.get(first_obj) &lt; base.get(second_obj)) { ret = 1; } return ret; } } </code></pre> <p>Sample text in text file which is given as command line argument:</p> <blockquote> <pre class="lang-none prettyprint-override"><code> [Fri Jan 07 18:37:54 CET 2011] new query: [ip=60.112.154.0, query=this year] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=116.161.234.129, query=fashion] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=38.214.87.66, query=big lies] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=60.112.154.0, query=this year] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=116.161.234.129, query=fashion] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=38.214.87.66, query=big lies] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=68.175.141.150, query=seven levels] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=114.235.27.231, query=head] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=67.238.116.254, query=special] [Fri Jan 07 18:37:54 CET 2011] new query: [ip=220.153.109.208, query=present] </code></pre> </blockquote>
[]
[ { "body": "<p>Your names could be improved, e.g. <code>hm</code> isn't a good name for a member variable.</p>\n\n<p>You could replace the <code>HashMap</code> by a multiset implementation, e.g. <a href=\"http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/collect/HashMultiset.java\"><code>HashMultiset</code></a> from Google Guava. Then you get <code>putWord</code> for free.</p>\n\n<p>The <code>Comparator</code> (and its <code>Map</code>) should be generified. Further, it seems to be plain wrong, as it never gives 0 as result of <code>compare</code>, but that is the expected outcome if two values are \"equal\" (whatever this means in the actual context). Without looking too deep in the code, it <em>might</em> even be that a simple priority queue could replace all the <code>Comparator</code> and <code>TreeMap</code> stuff.</p>\n\n<p>The <code>main</code> method is too long and should be split in logical parts. Probably it would be better to avoid static methods, but to create a <code>Topfive</code> instance which does most of the work.</p>\n\n<p>If you can use Java 7, try out the <a href=\"http://javarevisited.blogspot.com/2011/09/arm-automatic-resource-management-in.html\">ARM block feature</a> for your file access.</p>\n\n<p>For your question you used the tag \"clean code\", but it looks like you didn't read the <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\">book by Uncle Bob</a>. Check it out!</p>\n\n<p><strong>[Edit]</strong></p>\n\n<p>Based on your clarification I would write the class as follows:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\n\npublic class TopWords {\n private final SortedSet&lt;Freq&gt; frequencies = new TreeSet&lt;Freq&gt;();\n\n public TopWords(File file)\n throws IOException {\n List&lt;String&gt; wordList = readWords(file);\n Map&lt;String, Integer&gt; freqMap = getFrequencies(wordList);\n sortFrequencies(freqMap);\n }\n\n public SortedSet&lt;Freq&gt; getFrequencies() {\n return frequencies;\n }\n\n private List&lt;String&gt; readWords(File file) throws IOException {\n List&lt;String&gt; result = new ArrayList&lt;String&gt;();\n BufferedReader br = new BufferedReader(new FileReader(file));\n for (String line = br.readLine(); line != null; line = br.readLine()) {\n result.add(line);\n }\n return result;\n }\n\n private Map&lt;String, Integer&gt; getFrequencies(List&lt;String&gt; wordList) throws IOException {\n Map&lt;String, Integer&gt; freqMap = new HashMap&lt;String, Integer&gt;();\n for (String line : wordList) {\n int start = line.indexOf(\"query=\") + 6;\n int end = line.length() - 1;\n String word = line.substring(start, end).trim();\n Integer frequency = freqMap.get(word);\n freqMap.put(word, frequency == null ? 1 : frequency + 1);\n }\n return freqMap;\n }\n\n private void sortFrequencies(Map&lt;String, Integer&gt; freqMap) {\n for (Entry&lt;String, Integer&gt; entry : freqMap.entrySet()) {\n frequencies.add(new Freq(entry.getKey(), entry.getValue()));\n }\n }\n\n public List&lt;String&gt; getTop(int count) {\n List&lt;String&gt; result = new ArrayList&lt;String&gt;(count);\n for (Freq freq : frequencies) {\n if (count-- == 0) {\n break;\n }\n result.add(freq.word);\n }\n return result;\n }\n\n public static void main(String[] args) {\n if (args.length &gt; 0) {\n try {\n TopWords topFive = new TopWords(new File(args[0]));\n List&lt;String&gt; topList = topFive.getTop(5);\n for (String word : topList) {\n System.out.println(word);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public class Freq implements Comparable&lt;Freq&gt; {\n public final String word;\n public final int frequency;\n\n private Freq(String word, int frequency) {\n this.word = word;\n this.frequency = frequency;\n }\n\n public int compareTo(Freq that) {\n int result = that.frequency - this.frequency;\n return result != 0 ? result : that.word.compareTo(this.word);\n }\n }\n}\n</code></pre>\n\n<p>Of course this might be suboptimal depending on the intended use, but I think you get the general idea.</p>\n\n<p><strong>[Update]</strong></p>\n\n<p>After some meditation I came to the conclusion that I thought way too complicated. Try the following version:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class TopWords {\n\n private final List&lt;Freq&gt; frequencies = new ArrayList&lt;Freq&gt;();\n\n public TopWords(File file)\n throws IOException {\n List&lt;String&gt; wordList = getSortedWordList(file);\n sortFrequencies(wordList);\n }\n\n public List&lt;Freq&gt; getFrequencies() {\n return frequencies;\n }\n\n private List&lt;String&gt; getSortedWordList(File file) throws IOException {\n List&lt;String&gt; result = new ArrayList&lt;String&gt;();\n BufferedReader br = new BufferedReader(new FileReader(file));\n for (String line = br.readLine(); line != null; line = br.readLine()) {\n int start = line.indexOf(\"query=\") + 6;\n int end = line.length() - 1;\n String word = line.substring(start, end).trim();\n result.add(word);\n }\n br.close();\n Collections.sort(result);\n return result;\n }\n\n private void sortFrequencies(List&lt;String&gt; wordList) {\n String lastWord = null;\n int count = 0;\n for (String word : wordList) {\n if (word.equals(lastWord)) {\n count++;\n } else {\n if (lastWord != null) {\n frequencies.add(new Freq(lastWord, count));\n }\n lastWord = word;\n count = 1;\n }\n }\n if (lastWord != null) {\n frequencies.add(new Freq(lastWord, count));\n } \n Collections.sort(frequencies);\n }\n\n public List&lt;Freq&gt; getTop(int count) {\n return frequencies.subList(0, Math.min(frequencies.size(), count));\n }\n\n public static void main(String[] args) {\n if (args.length &gt; 0) {\n try {\n TopWords topFive = new TopWords(new File(args[0]));\n List&lt;Freq&gt; topList = topFive.getTop(5);\n for (Freq freq : topList) {\n System.out.println(freq.word + \" \" + freq.frequency);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public class Freq implements Comparable&lt;Freq&gt; {\n\n public final String word;\n public final int frequency;\n\n private Freq(String word, int frequency) {\n this.word = word;\n this.frequency = frequency;\n }\n\n public int compareTo(Freq that) {\n int result = that.frequency - this.frequency;\n return result != 0 ? result : that.word.compareTo(this.word);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T18:01:53.643", "Id": "11126", "Score": "0", "body": "@I cannot use third-party libraries ( Google guava) :)\nRegarding return 0, it makes list populated with Unique items.\nRegarding ARM feature , I can use only Java(SUN 1.6.0_20)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T13:00:17.380", "Id": "11140", "Score": "0", "body": "@cypronmaya: See my new version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T15:15:37.557", "Id": "11142", "Score": "0", "body": "Well written if i must say, no clutter etc., thanks for your time to write it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T15:26:57.267", "Id": "11143", "Score": "0", "body": "Regarding metric comparison, FYI \n 1) Cyclomatic complexity -- Your version beats mine by reducing 5->4\n 2) Memory usage -- Your's = 4* Mine \n 3) Execution time -- Yours's = 1/2 * Mine \n 4) Page Faults -- Your's = 4*Mine\n\nMay be i've picked wrong language to do it :) To compare such metrics with others.I Couldn't even stood a chance against C,Perl,PHP w.r.t metrics\nofcourse Java is the easiest one for me :)\n\nAnyway i've learned something, will try to write better code next time. \nAgain thanks for your time to write it . :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T23:21:31.520", "Id": "11191", "Score": "0", "body": "You have always a kind of compromise. E.g. you don't need the intermediate variable `wordList`, you can merge `readWords` and `getFrequencies` in one method with one loop. Then you need less memory, but it is less readable (and you violated the Single Responsibility Principle)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T07:49:53.763", "Id": "11197", "Score": "0", "body": "@cypronmaya: The intermediate map is indeed overkill, see my simplified version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T14:00:21.230", "Id": "11208", "Score": "0", "body": "@Landei BTW new simplified version has decreased a lot incl (source code size,memory usage,page faults,exec cost) but not Exec time and main thing cyclomatic complexity is 5 now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T07:26:19.200", "Id": "11250", "Score": "1", "body": "I think `sortFrequencies` is responsible for that. It is quite ugly, but I found no better way to count the elements in one go. Java collections should really contain a multiset implementation, then this would be a no-brainer." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T15:57:58.520", "Id": "7137", "ParentId": "7120", "Score": "8" } }, { "body": "<p>Your <code>compare</code> method should be as follows:</p>\n\n<pre><code>@Override\npublic int compare(Object a, Object b) \n{\n return (Integer)base.get(a) - (Integer)base.get(b);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T18:01:03.970", "Id": "11125", "Score": "0", "body": "That only populates sorted_map with unique key's.(Utmost query'ed term's can also be multiple)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T13:06:38.847", "Id": "11206", "Score": "0", "body": "Don't leave out generics. Every single cast in your code is sign that your code works outside the type system (so either the type system is too weak, or you were not clever enough to find a solution without bending the rules) and is a possible source of error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T13:09:42.447", "Id": "11207", "Score": "0", "body": "@Landei sure, I just did not want to deviate too much from the existing compare method in the OP's code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T16:11:20.410", "Id": "7138", "ParentId": "7120", "Score": "0" } } ]
{ "AcceptedAnswerId": "7137", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T17:37:52.907", "Id": "7120", "Score": "5", "Tags": [ "java", "performance", "logging", "statistics" ], "Title": "Extracting the five most frequent queries from a log file" }
7120
<p>Below is a simple "class" for displaying messages. It stores the output html div and then displays messages to it as needed. </p> <p>It works fine. For readability, and encapsulation purposes, I'd like the componenets of the "class" in a contianer of sorts or a javascript object? What is the simplest way to to do this.</p> <p>Or...is there a simple way to do this?</p> <p>Currently the only container is the comments I've surrounded the code with.</p> <pre><code>/** * Module : Model * Name : -Message * Input : div via the constructor message type via display * Output : TextStream via display to Control.sendInner * Notes : Symmetric, client holds message location so needs extra variable */ var Message = function( div ) { this.div = document.getElementById( div ); }; Message.prototype.messages = { name: 'Please enter a valid name', email: 'Please enter a valid email', pass: 'Please enter passoword, 6-40 characters', url: 'Pleae enter a valid url', title: 'Pleae enter a valid title', tweet: 'Please enter a valid tweet', empty: 'Please complete all fields', empty_bm: 'Please complete all fields', same: 'Please make emails equal', taken: 'Sorry, that email is taken', validate: 'Please contact &lt;a class="d" href="mailto:support@.com"&gt;support&lt;/a&gt; to reset your password' }; Message.prototype.display = function( type ) { Control.sendInner( this.div, this.messages[type] ) }; /** Message End */ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T21:23:32.920", "Id": "11654", "Score": "0", "body": "Please don't edit the question to make the existing answers meaningless. If you have new versions of the code post a new question. Reference this one (in it's original form) and explain that it's a new issue.\n http://meta.stackexchange.com/questions/94446/editing-a-question-and-asking-a-completely-different-question\n http://meta.stackexchange.com/questions/64459/rolling-back-a-completely-changed-question" } ]
[ { "body": "<p>You could wrap your whole file in a namespace, as <a href=\"https://stackoverflow.com/questions/881515/javascript-namespace-declaration\">described here</a>.</p>\n\n<p>Of all the possibilities, this is the one I like the most:</p>\n\n<pre><code>var YourNamespace = (function () {\n var Message = function (div) {\n ...\n }\n var aPrivateFunction = function () { ... }\n ...\n return {\n 'Message': Message\n };\n})();\n</code></pre>\n\n<p>This lets you define private functions, like <code>aPrivateFunction</code>, not visible outside <code>YourNamespace</code>. You can access <code>Message</code> as <code>YourNamespace.Message</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T21:57:19.123", "Id": "7145", "ParentId": "7121", "Score": "1" } }, { "body": "<p>For readability purposes, you could do something like this to create class definitions:</p>\n\n<pre><code>// utility function\nUTIL = {\n createClass: function(o) {\n var F = o.constructor || function() { };\n for(var i in o) {\n F.prototype[i] = o[i];\n }\n return F;\n }\n};\n\n// class definition\nMessage = UTIL.createClass({\n\n constructor: function(div) { ... },\n\n messages: { ... },\n\n display: function() { ... }\n\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T01:38:41.837", "Id": "7146", "ParentId": "7121", "Score": "1" } }, { "body": "<p>The simplest way is to do something like this.</p>\n\n<pre><code>var My = {};\n\nMy.Message = function ( div ) \n{\n this.div = document.getElementById( div ); \n};\n\nMy.Message.prototype.messages = \n{ //... \n};\n</code></pre>\n\n<p>Here is another way that is unusual enough that linters (and peer-reviewers) will complain, but really it's harmless.</p>\n\n<pre><code>var My = new function(){\n\n this.Message = function ( div ) \n {\n this.div = document.getElementById( div ); \n };\n\n this.Message.prototype.messages = \n { //... \n };\n\n}();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T03:45:36.400", "Id": "7248", "ParentId": "7121", "Score": "1" } } ]
{ "AcceptedAnswerId": "7146", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T17:39:44.400", "Id": "7121", "Score": "1", "Tags": [ "javascript" ], "Title": "Wrapping a javascript \"class\"?" }
7121
<p>I have a C# WinForms app containing a <code>ListBox</code> control, which I populate with objects of type <code>BukkitServer</code>. When an object is added or removed from the list, I want to write them to an XML file. I have a static method in a helper class that takes an <code>ICollection</code> argument and achieves this.</p> <p>However, since the <code>ListBox.ObjectCollection</code> class is not serializable (fittingly, since it contains elements of type <code>object</code>), I wrote a helper method to convert it to a <code>List&lt;BukkitServer&gt;</code>.</p> <p>It feels like a hack, though, and I feel (hope) there is a cleaner answer.</p> <p>Any other comments and criticisms are welcome as well.</p> <pre><code>static class BukkitServerDataWriter { public static void SaveServers(ICollection objects) { using (XmlTextWriter writer = new XmlTextWriter("servers.xml", Encoding.UTF8)) { XmlSerializer xml = new XmlSerializer( typeof(List&lt;BukkitServer&gt;), new Type[] { typeof(BukkitServer) }); List&lt;BukkitServer&gt; servers = MakeBukkitServerList(objects); xml.Serialize(writer, servers); } } private static List&lt;BukkitServer&gt; MakeBukkitServerList(ICollection collection) { List&lt;BukkitServer&gt; servers = new List&lt;BukkitServer&gt;(); foreach (object obj in collection) { servers.Add((BukkitServer)obj); } return servers; } } </code></pre>
[]
[ { "body": "<p>If you don't mind using a little bit of LINQ, it can be simplified (and optimized) as such:</p>\n\n<pre><code>static class BukkitServerDataWriter\n{\n private static readonly XmlSerializer xml = new XmlSerializer(\n typeof(List&lt;BukkitServer&gt;),\n new[] { typeof(BukkitServer) });\n\n public static void SaveServers(ICollection objects)\n {\n using (var writer = new XmlTextWriter(\"servers.xml\", Encoding.UTF8))\n {\n xml.Serialize(writer, objects.Cast&lt;BukkitServer&gt;().ToList());\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T03:39:05.977", "Id": "11114", "Score": "0", "body": "My pleasure. Glad to assist." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T02:12:44.307", "Id": "7131", "ParentId": "7126", "Score": "1" } } ]
{ "AcceptedAnswerId": "7131", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T22:50:05.660", "Id": "7126", "Score": "2", "Tags": [ "c#", "winforms", "collections" ], "Title": "Persisting objects in a ListBox ObjectCollection" }
7126
<p>I'm new to template meta-programming and wrote some code to determine if a number is a perfect square. For example, in my program, <code>SQUARE&lt;1&gt;::value</code> and <code>SQUARE&lt;4&gt;::value</code> evaluate to <code>true</code> while <code>SQUARE&lt;5&gt;::value</code> is <code>false</code>. I'm open to any suggestions on how I could implement this better, cleaner, or make use of standard library functions. Also, please point out any meta-programming conventions I may have overlooked.</p> <pre><code>template&lt;bool condition, bool Then, bool Else&gt; struct IF { static const bool ret = Then; }; template&lt;bool Then, bool Else&gt; struct IF&lt;false, Then, Else&gt; { static const bool ret = Else; }; template&lt;size_t v1, size_t v2&gt; struct GREATER { static const bool ret = v1 &gt; v2; }; template&lt;size_t n, size_t r&gt; struct IS_SQUARE { static const bool value = IF&lt;n == r*r, true, IF&lt;GREATER&lt;n, r*r&gt;::ret, IS_SQUARE&lt;n, r+1&gt;::value, false&gt;::ret &gt;::ret; }; template&lt;size_t n&gt; struct IS_SQUARE&lt;n, n&gt; { static const bool value = false; }; template&lt;size_t n&gt; struct SQUARE { static const bool value = IS_SQUARE&lt;n, 1&gt;::value; }; template&lt;&gt; struct SQUARE&lt;1&gt; { static const bool value = true; }; // example usage int main() { static_assert(SQUARE&lt;1&gt;::value, "must be square"); static_assert(SQUARE&lt;4&gt;::value, "must be square"); static_assert(SQUARE&lt;5&gt;::value, "must be square"); // compile error } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T00:22:02.710", "Id": "11103", "Score": "0", "body": "Does your use of `static_assert` indicate that C++11 features are okay in general? Because the code could be much improved by using `constexpr`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T00:24:07.197", "Id": "11104", "Score": "0", "body": "Yes, c++11 features are okay." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T00:39:18.987", "Id": "11106", "Score": "0", "body": "Hm. If my proposal doesn't use templates at all (while still evaluating everything at compile time (so you'd still be able to use the result from inside other templates) and supporting `static_assert`), would that still be in the spirit of the exercise?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T08:31:27.070", "Id": "11118", "Score": "0", "body": "@sepp2k I wasn't aware of `constexpr`. I guess I could have stated my question more generally as wanting a compiler error if a number that isn't a perfect square is used." } ]
[ { "body": "<p>I'd recommend against using ALL_CAPS for class-names. It's not really in accordance with C++ conventions.</p>\n\n<pre><code>template&lt;size_t n, size_t r&gt;\nstruct IS_SQUARE {\n static const bool value = IF&lt;n == r*r,\n true,\n IF&lt;GREATER&lt;n, r*r&gt;::ret,\n IS_SQUARE&lt;n, r+1&gt;::value,\n false&gt;::ret\n &gt;::ret;\n};\n</code></pre>\n\n<p>You can replace the outer if with <code>||</code> (<code>if foo then true else bar</code> is equivalent to <code>foo || bar</code>) here to get rid of one level of nesting and simplify the condition a bit. One might think that you can also replace the inner if with <code>&amp;&amp;</code>, but that won't work because template-instantiation doesn't short-circuit in the way you'd want it to when using logical operators (i.e. <code>foo &amp;&amp; Bar&lt;baz&gt;</code> will try to instantiate <code>Bar&lt;baz&gt;</code> even if <code>foo</code> is false, leading to infinite recursion in this case).</p>\n\n<pre><code>template&lt;size_t n&gt;\nstruct SQUARE {\n static const bool value = IS_SQUARE&lt;n, 1&gt;::value;\n};\n</code></pre>\n\n<p>You might want to use 0 instead of 1 as the starting value here. Otherwise you'll get incorrect results for <code>n=0</code> (which is a square of itself and should thus return true).</p>\n\n<pre><code>template&lt;&gt;\nstruct SQUARE&lt;1&gt; {\n static const bool value = true;\n};\n</code></pre>\n\n<p>This is redundant because <code>IS_SQUARE&lt;1, 1&gt;</code> (or <code>IS_SQUARE&lt;1,0&gt;</code>) is true anyway.</p>\n\n<hr>\n\n<p>Apart from the nitpicks listed above, your code looks fine (or as fine as TMP code ever looks, anyway). However it can be completely replaced using <code>constexpr</code>, which still gives you compile-time evaluation (including the ability to use the result inside template arguments or <code>static_assert</code>), while being greatly more readable:</p>\n\n<p>The beauty of C++11's <code>constexpr</code> feature is that it allows you to write compile-time expressions using normal C++ syntax, instead of encoding everything using template classes. You're not allowed to use loops or any side-effects, so you still have to use the recursive approach you used (as opposed to the iterative approach you'd probably use at run-time), but it can be greatly simplified by expressing it as a simple recursive function instead of a bunch of templates:</p>\n\n<pre><code>constexpr bool is_square(size_t n, size_t r=0) {\n return (r*r == n) || ( (r*r &lt; n) &amp;&amp; is_square(n, r+1));\n}\n\nint main() {\n static_assert(is_square(1), \"must be square\");\n static_assert(is_square(4), \"must be square\");\n static_assert(is_square(5), \"must be square\"); // compile error\n}\n</code></pre>\n\n<p>As a learning-exercise for template meta programming this version is completely useless, of course, as it does not actually contain any templates. But it's definitely more readable (and more writable as well) and can be used in any scenario where the template-version can be used. So in any real C++11 meta-programming project, I'd always recommend using <code>constexpr</code> over templates when it's possible. This way you can perform your calculations in functions that look like C++ functions (well, C++ functions that are written in a surprisingly functional style) and use templates to define classes (which depend on the results of those calculations).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T08:33:52.387", "Id": "11119", "Score": "0", "body": "Thanks! I definitely like the `constexpr` better than using templates since it is much clearer and should be easier maintain." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T01:12:59.870", "Id": "7130", "ParentId": "7128", "Score": "5" } } ]
{ "AcceptedAnswerId": "7130", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T23:37:49.973", "Id": "7128", "Score": "5", "Tags": [ "c++", "c++11", "template-meta-programming" ], "Title": "Meta-program to find square numbers" }
7128
<p>I have been reading about <code>ZF2 EventManager</code> for some time now and I wonder what you'd think about this approach.</p> <pre><code>class Model_Member extends App_Model_Model { protected $_data = array( 'ID' =&gt; null, 'UserName' =&gt; null, 'Password' =&gt; null, 'EmailAddress' =&gt; null, 'CreatedOn' =&gt; null, 'Status' =&gt; 0, 'PasswordResetHash' =&gt; null, 'Role' =&gt; 'member' ); const EVENT_SAVE = 'save'; const EVENT_POSTSAVE = 'post.save'; public function init() { $this-&gt;events()-&gt;attach(self::EVENT_SAVE, array('Service_Member', 'save')); } public function save() { $id = $this-&gt;events()-&gt;trigger(self::EVENT_SAVE, $this)-&gt;last(); $this-&gt;ID = $id; $this-&gt;events()-&gt;trigger(self::EVENT_POSTSAVE, $this); } } </code></pre> <p>And of course there is Service_Member</p> <pre><code>public function save($event) { // Get the member from the event $member = $event-&gt;getTarget(); // If there is no id, save, otherwise update if (!$member-&gt;ID) { $id = $this-&gt;doSave($member); $event-&gt;setParam('id', $id); return $id; } else { return $this-&gt;doUpdate($member); } } public function doSave(Model_Member $member) { // Check if username is taken if ($this-&gt;checkIfExists('UserName', $member-&gt;UserName)) { throw new App_Exception_UserNameExists('This username is already taken.'); } // Check if email address already registered if ($this-&gt;checkIfExists('EmailAddress', $member-&gt;EmailAddress)) { throw new App_Exception_EmailAddressExists('This email is already registered.'); } // Set default values $member-&gt;CreatedOn = date('Y-m-d H:i:s'); // Encrypt password $member-&gt;Password = sha1($member-&gt;Password); // Get the data and save. Return the member with new ID $data = $member-&gt;_toArray(); unset($data['ID']); $this-&gt;getWriteDb()-&gt;insert('members', $data); $id = $this-&gt;getWriteDb()-&gt;lastInsertId(); return $id; } </code></pre> <p>Do you think this is an acceptable approach?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T14:08:39.380", "Id": "11346", "Score": "0", "body": "I think I chose a very bad time for asking a question? is everyone on holiday :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T12:26:51.493", "Id": "11686", "Score": "0", "body": "Back from holiday :) I think your code is just fine, don't see anything wrong with it. There is no point in some of your comments, like `// Check if username is taken` when the condition is `($this->checkIfExists('UserName', $member->UserName))` - It's pretty obvious what you do, no need to write a comment about it. Same with `// Encrypt password`, `// Get the member from the event` etc. But if those are helpful to you, leave them as is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T13:01:17.447", "Id": "11687", "Score": "0", "body": "Hi Yannis, thanks for the reply. The comments were place holders. I put them before I write the code.\n\nMy question was is it a good practice to use EventManager to persist models." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-04T13:02:59.350", "Id": "11688", "Score": "0", "body": "Yeah, I do that a lot :) Beware of [comment smell](http://programmers.stackexchange.com/questions/1/comments-are-a-code-smell)." } ]
[ { "body": "<p>I haven't used PHP recently, just a few, mostly minor notes:</p>\n\n<ol>\n<li><blockquote>\n<pre><code>// Encrypt password\n$member-&gt;Password = sha1($member-&gt;Password);\n</code></pre>\n</blockquote>\n\n<p>You might want to use <a href=\"https://crypto.stackexchange.com/q/1776/8221\">a salt</a> here to make your hashing stronger.</p></li>\n<li><blockquote>\n<pre><code>$this-&gt;getWriteDb()-&gt;insert('members', $data);\n$id = $this-&gt;getWriteDb()-&gt;lastInsertId();\n</code></pre>\n</blockquote>\n\n<p>If that's possible, <code>insert</code> could return the ID. It would eliminate temporal coupling (users can't call the methods in the wrong order).</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G31: Hidden Temporal Couplings</em>, p302)</p></li>\n<li><blockquote>\n<pre><code>'Status' =&gt; 0,\n</code></pre>\n</blockquote>\n\n<p><code>0</code> is a magic number here. What could it mean? A named constants would express the intent.</p></li>\n<li><p>These comments are rather redundant, the code is clear and says the same:</p>\n\n<blockquote>\n<pre><code>// Check if username is taken\nif ($this-&gt;checkIfExists('UserName', $member-&gt;UserName)) {\n throw new App_Exception_UserNameExists('This username is already taken.');\n}\n\n// Check if email address already registered\nif ($this-&gt;checkIfExists('EmailAddress', $member-&gt;EmailAddress)) {\n throw new App_Exception_EmailAddressExists('This email is already registered.');\n}\n</code></pre>\n</blockquote>\n\n<p>...</p>\n\n<blockquote>\n<pre><code>// Get the member from the event\n$member = $event-&gt;getTarget();\n</code></pre>\n</blockquote>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Redundant Comments</em>, p60)</p></li>\n<li><p>Btw, are you sure that you need two different type of exceptions here? Wouldn't be the same exception type with different messages enough?</p></li>\n<li><p>Use <code>private</code> instead of <code>protected</code> if possible:</p>\n\n<blockquote>\n<pre><code>protected $_data = array(\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/questions/5484845/should-i-always-use-the-private-access-modifier-for-class-fields\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.</p></li>\n<li><blockquote>\n<pre><code>class Model_Member extends App_Model_Model\n</code></pre>\n</blockquote>\n\n<p>The class name is weird a little bit. Model of a model? <code>App</code> also too generic, something more descriptive would be better.</p></li>\n<li><blockquote>\n<pre><code>$member-&gt;CreatedOn = date('Y-m-d H:i:s');\n</code></pre>\n</blockquote>\n\n<p>Wouldn't be better using <a href=\"http://www.php.net/manual/en/class.datetime.php\" rel=\"nofollow noreferrer\">DateTime</a> objects here?</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T07:05:33.377", "Id": "44729", "ParentId": "7132", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T03:18:13.473", "Id": "7132", "Score": "5", "Tags": [ "php", "object-oriented", "php5", "zend-framework" ], "Title": "Using ZF2 Event manager to save a model" }
7132
<p>I have a small program where I have a background thread that plays sound, so it needs to run really fast, but it also needs to do a small amount of memory management. I didn't want to use normal new and delete in a time critical area, so I threw this together, but set it up so I could reuse it elsewhere. </p> <pre><code>template &lt;typename T, unsigned int capacity&gt; class MemoryPool { public: MemoryPool() { for (unsigned int i = 0; i &lt; capacity; i++) { myUnusedMemory[i] = &amp;myMemory[i]; } } void* operator new(std::size_t size) { return myUnusedMemory[myUnusedIndex--]; } void operator delete(void* ptr) { myUnusedMemory[++myUnusedIndex] = (T*)ptr; } private: static int myUnusedIndex; static T myMemory[capacity]; static T* myUnusedMemory[capacity]; }; template &lt;typename T, unsigned int capacity&gt; int MemoryPool&lt;T, capacity&gt;::myUnusedIndex = capacity-1; template &lt;typename T, unsigned int capacity&gt; T MemoryPool&lt;T, capacity&gt;::myMemory[capacity]; template &lt;typename T, unsigned int capacity&gt; T* MemoryPool&lt;T, capacity&gt;::myUnusedMemory[capacity]; </code></pre> <p>The intended usage is something like this:</p> <pre><code>struct Sound : public ag::util::MemoryPool&lt;Sound, 100&gt; { // ... }; </code></pre> <p>Now when calling <code>new Sound()</code> I get one from my memory pool, which should be super fast. The only things that I can think of that could be improved are making <code>operator new</code> throw an exception when at capacity. I think I might be able to do away with <code>typename T</code>. The only reason it's needed is so that <code>myMemory</code> knows the size of its elements, but I feel like there's another solution here.</p>
[]
[ { "body": "<p>This currently will not work.</p>\n\n<p>As every-time you create an object derived from <code>MemoryPool</code> you re-initialize the <code>myUnusedMemory</code> structure thus potentially messing up your management.</p>\n\n<pre><code>struct Game : public ag::util::MemoryPool&lt;Game, 2&gt; {};\n\n\nint main()\n{\n Game* p1 = new Game;\n Game* p2 = new Game;\n delete p1;\n delete p2;\n\n // myUnusedMemory now set like this:\n // myUnusedMemory[0] = &amp;myMemory[1];\n // myUnusedMemory[1] = &amp;myMemory[0];\n\n // Now when we create the next one it resets the array:\n\n Game* p3 = new Game;\n // myUnusedMemory now set like this: (because the constructor reset the array)\n // myUnusedMemory[0] = &amp;myMemory[0];\n // myUnusedMemory[1] = &amp;myMemory[1];\n\n Game* p4 = new Game; // Now p3 and p4 point at the same memory location\n}\n</code></pre>\n\n<p>This line:</p>\n\n<pre><code>static T myMemory[capacity];\n</code></pre>\n\n<p>Is also not good as you are actually initializing the objects. Thus, when you are calling <code>new</code> your <code>new operator</code> is returning a pointer to an already initialized object . The constructor will then be re-called. Thus overriding the original content without the destructor being called (thus leaking any memory that should have been deleted).</p>\n\n<p>I suppose you could call the destructor inside the <code>new operator</code> but that seems wasteful (and may be expensive) and sort of counter intuitive. So you want to use uninitialized memory for your pool.<br>\nYou could do this:</p>\n\n<pre><code>static char myMemory[capacity * sizeof(T)];\n</code></pre>\n\n<p>But unfortunately this is not guaranteed to be correctly aligned.<br>\nIf you dynamically allocate the memory then it will be fine. Use <code>std::vector</code> and it will be dynamically allocated and safe.</p>\n\n<pre><code>static std::vector&lt;char&gt; myMemory(capacity * sizeof(T));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T15:53:45.447", "Id": "11123", "Score": "0", "body": "Oh duh, you're right wrt the constructor. Thank you much." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T12:20:13.677", "Id": "50912", "Score": "0", "body": "`boost` and `c++11` can help with alignment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T15:16:55.287", "Id": "50926", "Score": "0", "body": "@user1095108: C++03 works well on alignment. Just use a `std::vector<>`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T16:18:34.087", "Id": "50938", "Score": "0", "body": "@LokiAstari Not, if you _don't_ want to allocate from the heap." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-27T16:59:23.440", "Id": "50946", "Score": "0", "body": "@user1095108: (1) don't use the term heap in C++ its not accurate. You mean \"dynamic\" memory. (2) It is a bad idea to use \"automatic\" memory as there is a size limit relative to the [maximum size of the stack frame](http://stackoverflow.com/a/216731/14065) which is very variable and compiler/hardware dependant." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T08:26:41.900", "Id": "7134", "ParentId": "7133", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T06:45:52.973", "Id": "7133", "Score": "9", "Tags": [ "c++", "memory-management" ], "Title": "Super simple templated memory pool in C++" }
7133
<p>How do I make my Python program faster?</p> <p>I have 3 suspects right now for it being so slow:</p> <ol> <li><p>Maybe my computer is just slow</p></li> <li><p>Maybe my Internet is too slow (sometimes my program has to download the html of web pages and then it searches through the html for a specific piece of text)</p></li> <li><p>My code is slow (too many loops maybe? something else? I'm new to this so I wouldn't know!)</p></li> </ol> <p>My code uses lots of loops I think...ALSO, another thing is that for the program to work you have to be logged in to this website: <a href="http://www.locationary.com/" rel="nofollow">http://www.locationary.com/</a></p> <pre><code>from urllib import urlopen from gzip import GzipFile from cStringIO import StringIO import re import urllib import urllib2 import webbrowser import mechanize import time from difflib import SequenceMatcher import os def download(url): s = urlopen(url).read() if s[:2] == '\x1f\x8b': # assume it's gzipped data with GzipFile(mode='rb', fileobj=StringIO(s)) as ifh: s = ifh.read() return s s = download('http://www.locationary.com/place/en/US/Utah/Provo-page5/?ACTION_TOKEN=NumericAction') findLoc = re.compile('http://www\.locationary\.com/place/en/US/.{1,50}/.{1,50}/.{1,100}\.jsp') findLocL = re.findall(findLoc,s) W = [] X = [] XA = [] Y = [] YA = [] Z = [] ZA = [] for i in range(0,25): b = download(findLocL[i]) findYP = re.compile('http://www\.yellowpages\.com/') findYPL = re.findall(findYP,b) findTitle = re.compile('&lt;title&gt;(.*) \(\d{1,10}.{1,100}\)&lt;/title&gt;') getTitle = re.findall(findTitle,b) findAddress = re.compile('&lt;title&gt;.{1,100}\((.*), .{4,14}, United States\)&lt;/title&gt;') getAddress = re.findall(findAddress,b) if not findYPL: if not getTitle: print "" else: W.append(findLocL[i]) b = download(findLocL[i]) if not getTitle: print "" else: X.append(getAddress) b = download(findLocL[i]) if not getTitle: print "" else: Y.append(getTitle) sizeWXY = len(W) def XReplace(text, dic): for i, j in dic.iteritems(): text = text.replace(i, j) XA.append(text) def YReplace(text2, dic2): for k, l in dic2.iteritems(): text2 = text2.replace(k, l) YA.append(text2) for d in range(0,sizeWXY): old = str(X[d]) reps = {' ':'-', ',':'', '\'':'', '[':'', ']':''} XReplace(old, reps) old2 = str(Y[d]) YReplace(old2, reps) count = 0 for e in range(0,sizeWXY): newYPL = "http://www.yellowpages.com/" + XA[e] + "/" + YA[e] + "?order=distance" v = download(newYPL) abc = str('&lt;h3 class="business-name fn org"&gt;\n&lt;a href="') dfe = str('" class="no-tracks url "') findFinal = re.compile(abc + '(.*)' + dfe) getFinal = re.findall(findFinal, v) if not getFinal: W.remove(W[(e-count)]) X.remove(X[(e-count)]) count = (count+1) else: for f in range(0,1): Z.append(getFinal[f]) XA = [] for c in range(0,(len(X))): aGd = re.compile('(.*), .{1,50}') bGd = re.findall(aGd, str(X[c])) XA.append(bGd) LenZ = len(Z) V = [] for i in range(0,(len(W))): if i == 0: countTwo = 0 gda = download(Z[i-(countTwo)]) ab = str('"street-address"&gt;\n') cd = str('\n&lt;/span&gt;') ZAddress = re.compile(ab + '(.*)' + cd) ZAddress2 = re.findall(ZAddress, gda) for b in range(0,(len(ZAddress2))): if not ZAddress2[b]: print "" else: V.append(str(ZAddress2[b])) a = str(W[i-(countTwo)]) n = str(Z[i-(countTwo)]) c = str(XA[i]) d = str(V[i]) #webbrowser.open(a) #webbrowser.open(n) m = SequenceMatcher(None, c, d) if m.ratio() &lt; 0.50: Z.remove(Z[i-(countTwo)]) W.remove(W[i-(countTwo)]) countTwo = (countTwo+1) #LenZ2 = LenZ - (len(Z)) #if len(Z) == LenZ: #print "All of the Yellowpages were correct!" #else: #if LenZ2 &gt; 1: #print str(LenZ2) + " of the Yellowpages were incorrect!" #else: #print str(LenZ2) + " of the Yellowpages was incorrect!" def ZReplace(text3, dic3): for p, q in dic3.iteritems(): text3 = text3.replace(p, q) ZA.append(text3) for y in range(0,len(Z)): old3 = str(Z[y]) reps2 = {':':'%3A', '/':'%2F', '?':'%3F', '=':'%3D'} ZReplace(old3, reps2) #br = mechanize.Browser() for z in range(0,len(ZA)): findPID = re.compile('\d{5,20}') getPID = re.findall(findPID,str(W[z])) newPID = re.sub("\D", "", str(getPID)) finalURL = "http://www.locationary.com/access/proxy.jsp?ACTION_TOKEN=proxy_jsp$JspView$SaveAction&amp;inPlaceID=" + str(newPID) + "&amp;xxx_c_1_f_987=" + str(ZA[z]) webbrowser.open(finalURL) time.sleep(5) os.system("taskkill /F /IM firefox.exe") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T16:56:20.190", "Id": "11124", "Score": "1", "body": "What do you mean by \"very slow\"? Does it take hours, days? How long does it take and what were you expecting?" } ]
[ { "body": "<pre><code>from urllib import urlopen\nfrom gzip import GzipFile\nfrom cStringIO import StringIO\nimport re\nimport urllib\nimport urllib2\nimport webbrowser\nimport mechanize\nimport time\nfrom difflib import SequenceMatcher\nimport os\n\ndef download(url):\n s = urlopen(url).read()\n if s[:2] == '\\x1f\\x8b': # assume it's gzipped data\n with GzipFile(mode='rb', fileobj=StringIO(s)) as ifh:\n s = ifh.read()\n return s\n</code></pre>\n\n<p>I'd probably pick a more descriptive name then <code>s</code></p>\n\n<pre><code>s = download('http://www.locationary.com/place/en/US/Utah/Provo-page5/?ACTION_TOKEN=NumericAction')\n\nfindLoc = re.compile('http://www\\.locationary\\.com/place/en/US/.{1,50}/.{1,50}/.{1,100}\\.jsp')\n</code></pre>\n\n<p>For constants, its usually best practice to name them in ALL_CAPS and put them outside of the actual logic. The logic in your program should really be in a main function not at the module level.</p>\n\n<pre><code>findLocL = re.findall(findLoc,s)\n</code></pre>\n\n<p>Not a very descriptive name, perhaps you can come up with a better one.</p>\n\n<pre><code>W = []\n\nX = []\n\nXA = []\n\nY = []\n\nYA = []\n\nZ = []\n\nZA = []\n</code></pre>\n\n<p>Don't double-space your code. Also, these variables are either really badly name or shouldn't be seperate variables. Possibly both.</p>\n\n<pre><code>for i in range(0,25):\n</code></pre>\n\n<p>Why 25? Do you want everything in findLocL? Then you should use <code>for loc in findLocL</code>.</p>\n\n<pre><code> b = download(findLocL[i])\n\n findYP = re.compile('http://www\\.yellowpages\\.com/')\n\n findYPL = re.findall(findYP,b)\n</code></pre>\n\n<p>You don't have to call compile, you can just pass the regular expression as the first parameter. Compiling is only helpful if you use the compiled expression multiple times. Also, aren't you just searching for a simple string here? Why use regular expressions?</p>\n\n<pre><code> findTitle = re.compile('&lt;title&gt;(.*) \\(\\d{1,10}.{1,100}\\)&lt;/title&gt;')\n\n getTitle = re.findall(findTitle,b)\n\n findAddress = re.compile('&lt;title&gt;.{1,100}\\((.*), .{4,14}, United States\\)&lt;/title&gt;')\n\n getAddress = re.findall(findAddress,b)\n\n if not findYPL:\n\n if not getTitle:\n</code></pre>\n\n<p>Why did you findall if you just endup checking for a single match?</p>\n\n<pre><code> print \"\"\n\n else:\n\n W.append(findLocL[i])\n</code></pre>\n\n<p>What the fried monkey is W? What you are searching for? You code is difficult to follow.</p>\n\n<pre><code> b = download(findLocL[i])\n\n if not getTitle:\n\n print \"\"\n\n else:\n\n X.append(getAddress)\n\n b = download(findLocL[i])\n</code></pre>\n\n<p>So you just downloaded this file a few lines before. Why are you downloading it again? And why don't you ever do anything with the b you get?</p>\n\n<pre><code> if not getTitle:\n\n print \"\"\n\n else:\n\n Y.append(getTitle)\n\nsizeWXY = len(W)\n</code></pre>\n\n<p>Was that really helpful? </p>\n\n<pre><code>def XReplace(text, dic):\n for i, j in dic.iteritems():\n text = text.replace(i, j) \n XA.append(text)\n\ndef YReplace(text2, dic2):\n for k, l in dic2.iteritems():\n text2 = text2.replace(k, l) \n YA.append(text2)\n</code></pre>\n\n<p>These functions do pretty much the same thing. The only difference is that they both modify global variables. You shouldn't really be modifying global variables anyways.</p>\n\n<pre><code>for d in range(0,sizeWXY):\n\n old = str(X[d])\n</code></pre>\n\n<p>So... sizeWXY is len(W) but here you are fetching from X, what the fried turkey?</p>\n\n<pre><code> reps = {' ':'-', ',':'', '\\'':'', '[':'', ']':''}\n\n XReplace(old, reps)\n\n old2 = str(Y[d])\n\n YReplace(old2, reps)\n\ncount = 0\n\nfor e in range(0,sizeWXY):\n\n newYPL = \"http://www.yellowpages.com/\" + XA[e] + \"/\" + YA[e] + \"?order=distance\"\n\n v = download(newYPL)\n\n abc = str('&lt;h3 class=\"business-name fn org\"&gt;\\n&lt;a href=\"')\n</code></pre>\n\n<p>Why are constructing a string from a string?</p>\n\n<pre><code> dfe = str('\" class=\"no-tracks url \"')\n\n findFinal = re.compile(abc + '(.*)' + dfe)\n\n getFinal = re.findall(findFinal, v)\n\n if not getFinal:\n\n W.remove(W[(e-count)])\n</code></pre>\n\n<p>Use <code>del W[e-count]</code></p>\n\n<pre><code> X.remove(X[(e-count)])\n\n count = (count+1)\n</code></pre>\n\n<p>No need for those parens</p>\n\n<pre><code> else:\n\n for f in range(0,1):\n\n Z.append(getFinal[f])\n</code></pre>\n\n<p>So... that loop only executes once. Why is it a loop?</p>\n\n<pre><code>XA = []\n</code></pre>\n\n<p>Rather then reusing XA, I'd suggest working with a new list here.</p>\n\n<pre><code>for c in range(0,(len(X))):\n\n aGd = re.compile('(.*), .{1,50}')\n\n bGd = re.findall(aGd, str(X[c]))\n</code></pre>\n\n<p>bGd? seriously? What the fried turkey marshmallow duck is that supposed to be?</p>\n\n<pre><code> XA.append(bGd)\n\nLenZ = len(Z)\n</code></pre>\n\n<p>Don't do this. You are probably doing this because if you don't in C, it'll recalculate the length constantly as you execute a loop. Python doesn't do that. </p>\n\n<pre><code>V = []\n\nfor i in range(0,(len(W))):\n</code></pre>\n\n<p>Here you do pass the length to range. But you don't need those parens around it.</p>\n\n<pre><code> if i == 0:\n\n countTwo = 0\n</code></pre>\n\n<p>Why don't you do this before the loop starts? That should be the same</p>\n\n<pre><code> gda = download(Z[i-(countTwo)])\n</code></pre>\n\n<p>No need for the parens around countTwo. </p>\n\n<pre><code> ab = str('\"street-address\"&gt;\\n')\n\n cd = str('\\n&lt;/span&gt;')\n\n ZAddress = re.compile(ab + '(.*)' + cd)\n\n ZAddress2 = re.findall(ZAddress, gda)\n\n for b in range(0,(len(ZAddress2))):\n</code></pre>\n\n<p>In python you should almost never use a range loop unless you are actually counting. If you are looping with a length of something, you should almost always be looping over the list not range.</p>\n\n<pre><code> if not ZAddress2[b]:\n\n print \"\"\n\n else:\n\n V.append(str(ZAddress2[b]))\n\n a = str(W[i-(countTwo)])\n\n n = str(Z[i-(countTwo)])\n\n c = str(XA[i])\n\n d = str(V[i])\n</code></pre>\n\n<p>So many hopelessly badly named variables. It hurts!</p>\n\n<pre><code> #webbrowser.open(a)\n\n #webbrowser.open(n)\n\n m = SequenceMatcher(None, c, d)\n</code></pre>\n\n<p>Ok, I'm impressed that you know about and use this.</p>\n\n<pre><code> if m.ratio() &lt; 0.50:\n\n Z.remove(Z[i-(countTwo)])\n\n W.remove(W[i-(countTwo)])\n\n countTwo = (countTwo+1)\n\n#LenZ2 = LenZ - (len(Z))\n\n\n\n#if len(Z) == LenZ:\n\n #print \"All of the Yellowpages were correct!\"\n\n#else:\n\n #if LenZ2 &gt; 1:\n\n #print str(LenZ2) + \" of the Yellowpages were incorrect!\"\n\n #else:\n\n #print str(LenZ2) + \" of the Yellowpages was incorrect!\"\n</code></pre>\n\n<p>Don't keep dead code in comments</p>\n\n<pre><code>def ZReplace(text3, dic3):\n for p, q in dic3.iteritems():\n text3 = text3.replace(p, q) \n ZA.append(text3)\n</code></pre>\n\n<p>Deja vu!</p>\n\n<pre><code>for y in range(0,len(Z)):\n\n old3 = str(Z[y])\n\n reps2 = {':':'%3A', '/':'%2F', '?':'%3F', '=':'%3D'}\n\n ZReplace(old3, reps2)\n</code></pre>\n\n<p>When you find yourself repeating the same code several times, its a sign you need to refactor</p>\n\n<pre><code>#br = mechanize.Browser()\n\nfor z in range(0,len(ZA)):\n\n findPID = re.compile('\\d{5,20}')\n\n getPID = re.findall(findPID,str(W[z]))\n\n newPID = re.sub(\"\\D\", \"\", str(getPID))\n\n finalURL = \"http://www.locationary.com/access/proxy.jsp?ACTION_TOKEN=proxy_jsp$JspView$SaveAction&amp;inPlaceID=\" + str(newPID) + \"&amp;xxx_c_1_f_987=\" + str(ZA[z])\n\n webbrowser.open(finalURL)\n\n time.sleep(5)\n\nos.system(\"taskkill /F /IM firefox.exe\")\n</code></pre>\n\n<p>Stylistically, your code has a few issues which I've mentioned above. But in terms of performance, you are downloading web pages. The downloads will take way longer then the code so any speed issues in your code itself will not be noticeable. </p>\n\n<p>I did point a couple of cases where you are downloading files you don't actually do anything with. Getting rid of those will help your code be faster. </p>\n\n<p>You are trying to pull things out of HTML using regular expressions. This is a bad idea. It'll be brittle, hard to get right, and hard to read. Instead you should use something like BeautifulSoup: <a href=\"http://www.crummy.com/software/BeautifulSoup/\">http://www.crummy.com/software/BeautifulSoup/</a>. It'll parse HTML, (even broken HTML) and make it easy to pull out the pieces you are interested in. </p>\n\n<p>The way to speed up the code is to fetch multiple web pages at the same time, and to process once web page while waiting for the others to download. The easiest way to do this is with the eventlet library.</p>\n\n<p>Here is my rewrite of your code. I make no guarantees of correctness and I know it doesn't do the error handling it should. It also has too much stuff going on in the main function. But it doesn't suffer from the same speed problems. I'm just trying to give a hint at how your code could be easier to follow and not have the same performance problems.</p>\n\n<pre><code>from gzip import GzipFile\nfrom cStringIO import StringIO\nimport re\nimport webbrowser\nimport time\nfrom difflib import SequenceMatcher\nimport os\nimport sys\nfrom BeautifulSoup import BeautifulSoup\nimport eventlet\nfrom eventlet.green import urllib2\n\nSTART_URL = 'http://www.locationary.com/place/en/US/Utah/Provo-page5/?ACTION_TOKEN=NumericAction'\nTITLE_MATCH = re.compile(r'(.*) \\(\\d{1,10}.{1,100}\\)$')\nADDRESS_MATCH = re.compile(r'.{1,100}\\((.*), .{4,14}, United States\\)$')\nLOCATION_LISTING = re.compile(r'http://www\\.locationary\\.com/place/en/US/.{1,50}/.{1,50}/.{1,100}\\.jsp')\n\ndef download(url):\n print \"Downloading:\", url\n s = urllib2.urlopen(url).read()\n if s[:2] == '\\x1f\\x8b': # assume it's gzipped data\n ifh = GzipFile(mode='rb', fileobj=StringIO(s))\n s = ifh.read()\n print \"Downloaded: \", url\n return s\n\ndef replace_chars(text, replacements):\n return ''.join(replacements.get(x,x) for x in text)\n\ndef handle_listing(listing_url):\n listing_document = BeautifulSoup(download(listing_url))\n\n # ignore pages that link to yellowpages\n if not listing_document.find(\"a\", href=re.compile(re.escape(\"http://www.yellowpages.com/\") + \".*\")):\n listing_title = listing_document.title.text\n reps = {' ':'-', ',':'', '\\'':'', '[':'', ']':''}\n title, = TITLE_MATCH.match(listing_title).groups()\n address, = ADDRESS_MATCH.match(listing_title).groups()\n\n yellow_page_url = \"http://www.yellowpages.com/%s/%s?order=distance\" % (\n replace_chars(address, reps),\n replace_chars(title, reps),\n )\n\n yellow_page = BeautifulSoup(download(yellow_page_url))\n\n page_url = yellow_page.find(\"h3\", {\"class\" : \"business-name fn org\"})\n if page_url:\n page_url = page_url.a[\"href\"]\n\n business_name = title[:title.index(\",\")]\n\n page = BeautifulSoup(download(page_url))\n yellow_page_address = page.find(\"span\", {\"class\" : \"street-address\"})\n if yellow_page_address:\n\n if SequenceMatcher(None, address, yellow_page_address.text).ratio() &gt;= 0.5:\n pid, = re.search(r'p(\\d{5,20})\\.jsp', listing_url).groups(0)\n page_escaped = replace_chars(page_url, {':':'%3A', '/':'%2F', '?':'%3F', '=':'%3D'})\n\n final_url = \"http://www.locationary.com/access/proxy.jsp?ACTION_TOKEN=proxy_jsp$JspView$SaveAction&amp;inPlaceID=%s&amp;xxx_c_1_f_987=%s\" % (\n pid, page_escaped)\n return final_url\n\n\ndef main():\n pool = eventlet.GreenPool()\n listings_document = BeautifulSoup(download(START_URL))\n listings = listings_document.findAll(\"a\", href = LOCATION_LISTING)\n listings = [listing['href'] for listing in listings]\n\n for final_url in pool.imap(handle_listing, listings):\n print final_url\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T22:28:56.437", "Id": "11135", "Score": "0", "body": "Thank you so much!! I especially like your humor! I'm new to this and I know I didn't originally post that but you still can't expect very good code from me...I just did this to automate using this website. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T06:31:04.590", "Id": "11139", "Score": "1", "body": "@jacob501, no worries. Making something this complex and having it works shows you've got something right!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T19:13:26.783", "Id": "7140", "ParentId": "7136", "Score": "14" } }, { "body": "<p>I won't cover everything, but do you suppose this:</p>\n\n<pre><code>for z in range(0,len(ZA)):\n # ...\n time.sleep(5)\n</code></pre>\n\n<p>has anything to do with the code being slow? I didn't take the time to completely parse what in the world you are storing in a variable named <code>ZA</code>, but for each one in it you're going to <a href=\"http://docs.python.org/library/time.html#time.sleep\" rel=\"nofollow\">sleep for 5 seconds</a>. It seems to me that would slow the program down well more than almost any effect you'll get from actual processing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T17:30:55.967", "Id": "11216", "Score": "1", "body": "That only happens in the last loop when it is launching web browsers. It is very slow in getting to that loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T03:53:07.540", "Id": "7177", "ParentId": "7136", "Score": "1" } } ]
{ "AcceptedAnswerId": "7140", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T13:39:09.423", "Id": "7136", "Score": "6", "Tags": [ "python", "performance", "io", "web-scraping", "compression" ], "Title": "Slow web-scraping geolocator" }
7136
<p>This is my first attempt at a hash map and I feel it is a great start. Although it does have a certain naive feel that I'm having trouble with.</p> <pre><code>public class HashMap&lt;TKey, TValue&gt; { const int BlockSize = 100000; const int NumberOfBlocks = 42950; readonly Entry[][] _blocks = new Entry[NumberOfBlocks][]; readonly IEqualityComparer&lt;TKey&gt; _comparer = EqualityComparer&lt;TKey&gt;.Default; public void Add(TKey key, TValue value) { uint hashCode = (uint)_comparer.GetHashCode(key); int blockIndex = (int)(hashCode / BlockSize); int slotIndex = (int)(hashCode - blockIndex * BlockSize); var block = _blocks[blockIndex]; if (block == null) { block = _blocks[blockIndex] = new Entry[BlockSize]; } var entry = block[slotIndex]; if (entry == null) { entry = block[slotIndex] = new Entry(key, value); } else { while (entry != null &amp;&amp; entry.Next != null) { if (_comparer.Equals(key, entry.Key)) { throw new Exception(); } entry = entry.Next; } entry = entry.Next = new Entry(key, value); } } public bool ContainsKey(TKey key) { uint hashCode = (uint)_comparer.GetHashCode(key); int blockIndex = (int)(hashCode / BlockSize); int slotIndex = (int)(hashCode - blockIndex * BlockSize); var block = _blocks[blockIndex]; if (block == null) return false; var entry = block[slotIndex]; while (entry != null) { if (_comparer.Equals(key, entry.Key)) return true; entry = entry.Next; } return false; } class Entry { public readonly TKey Key; public readonly TValue Value; public Entry Next; public Entry(TKey key, TValue value) { Key = key; Value = value; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T17:15:19.847", "Id": "11144", "Score": "0", "body": "wouldn't it be a good idea to implement [IDictionary<TKey,TValue>](http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx), and maybe using `KeyValuePair<TKey,TValue>`s as entries instead of your custom `Entry`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T18:22:21.730", "Id": "11148", "Score": "0", "body": "@codesparkle - I briefly thought about using `KeyValuePair<TKey,TValue>` but I wanted each slot to work also as a singly linked list so that collisions could be handled simply. As for `IDictionary<TKey,TValue>` I wanted to keep things simple so I could focus on the logic." } ]
[ { "body": "<p>(I'm assuming you're implementing your own hashtable as an exercise/kata instead of using the CLR's, as I haven't seen anything unique here that justifies rolling your own.)</p>\n\n<p>Here's some feedback:</p>\n\n<ol>\n<li><p><code>HashMap</code> should implement core interfaces and functionality as other .NET containers do (e.g.: <code>IEnumerable&lt;T&gt;</code>, <code>IDictionary&lt;TKey,TValue&gt;</code>, provide an enumerator implementation). As a guide, look at the <code>Dictionary&lt;TKey,TValue&gt;</code> class and see what interfaces it implements. I'd expect your code to have a similar level of service;</p></li>\n<li><p><code>_blocks</code> should be a <code>List</code> instead of an array, and its capacity (<code>NumberOfBlocks</code>) should be passed optionally through an optional constructor argument. Same applies to the equality comparer. Notice that these initial values seem very, very high - allocating a 42950-Entry[] array right off the bet for an empty container, and an additional 100,000 Entry array at first addition;</p></li>\n<li><p>Why cast <code>hashCode</code> to <code>uint</code>?</p></li>\n<li><p>Notice the duplicate code between <code>Add</code> and <code>ContainsKey</code>. This should be cleanly refactored;</p></li>\n<li><p><code>blockIndex</code>'s and <code>slotIndex</code>'s calculations do not seem correct. For example, you are dividing by 100,000, so this will work because <code>int.MaxValue &lt; 100000 * 100000</code>. However, if you make this configurable and a lower value is used, you could go past your <code>_blocks</code> size. You should use modulo instead of division. Also, <code>slotIndex</code> will always be zero (or 1 due to rounding) as <code>(hashCode - blockIndex * BlockSize) == (hashCode - hashCode/BlockSize * BlockSize) == (hashCode - hashCode) == 0</code>. <code>NumberOfBlocks</code> is not used at all here, which is weird;</p></li>\n<li><p>You should use <code>LinkedList</code> instead of rolling your own linked list (again, I'm assuming you're writing some exercise code, otherwise it's a must). Or at least you should define properties instead of exposing the values as public members;</p></li>\n<li><p>Don't throw <code>Exception</code>. Create your own custom exception with a proper name;</p></li>\n<li><p>Setting the entry variable in the if statement in <code>Add</code> is needless and just reduces readability.</p></li>\n<li><p>The while loop in <code>Add</code> is a bit weird. Why do you need to check <code>entry</code> and <code>entry.Next</code>? I think you meant <code>entry.Next</code> only.</p></li>\n<li><p>Setting entry at the end of the while look is needless and just reduces readability. I'd actually rename <code>entry</code> to <code>previous</code> for clarity.</p></li>\n</ol>\n\n<p>Did you write any unit tests for this? Make sure you do so.</p>\n\n<p>EDIT: typo: CRL => CLR</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T04:48:37.667", "Id": "7178", "ParentId": "7139", "Score": "4" } } ]
{ "AcceptedAnswerId": "7178", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T17:12:14.063", "Id": "7139", "Score": "2", "Tags": [ "c#" ], "Title": "Care to review my first hash map?" }
7139
<p>File manipulation code, I've noticed, has two salient properties:</p> <blockquote> <ol> <li>It's everywhere, and vitally important to functional software</li> <li>It has <em>lots</em> of exceptions.</li> </ol> </blockquote> <p>Please give me some pointers on how I can better improve the usability of this rough draft I wrote yesterday. It assumes some very basic things, and was scrapped together after browsing Google as I stumbled through the concepts.</p> <h1>makeproject.py</h1> <pre><code>'''create a simple setup folder for a new project </code></pre> <p>Follows the guide posted at:<br> <a href="http://guide.python-distribute.org/quickstart.html#lay-out-your-project" rel="nofollow">http://guide.python-distribute.org/quickstart.html#lay-out-your-project</a></p> <p>The structure built will match the following:</p> <pre><code>| ProjectName/ |---&gt; LICENSE.txt | README.txt | setup.py | projectname/ | ---&gt; __init__.py #For the sake of best practices, __init__.py is left empty. ''' #! usr/bin/env python import sys, os, errno class NewProject(object): '''interface for building a directory with a new project in it''' def __init__(self, projectname, directory): self.project = projectname self.base = check_path(directory) #project defaults: I don't want them here as class attributes! self.SETUP = { 'README.txt' : '''This is an unmodified README text file. It contains a list of changes to the program. It also contains help for dealing with the application. ''', 'LISCENSE.txt' : '''Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License ''' } def newproject(self): '''creates a file structure for a new project at `directory` ''' self.name = self.project.replace(' ', '') self.path = os.sep.join([self.base, self.name]) sub = self.name.lower() subpath = os.sep.join([self.path, sub]) check_build_path(subpath) for filename, content in self.SETUP.items(): self.buildfile(filename, content, directory=self.path) #setup takes arguments, it has its own method setup = self.buildsetup() self.buildfile('setup.py', setup) self.buildfile('__init__.py', directory=subpath) def buildfile(self, name, content="", directory = ""): '''opens and creates a new file at `directory` with `contents`''' #assumes bad directories have been purified if directory == "": loc = os.sep.join([self.path, name]) w = open(loc, 'w') else: directory = os.sep.join([directory, name]) w = open(directory, 'w') w.write(content) w.close() def buildsetup(self): return '''from distutils.core import setup setup( name='{0}', version='0.1dev', packages=['{1}',], license=open('LISCENSE.txt').read(), long_description=open('README.txt').read(), ) '''.format(self.project, self.name.lower()) def check_path(loc): '''recursively check if last character in `loc` is like os.sep character. If so, remove.''' if loc[-1] == os.sep: return check_path(loc[:-1]) return loc def check_build_path(loc): d = os.path.normpath(loc) if not os.path.exists(d): os.makedirs(d) else: try: os.rmdir(d) except OSError as ex: if ex.errno == errno.ENOTEMPTY: print "Directory specified must be new or empty" sys.exit(1) #if delete was successful, build the directory check_build_path(loc) if __name__ == '__main__': if len(sys.argv) != 3: print "Usage: string 'Project Name', string '/abs/path'" sys.exit(1) project = NewProject(sys.argv[1], sys.argv[2]) project.newproject() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T02:56:30.703", "Id": "11136", "Score": "0", "body": "What do you mean by \"operating system code\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T15:01:24.980", "Id": "11165", "Score": "0", "body": "Code that manages operating system resources: directories, files, permissions, etc. To me, it is one of the lines that separates toy scripts from actual work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T15:03:30.023", "Id": "11166", "Score": "0", "body": "Unusual definition, one that I don't understand. To me OS code is part of the OS. I don't know what a \"toy script\" is--if it does useful work, it's not a toy." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T15:17:02.060", "Id": "11168", "Score": "0", "body": "[Toy scripts](http://norvig.com/spell-correct.html) are for proof of concept or trying out a new branch of study. It doesn't mean it's useless, just not production quality." } ]
[ { "body": "<pre><code>'''create a simple setup folder for a new project\n</code></pre>\n\n<p>The recommendation is to always use \"\"\" not ''' for docstrings</p>\n\n<pre><code>Follows the guide posted at:\nhttp://guide.python-distribute.org/quickstart.html#lay-out-your-project\n\nThe structure built will match the following:\n\n| ProjectName/\n|---&gt; LICENSE.txt\n | README.txt\n | setup.py\n | projectname/\n | ---&gt; __init__.py\n\nFor the sake of best practices, __init__.py is left empty.\n\n'''\n\n#! usr/bin/env python\n\nimport sys, os, errno\n\nclass NewProject(object):\n '''interface for building a directory with a new project in it'''\n\n def __init__(self, projectname, directory):\n</code></pre>\n\n<p>The python style guide recommends underscores to separate words\n self.project = projectname</p>\n\n<p>I'd call it self.name not self.project. The name project doesn't convey much useful information.</p>\n\n<pre><code> self.base = check_path(directory)\n #project defaults: I don't want them here as class attributes!\n self.SETUP = {\n\n'README.txt' :\n'''This is an unmodified README text file.\nIt contains a list of changes to the program.\nIt also contains help for dealing with the application.\n''',\n\n'LISCENSE.txt' :\n'''Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License\n'''\n}\n</code></pre>\n\n<p>I wouldn't mix large docstrings into my python files. I think that makes it rather hard to read.</p>\n\n<pre><code> def newproject(self):\n '''creates a file structure for a new project at `directory`\n '''\n self.name = self.project.replace(' ', '')\n</code></pre>\n\n<p>I dislike adding object attirbutes not present in the constructor. It makes it harder to know what attributes an object will have</p>\n\n<pre><code> self.path = os.sep.join([self.base, self.name])\n</code></pre>\n\n<p>Use os.path.join for joining paths together. It'll handle a few corner cases that os.sep.join won't.</p>\n\n<pre><code> sub = self.name.lower()\n subpath = os.sep.join([self.path, sub])\n\n check_build_path(subpath)\n for filename, content in self.SETUP.items():\n self.buildfile(filename, content, directory=self.path)\n #setup takes arguments, it has its own method\n setup = self.buildsetup()\n self.buildfile('setup.py', setup)\n self.buildfile('__init__.py', directory=subpath)\n</code></pre>\n\n<p>I'd probably pass a blank content for <code>__init__.py</code> rather then having it be the default. I figure its rate that you want to have a file like that, so making it default doesn't make sense.</p>\n\n<pre><code> def buildfile(self, name, content=\"\", directory = \"\"):\n '''opens and creates a new file at `directory` with `contents`'''\n #assumes bad directories have been purified\n if directory == \"\":\n loc = os.sep.join([self.path, name])\n w = open(loc, 'w')\n else:\n directory = os.sep.join([directory, name])\n</code></pre>\n\n<p>That's not a directory if you've saved the file name over it.\n w = open(directory, 'w')</p>\n\n<p>If you use os.path.join, you won't need to handle these two cases separately.\n w.write(content)\n w.close()</p>\n\n<p>I recommend you use with statement to make sure the file closes correctly</p>\n\n<pre><code> def buildsetup(self):\n return '''from distutils.core import setup\n\nsetup(\n name='{0}',\n version='0.1dev',\n packages=['{1}',],\n license=open('LISCENSE.txt).read(),\n long_description=open('README.txt').read(),\n)\n'''.format(self.project, self.name.lower())\n</code></pre>\n\n<p>Again, I don't like putting huge docstrings in the middle of the code. I recommend having a template folder that you copy over to the target. Just do search/replace on filenames and contents for a few keywords like NAME or MODULE. </p>\n\n<pre><code>def check_path(loc):\n '''recursively check if last character in `loc` is like os.sep character.\n If so, remove.'''\n if loc[-1] == os.sep:\n return check_path(loc[:-1])\n return loc\n</code></pre>\n\n<p>This is the sorta thing that os.path.join will do for you. I'd also avoid recursion, because its pretty easy to make this a while loop. Also what happens when loc is \"/\"</p>\n\n<pre><code>def check_build_path(loc):\n d = os.path.normpath(loc)\n</code></pre>\n\n<p>I discourage single letter variable names whenever I can</p>\n\n<pre><code> if not os.path.exists(d):\n os.makedirs(d)\n else:\n try:\n os.rmdir(d)\n except OSError as ex:\n if ex.errno == errno.ENOTEMPTY:\n print \"Directory specified must be new or empty\"\n sys.exit(1)\n</code></pre>\n\n<p>You should reraise the exception if it was something else.</p>\n\n<pre><code> #if delete was successful, build the directory\n check_build_path(loc)\n</code></pre>\n\n<p>This function would be simpler if done like this:</p>\n\n<pre><code>try:\n os.rmdir(d)\nexcept OSError as error:\n if error == ERROR_CODE_FOR_NOT_EXIT:\n pass # OK\n else:\n print \"Failed to delete because: \", error\n sys.exit(1)\nos.makedirs(d)\n</code></pre>\n\n<p>I think that conveys the logic better</p>\n\n<pre><code>if __name__ == '__main__':\n if len(sys.argv) != 3:\n print \"Usage: string 'Project Name', string '/abs/path'\"\n sys.exit(1)\n project = NewProject(sys.argv[1], sys.argv[2])\n project.newproject()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T09:45:14.470", "Id": "11159", "Score": "0", "body": "There are 3-4 lines of code with formatting issues. Reading would be much better if fixed. I did myself but as formatting doesn't consume characters the fix didnt get accepted as the system requires 6 char changes. I didnt like/want to add text to others answer, but maybe you do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T16:59:49.010", "Id": "11185", "Score": "0", "body": "@joaquin, I'm not sure what issue you are concerned about. Feel free to add text if you want." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T06:59:18.263", "Id": "7148", "ParentId": "7142", "Score": "3" } } ]
{ "AcceptedAnswerId": "7148", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T19:30:27.710", "Id": "7142", "Score": "3", "Tags": [ "python", "exception-handling", "file-system", "makefile" ], "Title": "Tips for Python build scripts?" }
7142
<p>The goal is displaying the date and time of an article in a humanized and localized way:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Yesterday 13:21 </code></pre> </blockquote> <p>or if the Swedish language parameter is set it will display:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Igår 13:21 </code></pre> </blockquote> <p>And if the date wasn't yesterday or today, it will print the date and 24-hour time. I think I succeeded with everything except handling the timezone:</p> <pre class="lang-py prettyprint-override"><code>def datetimeformat_jinja(value, format='%H:%M / %d-%m-%Y', locale='en'): now= datetime.now() info = None if datetime.date(value) == datetime.date(now): info= _('Today') elif (now - value).days &lt; 2: info= _('Yesterday') else: month = value.month if month == 1: info = str(value.day)+' '+_('Jan') elif month == 2: info = str(value.day)+' '+_('Feb') elif month == 3: info = str(value.day)+' '+_('Mar') elif month == 4: info = str(value.day)+' '+_('April') elif month == 5: info = str(value.day)+' '+_('May') elif month == 6: info = str(value.day)+' '+_('June') elif month == 7: info = str(value.day)+' '+_('July') elif month == 8: info = str(value.day)+' '+_('Aug') elif month == 9: info = str(value.day)+' '+_('Sep') elif month == 10: info = str(value.day)+' '+_('Oct') elif month == 11: info = str(value.day)+' '+_('Nov') else: info = str(value.day)+' '+_('Dec') return info+'&lt;br&gt;'+format_time(value, 'H:mm', locale=locale) </code></pre> <p>The above code localizes and humanizes the output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Today 3:29 </code></pre> </blockquote> <p>I can also switch languages to, for example, Portuguese:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Hoje 3:29 </code></pre> </blockquote> <p>Where "Hoje" means "today," so the filter appears to work. </p> <p>Could you please review it or give me a hint on how I can admit my code to also allow time zones? I use babel for localization and Jinja2 for rendering. </p>
[]
[ { "body": "<pre><code>def datetimeformat_jinja(value, format='%H:%M / %d-%m-%Y', locale='en'):\n now= datetime.now()\n</code></pre>\n\n<p>Put a space after now and before =</p>\n\n<pre><code> info = None\n</code></pre>\n\n<p>Info will always be assigned something later, there is no reason to assign here.</p>\n\n<pre><code> if datetime.date(value) == datetime.date(now):\n</code></pre>\n\n<p>Compare with datetime.date.today(), that'll be a bit clearer.</p>\n\n<pre><code> info= _('Today')\n elif (now - value).days &lt; 2:\n</code></pre>\n\n<p>I'd also use today here.</p>\n\n<pre><code> info= _('Yesterday')\n else:\n month = value.month\n if month == 1:\n info = str(value.day)+' '+_('Jan')\n elif month == 2:\n info = str(value.day)+' '+_('Feb')\n elif month == 3:\n info = str(value.day)+' '+_('Mar')\n elif month == 4:\n info = str(value.day)+' '+_('April')\n elif month == 5:\n info = str(value.day)+' '+_('May')\n elif month == 6:\n info = str(value.day)+' '+_('June')\n elif month == 7:\n info = str(value.day)+' '+_('July')\n elif month == 8:\n info = str(value.day)+' '+_('Aug')\n elif month == 9:\n info = str(value.day)+' '+_('Sep')\n elif month == 10:\n info = str(value.day)+' '+_('Oct')\n elif month == 11:\n info = str(value.day)+' '+_('Nov')\n else:\n info = str(value.day)+' '+_('Dec')\n</code></pre>\n\n<p>Firstly, no reason to duplicate the code that much. You should have at least put the months in a list and taken advantage of that. But you can get the month name by value.strftime(\"%b\"). </p>\n\n<p>Python itself really doesn't have support for time zones. You need a third party library for that. pytz is often used for this purpose.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T07:15:18.143", "Id": "7149", "ParentId": "7147", "Score": "2" } }, { "body": "<h2>Adding time zone support</h2>\n\n<p>Add a new argument to your function: <code>now</code>. This should be the localized datetime of the client. Compare <code>now</code> to the current server datetime and adjust the formatted time by the difference between them. Boom, timezone support added.</p>\n\n<p>That said <strong><em>you cannot get the client timezone server-side</em></strong>. Look into client-side solutions with JavaScript (either full client-side date formatting, or phoning home). <a href=\"https://stackoverflow.com/q/2542206/998283\">This should start you off on the right track.</a></p>\n\n<p>On with the code review.</p>\n\n<h2>Tidying up the code</h2>\n\n<h3>Variable and function naming</h3>\n\n<ul>\n<li><code>info</code> and <code>value</code> are excessively vague. </li>\n<li><code>datetimeformat_jinja()</code> is a bit eccentric as a function name, as its not in imperative form (eg <code>format_datetime</code>).</li>\n</ul>\n\n<h3>String formatting</h3>\n\n<p>Concatenating strings with addition is considered bad practice is Python. You should format individual elements of your message together, rather than starting with <code>info=''</code> and adding new parts as you go along. Use <a href=\"http://docs.python.org/library/string.html#string-formatting\" rel=\"nofollow noreferrer\"><code>str.format()</code></a> (or <code>%s</code>-formatting with Python 2.5 and below) to achieve this.</p>\n\n<h3>The <code>If</code>-<code>elif</code>-<code>else</code> chain</h3>\n\n<p>In lines 9 through 33 you copy-pasted the same logic twelve times over; that's a sure-fire sign you need to express things more generically.</p>\n\n<h3>Style</h3>\n\n<p>Take this suggestion for the petty nothing it is, but—please, please, please—unless you're following the style guidelines of your team or employer, read and obey <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</p>\n\n<h2>Result</h2>\n\n<pre><code>MONTHS = ('Jan', 'Feb', 'Mar', 'April', 'May', 'June',\n 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')\nFORMAT = '%H:%M / %d-%m-%Y'\n\ndef format_datetime(to_format, format=FORMAT, locale='en'):\n now = datetime.now()\n if datetime.date(to_format) == datetime.date(now):\n date_str = _('Today')\n elif (now - to_format).days &lt; 2:\n date_str = _('Yesterday')\n else:\n month = MONTHS[to_format.month - 1]\n date_str = '{0} {1}'.format(to_format.day, _(month))\n time_str = format_time(to_format, 'H:mm', locale=locale)\n return \"{0}&lt;br&gt;{1}\".format(date_str, time_str)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T07:33:11.817", "Id": "7150", "ParentId": "7147", "Score": "4" } } ]
{ "AcceptedAnswerId": "7150", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-25T03:41:20.930", "Id": "7147", "Score": "4", "Tags": [ "python", "datetime", "i18n" ], "Title": "Date and time of an article in a humanized and localized way" }
7147
<pre><code>var newObject = keyValuePair.Key; var originalObject = keyValuePair.Value; List&lt;ChargeBITValue&gt; bitValues = new List&lt;ChargeBITValue&gt;(); foreach (var item in originalObject.ChargeBITValues) { ChargeBITValue bitValue = new ChargeBITValue() { ChargeTypeEnumID = item.ChargeTypeEnumID, DataValue = item.DataValue, ClientTripTypeContractChargeValueList = newObject }; bitValues.Add(bitValue); } </code></pre> <p>I have similar loops for rest of the values, bitValues, moneyValues, Rupees Values, how can I remove the duplication from my code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T07:19:31.480", "Id": "11154", "Score": "0", "body": "Please include the type of the `KeyValuePair<TKey,TValue>`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T09:19:32.090", "Id": "11155", "Score": "1", "body": "Not only that but for _all_ the types involved." } ]
[ { "body": "<p>First, if you don't have it already, you need to define a common <strong>Interface</strong> that is implemented by <code>ChargeBITValue</code>, <code>ChargeMoneyValue</code>, <code>ChargeRupeeValue</code> etc (you need to adapt the interface using the actual types of your properties instead of <code>int</code>, <code>List&lt;string&gt;</code> and <code>IEnumerable&lt;IChargeValue&gt;</code>). Let' call it <code>IChargeValue</code>:</p>\n\n<pre><code>interface IChargeValue\n{\n int ChargeTypeEnumID { get; set; }\n int DataValue { get; set; }\n List&lt;string&gt; ClientTripTypeContractChargeValueList { get; set; }\n IEnumerable&lt;IChargeValue&gt; ChargeValues { get; }\n}\n</code></pre>\n\n<p>Then, you change your method to use <a href=\"http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx\" rel=\"nofollow\">generics</a> and type constraints:</p>\n\n<pre><code>private void YourMethod&lt;T&gt;() where T : IChargeValue, new()\n{\n // KeyValuePair&lt;YourTKey, YourTValue&gt; keyValuePair = new ...\n var newObject = keyValuePair.Key;\n var originalObject = keyValuePair.Value;\n List&lt;T&gt; values = new List&lt;T&gt;();\n foreach (var item in originalObject.ChargeValues)\n {\n T value = new T()\n {\n ChargeTypeEnumID = item.ChargeTypeEnumID,\n DataValue = item.DataValue,\n ClientTripTypeContractChargeValueList = newObject\n };\n values.Add(value);\n }\n}\n</code></pre>\n\n<p>If you want to, you can use LINQ instead of the foreach statement: </p>\n\n<pre><code>var values =\n from item in originalObject.ChargeValues\n select new T\n {\n ChargeTypeEnumID = item.ChargeTypeEnumID,\n DataValue = item.DataValue,\n ClientTripTypeContractChargeValueList = newObject\n };\nList&lt;T&gt; valuesAsList = values.ToList();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T09:21:32.357", "Id": "11156", "Score": "1", "body": "Though the LINQ code would need a final `ToList()` call to make it complete." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T09:22:47.927", "Id": "11157", "Score": "0", "body": "@Jeff that depends on whether he really needs to have the values in a List. Possibly an IEnumerable<T> will do, but thanks for pointing out the discrepancy between my answer and his example code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T09:25:37.100", "Id": "11158", "Score": "0", "body": "I've edited my answer to include your correction - it serves to remind us of deferred execution as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T12:21:18.127", "Id": "11263", "Score": "0", "body": "@Manvinder has this answer helped you? Is it unsatisfactory?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T07:33:47.723", "Id": "7155", "ParentId": "7154", "Score": "6" } }, { "body": "<p>Not a complete answer - but building on codesparkle's code, how about something like this lambda expression instead of LINQ/<code>foreach</code> statements (looks less verbose):</p>\n\n<pre><code>var bitValues = originalObject.ChargeBITValues.Select(item =&gt; new T\n {\n ChargeTypeEnumID = item.ChargeTypeEnumID,\n DataValue = item.DataValue,\n ClientTripTypeContractChargeValueList = newObject\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-30T13:32:03.610", "Id": "11438", "Score": "0", "body": "you'll need to decide between using `a` or `item` as a parameter for the lambda." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T10:01:35.173", "Id": "7258", "ParentId": "7154", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T06:23:50.933", "Id": "7154", "Score": "6", "Tags": [ "c#" ], "Title": "Minimize code in c#" }
7154
<p>I have the following:</p> <pre><code>public interface IBehaviour { event EventHandler Completed; void Execute(); } public interface IBehaviourA : IBehaviour { // Some specific stuff here object A { get; set; } } public interface IBehaviourB : IBehaviour { // Some specific stuff here object B {get;set;} } public interface IBehaviourQueue { void Run(); BehaviourQueueItem&lt;IBehaviour&gt; AddBehaviour&lt;T&gt;() where T : IBehaviour; } public class BehaviourQueue : Queue&lt;BehaviourQueueItem&lt;IBehaviour&gt;&gt;, IBehaviourQueue { private IBehaviourFactory factory; public BehaviourQueue(IBehaviourFactory factory) { this.factory = factory; } public BehaviourQueueItem&lt;IBehaviour&gt; AddBehaviour&lt;T&gt;() where T:IBehaviour { T behaviour = factory.GetNew&lt;T&gt;(); var queueItem = new BehaviourQueueItem&lt;IBehaviour&gt;(behaviour); Enqueue(queueItem); return queueItem; } public void Run() { //Run each queue item } } public class BehaviourQueueItem&lt;T&gt; { public IBehaviour behaviour; public BehaviourQueueItem(IBehaviour behaviour) { this.behaviour = behaviour; } public void WhenComplete(Func&lt;T, bool&gt; action) { CompletedAction = action; } public BehaviourQueueItem&lt;T&gt; ConfigureFor&lt;Z&gt;(Action&lt;Z&gt; dow) where Z : IBehaviour { dow((Z)behaviour); return this; } } </code></pre> <p>This is how it is used:</p> <pre><code>var q =new BehaviourQueue(new BehaviourFactory()); // Queue here is IBehaviour q.AddBehaviour&lt;IBehaviourA&gt;() .ConfigureFor&lt;IBehaviourA&gt;(x =&gt; x.A = "someValueA") .WhenComplete(x =&gt; DoStuffWithSomeProperty(((IBehaviourA)x).A)); q.AddBehaviour&lt;IBehaviourB &gt;() .ConfigureFor&lt;IBehaviourB &gt;(x =&gt; x.B = "someValueB") .WhenComplete(x =&gt; DoStuffWithSomeProperty(((IBehaviourB)x).B)); </code></pre> <p>What I don't really like is that I have to specify which type of <code>IBehaviour</code> I am referring to every time. I would like to be able to write:</p> <pre><code>var q =new BehaviourQueue(new BehaviourFactory()); // Queue here is IBehaviour q.AddBehaviour&lt;IBehaviourA&gt;() .Configure(x =&gt; x.A = "someValueA") .WhenComplete(x =&gt; DoStuffWithSomeProperty(x.A)); q.AddBehaviour&lt;IBehaviourB&gt;() .Configure(x =&gt; x.B = "someValueB") .WhenComplete(x =&gt; DoStuffWithSomeProperty(x.B)); </code></pre> <p>I know that I have to modify this part:</p> <pre><code>public BehaviourQueueItem&lt;IBehaviour&gt; AddBehaviour&lt;T&gt;() where T:IBehaviour { T behaviour = factory.GetNew&lt;T&gt;(); var queueItem = new BehaviourQueueItem&lt;IBehaviour&gt;(behaviour); Enqueue(queueItem); return queueItem; } </code></pre> <p>to something like</p> <pre><code>public BehaviourQueueItem&lt;T&gt; AddBehaviour&lt;T&gt;() where T:IBehaviour { T behaviour = factory.GetNew&lt;T&gt;(); var queueItem = new BehaviourQueueItem&lt;T&gt;(behaviour); Enqueue(queueItem); // It won't let me know do it because of Covariance/Contravariance thingy return queueItem; } </code></pre> <p>Do you have any idea what I should write to be able to create a base typed list and add specific items and configuring it fluently?</p> <p>Keep in mind that I should be able to add any type of <code>IBehaviour</code> to <code>BehaviourQueue</code> so the queue can't be a derived type.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T11:13:23.777", "Id": "11256", "Score": "0", "body": "You will perhaps be interested in how other projects try to handle that, I found that one: http://flit.codeplex.com/" } ]
[ { "body": "<p>If I understand it right, you would want IBehaviourA associated with property A, and IBehaviourB with property B.</p>\n\n<p>If the above is right, could you try something like:</p>\n\n<pre><code>BehaviourQueueItem&lt;T&gt; AddBehaviour() where T : IBehaviour;\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>BehaviourQueueItem&lt;IBehaviour&gt; AddBehaviour&lt;T&gt;() where T : IBehaviour;\n</code></pre>\n\n<p>By this we can determine the object type at BehaviourQueueItem class level itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-01T13:39:05.270", "Id": "11515", "Score": "0", "body": "If I do this, I cannot choose what type of IBehaviour I want to add and that would force me to make the type of queue to IBehaviourA Or B." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T10:14:50.143", "Id": "7260", "ParentId": "7159", "Score": "1" } }, { "body": "<p>One possible workaround would be to declare the <code>BehaviourQueue</code> class as being <code>Queue&lt;object&gt;</code> instead of <code>Queue&lt;BehaviourQueueItem&lt;IBehaviour&gt;&gt;</code>.</p>\n\n<p>This will allow you to define the <code>AddBehaviour&lt;T&gt;()</code> method the way you want:</p>\n\n<pre><code>public BehaviourQueueItem&lt;T&gt; AddBehaviour&lt;T&gt;() where T : IBehaviour\n{\n T behaviour = factory.GetNew&lt;T&gt;();\n var queueItem = new BehaviourQueueItem&lt;T&gt;(behaviour);\n Enqueue(queueItem); // no problem here now...\n return queueItem;\n}\n</code></pre>\n\n<p>Furthermore, you'll be able to change the <code>ConfigureFor</code> method to:</p>\n\n<pre><code>public BehaviourQueueItem&lt;T&gt; Configure(Action&lt;T&gt; dow)\n{\n dow((T)behaviour);\n return this;\n}\n</code></pre>\n\n<p>and now the configuration looks like this:</p>\n\n<pre><code>q.AddBehaviour&lt;IBehaviourA&gt;()\n .Configure(x =&gt; x.A = \"someValueA\")\n .WhenComplete(x =&gt; DoStuffWithSomeProperty(x.A));\n\nq.AddBehaviour&lt;IBehaviourB&gt;()\n .Configure(x =&gt; x.B = \"someValueB\")\n .WhenComplete(x =&gt; DoStuffWithSomeProperty(x.B));\n</code></pre>\n\n<p>The only problem that remains is the dirty <code>Queue&lt;object&gt;</code> thing, meaning that the <code>Dequeue</code>d objects will need to be cast back to <code>BehaviourQueueItem&lt;IBehaviour&gt;</code>.</p>\n\n<p>It's up to you to decide whether that's an acceptable compromise.</p>\n\n<p>However, looking at the code I see that the actual Queue implementation is not meant to be used by the class's clients. Clients don't call <code>Enqueue</code> directly, but <code>AddBehaviour</code> (which uses <code>Enqueue</code> internally). Similarly, I could male the assumption that <code>Dequeue</code> is only called by the <code>Run()</code> method, when it processes the items. If this is the case, the <code>BehaviourQueue</code> class may not even expose the <code>Queue</code> interface; it could instead just have a <code>Queue&lt;object&gt;</code> field that does the queue job and only expose the <code>AddBehaviour</code> and <code>Run</code> public methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T21:10:34.903", "Id": "13542", "Score": "0", "body": "After applying the changes I had problem casting IBehaviourQueueItem<IBehaviour> back to IBehaviourQueueItem<IBehaviourA>. Making T covariant on IBehaviourQueueItem interface made it work.\n\npublic interface IBehaviourQueueItem<out T>" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-28T21:32:44.120", "Id": "8402", "ParentId": "7159", "Score": "1" } } ]
{ "AcceptedAnswerId": "8402", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T14:02:32.860", "Id": "7159", "Score": "7", "Tags": [ "c#" ], "Title": "Creating simpler fluent interface" }
7159
<p>I'm extremely new to Java, and I had a bit of an attempt at making something that you could call lotto. I've still got a lot more to go on it, but things are becoming tedious, and I am sure there is a simpler way to do what I am doing. How can this code be changed to have less repetitive code/optimized?</p> <pre><code>import java.util.Random; import java.util.Scanner; public class Lotto { //Pick 6 numbers from 1 to 100 //If all of your numbers gets called out, you win public static void wait (int n) { long t0,t1; t0=System.currentTimeMillis(); do{ t1=System.currentTimeMillis(); } while (t1-t0&lt;1000); } public static void main(String[] args) { Random rand = new Random(); Scanner numScan1 = new Scanner(System.in); Scanner numScan2 = new Scanner(System.in); Scanner numScan3 = new Scanner(System.in); Scanner numScan4 = new Scanner(System.in); Scanner numScan5 = new Scanner(System.in); Scanner numScan6 = new Scanner(System.in); boolean num1Cor = false; boolean num2Cor = false; boolean num3Cor = false; boolean num4Cor = false; boolean num5Cor = false; boolean num6Cor = false; System.out.print("Pick 6 numbers from 0 to 25. Pick your first number: "); int num1 = numScan1.nextInt(); System.out.println(); System.out.print("Pick your second number: "); int num2 = numScan2.nextInt(); System.out.println(); System.out.print("Pick your third number: "); int num3 = numScan3.nextInt(); System.out.println(); System.out.print("Pick your fourth number: "); int num4 = numScan4.nextInt(); System.out.println(); System.out.print("Pick your fifth number: "); int num5 = numScan5.nextInt(); System.out.println(); System.out.print("Pick your final number: "); int num6 = numScan6.nextInt(); System.out.println("Numbers will now start to be drawn, if all of your numbers are called, you win."); while (true) { int random = rand.nextInt(25); System.out.println("Number " + random + "."); if (random == num1) { num1Cor = true; System.out.println("Your number, " + num1 + ", has been called."); } else if (random == num2) { num2Cor = true; System.out.println("Your number, " + num2 + ", has been called."); } else if (random == num3) { num3Cor = true; System.out.println("Your number, " + num3 + ", has been called."); } else if (random == num4) { num4Cor = true; System.out.println("Your number, " + num4 + ", has been called."); } else if (random == num5) { num5Cor = true; System.out.println("Your number, " + num5 + ", has been called."); } else if (random == num6) { num6Cor = true; System.out.println("Your number, " + num6 + ", has been called."); } if (num1Cor == true &amp;&amp; num2Cor == true &amp;&amp; num3Cor == true &amp;&amp; num4Cor == true &amp;&amp; num5Cor == true &amp;&amp; num6Cor == true) { System.out.println("You win!!"); break; } wait(100); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:45:15.243", "Id": "11161", "Score": "3", "body": "You could do it using only one `Scanner`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:51:32.980", "Id": "11162", "Score": "1", "body": "I am not able to figure out what u do with the parameter in the wait method" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:45:47.257", "Id": "64500", "Score": "0", "body": "You can make your `numScan` and `numCor` into arrays and use a `for` loop to access them." } ]
[ { "body": "<p>What not to do:</p>\n\n<p>Using single numbered variables that have the same function... This works but it becomes tedious as the program gets larger and more complex.</p>\n\n<p>What to do:</p>\n\n<p>-> Favor the use of \"arrays\" instead.</p>\n\n<p>Arrays are explained here for use in Java:\n<a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T11:19:17.967", "Id": "11201", "Score": "0", "body": "-1: Read up on [answer]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T22:23:30.863", "Id": "11238", "Score": "0", "body": "@codesparkle *update* Thanks for learning things to new users :) I edited now the answer in favor of the community and the asker.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T22:26:04.430", "Id": "11239", "Score": "0", "body": "I removed my downvote." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:48:19.247", "Id": "7162", "ParentId": "7160", "Score": "2" } }, { "body": "<p>I'm no java expert but you could start unitizing things. Your code needs to be less repetitive.</p>\n\n<p>Like this, write functions for what you need to keep doing.</p>\n\n<pre><code>int AcceptInt()\n{\n Scanner numSc = new Scanner(System.in);\n return numSc.NextInt();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Untested code</strong>, I don't even have Java on my PC. But it should give you some direction. Hope I haven't made any silly typos, I used notepad.</p>\n\n<pre><code>public class Lotto {\n\n //Pick 6 numbers from 1 to 100\n //If all of your numbers gets called out, you win\n\n public static void wait (int n) throws InterruptedException \n {\n Thread.sleep(n*1000);//*1000 for seconds?\n }\n\n static int[] nums = new int[6];\n static boolean[] states = new boolean[6];\n\n public static void main(String[] args) {\n Random rand = new Random();\n //set all to false.\n //dunno if java defaults boolean to false.\n int i = 0;\n while(i++&lt;6) { states[i] = false; }\n\n System.out.print(\"Pick 6 numbers from 0 to 25.\");\n for(int k=0; k&lt;6; k++) {\n System.out.print(\"Gimme number :\"+ k); \n nums[k] = AcceptInt();//check for validity?\n System.out.println();\n }\n System.out.println(\"Numbers will now start to be drawn, if all of your numbers are called, you win.\");\n\n while (true) {//Shouldn't this be finite?\n int random = rand.nextInt(25);\n System.out.println(\"Number \" + random + \".\");\n\n for(int l= 0;l&lt;6; l++) {\n if (random == nums[l]) {\n states[l] = true;\n System.out.println(\"Your number, \" + nums[l]+ \", has been called.\");\n }\n }\n\n for(int j= 0;j&lt;6; j++)\n {\n if(states[j] == false)\n {\n break;\n }\n System.out.println(\"You win!!\");\n //maybe set another flag here and break out of your \n //while infinite loop.\n }\n wait(100);//assuming seconds?\n }\n }\n static int AcceptInt()\n {\n Scanner numSc = new Scanner(System.in);\n return numSc.NextInt();\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T11:09:11.350", "Id": "11200", "Score": "1", "body": "-1, full of errors. Where have you defined the `i` for your first `while` loop? Why are you setting `k=0` without ever incrementing it in your first `for` loop, and again using your *non-existant* `i`? `rand` doesn't exist, either - did you mean to call `GetNextRand()` instead? `nums`, `states` and `AcceptInt()` **have to be** `static`. Why are you creating a new `Scanner` for every `int`? Why are you creating a new `Random` for every call to `GetNextRand()`? `Random` uses `System.nanoTime()` as a starting seed, so it will return nearly the same values if you create a new instance every time!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T05:16:45.970", "Id": "11248", "Score": "0", "body": "sorry!! Fixed! Though, this was on stackoverflow when I answered it and I wanted to just give a simple idea about what he should do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T08:19:50.440", "Id": "11251", "Score": "0", "body": "there are still two problems: because `Thread.Sleep` can throw a *checked* `InterruptedException` your code will not compile without adding a `try-catch` block or declaring `public static void wait(int n) throws InterruptedException { /*...*/ }`. And, if you define `int i` on the second line of code in `main`, you cannot re-define it in the first `for` loop inside your `while(true)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T08:56:11.027", "Id": "11252", "Score": "0", "body": "@codesparkle thanks. =S Guess I really need to brush on java, haven't done it in years. Fixed again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T09:00:09.967", "Id": "11253", "Score": "0", "body": "I removed my downvote, but note that `random.nextInt(n)` will **never** return `n`, but always something between `[0|n-1]`. You therefore need to do `random.nextInt(26)`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:49:07.037", "Id": "7163", "ParentId": "7160", "Score": "1" } }, { "body": "<p>First, you need just one <code>Scanner</code>.</p>\n\n<p>Second, you could store the number choose by the user in an array.</p>\n\n<p>Third, you could iterate the array to find the number there, instead of doing a lot of <code>if</code> and <code>else if</code>.</p>\n\n<p>Forth, the user always wins. This looks like a bug. The while(true) ensures that the numbers are choosen in a way that eventually all the choosen numbers will be drawn. More, nothing stops the user from choosing a number more than once.</p>\n\n<p>Fifth, <strike>the <code>wait(100)</code> will fail.</strike> You should use <code>Thread.sleep(100)</code> instead. EDIT, oops, I thought you were using <code>Object.wait</code>. It currently works, but <code>Thread.sleep</code> is better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T16:06:34.943", "Id": "11214", "Score": "2", "body": "I think most would agree with the last point, but you should **nevertheless** provide a reason _why_ his approach is worse than `Thread.sleep`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T21:31:51.770", "Id": "16173", "Score": "1", "body": "@codesparkle I think you have the wrong approach. If the system already provides something, you shouldn't roll your own unless the provided one isn't sufficient for some reason. That said, `Thread.sleep` is better because it sleeps the thread for at least the specified amount of time, rather than actively spinning in a tight loop for that amount of time; that's going to waste CPU time. (Further, the wait() method as implemented ignores its parameter.)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:51:03.280", "Id": "7164", "ParentId": "7160", "Score": "8" } }, { "body": "<p>I have modified the code, executed and played too. Good game :)</p>\n\n<p>I have used <code>ArrayList</code> because it has enough built-in methods to handle this scenario easily.</p>\n\n<p><strong>You should also validate if user is entering a number outside of 0 and 25. That's very important.</strong> This will force user to enter the nth number only between 0 to 25 otherwise it will not go for next number.</p>\n\n<pre><code>public static void main(String[] args) throws InterruptedException {\n Random rand = new Random();\n Scanner scan = new Scanner(System.in);\n System.out.print(\"Enter 6 numbers from 0 to 25 separating.\\n\");\n List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();\n for (int i = 0; i &lt; 6; i++) {\n boolean flag = false;\n do {\n System.out.println(\"Enter \" + (i+1) + \"th number :\");\n int num = scan.nextInt();\n if (num &gt; -1 &amp;&amp; num &lt; 26) {\n list.add(new Integer(num));\n flag = false;\n } else {\n System.out.println(\"not valid number.\");\n flag = true;\n }\n } while(flag);\n }\n System.out.println(\"Numbers will now start to be drawn, you win if all of your numbers are called.\");\n for (int i = 0; i &lt; 6; i++) {\n Integer random = new Integer(rand.nextInt(25));\n if (list.contains(random)) {\n System.out.println(\"Your number, \" + random +\", has been called.\");\n list.remove(random);\n }\n Thread.sleep(1000);\n }\n if (list.size() == 0) {\n System.out.println(\"You won...\");\n } else {\n System.out.println(\"You didn't win...\");\n }\n}\n</code></pre>\n\n<p><strong>OUTPUT:</strong></p>\n\n<pre><code>Enter 6 numbers from 0 to 25 separating.\nEnter 1th number :\n12\nEnter 2th number :\n34\nnot valid number.\nEnter 2th number :\n54\nnot valid number.\nEnter 2th number :\n15\nEnter 3th number :\n-23\nnot valid number.\nEnter 3th number :\n4\nEnter 4th number :\n5\nEnter 5th number :\n-100\nnot valid number.\nEnter 5th number :\n34\nnot valid number.\nEnter 5th number :\n10\nEnter 6th number :\n9\nNumbers will now start to be drawn, you win if all of your numbers are called.\nYour number, 9, has been called.\nYour number, 4, has been called.\nYou didn't win...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T06:59:26.467", "Id": "11163", "Score": "0", "body": "I also made an improvment of it. See above ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T02:35:05.167", "Id": "11195", "Score": "2", "body": "There are a few issues here, aside from having one giant `main` method--biggest is that `nextInt(25)` will never return `25` ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T06:37:59.060", "Id": "7165", "ParentId": "7160", "Score": "1" } }, { "body": "<p>What I'd made and make sense for me, hope it'll help you:<br>\nYou named it Lotto, and unless the rules changed, we can't replay when we've lost, so the loop <code>while(true)</code> is useless in your code ;)</p>\n\n<pre><code>public class Lotto {\n\n private static final int INPUT_SIZE = 6;\n\n private static final int MIN_NUMBER_POSSIBLE = 0;\n\n private static final int MAX_NUMBER_POSSIBLE = 25;\n\n private Set&lt;Integer&gt; userNumbers = new HashSet&lt;Integer&gt;();\n\n private Set&lt;Integer&gt; randomNumbers = new HashSet&lt;Integer&gt;();\n\n public static void main(String[] args) {\n Lotto c = new Lotto();\n c.generateRandomNumbers();\n System.out.println(\"Pick \" + INPUT_SIZE + \" numbers from \" + MIN_NUMBER_POSSIBLE + \" to \" + MAX_NUMBER_POSSIBLE + \".\");\n c.readUserNumbers();\n if (c.doUserNumbersMatchRandomNumbers()) {\n System.out.println(\"You win :) !\");\n } else {\n System.out.println(\"Sorry you failed :( !\");\n c.showRandomNumbersToUser();\n }\n }\n\n private void generateRandomNumbers() {\n Random random = new Random();\n for (int i = 0; i &lt; INPUT_SIZE; i++) {\n randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));\n }\n }\n\n private void showRandomNumbersToUser() {\n System.out.println(\"\\nRandom numbers where : \");\n for (Integer randomNumber : randomNumbers) {\n System.out.println(randomNumber + \"\\t\");\n }\n }\n\n private void readUserNumbers() {\n Scanner input = new Scanner(System.in);\n int inputSize = 1;\n while (input.hasNextInt() &amp;&amp; inputSize &lt; INPUT_SIZE) {\n int numberChoosen = input.nextInt();\n if (numberChoosen &lt; MIN_NUMBER_POSSIBLE || numberChoosen &gt; MAX_NUMBER_POSSIBLE) {\n System.out.println(\"Your number must be in \" + MIN_NUMBER_POSSIBLE + \" - \" + MAX_NUMBER_POSSIBLE + \" range.\");\n } else {\n userNumbers.add(numberChoosen);\n inputSize++;\n }\n }\n }\n\n private boolean doUserNumbersMatchRandomNumbers() {\n for (Integer userNumber : userNumbers) {\n if (!randomNumbers.contains(userNumber)) {\n return false;\n }\n printMatchingNumber(userNumber);\n }\n return true;\n }\n\n private void printMatchingNumber(int num) {\n System.out.println(\"Your number, \" + num + \", has been called.\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T07:10:04.233", "Id": "11164", "Score": "0", "body": "Advantage : can enter 6 numbers directly without one by one. No need status variables, (works with contains() method of Collection) and validation of inputs in the beginning. And of course, no duplicates, the horror for a developer :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T23:53:15.790", "Id": "11192", "Score": "0", "body": "+1 for the pleasant short functions, meaningful names and effort. Two suggestions: you can move the `HashSet` initializing code out of the constructor: `private Set<Integer> userNumbers = new HashSet<Integer>();` - then you can delete the empty constructor. Next, in the `sysout` calls, don't use the magic numbers 0 and 25 - use your named constants instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T05:41:28.970", "Id": "11196", "Score": "1", "body": "You're right. I've just made changes. And I place a StringBuilder for two sysout instead of repetitive concatenations for avoiding reinstanciating new String Class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T15:24:57.817", "Id": "11209", "Score": "0", "body": "Wouldn't the compiler generate the equivalent StringBuilder implementation from the original string concatenation code? (http://java.sun.com/developer/technicalArticles/Interviews/community/kabutz_qa.html)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T15:35:28.563", "Id": "11210", "Score": "2", "body": "In fact, since all of the pieces of the string are either literal strings or constant integers, the compiler can/will construct the final string at compile time, so the original code just using string concatenation with `+` would be better. (http://www.znetdevelopment.com/blogs/2009/04/06/java-string-concatenation/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T16:05:11.713", "Id": "11213", "Score": "0", "body": "I wholeheartedly agree with @Dr.Wily'sApprentice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-27T16:16:04.677", "Id": "11215", "Score": "0", "body": "@Dr.Wily'sApprentice, very good advice, corrected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T09:12:14.207", "Id": "11254", "Score": "0", "body": "@Mik378 beware-at the moment your algorithm will never choose the `MAX_NUMBER_POSSIBLE` - and I think that you should also change it to work with any `MIN_NUMBER_POSSIBLE`, so you need to do `MIN_NUMBER_POSSIBLE + random.nextInt(MAX_NUMBER_POSSIBLE - MIN_NUMBER_POSSIBLE + 1)` to get a correct random number." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T06:43:39.690", "Id": "7166", "ParentId": "7160", "Score": "7" } }, { "body": "<p>One small thing I noticed is the call to <code>rand.nextInt(25)</code>. The player is told to select a number between <code>1</code> and <code>25</code>, but <code>rand.nextInt(25)</code> will only generate <code>0 - 24</code>. Change it to one of the following:</p>\n\n<ul>\n<li><code>rand.nextInt(25) + 1</code></li>\n<li><code>rand.nextInt(26)</code> (if you want to include the <code>0</code> =))</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-13T06:29:27.993", "Id": "7740", "ParentId": "7160", "Score": "5" } }, { "body": "<p>@Victor has pointed out that you keep generating random numbers until the user wins.</p>\n\n<p>@wayne has pointed out that you generate random numbers between 0 and 24 (inclusive), while asking the user to enter numbers between 0 and 25. While inclusive-exclusive ranges such as [0, 25) are handy for programmers, humans will perceive it as an inconsistency.</p>\n\n<p>Besides those bugs, your number generator is an unfaithful implementation of the Lotto ball-picking process. Lotto balls are drawn from the cage <em>without replacement</em> — once a number has been picked, it will not be picked again. Your code just keeps generating random integers under 25.</p>\n\n<p>One way to produce six different numbers is to check each generated number against the list of previously generated numbers. Another method is to start with an array of all 24 (or 25) numbers, <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow\">shuffle</a> the array, and take the first six elements after shuffling.</p>\n\n<hr>\n\n<p>To check for a win:</p>\n\n<pre><code>int[] userPicks = …;\nint[] drawnNumbers = …;\nArrays.sort(userPicks);\nArrays.sort(drawnNumbers);\nboolean isWinner = Arrays.equals(userPicks, drawnNumbers);\n</code></pre>\n\n<p>The probability of winning Lotto 6/24 is 1 in 134596. If you play 10 simulations per second, then the expected time until winning should be around 3.8 hours.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T01:42:01.350", "Id": "45456", "ParentId": "7160", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-26T05:42:17.600", "Id": "7160", "Score": "4", "Tags": [ "java", "beginner", "random" ], "Title": "Reduce repetitive code in Lotto simulator" }
7160