body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am trying to write something that will copy the current <code>&lt;input&gt;</code>s value and enter it into any <code>&lt;input&gt;</code> that start with the same name.</p> <p><code>&lt;input&gt;</code> names will follow this pattern: <code>price-0</code>, <code>price-1</code>, <code>price-2</code>, <code>upc-0</code>, <code>upc-1</code>, <code>upc-2</code>.</p> <p>So if a user enters a value in <code>&lt;input name="price-0"&gt;</code> and hits copy the value should be transferred over to all input whos name start with <code>price</code></p> <p>This is the code I've written:</p> <pre><code>$(document).on('click', '.--copy', function () { var input_name = $(this).closest('div').find('input').attr('name').split('-')[0]; $('input[name^=' + input_name + ']').val($(this).closest('div').find('input').val()); }); </code></pre> <p>A fiddle to make everyones life easier: <a href="http://jsfiddle.net/6jGLD/" rel="nofollow">http://jsfiddle.net/6jGLD/</a></p> <p>I feel like there are too many selectors being called upon and the code is somewhat difficult to read.</p>
[]
[ { "body": "<p>Why not at least save the intermediate to avoid rerunning that:</p>\n\n<pre><code>$(document).on('click', '.--copy', function () {\n var obj = $(this).closest('div').find('input');\n var input_name = obj.attr('name').split('-')[0];\n $('input[name^=' + input_name + ']').val(obj.val());\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T05:48:30.993", "Id": "33214", "ParentId": "33213", "Score": "2" } }, { "body": "<p>The whole thing could by simplified by adding to the HTML, for example using data attributes:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input type=\"text\" name=\"price-0\" data-copy-group=\"price\"&gt;\n</code></pre>\n\n<pre class=\"lang-js prettyprint-override\"><code>$(document).on('click', '.--copy', function () {\n var input = $(this).closest('div').find('input');\n var copyGroup = input.data('copy-group');\n $('input[data-copy-group=' + copyGroup + ']').val(input.val());\n});\n</code></pre>\n\n<hr>\n\n<p>It maybe also be a good idea to add an attribute that explicitly connects the copy link to its input, so in case the HTML structure changes, you don't need to remember to change the script.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;input type=\"text\" name=\"price-0\" id=\"price-0\" data-copy-group=\"price\"&gt;\n&lt;a class=\"--copy\" href=\"#\" data-source=\"#price-0\"&gt;copy&lt;/a&gt;\n</code></pre>\n\n<pre class=\"lang-js prettyprint-override\"><code>$(document).on('click', '.--copy', function () {\n var input = $($(this).data(\"source\"));\n var copyGroup = input.data('copy-group');\n $('input[data-copy-group=' + copyGroup + ']').val(input.val());\n});\n</code></pre>\n\n<p>Even if you don't do this, you should at the very least add a class to surrounding <code>div</code> and refer to that when using <code>.closest()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-06T11:32:24.407", "Id": "230260", "ParentId": "33213", "Score": "2" } }, { "body": "<p>If you are just wanting to take the current input value and copy it to the first other input you find that begins with the same name... (Not sure this is what you are after, but...)</p>\n\n<pre><code>&lt;!-- using onClick(),or use addListener() if you prefer --&gt;\n\n&lt;input type=\"text\" name=\"myName\" value=\"abd\" id=srcInput onClick=\"copyThis2That(this)\"/&gt;\n&lt;input type=\"text\" name=\"myName1\" value=\"\" /&gt;\n&lt;input type=\"text\" name=\"myName2\" value=\"\" /&gt;\n&lt;input type=\"text\" name=\"myName3\" value=\"\" /&gt;\n</code></pre>\n\n<p>You can move your call to <code>copyThis2That()</code> to a button, or anything else you like, so long as you reference it back to the specific input whose value you want to copy by sending <code>copyThis2That(document.getElementById(\"srcInput\"))</code> as the parameter to the function.</p>\n\n<p>Then...</p>\n\n<pre><code>&lt;script&gt;\n\n function copyThis2That(e) {\n\n var x = document.querySelectorAll(\"input\");\n\n for (var i = 0; i &lt; x.length; i++) {\n if (x[i].name) {\n if (x[i].name !== e.name &amp;&amp; (x[i].name + \" \".repeat(100)).substr(0,e.name.length) == e.name) {\n x[i].value = e.value;\n }\n }\n\n }\n\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>description: for each input on page, </p>\n\n<ol>\n<li>IF it HAS a name, and </li>\n<li>if that name is not exactly equal to the source input's name (ie, begins with it but is longer), and</li>\n<li>if it BEGINS with the same as the source input's entire name, THEN copy the value to this input.</li>\n</ol>\n\n<p>Again, this copies the source input value to the <strong>FIRST</strong> other input it finds that begins with the same characters as the source input name.</p>\n\n<p>This snippet assumes that you have no elements on the page whose name is longer than 100 characters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-08T00:09:50.297", "Id": "230346", "ParentId": "33213", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-25T05:41:33.127", "Id": "33213", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Copying and pasting one inputs value into other input with the same name" }
33213
<p>I have this code which compares data from two data tables. It does this by using a primary column and inserting the new record from <code>table2</code> to <code>table1</code>. This loop continues for a large number of tables. I want to optimize it. Kindly give suggestions.</p> <pre><code>foreach (DataRow drRow in table2.Rows) { if(!table1.Rows.Contains(drRow["KeyId"])) { table1.ImportRow(drRow); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T07:33:58.373", "Id": "53212", "Score": "0", "body": "What version of .net framework is being used ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T08:22:00.253", "Id": "53213", "Score": "0", "body": "Hi purnil, its 3.5" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T13:50:44.200", "Id": "53227", "Score": "0", "body": "I think that this might be the best way to do it. I have done a little bit of looking and it seems like the other ways that I have thought about doing it fall short of this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T04:39:15.337", "Id": "53435", "Score": "0", "body": "Malachi, thanks a lot for looking into it. I too trying to find other way which will be more optimized." } ]
[ { "body": "<p>For .net framework 3.5, you can have following code improvements:</p>\n\n<pre><code>foreach (var drRow in table2.Rows.Cast&lt;DataRow&gt;()\n .Where(drRow =&gt; !table1.Rows.Contains(drRow[\"KeyId\"]))) \n{\n table1.ImportRow(drRow); \n}\n</code></pre>\n\n<ol>\n<li>part of body can be converted to LINQ-expression</li>\n<li>use \"var\" (implicitly typed) instead of \"DataRow\" (explicitly typed)</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T06:19:32.247", "Id": "53769", "Score": "0", "body": "Hi Purnil,I tried and i was not able to see any improvement in performance. In fact the old code was faster. Anyways thanks for your inputs :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T05:59:49.813", "Id": "33431", "ParentId": "33215", "Score": "1" } } ]
{ "AcceptedAnswerId": "33431", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T06:24:37.147", "Id": "33215", "Score": "1", "Tags": [ "c#", "optimization" ], "Title": "Comparing data from two data tables" }
33215
<p>At the moment I have seven if statements that resemble the following code:</p> <pre><code>if(hit.collider.gameObject.tag == "Colour1" &amp;&amp; start_time &gt; look_at_time) { new_colour1.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color); var colums = GameObject.FindGameObjectsWithTag("column"); foreach( GameObject c in colums) c.GetComponent&lt;MeshRenderer&gt;().materials[1].color = new_colour1.orignalMaterial; } else if(hit.collider.gameObject.tag == "Colour2" &amp;&amp; start_time &gt; look_at_time) { new_colour2.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color); var colums = GameObject.FindGameObjectsWithTag("column"); foreach( GameObject c in colums) c.GetComponent&lt;MeshRenderer&gt;().materials[1].color = new_colour2.orignalMaterial; } </code></pre> <p>Each statement is roughly 6 lines of code and takes up a lot of space and can be a little tricky to read. What I'm wanting to do is find a way to re factor this so that my code is little less clunky and doesn't take up too much space. </p> <p>I had thought about changing my collection of if statements into a switch statement but I discovered that switch statements can't handle two arguments like I have above. If there any other way I can re factor my code but keep the same functionality or am I stuck with my collection of if statements? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T08:48:43.847", "Id": "53214", "Score": "0", "body": "The only thing different in the bodies of the if statements is the new_colour1/new_colour2 object. If you made a helper function that took hit.collider.gameObject.tag and returned the appropriate object, you could pass that object to a function defined by the stuff in the bodies of the if statements." } ]
[ { "body": "<p>We can start looking at what is duplicated. For example, the only difference between the two blocks of code is the string <code>\"Color1\"</code> and <code>\"Color2\"</code> in the if statement, and the variable <code>new_colour1</code> which is replaced with <code>new_colour2</code>.</p>\n\n<p>From here I'd suggest something like the following:</p>\n\n<pre><code>//This should be declared once - e.g. class level not method level.\nvar colorDict = new Dictionary&lt;string, NewColorType&gt; \n {\n {\"Colour1\", new_colour1}, \n {\"Colour2\", new_colour2}\n };\nNewColorType newColor;\nif(start_time &gt; look_at_time &amp;&amp; colorDict.TryGetValue(hit.collider.gameObject.tag, out newColor))\n{\n newColor.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color);\n var colums = GameObject.FindGameObjectsWithTag(\"column\");\n foreach( GameObject c in colums)\n c.GetComponent&lt;MeshRenderer&gt;().materials[1].color = newColor.orignalMaterial;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:22:33.813", "Id": "33219", "ParentId": "33217", "Score": "1" } } ]
{ "AcceptedAnswerId": "33219", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T08:23:55.247", "Id": "33217", "Score": "1", "Tags": [ "c#" ], "Title": "Refactoring a collection of if statements that contain 2 arguments." }
33217
<p>CodeEval's "<a href="https://www.codeeval.com/public_sc/60/" rel="nofollow">Grid Walk</a>" problem is as follows:</p> <blockquote> <p>There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself?</p> </blockquote> <p>Here is my solution. I'd appreciate any advice on my code style.</p> <pre><code>points = [[0,0]] def sum_of_digits(number): return sum(map(int, str(number))) def is_good(x, y): return sum_of_digits(abs(x))+sum_of_digits(abs(y)) &lt;= 19 def add_neighbors(x, y): for (i, j) in [(x+1, y), (x, y+1), (x-1, y), (x, y-1)]: if is_good(i, j) and [i, j] not in points: points.append([i, j]) if __name__ == "__main__": i = 0 while True: add_neighbors(points[i][0], points[i][1]) i += 1 if i &gt;= len(points): break print len(points) </code></pre>
[]
[ { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>There are no docstrings. What do your functions do and how am I supposed to call them?</p></li>\n<li><p>This kind of code is a good opportunity to write some <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctests</a>.</p></li>\n<li><p>Your program takes a very long time to run:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ time python2.7 cr33220.py\nreal 21m42.537s\nuser 20m6.233s\nsys 0m9.336s\n</code></pre>\n\n<p>There are two main reasons for this: the int-to-string-to-int conversions in <code>sum_of_digits</code> (see §1.4 below), and the use of a list to maintain the set of visited positions (see §1.8 below).</p></li>\n<li><p>Your <code>sum_of_digits</code> function has to convert back and forth between numbers and strings. It would be substantially faster if you worked with numbers throughout. On my machine, your version of the function takes 7.4 seconds to sum the digits the numbers below a million:</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit(lambda:sum(sum_of_digits(i) for i in range(10**6)), number=1)\n7.442514896392822\n</code></pre>\n\n<p>But with a pure-number implementation it only takes 1.7 seconds:</p>\n\n<pre><code>def sum_of_digits(number):\n result = 0\n while number &gt; 0:\n result += number % 10\n number //= 10\n return result\n\n&gt;&gt;&gt; timeit(lambda:sum(sum_of_digits(i) for i in range(10**6)), number=1)\n1.6833391189575195\n</code></pre></li>\n<li><p>A name like <code>accessible</code> would be clearer than <code>is_good</code> (good in what way?).</p></li>\n<li><p>You have <em>three</em> different ways of representing positions: (i) as a pair of variables <code>i</code> and <code>j</code>; (ii) as a tuple <code>(i, j)</code>; (iii) as a list <code>[i, j]</code>. This kind of variation makes it hard to remember what kinds of value to pass to functions, and in a larger program could easily lead to errors like this:</p>\n\n<pre><code>&gt;&gt;&gt; [0, 0] in [(0, 0), (1, 1)]\nFalse\n</code></pre>\n\n<p>I would recommend sticking to a single representation of positions throughout, and this representation should be a tuple, for the reason given in §1.8 below.</p></li>\n<li><p>The use of the global variable <code>points</code> means that you can only solve the problem once. If you wanted to solve it again (for example, with a different starting position, or a different value of <code>19</code>, or in order to time its performance), it wouldn't work because <code>points</code> would already be full up. It would be better to make <code>points</code> a local variable.</p></li>\n<li><p>You use the <code>points</code> list for two different purposes: (i) to ensure that you don't visit a point more than once, and (ii) to maintain a <a href=\"http://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29\" rel=\"noreferrer\"><em>queue</em></a> of positions whose neighbours need to be visited.</p>\n\n<p>However, a list is not suitable for purpose (i): in order to evaluate <code>[i, j] not in points</code>, Python has to scan the whole list and compare <code>[i, j]</code> with each item. When there are many thousands of items in the list (as in this program) this takes a long time. It would be much more efficient to use a <a href=\"http://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset\" rel=\"noreferrer\"><code>set</code></a> for this purpose, as sets have (amortized) <em>constant</em> lookup time. It would also be convenient to use <a href=\"http://docs.python.org/3/library/collections.html#collections.deque\" rel=\"noreferrer\"><code>collections.deque</code></a> for purpose (ii).</p>\n\n<p>Note that objects have to be <a href=\"http://docs.python.org/3/glossary.html#term-hashable\" rel=\"noreferrer\"><em>hashable</em></a> in order to store them in a set, so this is why you have to represent your points as tuples rather than lists.</p></li>\n<li><p>Because most of the code runs at top level in your program, it is hard for you to test your code from the interactive interpreter. You should put the code into a function and call it from the top level, like this:</p>\n\n<pre><code>def accessible_points(start, max_digit_sum):\n \"\"\"... docstring here ...\"\"\"\n # ... implementation here ...\n return visited\n\nif __name__ == \"__main__\":\n print(len(accessible_points((0, 0), 19))\n</code></pre>\n\n<p>This makes it possible to run tests interactively:</p>\n\n<pre><code>&gt;&gt;&gt; accessible_points((0, 0), 2)\n{(0, 1), (-1, 1), (0, 0), (-2, 0), (0, -2), (1, 1), (2, 0),\n (-1, -1), (0, -1), (1, 0), (1, -1), (0, 2), (-1, 0)}\n</code></pre></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>Putting all this together, here's how I'd write it:</p>\n\n<pre><code>def sum_of_digits(number):\n \"\"\"Return the sum of digits in the decimal representation of 'number'.\n\n &gt;&gt;&gt; sum_of_digits(123)\n 6\n &gt;&gt;&gt; sum_of_digits(999999)\n 54\n\n \"\"\"\n result = 0\n while number &gt; 0:\n result += number % 10\n number //= 10\n return result\n\ndef accessible(point, max_digit_sum):\n \"\"\"Return True if 'point' is accessible: that is, if the sum of its\n digits is less than or equal to 'max_digit_sum'; return False\n otherwise.\n\n &gt;&gt;&gt; accessible((19, 28), 19)\n False\n &gt;&gt;&gt; accessible((-5, -77), 19)\n True\n\n \"\"\"\n return sum(sum_of_digits(abs(i)) for i in point) &lt;= max_digit_sum\n\ndef neighbors(point):\n \"\"\"Return a list of the neighbors of 'point'.\n\n &gt;&gt;&gt; neighbors((0, 0))\n [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\n \"\"\"\n x, y = point\n return [(x+1, y), (x, y+1), (x-1, y), (x, y-1)]\n\ndef accessible_points(start, max_digit_sum):\n \"\"\"Return the set of points that are reachable from 'start' via a\n chain of accessible points (that is, points whose digit sum is\n less than or equal to 'max_digit_sum').\n\n &gt;&gt;&gt; accessible_points((0, 0), 1)\n {(0, 1), (0, -1), (1, 0), (0, 0), (-1, 0)}\n &gt;&gt;&gt; [len(accessible_points((0, 0), i)) for i in range(10)]\n [1, 5, 13, 25, 41, 61, 85, 113, 145, 505]\n\n \"\"\"\n from collections import deque\n assert(accessible(start, max_digit_sum))\n visited = set([start])\n queue = deque([start])\n while queue:\n point = queue.pop()\n for neighbor in neighbors(point):\n if neighbor not in visited and accessible(neighbor, max_digit_sum):\n visited.add(neighbor)\n queue.append(neighbor)\n return visited\n\nif __name__ == '__main__':\n print(len(accessible_points((0, 0), 19)))\n</code></pre>\n\n<p>How fast is it compared to yours?</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:len(accessible_points((0, 0), 19)), number=1)\n0.833313750976231\n</code></pre>\n\n<p>That's more than a thousand times faster!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T11:59:04.010", "Id": "33223", "ParentId": "33220", "Score": "5" } } ]
{ "AcceptedAnswerId": "33223", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T09:41:34.707", "Id": "33220", "Score": "3", "Tags": [ "python", "search" ], "Title": "Grid walk problem" }
33220
<p>Would you please run through this code and provide your comments?</p> <pre><code>void quote_container::allocate(string *i_string, string *i_value){ string temp_name = *i_string; double temp_value; // Convert the input string to upper case. stringToUpper(temp_name); if (temp_name =="OPEN"){ temp_value = atof( (*i_value).c_str() ); open = (float)temp_value; } else if (temp_name =="DAYHIGH") { temp_value = atof( (*i_value).c_str() ); high = (float)temp_value; } else if (temp_name =="DAYLOW") { temp_value = atof( (*i_value).c_str() ); low = (float)temp_value; } else if (temp_name =="LOW52") { temp_value = atof( (*i_value).c_str() ); year_low = (float)temp_value; } else if (temp_name =="HIGH52") { temp_value = atof( (*i_value).c_str() ); year_high = (float)temp_value; } else if (temp_name =="PRICEBANDLOWER") { temp_value = atof( (*i_value).c_str() ); lower_price_band = (float)temp_value; } else if (temp_name =="PRICEBANDUPPER") { temp_value = atof( (*i_value).c_str() ); upper_price_band = (float)temp_value; } else if (temp_name =="TOTALBUYQUANTITY"){ temp_value = atof( (*i_value).c_str() ); tbq = temp_value; } else if (temp_name =="TOTALSELLQUANTITY") { temp_value = atof( (*i_value).c_str() ); tsq = temp_value; } else if (temp_name == "BUYQUANTITY5" || temp_name == "BUYQUANTITY4" || temp_name == "BUYQUANTITY3"|| temp_name == "BUYQUANTITY2"|| temp_name == "BUYQUANTITY1") { temp_value = atof( (*i_value).c_str() ); tbq2 = tbq2 + temp_value; } else if (temp_name == "SELLQUANTITY5" || temp_name == "SELLQUANTITY4" || temp_name == "SELLQUANTITY3"|| temp_name == "SELLQUANTITY2" || temp_name == "SELLQUANTITY1") { temp_value = atof( (*i_value).c_str() ); tsq2 = (float)tsq2 + temp_value; } else if (temp_name == "BUYPRICE1" || temp_name == "BUYPRICE2" || temp_name == "BUYPRICE3"|| temp_name == "BUYPRICE4" || temp_name == "BUYPRICE5") { temp_value = atof( (*i_value).c_str() ); avg_buy_price = avg_buy_price + (float)temp_value ; } else if (temp_name == "SELLPRICE5" || temp_name == "SELLPRICE4" || temp_name == "SELLPRICE3"|| temp_name == "SELLPRICE2" || temp_name == "SELLPRICE1") { temp_value = atof( (*i_value).c_str() ); avg_sell_price = tsq2 + (float)temp_value; } else if (temp_name == "FACEVALUE") { temp_value = atof( (*i_value).c_str() ); face_value = (float)temp_value; } else if (temp_name == "PREVIOUSCLOSE") { temp_value = atof( (*i_value).c_str() ); prev_close = (float)temp_value; } else if (temp_name == "LASTPRICE") { temp_value = atof( (*i_value).c_str() ); last_price = (float)temp_value; } else if (temp_name == "TOTALTRADEDVOLUME") { temp_value = atof( (*i_value).c_str() ); ttv = (float)temp_value; } else cout &lt;&lt;"\n\t Ignoring --"&lt;&lt;temp_name&lt;&lt;"---"&lt;&lt;*i_value; } </code></pre> <p>Also</p> <pre><code>void quote_container::stringToUpper(string &amp;s) { for(unsigned int l = 0; l &lt; s.length(); l++) s[l] = toupper(s[l]); } </code></pre> <p>Could the above code be improved in any way?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:22:34.300", "Id": "53249", "Score": "0", "body": "Recommendation #1: Don't use strings!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:28:03.057", "Id": "53255", "Score": "1", "body": "^ Buffer lover, don't mind him." } ]
[ { "body": "<p>First step: move the code common to all cases out of the conditions:<br>\n(you may add handling if *i_value cannot always be converted to float)</p>\n\n<pre><code>void quote_container::allocate(string *i_string, string *i_value){\n string temp_name = *i_string;\n double temp_value = atof( (*i_value).c_str() ); \n stringToUpper(temp_name);\n\n if (temp_name ==\"OPEN\"){\n open = (float)temp_value;\n }\n else if (temp_name ==\"DAYHIGH\") {\n high = (float)temp_value;\n }\n else if (temp_name ==\"DAYLOW\") {\n low = (float)temp_value;\n }\n else if (temp_name ==\"LOW52\") {\n year_low = (float)temp_value;\n }\n else if (temp_name ==\"HIGH52\") {\n year_high = (float)temp_value;\n }\n else if (temp_name ==\"PRICEBANDLOWER\") {\n lower_price_band = (float)temp_value;\n }\n else if (temp_name ==\"PRICEBANDUPPER\") {\n upper_price_band = (float)temp_value;\n }\n else if (temp_name ==\"TOTALBUYQUANTITY\"){\n tbq = temp_value;\n }\n else if (temp_name ==\"TOTALSELLQUANTITY\") {\n tsq = temp_value;\n }\n else if (temp_name == \"BUYQUANTITY5\" || temp_name == \"BUYQUANTITY4\" || temp_name == \"BUYQUANTITY3\"|| \n temp_name == \"BUYQUANTITY2\"|| temp_name == \"BUYQUANTITY1\") {\n tbq2 = tbq2 + temp_value;\n }\n else if (temp_name == \"SELLQUANTITY5\" || temp_name == \"SELLQUANTITY4\" || temp_name == \"SELLQUANTITY3\"|| \n temp_name == \"SELLQUANTITY2\" || temp_name == \"SELLQUANTITY1\") {\n tsq2 = (float)tsq2 + temp_value;\n }\n else if (temp_name == \"BUYPRICE1\" || temp_name == \"BUYPRICE2\" || temp_name == \"BUYPRICE3\"|| \n temp_name == \"BUYPRICE4\" || temp_name == \"BUYPRICE5\") {\n avg_buy_price = avg_buy_price + (float)temp_value ;\n }\n else if (temp_name == \"SELLPRICE5\" || temp_name == \"SELLPRICE4\" || temp_name == \"SELLPRICE3\"|| \n temp_name == \"SELLPRICE2\" || temp_name == \"SELLPRICE1\") {\n avg_sell_price = tsq2 + (float)temp_value;\n }\n else if (temp_name == \"FACEVALUE\") {\n face_value = (float)temp_value;\n }\n else if (temp_name == \"PREVIOUSCLOSE\") {\n prev_close = (float)temp_value;\n }\n else if (temp_name == \"LASTPRICE\") {\n last_price = (float)temp_value;\n }\n else if (temp_name == \"TOTALTRADEDVOLUME\") {\n ttv = (float)temp_value;\n }\n else\n cout &lt;&lt;\"\\n\\t Ignoring --\"&lt;&lt;temp_name&lt;&lt;\"---\"&lt;&lt;*i_value;\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T12:44:50.307", "Id": "33226", "ParentId": "33225", "Score": "0" } }, { "body": "<p>Yes:</p>\n\n<p>First, the if-else if-...- is big, difficult to maintain an monolithic.</p>\n\n<p>Consider replacing it with a hierarchy of classes and allowing your function to do simple dispatching.</p>\n\n<p>(also look for my comments in the code below):</p>\n\n<pre><code>class operation {\n vector&lt;string&gt;&amp; patterns_;\nprotected:\n double &amp;value_; // will be reference to value within quote_container\npublic:\n operation(const vector&lt;string&gt;&amp; patterns, double&amp; value)\n : patterns_(patterns), value_(value) {}\n virtual ~operation() = 0 {}\n virtual void apply(const string&amp; i_value) = 0; // if you don't need\n // to check for null,\n // pass by reference\n virtual bool matches(string i_string) { // pass by value as we modify\n // this within the function\n transform(i_string.begin(), i_string.end(), i_string.begin(), toupper);\n return patterns_.end() != std::find(i_string);\n }\n};\n\nclass assignment: public operation {\npublic:\n assignment(const vector&lt;string&gt;&amp; patterns, double&amp; value)\n : operation(patterns, value) {}\n virtual ~assignment() {}\n virtual void apply(const string&amp; i_value) {\n value_ = atof(i_value.c_str() );\n }\n};\n\nclass append: public operation {\npublic:\n append(const vector&lt;string&gt;&amp; patterns, double&amp; value)\n : operation(patterns, value) {}\n virtual ~append() {}\n virtual void apply(const string&amp; i_value) {\n value_ += atof(i_value.c_str() );\n }\n};\n</code></pre>\n\n<p>With this, your function becomes:</p>\n\n<pre><code>// defined in header (store by pointer to avoid slicing &amp; for polymorphic behavior)\nvector&lt;unique_ptr&lt;operation&gt;&gt; quote_container::operations;\n\nquote_container::quote_container() {\n operations.push_back(new assignment{{\"OPEN\"}, open});\n operations.push_back(new assignment({\"DAYHIGH\"}, high});\n // ... other ops\n operations.push_back(new append(\n {\"BUYQUANTITY5\", \"BUYQUANTITY4\", \"BUYQUANTITY3\",\n \"BUYQUANTITY2\", \"BUYQUANTITY1\"}, tbq2});\n // ... other ops\n}\n\nquote_container::¬quote_container() {\n for_each(operations.begin(), operations.end(), default_delete&lt;operation&gt;);\n}\n\nvoid quote_container::allocate(string *i_string, string *i_value){\n for(operation* op: operations) {\n if(op-&gt;matches(*i_string)) {\n op-&gt;apply(*i_value);\n return;\n }\n }\n cout &lt;&lt;\"\\n\\t Ignoring --\"&lt;&lt;*i_string&lt;&lt;\"---\"&lt;&lt;*i_value;\n}\n</code></pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li><p>each part of the logic is now in a different place: you can define, test and maintain the operations separately (assignment, appending)</p></li>\n<li><p>this is very extensible: adding a new operation (for example, \"weighted average with previous values\") means defining a new class (which is also separately testable, maintainable and so on)</p></li>\n<li><p>modifying your dispatch map is different from the implementation of your operations</p></li>\n<li><p>all your functions became small (and more maintainable)</p></li>\n<li><p><code>quote_container::allocate</code> doesn't change when you add a new operation (it is now boilerplate code, and will remain the same)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T13:49:05.847", "Id": "53226", "Score": "0", "body": "Rather tan a vector. You can use a map. This basically pushes your search loop down into the standard container itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T14:07:26.683", "Id": "53229", "Score": "0", "body": "I thought about that, but a map would require indexing/comparison by key and disallow custom matching criteria. This was an easier implementation for explaining the new implementation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T13:11:34.657", "Id": "33227", "ParentId": "33225", "Score": "2" } }, { "body": "<p>Lets start with the simple one:</p>\n\n<pre><code>void quote_container::stringToUpper(string &amp;s)\n{\n for(unsigned int l = 0; l &lt; s.length(); l++) \n s[l] = toupper(s[l]); \n}\n</code></pre>\n\n<p>How about:</p>\n\n<pre><code>std::transform(s.begin(), e.end(), s.begin(), ::toupper);\n</code></pre>\n\n<p>Knowledge of the standard library is very useful.</p>\n\n<p>Never pass anything as a pointer (this is C++ not C).</p>\n\n<pre><code>void quote_container::allocate(string *i_string, string *i_value){\n</code></pre>\n\n<p>I see no testing of <code>i_string</code> or <code>i_value</code> for <code>NULL</code> so they can't be <code>NULL</code> so there is no need to pass them as pointers. So you should be passing them as references. Since neither value is modified by the function you should also probably be passing them as const to prevent accidental modification of the original value.</p>\n\n<pre><code>void quote_container::allocate(string const&amp; iString, string const&amp; iValue){\n</code></pre>\n\n<p>Don't explicitly cast values.</p>\n\n<pre><code>open = (float)temp_value;\n // ^^^^^^^\n</code></pre>\n\n<p>This is code smell. If you must cast (and usually you should not) then use one of the C++ cast operators (there should <strong>never</strong> be a need to use a C cast operator (as above)). But in this case it looks like it is not needed. If you don't cast the same conversion will happen anyway.</p>\n\n<p>In this case</p>\n\n<pre><code>avg_buy_price = avg_buy_price + (float)temp_value ;\n</code></pre>\n\n<p>You are getting worse results. Let the compiler to the cast for you. If you had let the compiler do the cast for you with:</p>\n\n<pre><code>avg_buy_price = avg_buy_price + temp_value;\n\n// Then the compiler would have generated this code\navg_buy_price = static_cast&lt;float&gt;(static_cast&lt;double&gt;(avg_buy_price) + temp_value);\n</code></pre>\n\n<p>This way you would have retained a tiny bit more accuracy during the addition (which may have mattered). Before you cast it back to float.</p>\n\n<p>As mentioned by \"The Dr\" (MrSmith) above factor out any common code. But I would do it differently. Put all your conditions in a map to make the code more readable. You actually have two types of assignment. The first is simple assignment while the second is accumulation. So we break these two types of action into their own maps</p>\n\n<pre><code>std::map&lt;std::string, float*&gt; assign= {\n {\"OPEN\", &amp;open},\n {\"DAYHIGH\", &amp;high},\n {\"DAYLOW\" &amp;low},\n {\"LOW52\", &amp;year_low},\n {\"HIGH52\", &amp;year_high},\n {\"PRICEBANDLOWER\", &amp;lower_price_band},\n {\"PRICEBANDUPPER\", &amp;upper_price_band},\n {\"TOTALBUYQUANTITY\", &amp;tbq},\n {\"TOTALSELLQUANTITY\", &amp;tsq},\n {\"FACEVALUE\", &amp;face_value},\n {\"PREVIOUSCLOSE\", &amp;prev_close},\n {\"LASTPRICE\", &amp;last_price},\n {\"TOTALTRADEDVOLUME\", &amp;ttv}\n };\nstd::map&lt;std::string, float*&gt; accum = {\n {\"BUYQUANTITY5\", &amp;tbq2},\n {\"BUYQUANTITY4\", &amp;tbq2},\n {\"BUYQUANTITY3\", &amp;tbq2},\n {\"BUYQUANTITY2\", &amp;tbq2},\n {\"BUYQUANTITY1\", &amp;tbq2},\n {\"SELLQUANTITY5\", &amp;tsq2},\n {\"SELLQUANTITY4\", &amp;tsq2},\n {\"SELLQUANTITY3\", &amp;tsq2},\n {\"SELLQUANTITY2\", &amp;tsq2},\n {\"SELLQUANTITY1\", &amp;tsq2},\n {\"BUYPRICE1\", &amp;avg_buy_price},\n {\"BUYPRICE2\", &amp;avg_buy_price},\n {\"BUYPRICE3\", &amp;avg_buy_price},\n {\"BUYPRICE4\", &amp;avg_buy_price},\n {\"BUYPRICE5\" &amp;avg_buy_price},\n {\"SELLPRICE5\", avg_sell_price}, /*avg_sell_price = tsq2 + (float)temp_value;*/\n {\"SELLPRICE4\", avg_sell_price}, /* I assumed this was a copy paste mistake you */\n {\"SELLPRICE3\", avg_sell_price}, /* made. If it is not then this array is slightly */\n {\"SELLPRICE2\", avg_sell_price}, /* More complex for SELL (but not much) */\n {\"SELLPRICE1\", avg_sell_price}\n };\n</code></pre>\n\n<p>Now that we have all the data stored in maps the code is highly simplified.</p>\n\n<pre><code> std::map&lt;std::string,float*&gt;::const_iterator find;\n find = assign.find(iString);\n if (find != assign.end())\n {\n (*find-&gt;second) = atof( iValue.c_str() );\n }\n else\n {\n find = accum.find(iString);\n if (find != accum.end())\n {\n (*find-&gt;second) += atof( iValue.c_str() );\n }\n else\n {\n std::cout &lt;&lt; \"\\n\\t Ignoring --\" &lt;&lt; iString &lt;&lt; \"---\" &lt;&lt; iValue;\n }\n }\n</code></pre>\n\n<p>You can compreses the two maps into a single map (and thus reduce the code here) by using a functor or class abstraction as described by (@utnapistim) in his answer. Personally I would go with using std::function rather than building my own class hierarchy (but that's a you say potato I say tomato argument and down to personal preference).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:16:48.670", "Id": "53574", "Score": "0", "body": "Thanks for an eloberated answer. regarding your comment, i am receiving the content from source in the above format, hence using the same as is. Everytime appending it to sell & buy quantity." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T13:42:37.700", "Id": "33229", "ParentId": "33225", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T12:20:53.193", "Id": "33225", "Score": "2", "Tags": [ "c++", "strings" ], "Title": "Comparing and assigning strings" }
33225
<p>I've wrote a generic function to add an item to an Array 2D</p> <p>This is what I have:</p> <pre><code>Private Sub Add_Item_Array_2D(ByRef Array_2D As String(,), _ ByVal Items As String()) Dim tmp_array(Array_2D.GetUpperBound(0) + 1, Array_2D.GetUpperBound(1)) As String For x As Integer = 0 To Array_2D.GetUpperBound(0) tmp_array(x, 0) = Array_2D(x, 0) tmp_array(x, 1) = Array_2D(x, 1) Next For x As Integer = 0 To Items.Count - 1 tmp_array(tmp_array.GetUpperBound(0), x) = Items(x) Next Array_2D = tmp_array End Sub </code></pre> <p>The code works, but I want to know if can be improved using Array.Resize method of LINQ extensions.</p> <p>This is an usage example:</p> <pre><code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.shown ' Create Array 2D (2,2) Dim MyArray As String(,) = _ {{"Item 0,0", "Item 0,1"}, {"Item 1,0", "Item 1,1"}, {"Item 2,0", "Item 2,1"}} ' Add Item Add_Item_Array_2D(MyArray, {"Item 3,0", "Item 3,1"}) ' Loop over the Array 2D For x As Integer = 0 To MyArray.GetUpperBound(0) MsgBox(String.Format("Array 2D {1},0: {2}{0}Array 2D {1},1: {3}", Environment.NewLine, _ x, MyArray(x, 0), MyArray(x, 1))) Next End Sub </code></pre>
[]
[ { "body": "<p>Couple nitpicks:</p>\n\n<ul>\n<li><strong>Try to stick to <em>PascalCasing</em> for method names</strong>. Using <code>_</code> underscores not only makes your method names look rather messy, the underscore is conventionally used for event handler methods (like <code>Form1_Load</code>, i.e. <code>object_event</code>).</li>\n<li><strong>Consistency is king</strong>. Your two snippets aren't consistent as far as parameter naming goes: you're using <em>PascalCasing</em> in your top example, and <em>camelCasing</em> in the bottom one. <strong>Pick one, stick to it.</strong></li>\n<li>The term <strong>generic</strong> <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms235246.aspx\" rel=\"nofollow noreferrer\">has a specific meaning in the .net world</a>. That's not a <em>generic</em> function. <em>General-purpose</em>, maybe?</li>\n</ul>\n\n<hr>\n\n<p>A quick Google search didn't yield much interesting results in VB.net, but <a href=\"https://stackoverflow.com/a/6539620/1188513\">this StackOverflow answer</a> has a decent C# version of the code - and it just happens to be an actual <em>generic</em> method:</p>\n\n<blockquote>\n <p>Most methods in the array class only work with one-dimensional arrays, so you have to perform the copy manually:</p>\n\n<pre><code>T[,] ResizeArray&lt;T&gt;(T[,] original, int rows, int cols)\n{\n var newArray = new T[rows,cols];\n int minRows = Math.Min(rows, original.GetLength(0));\n int minCols = Math.Min(cols, original.GetLength(1));\n for(int i = 0; i &lt; minRows; i++)\n for(int j = 0; j &lt; minCols; j++)\n newArray[i, j] = original[i, j];\n return newArray;\n}\n</code></pre>\n</blockquote>\n\n<p>Now I know this isn't VB, but an <em>array</em> is an <em>array</em> regardless of the language, so I strongly recommend you take a look at the SO answer, as it goes in much more details than I'd care to quote over here.</p>\n\n<p><strong>Bottom line: You cannot use Array.Resize() with multidimensional arrays</strong>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T02:15:59.970", "Id": "35738", "ParentId": "33232", "Score": "1" } }, { "body": "<blockquote>\n <p><strong>Bottom line</strong>: You cannot use <code>Array.Resize()</code> with multidimensional\n arrays.</p>\n</blockquote>\n\n<p>On the other hand, a 2-D list eliminates the resizing altogether.<code>List(Of List(Of String))</code> adding items is as easy as the following:</p>\n\n<pre><code>Private Sub Add_Item_Array_2D(ByRef Array_2D As List(Of List(Of String)), _\n ByVal Items As String())\n Array_2D.Add(New List(Of String)(Items))\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T19:57:17.437", "Id": "37159", "ParentId": "33232", "Score": "1" } }, { "body": "<p>To resize multidimentional arrays without using any lists, read the <a href=\"https://msdn.microsoft.com/en-us/library/bb348051(v=vs.110).aspx\" rel=\"nofollow noreferrer\">MSN documentation for <code>Array.Resize&lt;T&gt;()</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-09T22:42:18.257", "Id": "184693", "ParentId": "33232", "Score": "1" } } ]
{ "AcceptedAnswerId": "35738", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T13:59:35.427", "Id": "33232", "Score": "2", "Tags": [ ".net", "array", "linq", "vb.net", "generics" ], "Title": "Add item to an Array 2D using LINQ" }
33232
<p>Version 3.5 of the .NET Framework was released on 19 November 2007, but it is not included with Windows Server 2008. As with .NET Framework 3.0, version 3.5 uses Common Language Runtime (CLR) 2.0, that is, the same version as .NET Framework version 2.0. </p> <p>In addition, .NET Framework 3.5 also installs .NET Framework 2.0 SP1 and 3.0 SP1 (with the later 3.5 SP1 instead installing 2.0 SP2 and 3.0 SP2), which adds some methods and properties to the BCL classes in version 2.0 which are required for version 3.5 features such as Language Integrated Query (LINQ). </p> <p>These changes do not affect applications written for version 2.0, however.</p> <p>As with previous versions, a new .NET Compact Framework 3.5 was released in tandem with this update in order to provide support for additional features on Windows Mobile and Windows Embedded CE devices.</p> <p>The source code of the Base Class Library in this version has been partially released (for debugging reference only) under the Microsoft Reference Source License.</p> <p><a href="http://en.wikipedia.org/wiki/.NET_Framework_version_history" rel="nofollow">.NET Framework version history Wikipedia</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T14:12:30.787", "Id": "33233", "Score": "0", "Tags": null, "Title": null }
33233
Version #3.5.21022.8 of the .NET Framework was released on November 11th, 2007. It is needed to support windows 7 and windows server 2008 R2. Its preferred IDE is Visual Studio 2008.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T14:12:30.787", "Id": "33234", "Score": "0", "Tags": null, "Title": null }
33234
<p>I'm currently populating my drop downlists like this...</p> <pre><code> public List&lt;NewLogin&gt; GetRolesForDDL() { using (database db = new database()) { return (from r in db.UserRole select new NewLogin { UserRole = r.Role, RoleID = r.RoleID }).ToList(); } } public NewLogin RoleDDL() { NewLogin nl = new NewLogin(); using (database db = new database()) { // populates ddl nl.RoleList = new SelectList(GetRolesForDDL(), "RoleID", "UserRole"); } return nl; } </code></pre> <p>The part I don't like in particular is where <code>nl.RoleList = new SelectList(GetRolesForDDL()</code> Is there a better way I can do this, by keeping within the same style and bypassing that method and using a quick and easy lambda expression instead?</p> <p>Also another quick question is...</p> <p><code>@Html.DropDownListFor(u =&gt; u.RoleID, Model.RoleList)</code> When I pass this to the controller I get the RoleID value, but my RoleName(text of ddl) get's passed as null. Can I access both RoleName and ID without fetching it in the backend?</p> <p>I know this doesn't work, but I'm thinking it would have to be something like </p> <p><code>DDLFor(u =&gt; u.RoleID, u.RoleName)</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T07:07:29.823", "Id": "53298", "Score": "1", "body": "Is there code missing? Why are you making a database connection twice?" } ]
[ { "body": "<blockquote>\n <p>Can I access both RoleName and ID without fetching it in the backend?</p>\n</blockquote>\n\n<p>Yes, I believe so if you want to write a bit of javascript. You would need to create a \nhidden field and on every select list change event set the value of that field.</p>\n\n<p>Something like</p>\n\n<pre><code>$(body).on(\"change\", \"#selectbox\", function() {\n $(\"#inputbox\").val($(this).val());\n});\n</code></pre>\n\n<p>I'm also unsure as to why you are creating the database connection twice but I would consider\npassing that into the GetRoles method like so:</p>\n\n<pre><code>public IEnumerable&lt;NewLogin&gt; GetRolesForDDL(database db)\n{\n return (from r in db.UserRole\n select new NewLogin\n {\n UserRole = r.Role,\n RoleID = r.RoleID\n }); \n} \npublic NewLogin RoleDDL()\n{\n using (database db = new database())\n { \n var roles = GetRolesForDDL(db).ToList();\n // populates ddl\n return new NewLogin\n {\n RoleList = new SelectList(roles, \"RoleID\", \"UserRole\"); \n }\n }\n}\n</code></pre>\n\n<p>Or even if both of these methods are part of a class consider passing the database into the class constructor and using it as a private instance variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:57:39.577", "Id": "53486", "Score": "0", "body": "thats pointing that out about multiple db connections, it's unnecessary" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T07:19:47.063", "Id": "33284", "ParentId": "33236", "Score": "1" } } ]
{ "AcceptedAnswerId": "33284", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T14:34:19.823", "Id": "33236", "Score": "2", "Tags": [ "c#", "linq", "asp.net-mvc-4" ], "Title": "Improving MVC 4 DropDownList" }
33236
<p>I've written my first completely self-written jQuery today. I just used the jQuery docs and I'm reasonably proud I got it to work, and working fine. It's not a very complex problem I'm solving, just an animated UI element, but it are my first steps, and I want to make sure I'm starting off right.</p> <p>I think it's a lot of code for what I'm trying to achieve, and I'm looking for pointers or tips on how I could improve my code. I'm not at all averse to scrapping all jQuery here and doing it with pure JS either.</p> <pre><code>jQuery(document).ready(function () { event.preventDefault(); var nav = jQuery(".navigation-menu"); var button = jQuery(".navigation-title"); function showNav() { nav.show('fast'); button.removeClass('closed'); button.addClass('open'); } function hideNav() { nav.hide('fast'); if (button.hasClass('open')) { button.removeClass('open'); } button.addClass('closed'); } hideNav(); button.click(function () { if (button.hasClass('closed')) { showNav(); } else if (button.hasClass('open')) { hideNav(); } else if (!button.hasClass('open') || !button.hasClass('closed')) { hideNav(); } }); }); </code></pre> <p>Here's the fiddle: <a href="http://jsfiddle.net/yeawg/2/" rel="nofollow">http://jsfiddle.net/yeawg/2/</a></p> <p>I'm also wondering: am I using event.preventDefault() right?</p>
[]
[ { "body": "<p>For one, it can be done <a href=\"http://jsfiddle.net/yeawg/4/\" rel=\"nofollow\">CSS-only</a>.</p>\n\n<p>JS:</p>\n\n<pre><code>None at all. Remove your JS.\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code>&lt;nav class=\"mobile-navigation\"&gt;\n &lt;!-- dummy target since CSS has no \"prev\" --&gt;\n &lt;i id=\"menu\"&gt;&lt;/i&gt;\n\n &lt;div class=\"navigation-menu\"&gt;\n &lt;a id=\"menu-open\" href=\"#menu\"&gt;Menu&lt;/a&gt;\n &lt;a id=\"menu-close\" href=\"#\"&gt;Menu&lt;/a&gt;\n &lt;/div&gt;\n\n &lt;ul id=\"menu-real\" class=\"navigation-menu\"&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Cafe&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Toys&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Shop-in-Shop&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Feestjes&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Agenda&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#\"&gt;Fietsverhuur&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/nav&gt;\n</code></pre>\n\n<p>Add this CSS to your existing CSS:</p>\n\n<pre><code>/* menu animators */\n#menu ~ #menu-real {\n height:0;\n width:0;\n opacity:0;\n box-sizing:border-box;\n position:absolute;\n overflow:hidden;\n transition: all 0.5s ease;\n}\n#menu:target ~ #menu-real {\n width: 100%;\n height : 100%;\n opacity : 1;\n position:relative;\n}\n\n/* Menu button swappers */\n#menu ~ * &gt; #menu-open {display:block}\n#menu:target ~ * &gt; #menu-open {display:none}\n\n#menu ~ * &gt; #menu-close {display:none}\n#menu:target ~ * &gt; #menu-close {display:block}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T14:28:54.960", "Id": "53325", "Score": "0", "body": "Thanks for your answer, however I'm trying to learn more about JavaScript. I'm definitely looking in to your solution however. Seems the better option performance-wise. (Even though it probably won't matter much in this case, at least I don't have to load jQuery)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T15:54:03.337", "Id": "33239", "ParentId": "33237", "Score": "1" } }, { "body": "<p>Some points:</p>\n\n<ul>\n<li>The <code>preventDefault</code> doesn't do anything in a <code>ready</code> event handler, as there is no default action that would happen after the event. (If you would use the <code>preventDefault</code> method you should declare a parameter in the event handler to catch the event object sent to it.)</li>\n<li>You don't need to check if an element has a class before removing it, if it's not there the <code>removeClass</code> method will just change nothing.</li>\n<li>You can chain calls that work with the same jQuery object.</li>\n<li>When checking what to do with the navigation, you can just use an <code>else</code> instead of checking every combination.</li>\n</ul>\n\n<p>So:</p>\n\n<pre><code>jQuery(document).ready(function () {\n var nav = jQuery(\".navigation-menu\");\n var button = jQuery(\".navigation-title\");\n\n function showNav() {\n nav.show('fast');\n button.removeClass('closed').addClass('open');\n }\n\n function hideNav() {\n nav.hide('fast');\n button.removeClass('open').addClass('closed');\n }\n\n hideNav();\n\n button.click(function () {\n if (button.hasClass('closed')) {\n showNav();\n } else {\n hideNav();\n }\n });\n\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:14:48.910", "Id": "33254", "ParentId": "33237", "Score": "1" } }, { "body": "<p>I found <code>.toggle()</code> in the jQuery docs, and it seemed to me I could use that far better. I changed my code into:</p>\n\n<pre><code>jQuery(document).ready(function(){\n var nav = jQuery(\".navigation-menu\");\n var button = jQuery(\".navigation-title\");\n\n nav.toggle();\n\n button.click(function(event){\n event.preventDefault();\n nav.toggle('fast');\n });\n});\n</code></pre>\n\n<p>This looks a lot leaner and better readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T15:23:21.907", "Id": "33295", "ParentId": "33237", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T14:58:39.770", "Id": "33237", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "My first-ever jQuery works, but it's not efficient. Any pointers?" }
33237
<p>I've finally got all my code working as expected and it handles the data quickly. But now I'm looking to refactor it because there is some duplicate sections that just looks like can be broken down for more efficiency and readability. With out making this too long, here is the original:</p> <p>I created functions <code>createNumLabel</code> and <code>createPctLabel</code> to basically do what is in the if statement. So if codeID = 1,32,28,33,10 call <code>createNumLabel</code> else call <code>createPctLabel</code>. While that doesn't crash the map no labels on the map are drawn. Any ideas would be helpful. </p> <pre><code> function labels(graphics) { globals.map.on("update-end", function () { var font = new esri.symbol.Font(10, esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_BOLDER, "Arial");//create font object //var gl = globals.featureLayers[1].graphics;//low res var gl2 = globals.featureLayers[2].graphics;//high res console.log("Initial zoom level is :" + globals.map.getZoom()); console.log("Scale is :" + globals.map.getScale()); globals.map.graphics.clear(); if(globals.map.getZoom() &gt;=9) { console.log(gl2.length); //globals.featureLayers[1].setVisibility(false); for (var i = 0; i &lt; gl2.length; i++) { if (codeID == 1 || codeID == 32 || codeID == 28 || codeID == 33 || codeID == 10) { //createNumLabel(graphics); var g2 = globals.featureLayers[2].graphics[i]; var strLabel2 = g2.attributes.NAME + ":" + $.formatNumber(findFips(g2), { format: '#,###', locale: "us" });//creates string label formatted var textSymbol2 = new esri.symbol.TextSymbol(strLabel2, font); textSymbol2.setColor(new dojo.Color([0, 0, 0])); var pt2 = g2.geometry.getExtent().getCenter(); var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2); //add label to the map globals.map.graphics.add(labelPointGraphic2); }//end if else { //createPctLabel(graphics); var g2 = globals.featureLayers[2].graphics[i]; var strLabelPct2 = g2.attributes.NAME + " : " + $.formatNumber(findFips(g2), { format: '#,###.0', locale: "us" }) + "%"; var textSymbol2 = new esri.symbol.TextSymbol(strLabelPct2, font);//create symbol with attribute name textSymbol2.setColor(new dojo.Color([0, 0, 0]));//set the color var pt2 = g2.geometry.getExtent().getCenter(); //get center of county var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2); //create label graphic //add label to the map globals.map.graphics.add(labelPointGraphic2); }//end else }//end for }//ends if });//ends update end }//ends labels function </code></pre>
[]
[ { "body": "<p>Addressing the duplication, it seems that both conditions are processed the same with the exception of <code>format</code>. You could either provide an inline conditional (ternary statement) to determine the format to use or pass the <code>codeID</code> to a function and return the respective format. At that point the <code>if/else</code> narrows in context and is only applied at the building of <code>strLabel/strLabelPct2</code>. </p>\n\n<p>The <code>function</code> usage would be more extensible if the need for code modifications were to arise, as such, it would be my preference.</p>\n\n<p>Function:</p>\n\n<pre><code>var applyFormatting = function(codeID, data) {\n if (codeID == 1 || codeID == 32 || codeID == 28 || codeID == 33 || codeID == 10) {\n return $.formatNumber(data, { format: '#,###', locale: \"us\" }); \n }\n return $.formatNumber(data, { format: '#,###.0', locale: \"us\" }) + \"%\";\n };\n\nfor (var i = 0; i &lt; gl2.length; i++) { \n var g2 = globals.featureLayers[2].graphics[i];\n\n var affectedValue = applyFormatting(codeID, findFips(g2));\n\n var strLabel2 = g2.attributes.NAME + \":\" + affectedValue;\n var textSymbol2 = new esri.symbol.TextSymbol(strLabel2, font);\n textSymbol2.setColor(new dojo.Color([0, 0, 0]));\n var pt2 = g2.geometry.getExtent().getCenter();\n var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2);\n\n //add label to the map\n globals.map.graphics.add(labelPointGraphic2);\n} \n</code></pre>\n\n<p>Ternary: </p>\n\n<pre><code> var codesThatAffectLabel = [1, 32, 28, 33, 10];\n\n for (var i = 0; i &lt; gl2.length; i++) { \n var g2 = globals.featureLayers[2].graphics[i];\n var data = findFips(g2);\n\n var affectedValue = (-1 != codesThatAffectLabel.indexOf(codeID))\n ? $.formatNumber(data, { format: '#,###', locale: \"us\" })\n : $.formatNumber(data, { format: '#,###.0', locale: \"us\" }) + \"%\";\n\n var strLabel2 = g2.attributes.NAME + \":\" + affectedValue;\n var textSymbol2 = new esri.symbol.TextSymbol(strLabel2, font);\n textSymbol2.setColor(new dojo.Color([0, 0, 0]));\n var pt2 = g2.geometry.getExtent().getCenter();\n var labelPointGraphic2 = new esri.Graphic(pt2, textSymbol2);\n\n //add label to the map\n globals.map.graphics.add(labelPointGraphic2);\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:13:26.133", "Id": "33246", "ParentId": "33240", "Score": "1" } } ]
{ "AcceptedAnswerId": "33246", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T16:16:45.477", "Id": "33240", "Score": "0", "Tags": [ "javascript", "performance" ], "Title": "Refactoring code for more readability" }
33240
<p>How will you merge two sorted arrays, when The longer array has empty spaces to accomodate the second array. Complexity: O (items in longer + items in smaller). Request for making code concise, clean and optimal. </p> <pre><code>public final class MergeArrays { private MergeArrays() {} private static void check(Integer[] big, Integer[] small) { if (big == null &amp;&amp; small == null) { throw new NullPointerException("The input arrays are null."); } if (big.length &lt; small.length) { throw new IllegalArgumentException("The arrays is smaller smaller array"); } } public static Integer[] mergeSortedArrays(Integer[] big, Integer[] small) { check(big, small); int limit = 0; for (Integer val : big) { if (val == null) { break; } limit++; } return mergeSortedArrays(big, limit, small); } private static Integer[] mergeSortedArrays(Integer[] big, int limit, Integer[] small) { assert big != null; assert small != null; int limitIndex = limit - 1; int bigIndex = big.length - 1; int smallIndex = small.length - 1; while (smallIndex &gt;= 0) { if (limitIndex &lt; 0 || big[limitIndex] &lt; small[smallIndex]) { big[bigIndex--] = small[smallIndex--]; } else { big[bigIndex--] = big[limitIndex--]; } } return big; } </code></pre>
[]
[ { "body": "<p>Do not throw NullPointerException when arguments are null. NPE is thrown when you are trying to access properties and methods of null reference. Not when you are checking on some preconditions. Throw IllegalArgumentException as you do in length validation. In other method you use assertions. Chose one method and stick with it, dont mix them.</p>\n\n<p>You don have to define empty constructor. It is created implicitly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T19:37:26.047", "Id": "58447", "Score": "0", "body": "In this case, the empty constructor needs to be defined because it is marked `private`. An implicit empty constructor is always `public`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T11:09:56.980", "Id": "33443", "ParentId": "33243", "Score": "1" } } ]
{ "AcceptedAnswerId": "33443", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T16:35:13.427", "Id": "33243", "Score": "1", "Tags": [ "java", "algorithm", "array" ], "Title": "Merge 2 arrays, when one is larger and can accomodate smaller" }
33243
<p>Someone posted a question on <a href="http://math.stackexchange.com">http://math.stackexchange.com</a> earlier because their program to tranpose a matrix wasn't working. I copied the code they posted (which was just the transpose method) and added the code necessary to check if it worked on their example matrix and it does, so there's obviously a problem elsewhere in their code. I've posted my code below. </p> <p>I don't have much programming experience and I suspect my style is unconventional. I implement most of the main program in the constructor, because every time I try to do it in the main method, I get lots of errors because I'm referencing non-static variables and methods from a static context. Maybe there are good reasons for using the static keyword, but I just wanted to write quickly a program to check whether the other person's method was correct and it seemed like the fact that the main method was static was getting in the way, so I just transferred most of the program to the constructor. I have 9 questions (question 8 is actually 2 questions), but question 8 is the most important: </p> <ol> <li><p>Is my program ok? </p></li> <li><p>Could it be better and if so, why?</p></li> <li><p>What would be the conventional way to write the program?</p></li> <li><p>How would the program be written with the main method in the main method rather than the constructor?</p></li> <li><p>How does having the main method static help? </p></li> <li><p>Someone wrote 'It is good to move code into on or more classes instead of having everything in the main method!'. If I do this, it seems like I get lot of errors because I'm referencing a static variable from a non-static context (since I must at least instantiate one class in the static main method). How would I best overcome this? </p></li> <li><p>Someone else suggested changing everything to static, but that can't be normal, can it? </p></li> <li><p>I know that's a lot of questions. I think the following 2 questions could pin down what I want to find out: where would <code>printMatrix()</code> be in a conventional program (presumably not in the constructor like it is in mine)? If there wouldn't even be such a method in a conventional program, how <em>would</em> the printing of the matrix and its transpose be implemented?</p></li> </ol> <p></p> <pre><code>public class Matrix { double[][] M = new double[3][3]; static int mat_size=3; public Matrix() { M[0][0]=1; M[0][1]=0; M[0][2]=0; M[1][0]=5; M[1][1]=1; M[1][2]=0; M[2][0]=6; M[2][1]=5; M[2][2]=1; System.out.println("M"); printMatrix(); transpose(); System.out.println("M'"); printMatrix(); } public static void main(String[] args) { // TODO Auto-generated method stub new Matrix(); } public void transpose() { System.out.println(); for(int i = 0; i &lt; mat_size; ++i) { for(int j = 0; j &lt; i ; ++j) { double tmpJI = get(j, i); put(j, i, get(i, j)); put(i, j, tmpJI); } } } public void printMatrix() { System.out.println(); for(int i = 0; i &lt; mat_size; ++i) { for(int j = 0; j &lt; mat_size ; ++j) { System.out.print((int)get(i,j)+" "); } System.out.println(); } } private void put(int i, int j, double d) { // TODO Auto-generated method stub M[i][j]=d; } private double get(int i, int j) { // TODO Auto-generated method stub return M[i][j]; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:18:44.027", "Id": "53247", "Score": "2", "body": "Hmm, the code is awful but you did ask the right questions to improve it. However, any answer would have to focus more on Java basics than an actual code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:20:41.790", "Id": "53248", "Score": "0", "body": "lol. +1 for feedback. I did try asking the question on Stack Overflow but it got put on hold as off-topic. @amon" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:23:28.417", "Id": "53250", "Score": "0", "body": "Well, it is absolutely off topic over *there*, a bit less so here. I might just as well attempt an answer. Do you have prior experience with object-oriented programming? If so, which language?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:30:31.963", "Id": "53252", "Score": "0", "body": "java and C#, but this is java. It was an earlier version of the question, which didn't have questions 6-8, but still, I didn't see how it failed to meet the requirement they cited: \"Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself.\" I might take a look at a sample program on the Java Outside In Website: that might improve my understanding or even perfect it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:15:19.647", "Id": "53253", "Score": "1", "body": "I've found the info I needed by looking at a sample program on the Java Outside In website. The problem was I was just putting printMatrix(); in the main method rather, than instantiating a Matrix Ma and then putting Ma.printMatrix(); I did know this: it's just been a while since I've done any java, except for a program I wrote using WindowBuilderPro, which seemed to put the main program in the constructor, like I did." } ]
[ { "body": "<p>I've found the info I needed by looking at a sample program on the Java Outside In website. The problem was I was just putting </p>\n\n<p><code>printMatrix();</code></p>\n\n<p>in the main method rather, than instantiating a Matrix Ma and then putting </p>\n\n<p><code>Ma.printMatrix();</code></p>\n\n<p>I did know this: it's just been a while since I've done any java, except for a program I wrote using WindowBuilderPro, which seemed to put the main program in the constructor, like I did.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:17:12.470", "Id": "33255", "ParentId": "33245", "Score": "0" } }, { "body": "<blockquote>\n <p>Is my program ok?</p>\n</blockquote>\n\n<p>Well, I guess it works. However, it can be structured far better.</p>\n\n<h1>Basic Object Oriented Programming in Java</h1>\n\n<p>In Java (and all of this is also true for C#), every <em>object</em> has a <em>type</em> which is represented by a so-called <em>class</em>. We can define operations on each type, which we call <em>methods</em>. Some methods operate on an individual <em>instance</em> of a type. Other operations are not inherently bound to instances, and operate on the whole class. We call this second kind of operations <em>static methods</em>.</p>\n\n<p>Likewise, data can either belong to a specific instance, or is shared across all instances, in which case it's called static. Every method (static and non-static) can refer to static data, because that is shared. However, static methods cannot reference instance data, because a static method can't tell from which instance you'd like the data – and sometimes, no instance may exist at all. Static methods are mostly useful for general helpers.</p>\n\n<p>It is really important to grok the difference between static and non-static methods in order to use Java effectively (the same holds for any other class-based programming language).</p>\n\n<h2>Meaning of the <code>main</code></h2>\n\n<p>What is the <code>main</code> and why do we need it? The <code>main</code> originated as a feature of the C programming language. It defines an entry point into the program. At startup, your classes are initialized and then the <code>main</code> methods gets called with the command line arguments in an array as parameter. The <code>main</code> method doesn't return a value (it is <code>void</code>), because returning from it aborts the process.</p>\n\n<p>The <code>main</code> is static because it's a helper method to get your control flow going – it is not coupled to any instance. It is therefore common in a <code>main</code> to create an instance of the surrounding class, and work with that.</p>\n\n<h2>Constructors</h2>\n\n<p>A constructor is a special method used to <em>initialize</em> a fresh instance. All it usually does is assigning its arguments to the corrects data fields of the instance. It isn't recommended to do the actual work here – put that into another method.</p>\n\n<p>In your code, everything after the initialization can be moved into the <code>main</code> method where it belongs. Note that methods are invoked on a specific instance with the dot operator. The <code>main</code> now looks like:</p>\n\n<pre><code>public static void main(String[] args) {\n Matrix matrix = new Matrix();\n\n System.out.println(\"M\");\n matrix.printMatrix();\n\n matrix.transpose();\n\n System.out.println(\"M'\");\n matrix.printMatrix();\n}\n</code></pre>\n\n<p>Now we are already getting into the code review zone of this answer.</p>\n\n<h1>Design spotlights</h1>\n\n<h2>A method should do one thing only and – no “and”!</h2>\n\n<p>Every method should do <em>one</em> thing only. Exaggerated: While a description of your method uses the word “and”, it is doing to much. Split the functionality into more methods. For example, your <code>transpose</code> method does this: “<em>It prints an empty line <strong>and</strong> swaps columns with rows of the matrix</em>”. Is printing an empty line really necessary in a method called “transpose”?</p>\n\n<p>The same goes for your version of the constructor: “<em>It initialized the matrix <strong>and</strong> prints it out <strong>and</strong> transposes it <strong>and</strong> prints it out again</em>” – but we already cleaned that up above.</p>\n\n<h2>Composability</h2>\n\n<p>An advantage of having each method doing one concept only makes it easier to <em>compose</em> them in a different way to do new things. There are a few important things that can make this easier:</p>\n\n<h3>Don't hardcode stuff – parameterize it</h3>\n\n<p>Don't hardcode things that aren't universal constants. Actually, don't hardcode things at all. For example, you assign <code>static int mat_size = 3</code> – but what if I want to use a 5×5 matrix? You don't provide any functionality that actually depends on the number three. Instead, the size is a property of each <em>instance</em>. Therefore, we'll remove the <code>static</code> modifier, and initialize it in the constructor.</p>\n\n<p>The constructor is another example of hardcoding: The whole test matrix is specified there. It would be better to move that data out of the constructor, and have the constructor take an array as argument instead. I'd rather initialize a new matrix like:</p>\n\n<pre><code>// array literals :) – however, I'm unsure about the exact syntax\ndouble[3][3] testData = { { 1, 0, 0 },\n { 5, 1, 0 },\n { 6, 5, 1 } };\nMatrix matrix = new Matrix(3, testData);\n</code></pre>\n\n<p>We can now initialize a matrix with arbitrary other values, not only that specific data set.</p>\n\n<h3>Immutability</h3>\n\n<p>When objects <em>don't</em> change their internal state over time, programs often get a bit simpler. Mathematics does this as well: When we transpose a matrix <em>M</em>, the <em>M</em> still has its old values. The transposition produces a new and distinct matrix, which we can call <em>M'</em> (you even do this in your printout). There is no reason our <code>transpose</code> method shouldn't return a new matrix either. Now we get something along the lines of:</p>\n\n<pre><code>public Matrix transpose() {\n double[size][size] newData = new double[size][size];\n\n for(int i = 0; i &lt; size; i++) {\n for(int j = 0; j &lt; i ; j++) {\n newData[i][j] = get(j, i);\n newData[j][i] = get(i, j);\n }\n newData[i][i] = get(i, i);\n }\n\n return new Matrix(size, newData);\n}\n</code></pre>\n\n<p>This changes our <code>main</code>:</p>\n\n<pre><code>public static void main(String[] args) {\n Matrix matrix = new Matrix();\n\n System.out.println(\"M\");\n matrix.printMatrix();\n\n Matrix transposed = matrix.transpose();\n\n System.out.println(\"M'\");\n transposed.printMatrix();\n}\n</code></pre>\n\n<h3>No side effects</h3>\n\n<p>When a method has any effect except returning some data, it has side effects. Such effects might be changing the state of some object (thus voiding the point about immutability), or printing out some data. These side effects make it more difficult to combine these methods in a new way.</p>\n\n<p>Specifically, <code>printMatrix</code> is an offender here. Also because it can't be changed to print to anything other than <code>System.out</code>. What happens when I want a string representation to display on a GUI? I can't simply use your awesome <code>Matrix</code> class :(</p>\n\n<p>Here, it would be better to implement the <code>toString()</code> function, which returns a string representation of your object. There is already a default implementation for every object, but we can override it. Then, our <code>main</code> will look like:</p>\n\n<pre><code>public static void main(String[] args) {\n Matrix matrix = new Matrix();\n\n System.out.println(\"M\");\n System.out.println(matrix.toString());\n\n Matrix transposed = matrix.transpose();\n\n System.out.println(\"M'\");\n System.out.println(transposed.toString());\n}\n</code></pre>\n\n<p>That is more ugliness here, but massively clears up the rest of your code. The <code>toString</code> might be:</p>\n\n<pre><code>public String toString() {\n StrinBuilder sb = new StringBuilder();\n for(int i = 0; i &lt; size; i++) {\n for(int j = 0; j &lt; size ; j++) {\n sb.append(\" \" + (int) get(i, j));\n }\n sb.append(\"\\n\");\n }\n return sb.toString();\n}\n// apologies if I mixed up the StringBuilder API\n</code></pre>\n\n<h1>A closing note on naming things</h1>\n\n<p>In Java, names are written in camelCase. Class names are capitalized. Any other names start with a lowercase letter: <code>Matrix</code> refers to a class, while <code>matrix</code> is a local variable, field, or method. As an exception, constants are written all-uppercase and seperated by underscores. Because for normal names the parts of a word are distinguished by capitalization, no underscores are ever used.</p>\n\n<p>It is advisable to use meaningful names like <code>matrix</code> or <code>transformedMatrix</code>, not shortcuts like <code>m</code> or <code>t</code> or <code>m_</code>. Choosing longer names makes it easier to read a piece of code for someone who isn't used to your shortcut notation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:48:34.603", "Id": "53259", "Score": "0", "body": "We touched on almost the exact same issues. You got me on transpose returning a new Matrix. I didn't even consider that. I like it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:31:16.800", "Id": "33257", "ParentId": "33245", "Score": "6" } }, { "body": "<p>When referencing my example in the text below, refer to <a href=\"http://ideone.com/a5KmQ3\" rel=\"nofollow noreferrer\">my implementation</a>.</p>\n\n<p><code>1. Is my program ok?</code></p>\n\n<p>If it runs, you are doing better than most people. A great place to start is the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html\" rel=\"nofollow noreferrer\">Code Conventions for Java</a>. Other than that, its just a little cleanup and application of object oriented programming (OOP) principles.</p>\n\n<p><code>5. How does having the main method static help?</code> </p>\n\n<p>The method marks the entry point for executing the program. Here are a few posts regarding the topic: <a href=\"https://stackoverflow.com/questions/146576/why-is-the-java-main-method-static\">First</a>, <a href=\"https://stackoverflow.com/questions/3181207/why-main-method-is-static-in-java\">Second</a>. Others are most certainly available.</p>\n\n<p><code>7. Someone else suggested changing everything to static, but that can't be normal, can it?</code></p>\n\n<p>The keyword <code>static</code> only fits a select few scenarios and is best avoided for all but those cases. You can search for plenty of posts regarding the topic. </p>\n\n<p><code>6. ... use more classes ... How would I best overcome [static]?</code></p>\n\n<p>A way to drop the <code>static</code> context is to have your top-level java class implement the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html\" rel=\"nofollow noreferrer\">Runnable</a> interface and launch a new thread. From this point, you can have any number of classes you like. In the example, my <code>Matrix</code> has no concept of how to run. The <code>MatrixRunner</code> assumes that responsibility. Since the runner is the direct link to the <code>main</code> method it eats the <code>static context</code> and allows any further coding to be static free.</p>\n\n<p><code>8. ... where would printMatrix() be ... where would transpose be implemented</code></p>\n\n<p>Since the actions involve a matrix object, it should be encapsulated within the class. In my example, I chose to allow the override of <code>.toString()</code> represent my <code>print</code> function. Thus, you would just call whatever variation of <code>System.out.print</code> you like on some instantiated <code>Matrix</code> object. Similarly, <code>transpose</code> is a action on a matrix; actions are represented as methods, thus transpose becomes a method within the matrix class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T11:43:36.943", "Id": "53317", "Score": "0", "body": "How does the toString() method get called? I don't see any explicit reference to it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T18:21:16.910", "Id": "53329", "Score": "1", "body": "It gets called \"behind the scenes\" by the print statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T20:29:07.150", "Id": "53336", "Score": "0", "body": "+1 because it's useful. I've seen this with a paint() method in another program. How can I know which methods operate this way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T07:06:35.697", "Id": "53366", "Score": "1", "body": "toString(), equals(), and hashCode() are the three primary methods that come to mind" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:40:08.610", "Id": "33259", "ParentId": "33245", "Score": "2" } } ]
{ "AcceptedAnswerId": "33257", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T18:44:16.540", "Id": "33245", "Score": "0", "Tags": [ "java", "static" ], "Title": "How to overcome static referencing errors in Java/basic programming?" }
33245
<p>I plan on including this work in a portfolio. </p> <p>Will this code get me hired or laughed at?</p> <p>More specifically:</p> <ol> <li>How would you rate the general complexity of the code?</li> <li>How bad does the code smell?</li> <li>Is the VC too fat?</li> <li>Glaring best practices mistakes?</li> </ol> <p>Follow-up questions:</p> <ol> <li><p>Can you expand on what you said about magic numbers? (Totally missed the bool/BOOL usually I'm better than that. The names w/2 are just temp renames for SO)</p></li> <li><p>I have a lot of .h files because I tried to refactor somethings, like animation and URL methods, into helpers, presumably to increase readability. Did I go overboard?</p></li> <li><p>In theory, the way the program is setup, the MasterVC should never be deallocated. VC's are just pushed on top, not more than one layer at a time. Is it still necessary to unsubscribe from notifications?</p></li> <li><p>Lastly, on a scale of 1-10 what is your impression of the code overall? (from what you've seen and discounting the name and bool problem) </p></li> </ol> <p><strong>Details:</strong></p> <ul> <li>iOS: 6 (updating to 7 currently) </li> <li>Xcode: 4.6</li> <li>Tested: iPhone 4 device</li> <li>ARC Enabled</li> </ul> <h2>MasterViewController.h</h2> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "SRAPI.h" #import "SRChoiceBox.h" #import "SRPostTopic.h" #import "SRDetailViewController.h" #import "SRCollapsibleCell.h" #import "SRAnimationHelper.h" #import "SROpenTokVideoHandler.h" #import "SRObserveViewController.h" @interface SRMasterViewController2 : UIViewController &lt;UITableViewDelegate, UITableViewDataSource, SRChoiceBoxDelegate, SRPostTopicDelegate&gt; @property (weak, nonatomic) IBOutlet UITableView *topicsTableView; @property (weak, nonatomic) IBOutlet UIView *postTopicContainer; @property (weak, nonatomic) IBOutlet UILabel *statusLabel; @property (strong, nonatomic) NSIndexPath *openCellIndex; @property (strong, nonatomic) RKPaginator *paginator; @property (strong, nonatomic) SROpenTokVideoHandler *openTokHandler; @end </code></pre> <h2>MasterViewController.m</h2> <pre><code>#import "SRMasterViewController2.h" #import "UIScrollView+SVPullToRefresh.h" #import "UIScrollView+SVInfiniteScrolling.h" #import "SRUrlHelper.h" #import "SRNavBarHelper.h" @interface SRMasterViewController2 () @property NSInteger offset; @property NSInteger totalPages; @property NSMutableArray *topicsArray; @property bool isPaginatorLoading; @end @implementation SRMasterViewController2 - (void)viewDidLoad { [super viewDidLoad]; [self configureTableView]; [self configureNavBar]; [self configurePostTopicContainer]; [SRAPI sharedInstance]; [self paginate]; self.openTokHandler = [SROpenTokVideoHandler new]; [self configureNotifications]; } - (void)configureNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotifications:) name:kFetchNewTopicsAndReloadTableData object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotifications:) name:kFetchRoomFromUrl object:nil]; } - (void)receiveNotifications:(NSNotification *)notificaiton { if ([notificaiton.name isEqualToString:kFetchRoomFromUrl]) { NSURL *url = notificaiton.userInfo[@"url"]; [self fetchRoomWithUrl:url]; } else if ([notificaiton.name isEqualToString:kFetchNewTopicsAndReloadTableData]) { self.offset = 1; [self.topicsTableView.infiniteScrollingView startAnimating]; [self paginate]; } } - (void)fetchRoomWithUrl:(NSURL *)url { NSDictionary *dict = [SRUrlHelper parseQueryString:[url query]]; SRRoom *room = [[SRRoom alloc] init]; room.position = (NSString *)[url pathComponents][3]; room.topicId = [url pathComponents][2]; room.sessionId = dict[@"sessionID"]; [self performSegueWithIdentifier:@"showDetail2" sender:room]; } - (void)configureNavBar { //Button displays container for posting topics UIBarButtonItem *rightPostTopicButton = [SRNavBarHelper buttonForNavBarWithImage:[UIImage imageNamed:@"logo"] highlightedImage:nil selector:@selector(showPostTopicContainer) target:self]; self.navigationItem.rightBarButtonItem = rightPostTopicButton; //suffle button - Joins random room UIBarButtonItem *leftShuffleButton = [SRNavBarHelper buttonForNavBarWithImage:[UIImage imageNamed:@"shuffle.png"] highlightedImage:[UIImage imageNamed:@"shufflePressed.png"] selector:@selector(joinRandomRoom) target:self]; self.navigationItem.leftBarButtonItem = leftShuffleButton; } - (void)joinRandomRoom { NSMutableArray *activeTopics = [NSMutableArray new]; SRTopic *randomTopic = [SRTopic new]; SRRoom *randomRoom = [SRRoom new]; //find topics with people in them for (SRTopic *topic in self.topicsArray) { if ([topic.agreeDebaters integerValue] &gt; 0 || [topic.disagreeDebaters integerValue] &gt; 0) { [activeTopics addObject:topic]; } } int numberOfActiveTopics = activeTopics.count; if (numberOfActiveTopics &gt; 0) { //Put user into a random Active Room int random = arc4random() % numberOfActiveTopics; randomTopic = (SRTopic *)activeTopics[random]; if (randomTopic.agreeDebaters.intValue &gt; randomTopic.disagreeDebaters.intValue) { randomRoom.position = @"disagree"; } else if (randomTopic.agreeDebaters.intValue &lt; randomTopic.disagreeDebaters.intValue) { randomRoom.position = @"agree"; } else { randomRoom.position = [self randomlyChooseAgreeDisagree]; } } else { //No Active Rooms, put user in a random room int random = arc4random() % self.topicsArray.count; randomTopic = (SRTopic *)self.topicsArray[random]; randomRoom.position = [self randomlyChooseAgreeDisagree]; } randomRoom.topicId = randomTopic.topicId; [self performSegueWithIdentifier:@"showDetail2" sender:randomRoom]; } - (NSString *)randomlyChooseAgreeDisagree { int r = arc4random() % 2; return (r == 0) ? @"agree" : @"disagree"; } - (void)configureTableView { //set offset for loading tabledata self.offset = 1; //add pull to refresh controls UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; [refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged]; [self.topicsTableView addSubview:refreshControl]; //add infinite scrolling [self addInfiniteScrolling:self.topicsTableView]; //close all cells self.openCellIndex = nil; //Smooth scrolling self.topicsTableView.layer.shouldRasterize = YES; self.topicsTableView.layer.rasterizationScale = [[UIScreen mainScreen] scale]; } - (void)configurePostTopicContainer { //configure container for posting topics SRPostTopic *postTopic = [[SRPostTopic alloc]initWithFrame:CGRectMake(0, 0, 320, 133)]; [self.postTopicContainer addSubview:postTopic]; postTopic.delegate = self; } - (void)addInfiniteScrolling:(UITableView *)tableView { [tableView addInfiniteScrollingWithActionHandler: ^(void) { self.offset += 1; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self paginate]; double delayInSeconds = 0.8; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void) { [self.topicsTableView.infiniteScrollingView stopAnimating]; }); }); }]; //configure infinite scrolling style self.topicsTableView.infiniteScrollingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge; } - (void)refresh:(UIRefreshControl *)refreshControl { self.offset = 1; self.openCellIndex = nil; //stop refresh after successful AJAX call for topics dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self paginate]; double delayInSeconds = 1; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void) { [refreshControl endRefreshing]; }); }); } - (void)paginate { // Create weak reference to self to use within the paginators completion block __weak typeof(self) weakSelf = self; // Setup paginator if (!self.paginator) { self.paginator.perPage = 20; NSString *requestString = [NSString stringWithFormat:@"?page=:currentPage&amp;per_page=:perPage"]; self.paginator = [[RKObjectManager sharedManager] paginatorWithPathPattern:requestString]; [self.paginator setCompletionBlockWithSuccess: ^(RKPaginator *paginator, NSArray *objects, NSUInteger page) { NSMutableArray *topicsArrayTemp = [objects mutableCopy]; weakSelf.isPaginatorLoading = NO; if (weakSelf.offset == 1) { [weakSelf replaceRowsInTableView:topicsArrayTemp]; } else { [weakSelf insertRowsInTableView:topicsArrayTemp]; } [weakSelf.topicsTableView.infiniteScrollingView stopAnimating]; } failure: ^(RKPaginator *paginator, NSError *error) { weakSelf.isPaginatorLoading = NO; [weakSelf.topicsTableView.infiniteScrollingView stopAnimating]; [weakSelf.self noResults]; }]; } if (!weakSelf.isPaginatorLoading) { weakSelf.isPaginatorLoading = YES; [self.paginator loadPage:self.offset]; } } - (void)noResults { double delayInSeconds = 0.6; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void) { [self performSegueWithIdentifier:@"noResults" sender:nil]; }); } #pragma mark - Posting a new topic //open/close container for posting topics - (void)showPostTopicContainer { [self.view endEditing:YES]; CGRect newTableViewFrame = self.topicsTableView.frame; CGRect newPostTopicFrame = self.postTopicContainer.frame; float duration, alpha; if ([self isPostTopicContainerOpen]) { newTableViewFrame.origin.y -= 133; newPostTopicFrame.origin.y -= 133; duration = .3; alpha = 0; } else { newTableViewFrame.origin.y += 133; newPostTopicFrame.origin.y += 133; duration = .4; alpha = 1; } [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations: ^{ self.postTopicContainer.alpha = alpha; self.topicsTableView.frame = newTableViewFrame; self.postTopicContainer.frame = newPostTopicFrame; } completion:nil]; } - (BOOL)isPostTopicContainerOpen { return (self.postTopicContainer.frame.origin.y &lt; 0) ? NO : YES; } //update fading status UILabel at the bottom of the screen - (void)statusUpdate:(NSString *)message { self.statusLabel.text = message; [self.statusLabel.layer addAnimation:[SRAnimationHelper fadeOfSRMasterViewStatusLabel] forKey:nil]; } //Post a new Topic to the Server - (void)postTopicButtonPressed:(NSString *)contents { //set up params NSDictionary *newTopic = @{ @"topic":contents }; //send new topic posting [[RKObjectManager sharedManager] postObject:nil path:@"topics/new" parameters:newTopic success: ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { if ([self isPostTopicContainerOpen]) { //close post box if it's open [self showPostTopicContainer]; } [self statusUpdate:@"Topic Posted!"]; } failure: ^(RKObjectRequestOperation *operation, NSError *error) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops" message:@"We weren't able to post your shout. Try again soon!" delegate:nil cancelButtonTitle:@"Sure" otherButtonTitles:nil, nil]; [alert show]; }]; } //Delegate for SRChoiceBox - user chooses Agree/Disagree/Observe - (void)positionWasChoosen:(NSString *)choice topicId:(NSNumber *)topicId { SRRoom *room = [[SRRoom alloc] init]; room.position = choice; room.topicId = topicId; if ([choice isEqualToString:@"observe"]) { [self performSegueWithIdentifier:@"showObserve" sender:room]; } else { [self performSegueWithIdentifier:@"showDetail2" sender:room]; } } - (void)segueToRoomWithTopicID:(NSNumber *)topicId andPosition:(NSString *)choice { SRRoom *room = [[SRRoom alloc] init]; room.position = choice; room.topicId = topicId; if ([choice isEqualToString:@"observe"]) { [self performSegueWithIdentifier:@"showObserve" sender:room]; } else { [self performSegueWithIdentifier:@"delete" sender:nil]; } } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { //close Post Topic Container if ([self isPostTopicContainerOpen]) { [self showPostTopicContainer]; } if ([[segue identifier] isEqualToString:@"showDetail2"] || [[segue identifier] isEqualToString:@"showObserve"]) { if (self.openTokHandler) { [self.openTokHandler safetlyCloseSession]; } [[segue destinationViewController] setOpenTokHandler:self.openTokHandler]; [[segue destinationViewController] setRoom:sender]; } sender = nil; } #pragma mark - UITABLEVIEW - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.topicsArray count]; } - (void)insertRowsInTableView:(NSMutableArray *)topics { if (topics.count &lt; 1) { [self noNewResults]; return; } NSMutableArray *temp = [NSMutableArray new]; int lastRowNumber = [self.topicsTableView numberOfRowsInSection:0] - 1; for (SRTopic *topic in topics) { if (![self.topicsArray containsObject:topic]) { [self.topicsArray addObject:topic]; NSIndexPath *ip = [NSIndexPath indexPathForRow:lastRowNumber inSection:0]; [temp addObject:ip]; ++lastRowNumber; } } [self.topicsTableView beginUpdates]; [self.topicsTableView insertRowsAtIndexPaths:temp withRowAnimation:UITableViewRowAnimationTop]; [self.topicsTableView endUpdates]; if (temp.count == 0) { [self noNewResults]; } } - (void)noNewResults { int lastRowNumber = [self.topicsTableView numberOfRowsInSection:0] - 1; [self statusUpdate:@"No New Topics. Check Back Soon!"]; [self.topicsTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:lastRowNumber - 6 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; self.offset--; } - (void)replaceRowsInTableView:(NSMutableArray *)topics { self.topicsArray = topics; [UIView animateWithDuration:.3 delay:.5 options:UIViewAnimationOptionCurveEaseInOut animations: ^{ self.topicsTableView.layer.opacity = 0; } completion: ^(BOOL finished) { self.topicsTableView.layer.opacity = 1; [[self.topicsTableView layer] addAnimation:[SRAnimationHelper tableViewReloadDataAnimation] forKey:@"UITableViewReloadDataAnimationKey"]; [self.topicsTableView reloadData]; }]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *CellIdentifier2 = @"SRCollapsibleCellClosed"; SRCollapsibleCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2]; if (cell == nil) { cell = [[SRCollapsibleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]; } SRTopic *topic = [self.topicsArray objectAtIndex:indexPath.row]; [cell updateWithTopic:topic]; if ([self isCellOpen:indexPath]) { CGAffineTransform transformation = CGAffineTransformMakeRotation(M_PI / 2); cell.arrow.transform = transformation; if (![self hasChoiceBox:cell]) { [self insertChoiceBox:cell atIndex:indexPath]; } } else { CGAffineTransform transformation = CGAffineTransformMakeRotation(0); cell.arrow.transform = transformation; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if ([self isCellOpen:indexPath]) { [self closeCellAtIndexPath:indexPath]; } else { NSIndexPath *openCell = self.openCellIndex; NSIndexPath *newOpenCell = indexPath; [self closeCellAtIndexPath:openCell]; [self openCellAtIndexPath:newOpenCell]; } [tableView beginUpdates]; [tableView endUpdates]; [tableView deselectRowAtIndexPath:indexPath animated:NO]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if ([indexPath isEqual:self.openCellIndex]) { return 217.0; } else { return 63.0; } } - (void)rotateCellArrowAtIndexPath:(NSIndexPath *)indexPath willOpen:(bool)willOpen animated:(bool)animated { // Change Arrow orientation SRCollapsibleCell *cell = (SRCollapsibleCell *)[self.topicsTableView cellForRowAtIndexPath:indexPath]; CGAffineTransform transformation; if (willOpen) { transformation = CGAffineTransformMakeRotation(M_PI / 2); } else { transformation = CGAffineTransformMakeRotation(0); } if (animated) { [UIView animateWithDuration:.2 delay:0 options:UIViewAnimationOptionCurveLinear animations: ^{ cell.arrow.transform = transformation; } completion:nil]; } else { cell.arrow.transform = transformation; } } - (BOOL)isCellOpen:(NSIndexPath *)indexPath { return [indexPath isEqual:self.openCellIndex]; } - (void)closeCellAtIndexPath:(NSIndexPath *)indexPath { [self rotateCellArrowAtIndexPath:indexPath willOpen:NO animated:YES]; [self removeSRChoiceBoxFromCellAtIndexPath:indexPath]; self.openCellIndex = nil; } - (void)openCellAtIndexPath:(NSIndexPath *)indexPath { [self rotateCellArrowAtIndexPath:indexPath willOpen:YES animated:YES]; SRCollapsibleCell *cell = (SRCollapsibleCell *)[self.topicsTableView cellForRowAtIndexPath:indexPath]; [self insertChoiceBox:cell atIndex:indexPath]; self.openCellIndex = indexPath; } - (void)removeSRChoiceBoxFromCellAtIndexPath:(NSIndexPath *)indexPath { SRCollapsibleCell *cell = (SRCollapsibleCell *)[self.topicsTableView cellForRowAtIndexPath:indexPath]; for (id subview in cell.SRCollapsibleCellContent.subviews) { if ([subview isKindOfClass:[SRChoiceBox class]]) { [subview removeFromSuperview]; } } } - (void)insertChoiceBox:(SRCollapsibleCell *)cell atIndex:(NSIndexPath *)indexPath { SRChoiceBox *newBox = [[SRChoiceBox alloc] initWithFrame:CGRectMake(0, 0, 310, 141)]; SRTopic *topic = [self.topicsArray objectAtIndex:indexPath.row]; [newBox updateWithSRTopic:topic]; newBox.delegate = self; [cell.SRCollapsibleCellContent addSubview:newBox]; } - (bool)hasChoiceBox:(SRCollapsibleCell *)cell { for (UIView *subview in cell.SRCollapsibleCellContent.subviews) { if ([subview isKindOfClass:[SRChoiceBox class]]) { return true; } } return false; } @end </code></pre>
[]
[ { "body": "<p>A few things I would ask if I saw this as an interviewer (from a very quick read, and obviously not having seen it run):</p>\n\n<ul>\n<li>why use a UIViewController and not a UITableViewController (refresh control property is free then)</li>\n<li>the rasterisation on table view shouldn't be needed for smooth scrolling, you have other problems if that is required</li>\n<li>there are a few things which I wouldn't like to see and would ask about: magic numbers, names with a 2 at the end, inconsistencies (bool vs BOOL etc)</li>\n<li>why all the imports in the .h?</li>\n<li>why aren't the notification observers removed?</li>\n</ul>\n\n<p>Follow-up responses:</p>\n\n<ol>\n<li>makes sense</li>\n<li>was just more about practice of importing .h files in a .h (meaning any class that needs to import your class knows about all those imported classes)</li>\n<li>It's just good practice I guess, but I didn't realise this was a permanent view controller </li>\n<li>Overall impressions are good (would depend a bit on the level of developer the job is for): the code is reasonably complex, uses 3rd party libraries, has some fairly advanced functions like dealing with layers / transforms. </li>\n</ol>\n\n<p>The real test though would be how well you can explain it during the interview, e.g. if you sound like its just a cut and paste job then the impression is lessened, but if you can explain your choices, pitfalls of the approach, anything you tried which you discard and why, and are able to talk about what you have learnt and where you would make improvements next time then you'd be looking pretty good I think. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T10:21:37.160", "Id": "33382", "ParentId": "33247", "Score": "4" } }, { "body": "<p>First let me say up front that this code looks quite good compared to a lot of code I've been asked to maintain, so you have nothing to be ashamed of here. I'll make a few more suggestions beyond the ones wattson12 offered, but you should view these as ways to make your good code incrementally better.</p>\n\n<p><strong>viewDidLoad</strong></p>\n\n<p>First, a technical point. You should be aware that this code may not work the way you expect, especially if it needs to run on iOS 5. It's a common mistake to assume that viewDidLoad will only get called once. In fact, viewDidLoad can get called many times in the life of a view controller. If the view controller receives a memory warning when its view isn't visible, the default behavior up until iOS 6 was to unload its view hierarchy and set self.view to nil. The next time self.view gets accessed after that, it gets lazy-loaded from the NIB again, and viewDidLoad gets called again. This can lead to some tricky bugs if your code isn't designed to handle it. For example, your implementation of viewDidLoad re-adds your notification handlers. This will cause them to get called twice when their notifications are posted.</p>\n\n<p>Since iOS 6 the risk is greatly reduced because self.view isn't set to nil by default in response to memory warnings, but you may decide to do so manually at some point as an optimization, so I'd still consider designing your viewDidLoad to leave your object in a valid state if it gets called multiple times. If nothing else, you should be prepared to explain to an old-school iOS developer in an interview why your code should be safe in iOS 6. Review <a href=\"https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10-SW1\" rel=\"nofollow\">Resource Management in View Controllers</a> in the View Controller Programming Guide.</p>\n\n<p>Now then, on to code smells. </p>\n\n<p><strong>Comments</strong></p>\n\n<p>The main code smell that jumps out at me here is, believe it or not, the comments. Whenever you feel the urge to add a comment, you should stop and ask yourself a couple of questions:</p>\n\n<ol>\n<li>Could I make this comment unnecessary by extracting a block of code out into a method?</li>\n<li>Could I make this comment unnecessary by renaming my methods to something more descriptive?</li>\n</ol>\n\n<p>For example, applying just this one principle to the comments in <code>-joinRandomRoom</code> would turn this:</p>\n\n<pre><code>- (void)joinRandomRoom {\n NSMutableArray *activeTopics = [NSMutableArray new];\n SRTopic *randomTopic = [SRTopic new];\n SRRoom *randomRoom = [SRRoom new];\n\n //find topics with people in them\n for (SRTopic *topic in self.topicsArray) {\n if ([topic.agreeDebaters integerValue] &gt; 0 || [topic.disagreeDebaters integerValue] &gt; 0) {\n [activeTopics addObject:topic];\n }\n }\n int numberOfActiveTopics = activeTopics.count;\n\n if (numberOfActiveTopics &gt; 0) {\n //Put user into a random Active Room\n int random = arc4random() % numberOfActiveTopics;\n randomTopic = (SRTopic *)activeTopics[random];\n if (randomTopic.agreeDebaters.intValue &gt; randomTopic.disagreeDebaters.intValue) {\n randomRoom.position = @\"disagree\";\n }\n else if (randomTopic.agreeDebaters.intValue &lt; randomTopic.disagreeDebaters.intValue) {\n randomRoom.position = @\"agree\";\n }\n else {\n randomRoom.position = [self randomlyChooseAgreeDisagree];\n }\n }\n else {\n //No Active Rooms, put user in a random room\n int random = arc4random() % self.topicsArray.count;\n randomTopic = (SRTopic *)self.topicsArray[random];\n randomRoom.position = [self randomlyChooseAgreeDisagree];\n }\n randomRoom.topicId = randomTopic.topicId;\n [self performSegueWithIdentifier:@\"showDetail2\" sender:randomRoom];\n}\n</code></pre>\n\n<p>... into this:</p>\n\n<pre><code>- (void)joinRandomRoom {\n SRRoom *randomRoom;\n\n //find topics with people in them\n NSMutableArray *activeTopics = [self activeTopicsWithPeopleInThem];\n int numberOfActiveTopics = activeTopics.count\n\n if (numberOfActiveTopics &gt; 0) {\n //Put user into a random Active Room\n randomRoom = [self activeRandomRoom];\n }\n else {\n //No Active Rooms, put user in a random room\n randomRoom = [self anyRandomRoom];\n }\n\n [self performSegueWithIdentifier:@\"showDetail2\" sender:randomRoom];\n}\n</code></pre>\n\n<p>Note that the method names are expressive enough that the comments are now redundant, so I can remove them:</p>\n\n<pre><code>- (void)joinRandomRoom {\n SRRoom *randomRoom;\n\n NSMutableArray *activeTopics = [self activeTopicsWithPeopleInThem];\n int numberOfActiveTopics = activeTopics.count\n\n if (numberOfActiveTopics &gt; 0) {\n randomRoom = [self activeRandomRoom];\n }\n else {\n randomRoom = [self anyRandomRoom];\n }\n\n [self performSegueWithIdentifier:@\"showDetail2\" sender:randomRoom];\n}\n</code></pre>\n\n<p>It's already much easier to tell at a glance what this method is doing, but I'd personally continue refactoring to this:</p>\n\n<pre><code>- (void)joinRandomRoom {\n SRRoom *randomRoom;\n\n if ([self numberOfActiveTopics] &gt; 0) {\n randomRoom = [self activeRandomRoom];\n }\n else {\n randomRoom = [self anyRandomRoom];\n }\n [self performSegueWithIdentifier:@\"showDetail2\" sender:randomRoom];\n}\n</code></pre>\n\n<p>and ultimately to this:</p>\n\n<pre><code>- (void)joinRandomRoom {\n [self performSegueWithIdentifier:kSegueIdentifierShowDetail2\n sender:[self randomRoom]];\n}\n</code></pre>\n\n<p>It's almost always possible to refactor your code into a form that documents itself expressively enough that your comments add no value and can therefore be removed. When you're done, your methods will almost read like pseudocode.</p>\n\n<p>BTW, you'll notice your classes filling up with lots of little private methods. Don't fret. That's generally preferable to a handful of large methods, but if all the little private methods start to feel overwhelming, that's a code smell of its own. It suggests that some of your methods may belong on other classes. Move each method its most appropriate class. Don't be afraid to invent new classes, but also consider using Objective-C categories as convenient home for your stateless methods.</p>\n\n<p><strong>#pragma mark</strong></p>\n\n<p>My next suggestion is to come up with some convention for your #pragma mark statements, and then apply it with consistency and discipline. It really helps to know exactly where to put each method, and where you can go to find it later. </p>\n\n<p>My personal convention is to put \"Constructors\" at the top and \"Private\" methods at the bottom for quick access. Above my private methods I have special sections for \"Notification handlers\", \"Actions\", \"Dynamic properties\", and \"Public\". Then above those I put all my protocol implementations and overridden methods in sections named after the place they were originally declared. So I would organize your file like this:</p>\n\n<pre><code>@implementation SRMasterViewController2\n\n#pragma mark UIViewController\n- (void)viewDidLoad {}\n- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {}\n\n#pragma mark &lt;UITableViewDataSource&gt;\n- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {}\n- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {}\n- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {}\n- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {}\n\n#pragma mark &lt;UITableViewDelegate&gt;\n- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {}\n\n#pragma mark &lt;SRPostTopicDelegate&gt;\n- (void)postTopicButtonPressed:(NSString *)contents {}\n- (void)positionWasChoosen:(NSString *)choice topicId:(NSNumber *)topicId {}\n- (void)segueToRoomWithTopicID:(NSNumber *)topicId andPosition:(NSString *)choice {}\n\n#pragma mark Notification handlers\n- (void)receiveNotifications:(NSNotification *)notificaiton {}\n\n#pragma mark Actions\n- (void)showPostTopicContainer {}\n- (void)joinRandomRoom {}\n- (void)refresh:(UIRefreshControl *)refreshControl {}\n\n#pragma mark Private\n- (void)configureNotifications {}\n- (void)fetchRoomWithUrl:(NSURL *)url {}\n- (void)configureNavBar {}\n- (NSString *)randomlyChooseAgreeDisagree {}\n- (void)configureTableView {}\n- (void)configurePostTopicContainer {}\n- (void)addInfiniteScrolling:(UITableView *)tableView {}\n- (void)paginate {}\n- (void)noResults {}\n- (BOOL)isPostTopicContainerOpen {}\n- (void)statusUpdate:(NSString *)message {}\n- (void)insertRowsInTableView:(NSMutableArray *)topics {}\n- (void)noNewResults {}\n- (void)replaceRowsInTableView:(NSMutableArray *)topics {}\n- (void)rotateCellArrowAtIndexPath:(NSIndexPath *)indexPath willOpen:(bool)willOpen animated:(bool)animated {}\n- (BOOL)isCellOpen:(NSIndexPath *)indexPath {}\n- (void)closeCellAtIndexPath:(NSIndexPath *)indexPath {}\n- (void)openCellAtIndexPath:(NSIndexPath *)indexPath {}\n- (void)removeSRChoiceBoxFromCellAtIndexPath:(NSIndexPath *)indexPath {}\n- (void)insertChoiceBox:(SRCollapsibleCell *)cell atIndex:(NSIndexPath *)indexPath {}\n- (bool)hasChoiceBox:(SRCollapsibleCell *)cell {}\n\n@end\n</code></pre>\n\n<p>It doesn't matter if you adopt my convention, but choose some convention and apply it with discipline.</p>\n\n<p><strong>A couple more random suggestions:</strong></p>\n\n<ul>\n<li><p>Don't use a single <code>receiveNotifications:</code> handler with a big if-then inside it. Instead handle each notification using its own well-named method like didFetchNewTopicsAndReloadTableDataNotification: and didFetchRoomFromUrlNotification:. Much simpler.</p></li>\n<li><p>Rather than registering <code>joinRandomRoom</code> as the selector for the shuffle button press, register a method named something like <code>shuffleButtonPressed:</code>. That way when you need to change that behavior later a quick search for \"shuffleButton\" or \"Pressed\" will you bring you quickly to the right method. Much easier than tracing your way back to joinRandomRoom through the <code>@selector(joinRandomRoom)</code> parameter passed to the <code>SRNavBarHelper</code> class method.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T07:35:07.730", "Id": "33903", "ParentId": "33247", "Score": "1" } } ]
{ "AcceptedAnswerId": "33382", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:22:40.940", "Id": "33247", "Score": "4", "Tags": [ "objective-c", "interview-questions", "ios" ], "Title": "MasterViewController" }
33247
<p>I'm open to any comments on this code/approach. This is mostly architecture and threading.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.ServiceModel; using System.ServiceProcess; using System.Configuration; using System.Configuration.Install; using System.Runtime.Serialization; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Security.Permissions; using System.Diagnostics; using System.Timers; namespace Mobwt.MessageService { [ServiceContract] public interface IStepMessageCallback { [OperationContract] void Callback(StepMessage message); [OperationContract] List&lt;StepMessage&gt; GetMessages(string JobId, bool unreadonly); // TODO: Add your service operations here } public class StepMessageCallback : IStepMessageCallback { [PrincipalPermission(SecurityAction.Demand, Role = "mobwta_admin")] public void Callback(StepMessage message) { if (message != null) { DataManager.AddMessage(message); //using (MessageContext db = new MessageContext()) //{ // message.FlashRead = false; // db.Messages.Add(message); // db.SaveChanges(); //} } } [PrincipalPermission(SecurityAction.Demand, Role = "mobwta_admin")] public List&lt;StepMessage&gt; GetMessages(string JobId, bool unreadonly = true) { return DataManager.ReadMessages(JobId, unreadonly); //List&lt;StepMessage&gt; msgs = null; //using (MessageContext db = new MessageContext()) //{ // var msgqry = db.Messages.Where(m =&gt; unreadonly ? !m.FlashRead &amp;&amp; m.JobId == JobId : m.JobId == JobId).Take(10); // msgs = msgqry.ToList(); // foreach (var m in msgqry) // m.FlashRead = true; // db.SaveChanges(); //} //return msgs; } } public static class DataManager { static object lockobj = new object(); static int deadcount = 0; static int deadreadcount = 0; static Timer _saveTimer; static Timer _readTimer; static List&lt;StepMessage&gt; messages; static List&lt;StepMessage&gt; Messages { get { if (messages == null) { lock (lockobj) { if (messages == null) messages = new List&lt;StepMessage&gt;(); } } return messages; } } static MessageContext saveContext; static MessageContext SaveContext { get { if (saveContext == null) { saveContext = new MessageContext(); } return saveContext; } } static MessageContext readContext; static MessageContext ReadContext { get { if (readContext == null) { lock (lockobj) { if (readContext == null) { readContext = new MessageContext(); deadreadcount = 0; if (_readTimer == null) InitializeReadTimer(); } } } return readContext; } } static void _timer_Elapsed(object sender, ElapsedEventArgs e) { if (Messages.Count &gt; 0) { try { List&lt;StepMessage&gt; cMsgs; lock (lockobj) { cMsgs = Messages.ToList(); Messages.Clear(); } SaveContext.Messages.AddRange(cMsgs); SaveContext.SaveChanges(); deadcount = 0; } catch (Exception ex) { } } else { deadcount++; if (deadcount &gt; 20) { DisposeTimer(_saveTimer); DisposeContext(); deadcount = 0; } } } private static void DisposeContext() { SaveContext.Dispose(); saveContext = null; } private static void DisposeTimer(Timer timer) { if (timer != null) { if (timer.Enabled) timer.Stop(); timer.Dispose(); timer = null; } } public static bool AddMessage(StepMessage message) { try { if (_saveTimer == null) InitializeSaveTimer(); lock (lockobj) { Messages.Add(message); } return true; } catch { return false; } } public static List&lt;StepMessage&gt; ReadMessages(string jobid, bool unreadonly) { deadreadcount = 0; List&lt;StepMessage&gt; msgs = null; try { lock (lockobj) { var msgqry = ReadContext.Messages.Where(m =&gt; unreadonly ? !m.FlashRead &amp;&amp; m.JobId == jobid : m.JobId == jobid).Take(10); if (msgqry.Count() &gt; 0) { msgs = msgqry.ToList(); foreach (var m in msgqry) m.FlashRead = true; ReadContext.SaveChanges(); } } } catch (Exception ex) { } return msgs; } private static void InitializeReadTimer() { _readTimer = new Timer(500); _readTimer.Elapsed += _readTimer_Elapsed; _readTimer.Start(); } static void _readTimer_Elapsed(object sender, ElapsedEventArgs e) { deadreadcount++; if (deadreadcount &gt; 20 &amp;&amp; readContext != null) { DisposeTimer(_readTimer); readContext.Dispose(); readContext = null; } } private static void InitializeSaveTimer() { _saveTimer = new Timer(500); _saveTimer.Elapsed += _timer_Elapsed; _saveTimer.Start(); } } [DataContract] public enum ProgressState { [EnumMember] Running, [EnumMember] Idle, [EnumMember] Success, [EnumMember] Failed, [EnumMember] Error } [DataContract] public class StepMessage { [DataMember] [Key] public int StepMessageID { get; set; } [DataMember] public string StepId { get; set; } [DataMember] public string JobId { get; set; } [DataMember] public string StepName { get; set; } [DataMember] public string Message { get; set; } [DataMember] public int Progress { get; set; } [DataMember] public ProgressState JobState { get; set; } [DataMember] public ProgressState StepState { get; set; } [DataMember] public DateTime StepStart { get; set; } [DataMember] public DateTime StepEnd { get; set; } [DataMember] public DateTime JobStart { get; set; } [DataMember] public DateTime JobEnd { get; set; } [DataMember] public DateTime TimeStamp { get; set; } [DataMember] public bool FlashRead { get; set; } } public class MessageContext : DbContext { public MessageContext() : base("MobileBilling") { } public DbSet&lt;StepMessage&gt; Messages { get; set; } } public class MessageService : ServiceBase { public ServiceHost host = null; public MessageService() { ServiceName = ConfigurationManager.AppSettings["ServiceName"]; } public static void Main() { ServiceBase.Run(new MessageService()); } protected override void OnStart(string[] args) { if (host != null) host.Close(); host = new ServiceHost(typeof(StepMessageCallback)); host.Open(); } protected override void OnStop() { if (host != null) { host.Close(); host = null; } } } [RunInstaller(true)] public class ProjectInstaller : Installer { private ServiceProcessInstaller proc; private ServiceInstaller svc; public ProjectInstaller() { proc = new ServiceProcessInstaller(); proc.Account = ServiceAccount.LocalSystem; svc = new ServiceInstaller(); svc.ServiceName = ConfigurationManager.AppSettings["ServiceName"]; Installers.Add(proc); Installers.Add(svc); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:43:04.637", "Id": "53257", "Score": "2", "body": "it is unclear what you want us to review, if you would like an overall review please state this in the question please. Code-Only Questions are frowned upon, on Stack Exchange sites." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:14:18.217", "Id": "53262", "Score": "0", "body": "sorry, I had a feeling this site was more informal than so but I'm sure that even here there are standards. thx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:17:06.483", "Id": "53263", "Score": "0", "body": "thank you, remember that the longer the code snippet you give us to review the longer it might take for reviews. it is okay to post several questions with shorter code snippets, you can even add links to the other questions, we don't mind that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:00:50.517", "Id": "53266", "Score": "0", "body": "So many namespaces … Maybe you should split this into multiple files? Or is that just for posting here?" } ]
[ { "body": "<ol>\n<li><p>Your double checked lock implementation for <code>messages</code> is subtly broken (the field should be volatile in order to create a memory barrier, this <a href=\"http://msdn.microsoft.com/en-us/library/ff650316.aspx\" rel=\"nofollow\">MSDN</a> explains it with singleton as example but it is valid for any other field as well). It's also completely unnecessary:</p>\n\n<pre><code>static List&lt;StepMessage&gt; messages = new List&lt;StepMessage&gt;();\n\nstatic List&lt;StepMessage&gt; Messages\n{\n get { return messages; }\n}\n</code></pre>\n\n<p>Less code, less clever (clever is bad) and thread safe.</p></li>\n<li>Some goes for your <code>readContext</code> except that you can't do the static init as it's destroyed occasionally. I'd stick to a simple lock unless it's proven to be a performance problem.</li>\n<li><code>deadreadcount++</code> is not atomic. You do that a timer callback while assigning it in <code>ReadMessage</code> which can lead to the assignment of 0 being overwritten. Use Interlocked* methods to increment/decrement shared counters.</li>\n<li>You swallow exceptions in many places. This is usually bad because the caller will have no idea that something went wrong when it does. I sincerely hope that you at least log them.</li>\n<li>Returning <code>null</code> from a method (<code>ReadMessages</code>) which returns a collection is a pain in the butt as the caller as to specifically check for that. Returning an empty list is much nicer from a service consumer point of view.</li>\n<li>It is not obvious from your code why <code>lockobj</code> protects both <code>Messages</code> and <code>readContext</code>.</li>\n<li>In <code>_readTimer_Elapsed</code> you dispose of the read context while potentially accessing it in <code>ReadMessage</code>. The end result will be that the caller of <code>ReadMessage</code> will not get any result. It also means that <code>ReadMessage</code> was called in about 10sec intervals so I guess it doesn't matter that much for your use case but it's still ugly. It's bound to cause weird problems in the future when the code is extended.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T23:40:24.800", "Id": "53347", "Score": "0", "body": "What is subtly broken about the singleton implementation? It's almost a verbatim copy of the *Multithreaded Singleton* implementation in the article you posted. [Note that `lock` is an implicit full memory barrier](http://www.albahari.com/threading/part4.aspx). On a related note, it might be useful to compare singleton implementations with [this answer](http://codereview.stackexchange.com/a/81/31266)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T07:42:03.513", "Id": "53369", "Score": "0", "body": "@ta.speot.is: Yes, \"almost\". If you read the linked article again you will find this \"Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T07:53:48.770", "Id": "53370", "Score": "0", "body": "You are correct." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T09:12:12.780", "Id": "33287", "ParentId": "33248", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:24:47.490", "Id": "33248", "Score": "1", "Tags": [ "c#", "wcf" ], "Title": "Simple WCF messaging system via EF" }
33248
<p>I need to use sockets from winsok2.h. So, I written a class NetObject to use it. But, when I do compilation I am getting an error:</p> <pre><code>error LNK2019: unresolved external symbol "public: int __thiscall wsa::NetObject::connect(void)" (?connect@NetObject@wsa@@QAEHXZ) referenced in function _main </code></pre> <p>I do this using Visual C++ compiler.</p> <p>Here is some code:</p> <pre><code>//wsa.h #ifndef WSA_H_ #define WSA_H_ #include &lt;winsock2.h&gt; namespace wsa { sockaddr_in init(const int, const char *, const int); sockaddr_in init(const int, const char *); SOCKET init(const int, const int, const int); class NetObject { private: SOCKET sock; sockaddr_in addr; int check(const int); public: NetObject ( const int addr_family, const int sock_type, const int protocol, const char * ip_addr, const int port ): sock(init(addr_family, sock_type, protocol)), addr(init(addr_family, ip_addr, port)) {}; int connect(); }; } #endif //WSA_H_ //wsa.cpp #include "wsa.h" #include &lt;winsock2.h&gt; namespace wsa { sockaddr_in init(const int af, const char * ip_addr) { sockaddr_in addr; memset(&amp;addr, 0, sizeof(addr)); addr.sin_family = af; addr.sin_addr.s_addr = inet_addr(ip_addr); return addr; } sockaddr_in init(const int af, const char * ip_addr, const int port) { sockaddr_in addr = init(af, ip_addr); addr.sin_port = htons(port); return addr; } SOCKET init ( const int af, const int type, const int protocol ) { SOCKET s; s = socket(af, type, protocol); while (s == INVALID_SOCKET) { if (closesocket(s) == SOCKET_ERROR) { return INVALID_SOCKET; } s = socket(af, type, protocol); } return s; } inline int NetObject::check(const int code) { if (code == SOCKET_ERROR) { if (closesocket(sock) == SOCKET_ERROR) return 1; return SOCKET_ERROR; } return 0; } inline int NetObject::connect() { int res = ::connect(sock, (sockaddr *)&amp;addr, sizeof(addr)); return check(res); } } //main.cpp #include "wsa.h" #include &lt;winsock2.h&gt; const int af = AF_INET; const int type = SOCK_STREAM; const int protocol = IPPROTO_TCP; int main(int argc, char * argv[]) { WSADATA ws; if (WSAStartup(MAKEWORD(2, 0), &amp;ws) == -1) { return 1; } wsa::NetObject server(af, type, protocol, argv[1], 80); server.connect(); WSACleanup(); } </code></pre> <p>I can't see any errors. Please, help!</p>
[]
[ { "body": "<p>Thats because in Visual Studio, including <code>winsock2.h</code> to your headers is not enough. You have to tell the Linker your project will need the library <code>wsock32.lib</code>.</p>\n\n<p>You can do that either by editing the properties of your project, or by including this line to your code:</p>\n\n<pre><code>#pragma comment(lib, \"wsock32.lib\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:12:18.753", "Id": "33253", "ParentId": "33250", "Score": "1" } } ]
{ "AcceptedAnswerId": "33253", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T19:44:13.477", "Id": "33250", "Score": "2", "Tags": [ "c++" ], "Title": "Unresolved External Symbol C++" }
33250
<p>I'm trying to simulate the Monty Hall problem, to statistically determine if there is any benefit to changing my choice after a door containing a goat is open (testing <a href="https://www.youtube.com/watch?v=mhlc7peGlGg" rel="nofollow">this guy's</a> Monty Hall theory on YouTube).</p> <p>So, does this manage to simulate it properly? (Just for the curious: Changing doors doesn't seem to have any benefit, but I want to make sure my simulator isn't flawed). I also want style help, if possible!</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #define DOOR_COUNT 3 #define TEST_COUNT 1000000 void InitRandom(); int RunTest(char change); void RandomizeDoors(); int GetRandom(int floor, int roof); void OpenGoatDoor (int choice); int OtherDoor (int choice); int ChoiceWasCar(int choice); char doors[DOOR_COUNT+1]; int main (const char argc, const char **argv) { int run[2], yes[2]; InitRandom(); run[0] = 0; run[1] = 0; yes[0] = 0; yes[1] = 0; // Control Group for (int i = 0; i &lt; TEST_COUNT; i++ ) { run[0]++; yes[0] += RunTest(0); } for (int i = 0; i &lt; TEST_COUNT; i++ ) { run[1]++; yes[1] += RunTest(1); } printf("Control Group:\n\t%d tests run\n\t%d yes.\n\n", run[0], yes[0]); printf("Other Group:\n\t%d tests run\n\t%d yes.\n\n", run[1], yes[1]); } void InitRandom() { unsigned int iseed = (unsigned int)time(NULL); srand (iseed); } int RunTest(char change) { RandomizeDoors(); int choice = GetRandom(1, DOOR_COUNT); //printf("Choice is: %d\n", choice); OpenGoatDoor(choice); if (change) { choice = OtherDoor(choice); } return ChoiceWasCar(choice); } void RandomizeDoors() { char n = GetRandom(1,DOOR_COUNT); for (int i = 0; i &lt;= DOOR_COUNT; i++) { doors[i] = n == i ? 1 : 0; //printf("Door %d is %d\n", i, doors[i]); } // printf("\n"); } int GetRandom(int floor, int roof) { int n; n = (rand()%(roof-floor)); n += floor; return n; } void OpenGoatDoor (int choice) { int doorCur = GetRandom(1, DOOR_COUNT); while ( doors[doorCur] == 1 || doorCur == choice ) { if (doorCur &gt; DOOR_COUNT) { doorCur = GetRandom(1, DOOR_COUNT); } else { doorCur++; } } //printf("Opened Door is %d\n", doorCur); doors[doorCur] = -1; } int OtherDoor (int choice) { int doorCur = 1; while ( doorCur == choice || doors[doorCur] == -1 ) { doorCur++; } return doorCur; } int ChoiceWasCar(int choice) { return doors[choice] == 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:52:44.257", "Id": "53260", "Score": "0", "body": "this question might be better suited for programmers.stackexchange.com rather than here. how have you tested this code to make sure that it works?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:27:39.823", "Id": "53265", "Score": "0", "body": "will post an answer this evening (or delete this comment!). would be frustrating if you moved it while i was working on it..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T08:33:45.760", "Id": "53375", "Score": "1", "body": "Your `GetRandom()` is a tiny bit biased: see [Generating a uniform distribution of integers in C](http://stackoverflow.com/q/11641629)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T10:35:35.480", "Id": "53383", "Score": "0", "body": "`void InitRandom();` should be `void InitRandom(void);`. `void InitRandom();` will accept any arguments." } ]
[ { "body": "<p>ok, so i ended up changing more than was strictly necessary, sorry. as you probably know, it <em>does</em> pay to change doors, so your code <em>did</em> have a bug. i didn't try to trace it down exactly, but i assume it was related to you having 4 doors instead of 3, which i guess was because you had</p>\n\n<pre><code>for (int i = 0; i &lt;= DOOR_COUNT; i++) {\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>for (int i = 0; i &lt; DOOR_COUNT; i++) {\n</code></pre>\n\n<p>in C you always start from 0 and use <code>&lt;</code> in loops. it's the law.</p>\n\n<p>[in general your code is super neat and pretty good. you had a muddle with array indexing, which is very common, and didn't make use of <code>enum</code>, but apart from that, it was nice code. edit: also, your general approach was fine. this is a good way to test the problem.]</p>\n\n<p>some other issues were:</p>\n\n<ul>\n<li><p>the random number generation was strangely general, yet always picked a door. it also started from 1, which i guess is related to the confusion over door array indexing.</p></li>\n<li><p>it wasn't clear to me what the <code>doors</code> array contained at first. when i understood i clarified it with an <code>enum</code>.</p></li>\n<li><p>it wasn't clear to me what the two groups were (\"control\" didn't explain things). when i understood i clarified things with another enum (note the <code>GROUP_COUNT</code> trick which gives the number of entries in the enum, excluding that).</p></li>\n<li><p>given the <code>group</code> enum, there's no need to have two print statements - we can use an array of group names. and there's no need for arrays of results, since we have everything in a loop now.</p></li>\n<li><p>i clarified the logic in <code>OpenGoatDoor</code> - the code initialises the door to <code>choice</code>, which we know is \"bad\" so that the <code>while</code> is triggered and so we only need a single call to <code>RandomDoor</code>.</p></li>\n<li><p>i tried to clarify the logic in <code>OtherDoor</code> but i am not sure i helped.</p></li>\n<li><p>i don't think <code>ChoiceWasCar</code> is necessary - with the enum it's pretty clear what <code>return doors[choice] == car</code> means.</p></li>\n</ul>\n\n<p>here's the modified code. thanks for posting - i was bored and this was interesting to look at.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\n#undef DEBUG\n#define DOOR_COUNT 3\n#define TEST_COUNT 1000000\n\ntypedef enum {goat, car, opened} door;\ndoor doors[DOOR_COUNT];\n\ntypedef enum {nochange, change, GROUP_COUNT} group;\nchar *groupName[GROUP_COUNT] = {\"No Change\", \"Change\"};\n\nvoid InitRandom();\nint RunTest(group g);\nvoid RandomizeDoors();\nint RandomDoor();\nvoid OpenGoatDoor(int choice);\nint OtherDoor(int choice);\n\nint main (void)\n{\n InitRandom();\n\n for (group g = 0; g &lt; GROUP_COUNT; ++g) {\n int wins = 0;\n for (int i = 0; i &lt; TEST_COUNT; ++i) {\n wins += RunTest(g);\n }\n printf(\"%s:\\n\\t%d tests run\\n\\t%d win car.\\n\\n\", \n groupName[g], TEST_COUNT, wins);\n }\n return 0;\n}\n\nvoid InitRandom()\n{\n unsigned int iseed = (unsigned int)time(NULL);\n srand (iseed);\n}\n\nint RunTest(group g)\n{\n RandomizeDoors();\n int choice = RandomDoor();\n #ifdef DEBUG\n printf(\"Choice is: %d\\n\", choice);\n #endif\n OpenGoatDoor(choice);\n if (g == change) {\n choice = OtherDoor(choice);\n }\n return doors[choice] == car;\n}\n\nvoid RandomizeDoors()\n{\n char carDoor = RandomDoor();\n for (int i = 0; i &lt; DOOR_COUNT; i++) {\n doors[i] = carDoor == i ? car : goat;\n #ifdef DEBUG\n printf(\"Door %d is %d\\n\", i, doors[i]);\n #endif\n }\n #ifdef DEBUG\n printf(\"\\n\");\n #endif\n}\n\nint RandomDoor()\n{\n // this is very slightly biased, but we don't care.\n return rand() % DOOR_COUNT;\n}\n\nvoid OpenGoatDoor(int choice)\n{\n int randomDoor = choice;\n while ( randomDoor == choice || doors[randomDoor] != goat) {\n randomDoor = RandomDoor();\n }\n #ifdef DEBUG\n printf(\"Opened Door is %d\\n\", randomDoor);\n #endif\n doors[randomDoor] = opened;\n}\n\nint OtherDoor(int choice)\n{\n int otherDoor = choice;\n while ( otherDoor == choice || doors[otherDoor] == opened ) {\n otherDoor = (otherDoor + 1) % DOOR_COUNT;\n }\n return otherDoor;\n}\n</code></pre>\n\n<p>for anyone following along at home, gcc needs <code>-std=c99</code>.</p>\n\n<p>output:</p>\n\n<pre><code>: gcc -std=c99 mhall.c; ./a.out\nNo Change:\n 1000000 tests run\n 333875 win car.\n\nChange:\n 1000000 tests run\n 667098 win car.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T08:43:33.123", "Id": "53376", "Score": "0", "body": "I got `monty.c:22:5: error: first parameter of 'main' (argument count) must be of type 'int'`, and edited your code to fix it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:29:27.063", "Id": "33264", "ParentId": "33256", "Score": "3" } } ]
{ "AcceptedAnswerId": "33264", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:26:38.323", "Id": "33256", "Score": "4", "Tags": [ "c", "simulation" ], "Title": "Is this an elegant/accurate simulation of the Monty Hall problem?" }
33256
<p>I'm new to scala and have been working to understand the syntax so that I can be more efficient. How does this look in terms of functional syntax and scala idioms?</p> <p>In particular, I'd like to know if this is a good way of handling futures. I'm aware of onComplete, onSuccess, etc..., matching but I had trouble getting a return value back out. map seemed like the right approach here.</p> <pre><code>object Application extends Controller with securesocial.core.SecureSocial { val inboxSlurper = Akka.system.actorOf(Props[InboxSlurper], name = "inboxSlurper") def index = SecuredAction.async { implicit request =&gt; implicit val timeout = Timeout(10 seconds) val user: User = request.user.asInstanceOf[User] val f = inboxSlurper.ask( OauthIdentity( user.email.get, user.oAuth2Info.get.accessToken)) f flatMap { reply =&gt; val emailFeed = reply.asInstanceOf[Enumerator[Message]] val iter = Iteratee.fold[Message, String]("")((result, msg) =&gt; result + msg.getSubject()) emailFeed |&gt;&gt;&gt; iter } map { str =&gt; Logger.debug(str); val subj = "Subject: %s".format(str) Ok(views.html.index(subj)) } } } </code></pre>
[]
[ { "body": "<p>Future \"callbacks\" can be simplified by using the <code>for</code> comprehension to compose futures. More information can be found here <a href=\"http://docs.scala-lang.org/overviews/core/futures.html#functional_composition_and_forcomprehensions\" rel=\"nofollow\">http://docs.scala-lang.org/overviews/core/futures.html#functional_composition_and_forcomprehensions</a></p>\n\n<p>I'm not a Scala expert, but this is how i would replace the flatMap and map with a <code>for</code></p>\n\n<pre><code>object Application extends Controller with securesocial.core.SecureSocial {\n\n val inboxSlurper = Akka.system.actorOf(Props[InboxSlurper], name = \"inboxSlurper\")\n\n def index = SecuredAction.async { implicit request =&gt;\n implicit val timeout = Timeout(10 seconds)\n val user = request.user.asInstanceOf[User]\n\n for {\n emailFeed &lt;- (inboxSlurper ? OauthIdentity(user.email.get, user.oAuth2Info.get.accessToken))).mapTo[Enumerator[Message]]\n str &lt;- emailFeed |&gt;&gt;&gt; Iteratee.fold[Message, String](\"\")((result, msg) =&gt; result + msg.getSubject())\n } yield Ok(views.html.index(\"Subject: %s\".format(str)))\n }\n\n}\n</code></pre>\n\n<p>The example demonstrates the sequential composition of futures, str will be calculated when emailFeed has retrieved the data for the inboxSlurper actor. After all futures have been completed then a result can be returned with <code>yield</code>.</p>\n\n<p>Because everything is a expression in Scala <code>for {} yield Ok()</code> will be returned as result for the Action, which is a Future[SimpleResult].</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T21:31:56.480", "Id": "39244", "ParentId": "33260", "Score": "3" } } ]
{ "AcceptedAnswerId": "39244", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T20:47:57.453", "Id": "33260", "Score": "4", "Tags": [ "scala" ], "Title": "is this future map scala syntax good?" }
33260
<p>Can this be shortened/improved? I'm trying to make a password checker in Python.</p> <p>Could the <code>if</code>s be put into a <code>for</code> loop? If so, how?</p> <pre><code>pw = input("Enter password to test: ") caps = sum(1 for c in pw if c.isupper()) lower = sum(1 for c in pw if c.islower()) nums = sum(1 for c in pw if c.isnumeric()) scr = ['weak', 'medium', 'strong'] r = [caps, lower, nums] if len(pw) &lt; 6: print("too short") elif len(pw) &gt; 12: print("too long") if caps &gt;= 1: if lower &gt;= 1: if nums &gt;= 1: print(scr[2]) elif nums &lt; 1: print("your password is " + scr[1]) elif lower &lt; 1: print("your password strength is " + scr[0]) elif caps &lt; 1: print("your password strength is " + scr[1]) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:18:01.170", "Id": "53268", "Score": "3", "body": "the code works from the looks of Gareth's answer, but I agree that your knowledge of Password strength is lacking. Note: [Password Strength](http://xkcd.com/936/)" } ]
[ { "body": "<pre class=\"lang-none prettyprint-override\"><code>Enter password to test: premaintenance disdainful hayloft seer\ntoo long\nyour password strength is medium\n\nEnter password to test: NXJCWGGDVQZO\nyour password strength is weak\n\nEnter password to test: Password1\nstrong\n</code></pre>\n\n<p>Your knowledge of password strength is: weak.</p>\n\n<h3>Explanation</h3>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Password_strength\">Password strength</a> is normally measured in \"<a href=\"https://en.wikipedia.org/wiki/Information_entropy\">bits of entropy</a>\" — the idea being that if a password has been picked randomly from a pool of similar passwords of size <em>N</em>, then its entropy is log<sub>2</sub><em>N</em> bits.</p>\n\n<p>The first password I tried above was picked using a <a href=\"http://xkcd.com/936/\">method suggested by Randall Munroe</a>, like this:</p>\n\n<pre><code>&gt;&gt;&gt; words = list(open('/usr/share/dict/words'))\n&gt;&gt;&gt; import random\n&gt;&gt;&gt; random.SystemRandom().shuffle(words)\n&gt;&gt;&gt; print(' '.join(w.strip() for w in words[:4]))\npremaintenance disdainful hayloft seer\n</code></pre>\n\n<p>Its entropy can be calculated like this:</p>\n\n<pre><code>&gt;&gt;&gt; from math import log\n&gt;&gt;&gt; l = len(words)\n&gt;&gt;&gt; log(l * (l - 1) * (l - 2) * (l - 3), 2)\n71.39088438576361\n</code></pre>\n\n<p>This is a strong password—a cracker that tried a billion such passwords a second would take on average about 50,000 years to find it.</p>\n\n<p>The second password is also strong, but not as good as the first. I generated it like this:</p>\n\n<pre><code>$ &lt;/dev/random base64 | tr -cd A-Z | head -c 12\nNXJCWGGDVQZO\n</code></pre>\n\n<p>Its entropy is 12 × log<sub>2</sub>26 = 56.4 bits.</p>\n\n<p>The third password is, of course, the weakest. <code>password1</code> is about the 600th most common password (<a href=\"https://xato.net/passwords/more-top-worst-passwords/\">according to Mark Burnett, here</a>) and the initial capital letter is a common substitution that <a href=\"https://en.wikipedia.org/wiki/Password_cracking\">password cracking programs</a> know all about.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:16:29.083", "Id": "53267", "Score": "3", "body": "that was kind of harsh. but I agree." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:23:56.380", "Id": "53269", "Score": "0", "body": "Judging from the last one, this code needs *emergency* improvement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:47:08.073", "Id": "33263", "ParentId": "33262", "Score": "16" } }, { "body": "<p>Gareth's answer is correct and shows the real issues with what you are trying to achieve.</p>\n\n<p>For the sake of learning more, let's review the actual code.</p>\n\n<p><strong>What is good</strong></p>\n\n<ul>\n<li>Your code is simple and easy to understand.</li>\n<li>You are using <code>sum</code>, <code>isupper</code>, <code>islower</code> and <code>isnumeric</code> properly.</li>\n</ul>\n\n<p><strong>What can be improved</strong></p>\n\n<ul>\n<li>Don't repeat yourself :</li>\n</ul>\n\n<p>You don't need to do something like :</p>\n\n<pre><code>if condition:\n foo\nelif not condition:\n bar\n</code></pre>\n\n<p>Just write :</p>\n\n<pre><code>if condition:\n foo\nelse:\n bar\n</code></pre>\n\n<p>Also, you don't need to repeat <code>print(\"your password strength is \" + whatever)</code>.</p>\n\n<p>The corresponding snippet can be written :</p>\n\n<pre><code>if caps &gt;= 1:\n if lower &gt;= 1:\n if nums &gt;= 1:\n strength = scr[2]\n else:\n strength = scr[1]\n else:\n strength = scr[0]\nelse:\n strength = scr[1]\nprint(\"your password strength is \" + scr[1])\n</code></pre>\n\n<ul>\n<li>Keep things simple :</li>\n</ul>\n\n<p>Also, because of the way Python evaluates integers as boolean, you can write the conditions : <code>if caps:</code>, <code>if lower</code> and <code>if nums</code>.</p>\n\n<p>The <code>r</code> list is not used, get rid of it.</p>\n\n<p>In a \"normal\" password checker, I guess it would be possible to factorise the different possible cases on the different criteria to make your code more concise. Here, I have troubles trying to see a logic behind the different cases you are considering. Why would a lower case password be <code>medium</code> no matter the other criteria while a pure upper case password would be <code>weak</code>...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T15:40:37.297", "Id": "42772", "ParentId": "33262", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T21:34:34.717", "Id": "33262", "Score": "7", "Tags": [ "python", "security" ], "Title": "Password checker containing many conditional statements" }
33262
<p>I'm a beginner in JEE development. I have just finished a web application that I'm going to deploy in a server.</p> <p>It's a new level for me; it's not just a simple application that I can run for 10 min, etc.</p> <p>My question is for the quality of code. Of course we all know that a piece of code that works does not mean it's correct. In my managed beans, I use <code>@postConstruct</code>, for example:</p> <pre><code>@PostConstruct public void post() { listChaletss = chaletService.getAllChalet(); for (Chalet it : listChaletss) { if (it.getType().equals("permanent")) { listChaletp.add(it); } } allPeriodes = periodeService.getAllPeriodes(); // System.out.println("size periode" + allPeriodes.size()); for (Chalet order : listChaletss) { order.setEditable(false); } } </code></pre> <p>I'm wondering if someone can determine if we can face any memory problems using this application. Some piece of code and any help from some Java experts will be welcomed.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T05:05:21.313", "Id": "53288", "Score": "3", "body": "you are iterating listChaletss two times. This could be expensive. When you have this type situation, try to manage your structure in one iteration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:49:58.083", "Id": "53580", "Score": "2", "body": "Why are you worried about memory problems in this particular code sample (when i overlook the loop redundancy)? Did you run it through some analysis or does it sometimes causes problems/exceptions/etc?" } ]
[ { "body": "<p>A possible memory concern that I can think of is this line:</p>\n\n<pre><code>listChaletp.add(it);\n</code></pre>\n\n<p>If you're never <strong>removing</strong> elements from that list (which is hard for me to know since I only see a portion of your code), then sooner or later <strong>that list will get out of control</strong> (have too many useless elements) which will <strong>eat up your memory</strong>.</p>\n\n<p>Besides this, the only possible concerns is your <code>periodeService.getAllPeriodes()</code> and <code>chaletService.getAllChalet()</code> but if those do what it sounds like they do (simply return a list without any computation or modifications of those lists) then you don't need to worry about those methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T01:08:07.120", "Id": "35737", "ParentId": "33265", "Score": "1" } }, { "body": "<p>Your variables <code>listChaletss</code>, <code>listChaletp</code>, and <code>allPeriodes</code> appear to be instance variables. We can't tell whether you're leaking memory without further context — what is the expected lifetime of this object? If this object only has a brief existence, then you probably don't have to worry about how it uses memory. On the other hand, if it's a long-lived object, you have to be careful.</p>\n\n<p>There is cause for concern, though. You store the result of <code>.getAllChalet()</code> in instance variable <code>listChaletss</code>. Why an instance variable? Is <code>listChaletss</code> acting as some kind of cache? If so, then the code would likely be:</p>\n\n<pre><code>public void post() {\n if (null == listChaletss) {\n listChaletss = chaletService.getAllChalet();\n }\n ...\n}\n</code></pre>\n\n<p>… or better yet:</p>\n\n<pre><code>private Chalet[] getChalets() {\n if (null == listChaletss) {\n listChaletss = chaletService.getAllChalet();\n }\n return listChaletss;\n}\n\npublic void post() {\n for (Chalet it : getChalets()) {\n ...\n}\n</code></pre>\n\n<p>… or better yet, use a <code>WeakReference</code>.</p>\n\n<p>On the other hand, if <code>listChaletss</code> is <em>not</em> meant to be a cache, then you should just make it a local variable so that you don't hang on to the result. Unintentionally keeping a reference to the result leads to a \"lingering\" memory leak: you waste memory storing <code>listChaletss</code>, but you recover that memory the next time you call <code>.post()</code>, only to waste it again.</p>\n\n<p>Similar considerations apply to your other two instance variables.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T22:56:47.097", "Id": "35791", "ParentId": "33265", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T22:53:10.837", "Id": "33265", "Score": "3", "Tags": [ "java", "beginner", "memory-management" ], "Title": "A good management of Java code" }
33265
<p>This is my solution to the problem in the title. The code is pretty straightforward. The one problem is with <code>substring</code>; it's \$O(n)\$ in .Net and creates garbage. Any other improvements?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LongestWordFromWords { internal class Program { public static string FindLongestWords(string[] listOfWords) { if (listOfWords == null) throw new ArgumentException("listOfWords"); var sortedWords = listOfWords.OrderByDescending(word =&gt; word.Length).ToList(); var dict = new HashSet&lt;String&gt;(sortedWords); foreach (var word in sortedWords) { if (isMadeOfWords(word, dict)) { return word; } } return null; } private static bool isMadeOfWords(string word, HashSet&lt;string&gt; dict) { if (String.IsNullOrEmpty(word)) return false; if (word.Length == 1) { if (dict.Contains(word)) return true; else return false; } foreach (var pair in generatePairs(word)) { if (dict.Contains(pair.Item1)) { if (dict.Contains(pair.Item2)) { return true; } else { return isMadeOfWords(pair.Item2, dict); } } } return false; } private static List&lt;Tuple&lt;string, string&gt;&gt; generatePairs(string word) { var output = new List&lt;Tuple&lt;string, string&gt;&gt;(); for (int i = 1; i &lt; word.Length; i++) { output.Add(Tuple.Create(word.Substring(0, i), word.Substring(i))); } return output; } private static void Main(string[] args) { string[] listOfWords = { "ala", "ma", "kota", "aa", "aabbb", "bbb", "cccc", "aabbbmacccc", "aabbbmaxxcccc" }; string longest = FindLongestWords(listOfWords); Console.WriteLine(longest); string[] listOfWords2 = { "cat", "cats", "catsdogcats", "catxdogcatsrat", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat" }; Console.WriteLine(FindLongestWords(listOfWords2)); } } } </code></pre>
[]
[ { "body": "<p>The first thing that strikes me is that you've put everything within the <code>Program</code> class, which forces your methods to be <code>static</code>, and any program where everything is <code>static</code> is a program I want to rewrite :)</p>\n\n<p>Let's start with <code>FindLongestWords(string[])</code>:</p>\n\n<pre><code>if (listOfWords == null) throw new ArgumentException(\"listOfWords\");\n</code></pre>\n\n<p>This guard clause is throwing the wrong exception, it should be an <code>ArgumentNullException</code>. Now the goal of a guard clause is to <em>fail fast</em>. Interestingly if you leave it out, the next line would throw an <code>ArgumentNullException</code> all by itself, merely by passing it to the <code>OrderByDescending</code> extension method:</p>\n\n<pre><code>var sortedWords = listOfWords.OrderByDescending(word =&gt; word.Length).ToList();\n</code></pre>\n\n<p>I see you're using <code>var</code> - I like that. So <code>sortedWords</code> is a <code>List&lt;string&gt;</code>. I think the method could happily take any <code>IEnumerable&lt;string&gt;</code> instead of an array.</p>\n\n<p>Now the next thing I see is a lie - <code>dict</code> would be an almost-acceptable name for any <code>IDictionary</code>, but it's a <code>HashSet&lt;T&gt;</code>...</p>\n\n<pre><code>var dict = new HashSet&lt;String&gt;(sortedWords);\n</code></pre>\n\n<p>And here we are. You're <code>using System.Linq</code>, so this loop could very well be rewritten with a much shorter Linq-expression:</p>\n\n<pre><code>foreach (var word in sortedWords)\n{\n if (isMadeOfWords(word, dict))\n {\n return word;\n }\n}\nreturn null;\n</code></pre>\n\n<p>Turns into this one-liner (notice <code>dict</code> is gone!):</p>\n\n<pre><code>return sortedWords.FirstOrDefault(word =&gt; isMadeOfWords(word, sortedWords));\n</code></pre>\n\n<p><code>isMadeOfWords</code> should be named <code>IsMadeOfWords</code>, and can be happy with some <code>ICollection</code>:</p>\n\n<pre><code>private static bool IsMadeOfWords(string word, ICollection&lt;string&gt; dict)\n{\n if (String.IsNullOrEmpty(word)) return false;\n if (word.Length == 1)\n {\n return dict.Contains(word);\n }\n foreach (var pair in generatePairs(word).Where(pair =&gt; dict.Contains(pair.Item1)))\n {\n return dict.Contains(pair.Item2) || IsMadeOfWords(pair.Item2, dict);\n }\n return false;\n}\n</code></pre>\n\n<p>I find that's more readable than the more concise form that ReSharper suggests:</p>\n\n<pre><code> if (String.IsNullOrEmpty(word)) return false;\n return word.Length == 1 \n ? dict.Contains(word) \n : generatePairs(word).Where(pair =&gt; dict.Contains(pair.Item1))\n .Select(pair =&gt; dict.Contains(pair.Item2) || IsMadeOfWords(pair.Item2, dict))\n .FirstOrDefault();\n</code></pre>\n\n<p>And then <code>generatePairs</code> should be renamed to <code>GeneratePairs</code> and can return <code>IEnumerable&lt;Tuple&lt;string, string&gt;&gt;</code> instead of <code>List&lt;Tuple&lt;string, string&gt;&gt;</code>. The only thing that itches here is the absence of <code>var</code> in <code>for(int i = 1...</code> - if you're going to use <code>var</code>, might as well go all the way!</p>\n\n<p>I'd put that logic in its own class, and then... looks good!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T18:36:12.043", "Id": "53330", "Score": "0", "body": "1. Static is OK in this case - no mutation e.g. Math.Sin 2. IEnumberable - sure, but only for public interface `FindLongestWords` 3. By dict I meant dictionary of words not `IDictionary` 4. private methods in C# should start with lower case. 5. ReSharper suggestion is ugly as hell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T18:39:22.057", "Id": "53331", "Score": "1", "body": "Also if you remove HashSet contains look up is O(n) not O(1)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T20:33:36.110", "Id": "53337", "Score": "0", "body": "1. Fine, but not in `Program` class 3. I think `words` would be appropriate and less confusing 4. That makes it look like Java code; I always capitalize method names but we can argue all night! 5. Agreed, I put it there just to show how it could be written as a `return` statement. And you're probably right about `HashSet.Contains` vs Linq `IEnumerable.Contains`, I can't wait to read an answer that covers performance and algorithm...and Hell should start with uppercase 'H' :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-29T08:27:41.307", "Id": "117296", "Score": "0", "body": "The capitalization convention for methods in C# is PascalCase, [according to Microsoft](http://msdn.microsoft.com/en-us/library/vstudio/ms229043(v=vs.100).aspx); [here's why](http://programmers.stackexchange.com/questions/53498/what-is-the-philosophy-reasoning-behind-cs-pascal-casing-method-names)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-29T12:54:08.790", "Id": "117314", "Score": "0", "body": "@lukas Methods in C# always are pascal cased" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T03:29:37.683", "Id": "33277", "ParentId": "33266", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T23:38:19.377", "Id": "33266", "Score": "6", "Tags": [ "c#", "strings", "interview-questions" ], "Title": "Write a program to find the longest word made of other words" }
33266
<pre><code>function score_to_grade(score1) { var score = 100 - score1; if (score == 100) return 'A+'; else if (score &gt; 93) return 'A'; else if (score &gt; 87) return 'A-'; else if (score &gt; 81) return 'B+'; else if (score &gt; 69 ) return 'B'; else if (score &gt; 63 ) return 'B-'; else if (score &gt; 56 ) return 'C+'; else if (score &gt; 44 ) return 'C'; else if (score &gt; 38 ) return 'C-'; else if (score &gt; 32 ) return 'D+'; else if (score &gt; 19 ) return 'D'; else if (score == 0 ) return 'F'; else return 'D-'; } </code></pre>
[]
[ { "body": "<p>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch\" rel=\"nofollow\">switch statement</a> would serve you much better in this case.</p>\n\n<p>I'm not quite sure what the line <code>var score = 100 - score1;</code> does. is <code>score1</code> the number of points the test-taker lost? It could use a much better name, such as <code>pointsLost</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T00:36:20.810", "Id": "53271", "Score": "1", "body": "Perhaps it is just some kind of conversion. In GER we have some strange dual grading schemes: 1) [1,2,3,4,5,6] which is equivalent to US [A,B,C,D,E,F] but on the other hand a scoring system [15/14/13, 12/11/10, 9/8/7, 6/5/4, 3/2/1, 0] where you would have to write a conversion from the lower to the higher. Perhaps in this case there is a similar case. We never know ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T23:50:07.960", "Id": "33268", "ParentId": "33267", "Score": "3" } }, { "body": "<pre><code>function score_to_grade(pointsLost) {\n\n // A more meaningful name to what's subtracted from the total\n var score = 100 - pointsLost\n\n // A map of grade to score in \"at least\" basis. Examples, an A is at least 93.\n // You can easily add and remove mappings here\n var map = [\n ['A+', 100],\n ['A', 93],\n ['A-', 87],\n ['B+', 81],\n ['B', 69],\n ['B-', 63],\n ['C+', 56],\n ['C', 44],\n ['C-', 38],\n ['D+', 32],\n ['D', 19],\n ['D-', 1],\n ['F', 0]\n ]\n\n // Loop through the map and check if the score is at least a certain level\n for (var i = 0; i &lt; map.length; i++) {\n if (score &gt;= map[i][1]) return map[0];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T00:55:45.850", "Id": "53273", "Score": "1", "body": "That assumes iterating over the properties of an object is in definition order... which you shouldn't..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T00:45:51.580", "Id": "33272", "ParentId": "33267", "Score": "2" } } ]
{ "AcceptedAnswerId": "33272", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-25T23:44:42.317", "Id": "33267", "Score": "-1", "Tags": [ "javascript" ], "Title": "Mapping a score to a string" }
33267
<p>I have implemented kNN (<a href="http://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm" rel="nofollow">k-nearest neighbors</a>) as follows, but it is very slow. I want to get an exact k-nearest-neighbor, not the approximate ones, so I didn't use the <a href="http://www.cs.ubc.ca/research/flann/" rel="nofollow">FLANN</a> or <a href="http://www.cs.umd.edu/~mount/ANN/" rel="nofollow">ANN</a> libraries.</p> <p><strong>mexFindNN.cpp</strong></p> <pre><code>#include &lt;iostream&gt; using namespace std; #include "mex.h" #include &lt;cstdio&gt; #include &lt;cstdlib&gt; #include &lt;cmath&gt; #include &lt;string.h&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; struct Pair{ int id; double value; Pair(int id, double value){ this-&gt;id=id; this-&gt;value=value; } }; struct PairCompare { bool operator()(Pair const &amp;left, Pair const &amp;right) { return left.value &lt; right.value; } }; template&lt;typename T&gt; void FindNN(T *X, T *Y, int N, int d, int type, int inner_k, int outer_k, mxArray *innerM, mxArray *outerM){ if(!type)//just inner_k { vector&lt;size_t&gt; ir; vector&lt;size_t&gt; jc;jc.push_back(0); vector&lt;double&gt; pr; size_t num_ele=0; for(int i=0;i&lt;N;i++){//X[j*N+i] vector&lt;Pair&gt; inner; for(int j=0;j&lt;N;j++){ double temp=0.0; for(int k=0;k&lt;d;k++){ temp+=(X[k*N+i]-X[k*N+j])*(X[k*N+i]-X[k*N+j]); } if(Y[i]==Y[j]){ inner.push_back(Pair(j,sqrt(temp))); } } std::sort(inner.begin(),inner.end(),PairCompare()); for(int j=1;j&lt;=inner_k &amp;&amp; j&lt;inner.size();j++){ Pair x=inner[j]; ir.push_back(x.id); pr.push_back(x.value); num_ele++; } jc.push_back(num_ele); } size_t *pIr=(size_t *)mxGetIr(innerM); size_t *pJc=(size_t *)mxGetJc(innerM); double *pPr=(double *)mxGetPr(innerM); memcpy(pIr,&amp;ir[0],ir.size()*sizeof(size_t)); memcpy(pJc,&amp;jc[0],jc.size()*sizeof(size_t)); memcpy(pPr,&amp;pr[0],pr.size()*sizeof(double)); } else { vector&lt;size_t&gt; ir,ir2; vector&lt;size_t&gt; jc,jc2;jc.push_back(0);jc2.push_back(0); vector&lt;double&gt; pr,pr2; size_t num_ele=0; size_t num_ele2=0; for(int i=0;i&lt;N;i++){//X[j*N+i] vector&lt;Pair&gt; inner, outer; for(int j=0;j&lt;N;j++){ double temp=0.0; for(int k=0;k&lt;d;k++){ temp+=(X[k*N+i]-X[k*N+j])*(X[k*N+i]-X[k*N+j]); } if(Y[i]==Y[j]){ inner.push_back(Pair(j,sqrt(temp))); }else{ outer.push_back(Pair(j,sqrt(temp))); } } std::sort(inner.begin(),inner.end(),PairCompare()); std::sort(outer.begin(),outer.end(),PairCompare()); for(int j=1;j&lt;=inner_k &amp;&amp; j&lt;inner.size();j++){ Pair x=inner[j]; ir.push_back(x.id); pr.push_back(x.value); num_ele++; } jc.push_back(num_ele); for(int j=0;j&lt;outer_k &amp;&amp; j&lt;outer.size();j++){ Pair x=outer[j]; ir2.push_back(x.id); pr2.push_back(x.value); num_ele2++; } jc2.push_back(num_ele2); } size_t *pIr=(size_t *)mxGetIr(innerM); size_t *pJc=(size_t *)mxGetJc(innerM); double *pPr=(double *)mxGetPr(innerM); memcpy(pIr,&amp;ir[0],ir.size()*sizeof(size_t)); memcpy(pJc,&amp;jc[0],jc.size()*sizeof(size_t)); memcpy(pPr,&amp;pr[0],pr.size()*sizeof(double)); size_t *pIr2=(size_t *)mxGetIr(outerM); size_t *pJc2=(size_t *)mxGetJc(outerM); double *pPr2=(double *)mxGetPr(outerM); memcpy(pIr2,&amp;ir2[0],ir2.size()*sizeof(size_t)); memcpy(pJc2,&amp;jc2[0],jc2.size()*sizeof(size_t)); memcpy(pPr2,&amp;pr2[0],pr2.size()*sizeof(double)); } } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { //prhs[0]: X //prhs[1]: Y //prhs[2]: inner_k //prhs[3]: outer_k //plhs[0]: inner_kNN_Matrix //plhs[1]: outer_kNN_Matrix //mwSize dims_n=mxGetNumberOfDimensions(prhs[0]); const mwSize *dims= mxGetDimensions(prhs[0]); int type=(int)mxGetScalar(prhs[2]); int inner_k=(int)mxGetScalar(prhs[3]); int outer_k=(int)mxGetScalar(prhs[4]); mxClassID clsID = mxGetClassID(prhs[0]); if(clsID==mxSINGLE_CLASS){ int N=dims[0]; int d=dims[1]; float *X=(float *)mxGetPr(prhs[0]); float *Y=(float *)mxGetPr(prhs[1]); plhs[0]=mxCreateSparse(N,N,N*inner_k,mxREAL); if(type) { plhs[1]=mxCreateSparse(N,N,N*outer_k,mxREAL); FindNN&lt;float&gt;(X,Y,N,d,type,inner_k,outer_k,plhs[0],plhs[1]); } else { FindNN&lt;float&gt;(X,Y,N,d,type,inner_k,outer_k,plhs[0],NULL); } }else if(clsID==mxDOUBLE_CLASS){ int N=dims[0]; int d=dims[1]; double *X=(double *)mxGetPr(prhs[0]); double *Y=(double *)mxGetPr(prhs[1]); plhs[0]=mxCreateSparse(N,N,N*inner_k,mxREAL); if(type) { plhs[1]=mxCreateSparse(N,N,N*outer_k,mxREAL); FindNN&lt;double&gt;(X,Y,N,d,type,inner_k,outer_k,plhs[0],plhs[1]); } else { FindNN&lt;double&gt;(X,Y,N,d,type,inner_k,outer_k,plhs[0],NULL); } } } </code></pre> <p><strong>ConstructNNGraph2.m</strong></p> <pre><code>function [innerG,outerG]=ConstructNNGraph2(X,Y,inner_k,outer_k) [N,d]=size(X); if isempty(Y) Y=ones(N,1); end type=0; if outer_k&gt;0 type=1; end if(type) [innerG,outerG]=mexFindNN(X,Y,1,inner_k,outer_k); innerG = max(innerG, innerG'); outerG = max(outerG, outerG'); else [innerG]=mexFindNN(X,Y,0,inner_k,0); outerG=[]; end </code></pre> <p>The code above needs to be compiled in a MATLAB environment. The compile command is </p> <blockquote> <pre><code>mex -largeArrayDims mexFindNN.cpp </code></pre> </blockquote> <p>The sample input <code>X</code> and <code>Y</code> is as follows:</p> <blockquote> <pre><code>load fisheriris; Y=zeros(150,1); Y(1:50)=1; Y(51:100)=2; Y(101:end)=3; X=meas; [innerG,outerG]=ConstructNNGraph2(X,Y,3,5); </code></pre> </blockquote>
[]
[ { "body": "<p>Your code appears to be very C-like with some C++. I'll just give some feedback in regards to that:</p>\n\n<ul>\n<li><p>Try not to use <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>.</p></li>\n<li><p><code>&lt;string.h&gt;</code> is a C library; use <code>&lt;string&gt;</code> with C++.</p></li>\n<li><p>In C++, prefer <code>std::size_t</code> over <code>size_t</code> from C.</p></li>\n<li><p>For testing algorithms such as these, it's good to provide your <code>main()</code> to show how you're doing your testing. Although the code there may already work, you cannot always determine how well an algorithm works if there is no test code.</p></li>\n<li><p>Instead of creating a new <code>Pair</code> structure, consider using <a href=\"http://en.cppreference.com/w/cpp/utility/pair\" rel=\"nofollow noreferrer\"><code>std::pair</code></a> from the STL. It is more idiomatic C++, and it already comes with a few functions and operator overloads.</p>\n\n<p>Moreover, <code>Pair</code> is not a very descriptive name in relation to this program. All that's known is that it holds an <code>int</code> and a <code>double</code>.</p>\n\n<p>Here's how you can change this with <code>std::pair</code>:</p>\n\n<pre><code>// this creates an alias for a new std::pair type\n// this is just a generic type name for demonstration\ntypedef std::pair&lt;int, double&gt; SomePair;\n\n// create a new std::pair\nSomePair newPair;\n\n// pass it to a function\nvoid someFunc(SomePair pair /* ... */) {}\n</code></pre></li>\n<li><p>For better readability, keep operators and operands separated by whitespace:</p>\n\n<pre><code>for (int i = 0; i &lt; 10; ++i) {}\n</code></pre></li>\n<li><p>In this function:</p>\n\n<pre><code>void FindNN(T *X, T *Y, int N, int d, int k)\n</code></pre>\n\n<p>It's not clear what these variables are for as they're single-character. An exception to this is loop counters, which can be single-character.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:07:13.173", "Id": "67176", "Score": "0", "body": "The OP's question was how to make the code faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:08:49.513", "Id": "67177", "Score": "3", "body": "@ChrisW: I know, but on Code Review, we could review any aspects of the code we'd like. I also prefer for there to be something else for other reviewers to address, as that means more answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:45:41.613", "Id": "67211", "Score": "0", "body": "@Jamal, Thanks. I'm not very familiar with the `C++` syntax, so the code looks like `C`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:47:18.557", "Id": "67212", "Score": "0", "body": "@NicolasZhong: That's understandable. You did use `std::vector` and `std::sort`, which is a start. When you get more familiar with the language, you'll see how useful these tools can be." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T21:33:05.610", "Id": "40000", "ParentId": "33269", "Score": "9" } }, { "body": "<p>Use a run-time profiler (test and measure, instead of or as well as trying to guess what's slow). Who knows, just from looking at it: the most expensive line of code might be something innocuous-looking like your <code>push_back</code> method calls.</p>\n\n<p>For a description of how to do this, see for example <a href=\"https://stackoverflow.com/questions/1276834/profiling-a-mex-function\">Profiling a mex-function</a>.</p>\n\n<hr>\n\n<p><strong>Code review</strong></p>\n\n<p>The following apply to the small code fragment posted in the original version of this question:</p>\n\n<ul>\n<li><p><code>std::sort</code> followed by <code>for(int j=1;j&lt;=k...)</code> isn't the cheapest way to get the k smallest elements in a vector. Instead, <a href=\"http://en.cppreference.com/w/cpp/algorithm/nth_element\" rel=\"nofollow noreferrer\"><code>std::nth_element</code></a> has linear cost.</p></li>\n<li><p>It would be better to reserve a capacity for <code>knn_samples</code>, otherwise its doing (expensive) heap allocations and reallocations when you <code>push_back</code>. You could define it once outside your outer loop, and empty it (in order to reuse it) at the top of each loop.</p></li>\n</ul>\n\n<p>The above is an inadequate/incomplete review (there was much more code added the new version of the question) but I don't have time to add to it now.</p>\n\n<hr>\n\n<p><strong>Algorithm review</strong></p>\n\n<ul>\n<li>In the question you said, \" I want to get an exact k-nearest-neighbor, not the approximate ones, so I didn't use the FLANN or ANN libraries\"</li>\n<li>In his answer, @miniBill said, \"Your algorithm is O(n^2), and as much as you can optimize, you can't do better with this.\"</li>\n</ul>\n\n<p>Here's an idea for improving the algorithm (I don't know whether this idea might be helpful):</p>\n\n<ul>\n<li>Use one of the fast, \"approximate\" libraries to categorize your data set into zones</li>\n<li>Use your expensive, exact, O(n^2) algorithm on data already partitioned into much smaller zones.</li>\n</ul>\n\n<p>For example, imagine that you need to run this algorithm against all stars in the universe. An O(n^2) algorithm would do that slowly. I think it would be faster if you used an inexact algorithm to partition the stars into galaxies, and then run your exact algorithm on the stars within each galaxy.</p>\n\n<p>There's no need to get exact values between two stars in different galaxies: an approximate result is enough to tell you that this pair would not be nearest neighbours.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:51:19.317", "Id": "67213", "Score": "0", "body": "Thanks, sir. I have updated the question. Maybe it is now easy to review. In the code, I want to generate k-nearest-neighbor matrix of a data matrix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T20:19:36.417", "Id": "67284", "Score": "1", "body": "Welcome to CodeReview. I updated my answer to suggest that perhaps using a combination of algorithms might make it faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T00:11:37.830", "Id": "67302", "Score": "0", "body": "thanks, sir. I think I still should learn the `FLANN/ANN` library, especially for large scale data set." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T22:56:10.410", "Id": "40006", "ParentId": "33269", "Score": "7" } }, { "body": "<p>Your algorithm is O(n^2), and as much as you can optimize, you can't do better with this.</p>\n\n<p>I don't see any particularly slow path. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-25T01:52:18.963", "Id": "67214", "Score": "0", "body": "Thanks, sir. I think it will be better to use paralleled code, but I'm not very familiar with that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:42:27.220", "Id": "40011", "ParentId": "33269", "Score": "1" } } ]
{ "AcceptedAnswerId": "40006", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T00:00:05.037", "Id": "33269", "Score": "7", "Tags": [ "c++", "performance", "matlab", "clustering", "native-code" ], "Title": "k-nearest neighbors using MATLAB with MEX" }
33269
<h1>background</h1> <p>A little over a year ago I was given the creative freedom to develop on the side of my primary responsibilities. I want to move into development, but am not currently in that role. I was given the resources to develop a PHP application that handled a lot of the reporting functions for our business.</p> <p>My problem is that I have been building upon my (inexperienced) design over the last year and it is becoming cumbersome to maintain and I know I'm duplicating a lot of work (copy, pasting) and I'm looking for pointers and on where to go from here.</p> <p>I expect criticism from this because even I am not happy with this design, but it has been very effective overall for my division.</p> <p>The website is a HTML/JS based with PHP as the server side scripting. I use several libraries, but for the most part, I hand code a lot of the extra features. I didn't have the concept of a framework down when I first built this.</p> <h1>code review</h1> <p><em><strong>Note</strong></em>: Please pardon the lack of documentation, I literally just created this specific example and it's the reason I'm posting on here. Because I want to fix this.</p> <p>I have an index.php that is the router that dynamically pulls another php file, like the one below and displays in a div, based on the url.</p> <h1>index.php</h1> <pre><code>&lt;?php // require_once to have HTML headers. require_once('inc/header.php'); // require_once for wrapper, this is the menu bar located underneath the logo. require_once('inc/wrapper.php'); // start main div. echo &quot;&lt;div id='main'&gt; &quot;; // conditional to check if $_GET for file is valid. if (!empty($_GET['p'])) { $access = ms_escape_string($_GET['p']); } // prepares the query for access_level_control and stores it in an array. $sql = &quot;SELECT access_level FROM test.dbo.users_access_control WHERE filename='$access'&quot;; $result = sqlsrv_query($msdb, $sql); $row = sqlsrv_fetch_array($result); // uses the above array to pull a case/switch with access_level to arrange content for website, an an access level. if (!isset($_GET['p'])) { ?&gt; &lt;script type='text/javascript'&gt; //&lt;![CDATA[ document.title = 'test'; $(document).ready(function () { document.getElementById('subpagetitle').innerHTML = 'Main'; }); //]]&gt; &lt;/script&gt; Please choose from the menu on the left.&lt;/br&gt; &lt;?php } elseif ($_SESSION['accesslevel'] &lt; $row['access_level']) { echo &quot;You are not authorized to use this tool.&quot;; // if access level is insufficient. } else { $access = ms_escape_string($_GET['p']); $sql = &quot;SELECT name FROM test.dbo.users_access_control WHERE filename='$access'&quot;; $result = sqlsrv_query($msdb, $sql); $row = sqlsrv_fetch_array($result); ?&gt; &lt;script type='text/javascript'&gt; //&lt;![CDATA[ document.title = 'test - &lt;?php echo $row['name'] ?&gt;'; $(document).ready(function () { document.getElementById('subpagetitle').innerHTML = '&lt;?php echo $row['name'] ?&gt;'; }); //]]&gt; &lt;/script&gt; &lt;?php require_once($access . &quot;.php&quot;); // opens the php file based on request. } // end main.div. echo &quot;&lt;/div&gt;&quot;; // require_once footer. require_once(&quot;inc/footer.php&quot;); ?&gt; </code></pre> <p>Here is an example of how just ONE of the reports functions. After calling index.php?p=datadump, the main div html is updated with the following php file.</p> <h1>datadump.php</h1> <pre><code>&lt;h3&gt;Data Dump&lt;/h3&gt; &lt;form id='filterform'&gt; &lt;table class='data'&gt; &lt;tr&gt; &lt;th class='center'&gt;Option&lt;/th&gt; &lt;th class='center'&gt;Date Range&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class='center'&gt; &lt;select id='option'&gt; &lt;?php $sql = &quot;SELECT call_type_group_id id, call_type_group_name name FROM test.dbo.call_type_groups&quot;; $result = sqlsrv_query($msdb, $sql); while ($row = sqlsrv_fetch_array($result)) { echo &quot;&lt;option value=&quot; . $row['id'] . &quot;&gt;&quot; . $row['name'] . &quot;&lt;/option&gt;&quot;; } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt; &lt;input type='text' size='8' name='sdate' id='sdate' name='sdate' readonly='1' value=''/&gt; - &lt;input type='text' size='8' name='sdate' id='edate' name='edate' readonly='1' value=''/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th class='center' colspan='4'&gt;&lt;input type='button' id='run' onclick=&quot;pullDataDump();&quot; value='Run'/&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/br&gt; &lt;div id=&quot;container&quot;&gt;&lt;/div&gt; &lt;script type='text/javascript'&gt; addTooltip(); // found in functions.js dateRange(); // found in functions.js enableEnter(); // found in functions.js &lt;/script&gt; </code></pre> <p>The onclick button calls a function found in ajax.js. ajax.js is essentially all very similiar looking functions that typically have one off things that make it hard to re-use the same function. So sadly, a lot of copy, pasting, tweaking happens in that file.</p> <h1>ajax.js</h1> <pre><code>function pullDataDump() { $(function () { var option = $('#option').val() var sdate = $('#sdate').val() var edate = $('#edate').val() $('#container').html('&lt;img src=&quot;inc/img/busy.gif&quot; alt=&quot;Currently Loading&quot; id=&quot;loading&quot; /&gt;'); $.ajax({ url: 'inc/ajax.php?p=pullDataDump', type: 'POST', data: 'sdate=' + sdate + '&amp;edate=' + edate + '&amp;option=' + option, success: function (html) { $('#container').html(html); dataTable(); // found in functions.js } }); return false; }); } </code></pre> <p>Which then calls a php file with the arguments in a POST request where the server side scripting retrieves the data. ajax.php is essentially a massive case/switch that I have been building upon for a <strong>long</strong> time.</p> <h1>ajax.php</h1> <pre><code>case 'pullDataDump': { $sdate = $_POST['sdate']; $edate = $_POST['edate']; $option = $_POST['option']; ?&gt; &lt;table id=&quot;report&quot; class=&quot;data&quot;&gt; &lt;thead&gt; &lt;th class=&quot;center&quot;&gt;DateTime&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;Calls Offered&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;Calls Handled&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;Calls Abandoned&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;Handle Time&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;Overflow Out&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;SL Calls Offered&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;SL Calls Abandoned&lt;/th&gt; &lt;th class=&quot;center&quot;&gt;SL Calls Handled&lt;/th&gt; &lt;/thead&gt; &lt;?php $sql = &quot;SELECT DateTime, SUM(CallsOfferedHalf - OverflowOutHalf) CallsOffered, SUM(CallsHandledHalf) CallsHandled, SUM(TotalCallsAbandToHalf) CallsAbandonded, SUM(HandleTimeHalf) HandleTime, SUM(OverflowOutHalf) OverFlowOut, SUM(ServiceLevelCallsOfferedHalf) ServiceLevelCallsOffered, SUM(ServiceLevelAbandHalf) ServiceLevelAbandHalf, SUM(ServiceLevelCallsHalf) ServiceLevelCallsHandled FROM test.dbo.Call_Type_Half_Hour hh WHERE CallTypeID IN (SELECT call_type_id FROM ww_sl.dbo.call_type_group_members WHERE call_type_group_id = $option) AND DateTime &gt;= '$sdate 00:00:00' AND DateTime &lt;= '$edate 23:30:00' GROUP BY hh.DateTime ORDER BY hh.DateTime&quot;; $result = sqlsrv_query($msdb, $sql); while ($row = sqlsrv_fetch_array($result)) { ?&gt; &lt;tr&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['DateTime']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['CallsOffered']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['CallsHandled']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['CallsAbandonded']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['HandleTime']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['OverFlowOut']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['ServiceLevelCallsOffered']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['ServiceLevelAbandHalf']; ?&gt;&lt;/td&gt; &lt;td class=&quot;center&quot;&gt;&lt;?php echo $row['ServiceLevelCallsHandled']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } echo &quot;&lt;/table&gt;&quot;; } break; </code></pre> <p>The #container div is updated with the results and I have a jquery library that allows manipulation of the displayed results.</p> <p>My big concern is the increasing growing ajax.js and ajax.php, and I'm not sure where to move from here.</p>
[]
[ { "body": "<p>My general suggestion to you is use a <a href=\"http://en.wikipedia.org/wiki/Web_content_management_system\" rel=\"nofollow\">CMS</a>, like <a href=\"http://wordpress.org/\" rel=\"nofollow\">WordPress</a> or <a href=\"https://drupal.org/\" rel=\"nofollow\">Drupal</a> or if you want a more low-level approach, a framework like <a href=\"http://ellislab.com/codeigniter\" rel=\"nofollow\">CodeIgniter</a> or <a href=\"http://framework.zend.com/\" rel=\"nofollow\">Zend</a>. Just so you know, a CMS is usually built on top of a framework. </p>\n\n<p>One reason I suggested a framework or CMS (and not to fix your code) is because when your app grows, plain PHP just won't cut it. And reinventing the wheel isn't efficient either. As you can see, your code is a mashup of both server-side and client-side code, presentational and operational code.</p>\n\n<p>Aside from good looking code, you need to consider:</p>\n\n<ul>\n<li>Maintainability - Is it easy to fix? Can I find the problem easily?</li>\n<li>Extendability - Is it easy to add more parts?</li>\n<li>Fault-resistant - Will it survive when a part breaks? <em>Or does everything explode?</em></li>\n</ul>\n\n<p>A framework usually splits your code into <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a>. Your data (usually the SQL part), your page and your logic will be split into modules, so that if anything goes wrong, you would easily know where to find it.</p>\n\n<p>So, all in all, I suggest you learn a framework or CMS and refactor your code. Learning curves differ per system, so I suggest you try one out and see if it fits your style.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T09:06:16.717", "Id": "53308", "Score": "0", "body": "Thank you Joseph! I actually starting playing around with Symfony2 during the slow part of my day yesterday, as well as attempting to install Drupal. (I didn't get a choice, I **HAVE** to use SQL Server, so I ran into a wall.) I imagine it is going to be quite an undertaking for me to move what I have made into a framework or CMS.\n\nYour 3rd point is the reason I actually started looking around. If ajax.js or ajax.php fail, the entire project self-destructs, which is worrisome." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T01:56:36.810", "Id": "53353", "Score": "0", "body": "@tmac You can try [CodeIgniter](http://ellislab.com/codeigniter) or [Cake](http://cakephp.org/). They're much nearer to low-level PHP. You could start with them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T07:50:02.513", "Id": "53440", "Score": "1", "body": "@JosephtheDreamer: Cake is monstrously slow, especially compared to Symphony2. CodeIgniter has the filthy habit of bootstrapping everything, even those parts you don't need (like bootstrapping caching modules, even if none of your code uses them). There's a reason why ZendFW2 is so remarkably similar to Symfony2. Because it's a good framework." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T21:34:02.953", "Id": "54362", "Score": "0", "body": "I strongly disagree that using a CMS/framework is the solution to any of the problems described in the question - using a framework or CMS is a very valid approach but it doesn't help to solve these problems." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T03:25:22.037", "Id": "33276", "ParentId": "33273", "Score": "1" } }, { "body": "<p>Joseph's answer will help you in the short term, but continuing bad practices will hurt you in the long term. So, here are some things you can look at.</p>\n\n<p>Your code should not have circular logic in it, so the <code>*_once()</code> versions of <code>require()</code> and <code>include()</code> should be unnecessary. There are occasions where it can't be avoided, but most of the time it is simple to avoid.</p>\n\n<pre><code>require 'inc/header.php';//you can use parenthesis if you want\n</code></pre>\n\n<p>You really should avoid echoing HTML directly from your PHP. Your editor or IDE will have a much easier time performing proper highlighting, auto-completion, etc..., if you escape PHP, especially for simple HTML.</p>\n\n<pre><code>?&gt;\n&lt;div id='main'&gt;\n&lt;?php\n</code></pre>\n\n<p>Proper HTML uses double quotes for attributes not single quotes. And neglecting them entirely, as I've seen you do later in your code, should also be avoided. HTML is very forgiving, but it will only go so far. Say for instance that one of your dynamically included attributes has a space in it and you neglect to use quotes. How is your browser supposed to know what to do with that second part of the attribute? I haven't really seen the single/double quote issue cause too much harm, but I imagine there is something out there that will throw a fit. Maybe something that requires proper syntax to iterate over the DOM. Its better to just use proper syntax and avoid the issue.</p>\n\n<pre><code>&lt;div class=\"class1 class2\" id=\"main\"&gt;\n</code></pre>\n\n<p>Your variables and array pointers should be descriptive. What is \"p\"? I have the same issue at work with the code I'm currently working on. The previous programmer's excuse for using \"arg0\" was that it was purposefully ambiguous so the customer wouldn't know what the values were being used for and now neither do I because we have 15 different instances where \"arg0\" is being used. The problem with trying to hide information away from the client is that the information is being used in GET and is thus public. More than likely, and especially so in my case, the same information is displayed to the customer in plain text on the the screen explaining what those values were anyway. If you want to hide information from the customer, use POST or a session.</p>\n\n<pre><code>if (!empty($_GET['p'])) {\n</code></pre>\n\n<p>Don't use JavaScript to perform a static change to your webpage. The document title is a field in the HTML headers that can easily be changed. You can even use PHP in it, like I see you doing later.</p>\n\n<pre><code>document.title = 'test';\n//is the same as\n&lt;title&gt;test&lt;/title&gt;\n</code></pre>\n\n<p>If you have access to jQuery, you should definitely utilize it. jQuery makes using JavaScript enjoyable. jQuery is JS simplified.</p>\n\n<pre><code>$(document).ready(function () {\n document.getElementById('subpagetitle').innerHTML = 'Main';\n});\n//compared to\n$( document ).ready( function() {\n $( '#subpagetitle' ).html( 'Main' );\n} );\n</code></pre>\n\n<p>Double quotes in PHP tells the PHP parser that there is something in the quoted string that needs to be parsed, thus using double quotes requires the slightest bit more processing power. That's not to say you should go through and change all of your double quotes over to single quotes, that's premature optimization. I'm just pointing this out so that I can now say that if you are using double quotes anyway, you might as well throw your PHP variables into your string to be parsed rather than escape from the string.</p>\n\n<pre><code>require_once($access . \".php\");\nrequire_once(\"$access.php\");//the same thing\n\necho \"&lt;option value=\" . $row['id'] . \"&gt;\" . $row['name'] . \"&lt;/option&gt;\";\n//braces allow you to use more complex variables\necho \"&lt;option value=\\\"{$row['id']}\\\"&gt;{$row['name']}&lt;/option&gt;\";\n//braces also let you append text to the end of a simple variable\necho \"{$var}iable\";\n</code></pre>\n\n<p>There are a few things that might potentially be wrong with your <code>pullDataDump()</code> function. First, why are you calling a jQuery function inside of the JS function? This seems redundant and unnecessary. Second, your variables <code>option, sdate, edate</code> are missing semicolons and seem unnecessary. Using jQuery <code>serialize()</code> on the form will get you the same string. Finally, the <code>url, type</code> properties of your AJAX object can be retrieved from the form. Doing so means that should you need to change the action or method later you will only have to do so in one location.</p>\n\n<pre><code>function pullDataDump() {\n $('#container').html('&lt;img src=\"inc/img/busy.gif\" alt=\"Currently Loading\" id=\"loading\" /&gt;');\n $.ajax({\n $form = $( '#form' );\n url: $form.attr( 'action' ),\n type: $form.attr( 'method' ),\n data: $form.serialize(),\n success: function (html) {\n $('#container').html(html);\n dataTable(); // found in functions.js\n }\n });\n return false;\n}\n</code></pre>\n\n<p>Finally, don't use <code>return false</code> use <a href=\"https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false\">preventDefault()</a>.You might also consider changing the above to use jQuery's <code>load()</code> method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T03:52:32.490", "Id": "33898", "ParentId": "33273", "Score": "1" } } ]
{ "AcceptedAnswerId": "33276", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T01:52:16.230", "Id": "33273", "Score": "2", "Tags": [ "javascript", "php", "ajax" ], "Title": "PHP Application, attempting to restructure (Massive case/switch, ajax calls)" }
33273
<p>Is there any other way to shorten this code without sacrificing readability? I am fairly new to C#, let alone programming, and I wanted to know if this is as short as this code can possibly become. Feedback would be greatly welcomed.</p> <p>Side note: was <code>Questions.Questask</code> used properly here, or could there have been a better way?</p> <pre><code> class Program { static void Main(string[] args) { string name = ""; while (name.ToLower() != "none") { Console.WriteLine("Are you Kydd,Leo,Jay,Sha, or Zigg"); name = Console.ReadLine(); if (name.ToLower() == "kydd") Question.Questask("Input question here", "Kquestion","Link"); else if (name.ToLower() == "leo") Question.Questask("Input question here", "Lquestion", "Link"); else if (name.ToLower() == "jay") Question.Questask("Input question here", "Jquestion", "Link"); else if (name.ToLower() == "sha") Question.Questask("Input question here", "Squestion", "Link"); if (name.ToLower() == "zigg") Question.Questask("Input question here", "Zquestion", "Link"); } } class Question { public static void Questask(string question, string questAnswer, string url) { Console.WriteLine(question); questAnswer = Console.ReadLine(); if (questAnswer.ToLower() == "yes") { Console.WriteLine("You are right!"); Console.ReadKey(); } else { System.Diagnostics.Process.Start(url); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T02:48:51.090", "Id": "53281", "Score": "2", "body": "Stick the result of ToLower() into a new variable. You'll only have to call ToLower() once that way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T02:49:48.640", "Id": "53282", "Score": "0", "body": "For any non-trivial application, the questions and names would be stored in some sort of data repository like an XML file or database, not emblazoned into the actual code itself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T02:55:34.753", "Id": "53283", "Score": "0", "body": "You could place \"Input Question Here\" in a string instead of repeating it many times. Also, do you really want a Console.ReadKey() at the class code?" } ]
[ { "body": "<p>When I need a simple <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy pattern</a> I'll use a <code>Dictionary</code>. This can drastically reduce code by cutting repetition.</p>\n\n<p>Note the use of <code>StringComparer.InvariantCultureIgnoreCase</code> for <a href=\"http://msdn.microsoft.com/en-us/library/ms132072.aspx\" rel=\"nofollow\"><code>comparer</code></a> to do away with the <code>String.ToLower</code> calls.</p>\n\n<pre><code>private static readonly IDictionary&lt;string, Tuple&lt;string, string&gt;&gt; NamesDictionary =\n new Dictionary&lt;string, Tuple&lt;string, string&gt;&gt;(StringComparer.InvariantCultureIgnoreCase)\n {\n { \"kydd\", Tuple.Create(\"question 1\", \"link1\") },\n { \"zydd\", Tuple.Create(\"question 2\", \"link2\") },\n ...\n };\n\nprivate static void DoSomething(string name)\n{\n Tuple&lt;string, string&gt; questionAndLinkTuple;\n\n if (!NamesDictionary.TryGetValue(name, out questionAndLinkTuple))\n return;\n\n var question = questionAndLinkTuple.Item1;\n var link = questionAndLinkTuple.Item2;\n\n Question.AskQuestion(\"Input answer here\", question, link);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T23:09:59.790", "Id": "53344", "Score": "1", "body": "+1 for being the only answer that renames `Questask` to `AskQuestion` :) Actually since the class is `Question` and the method is `static`, a perhaps even better name would be simply `Ask()`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T23:32:11.683", "Id": "53345", "Score": "1", "body": "@retailcoder I didn't bother with it in my answer, but a more complex example I could understand the need for a `Question` class. OP's example would have been just fine without `Question` and instead have a static `Program.AskQuestion`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T02:55:44.463", "Id": "33275", "ParentId": "33274", "Score": "1" } }, { "body": "<p>I rewrote this for you, making it easier to understand and making it a little more efficient (although, the size is just a tad bigger then your original). Hopefully it makes a little more sense and you can ask any questions if you need to:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n var names = new List&lt;NameClass&gt;\n {\n new NameClass {Name = \"Kydd\", Answer = \"Kquestion\"},\n new NameClass {Name = \"Leo\", Answer = \"Lquestion\"},\n new NameClass {Name = \"Jay\", Answer = \"Jquestion\"},\n new NameClass {Name = \"Sha\", Answer = \"Squestion\"},\n new NameClass {Name = \"Zigg\", Answer = \"Zquestion\"}\n };\n\n string name = \"\";\n while (name.ToLower() != \"none\")\n {\n Console.WriteLine(\"Are you Kydd,Leo,Jay,Sha, or Zigg\");\n name = Console.ReadLine().ToLower();\n\n var a = names.FirstOrDefault(z =&gt; z.Name.ToLower() == name);\n if (a != null)\n {\n Questask(a.Question, a.Answer, a.Url);\n }\n }\n }\n\n private static void Questask(string question, string questAnswer, string url)\n {\n Console.WriteLine(question);\n questAnswer = Console.ReadLine();\n if (questAnswer.ToLower() == \"yes\")\n {\n Console.WriteLine(\"You are right!\");\n Console.ReadKey();\n }\n else\n {\n System.Diagnostics.Process.Start(url);\n }\n }\n\n public class NameClass\n {\n public string Name { get; set; }\n public string Question { get; set; }\n public string Answer { get; set; }\n public string Url { get; set; }\n\n public NameClass()\n {\n Question = \"Input question here\";\n Url = \"Link\";\n }\n }\n}\n</code></pre>\n\n<p>The beauty of this code is that you don't need a bunch of <code>if</code> statements. If you need to add more, simply add one more line of code in the names definition.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T11:07:24.840", "Id": "53314", "Score": "0", "body": "It would be helpful if you explained what exactly did you change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T15:31:32.517", "Id": "53327", "Score": "0", "body": "Thank you for this Beauty of a Code It will help me better understand the use of classes which I still struggle with. Just one Question What exactly does names.FirstOrDefault(z => z.Name.ToLower() == name) line of do kinda stumped on it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T23:33:54.387", "Id": "53346", "Score": "0", "body": "It's a LINQ expression that returns the first NameClass in the list names that has a Name.ToLower that equals name or a default value (null)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T04:31:35.870", "Id": "33278", "ParentId": "33274", "Score": "1" } }, { "body": "<p>I like icemanind's answer, but to give an alternate point of view -- sometimes you just need to get it done.</p>\n\n<pre><code>string[] names = {\"kydd\",\"leo\",\"jay\",\"sha\",\"zigg\");\nif (Array.IndexOf(names, name.ToLower())&gt;-1){\n Question.Questask(\"Input question here\", \n string.Format(\"{0}question\",name[0].ToUpper()),\"Link\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T06:46:34.637", "Id": "33282", "ParentId": "33274", "Score": "1" } } ]
{ "AcceptedAnswerId": "33278", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T02:46:29.403", "Id": "33274", "Score": "2", "Tags": [ "c#", "beginner", "url" ], "Title": "Shortening my questions code" }
33274
<p>This works just fine, however, the assignment was to write a recursive "function". I'm curious to see if this should count. </p> <p>Any comments / suggestions/ stuff I should watch out for are appreciated. </p> <pre><code>#include &lt;iostream&gt; #include &lt;functional&gt; #include &lt;cctype&gt; #include &lt;cstdlib&gt; int main() { char go_again = 'Y'; do { int lhs, rhs; std::cout &lt;&lt; "Enter 2 integer values: "; std::cin &gt;&gt; lhs &gt;&gt; rhs; if (lhs &lt; 0 || rhs &lt; 0) std::cout &lt;&lt; "Implicit converstion to positive integers.\n"; std::function&lt;int(int, int)&gt; gcd = [&amp;](int lhs, int rhs) -&gt; int { return rhs == 0 ? std::abs(lhs) : gcd(rhs, lhs % rhs); }; std::cout &lt;&lt; "gcd == " &lt;&lt; gcd(lhs, rhs) &lt;&lt; '\n'; std::cout &lt;&lt; "Go again? &lt;Y/N&gt; "; std::cin &gt;&gt; go_again; } while (std::toupper(go_again) == 'Y'); } </code></pre>
[]
[ { "body": "<p>Not that familiar with C++, but that certainly looks like recursion to me...</p>\n\n<p>The variable gcd contains a function, which then calls itself. The very definition of recursion.</p>\n\n<p>But I would ask what you gain by not making it a regular function?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T06:18:09.990", "Id": "33281", "ParentId": "33280", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T05:53:48.603", "Id": "33280", "Score": "1", "Tags": [ "c++", "recursion", "lambda" ], "Title": "Recursive GCD using a lambda" }
33280
<p>[Please don't comment on using Turbo C++. I know that it's obsolete but we are taught this way only.]</p> <pre><code>#include&lt;fstream.h&gt; #include&lt;conio.h&gt; void main() { clrscr(); char ch; ifstream read; read.open("Employee.txt"); ofstream write; write.open("Another.txt"); while(!read.eof()) { read.get(ch); //Also when I use, write&lt;&lt;read.get(ch) is it writes some kind of write&lt;&lt;ch; //address in the file. Please tell me about that too why it happens. } read.close(); write.close(); getch(); } </code></pre> <p>The problem I'm facing is that it appends <strong><em>ÿ</em></strong> character at the end of 'another' file.</p> <p><img src="https://i.stack.imgur.com/1w2KV.png" alt="enter image description here"></p>
[]
[ { "body": "<p>This is a deprecated head (C++ headers don't have .h on the end)</p>\n\n<pre><code>#include&lt;fstream.h&gt;\n// Should be\n#include&lt;fstream&gt;\n</code></pre>\n\n<p>OK your Turbo stuff:</p>\n\n<pre><code>#include&lt;conio.h&gt;\n</code></pre>\n\n<p>This is not a valid main() declaration:</p>\n\n<pre><code>void main()\n</code></pre>\n\n<p>There are two valid main() declarations accepted by the standard:</p>\n\n<pre><code>int main()\nint main(int argc, char* argv[])\n</code></pre>\n\n<p>Declare varaibles as close to the point of use as you can:</p>\n\n<pre><code>char ch; // You don't use this till the other end of the function.\n // How am I supposed to remember its type. O yes you\n // seem to have just shortened the name of the type.\n // more meaningful names is also useful (this is not a\n // tersity competition).\n</code></pre>\n\n<p>May as well use the constructor the at opens them.</p>\n\n<pre><code>ifstream read;\nread.open(\"Employee.txt\");\n\n// Much easier to read and write as\nifstream read(\"Employee.txt\");\n</code></pre>\n\n<p>Same again</p>\n\n<pre><code>ofstream write;\nwrite.open(\"Another.txt\");\n</code></pre>\n\n<p>Note. If you had included the correct header file. These are both in the standard namespace.</p>\n\n<p>This is nearly always wrong way to write a loop</p>\n\n<pre><code>while(!read.eof())\n</code></pre>\n\n<p>The problem is that the eof flag is not set until you read past the end of file. But the last successful read will read upto the end of file (not past). So even though there is absolutely no data left on the stream the eof flag is still false. It is not until you try and read a character that is not there that the flag is set.</p>\n\n<p>To get around this you can write the loop like this.</p>\n\n<pre><code>while(!read.eof())\n{\n read.get(ch);\n if (read.eof()) { break;}\n\n // PS. This is why you are seeing the funny character on your output\n // You read past the end of file and even though the stream told\n // you it had failed (by setting the eof flag). You failed to\n // check the value after the read and thus printed some random\n // garbage to your output (as ch was set to random stuff).\n\n // STUFF\n}\n</code></pre>\n\n<p><strong>BUT</strong> wait. There are more problems with the above. What happens if eof is never set. But you say that can never happen. Actually it can (and is very common in normal use). If you set any of the other bad bits on the stream you now get stuck in an infinite loop. Because once the bad bit is set no more data is read from the stream so it never advances to reach the end (luckily for you get() is not going to do that but other standard read commands are). But what happens if the file does not exist? It is not eof() but a bad bit is set. So if the file does not exist your loop enters an infinite blocking loop.</p>\n\n<pre><code>while(!read.eof())\n{\n int x;\n read &gt;&gt; x;\n if (read.eof()) { break;}\n\n // STUFF\n}\n</code></pre>\n\n<p>Here if the input does not contain an int you have an infinite loop. You can fix it by testing for <code>read.bad()</code> but now things are getting more complex.</p>\n\n<p>But an easier way to write this is (The correct way):</p>\n\n<pre><code>while(read.get(ch))\n{\n // STUFF\n}\n</code></pre>\n\n<p>Your loop is only entered if the read worked.<br>\nThis works because the result of the <code>get()</code> is a reference to the stream (i.e. a reference to <code>read</code>). When a stream is used in a boolean context (like a while loop test) it is auto converted into a boolean <em>like</em> type. The value of this boolean type is based on the state of the stream, if you can still read from it (ie the last read worked) then it is true otherwise false.</p>\n\n<p>As noted above you should declare variables as close to the point of use as possible. Because you declared ch at the top but only use it inside the loop you are polluting the rest of the code with an unneeded value. This can lead to errors where you accidentally use the value.</p>\n\n<blockquote>\n <p>Also when I use, write&lt;&lt;read.get(ch) is it writes some kind of address in the file. Please tell me about that too why it happens.</p>\n</blockquote>\n\n<p>This happens because the result of <code>get()</code> returns a reference to the stream. When used on the right hand side of <code>operator&lt;&lt;</code> there is a conversion into a type that can be written to an output stream. As it happens it is the same as the conversion that happens above (as explained for while). The <code>boolean like type</code> in C++03 is a pointer (NULL pointer is false all other pointers are true). In C++11 this was fixed and the <code>boolean like type</code> is actually a <code>bool</code>. I would not read too much into the value of the pointer only that it is (or is not) NULL.</p>\n\n<p>Don't manually close the streams. This is what RAII is for: see <a href=\"https://codereview.stackexchange.com/a/544/507\">My C++ code involving an fstream failed review</a></p>\n\n<pre><code>read.close();\nwrite.close();\n</code></pre>\n\n<p>You can use standard functions to achieve the same affect as pausing for the human.</p>\n\n<pre><code>getch();\n\n// standard compliant way.\nstd::cin.clear();\nstd::string line;\nstd::getline(std::cin, line);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T12:54:35.817", "Id": "33290", "ParentId": "33285", "Score": "4" } } ]
{ "AcceptedAnswerId": "33290", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T07:41:33.817", "Id": "33285", "Score": "-1", "Tags": [ "c++", "file" ], "Title": "C++ File handling, inserts ÿ character while copying contents" }
33285
<p>I am looking for a review regarding C++ streams behaviour conformance.</p> <p>I have made this <code>win32_file_streambuf</code> so that I can use it in log4cplus project. I basically need it so that log files can be renamed when they are still opened by another process logging into the same file. This can be done when file is opened with <code>FILE_SHARE_DELETE</code> share mode flag.</p> <p>The <code>win32_file_streambuf</code> has its limitations, like not being able to seek to arbitrary offset in the file when its encoding is variable width.</p> <p>According to some people, it is better to use <a href="https://bitbucket.org/wilx/custom_ostream/commits/b38941b06b95b7b829d23d17b76eaa0abfa71bea?at=default" rel="nofollow">review feature on BitBucket.org</a>.</p> <pre><code>// File: custom_ostream.cpp // Created: 9/2013 // Author: Vaclav Zeman // // // Copyright (C) 2013, Vaclav Zeman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- // DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //#include "stdafx.h" #include &lt;ios&gt; #include &lt;istream&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;locale&gt; #include &lt;codecvt&gt; #include &lt;sstream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;cassert&gt; #include &lt;limits&gt; #include &lt;cstdlib&gt; #include &lt;WinSock2.h&gt; void clear_mbstate (std::mbstate_t &amp; mbs) { // Initialize/clear mbstate_t type. // XXX: This is just a hack that works. The shape of mbstate_t varies // from single unsigned to char[128]. Without some sort of initialization // the codecvt::in/out methods randomly fail because the initial state is // random/invalid. std::memset (&amp;mbs, 0, sizeof (std::mbstate_t)); } template &lt;typename OuterRep, typename InnerChar&gt; std::codecvt_base::result do_codecvt_out (std::vector&lt;OuterRep&gt; &amp; dest, InnerChar const * src, std::size_t size, std::ptrdiff_t &amp; converted, std::codecvt&lt;InnerChar, OuterRep, std::mbstate_t&gt; const &amp; cdcvt, std::mbstate_t &amp; state) { if (size == 0) { dest.clear (); return std::codecvt_base::noconv; } InnerChar const * from_first = src; std::size_t const from_size = size; InnerChar const * const from_last = from_first + from_size; InnerChar const * from_next = from_first; // If the destination is too small here and the facet is codecvt_utf8 // facet, then the conversion will fail because there is not enough space // for all bytes of the output. IMHO, the codecvt_utf8 facet should be // handling the overflow through the std::mbstate_t parameter but // unfortunately it does not do that. dest.resize ((std::max) (from_size, static_cast&lt;std::size_t&gt;(cdcvt.max_length ()))); OuterRep * to_first = &amp;dest.front (); std::size_t to_size = dest.size (); OuterRep * to_last = to_first + to_size; OuterRep * to_next = to_first; std::codecvt_base::result result; std::size_t converted_out = 0; while (from_next != from_last) { result = cdcvt.out ( state, from_first, from_last, from_next, to_first, to_last, to_next); // XXX: Even if only half of the input has been converted the // in() method returns CodeCvt::ok with VC8. I think it should // return CodeCvt::partial. if (result == std::codecvt_base::ok &amp;&amp; from_next != from_last) { to_size = dest.size () * 2; dest.resize (to_size); converted_out = to_next - to_first; to_first = &amp;dest.front (); to_last = to_first + to_size; to_next = to_first + converted_out; } else break; } converted_out = to_next - &amp;dest[0]; dest.resize(converted_out); converted = from_next - from_first; return result; } template &lt;typename Char&gt; struct win32_file_ops; template &lt;&gt; struct win32_file_ops&lt;char&gt; { static HANDLE create (char const * file_name, DWORD desired_access, DWORD share_mode, DWORD creation_disposition, DWORD flags_and_attributes) { return CreateFileA (file_name, desired_access, share_mode, 0, creation_disposition, flags_and_attributes, 0); } }; template &lt;&gt; struct win32_file_ops&lt;wchar_t&gt; { static HANDLE create (wchar_t const * file_name, DWORD desired_access, DWORD share_mode, DWORD creation_disposition, DWORD flags_and_attributes) { return CreateFileW (file_name, desired_access, share_mode, 0, creation_disposition, flags_and_attributes, 0); } }; template &lt;typename Char, typename Traits = std::char_traits&lt;Char&gt; &gt; class win32_file_streambuf : public std::basic_streambuf&lt;Char, Traits&gt; { enum constants { DATA_BUF_INITIAL_SIZE = 1024 * 64 / sizeof (Char) }; public: typedef std::basic_streambuf&lt;Char, Traits&gt; base_type; typedef typename base_type::char_type char_type; typedef typename base_type::int_type int_type; typedef typename base_type::traits_type traits_type; typedef typename base_type::pos_type pos_type; typedef std::ios_base::openmode openmode; typedef typename traits_type::off_type off_type; win32_file_streambuf () : fh (INVALID_HANDLE_VALUE) , data_buf () , loc () , cdcvt (0) , file_pos (0) , open_mode (openmode (0)) { imbue (loc); this-&gt;setp (0, 0, 0); } virtual ~win32_file_streambuf () { try { close (); } catch (std::ios_base::failure const &amp;) { } } protected: static void prepare_flags(DWORD &amp; desired_access, DWORD &amp; share_mode, DWORD &amp; creation_disposition, DWORD &amp; flags_and_attributes, openmode om) { desired_access = FILE_GENERIC_READ | STANDARD_RIGHTS_WRITE | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_WRITE_DATA; share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; creation_disposition = 0; if (om &amp; std::ios_base::trunc) creation_disposition |= CREATE_ALWAYS; else creation_disposition |= OPEN_ALWAYS; flags_and_attributes = FILE_ATTRIBUTE_ARCHIVE; } template &lt;typename FNChar&gt; win32_file_streambuf * do_open (FNChar const * file_name, openmode om) { open_mode = om; DWORD desired_access, share_mode, creation_disposition, flags_and_attributes; prepare_flags (desired_access, share_mode, creation_disposition, flags_and_attributes, open_mode); fh = win32_file_ops&lt;FNChar&gt;::create (file_name, desired_access, share_mode, creation_disposition, flags_and_attributes); if (! fh || fh == INVALID_HANDLE_VALUE) return 0; if (open_mode &amp; std::ios_base::ate &amp;&amp; do_seekoff (0, std::ios_base::end) == off_type (-1)) return 0; file_pos = win32_get_file_pos (); return this; } public: win32_file_streambuf * open(wchar_t const * file_name, openmode om) { return do_open (file_name, om); } win32_file_streambuf * open(char const * file_name, openmode om) { return do_open (file_name, om); } win32_file_streambuf * close () { int_type res = sync () || flush_conversion_state (); char_type * pb = this-&gt;pbase (); this-&gt;setp (pb, pb, this-&gt;epptr ()); if (fh != INVALID_HANDLE_VALUE) { BOOL ret = CloseHandle (fh); if (! ret) //throw std::ios_base::failure ("CloseHandle"); return 0; fh = INVALID_HANDLE_VALUE; } return res == 0 ? this : 0; } bool is_open () const { return fh &amp;&amp; fh != INVALID_HANDLE_VALUE; } protected: static bool is_eof (int_type ch) { return traits_type::eq_int_type(ch, traits_type::eof ()); } static int_type not_eof () { return traits_type::not_eof(traits_type::eof ()); } off_type win32_get_file_pos () { LARGE_INTEGER to = { }; LARGE_INTEGER cur = { }; BOOL ret = SetFilePointerEx (fh, to, &amp;cur, FILE_CURRENT); if (! ret) return off_type (-1); else return off_type (cur.QuadPart); } off_type win32_get_file_size () { LARGE_INTEGER li; BOOL ret = GetFileSizeEx (fh, &amp;li); if (! ret || (std::numeric_limits&lt;off_type&gt;::max) () &lt; li.QuadPart) return off_type (-1); else return off_type (li.QuadPart); } BOOL win32_write_file (char const * buf, DWORD to_write, DWORD &amp; written) { // Perepare OVERLAPPED structure. OVERLAPPED overlapped = { }; if (open_mode &amp; std::ios_base::app) { overlapped.OffsetHigh = 0xFFFFFFFFu; overlapped.Offset = 0xFFFFFFFFu; } else { overlapped.OffsetHigh = LONGLONG (file_pos) &gt;&gt; 32; overlapped.Offset = LONGLONG (file_pos) &amp; 0xFFFFFFFFu; } // Do the actual write. BOOL wfret = WriteFile (fh, buf, to_write, &amp;written, &amp;overlapped); return wfret; } int_type update_file_pos (DWORD written) { if (open_mode &amp; std::ios_base::app) { off_type file_size = win32_get_file_size (); if (file_size == -1) return traits_type::eof (); } else file_pos += written; return not_eof (); } virtual int_type overflow (int_type ch) { int_type ret = traits_type::not_eof (ch); // Set up a buffer if we do not have one, yet. if (! this-&gt;pbase()) { data_buf.resize(DATA_BUF_INITIAL_SIZE); this-&gt;setp(&amp;data_buf[0], &amp;data_buf[0], &amp;data_buf[0] + data_buf.size()); } for (;;) { char_type * mid = this-&gt;pptr (); std::ptrdiff_t const buffer_space = this-&gt;epptr () - mid; // Try to store a character if it is not EOF // and we have a space for it. if (! is_eof (ch) &amp;&amp; buffer_space &gt; 0) { *mid = traits_type::to_char_type (ch); this-&gt;pbump (1); break; } // Check for anything to do first. else if (mid == this-&gt;pbase ()) { // Nothing to do. break; } // Else flush buffer. else { char_type * const pb = this-&gt;pbase (); std::size_t to_write = 0; char const * buf = 0; char_type * new_pmid = 0; // Do characters need a conversion? if (cdcvt-&gt;always_noconv ()) { // No conversion is necessary. buf = reinterpret_cast&lt;char const *&gt;(pb); to_write = (mid - pb) * sizeof (char_type); new_pmid = pb; } else { // Convert using codecvt facet from our locale. std::ptrdiff_t converted = 0; std::ptrdiff_t const to_convert = mid - pb; std::codecvt_base::result codecvt_res = do_codecvt_out&lt;char&gt; (out_buf, pb, to_convert, converted, *cdcvt, cdcvt_state); if (codecvt_res == std::codecvt_base::noconv) { buf = reinterpret_cast&lt;char const *&gt;(pb); to_write = to_convert; new_pmid = pb; } else if (codecvt_res == std::codecvt_base::error) { ret = traits_type::eof (); break; } else { if (converted &lt; to_convert) { // Handle partial conversion. // Move remaining characters down. std::ptrdiff_t const remaining_conv = to_convert - converted; traits_type::move (pb, pb + converted, remaining_conv); new_pmid = pb + remaining_conv; } else new_pmid = pb; buf = &amp;out_buf[0]; to_write = out_buf.size (); } } DWORD written = 0; BOOL wfret = win32_write_file (buf, to_write, written); if (! wfret) { //throw std::ios_base::failure("WriteFile"); ret = traits_type::eof (); break; } if (is_eof (update_file_pos (written))) { ret = traits_type::eof (); break; } if (written &lt; to_write) { ret = traits_type::eof (); break; //std::ptrdiff_t const remaining = to_write - written; //traits_type::move(pb, pb + written, remaining); //this-&gt;pbump(-static_cast&lt;std::ptrdiff_t&gt;(written)); } this-&gt;setp (pb, new_pmid, this-&gt;epptr ()); if (! is_eof (ch)) // Try character again after we have freed some buffer // space. continue; else { // Or just exit, if were were just supposed to flush. break; } } } return ret; } virtual int sync () { if (is_eof (overflow (traits_type::eof ()))) return -1; else return 0; } virtual basic_streambuf&lt;Char, Traits&gt; * setbuf (char_type * s, std::streamsize n) { if (! this-&gt;pbase () &amp;&amp; n &gt; 0) { this-&gt;setp(s, s, s + n); return this; } else return 0; } virtual void imbue (const std::locale&amp; new_loc) { loc = new_loc; cdcvt = &amp;std::use_facet&lt;codecvt_type&gt;(loc); clear_mbstate (cdcvt_state); } private: int_type flush_conversion_state() { if (cdcvt-&gt;always_noconv()) return not_eof (); char out = 0; char * mid = 0; std::codecvt_base::result res; int_type ret = not_eof (); out_buf.resize ((std::max) (static_cast&lt;int&gt;(out_buf.size ()), (std::min) (cdcvt-&gt;max_length (), 64))); for (;;) { char * const buf = &amp;out_buf[0]; mid = buf; res = cdcvt-&gt;unshift (cdcvt_state, buf, buf + out_buf.size (), mid); if (res == std::codecvt_base::noconv) return not_eof (); else if (res == std::codecvt_base::partial || res == std::codecvt_base::ok) { DWORD to_write = mid - buf; DWORD written = 0; BOOL wfret = win32_write_file (buf, to_write, written); if (! wfret) { //throw std::ios_base::failure("WriteFile"); ret = traits_type::eof (); break; } if (is_eof (update_file_pos (written))) { ret = traits_type::eof (); break; } if (written &lt; to_write) { ret = traits_type::eof (); break; //std::ptrdiff_t const remaining = to_write - written; //traits_type::move(pb, pb + written, remaining); //this-&gt;pbump(-static_cast&lt;std::ptrdiff_t&gt;(written)); } if (res == std::codecvt_base::partial) continue; else break; } else { ret = traits_type::eof (); break; } } return ret; } pos_type do_seekoff (off_type off, std::ios_base::seekdir dir, openmode /* which */ = std::ios_base::in | std::ios_base::out) { if (! is_open ()) return pos_type (off_type (-1)); if (sync () != 0) return pos_type (off_type (-1)); if (is_eof (flush_conversion_state ())) return pos_type (off_type (-1)); int const width = cdcvt-&gt;encoding (); off_type new_off = 0; switch (dir) { case std::ios_base::beg: if (off &lt; 0 || off != 0 &amp;&amp; width &lt;= 0) return pos_type (off_type (-1)); clear_mbstate (cdcvt_state); new_off = off * width; break; case std::ios_base::cur: if ((off != 0 &amp;&amp; width &lt;= 0) || (off &gt; 0 &amp;&amp; (std::numeric_limits&lt;off_type&gt;::max) () - file_pos &lt; off * width) || (off &lt; 0 &amp;&amp; off * width + file_pos &lt; 0)) return pos_type (off_type (-1)); new_off = file_pos + off * width; break; case std::ios_base::end: off_type const file_size = win32_get_file_size (); if (file_size == off_type (-1)) return pos_type (file_size); if (off &lt; 0 || (off != 0 &amp;&amp; width &lt;= 0) || off * width &gt; file_size) return pos_type (off_type (-1)); new_off -= off * width; break; } if (new_off == file_pos) return file_pos; file_pos = new_off; return pos_type (file_pos); } protected: virtual pos_type seekpos (pos_type pos, openmode which = std::ios_base::in | std::ios_base::out) { return do_seekoff (pos, std::ios_base::beg, which); } virtual pos_type seekoff (off_type off, std::ios_base::seekdir dir, openmode which = std::ios_base::in | std::ios_base::out) { return do_seekoff (off, dir, which); } public: std::locale getloc () const { return loc; } private: typedef std::codecvt&lt;char_type, char, std::mbstate_t&gt; codecvt_type; HANDLE fh; std::vector&lt;char_type&gt; data_buf; std::vector&lt;char&gt; out_buf; std::locale loc; codecvt_type const * cdcvt; std::mbstate_t cdcvt_state; off_type file_pos; openmode open_mode; }; template &lt;typename Char, typename Traits = std::char_traits&lt;Char&gt; &gt; class win32_file_stream : public std::basic_ostream&lt;Char, Traits&gt; { public: enum { default_open_mode = static_cast&lt;std::ios_base::openmode&gt;( std::ios_base::trunc | std::ios_base::out) }; win32_file_stream () : std::ostream (&amp;sbuf) { } win32_file_stream (char const * file_name, std::ios_base::openmode om = win32_file_stream::default_open_mode) : std::basic_ostream&lt;Char, Traits&gt; (&amp;sbuf) { do_open(file_name, om); } win32_file_stream (wchar_t const * file_name, std::ios_base::openmode om = win32_file_stream::default_open_mode) : std::basic_ostream&lt;Char, Traits&gt; (&amp;sbuf) { do_open(file_name, om); } win32_file_stream &amp; open(char const * file_name, std::ios_base::openmode om = win32_file_stream::default_open_mode) { return do_open (file_name, om); } win32_file_stream &amp; open(wchar_t const * file_name, std::ios_base::openmode om = win32_file_stream::default_open_mode) { return do_open(file_name, om); } win32_file_stream &amp; close () { if (! sbuf.close ()) this-&gt;clear (+this-&gt;rdstate () | +std::ios_base::badbit); this-&gt;clear (); return *this; } protected: template &lt;typename FNChar&gt; win32_file_stream &amp; do_open (FNChar const * file_name, std::ios_base::openmode om) { if (! sbuf.open(file_name, om)) this-&gt;clear (std::ios_base::badbit); return *this; } win32_file_streambuf&lt;typename char_type&gt; sbuf; }; template &lt;typename Stream&gt; void set_exceptions (Stream &amp; s) { s.exceptions (std::ios_base::failbit | std::ios_base::badbit | std::ios_base::eofbit); } int main(int argc, char* argv[]) { #if 0 std::mbstate_t state = std::mbstate_t (); std::locale loc (std::locale (), new std::codecvt_utf8&lt;wchar_t&gt;); typedef std::codecvt&lt;wchar_t, char, std::mbstate_t&gt; codecvt_type; codecvt_type const &amp; cvt = std::use_facet&lt;codecvt_type&gt; (loc); wchar_t ch = L'\u5FC3'; wchar_t const * from_first = &amp;ch; wchar_t const * from_mid = &amp;ch; wchar_t const * from_end = from_first + 1; char out_buf[1]; char * out_first = out_buf; char * out_mid = out_buf; char * out_end = out_buf + 1; std::codecvt_base::result cvt_res = cvt.out (state, from_first, from_end, from_mid, out_first, out_end, out_mid); // This is what I expect: if (cvt_res == std::codecvt_base::partial &amp;&amp; out_mid == out_end &amp;&amp; state != 0) ; else abort (); #endif { win32_file_stream&lt;char&gt; fs(L"test.txt"); set_exceptions (fs); fs &lt;&lt; "test\n" &lt;&lt; std::flush; fs.close (); fs.imbue (std::locale ("")); fs.open ("test.txt"); fs &lt;&lt; "test\n"; } { win32_file_stream&lt;wchar_t&gt; fs("test.txt"); set_exceptions (fs); fs.imbue (std::locale ("Japanese_Japan")); fs &lt;&lt; L"\u5FC3\n"; // KOKORO fs &lt;&lt; L"test\n"; fs.close (); std::cerr &lt;&lt; "my stream\n"; fs.open ("test.txt", std::ios_base::app); std::cerr &lt;&lt; "on open: " &lt;&lt; fs.tellp () &lt;&lt; "\n"; fs &lt;&lt; L"appended\n"; std::cerr &lt;&lt; "after output: " &lt;&lt; fs.tellp () &lt;&lt; "\n"; fs.seekp (0, std::ios_base::beg); fs &lt;&lt; L"should go to end\n"; } { win32_file_stream&lt;wchar_t&gt; fs("test.txt", std::ios_base::app); set_exceptions (fs); wchar_t buf[1]; fs.rdbuf ()-&gt;pubsetbuf (buf, 1); fs.imbue ( std::locale ( std::locale ( std::locale ("Japanese_Japan"), new std::codecvt_utf8&lt;wchar_t&gt;), new std::codecvt_utf8&lt;char&gt;)); fs &lt;&lt; L"\u5FC4\n"; } { std::cerr &lt;&lt; "ofstream\n"; std::ofstream ofs ("test.txt", std::ios_base::app); set_exceptions (ofs); std::cerr &lt;&lt; "on open: " &lt;&lt; ofs.tellp () &lt;&lt; "\n"; ofs &lt;&lt; "from ofstream\n"; std::cerr &lt;&lt; "after output: " &lt;&lt; ofs.tellp () &lt;&lt; "\n"; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T13:33:29.873", "Id": "53321", "Score": "0", "body": "Be careful imbuing a file after it has been opened. Once any data is read from the stream an imbue will usually fail. Sometimes when a file is opened the stream will read the BOM marker (thus implicitly reading from the stream). This read of the BOM can potentially cause an subsequent imbue to fail. Best to declare/imbue/open." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T13:35:40.833", "Id": "53322", "Score": "4", "body": "Lots of good looking code here. I will try and give it a bash over the weekend. But this site has very few good C++ reviewers (we are mostly used to seeing bad C++ code and correcting the obvious); so you may want to get it reviewed by other sources as well." } ]
[ { "body": "<p>When you have an <code>if</code>/<code>else</code> statement, and you find it necessary to use curly braces on the <code>if</code> statement, you should also use curly braces on the <code>else</code> statement.</p>\n\n<p>Like here:</p>\n\n<blockquote>\n<pre><code> if (result == std::codecvt_base::ok\n &amp;&amp; from_next != from_last)\n {\n to_size = dest.size () * 2;\n dest.resize (to_size);\n converted_out = to_next - to_first;\n to_first = &amp;dest.front ();\n to_last = to_first + to_size;\n to_next = to_first + converted_out;\n }\n else\n break;\n</code></pre>\n</blockquote>\n\n<p>you should have encompassed the <code>else</code> in curly brace, or even better you should have made this a guard clause to break from the <code>while</code>.</p>\n\n<p>Like this:</p>\n\n<pre><code>if (result != std::codecvt_base::ok\n &amp;&amp; from_next == from_last)\n{\n break;\n}\nto_size = dest.size () * 2;\ndest.resize (to_size);\nconverted_out = to_next - to_first;\nto_first = &amp;dest.front ();\nto_last = to_first + to_size;\nto_next = to_first + converted_out;\n</code></pre>\n\n<hr>\n\n<p>Here you have 2 specific instances where you want the function to <code>return 0;</code>:</p>\n\n<blockquote>\n<pre><code> if (! fh\n || fh == INVALID_HANDLE_VALUE)\n return 0;\n\n if (open_mode &amp; std::ios_base::ate\n &amp;&amp; do_seekoff (0, std::ios_base::end) == off_type (-1))\n return 0;\n</code></pre>\n</blockquote>\n\n<p>I think that you should merge these into one <code>if</code> statement, but if you just merge the conditional statement it will look messy. You should find good variable names for each condition statement and use the variables in one <code>if</code> statement, something like this:</p>\n\n<pre><code>bool firstCondition = ! fh || fh = INVALID_HANDLE_VALUE;\nbool secondCondition = open_mode &amp; std::ios_base::ate &amp;&amp; do_seekoff (0, std::ios_base::end) == off_type (-1);\n\nif (firstCondition || secondCondition)\n{\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>Here again you have an <code>if</code>/<code>else</code> statement where you use curly braces inconsistently:</p>\n\n<pre><code>int_type\nupdate_file_pos (DWORD written)\n{\n if (open_mode &amp; std::ios_base::app)\n {\n off_type file_size = win32_get_file_size ();\n if (file_size == -1)\n return traits_type::eof ();\n }\n else\n file_pos += written;\n\n return not_eof ();\n}\n</code></pre>\n\n<p>I advise against this. I think that when you didn't use curly braces inside the <code>if</code> block, on the one lined <code>if</code> statement, that it is acceptable, I personally don't like it but it seems reasonable. The <code>else</code> statement should have braces because the accompanying <code>if</code> statement needs the braces.</p>\n\n<hr>\n\n<p>I stopped at this <code>else</code> statement:</p>\n\n<blockquote>\n<pre><code>else\n{ \n if (converted &lt; to_convert)\n {\n // Handle partial conversion.\n // Move remaining characters down.\n\n std::ptrdiff_t const remaining_conv\n = to_convert - converted;\n traits_type::move (pb, pb + converted,\n remaining_conv);\n\n new_pmid = pb + remaining_conv;\n }\n else\n new_pmid = pb;\n\n buf = &amp;out_buf[0];\n to_write = out_buf.size ();\n}\n</code></pre>\n</blockquote>\n\n<p>My first thought was that this should just be another <code>else if</code> then <code>else</code> statement instead of a nested <code>if</code>/<code>else</code> statement, but then I noticed that you did that fun stuff with the curly braces again, and that there are 2 lines of code that need to run if the <code>else</code> statement is hit no matter what the nested <code>if</code> statement calculates to. </p>\n\n<p>Again I am going to say that I think you should use the curly braces on the <code>else</code> statement because you used them on the <code>if</code> statement.</p>\n\n<hr>\n\n<p>In the same long <code>if</code>/<code>else</code> <code>if</code>/<code>else</code> statement nest you have the following:</p>\n\n<blockquote>\n<pre><code>DWORD written = 0;\nBOOL wfret = win32_write_file (buf, to_write, written);\nif (! wfret)\n{\n //throw std::ios_base::failure(\"WriteFile\");\n ret = traits_type::eof ();\n break;\n}\n\nif (is_eof (update_file_pos (written)))\n{\n ret = traits_type::eof ();\n break;\n}\n\nif (written &lt; to_write)\n{\n ret = traits_type::eof ();\n break;\n //std::ptrdiff_t const remaining = to_write - written;\n //traits_type::move(pb, pb + written, remaining);\n //this-&gt;pbump(-static_cast&lt;std::ptrdiff_t&gt;(written));\n}\n</code></pre>\n</blockquote>\n\n<p>I really think that you should merge these together using the <code>||</code> functionality in your conditional, this will reduce these 3 statements down to just 1 statement.</p>\n\n<p>Ending up with this:</p>\n\n<pre><code>DWORD written = 0;\nBOOL wfret = win32_write_file (buf, to_write, written);\nif ((! wfret) || (is_eof (update_file_pos (written))) || (written &lt; to_write))\n{\n ret = traits_type::eof ();\n break;\n}\n</code></pre>\n\n<p><em>Note</em>: I ignored the comments in these statements.</p>\n\n<p><strong>Copy Paste Alert</strong></p>\n\n<p>In the next <code>private</code> block I found that you have the same exact 3 <code>if</code> statements preceded by 2 variables define the same exact way as above. Maybe you should think about making this a function and pass in the parameters?</p>\n\n<hr>\n\n<p>Another 3 <code>if</code> statements that should be merged using the <code>||</code> operator:</p>\n\n<blockquote>\n<pre><code>if (! is_open ())\n return pos_type (off_type (-1));\n\nif (sync () != 0)\n return pos_type (off_type (-1));\n\nif (is_eof (flush_conversion_state ()))\n return pos_type (off_type (-1));\n</code></pre>\n</blockquote>\n\n<pre><code>if ((! is_open ()) || (sync () != 0) || (is_eof (flush_conversion_state ())))\n return pos_type (off_type (-1));\n</code></pre>\n\n<p>and I am okay with not using the curly braces here, although I prefer to use them all the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:09:48.587", "Id": "158012", "Score": "1", "body": "*You should find good variable names for each condition statement and use the variables in one if statement,* - why didn't you propose such names? Your proposed solution, as it stands, is certainly worse than the original. Besides, you haven't explained why merging the statements is a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:12:23.557", "Id": "158014", "Score": "0", "body": "I am not familiar with C++ naming standards, and I thought it was pretty clear that one if statement was better than 2? please do correct me if I am wrong in that assumption, @BartekBanachewicz." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:13:52.373", "Id": "158015", "Score": "0", "body": "I don't like that this answer suggests that there are times when curly braces might be unnecessary for `if` statements, but I upvoted anyway..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:14:23.633", "Id": "158017", "Score": "0", "body": "Going by induction, you could apply that to any number of `if` statements `:)`. No, I don't think that merging two different clauses, even if they result in the same return value, is *always* a good idea. As for \"C++ naming standards\", I'm pretty sure you could do better than `first/secondCondition`; not nitpicking, I honestly think a good name suggestion would help a lot here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:14:43.277", "Id": "158018", "Score": "2", "body": "This is _all_ about formatting. It's trivial. Why not give a useful review about the code's functionality and design? I must say, though, I agree with almost all of your points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:22:52.937", "Id": "158022", "Score": "0", "body": "@LightningRacisinObrit, honestly I know very little C++, so I don't know what half the code is doing. there were several things that seemed odd to me, but I wasn't sure if it is just because that is the way it is done in C++ or not. I reviewed the code that I could and left the rest for someone with more experience to review. this is what we call a zombie question and I figured it deserved at least this much of a review. please feel free to join the regulars in [The Second Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:24:07.620", "Id": "158023", "Score": "0", "body": "@LightningRacisinObrit there is a portion of the code that I suggested be turned into a function so that there is less copy/paste going on, that isn't really *formatting*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:28:42.887", "Id": "158026", "Score": "0", "body": "It pretty much is" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:32:39.623", "Id": "158027", "Score": "0", "body": "I'm doubtful of how useful could be reviewing a 2 year old post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:38:42.357", "Id": "158030", "Score": "4", "body": "For those asking why the sudden interest in a 2-year-old post: http://meta.codereview.stackexchange.com/a/1511/31503 it ***was*** a zombie." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-20T14:05:34.093", "Id": "87434", "ParentId": "33288", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T09:14:03.323", "Id": "33288", "Score": "6", "Tags": [ "c++", "windows", "i18n" ], "Title": "custom win32_file_streambuf" }
33288
<p>I have just wrote this Pong game in Pygame:</p> <pre><code>import pygame import sys import math class Ball(object): def __init__(self, x, y, width, height, vx, vy, colour): self.x = x self.y = y self.width = width self.height = height self.vx = vx self.vy = vy self.colour = colour def render(self, screen): pygame.draw.ellipse(screen, self.colour, self.rect) def update(self): self.x += self.vx self.y += self.vy @property def rect(self): return pygame.Rect(self.x, self.y, self.width, self.height) class Paddle(object): def __init__(self, x, y, width, height, speed, colour): self.x = x self.y = y self.width = width self.height = height self.vx = 0 self.speed = speed self.colour = colour def render(self, screen): pygame.draw.rect(screen, self.colour, self.rect) def update(self): self.x += self.vx def key_handler(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.vx = -self.speed elif event.key == pygame.K_RIGHT: self.vx = self.speed elif event.key in (pygame.K_LEFT, pygame.K_RIGHT): self.vx = 0 @property def rect(self): return pygame.Rect(self.x, self.y, self.width, self.height) class Pong(object): COLOURS = {"BLACK": ( 0, 0, 0), "WHITE": (255, 255, 255), "RED" : (255, 0, 0)} def __init__(self): pygame.init() (WIDTH, HEIGHT) = (640, 480) self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Lewis' Pong") self.ball = Ball(5, 5, 50, 50, 5, 5, Pong.COLOURS["BLACK"]) self.paddle = Paddle(WIDTH / 2, HEIGHT - 50, 100, 10, 3, Pong.COLOURS["BLACK"]) self.score = 0 def play(self): clock = pygame.time.Clock() while True: clock.tick(50) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type in (pygame.KEYDOWN, pygame.KEYUP): self.paddle.key_handler(event) self.collision_handler() self.draw() def collision_handler(self): if self.ball.rect.colliderect(self.paddle.rect): self.ball.vy = -self.ball.vy self.score += 1 if self.ball.x + self.ball.width &gt;= self.screen.get_width(): self.ball.vx = -(math.fabs(self.ball.vx)) elif self.ball.x &lt;= 0: self.ball.vx = math.fabs(self.ball.vx) if self.ball.y + self.ball.height &gt;= self.screen.get_height(): pygame.quit() sys.exit() elif self.ball.y &lt;= 0: self.ball.vy = math.fabs(self.ball.vy) if self.paddle.x + self.paddle.width &gt;= self.screen.get_width(): self.paddle.x = self.screen.get_width() - self.paddle.width elif self.paddle.x &lt;= 0: self.paddle.x = 0 def draw(self): self.screen.fill(Pong.COLOURS["WHITE"]) font = pygame.font.Font(None, 48) score_text = font.render("Score: " + str(self.score), True, Pong.COLOURS["RED"]) self.screen.blit(score_text, (0, 0)) self.ball.update() self.ball.render(self.screen) self.paddle.update() self.paddle.render(self.screen) pygame.display.update() if __name__ == "__main__": Pong().play() </code></pre> <p>This is my first ever game in Pygame, so I'm asuming there's a few bad practices. Can anyone improve my code and find those bad practices?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T13:12:57.107", "Id": "53320", "Score": "0", "body": "See [this question](http://codereview.stackexchange.com/q/31408/11728) and its answer." } ]
[ { "body": "<p>Because Paddle and Ball have a lot in common, I think it would make sense if they were to inherit from a common class (PhysicalObject for instance) with size, position, velocity, color, etc...</p>\n\n<p><code>self.ball.vy = -self.ball.vy</code> can be written <code>self.ball.vy *= -1</code>.</p>\n\n<p>You could try to handle collision in a slightly more generic way by creating 4 walls inheriting from PhysicalObject around the area and then handle the collisions between 2 PhysicalObject. Also, it would be nice to have some fancy behavior like the speed of the paddle having an impact on the speed of the ball when they interact.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T22:42:21.070", "Id": "33419", "ParentId": "33289", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T12:12:46.863", "Id": "33289", "Score": "3", "Tags": [ "python", "game", "pygame" ], "Title": "Basic Pong game in Pygame" }
33289
<p>I was working on a problem set and I came across this problem:</p> <blockquote> <p>Assume <code>s</code> is a string of lower case characters.</p> <p>Write a program that prints the longest substring of <code>s</code> in which the letters occur in alphabetical order. For example, if <code>s = 'azcbobobegghakl'</code>, then your program should print:</p> <pre class="lang-none prettyprint-override"><code>Longest substring in alphabetical order is: beggh </code></pre> <p>In the case of ties, print the first substring. For example, if <code>s = 'abcbcd'</code>, then your program should print</p> <pre class="lang-none prettyprint-override"><code>Longest substring in alphabetical order is: abc </code></pre> </blockquote> <p>I actually was able to get a solution, but it was the <em>most</em> inefficient ever! And here's what I came up with:</p> <pre><code>def test(): index = 1 prev_index = 0 count = 0 global largest largest = '' test = s[prev_index] while count &lt; len(s): if ord(s[index]) &gt; ord(s[prev_index]): test += s[index] index += 1 prev_index += 1 elif ord(s[index]) == ord(s[prev_index]): test += s[index] index += 1 prev_index += 1 else: if len(largest) &lt; len(test): largest = test[:] test = s[index] prev_index += 1 index += 1 count += 1 return largest try: test() except IndexError: pass finally: print largest </code></pre> <p>Can anyone give me an example of better code that produces the same output?</p>
[]
[ { "body": "<p>It's the famous <a href=\"http://en.wikipedia.org/wiki/Talk%3aLongest_increasing_subsequence\" rel=\"nofollow\">Longest increasing subsequence</a> problem. Convert the chars to ints using the ord function</p>\n\n<pre><code>def longest_increasing_subsequence(X):\n \"\"\"\n Find and return longest increasing subsequence of S.\n If multiple increasing subsequences exist, the one that ends\n with the smallest value is preferred, and if multiple\n occurrences of that value can end the sequence, then the\n earliest occurrence is preferred.\n \"\"\"\n n = len(X)\n X = [None] + X # Pad sequence so that it starts at X[1]\n M = [None]*(n+1) # Allocate arrays for M and P\n P = [None]*(n+1)\n L = 0\n for i in range(1,n+1):\n if L == 0 or X[M[1]] &gt;= X[i]:\n # there is no j s.t. X[M[j]] &lt; X[i]]\n j = 0\n else:\n # binary search for the largest j s.t. X[M[j]] &lt; X[i]]\n lo = 1 # largest value known to be &lt;= j\n hi = L+1 # smallest value known to be &gt; j\n while lo &lt; hi - 1:\n mid = (lo + hi)//2\n if X[M[mid]] &lt; X[i]:\n lo = mid\n else:\n hi = mid\n j = lo\n\n P[i] = M[j]\n if j == L or X[i] &lt; X[M[j+1]]:\n M[j+1] = i\n L = max(L,j+1)\n\n # Backtrack to find the optimal sequence in reverse order\n output = []\n pos = M[L]\n while L &gt; 0:\n output.append(X[pos])\n pos = P[pos]\n L -= 1\n\n output.reverse()\n return output\n\ndef main():\n TEST_STRING = 'azcbobobegghakl'\n print(''.join(map(chr, longest_increasing_subsequence(map(ord, TEST_STRING)))))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T18:54:54.023", "Id": "53332", "Score": "0", "body": "In the OP's problem it's clear that the sequence must be *contiguous* (consider the first example, where the answer is `beggh`, not `abegghkl`). So your answer is solving a different problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T19:16:44.660", "Id": "53333", "Score": "0", "body": "The example was invisible and there aren't any word about contiguous sequence only." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T19:20:53.207", "Id": "53335", "Score": "0", "body": "The OP may have been poorly formatted but [the example was not invisible if you read it carefully](http://codereview.stackexchange.com/revisions/33291/1)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T18:29:49.067", "Id": "33297", "ParentId": "33291", "Score": "-1" } }, { "body": "<p>This answer doesn't have docstrings (Python isn't my main language), but the basic idea is to just start at every character and see how far you can go:</p>\n\n<pre><code>def longest_nondecreasing(s):\n start = -1\n maxlen = -1\n\n for i in range(len(s)): \n for j in range(i+1, len(s)):\n if s[j] &lt; s[i]: \n break\n else: # we made it to the end!\n j = len(s)\n\n #so now our nondecreasing string goes from i to j\n if j - i &gt; maxlen:\n maxlen = j - i\n start = i\n\n return s[start:start + maxlen]\n</code></pre>\n\n<p>Once we have a working solution, we can work on making some optimizations. For instance, if we have one contiguous non-decreasing sequence from say... 4 to 9, we definitely know that the longest non-decreasing sequence starting at 5 will also end at 9. Hence after the <code>j</code> loop we can just set <code>i</code> to <code>j</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:28:57.153", "Id": "53529", "Score": "0", "body": "The Python tutorial [explains how to write documentation strings](http://docs.python.org/3/tutorial/controlflow.html#defining-functions). It's not hard!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T21:52:33.160", "Id": "33304", "ParentId": "33291", "Score": "0" } }, { "body": "<p>Your algorithm is basically fine, but it is expressed in the code clumsily.</p>\n\n<p>The biggest problem is the interface of the function: it should accept a string parameter and return a string. Instead, your function takes <code>s</code> from its environment and uses the global variable <code>largest</code> to store the answer. Although there is a <code>return largest</code> statement, it is very misleading. What actually happens is that <code>s[index]</code> raises an <code>IndexError</code>, so that the <code>return largest</code> is never reached, and the answer is passed back using the global variable instead.</p>\n\n<p>The root cause for the <code>IndexError</code> is that there are too many variables, causing confusion. With each iteration through the loop, you increment <code>index</code>, <code>prev_index</code>, and <code>count</code>. That means that those three variables could be reduced to one, which could just be called <code>i</code>. (If you think about it, you'll find that <code>count</code> is always one less than <code>index</code>. Since the loop condition is <code>count &lt; len(s)</code>, <code>s[index]</code> will go one position beyond the end of the string.)</p>\n\n<p>The next observation to make is that your <code>if</code> and <code>elif</code> blocks are almost identical. You can combine them by using <code>&gt;=</code> for the test.</p>\n\n<p>Python strings are immutable, so <code>largest = test[:]</code> could just be <code>largest = test</code>.</p>\n\n<p>Putting everything together…</p>\n\n<pre><code>def longest_nondecreasing_substring(s):\n if s is None or len(s) &lt;= 1:\n return s\n\n longest = test = s[0]\n\n for i in range(1, len(s)):\n if ord(s[i]) &gt;= ord(s[i - 1]):\n test += s[i]\n else:\n if len(longest) &lt; len(test):\n longest = test\n test = s[i]\n if len(longest) &lt; len(test):\n longest = test\n return longest\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T10:26:22.170", "Id": "53447", "Score": "0", "body": "What, no docstring?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T22:16:51.193", "Id": "33306", "ParentId": "33291", "Score": "2" } } ]
{ "AcceptedAnswerId": "33306", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T13:14:37.673", "Id": "33291", "Score": "4", "Tags": [ "python", "optimization", "algorithm", "strings" ], "Title": "Improving efficiency for finding longest contiguous non-decreasing substring" }
33291
<p>Recently I was asked in an interview to convert the string say "aabbbccccddddd" to "a2b3c4d5". i.e we have to avoid repeating same character and just adding the repeat count. Here 'a' is repeated twice in the input and so we have to write it as 'a2' in the output. Also i have to write a function to reverse the format (i.e from the string "a2b3c4d5" to "aabbbccccddddd") back to the original one. I was free to use either C or C++ language. I have tried the below code. But the interviewer seems to be not very happy with this. He asked me to try some smart way than this.</p> <p>In the below code, I used <code>formatstring()</code> to eliminate repeated chars by just adding the repeated count and used <code>reverseformatstring()</code> to convert back to the original string.</p> <p><strong><code>formatstring()</code></strong></p> <pre><code>void formatstring(char* target, const char* source) { int charRepeatCount = 1; bool isFirstChar = true; while (*source != '\0') { if (isFirstChar) { //Whatever be the first character, we have to add it to the target isFirstChar = false; *target = *source; source++; target++; }else { if (*source == *(source-1)) { //Comparing the current char with previous one and incrementing repeat count charRepeatCount++; source++; }else { if (charRepeatCount &gt; 1) { //Converting repeat count to string and appending it to the target char repeatStr[10]; _snprintf(repeatStr, 10, "%i", charRepeatCount); int repeatCount = strlen(repeatStr); for (int i = 0; i &lt; repeatCount; i++) { *target = repeatStr[i]; target++; } charRepeatCount = 1; //Reseting repeat count } *target = *source; source++; target++; } } } if (charRepeatCount &gt; 1) { //Converting repeat count to string and appending it to the target char repeatStr[10]; _snprintf(repeatStr, 10, "%i", charRepeatCount); int repeatCount = strlen(repeatStr); for (int i = 0; i &lt; repeatCount; i++) { *target = repeatStr[i]; target++; } } *target = '\0'; } </code></pre> <p><strong><code>reverseformatstring()</code></strong></p> <pre><code>void reverseformatstring(char* target, const char* source) { int charRepeatCount = 0; bool isFirstChar = true; while (*source != '\0') { if (isFirstChar) { //Whatever be the first character, we have to add it to the target isFirstChar = false; *target = *source; source++; target++; }else { if (isalpha(*source)) { //If current char is alphabet, we can simply add it to the target *target = *source; target++; source++; } else { while (isdigit(*source)) //Getting repeat count of previous character { int currentDigit = (*source) - '0'; charRepeatCount = (charRepeatCount == 0) ? currentDigit : (charRepeatCount * 10 + currentDigit); source++; } //Decrement repeat count as we have already written first unique char to the target charRepeatCount--; while (charRepeatCount &gt; 0) //Repeating the last char for this count { *target = *(target - 1); target++; charRepeatCount--; } } } } *target = '\0'; } </code></pre> <p>I didn't find any issues with the above one. Is there any better way of doing the same?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T13:51:01.207", "Id": "53323", "Score": "0", "body": "First. Don't write C and claim it is C++. The languages are very distinct in the style they are used (they may have the same underlying base syntax but their usage is very different and good C is not nesacerily good C++). So what language did you use C or C++. The answer is important on how we review the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T14:08:04.753", "Id": "53324", "Score": "0", "body": "@LokiAstari, Yes I understand it. I have used C rather than C++." } ]
[ { "body": "<h3>Did you ask any questions before you started?</h3>\n<p>It seems like there are a couple of holes in the design that need firming up.</p>\n<ol>\n<li>Is there a maximum run length? (ie is single digit lengths enough)</li>\n<li>Does the input string only contain alpha? (ie no numbers).</li>\n<li>Do you encode single character runs? (ababab =&gt; a1b1a1b1a1b1 or ababab)</li>\n</ol>\n<h3>General comments</h3>\n<p>The algorithm you are using is too complex.<br />\nSome of the answers on SO show you how to simplify the algorithm so I will not repeat that here (they are all good).</p>\n<h3>Code comments</h3>\n<p>Don't put two variables on a line:</p>\n<pre><code>int charRepeatCount = 0; bool isFirstChar = true;\n</code></pre>\n<p>Any function that begins with an underscore is a not a good idea.</p>\n<pre><code>_snprintf(repeatStr, 10, &quot;%i&quot;, charRepeatCount);\n</code></pre>\n<p>The underscore means that it is implementation defined. If there are no alternatives fine. But always prefer standard functions to non-standard implementations hacks (especially if they were done by MS). In this specific case the standard one is better designed and make usage easier.</p>\n<p>Also why are you printing to a character array then copying to the destination array?</p>\n<pre><code> _snprintf(repeatStr, 10, &quot;%i&quot;, charRepeatCount);\n int repeatCount = strlen(repeatStr);\n for (int i = 0; i &lt; repeatCount; i++)\n {\n *target = repeatStr[i];\n target++;\n }\n</code></pre>\n<p>You can print directly to the destination:</p>\n<pre><code> sprintf(target, &quot;%i&quot;, charRepeatCount); // notice not snprintf because I\n // I don't know the size of the\n // target. That is comming up.\n // You should definately use the\n // snprintf() version if you can.\n</code></pre>\n<p>You have sections of repeated code (the bit above).<br />\nIf you are repeating code you should break it into a separate function.</p>\n<p>Interface design:</p>\n<pre><code>void formatstring(char* target, const char* source)\n</code></pre>\n<p>I have no idea how much space I am allowed to use in target. Either allow the function to allocate its own space (and return the pointer) or get a maximum size passed into the function. If you pass in a size the return value is usually the amount of space you would have needed to succeed. This allows the user to do pre-flighting to work out the size required.</p>\n<pre><code>int size = LokiFormatString(source, NULL, 0);\nchar* tareget = (char*) malloc(size + 1);\nint size = LokiFormatString(source, target, size);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T14:39:36.847", "Id": "33294", "ParentId": "33293", "Score": "5" } }, { "body": "<p>I'll just go over the first function. Step one should always be a working solution, we can always deal with optimizations later (obvious example would be not using <code>sprintf</code>...)</p>\n\n<pre><code>void formatstring(char* dst, const char* src) \n{\n while (*src) {\n // in this loop, we'll do one char/num pair at a time\n *dst = *src++;\n\n int count = 1;\n for (; *src == *dst; ++src) {\n ++count;\n }\n\n // now src points to a different character than we started with\n // .. which could be the end of the string too\n ++dst; \n dst += sprintf(dst, \"%d\", count);\n }\n\n *dst = 0; // remember to null terminate\n}\n</code></pre>\n\n<p>That is how I would do it in C, anyway. In C++, we can get some more clarity by using algorithms and <code>std::string</code>:</p>\n\n<pre><code>std::string formatString(const std::string&amp; src) {\n std::ostringstream dst;\n auto it = src.begin();\n\n while (it != src.end()) {\n dst &lt;&lt; *it;\n\n auto next = std::find_if(it, src.end(), [&amp;](const char c) { \n return c != *it; \n });\n\n dst &lt;&lt; std::distance(it, next);\n it = next;\n }\n\n return dst.str();\n}\n</code></pre>\n\n<p>Probably worse performance, but that shouldn't be an issue until it is. Here we just take advantage of <code>stringstream</code> knowing how to write integers, and take advantage of <code>find_if</code> to do the look-ahead instead of writing our own loop. Also, <code>stringstream</code> takes care of the terminating 0 so we don't have to worry about it. </p>\n\n<p><strong>Update:</strong> Wanted to add the other function too. Again with C++ if performance isn't an issue, we can do this very cleanly using the objects at our disposal in the standard:</p>\n\n<pre><code>std::string reverse_format_string(const std::string&amp; input_str) {\n std::istringstream input(input_str); \n std::string output;\n\n char c;\n int count;\n\n while (input &gt;&gt; c &gt;&gt; count) {\n output += std::string(count, c); // this is the string ctor that gives you a string of 'count' c's. \n }\n\n return output;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T22:27:49.520", "Id": "33307", "ParentId": "33293", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T13:22:52.020", "Id": "33293", "Score": "0", "Tags": [ "c", "strings", "interview-questions", "compression" ], "Title": "Run-length encoding using C" }
33293
<p>I need to optimize this piece of code I made because this will run in real-time mode.</p> <p>It's a matrix shifter that pulls downward and will neglect any transparent element.</p> <p><strong>Code:</strong></p> <pre><code>void shiftDown(int col) { int x = 0; //transparent element int N = 5; //size int i,j,k,l; for ( i = N - 1;i &gt;= 0; --i ) { if( map[i][col] == x ) { for( j = i;j &gt;= 0; --j ) { if ( map[j][col] != x ) { for ( l = i, k = j;l &gt;= 0; --l, --k ) { map[l][col] = map[k][col]; } } } } } } </code></pre> <p><strong>Data:</strong></p> <p>(<em>before</em>)</p> <pre><code>0 2 3 2 0 0 1 4 0 1 1 2 2 0 3 2 1 0 0 4 4 3 1 1 3 </code></pre> <p>(<em>after</em>)</p> <pre><code>0 2 0 0 0 0 1 3 0 1 1 2 4 0 3 2 1 2 2 4 4 3 1 1 3 ^ ^ </code></pre> <p><strong>Other code</strong></p> <pre><code>int map[][5] = { {0, 2, 3, 2, 0}, {0, 1, 4, 0, 1}, {1, 2, 2, 0, 3}, {2, 1, 0, 0, 4}, {4, 3, 1, 1, 3} }; void printMap(); void shiftDown(int col); int main() { cout &lt;&lt; "before\n"; printMap(); for (int i = 0;i &lt; 5; ++i) { shiftDown(i); } cout &lt;&lt; "after\n"; printMap(); cin.get(); return 0; } void printMap() { for (int row = 0;row &lt; 5; ++row) { for (int col = 0;col &lt; 5; ++col) { cout &lt;&lt; map[row][col] &lt;&lt; '\t'; } cout &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl &lt;&lt; endl; } } </code></pre> <p><strong>Note:</strong> Looked at my comment again and I need to correct my error. Its <code>int map[N][N]</code> again. This will not work for M x N matrix.</p>
[]
[ { "body": "<p>You can sort each column separately (only move the transparent value to the top of the column) with a fast sorting algorithm like merge sort:</p>\n\n<pre><code>void mergeSortBlock(int *a, int index1, int index2, int size, int transparent){\n int *result;\n int resultIndex = 0;\n int mergeIndex1 = index1;\n int mergeIndex2 = index2;\n\n result = new int [size*2];\n\n while (mergeIndex1 &lt;= (index1 + size -1) &amp;&amp; mergeIndex2 &lt;= (index2 + size -1)){\n if (a[mergeIndex2] == transparent) { // check the transparency\n result[resultIndex] = a[mergeIndex2];\n resultIndex++;\n mergeIndex2++;\n }\n else {\n result[resultIndex] = a[mergeIndex1];\n resultIndex++;\n mergeIndex1++;\n }\n }\n\n if (mergeIndex2 &lt;= (index2 + size - 1)) {\n for (int i = mergeIndex2 ; i&lt; (index2 + size); i++) {\n result[resultIndex] = a[mergeIndex2];\n resultIndex++;\n mergeIndex2++; \n }\n }\n else{\n for (int i = mergeIndex1 ; i&lt; (index1 + size); i++) {\n result[resultIndex] = a[mergeIndex1];\n resultIndex++;\n mergeIndex1++;\n }\n }\n\n // copy the result back\n for (int i=0; i &lt; size*2; i++) {\n a[index1+i] = result[i];\n } \n delete [] result;\n}\n\nvoid mergeSort(int *a, int indexFront,int indexEnd, int transparent){\n int size = (indexEnd - indexFront +1)/2;\n if (size &gt; 1){\n mergeSort(a, indexFront, indexFront + size - 1, transparent); \n mergeSort(a, indexFront + size, indexEnd, transparent);\n }\n mergeSortBlock(a, indexFront, indexFront + size, size, transparent);\n}\n</code></pre>\n\n<p>As you can see, in the <strong>mergeSortBlock</strong> function, instead of examining <code>a[mergeIndex1]&gt;a[mergeIndex2]</code> you check the <strong>transparency</strong> condition.</p>\n\n<p>the <strong>indexFront</strong> is the index of the first element of your array and <strong>indexEnd</strong> is the index of the last element.</p>\n\n<p>Now in your main, first you need to transpose the matrix so that the <em>ith</em> row of the transposed matrix (called <strong>result</strong> in this example) represents the <em>ith</em> column of your <strong>map</strong> matrix. then call the <strong>mergeSort</strong> function for each row of the transposed matrix, <strong>Result</strong> . </p>\n\n<pre><code>int main()\n int result[5][5];\n int map[][5] =\n {\n {0, 2, 3, 2, 0},\n {0, 1, 4, 0, 1},\n {1, 2, 2, 0, 3},\n {2, 1, 0, 0, 4},\n {4, 3, 1, 1, 3}\n };\n\n //transpose map =&gt; map's ith column = result's ith row\n for (int i = 0; i&lt;5; i++)\n for (int j = 0; j&lt;5; j++)\n result[j][i] = map[i][j];\n\n\n for (int i=0; i&lt;5; i++) \n mergeSort(result[i],0,4,0);\n\n\n //transpose reuslt =&gt; result's ith row = map's ith column\n for (int i = 0; i&lt;5; i++)\n for (int j = 0; j&lt;5; j++)\n map[j][i] = result[i][j];\n\n return 0;\n}\n</code></pre>\n\n<p>At the end again we need to transpose the matrix <strong>result</strong>.</p>\n\n<p>Note: The complexity of merge sort is O(n.logn). You have n columns. This makes the complexity of the matrix shifter O(n^2.logn). Thanks to the nature of your problem, you can still improve this by parallel programming (of course if you have multiple processors). The complexity of transpose is O(n^2). The complexity of your own algorithm is O(n^3). </p>\n\n<p>Note2: You can modify <strong>mergeSort</strong> and <strong>mergeSortBlock</strong> functions to work directly with the columns of your matrix. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:59:18.047", "Id": "53513", "Score": "0", "body": "Thanks for answering, but that would alter all its content. I need to preserved their order. Only the `transparent` element are needed to move up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:25:46.473", "Id": "53545", "Score": "0", "body": "@mr5: I know. You can still do it. check the answer. Hope it's clear enough." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:31:46.427", "Id": "53546", "Score": "0", "body": "I haven't tested this entire thing yet, but it looks like you should still consider an `std::vector` to avoid the `new` and `delete`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:37:07.467", "Id": "53547", "Score": "0", "body": "@Jamal: Yes, you can use `std::vector`. You can also use smart pointers like `std::auto_ptr` or `boost::shared_ptr` but that's beyond the scope of this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:38:05.983", "Id": "53548", "Score": "0", "body": "Right, but it could help with optimization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:38:52.443", "Id": "53549", "Score": "0", "body": "@Jamal: I don't think so :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:41:54.640", "Id": "53550", "Score": "0", "body": "Eh, well, I suppose it comes down to whether or not the OP can use the STL. It's your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T10:18:33.340", "Id": "53582", "Score": "0", "body": "@NejlaGhaboosi Uhmm, your code kinda alter all the columns position of the matrix. The logic is that pull down all `non-transparent` element on every column preserving their order. See the output [here](http://ideone.com/kRsDi7) or I think I don't get it right. Also the size of the matrix should be N x N (2 dimensional) and `5` != N x N." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T11:02:03.870", "Id": "53584", "Score": "0", "body": "@mr5 No you didn't get it right and what is 5? I didn't get it. What I wrote above was a one dimensional array (just an example to show you how you can call the function). anyway, I write your full code tomorrow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-28T08:17:09.687", "Id": "74242", "Score": "0", "body": "you can also use openMP in order to do it :)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:51:47.997", "Id": "33388", "ParentId": "33299", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T19:19:41.010", "Id": "33299", "Score": "2", "Tags": [ "c++", "optimization", "matrix" ], "Title": "Optimizing this matrix shifter" }
33299
<p>I recently had a programming challenge, which was to create the N grams. The description is as follows:</p> <blockquote> <p>Trigram analysis is very simple. Look at each set of three adjacent words in a document. Use the first two words of the set as a key, and remember the fact that the third word followed that key. Once you’ve finished, you know the list of individual words that can follow each two word sequence in the document. For example, given the input:</p> <pre><code>I wish I may I wish I might </code></pre> <p>You might generate:</p> <pre><code>"I wish" =&gt; ["I", "I"] "wish I" =&gt; ["may", "might"] "may I" =&gt; ["wish"] "I may" =&gt; ["I"] </code></pre> <p>This says that the words "I wish" are twice followed by the word "I", the words "wish I" are followed once by "may" and once by "might" and so on. To generate new text from this analysis, choose an arbitrary word pair as a starting point. Use these to look up a random next word (using the table above) and append this new word to the text so far. This now gives you a new word pair at the end of the text, so look up a potential next word based on these. Add this to the list, and so on. In the previous example, we could start with "I may". The only possible next word is "I", so now we have:</p> <pre><code>I may I </code></pre> <p>The last two words are "may I", so the next word is "wish". We then look up "I wish", and find our choice is constrained to another "I".</p> <pre><code>I may I wish I </code></pre> <p>Now we look up "wish I", and find we have a choice. Let’s choose "may".</p> <pre><code>I may I wish I may </code></pre> <p>Now we’re back where we started from, with "I may." Following the same sequence, but choosing "might" this time, we get:</p> <pre><code>I may I wish I may I wish I might </code></pre> <p>At this point we stop, as no sequence starts "I might." Given a book, so the resulting output can be surprising.</p> </blockquote> <p>I've implemented this idea in Java with generic Ngrams, whose value should be > 1. I want to know whether I can improve the efficiency of my code like runtime or space complexity.</p> <pre><code>public class Ngrams { private String words[]; // List of words in Supplied String private HashMap&lt;String ,List&lt;String&gt; &gt; nGramsMap; // Mapping of the Ngrams private int n; // Value for NGram Ngrams(String text, int n){ if(n&lt;1 || text==null || text.length()==0) throw new IllegalArgumentException("Check the input Parameters : String Should not be null or empty and Ngram value should be &gt; 1"); words=text.split(" "); nGramsMap=new HashMap&lt;String ,List&lt;String&gt;&gt;(); this.n=n; } public Map&lt;String ,List&lt;String&gt;&gt; generateNgrams( ){ // Filling the HashMap based on N value and using WOrds Array /*Look at each set of N adjacent words in a document. Use the first N-1 words of the set as a key, and remember the fact that the nth word followed that key. Once you’ve finished, you know the list of individual words that can follow each N-1 word sequence in the document. */ for(int i=0; i &lt;= words.length-n ;i++ ){ StringBuilder sb=new StringBuilder(); int j=0; while(j &lt; n-1){ sb.append(words[i+j].trim()); j++ ; if(j&lt;n-1) sb.append(" "); } String key=sb.toString(); if(!nGramsMap.containsKey(key)){ ArrayList&lt;String&gt; list=new ArrayList&lt;&gt;(); list.add(words[i+j]); nGramsMap.put(key, list); }else{ List&lt;String&gt; list=nGramsMap.get(key); list.add(words[i+j]); } // System.out.println("Key: "+key+" Value : "+words[i+j]); } return nGramsMap; } public String getNGramsText( ){ /* To generate new text from this analysis, choose an arbitrary word pair as a starting point. Use these to look up a random next word (using the table above) and append this new word to the text so far. This now gives you a new word pair at the end of the text, so look up a potential next word based on these. Add this to the list, and so on. */ if(nGramsMap.size()==0) generateNgrams( ); StringBuilder result= new StringBuilder(); Random gen=new Random(); int st= gen.nextInt(words.length-n); //arbitrary word pair StringBuilder startSb=new StringBuilder(); for(int i=0;i&lt; n-1;i++){ startSb.append(words[st+i]); if(i+1&lt; n-1)startSb.append(" "); } String start= startSb.toString(); result.append(start+" "); while(true){ int size=nGramsMap.get(start).size(); String next; if(size&gt;1){ st=gen.nextInt(size-1); next=nGramsMap.get(start).remove(st); } else{ st=0; next=nGramsMap.get(start).get(st); } String start_split[]=start.split(" "); String nextKey; if(start_split.length&gt;1) { nextKey=start.substring(start_split[0].length()+1); start= nextKey+" "+next; } else { start=next; } result.append(next); //append this new word to the text so far if(nGramsMap.containsKey(start)) result.append(" "); else break; } return result.toString(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T22:51:44.547", "Id": "64387", "Score": "0", "body": "Can you include a `main()` method so that people can copy and paste this code, and immediately run it? It would help a lot in knowing whether I can improve the efficiency of the code (run-time or space complexity)." } ]
[ { "body": "<p>If <code>text</code> is <code>null</code>, you throw an <code>IllegalArgumentException</code>. It should throw a <code>NullPointerException</code>.</p>\n\n<pre><code>if (text == null) throw new NullPointerException(\"Check the input parameters: String should not be null\");\nif(n&lt;1 || text.length()==0) throw new IllegalArgumentException(\"Check the input parameters : String should not empty and Ngram value should be &gt; 1\");\n</code></pre>\n\n<p><strong>If</strong> the user is inputting the text directly I don't believe text can be <code>null</code> (I'm not completely sure on this), you can simplify your <code>if</code> condition test down a bit using the <code>String</code> method <code>.equals()</code>.</p>\n\n<pre><code>if (n&lt;1 || text.equals(\"\"))\n</code></pre>\n\n<p>I included the upper example in the final code.</p>\n\n<hr>\n\n<p>I am usually in support of using whitespace in programming. However, in this case I think you have a lot of superfluous whitespace in your program. Especially in between braces.</p>\n\n<pre><code>// There are only 4 real lines of code here, 5 if you include the comment.\n// With your spacing scheme you have 10 (comment included).\n\n }\n\n\n// System.out.println(\"Key: \"+key+\" Value : \"+words[i+j]);\n }\n\n return nGramsMap;\n\n\n }\n</code></pre>\n\n<hr>\n\n<p>You comment what the variable <code>n</code> is, instead of giving it a more helpful name to begin with. It's good that you had the comment though, many people don't comment what obscure variables mean.</p>\n\n<pre><code>private int value; // Value for NGram\n</code></pre>\n\n<hr>\n\n<p>I don't see the imports you need. I assume you have all of these somewhere else in your program.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\n</code></pre>\n\n<hr>\n\n<p>Other than that, the program looks pretty good. You didn't include <code>main()</code>, so I couldn't do too much refining without making sure I wasn't breaking the program.</p>\n\n<h2>Final code:</h2>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\npublic class Test\n{\n\n private String words[]; // List of words in Supplied String\n private HashMap&lt;String, List&lt;String&gt;&gt; nGramsMap; // Mapping of the Ngrams\n private int value; // Value for NGram\n\n Test(String text, int n)\n {\n if (text == null) throw new NullPointerException(\"Check the input parameters: String should not be null\");\n if(n&lt;1 || text.length()==0) throw new IllegalArgumentException(\"Check the input parameters : String should not empty and Ngram value should be &gt; 1\");\n\n words = text.split(\" \");\n nGramsMap = new HashMap&lt;String, List&lt;String&gt;&gt;();\n this.value = n;\n }\n\n public Map&lt;String, List&lt;String&gt;&gt; generateNgrams()\n {\n // Filling the HashMap based on N value and using WOrds Array\n\n /*\n * Look at each set of N adjacent words in a document. Use the first N-1 words of the set as a key, and remember the fact that the nth word\n * followed that key. Once you’ve finished, you know the list of individual words that can follow each N-1 word sequence in the document.\n */\n for (int i = 0; i &lt;= words.length - value; i++)\n {\n StringBuilder sb = new StringBuilder();\n int j = 0;\n\n while (j &lt; value - 1)\n {\n sb.append(words[i + j].trim());\n j++;\n if (j &lt; value - 1) sb.append(\" \");\n }\n\n String key = sb.toString();\n\n if (!nGramsMap.containsKey(key))\n {\n\n ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();\n list.add(words[i + j]);\n nGramsMap.put(key, list);\n\n }\n else\n {\n List&lt;String&gt; list = nGramsMap.get(key);\n list.add(words[i + j]);\n }\n // System.out.println(\"Key: \"+key+\" Value : \"+words[i+j]);\n }\n return nGramsMap;\n }\n\n public String getNGramsText()\n {\n /*\n * To generate new text from this analysis, choose an arbitrary word pair as a starting point. Use these to look up a random next word (using\n * the table above) and append this new word to the text so far. This now gives you a new word pair at the end of the text, so look up a\n * potential next word based on these. Add this to the list, and so on.\n */\n if (nGramsMap.size() == 0) generateNgrams();\n StringBuilder result = new StringBuilder();\n Random gen = new Random();\n int st = gen.nextInt(words.length - value); // arbitrary word pair\n StringBuilder startSb = new StringBuilder();\n\n for (int i = 0; i &lt; value - 1; i++)\n {\n startSb.append(words[st + i]);\n if (i + 1 &lt; value - 1) startSb.append(\" \");\n }\n\n String start = startSb.toString();\n\n result.append(start + \" \");\n\n while (true)\n {\n\n int size = nGramsMap.get(start).size();\n String next;\n if (size &gt; 1)\n {\n st = gen.nextInt(size - 1);\n next = nGramsMap.get(start).remove(st);\n }\n else\n {\n st = 0;\n next = nGramsMap.get(start).get(st);\n }\n\n String start_split[] = start.split(\" \");\n String nextKey;\n if (start_split.length &gt; 1)\n {\n nextKey = start.substring(start_split[0].length() + 1);\n start = nextKey + \" \" + next;\n }\n else start = next;\n\n result.append(next); // append this new word to the text so far\n\n if (nGramsMap.containsKey(start)) result.append(\" \");\n else break;\n }\n return result.toString();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T10:07:37.983", "Id": "64419", "Score": "0", "body": "I would either keep the `IllegalArgumentException` or let it trigger `NullPointerException` naturally. Throwing `NullPointerException` deliberately is weird, in my opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T10:34:14.423", "Id": "64423", "Score": "1", "body": "`IAE` vs `NPE` and the debate goes on...! :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T12:21:19.500", "Id": "64432", "Score": "0", "body": "Also, I think `n` is actually clearer than `value`. It is, after all, an n-gram, so `n` is self-documenting in this domain." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T22:30:21.863", "Id": "38596", "ParentId": "33300", "Score": "5" } }, { "body": "<p>I'm not a linguistics expert, but I believe <code>n &lt;= 1</code> should be illegal, because I have a hard time seeing how the <code>n == 1</code> case should behave.</p>\n\n<p>I think that an n-gram would be better represented as an n-level trie, as evidenced by all the work necessary to split and concatenate words to form the keys. Nevertheless, I'll continue this answer using maps of concatenated words to lists of words, since it would be hard to write a review incorporating such a radical change.</p>\n\n<p>My biggest complaint is that <code>getNGramsText()</code> cheats by using the <code>words</code> array. Isn't the point of the exercise to reconstruct the text using only the n-gram data? To enforce discipline, I would recommend an interface like the following:</p>\n\n<pre><code>public class NGramAnalyzer {\n public NGramAnalyzer(int n) { ... }\n\n public Map&lt;String, List&lt;String&gt;&gt; fromText(String text) { ... }\n\n public static String toText(Map&lt;String, List&lt;String&gt;&gt; nGrams) { ... }\n}\n</code></pre>\n\n<p>To arbitrarily pick the initial words for the reconstructed text, just use any key of the map. Also, I believe that the code to generate <code>nextKey</code> can be simplified to:</p>\n\n<pre><code>String nextKey = start.substring(1 + start.indexOf(\" \")) + \" \" + next;\n</code></pre>\n\n<p>I recommend a few changes to <code>generateNgrams()</code>, noted in comments:</p>\n\n<pre><code>public Map&lt;String, List&lt;String&gt;&gt; fromText(String text) {\n // Use .isEmpty() instead of .length() == 0\n if (text == null || text.isEmpty()) {\n throw new IllegalArgumentException(\"null or empty text\");\n }\n String[] words = text.split(\" \");\n Map&lt;String, List&lt;String&gt;&gt; nGramsMap = new HashMap&lt;String, List&lt;String&gt;&gt;();\n\n for(int i = 0; i &lt;= words.length-n ; i++) {\n // Renamed sb to give it purpose. Use a for-loop.\n // Removed the special case within the loop.\n StringBuilder keyBuilder = new StringBuilder(words[i].trim());\n for (int j = 1; j &lt; n - 1; j++) {\n keyBuilder.append(' ').append(words[i + j].trim());\n }\n String key = keyBuilder.toString();\n\n // Calling .containsKey() is redundant work; just call .get().\n // (The only reason to call .containsKey() would be to check for\n // an entry with a null value, which wouldn't be the case for us.)\n List&lt;String&gt; list = nGramsMap.get(key);\n if (list == null) {\n nGramsMap.put(key, list = new ArrayList&lt;String&gt;());\n }\n // Added benefit: we can write the following line just once.\n list.add(words[i + n - 1]);\n }\n return nGramsMap;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-05T12:19:21.537", "Id": "38624", "ParentId": "33300", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T20:06:35.413", "Id": "33300", "Score": "11", "Tags": [ "java", "performance" ], "Title": "N grams generator" }
33300
<p>I have a method which checks all of its surrounding squares and returns the number of bombs around it. It uses a long list of <code>if</code> statements, which is pretty ugly and probably inefficient.</p> <pre><code> public int countArround(){ int bombNum = 0; //x=0 y=1 works if(((SmartSquare)board.getSquareAt(xLocation, yLocation+1)!=null)&amp;&amp; (((SmartSquare)board.getSquareAt(xLocation, yLocation+1)).getBomb())){ bombNum++; } //x=1 y=1 if(((SmartSquare)board.getSquareAt(xLocation+1, yLocation+1)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation +1, yLocation+1)).getBomb()){ bombNum++; } //x=1 y=0 works if(((SmartSquare)board.getSquareAt(xLocation+1, yLocation)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation+1, yLocation)).getBomb()){ bombNum++; } //x=1, y=-1 works if(((SmartSquare)board.getSquareAt(xLocation+1, yLocation-1)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation+1, yLocation-1)).getBomb()){ bombNum++; } //x=0 y=-1 if(((SmartSquare)board.getSquareAt(xLocation, yLocation-1)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation, yLocation-1)).getBomb()){ bombNum++; } //x=-1, y=-1 works if(((SmartSquare)board.getSquareAt(xLocation-1, yLocation-1)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation-1, yLocation-1)).getBomb()){ bombNum++; } //x=-1, y=0 works if(((SmartSquare)board.getSquareAt(xLocation-1, yLocation)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation-1, yLocation)).getBomb()){ bombNum++; } //x=-1 y=1 works if(((SmartSquare)board.getSquareAt(xLocation-1, yLocation+1)!=null)&amp;&amp; ((SmartSquare)board.getSquareAt(xLocation-1, yLocation+1)).getBomb()){ bombNum++; } return bombNum; </code></pre> <p>I was wondering how this can be cleaned up. I cannot seem to get it into an <code>if/while/for</code> statement.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T08:11:33.610", "Id": "53372", "Score": "1", "body": "Related question: [Neighbors of a matrix element](http://codereview.stackexchange.com/q/33042/9357)" } ]
[ { "body": "<p>A double-for-loop over <code>x</code> and <code>y</code> seems appropriate.</p>\n\n<p>Also, it seems like a good idea to assign <code>(SmartSquare)board.getSquareAt(...)</code> to a variable.</p>\n\n<pre><code>int bombNum = 0;\nfor (int xOffset = -1; xOffset &lt;= 1; xOffset++)\n for (int yOffset = -1; yOffset &lt;= 1; yOffset++)\n {\n if (xOffset == 0 &amp;&amp; yOffset == 0)\n {\n continue;\n }\n SmartSquare neighbour = (SmartSquare)board.getSquareAt(xLocation+xOffset, yLocation+yOffset);\n if (neighbour != null &amp;&amp; neighbour.getBomb())\n {\n bombNum++;\n }\n }\nreturn bombNum;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T21:25:14.980", "Id": "53338", "Score": "0", "body": "Beutiful thank you very much, \nDo you know any good sites/articles/books about code 'elegance'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T21:29:21.760", "Id": "53339", "Score": "0", "body": "Glad I could help. No, unfortunately I don't know of any such resources." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T00:53:02.437", "Id": "53349", "Score": "1", "body": "@Babbleshack **Clean Code** by Robert C. Martin: http://www.amazon.ca/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T08:18:58.890", "Id": "53373", "Score": "3", "body": "I find this non-indentation to be a sneaky way to disguise the nested for-loop. Indent the inner loop! If you _really_ want the characters in your code to line up vertically, put extra spaces between the \"for\" and left parenthesis of the outer for-loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T21:33:38.153", "Id": "53410", "Score": "0", "body": "@200_success Edited (not that I particularly agree - I find this to be unnecessary over-indentation). I assume what I did is what you meant by the extra spaces note." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T09:15:20.570", "Id": "53445", "Score": "0", "body": "Just as a friendly note, Java normally uses a modified K&R-style with opening braces on the same line. While K&R with opening braces on the same line is mostly used by C#." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T21:17:58.393", "Id": "33302", "ParentId": "33301", "Score": "5" } } ]
{ "AcceptedAnswerId": "33302", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T20:48:37.167", "Id": "33301", "Score": "2", "Tags": [ "java", "game", "matrix", "minesweeper" ], "Title": "Minesweeper, Bombcount method" }
33301
<p>Maze, assumption - single point of entry and a single point of exit. Also directions to travel in maze are North South East West. Request for optimization and code cleanup.</p> <pre><code>final class Coordinate { private final int x; private final int y; public Coordinate(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; // now to the check. final Coordinate coordinate = (Coordinate) o; return coordinate.x == x &amp;&amp; coordinate.y == y; } public int hashCode() { return x + y; } } public class Maze { private final int[][] maze; public Maze(int[][] maze) { if (maze == null) { throw new NullPointerException("The input maze cannot be null"); } if (maze.length == 0) { throw new IllegalArgumentException("The size of maze should be greater than 0"); } this.maze = maze; } public Set&lt;Coordinate&gt; solve() { Set&lt;Coordinate&gt; setCoordinate = new LinkedHashSet&lt;Coordinate&gt;(); for (int j = 0; j &lt; maze[0].length; j++) { if (maze[0][j] == 1) { getMazePath(0, j, setCoordinate); return setCoordinate; } if (maze[maze.length - 1][j] == 1) { getMazePath(maze.length - 1, j, setCoordinate); return setCoordinate; } } // note - we dont want to double count tile. for (int i = 1; i &lt; maze.length - 1; i++) { if (maze[i][0] == 1) { getMazePath(i, 0, setCoordinate); return setCoordinate; } if (maze[i][maze[0].length - 1] == 1) { getMazePath(i, maze[0].length - 1, setCoordinate); return setCoordinate; } } throw new IllegalArgumentException("The input maze does not have an entry point"); } private boolean getMazePath(int row, int col, Set&lt;Coordinate&gt; set) { assert set != null; if (set.contains(new Coordinate(row, col))) return false; if ((((row == 0) || (row == maze.length - 1)) || ((col == maze[0].length - 1) || col == 0)) &amp;&amp; !set.isEmpty() /* discard the entry tile */) { set.add(new Coordinate(row, col)); return true; } set.add(new Coordinate(row, col)); boolean getMaze = false; /** * travel in all 4 language */ if (((col - 1) &gt;= 0) &amp;&amp; (maze[row][col - 1] == 1) &amp;&amp; !getMaze) { getMaze = getMazePath(row, col - 1, set); } if (((row - 1) &gt;= 0) &amp;&amp; (maze[row - 1][col] == 1) &amp;&amp; !getMaze) { getMaze = getMazePath(row - 1, col, set); } if (((col + 1) &lt; maze[0].length) &amp;&amp; (maze[row][col + 1] == 1) &amp;&amp; !getMaze) { getMaze = getMazePath(row, col + 1, set); } if (((row + 1) &lt; maze.length) &amp;&amp; (maze[row + 1][col] == 1) &amp;&amp; !getMaze) { getMaze = getMazePath(row + 1, col, set); } if (!getMaze) { set.remove(new Coordinate(row, col)); } return getMaze; } public static void main(String[] args) { int[][] m1 = { { 0, 1, 0 }, { 1, 1, 0 }, { 0, 0, 0 } }; for (Coordinate coord : new Maze(m1).solve()) { System.out.println(coord.getX() + " : " + coord.getY()); } System.out.println("-------------------------------------"); int[][] m2 = { { 0, 0, 0, 0 }, { 0, 0, 1, 1 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }; for (Coordinate coord : new Maze(m2).solve()) { System.out.println(coord.getX() + " : " + coord.getY()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T23:03:54.187", "Id": "53342", "Score": "0", "body": "Wouldn't `hashCode()` return the same hash code for (1,2) and (2,1)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T23:09:54.973", "Id": "53343", "Score": "1", "body": "hashcode can be same for different objects, that does not violate ( as per my knowledge ) any contract. but if 2 objects satisfy equals hashcode must match" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T05:56:16.933", "Id": "53363", "Score": "2", "body": "While you're correct about the hashcode not needing to be equal, you're probably better off using a method that will return more unique hashcodes, especially given that you're using grid coordinates (you have more than twice as many coordinates as hashcodes with the current method). Given that you're unlikely to use the entire range of integers you could probably use one to set the high bits, and the other the low bits (or something like that)." } ]
[ { "body": "<p>Your algorithm finds all routes, but only returns one, which is sub-optimal. Run it on the following data:</p>\n\n<pre><code> int[][] m3 = { { 0, 0, 0, 0, 0 }, \n { 0, 1, 1, 1, 1 }, \n { 0, 1, 0, 1, 0 }, \n { 0, 1, 0, 1, 0 }, \n { 1, 1, 1, 1, 0 }, \n { 0, 0, 0, 0, 0 } };\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T01:12:38.337", "Id": "33308", "ParentId": "33303", "Score": "0" } }, { "body": "<p>Change the following lines:</p>\n\n<pre><code>System.out.println(coord.getX() + \" : \" + coord.getY());\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>System.out.println( coord );\n</code></pre>\n\n<p>Override <code>toString()</code> as appropriate to eliminate duplication and maintain encapsulation.</p>\n\n<p>As a technique, I prefer not to write the following:</p>\n\n<pre><code>Set&lt;Coordinate&gt; setCoordinate = new LinkedHashSet&lt;Coordinate&gt;();\n</code></pre>\n\n<p>Instead, I would write:</p>\n\n<pre><code>Set&lt;Coordinate&gt; setCoordinate = createCoordinateSet();\n</code></pre>\n\n<p>And then add a <code>protected createCoordinateSet</code> method so that subclasses can override creating a <code>LinkedHashSet</code>. This opens up the door to the Open-Closed Principle (adding behaviour by extension, rather than modification). Consider:</p>\n\n<pre><code>protected Set&lt;Coordinate&gt; createCoordinateSet() {\n return new LinkedHashSet&lt;Coordinate&gt;();\n}\n</code></pre>\n\n<p>This adds almost no overhead to implement or execute, while unlocking a myriad of possibilities for anyone wanting to use and extend the library.</p>\n\n<p>I think that Java short-circuits:</p>\n\n<pre><code> if (o == null)\n return false;\n if (getClass() != o.getClass())\n return false;\n</code></pre>\n\n<p>Can be:</p>\n\n<pre><code> if( (o == null) || (getClass() != o.getClass()) ) {\n return false;\n }\n</code></pre>\n\n<p>Why make these public?</p>\n\n<pre><code>public int getX() {\n return x;\n}\n\npublic int getY() {\n return y;\n}\n</code></pre>\n\n<p>Consider making them <code>private</code> or <code>protected</code>. If another class \"needs\" the coordinates, ask <em>why</em>. Accessors, in my experience, often lead to poor encapsulation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T01:39:52.520", "Id": "33309", "ParentId": "33303", "Score": "2" } }, { "body": "<p>I would say that this part of your code actually is a bit of unnecessary code duplication:</p>\n\n<pre><code> if (((col - 1) &gt;= 0) &amp;&amp; (maze[row][col - 1] == 1) &amp;&amp; !getMaze) {\n getMaze = getMazePath(row, col - 1, set);\n }\n\n if (((row - 1) &gt;= 0) &amp;&amp; (maze[row - 1][col] == 1) &amp;&amp; !getMaze) {\n getMaze = getMazePath(row - 1, col, set);\n }\n\n if (((col + 1) &lt; maze[0].length) &amp;&amp; (maze[row][col + 1] == 1) &amp;&amp; !getMaze) {\n getMaze = getMazePath(row, col + 1, set);\n }\n\n if (((row + 1) &lt; maze.length) &amp;&amp; (maze[row + 1][col] == 1) &amp;&amp; !getMaze) {\n getMaze = getMazePath(row + 1, col, set);\n }\n</code></pre>\n\n<p>I think that you could use a <a href=\"https://codereview.stackexchange.com/questions/34054/random-walk-on-a-2d-grid/34056#34056\">direction enum</a>, loop through the directions and then for each direction you can check:</p>\n\n<ul>\n<li>Is the coordinate in the current direction within the bounds? (You can use one method to check all four bounds)</li>\n<li>If it is, call <code>getMazePath</code> for then new coordinate.</li>\n</ul>\n\n<p>Using the same <code>Direction4</code> enum as in the linked answer above,</p>\n\n<pre><code>public enum Direction4 {\n NORTH(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);\n\n private Direction4(int dx, int dy) {\n this.dx = dx;\n this.dy = dy;\n }\n public int getX() { return dx; }\n public int getY() { return dy; }\n}\n</code></pre>\n\n<p>You can replace the code snippet with:</p>\n\n<pre><code>for (Direction4 dir : Direction4.values()) {\n int newRow = row + dir.getY();\n int newCol = col + dir.getX();\n if (!getMaze &amp;&amp; isInBounds(newRow, newCol)) {\n getMaze = getMazePath(newRow, newCol, set);\n }\n}\n\nboolean isInBounds(int row, int col) {\n return row &gt;= 0 &amp;&amp; col &gt;= 0 &amp;&amp; row &lt; maze.length &amp;&amp; col &lt; maze[0].length;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T15:27:16.577", "Id": "35537", "ParentId": "33303", "Score": "3" } } ]
{ "AcceptedAnswerId": "33309", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T21:30:20.490", "Id": "33303", "Score": "4", "Tags": [ "java", "optimization", "algorithm", "pathfinding" ], "Title": "Maze problem cleanup and optimization" }
33303
<p>I want to implement a thread-safe singly linked list in C. Its nodes contain unique entries and I only need functions to add nodes (to head only), remove nodes and to locate a specific node.</p> <p>I am reasonably confident of the linked-list logic (any performance tips would be greatly appreciated though), but I am more concerned with my thread-safety logic. This is my first real foray into coding a thread-safe data structure. Is it optimal? Is it overkill? Is there a more performant way to get thread-safety for this data structure?</p> <p><em>Thread-safety definitions from header:</em></p> <pre><code>#define MY_SPINLOCK_INIT 0 typedef volatile int MYSpinLock; __attribute__((always_inline)) static inline void MYSpinLockLock(MYSpinLock *lock) { while (__sync_lock_test_and_set(lock, 1)) while (*lock) ; } __attribute__((always_inline)) static inline void MYSpinLockUnlock(MYSpinLock *lock) { __sync_lock_release(lock); } </code></pre> <p><em>Struct definitions:</em></p> <pre><code>typedef struct { const void *_key; uintptr_t _value; } MYEntry; typedef struct __MYNode { MYEntry _entry; struct __MYNode *_next; } MYNode; typedef struct { MYNode *_head; MYSpinLock _lockLL; } MYLinkedList; </code></pre> <p><em>Implementation:</em></p> <pre><code>#define MY_LISTLOCK_LOCK MYSpinLock *MY_macro_lock = &amp;(list-&gt;_lockLL); MYSpinLockLock(MY_macro_lock) #define MY_LISTLOCK_UNLOCK MYSpinLockUnlock(MY_macro_lock) MYLinkedList *MYLinkedListConstruct() { MYLinkedList *list = malloc(sizeof(MYLinkedList)); list-&gt;_head = NULL; list-&gt;_lockLL = MY_SPINLOCK_INIT; return list; } void MYLinkedListFree(MYLinkedList *list) { MY_LISTLOCK_LOCK; MYNode *node = list-&gt;_head; MYNode *next; while (node != NULL) { next = node-&gt;_next; free(node); node = next; } MY_LISTLOCK_UNLOCK; free(list); } void MYLinkedListAdd(MYLinkedList *list, MYEntry *entry) { MY_LISTLOCK_LOCK; MYNode *oldHead = list-&gt;_head; MYNode *newHead = malloc(sizeof(MYNode)); newHead-&gt;_entry = *entry; newHead-&gt;_next = oldHead; list-&gt;_head = newHead; MY_LISTLOCK_UNLOCK; } MYBool MYLinkedListRemoveNodeWithEntryKey(MYLinkedList *list, void *keyOfNodeToRemove) { if (keyOfNodeToRemove == NULL) return MYFalse; MY_LISTLOCK_LOCK; MYNode *node = list-&gt;_head; MYNode *prev = NULL; while (node != NULL) { // We found it, break if (node-&gt;_entry._key == keyOfNodeToRemove) break; prev = node; node = node-&gt;_next; } // We never found it if (node == NULL) { MY_LISTLOCK_UNLOCK; return MYFalse; } // We found it if (prev == NULL) { list-&gt;_head = node-&gt;_next; free(node); } else { prev-&gt;_next = node-&gt;_next; free(node); } MY_LISTLOCK_UNLOCK; return MYTrue; } MYNode *MYLinkedListFindNodeWithKey(MYLinkedList *list, void *keyToFind) { if (keyToFind == NULL) return NULL; MY_LISTLOCK_LOCK; MYNode *node = list-&gt;_head; while (node != NULL) { if (node-&gt;_entry._key == keyToFind) { MY_LISTLOCK_UNLOCK; return node; } node = node-&gt;_next; } MY_LISTLOCK_UNLOCK; return NULL; } </code></pre>
[]
[ { "body": "<blockquote>\n <p>Is there a more performant way to get thread-safety for this data structure?</p>\n</blockquote>\n\n<p>It all depends on how the list will be used. Just a few examples:</p>\n\n<ul>\n<li>Reads are more common than writes - use separate read/write locks.</li>\n<li>Average list is short - use copy-on-write array instead of linked list.</li>\n<li>Average list is long - use more efficient search method.</li>\n<li>Lots of threads access list - use mutex instead of spinlock to avoid wasted cycles.</li>\n<li>Lots of elements is added/removed in bulk - use external lock.</li>\n</ul>\n\n<p>Have you actually measured performance in real world scenarios and identified bottlenecks? It looks like most of it is prematurely optimized.</p>\n\n<pre><code>__attribute__((always_inline))\n</code></pre>\n\n<p>Is this really necessary? Does it bring any measurable performance gain?</p>\n\n<pre><code>while (__sync_lock_test_and_set(lock, 1))\n while (*lock)\n</code></pre>\n\n<p>I do not understand this second while loop. Why are you checking the value twice?</p>\n\n<pre><code>#define MY_LISTLOCK_LOCK MYSpinLock *MY_macro_lock = &amp;(list-&gt;_lockLL); MYSpinLockLock(MY_macro_lock)\n#define MY_LISTLOCK_UNLOCK MYSpinLockUnlock(MY_macro_lock)\n</code></pre>\n\n<p>Avoid macros which can be replaced with functions.</p>\n\n<pre><code>MYBool\n</code></pre>\n\n<p>Use <code>bool</code> from <code>stdbool.h</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T10:31:24.853", "Id": "33322", "ParentId": "33311", "Score": "5" } }, { "body": "<p>Some comments, discussed in the order of reading the code:</p>\n\n<p>Why so many leading underscores in the structures? What do you think is gained \nby using them? They are just noise to me. They are also reserved by something or other\n(Posix?) and so should be avoided. And using MY as a prefix for everything is\ndistracting. Try lowercase if you really need a prefix - but you don't, so\njust drop it.</p>\n\n<p>What is the context in which you want to use this code and its locks? You say you want it <em>thread</em> safe, but without knowing your context, I'm wondering about the lock and whether spinning is appropriate.</p>\n\n<ul>\n<li>In <code>SpinLockLock</code>, if the lock is busy, you spin in the inner <code>while(*lock)</code>\nloop, <em>reading</em> the lock to detect when it becomes free. If you omit the inner loop, \nthe function spins <em>writing</em> the lock. Is there an advantage in reading rather than writing? </li>\n<li>As you are spinning \n(hogging the CPU), another thread can free the lock only if threads are time-slicing (in other words the lock is held by another thread that got sliced-out while holding the lock). </li>\n<li>Alternatively, the lock can be freed if another\nprocessor/core releases it - is this what you are\nplanning? </li>\n</ul>\n\n<p>Your <code>MY_LISTLOCK_LOCK</code> and <code>MY_LISTLOCK_UNLOCK</code> macros are a bad idea. Macros are a\nbad idea in general, inline functions being preferable. But here you have\nmacros that use a variable from their context instead of using a call\nparameter and one that defines and hides a variable that both it and the next\nmacro use. What is wrong with:</p>\n\n<pre><code>SpinLockLock(&amp;list-&gt;lock);\n\n...\n\nSpinLockUnlock(&amp;list-&gt;lock);\n</code></pre>\n\n<p>In <code>LinkedListFree</code> you are careful to protect the freeing of each node within\nthe locked section. But then you free the list structure itself outside of\nthe locked section. Clearly you should not free a lock while you are using\nit, so what you do might be logical. But if there was any point in protecting\nthe freeing of nodes, it must be necessary also to protect the freeing of the\nlist itself. For example another thread could get in (and presumably do\nsomething) between your unlocking the list and freeing it.</p>\n\n<pre><code>static void LinkedListFree(LinkedList **list)\n{\n SpinLockLock(&amp;(*list)-&gt;lock);\n LinkedList *l = *list;\n *list = NULL;\n\n Node *node = l-&gt;head;\n while (node != NULL) {\n Node *next = node-&gt;next;\n free(node);\n node = next;\n }\n SpinLockUnlock(&amp;l-&gt;lock);\n free(l);\n}\n</code></pre>\n\n<p>Note the double pointer to the list so we can clear the list in the caller.\nNote also that other functions must now check for a NULL list. This is\nprobably excessive (but it is consistent), as you are most likely to free the\nlist when everything is done and you know that no other thread will be using\nthe list - in which case there is no point in protecting the freeing of nodes.</p>\n\n<p>In <code>LinkedListAdd</code>, <code>oldHead</code> is redundant.</p>\n\n<p>In <code>LinkedListRemoveNodeWithEntryKey</code>, the function name is verbose. Would\n<code>LinkedListRemove</code> not suffice? There is no other removal function after all.\nIn this function the ambiguity of the <code>void *key</code> in the <code>Entry</code> structure is\napparent.</p>\n\n<pre><code>if (node-&gt;entry.key == keyOfNodeToRemove) break;\n</code></pre>\n\n<p>This is comparing two pointers implying that the 'key' exists outside of the\nlist for the duration of the list's existence (as opposed to being passed in\nand then forgotten about). That might be true - maybe you have some organized\ndata that you want to reorganize as a list.... - is that so? The key clearly\nis a pointer, not just something else that takes the same space as a pointer\ncast into a pointer, because you treat 0 as an invalid value (although you\ndon't check for it when adding to the list).</p>\n\n<p>Also in that function, I don't much like the twin exits that must unlock the\nspin lock. It is usually better to have just one lock and one corresponding\nunlock.</p>\n\n<p>Function <code>LinkedListFindNodeWithKey</code> suffers the same problems as the previous\nfunction. The name is too long (<code>LinkedListFind</code> perhaps), the key/pointer\ncomparison is the same and there are two unlock calls. You can reorgansie to\navoid the latter with:</p>\n\n<pre><code>LISTLOCK_LOCK;\nNode *node = list-&gt;head;\nwhile (node != NULL) {\n if (node-&gt;entry.key == keyToFind) {\n break;\n }\n node = node-&gt;next;\n}\nLISTLOCK_UNLOCK;\nreturn node;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-08T03:27:56.313", "Id": "34034", "ParentId": "33311", "Score": "3" } } ]
{ "AcceptedAnswerId": "33322", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T03:40:23.457", "Id": "33311", "Score": "7", "Tags": [ "c", "thread-safety", "linked-list" ], "Title": "Thread-safe linked list review" }
33311
<p>I have implemented my first program in JavaScript, <a href="http://en.wikipedia.org/wiki/Rock-paper-scissors" rel="nofollow">Rock-Paper-Scissors</a>. I would like JavaScript developers to help me make this program more JavaScript-like by following the idioms of the language. I am also open to any suggestions related to simplification of logic and code readability.</p> <p>The following is the complete listing of the program:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;script&gt; var choiceArray = ["paper", "rock", "scissors"]; var getUserChoice = function() { var userChoice = undefined; var userChoiceIndex = undefined; while (true) { userChoice = prompt("What do you like - paper, scissor or rock"); userChoiceIndex = choiceArray.indexOf(userChoice); if (userChoiceIndex &gt;= 0 &amp;&amp; userChoiceIndex &lt;= 2) return userChoice; alert("Invalid Choice!"); } } var getComputerChoice = function() { var computerChoiceIndex = Math.floor(Math.random() * 3); return choiceArray[computerChoiceIndex]; } var decideWinner = function(userChoice, computerChoice) { if (userChoice === computerChoice) return "There is a tie!"; if (userChoice === "paper") { if (computerChoice === "rock") { return "paper wins!"; } else //scissors { return "scissors win!"; } } if (userChoice === "rock") { if (computerChoice === "paper") { return "paper wins!"; } else //scissors { return "rock wins!"; } } else //scissors { if (computerChoice === "paper") { return "scissors wins!"; } else //rock { return "rock wins!"; } } } var runGame = function() { var userChoice = getUserChoice(); var computerChoice = getComputerChoice(); var gameResult = decideWinner(userChoice, computerChoice); gameResult = "Computer Choice = " + computerChoice + ". " + gameResult; alert(gameResult); } runGame(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Well, there might be a few things.</p>\n\n<p>The most important thing that can be changed is removing all those magic numbers: What happens when we want to play “<em>Rock, Paper, Scissors, Lizard, Spock</em>” instead? You'd think you would only have to update the <code>choiceArray</code> – but unfortunately the length of that array is encoded in various places.</p>\n\n<p>This means that <code>if (userChoiceIndex &gt;= 0 &amp;&amp; userChoiceIndex &lt;= 2)</code> should be </p>\n\n<pre><code>if (userChoiceIndex &gt;= 0 &amp;&amp; userChoiceIndex &lt;= choiceArray.length - 1)\n</code></pre>\n\n<p>and <code>var computerChoiceIndex = Math.floor(Math.random() * 3)</code> should be</p>\n\n<pre><code>var computerChoiceIndex = Math.floor(Math.random() * choiceArray.length);\n</code></pre>\n\n<p>Your <code>decideWinner</code> function isn't really extensible, because you encode the winning relationships as <em>code</em>, not as the <em>data</em> it actually is. I'd use an object literal that only encodes what choice wins over another, like:</p>\n\n<pre><code>var winningData = {\n paper: { rock: true },\n rock: { scissors: true },\n scissors: { paper: true }\n};\n</code></pre>\n\n<p>Also, I'd implement <code>decideWinner</code> as a comparator that returns one of <code>-1, 0, 1</code> depending on whether the first or the second argument won. This decouples the decision logic from UI like text.</p>\n\n<pre><code>function(choiceA, choiceB) {\n if (choiceA === choiceB) return 0;\n if (winningData[choiceA][choiceB]) return -1;\n if (winningData[choiceB][choiceA]) return 1;\n console.warn(\"No ordering between \" + choiceA + \" and \" + choiceB + \" was found\");\n return 0;\n}\n</code></pre>\n\n<p>The game result is then determined as:</p>\n\n<pre><code>var ordering = decideWinner(userChoice, computerChoice);\nvar winningMessage = ordering &lt; 0 ? \"You win!\" :\n ordering &gt; 0 ? \"The computer wins!\" :\n \"It's a tie!\";\nvar gameResult = \"You chose: \" + userChoice + \".\\n\" +\n \"The computer chose: \" + computerChoice + \".\\n\" +\n winningMessage;\n</code></pre>\n\n<p>Now when we extend the game, we just have to update the <code>winningData</code>. Notice that I display <em>who</em> wins, not <em>what</em> choice wins, as I don't think that would be tremendously interesting to a player. Also, he would have to make an association from the choice to the player, which is unnecessary mental effort.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T09:03:47.317", "Id": "53377", "Score": "0", "body": "Note, for an even balance of power, there must be an odd number of possible choices." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T09:08:48.743", "Id": "53378", "Score": "1", "body": "@luserdroog thanks, I removed the phaser from my example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T14:05:54.933", "Id": "53385", "Score": "0", "body": "@amon, thanks for excellent tips on extensibility. I will definitely rewrite the program considering extensibility in mind. +1." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T06:42:59.600", "Id": "33317", "ParentId": "33314", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T04:18:09.297", "Id": "33314", "Score": "3", "Tags": [ "javascript", "game", "rock-paper-scissors" ], "Title": "How do I make my Rock-Paper-Scissor program more JavaScript-like?" }
33314
<p>According to <a href="https://stackoverflow.com/questions/19608546/optimize-regex-for-maximum-speed">https://stackoverflow.com/questions/19608546/optimize-regex-for-maximum-speed</a> and comments to ask my question here . Please help me to optimize following regex to best performance . I have read some articles but this problem should solve quickly to decrease cpu usage and delay time so i don't have enough time for try and false .</p> <p>First one should match for example </p> <p><code>http://microsoft.com/test/temp.iso</code></p> <p><code>http://download.microsoft.com/TEMP.iso</code></p> <p><code>http://www.download.microsoft.com/test.aspx?hdwjdhcjdgcjhdc=TEMP.iso</code></p> <p><strong>note</strong>: </p> <ul> <li><p><em>All url should start with <code>http://</code> so i don't know it is better to put <code>^http://</code> at first or not ?</em></p></li> <li><p><em>first line and last line have specific rules but lines between them may combined.</em></p></li> <li><p><em>These regexp are used in <a href="http://www.squid-cache.org/Doc/config/refresh_pattern/" rel="nofollow noreferrer">squid configuration</a>.</em></p></li> </ul> <p>Any help appreciated .</p> <pre><code>refresh_pattern -i (.+\.||)(microsoft|windowsupdate).com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|iso|psf) refresh_pattern -i (.+\.||)eset.com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ver|nup) refresh_pattern -i (.+\.||)avg.com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz) refresh_pattern -i (.+\.||)grisoft.(com|cz)/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz) refresh_pattern -i (.+\.||)avast.com/.*\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|vpx|vpu|vpa|vpaa|def|stamp) refresh_pattern -i (.+\.||)(kaspersky-labs|kaspersky).com/.*\.(cab|zip|exe|msi|msp|bz2|avc|kdc|klz|dif|dat|kdz|kdl|kfb) refresh_pattern -i (.+\.||)nai.com/.*\.(gem|zip|mcs|tar|exe|) refresh_pattern -i (.+\.||)adobe.com/.*\.(cab|aup|exe|msi|upd|msp) refresh_pattern -i (.+\.||)symantecliveupdate.com/.*\.(zip|exe|msi) refresh_pattern -i (.+\.||)(192\.168\.10\.34|mywebsite.com)/.* </code></pre> <p>After help of Stackoverflow guys i have changed it to this . <strong>Any more optimization ?</strong></p> <pre><code>refresh_pattern -i (.+\.)?(microsoft|windowsupdate)\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|iso|psf)$ refresh_pattern -i (.+\.)?eset\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ver|nup)$ refresh_pattern -i (.+\.)?avg\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$ refresh_pattern -i (.+\.)?grisoft\.(com|cz)/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$ refresh_pattern -i (.+\.)?avast\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|vpx|vpu|vpa|vpaa|def|stamp)$ refresh_pattern -i (.+\.)?(kaspersky-labs|kaspersky)\.com/.*?\.(cab|zip|exe|msi|msp|bz2|avc|kdc|klz|dif|dat|kdz|kdl|kfb)$ refresh_pattern -i (.+\.)?nai\.com/.*?\.(gem|zip|mcs|tar|exe|)$ refresh_pattern -i (.+\.)?adobe\.com/.*?\.(cab|aup|exe|msi|upd|msp)$ refresh_pattern -i (.+\.)?symantecliveupdate\.com/.*?\.(zip|exe|msi)$ refresh_pattern -i (.+\.)?(192\.168\.10\.34|mywebsite\.com)/.*?$ </code></pre> <p>Edit: Squid does not accept (?:content) so i removed it . any replacement ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T05:03:53.213", "Id": "60131", "Score": "0", "body": "I realize it has been a while since you asked this question. In the interim, have you found a way to make your regexes faster? If you have, you should consider providing an answer here so we can all benefit. Self-answering your questions is perfectly valid, and encouraged." } ]
[ { "body": "<p>Since all your patterns have similar structure, we only need to focus on one, e.g.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>refresh_pattern -i (.+\\.)?avg\\.com/.*?\\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$\n</code></pre>\n\n<p>This pattern starts with <code>(.+\\.)?</code>. This pattern says 'match any characters that end in a '.', but, the <code>?</code> means that if nothing matches, then that's OK..... so, what the <code>(.+\\.)?</code> really means is \"Match something with a dot at the end, or match nothing\".</p>\n\n<p>This is apparently sensible, <strong>but</strong>, because the entire URL is not anchored to the start of the line (there is no <code>^</code>) it really means \"match anything\".</p>\n\n<p>For example, all of these URL's will successfully match:</p>\n\n<ul>\n<li><code>http://www.avg.com/file.gz</code> // we would expect this</li>\n<li><code>http://avg.com/file.gz</code> // we would <strong>maybe</strong> expect this</li>\n<li><code>http://cravg.com/file.gz</code> // we would <strong>not</strong> expect this</li>\n<li><code>https://downloads.avg.com/file.gz</code> // we would expect this</li>\n<li><code>mailto:me@www.avg.com/file.gz</code> // we would expect this</li>\n<li><code>ftp://ftp.avg.com/file.gz</code> // we would expect this</li>\n</ul>\n\n<p>This is all beside the point, though, because whether we use <code>(.+\\.)?</code> or not it makes no difference whatsoever (functionality wise).</p>\n\n<p>It is possible that the squid regex engine is smart enough to identify that the <code>(.+\\.)?</code> is useless, and it may optimize it out.... but, I doubt it.</p>\n\n<p>So, you can remove <strong>all</strong> the <code>(.+\\.)?</code> structures.</p>\n\n<p>I believe that you should replace them with a <code>\\b</code> which is a 'word break'. This will match things like <code>http://avg.com/...</code> and <code>http://www.avg.com/...</code> but it will not match <code>http://cravg.com/...</code>. I believe this is what you want.</p>\n\n<p>It would likely be better to also anchor the regex to the beginning of the URL. If you can assume that it is an http or https URL then I would absolutely recommend that you include it as part of the regex. It will anchor the query well.</p>\n\n<p>I will assume that the protocol could be https as well as http, in which case the match would be:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>refresh_pattern -i ^https?//.*\\bavg\\.com/.*?\\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$\n</code></pre>\n\n<p>This change can be applied to all the refresh_patterns. (replace <code>(.+\\.)?</code> with <code>^https?//.*\\b</code>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T20:25:10.827", "Id": "61262", "Score": "0", "body": "You should anchor the regexes to the beginning not just for performance, but for correctness. Phishers, for example, try to mislead people all the time by putting strings that look like domain names in the path of the URL. Furthermore, slashes should be disallowed in the domain name — `^https?//[^/]*\\bavg\\.com/.*\\.(cab|exe|etc)$`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T23:21:14.190", "Id": "36670", "ParentId": "33319", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T07:37:55.603", "Id": "33319", "Score": "4", "Tags": [ "optimization", "regex", "performance" ], "Title": "Optimize regex for maximum speed" }
33319
<p>I have an array of structure records and function <code>intersection</code> and <code>difference</code>.</p> <p>The <code>intersection</code> function take <code>list1</code>,<code>list2</code>,<code>list3</code>(an array of records),and <code>size</code> of both <code>list1</code> and <code>list2</code>. </p> <p>Here, <code>intersection</code> and <code>difference</code> both are the <code>boolean operators</code> ( like : A <code>U</code> B , A <code>-</code> B , A <code>intersection</code> B). Also <code>list1</code> and <code>list2</code> are given as input and the result is copied to <code>list3</code>. </p> <p>My both functions are working fine. But given that the two lists are already sorted (on author name and if same author name then name of the book), how can I optimize the code? <code>intersection</code> is of O(n<sup>2</sup>) and <code>difference</code> is less than O(n<sup>2</sup>). </p> <p><code>copy()</code> copies a record to first argument from second argument. </p> <pre><code>//Intersection of two lists void intersection(struct books *list1,struct books *list2,struct books *list3,int n1,int n2) { int i,j,size1,size2; if(n1&lt;n2){size1=n1;size2=n2;}else{size1=n2;size2=n1;} for(i=0;i&lt;size1;i++) { for(j=0;j&lt;size2;j++) { if(strcmp(list1[i].name,list2[j].name)==0 &amp;&amp; strcmp(list1[i].author,list2[j].author)==0) { if(list1[i].copies &lt; list2[j].copies) { copy(&amp;list3[i],&amp;list1[i]); } else { copy(&amp;list3[i],&amp;list2[j]); } } } } } //set difference on lists (optimised) void difference(struct books *list1,struct books *list2,struct books *list3,int n1,int n2) { int i,j,k=0,exists=0; for(i=0;i&lt;n1;i++) { exists=0; for(j=0;j&lt;n2 &amp;&amp; exists==0;j++) { if(strcmp(list1[i].author,list2[j].author)==0 &amp;&amp; strcmp(list1[i].author,list2[j].author)==0) { exists=1; } } if(exists==0) { copy(&amp;list3[k],&amp;list1[i]); k++; } } } </code></pre>
[]
[ { "body": "<p>Given that the two lists are already sorted, you can do MUCH better than just the naive <code>O(|A| * |B|)</code> implementation. Let me reduce the problem to just intersecting lists of chars, and let's say our lists are:</p>\n\n<pre><code>A: [... a elems ..., 'C', 'D', ... ]\nB: [... b elems ..., 'C', 'E', ... ]\n</code></pre>\n\n<p>Let's say we just in the outer looped matched A's <code>'C'</code> to B's <code>'C'</code>. Cool, we got that right. Now, we're going to try to check for <code>'D'</code>. Do we really need to start looking at <code>B[0]</code>? We know that <code>B</code> is sorted... and we know that <code>B[b] == 'C'</code>, so we know for sure that if there is a <code>'D'</code> in <code>B</code> then it cannot be in the first <code>b+1</code> elements. </p>\n\n<p>If you change your inner loop from looping over every element in the 2nd list, to just making sure you end up only walking over the list once, you can reduce your complexity to <code>O(|A| + |B|)</code>, which is pretty huge.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T18:23:29.480", "Id": "33338", "ParentId": "33321", "Score": "1" } } ]
{ "AcceptedAnswerId": "33338", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T10:10:04.257", "Id": "33321", "Score": "0", "Tags": [ "optimization", "c" ], "Title": "Optimised library database code for sorted array of structures" }
33321
<p><code>CellDrawableProvider</code> is an Android class used in the game <em>Tic-Tac-Toe</em>. It provides drawables for cells of game board (drawables for figures X and O, and "Fire" if the cell is in the firing line). To save memory, this class uses a <code>map</code> to store the already created drawables.</p> <pre><code>class CellDrawableProvider { private final Map&lt;Object, Drawable&gt; drawables; private final Resources resources; CellDrawableProvider(Resources resources) { this.resources = resources; this.drawables = new HashMap&lt;Object, Drawable&gt;(); } Drawable getCellDrawable(int moveIconId, int fireIconId) { if (fireIconId == android.R.color.transparent) { return getDrawable(moveIconId); } else { return getLayerDrawable(moveIconId, fireIconId); } } private Drawable getLayerDrawable(int moveIconId, int fireIconId) { Object layerDrawableKey = Pair.create(moveIconId, fireIconId); Drawable layerDrawable = drawables.get(layerDrawableKey); if (layerDrawable == null) { layerDrawable = createLayerDrawable(moveIconId, fireIconId); drawables.put(layerDrawableKey, layerDrawable); } return layerDrawable; } private Drawable createLayerDrawable(int moveIconId, int fireIconId) { Drawable[] layers = new Drawable[2]; layers[0] = getDrawable(moveIconId); layers[1] = getDrawable(fireIconId); return new LayerDrawable(layers); } private Drawable getDrawable(int iconId) { Drawable drawable = drawables.get(iconId); if (drawable == null) { drawable = resources.getDrawable(iconId); drawables.put(iconId, drawable); } return drawable; } } </code></pre> <p>I do not like the class name <code>CellDrawableProvider</code> and method name <code>getCellDrawable()</code>. </p> <p>Can you suggest better names?</p>
[]
[ { "body": "<p>How about <code>DrawableCellProvider</code> and replacing the function name to 'get()' , </p>\n\n<p>Also is <code>null</code> really acceptable in </p>\n\n<pre><code>private Drawable getDrawable(int iconId) {\n Drawable drawable = drawables.get(iconId);\n if (drawable == null) {\n drawable = resources.getDrawable(iconId);\n drawables.put(iconId, drawable);\n }\n return drawable;\n}\n</code></pre>\n\n<p>or do you want to return a non-nullable values. Null values tend to bite back and you can spend days looking for the method causing the problem.</p>\n\n<p>Lastly if you really want to be neutoric about code cleanliness and easy to test code, I'd recommend moving the <code>getDrawable()</code> into a <code>DrawableProvider</code> with another <code>get()</code> </p>\n\n<p>Also, If you really want to same memory, why are you trying to <code>put</code> the value every time? I'm assuming the you don't get a new drawable/layerDrawable object for the same key. So doing a check for the key in the map would save you tiny bit of time and ease up your garbage collecction.</p>\n\n<p>would <code>private final Map&lt;Object, Drawable&gt; drawables;</code> be better named as <code>drawableCache</code>. Also, unless two different type of objects can have the same hashcode for very different things, hence I'd recommend having a separate cache for your normal drawables and another one for layerDrawables. </p>\n\n<p>Hope I was more helpful that I currently think I am</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T18:40:43.973", "Id": "33340", "ParentId": "33324", "Score": "1" } }, { "body": "<p>You don't need to \"cache\" the drawables yourself. Android does that internally, as can be seen <a href=\"https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/res/Resources.java\" rel=\"nofollow\">in the source code</a>.</p>\n\n<pre><code> Drawable dr = getCachedDrawable(isColorDrawable ? mColorDrawableCache : mDrawableCache, key);\n\n if (dr != null) {\n return dr;\n }\n</code></pre>\n\n<p>Therefore, you're actually not saving any memory at all. (Technically you're wasting memory by creating a map for it, but that's so little memory it barely counts)</p>\n\n<p>Instead of creating a <code>LayerDrawable</code> you might want to use <a href=\"http://developer.android.com/reference/android/view/View.html#setBackgroundResource%28int%29\" rel=\"nofollow\">setBackgroundResource()</a> and <a href=\"http://developer.android.com/reference/android/widget/ImageView.html#setImageResource%28int%29\" rel=\"nofollow\">setImageResource()</a> (assuming you're using <code>ImageView</code>s)</p>\n\n<p>As for the name <code>CellDrawableProvider</code>, I don't see what would be wrong with it. It's purpose is clear: A provider for cell drawables.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T00:28:12.120", "Id": "35734", "ParentId": "33324", "Score": "3" } } ]
{ "AcceptedAnswerId": "35734", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T11:44:16.227", "Id": "33324", "Score": "1", "Tags": [ "java", "android", "tic-tac-toe" ], "Title": "Android class in Tic-Tac-Toe" }
33324
<p>This is my solution to <a href="http://projecteuler.net/problem=2" rel="nofollow">Project Euler problem 2</a>:</p> <blockquote> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <p>The class <code>fibonacci_Even_Sum_Calculator</code> does two things:</p> <ol> <li>calculate the sum of the even-valued Fibonacci numbers</li> <li>cache the results in a dictionary</li> </ol> <p>Is this a sign that this code violates the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow">Single Responsibility Principle</a>?</p> <pre><code>class fibonacci_Even_Sum_Calculator: def __init__(self): self.cached_result = dict() def F(self, n): if n == 0: return 0 elif n == 1: return 1 else: if(self.cached_result.has_key(n)): return self.cached_result[n] else: result = self.F(n-1) + self.F(n-2) self.cached_result[n] = result return result def is_even(self, number): return number % 2 == 0 def get_result(self,limit_value): sequence = 2 sum = 0 while True: result = self.F(sequence) if result &gt; limit_value: break if self.is_even(result) : sum = sum + result sequence = sequence + 1 return sum fibonacci_calculator = fibonacci_Even_Sum_Calculator() result = fibonacci_calculator.get_result(4000000) print result </code></pre>
[]
[ { "body": "<p>I think you are violating SRP, but not for the reason you think you are. Memoization is fine, it's definitely one approach to calculating the fibonacci values, but you have one class that is doing BOTH calculating the Fibonacci values AND summing the even ones. </p>\n\n<p>If you are really worried about SRP, I would have a generator to calculate the Fibonacci numbers, and then an external function to sum them:</p>\n\n<pre><code>def sum_evens(limit):\n sum = 0\n for f in fibonacci_numbers(): # left as an exercise\n if f &gt; limit: \n break\n elif f % 2 == 0:\n sum += f\n return sum\n</code></pre>\n\n<p>Otherwise, minor notes, your class is named <code>fibonacci_Even_Sum_Calculator</code>. The most accepted convention for class names is CamelCase, so <code>FibonacciEvenSumCalculator</code> is strongly preferred. Similarly, function names should be lowercase, and <code>f</code> is an insufficient name for code that is \"get the nth Fibonacci number\". </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T15:58:59.060", "Id": "33330", "ParentId": "33326", "Score": "1" } }, { "body": "<p>TL;DR</p>\n\n<p><code>yes, you are probably violating the SRP but in this case I wouldn't care.</code></p>\n\n<p>I think this is a hard one. </p>\n\n<p>First I tend towards Barry's point of view:</p>\n\n<p>You are really doing \"two things\" in your class. So, if you take the dictum of \"reasons\" to change to the letter, you are violating the <code>SRP</code>. </p>\n\n<p>But on the other hand: I think breaking this up into a <em>fibonacci-series</em>-producing class and another <em>summing</em>-class is nonsensical.</p>\n\n<p>My personal interpretation of the <code>Single Responsibility Principle</code> is:\n\"dealing with one topic\". And when objects tend to grow too much, I have to decide, which functions are <em>off-topic</em> and need to be refactored in some way. \nIf you want: I am advocating a more pragmatically - perhaps not really orthodox position. </p>\n\n<p>In your case that means, if I say \"dealing with fibonacci numbers\" is our topic and the resulting class results in two \"subtopics\" <em>generating</em> and <em>summing</em> that is a possible code smell, but more in the future than now. </p>\n\n<p>Don't forget: Those principles weren't developed for their own sake, they were developed with some purposes. And one of those purposes is <em>maintainability</em>.\nAnd as far as you code goes, I tend to say, it is still maintainable.</p>\n\n<p>One last word:\nIf you really want to improve your code - get rid of the class at all. \nI see no reason, why one should write for such a job a class at all - except, perhaps, you are on the one hand obsessed with classes or on the other hand, for educational purposes.</p>\n\n<p>Two simple functions were sufficient. </p>\n\n<p>Python is a decent objectoriented language though, but sometimes it is overhead to write a class for everything. Python is not Java, where it is necessary to write <em>explicit</em> classes for everything. Python is not forcing you to do that.</p>\n\n<p>First take care of writing clean code. Later take care of your overall design. Start with naming. Barry pointed out, that you should name your functions more pythonic. Another point worth mentioning is your function naming in general. Function names should reveal their intention. So what is the intention of <code>fibonacci_calculator.get_result</code>? Reading this, withouht investigating your code, my answer is: I don't have any clue. I know there are fibonacci numbers involved and somehow there is a <code>result</code>. How it is claculated: the heck, I do not know. On the other hand: <code>fibonacci.sum_evens_up_to()</code> clearly says, what it does: it sums up the <em>fibonacci</em> evens up to a <em>paramter</em> given. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T21:17:41.583", "Id": "33345", "ParentId": "33326", "Score": "0" } }, { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>There are no docstrings. How are we supposed to know what this code does and how to call it?</p></li>\n<li><p>There are no test cases. This kind of code is an ideal opportunity to use <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p></li>\n<li><p>To memoize a function, the most convenient way to do it is to use a <em>decorator</em>. This keeps the memoization logic separate from the code being memoized, and also makes the memoization re-usable for other functions. Using <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow\"><code>functools.lru_cache</code></a> you could write:</p>\n\n<pre><code>from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef F(n):\n \"\"\"Return the 'n'th Fibonacci number.\n\n &gt;&gt;&gt; [F(i) for i in range(10)]\n [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n\n \"\"\"\n if n &lt;= 2:\n return (0, 1, 1)[n]\n else:\n return F(n - 1) + F(n - 2)\n</code></pre></li>\n<li><p>Once you split the memoization into its own function or class, there will no longer be any persistent state in your program (the only use of <code>self</code> at present is <code>self.cached_result</code>). So there is no need to use a class here.</p>\n\n<p>Even in its current state, the method <code>is_even</code> does not refer to <code>self</code> and so does not need to be a method.</p></li>\n<li><p>You start your summation loop with <code>sequence = 2</code>. But this means that someone who wants to check that your code is correct would have to go through a complicated analysis: \"why start at \\$2\\$? ... er ... Oh, I see, \\$F(0)=0\\$ which doesn't contribute anything to the sum, and \\$F(1)=1\\$ which is odd. But \\$F(2)=1\\$ too so why not start at \\$3\\$?\"</p>\n\n<p>I would recommend making it easy for someone to read the program, by starting with <code>sequence = 0</code>. The efficiency gain of avoiding two calls to <code>F</code> is negligible.</p></li>\n<li><p>Your loop looks like this:</p>\n\n<pre><code>sequence = 2\nwhile True:\n # ...\n sequence += 1\n</code></pre>\n\n<p>It would simplify your loop if you used <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow\"><code>itertools.count</code></a>:</p>\n\n<pre><code>from itertools import count\nfor sequence in count(2):\n</code></pre>\n\n<p>but as discussed above, it would be better to start from 0:</p>\n\n<pre><code>for sequence in count():\n</code></pre></li>\n<li><p>Your method <code>is_even</code> is just one line long, and called from just one place. It hardly seems worth making it into a separate function.</p></li>\n</ol>\n\n<h3>2. A simpler approach</h3>\n\n<p>This is the kind of problem that can be solved very simply. No need for classes, memoization, or multiple functions; all that's needed is a simple loop:</p>\n\n<pre><code>def sum_even_fibonacci(limit):\n \"\"\"Return the sum of the even Fibonacci numbers up to 'limit'.\n\n &gt;&gt;&gt; # See &lt;http://oeis.org/A099919&gt;\n &gt;&gt;&gt; [sum_even_fibonacci(4 ** i) for i in range(1, 11)]\n [2, 10, 44, 188, 798, 3382, 14328, 60696, 257114, 1089154]\n\n \"\"\"\n total = 0\n # a = F(2) and b = F(3), so b is first nonzero even Fibonacci number.\n a, b = 1, 2\n while b &lt;= limit:\n total += b\n a, b = a + 2*b, 2*a + 3*b\n return total\n</code></pre>\n\n<p>This works because every third Fibonacci number is even, so we skip directly from \\$F(3n)\\$ to \\$F(3n+3)\\$, the next even value. If we have $$\\eqalign{a &amp;= F(3n-1) \\\\ b &amp;= F(3n)}$$ then $$\\eqalign{F(3n+1) &amp;= a+b \\\\ F(3n+2) &amp;= a+2b \\\\ F(3n+3) &amp;= 2a+3b}$$</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T16:14:19.763", "Id": "33406", "ParentId": "33326", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T13:00:41.487", "Id": "33326", "Score": "2", "Tags": [ "python", "programming-challenge", "fibonacci-sequence" ], "Title": "Maintaining the Single Responsibility Principle with Project Euler #2" }
33326
<p>This is my importer to database from excel file. I would like to handle situations when any error raise. To not breaks whole import when one errors occurs.</p> <p>For example when there is duplicated record and I have uniqueness validations. I would like to store this row id in errors table and inform about that at the end.</p> <pre><code>class DDImporter attr_accessor :file def initialize(path) @path = path end def open @file = Roo::Excelx.new(@path) end def sheets @file.sheets end def extract_sheets sheets.each do |sheet| unless sheet == ("risks" || "allergies_symptoms") extract sheet end end end def extract sheet_name @file.default_sheet = sheet_name header = file.row 1 2.upto(file.last_row) do |i| row = Hash[[header, file.row(i)].transpose] # row.delete "id" object = sheet_name.classify.constantize object.create!(row) end end end </code></pre>
[]
[ { "body": "<p>It can be as simple as :</p>\n\n<pre><code> def initialize(path)\n @path = path \n @imported = []\n @errors = []\n end\n\n def extract sheet_name\n @file.default_sheet = sheet_name\n\n header = file.row 1\n 2.upto(file.last_row) do |i|\n row = Hash[[header, file.row(i)].transpose]\n # row.delete \"id\"\n model = sheet_name.classify.constantize\n\n # this is the part that gets the job done.\n object = model.new(row)\n if object.save\n @imported &lt;&lt; object\n else\n @rejected &lt;&lt; object\n end\n\n end\n end\n</code></pre>\n\n<p>... this way you can iterate through <code>@imported</code> or <code>@rejected</code> at the end of the import process (to display errors, or perform additional tasks).</p>\n\n<p>This code can also easily be adapted to only catch exceptions : </p>\n\n<pre><code> def extract sheet_name\n @file.default_sheet = sheet_name\n\n header = file.row 1\n 2.upto(file.last_row) do |i|\n row = Hash[[header, file.row(i)].transpose]\n # row.delete \"id\"\n object = sheet_name.classify.constantize\n object.create!(row)\n end\n rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid =&gt; error\n # rejected record for these errors can be accessed with :\n error.record\n # to resume processing, just :\n error.continue\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T22:41:56.053", "Id": "33351", "ParentId": "33327", "Score": "1" } } ]
{ "AcceptedAnswerId": "33351", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T14:20:00.773", "Id": "33327", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "exception-handling", "data-importer" ], "Title": "How to refactor this importer to handle validation errors?" }
33327
<p>I want move a <strong>Vertical</strong> line segment across a plane or another way sweep the plane, from <em>Left</em> to <em>right</em>.</p> <p>The figure illustrates how the segment is moving at the <strong>X-axis</strong>. When <strong>x1 >= X</strong> beginning and i translate it to the upper part and so on, till <strong>y2</strong> which is the upper part of the segment reaches <strong>Y</strong>. You can think of it as how a scanner works. </p> <p><img src="https://i.stack.imgur.com/3pCgp.png" alt="enter image description here"></p> <h2><strong>Line = (x<sub>1</sub>,y<sub>1</sub>,x<sub>2</sub>,y<sub>2</sub>)</strong></h2> <p>When x<sub>1</sub> pr x<sub>2</sub> coordinates becomes greater or equal to -rightBorder I increase y<sub>1</sub> and y<sub>2</sub> to the next level and so on till y<sub>2</sub> becomes greater than Y.</p> <hr> <p><strong>Algorithm:</strong></p> <pre><code> #define STEP 9 #define Y 20 #define X 30 void moveLine(int, int, int, int); int main() { moveLine(5, 0, 5, 10); return 0; } void moveLine(int x1, int y1, int x2, int y2) { //Reaches upper border (Y-axis) if (y1 &gt;= Y) { return; } // cout &lt;&lt; y1 &lt;&lt;" "&lt;&lt; y2 &lt;&lt; endl; // Increase y1 and y2 and Return to the beginning if (x1 &gt;= X) { //startint points y1 += 10; y2 += 10; // Reinitialize x1 and x2 x1 = -4; x2 = -4; } // sweep again moveLine(x1 + STEP, y1, x2 + STEP,y2); } </code></pre> <hr> <p><strong>Explanation:</strong> </p> <p>I start with x<sub>1</sub> = 5, and x<sub>2</sub> = 5, y<sub>1</sub> = 5 and y<sub>2</sub> = 10 then x<sub>1</sub>+=9, x<sub>2</sub>+=9 till x<sub>1</sub> >= X, then I reinitialize the x<sub>1</sub> and x<sub>2</sub>, and increase y<sub>1</sub> by 5 and y<sub>2</sub> + 5 till y<sub>2</sub> becomes greater than Y.</p> <p>I wrote the piece of Code. it worked ok, but I wanted to your advice and if the recursion function is okay.</p> <p>Thank you.</p>
[]
[ { "body": "<p>I don't know what your code is doing (it is a function without a return value OR side effects), but one way it could be greatly improved is if you use classes to represent the individual pieces:</p>\n\n<pre><code>struct Point {\n int x, y;\n};\n\nstruct LineSegment {\n Point left, right;\n\n LineSegment(const Point&amp; a, const Point&amp; b) {\n // logic here to make sure you assign 'left' and 'right' correctly\n }\n};\n</code></pre>\n\n<p>That way, your signature becomes:</p>\n\n<pre><code>void moveLine(LineSegment ls);\n\n\nint main() {\n Point a{5, 0};\n Point b{5, 10};\n\n moveLine(LineSegment{a, b});\n}\n</code></pre>\n\n<p>This makes the logic much clearer. Your function takes a <code>LineSegment</code> rather than 4 <code>int</code>s.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T16:50:08.683", "Id": "53391", "Score": "0", "body": "Thank you @Barry. Barry What i am trying to do exactly is to move a **vertical** segment along the **x** axis (Sweep a plane). When x1 becomes greater than a threshold then I increase y1 and y2, and then i continue sweeping, Till the coordinate y2 along the Y axis reaches a threshold (y2 is the upper part of the segment), when y2 reaches this threshold I stop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T16:52:15.223", "Id": "53392", "Score": "0", "body": "the figure illustrates how the segments are moving from to right. It's similar to a scanner, when u scan a paper" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T16:03:39.130", "Id": "33331", "ParentId": "33328", "Score": "2" } }, { "body": "<p>Your code has a lot of magic numbers. I can't tell what the significance of the number 20 that is being compared to y1, or the significance of the 20 that is being compared to x1, or whether the two numbers are the same or different (if I changed the number compared to y1 to 30, should I also change the number compared to x1?). One of the comparisons uses > and the other uses >=. I can't tell whether this is what you meant to do or a bug. </p>\n\n<p>If you created named constants with descriptive names, probably all of those things would be obvious. </p>\n\n<p>I think you have a misconception about how function arguments work. Despite having the same name and the same type, the int x1 in main() and the int x1 in moveLine() are different, and the x1 in each recursive call of moveLine() are different. </p>\n\n<p>The line <code>moveLine(x1 += 9, y1, x2+=9,y2);</code> should work, but writing it as <code>moveLine(x1+9, y1, x2+9, y2);</code> is less confusing and would also work. </p>\n\n<p>Also, this code:</p>\n\n<pre><code>int x1 = 5;\nint y1 = 0;\nint x2 = 5;\nint y2 = 10;\nmoveLine(x1, y1, x2, y2);\n</code></pre>\n\n<p>could be written like this:</p>\n\n<pre><code>moveLine(5, 0, 5, 10);\n</code></pre>\n\n<p>(I'm not suggesting you keep the 4 int style; Barry's suggestion is good. I'm just pointing out what looks like a misconception and trying to clear it up.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T17:40:22.330", "Id": "53396", "Score": "0", "body": "yes I understand @Michael. I'm also formating my code according to Barry's suggestion, which is much better. But in general do u think that there is a problem in the recursion function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T18:55:32.217", "Id": "53398", "Score": "0", "body": "I can't see a problem with it. It's possible that you might run into problems with the stack not being large enough if you increased X and Y enough that you ended up making a very large number of recursive calls. If that became a problem, you could replace the recursion with a loop to get around it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T17:27:57.177", "Id": "33336", "ParentId": "33328", "Score": "3" } } ]
{ "AcceptedAnswerId": "33336", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T15:02:47.310", "Id": "33328", "Score": "3", "Tags": [ "c++", "algorithm", "recursion", "computational-geometry" ], "Title": "Move Line across Plane" }
33328
<p>I'm just learning OOP, and I have an assignment to create a Stack. I came up with the following. Is it "beauty" enough, or to "schooly". Where can I evolve?</p> <p>This is the class:</p> <pre><code>class Stack { private int _length; private List&lt;int&gt; _members = new List&lt;int&gt;(); public Stack() { _length = 10; } public Stack(int length) { _length = length; } public List&lt;int&gt; Members { get { return _members; } } public int Length { get { return _members.Count; } } public bool IsEmpty { get { return (_members.Count == 0); } } public void Push(int member) { if (_members.Count &lt; _length) _members.Add(member); else throw new Exception("The Stack is full."); } public int Pop() { if (!IsEmpty) { int last_one = _members[_members.Count - 1]; _members.RemoveAt(_members.Count - 1); return last_one; } else throw new Exception("The Stack is empty."); } } </code></pre> <p>And this is my Form:</p> <pre><code>public partial class Form1 : Form { Stack verem = new Stack(20); Random rnd = new Random(); public Form1() { InitializeComponent(); } private void refreshStack() { lbStack.Items.Clear(); foreach (int member in verem.Members) { lbStack.Items.Insert(0, member); } } private void btnIsEmpty_Click(object sender, EventArgs e) { MessageBox.Show(verem.IsEmpty.ToString()); } private void btnLength_Click(object sender, EventArgs e) { MessageBox.Show(verem.Length.ToString()); } private void btnPush_Click(object sender, EventArgs e) { verem.Push((int)rnd.Next()); refreshStack(); } private void btnPop_Click(object sender, EventArgs e) { verem.Pop(); refreshStack(); } } </code></pre>
[]
[ { "body": "<pre><code>class Stack\n</code></pre>\n\n<p>Stack (or any other collection) is a prime example of type that should be generic.</p>\n\n<pre><code>private int _length;\n</code></pre>\n\n<p>I think length is not a good name for this. You should rename it to something like <code>_maxLength</code>, or even better, <code>_maxCount</code> (see below).</p>\n\n<p>Also, I'm not completely sure if this feature is necessary, but it could make sense (for example <code>System.Collections.Generic.Stack&lt;T&gt;</code> doesn't have anything like this, but <code>System.Collections.Concurrent.BlockingCollection&lt;T&gt;</code> does).</p>\n\n<pre><code>_length = 10;\n</code></pre>\n\n<p>I don't think 10 is a reasonable default here. It would certainly be unexpected to me. A much better default would be infinity. Or maybe don't have a default at all.</p>\n\n<pre><code>public List&lt;int&gt; Members\n</code></pre>\n\n<p>Unless absolutely necessary, you should <em>never</em> expose private implementation details like this. Using this member, anyone can do anything to the underlying collection (including adding items beyond the allowed maximum number).</p>\n\n<p>If you want to be able to iterate over the items in the collection, you should implement <code>IEnumerable&lt;T&gt;</code>.</p>\n\n<pre><code>public int Length\n</code></pre>\n\n<p>The name <code>Length</code> makes some sense for arrays, but not so much for other collections. For consistency with other collections, the best name would be <code>Count</code>.</p>\n\n<pre><code>return (_members.Count == 0);\n</code></pre>\n\n<p>The parentheses are not necessary here.</p>\n\n<pre><code>if (_members.Count &lt; _length) _members.Add(member);\nelse throw new Exception(\"The Stack is full.\");\n</code></pre>\n\n<p>You probably shouldn't write the body of <code>if</code> and <code>else</code> on the same line like this. Putting them on a line of their own will make your code clearer to read.</p>\n\n<pre><code>throw new Exception(\"The Stack is full.\")\n</code></pre>\n\n<p>You shouldn't throw <code>Exception</code> directly, you should create your own type that inherits from <code>Exception</code> and throw that. Alternatively, you could use an existing exception type, like <code>InvalidOperationException</code>.</p>\n\n<pre><code>if (!IsEmpty)\n{\n …\n}\nelse throw new Exception(\"The Stack is empty.\");\n</code></pre>\n\n<p>You could simplify this by reversing the condition and putting the exception first. This way, the main code will be less indented.</p>\n\n<pre><code>public partial class Form1 : Form\n</code></pre>\n\n<p>You should name your forms with more descriptive names, even if it's something as simple as <code>MainForm</code>.</p>\n\n<pre><code>lbStack\n</code></pre>\n\n<p>This form of <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\">Hungarian notation</a> is usually frowned on. If you want to indicate that the variable is a list box, you can name is something like <code>stackListBox</code>.</p>\n\n<pre><code>(int)rnd.Next()\n</code></pre>\n\n<p>You don't need a cast here, <code>Next()</code> already returns an <code>int</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T16:34:37.847", "Id": "33333", "ParentId": "33329", "Score": "6" } }, { "body": "<p>Some thoughts:</p>\n\n<ul>\n<li><p>Indent your code or type Ctrl-E-D in Visual Studio, this will reformat your code automatically. It makes it more readable.</p></li>\n<li><p>Rename your <code>_length</code> variable and your <code>length</code> parameter to <code>_maxCapacity</code> and <code>maxCapacity</code>. This makes its meaning clearer.</p></li>\n<li><p>A <code>List&lt;T&gt;</code> grows automatically, so either drop your maximum capacity constraint or use an array instead, because arrays have a fixed length once they have been created. Since you can get the array length with <code>a.Length</code>, drop the <code>_length</code> (or <code>_maxCapacity</code>) field and instead use a <code>_count</code> field in order to know how many items are in the stack (in case you chose the second variant).</p></li>\n<li><p>By adding a generic type parameter <code>T</code> to the class and replacing every occurrence of <code>int</code> representing a stack item by <code>T</code> you would get a generic stack for free.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Stack&lt;T&gt;\n{\n private List&lt;T&gt; _members = new List&lt;T&gt;();\n // OR\n private T[] _members = new T[_maxCapacity];\n ...\n</code></pre>\n\n<p>Then you can create stacks like this:</p>\n\n<pre><code>var stringStack = new Stack&lt;string&gt;(10);\nstringStack.Push(\"Hello\");\nvar doubleStack = new Stack&lt;double&gt;(10);\n</code></pre></li>\n<li><p>Let the <code>Members</code> property return an <code>IEnumerable&lt;int&gt;</code> (or <code>IEnumerable&lt;T&gt;</code>) or let the <code>Stack</code> class implement <code>IEnumerable&lt;T&gt;</code> directly (if you don't know how to do that, changing the return type of the <code>Members</code> property is good enough to begin with). Exposing <code>_members</code> through a list allows manipulations of it from outside. IEnumerables can only be read. If you need to return a list or an array then return a copy of <code>_members</code>, not the original.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T17:30:24.143", "Id": "53394", "Score": "0", "body": "Thank you. I think I've corrected everything. I've got one more question, thou. How can I create another button with which I can add the maxCount and I can instantiate a new stack with that maxCount values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T18:44:53.317", "Id": "53397", "Score": "0", "body": "What is the question exactly? I assume that you know how to add buttons and textboxes. In the button Click event handler you will have to convert the textbox's text to an `int`. `int maxCount; if(Int32.TryParse(maxCountTextBox.Text, out maxCount)) { stack = new Stack(maxCount); }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T20:08:08.957", "Id": "53405", "Score": "0", "body": "Sorry. It's okay. I forgot that I'm using list instead of array." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T17:02:59.073", "Id": "33335", "ParentId": "33329", "Score": "2" } } ]
{ "AcceptedAnswerId": "33333", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T15:45:14.870", "Id": "33329", "Score": "3", "Tags": [ "c#", "stack" ], "Title": "Is it needed to \"beautify\" this Stack implementation?" }
33329
<p>I have just made what seems to me to be the first reliable prime-checking program that works. However, I am not sure if it is completely reliable, or if there are problems. It relies on list-making more than math, and it can be slow for bigger numbers. Do you think there are any problems?</p> <pre><code>def primeChecker(x): if x &lt;= 1 or isinstance(x,float) == True: return str(x) + " is not prime" else: div = ["tepi"] #tepi denotes test element please ignore for i in range(1,x+1,1): if x % i == 0: div.append("d") #d denotes divisible else: div.append("n") #n denotes not divisible if div[1] == "d" and div[x] == "d" and div.count("n") == x - 2: return str(x) + " is prime" else: return str(x) + " is not prime" def primeCheckList(d,e): for i in range(d,e + 1): print primeChecker(i) </code></pre> <p>Here are some of the tools I used in <code>primeChecker()</code> to see if it was working right.</p> <pre><code>print div #these are testing tools print range(1,x+1,1) print div[1] print div[x] print div[2:x] print div.count("n") print x - 2 </code></pre> <p>edit: Barry's feedback</p> <p>OK, based on what Barry told me, i was able to clean up and otherwise format my code to be more concise, no more lists needed. it seems to run smoother, and is otherwise easier to read. here it is:</p> <pre><code>def isPrime(x): if x &lt;= 1 or isinstance(x,float): return False else: for divisor in range(2,x,1): if x % divisor == 0: return False return True def primeChecker(n): if isPrime(n): return "%d is prime" % n else: return "%d is not prime" % n def primeCheckList(d,e): for i in range(d,e + 1): print primeChecker(i) </code></pre> <p>any more feedback to give?</p>
[]
[ { "body": "<p>There is lots of room for improvement here. Let me give some broad guidelines:</p>\n\n<p>First, Your function checking if its input is prime should return a boolean and probably be called something like <code>isPrime</code> or <code>is_prime</code>. The string you are returning is nice for being human readible, but the goal should be to build components that can be used elsewhere, and the function as written isn't really something you can build on. And given the boolean function, you can easily build your version on top of that:</p>\n\n<pre><code>def prime_checker(n):\n if is_prime(n):\n return \"%d is prime\" % n\n else:\n return \"%d is not prime\" % n\n</code></pre>\n\n<p>Second, there is some improper use of Booleans (and lack thereof). You have <code>isinstance(x,float) == True</code>. The <code>isinstance</code> function already returns a boolean, there's no need to compare against <code>True</code>. That clause can just be <code>if x &lt;= 1 or isinstance(x, float):</code>. But then, does it make sense that 2.7 is not prime? Maybe that should raise an Exception. You are also building up a list of size <code>x</code> consisting of values that are intended to indicate whether or not the value at that index divides <code>x</code>. You chose:</p>\n\n<pre><code>div.append(\"d\") #d denotes divisible\n</code></pre>\n\n<p>Which you realized was cryptic because you had to comment what that meant. Rather than relying on a comment to explain what you're doing, it's much better for the code to comment itself. In this case, what should we append to indicate that a number is a true divisor? How about:</p>\n\n<pre><code>div.append(True)\n</code></pre>\n\n<p>Third, you're building up a long list of things that should be Booleans but are instead strings. But that is a whole lot of extra work for what we actually want to count: the number of factors. The simplest explanation for why it's extra work is that first you're walking through all potential divisors, and then you're walking through it again to count how many were actual divisors. Instead, you can do this in one go:</p>\n\n<pre><code>divisors = 0\nfor divisor in range(1, x+1): \n if x % divisor == 0:\n ++divisors\nreturn divisors == 2 #because a number prime iff it has exactly 2 divisors, 1 and itself\n</code></pre>\n\n<p>Once you write it that way, this has lots of room for simple optimizations. For instance, obviously every integer is divisible by 1 and itself, so you can exclude those two:</p>\n\n<pre><code>for divisor in range(2, x):\n if x % divisor == 0:\n return False # because we have a divisor other than 1 or x\nreturn True\n</code></pre>\n\n<p>After that, things get more interesting. For instance, let's say we're checking a number like 5077 for primality. If it is NOT prime, then there are two numbers, <code>a</code> and <code>b</code>, such that <code>1 &lt; a &lt;= b &lt; n</code> and <code>a*b == n</code>. What is the largest possible value for <code>a</code> as a function for <code>n</code>? I'll leave that as an exercise, but the last algorithm I proposed assumes the maximum possible value is <code>x - 1</code>, and we can do much better. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T19:47:22.757", "Id": "53400", "Score": "0", "body": "i must say, you kind of lost me with your last paragraph, can you explain what you are talking about? like im 5?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T18:40:21.630", "Id": "33339", "ParentId": "33337", "Score": "1" } } ]
{ "AcceptedAnswerId": "33339", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T18:20:51.193", "Id": "33337", "Score": "3", "Tags": [ "python", "beginner", "primes" ], "Title": "Any problems with this prime checker script?" }
33337
<p>Generate new password and send to user, if user is registered.</p> <ul> <li>Two <code>TextBox</code> on page, <code>txtUserName</code> &amp; <code>txtEamil</code>.</li> <li>User can provide either <code>UserName</code> or <code>Email</code> to get new password.</li> <li>If <code>UserName</code> is provided then find User on <code>username</code>, if exists then generate new password and Email.</li> <li>If user provided email then check if any user exists with provided email then generate new password and Email.</li> </ul> <p></p> <pre><code>protected void btnSubmit_Click(object sender, EventArgs e) { string userName = txtUserName.Text.Trim(); string email = txtEmail.Text.Trim(); // if (string.IsNullOrEmpty(userName) &amp;&amp; string.IsNullOrEmpty(email)) { lblMessage.Text = "Please provide at least either of the one, User Name or Email."; } else { SendNewPasswordToUser(userName, email); } } private void SendNewPasswordToUser(string userName, string email) { if (!string.IsNullOrEmpty(userName)) { MembershipUser mu = Membership.GetUser(userName); if (mu != null) { string password = mu.ResetPassword(); EmailPassword(password, mu.Email); } } else if (!string.IsNullOrEmpty(email)) { userName = Membership.GetUserNameByEmail(email); if (!string.IsNullOrEmpty(userName)) { MembershipUser mu = Membership.GetUser(userName); string password = mu.ResetPassword(); EmailPassword(password, mu.Email); } } } private void EmailPassword(string password, string toEmail) { string mailBody = string.Format("Your new password is {0}", password); Mail.SendMail("admin@abc.com", toEmail, "New Password", mailBody); } </code></pre> <p>Is there a better approach to avoid so many <code>if</code>s?</p>
[]
[ { "body": "<p>The only thing that I can think of right now is making <code>SendNewPasswordToUser</code> two separate methods.</p>\n\n<p>but this would just move the code around a little bit, on the other hand the way you have it written right now, you are sending an Empty variable into the Method whether the users gives an E-mail or a Username, and that seems a little messy to me.</p>\n\n<p>personally, I think that I would split it up as two separate methods so that if the user inputs a Username it sends a Username into the proper method, and if the user inputs an E-mail it sends the E-mail into the proper method. </p>\n\n<p>I think that this would also help with maintainability further down the road.</p>\n\n<p>if you want to do some checking on the username or the E-mail address, you can work on that stuff separately, it makes things easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T03:13:13.367", "Id": "33360", "ParentId": "33341", "Score": "3" } }, { "body": "<p>Before reviewing the code, the concept itself has some flaws:</p>\n\n<ul>\n<li>It is possible to reset the password of another user by entering their email address or username.</li>\n<li>The password is provided directly in the email which is bad practise (not only is this in clear text but it will be retained in the user's inbox which is not a good place to store passwords).</li>\n</ul>\n\n<p>Entering the email or username should display the same message to the website user regardless of whether the user exists or not. This would stop an attacker from enumerating usernames (i.e. finding whether a particular username or email address is registered on your system). In the email itself include either the details of a password reset link or an account not found message as appropriate for that username/email - this way only the email address owner can see whether they have an account on your system.</p>\n\n<p>The password reset link should be include a time limited reset token that will allow the user to change their password to one of their choosing and it should not then email this out anywhere. Make sure the token is securely generated and does not use a predictable sequence (i.e. a cryptographically secure sequence and not one generated using a <code>Random</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T18:10:49.370", "Id": "53514", "Score": "0", "body": "Thanks to review my code. I have changed my logic and now I send a link to user to change password." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T18:17:46.947", "Id": "53517", "Score": "0", "body": "I agree SilverlightFox ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-02T12:11:18.013", "Id": "214695", "Score": "0", "body": "@Kashif if you're still supporting this system, please move to the built in asp.net membership system. It handles all these nitty gritty details for you. Much more secure than anything we could write ourselves. It behaves exactly as SilverloghtFox suggested it should." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:14:02.273", "Id": "33393", "ParentId": "33341", "Score": "4" } }, { "body": "<p>Something like this? The booleans are there so you can warn the user if you didn't send an email. That said, I agree with <a href=\"https://codereview.stackexchange.com/a/33393/8243\">SilverlightFox's answer</a>; allowing users to reset each other's passwords is probably a bad idea.</p>\n\n<pre><code>private bool SendNewPasswordToUserByEmail(string email)\n{\n return SendNewPasswordToUser(Membership.GetUserNameByEmail(email ?? String.Empty));\n}\n\nprivate bool SendNewPasswordToUser(string userName)\n{\n MembershipUser mu = Membership.GetUser(userName ?? String.Empty);\n if (mu == null)\n {\n return false;\n }\n string password = mu.ResetPassword();\n EmailPassword(password, mu.Email);\n return true;\n}\n</code></pre>\n\n<p>Personally, I'd add another <code>if</code> to check for null rather than using <code>??</code>, but you said to reduce use of conditionals.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:38:23.967", "Id": "53510", "Score": "0", "body": "It would be even cleaner if the `btnSubmit_Click` function decided which one of these functions to call (and you could omit both null checks and coalescing either way; I wrote these functions independent of knowledge of the callers)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T18:12:26.970", "Id": "53516", "Score": "0", "body": "Thanks for the effort. Your suggestions are good and I just missed this ?? operator. I have changed my logic to email a change password link to user." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-02T14:14:37.620", "Id": "360537", "Score": "0", "body": "In hindsight, warning the user if no e-mail was sent may be considered a security hole. Depending on the value of your site, you may want it to be difficult for malicious users to detect which users have an account." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:34:07.570", "Id": "33410", "ParentId": "33341", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T19:15:35.320", "Id": "33341", "Score": "5", "Tags": [ "c#", "asp.net" ], "Title": "Generating and sending new password to user" }
33341
<pre><code>let reply = ref "" let doAuto = async { let! resultAA = async { return SqlCmd.aaHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultBB = async { return SqlCmd.bbHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultCC = async { return SqlCmd.ccHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultDD = async { return SqlCmd.ddHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultEE = async { return SqlCmd.ddHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultFF = async { return SqlCmd.ffHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultGG = async { return SqlCmd.ggHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultHH = async { return SqlCmd.hhHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultII = async { return SqlCmd.iiHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultJJ = async { return SqlCmd.jjHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let! resultKK = async { return SqlCmd.kkHits query |&gt; Async.RunSynchronously |&gt; List.ofSeq } let length1 = resultAA.Length + resultBB.Length if length1 &gt; 9 then reply := "hey " + length1.ToString() else let x = resultCC.Length + resultDD.Length + resultEE.Length + resultFF.Length + resultGG.Length + resultHH.Length + resultII.Length + resultJJ.Length + resultKK.Length + length1 reply := x.ToString() } |&gt; Async.StartImmediate !reply </code></pre> <p>The typical <code>SqlCmd.xxHits</code> (in module <code>SqlCmd</code>) built using <code>FSharp.Data.SqlCommandTypeProvider</code> looks like this:</p> <pre><code>[&lt;Literal&gt;] let sqlXX = "SELECT ...@startsWith..." type QueryXX = SqlCommand&lt;sqlXX, ConnectionStringName=...&gt; let xxHits query = let cmdXxHits = QueryXX(connectionString = connectionString, startsWith = query) cmdXxHits.AsyncExecute() </code></pre> <p>I'm pretty inexperienced at using async. Looking for feedback, especially in a couple of areas:</p> <ol> <li><p>I couldn't think of a better way to get my results out from inside the outer async than the ref. From what I read it sounded like <code>Async.StartImmediate</code> was the best solution for something running in an IIS application. </p></li> <li><p>From the results of the first 2 inner asyncs, I may choose to quit before waiting for any more completions. Should I really be cancelling the remaining asyncs? Does it matter?</p></li> </ol>
[]
[ { "body": "<p>Avoid <code>Async.RunSynchronously</code> until absolutely necessary. It is very inefficient by design. Looks like you need:</p>\n\n<pre><code>async { let! xs = SqlCmd.xxxHits query\n return List.ofSeq xs }\n</code></pre>\n\n<p>Which you should probably abstract into a function.</p>\n\n<p>Once you remove the blocking (<code>RunSynchronously</code>), the <code>ref</code> use also becomes invalid - you are querying the <code>ref</code> potentially before the async changes it - race condition. Try returning it (<code>return</code>) in the main async instead.</p>\n\n<p>If you really want the subqueries to execute in parallel, consider a helper combinator like <code>Async.Parallel</code> rather than starting multiple sub-computations manually.</p>\n\n<p>Your function should return <code>Async&lt;string&gt;</code> instead of <code>string</code>. If the caller of your code wants a <code>string</code> and cannot possibly use <code>Async</code>, they'll call <code>Async.RunSynchronously</code> - make it their problem.</p>\n\n<p>Concerning choosing to quit based on the result of first two asyncs, not sure what you need exactly. Cancellation is an optimization - it may be tricky to get right but may make the code better performing. It's your decision based on the problem domain whether it is worth it or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T22:44:15.277", "Id": "53413", "Score": "0", "body": "Yes I want to execute in parallel, but I want to evaluate the first 2 as soon as they are ready, at which point either quit or await the remaining queries. Maybe this is too impractical and I should just execute all in parallel. Another issue I have with Async.Parallel is telling results apart." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T23:02:45.180", "Id": "53415", "Score": "0", "body": "You can execute the first 2 in parallel, and then the rest in parallel, with these two steps sequential. You might want some helper combinators like this: https://gist.github.com/toyvo/20f10e29b09688a08138" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T22:14:55.763", "Id": "33349", "ParentId": "33347", "Score": "1" } }, { "body": "<p>You're running all the Asyncs through Async.RunSynchronously, which means you shouldn't be running them Async at all. You should be using Execute instead of AsyncExecute in xxHits, and all those <code>Async.RunSynchronously</code> disappear. The <code>let!</code> means that you're still waiting for each before going to the next, even if you are inside of an async. <code>let!</code> in this context just means wait for this async before continuing with the rest of this computation. </p>\n\n<p>The ref lets you (try to) read the result before it is done. It should be replaced with a return. return means that the 'T in your Async&lt;'T> is your result, and you can not get at it before it is done. One less source of bugs. </p>\n\n<p>Given xxHits is:</p>\n\n<pre><code>let xxHits query = \n let cmdXxHits = QueryXX(connectionString = connectionString, startsWith = query)\n cmdXxHits.Execute()\n</code></pre>\n\n<p>your main body becomes something like</p>\n\n<pre><code>let doAuto = \n let! resultAA = SqlCmd.aaHits query |&gt; List.ofSeq\n let! resultBB = SqlCmd.bbHits query |&gt; List.ofSeq\n ... \n\n let length1 = resultAA.Length + resultBB.Length\n\n if length1 &gt; 9 then reply := \"hey \" + length1.ToString()\n else\n let x = resultCC.Length + resultDD.Length + resultEE.Length + resultFF.Length + resultGG.Length \n + resultHH.Length + resultII.Length + resultJJ.Length + resultKK.Length + length1\n x.ToString()\n</code></pre>\n\n<p>As it is, you have a perf hit for running async computations that are not async.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T22:53:10.200", "Id": "53414", "Score": "0", "body": "I simplified the queries, the real ones each return something quite different. I'm trying do them in parallel (but I think Async.Parallel will not work for me) and evaluate the first 2 as soon as they are available." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T22:21:27.103", "Id": "33350", "ParentId": "33347", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T21:47:50.927", "Id": "33347", "Score": "1", "Tags": [ "sql", "f#" ], "Title": "Async querying SQL in IIS" }
33347
<p>I have a list of tuples (<code>key</code>, <code>value1</code>, <code>value2</code>, ...). I simplify the tuple here so it is only of length 2. Keys contain duplicated figures.</p> <pre><code>xs = zip([1,2,2,3,3,3,4,1,1,2,2], range(11)) # simple to input [(1, 0), (2, 1), (2, 2), (3, 3), (3, 4), (3, 5), (4, 6), (1, 7), (1, 8), (2, 9), (2, 10)] </code></pre> <p>Now, I would like to build a function, which takes the list as input, and return a list or generator, which is a subset of the original list.</p> <p>It must captures all items where the keys are changed, and include the first and last items of the list if they are not already there.</p> <pre><code>f1(xs) = [(1, 0), (2, 1), (3, 3), (4, 6), (1, 7), (2, 9), (2, 10)] f1([]) = [] </code></pre> <p>The following is my code, it works, but I don't really like it:</p> <pre><code>xs = zip([1,2,2,3,3,3,4,1,1,2,2], range(11)) def f1(xs): if not xs: return last_a = None # I wish I don't have to use None here. is_yield = False for a, b in xs: if a != last_a: last_a = a is_yield = True yield (a, b) else: is_yield = False if not is_yield: yield (a, b) # Ugly...in C# a, b is not defined here. print list(f1(xs)) print list(f1([])) </code></pre> <p>What's a better (functional or nonfunctional) way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T23:10:46.573", "Id": "53417", "Score": "0", "body": "@Barry I rephased a little bit. My input list is a list of tuples... so on input `[(1,a),(2,b),(2,c)]` I want `[(1,a),(2,b),(2,c)]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T16:19:43.970", "Id": "59307", "Score": "1", "body": "if you want an answer for specific languages you need to post separate questions with the coding done in those languages. we will not translate this code for you, nor will we write code for you" } ]
[ { "body": "<p>The <code>itertools</code> library has a handy function for this problem called <a href=\"http://docs.python.org/2/library/itertools.html#itertools.groupby\" rel=\"nofollow\">groupby</a>:</p>\n\n<pre><code>def f1(xs):\n for _, group_iter in itertools.groupby(xs, key = lambda pair: pair[0]):\n group = list(group_iter)\n yield group[0]\n</code></pre>\n\n<p>That'll get us the pairs for which the first element changed from the previous one. Now we just need to make sure we're yield-ing the last element. Which will only NOT be yielded if the last group has size more than 1, hence:</p>\n\n<pre><code>def f1(xs):\n for _, group_iter in itertools.groupby(xs, key = lambda pair: pair[0]):\n group = list(group_iter)\n yield group[0]\n\n # make sure we yield xs[-1]\n if len(group) &gt; 1:\n yield group[-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T23:47:26.690", "Id": "53418", "Score": "0", "body": "great, don't know that `groupby` is not the same as SQL" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:35:59.883", "Id": "53509", "Score": "2", "body": "Need `group = None` and then check `if group` to handle empty `xs`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T23:33:33.920", "Id": "33354", "ParentId": "33352", "Score": "2" } }, { "body": "<p>For interest value here's a custom recursive solution in F# that performs a pairwise comparison, always keeping the first value, and the last if it wasn't already included. </p>\n\n<pre><code>let pairwiseFilter input = \n let rec aux acc = function\n | x::y::xs when fst x &lt;&gt; fst y -&gt; aux (y::acc) (y::xs)\n | x::y::xs -&gt; aux acc (y::xs)\n | x::[] -&gt; List.rev (if x &lt;&gt; acc.Head then x::acc else acc)\n | [] -&gt; acc\n aux [List.head input] input\n</code></pre>\n\n<p>Note the requirement to always include the first item is handled by simply passing it in as the initial value of the results accumulator. From there we compare the first and second items, and if they are different we add the second item to the results. Then we take the second item and cons it to the rest of the list (pairwise) which is processed recursively.</p>\n\n<p>Finally the resulting list has the last element appended if it wasn't already in the previous step (eg, its not the same as the head of the results accumulator). The results are then reversed to preserve the original input order.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-11T00:00:14.933", "Id": "35145", "ParentId": "33352", "Score": "1" } }, { "body": "<p>Here's a sloution using <code>Seq.pairwise</code>:</p>\n\n<pre><code>let f input = \n let result = \n [-1,-1] @ input\n |&gt; Seq.pairwise \n |&gt; Seq.filter (fun ((key1, valu1), (key2, value2)) -&gt; key1 &lt;&gt; key2)\n |&gt; Seq.map snd\n |&gt; Seq.toList\n if not input.IsEmpty &amp;&amp; Seq.last result &lt;&gt; Seq.last input \n then result @ [Seq.last input] else result \n</code></pre>\n\n<p>We add a dummy element to the beginning of the list to make sure it is included, and then at the end cover the last item</p>\n\n<pre><code>&gt;let xs = [1, 0\n 2, 1\n 2, 2\n 3, 3\n 3, 4\n 3, 5\n 4, 6\n 1, 7\n 1, 8\n 2, 9\n 2, 10]\n&gt;f xs\nval it : (int * int) list =\n [(1, 0); (2, 1); (3, 3); (4, 6); (1, 7); (2, 9); (2, 10)]\n\n&gt;f []\nval it : (int * int) list = []\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T15:31:32.530", "Id": "36218", "ParentId": "33352", "Score": "1" } } ]
{ "AcceptedAnswerId": "33354", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T23:00:30.620", "Id": "33352", "Score": "2", "Tags": [ "python" ], "Title": "Returning items which are different from their preceding items from a list" }
33352
<p>The idea is to get a listing of monthly bills with amounts paid. The subquery does a total through a group by using <code>bill_id</code> and <code>party_id</code>.</p> <p>I wish to know how it can be improved. I'm not comfortable with <code>JOIN</code>s and am willing to learn.</p> <pre><code>SELECT bill.id as bill_id, master.id as party_id, master.name as party_name, `amountExcVat`, bill.vat, amountExcVat + bill.vat as 'amtIncVat', `purchasedDate`, (SELECT SUM( cashPaid ) + SUM( chequePaid ) FROM `partypayment` WHERE party_id = partyId AND bill_id = partyBillId GROUP BY partyId, partyBillId) as 'Amount Paid(cash+chq)', bill.status FROM `partybill` as bill, `partymaster` as master, partypayment as payment WHERE bill.partyId = master.id AND bill.partyId = payment.id AND UPPER(MONTHNAME(`purchasedDate`)) = 'OCTOBER' AND YEAR(`purchasedDate`) = '2013' </code></pre> <p>Tables are as follows. <strong>They provided by a third party so I can't modify them.</strong></p> <blockquote> <pre><code>create table partymaster ( id INT(4) ,name varchar(100) PRIMARY KEY ,address varchar(200) ,contactNo1 BIGINT(14) ,contactNo2 BIGINT(14) ); </code></pre> <hr> <pre><code>create table partypurchase ( id INT(10) ,partyId INT(4) references partymaster(id) ,head varchar(100) ,brand varchar(100) ,size varchar(10) ,costPrice INT(6) ,sellingPrice INT(6) ,quantity INT(4) ,totalCost INT(10) ,purchasedDate date ); </code></pre> <hr> <pre><code>create table partybill ( id INT(10) PRIMARY KEY ,partyId INT(4) references partymaster(id) ,amountExcVat INT(10) ,vat INT(10) ,amountIncVat INT(10) ,purchasedDate date ,expectedPaymentDate date ,status varchar(10) ); </code></pre> <hr> <pre><code>create table partypayment ( id INT(10) PRIMARY KEY ,partyId INT(4) references partymaster(id) ,partyBillId INT(10) references partybill(id) ,cashPaid INT(10) ,chequePaid INT(10) ,chequeBankName varchar(50) ,chequeNumber INT(10) ,chequeDate date ,paymentDate date ); </code></pre> </blockquote>
[]
[ { "body": "<p>Do you really need the subquery?</p>\n\n<pre><code>SELECT\nbill.id as bill_id,\nmaster.id as party_id,\nmaster.name as party_name,\n`amountExcVat`,\nbill.vat,\namountExcVat + bill.vat as 'amtIncVat',\n`purchasedDate`,\nbill.status,\nSUM(payment.cashPaid) + SUM(payment.chequePaid) as 'Amount Paid(cash+chq)',\nFROM `partybill` as bill, `partymaster` as master, partypayment as payment\nWHERE\nparty_id = partyId AND\nbill_id = partyBillId AND\nbill.partyId = master.id AND\nbill.partyId = payment.id AND\nUPPER(MONTHNAME(`purchasedDate`)) = 'OCTOBER' AND\nYEAR(`purchasedDate`) = '2013'\nGROUP BY partyId, partyBillId)\n</code></pre>\n\n<p>(I just wrote this without testing it so it might not work right out of the box)</p>\n\n<p>Since you are already querying <em>partypayment</em> you should be able to do this</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T09:01:04.967", "Id": "33378", "ParentId": "33353", "Score": "2" } } ]
{ "AcceptedAnswerId": "33378", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T23:33:07.613", "Id": "33353", "Score": "4", "Tags": [ "sql", "mysql", "finance" ], "Title": "SQL query for monthly bills with amounts paid" }
33353
<p>Today I started to make a class called <code>Fraction</code>, where the class will act just like a fraction does in real mathematics. I am doing this just for the challenge. So far I only made the addition part, because I wanted to know if anybody had any suggestions for me.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cmath&gt; //fmax #include &lt;vector&gt; #include &lt;sstream&gt; //stringstream typedef const std::string constr; namespace Util { template &lt;typename T&gt; constr tostring (T t) { std::stringstream s; s &lt;&lt; t; return s.str(); } }//namespace Util namespace math { class Fraction; typedef const double cd; typedef const long cl; typedef std::vector&lt;Fraction&gt; vf; class Math //for future use { private: public: }; class Fraction //Fractions cannot be of type 1.2/5.6 { private: //variables public: //variables long numerator; long denominator; private: //functions public: Fraction(); Fraction(cl numerator_, cl denominator_); ~Fraction(); Fraction operator+ (const Fraction num); Fraction operator+ (cl num); //should be possible, for mixed numbers (1 1/2 = 1+1/2=1/2+1) cl getcommondemon (cl num1, cl num2); vf setcommondemon (const Fraction&amp; num1, const Fraction&amp; num2); constr tostring(void); }; Fraction Fraction::operator+ (const Fraction num) { vf out = Fraction::setcommondemon(*this, num); Fraction nn1 = out.at(0); Fraction nn2 = out.at(1); Fraction output; output.numerator = nn1.numerator+nn2.numerator; output.denominator = nn1.denominator; return output; } cl Fraction::getcommondemon(cl num1, cl num2) { if(num1 == num2) return num1; int max = fmax(num1, num2); int min = fmin(num1, num2); if(max % min == 0) //is max a multiple of min? if yes { return max; } else { return max*min; } } Fraction::Fraction() { numerator = 0; denominator = 0; } Fraction::Fraction(cl numerator_, cl denominator_) { numerator = numerator_; denominator = denominator_; } Fraction::~Fraction() { //destructor } vf Fraction::setcommondemon(const Fraction&amp; num1, const Fraction&amp; num2) { vf output; Fraction out1; Fraction out2; if(num1.denominator == num2.denominator) { output.push_back(num1); output.push_back(num2); return output; } bool num1bigger = false; long max = 0; long min = 0; if(num1.denominator &gt; num2.denominator) { num1bigger= true; max = num1.denominator; min = num2.denominator; } else { min = num1.denominator; max = num2.denominator; } if(max % min == 0) //is max a multiple of min? if yes { cl multi = max/min; if(num1bigger == true) { out2.numerator = num2.numerator*multi; out2.denominator = num2.denominator*multi; out1 = num1; } else { out1.numerator = num1.numerator*multi; out1.denominator = num1.denominator*multi; out2 = num2; } output.push_back(out1); output.push_back(out2); return output; } else { out1.numerator = num1.numerator*num2.denominator; out1.denominator = num1.denominator*num2.denominator; out2.numerator = num2.numerator*num1.denominator; out2.denominator = num2.denominator*num1.denominator; output.push_back(out1); output.push_back(out2); return output; } } constr Fraction::tostring() { return Util::tostring(numerator) + "/" + Util::tostring(denominator); } } //namespace math int main(int argc, char* argv[]) { math::Fraction a(1,6); math::Fraction b(1,3); math::Fraction out = a+b; std::cout &lt;&lt; out.tostring() &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<p>Here's a few pointers:</p>\n\n<p>Do not typedef cv-qualified types. It will confuse everybody who reads your code. Seeing <code>cl</code> is really confusing, seeing <code>const long</code> is completely understandable. So get rid of the <code>cd</code> and <code>constr</code>. </p>\n\n<p>If you want to typedef <code>std::vector&lt;Fraction&gt;</code>, you need to provide a reasonable name for that type... <code>vf</code> while concise conveys precisely zero information. So either do not typedef it, which is fine, or call it <code>FractionVec</code> or <code>Fractions</code>.</p>\n\n<p><code>Fraction</code> should not have a default constructor. Why would 0/0 be the default?</p>\n\n<p>You either need to provide <code>operator==</code> or change the internal representation to keep things to lowerst terms, cause right now <code>Fraction{1, 2} != Fraction{2, 4}</code>. </p>\n\n<p>Functions with multiple words in the name should either look like <code>getCommonDenom</code> or <code>get_common_denom</code>. Running words together having everything be lowercase makes it hard to read. Also, not sure why either of those functions exist, or how it makes sense that a function named <code>setcommondenom</code> returns a <code>vector&lt;Fraction&gt;</code>??? Also this function is almost certainly wrong given its length, look up Euler's algorithm for gcd and use it. </p>\n\n<p>Rather than defining two separate <code>operator+</code> member functions (one of them is wrong, it should take a <code>const Fraction&amp;</code> btw), you should create an external friend function and make <code>long</code>s implicitly convert to <code>Fraction</code>:</p>\n\n<pre><code>Fraction() = delete; // no\nFraction(long numer, long denom = 1); // doesn't have to be const\nfriend Fraction operator+(const Fraction&amp; a, const Fraction&amp; b); // non-member +\n</code></pre>\n\n<p>This lets you do 1 + Fraction{2,3} too!</p>\n\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T03:15:42.310", "Id": "33361", "ParentId": "33358", "Score": "3" } }, { "body": "<p>Below I propose my cleaning to your code. Some comments:</p>\n\n<ul>\n<li><p>don't use typedef to spare key-typing: it is best to let the code be verbose</p></li>\n<li><p>maybe you can use it for future flexibility (as I did in my sample below). Maybe in the future you want to parameterize your class over integer type</p></li>\n<li><p>if you want to define a general purpose class, the less includes the better (less dependencies).</p></li>\n<li><p>a fraction can be represented in many different ways. It is a good choice to guarantee that it is always in normalized form. This is achieved by a Fraction::normalize private function. To assure that the user does not violate this, data members should be private. If needed you can write public method to access the values</p></li>\n<li><p>if you put a denominator=1 default value in the constructor you have implicit cast from integers to fractions. No need to define two different operator+</p></li>\n<li><p>why to use stringbuf to convert fraction to a string? Provide an operator&lt;&lt; to write to a stream and let the user use stringbuf if he really needs a string.</p></li>\n<li><p>define a GCD function ones for ever. Check it carefully for boundary cases! (I wrote it quickly, I'm not really sure my version is correct). Once you have a well founded GCD function, always refer to it to compute common denominator and to normalize your fraction.</p></li>\n<li><p>don't use const where it is not needed</p></li>\n</ul>\n\n<p>here is a possible cleanup of your code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nnamespace math\n{ \n class Fraction //Fractions cannot be of type 1.2/5.6\n {\n private:\n typedef long value_type;\n value_type numerator;\n value_type denominator;\n\n public:\n Fraction(value_type numerator_, value_type denominator_=1)\n : numerator(numerator_), denominator(denominator_) \n {\n normalize();\n }\n\n Fraction operator+ (const Fraction &amp;other) const \n {\n value_type c = gcd(denominator,other.denominator);\n value_type m_this = denominator / c;\n value_type m_other = other.denominator / c;\n return Fraction(numerator * m_other + other.numerator * m_this,\n denominator * m_other);\n }\n\n static value_type gcd(value_type a, value_type b);\n\n friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;out, const Fraction &amp;fraction) \n {\n return out &lt;&lt; \"(\" &lt;&lt; fraction.numerator &lt;&lt; \"/\" &lt;&lt; fraction.denominator &lt;&lt; \")\";\n }\n\n private:\n void normalize();\n };\n\n Fraction::value_type Fraction::gcd(value_type a, value_type b) \n {\n if (a&lt;0) a=-a;\n if (b&lt;0) b=-b;\n for (;;) \n {\n if (a&gt;b) \n {\n if (b==0) \n return a;\n a -= a/b*b;\n } \n else \n {\n if (a==0) \n return b;\n b -= b/a*a;\n }\n }\n }\n\n void Fraction::normalize() {\n if (denominator&lt;0) \n {\n denominator = -denominator;\n numerator = -numerator;\n }\n value_type c = gcd(numerator,denominator);\n numerator /= c;\n denominator /= c;\n }\n\n} //namespace math\n\nint main(int argc, char* argv[]) \n{\n math::Fraction a(1,-6);\n math::Fraction b(1,3); \n\n std::cout &lt;&lt; a &lt;&lt; \" + \" &lt;&lt; b &lt;&lt; \" = \" &lt;&lt; a+b &lt;&lt; std::endl;\n std::cout &lt;&lt; a &lt;&lt; \" + \" &lt;&lt; 1 &lt;&lt; \" = \" &lt;&lt; a+1 &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-05T12:58:03.440", "Id": "59116", "ParentId": "33358", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T02:19:18.637", "Id": "33358", "Score": "3", "Tags": [ "c++", "rational-numbers" ], "Title": "Fraction program with Fraction class" }
33358
<p>I've made an unbeatable Tic-Tac-Toe in Python 3.3. While it truly was unbeatable, it was an eyesore to look at and nigh impossible to read. That code is <a href="https://github.com/gferiancek/ITicTacToe/blob/master/tic-tac-toe.py">here</a>.</p> <p>I have since then optimized it for Python 2.7.5 as follows:</p> <pre><code>from random import randrange, random from time import sleep #First, setup the board!! def draw_board(): print '', board[1], '|', board[2], '|', board[3], \ '\n-----------\n', \ '', board[4], '|', board[5], '|', board[6], \ '\n-----------\n', \ '', board[7], '|', board[8], '|', board[9], \ '\n' #Next, Choose what team you're on! def player_team(): team = raw_input('Do you want to be X or O? \n').upper() print if team == 'X': return ['X', 'O'] elif team == 'O': return ['O', 'X'] else: print ('That is not a valid choice. Please try again \n') return player_team() #Next, Find out what player goes first! def first_turn(): turn = random() if turn &lt;= .494: print 'You will go first \n' return ('user', True) else: print 'The Computer will go first \n' return ('computer', False) #Next, be able to determine which spaces are available! def available(space): if board[space] == ' ': return True #Next, allow a player to pick their move! def user_turn(): try: move = int(raw_input('Where would you like to move? (Enter a number from 1-9) \n')) if 0 &lt; move &lt; 10: if not available(move): print ('That space is already taken by a player. ' 'Please select an open space \n') return user_turn() else: board[move] = user_team print except: print 'That is not a valid move. Please try again. \n' return user_turn() #Now define the A.I! def computer_turn(): move = randrange(1, 10) if available(move): board[move] = computer_team return move else: return computer_turn() #Next, we must check if the game has ended or not, and see who won! def end_game(): for row in range(1, 10, 3): if not available(row): if board[row] == board[row + 1] and board[row] == board[row + 2]: return True for column in range(1, 4): if not available(column): if board[column]== board[column + 3] and board[column] == board[column + 6]: return True for diagonal in range(1, 10, 2): if not available(diagonal): if (diagonal == 1 and board[diagonal] == board[diagonal + 4] and board[diagonal] == board[diagonal + 8]): return True elif (diagonal == 3 and board[diagonal] == board[diagonal + 2] and board[diagonal] == board[diagonal + 4]): return True if board.count('X') + board.count('O') == 9: return 'Tie' def check_winner(): global user_win, computer_win, ties if end_game() == 'Tie': ties += 1 draw_board() print ("The game is a tie. You're going to have to try harder" "\nif you wish to beat the computer! \n") elif end_game(): if turn == 'user': user_win += 1 draw_board() print ('You won! \n') else: computer_win += 1 draw_board() print ('The computer has won! But... We already knew' 'that would happen. (: \n') #Finally, give the option of a New Game+! def play_again(): print 'Your wins:', user_win, '\n' \ 'Computer wins:', computer_win, '\n' \ 'Ties:', ties, '\n' restart = raw_input('Do you wish to play another game? Yes or no? \n').upper() print if restart == 'YES': return True elif restart == 'NO': return False else: print ('That is not a valid choice. Please try again. \n') return play_again() #Main Program: print ('Welcome to my Impossible Tic-Tac-Toe game! You are of the bravest' 'of souls \nto take on my challenge, but only failure awaits you. \n') count = 1 user_win, computer_win, ties = 0, 0, 0 new_game = True while new_game: board = [' '] * 10 user_team, computer_team = player_team() turn, strategy = first_turn() print 'Game', count, '\n' while not end_game(): if turn == 'user': draw_board() user_turn() check_winner() turn = 'computer' else: draw_board() print 'The computer is thinking... \n' sleep(1) space_taken = computer_turn() print 'The computer moved on space', space_taken, '\n' check_winner() turn = 'user' if not play_again(): new_game = False count += 1 </code></pre> <p>(The AI in the new code is just a placeholder until I fix up the old one.)</p> <p>I definitely feel like it's improved a lot, but I am still unfamiliar about a few things.</p> <p>My program is mainly functional-based, but would switching to OOP have any benefits in this scenario?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T05:26:56.997", "Id": "53438", "Score": "0", "body": "@Barry, remember that the interval on random() is [0, 1), meaning that in theory, 1 is never actually reached. I simply had .99/2 which is .495. I moved it down to .494 since that side will include 0, which makes it like a .001 difference? :P" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:38:45.757", "Id": "53481", "Score": "1", "body": "One small comment. Instead of using `and` in some of your `if` statements, you can say `if a == b == c`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:44:54.430", "Id": "53484", "Score": "0", "body": "Why `for diagonal in range(1, 10, 2):`? There are only two diagonals, right? Maybe just deal with them individually, since they use different code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:46:51.563", "Id": "53485", "Score": "0", "body": "In check_winner(), just call draw_board() once after the elif block, rather than inside every if block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T15:28:40.810", "Id": "53495", "Score": "0", "body": "@Barry, even if it was a a number from 0 to 1, wouldn't .49 still be correct? (Either way actually..) Remember, that from 0 to 1, there are 101 numbers( 0, 0.01, 0.02, etc). So 0 up to .49 is 50 numbers, and 50 up to 1 is 51 numbers. It'll never be exactly even." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T15:32:27.733", "Id": "53498", "Score": "0", "body": "@jcfollower thank you for those few tips, they'll help out. :3 As far as the Diagonal thing, I know that there are only 2, but if they were done in if statements, it would read ' if board[1] == board[4] == board[7]' instead of 'if board[diagnal].. etc.' I just felt that it made it more readable, even if it is just a little less efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T23:18:15.847", "Id": "86252", "Score": "0", "body": "I beat it my second try. Change the AI on your program because it allowed me to make the winning move." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T21:02:40.863", "Id": "86448", "Score": "1", "body": "Not sure if anyone mentioned this, but this is _procedurally_ written code, see [this](http://en.wikipedia.org/wiki/Procedural_programming) . _Functional_ programming is a bit different, see [here](http://en.wikipedia.org/wiki/Functional_programming)" } ]
[ { "body": "<ol>\n<li><p>Some of the comments are wrong, for example:</p>\n\n<pre><code>#First, setup the board!!\n</code></pre>\n\n<p>appears just before the <code>draw_board</code> function, which does not set up the board.</p>\n\n<p>The best practice here is to write a <a href=\"http://docs.python.org/3/tutorial/controlflow.html#documentation-strings\">docstring</a> for each function explaining what it does, how to call it, and what kind of values it returns.</p></li>\n<li><p>You use global variables <code>board</code>, <code>user_win</code>, <code>computer_win</code>, <code>ties</code>, <code>user_team</code>, <code>computer_team</code>, <code>turn</code>. Global variables make code hard to read, because you have to remember which variables are globals, and this might not be at all obvious. For example, the function <code>first_turn</code> starts with the line:</p>\n\n<pre><code>turn = random()\n</code></pre>\n\n<p>but this is not the global <code>turn</code>, it's a local variable with the same name!</p>\n\n<p>Global variables also make it hard to test from the interactive interpreter, because you have to fiddle about getting the globals into the right state for whatever it is you want to test. </p>\n\n<p>It is generally better if you pass your state as parameters to functions (for example, the <code>draw_board</code> function could take <code>board</code> as a parameter), or maintain it as properties of objects (for example, <code>user_win</code> could be a property of an object).</p></li>\n<li><p>Your <code>draw_board</code> function could benefit from using Python's <a href=\"http://docs.python.org/3/library/string.html#string-formatting\">string formatting interface</a>. I would also rename it <code>print_board</code> (because I prefer to reserve the word <code>draw</code> for rendering graphics).</p>\n\n<pre><code>def print_board(board):\n \"\"\"Print 'board' to standard output.\"\"\"\n print(\" {1} | {2} | {3}\\n\"\n \"---+---+---\\n\"\n \" {4} | {5} | {6}\\n\"\n \"---+---+---\\n\"\n \" {7} | {8} | {9}\\n\".format(*board))\n</code></pre>\n\n<p>Now it's straightforward to test it from the interactive interpreter:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; print_board('.XOXXOOOXX')\n X | O | X\n---+---+---\n X | O | O\n---+---+---\n O | X | X\n</code></pre></li>\n<li><p>Your function <code>player_team</code> uses <a href=\"http://en.wikipedia.org/wiki/Tail_call\">tail recursion</a> to implement a potentially infinite loop. But Python does not support tail call elimination, so a player who insists on repeatedly entering a wrong choice will eventually overflow the Python stack and cause it to fail:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; sys.setrecursionlimit(3)\n&gt;&gt;&gt; player_team()\nDo you want to be X or O? \nNo!\n\nThat is not a valid choice. Please try again \n\nDo you want to be X or O? \nNo, thank you.\n\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"cr33359.py\", line 23, in player_team\n return player_team()\n File \"cr33359.py\", line 17, in player_team\n if team == 'X':\nRuntimeError: maximum recursion depth exceeded in cmp\n</code></pre>\n\n<p>(In real life, <a href=\"http://docs.python.org/3/library/sys.html#sys.setrecursionlimit\"><code>sys.setrecursionlimit</code></a> is larger than 3, so it would take somewhat longer to reach the maximum recursion depth, but a determined player could get there in the end.)</p>\n\n<p>Instead, you should use iteration, for example like this:</p>\n\n<pre><code>def player_teams():\n \"\"\"Prompt user for their preferred symbol (X or O), repeatedly if\n necessary, and return a string consisting of the player's symbol\n and the computer's symbol.\n\n \"\"\"\n while True:\n team = raw_input('Do you want to be X or O? ').upper()\n if team == 'X': return 'XO'\n elif team == 'O': return 'OX'\n else: print(\"Please enter X or O.\")\n</code></pre>\n\n<p>There are similar problems in <code>user_turn</code>, <code>computer_turn</code>, and <code>play_again</code>.</p></li>\n<li><p>The <code>first_turn</code> function returns a pair whose second value (called <code>strategy</code> in the main loop) is unused. So why bother returning it?</p></li>\n<li><p>In the <code>available</code> function:</p>\n\n<pre><code>def available(space):\n if board[space] == ' ':\n return True\n</code></pre>\n\n<p>what happens if <code>board[space]</code> is not a space? There's no <code>else:</code> clause, so the function just ends without explicitly returning anything. Luckily for you, \"<a href=\"http://docs.python.org/3/tutorial/controlflow.html#defining-functions\">Falling off the end of a function returns <code>None</code></a>\"</p>\n\n<pre><code>&gt;&gt;&gt; def noreturn(): pass\n... \n&gt;&gt;&gt; print(noreturn())\nNone\n</code></pre>\n\n<p>and <code>None</code> becomes <code>False</code> when converted to a Boolean:</p>\n\n<pre><code>&gt;&gt;&gt; bool(None)\nFalse\n</code></pre>\n\n<p>so <code>available</code> works. But this seems needlessly tricky. It's simpler and clearer to write:</p>\n\n<pre><code>def available(board, position):\n \"\"\"Return True if 'position' is available to play on 'board'.\"\"\"\n return board[position] == ' '\n</code></pre></li>\n<li><p>Your function <code>end_game</code> returns the Boolean <code>True</code> if the game is over and there's a winner, the string <code>'Tie'</code> if the game is over and there's no winner, and it falls off the end (thus returning <code>None</code>) if the game is not over. This is a confusing interface. If you had tried to write a docstring for the function, as recommended in point 1 above, that explained what it was supposed to return then the confusion would have become apparent.</p>\n\n<p>It would be better to redesign the interface so that it's easier to understand, for example like this:</p>\n\n<pre><code>def game_status(board):\n \"\"\"Return the status of 'board' as one of the following strings:\n 'X' or 'O' if that player has three in a row;\n 'tie' if the board is full but neither player has won; or\n 'unfinished' otherwise.\n \"\"\"\n</code></pre></li>\n<li><p>The function <code>end_game</code> seems rather complex. In tic-tac-toe there are just eight winning lines, so why not just list them? I would write:</p>\n\n<pre><code># The legal board positions.\nBOARD_POSITIONS = list(range(1, 10))\n\n# Triples of board positions giving the eight winning lines.\nWINNING_LINES = [(1, 2, 3), (4, 5, 6), (7, 8, 9)\n (1, 4, 7), (2, 5, 8), (3, 6, 9),\n (1, 5, 9), (3, 5, 7)]\n\ndef game_status(board):\n \"\"\"Return the status of 'board' as one of the following strings:\n 'X' or 'O' if that player has three in a row;\n 'tie' if the board is full but neither player has won; or\n 'unfinished' otherwise.\n \"\"\"\n for i, j, k in WINNING_LINES:\n if not available(board, i) and board[i] == board[j] == board[k]:\n return board[i]\n if any(available(board, i) for i in BOARD_POSITIONS):\n return 'unfinished'\n return 'tie'\n</code></pre>\n\n<p>Note the use of Python's <a href=\"http://docs.python.org/3/reference/expressions.html#not-in\"><em>chained comparisons</em></a> here. In some other languages you would have to write:</p>\n\n<pre><code>board[i] == board[j] and board[j] == board[k]\n</code></pre></li>\n<li><p>In <code>check_winner</code> you call <code>end_game</code> twice, and you call it again in the main loop. But nothing changes between the first call and the subsequent calls, so why not remember the value and avoid the unnecessary computation?</p></li>\n</ol>\n\n<p>That's probably enough comments to be going on with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:19:42.040", "Id": "53642", "Score": "0", "body": "Thanks for all of the input! I'll look into the string formatting interface, and it's nice to know about that Tail Recursion limit (I thought about changing it to a while loop, but it worked, so I left it. Nice to know that it isn't good to do). The chained comparisons will also help out a lot!\nAs far as 'strategy' goes, was used in the old code to tell the computer if it starts first, but thinking back it does seem unnecessary. Using parameters does seem to be cleaner. Do you think it'd be better off as is or more Object oriented with the objects 'board' and 'player'? Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T10:51:20.577", "Id": "53675", "Score": "0", "body": "Why not try both and see which is better?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T13:34:00.360", "Id": "53694", "Score": "0", "body": "Hmm, good point. :P I'm still a little hazy with OOP, but I'm working on learning! I do feel that it would help clean up those globals though, since most of them would then become an argument in some part of the class." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:59:15.277", "Id": "33441", "ParentId": "33359", "Score": "16" } }, { "body": "<p>Since you are interested in an OOP approach, I take the opportunity to show you a toy program I did during a programming course. The comments in the code are in italian (sorry) but I hope it is clear anyway.</p>\n\n<p>The code comprises:</p>\n\n<ul>\n<li>a Board class which represents the state of the game (with all the rules and check for valid moves and winner);</li>\n<li>a Player class which is a dummy base class to implement players:</li>\n<li>the Human player ask the moves to the user,</li>\n<li>the Random player makes a random valid move,</li>\n<li>the Smart player finds the better move through an exaustive search in the tree of moves (this actually requires memoization otherwise it would take a long time also for a game as simple as this);</li>\n<li>a Game object takes two Players and let them play one against the other.</li>\n<li>the <code>__main__</code> function let the Human player play against the Smart player.</li>\n</ul>\n\n<p>Just a funny note: I asked my students to write their own implementation of Player... but I was disappointed to see that most of them were beaten by my Random player!</p>\n\n<hr>\n\n<pre><code>import random\n\n'''\nGioco del tris (filetto). Mette a disposizione le seguenti classi:\n\nBoard: schema di gioco\n\nPlayer: giocatore stupido (esegue prima mossa possibile)\nHuman: giocatore umano (chiede la mossa da eseguire)\nRandom: giocatore casuale (esegue una mossa a caso)\n\nGame: partita tra due giocatori\n'''\n\nclass Board(object):\n '''\n rappresentazione del gioco Tris\n scacchiera 3x3: ogni cella contiene X, O oppure .\n inoltre mantiene informazione sul turno di gioco\n Le caselle sono identificate da una cifra da 1-9 come nello schema:\n\n 123\n 456\n 789\n\n ''' \n def __init__(self,board=None):\n 'nuovo schema di gioco vuoto oppure copia di @board'\n if board is None:\n self.s = '.........' # '.'*9\n self.turn = 'O'\n else:\n self.s = board.s\n self.turn = board.turn\n self._state = 'not ended'\n\n def rows(self):\n 'restituisce le tre righe di tre caratteri'\n return [self.s[n*3:(n+1)*3] for n in range(3)]\n\n def cols(self):\n 'restituisce le tre colonne di tre caratteri'\n return [self.s[n] + self.s[n+3] + self.s[n+6] for n in range(3)]\n\n def diags(self):\n 'restituisce le due diagonali di tre caratteri'\n return [self.s[0]+self.s[4]+self.s[8], self.s[2]+self.s[4]+self.s[6]]\n\n def __str__(self):\n 'rappresentazione dello schema in una stringa multi-linea'\n r = '\\n'.join(self.rows())+'\\n'+'turn: '+self.turn+'\\n'\n s = self.state()\n if s != 'not ended':\n if s == 'draw':\n r += 'DRAW!\\n'\n else:\n r += s + ' WINS!'\n return r\n\n def is_valid(self,move):\n '''la mossa @move e' valida?'''\n return move in range(1,10) and self.s[move-1] == '.'\n\n def valid_moves(self):\n 'lista di tutte le mosse valide'\n return [x for x in range(1,10) if self.is_valid(x)]\n\n def state(self):\n '''stato corrente: 'O', 'X', 'draw', 'not ended' '''\n return self._state\n\n def compute_state(self):\n for r in self.rows() + self.cols() + self.diags():\n if r == 'OOO':\n self._state = 'O'\n return\n if r == 'XXX':\n self._state = 'X'\n return\n if self.s.find('.') == -1:\n self._state = 'draw'\n return\n return 'not ended'\n\n def play(self, move):\n 'effettua una mossa nella posizione @move: 1,2,3, 4,5,6, 7,8,9'\n if self.is_valid(move):\n self.s = self.s[0:move-1] + self.turn + self.s[move:9] \n if self.turn == 'O':\n self.turn = 'X'\n else:\n self.turn = 'O'\n self.compute_state()\n else:\n # print 'mossa non valida!'\n if move in range(1,10):\n self.s = self.s[0:move-1] + (self.turn.lower()) + self.s[move:9]\n else:\n self.s = self.turn.lower()*9\n if self.turn == 'O':\n self._state = 'X'\n else:\n self._state = 'O'\n\nclass Player(object):\n ''' Giocatore. Puo' essere inizializzato con un nome. \n Gioca la prima mossa valida\n '''\n\n def __init__(self,name='no-name'):\n self.name = name\n\n def move(self,board):\n return board.valid_moves()[0]\n\n def __str__(self):\n return '{0}: {1}'.format(type(self).__name__, self.name)\n\nclass Human(Player):\n def move(self,board):\n while True:\n move = raw_input('%s: che mossa vuoi fare? ' % self.name)\n try: \n move = int(move)\n if board.is_valid(move):\n return move\n else:\n print 'mossa non valida: %s' % move\n print board\n except ValueError:\n print 'la mossa deve essere un numero tra 1 e 9'\n\nclass Random(Player):\n def move(self,board):\n return random.choice(board.valid_moves())\n\nclass Smart(Player):\n def think(self,board):\n ''' restituisce una coppia (esito,move) con la mossa migliore e relativo esito '''\n\n # controlla se abbiamo gia' esaminato questa posizione\n if not hasattr(self,'cache'):\n self.cache = {}\n hash = board.turn + board.s\n if hash in self.cache:\n return self.cache[hash]\n\n me = board.turn\n draw_move = None\n for m in board.valid_moves():\n b = Board(board)\n b.play(m)\n s = b.state()\n if s == me:\n self.cache[hash] = (me,m)\n return (me,m) # mossa vincente!\n if s == 'draw': # unica mossa possibile!\n self.cache[hash] = ('draw',m)\n return ('draw',m)\n assert s == 'not ended'\n (s,mm) = self.think(b)\n if s == me:\n self.cache[hash] = (me,m)\n return (me,m) # mossa vincente!\n if s == 'draw':\n draw_move = m # mossa pattante... c'e' di meglio?\n # nessuna mossa vincente trovata. puntiamo alla patta\n if draw_move:\n self.cache[hash] = ('draw',draw_move)\n return ('draw',draw_move)\n # vince avversario :( scegliamo una mossa a caso\n self.cache[hash] = (b.turn,random.choice(board.valid_moves()))\n return self.cache[hash]\n\n def move(self,board):\n return self.think(board)[1]\n\nclass Game(object):\n def __init__(self,player_O,player_X,verbose=2):\n self.players = {'O': player_O,\n 'X': player_X}\n self.board = Board()\n self.verbose = verbose\n if self.verbose &gt; 0:\n print 'O={0}, X={1}'.format(player_O.name, player_X.name)\n\n def play(self):\n while self.board.state() == 'not ended':\n # visualizza schema di gioco:\n if self.verbose&gt;1:\n print self.board\n\n # chiede al giocatore di turno la mossa da fare:\n current_player = self.players[self.board.turn]\n move = current_player.move(Board(self.board))\n if self.verbose&gt;1:\n print \"{0} sceglie la mossa: {1}\".format(current_player, move)\n\n # esegue mossa sullo schema:\n self.board.play(move)\n\n # visualizza posizione finale \n state = self.board.state()\n if self.verbose &gt; 1:\n print self.board\n if state in self.players:\n print 'Ha vinto: {0}'.format(self.players[state])\n return self.board\n\nif __name__ == '__main__':\n # esecuzione diretta del codice\n name = raw_input('Come ti chiami? ')\n game = Game(Human(name),Smart('computer'))\n game.play()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-14T21:07:13.613", "Id": "62908", "ParentId": "33359", "Score": "3" } } ]
{ "AcceptedAnswerId": "33441", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T02:24:00.710", "Id": "33359", "Score": "14", "Tags": [ "python", "game", "python-3.x", "tic-tac-toe" ], "Title": "Unbeatable Tic-Tac-Toe program seems difficult to read" }
33359
<p>My in-laws taught me a dice game a couple years ago, and we play every once in a while. <a href="https://codereview.stackexchange.com/a/33151/23788">A recent excellent answer from @radarbob</a> inspired me to proceed with translating the rules of that dice game into code.</p> <p>Here's what came out of it:</p> <p><img src="https://i.stack.imgur.com/cISCX.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/vf78B.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/gUtmw.png" alt="enter image description here"></p> <p>So it works perfectly, and somehow I'm just as unlucky with this virtual version as in the real-life one (had to click dozens of time to get a freakin' <em>opening roll</em>; by that time my mother-in-law already has thousands of points, every time). At least in this version I can inject some <code>CrookedDie</code> implementation if I want!</p> <p>I'd like the <code>CalculateRollScore</code> method reviewed, to see what could be improved.</p> <p>It turns out I <em>thought</em> the code was working as it should. So I wrote a couple unit tests and... well this is where <em>not writing unit tests</em> has bitten me.</p> <p>Well I had to change the rules anyway, since the rule for 4x 1's was just my wife being mixed-up. My mother-in-law and I agree that 3x 1's is 1000, 4x 1's is 2000 and 5x 1's is 3000.</p> <p>So before I show any code, I'll show this:</p> <p><img src="https://i.stack.imgur.com/ZjkBA.png" alt="passing tests"></p> <p>Now here's the <em>working</em> code (<a href="https://codereview.stackexchange.com/revisions/33363/2">view original code here</a>), with only minor changes that don't mootinize any already posted answer:</p> <pre><code>namespace DiceGame { public interface IRollScoreRules { int CalculateRollScore(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results); } public class GameRollScoreRules : IRollScoreRules { public virtual bool IsOpeningRoll(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results) { return CalculateRollScore(results) &gt;= 500; } public virtual int CalculateRollScore(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results) { var score = 0; // if less than 3 1's were rolled, each rolled 1 is 100pts: score += results.GroupBy(e =&gt; e.Value) .Where(g =&gt; g.Key == 1) .Where(g =&gt; g.Count() &lt; 3) .Sum(g =&gt; g.Count() * 100); // if less than 3 5's were rolled, each rolled 5 is 50pts: score += results.GroupBy(e =&gt; e.Value) .Where(g =&gt; g.Key == 5) .Where(g =&gt; g.Count() &lt; 3) .Sum(g =&gt; g.Count() * 50); // if more than 3 of anything other than 1 were rolled, determine number of "extra dice": var extras = results.GroupBy(e =&gt; e.Value) .Where(g =&gt; g.Key != 1 &amp;&amp; g.Count() &gt; 3) .ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; kvp.Count() - 3); var extraOnes = results.GroupBy(e =&gt; e.Value) .Where(g =&gt; g.Key == 1 &amp;&amp; g.Count() &gt; 3) .ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; kvp.Count() - 3); // any triplet is 100x nominal value; each extra die is another 100x nominal value: score += results.GroupBy(e =&gt; e.Value) .Where(g =&gt; (g.Key != 1 &amp;&amp; g.Count() &gt;= 3)) .Sum(g =&gt; (g.Key * 100) + (extras.ContainsKey(g.Key) ? extras[g.Key] : 0) * (g.Key * 100)); //score += results.GroupBy(e =&gt; e.Value) // .Where(g =&gt; (g.Key == 1 &amp;&amp; g.Count() &gt;= 3)) // .Sum(g =&gt; (g.Key * 100) + (extraOnes.ContainsKey(g.Key) ? extraOnes[g.Key] : 0) * (g.Key * 100)); // 3x 1's is 1000x nominal value; each extra die is another 1000x nominal value: score += results.GroupBy(e =&gt; e.Value) .Where(g =&gt; g.Key == 1 &amp;&amp; g.Count() &gt;= 3) .Sum(g =&gt; (g.Key * 1000) + (extraOnes.ContainsKey(g.Key) ? extraOnes[g.Key] : 0) * (g.Key * 1000)); return score; } } } </code></pre>
[]
[ { "body": "<p>Well, I am not familiar with die, but the obvious improvement is to encapsulate those rules into separate entities. For example:</p>\n\n<pre><code>public interface IRollScoreRule\n{\n int CalculateRollScore(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results);\n}\n\npublic interface IRollScoreRules : IRollScoreRule\n{\n bool IsOpeningRoll(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results);\n void AddRule(IRollScoreRule rule);\n void RemoveRule(IRollScoreRule rule);\n}\n\npublic class ScoreFivesRule : IRollScoreRule\n{\n int CalculateRollScore(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results)\n {\n // i think some of this logic can be extracted to base class\n // results.GroupBy(e =&gt; e.Value).Where(g =&gt; g.Key == 5) part for example\n // is common for most of the rules\n var score = results.GroupBy(e =&gt; e.Value)\n .Where(g =&gt; g.Key == 5)\n .Where(g =&gt; g.Count() &lt; 3)\n .Sum(g =&gt; g.Count() * 50);\n return score;\n }\n}\n</code></pre>\n\n<p>Then in your <code>GameRollScoreRules.CalculateRollScore</code> method you can iterate through collection of rules (using <code>IEnumerable.Aggregate</code>, for example) to get the total score, instead of having one huge method.</p>\n\n<p>I also think you might want to tweak the <code>IsOpeningRoll</code> method. I mean, if I understand the use-case from your screenshots correctly, then with every dice roll, you want to know both - score value and if this value is higher then <code>500</code>. Which means that using your <code>GameRollScoreRules</code> class as it is you would essentially calculate score twice (by calling <code>CalculateRollScore</code> and <code>IsOpeningRoll</code> methods). I think you sould either pass the resulting score to <code>IsOpeningRoll</code> method as a parameter, or remove this method all together and replace <code>CalculateRollScore</code> return type with some complex object (which will contain score value and bool flag) instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T06:52:09.760", "Id": "33370", "ParentId": "33363", "Score": "5" } }, { "body": "<p>Frankly speaking, if someone in my team wrote those LINQ statements, I would kill him. Using LINQ on this, you just complicated the simple task. I tried to reconstruct it using simple C#, but yet I am still not sure if it's correct.</p>\n\n<pre><code> public virtual int CalculateRollScore(IEnumerable&lt;IRollResult&lt;int&gt;&gt; results)\n {\n var score = 0;\n var diceMap = (new int[7]).ToList();\n foreach (var item in results)\n {\n diceMap[item.Value]++;\n }\n\n // if less than 4 1's were rolled, each rolled 1 is 100pts:\n if (diceMap[1] &lt; 4)\n {\n score += diceMap[1] * 100;\n }\n\n // if less than 3 5's were rolled, each rolled 5 is 50pts:\n if (diceMap[5] &lt; 3)\n {\n score += diceMap[5] * 50;\n }\n\n int nominalValue = diceMap.FindIndex(i =&gt; i &gt;= 3);\n int dieCount = nominalValue &gt; 0 ? diceMap[nominalValue] : 0;\n // any triplet is 100x nominal value; each extra die is another 100x nominal value:\n if (nominalValue &gt; 0)\n {\n int extra = dieCount &gt; 3 ? (dieCount - 3) * nominalValue * 100 : 0;\n score += nominalValue * 100 + extra;\n }\n\n // 4x 1's is 1000x nominal value; each extra die is another 1000x nominal value:\n if (nominalValue == 1 &amp;&amp; dieCount &gt;= 4)\n {\n int extra1 = dieCount &gt; 4 ? (dieCount - 4) * nominalValue * 1000 : 0;\n score += nominalValue * 1000 + extra1;\n }\n return score;\n }\n</code></pre>\n\n<p>As I tested my method, the score of the set <code>{ 4, 1, 1, 1, 1 }</code> is not matched with your method. Your method returns 1100, but it should be 1200 </p>\n\n<ul>\n<li>100 for triplet of 1's</li>\n<li>100 for extra 1</li>\n<li>1000 for 4x of 1</li>\n</ul>\n\n<p>Correct me if I'm wrong, as I'm not familiar with the rules at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T01:01:15.597", "Id": "53551", "Score": "1", "body": "now this is where *not writing unit tests* has bitten me - you're absolutely right, I have undeniable proof right before my eyes (with a nicely failing test) that 4x 1's scores 1100. I'll fix that and edit OP with corrected code (I'll leave the nasty Linq, to not mootinize your answer :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:53:56.873", "Id": "33415", "ParentId": "33363", "Score": "4" } }, { "body": "<h3>I think you're over-thinking the solution</h3>\n\n<p>My first thought is that I'd like to iterate a <code>Rule</code> collection, and give each rule the dice roll results. </p>\n\n<pre><code>foreach(Rule rule in RulesCollection) {\n score =+ rule.calculate(results);\n}\n</code></pre>\n\n<p>With this \"wishful thinking\" starting point this means all your rules derive, or implement, <code>Rule</code> (or whatever you want to call it). If in the final analysis every rule calculates a score for that specific dice combination then the above snippet should be achievable. If a given rule needs unique methods, fine; but for polymorphic purposes they all <code>calculate</code> so they can all implement (or inherit) <code>Rule</code>.</p>\n\n<h3>Dump the interfaces</h3>\n\n<p><code>interface</code>s implementing <code>interfaces</code> implemented by <code>abstract</code> classes. This is madness. If all this is coming from <em>code to interfaces, not implementation</em> \"interface\" can be an <code>abstract</code> class, <code>interface</code>, or even a non-abstract class. The \"interface\" means giving the client code a consistent set of methods &amp; properties so every object can be handled the same. If there is only one class implementing an <code>interface</code>, that interface is likely unnecessary. If in the future you need one, make it then.</p>\n\n<h3>Encapsulate for Consistency, Clarity, and Expressiveness</h3>\n\n<p>There is clearly a need for the grouped dice. My initial thought is that this best fits in the <code>Dice</code> class. AND that <em>data structure</em> could be a class as well.</p>\n\n<pre><code>public class Dice {\n public DiceMap Map { get; private set; }\n\n public Dice (int diceCount) {\n //existing code\n\n DiceMap = new DiceMap(sidesCount);\n }\n\n public int Roll() {\n //did not show all original code.\n\n int temp;\n\n foreach (Die die in dice) { //does this need to be a \"for\" ?\n temp = die.Roll();\n total =+ temp;\n DiceMap[temp-1]++;\n }\n }\n\n // calling before rolling returns zero, makes sense.\n public int HowMany(int count) { return groups.HowMany(count); }\n\n // yes, an inner class. Only Dice class needs it.\n // I'll admit this may be overkill but I want to illustrate the idea\n // of encapsulating - hiding structure (the array) while exposing\n // it's meaning - how many 1's? for example.\n\n // The other point is to \"go deep with OO design\", so to speak.\n\n public class DiceMap {\n int[] groups;\n\n public DiceMap (int count) { groups = new int[count]; }\n\n public int HowMany(int dieFace) {\n // check for dieFace out of array bounds\n\n return groups[dieFace-1];\n }\n }\n}\n</code></pre>\n\n<p>now deep in some <code>Rule</code> class this:</p>\n\n<pre><code>if (myDice.HowMany(3) &gt; 3) { // your code here }\n</code></pre>\n\n<p>or this, depending on what we decide to pass in</p>\n\n<pre><code>if (myDiceMap.HowMany(3) &gt; 3 ) \n</code></pre>\n\n<h3>RuleCollection</h3>\n\n<p>Make a class and put those \"Add\" and \"Remove\" functions in there!</p>\n\n<pre><code>public class RuleCollection {\n protected List&lt;Rule&gt; rules;\n\n public RuleCollection (params Rule[] rules) {\n this.rules = new List&lt;Rule&gt;;\n foreach (Rule rule in Rules) { rules.Add(rule); }\n\n public void Add (Rule rule) { rules.Add(rule); }\n public bool Remove (Rule rule) { return rules.Remove(rule) }\n // List&lt;T&gt;.Remove() returns a bool.\n\n // assumes dice have been rolled\n public int Calculate(DiceMap diceMap) {\n int score = 0;\n\n foreach (Rule rule in rules) {\n score =+ rule.Calculate(diceMap);\n }\n }\n}\n</code></pre>\n\n<h3>OpeningRoleRule</h3>\n\n<p>Seems to me every <code>Rule</code> implements a piece of the overall score counting for a single roll of the dice. So the opening roll is just all those rules applied - see above - then checked against some minimum value. So maybe it's not a <code>Rule</code> per-se.</p>\n\n<pre><code>public class TheGameClass {\n protected RulesCollection rules;\n protected Dice dice;\n\n dice.Roll();\n if ( rules.Calculate(dice.Map) &gt;= minimumOpeningScore ) { ... }\n}\n</code></pre>\n\n<h3>OO Change Goodness</h3>\n\n<p>If the number of dice sides does not change, I want to do this:</p>\n\n<pre><code>public class DiceMap {\n // new properties\n public int Ones { get { return groups[0]; }\n public int Twos { get { return groups[1]; }\n // and so on\n public int Sixes { get { return groups[5]; }\n}\n</code></pre>\n\n<p><strong>Notice all the dice game code we don't have to touch!</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T22:42:47.323", "Id": "53945", "Score": "0", "body": "+1 I *am* overthinking it! ...but there's more to the game, I was going to post a follow-up question later, maybe over the weekend. You're right the interfaces stem from my understanding of SOLID, I'll see what I'm actually using and what I can dump. Thanks a lot!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T19:20:20.897", "Id": "58793", "Score": "0", "body": "Make sure any rule precedence is accounted for in the `Rule` list ordering." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T21:49:58.470", "Id": "33682", "ParentId": "33363", "Score": "3" } } ]
{ "AcceptedAnswerId": "33370", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T03:36:05.213", "Id": "33363", "Score": "7", "Tags": [ "c#", "algorithm", "dice" ], "Title": "Dice game rules implementation" }
33363
<p>I wrote some math formulas in Haskell and was wondering about how to clean the code up and make it more readable.</p> <pre><code>import Math.Gamma pdf :: Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double pdf mu alpha beta x = ( beta / (2 * alpha * gamma ( 1/beta) ) ) ** exp ( -1* ( abs(x - mu )/alpha )) ** beta cdf :: Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double cdf mu alpha beta x = 0.5 + signum(x - mu) * ( lowerGamma (1/beta) ((abs(x-mu) / alpha)**beta) / (2 * gamma(1/beta))) main = do let x = pdf 0 1 2 0.5 print x let y = cdf 0 1 2 0.5 print y </code></pre>
[]
[ { "body": "<p>Your code looks fine to me. If you wish, you could use Greek letters. This makes the formula easier to read, but if you expect to modify it often, it may be too much trouble to enter the Greek letters. You might find it helpful to split up long formulas, as I've done for <code>pdf</code>. If you can think of more meaningful names than <code>foo</code> and <code>bar</code>, this might be a good idea. However, if this is a well-known formula in your field, splitting it up might actually make it <em>less</em> recognisable. It's a judgement call.</p>\n\n<p>If you wrote this in <a href=\"http://www.haskell.org/haskellwiki/Literate_programming\" rel=\"nofollow\">literate Haskell</a>, you could include a nicely-formatted version of the formula using LaTeX. That might be useful if you're writing code with a lot of formulas.</p>\n\n<pre><code>import Math.Gamma\n\nγ :: Double -&gt; Double\nγ = gamma\n\npdf :: Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double\npdf μ α β x = foo ** bar ** β\n where foo = ( β / (2 * α * γ ( 1/β) ) )\n bar = exp ( -1* ( abs(x - μ )/α ))\n\ncdf :: Double -&gt; Double -&gt; Double -&gt; Double -&gt; Double\ncdf μ α β x = 0.5 + signum(x - μ) * ( lowerGamma (1/β) ((abs(x-μ) / α)**β) / (2 * γ(1/β))) \n\n\nmain = do\n let x = pdf 0 1 2 0.5\n print x\n let y = cdf 0 1 2 0.5\n print y\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:53:32.200", "Id": "58430", "Score": "0", "body": "good review. I don't think putting greek letters into the code is a idea personally, but you explained that as well. again good review" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T21:36:46.787", "Id": "58474", "Score": "0", "body": "The great letters are a great idea! as well as literate haskell. Now i just need to find out how to type them easily with my editor." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T18:12:48.847", "Id": "35865", "ParentId": "33364", "Score": "4" } } ]
{ "AcceptedAnswerId": "35865", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T03:40:27.207", "Id": "33364", "Score": "2", "Tags": [ "haskell", "mathematics" ], "Title": "Math formulas in Haskell" }
33364
<p>I know heaps are commonly implemented by an array. But, I wanted to share my pointer implementation and have your feedback(s) :)</p> <p>General idea:</p> <ol> <li><p>I convert the index to its binary value and then trace the heap (0 = leftChild &amp; 1 = rightChild)] Note: The first 1 is for entering the root.</p></li> <li><p>I do the push at the same time.</p></li> </ol> <p>Example: for the 12th element, 12 = 1100. The first 1 is for entering the root. Now I trace the heap by following 100.</p> <pre><code> struct Node{ Node *leftChild; Node *rightChild; int data; }; bool insertHeap(Node **heap, int data, short index){ Node *newNode, *temp, *parent; int tempData; short mask = 0x80; try{ newNode = new Node; } catch (bad_alloc&amp; e) { cerr &lt;&lt; "Memory allocation error: " &lt;&lt; e.what() &lt;&lt; endl; return false; } while (!(index &amp; mask)) index &lt;&lt;= 1; index &lt;&lt;= 1; parent = NULL; temp = *heap; while (temp){ if (data &gt; temp-&gt;data){ tempData = temp-&gt;data; temp-&gt;data = data; data = tempData; } parent = temp; if (!(index &amp; mask)) temp = temp-&gt;leftChild; else temp = temp-&gt;rightChild; if (temp) index &lt;&lt;= 1; } newNode-&gt;leftChild = NULL; newNode-&gt;rightChild = NULL; newNode-&gt;data = data; if(!parent){ *heap = newNode; return true; } if (!(index &amp; mask)) parent-&gt;leftChild = newNode; else parent-&gt;rightChild = newNode; return true; } </code></pre> <p>This is my <code>main()</code>:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main (){ Node *heap = NULL; int arr[13] = {3,6,8,1,5,9,4,2,0,7,11,14,13}; for (int i=0; i&lt;13; i++) insertHeap(&amp;heap, arr[i], i+1); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T04:10:56.287", "Id": "53434", "Score": "0", "body": "@Barry: it's the element counter. For example, 12 means the entered data will be the 12th element (at this time it has 11 elements). In its class version, you can have a protected 'int size' variable and **increment** it at the end of the _insertHeap_ function. In that way, the function will have only two arguments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:29:43.310", "Id": "53474", "Score": "0", "body": "@Barry: As I said above, the user doesn't need to track the size externally. I can't write it here due to characters limit. I write it as an answer" } ]
[ { "body": "<p>This class uses a member variable and hides the size completely. As you can see there is no need to know the index value. It can be hidden from the user. (Note: This class is not complete. It's necessary to have ~cHeap() to free up all the allocated memories) </p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nstruct Node{\n Node *leftChild;\n Node *rightChild;\n int data;\n};\n\nclass cHeap{\nprotected:\n short size;\n Node *heap;\n\npublic:\n cHeap();\n bool insertHeap(int data);\n};\n\ncHeap::cHeap(){\n heap = NULL; \n size=0; // here we initialise size\n}\n\n bool cHeap::insertHeap(int data){\n Node *newNode, *temp = heap, *parent = NULL;\n int tempData, index;\n short mask = 0x80;\n\n try{\n newNode = new Node;\n }\n catch (bad_alloc&amp; e) {\n cerr &lt;&lt; \"Memory allocation error: \" &lt;&lt; e.what() &lt;&lt; endl;\n return false;\n }\n\n size++; // here we increment size by one (for each insertion)\n index = size;\n while (!(index &amp; mask)) index &lt;&lt;= 1; \n index &lt;&lt;= 1;\n\n while (temp){\n if (data &gt; temp-&gt;data){\n tempData = temp-&gt;data;\n temp-&gt;data = data;\n data = tempData;\n } \n parent = temp;\n\n if (!(index &amp; mask)) temp = temp-&gt;leftChild; \n else temp = temp-&gt;rightChild;\n\n if (temp) index &lt;&lt;= 1;\n }\n\n newNode-&gt;leftChild = NULL;\n newNode-&gt;rightChild = NULL;\n newNode-&gt;data = data;\n\n if(!parent){\n heap = newNode;\n return true;\n }\n\n if (!(index &amp; mask)) parent-&gt;leftChild = newNode;\n else parent-&gt;rightChild = newNode;\n return true;\n }\n\n int main(){\n cHeap myHeap;\n\n int arr[13] = {3,6,8,1,5,9,4,2,0,7,11,14,13}; \n\n for (int i=0; i&lt;13; i++) myHeap.insertHeap(arr[i]); // as you can see you have nothing to do with size tracking\n return 0;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:34:13.007", "Id": "33394", "ParentId": "33365", "Score": "0" } }, { "body": "<p>You could also use a map, associative array, or dictionary to implement a heap (like the following):</p>\n\n<pre><code>class Heap(dict):\n\n \"Heap() -&gt; Heap instance\"\n\n def retrieve(self, address):\n \"Get the virtual value stored at the address.\"\n return self.get(address, 0)\n\n def store(self, value, address):\n \"Set the virtual value meant for the address.\"\n if value:\n self[address] = value\n else:\n self.pop(address, None)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T14:46:46.187", "Id": "33401", "ParentId": "33365", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T03:46:58.570", "Id": "33365", "Score": "5", "Tags": [ "c++", "heap", "pointers" ], "Title": "Heap implementation using pointer" }
33365
<pre><code>SELECT * FROM (SELECT a.*, ROWNUM rnum from (SELECT a.CUST_FULL_NAME,a.TAX_NET, (SELECT NEXT_INT_PAYMENT_AMOUNT_NET FROM (SELECT a.*, ROWNUM rnum from (SELECT NEXT_INT_PAYMENT_AMOUNT_NET,NEXT_INT_PAYMENT_DATE FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='01' OR CODE ='01')) AND CIF LIKE '1690XD' ORDER BY NEXT_INT_PAYMENT_DATE DESC) a ) WHERE rnum=1) AS GIRO, FROM SINAYA.T_XLS_DEPOSIT a JOIN SINAYA.R_BRANCH b ON a.BRANCH=b.BRANCH_CODE JOIN SINAYA.R_CAS_CODE c ON c.CODE=a.DEAL_TYPE WHERE CIF LIKE '1690XD' ORDER BY NEXT_INT_PAYMENT_DATE DESC) a) WHERE rnum=1 </code></pre> <p>Here it is, i've fixed the query above :</p> <pre><code>SELECT RATE_GIRO,GIRO,TAX_NET_GIRO,RATE_TABUNGAN,TABUNGAN,TAX_NET_TABUNGAN,RATE_DEPOSITO,DEPOSITO,TAX_NET_DEPOSITO FROM (SELECT a.*, ROWNUM rnum from (SELECT (TAX_RATE) AS RATE_GIRO,(NEXT_INT_PAYMENT_AMOUNT_NET) AS GIRO,(TAX_NET) AS TAX_NET_GIRO FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='01' OR CODE ='01')) AND CIF LIKE '1966P2' ORDER BY NEXT_INT_PAYMENT_DATE DESC)a) GIRO FULL JOIN (SELECT b.*, ROWNUM rnum from (SELECT (TAX_RATE) AS RATE_TABUNGAN,(NEXT_INT_PAYMENT_AMOUNT_NET) AS TABUNGAN,(TAX_NET) AS TAX_NET_TABUNGAN FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='02' OR CODE ='02')) AND CIF LIKE '1966P2' ORDER BY NEXT_INT_PAYMENT_DATE DESC)b) TAB ON GIRO.rnum=TAB.rnum FULL JOIN (SELECT c.*, ROWNUM rnum from (SELECT (TAX_RATE) AS RATE_DEPOSITO,(NEXT_INT_PAYMENT_AMOUNT_NET) AS DEPOSITO,(TAX_NET) AS TAX_NET_DEPOSITO FROM SINAYA.T_XLS_DEPOSIT WHERE DEAL_TYPE IN (SELECT CODE FROM SINAYA.R_CAS_CODE WHERE (CODE_PARENT='03' OR CODE ='03')) AND CIF LIKE '1966P2' ORDER BY NEXT_INT_PAYMENT_DATE DESC)c) DEPO ON DEPO.rnum = TAB.rnum WHERE GIRO.rnum=1 OR TAB.rnum=1 OR DEPO.rnum=1 </code></pre> <p>the new one three times better but still takes time around 45sec for the query to finish (before takes 3 minutes because the size of data is very large)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T22:29:50.120", "Id": "53543", "Score": "0", "body": "Try asking on http://dba.stackexchange.com/." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T13:38:30.790", "Id": "53588", "Score": "0", "body": "being simple is more than just how many Select Statements are Nested, does this Query Run efficiently? if so, will it continue to run efficiently when the Database doubles or triples in size?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T03:49:27.617", "Id": "53766", "Score": "0", "body": "you're right malachi it takes long time to run the first query, i got new one, check it out. maybe you could end up with another more efficient query, thx for rep" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T05:14:39.757", "Id": "33367", "Score": "1", "Tags": [ "sql", "oracle" ], "Title": "is there a way to simplify this query?" }
33367
<p>I was just wondering if this is a good example, following good practices, of a C program for launching an interpreted script from a native binary executable. Here the interpreter is Perl and the script an implementation of something analogous to du --apparent-size, but the idea is general.</p> <p>Also, is this code secure against potentially hostile users, at least if Perl is the interpreter (for instance, in a suid or sgid program)?</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;errno.h&gt; int main(int argc, char** argv) { char* command[argc+3]; command[0] = "/usr/bin/perl"; command[1] = "-W"; command[2] = "-T"; command[3] = "/home/demetri/bin/awklikeperl.pl"; for (int i = 0; i &lt; argc; i++) { command[i+4] = argv[i+1]; } execv(command[0], command); int error = errno; fprintf(stderr, "Failed to exec: %s\n", strerror(error)); if (error == ENOENT) { return(127); } else { return(126); } } </code></pre>
[]
[ { "body": "<p>No it is not safe:</p>\n\n<ol>\n<li>Classic off-by-one error. You reserve space for 3 additional entries with <code>command[argc+3]</code> but you add 4. <code>argv[i+1]</code> and <code>command[i+4]</code> will be out of bounds on the last iteration (last valid index is <code>argv[argc-1]</code> and <code>command[argc+2]</code> respectively)</li>\n<li><a href=\"http://linux.die.net/man/3/execv\"><code>execv</code></a> expects a NULL terminated array of NULL terminated strings. So the last entry in <code>commands</code> needs to be NULL (otherwise how would <code>execv</code> know how many arguments to pass when starting the process?).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T14:25:07.947", "Id": "53488", "Score": "0", "body": "You are correct about the off by one error. However, argv[argc] is guaranteed to be 0 by the C standard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T21:38:01.930", "Id": "53632", "Score": "0", "body": "Ah true, it's a NULL terminated list, I forgot" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T08:32:56.240", "Id": "33376", "ParentId": "33369", "Score": "13" } }, { "body": "<p>Consider starting the child process in <a href=\"https://stackoverflow.com/questions/4249063/how-can-i-run-an-untrusted-c-program-in-a-sandbox-in-linux\">a sandbox</a>. <code>/usr/bin/perl</code> is likely safe from a malicious user since <code>/usr/bin</code> is typically locked down by the root user(s). But <code>/home/demetri/bin/awklikeperl.pl</code> could be replaced if the owner is not careful with permissions. Putting the process in a sandbox will not only protect the rest of your system from attack, but help you think about what files will be made available.</p>\n\n<p>Obviously, the content of the script should be reviewed for vulnerabilities as well. Take a look at <a href=\"http://perldoc.perl.org/perlsec.html\" rel=\"nofollow noreferrer\"><code>perlsec</code></a> for help on that front.</p>\n\n<p><code>3</code> is a bit of a magic number in the C program. As you've already discovered, it's easy to forget to change that number if you add or subtract parameters from the <code>command</code> array. If you define that in one place (say <code>#DEFINE STARTING_ARGS 3</code>) you'll only need to change the value in one place.</p>\n\n<p>Speaking of which, I considered suggesting adding a <code>--</code> parameter to prevent any shenanigans with adding extra switches. But once you pass the script name to perl, it passes all other arguments onto the script. So I think it's not possible to use <code>-e</code> to execute an arbitrary command.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-14T18:46:00.673", "Id": "211092", "Score": "4", "body": "Where would you put the `--` if you suggested it? The only place it would make sense is immediately *before* the script-to-run (i.e. before `command[3]`) - And, since the path/script name itself is \"clean\", it won't be interpreted as a perl argument. Having said that, I would actually recommend that you actually do suggest that ;-) - that way a later change to the script that's run - even a dynamic script, possibly, will still work - including if someone were to make their input file `-` or the traditional \"use standard in\" `cat myperl.pl | perl -W -T -- -`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-19T16:40:17.960", "Id": "212153", "Score": "1", "body": "If we're relying on [`chroot` to sandbox `perl`](https://security.stackexchange.com/questions/5334/what-is-sandboxing/5337#5337), it looks like it's not too hard to [break out of it too](https://stackoverflow.com/questions/7613325/how-to-exit-a-chroot-inside-a-perl-script)..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-20T17:27:54.323", "Id": "212345", "Score": "5", "body": "You say that the OP should use `#DEFINE STARTING_ARGS 3` but `#DEFINE` does not enforce type safety and is a nightmare when debugging, I suggest `const int STARTING_ARGS = 3` at the start of `main` to overcome these issues." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T08:24:29.573", "Id": "35680", "ParentId": "33369", "Score": "17" } }, { "body": "<p>Your <code>fprintf()</code> call can be written more simply using <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/perror.html\"><code>perror()</code></a>:</p>\n\n<pre><code>perror(\"Failed to exec\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-15T05:45:37.083", "Id": "114009", "ParentId": "33369", "Score": "6" } } ]
{ "AcceptedAnswerId": "33376", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T06:06:30.083", "Id": "33369", "Score": "15", "Tags": [ "c", "security", "perl", "unix" ], "Title": "Launching an interpreted script" }
33369
<p>I have a lock class, that handels a database lock. It's not important how.<br/> It is used in the beginning of a large operation, here is how it is used today:</p> <pre><code>public void LargeOperation() { try { MyLock.DoLock("SomeId"); // Do lots of stuff that might thorw exceptions } finally { MyLock.ReleaseLock("SomeId"); } } </code></pre> <p>I would like to use it like this instead:</p> <pre><code>public void LargeOperation() { using(new MyLock("someId")) { // Do lots of stuff that might thorw exceptions } } </code></pre> <p>this works fine, but im not sure wether it is a bad idea. I have implemented IDisposable on my class <code>MyLock</code> but it doesn't dispose.. instead it releases the lock. Here is how the class look:</p> <pre><code>public class MyLock : IDisposable { private string _id; public MyLock(string id) { DoLock(id); } public static void DoLock(string id) { //..code omitted } public static void ReleaseLock(string id) { //..code omitted } public void Dispose() { ReleaseLock(_id); } } </code></pre> <p>Is this abuse of the IDisposable interface?</p>
[]
[ { "body": "<p>Following the guidelines for implementing the <code>IDisposable</code> interface i would say it depends on how you have implemented the <code>MyLock</code> class. If your Lock class uses unmanaged resources it is correct to implement the interface. But i would not implement the <code>IDisposable</code> interface to make coding easier. </p>\n\n<p>Maybe you should use a CodeSnippets in Visual Studio to insert the necessary code to use your Lock class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T08:11:19.497", "Id": "53442", "Score": "0", "body": "thanks for the review. You have a valid point (+1), however it is not the typing (of code) that my problem. I think it is easier to *read* the *buisness code* when locks (like mine) fill as little as possible." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T07:59:09.433", "Id": "33372", "ParentId": "33371", "Score": "0" } }, { "body": "<p>The <code>IDisposable</code> was primarily added in order to be able to release acquired unmanaged resources in a deterministic fashion. However it also provides a nice way of releasing other resources in a deterministic fashion as you have found.</p>\n\n<p>I would not say that this is an abuse of the disposable pattern: You acquire a lock which is a resource and you need to release it at a given point in time. For me this is good enough especially since you said it's some kind of db lock which I assume lives outside of the application (that is unmanaged for me). It provides you with native support through <code>using</code> to make sure it's released in case the executing code throws an exception.</p>\n\n<p>However I don't particularly like your two public static methods on there. Now you all of a sudden have two interfaces into the class. If you want a factory like interface then make the <code>DoLock</code> method a proper factory method returning the lock which was acquired (in which case the ctor should become private):</p>\n\n<pre><code>public class MyLock : IDisposable\n{\n private string _id;\n\n private MyLock(string id)\n {\n _id = id;\n DoLock();\n }\n\n public static MyLock Acquire(string id)\n {\n return new MyLock(id);\n }\n\n private void DoLock()\n {\n // get the lock\n }\n\n public void Release()\n {\n // release it\n }\n\n public void Dispose()\n {\n Release();\n }\n}\n</code></pre>\n\n<p>While you could do without a public <code>Release</code> method having <code>Dispose</code> calling <code>Release</code> is semantically useful in case you can't use <code>using</code> and need to release the lock explicitly. In this case the code will be clearer when you call <code>Release</code> rather than <code>Dispose</code>. The .NET stream classes do a similar thing (where <code>Dispose</code> calls <code>Close</code>).</p>\n\n<p>Some things to consider:</p>\n\n<ul>\n<li>Add an \"object is disposed\" flag so you don't try to release the same lock twice.</li>\n<li>Add a finalizer to try and release the lock in case it was not properly released. Add a <code>Debug.Assert</code> at least for that case. Note that adding a finalizer will make all <code>MyLock</code> objects go through the finalizer queue which will add overhead for the GC. You could wrap the finalizer into a <code>#ifdef DEBUG</code> to only do that in debug builds - depends how many of these locks you create (although I guess if you create lots of them you have another problem altogether).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T08:08:15.367", "Id": "53441", "Score": "0", "body": "This was great review :) thanks! I will implement the `Acquire` as you suggested." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:06:18.457", "Id": "53463", "Score": "1", "body": "I think that you want to have the finalizer in release builds too. If you log the fact that the finalizer was called, you're not actually hiding the bug and you're making the application behave better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:21:52.203", "Id": "53473", "Score": "0", "body": "You should never throw an ObjectDisposedException when Dispose is called a second time. See http://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:13:19.277", "Id": "53521", "Score": "0", "body": "@Bort: Good point. Although it probably only matters when you also implement a finalizer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T07:59:24.077", "Id": "33373", "ParentId": "33371", "Score": "5" } } ]
{ "AcceptedAnswerId": "33373", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T06:59:00.527", "Id": "33371", "Score": "6", "Tags": [ "c#", "design-patterns" ], "Title": "Custom database Lock - implemented with IDisposable" }
33371
<p>I have done the source code for my lesson, which I shall publish later on my website:</p> <pre><code>&lt;script src="three.min.js"&gt;&lt;/script&gt; &lt;script&gt; var renderer, scene, camera, geometry, material, mesh, light, axisRotation; function createScene() { renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 ); camera.position.set( 3, 3, 3 ); camera.lookAt( scene.position ); scene.add( camera ); geometry = new THREE.CubeGeometry( 1, 1, 1 ); material = new THREE.MeshLambertMaterial( { color: 0xff0000 } ); mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); light = new THREE.PointLight( 0xffff00 ); light.position.set( 10, 10, 10 ); scene.add( light ); } function rotateCube( axis ) { switch ( axis ) { case 'x': mesh.rotation.x += 0.02; break; case 'y': mesh.rotation.y += 0.02; break; case 'z': mesh.rotation.z += 0.02; break; } } function toggleObjectWireframe() { material.wireframe = !material.wireframe; } function renderScene() { renderer.render( scene, camera ); } function animateScene() { requestAnimationFrame( animateScene ); renderScene(); rotateCube( axisRotation ); } function getChar( event ) { var inputChar = null; if ( event.which === null ) { if ( event.keyCode &lt; 32 ) inputChar = null; else inputChar = String.fromCharCode( event.keyCode ); } if ( event.which != 0 &amp;&amp; event.charCode != 0 ) { if ( event.which &lt; 32 ) inputChar = null; else inputChar = String.fromCharCode( event.which ); } if ( ~['x', 'y', 'z'].indexOf( inputChar ) ) { axisRotation = inputChar; } else if ( inputChar == 'w' ) toggleObjectWireframe(); else inputChar = null; } function initWebGLApp() { axisRotation = 'x'; createScene(); animateScene(); } function setCssStyle() { document.body.style.width = "100%"; document.body.style.height = "100%"; document.body.style.margin = 0; document.body.style.padding = 0; document.querySelector('canvas').style.display = 'block'; } window.onload = function() { initWebGLApp(); setCssStyle(); document.onkeypress = getChar; } &lt;/script&gt; </code></pre> <p>You can see the working results on <a href="http://jsfiddle.net/xBLYa/" rel="nofollow">JSFiddle</a>.</p>
[]
[ { "body": "<p>This code is good for tutorial use.</p>\n\n<p>Some suggestion:</p>\n\n<p>You are switching over 'x','y' and 'z' : </p>\n\n<pre><code>function rotateCube( axis ) {\n switch ( axis ) {\n case 'x':\n mesh.rotation.x += 0.02;\n break;\n case 'y':\n mesh.rotation.y += 0.02;\n break;\n case 'z':\n mesh.rotation.z += 0.02;\n break;\n }\n}\n</code></pre>\n\n<p>You could simply use <code>axis</code> straight.</p>\n\n<pre><code>function rotateCube( axis ) {\n mesh.rotation[axis] += 0.02;\n}\n</code></pre>\n\n<p>You could explain some of your magical constants, like <code>10000</code>, it is those values that always throw me off when I experiment with this 3d library.</p>\n\n<p>You should probably extract your rgb codes into well named variables like cubeColor, pointLightColor etc.</p>\n\n<p>This line could use some comment: <code>requestAnimationFrame( animateScene );</code></p>\n\n<p>One liner functions that are called only once are wrong, I'd much rather you keep those lines in-line with a comment above them as to what is going on.</p>\n\n<pre><code>function renderScene() {\n renderer.render( scene, camera );\n}\n\nfunction animateScene() {\n requestAnimationFrame( animateScene );\n renderScene();\n rotateCube( axisRotation );\n}\n</code></pre>\n\n<p>is less readable than</p>\n\n<pre><code>function animateScene() {\n requestAnimationFrame( animateScene );\n //Render scene\n renderer.render( scene, camera );\n rotateCube( axisRotation );\n}\n</code></pre>\n\n<p>You could merge the treatment of <code>keyCode</code> and <code>which</code>.</p>\n\n<pre><code>var inputChar = null;\n\nif ( event.which === null ) {\n if ( event.keyCode &lt; 32 ) inputChar = null;\n else inputChar = String.fromCharCode( event.keyCode );\n}\n\nif ( event.which != 0 &amp;&amp; event.charCode != 0 ) {\n if ( event.which &lt; 32 ) \n inputChar = null;\n else \n inputChar = String.fromCharCode( event.which );\n}\n</code></pre>\n\n<p>you can change the above to</p>\n\n<pre><code>var keyCode = event.keyCode || event.which,\n inputChar = keyCode &lt; 32 ? null : String.fromCharCode( keyCode );\n</code></pre>\n\n<p>Though I will admit that might be too Golfic for a tutorial, you could turn the ternary into a regular <code>if</code> statement to keep things easy.</p>\n\n<p>Furtermore, from a style perspective, your <code>if</code>'s look bad</p>\n\n<pre><code> if ( event.keyCode &lt; 32 ) inputChar = null;\n else inputChar = String.fromCharCode( event.keyCode );\n</code></pre>\n\n<p>should be </p>\n\n<pre><code> if ( event.keyCode &lt; 32 ) \n inputChar = null;\n else \n inputChar = String.fromCharCode( event.keyCode );\n</code></pre>\n\n<p>and </p>\n\n<pre><code>if ( ~['x', 'y', 'z'].indexOf( inputChar ) ) {\n axisRotation = inputChar;\n}\nelse if ( inputChar == 'w' ) toggleObjectWireframe();\nelse inputChar = null;\n</code></pre>\n\n<p>should be either</p>\n\n<pre><code>if ( ~['x', 'y', 'z'].indexOf( inputChar ) ) {\n axisRotation = inputChar;\n}\nelse if {\n ( inputChar == 'w' ) toggleObjectWireframe();\n}\nelse { \n inputChar = null;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if ( ~['x', 'y', 'z'].indexOf( inputChar ) )\n axisRotation = inputChar;\nelse if ( inputChar == 'w' ) \n toggleObjectWireframe();\nelse \n inputChar = null;\n</code></pre>\n\n<p>I would advocate the second approach.</p>\n\n<p>Furthermore, the following 2 lines seem pointless, I took them out in the fiddle, and it works just fine;</p>\n\n<pre><code>document.body.style.width = \"100%\";\ndocument.body.style.height = \"100%\";\n</code></pre>\n\n<p>Finally, this : </p>\n\n<pre><code>document.onkeypress = getChar;\n</code></pre>\n\n<p>is old skool, and should be avoided in general, I understand it is easy for a tutorial, but you should at least put a line of comment that this is not ideal.</p>\n\n<p>All in all, I like your code, even though this review got a bit lengthy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-10T13:42:46.590", "Id": "38997", "ParentId": "33375", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T08:29:54.910", "Id": "33375", "Score": "4", "Tags": [ "javascript", "dom", "opengl", "webgl" ], "Title": "WebGL (Three.js) simple application" }
33375
<p>I've written a program showing the process of bubble sort arithmetic in C. I need some suggestions on improving it.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;Windows.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #define SIZE 20 #define WIDE (SIZE * 2) void RepaintScreen(int *pData, int count, int p1, int p2) { system("cls"); char b[(WIDE + 1) * (SIZE)]; b[0] = '\0'; for (int i = 0; i &lt; count; i++) { if (i == p1 || i == p2) { strcat(b, "--&gt;"); } else { strcat(b, " "); } for (int j = 0; j &lt; pData[i]; j++) { strcat(b, "|"); } strcat(b, "\n"); } printf("%s", b); } void BubbleSort(int *pData, int count) { int iTemp; for (int i = 0; i &lt; count; i++) { for (int j = count - 1; j &gt; i; j--) { if (pData[j] &lt; pData[j - 1]) { iTemp = pData[j]; pData[j] = pData[j - 1]; pData[j - 1] = iTemp; RepaintScreen(pData, count, i, j); //refresh the screen Sleep(10); } } } } int main( int argc, char **argv ) { int data[SIZE]; srand(time(NULL)); //initiate data for (int i = 0; i &lt; SIZE; i++) { data[i] = rand() % WIDE; } BubbleSort(data, SIZE); return 1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T10:57:57.030", "Id": "53449", "Score": "0", "body": "I would create the line to print first and than print with one `printf`-call. Or even create all lines to print first and than make only one `printf`-call for all lines together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T02:31:29.113", "Id": "53556", "Score": "0", "body": "Thank you! I rewrite the RepaintScreen function with printf call for all lines, and it works better. But it flickers sometimes, it may be the problem of system call \"cls\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T03:03:46.633", "Id": "53557", "Score": "1", "body": "I'm sorry I clicked the `reopen` link too fast, saw your recent edit and assumed you had fixed your code; please edit the title of this question so it doesn't look like a StackOverflow question, remove references to the flickering problem and you might get more `reopen` votes :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T04:35:57.803", "Id": "53560", "Score": "0", "body": "@retailcoder: Got it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T15:28:50.263", "Id": "53593", "Score": "0", "body": "@retailcoder: In fact, the filckering problem is still existing, so I said it may be the problem of system call \"cls\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T15:35:00.670", "Id": "53594", "Score": "0", "body": "It's all right - flickering doesn't make it non-working code, a review might note that it's flickering because of *abc* and would stop doing that if you did *xyz*, but this site isn't meant to address specific problems - if you want to get this code peer reviewed, you're in the right place. If you want to get the flickering issue fixed, ask StackOverflow :)" } ]
[ { "body": "<p>Your code works nicely. </p>\n\n<p>In <code>BubbleSort</code> I would move the definition of <code>iTemp</code> to the point of first use. The name <code>iTemp</code> is ugly and the 'i' makes me think you are using a type prefix (as does the 'p' in <code>pData</code>). I don't know anyone who thinks that is a good idea - just use <code>temp</code> and <code>data</code>.</p>\n\n<p>In <code>RepaintScreen</code> I don't see the need to buffer the data yourself. You can just use <code>stdio</code> to buffer it for you:</p>\n\n<pre><code>static void RepaintScreen(const int *data, int count, int p1, int p2)\n{\n for (int i = 0; i &lt; count; i++) {\n fputs((i == p1 || i == p2) ? \"--&gt;\" : \" \", stdout);\n\n for (int j = 0; j &lt; data[i]; j++) {\n putc('|', stdout);\n }\n putc('\\n', stdout);\n }\n}\n</code></pre>\n\n<p>If you do accumulate a string, using <code>strcat</code> is inefficient and prone to buffer overflow. It is inefficient because on each call it must traverse the whole string to find the end. It would be better to keep track of the end of the string yourself. For example:</p>\n\n<pre><code>static void RepaintScreen(const int *data, int count, int p1, int p2)\n{\n system(\"cls\");\n char buf[(WIDE + 1) * (SIZE)];\n char *b = buf;\n\n for (int i = 0; i &lt; count; i++) {\n if (i == p1 || i == p2) {\n *b++ = '&gt;';\n } else {\n *b++ = ' ';\n }\n for (int j = 0; j &lt; data[i]; j++) {\n *b++ = '|';\n }\n *b++ = '\\n';\n }\n *b++ = '\\0';\n fputs(buf, stdout);\n}\n</code></pre>\n\n<p>Overflow occurs if you get the size of the buffer size wrong. Avoiding overflow is messy as you must check that there is enough space each time you insert into the buffer and exit sensibly if there is not. Using fputs/putc, as shown above, avoids overruns. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T13:54:02.200", "Id": "33999", "ParentId": "33377", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T08:59:35.177", "Id": "33377", "Score": "2", "Tags": [ "c", "sorting", "windows" ], "Title": "Visualization of bubble sort in progress" }
33377
<p>I have WCF Service. It works fine and I want to have test coverage for it. Unit tests and acceptance. </p> <p>The problem is the <code>static</code> class in the code. How is it possible to avoid it?</p> <p>If it will be refactored to the code without static classes - I can use mocks for example <code>Moq</code>.</p> <p>I have also used <code>Ninject</code> as DI Framework so far.</p> <pre><code> [ServiceContract] public interface IWorkingService { [OperationContract] Collection&lt;Result&gt; UpdateEntity(int entityID); } public class WorkingService : IWorkingService { private static readonly WorkingService Logger = ProviderLog4Net.GiveLogger(typeof(SomeService)); /// &lt;inheritdoc /&gt; public Collection&lt;Result&gt; UpdateEntity(int entityID) { Logger.Info("------- UpdateEntity call ------------"); try { return CoreFacade.UpdateEntity(entityID); } catch (Exception exception) { Logger.Fatal(exception); throw; } } } public static class CoreFacade { ... } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T09:12:47.227", "Id": "53444", "Score": "0", "body": "One way *might* be, if possible, to change the static class into a Singleton. Though, Singletons are a completely different beast." } ]
[ { "body": "<p>Personally I would not recommend writing a Unit test for a WCF service. It is an infrastructure and generally you would orchestrate routines, call a façade or a another service, provide addition infrastructure such as logging caching etc. There is no much behaviour, and you should not. I think you get more benefit writing an integration test or an acceptance test. Also doing TDD for WCF is unheard-of.</p>\n\n<p>I have seen developers attempt write Unit Tests for WCF services and caught up with mocking issues, etc. And maintenance issue on both test and the code when there is a need to add additional infrastructure. Even if you were able to mock certain things as it current state, then you would test pretty much verification type testing. For example, whether a method has been called or not. We encourage more state based type testing, not verification type testing. Now you see when adding more tests means more code to maintain. </p>\n\n<p>You get more value of for your effort if you Unit Test your domain, or your standard POCO classes with behaviour, or even the services (which may have behaviour) that might consume your WCF service.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T14:45:48.963", "Id": "53490", "Score": "0", "body": "Thank you for you answer! Yes I want to have acceptance/integration tests. For example test call my service and I test the result. For this purpose I have to use mocks, but it is difficult cause of **static**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T14:47:08.220", "Id": "53491", "Score": "0", "body": "You write also \"I have seen developers attempt write Unit Tests for WCF services and caught up with mocking issues, etc.\" Thats why I have posted my code here to avoid such a problems" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-25T23:36:51.610", "Id": "225607", "Score": "0", "body": "Also doing TDD for WCF is unheard-of... except for @PeterKiss excellent answer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T10:04:32.197", "Id": "33381", "ParentId": "33379", "Score": "4" } }, { "body": "<p>I agree with Raj that you are probably best off not trying to unit test your WCF services themselves, but I have a suggestion specifically around your concerns regarding your static class/methods, assuming you are using VS2012 or later.</p>\n\n<p>I recently had to write some unit tests for some classes that themselves called some static methods that I could not modify. What I ended up doing after some research was utilizing <a href=\"http://msdn.microsoft.com/en-us/library/hh549175%28v=vs.110%29.aspx\" rel=\"nofollow\">shims</a>.</p>\n\n<p>Here's a simple example:</p>\n\n<pre><code>public class Car\n{\n public static int RetrieveTopSpeed(string carName)\n {\n //logic here\n }\n}\n</code></pre>\n\n<p>And my test method (using MSTest):</p>\n\n<pre><code>[TestMethod]\npublic void TestClassRelyingOnTopSpeed()\n{\n using (ShimsContext.Create())\n {\n //this will always return 10 regardless of the car name, you can of course make this smarter\n ShimCar.RetrieveTopSpeed = name =&gt; 10;\n\n var result = foo.MethodThatUsesRetrieveTopSpeed();\n Assert.IsTrue(result);\n }\n}\n</code></pre>\n\n<p>My situation only included static methods on non-static classes, but it should work just the same for your situation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T12:49:27.153", "Id": "33647", "ParentId": "33379", "Score": "1" } }, { "body": "<p>You are doing it wrong.</p>\n\n<p>Why are you using WCF if you are only using it as an old timer ASMX service without using the extensibility points?</p>\n\n<p><strong>First things first - clean up</strong></p>\n\n<pre><code>[ServiceContract]\npublic interface IWorkingService\n{\n [OperationContract]\n Collection&lt;Ergebnis&gt; UpdateEntity(int entityId);\n}\n</code></pre>\n\n<p>The service interface is the same as yours, but:</p>\n\n<ul>\n<li>Why are you using <code>Collection&lt;T&gt;</code> as the return type? Use someting more generic.</li>\n<li><p><strong>Do not use primitives as service parameters, ever!</strong> Using primitives as parameters means that you cannot versionize your service, such as adding extra non-required properties.</p>\n\n<pre><code>public class WorkingService : IWorkingService\n{\n private readonly NotStaticFacade _notStaticFacade;\n\n public WorkingService(NotStaticFacade notStaticFacade)\n {\n _notStaticFacade = notStaticFacade;\n }\n\n public Collection&lt;Ergebnis&gt; UpdateEntity(int entityId)\n {\n return _notStaticFacade.UpdateEntity(entityId);\n }\n}\n</code></pre></li>\n</ul>\n\n<p>The service implementation is much more slimmer then yours because it's missing the logging stuff (be patient!). The important thing is that it isn't containing a parameter-less constructor because the service has a dependency: the <code>NotStaticService</code> (in your code this is the static <code>CoreFacade</code>). What does this mean? We will need a custom <code>ServiceHostFactory</code> because the default one cannot handle these kinds of situation, but don't worry; Ninject is with us!</p>\n\n<p><strong>Install-Package Ninject.Extensions.Wcf</strong></p>\n\n<p>The Ninject has an extension for WCF so install it via NuGet (remove <code>App_Start</code> directory after installation) and after that, create our own <code>ServiceHostFactory</code>:</p>\n\n<pre><code>public class WorkingServiceHostFactoryWithNinject : NinjectServiceHostFactory\n{\n private readonly IKernel _kernel;\n\n public WorkingServiceHostFactoryWithNinject()\n {\n _kernel = new StandardKernel(new WorkingServiceNinjectModule());\n\n // SetKernel is a static method in Ninject WCF!\n SetKernel(_kernel);\n }\n} \n</code></pre>\n\n<p>Nothing fancy; we only telling the factory which <code>IKernel</code> instance we want to use. As you see, you will have a <code>NinjectModule</code> prepared to map the bindings.</p>\n\n<pre><code>public class WorkingServiceNinjectModule : NinjectModule\n{\n public override void Load()\n {\n // what ever other binding is need\n Kernel.Bind&lt;NotStaticFacade&gt;().ToSelf();\n }\n}\n</code></pre>\n\n<p>I'm only telling the kernel how to resolve the <code>NotStaticFacade</code> but this isn't necessary this way. We haven't finished yet because we haven't told the system to use our factory to build up our service. To do this, we need to open the *.svc markup (right-click on the file then View markup) and write into the directive the Factory attribute:</p>\n\n<pre><code>&lt;%@ ServiceHost Language=\"C#\" Debug=\"true\" Service=\"CodeReview.WorkingService\" CodeBehind=\"WorkingService.svc.cs\"\n Factory=\"CodeReview.WorkingServiceHostFactoryWithNinject\" %&gt;\n</code></pre>\n\n<p>Save and close this.</p>\n\n<p>Now we have a service with dependency injection and the only one real facade is our service.</p>\n\n<p><strong>WCF extensibility - <code>IServiceBehavior</code>, <code>IErrorHandler</code></strong></p>\n\n<p>The WCF infrastructure has great possibilities for extending its capabilities, such as handling an error!</p>\n\n<p>To do that we will create a new service behavior and we will use it for adding our error handlers to the service:</p>\n\n<pre><code>public class ErrorHandlerBehaviorWithNinjectKernel : IServiceBehavior\n{\n private readonly IKernel _kernel;\n\n public ErrorHandlerBehaviorWithNinjectKernel(IKernel kernel)\n {\n _kernel = kernel;\n }\n\n public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)\n {\n }\n\n public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection&lt;ServiceEndpoint&gt; endpoints,\n BindingParameterCollection bindingParameters)\n {\n }\n\n public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)\n {\n var errorHandlers = _kernel.GetAll&lt;IErrorHandler&gt;().ToArray();\n\n if (!errorHandlers.Any())\n {\n throw new Exception(\"No errorhandler was found\");\n }\n\n foreach (var channelDispatcher in serviceHostBase.ChannelDispatchers.Select(channelDispatcherBase =&gt; channelDispatcherBase as ChannelDispatcher))\n {\n foreach (var errorHandler in errorHandlers)\n {\n channelDispatcher.ErrorHandlers.Add(errorHandler);\n }\n }\n }\n}\n</code></pre>\n\n<p>What can we see here? We are adding all <code>IErrorHandler</code> instance to all possible dispatchers to use it. <code>IErrorHandler</code> is coming from the WCF infrastructure. You need to create your own implementation of it like this:</p>\n\n<pre><code>public class ErrorLogger : IErrorHandler\n{\n private readonly IAmLogger _logger;\n\n public ErrorLogger(IAmLogger logger)\n {\n _logger = logger;\n }\n\n public void ProvideFault(Exception error, MessageVersion version, ref Message fault)\n {\n //nothing to do here\n }\n\n public bool HandleError(Exception error)\n {\n _logger.Fatal(error);\n\n return true;\n }\n}\n</code></pre>\n\n<p>I have created the <code>IAmLogger</code> interface to fake your Log4Net stuff, nothing more:</p>\n\n<pre><code>public interface IAmLogger\n{\n void Info(string info);\n void Fatal(Exception exception);\n}\n</code></pre>\n\n<p>If you have created your <code>IErrorHandler</code> implementation, register it in your <code>NinjectModule</code>:</p>\n\n<pre><code>Kernel.Bind&lt;IErrorHandler&gt;().To&lt;ErrorLogger&gt;();\n</code></pre>\n\n<p>There are two ways to add an <code>IServiceBehavior</code> to a service: view attributes (then our class have to derive from Attribute) and programatically.\nWe will use the last one because of the <code>IKernel</code> dependency.</p>\n\n<p>Let's bring up the factory again and extend it with overriding the <code>CreateServiceHost</code> method:</p>\n\n<pre><code>public class WorkingServiceHostFactoryWithNinject : NinjectServiceHostFactory\n{\n private readonly IKernel _kernel;\n\n public WorkingServiceHostFactoryWithNinject()\n {\n _kernel = new StandardKernel(new WorkingServiceNinjectModule());\n\n // SetKernel is a static method in Ninject WCF!\n SetKernel(_kernel);\n }\n\n protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)\n {\n var serviceHost = base.CreateServiceHost(serviceType, baseAddresses);\n\n serviceHost.Description.Behaviors.Add(new ErrorHandlerBehaviorWithNinjectKernel(_kernel));\n\n return serviceHost;\n }\n}\n</code></pre>\n\n<p>Now we are creating the <code>ServiceHost</code> and after that we are adding our behavior (<code>ErrorHandlerBehaviorWithNinjectKernel</code>) to it. That is how every exception in the system will be logged and we don't need to write anything into our service.</p>\n\n<p><strong>Logging operation calls - <code>IOperationInvoker</code>, <code>IOperationBehavior</code></strong></p>\n\n<p>In WCF we can specify our own Operation invoker by implementing the <code>IOperationInvoker</code> interface and applying it to our operations via an <code>IOperationBehavior</code> instance inside a service behavior instance. (That's all, really!)</p>\n\n<p>First create an <code>IOperationLogger</code> implementation:</p>\n\n<pre><code>public class OperationInvokerWithLogging : IOperationInvoker\n{\n private readonly IAmLogger _logger;\n private readonly IOperationInvoker _invoker;\n private readonly DispatchOperation _dispatchOperation;\n\n public OperationInvokerWithLogging(IAmLogger logger, IOperationInvoker invoker, DispatchOperation dispatchOperation)\n {\n _logger = logger;\n _invoker = invoker;\n _dispatchOperation = dispatchOperation;\n }\n\n public object[] AllocateInputs()\n {\n return _invoker.AllocateInputs();\n }\n\n public object Invoke(object instance, object[] inputs, out object[] outputs)\n {\n _logger.Info(string.Format(\"Operation {0} called (Invoke)\", _dispatchOperation.Name));\n return _invoker.Invoke(instance, inputs, out outputs);\n }\n\n public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)\n {\n _logger.Info(string.Format(\"Operation {0} called (InvokeBegin)\", _dispatchOperation.Name));\n return _invoker.InvokeBegin(instance, inputs, callback, state);\n }\n\n public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)\n {\n _logger.Info(string.Format(\"Operation {0} called (InvokeEnd)\", _dispatchOperation.Name));\n return _invoker.InvokeEnd(instance, out outputs, result);\n }\n\n public bool IsSynchronous { get { return _invoker.IsSynchronous; } }\n}\n</code></pre>\n\n<p>This is mostly a stub for the real <code>IOperationInvoker</code> what comes from the WCF infrastructure (we will see it soon). The only additional mechism is the logging parts (with out <code>IAmLogger</code> instance!).</p>\n\n<p>Let's create our <code>IOperationBehavior</code> implementation; this will map the <code>IOperationInvoker</code> to all of our operations:</p>\n\n<pre><code>public class LoggingOperationBehaviorWithNinjectKernel : IOperationBehavior\n{\n private readonly IKernel _kernel;\n\n public LoggingOperationBehaviorWithNinjectKernel(IKernel kernel)\n {\n _kernel = kernel;\n }\n\n public void Validate(OperationDescription operationDescription)\n {\n\n }\n\n public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)\n {\n dispatchOperation.Invoker = new OperationInvokerWithLogging(_kernel.Get&lt;IAmLogger&gt;(), dispatchOperation.Invoker, dispatchOperation);\n }\n\n public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)\n {\n\n }\n\n public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)\n {\n\n }\n}\n</code></pre>\n\n<p>Only mapping the invoker, nothing more except that we are resolving the <code>IAmInvoker</code> with Ninject.</p>\n\n<p>Now we need a service behavior to apply the operation behavior to our service like the error handling stuff:</p>\n\n<pre><code>public class ServiceLoggingBehavior : IServiceBehavior\n{\n private readonly IKernel _kernel;\n\n public ServiceLoggingBehavior(IKernel kernel)\n {\n _kernel = kernel;\n }\n\n public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)\n {\n }\n\n public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection&lt;ServiceEndpoint&gt; endpoints,\n BindingParameterCollection bindingParameters)\n {\n }\n\n public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)\n {\n foreach (var operation in serviceDescription.Endpoints.SelectMany(endpoint =&gt; endpoint.Contract.Operations))\n {\n operation.Behaviors.Add(new LoggingOperationBehaviorWithNinjectKernel(_kernel));\n }\n }\n}\n</code></pre>\n\n<p>More or less the same as above nothing new here, map it in our factory and lets see what we have got:</p>\n\n<pre><code>public class WorkingServiceHostFactoryWithNinject : NinjectServiceHostFactory\n{\n private readonly IKernel _kernel;\n\n public WorkingServiceHostFactoryWithNinject()\n {\n _kernel = new StandardKernel(new WorkingServiceNinjectModule());\n\n // SetKernel is a static method in Ninject WCF!\n SetKernel(_kernel);\n }\n\n protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)\n {\n var serviceHost = base.CreateServiceHost(serviceType, baseAddresses);\n\n serviceHost.Description.Behaviors.Add(new ErrorHandlerBehaviorWithNinjectKernel(_kernel));\n serviceHost.Description.Behaviors.Add(new ServiceLoggingBehavior(_kernel));\n\n return serviceHost;\n }\n}\n</code></pre>\n\n<p>Pretty clear stuff and still no extra code in our service implementation!</p>\n\n<p><strong>About unit testing</strong></p>\n\n<p>As the others mentioned above, we are not really unit testing service implementations because, as you see, it contains a lot of infrastructure stuff in it. These are small parts which can be tested but mostly it isn't worth it.</p>\n\n<p>Now you only have to test your <code>NotStaticFacade</code> class and not the service itself because it's just a stub. Of course it can contain code parts which are needed to be tested (for example the service using EF entities and transforms them to DTO instances) but now you can test these thing simpler:</p>\n\n<p>Create an interface for the <code>NotStaticFacade</code> so you can fake it out with a simple implementation and modify your service constructor to accept the interface (<code>ICoreStuff</code> or whatever) not the concrete implementation. If you created a stub for the interface you can have unit tests to check your service output.</p>\n\n<p>And of course you can still have integration tests to check the whole service behavior and in those tests you can set up different or no logger for example.</p>\n\n<p>I'm not sure the things above will work as the way they are because I haven't tested it, but the main implementation steps are covered in the code examples.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T17:24:49.703", "Id": "53926", "Score": "2", "body": "Great answer. Why not use the `Ninject.Extensions.Logging` extension though? It works with both NLog and Log4Net. Also not too sure about injecting a `Kernel` as a dependency, sounds like *service locator anti-pattern*; I guess the service being an infrastructure thing makes it ok." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T17:36:38.327", "Id": "53928", "Score": "0", "body": "Yes, injecting the whole IKernel is kind of service locator stuff but i think it's fair enough in those spaces becouse they (consumer classes) will not be tested." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-28T22:17:16.777", "Id": "226046", "Score": "0", "body": "Great answer. Hey can you please explain (may be provide provide a link if you have) on \"Do not use primitives as service parameters, ever! \" much appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-08T06:51:16.093", "Id": "245024", "Score": "0", "body": "It is simple - you cannot \"version\" your service. You cannot add more parameter to any of you operations without any breaking change. If one of your client is already using your service then after you modify your operations' signature they probably cannot use your service any longer without code changes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T16:24:03.910", "Id": "33658", "ParentId": "33379", "Score": "14" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T09:10:41.690", "Id": "33379", "Score": "8", "Tags": [ "c#", "unit-testing", "wcf" ], "Title": "Make WCF Service testable" }
33379
<p>As I get to some performance issues in my app and find that I use database access in a bad way.<br/> So I decided to move to singleton pattern.<br/> I need someone to review this code and confirm me that I made a good database access via singleton pattern or I am doing something wrong:<br/> This is the class:</p> <pre><code>@interface DataAccessController : NSObject{ sqlite3 *databaseHandle; } + (id)sharedManager; -(void)initDatabase; ... + (id)sharedManager { static DataAccessController *sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&amp;onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager; } - (id)init { if (self = [super init]) { [self initDatabase]; // open database connection } return self; } ... </code></pre> <p>AppDelegate.m</p> <pre><code>DataAccessController *d = [DataAccessController sharedManager]; </code></pre> <p>Usage through the application every time I need data I use:</p> <pre><code>DataAccessController *d = [DataAccessController sharedManager]; NSMutableArray* data = [d getAllRecordedUnits]; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:58:57.970", "Id": "53512", "Score": "0", "body": "To my untrained eye this looks like a straight-forward, by-the-book singleton construction. If there are still performance bottlenecks in your code, they're probably elsewhere" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T23:30:22.373", "Id": "59169", "Score": "0", "body": "There's no need to initialize sharedMyManager to nil." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-04T17:18:04.937", "Id": "60224", "Score": "0", "body": "There's a good chance that the bottleneck is not with your application but with your database. You mentioned it's a local database server so network shouldn't be a problem. How do you use your singleton to access the database and what do you access? Any performance heavy querys perhaps?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T23:29:39.993", "Id": "61109", "Score": "0", "body": "@RhythmicFistman, opinions differ on this. In this instance, there isn't a need to set `sharedMyManager` to `nil` explicitly, but I would as a general practice when creating variables." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-11T01:55:09.047", "Id": "61119", "Score": "0", "body": "Sure, it's a bug waiting to happen if you decide to replace `dispatch_once` with a simple if statement. I think that since `dispatch_once` became the singleton idiom it is often misused in two ways: 1. unnecessarily, in singletons that are intended to be single threaded only and 2. as magic DWIM dust, in multithreaded singletons in which `dispatch_once` is the author's first _and last_ attempt at synchronization." } ]
[ { "body": "<p>Based on your provided code, this is the correct way to create a singleton object.</p>\n\n<p>In such, here's a <a href=\"http://www.galloway.me.uk/tutorials/singleton-classes/\" rel=\"nofollow noreferrer\">reference link</a> from Matt Gallow's site showing the same singleton setup as you're doing.</p>\n\n<p>However, there is not enough information provided to determine the cause of your performance issues (whether or not caused by accessing the database). In general, writing efficient database code is hard, which is why <code>Core Data</code> exists.</p>\n\n<p>You might consider looking into <code>Core Data</code> to see if this will work better for your app or perhaps creating a question on <a href=\"https://stackoverflow.com/\">StackOverflow</a> describing the issue you're seeing in more detail and asking for help on how to implement what you're trying to do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-10T23:36:14.797", "Id": "37090", "ParentId": "33380", "Score": "3" } }, { "body": "<p>It's the same pattern I always use for \"singletons\". </p>\n\n<p>I have two more picky comments.</p>\n\n<ol>\n<li>Move the declaration of the <code>databaseHandle</code> instance variable into the implementation. With modern Objective-C, you should never have instance variables in your interface declaration.</li>\n<li>Rename <code>-initDatabase</code>. The convention is that methods beginning with <code>init...</code> are initialisers. Perhaps call it <code>openDatabase</code>.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T17:40:56.173", "Id": "38774", "ParentId": "33380", "Score": "1" } } ]
{ "AcceptedAnswerId": "37090", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T09:40:13.257", "Id": "33380", "Score": "2", "Tags": [ "objective-c", "ios", "singleton", "sqlite" ], "Title": "I need code review on using singleton to access local database" }
33380
<p>I have to create a button which counts from 0 to 9, and after 9 come 0 again. One of my friends said that this code is not good enough. Can you explain to me why it's a problem to use <code>-1</code>?</p> <pre><code>int szám = 0; private void counterButton_Click(object sender, EventArgs e) { szám++; this.Text = szám.ToString(); if (szám == 9) { szám = -1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:03:33.333", "Id": "53450", "Score": "3", "body": "szám? not very clear what is it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:05:14.440", "Id": "53451", "Score": "0", "body": "it's just a simple variable. It means number in hungarian." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:07:28.463", "Id": "53452", "Score": "3", "body": "I recommend to use only ASCII characters in source code, because some tools bay have problems with unicode." } ]
[ { "body": "<p>Your code is ok. But there are always other ways to get the same result which may be more elegant.</p>\n\n<pre><code>private void counterButton_Click(object sender, EventArgs e)\n{\n szám=(szám +1) % 10;\n this.Text = szám.ToString();\n}\n</code></pre>\n\n<p>or you can do:</p>\n\n<pre><code>private void counterButton_Click(object sender, EventArgs e)\n{\n szám=(9==szám)?0:szám+1;\n this.Text = szám.ToString();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:10:00.307", "Id": "53453", "Score": "0", "body": "Thanks. But is there a problem with the -1? why is it less elegent than use an if statement with 0?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:12:22.347", "Id": "53454", "Score": "0", "body": "There is no problem with your `-1` way. It is only more lines of code and a little bit unusual. No Problem as long as your `szám` is a signed variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:10:56.603", "Id": "53470", "Score": "4", "body": "There is no good reason to write [Yoda conditions](https://en.wikipedia.org/wiki/Yoda_conditions) in C#. Just write `szám == 9`, it's more readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:00:22.987", "Id": "53476", "Score": "0", "body": "@svick: That is just a matter of different tastes. I like Yoda conditions and am used to read them. And they are still useful. E.g. `\"Hello\".Equals(input)` can never throw an NullReferenceException, but `input.Equals(\"hello\")` can." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:13:41.320", "Id": "53478", "Score": "1", "body": "@MrSmith42 `input == \"hello\"` also never throws and works just as well. (Many types that have `Equals()` also have `==`.) As an alternative, you could write `object.Equals(input, \"Hello\")`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:15:46.143", "Id": "53479", "Score": "1", "body": "I think, the first option is the best you can do with C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T15:25:26.800", "Id": "53494", "Score": "0", "body": "@svick: what if `input` is `null` than `input.Equals(\"hello\")` should throw the Exception." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:06:01.987", "Id": "33385", "ParentId": "33383", "Score": "4" } }, { "body": "<p>The only problem with the -1 is that it's a bit harder to follow what the code is doing.</p>\n\n<p>You are doing half of an operation by setting the variable to -1, and the operation is only completed when the event handler is called again and the value is increased to 0. By splitting the operation over two executions of the event handler, you have to think two steps further to understand what the code actually does.</p>\n\n<p>One way to write the code in clear steps is to increase the variable, then make sure that it's in the range 0..9, and finally display the value. That makes it easy to follow what's happening to the value:</p>\n\n<pre><code>int szám = 0;\nprivate void counterButton_Click(object sender, EventArgs e)\n{\n szám++;\n szám %= 10;\n this.Text = szám.ToString();\n}\n</code></pre>\n\n<p>You can of course write that as an <code>if</code> statement if you like:</p>\n\n<pre><code>int szám = 0;\nprivate void counterButton_Click(object sender, EventArgs e)\n{\n szám++;\n if (szám == 10) {\n szám = 0;\n }\n this.Text = szám.ToString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:57:59.370", "Id": "33395", "ParentId": "33383", "Score": "4" } } ]
{ "AcceptedAnswerId": "33395", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T10:59:21.337", "Id": "33383", "Score": "2", "Tags": [ "c#" ], "Title": "Button incrementing from 0 to 9 and repeating" }
33383
<p>I am fairly new to jQuery and I am making a new search results page. In this snippet I am switching from a grid to list view and vice versa. Can anyone suggest a cleaner method of performing this change? I did try using a variable to minimize all my (this) calls but I couldn't get them to work. Any help would be much appreciated.</p> <p>JS</p> <pre><code> $('.btn.grid').click(function() { if (!$(this).hasClass("active")) { $(this).addClass("active"); $('.results-wrapper .grid_12').removeClass("grid_12").addClass("grid_3"); $('.wrapper .results').addClass("grid-view-active"); if ($(".btn.list").hasClass("active")) { $(".btn.list").removeClass("active"); $('.wrapper .results').removeClass("list-view-active"); } } }); $('.btn.list').click(function() { if (!$(this).hasClass("active")) { $(this).addClass("active"); $('.results-wrapper .grid_3').removeClass("grid_3").addClass("grid_12"); $('.wrapper .results').addClass("list-view-active"); if ($(".btn.grid").hasClass("active")) { $(".btn.grid").removeClass("active"); $('.wrapper .results').removeClass("grid-view-active"); } } }); </code></pre> <p>HTML</p> <pre><code>&lt;span class="btn grid active"&gt;grid&lt;/span&gt; &lt;span class="btn list"&gt;list&lt;/span&gt; &lt;div class="wrapper"&gt; &lt;div class="results-wrapper"&gt; &lt;ul class="results"&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;li class="grid_3"&gt; &lt;h1&gt;Title&lt;/h1&gt; &lt;img src="http://rosherunwoven.co.uk/images/Nike%20Free%20Trainer%205.0%20Mens%20Trainers%20Black.jpg"/&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.btn { background: #ccc; cursor: pointer; display: inline-block; height: 35px; width: 35px; } .btn.active { background: red; } li { float: left; height: 200px; width: 200px; } li img { max-width: 100%; max-height: 100%; } .grid_3 { width: 25%; } .grid_12 { width: 100%; } </code></pre>
[]
[ { "body": "<p>You can simply use JS to toggle a list class. In CSS, you can simply override the style to either display block (item per row, list style), or display inline-block (several items side-by-side per row, grid style).</p>\n\n<p><a href=\"http://jsfiddle.net/7d6S3/1/\" rel=\"nofollow\">A simple demo here</a>:</p>\n\n<p>JS:</p>\n\n<pre><code>$('.btn.grid').click(function (event) {\n event.preventDefault();\n $('.results').addClass('grid');\n});\n$('.btn.list').click(function (event) {\n event.preventDefault();\n $('.results').removeClass('grid');\n});\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>/* default list mode */\n.results li{\n padding: 0;\n margin: 0;\n display : block;\n}\n\n/* grid mode */\n.results.grid li{\n display:inline-block;\n width: 100px;\n}\n\n.results img{\n display:block;\n width: 100%;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T18:53:08.653", "Id": "53519", "Score": "0", "body": "That does work well but i need to have the grid or list class on the container for the css. I also need to add the active state to my buttons" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:43:30.923", "Id": "33398", "ParentId": "33384", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:03:00.920", "Id": "33384", "Score": "1", "Tags": [ "javascript", "jquery", "optimization" ], "Title": "Optimize ineffiecient Jquery - UX list to grid view" }
33384
<p>I'm writing a C++ library with MinGW (4.8.0, DW2, POSIX) compiler. But this library must be used by another compiler. I've read this <a href="http://chadaustin.me/cppinterface.html">post</a>, so I've re-written the C++ library interface in this way:</p> <pre><code>#ifndef SERIALPORT_H #define SERIALPORT_H #include &lt;cstring&gt; // size_t #include &lt;memory&gt; // unique_ptr #if defined( _MSC_VER ) || defined( __MINGW32__ ) || defined( __MINGW64__ ) # define SERIALPORT_IMPORT __declspec( dllimport ) # define SERIALPORT_EXPORT __declspec( dllexport ) # define SERIALPORT_CALL __stdcall #elif defined( __GNUG__ ) &amp;&amp; !defined( WIN32 ) # define SERIALPORT_IMPORT # define SERIALPORT_EXPORT __attribute__ ((visibility ("default"))) #else # define SERIALPORT_IMPORT # define SERIALPORT_EXPORT #endif #if defined( SERIALPORT_EXPORTS ) # define SERIALPORT_API SERIALPORT_EXPORT #else # define SERIALPORT_API SERIALPORT_IMPORT #endif namespace serialport { /** * @brief Milliseconds_t rappresent a duration of time expressed in milliseconds */ typedef unsigned long Milliseconds_t; /** * Possible read return value. */ enum ReadStatus { SERIAL_OK, SERIAL_TIMEOUT, SERIAL_ERROR }; /** * Interface to access to a serial port */ class ISerialPort { public: /** * @brief operator delete overload the delete operator so we can destroy * class inside shared library bounds. */ void operator delete( void* p ) { if ( p ) { ISerialPort* s = static_cast&lt; ISerialPort* &gt;( p ); s-&gt;destroy(); } } /** * Get serial port path */ virtual const char* SERIALPORT_CALL getDeviceName() const = 0; /** * Get serial port baudrate */ virtual int SERIALPORT_CALL baudrate() const = 0; /** * Flush serial port rx and tx buffers. */ virtual void SERIALPORT_CALL flush() = 0; /** * @brief setTimeout set the serial port timeout * @param timeout_ms timeout in milliseconds */ virtual void SERIALPORT_CALL setTimeout( Milliseconds_t timeout_ms ) = 0; /** * @brief getTimeoutGet serial port timeouts. * @return serial port timeouts in milliseconds */ virtual Milliseconds_t SERIALPORT_CALL getTimeout() const = 0; /** * Read data from serial port in the specified timeout. * @param[out] buffer pointer to the destination buffer. * @param[in] size size in bytes of data that must be read. * @throw SerialTimeout if a timeout occured */ virtual ReadStatus SERIALPORT_CALL read( void* buffer, size_t size ) const = 0; /** * Read data from serial port the aviable data. * @param[out] buffer storage where to put incoming data. * @param[in] size size in bytes of data that must be read. * @return SerialBuffer buffer containing the data. */ virtual size_t SERIALPORT_CALL readSome( void* buffer, size_t size ) const = 0; /** * Read data from serial port in a infinite timeout. * @param[out] buffer pointer to the destination buffer. * @param[in] size size in bytes of data that must be read. */ virtual void SERIALPORT_CALL read_n( void* buffer, size_t size ) const = 0; /** * Send data to the serial port. * @param[out] buffer pointer to the destination buffer. * @param[in] size size in bytes of data that must be read. */ virtual void SERIALPORT_CALL send( const void* orig, size_t size ) const = 0; protected: /** * @brief ~ISerialPort The destructor is protected to avoid that library is * deleted outside dll bounds. */ virtual ~ISerialPort() {} /** * @brief destroy need to free resource: we cannot use dctor so operator delete * will call destroy() to release the resource */ virtual void SERIALPORT_CALL destroy() = 0; }; /** * @brief The SerialDeleter class is used by SerialPtr to safely delete the class */ class SerialDeleter { public: void operator() ( ISerialPort* s ) { s-&gt;destroy(); } }; } // serialport namespace typedef std::unique_ptr &lt; serialport::ISerialPort, serialport::SerialDeleter &gt; SerialPtr; /** * Factory function for creating a serial port class * @param path path of the serial port. * @param baudrate baudrate of the serial port. */ extern "C" SERIALPORT_API serialport::ISerialPort* CreateSerialPort( const char* deviceName, int baudrate ); #endif // SERIALPORT_H </code></pre> <p>Assuming the compiler is C++11-compliant (I've tested with Visual C++ 2013), is this a good interface for cross-compiler integration?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T15:13:55.810", "Id": "54115", "Score": "0", "body": "This is not a good solution: The code above if compiled with MinGW won't work correctly on msvc compiler." } ]
[ { "body": "<ul>\n<li><p>You should just include <a href=\"http://en.cppreference.com/w/cpp/header/cstddef\"><code>&lt;cstddef&gt;</code></a> in order to use <code>std::size_t</code>. Including <code>&lt;cstring&gt;</code> seems unnecessary if you're not actually going to utilize anything else.</p></li>\n<li><p>Since this is C++11, you can now use <a href=\"http://www.codeguru.com/cpp/cpp/article.php/c19083/C-2011-Stronglytyped-Enums.htm\">strongly-typed <code>enum</code>s</a> over plain ones. One difference is that plain <code>enum</code>s are implicitly cast to <code>int</code>, whereas strongly-typed ones must be explicitly cast in order to not be implicitly cast as well.</p></li>\n<li><p>Both of these classes have no <code>private</code> fields, so they can just become <code>struct</code>s, which are <code>public</code> by default.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-02T22:06:12.477", "Id": "58863", "ParentId": "33386", "Score": "9" } }, { "body": "<p>I have a number of questions that you might find useful to answer for yourself with the idea of improving your code.</p>\n\n<h2>Are <code>read</code> and <code>send</code> really <code>const</code>?</h2>\n\n<p>It would be a most unusual implementation of a serial port class that didn't actually modify internal state when doing a <code>read</code> or <code>send</code> operation. These should probably not be declared <code>const</code>, including variations such as <code>readSome</code>.</p>\n\n<h2>Does <code>operator delete</code> need a header?</h2>\n\n<p>I suspect that you will want to <code>#include &lt;new&gt;</code> because that is where your <code>operator delete</code> is defined.</p>\n\n<h2>What about constructors?</h2>\n\n<p>This interface provides no constructors, which is probably not realistic. Specifically, if you're using <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow\">RAII</a>, the class would probably need to acquire a particular serial port and initialize it for use. It may also be a useful place to document default baudrate and timeout if you have such for your class. Your factory function <code>CreateSerialPort</code> would be most useful if it returned an initialized instance and that initialization is probably more reasonably the domain of the class itself rather than the factory class.</p>\n\n<h2>Do <code>readSome</code> and <code>read_n</code> never <code>throw</code> exceptions?</h2>\n\n<p>You have nicely documented the interface, including noting that <code>read</code> can <code>throw</code> a <code>SerialTimeout</code> exception. It seems likely that the other functions could also <code>throw</code> that exception unless they're blocking functions, in which case it would be nice to explicitly say. For example, <code>read_n</code> says that it uses <code>infinite timeout</code> which implies blocking without specifically saying so.</p>\n\n<h2>Have you run a spell check on comments?</h2>\n\n<p>If you run a spell check on your comments, you'll find a number of things such as \"aviable\" instead of \"available\" and \"rappresent\" instead of \"represent\". Since your code is nicely commented, it's worth the extra step to eliminate spelling errors.</p>\n\n<h2>What about <code>move</code> constructors?</h2>\n\n<p>Although your use of the class through <code>SerialPtr</code> seems intended to eliminate the possibility of inadvertent copies, the class can still be moved but the class provides no such call. This means that the compiler-provided <code>move</code> constructor will be used. This may be fine, but it's worth documenting in the interface if that is really your intent.</p>\n\n<h2>Does the factory actually create a <code>SerialPtr</code>?</h2>\n\n<p>If your factory function actually creates a <code>unique_ptr</code> rather than a mere instance pointer, it's probably worth saying so explicitly in the comments or in the declaration. I understand that there may be some problems in doing so due to the fact that you're passing things through a \"C\" interface because of the limitations of the Windows interface.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-03T13:53:02.450", "Id": "58914", "ParentId": "33386", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T11:09:56.447", "Id": "33386", "Score": "8", "Tags": [ "c++", "c++11", "library", "portability", "serial-port" ], "Title": "Serial port library across different compilers" }
33386
<p>Here is my code. It works fine but I need to make the code more efficient.</p> <pre><code>def o(s): l=len(s) return len(set([a+b+c for a in s for b in s for c in s]) )==l*(l+1)*(l+2)//6 M=int(input()) N=3**M i=1 s=M*[i] while i: if s[i]-N: s[i]=s[i]+1 if o(s[:i+1]): if i&lt;M-1: i=i+1 s[i]=s[i-1] else: N=s[-1] else: i=i-1 print(N) </code></pre> <p>Note: Input should be between 1 and 12. For the inputs 2,3,4 the code is efficient, but for inputs more than 4, it is taking too much time to run. How can I improve this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T09:55:30.423", "Id": "53465", "Score": "0", "body": "@Dilini: Have you profiled it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T09:57:53.523", "Id": "53466", "Score": "6", "body": "Could you explain what you are trying to do with this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T10:10:13.757", "Id": "53467", "Score": "2", "body": "If you want constructive answers to Python questions you should try writing the code in a readable style. Use good names for variables. For example instead of `l`, write `length`. It means that people can read your code. Without doing this people won't even bother taking the time to figure out what your code is trying to express." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T11:26:17.277", "Id": "53468", "Score": "0", "body": "If it's really important to get performance, then write it in C/C++ and bind python to it." } ]
[ { "body": "<p>It is not clear what this code is supposed to do. How can you possibly expect us to help you improve it if we can't understand it?</p>\n\n<p>For example, consider the function <code>o</code>. It takes a collection of numbers, \\$s\\$ (with length \\$l\\$), iterates over all triples \\$a, b, c\\$ of three elements from \\$s\\$ (with repetition), counts the number of distinct sums \\$ a + b + c \\$, and returns <code>True</code> if the number of distinct sums is equal to \\$ l+2 \\choose 3\\$.</p>\n\n<p>So for example, if you call <code>o([2, 3, 4])</code> then the set of distinct sums will be { \\$ 2+2+2 = 6 \\$, \\$2+2+3 = 7\\$, \\$2+2+4 = 8\\$, \\$2+3+4 = 9\\$, \\$2+4+4 = 10\\$, \\$3+4+4 = 11\\$, \\$4+4+4 = 12\\$ }, which has length 7, but \\$ l+2 \\choose 3\\$ is 10, so <code>o([2, 3, 4])</code> returns <code>False</code>.</p>\n\n<p>This seems like a strange function to want to compute. What is your motivation here? Maybe you have made a mistake and you really wanted to compute something else? How can we possibly help you when it's not clear what you want?</p>\n\n<p>Let me try to reverse engineer this function. When does <code>o</code> return <code>True</code>? Well, the number of sums of three numbers chosen with repetition from a collection of length \\$l\\$ is:</p>\n\n<p>$$ \\eqalign{ { l \\choose 3 } + l (l − 1) + l \n &amp;= { l (l − 1) (l − 2) \\over 6 } + l (l − 1) + l \\\\\n &amp;= { l (l + 1) (l + 2) \\over 6 } \\\\\n &amp;= { l + 2 \\choose 3 } }$$</p>\n\n<p>So <code>o</code> returns <code>True</code> if and only if all sums of three numbers chosen from \\$s\\$ (with repetition) are distinct. So why didn't you say so in the first place? All you had to do was to choose a good name for your function and write a <a href=\"http://docs.python.org/3/tutorial/controlflow.html#documentation-strings\" rel=\"nofollow\">docstring</a> and maybe a comment. Like this:</p>\n\n<pre><code>def distinct_triple_sums(s):\n \"\"\"Return True if all sums of three items chosen with repetition from\n the sequence 's' are distinct.\n\n \"\"\"\n # If the length of s is l, then there are C(l, 3) + l(l-1) + l =\n # C(l + 2, 3) different ways to choose three items from s with\n # repetition.\n # ... implementation here ...\n</code></pre>\n\n<p>What about the rest of the code? What does that do? Well, I added the line <code>print(i, s[:i+1], o(s[:i+1]))</code> in there, and this is the output when <code>M</code> is 3:</p>\n\n<pre><code>1 [1, 2] True\n2 [1, 2, 3] False\n2 [1, 2, 4] False\n2 [1, 2, 5] True\n1 [1, 3] True\n2 [1, 3, 4] False\n2 [1, 3, 5] False\n1 [1, 4] True\n2 [1, 4, 5] True\n1 [1, 5] True\n5\n</code></pre>\n\n<p>So it looks to me as though the original challenge must have been something like this:</p>\n\n<blockquote>\n <p>Given a number \\$M\\$, return the smallest number \\$N\\$ such that there exists a set \\$S\\$ of \\$M\\$ numbers between \\$1\\$ and \\$N\\$ inclusive such that all sums of three numbers from \\$S\\$ (chosen with repetition) are distinct.</p>\n</blockquote>\n\n<p>Is that right? And is Fawar right to say that this is a live <a href=\"http://www.ieee.org/membership_services/membership/students/competitions/xtreme/index.html\" rel=\"nofollow\">IEEEXtreme</a> problem? If so, it seems a bit remiss for you not to mention that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T15:33:01.720", "Id": "53469", "Score": "1", "body": "It is.... im doing the competition and trying to understand part of the code I ended up on this post..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T10:18:31.007", "Id": "33391", "ParentId": "33390", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-26T09:53:45.087", "Id": "33390", "Score": "-3", "Tags": [ "python", "performance", "combinatorics" ], "Title": "Distinct triple sums" }
33390
<p>I have written a <a href="http://en.wikipedia.org/wiki/Manchester_code" rel="noreferrer">Manchester Encoding</a> encoder / decoder based on my misconception of how it works (<em>whoops</em>). My encoder accepts an array of ones and zeroes, and returns the 'manchester encoded' data (pretending there is a constant clock to overlay onto the data). I am reasonably new to C++, and would like to advance my knowledge and coding skill in it, hence why I coded this small application. I am looking for ways to improve my code, as well as ways to increase its efficiency.</p> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "Manchester.h" int main() { int data[] = { 1, 1, 0, 0 }; // Some unencoded data int* encoded = Manchester::encode(data, 4); int* decoded = Manchester::decode(encoded, 8); return 0; } </code></pre> <p><strong>Manchester.cpp</strong></p> <pre><code>#include "Manchester.h" #include &lt;stdexcept&gt; #include &lt;sstream&gt; #include &lt;cstring&gt; #include &lt;cstdlib&gt; #ifdef DEBUG #include &lt;iostream&gt; #endif int *Manchester::encode(int *data, int length) { int *output = new int[length * 2]; for (int i = 0; i &lt; length; i++) { // Work out the array indexes to use int bid = i * 2; int nbid = bid + 1; // Get the data int real = data[i]; int bit = 0; int nbit = 0; // Work out what it is switch (real) { case 0: bit = MANCHESTER_ZERO[0] - '0'; // Subtract 48 to work out the real value nbit = MANCHESTER_ZERO[1] - '0'; break; case 1: bit = MANCHESTER_ONE[0] - '0'; // Subtract 48 to work out the real value nbit = MANCHESTER_ONE[1] - '0'; break; } #ifdef DEBUG std::cout &lt;&lt; "[encode] " &lt;&lt; real &lt;&lt; " [" &lt;&lt; bit &lt;&lt; nbit &lt;&lt; "]" &lt;&lt; std::endl; #endif output[bid] = bit; output[nbid] = nbit; } return output; } int *Manchester::decode(int *data, int length) { if ((length % 2) != 0) { throw std::range_error("length is not a multiple of 2"); } int *output = new int[length / 2]; for (int i = 0; i &lt; (length / 2); i++) { // Work out the array indexes to use int bid = i * 2; int nbid = bid + 1; // Get the data int bit = data[bid]; int nbit = data[nbid]; // Put the data into a stringstream for comparison std::stringstream con; con &lt;&lt; bit &lt;&lt; nbit; const char* sbit = con.str().c_str(); int real = 0; // Compare the data and work out the value if (strcmp(sbit, MANCHESTER_ONE) == 0) { real = 1; } else if (strcmp(sbit, MANCHESTER_ZERO) == 0) { real = 0; } #ifdef DEBUG std::cout &lt;&lt; "[decode] bit: " &lt;&lt; bit &lt;&lt; nbit &lt;&lt; " [" &lt;&lt; real &lt;&lt; "]" &lt;&lt; std::endl; #endif output[i] = real; } return output; } </code></pre> <p><strong>Manchester.h</strong></p> <pre><code>#ifndef MANCHESTER_H #define MANCHESTER_H #define DEBUG #define MANCHESTER_ONE "01" #define MANCHESTER_ZERO "10" class Manchester { public: static int *encode(int *data, int length); static int *decode(int *data, int length); }; #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T18:21:59.870", "Id": "53518", "Score": "2", "body": "You shouldn't return and use a local dynamic variable. You must free it up before going out of scope, see this post about [memory leak](http://stackoverflow.com/questions/6261201/how-to-find-memory-leak-in-c-code-project). Also, I don't see the logic by making the length of `decode` twice in `encode` since you will divide it to half w/c is equal to length of array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:37:36.027", "Id": "53570", "Score": "0", "body": "Ah yes, I just spotted the useless dividing and multiplying inside encode, thanks ^_^ I'll take a look at the memory leak post too :)" } ]
[ { "body": "<h1>Manipulating bits</h1>\n\n<p>One of the areas where your code may be improved is the way it handles and compares bits. You are using <code>char*</code> strings to represent bits while you could have used <code>unsigned</code> values and bitwise operations to speed up most of your operations. Actually, you should even replace every <code>int</code> representing bits by <code>unsigned</code> since the representation of <code>unsigned</code> values is known and they are the tool to use when representing bits.</p>\n\n<ul>\n<li><p>You can replace the <code>MANCHESTER_ONE</code> and <code>MANCHESTER_ZERO</code> definitions by:</p>\n\n<pre><code>#define MANCHESTER_ONE 1u\n#define MANCHESTER_ZERO 2u\n</code></pre>\n\n<p><code>1u</code> is <code>0b01</code> in binary and <code>2u</code> is <code>0b10</code>.</p></li>\n<li><p>Then you can change the following bit of code in <code>encode</code>:</p>\n\n<pre><code>switch (real)\n{\ncase 0:\n bit = MANCHESTER_ZERO[0] - '0'; // Subtract 48 to work out the real value\n nbit = MANCHESTER_ZERO[1] - '0';\n break;\ncase 1:\n bit = MANCHESTER_ONE[0] - '0'; // Subtract 48 to work out the real value\n nbit = MANCHESTER_ONE[1] - '0';\n break;\n}\n</code></pre>\n\n<p>By the way, the <code>switch</code> is useless since your are only checking for two values. You can replace it by a regular <code>if</code>:</p>\n\n<pre><code>if (real == 0)\n{\n bit = (MANCHESTER_ZERO &gt;&gt; 1) &amp; 1;\n nbit = MANCHESTER_ZERO &amp; 1;\n}\nelse // real == 1\n{\n bit = (MANCHESTER_ONE &gt;&gt; 1) &amp; 1;\n nbit = MANCHESTER_ONE &amp; 1;\n}\n</code></pre>\n\n<p>Since we replaced the strings <code>MANCHESTER_*</code> by <code>unsigned</code> values, we use bitwise <code>AND</code>s instead of array subtracts.</p></li>\n<li><p>A gain in efficiency may be obtained by refactoring this piece of code:</p>\n\n<pre><code>// Put the data into a stringstream for comparison\nstd::stringstream con;\ncon &lt;&lt; bit &lt;&lt; nbit;\nconst char* sbit = con.str().c_str();\n\nint real = 0;\n\n// Compare the data and work out the value\nif (strcmp(sbit, MANCHESTER_ONE) == 0)\n{\n real = 1;\n} else if (strcmp(sbit, MANCHESTER_ZERO) == 0) {\n real = 0;\n}\n</code></pre>\n\n<p><code>std::stringstream</code> is known to be slow since you have to convert your integer values into strings first before performing operations on them. In a <code>for</code> loop, it may be a big performance loss. Here is how you can refactor this bit of code:</p>\n\n<pre><code>// Put the bits in an unsigned\nunsigned sbit = (bit &lt;&lt; 1) | nbit;\n\n// Check only for MANCHESTER_ONE,\n// assuming that it will be equal\n// to MANCHESTER_ZERO if not\nint real = int(sbit == MANCHESTER_ONE);\n</code></pre>\n\n<p>As said in the comments, I make the assumption that once computed, <code>sbit</code> can only be equal to <code>MANCHESTER_ONE</code> or <code>MANCHESTER_ZERO</code> and nothing else.</p></li>\n</ul>\n\n<h1>General advice about C++</h1>\n\n<p>I cannot see any hint that you are using C++11, therefore I will review your code as C++03 code:</p>\n\n<ul>\n<li>As said in the comments, allocating memory in a function and not deallocating it is not a good idea. You should simply use a <code>std::vector</code> to represent your arrays of numbers.</li>\n<li><code>#define</code> is to be avoided whenever possible in C++. Consider using <code>const</code> variables instead.</li>\n<li>The standard way to check whether you are debugging is <code>#ifndef NDEBUG</code> (the double negative is kind of ugly, but it's the standard way).</li>\n<li>In C++, it is useless to write <code>return 0;</code> at the end of <code>main</code>. If no <code>return</code> statement is given, the compiler will add an implicit <code>return 0;</code>.</li>\n<li>If the <code>MANCHESTER_*</code> constants are not used anywhere else, you can define them as <code>private</code> <code>static const</code> variables of the class <code>Machester</code>.</li>\n</ul>\n\n<hr>\n\n<p>Here is your code once refactored:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;vector&gt;\n\nclass Manchester\n{\npublic:\n\n static std::vector&lt;unsigned&gt; encode(const std::vector&lt;unsigned&gt;&amp; data, unsigned length)\n {\n std::vector&lt;unsigned&gt; output(length * 2);\n\n for (unsigned i = 0; i &lt; length; i++)\n {\n\n // Work out the array indexes to use\n unsigned bid = i * 2;\n unsigned nbid = bid + 1;\n\n // Get the data\n unsigned real = data[i];\n\n unsigned bit = 0;\n unsigned nbit = 0;\n\n // Work out what it is\n if (real == 0)\n {\n bit = (ZERO &gt;&gt; 1) &amp; 1;\n nbit = ZERO &amp; 1;\n }\n else // real == 1\n {\n bit = (ONE &gt;&gt; 1) &amp; 1;\n nbit = ONE &amp; 1;\n }\n\n #ifndef NDEBUG\n std::cout &lt;&lt; \"[encode] \" &lt;&lt; real &lt;&lt; \" [\" &lt;&lt; bit &lt;&lt; nbit &lt;&lt; \"]\" &lt;&lt; std::endl;\n #endif\n\n output[bid] = bit;\n output[nbid] = nbit;\n }\n\n return output;\n }\n\n static std::vector&lt;unsigned&gt; decode(const std::vector&lt;unsigned&gt;&amp; data, unsigned length)\n {\n if ((length % 2) != 0)\n {\n throw std::range_error(\"length is not a multiple of 2\");\n }\n\n std::vector&lt;unsigned&gt; output(length / 2);\n\n for (unsigned i = 0; i &lt; (length / 2); i++)\n {\n // Work out the array indexes to use\n unsigned bid = i * 2;\n unsigned nbid = bid + 1;\n\n // Get the data\n unsigned bit = data[bid];\n unsigned nbit = data[nbid];\n\n // Put the data into an unsigned int\n unsigned sbit = (bit &lt;&lt; 1) | nbit;\n\n // Check only for MANCHESTER_ONE,\n // assuming that it will be equal\n // to MANCHESTER_ZERO if not\n unsigned real = unsigned(sbit == ONE);\n\n #ifndef NDEBUG\n std::cout &lt;&lt; \"[decode] bit: \" &lt;&lt; bit &lt;&lt; nbit &lt;&lt; \" [\" &lt;&lt; real &lt;&lt; \"]\" &lt;&lt; std::endl;\n #endif\n\n output[i] = real; \n }\n return output;\n }\n\nprivate:\n\n static const unsigned ONE;\n static const unsigned ZERO;\n};\n\nconst unsigned Manchester::ONE = 1u;\nconst unsigned Manchester::ZERO = 2u;\n\n\nint main()\n{\n typedef std::vector&lt;unsigned&gt; vec_t;\n\n // Some unencoded data\n unsigned data[] = { 1u, 1u, 0u, 0u };\n // Initialize vector with array\n vec_t vec(data, data+sizeof(data) / sizeof(unsigned));\n\n vec_t encoded = Manchester::encode(vec, 4);\n vec_t decoded = Manchester::decode(encoded, 8);\n}\n</code></pre>\n\n<p>You can find a live working version <a href=\"http://coliru.stacked-crooked.com/a/8380911333b19863\" rel=\"nofollow noreferrer\">here</a> at Coliru.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2014-03-21T09:09:15.073", "Id": "44946", "ParentId": "33396", "Score": "7" } } ]
{ "AcceptedAnswerId": "44946", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:10:00.360", "Id": "33396", "Score": "7", "Tags": [ "c++", "optimization", "beginner", "array" ], "Title": "Manchester encoder/decoder" }
33396
<p>I made this program in C that tests if a number is prime. I'm as yet unfamiliar with Algorithm complexity and all that Big O stuff, so I'm unsure if my approach, which is a <strong>combination of iteration and recursion</strong>, is actually more efficient than using a <strong>purely iterative</strong> method.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; typedef struct primenode{ long int key; struct primenode * next; }primenode; typedef struct{ primenode * head; primenode * tail; primenode * curr; unsigned long int size; }primelist; int isPrime(long int number, primelist * list ,long int * calls, long int * searchcalls); primenode * primelist_insert(long int prime, primelist * list); int primelist_search(long int searchval, primenode * searchat, long int * calls); void primelist_destroy(primenode * destroyat); int main(){ long int n; long int callstoisprime = 0; long int callstosearch = 0; int result = 0; primelist primes; //Initialize primelist primes.head = NULL; primes.tail = NULL; primes.size = 0; //Insert 2 as a default prime (optional step) primelist_insert(2, &amp;primes); printf("\n\nPlease enter a number: "); scanf("%d",&amp;n); printf("Please wait while I crunch the numbers..."); result = isPrime(n, &amp;primes, &amp;callstoisprime, &amp;callstosearch); switch(result){ case 1: printf("\n%ld is a prime.",n); break; case -1: printf("\n%ld is a special case. It's neither prime nor composite.",n); break; default: printf("\n%ld is composite.",n); break; } printf("\n\n%d calls made to function: isPrime()",callstoisprime); printf("\n%d calls made to function: primelist_search()",callstosearch); //Print all prime numbers in the linked list printf("\n\nHere are all the prime numbers in the linked list:\n\n"); primes.curr = primes.head; while(primes.curr != NULL){ printf("%ld ", primes.curr-&gt;key); primes.curr = primes.curr-&gt;next; } printf("\n\nNote: Only primes up to the square root of your number are listed.\n" "If your number is negative, only the smallest prime will be listed.\n" "If your number is a prime, it will itself be listed.\n\n"); //Free up linked list before exiting primelist_destroy(primes.head); return 0; } int isPrime(long int number, primelist * list ,long int * calls, long int *searchcalls){ //Returns 1 if prime // 0 if composite // -1 if special case *calls += 1; long int i = 2; if(number==0||number==1){ return -1; } if(number&lt;0){ return 0; } //Search for it in the linked list of previously found primes if(primelist_search(number, list-&gt;head, searchcalls) == 1){ return 1; } //Go through all possible prime factors up to its square root for(i = 2; i &lt;= sqrt(number); i++){ if(isPrime(i, list,calls,searchcalls)){ if(number%i==0) return 0; //It's not a prime } } primelist_insert(number, list); /*Insert into linked list so it doesn't have to keep checking if this number is prime every time*/ return 1; } primenode * primelist_insert(long int prime, primelist * list){ list-&gt;curr = malloc(sizeof(primenode)); list-&gt;curr-&gt;next = NULL; if(list-&gt;head == NULL){ list-&gt;head = list-&gt;curr; } else{ list-&gt;tail-&gt;next = list-&gt;curr; } list-&gt;tail = list-&gt;curr; list-&gt;curr-&gt;key = prime; list-&gt;size += 1; return list-&gt;curr; } int primelist_search(long int searchval, primenode * searchat, long int * calls){ *calls += 1; if(searchat == NULL) return 0; if(searchat-&gt;key == searchval) return 1; return primelist_search(searchval, searchat-&gt;next, calls); } void primelist_destroy(primenode * destroyat){ if(destroyat == NULL) return; primelist_destroy(destroyat-&gt;next); free(destroyat); return; } </code></pre> <p>Basically, a lot of what I've seen simple primalty tests do is: 0. 2 is a prime. 1. Cycle through all integers from 2 to half or the square root of the number being tested. 2. If the number is divisible by anything, break and return false; it's composite. 3. Otherwise, return true after the last iteration; it's prime.</p> <p>I figured that you don't have to test against every number from 2 to the square root, just every prime number, because all other numbers are multiples of primes. So, the function calls itself to find out if a number is prime before using the modulus on it. This works, but I thought it a bit tedious to keep testing all those primes over and over again. So, I used a linked list to store every prime found in it as well, so that before testing primalty, the program searches the list first.</p> <p>Is it really faster, or more efficient, or did I just waste a lot of time? I did test it on my computer, and for the larger primes it did seem faster, but I'm not sure. I also don't know if it uses significantly more memory since Task Manager just stays a constant 0.7 MB whatever I do.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T10:48:30.133", "Id": "53775", "Score": "1", "body": "Recursion _never_ gives the fastest possible algorithm, because the function calling/return overhead takes far longer to execute than the actual comparison. Also, recursion likely forces the program to use stack where it could have used CPU registers. If you want the fastest possible algorithm, start with unrolling the recursion to a plain loop." } ]
[ { "body": "<p>So after looking at this we can do some basic BigO analysis(recursion aside)</p>\n\n<p>so we have your number linked list(O(n)) + prime function(O(sqrt(n)) so lets just go with O(n) since it is larger so really yes this way is slower for smaller numbers since primes tend to be closer together when numbers are small.</p>\n\n<p>You are also using memory to store that linked list which does grow as the number of primes grow. I'm not sure the added complexity is really worth the possible benefits you are receiving here for larger numbers(although I'm not quite sure where the tipping point begins to tip in your favor) maybe when you reached n > sqrt(number of primes below n?)</p>\n\n<p>If you are really looking for possible speed boosts maybe use something like a dictionary to store your prime numbers O(1) or really anything that has a better look up than O(n) but again you'll be using memory as a consequence.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T21:18:54.307", "Id": "33680", "ParentId": "33397", "Score": "2" } } ]
{ "AcceptedAnswerId": "33680", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T13:11:44.293", "Id": "33397", "Score": "6", "Tags": [ "c", "performance", "recursion", "primes", "iteration" ], "Title": "Is a Recursive-Iterative Method Better than a Purely Iterative Method to find out if a number is prime?" }
33397
<p><a href="https://www.codeeval.com/open_challenges/45/" rel="nofollow">This is one of codeeval challenges</a></p> <blockquote> <p><strong>Challenge Description:</strong></p> <p>Credits: Programming Challenges by Steven S. Skiena and Miguel A. Revilla </p> <p>The problem is as follows: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure. E.g.</p> <p>195 (initial number) + 591 (reverse of initial number) = 786</p> <p>786 + 687 = 1473</p> <p>1473 + 3741 = 5214</p> <p>5214 + 4125 = 9339 (palindrome) In this particular case the palindrome 9339 appeared after the 4th addition. This method leads to palindromes in a few step for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It is not proven though, that there is no such a palindrome.</p> </blockquote> <p>Here is my solution for it:</p> <pre><code>#!/usr/bin/env python import sys """ I've done some tests with timeit and it seems that both numeric and string version have the same performance (at least for numbers &lt; 10000) # def reverse_num(num): # rev = 0 # while(num &gt; 0): # rev = (10*rev)+num%10 # num //= 10 # return rev """ def reverse(num): """Reverses the number &gt;&gt;&gt; reverse(1456) 6541 &gt;&gt;&gt; reverse(111) 111 """ return int(str(num)[::-1]) def palindrome(num): """Return the number of iterations required to compute a palindrome &gt;&gt;&gt; palindrome(195) (4, 9339) """ # compute in 100 iterations or less for i in range(100): rnum = reverse(num) if rnum == num: break num = num + rnum return (i, num) if __name__ == "__main__": with open(sys.argv[1]) as f: for line in f: print "%s %s" % palindrome(int(line)) </code></pre> <p>Any remarks on the code style, on the algorithm itself?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T16:18:53.387", "Id": "53500", "Score": "0", "body": "Two comments: Probably nice to error-handle cases where it blew past a 100 iterations (vs. finishing exactly on iteration 100! :)) Also for curiosity's sake, did you re-write palindrome(num) using recursion to see if there would be a performance hit and by how much?" } ]
[ { "body": "<p>Only 2 things:</p>\n\n<ol>\n<li><p>Why do you have this? This makes your code a bit unclear and confusing. Remove this if you do not want to use it as it might make your actual code look messy.</p>\n\n<pre><code># def reverse_num(num):\n# rev = 0\n# while(num &gt; 0):\n# rev = (10*rev)+num%10\n# num //= 10\n# return rev\n</code></pre></li>\n<li><p>It is discouraged to use <code>for i in range(100):</code> in Python.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T16:29:07.967", "Id": "54120", "Score": "0", "body": "I assume that your comment in 2 indicates that using enumerate was more idiomatic?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T13:29:08.970", "Id": "58111", "Score": "2", "body": "`for i in range(100)` is in good use here. Could be `xrange` instead on Python 2, though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-03T22:15:26.727", "Id": "33757", "ParentId": "33403", "Score": "1" } }, { "body": "<p>Comments from an <a href=\"https://codereview.stackexchange.com/a/133653/9452\">answer to another question</a> apply here to the commented function <code>reverse_num</code>:</p>\n\n<p><strong><code>divmod</code></strong></p>\n\n<p>In Python, when you are performing arithmetic and are interested in both the quotient and the remainder of a division, you can use <a href=\"https://docs.python.org/2/library/functions.html#divmod\" rel=\"nofollow noreferrer\"><code>divmod</code></a>.</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>You have <code>10</code> hardcoded in multiple places. My preference is to use a default argument giving the base to use.</p>\n\n<pre><code>def reverse(integer, base=10):\n result = 0\n while integer:\n integer, r = divmod(integer, base)\n result = base * result + r\n return result\n</code></pre>\n\n<hr>\n\n<p><strong>More specific comments</strong></p>\n\n<ul>\n<li><p>The documentation for <code>palindrome</code> is somewhat imprecise. It implies that it returns a number but it actually returns a tuple.</p></li>\n<li><p><code>num = num + rnum</code> can be re-written <code>num += rnum</code></p></li>\n<li><p>it may be interesting to memoize any result you compute so that you do not it to spend time to compute it later on. This needs some benchmarking to be sure this is relevant.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-05T15:22:02.290", "Id": "133950", "ParentId": "33403", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T15:12:23.463", "Id": "33403", "Score": "4", "Tags": [ "python", "programming-challenge", "palindrome" ], "Title": "Reverse and Add: find a palindrome" }
33403
<p>I am learning from <em>C++ Primer</em> 5th edition. This is exercise 5.17:</p> <blockquote> <p>Given two vectors of ints, write a program to determine whether one vector is a prefix of the other. For vectors of unequal length, compare the number of elements of the smaller vector. For example, given the vectors containing 0, 1, 1, and 2 and 0, 1, 1, 2, 3, 5, 8, respectively your program should return true.</p> </blockquote> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; using std::cin; using std::cout; using std::endl; using std::string; using std::vector; using std::end; using std::begin; int main() { vector&lt;int&gt; i{0,1,1,2}, n{0,1,1,2,3,5,8}, smlr; char sml, bgr; long j = (i.end()-i.begin()) ,k = (n.end()-n.begin()); if ( j &gt; k) { sml = 'n', bgr = 'i', smlr = n; } else if (j &lt; k) { sml = 'i', bgr = 'n', smlr = i; } else if ( j == k) { cout &lt;&lt; "both are of equal length"; for (vector&lt;int&gt;::size_type a = 0; a &lt; i.size() ; ++a ) { if (i[a] != n[a]) { cout &lt;&lt; "both vectors are unequal and are not prefixes of the other"; return -1; } } } for ( int l = 0; l &lt; smlr.size() &amp;&amp; i[l] == n[l]; ++l ) { if(l == (smlr.size()-1)) { cout &lt;&lt; sml &lt;&lt; " is a prefix of " &lt;&lt; bgr; return 0; } } cout &lt;&lt; sml &lt;&lt; " is not a prefix of " &lt;&lt; bgr; return 0; } </code></pre> <ol> <li>Is my code efficient?</li> <li>Am I using too many variables?</li> <li>Is it better to write more code and use less variables or use less variables and less code?</li> </ol> <p>I am a beginner, so please be harsh.</p>
[]
[ { "body": "<p>Ok first, we want to determine if some condition is true or not based on some input. That calls for a boolean function! In particular, our inputs are two vectors. :</p>\n\n<pre><code>bool isPrefixOf(const std::vector&lt;int&gt;&amp; smaller, const std::vector&lt;int&gt;&amp; larger) \n{\n ...\n}\n</code></pre>\n\n<p>I named the first variable <code>smaller</code>, but it might not actually be smaller! Let's make sure that it is:</p>\n\n<pre><code> if (smaller.size() &gt; larger.size())\n {\n std::swap(smaller, larger); // this very efficiently swaps our vectors\n // in constant time\n }\n</code></pre>\n\n<p>Now once we got that, the algorithm in your <code>j == k</code> is exactly correct, but pretty hard to read. The convention is to use variables like <code>i</code>, <code>j</code>, <code>k</code> solely as indices in loops, not as important variables. So I'll rewrite it like this:</p>\n\n<pre><code> for (int i = 0; i &lt; smaller.size(); ++i) \n {\n if (smaller[i] != larger[i]) \n {\n return false; // clearly not a prefix\n }\n }\n\n return true; // we match up, so we must be done!\n}\n</code></pre>\n\n<p>So cool, we got our function that checks if a smaller vector is a prefix of a larger vector, so now our main just has to determine which way we call it:</p>\n\n<pre><code>int main() \n{\n vector&lt;int&gt; vec1{0, 1, 1, 2};\n vector&lt;int&gt; vec2{0, 1, 1, 2, 3, 5, 8};\n\n cout &lt;&lt; \"vec1 is a prefix of vec2?: \" &lt;&lt; isPrefixOf(vec1, vec2) &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Which should print true. So in general, your variable names don't line up with convention, and you coded the same logic twice - don't repeat yourself! Take advantage of functions to encode conceptually distinct functionality. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T16:21:22.093", "Id": "53501", "Score": "0", "body": "Hey! Thanks for the reply! I will take precautions from now on… I am trying to use the code you posted but it keeps showing an error:\nNo matching function for call to ‘swap’\nI am using Xcode 4.6.3 and added the header <utility>" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T16:24:48.930", "Id": "53503", "Score": "0", "body": "I added that too but still the same error persists.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T17:27:23.140", "Id": "53508", "Score": "0", "body": "I copy pasted your code.. I finally replaced std::swap(smaller, larger); with larger.swap(smaller); and still it didn’t work. [This](http://stackoverflow.com/questions/8867302/vectortswap-and-temporary-object) helped me figure out the problem.. The arguments for isPrefixOf() are consts but swap cannot have consts as arguments. As its essentially changing both the objects. *Phew*" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T21:34:43.383", "Id": "53540", "Score": "0", "body": "If the order of the arguments is interchangeable, then I would prefer to see them named symmetrically. As written, I would assume that it only checks for `smaller` being a prefix of `larger`, and not _vice versa_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T21:36:06.887", "Id": "53541", "Score": "0", "body": "To preserve `const`ness, instead of using `std::swap()`, have `isPrefixOf(a, b)` call itself as `isPrefixOf(b, a)` if `a` is longer than `b`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T05:43:23.597", "Id": "53563", "Score": "0", "body": "@200_success I maintained const-ness by replacing the arguments with pointers as the values of the pointers aren’t const they can be swapped and the values at the addresses of the pointers are const they cannot be changed." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T15:42:21.333", "Id": "33405", "ParentId": "33404", "Score": "3" } } ]
{ "AcceptedAnswerId": "33405", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T15:25:17.927", "Id": "33404", "Score": "3", "Tags": [ "c++", "optimization", "beginner" ], "Title": "Determining whether one vector is a prefix of the other" }
33404
<p>Essentially I'm attempting to select the top read (based on <code>read_date</code>), and check if it has a <code>type in ( 'R','S','C','B','Q','F','I','A')</code></p> <pre><code>select * from ( select * from ( select * FROM table WHERE id = 369514 order by read_date desc ) where rownum = 1 ) where type IN ( 'R','S','C','B','Q','F','I','A') </code></pre> <p>I only need to return a row if the top row has a type in the set, if not return nothing.</p> <p>The only way I seem to be able to is using all these nasty sub-queries.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T13:51:42.247", "Id": "53589", "Score": "0", "body": "is this Query slow? is it inefficient?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T21:06:08.383", "Id": "53628", "Score": "0", "body": "not slow, just looked like it could probably be improved" } ]
[ { "body": "<p>I was looking at the Query and you should be able to get rid of the outside Select.</p>\n\n<pre><code>select *\nfrom (\n select *\n FROM table\n WHERE id = 369514\n order by read_date desc\n )\nwhere rownum = 1 AND type IN ( 'R','S','C','B','Q','F','I','A')\n</code></pre>\n\n<p>I don't have anything to Test against, but it looks like this would work. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T21:24:09.633", "Id": "53630", "Score": "1", "body": "I've actually realised this myself and removed it. I've upvoted :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T13:55:08.170", "Id": "33460", "ParentId": "33407", "Score": "3" } } ]
{ "AcceptedAnswerId": "33460", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T16:20:04.717", "Id": "33407", "Score": "3", "Tags": [ "sql", "oracle" ], "Title": "Oracle nested query" }
33407
<p>I've nearly got this working. I wanted to know if there is a <em>much</em> better way. One problem is that no matter what there will be cases where a URL is incorrectly identified and as such the end result will be dependent on requirements. My requirements are lackadaisy, I just want something that works most of the time. However some of the URLs in my fiddle are not being detected correctly and I'd like advice on the regex part of this for overcome these. The main issue here is that the overall design is in question, the should be a simpler method.</p> <p><a href="https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links">Root problem</a></p> <p><a href="http://jsfiddle.net/EwzcD/" rel="nofollow noreferrer">Fiddle</a></p> <pre><code>function replaceURLWithHTMLLinks(text) { text = text.replace(/a/g, "--ucsps--"); text = text.replace(/b/g, "--uspds--"); var arrRegex = [ /(\([^)]*\b)((?:https?|ftp|file):\/\/[-A-Za-z0-9+&amp;@#\/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#\/%=~_()|])(.?\))/ig, /()(\b(?:https?|ftp|file):\/\/[-a-z0-9+&amp;@#\/%?=~_()|!:,.;]*[-a-z0-9+&amp;@#\/%=~_()|])(.?\b)/ig]; for (i = 0; i &lt; arrRegex.length; i++) { text = text.replace(arrRegex[i], "$1a$2b$3"); } text = text.replace(/a([^b]*)b/g, "&lt;a href='$1'&gt;$1&lt;/a&gt;"); text = text.replace(/--ucsps--/g, "a"); text = text.replace(/--uspds--/g, "b"); return text; } var elm = document.getElementById('trythis'); elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML); </code></pre> <p>Any thoughts?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T20:27:11.383", "Id": "53534", "Score": "0", "body": "what browser are you using? all of the links show up for me in chrome. and the code seems to be working. I am not very good at JavaScript, but there doesn't seem to be anything that really jumps out at me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T01:43:59.450", "Id": "53552", "Score": "1", "body": "I think that this contains code that does what the OP wants it too, but the OP wants a Better way to Handle what it does. the OP doesn't need the Javascript to catch all of the URLS just Most of them, right??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T16:49:55.023", "Id": "53596", "Score": "1", "body": "I'm using Chromium. Some of the URLs have extra 'junk' at the end. Specifically the last few have \".\" and \".)\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T16:51:28.347", "Id": "53597", "Score": "1", "body": "I'd like as many browsers to catch as many URLs as possible. This should be common code that everyone can use for any project, I'm amazed that there are so few good examples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T01:22:32.847", "Id": "53653", "Score": "0", "body": "@Malachi “some of the URLs […] are not being detected correctly and I'd like advice […] to overcome these” That sounds to me like it doesn't work the way Mike wants." } ]
[ { "body": "<p>I think that it's nutty to replace all characters 'a' and 'b' with junk, then un-replace them later, just so that you can use 'a' and 'b' as landmarks to indicate which points your two regular expressions have in common. If you're going to do that, then why not just use \"--ucsps--\" and \"--uspds--\" as your landmarks in the first place? Of course, using any special strings as landmarks is a bad idea.</p>\n\n<p>The fundamental problem is that you want to exclude the same number of closing parentheses as there are open parentheses. You can't use a regular expression to match left and right parentheses, because such an expression would not be regular. Well, some flavours of \"regular\" expressions support backreferences within the expression itself, which could do the job. RegExps in JavaScript don't.</p>\n\n<p>What JavaScript <em>can</em> do, though, is let you specify your own code to generate the replacement text. Here's what I came up with:</p>\n\n<pre><code>function replaceURLWithHTMLLinks(text) {\n var re = /(\\(.*?)?\\b((?:https?|ftp|file):\\/\\/[-a-z0-9+&amp;@#\\/%?=~_()|!:,.;]*[-a-z0-9+&amp;@#\\/%=~_()|])/ig;\n return text.replace(re, function(match, lParens, url) {\n var rParens = '';\n lParens = lParens || '';\n\n // Try to strip the same number of right parens from url\n // as there are left parens. Here, lParenCounter must be\n // a RegExp object. You cannot use a literal\n // while (/\\(/g.exec(lParens)) { ... }\n // because an object is needed to store the lastIndex state.\n var lParenCounter = /\\(/g;\n while (lParenCounter.exec(lParens)) {\n var m;\n // We want m[1] to be greedy, unless a period precedes the\n // right parenthesis. These tests cannot be simplified as\n // /(.*)(\\.?\\).*)/.exec(url)\n // because if (.*) is greedy then \\.? never gets a chance.\n if (m = /(.*)(\\.\\).*)/.exec(url) ||\n /(.*)(\\).*)/.exec(url)) {\n url = m[1];\n rParens = m[2] + rParens;\n }\n }\n return lParens + \"&lt;a href='\" + url + \"'&gt;\" + url + \"&lt;/a&gt;\" + rParens;\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T16:53:16.717", "Id": "53598", "Score": "1", "body": "This [works](http://jsfiddle.net/EwzcD/1/) very well, thank you! I plan on extending this to support other brackets." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T00:50:22.383", "Id": "33425", "ParentId": "33412", "Score": "2" } } ]
{ "AcceptedAnswerId": "33425", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T18:08:02.547", "Id": "33412", "Score": "2", "Tags": [ "javascript", "regex" ], "Title": "How to replace plain URLs with links, in javascript?" }
33412
<p>I am thinking of writing some online notes/book. Amongst other things, I want to use Backbone to show different sections within a chapter as separate views. In other words, I want each chapter to behave like a single page application; different chapters will behave as separate single page applications. Within a chapter, as the user navigates from one section to another, I don't want the page to reload and am thinking of using the Backbone router to show these section views.</p> <p>Please take a quick look at the code below and let me know if you see anything problematic with how I am using Backbone routing to render views.</p> <p>The code works, but I want to know if I am doing anything inefficiently and if there are any "good practice" principles that I am violating. For example, I create new view instance every time the route changes. Is there a way to do this better?</p> <pre><code>(function() { var bApp = { model: {}, view: {}, collection: {}, router: {} }; window.bApp = bApp; bApp.view.section = Backbone.View.extend({ el: 'div#chapter2', template: nunjucks.render('./client/views/client-templates/ch2_sec2.html'), render: function() { this.$el.html(this.template); return this; } }); bApp.router = Backbone.Router.extend({ routes: { '': 'showroute_ch2sec1', 'ch2sec1': 'showroute_ch2sec1', 'ch2sec2': 'showroute_ch2sec2' }, showroute_ch2sec1: function() { section1 = new bApp.view.section; section1.template = nunjucks.render('./client/views/client-templates/ch2_sec1.html'); section1.render(); }, showroute_ch2sec2: function() { section2 = new bApp.view.section; section2.template = nunjucks.render('./client/views/client-templates/ch2_sec2.html'); section2.render(); } }); var r = new bApp.router; Backbone.history.start(); })(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T21:43:52.967", "Id": "53524", "Score": "0", "body": "Do you have a `<div id=\"chapter2\">` in the DOM? Are you sure you want to render both views into the same element?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T22:01:01.440", "Id": "53525", "Score": "0", "body": "Sorry for the wrong title. The code works. I had chosen the title earlier when it was not working and then I got it to work. When I wrote the question above I forgot to change the title. My question is that since I am so new to Backbone I wanted to know whether there are any clearly \"bad approaches\" that I am using. The code, however, works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T12:39:45.627", "Id": "53526", "Score": "0", "body": "@SeanVieira I was not aware of that site. Can you move the question there, or do I have to do it myself? Would appreciate instructions on how to do so, if I am supposed to do move it to that site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T14:35:25.473", "Id": "53527", "Score": "0", "body": "@Curious2learn - unfortunately, I do not have the power to do this myself - I'll flag it for moderator attention and see if they can do it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T19:16:06.543", "Id": "53528", "Score": "1", "body": "@SeanVieira: I flagged it too. I'll try to keep an eye on it and give it a review once it has moved." } ]
[ { "body": "<p>A few minor tweaks could help you out:</p>\n\n<ul>\n<li>Add a <code>close</code> method to all of your views, which cleans up your DOM, and unbinds any bound events (eg, with <code>this.stopListening()</code>). This will prevent 'zombie events' -- events bound to views which are no longer rendered.</li>\n<li>Move the logic for switching pages to a high-level application contoller. This will keep your router from getting too logic-heavy, and will allow the application controller to handle view creation and cleanup.</li>\n</ul>\n\n<p>Here's how I might approach it.</p>\n\n<pre><code>// If all of your section views behave similarly\n// why not create a single base class\nbApp.view.Section = Backbone.View.extend({\n initialize: function(options) {\n this.template = options.template;\n },\n render: function() {\n var html = nunjucks.render(this.template);\n this.$el.html(html);\n return this;\n },\n close: function() {\n this.$el.empty();\n this.$el.off();\n this.stopListening();\n\n // Any other cleanup can go here...\n }\n}); \n\nbApp.Router = Backbone.Route.extend({\n routes: {\n // Use route parameters, to simplify routing\n 'book/:ch/:sec': 'navigateToSection'\n },\n\n navigateToSection: function(ch, sec) {\n // Delegate view-switching logic to application\n bApp.show(ch, sec);\n }\n});\n\nbApp.router = new bApp.Router();\n\n// Give the bApp controller\n// power over switching views\nbApp.show = function(ch, sec) {\n var templatePath = './client/views/client-templates/ch' + ch + '_sec' + sec + '.html';\n\n if (this.currentView) {\n // Clean up your old view\n this.currentView.close();\n } \n\n // render your new view\n this.currentView = new bApp.view.Section({\n el: 'div#chapter' + ch,\n template: templatePath \n });\n\n this.currentView.render()\n\n // Update the route\n // This may seem redundant, but this will allow\n // you to call bApp.show() directly, and keep your\n // route up to date.\n bApp.route.navigate('book/' + ch + '/' + sec);\n}\n</code></pre>\n\n<p><a href=\"http://lostechies.com/derickbailey/2011/08/28/dont-execute-a-backbone-js-route-handler-from-your-code/\" rel=\"nofollow\">Here's a good article by Derick Bailey about common pitfalls with Backbone routers.</a></p>\n\n<p>I hope this is helpful!</p>\n\n<p><strong>Edit: Clarify App/Router Separation</strong></p>\n\n<p>Think of the router just as one of many ways to change the state of your application. Just like you could click a \"first page\" button to go to the first page, you could enter in <code>/page/first</code> in your browser to go to the first page. The only difference is whether your application state is bound to a button, or to a route.</p>\n\n<p>This is the reason to keep the logic that changes the application state (ie. changing the rendered page) out of your router. </p>\n\n<p>Consider this:</p>\n\n<pre><code>bApp.view.Section = Backbone.View.extend({\n events: {\n 'change input.ch]': this.handlePageChange_\n 'change input.sec]': this.handlePageChange_\n }\n //...\n handlePageChange_ = function() {\n var ch = this.$('input.ch').val();\n var sec = this.$('input.sec').val();\n\n // Let your application handle state change\n bApp.show(ch, sec)\n }\n});\n</code></pre>\n\n<p>In this example, you've bound a input element to your application state, just as you bound a route to your application state. Either way, the state-changing logic belongs in your application controller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T01:58:19.383", "Id": "53554", "Score": "0", "body": "edan, thanks a lot. This is really helpful. Being new to backbone there are a few things I need to figure out, but overall I understand what you are doing. The only part that is not clear is what you mean when you say that I will be able to call bApp.show() directly and about route being up to date. Is the explicit call to route.navigate an alternative to Backbone.history.start()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T05:44:14.777", "Id": "53564", "Score": "0", "body": "This is pretty much what I was going to say but I usually override `remove` rather than adding a `close`. @Curious2learn You'll still need the `Backbone.history.start()` call to crank up the routing machinery." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T20:01:45.620", "Id": "33416", "ParentId": "33414", "Score": "4" } } ]
{ "AcceptedAnswerId": "33416", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T21:04:16.607", "Id": "33414", "Score": "2", "Tags": [ "javascript", "backbone.js", "url-routing" ], "Title": "Backbone Router" }
33414
<p>I wanted to write a script, which starts a rails app, and opens it in the browser.<br/> I'm trying to implement this in a peculiar way though - I expect two things:</p> <ol> <li>the script must wait until the server is started, then open the browser within a short time</li> <li>when I stop the script (Ctrl+C), the server process must stop.</li> </ol> <p>The script I've written actually works, but I was wondering if there is a simplerr/more standard/more correct way of writing it.</p> <p>The script is written for linux, but it's not meant to be platform specific - or more precisely, anything except Windows.</p> <pre><code>PROJECT_DIR = '/path/to/app' POLLING_TIME = 0.1 SERVER_STARTED_REGEX = /WEBrick::HTTPServer#start/ BROWSER_COMMAND = 'browser http://localhost:3000 &amp;' Dir.chdir( PROJECT_DIR ) thread = Thread.new do IO.popen( 'script/rails server 2&gt;&amp;1' ) do | io | Thread.current[ :last_server_line ] = io.gets while true end end sleep POLLING_TIME while thread[ :last_server_line ] !~ SERVER_STARTED_REGEX `#{ BROWSER_COMMAND }` thread.join </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:03:00.610", "Id": "54279", "Score": "0", "body": "Do you mean what anybody will edit you post, with better script, or make an answer below?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T20:13:01.640", "Id": "54347", "Score": "0", "body": "@majioa It's best to use the answer feature, so that others have the chance to see the original question and provide answers of their own." } ]
[ { "body": "<p>This was an interesting one. Thank you :)</p>\n\n<p>I dug around in the rails code and poked at webrick and rack for a while and this is what I came up with:</p>\n\n<pre><code>PROJECT_DIR = ENV['PROJECT_DIR'] || '/path/to/app'\nBROWSER_COMMAND = ENV['BROWSER_COMMAND'] || 'browser http://localhost:3000 &amp;'\nPORT = ENV['PORT'].to_i || 3000\n\nrequire \"#{PROJECT_DIR}/config/environment.rb\"\n\nthread = Thread.new do\n Rack::Handler::WEBrick.run Rails.application, Port: PORT\nend\n\n`#{ BROWSER_COMMAND }`\n\nRack::Handler::WEBrick.shutdown\n\nthread.join\n</code></pre>\n\n<p>This approach is actually borrowed from <a href=\"https://github.com/rack/rack/blob/master/lib/rack/handler/webrick.rb\" rel=\"nofollow noreferrer\">rack's webrick handler</a>.</p>\n\n<p>I load the environment prior to actually starting the webrick server making any waits unnecessary for me. If that should be necessary for you, I'm sure you could add it.</p>\n\n<p>Then I pretty much stuck to what you did, putting the actual server into a thread. The Handler already provides that neat shutdown method.</p>\n\n<p>Oh, I also took the liberty of adding some <code>ENV</code> variables so you can put this script into a file and run it from where ever you want.</p>\n\n<p><strong>EDIT:</strong> In the comments <a href=\"https://codereview.stackexchange.com/users/13166/marcus\">Marcus</a> pointed out, that in order to resolve the timing issue, one can set the closure (block variable) from <code>WEBrick.run {|server|}</code> to a thread-local variable that can be polled afterwards.</p>\n\n<p>There might also be ways to exploit <a href=\"https://github.com/celluloid/celluloid\" rel=\"nofollow noreferrer\">Celluloid</a> for messaging between the different threads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T15:17:15.003", "Id": "57509", "Score": "0", "body": "The logic is appropriate, but there is a bug! The completion of the application start is asynchronous, so that the browser starts before actually something is listening on the port. In addition to that, the webrick shutdown raises an error if the app is not fully started!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T15:25:36.657", "Id": "57510", "Score": "0", "body": "I've actually found a workaround - the WEBrick.run {|server|} variable can be stored in the thread local storage. immediately afterwards, it can be polled at intervals, until it's not nil. at that point, the server is ready." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T20:27:16.787", "Id": "57541", "Score": "0", "body": "Yeah, I mentioned that one in my answer. It was not necessary for me since my browser took a while to start and the server was ready by then. Glad you managed to figure it out." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T15:02:16.653", "Id": "33865", "ParentId": "33420", "Score": "1" } } ]
{ "AcceptedAnswerId": "33865", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T22:42:43.470", "Id": "33420", "Score": "2", "Tags": [ "ruby", "multithreading", "ruby-on-rails" ], "Title": "Script for starting a rails app, with some peculiarities" }
33420
<p>This is a function designed to return all the prime factors of a given number, in sorted order from least to greatest, in a list. It relies on another function that checks if a given number is prime. Here is the prime checking function:</p> <pre><code>def isPrime(x): if x &lt;= 1 or isinstance(x,float): return False else: for divisor in range(2,x,1): if x % divisor == 0: return False return True </code></pre> <p>Here is the prime factorization function:</p> <pre><code>def allPrimeFactors(y): primeFactors = [] restart = True while restart: restart = False for i in range(2,y,1): if y % i == 0 and isPrime(i): primeFactors.append(i) y = y / i if isPrime(y) and y == i: primeFactors.append(y) else: pass restart = True else: pass primeFactors.sort() return primeFactors </code></pre> <p>The while loop is designed to restart the for loop at the first iterable value, which is, in this case, 2. This is so that, if y factors into 2, or any other prime, more than once, it will appear in the final list more than once, how ever many times it, or any other prime, is part of the factorization of y. I found that, if a number's prime factorization was 2 primes of the same value, it would return an incomplete list, therefore I added the if statement to the end of the function so that if the final value of y was prime AND equal to the current value of i, it would append the final value of y to the end of the list, therefore making it complete.</p> <p>This is a looping function I made to test the prime factorization function with a large set of numbers:</p> <pre><code>def primeFactorsTester(d,e): for f in range(d,e+1,1): if f == 1: print "1 is undefined" elif isPrime(f): print str(f) + " is prime" else: print "the prime factors of " + str(f) + " are "+ str(allPrimeFactors(f)) </code></pre> <p>It is meant to produce an output that is human readable, and is primarily a testing function.</p> <p>Does my prime factorization function seem complete or incomplete? Any general feedback to give? I would love to know.</p>
[]
[ { "body": "<p>Your result is incorrect:</p>\n\n<pre><code>&gt;&gt;&gt; allPrimeFactors(360)\n[2, 2, 3, 3, 5]\n&gt;&gt;&gt; import operator\n&gt;&gt;&gt; reduce(operator.mul, allPrimeFactors(360), 1)\n180\n</code></pre>\n\n<p>It is also unnecessarily complicated. The usual approach is, whenever you encounter a prime factor, extract as many powers of it as possible from the number. Here's another function that works:</p>\n\n<pre><code>def reallyAllPrimeFactors(n):\n factors = []\n for i in range(2, n + 1):\n while n % i == 0:\n factors.append(i)\n n = n // i\n return factors\n&gt;&gt;&gt; reallyAllPrimeFactors(360)\n[2, 2, 2, 3, 3, 5]\n&gt;&gt;&gt; reduce(operator.mul, reallyAllPrimeFactors(360), 1)\n360\n</code></pre>\n\n<p>Further optimizations to that are possible, but it is already much more efficient than your original. For one thing, it doesn't need to check any of its results for primality. (Why?)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T01:57:27.517", "Id": "53553", "Score": "0", "body": "thank you, I guess I should be more rigorous in my testing. it seems the while loop is why it does not need to check any of it results for primality, because the while loop states while the condition n % i == o is true, it will add the value of i to the end of factors, then reset the value of n to be equal to n divided by i floored, and because while does not rely on a preset iterable sequence, when you get to a number that is not prime, the condition will no longer be true, I think, im not sure." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T01:14:47.993", "Id": "33426", "ParentId": "33423", "Score": "3" } } ]
{ "AcceptedAnswerId": "33426", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-28T23:46:53.383", "Id": "33423", "Score": "1", "Tags": [ "python", "beginner", "primes" ], "Title": "Review my prime factorization function. Is it complete?" }
33423
<p>I've hacked a method that auto-fits text into an <a href="http://www.php.net/manual/en/class.imagick.php" rel="nofollow"><code>Imagick</code></a> image, given a bounding box: the image's width (minus optional margins) and a certain maximum height. What it does is find the optimal font size and line lengths within the bounding box.</p> <p>It's still a work in progress (still needs thorough checking of the validity of arguments, cleaning up certain routines, etc.), but the basic algorithm works beautifully, except, and I anticipated this already... it's slow as a snail. The longer the supplied text, the slower it will get.</p> <pre><code>function fitImageAnnotation( Imagick $image, ImagickDraw $draw, $text, $maxHeight, $leading = 1, $strokeWidth = 0.04, $margins = array( 10, 10, 10, 10 ) ) { if( strlen( $text ) &lt; 1 ) { return; } $imageWidth = $image-&gt;getImageWidth(); $imageHeight = $image-&gt;getImageHeight(); // margins are css-type margins: T, R, B, L $boundingBoxWidth = $imageWidth - $margins[ 1 ] - $margins[ 3 ]; $boundingBoxHeight = $imageHeight - $margins[ 0 ] - $margins[ 2 ]; // We begin by setting the initial font size // to the maximum allowed height, and work our way down $fontSize = $maxHeight; $textLength = strlen( $text ); // Start the main routine where the culprits are do { $probeText = $text; $probeTextLength = $textLength; $lines = explode( "\n", $probeText ); $lineCount = count( $lines ); $draw-&gt;setFontSize( $fontSize ); $draw-&gt;setStrokeWidth( $fontSize * $strokeWidth ); $fontMetrics = $image-&gt;queryFontMetrics( $draw, $probeText, true ); // This routine will try to wordwrap() text until it // finds the ideal distibution of words over lines, // given the current font size, to fit the bounding box width // If it can't, it will fall through and the parent // enclosing routine will try a smaller font size while( $fontMetrics[ 'textWidth' ] &gt;= $boundingBoxWidth ) { // While there's no change in line lengths // decrease wordwrap length (no point in // querying font metrics if the dimensions // haven't changed) $lineLengths = array_map( 'strlen', $lines ); do { $probeText = wordwrap( $text, $probeTextLength ); $lines = explode( "\n", $probeText ); // This is one of the performance culprits // I was hoping to find some kind of binary // search type algorithm that eliminates // the need to decrease the length only // one character at a time $probeTextLength--; } while( $lineLengths === array_map( 'strlen', $lines ) &amp;&amp; $probeTextLength &gt; 0 ); // Get the font metrics for the current line distribution $fontMetrics = $image-&gt;queryFontMetrics( $draw, $probeText, true ); if( $probeTextLength &lt;= 0 ) { break; } } // Ignore font metrics textHeight, we'll calculate our own // based on our $leading argument $lineHeight = $leading * $fontSize; $lineSpacing = ( $leading - 1 ) * $fontSize; $lineCount = count( $lines ); $textHeight = ( $lineCount * $fontSize ) + ( ( $lineCount - 1 ) * $lineSpacing ); // This is the other performance culprit // Here I was also hoping to find some kind of // binary search type algorithm that eliminates // the need to decrease the font size only // one pixel at a time $fontSize -= 1; } while( $textHeight &gt;= $maxHeight || $fontMetrics[ 'textWidth' ] &gt;= $boundingBoxWidth ); // The remaining part is no culprit, it just draws the final text // based on our calculated parameters $fontSize = $draw-&gt;getFontSize(); $gravity = $draw-&gt;getGravity(); if( $gravity &lt; Imagick::GRAVITY_WEST ) { $y = $margins[ 0 ] + $fontSize + $fontMetrics[ 'descender' ]; } else if( $gravity &lt; Imagick::GRAVITY_SOUTHWEST ) { $y = $margins[ 0 ] + ( $boundingBoxHeight / 2 ) - ( $textHeight / 2 ) + $fontSize + $fontMetrics[ 'descender' ]; } else { $y = ( $imageHeight - $textHeight - $margins[ 2 ] ) + $fontSize; } $alignment = $gravity - floor( ( $gravity - .5 ) / 3 ) * 3; if( $alignment == Imagick::ALIGN_LEFT ) { $x = $margins[ 3 ]; } else if( $alignment == Imagick::ALIGN_CENTER ) { $x = $margins[ 3 ] + ( $boundingBoxWidth / 2 ); } else { $x = $imageWidth - $margins[ 1 ]; } $draw-&gt;setTextAlignment( $alignment ); $draw-&gt;setGravity( 0 ); foreach( $lines as $line ) { $image-&gt;annotateImage( $draw, $x, $y, 0, $line ); $y += $lineHeight; } } </code></pre> <p>Usage could be:</p> <pre><code>$image = new Imagick( '/path/to/an/image.jpg' ); $draw = new ImagickDraw(); // For now, setting a gravity other that 0 is necessary $draw-&gt;setGravity( Imagick::GRAVITY_NORTHWEST ); $text = 'Some text, preferably long, because the longer, the text, the slower the algorithm'; $maxHeight = 120; // In my actual code it's a class method fitImageAnnotation( $image, $draw, $text, $maxHeight ); header( 'Content-Type: image/jpeg', true ); echo $image; </code></pre> <p>As you can see, I've annotated the algorithm, so you can get a feel of what it does, and see where the culprits are.</p> <p>As noted: I believe I should be able to greatly improve performance with some type of heuristics or perhaps a binary search type of routine: instead of probing <code>wordwrap()</code> one char at a time, and probing <code>$fontSize</code> one pixel at a time, have something more efficient, yet still yield the best possible fit result.</p> <p>Can you suggest any improvement to the algorithm, without losing the best fit?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-02T10:29:43.337", "Id": "53961", "Score": "0", "body": "Looking at this code, If I feel you may consider rewriting the entire do-while part.There is a \"while\" inside the first do block. Inside the \"while\" there is another do block. This is not only making it difficult to read but also performance will suffer a lot." } ]
[ { "body": "<p>I'll give this my best shot, but first...</p>\n\n<p><strong>Some Minor Improvements</strong></p>\n\n<p><code>strlen()</code> can only return a positive number or 0. If the string is empty you get a 0 otherwise you get the length. So a less than check is unnecessary and can be replaced with a plain boolean check, since we know that 0 is a FALSE value.</p>\n\n<pre><code>if( ! strlen( $text ) ) {\n return;\n}\n</code></pre>\n\n<p>When you access a specific index in an array you are using magic numbers. Its relatively easy to determine what these values ought to represent, but you should declare them anyway.</p>\n\n<pre><code>list( $topMargin, $rightMargin, $botMargin, $leftMargin ) = $margins;\n$boundingBoxWidth = $imageWidth - $rightMargin - $leftMargins;\n$boundingBoxHeight = $imageHeight - $topMargin - $botMargin;\n</code></pre>\n\n<p>Performing a function inside a loop tells PHP to call that function on every iteration to update it. When that function itself is essentially a loop you start exponentially decreasing efficiency. I imagine this is also a contributor to your load times.</p>\n\n<pre><code>while( $lineLengths === array_map( 'strlen', $lines ) &amp;&amp; $probeTextLength &gt; 0 );\n</code></pre>\n\n<p>When you find yourself comparing the same value against multiple known values, it might be better to use a switch statement rather than if/elseif/else. One its cleaner, and two its slightly faster, though that speed is negligible. I don't know what the values of those imagick constants are, but it seems like you are only handling a few of them. So, I don't know if using a switch statement is practical here, but in case you want to know how its done, you would use fall-through case statements to cover the less than operation.</p>\n\n<pre><code>switch( $gravity ) {\n case Imagick::LOWERCONST :\n case Imagick::GRAVITY_WEST :\n $y = $margins[ 0 ] + $fontSize + $fontMetrics[ 'descender' ];\n break;\n</code></pre>\n\n<p><strong>Some Major Improvements</strong></p>\n\n<p>So, that covers the minor improvements. A major improvement would be to break apart this function into separate smaller functions. <code>fitImageAnnotation()</code> is doing entirely too much. A function should describe exactly what it is doing and do no more. Your function doesn't actually start doing what it says its supposed to do until you start messing with the gravity and alignment. You mentioned that this is actually a class method, if so you might also start using class properties to pass shared variables along to these new methods instead of large argument lists.</p>\n\n<p><strong>Analyzing the Algorithm</strong></p>\n\n<p>Now, on to the algorithm. How slow is your program running? I would expect that working with images is likely to run slow all by itself, but I don't have much experience in this department. As such, I can't speak to specifics, so here are a few things that jumped out at me.</p>\n\n<p>You seem to be neglecting PHP's <a href=\"http://php.net/manual/en/function.wordwrap.php\" rel=\"nofollow\"><code>wordwrap()</code></a> cut and break parameters. Specifying the break parameter tells PHP how newlines should be handled, in your case \"\\n\". Setting the cut parameter to TRUE tells PHP not to cut off words. Using both of these parameters you can do away with <code>$lines</code> until you need to loop over it later (if that's still necessary) and <code>$lineLengths</code> altogether. You don't actually seem to be using <code>$lineLengths</code> anyway; And its repetitive, its the same value only in array form as <code>$probeTextLength</code>. This leaves you with <code>$lineCount</code>, which you can get with <code>substr_count()</code>. This gets rid of a number of <code>explode()</code> function calls, and will make that <code>array_map()</code> function call in your while loop unnecessary.</p>\n\n<p>I imagine this should make a positive impact to your load times. I don't really see anything else right now, but I'll continue looking and edit my answer should I come up with anything else. Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T23:53:46.253", "Id": "54508", "Score": "0", "body": "Thanks for your suggestions. You made some fair points about minor improvements, that will definitely be addressed later. But I'm afraid you've missed the point of `$lineLengths === array_map( 'strlen', $lines )` though, so I've edited my question to elaborate of why it's there. And I'm afraid I don't agree about the responsibility of the method; the whole point of the algorithm is what the method says: fit an image annotation. I might call it `fitImageAnnotationInBoundingBox()`, but the last part of the method is just the rendering, after the fitting calculations are done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T01:24:10.573", "Id": "54525", "Score": "0", "body": "@fireeyedboy: Your method name is fine, but you are doing more than just fitting the text to your image, you are adjusting it as well. Essentially, the contents of each of your loops could be its own function, they actually look repetitive enough that it could probably be just one. You are right about wordwrap's cut parameter, I misread the documentation; but the break parameter stands. With it you don't have to explode the string to compare it, simply compare the old string with the new. If the newlines are in different spots it will object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-07T11:51:57.397", "Id": "54577", "Score": "0", "body": "O, wow, I see what you mean now, about the newlines. You're right, off course! Thank you. I'll have a look and see what that does for the algorithm." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T18:10:11.937", "Id": "33948", "ParentId": "33424", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T00:07:25.247", "Id": "33424", "Score": "2", "Tags": [ "php", "performance", "algorithm", "image" ], "Title": "Auto-fitting text into an Imagick image" }
33424
<p>I wrote an FAQ on a third-party website which pertains to thread-protecting objects in Delphi. What I'd like to know is if this thread-protection approach is accurate, or if I should change anything about it. I don't intend to ask about the FAQ in general, just the aim at the actual topic of multi-threading.</p> <p>This code comes from common practices of mine, and I'm starting to wonder if these practices are good or bad. I've used this <code>TLocker</code> object for a long time, and would like to know if there's anything wrong with any of this approach.</p> <p><strong>The FAQ content</strong>:</p> <p>There are many ways to thread-protect objects, but this is the most commonly used method. The reason you need to thread-protect objects in general is because if you have more than one thread which needs to interact with the same object, you need to prevent a deadlock from occuring. Deadlocks cause applications to freeze and lock up. In general, a deadlock is when two different threads try to access the same block of memory at the same time, each one keeps repeatedly blocking the other one, and it becomes a back and forth fight over access.</p> <p>Protection of any object(s) begins with the creation of a Critical Section. In Delphi, this is <strong>TRTLCriticalSection</strong> in the <strong>Windows</strong> unit. A Critical Section can be used as a lock around virtually anything, which when locked, no other threads are able to access it until it's unlocked. This ensures that only one thread is able to access that block of memory at a time, all other threads are blocked out until it's unlocked.</p> <p>It's basically like a phone booth with a line of people waiting outside. The phone its self is the object you need to protect, the phone booth is the thread protection, and the door is the critical section. While one person is using the phone with the door closed, the line of people has to wait. Once that person is done, they open the door and leave and the next comes in and closes the door. If someone tried to get in the phone booth while someone's using the phone, well, it's obvious that would lead to a fight. That fight would be a deadlock.</p> <p>It is still a risk to cause a deadlock even when using this method, for example, someone trying to use the phone when someone else is using it. If for any reason a thread attempts to access the object without locking it, and while another thread is accessing it, you will still run into issues. So, you need to use this protection EVERYWHERE that could possibly need to access it. Remember, when you lock this, nothing else is able to lock it again (under the promise that all other attempts would also be using this same Critical Section). The locking thread must unlock it before it can be locked again.</p> <p>Okay, so into the code. The four calls you will need to know are:</p> <ul> <li>InitializeCriticalSection() - Creates an instance of a Critical Section</li> <li>EnterCriticalSection() - Engages the lock</li> <li>LeaveCriticalSection() - Releases the lock </li> <li>DeleteCriticalSection() - Destroys an instance of a Critical Section</li> </ul> <p>First, you need to declare a Critical Section somewhere. It's usually something that would be instantiated for the entire duration of the application, so I'll assume in the main form.</p> <pre><code> TForm1 = class(TForm) private FLock: TRTLCriticalSection; </code></pre> <p>Then, you need to initialize (create) your critical section (presumably in your form's constructor or create event)...</p> <pre><code>InitializeCriticalSection(FLock); </code></pre> <p>Now you're ready to use it as a lock. When you need to access the object it's protecting, you enter the critical section (locking it)...</p> <pre><code>EnterCriticalSection(FLock); </code></pre> <p>Once you have done this, it is locked. No other thread other than the calling thread is able to access this lock. Remember, technically other threads are able to access the object (but would potentially cause a deadlock), so make sure all other threads are also first trying to lock it. That's the goal of this lock.</p> <p>Once you have done everything you need in this thread, you leave the critical section (unlocking it)...</p> <pre><code>LeaveCriticalSection(FLock); </code></pre> <p>Now, it is unlocked and the next thread which may have attempted a lock is now able to completely lock it. That's right, while a critical section is locked, it remembers any other lock attempt, and once the calling thread unlocks it, the next one in the queue automatically acquires this lock. Same concept as a line of people waiting outside a phone booth.</p> <p>When you're all finished with the object, make sure you dispose of this critical section (presumably in your form's destructor or destroy event)...</p> <pre><code>DeleteCriticalSection(FLock); </code></pre> <p>And those are the fundamentals. But we're not done yet.</p> <p>It's highly advised that you should always use a try..finally block when entering/leaving a critical section. This is to ensure that it gets unlocked, in case of any unhandled exceptions. So, your code should look something like this:</p> <pre><code>EnterCriticalSection(FLock); try DoSomethingWithTheProtectedObject; finally LeaveCriticalSection(FLock); end; </code></pre> <p>Now, the last thing you may wish to do is wrap this up in a nice simple class to do the work for you. This way, you don't have to worry about all the long procedure names whenever you use this lock. This object is called <code>TLocker</code>, which protects an object instance for you. You would need to create an instance of this for every object instance you need to protect. So, instead of declaring something like <code>FMyObject: TMyObject;</code> you would do it like <code>FMyObject: TLocker;</code> and then give the object instance to it upon its creation.</p> <pre><code>type TObjectClass = class of TObject; TLocker = class(TObject) private FLock: TRTLCriticalSection; FObject: TObject; public constructor Create(AObjectClass: TObjectClass); overload; constructor Create(AObject: TObject); overload; destructor Destroy; function Lock: TObject; procedure Unlock; end; constructor TLocker.Create(AObjectClass: TObjectClass); begin InitializeCriticalSection(FLock); FObject:= AObjectClass.Create; end; constructor TLocker.Create(AObject: TObject); begin InitializeCriticalSection(FLock); FObject:= AObject; end; destructor TLocker.Destroy; begin FObject.Free; DeleteCriticalSection(FLock); end; function TLocker.Lock: TObject; begin EnterCriticalSection(FLock); Result:= FObject; //Note how this is called AFTER the lock is engaged end; procedure TLocker.Unlock; begin LeaveCriticalSection(FLock); end; </code></pre> <p>The first constructor <code>TLocker.Create(AObjectClass: TObjectClass);</code> expects a class type to be specified (such as <code>TMyObject</code>).</p> <p>The other constructor <code>TLocker.Create(AObject: TObject);</code> expects an instance of an object already created. Bear in mind that if you do use this constructor, you should no longer refer directly to that object after passing it into this constructor.</p> <p>In both of these cases, your object which is being protected will be automatically free'd when the TLocker is free'd. </p> <p>Let's assume the second constructor of the two. Once you've created an instance of this class with your initial actual object reference, never reference to the actual object again. Instead, whenever you need to use that object, pull it out of the TLocker instance by locking it. Using a try..finally block, make sure you also unlock it once you're done, or else the lock is stuck.</p> <p>So, using the class above, you can access an object like this:</p> <pre><code>procedure TForm1.FormCreate(Sender: TObject); var O: TMyObject; begin O:= TMyObject.Create; FMyObjectLocker:= TLocker.Create(O); end; procedure TForm1.FormDestroy(Sender: TObject); begin FMyObjectLocker.Free; //Your original object will be free'd automatically end; procedure TForm1.DoSomething; var O: TMyObject; begin O:= TMyObject(FMyObjectLocker.Lock); try O.DoSomething; //etc... finally FMyObjectLocker.Unlock; end; end; </code></pre> <p>As you see, I acquire the object at the same time as locking it. This should be the only possible way to access this object. Just make sure you always unlock it when you're done. Notice also how I also don't define the actual protected object in the class - to prevent accidental direct calls to the object.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:42:54.960", "Id": "53577", "Score": "2", "body": "One tip: regarding \"In general, a deadlock is when two different threads try to access the same block of memory at the same time\", as far as I know, this is the definition of a *race condition*, not a deadlock. Deadlock is when two concurrent pieces of code mutually depend of each other, so they block each other. Take a look at http://en.wikipedia.org/wiki/Deadlock and http://en.wikipedia.org/wiki/Race_condition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:45:35.097", "Id": "53578", "Score": "0", "body": "In Delphi you have a class named `TCriticalSection` declared in `SyncObjs` unit that gives you a more object-oriented approach of working with critical sections. Using this or the routines in `Windows` units is a matter of style and preference, but I decided to inform you about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:48:53.610", "Id": "53579", "Score": "1", "body": "In your phone boot metaphore your say that when someone tries to use the door with someone already inside, this will lead to a deadlock. I believe that´s not accurate, since a deadlock means mutual dependency. What happens here is the blocking of the the second phone boot user and it will last as long as the door is closed. The one inside the phone boot is not blocked, so it´s not a deadlock." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:57:18.067", "Id": "53581", "Score": "0", "body": "I guess it would be nice to have a generic version of `TLock` class (for instance, `TLock<T>`). In more modern Delphi flavors you would be able to have a method that receives a anonymous method that would wrap the `try..finally` block, what would make it impossible to one to forget to unlock the protected resource. Those are just ideas for your consideration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T17:07:01.413", "Id": "53599", "Score": "0", "body": "you should probably break this up into several questions, and ask if there is something in the code that can be improved." } ]
[ { "body": "<p>Your first paragraph says \"this is the most commonly used method\" without saying what \"this\" is. When writing a FAQ answer, especially one about something as thorny as multithreading, it's important to be precise from the very start. Maybe \"this\" refers to something from the question, but I don't know because you didn't include the question in what you presented for review.</p>\n\n<p>You say accessing the same memory from multiple threads leads to deadlock, which is generally false. Accessing the same memory at the same time is a race condition that might be an issue, but also might be harmless. If it leads to <em>deadlock</em>, you probably have buggy hardware.</p>\n\n<p>Furthermore, if you have two threads going back and forth fighting over access, you again don't have deadlock. With deadlock, there's no back-and-forth anymore. If threads are repeatedly going back and forth, that's often an indication of a <em>lock convoy</em>, which is perfectly safe, but doesn't usually provide the desired level of performance.</p>\n\n<p>A critical section is just <em>one</em> way of writing thread-safe code, so it's incorrect to say that creating one begins the way of protecting <em>any</em> object.</p>\n\n<p><em>Critical section</em> is not a proper noun; there's no need to capitalize it.</p>\n\n<p>Regarding the phone booth, deadlock rarely involves a fight. The CPU doesn't pit two threads against each other and grant memory access to whichever is mightier. It happily grants access to both at the same time. Deadlock would be when someone inside the phone booth calls the home of another person in line for the booth. That person cannot answer his home phone because he's in line outside waiting for the booth, but the caller won't get off the phone until it's answered. This actually illustrates how adding locks can actually <em>lead to</em> deadlock, not prevent it. (When you have no threading protection at all, deadlock is rare.)</p>\n\n<p>You characterize the threads waiting to acquire a critical section as a line of people outside the phone booth. <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682608.aspx\" rel=\"nofollow\">MSDN specifically contradicts that analogy:</a></p>\n\n<blockquote>\n <p>There is no guarantee about the order in which waiting threads will acquire ownership of the critical section.</p>\n</blockquote>\n\n<p>Don't forget to mark <code>TLocker.Destroy</code> with <code>override</code>.</p>\n\n<p>The <code>TLocker</code> constructor that takes a metaclass is of limited utility, especially in the case demonstrated here with <code>TObjectClass</code> (also known as <code>TClass</code>). No matter what class is passed as an argument, the <code>TLocker</code> constructor will always call the zero-argument constructor introduced in the base class, and yet inspecting the <code>ClassType</code> of the created object, it will appear to be of the correct class. For it to call the proper constructor, the <code>Create</code> method of the base class would need to be declared virtual.</p>\n\n<p>I'd forego the metaclass constructor entirely. Leave the task of constructing objects to some other code; your class is called a <code>TLocker</code>, after all, not a <code>TLockerAndObjectFactory</code>.</p>\n\n<p>In <code>TLocker.Lock</code>, you call specific attention to the order of the two instructions. That reveals a misunderstanding on your part because the order of those instructions doesn't make any difference at all. Assigning <code>Result</code> doesn't grant any access to the object before the lock is acquired. Even if it did, that access would be useless because the thread that access was granted to is the <em>current</em> thread, and that thread can't possibly do anything with the object until <code>Lock</code> returns.</p>\n\n<p>There is no apostrophe in <em>freed</em>. It's an ordinary English word.</p>\n\n<p>You mention how you \"don't define the actual protected object in the class.\" That doesn't make any sense. I think what you wanted to convey was that you don't <em>expose</em> the protected object except through the <code>Lock</code> method. You want to point out that the <code>FObject</code> field is private intentionally.</p>\n\n<p>Ultimately, it's hard to judge how good a FAQ answer this is because the question it's meant to answer is absent. There's systemic confusion over what deadlock is and how it occurs, so I hope the question didn't ask about deadlock. You might just want to skip the introductory motivation and go straight to presenting the locking code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T22:05:22.537", "Id": "37631", "ParentId": "33427", "Score": "3" } }, { "body": "<p>As others have stated, a deadlock occurs when 2 (or more threads) vie for the same resource (object/handle/int/etc) and a thread does not release the lock appropriately:</p>\n\n<pre><code>// thread 1 and thread 2 call the following:\nvoid threadfn() {\n EnterCriticalSection(&amp;mtx);\n // do some work\n}\n</code></pre>\n\n<p>A dead lock condition will occur in the above code because a thread 'locked' the mutex (critical section) then never unlocked it, so the other thread who is blocking on <code>EnterCriticalSection</code> will stay blocked until a call to <code>LeaveCriticalSection</code> is made.</p>\n\n<p>A quick note on <code>CRITICAL_SECTION</code> 'objects' (handles): they are recursive/re-entrant by the same thread. In other words, given the above code, if thread 1 calls <code>threadfn</code> 10 times, then 10 calls to <code>EnterCriticalSection</code> would be made and thread 1 won't lock, but the same thread (thread 1) would have to call <code>LeaveCriticalSection</code> the same number of times (10 in our example) before any other thread would be able to 'grab' the lock.</p>\n\n<p>Using the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682438%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>CreateSeamphore</code></a> function, you can create a binary semaphore (a sempaphore with only 1 active lock); binary semaphores on the Windows platform are non re-entrant (non-recursive).</p>\n\n<p>There's also the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms686857%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>TryEnterCriticalSection</code></a> function which returns <code>TRUE</code> if the 'lock' operation succeeds.</p>\n\n<p>Another note: you stated that \"It's highly advised that you should always use a try..finally block when entering/leaving a critical section\", per the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682608%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>MSDN documentation on EnterCriticalSection</code></a>, it's not a good idea to <code>try...catch</code> a critical section error (and I agree) for numerous reasons; instead it's a better idea to debug WHY it threw the error which happens on a timeout of the critical section which indicates a genuine problem occurred that needs to be addressed in code and not just 'caught away' as it could indicate a deadlock.</p>\n\n<p>Last note: you talk in your FAQ about protecting 'objects' from a multi-threaded environment and present this via a Delphi/MS context using a <code>TForm</code> as an example, this is fine but if this FAQ is supposed to be on multi-threading (from this FAQ it looks specifically to be about the 'mutex' idiom WRT WinAPI) then try focusing specifically on that (smaller code snippets losing the TForms, just simple examples of multiple threads accessing the same 'object' .. an integer is fine for teaching purposes). You also need to make a note about how <code>CRITICAL_SECTION</code>'s don't like to be copied (i.e. if a copy constructor were to be introduced and you 'copied' the critical section from one object to the other), that behavior is undefined (as it should be).</p>\n\n<p>I hope that's helpful</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T23:25:12.060", "Id": "37639", "ParentId": "33427", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T02:01:51.910", "Id": "33427", "Score": "3", "Tags": [ "multithreading", "thread-safety", "delphi" ], "Title": "Is this the right way to thread-protect an object?" }
33427
<p>Which of the following is cleaner / more adopted standard of handling exceptions while coding a stream ? I would also appreciate a reason why one of the following trumps over other ? In my opinion I find option 1 better but nested try where first try does nothing more than a wrapper is making me not satisfied with approach.</p> <pre><code>NavigableSet&lt;String&gt; dictionary = new TreeSet&lt;String&gt;(); BufferedReader br = null; try { try { br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt")); String line; while ((line = br.readLine()) != null) { dictionary.add(line.split(":")[0]); } } finally { br.close(); } } catch (Exception e) { throw new RuntimeException("Error while reading dictionary"); } </code></pre> <p>VS</p> <pre><code>NavigableSet&lt;String&gt; dictionary = new TreeSet&lt;String&gt;(); BufferedReader br = null; try { br = new BufferedReader(new FileReader("/Users/ameya.patil/Desktop/text.txt")); String line; while ((line = br.readLine()) != null) { dictionary.add(line.split(":")[0]); } } } catch (Exception e) { throw new RuntimeException("Error while reading dictionary"); } finally { try{ if(br != null) br.close(); } catch (Exception ex){ } } </code></pre>
[]
[ { "body": "<p>For the second example you posted, I do not think <code>finally</code> is used in a correct way. using <code>try</code> in <code>finally</code> block is not a good idea\nyou can check the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html\" rel=\"nofollow\">documentation</a></p>\n\n<blockquote>\n <p>The finally block always executes when the try block exits. This\n ensures that the finally block is executed even if an unexpected\n exception occurs. But finally is useful for more than just exception\n handling — it allows the programmer to avoid having cleanup code\n accidentally bypassed by a return, continue, or break. Putting cleanup\n code in a finally block is always a good practice, even when no\n exceptions are anticipated.</p>\n</blockquote>\n\n<p>I have modified the first version here...</p>\n\n<pre><code>NavigableSet&lt;String&gt; dictionary = new TreeSet&lt;String&gt;(); \nBufferedReader br = null; \ntry { \n br = new BufferedReader(new FileReader(\"/Users/ameya.patil/Desktop/text.txt\")); \n String line = null; \n while ((line = br.readLine()) != null) { \n dictionary.add(line.split(\":\")[0]); \n } \n} catch(FileNotFoundException e) { \n System.err.println(\"Caught FileNotFoundException: \" + e.getMessage()); \n throw new RuntimeException(e); \n} catch(IOException e) { \n System.err.println(\"Caught IOException: \" + e.getMessage()); \n}finally { \n if (null != br) { br.close(); } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:30:42.187", "Id": "53568", "Score": "1", "body": "It was a while since I worked with Java, but I remember you had to enclose br.close() in a try/catch. In that case @JavaDevelopers second example was fine as it was." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:37:51.860", "Id": "53571", "Score": "1", "body": "well, @JavaDeveloper's second version of code is not a bad practice, but for readability I would avoid that. Here is a discussion on [link this](http://programmers.stackexchange.com/questions/188858/throwing-an-exception-inside-finally)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:11:31.083", "Id": "53604", "Score": "1", "body": "I appreciate the feedback and the posted link, which is so useful" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:00:53.543", "Id": "33436", "ParentId": "33428", "Score": "4" } }, { "body": "<p>First off, in Java 7 all of this is obsolete if you use 'try with resources'</p>\n\n<pre><code>NavigableSet&lt;String&gt; dictionary = new TreeSet&lt;&gt;();\ntry (BufferedReader br = new BufferedReader(new FileReader(\"/Users/ameya.patil/Desktop/text.txt\"))) {\n String line;\n while ((line = br.readLine()) != null) {\n dictionary.add(line.split(\":\")[0]);\n }\n} catch (Exception e) {\n throw new RuntimeException(\"Error while reading dictionary\");\n}\n</code></pre>\n\n<p>If you have to work on an earlier JDK consider these points :</p>\n\n<p>Both snippets you supply are not exactly equivalent. i.e. if closing the file fails, the first snippet will throw a <code>RuntimeException</code> wrapping <strong>the exception of the <code>close()</code></strong>. The second snippet will throw a <code>RuntimeException</code> wrapping <strong>the original exception</strong>.</p>\n\n<p>Again in SE 7 using the try with resources you'll be able to see both exceptions : the original exception is thrown and it has the exception upon <code>close()</code> attached as a <em>suppressed exception</em>.</p>\n\n<p>So I think style is irrelevant, you want the original exception (which may even not be related to I/O). If you can use SE 7, use that, otherwise go for snippet 2 (add logging for the exception on <code>close()</code>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:15:08.807", "Id": "33439", "ParentId": "33428", "Score": "5" } }, { "body": "<p>My usual answer in cases like this is to isolate the construction of the object from the consumption of it. If you split up these two methods, then you don't have to worry about branching in the finally clause -- if you have reached the method responsible for closing the object, then you finally close it.</p>\n\n<pre><code>BufferedReader br = createReader(\"/Users/ameya.patil/Desktop/text.txt\");\nNavigableSet&lt;String&gt; dictionary = createDictionary(br);\n\n...\nBufferedReader createReader(String fileName) {\n try {\n return new BufferedReader(new FileReader(fileName));\n } catch (IOException e) {\n throw new RuntimeException(\"Unable to create buffer: \" + fileName, e);\n }\n}\n\nNavigableSet&lt;String&gt; createDictionary(BufferedReader br) {\n try {\n NavigableSet&lt;String&gt; dictionary = new TreeSet&lt;String&gt;(); \n while((line = br.readLine()) != null) {\n dictionary.add(line.split(\":\")[0]);\n }\n return dictionary;\n } finally {\n // If we are in this method at all, we KNOW we need to\n // close() the reader when we are done with it.\n br.close();\n }\n</code></pre>\n\n<p>You probably wanted to refactor out createDictionary() anyway, so that you can test it properly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T15:22:48.507", "Id": "33466", "ParentId": "33428", "Score": "2" } } ]
{ "AcceptedAnswerId": "33436", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T02:37:47.860", "Id": "33428", "Score": "3", "Tags": [ "java", "exception", "stream" ], "Title": "Reading a text file, need help cleaning exception handling" }
33428
<p>I have written a custom endless/infinite scroll, which allows the user to load images as they scroll down.</p> <p>How can i make this code below modular and easily reusable? </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;Endless Scroll Flicker feed test 2&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script language="javascript"&gt; var perpage = 5; var currentPage = 1; $(document).ready(function () { $("#photos").empty(); $("#submit").click(function (event) { /**********************/ var searchTerm = $("#search").val(); // get the user-entered search term var URL2 = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&amp;api_key=e58bbdc1db64c8f63ff7f7460104aa9d&amp;'; //tags=flower&amp;text=&amp;per_page=5&amp;page=10&amp;format=json var tags = "&amp;tags=" + searchTerm; var tagmode = "&amp;tagmode=any"; var jsonFormat = "&amp;format=json"; var ajaxURL = URL2 + "per_page=" + perpage + "&amp;page=" + currentPage + tags + tagmode + jsonFormat; //var ajaxURL= URL+"?"+tags+tagmode+jsonFormat; $.ajax({ url: ajaxURL, dataType: "jsonp", jsonp: "jsoncallback", success: function (data) { // $("#photos").empty(); if (data.stat != "fail") { console.log(data); //$("#photos").empty(); // $("figure").empty(); $.each(data.photos.photo, function (i, photo) { // $("&lt;figure&gt;&lt;/figure&gt;").hide().append('&lt;img src="http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_q.jpg"/&gt;').appendTo("#photos").fadeIn(2000); var photoHTML = ""; photoHTML += " &lt;img src='"; photoHTML += "http://farm" + photo.farm + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_q.jpg'"; photoHTML += " title='" + photo.title + "'"; photoHTML += "&gt;&lt;br&gt;"; $("#photos").append(photoHTML).fadeIn(200); }); } } }); /**************************/ }); $("#photos").scroll(function () { //var page=1; //var scrolloffset=20; // if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) { // if($("#scrollbox").scrollTop() == $(document).height() - $("#scrollbox").height()-20) { // check if we're at the bottom of the scrollcontainer if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) //if ($(window).scrollTop() &gt;= $(document).height() - $(window).height() - 10) { // If we're at the bottom, retrieve the next page currentPage++; $("#submit").click(); //myAJAXfun(); // scrollalert() // console.log("page "+currentpage); } }); }); &lt;/script&gt; &lt;style type="text/css"&gt; /* #container{ width:400px; margin:0px auto; padding:40px 0; } #scrollbox{ width:400px; height:300px; overflow:auto; overflow-x:hidden; border:1px solid #f2f2f2; margin-top:150px;} #container &gt; p{ background:#eee; color:#666; font-family:Arial, sans-serif; font-size:0.75em; padding:5px; margin:0; text-align:right;}*/ #searchBar { align:center; position:fixed; height:65px; background-color:#777; border:1px solid red; width:100%; top:0; } #photos { position: absolute; left: 186px; top: 105px; width: 376px; height:550px; overflow:auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div align="center" id="searchBar"&gt; &lt;div&gt;Enter Search Term&lt;/div&gt; &lt;form&gt; &lt;input type="text" id=search /&gt; &lt;input type="button" id=submit value="Search" /&gt; &lt;input type="reset" value="Clear" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="photos"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I would wrap your jquery as a plugin. Here's a <a href=\"http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/\" rel=\"nofollow noreferrer\">boilerplate</a> to help you refactor this.</p>\n\n<p>You could then call your function as <code>$('#photos').myInfinteScroll();</code></p>\n\n<p>Anywhere you want to access dynamic controls I would then inject these into the plugin as options, so something like:</p>\n\n<pre><code>$(document).ready(function() {\n $('#photos').myInfinteScroll({\n searchTerm:\"#search\",\n submitClick:\"#submit\"\n });\n});\n</code></pre>\n\n<p>Allowing you to access these elements inside your plugin thus:</p>\n\n<pre><code>var searchTerm = $(plugin.settings.searchTerm).val();\n</code></pre>\n\n<p>and anywhere where you needed <code>$('#photos')</code> you'd use:</p>\n\n<pre><code>$element\n</code></pre>\n\n<p>you could also add some defaults thus:</p>\n\n<pre><code> var defaults = {\n perpage : 5,\n currentPage : 1\n }\n</code></pre>\n\n<p>and even override them:</p>\n\n<pre><code>$(document).ready(function() {\n $('#photos').myInfinteScroll({\n searchTerm:\"#search\",\n submitClick:\"#submit\",\n perpage:6\n });\n});\n</code></pre>\n\n<p><strike>You could then <a href=\"https://stackoverflow.com/questions/15505225/inject-css-stylesheet-as-string-using-javascript\">inject your css</a> so this would make your entire function callabled from inside the plugin and allow you to move it/use it on any elements you wish.</strike></p>\n\n<p>Forget that, just add the css as a dependency, also Jquery would also (obviously) be a dependency.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T08:31:23.163", "Id": "33831", "ParentId": "33429", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T04:35:58.220", "Id": "33429", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "How can I make my custom infinte scroll more reusable?" }
33429
<p>Consider an interface:</p> <pre><code>public interface IWindowOperations { // Some operation methods. } </code></pre> <p>Class definitions:</p> <ol> <li><pre><code>public abstract class BaseWindow&lt;T&gt; : IWindowOperations { // partially implemented class. } </code></pre></li> <li><pre><code>public class TraditionalWindow&lt;T&gt; : BaseWindow&lt;T&gt; { // Fully implemented class. } </code></pre></li> <li><pre><code>public class ModernWindow&lt;T&gt; : BaseWindow&lt;T&gt; { // Fully implemented class. } </code></pre></li> </ol> <p>(1) is already marked as an abstract so it cannot be instantiated. (2) and (3) are fully implemented though they should not be instantiated, rather they should be derived by other class specifying <code>&lt;T&gt;</code> so the application framework can register them. e.g.</p> <pre><code> public class SliderWindow&lt;Win8&gt; : ModernWindow&lt;Win8&gt; { // In general case this is just an empty class // unless special handling is needed. } </code></pre> <p>In this case is it right to mark (2) and (3) as an <code>abstract</code>? Those are just template defining some concrete functionality but also allows derived classes to override if required.</p>
[]
[ { "body": "<p>It depends on your design entirely. If classes (2) and (3) can not operate on their own, should not be instanciated and are there to serve as base classes only, then you are justified to make them abstract, and i think you should.</p>\n\n<p>Also, you should probably reflect your intent in class names by adding <code>Base</code> suffix to (2) and (3) (or prefix, but i think it is less common).</p>\n\n<p><strong>Edit</strong> Objects with protected constructor can still be instanciated. For example, you can create them from some method in derived class. It is not a realistic use-case in most cases, but you should not leave such holes nonetheless. If you want to forbid instanciation completely, the only way to do it is to mark the class abstract.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T07:14:00.743", "Id": "33433", "ParentId": "33432", "Score": "5" } } ]
{ "AcceptedAnswerId": "33433", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T06:56:14.123", "Id": "33432", "Score": "3", "Tags": [ "c#", "classes" ], "Title": "Marking class with no abstract methods as an abstract" }
33432
<p>I'm having an argument with my boss about whether or not it's better to have a separate function for a single line of code.</p> <p>The code reads something like:</p> <pre><code>while (count &lt;= poscount) { key = etc.substr(pos2prev+1, pos-pos2prev-1); std::string::iterator end_pos = std::remove(key.begin(), key.end(), ' '); key.erase(end_pos, key.end()); val = etc.substr(pos+1, pos2-pos-1); //process key and val DEBUG("{\n\t%s:%s\n}\n", key.c_str(), val.c_str()); json_object_object_add(paramList, key.c_str(), json_object_new_string(val.c_str())); count++; pos2prev = pos2; pos = etc.find("=", pos+1); pos2 = (count == poscount) ? etc.find("\0",pos2+1) : etc.find("&amp;", pos2+1); } </code></pre> <p>Is it better coding style to include the line</p> <pre><code>json_object_object_add(paramList, key.c_str(), json_object_new_string(val.c_str())); </code></pre> <p>in a separate function name such as <code>processKeyVal()</code>, or leave it as-is?</p>
[]
[ { "body": "<p>I would leave it as it is.</p>\n\n<p>It's only 1 line, and it's a function call of itself and not an evaluation or an operation, so why wrap a function call within a separate function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:25:57.473", "Id": "33438", "ParentId": "33434", "Score": "0" } }, { "body": "<p>Not a direct answer to your question and possibly far fetched but here you go:</p>\n\n<p>Your code looks like it's parsing a string (presumably a query string) and serializes it into JSON. I would consider extracting the json serialization dependency out of it and pass in an abstract serializer. The line in question would turn into:</p>\n\n<pre><code>m_serializer.Add(key, val);\n</code></pre>\n\n<p>Some advantages of this method:</p>\n\n<ul>\n<li>Separates the parsing of the code from the serialization</li>\n<li>Allows you to easily add different forms of serialization without having to change the parsing code</li>\n<li>Makes unit testing (in case you do have unit tests) cleaner because it would just test that the right methods with the right arguments are called on a mock serializer.</li>\n</ul>\n\n<p>As it stands now I probably would not bother adding an additional method however I would introduce local variables to hold the arguments for the call instead. Can make debugging a tad easier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T02:52:18.797", "Id": "57562", "Score": "0", "body": "...and readability++ :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:30:45.733", "Id": "33440", "ParentId": "33434", "Score": "1" } }, { "body": "<p>I'm guessing that your boss's argument is that a well named function would make the code more readable, and I agree with that in general. I often do that myself even when the function contains a single line.</p>\n\n<p>In this particular example I would not bother though. The comment above the json-call says the same thing as the function name would, and there are no obvious advantages to make a function for a single call.</p>\n\n<p>So if your question is specifically for this example, then I agree with you - keep it as it is, but if you want a more general answer, then I agree with your boss.</p>\n\n<p>For example - if this one-liner is something that you use in more than one place, i.e. if calling the \"processKeyVal()\" function in more than one place makes sense. Then I say you should make a function of it even if it would contain only one line of code.</p>\n\n<p>Or to put it another way - it is not (always) the number of code lines that should determine if you make a separate function of a code snippet.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T07:22:57.693", "Id": "33496", "ParentId": "33434", "Score": "2" } }, { "body": "<p>Give it its own function. Since this is C++, you can <code>inline</code> it so that it won't incur any performance penalty or use a dangerous macro. If you decide you want XML or a binary format or anything else tomorrow, you will be glad you didn't commit the rest of your code to JSON by using <code>json_object_object_add</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T11:23:59.913", "Id": "35529", "ParentId": "33434", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T07:45:02.800", "Id": "33434", "Score": "3", "Tags": [ "c++" ], "Title": "Separate method for a single line code? Or embed in the caller function?" }
33434
<p>I need to call a function exactly at certain hour, daily, my programs runs 24/7.</p> <p>I wrote the following timer mechanism, which generally works that way:</p> <ol> <li><p>Calculate time until hour and generate timer with that interval. </p></li> <li><p>When timer elapse, call timer event and generate another 24h timer. </p></li> <li><p>Go back to step 2.</p></li> </ol> <pre><code>private static void InitTimeBasedTimer(TimeSpan timeToRun, Action funcToRun) { TimeSpan interval = timeToRun.Subtract(DateTime.Now.TimeOfDay); double intervalMillis = interval.TotalMilliseconds; if (interval.TotalMilliseconds &lt; 0) { intervalMillis = (new TimeSpan(24, 0, 0)).Add(interval).TotalMilliseconds; } Timer timer = new Timer(intervalMillis); timer.AutoReset = false; timer.Elapsed += (sender, e) =&gt; TimeBasedCallback(timeToRun, funcToRun); timer.Start(); } public static void TimeBasedCallback(TimeSpan timeToRun, Action funcToRun) { funcToRun(); TimeSpan interval = timeToRun.Subtract(DateTime.Now.TimeOfDay); //24 h double intervalMillis = interval.TotalMilliseconds; if (intervalMillis &lt; 0) { intervalMillis = (new TimeSpan(24, 0, 0)).Add(interval).TotalMilliseconds; } Timer timer = new Timer(intervalMillis); timer.AutoReset = false; timer.Elapsed += (sender, e) =&gt; TimeBasedCallback(timeToRun, funcToRun); timer.Start(); } </code></pre> <p><strong>EDIT:</strong><br> There are several functions that each writes to a DB every day in different hours. Can't afford task scheduler / process for each function. Quartz.NET seems a bit overkill for such a simple task. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:36:03.610", "Id": "53569", "Score": "4", "body": "For this kind of Task you should use something like the TaskScheduler of Windows of a library like Quartz.NET" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T09:40:52.317", "Id": "53576", "Score": "0", "body": "I need several functions that each writes to a DB every day in different hours.\nCan't afford task / process for each function. Quartz.NET seems a bit overkill for such a simple task." } ]
[ { "body": "<p>Without knowing what you're trying to do, I'd say this is the wrong approach. I would create an executable and set it up as a scheduled task to run every 24 hours. </p>\n\n<p>Not sure what OS you are using, but assuming it's windows its fairly easy <a href=\"http://windows.microsoft.com/en-au/windows7/schedule-a-task\" rel=\"nofollow\">http://windows.microsoft.com/en-au/windows7/schedule-a-task</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T08:21:59.823", "Id": "33437", "ParentId": "33435", "Score": "4" } }, { "body": "<p>Agree with another answer. Trying to write your own scheduler is a wrong approach 99% of the time. </p>\n\n<p>Have you thought about these situations?</p>\n\n<ol>\n<li><p>What happens if your 'funcToRun' function throws an exception? Not only you will not setup the next timer, but depending upon how other things are setup, it will bring down your main program. </p></li>\n<li><p>Let's say you will set up a try/catch around 'funcToRun' so that you can run it during the next scheduled time. How would you know if it's okie to run it again? What if the user wants to kick off the process manually immediately after fixing the problem which caused the failure? </p></li>\n<li><p>What if user wants to change the time when the process runs? In your case, you will have to change the code and deploy it before the changes take effect. </p></li>\n<li><p>What if certain process requires higher privileges so that it can access certain network resource? In your design, you will have to give your main process higher privileges. </p></li>\n<li><p>What happens if 'funcToRun' itself runs for more than 24 hours? </p></li>\n<li><p>How can you specify that a given funcToRun should run for maximum of 1 hour? </p></li>\n<li><p>How would you account for Daylight Savings Time? Let's say your process is supposed to run at 5pm. If you were to use Task Scheduler, it will automatically run at 5pm accounting for the DST, your code will be off by hours adjusted by DST.</p></li>\n</ol>\n\n<p>I could go on and on. Do yourself a favor and go to Task Scheduler in Windows and look at the 'Create Task' dialog. Go through all the options. These are the things you will run into eventually whenever you try to design a scheduler system. Instead of trying to re-create Task Scheduler, why not use it?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T20:49:11.603", "Id": "33543", "ParentId": "33435", "Score": "2" } }, { "body": "<p>You can use a timer. Also you can do this:</p>\n\n<pre><code> public Form1()\n {\n InitializeComponent();\n DateTime today = DateTime.Today;\n StreamDate(today)\n timer1.Start();\n }\nprivate void timer1_Tick(object sender, EventArgs e)\n {\n DateTime today = DateTime.Today;\n string text = System.IO.File.ReadAllText(@\"C:\\date.txt\");\n DateTime newdate = Convert.ToDateTime(text);\n if (today != newdate)\n {\n StreamDate(today)\n\n }\nprivate void StreamDate(string today)\n{\n StreamWriter foldcreat = new StreamWriter(@\"C:\\date.txt\");\n foldcreat.WriteLine(String.Format(\"{0}\", today));\n foldcreat.Close();\n}\n</code></pre>\n\n<p>it's if you have oportunity to create text file ....\nAnother way : <a href=\"http://www.codeproject.com/Articles/6507/NET-Scheduled-Timer\" rel=\"nofollow\">http://www.codeproject.com/Articles/6507/NET-Scheduled-Timer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-07T11:14:13.807", "Id": "209115", "Score": "2", "body": "This hasn't very much in common to the question itself. Why do you need a `Form` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-07T17:20:04.467", "Id": "209194", "Score": "1", "body": "Please review the code, rather than providing your solution to the same problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-07T09:46:23.090", "Id": "113134", "ParentId": "33435", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T07:50:36.950", "Id": "33435", "Score": "2", "Tags": [ "c#", "callback", "timer" ], "Title": "Time of day based timer - run function at certain time, daily" }
33435
<p>The following code takes a decimal number and gives its IEEE 754 floating point representation. However, the code is not complete and I am totally fine because it does the job for me: </p> <ol> <li>It does not consider negative numbers. </li> <li>The input number is not a fraction. Its always in the form xx.yy</li> <li>As of now, it does not give representation in 32-bit or 64-bit format, it just gives exponent and significant value.</li> </ol> <p></p> <pre><code>function toBinary (decimal) { return decimal.toString(2); } function getIntegerPart (binary){ return binary.slice(0, binary.indexOf('.')); } function getFractionalPart (binary){ return binary.slice(binary.indexOf('.')+1); } function toNormalize (binary) { var normalizedRep = new Object(); exponentValue = binary.indexOf('.')-1; floatPosition = binary.indexOf('.'); normalizedRep.floatRep = binary[0]+ '.' + binary.slice(1, floatPosition) + binary.slice(floatPosition+1); normalizedRep.exponentValue = exponentValue; normalizedRep.floatPosition = floatPosition; return normalizedRep; } function getSignificand (normalizedRep) { return normalizedRep.floatRep.slice(normalizedRep.floatRep.indexOf('.')+1); } function twosComp() { var decimal = 15.22; var binary = toBinary(decimal); var integerPart = getIntegerPart(binary); var fractionalPart = getFractionalPart(binary); var floatPosition = binary.indexOf('.'); var normalizedRep = toNormalize(binary); var significand = getSignificand(normalizedRep); var exponentValue = normalizedRep.exponentValue; console.log(binary); console.log(floatPosition); console.log(normalizedRep.floatRep); console.log(significand); console.log(exponentValue); } </code></pre>
[]
[ { "body": "<p>I just don't get what you're trying to do. JavaScript does not know of integers, floats or any other numeric type, except for <code>Number</code>.<br/>\nThis data-type just happens to be a 64bit IEEE754 floating point value (or <code>double</code> in most strong-typed languages). <a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.19\" rel=\"nofollow noreferrer\">This is clearly described in the official language specs</a></p>\n<blockquote>\n<p>primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value</p>\n<p>NOTE A Number value is a member of the Number type and is a direct representation of a number.</p>\n</blockquote>\n<p>So a float representation of a number <em>is</em> the number itself. If you want <em><code>n</code></em> number of significant digits, then there's a handy method for that:</p>\n<pre><code>var num = 123.321;\nconsole.log(num.toFixed(2));//123.32\n</code></pre>\n<p>If you want the integer part of a non-integer number:</p>\n<pre><code>parseInt(num, 10);//123 (best to specify the radix)\n</code></pre>\n<p>If you want the remainder, either one of the following approaches will do:</p>\n<pre><code>num - parseInt(num, 10);\n//or\nnum%1//modulo || remainder of division by 1\n</code></pre>\n<p>Note that in this last case, you <em>will</em> see the rounding errors of the IEE754 spec show up, so:</p>\n<pre><code>num = 123.321;\n//get length of string rep for total number - int length, -1 for .\nvar fix = (&quot;&quot;+num).length - (&quot;&quot;+parseInt(num, 10)).length - 1;\n(num%1).toFixed(fix);\n</code></pre>\n<p>Might be required.</p>\n<p>As far as the fraction representation of a number is concerned, that is going to take some work. Thankfully, it's <a href=\"https://github.com/ekg/fraction.js\" rel=\"nofollow noreferrer\">all been done before</a> and the code is available on github.</p>\n<p>I don't know what you mean by: <em>&quot;It does not consider negative numbers&quot;</em>, because, like I said before: there is but one type for numbers in JS, and so it's always signed. Just use the absolute value, and keep track of the what the number was initially (prositive or negative) like so:</p>\n<pre><code>function processNumber(num)\n{\n var sign = !(num &gt; 0);//bool, true if num is negative\n var workVal = Math.abs(num);//get absolute value\n var returnObj = {};\n returnObj.intVal = parseInt(workVal, 10);\n returnObj.floatPart = (workVal%1).toFixed((&quot;&quot;+workVal).length - (&quot;&quot;+returnObj.intVal).length - 1);\n returnObj.fixed2 = workVal.toFixed(2);\n //and so on...\n if (sign === true)\n {\n for (prop in returnObj)\n {\n if (returnObj.hasOwnProperty(prop))\n {//they're all strings, just prepend the sign...\n returnObj[prop] = '-' + returnObj[prop];\n }\n }\n }\n return returnObj;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T11:23:46.007", "Id": "53776", "Score": "0", "body": "Seems I should have been clear about my code, apologizes for that. What my code does is, when you give a decimal number as input, it will give you its normalized representation with value of exponent and significand which will be stored in memory. The problem here I am trying to solve is, when you give a decimal number, how it will be stored in memory in IEEE-754 format." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T11:50:43.657", "Id": "53780", "Score": "2", "body": "@avi: That's exactly why I kicked off my answer with a link to the ECMA specification. _All_ numbers are stored in IEEE-754 64bit numbers. With all quirks this format that entails." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:37:32.423", "Id": "33507", "ParentId": "33442", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T11:04:11.153", "Id": "33442", "Score": "2", "Tags": [ "javascript", "floating-point" ], "Title": "Floating point representation in IEEE 754 format" }
33442
Simulation is the imitation of some real thing, state of affairs, or process. The act of simulating something generally entails representing certain key characteristics or behaviours of a selected physical or abstract system.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:16:43.837", "Id": "33445", "Score": "0", "Tags": null, "Title": null }
33445
<p>This tag refers to the <em>State</em> design pattern.</p> <p>References:</p> <ul> <li><p>The <a href="http://en.wikipedia.org/wiki/State_pattern" rel="nofollow">Wikipedia page</a> on the State pattern.</p></li> <li><p><a href="http://gameprogrammingpatterns.com/state.html" rel="nofollow">Design Patterns Revisited</a> - State.</p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:18:53.457", "Id": "33446", "Score": "0", "Tags": null, "Title": null }
33446
The State pattern is used to represent the internal state of an object and to encapsulate varying behavior for the same object based on its state. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements and thus improve maintainability.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:18:53.457", "Id": "33447", "Score": "0", "Tags": null, "Title": null }
33447
An abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds-checking.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:20:27.857", "Id": "33449", "Score": "0", "Tags": null, "Title": null }
33449
<p>A <a href="http://en.wikipedia.org/wiki/Heap_%28data_structure%29" rel="nofollow">heap</a> is a specialized tree-based data structure that is either</p> <ul> <li><strong>a max heap:</strong> the largest key is in the root node, and the keys of parent nodes ≥ those of the children</li> <li><strong>a min heap:</strong> the smallest key is in the root node, and the keys of parent nodes ≤ those of the children</li> </ul> <p>A min heap is a particularly efficient data structure for implementing priority queues, where it is necessary to repeatedly remove the element with the smallest key. Each <code>find_min()</code> operation takes constant time, and each <code>delete_min()</code> operation can be accomplished in Θ(log <em>n</em>) time.</p> <hr> <p>In programming, <a href="http://en.wikipedia.org/wiki/Heap_%28programming%29" rel="nofollow">"the heap"</a> is a term referring to an area of memory from which storage for non-local variables can be dynamically allocated. For such questions, use the <a href="/questions/tagged/memory-management" class="post-tag" title="show questions tagged &#39;memory-management&#39;" rel="tag">memory-management</a> tag instead.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:23:05.960", "Id": "33450", "Score": "0", "Tags": null, "Title": null }
33450
A heap is a tree-based data structure that satisfies the heap property. For questions about memory allocated from the system heap, use the [memory-management] tag.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:23:05.960", "Id": "33451", "Score": "0", "Tags": null, "Title": null }
33451
SFML (Simple Fast Media Library) is a portable and easy to use multimedia API written in C++. You can see it as a modern, object-oriented alternative to SDL. SFML is composed of several packages to perfectly suit your needs. You can use SFML as a minimal windowing system to interface with OpenGL, or as a fully-featured multimedia library for building games or interactive programs.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T12:25:23.423", "Id": "33453", "Score": "0", "Tags": null, "Title": null }
33453
<p>I have created a function using jQuery Ajax which create a new CSS element whenever I update the database using a form.</p> <p>Is it ok? If not, hat can be the best method to do it?</p> <pre><code>$(document).ready(function(){ $('#statusupdater').submit(function(e) { updatestatus(); e.preventDefault(); }); }); function updatestatus() { $.ajax({ type: "POST", url: "statusupdate.php", data: $('#statusupdater').serialize(), dataType: "dataString" }); $('#statuscontainer').prepend( $('&lt;div id="stat"&gt;').load('statusupdate.php')); $("#statusupdater")[0].reset(); $('.statuspop').fadeOut(300); $('#opacify').hide(); } </code></pre> <p><strong>statusupdate.php</strong></p> <pre><code>&lt;?php include "dbcon.php"; $status=$_POST['status']; $photo=$_POST['photoupload']; if ($status || $photo) { $date = date('m/d/Y h:i:s'); $statusinsert = mysqli_query($con,"INSERT INTO status (st_id,statu,date_created,userid) VALUES ('','$status','$date','$id')" ); } $selectstatus = mysqli_query($con,"select * from status where userid = '".$id."' order by st_id desc limit 1"); $getstatus=mysqli_fetch_array($selectstatus); ?&gt; &lt;div class="statbar"&gt;&lt;?php echo $getstatus["userid"];?&gt;&lt;/div&gt; &lt;div class="stattxt"&gt;&lt;?php echo $getstatus["statu"];?&gt;&lt;/div&gt; </code></pre>
[]
[ { "body": "<p>Set the return datatype to html and update the DOM in the success callback:</p>\n\n<pre><code>function updatestatus()\n{\n $.ajax({\n type: \"POST\",\n url: \"statusupdate.php\",\n data: $('#statusupdater').serialize(),\n dataType: \"html\",\n success: function(data, status, xhrObj){\n $('#statuscontainer').prepend($('&lt;div id=\"stat\"&gt;').html(data));\n $(\"#statusupdater\")[0].reset();\n $('.statuspop').fadeOut(300);\n $('#opacify').hide();\n }\n });\n}\n</code></pre>\n\n<p>You could also update the DOM using the <code>error</code> and <code>statusCode</code> callbacks if it fails.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T13:33:58.123", "Id": "33457", "ParentId": "33455", "Score": "3" } }, { "body": "<p>There really isn't much here and Ben got the big one. In addition to using the success callback, you could pass the form into your <code>updatestatus()</code> function. This will allow you to reuse this code, if necessary, and forces you to use a referenced pointer to the jQuery object rather than forcing jQuery to rebuild it every time you need to do something with it. Additionally, if you use the form's <code>action</code> and <code>method</code> attributes you wont have to worry about changing the <code>url</code> and <code>type</code> indices on multiple pages.</p>\n\n<pre><code>updatestatus( $( this ) );\n\nfunction updatestatus( $form ) {\n $.ajax({\n type: $form.attr( 'method' ),\n url: $form.attr( 'action' ),\n data: $form.serialize(),\n dataType: \"html\",\n success: function( data ){\n $('#statuscontainer').prepend($('&lt;div id=\"stat\"&gt;').html(data));\n $form[0].reset();\n $('.statuspop').fadeOut(300);\n $('#opacify').hide();\n }\n });\n}\n</code></pre>\n\n<p>Finally, you should really sanitize user input instead of using it directly.</p>\n\n<pre><code>$status = filter_input( INPUT_POST, 'status', FILTER_SANITIZE_STRING );\n</code></pre>\n\n<p>The only other thing I've really noticed is some minor inconsistencies in styling.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T04:57:57.340", "Id": "33820", "ParentId": "33455", "Score": "1" } } ]
{ "AcceptedAnswerId": "33457", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T13:07:12.027", "Id": "33455", "Score": "1", "Tags": [ "javascript", "php", "jquery", "css", "ajax" ], "Title": "Creating new CSS element everytime database updates" }
33455
<p>I would like some feedback on the appropriate way of ordering a numerical list using the most elementary <code>scheme</code> functions (sorry, i realise that elementary is not well defined). </p> <p>By way of background: I've been learning a bit of <code>scheme</code> on my ipad, where I have only a basic implementation -- this is a nice challenge as much as a problem, as i have to figure out simple things like sorting a list for myself. </p> <p>In doing this, i learnt that <code>(append (cdr list) (car list))</code> is not what you might expect -- which is how i had originally <em>wanted</em> to implement this simple sort. </p> <p>To hack around it, i discovered <code>list-tail</code> and <code>reverse</code> -- see the <code>else</code> clause below. </p> <pre><code>(define ra-sort (lambda (numList) (cond ((null? numList) '()) ((= (car numList) (apply max numList)) (cons (car numList) (ra-sort (cdr numList)))) (else (ra-sort (append (list-tail numList (- (length numList) 1)) (reverse (list-tail (reverse numList) 1))))) ))) (define a '(99 1 6 12 101 2 67 -3)) &gt; (ra-sort a) (101 99 67 12 6 2 1 -3) </code></pre> <p>Now this seems to work, but all this repeated calling of <code>reverse</code> seems <em>inefficient</em> -- how should it be done? </p> <p>Or am i missing something? Is it possible to make things work with the output of <code>(append (cdr a) (car a))</code>? </p> <p>what does the notation even mean in <code>(1 6 12 101 2 67 -3 . 99)</code>? and how is it useful? </p>
[]
[ { "body": "<p>So to answer your specific question, yes you can greatly simplify your algorithm in a couple places:</p>\n\n<pre><code>(list-tail numList (- (length numList) 1))\n</code></pre>\n\n<p>So you're taking the last <code>n - 1</code> elements of a list of length <code>n</code>? That's exactly:</p>\n\n<pre><code>(cdr numList)\n</code></pre>\n\n<p>As for this part:</p>\n\n<pre><code>(reverse (list-tail (reverse numList) 1))\n</code></pre>\n\n<p>So the <code>list-tail</code> will return a list of size 1, so you can drop the outer-most <code>reverse</code> entirely. Secondly, what are you getting here? Just the first element right? Which is to say...</p>\n\n<pre><code>(car numList)\n</code></pre>\n\n<p>So putting that together, we end up with this (+/- missing parens)</p>\n\n<pre><code>(define ra-sort\n (lambda (numList)\n (cond\n ((null? numList) '())\n ((= (car numList) (apply max numList))\n (cons (car numList) (ra-sort (cdr numList))))\n (else (ra-sort (append (cdr numList) (list (car numList))))\n )))\n</code></pre>\n\n<p>Ok so now think about this algorithm. At each iteration, we're checking if the head is in the right place, if it is we go to the next element, else we rotate the whole array. Checking if the first element is the max takes <code>O(n)</code> time. We expect to have to do this <code>O(n)</code> times per element, for every element... so we end up with <code>O(n^3)</code>.</p>\n\n<p>A simple insertion sort, which is what I think you're trying to implement, should be only <code>O(n^2)</code>. So try to redo your algorithm so that instead of just checking if the first elem is the maximum one, you actually find it. So your inner clause would be something like:</p>\n\n<pre><code>(cons maxElem # largest element\n (ra-sort (remove-elem numList maxElem)) # + rest of list\n)\n</code></pre>\n\n<p>That'll get you to where you want to be. At least for this sorting algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:38:59.077", "Id": "53622", "Score": "0", "body": "+1, thanks. I had realised that i wanted to switch the `cdr` of the list and the `car` of the list, but couldn't figure out how to do it. I had not realised that it failed as `(list? (car numList))` is `#f`, and that i could fix it with `(list (car numList))`. I do not have a `remove-elem` function, so i'll have to write that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T22:19:25.347", "Id": "53633", "Score": "0", "body": "i made a crude `remove-elem` function -- and asked a follow up [question](http://codereview.stackexchange.com/questions/33481/remove-first-occurance-of-element-from-list) about it. thanks for your help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T18:41:28.867", "Id": "33476", "ParentId": "33456", "Score": "1" } } ]
{ "AcceptedAnswerId": "33476", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T13:24:15.113", "Id": "33456", "Score": "1", "Tags": [ "scheme", "sorting" ], "Title": "sorting a numerical list using basic scheme" }
33456
<p>I have a static class:</p> <pre><code>public static class ConfigurationDetails { public static string SharepointServer { get; set; } public static string Username { get; set; } public static string Password { get; set; } public static string SharepointDomain { get; set; } public static string ServiceLibrary { get; set; } public static string SqlServer { get; set; } public static string SQLUsername { get; set; } public static string SQLPassword { get; set; } public static string SQLDomain { get; set; } } </code></pre> <p>which needs to be updated from the values of a dictionary.</p> <p>Using if the code is below:</p> <pre><code>var configValues = ReadConfiguration(); if (configValues.ContainsKey("SharepointServer")) { ConfigurationDetails.SharepointServer = configValues["SharepointServer"]; } if (configValues.ContainsKey("ServiceLibrary")) { ConfigurationDetails.ServiceLibrary = configValues["ServiceLibrary"]; } if (configValues.ContainsKey("Username")) { ConfigurationDetails.Username = configValues["Username"]; } if (configValues.ContainsKey("Password")) { ConfigurationDetails.Password= configValues["Password"]; } </code></pre> <p>Now this will do the job, but there would be a lot of <code>if</code>s. I've tried with LINQ, but this is the closest I've gotten:</p> <pre><code>configValues.Where(kv =&gt; kv.Key == "SharepointServer").ToList().ForEach(kv =&gt; ConfigurationDetails.SharepointServer = kv.Value); </code></pre> <p>and it's not doing any good. Any other ideas, please?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:21:57.930", "Id": "54296", "Score": "1", "body": "As a side-note: I wouldn't make configuration a static class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T18:14:05.990", "Id": "54326", "Score": "0", "body": "How much control do you have over the ReadConfiguration method? Could it be refactored to return a ConfigurationDetails instance rather than a dictionary?" } ]
[ { "body": "<p>One solution would be to encapsulate the logic into a method. A problem with that is that there is no simple way to pass a property to the method.</p>\n\n<p>If the case where the key is not in the dictionary means that the value is <code>null</code>, then you could write an extension method for <code>IDictionary</code> that returns the value, if it's present, or <code>null</code>:</p>\n\n<pre><code>public static string GetValueOrDefault(this IDictionary&lt;string, string&gt; dict, string key)\n{\n string result;\n dict.TryGetValue(key, out result);\n return result;\n}\n</code></pre>\n\n<p>You would then use it like this:</p>\n\n<pre><code>ConfigurationDetails.SharepointServer = configValues.GetValueOrDefault(\"SharepointServer\");\n</code></pre>\n\n<p>Another option (assuming the names of properties and keys always match) would be to use reflection to set all the properties at the same time. Something like:</p>\n\n<pre><code>var properties = typeof(ConfigurationDetails).Getproperties();\nforeach (var property in properties)\n{\n string value;\n if (configValues.TryGetValue(property.Name, out value))\n {\n property.SetValue(null, value);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T15:24:35.343", "Id": "33467", "ParentId": "33463", "Score": "10" } }, { "body": "<p>First off: \nI think, LINQ is of little help.</p>\n\n<ol>\n<li><p>You could do yourself a favour and change your configuration to a Dictionary and the problem would not occur.</p></li>\n<li><p>You could do it with the ternary operator:</p>\n\n<pre><code>ConfigurationDetails.SharepointServer=(configValues.ContainsKey(\"SharepointServer\"))?configValues[\"SharepointServer\"]:default;\n</code></pre>\n\n<p>To make things easier, you could wrap it up into a method like svick's solution</p></li>\n<li><p>You could do it like svick</p></li>\n<li><p>You could do it automagically, if you drop the idea of a static class, which is by the way nasty, and deal with a configuration object. then, you could leverage <em>reflection</em> to set the according fields, depending on the keys in your dictionary. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T15:46:20.337", "Id": "53595", "Score": "0", "body": "Oooh automagic reflection... I like :) and +1 for static class being nasty!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T15:42:22.220", "Id": "33468", "ParentId": "33463", "Score": "3" } }, { "body": "<p>I would carefully think about the class design. </p>\n\n<p>Do you really want your configuration values to be writable from outside the ConfigurationDetails class? </p>\n\n<p>Is ReadConfiguration a really expensive method? If not, why should you read the configuration once instead of reading it every time when user requests it? [In the current design, how would user force a refresh of configuration?]</p>\n\n<p>Do you really want to return NULL for setting value when it's not configured? I prefer to throw a helpful exception which can help me troubleshoot the problem just in case I forgot to specify a key or mistyped it.</p>\n\n<p>I can not answer the above questions for you but this is what you should think about.</p>\n\n<p>Assuming that ReadConfiguration method is cheap, here's how I would write the ConfigurationDetails class. </p>\n\n<pre><code>public static class ConfigurationDetails\n{\n public static string SharepointServer { get { return GetConfigValue('SharepointServer'; }\n\n public static string Username { get { return GetConfigValue(\"Username\"); }\n\n public static string Password { get { return GetConfigValue(\"Password\"); }\n\n /* Fill in the rest */\n\n private static string GetConfigValue(string key)\n {\n var configValues = ReadConfiguration();\n\n if(! configValues.ContainsKey(key))\n throw new ConfigurationErrorsException(\"Could not find configuration for key \" + key);\n\n return configValues[key];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T18:16:59.580", "Id": "54327", "Score": "0", "body": "Alternatively, if the configuration changes infrequently (or not at all), you could change ConfigurationDetails to be an instance class and use a Lazy<T> field for the configuration dictionary. In the case where there are infrequent changes, you can have a method to reset (i.e., re-assign) the field." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T17:55:32.020", "Id": "33530", "ParentId": "33463", "Score": "3" } }, { "body": "<p>Compressed code could look like:</p>\n\n<pre><code>string dictValue;\nConfigurationDetails.SharepointServer = \n configValues.TryGetValue(\"SharepointServer\", out dictValue) \n ? dictValue : null;\n</code></pre>\n\n<p>TryGetValue also sets dictValue to null if it fails, thus no init required on declaration.</p>\n\n<p>Anyway, I would not like a static class, but pass the dictionary to a constructor or Configure(IDictionary ...) method, and also validate the input before taking it into the config.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T20:05:45.943", "Id": "33541", "ParentId": "33463", "Score": "0" } }, { "body": "<p>I know it would not be worth answering this question, but I would like to suggest that using a dictionary and expecting optimization would not be a good idea.</p>\n\n<p>I have tried to refactor my conditions from <code>if</code>/<code>else</code> or <code>switch</code> to dictionary, and you won't believe that it has cost me more resources than a simple <code>if</code>/<code>else</code>.</p>\n\n<p>So you could try to resolve this issue by using Strategy Patterns. That can help you out for such issues. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-21T14:31:35.987", "Id": "54867", "ParentId": "33463", "Score": "2" } } ]
{ "AcceptedAnswerId": "33467", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T14:36:52.673", "Id": "33463", "Score": "7", "Tags": [ "c#", ".net", "linq" ], "Title": "Optimizing multiple if-else from static class with LINQ" }
33463
<p>I have the following structure:</p> <pre><code>struct Keys { //value of word in the vector&lt;string&gt; words. string word; //index of word in the vector&lt;string&gt; words. int index; //I want to compare the element **word** of the structure, this is why i overloaded the operators //After Editing bool operator&gt;(const Keys&amp; rhs) const { return word &gt; rhs.word; } bool operator==(const Keys&amp; rhs) const { return word == rhs.word; } }; </code></pre> <p>I want to insert this structure into a Red Black tree, then I want to search for a given word and print its index.</p> <pre><code>int main() { kreb = new RedBlackTree&lt;Keys&gt;(); vector&lt;string&gt; words; words.push_back("hello"); words.push_back("how"); words.push_back("are"); words.push_back("you"); for(size_t i = 0; i &lt; words.size(); i++) { kreb-&gt;InsertNode({words[i],i}); } string w = "hello"; //if word is found if(kreb-&gt;AccessNode({w,0}) != 0) { cout &lt;&lt; kreb-&gt;AccessNode({w,0})-&gt;GetValue().index &lt;&lt; endl; } } </code></pre> <p>Instead of inserting integers into the red black tree, I want to insert a structure. In the structure, I've overloaded the operators <code>&gt;</code> and <code>==</code> to be able to compare the structure objects in the red black tree (or whatever it is called).</p> <p>What do you think? I am new to C++ and I want to be sure that I am doing it correctly. </p> <p><strong>Red-Black Tree Code:</strong></p> <pre><code>#include &lt;queue&gt; #include &lt;stack&gt; #include &lt;windows.h&gt; //for coloring output only using namespace std; template &lt;class T&gt; class RBNode { private: bool isRed; T value; RBNode&lt;T&gt; *left, *right, *parent; public: //Node() //{ // left = NULL; // right = NULL; //} RBNode(T value) { this-&gt;isRed = true; this-&gt;value = value; left = NULL; right = NULL; parent = NULL; } void Recolor() { if (this-&gt;isRed) this-&gt;isRed = false; else this-&gt;isRed = true; } bool IsRed() { return isRed; } T GetValue() { return this-&gt;value; } RBNode* GetLeft() { return this-&gt;left; } RBNode* GetRight() { return this-&gt;right; } RBNode* GetParent() { return this-&gt;parent; } void ClearParent() { this-&gt;parent = NULL; } void SetLeft(RBNode* left) { this-&gt;left = left; if(left != NULL) left-&gt;parent = this; } void SetRight(RBNode* right) { this-&gt;right = right; if(right != NULL) right-&gt;parent = this; } }; template &lt;class T&gt; class RedBlackTree { private: RBNode&lt;T&gt;* root; //the three basic functionalities (inner implementation) RBNode&lt;T&gt;* AccessNode(RBNode&lt;T&gt; *root, T value) { if(root-&gt;GetValue() == value) { return root; } else if(root-&gt;GetValue() &gt; value) { if(root-&gt;GetLeft() == NULL) { return NULL; } else { return this-&gt;AccessNode(root-&gt;GetLeft(), value); } } else { if(root-&gt;GetRight() == NULL) { return NULL; } else { return this-&gt;AccessNode(root-&gt;GetRight(), value); } } } void InsertNode(RBNode&lt;T&gt; *root, T value) { //regular BST insert RBNode&lt;T&gt;* insertedNode = NULL; if(root-&gt;GetValue() == value) { //skip } else if(root-&gt;GetValue() &gt; value) { if(root-&gt;GetLeft() == NULL) { insertedNode = new RBNode&lt;T&gt;(value); root-&gt;SetLeft(insertedNode); } else { this-&gt;InsertNode(root-&gt;GetLeft(), value); } } else { if(root-&gt;GetRight() == NULL) { insertedNode = new RBNode&lt;T&gt;(value); root-&gt;SetRight(insertedNode); } else { this-&gt;InsertNode(root-&gt;GetRight(), value); } } //restore uniform black height if (insertedNode == NULL) return; this-&gt;SolveDoubleRedProblem(root); insertedNode = NULL; } public: RedBlackTree() { this-&gt;root = NULL; } bool IsEmpty() { return root == NULL; } //the three basic functionalities (clients interface) RBNode&lt;T&gt;* AccessNode(T value) { if (this-&gt;IsEmpty()) return NULL; else return this-&gt;AccessNode(root, value); } void InsertNode(T value) { if (this-&gt;IsEmpty()) { this-&gt;root = new RBNode&lt;T&gt;(value); this-&gt;root-&gt;Recolor(); } else this-&gt;InsertNode(this-&gt;root, value); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T18:36:17.837", "Id": "53600", "Score": "0", "body": "I'm getting an auto-flag saying that this is excessively long. You could probably split the red-black code into different parts, or just leave out some portion of it. Just keep whatever you absolutely need reviewed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:40:46.130", "Id": "53607", "Score": "0", "body": "ok @Jamal. All what I need from the Three is the Insert and AccessNode Functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:41:24.467", "Id": "53608", "Score": "0", "body": "Is the **bool operator>(const Keys& rhs){ return rhs.word < word; }** in the Key structure correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:52:17.527", "Id": "53612", "Score": "0", "body": "ok no problem. See @Jamal what i am doing is inserting Objects into the tree instead for example of integers and strings only. and I am comparing the objects by using Word." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:53:16.220", "Id": "53613", "Score": "0", "body": "the Tree class is not important. I am sure that it's right. I just need to know if the Operators > and == are right. And If can use another structure" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:55:01.920", "Id": "53614", "Score": "0", "body": "Yes, those should work, though I think `operator>` should be `word > rhs.word` or `!(word < rhs.word)`. They should also both be `const`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:55:59.020", "Id": "53615", "Score": "0", "body": "I see i'll edit the text.np" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:59:18.423", "Id": "53616", "Score": "0", "body": "The `const` in both overloads would look like this: `bool operator==(const Keys& rhs) const { return word == rhs.word; }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:00:21.883", "Id": "53617", "Score": "0", "body": "@Jamal one more question in the part \n**if(kreb->AccessNode({w,0}) != 0)** Can I use NULL instead of 0 **if(kreb->AccessNode({w,NULL}) != 0)** When I am doing the comparison I just Just the first parameter **w**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:04:31.277", "Id": "53618", "Score": "0", "body": "Yes, just use `NULL` when dealing with pointers and such (not numerical values). Or, if you have C++11, use `nullptr`." } ]
[ { "body": "<ul>\n<li><p><code>operator&gt;</code> and <code>operator==</code> are correct, but you should also define their complements. Users may also expect an <code>operator&lt;</code> and an <code>operator!=</code>:</p>\n\n<pre><code>bool operator&lt;(const Keys&amp; rhs) const { return word &lt; rhs.word; }\n</code></pre>\n\n<p></p>\n\n<pre><code>bool operator!=(const Keys&amp; rhs) const { return !(word == rhs.word); }\n</code></pre></li>\n<li><p><a href=\"https://stackoverflow.com/a/276053/1950231\">Prefer <code>std::size_type</code> over <code>size_t</code> for the vector's loop counter type</a>:</p>\n\n<pre><code>// template type depending on specific vector type\nstd::vector&lt;std::string&gt;::size_type;\n</code></pre>\n\n<p>This will allow you to access the entire vector, regardless of its size. <code>std::size_type</code> is also portable as it is defined as part of each STL container.</p></li>\n<li><p>Prefer <a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\"><code>nullptr</code></a> to <code>NULL</code> if using C++11.</p></li>\n<li><p>Member functions that don't modify data members should be <code>const</code>. This would include the \"getters\" and those that return <code>bool</code>.</p></li>\n<li><p>The <code>this-&gt;</code> is not needed everywhere as the current object is already in scope. However, you will need it if a parameter shares the same name as a data member (commonly found in a constructor). Then, you'll need the <code>this-&gt;</code> to refer to the data member.</p></li>\n<li><p><code>RBNode()</code> and <code>RedBlackTree()</code>:</p>\n\n<pre><code>RBNode(T value)\n{\n this-&gt;isRed = true;\n this-&gt;value = value;\n left = NULL;\n right = NULL;\n parent = NULL;\n}\n</code></pre>\n\n<p></p>\n\n<pre><code>RedBlackTree()\n{\n this-&gt;root = NULL;\n}\n</code></pre>\n\n<p>should be <a href=\"https://stackoverflow.com/questions/4589237/c-initialization-lists\">initializer lists</a>:</p>\n\n<pre><code>// could still be written vertically\n// to make list easier to maintain\nRBNode(T value)\n : isRed(true)\n , value(value)\n , left(NULL)\n , right(NULL)\n , parent(NULL)\n{}\n</code></pre>\n\n<p></p>\n\n<pre><code>RedBlackTree() : root(NULL) {}\n</code></pre></li>\n<li><p>You have this in <code>main()</code>:</p>\n\n<pre><code>kreb = new RedBlackTree&lt;Keys&gt;();\n</code></pre>\n\n<p>...but no <code>delete</code> anywhere! Whenever you use <code>new</code>, you <em>must</em> use <code>delete</code> appropriately, otherwise you'll cause a memory leak. <a href=\"https://stackoverflow.com/questions/147130/why-doesnt-c-have-a-garbage-collector\">C++ doesn't have a garbage collector</a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:16:58.177", "Id": "53640", "Score": "3", "body": "C++ **Fortunately** dies not have a garbage collector. It has fine grain deterministic garbage collection that guarantees that object destructors are called correctly. Garbage collected languages have problems guaranteeing object destruction and even when the destructor is called it does not mean the object is dead see [Java Resurrection](http://www.javacodegeeks.com/2012/12/java-object-resurrection.html) and see [C# implementing disposable the Garbage collector suppression and multiple destroys](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T20:24:36.400", "Id": "33478", "ParentId": "33470", "Score": "3" } }, { "body": "<p>You already use <code>std::vector</code> in your example, so then why don't you use <code>std::map</code>? All known <code>std::map</code> implementations are red-black tree based.</p>\n\n<p>Example:</p>\n\n<pre><code>typedef map&lt;string, int&gt; RedBlackTree;\nRedBlackTree myStorage;\n\nfor(size_t i = 0; i &lt; words.size(); i++)\n myStorage.emplace(words[i], i);\n\nstring w = \"hello\";\nauto itr = myStorage.find(w);\nif (itr != mtStorade.cend())\n cout &lt;&lt; itr-&gt;second &lt;&lt; endl;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:01:02.380", "Id": "54255", "Score": "0", "body": "Thank you. Your suggestion is great. I am actually using `multimap` which allows duplicates. `map` won't allow it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T08:53:11.877", "Id": "33569", "ParentId": "33470", "Score": "2" } } ]
{ "AcceptedAnswerId": "33478", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T16:19:46.197", "Id": "33470", "Score": "2", "Tags": [ "c++", "beginner", "classes", "tree" ], "Title": "Building a Red Black tree using a structure as a node" }
33470
<p>I have a form that I feel I am overcomplicating because of the relationship between models that are involved. Can you let me know if there's a more elegant solution to what I have?</p> <p>(<em>for reference</em>) The form ultimately looks like this:</p> <p><img src="https://i.stack.imgur.com/AOJ85.png" alt="Form that uses dots to represent select options"></p> <p>The relationship between the involved models:</p> <pre><code>user_relation has_many :user_relation_skills user_relation_skills has_many :progresses progress has_many :ratings, :as =&gt; :ratable </code></pre> <p>The form looks like this (I removed most of the classes/extraneous information but left the divs in to give a better idea of whats going on):</p> <pre><code>&lt;%= simple_form_for(@user_relation) do |f| %&gt; &lt;%= f.fields_for :user_relation_skills do |ff| %&gt; &lt;%= ff.fields_for :progresses do |fff| %&gt; &lt;%= fff.fields_for :ratings do |ffff| %&gt; &lt;div&gt; &lt;div&gt; &lt;%= link_to(user_relation_skill_path(ffff.object.scope)) do %&gt; &lt;%= ffff.object.scope.skill.category.name %&gt;&amp;nbsp&lt;i class='icon-arrow-right'&gt;&lt;/i&gt;&amp;nbsp&lt;%= ffff.object.scope.skill.name %&gt; &lt;% end %&gt; &lt;/div&gt; &lt;/div&gt; &lt;% if @current_type_for_views == 'coach' %&gt; &lt;div&gt; &lt;div&gt; &lt;%= ffff.select("value", 1..8, {}, {class: "ratings-skill"}) %&gt; &lt;/div&gt; &lt;div&gt; &lt;div class='small-offset-8 small-4 columns'&gt; &lt;%= button_tag(type: 'submit', class: "small button") do %&gt; &lt;i class="icon-check"&gt;&lt;/i&gt;Update &lt;% end %&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;% else %&gt; &lt;div&gt; &lt;div&gt; &lt;%= ffff.select("value", 1..8, {}, {class: "static-rating"}) %&gt; &lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>Are this many 'nests' in a form typical or should I be doing something else?</p> <p>I'm including part of a simple UML diagram with a focus on the "Rating" model that is attached to many things (there are lots of things in the app that can be rated):</p> <p>Most of the lines going up out of the screen connect either to unimportant models or Active Record directly. The only pertinent thing that is not pictured is the fact that Rating rates Users (a user model that someone would typically expect).</p> <p><img src="https://i.stack.imgur.com/8HYZ1.png" alt="Not pictured is the fact that Rating rates Users"></p>
[]
[ { "body": "<p>This is hard to say because I don't have a broader context but you may have over normalized your database. Something to consider when building these is that it can sometimes be better to add items to a model instead of doing a has relationship with them. This is the first 4 level deep nested form that I have came across.</p>\n\n<p>This will ultimately be a judgement call on your part, but I follow YAGNI (you ain't gonna need it) pretty strongly and program what i'm doing for just the problem at hand and any glaring long term consequences of the decision.</p>\n\n<p>Outside of that, you could do something like a Factory Pattern that takes care of all of this, I would start with reconsidering your model setup though. </p>\n\n<p>What is the type of problem you are trying to solve with this form and these models?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:34:58.380", "Id": "53684", "Score": "0", "body": "I added a simple uml diagram to show how Rating is tied to many other models not involved in this form (probably why it seems 'over-normalized' when looking at just this form -- we needed a lot of normalization because we use rating in a lot of places). As far as the problem we are trying to solve: We have an administrator-like user signed in who needs to assign a new rating to one or many of the displayed skills. . . So when the user, who is making progress in these skills, signs in they can see the progress they've made in the skill." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T03:34:15.290", "Id": "33491", "ParentId": "33471", "Score": "0" } }, { "body": "<p>This view knows far too much about your data model structure.</p>\n\n<p>One level of nesting is reasonably acceptable, but this many is dangerous : in fact, this view needs knowledge about no less than <em>4 different business objects</em>, not to mention it has to know the <em>relations between them</em>.</p>\n\n<h3>Solution 1 : the <a href=\"http://sourcemaking.com/design_patterns/facade\" rel=\"nofollow\">facade pattern</a></h3>\n\n<p>Abstract away all those details in another object, which would be the sole source of truth for your view : call it a <em>form object</em>, or a <em>presenter</em>, or a <em>context</em> in DCI idiom, whatever.</p>\n\n<p>The idea is that this object has a simple interface that maps to the complex underlying system. We'd need more details on your business logic to be able to help you on this one.</p>\n\n<h3>Solution 2 : cook your own \"accepts_nested_attributes\" method</h3>\n\n<p>on your <code>UserRelation</code> model, create a <code>ratings</code> method that provides direct access to your ratings. Then create another method that allows assignment, like <code>ratings_attributes=</code>. In this method, process the passed parameters to create / update associated ratings ; you can find inspiration for this in the source for the <code>accept_nested_attributes</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T12:36:47.607", "Id": "53685", "Score": "0", "body": "One of these solutions seems likely. Coming from the .NET world - it is standard to use ViewModels to solve many of these sorts of issues (too much model information in the view). I will give this a little while to stew and reply at a later time. (For now I have updated the question with a bit more information due to a response from another user - although that information is likely not pertinent to your response)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T09:42:51.267", "Id": "33499", "ParentId": "33471", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T16:35:45.727", "Id": "33471", "Score": "0", "Tags": [ "ruby", "ruby-on-rails", "form", "active-record" ], "Title": "Form involving several models related to each other" }
33471
<p>I'm working on implementing a syntax highlighter for a simple text editor I've been working on. To do this, I need a simple lexer for various languages (I don't need a full one - I'm only interested in highlighting things like comments, strings, numbers and keywords). The way my editor component works is it highlights the entire document, and then <em>re-highlights lines of the file as they are changed</em>. So I have some requirements for this lexer:</p> <ol> <li>It needs to be "fast," in that it should be more or less real-time while typing.</li> <li>I need to be able to re-lex a given line of text, given the state from the previous blocks (this should be trivial for a lexer implemented as a state machine).</li> <li>It should be written in C or C++ (I am using C++ for my project), and it should be fairly easily maintainable (I realize lexers are usually somewhat "messy", but I still want it as "clean" as possible).</li> </ol> <p>I am aware of and have used in the past various tools for creating lexers like (f)lex, Antlr, Quex, boost::spirit/qi, etc, but as far as I have been able to find none of them satisfy requirement (2) (if you have an example of how to achieve (2) using one of these tools, I would love to see it!).</p> <p>As such, I have implemented a very simple lexer for C-style languages by hand. Note that it is very obviously incomplete as far as language elements, and some more work needs to be done to turn lexer states into actual tokens. Here is my source code so far:</p> <p><strong>CLexer.h</strong></p> <pre><code>#ifndef INCLUDE_C_LEXER_H #define INCLUDE_C_LEXER_H #include &lt;map&gt; #include &lt;vector&gt; #include &lt;string&gt; class CLexer; typedef int (CLexer::*C_LEXER_TRANSITION)(char); struct CLexerToken; typedef struct CLexerToken CLexerToken; class CLexer { public: static const int INITIAL_STATE; CLexer(); virtual ~CLexer(); std::vector&lt;CLexerToken&gt; lexBlock(int &amp;s, const std::string &amp;t, int p); private: static const std::map&lt;int, C_LEXER_TRANSITION&gt; transitions; int rootTransition(char c); int stringTransition(char c); int stringEndTransition(char c); int escapeTransition(char c); }; struct CLexerToken { int start; int count; int state; }; #endif </code></pre> <p><strong>CLexer.cpp</strong></p> <pre><code>#include "CLexer.h" #include &lt;cassert&gt; #define ST_ROOT 1 #define ST_STRING 2 #define ST_STRING_END 3 #define ST_ESCAPE 4 // This is a list of functions which are used to transition between states. const std::map&lt;int, C_LEXER_TRANSITION&gt; CLexer::transitions = { {ST_ROOT, &amp;CLexer::rootTransition}, {ST_STRING, &amp;CLexer::stringTransition}, {ST_STRING_END, &amp;CLexer::stringEndTransition}, {ST_ESCAPE, &amp;CLexer::escapeTransition} }; const int CLexer::INITIAL_STATE = ST_ROOT; CLexer::CLexer() { } CLexer::~CLexer() { } /* * \param s This will receive the state at the end of this block. * \param t The text this block contains. * \param p The state at the end of the previous block. */ std::vector&lt;CLexerToken&gt; CLexer::lexBlock(int &amp;s, const std::string &amp;t, int p) { std::vector&lt;CLexerToken&gt; tokens; int start = 0; int state = p; for(size_t idx = 0; idx &lt; t.length(); ++idx) { std::map&lt;int, C_LEXER_TRANSITION&gt;::const_iterator transit = CLexer::transitions.find(state); assert(transit != CLexer::transitions.cend()); int newstate = (this-&gt;*(transit-&gt;second))(t.at(idx)); if(newstate != state) { CLexerToken tok; tok.start = start; tok.count = idx - start; tok.state = state; if(tok.count &gt; 0) { tokens.push_back(tok); } start = idx; } state = newstate; } CLexerToken tok; tok.start = start; tok.count = t.length() - start; tok.state = state; if(tok.count &gt; 0) { tokens.push_back(tok); } s = state; return tokens; } int CLexer::rootTransition(char c) { switch(c) { case '"': return ST_STRING; default: return ST_ROOT; } } int CLexer::stringTransition(char c) { switch(c) { case '\\': return ST_ESCAPE; case '"': return ST_STRING_END; default: return ST_STRING; } } int CLexer::stringEndTransition(char c __attribute__((unused))) { return ST_ROOT; } int CLexer::escapeTransition(char c __attribute__((unused))) { return ST_STRING; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include "CLexer.h" int main(void) { // A REALLY simple test program to lex. std::vector&lt;std::string&gt; lines { "#include &lt;iostream&gt;", "", "int main(void)", "{", "\tstd::cout &lt;&lt; \"Hello, world!\\n\";", "", "\treturn 0;", "}", "" }; CLexer lexer; int state = CLexer::INITIAL_STATE; for(size_t idx = 0; idx &lt; lines.size(); ++idx) { std::vector&lt;CLexerToken&gt; tokens = lexer.lexBlock(state, lines.at(idx), state); for(std::vector&lt;CLexerToken&gt;::iterator it = tokens.begin(); it != tokens.end(); ++it) { std::cout &lt;&lt; "Lexeme on line " &lt;&lt; (idx + 1) &lt;&lt; " from " &lt;&lt; (*it).start &lt;&lt; " for " &lt;&lt; (*it).count &lt;&lt; ", type " &lt;&lt; (*it).state &lt;&lt; "\n"; } } return 0; } </code></pre> <p>I'm hoping for feedback on my design - can I simplify this code to make it more maintainable? Is there a way I can use an existing tool to achieve the same thing?</p> <p>Note: I have been working on this code using gcc 4.7.3, with the flags <code>-Wall -Wextra -ansi -pedantic -Wshadow -Wpointer-arith -Wcast-qual -pipe -fomit-frame-pointer -Wall -W -O2 -std=c++0x</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T23:45:44.633", "Id": "53637", "Score": "0", "body": "It would be much easier to write in `flex`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T23:49:04.733", "Id": "53638", "Score": "0", "body": "No doubt, but I am not sure it is possible to satisfy my second requirement with flex, and re-lexing the entire document every time any change at all is made seems to violate my first requirement. Can you write or link an example of how to re-lex from a particular line after lexing the entire document once with flex?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:04:45.927", "Id": "53639", "Score": "0", "body": "Not sure youre requirements are valid. Why would you need to have state from the previous line. Normally the syntax highligter only highlights based on the type of the object string/keyword/identifier/literal etc. It does not use context from previous lines. Note: String (or other tokens) do can not cross lines in C/C++. Try vim. It highlights without regard to correct syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:18:04.967", "Id": "53641", "Score": "0", "body": "Certain things that will be highlighted can most definitely span multiple lines - e.g., comments (`/* ... */`) or preprocessor defines (`#define ... \\ `). If the user alters a line, and the previous line opened a comment block, my lexer needs to know this so it knows whether to mark the line as being a comment, or containing keywords (for example)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:21:01.337", "Id": "53643", "Score": "0", "body": "OK: I'll give you those two. Anything else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:29:25.857", "Id": "53645", "Score": "0", "body": "In the scope of this example, those are the only two I can think of. I still want a robust lexer, though, so in the future I can add support for more languages or make my highlighting rules more complex (e.g. some basic syntax checking might be something I look into doing further down the road)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T19:23:52.343", "Id": "54159", "Score": "2", "body": "I don't know much about Lexers myself, but I would suggest learning from the way that other projects do it. See http://sourceforge.net/p/scintilla/code/ci/default/tree/lexers/ for examples of lexers for the popular Scintilla Editor component. They also have lots of documentation on [their site](http://www.scintilla.org/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T20:45:06.993", "Id": "94061", "Score": "0", "body": "@LokiAstari Raw string literals. Which is ugly because the delimiter is user-defined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-11T20:48:33.363", "Id": "94063", "Score": "0", "body": "I'm not sure why you use a `std::map` here. It is a convenient data structure, but the convenience has a price in both space and time. Since the keys are contiguous anyway, you could use an array as well (maybe plus range checks), this would even allow compile-time initialization." } ]
[ { "body": "<ul>\n<li><p>You're using single-character variables in various places. With the exception of typical loop counters (such as <code>i</code>), variables should be descriptive and not need comments to help explain their meaning. This will also help you remember what they're for at a later point in the program.</p></li>\n<li><p>There are some remnants of C code that are not required in C++:</p>\n\n<ul>\n<li>You have a <code>typedef struct</code>, but C++ does the same thing with just <code>struct</code>.</li>\n<li>Functions with no parameters don't need <code>void</code>.</li>\n<li><code>return 0</code> is already applied by the compiler at the end of <code>main()</code>.</li>\n</ul></li>\n<li><p>You can now use C++11's <a href=\"http://en.wikipedia.org/wiki/C++11#Explicitly_defaulted_and_deleted_special_member_functions\" rel=\"noreferrer\"><code>default</code> constructor and destructor</a> instead of providing your own.</p>\n\n<p>Instead of having these in the .cpp file:</p>\n\n<blockquote>\n<pre><code>CLexer::CLexer()\n{\n}\n\nCLexer::~CLexer()\n{\n}\n</code></pre>\n</blockquote>\n\n<p>you'll just have these in the .h file:</p>\n\n<pre><code>CLexer() = default;\n~CLexer() = default;\n</code></pre>\n\n<p>In pre-C++11, you would just leave them out and let the compiler make them for you.</p></li>\n<li><p><code>#define</code>s aren't too common in C++ as opposed to C:</p>\n\n<blockquote>\n<pre><code>#define ST_ROOT 1\n#define ST_STRING 2\n#define ST_STRING_END 3\n#define ST_ESCAPE 4\n</code></pre>\n</blockquote>\n\n<p>This should instead be an <a href=\"http://en.cppreference.com/w/cpp/language/enum\" rel=\"noreferrer\"><code>enum</code></a>:</p>\n\n<pre><code>enum State { ROOT=1, STRING, STRING_END, ESCAPE };\n</code></pre>\n\n<p>The <code>1</code> is needed for the initial value (it normally starts at <code>0</code>), while all the following values will be one higher than the previous. This is generally how <code>enum</code>s work.</p></li>\n<li><p>For this loop statement:</p>\n\n<blockquote>\n<pre><code>for(size_t idx = 0; idx &lt; t.length(); ++idx)\n</code></pre>\n</blockquote>\n\n<p>Since <code>t</code> is of type <code>std::string</code>, use <code>std::string::size_type</code> as the loop counter type. This is the specific return value of <code>t.size()</code>. In general, <code>size()</code> returns an <code>std::size_type</code>.</p></li>\n<li><p>This function:</p>\n\n<blockquote>\n<pre><code>int CLexer::rootTransition(char c)\n{\n switch(c)\n {\n case '\"': return ST_STRING;\n default: return ST_ROOT;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>doesn't need a <code>switch</code> statement as there are only two possible outcomes. It can be done much simpler with a single-line <a href=\"http://en.wikipedia.org/wiki/%3F%3a#C.2B.2B\" rel=\"noreferrer\">ternary statement</a>.</p>\n\n<p>Using the aforementioned <code>enum</code>, this function should now return a <code>State</code>:</p>\n\n<pre><code>State CLexer::rootTransition(char c)\n{\n return (c == '\"') ? STRING : ROOT;\n}\n</code></pre>\n\n<p>This will return either the value on the left (if true) or on the right (if false).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T00:35:36.093", "Id": "75949", "Score": "0", "body": "This answer has a lot of great feedback. Thanks for taking the time to review this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T00:42:06.143", "Id": "75952", "Score": "0", "body": "@CmdrMoozy: You're welcome!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T21:32:26.780", "Id": "43888", "ParentId": "33472", "Score": "15" } }, { "body": "<p>There are still some things to add to complete Jamal's answer:</p>\n\n<ul>\n<li><p>You are using the GCC extension <code>__attribute__((unused))</code>. That's useful for C code, but since you are using C++, you can simply drop the parameter name, that's allowed an encouraged:</p>\n\n<pre><code>int CLexer::stringEndTransition(char)\n{\n return ST_ROOT;\n}\n</code></pre></li>\n<li><p>You are using the syntax <code>(*it).foo</code> all over the place. You can simply replace that with the shorthand syntax <code>it-&gt;foo</code>.</p></li>\n<li><p>Concerning your <code>#define</code>s, I would go even further than Jamal and use an <code>enum class</code> (we are using C++11 after all):</p>\n\n<pre><code>enum class state_t\n{\n ROOT,\n STRING,\n STRING_END,\n ESCAPE\n};\n</code></pre>\n\n<p>Then, wherever you use <code>int</code> to represent the state, you should replace it by <code>state_t</code>. Also, you will have to change <code>ST_ROOT</code> by <code>state_t::ROOT</code> and so on... However, in order to do so, you will have to refactor some amount of code. But it is worth it, strong typing is a good pratice.</p></li>\n<li><p>C++11 guidelines again: replace <code>static const</code> variables by <code>static constexpr</code> variables whenever possible (I don't think it is possible for <code>std::map</code> though). Also, you can initialize variables (including <code>static</code> ones) directly at their point of declaration:</p>\n\n<pre><code>static constexpr state_t INITIAL_STATE = state_t::ROOT;\n</code></pre></li>\n<li><p>And C++11 once again: you should consider replacing the meaningful <code>typedef</code>s (see Jamal's answer for the useless ones) by <code>using</code> declarations. It may be a mere matter of taste, but I find them easier to read:</p>\n\n<pre><code>using C_LEXER_TRANSITION = state_t (CLexer::*)(char);\n</code></pre></li>\n<li><p>You should use meaningful names for your functions parameters, especially the ones that are meant to be used by everone (aka the <code>public</code> ones). For example, in this definition:</p>\n\n<pre><code>lexBlock(state_t &amp;s, const std::string &amp;t, state_t p);\n</code></pre>\n\n<p>I don't really know what <code>s</code>, <code>t</code> and <code>p</code> mean. And it was even worse before I replaced <code>int</code> parameters by <code>state_t</code> ones.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T00:31:51.150", "Id": "75948", "Score": "0", "body": "This was super helpful. I haven't spent as much time as I should learning new C++ style. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T00:40:34.773", "Id": "75951", "Score": "2", "body": "@CmdrMoozy New C++ style will probably save your time once you know it. Also, it may reduce code length and improve readability, which is great :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T00:50:59.577", "Id": "75954", "Score": "0", "body": "@CmdrMoozy: I do give Morwenn credit for confirming that C++11 was to be used, while I barely noticed the initializer list at first. Moreover, you're welcome to post a follow-up question if you get more of the new style implemented, while also following all this advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T01:47:03.333", "Id": "75959", "Score": "0", "body": "@Jamal The flag `-std=c++0x` in the command line was also a good hint." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-09T22:20:29.567", "Id": "43890", "ParentId": "33472", "Score": "11" } } ]
{ "AcceptedAnswerId": "43890", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T16:41:25.210", "Id": "33472", "Score": "17", "Tags": [ "c++", "c++11", "parsing" ], "Title": "C-style language lexer for a syntax highlighter" }
33472
<p>I'm trying to solve 15 puzzle using A* algorithm, but something really bad goes on in my <code>get_solution()</code> function that ruins performance. I guess there is a too much usage of maps in here, but I don't understand why it slows down my program so much. What do you think?</p> <p>I would be really happy if you could review my coding style as well.</p> <pre><code>import random # Class represents playing desk class Desk(object): SHUFFLE_NUMBER = 20 # changing to 200 and higher ruins everything def __init__(self, width, height): self.matrix =[] for i in range(height): row = [x + 1 for x in range(i * width, (i+1) * width)] self.matrix.append(row) self.matrix[height - 1][ width - 1] = 0 def height(self): return len(self.matrix) def width(self): return len(self.matrix[0]) def __str__(self): str_list = [] for r in self.matrix: for c in r: str_list.append(str(c) + "\t") str_list.append("\n") str_list.pop() return "".join(str_list) def __eq__(self, other): if (self.width() != other.width() or self.height() != other.height()): return False for r in range(self.height()): for c in range(self.width()): if self.matrix[r][c] != other.matrix[r][c]: return False; return True def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(self.__str__()) def shuffle(self): for i in range(Desk.SHUFFLE_NUMBER): self.matrix = self.neighbors()[random.randint(0, len(self.neighbors()) - 1)].matrix def get_element(self, row, col): return self.matrix[row][col] def set_element(self, row, col, value): self.matrix[row][col] = value def copy(self): newDesk = Desk(self.width(), self.height()) for r in range(self.height()): for c in range(self.width()): newDesk.set_element(r, c, self.matrix[r][c]) return newDesk def heuristic_cost(self): totalSum = 0 for r in range(self.height()): for c in range(self.width()): n = self.matrix[r][c] - 1 if (n == -1): n = self.width() * self.height() - 1 r_solved = n / self.height() c_solved = n % self.width() totalSum += abs(r - r_solved) totalSum += abs(c - c_solved) return totalSum def swap(self, r1, c1, r2, c2): term = self.matrix[r1][c1] self.matrix[r1][c1] = self.matrix[r2][c2] self.matrix[r2][c2] = term def neighbors(self): neighbors = [] w = self.width() h = self.height() for r in range(h): for c in range(w): if (self.matrix[r][c] == 0): if (r != 0): neighbor = self.copy() neighbor.swap(r, c, r - 1, c) neighbors.append(neighbor) if (r != h - 1): neighbor = self.copy() neighbor.swap(r, c, r + 1, c) neighbors.append(neighbor) if (c != 0): neighbor = self.copy() neighbor.swap(r, c, r, c - 1) neighbors.append(neighbor) if (c != w - 1): neighbor = self.copy() neighbor.swap(r, c, r, c + 1) neighbors.append(neighbor) return neighbors # Class represents the game class Puzzle15(object): def __init__(self, width=4, height=4): self.desk = Desk(width, height) self.desk.shuffle() self.steps = 0 def __str__(self): return str(self.desk) def __repr__(self): return str(self.desk) def lowest_score_element(self, openset, score): min_score = 2**30 min_elem = None for elem in openset: if (elem in score.keys()): if (score[elem] &lt; min_score): min_elem = elem min_score = score[elem] return min_elem def get_solution(self): start = self.desk.copy() goal = Desk(self.desk.width(), self.desk.height()) closed_set = [] openset = [start] came_from = {} g_score = { start: 0 } f_score = { start: g_score[start] + start.heuristic_cost()} while len(openset) != 0: current = self.lowest_score_element(openset, f_score) if (current == goal): return self.reconstruct_path(came_from, current) openset.remove(current) closed_set.append(current) neighbors = current.neighbors() for neighbor in neighbors: tentative_g_score = g_score[current] + 1 tentative_f_score = tentative_g_score + neighbor.heuristic_cost() if neighbor in closed_set and f_score.has_key(neighbor) and tentative_f_score &gt;= f_score[neighbor]: continue if neighbor not in openset or (f_score.has_key(neighbor) and tentative_f_score &lt; f_score[neighbor]): came_from[neighbor] = current g_score[neighbor] = tentative_g_score f_score[neighbor] = tentative_f_score if neighbor not in openset: openset.append(neighbor) self.steps += 1 return None def reconstruct_path(self, came_from, current_node): if (came_from.has_key(current_node)): p = self.reconstruct_path(came_from, came_from[current_node]) return p + [current_node] else: return [current_node] if __name__ == '__main__': puzzle = Puzzle15(3,3) solution = puzzle.get_solution() print puzzle.steps for s in solution: print s print </code></pre>
[]
[ { "body": "<h3>1. You can't fix what you can't measure</h3>\n\n<p>In order to improve the performance of your code, we need to be able to measure its performance, and that's hard to do, because your <code>Puzzle15</code> class randomly shuffles the <code>Desk</code> associated with each instance, so it is not easy to set up and carry out a systematic test.</p>\n\n<p>Let's fix that, by changing <code>Puzzle15.__init__</code> so that it takes a <code>Desk</code> instance of our choosing:</p>\n\n<pre><code>def __init__(self, desk):\n self.desk = desk\n self.steps = 0\n</code></pre>\n\n<p>Now we can create some test cases:</p>\n\n<pre><code>def puzzle15_test_cases(n, width=4, height=4):\n \"\"\"Generate 'n' pseudo-random (but repeatable) test cases.\"\"\"\n random.seed(1252481602)\n for _ in range(n):\n desk = Desk(width, height)\n desk.shuffle()\n yield desk\n\nTEST_CASES = list(puzzle15_test_cases(100))\n</code></pre>\n\n<p>And a function that times the solution of all the cases, using the <a href=\"http://docs.python.org/2/library/timeit.html\"><code>timeit</code></a> module:</p>\n\n<pre><code>from timeit import timeit\n\ndef puzzle15_time():\n \"\"\"Return the time taken to solve the puzzles in the TEST_CASES list.\"\"\"\n return timeit('[Puzzle15(desk).get_solution() for desk in TEST_CASES]',\n 'from __main__ import TEST_CASES, Puzzle15; gc.enable()',\n number = 1)\n</code></pre>\n\n<p>(<a href=\"http://docs.python.org/2/library/timeit.html#timeit.Timer.timeit\">See here</a> for an explanation of <code>gc.enable()</code>.) It takes more than three minutes on my machine to solve all 100 test cases:</p>\n\n<pre><code>&gt;&gt;&gt; puzzle15_time()\n184.2024281024933\n</code></pre>\n\n<h3>2. Use sets for fast lookup</h3>\n\n<p>The first obvious time sink is the open and closed sets. You implement these using lists, but Python's <a href=\"http://docs.python.org/2/library/stdtypes.html#list\"><code>list</code></a> does not have an efficient membership test: to implement <code>neighbor in closed_set</code> Python has to scan all the way along the list, comparing <code>neighbor</code> with each item in turn until it finds one that matches. By using <a href=\"http://docs.python.org/2/library/stdtypes.html#set\"><code>set</code></a> objects instead, we get a constant-time membership test. So change:</p>\n\n<pre><code>closed_set = []\nopenset = [start]\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>closed_set = set()\nopenset = set([start])\n</code></pre>\n\n<p>and use the <a href=\"http://docs.python.org/2/library/stdtypes.html#set.add\"><code>set.add()</code></a> method instead of <code>list.append()</code>. This change gives us an immediate 28% speedup:</p>\n\n<pre><code>&gt;&gt;&gt; puzzle15_time()\n132.80268001556396\n</code></pre>\n\n<h3>3. Use the power of the dictionary</h3>\n\n<p>The next obvious problem is <code>lowest_score_element</code>. You have a double loop:</p>\n\n<pre><code>for elem in openset:\n if (elem in score.keys()):\n</code></pre>\n\n<p>So for each position in <code>openset</code>, you construct a fresh list containing the keys of the dictionary <code>score</code>, and then you look up the position in the list (which, as explained above, might require comparing the position to every item in the list). You could just write:</p>\n\n<pre><code>for elem in openset:\n if elem in score:\n</code></pre>\n\n<p>so that the membership test uses the fast dictionary lookup.</p>\n\n<p>But you don't even need to do this, because Python already has a function <a href=\"http://docs.python.org/2/library/functions.html#min\"><code>min</code></a> for finding the smallest element in a collection. So I would implement the method like this:</p>\n\n<pre><code>def lowest_score_element(self, openset, score):\n return min(openset, key=score.get)\n</code></pre>\n\n<p>And that yields a very dramatic improvement:</p>\n\n<pre><code>&gt;&gt;&gt; puzzle15_time()\n3.443160057067871\n</code></pre>\n\n<h3>4. Make positions immutable</h3>\n\n<p>Instances of the <code>Desk</code> class represent positions in the 15 puzzle. You need to look up these positions in sets and dictionaries, and that means they need to be <a href=\"http://docs.python.org/2/glossary.html#term-hashable\"><em>hashable</em></a>. But if you read the documentation for the special <a href=\"http://docs.python.org/2/reference/datamodel.html#object.__hash__\"><code>__hash__</code></a> method, you'll see that it says:</p>\n\n<blockquote>\n <p>If a class defines mutable objects and implements a <code>__cmp__()</code> or <code>__eq__()</code> method, it should not implement <code>__hash__()</code>, since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).</p>\n</blockquote>\n\n<p>Your <code>Desk</code> objects are currently <em>mutable</em> — they can be changed by the <code>swap</code> and <code>set_element</code> and <code>shuffle</code> methods. This makes them unsuitable for storing in sets or using as dictionary keys. So let's make them immutable instead. And at the same time, make the following improvements:</p>\n\n<ol>\n<li><p>Use the more understandable name <code>Position</code> instead of <code>Desk</code>.</p></li>\n<li><p>Write docstrings for the class and its methods.</p></li>\n<li><p>Represent the matrix as a single tuple instead of a list-of-lists. This means that a cell can be fetched in a single lookup instead of two lookups.</p></li>\n<li><p>Remove the <code>get_element</code> method (just look up cells directly, saving a method call) and remove the <code>set_element</code> method (it's not needed now that the class is immutable).</p></li>\n<li><p>Represent the blank item as 15 rather than 0, to avoid the special case in <code>heuristic_cost</code>.</p></li>\n<li><p>Remember where the blank element is, so that neighbours can be generated without having to search the matrix to find the blank.</p></li>\n<li><p>Generate the neighbours instead of returning them as a list.</p></li>\n<li><p>Speed up the <code>__hash__</code> by using <code>tuple.__hash__</code> instead of carrying out an expensive conversion to a string each time we want to compute the hash.</p></li>\n<li><p>Rename <code>swap</code> and <code>shuffle</code> to <code>swapped</code> and <code>shuffled</code> since they now return new objects instead of modifying the old object in place.</p></li>\n<li><p>Pass the number of swaps as a parameter to the <code>shuffled</code> method.</p></li>\n<li><p>Avoid calling <code>self.neighbors</code> twice in the <code>shuffle</code> method, by using <a href=\"http://docs.python.org/2/library/random.html#random.choice\"><code>random.choice</code></a>.</p></li>\n<li><p>Use <a href=\"http://docs.python.org/2/library/functions.html#divmod\"><code>divmod</code></a> instead of separately computing <code>/</code> and <code>%</code>.</p></li>\n<li><p>Divide the heuristic cost by 2 (because one swap changes the sum of distances by 2).</p></li>\n</ol>\n\n<p>That results in the following code:</p>\n\n<pre><code>class Position(object):\n \"\"\"A position in the 15 puzzle (or a variant thereof).\"\"\"\n\n def __init__(self, width, height, matrix=None, blank=None):\n assert(width &gt; 1 and height &gt; 1)\n self.width = width\n self.height = height\n self.cells = width * height\n if matrix is None:\n matrix = tuple(range(self.cells))\n blank = self.cells - 1\n assert(len(matrix) == self.cells)\n assert(0 &lt;= blank &lt; self.cells)\n self.matrix = matrix\n self.blank = blank\n\n def __repr__(self):\n return 'Position({0.width}, {0.height}, {0.matrix})'.format(self)\n\n def __eq__(self, other):\n return self.matrix == other.matrix\n\n def __ne__(self, other):\n return self.matrix != other.matrix\n\n def __hash__(self):\n return hash(self.matrix)\n\n def shuffled(self, swaps=20):\n \"\"\"Return a new position after making 'swaps' swaps.\"\"\"\n result = self\n for _ in range(swaps):\n result = random.choice(list(result.neighbors()))\n return result\n\n def heuristic_cost(self):\n \"\"\"Return an admissible estimate of the number of swaps needed to\n solve the puzzle from this position.\n\n \"\"\"\n total = 0\n for m, n in enumerate(self.matrix):\n mx, my = divmod(m, self.width)\n nx, ny = divmod(n, self.width)\n total += abs(mx - nx) + abs(my - ny)\n return total // 2\n\n def swapped(self, c):\n \"\"\"Return a new position with cell 'c' swapped with the blank.\"\"\"\n assert(c != self.blank)\n i, j = sorted([c, self.blank])\n return Position(self.width, self.height,\n self.matrix[:i] + (self.matrix[j],)\n + self.matrix[i+1:j] + (self.matrix[i],)\n + self.matrix[j+1:], c)\n\n def neighbors(self):\n \"\"\"Generate the neighbors to this position, namely the positions\n reachable from this position via a single swap.\n\n \"\"\"\n zy, zx = divmod(self.blank, self.width)\n if zx &gt; 0:\n yield self.swapped(self.blank - 1)\n if zx &lt; self.width - 1:\n yield self.swapped(self.blank + 1)\n if zy &gt; 0:\n yield self.swapped(self.blank - self.width)\n if zy &lt; self.height - 1:\n yield self.swapped(self.blank + self.width)\n</code></pre>\n\n<p>(We also have to make a couple of minor changes to <code>Puzzle15</code> and <code>puzzle15_time</code> for this to work, but it should be clear what's required.)</p>\n\n<p>This yields another 6× speedup:</p>\n\n<pre><code>&gt;&gt;&gt; puzzle15_time()\n0.42876315116882324\n</code></pre>\n\n<h3>5. Find the minimum using a heap</h3>\n\n<p>Python's <code>min</code> function still has to look at every element in the open set, taking O(<em>n</em>) time if there are <em>n</em> elements in the open set. If we kept a copy of the open set in a <a href=\"https://en.wikipedia.org/wiki/Heap_%28data_structure%29\"><em>heap</em> data structure</a>, then we'd be able to find the minimum element in O(log <em>n</em>).</p>\n\n<p>Python's built-in <a href=\"http://docs.python.org/2/library/heapq.html\"><code>heapq</code></a> module provides a way to do this, and moreover, by storing the f-score, g-score and parent position in the heap, we can get rid of the dictionaries in which you currently store these values.</p>\n\n<p>This answer is getting rather long, so I'll just give you the revised code and you can figure out how it works for yourself!</p>\n\n<pre><code>import heapq\n\nclass NotFoundError(Exception): pass\n\ndef puzzle15_solve(start):\n goal = Position(start.width, start.height)\n closed_set = set()\n\n # Heap items are lists [F-score, G-score, position, parent data]\n start_data = [start.heuristic_cost(), 0, start, None]\n\n # open_set and open_heap always contain the same positions.\n # open_set maps each position to the corresponding heap item.\n open_set = {start: start_data}\n open_heap = [start_data]\n\n while open_heap:\n current_data = heapq.heappop(open_heap)\n f_current, g_current, current, parent_data = current_data\n\n if current == goal:\n def path(data):\n while data:\n yield data[2]\n data = data[3]\n return list(path(current_data))[::-1]\n\n del open_set[current]\n closed_set.add(current)\n for neighbor in current.neighbors():\n if neighbor in closed_set:\n continue\n\n g_neighbor = g_current + 1\n f_neighbor = g_neighbor + neighbor.heuristic_cost()\n neighbor_data = [f_neighbor, g_neighbor, neighbor, current_data]\n\n if neighbor not in open_set:\n open_set[neighbor] = neighbor_data\n heapq.heappush(open_heap, neighbor_data)\n else:\n old_neighbor_data = open_set[neighbor]\n if neighbor_data &lt; old_neighbor_data:\n old_neighbor_data[:] = neighbor_data\n heapq.heapify(open_heap)\n\n raise NotFoundError(\"No solution for {}\".format(start))\n</code></pre>\n\n<p>(Note that there's no persistent data here, so there's no need to make this function into a class.)</p>\n\n<p>That yields another 2× speedup or so:</p>\n\n<pre><code>&gt;&gt;&gt; puzzle15_time()\n0.2613048553466797\n</code></pre>\n\n<h3>6. A different algorithm</h3>\n\n<p>I've managed to make your code about 700 times faster (on this particular set of 20-shuffle test cases), but you'll find that if you shuffle the start position many times, the search often still does not complete in a reasonable amount of time.</p>\n\n<p>This is due to a combination of (i) the size of the search space (10,461,394,944,000 positions); and (ii) the <a href=\"https://en.wikipedia.org/wiki/A%2a_search_algorithm\">A* algorithm</a>, which keeps searching until it has found the <em>best</em> (shortest) solution.</p>\n\n<p>But if you don't care about getting the <em>best</em> solution, but are willing to accept <em>any</em> solution, then you could change the algorithm to ignore the g-score. Replace:</p>\n\n<pre><code>f_neighbor = g_neighbor + neighbor.heuristic_cost()\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>f_neighbor = neighbor.heuristic_cost()\n</code></pre>\n\n<p>and now you can solve arbitrarily shuffled positions in a couple of seconds:</p>\n\n<pre><code>&gt;&gt;&gt; timeit(lambda:puzzle15_solve(Position(4, 4).shuffled(1000)), number=1)\n2.0673770904541016\n</code></pre>\n\n<p>This change turns A* into a form of <a href=\"https://en.wikipedia.org/wiki/Best-first_search\">best-first search</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-05T16:06:08.057", "Id": "313893", "Score": "0", "body": "You have done an amazing job,congratulations. It seems though that the best-first search algorithm needs 14x time to solve the TEST_CASES. Is this expected sometimes, or is it a blunder of mine?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-05T18:21:01.680", "Id": "313916", "Score": "0", "body": "@NameOfTheRose: Hard to know what happened without seeing exactly what you did, but I find that the best-first search is more than 140 times faster on a set of 20-shuffle test cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-06T12:16:30.900", "Id": "314093", "Score": "0", "body": "There is one particular puzzle that takes too long: `Position(4,4,(1, 2, 3, 7, 4, 0, 5, 6, 15, 9, 10, 11, 8, 12, 13, 14),8)`. But in general the _best-first-search_ is roughly only twice as fast. Of course it solves puzzles (like the 1000 shuffle above in 1.4s) that _A* search_ fails to solve. The only change I did was to change the `f_neighbor` calculation as shown above. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-07-07T12:48:28.523", "Id": "319225", "Score": "0", "body": "For python3 compatibility, one has to add `__lt__` method to the `Position class` `def __lt__(self, other): return self.heuristic_cost() < other.heuristic_cost()`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T22:27:59.507", "Id": "33549", "ParentId": "33473", "Score": "27" } } ]
{ "AcceptedAnswerId": "33549", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T17:36:02.183", "Id": "33473", "Score": "14", "Tags": [ "python", "performance", "sliding-tile-puzzle", "a-star" ], "Title": "Solving 15 puzzle" }
33473
<p>This code completes under a second, however its seems like I've taken the "Mr. Bean" way around getting there.</p> <p>The goal is to get the average number of orders processed in a single day based on how many days exist in the current database. The loadcount column represents how many orders are processed in a single batch. The batch is driven by the date and time during the day.</p> <pre><code> -- // ditch the time to get the start/end date ranges uniform by date //-- ;with makeuniform as (SELECT cast(startrangedatetime as date) as startdate ,cast(endrangedatetime as date) as enddate ,[LoadCount] FROM [audit].[Tracker] ) -- // next, rollup all the loadcounts by uniform date // -- select startdate, sum(loadcount) TotalOrders into #sumthedays from makeuniform group by startdate; -- // since the counts have been rolled up by day, get the table count // -- declare @howmanydays int select @howmanydays = count(*) from #sumthedays; -- // next get the average traffic per day // -- select sum(TotalOrders) / @howmanydays from #sumthedays drop table #sumthedays </code></pre>
[]
[ { "body": "<p>this doesn't look bad to me at all,</p>\n\n<ul>\n<li>I had no trouble following along</li>\n<li>you said it is a Fast Query</li>\n<li>nothing looks over complicated</li>\n</ul>\n\n<p>I would suggest testing it more, maybe see how it would run in a very large database, that is something that I always try to keep in mind, <em>what happens when my tables become very large?</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T14:17:17.280", "Id": "33514", "ParentId": "33480", "Score": "1" } }, { "body": "<p>This could be simplified. You don't have to create a temporary table to get your unique day count. You can use the <code>COUNT</code> function on the <code>StartDate</code> column directly. </p>\n\n<p>Try this:</p>\n\n<pre><code>SELECT\n TotalLoadCount / NULLIF(TotalDayCount, 0) AvgLoadCountByDay\nFROM\n(\nSELECT\n COUNT(DISTINCT CAST(StartDate as date)) TotalDayCount\n ,SUM(LoadCount) TotalLoadCount\nFROM\n dbo.Tracker\n) x \n</code></pre>\n\n<p>Obviously, you can write it directly like this as well:</p>\n\n<pre><code>SELECT\n SUM(LoadCount) / NULLIF(COUNT(DISTINCT CAST(StartDate AS date)), 0) AvgLoadCountByDay\nFROM\n dbo.Tracker\n</code></pre>\n\n<p>If my understanding of your problem is correct, this query should give you the same result. Let me know if it doesn't. </p>\n\n<p>I personally prefer the first version with derived table as it helps with the readability of the query. You are not paying any additional cost because SQL Server will generate the same execution plan for both the queries.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T21:16:09.533", "Id": "53853", "Score": "0", "body": "Brilliantly done! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T17:43:35.650", "Id": "33528", "ParentId": "33480", "Score": "2" } } ]
{ "AcceptedAnswerId": "33528", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T21:31:53.523", "Id": "33480", "Score": "3", "Tags": [ "sql", "sql-server" ], "Title": "SQL Server 2012: How do I eliminate multiple statements in this code to a more efficient, single statement?" }
33480
<p>As explained <a href="https://codereview.stackexchange.com/questions/33456/sorting-a-numerical-list-using-basic-scheme">here</a>, I'm learning a limited subset of Scheme.</p> <p>My task has been to sort a numerical list. To implement a simple insertion sort, I need to remove a single element from a list.</p> <p>I've done the following (in the spirit of <em>The Little Schemer</em>):</p> <pre><code>(define remove-elem (lambda (ll elem) (cond ((null? ll) '()) ((eq? (car ll) elem) (cdr ll)) (else (cons (car ll) (remove-elem (cdr ll) elem)))) )) </code></pre> <p>What are other ways of implementing this function?</p>
[]
[ { "body": "<p>That looks mostly right to me. I'll suggest two things.</p>\n\n<p>First, there is nice syntatic sugar for defining functions:</p>\n\n<pre><code>(define (remove-elem xs elem) \n (cond ...)\n)\n</code></pre>\n\n<p>Save yourself the lambda. </p>\n\n<p>Second, you are using <code>eq?</code>. That is the wrong checker for this problem. That function returns true if the two objects are the exact same object in memory. It could be true for primitives like ints, but it's not necessarily true. What you want to use is <code>eqv?</code> which will guaranteed work for numbers. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T23:06:26.097", "Id": "33482", "ParentId": "33481", "Score": "3" } } ]
{ "AcceptedAnswerId": "33482", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-10-29T22:17:15.743", "Id": "33481", "Score": "2", "Tags": [ "scheme" ], "Title": "Remove first occurrence of element from list" }
33481
<p>I've been reading too many papers and writing too little code. These are my first 300 lines of Haskell:</p> <pre><code>{-# LANGUAGE NoMonomorphismRestriction, TemplateHaskell #-} module Forth where import qualified Data.Map.Lazy as Map import Control.Monad.State import Control.Monad.Error import Text.Read (readMaybe) import Text.Parsec import Control.Applicative hiding ((&lt;|&gt;), optional, many) import Control.Lens import Control.Lens.Operators import Safe data Forth = Forth { _stack :: [Integer], _loopStack :: [Integer], _heap :: Map.Map String [Exp]} deriving (Show) data Exp = Cmt String | Dump | Num Integer | Plus | Min | Mul | Div | Mod | Dup | Swap | Drop | PP | LoopIndex Int | In | Out String | CR | Eq | Lt | Gt | Word String [Exp] | Call String | If [Exp] [Exp] | DoLoop [Exp] Bool | Leave deriving (Show) makeLenses ''Forth type ForthS a = ErrorT String (StateT Forth IO) a emptyForth :: Forth emptyForth = Forth [] [] Map.empty pushStack :: Integer -&gt; ForthS () pushStack n = stack %= (n:) popStack :: ForthS Integer popStack = do s &lt;- use stack case s of [] -&gt; throwError "Empty stack. Can't pop!" (n:ns) -&gt; do stack .= ns return n dumpStack :: ForthS [Integer] dumpStack = zoom stack get -- pushLoopStack :: Integer -&gt; ForthS () pushLoopStack n = loopStack %= (n:) popLoopStack :: ForthS Integer popLoopStack = do s &lt;- use loopStack case s of [] -&gt; throwError "Empty loop stack. Can't pop!" (n:ns) -&gt; do loopStack .= ns return n --(.?) :: MonadState s m =&gt; Getting s1 s s1 -&gt; Getting (f a) s1 a -&gt; m (Maybe a) (.?) a b = do v &lt;- use a return (v ^? b) peekLoopStack :: Int -&gt; ForthS Integer peekLoopStack i = do --a &lt;- (loopStack .? ix i) a &lt;- zoom loopStack (gets $ flip atMay i) case a of Just n -&gt; return n Nothing -&gt; throwError $ "Loop stack is empty." -- setWord :: String -&gt; [Exp] -&gt; ForthS () setWord word val = heap %= (Map.insert word val) getWord :: String -&gt; ForthS [Exp] getWord word = do h &lt;- use heap case Map.lookup word h of Just a -&gt; return a Nothing -&gt; throwError $ "Word \"" ++ word ++ "\" is not defined." ----------------------- execProg :: [Exp] -&gt; IO () execProg xs = do (success, machine) &lt;- runProg xs case success of Left m -&gt; putStrLn $ "\nFailed: " ++ m ++ show machine Right _ -&gt; putStrLn $ "\nOk: " ++ show machine runProg :: [Exp] -&gt; IO (Either String (), Forth) runProg xs = runEval (mapM_ eval xs) runEval :: Eval -&gt; IO (Either String (), Forth) runEval ev = runStateT (runErrorT ev) emptyForth type Eval = ForthS () eval :: Exp -&gt; Eval eval (Cmt _) = return () eval (Dump) = do ns &lt;- dumpStack liftIO $ print ns eval (Num n) = pushStack n eval (Plus) = do a &lt;- popStack b &lt;- popStack pushStack (b+a) eval (Min) = do a &lt;- popStack b &lt;- popStack pushStack (b-a) eval (Mul) = do a &lt;- popStack b &lt;- popStack pushStack (b*a) eval (Div) = do a &lt;- popStack b &lt;- popStack pushStack (b `div` a) eval (Mod) = do a &lt;- popStack b &lt;- popStack pushStack (b `mod` a) eval (Dup) = do a &lt;- popStack pushStack a pushStack a eval (Swap) = do a &lt;- popStack b &lt;- popStack pushStack a pushStack b eval (Drop) = do _ &lt;- popStack return () eval (PP) = do a &lt;- popStack liftIO $ print a eval (LoopIndex i) = do n &lt;- peekLoopStack i pushStack n eval (In) = do s &lt;- liftIO getLine case readMaybe s of Just n -&gt; pushStack n Nothing -&gt; throwError $ "Input \"" ++ s ++ "\" is not a number." eval (Out s) = liftIO $ putStr s eval (CR) = liftIO $ putStrLn "" eval (Eq) = do a &lt;- popStack b &lt;- popStack pushStack (if b==a then 1 else 0) eval (Lt) = do a &lt;- popStack b &lt;- popStack pushStack (if b&lt;a then 1 else 0) eval (Gt) = do a &lt;- popStack b &lt;- popStack pushStack (if b&gt;a then 1 else 0) eval (Word key val) = setWord key val eval (Call key) = do val &lt;- getWord key mapM_ eval val eval (If yes no) = do a &lt;- popStack mapM_ eval (if a/=0 then yes else no) eval (Leave) = mzero eval (DoLoop xs plusLoop) = do idx &lt;- popStack lim &lt;- popStack pushLoopStack lim pushLoopStack idx let go lim idx = do mapM_ eval xs inc &lt;- if plusLoop then popStack else return 1 guard $ not $ if inc &gt;= 0 then (lim &lt; idx) `xor` (lim &lt;= idx + inc) else (lim &lt;= idx) `xor` (lim &lt; idx + inc) _ &lt;- popLoopStack _ &lt;- popLoopStack pushLoopStack lim pushLoopStack (idx + inc) go lim (idx + inc) let finish = do _ &lt;- popLoopStack _ &lt;- popLoopStack return () mplus (go lim idx) finish xor :: Bool -&gt; Bool -&gt; Bool x `xor` y = (x || y) &amp;&amp; not (x &amp;&amp; y) ----------------------------- execParse :: String -&gt; IO () execParse = execProg . parseForth parseForth :: String -&gt; [Exp] parseForth s = case parse forthParser "YOLO" s of Left e -&gt; [Out $ "ERROR PARSED: " ++ show e] Right xs -&gt; xs forthParser = ws *&gt; many forthExp &lt;* eof forthExp = foldl1 (&lt;||&gt;) $ map (\e-&gt; e &lt;* (ws1 &lt;|&gt; eof))[ comments &gt;&gt;= pure . Cmt, integer &gt;&gt;= pure . Num, -- negative numbers suck char '-' *&gt; pure Min, char '+' *&gt; pure Plus, char '*' *&gt; pure Mul, char '/' *&gt; pure Div, char '.' *&gt; pure PP, char '=' *&gt; pure Eq, char '&lt;' *&gt; pure Lt, char '&gt;' *&gt; pure Gt, char '%' *&gt; pure Mod, char 'i' *&gt; pure (LoopIndex 0), char 'j' *&gt; pure (LoopIndex 2), char 'k' *&gt; pure (LoopIndex 4), string "false" *&gt; pure (Num 0), string "true" *&gt; pure (Num 1), string "CR" *&gt; pure CR, string "dump" *&gt; pure Dump, string "dup" *&gt; pure Dup, string "swap" *&gt; pure Swap, string "drop" *&gt; pure Drop, string "in" *&gt; pure In, string "leave" *&gt; pure Leave, ifThenElse, doLoop, stringLike &gt;&gt;= pure . Out , definition, many1 alphaNum &gt;&gt;= pure . Call -- if it isn't a keyword, it must be a call ] p &lt;||&gt; q = try p &lt;|&gt; q ws = skipMany (oneOf " \n\r") ws1 = skipMany1 (oneOf " \n\r") lexeme p = ws *&gt; p &lt;* ws integer = rd &lt;$&gt; (plus &lt;|&gt; minus &lt;|&gt; number) where rd = read :: String -&gt; Integer plus = char '+' *&gt; number minus = (:) &lt;$&gt; char '-' &lt;*&gt; number number = many1 digit stringLike = char '\'' *&gt; many (noneOf ['\'']) &lt;* char '\'' comments = char '(' *&gt; many (noneOf [')' , '\r', '\n']) &lt;* char ')' definition = do char ':' name &lt;- lexeme (many1 alphaNum) prog &lt;- forthParser char ';' return $ Word name prog ifThenElse = do string "if" ws yes &lt;- manyTill forthExp (try $ lookAhead $ string "else" &lt;|&gt; string "then") no &lt;- option [] $ do string "else" ws manyTill forthExp (try $ lookAhead $ string "then") string "then" return $ If yes no doLoop = do string "do" ws body &lt;- manyTill forthExp (try $ lookAhead $ string "loop" &lt;|&gt; string "+loop") choice [string "loop" *&gt; return (DoLoop body False), string "+loop" *&gt; return (DoLoop body True)] ---------------- main :: IO () main = do s &lt;- getContents execParse s </code></pre> <p><a href="http://lpaste.net/94976" rel="nofollow">Mirror</a></p> <p>Use execParse in GHCi to parse and run a program.</p> <p>Example:</p> <pre><code>execParse ": neg (n -- n') 0 swap - ; 'enter a number to negate' CR in neg . 'looping' CR 0 50 do i . -5 +loop true if 'always print this' else 'never print this' then dump" </code></pre> <p>In this project I've tried to use Parsec, a small transformer stack and basic lens functionality. Comments on the use of these are what I'm after, but everything helps.</p> <p>I've used <code>NoMonomorphismRestriction</code> to deal with Parsec. It can't infer types but the types are too complicated to figure out myself. I was wondering whether this could be because of type synonyms and whether there's an easy guide to typing Parsec functions, or maybe I'm complicating things too much.</p> <p>I've found using transformers pretty straightforward, and it matches pretty well with lens. But, all lens operators have State versions except the getters, which makes it pretty awkward. I can use zoom, but that isn't always pretty (can't be used with <code>^?</code> for example). </p>
[]
[ { "body": "<p>I think <code>popStack</code> might look a little nicer using the <code>LambdaCase</code> extension:</p>\n\n<pre><code>popStack :: ForthS Integer\npopStack = use stack &gt;&gt;= \\case\n [] -&gt; throwError \"Empty stack. Can't pop!\"\n (n:ns) -&gt; stack .= ns &gt;&gt; return n\n</code></pre>\n\n<p>The same transformation can occur with <code>popLoopStack</code>. It also applies to <code>peekLoopStack</code>, but in that case, you might even use <code>maybe</code> rather than a language extension:</p>\n\n<pre><code>peekLoopStack :: Int -&gt; ForthS Integer\npeekLoopStack = maybe (throwError \"Loop stack is empty.\") return\n . zoom loopStack . gets . flip atMay\n</code></pre>\n\n<p>You could also use <code>maybe</code> to eliminate the <code>do</code> in <code>getWord</code>.</p>\n\n<hr>\n\n<p>You have a lot of binary operators. Each one is implemented like this:</p>\n\n<pre><code>eval (Plus) = do\n a &lt;- popStack\n b &lt;- popStack\n pushStack (b+a)\n</code></pre>\n\n<p>I think that’s a little repetitive. I might define a little helper function:</p>\n\n<pre><code>binop :: (Integer -&gt; Integer -&gt; Integer) -&gt; Eval\nbinop f = do\n a &lt;- popStack\n b &lt;- popStack\n pushStack (f b a)\n</code></pre>\n\n<p>Then you can define your operators like this:</p>\n\n<pre><code>eval Plus = binop (+)\neval Min = binop (-)\neval Mul = binop (*)\n-- ...\n</code></pre>\n\n<p>This leaves less room for error.</p>\n\n<hr>\n\n<p>In a similar vein to the first suggestion, you might try to eliminate the <code>do</code> from <code>Call</code>:</p>\n\n<pre><code>eval (Call key) = getWord key &gt;&gt;= mapM_ eval\n</code></pre>\n\n<hr>\n\n<p><code>xor</code> is <code>/=</code>. There is no need to define <code>xor</code> when you could just use <code>/=</code>.</p>\n\n<hr>\n\n<h2><code>forthExp</code></h2>\n\n<p><code>comments &gt;&gt;= pure . Cmt</code> can be replaced with <code>fmap Cmt comments</code> or <code>Cmt &lt;$&gt; comments</code>. Similarly for <code>integer</code>, <code>stringLike</code>, and calls.</p>\n\n<p><code>char '-' *&gt; pure Min</code> can be replaced with <code>Min &lt;$ char '-'</code>. Similarly for the others.</p>\n\n<p>The outer structure, too, can probably be changed. Rather than using</p>\n\n<pre><code>foldl1 (&lt;||&gt;) $ map (\\e-&gt; e &lt;* (ws1 &lt;|&gt; eof))\n</code></pre>\n\n<p>I think this would be clearer:</p>\n\n<pre><code>choice $ map ((&lt;* (es1 &lt;|&gt; eof)) . try)\n</code></pre>\n\n<hr>\n\n<p>I would avoid the name <code>ifThenElse</code>, as that is used by GHC’s <code>RebindableSyntax</code> extension should you ever want to use it in the future.</p>\n\n<hr>\n\n<h2>Transformer stack</h2>\n\n<p>Your transformer stack looks okay, but I might consider replacing the underlying <code>IO</code> with a free monad providing only the operations (input, output) you need, and then provide an interpreter to use <code>IO</code>. This makes it trivial to test, as you can make it pure by just inspecting the resulting structure rather than using the <code>IO</code> interpreter. See <a href=\"http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html\" rel=\"nofollow\">this blog post</a> for more details.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T23:26:24.363", "Id": "74351", "ParentId": "33483", "Score": "5" } } ]
{ "AcceptedAnswerId": "74351", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T23:10:22.350", "Id": "33483", "Score": "6", "Tags": [ "haskell", "forth" ], "Title": "Toy Forth interpreter" }
33483
<p>I am trying to simplify my code, which will do several things:</p> <ol> <li>Give the same width to every columns no matter how many columns the table has.</li> <li>Add input field if there is no text inside a <code>td</code></li> <li>Make sure the input field is no wider than its table cell</li> <li>Make sure, if the input field has size attribute, the input field size will increase based on the size attribute</li> <li>If the table width is too narrow, increase if necessary</li> </ol> <p><strong>My HTML structure:</strong></p> <pre><code>&lt;table class='test' width='500'&gt; &lt;tr&gt; &lt;td&gt; &lt;span&gt;cell 1&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;span&gt;&lt;input size='18'/&gt;&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;span&gt;cell 3&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;span&gt;cell 4&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;span&gt;&lt;input size='15'/&gt;&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;span&gt;&lt;input size='15'/&gt; &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>$(".test td").each(function(){ columns = $(this).parent().find('td').length; inputField= $(this).find('input') tdWidth= $(this).width() - 35; inputSize = $(this).find('input').attr('size'); span = $(this).find('span'); oldTableWdith = $(this).closest('table').attr('width'); if($.trim($(span).html()) == '&amp;nbsp;'){ $(span).html("&lt;input type='text' style='width:" + tdWidth + "px;'&gt;&lt;/input&gt;"); } inputWidth = inputSize * 11; inputField.css('width',inputWidth); if(tableWidth &lt; (columns * inputWidth + 50)){ tableWidth = columns * inputWidth + 50; } if(tableWidth===0){ tableWidth = oldTableWdith } $(this).closest('table').width(tableWidth); }) </code></pre> <p>The code works, but I feel like I can greatly reduce it and achieve what I need. I also need the span tag because I need them to do some other functions. Can anyone help me simplify the code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:30:14.687", "Id": "53646", "Score": "0", "body": "one huge efficiency improvement is only test first row for number of columns. Checking how many cells in row...for every td is a massive duplication of effort. Same with setting the table width...you are setting it every time a td is checked. If it was me I would rip whole thing apart and start with top level issues...before checking each td" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T02:36:52.737", "Id": "53661", "Score": "0", "body": "Make sure you have tried to do all you can about widths using just CSS before you start setting widths with JavaScript." } ]
[ { "body": "<p>At first, you code looks good enough for the set of the requrements you specified. The constructions that you use are simple, so here may be place for the improvements, but this requeres developing understanding in the nontrivial subjects: CSS selectors, jQuery selectors and jQuery chaining details. I think that it may be possible to write down all the code in one chain but it may decrease maintainability.</p>\n\n<p>Some recommendations:</p>\n\n<ol>\n<li>Instead of getting element html use .text().trim().</li>\n<li>Use width:100% for inputs to let CSS do the work for you, but apply it only for the inputs without size - use combination of :not and [size] for that.</li>\n<li>Tables are stretching, so just remove the table size at the end - it should be autosized to the content.</li>\n<li>Use find(...)....end() to chain the queries and separate the realizations of the requirements.</li>\n<li>Use static code analysis tools, like Jshint, jslint - it is better to add var to not interfere with the global scope and these tools let know about such kind of the errors and more.</li>\n<li>It highly unclear what is the nature of the constants (like 35, 11, etc) in the code. It is better to add at least a very small explanation on them. It greatly improves understanding and review.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T03:08:40.363", "Id": "33490", "ParentId": "33485", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-30T00:24:46.147", "Id": "33485", "Score": "0", "Tags": [ "javascript", "jquery", "html", "form", "layout" ], "Title": "Resizing table widths and making input fields" }
33485